- src/dist 산출물 분리 원칙 정리(.gitignore, .gitattributes) - 루트 및 주요 폴더(config/scripts/prompts/tests/src, 런타임 폴더 5종)에 안내용 README.md 추가 - CHANGELOG.md, LICENSE, docs/ops/05-release-and-versioning.md 추가 - docs/README.md 문서 지도 갱신
348 KiB
RAW RESEARCH DUMP — agent-a13f3142511ff3665
ORIGINAL TASK PROMPT
오늘 날짜는 2026-09-02 이다. 너는 리서치 에이전트다. 반드시 먼저 ToolSearch 로 "select:WebSearch,WebFetch" 를 로드하고, WebSearch 로 최소 8회 이상 다양한 한국어/영어 질의를 던지고, 핵심 출처 페이지는 WebFetch 로 실제 열어 내용을 확인하라. 실제로 열어 확인한 항목만 verified_by_fetch=true 로 표시하라. 존재를 확인하지 못한 URL, GitHub 저장소, 논문, CLI 플래그는 절대 지어내지 말고 confidence='low' 로 표시하거나 제외하라. 한국 사이트(nedrug.mfds.go.kr, data.go.kr 등)는 WebFetch 가 실패할 수 있으니 실패하면 그 사실을 open_questions 에 적어라. 결과의 summary/detail/recommendations 는 한국어로 쓰되 고유명사·코드·플래그는 원문 유지. 코드 스니펫은 실제 동작 가능한 수준으로 구체적으로 작성하라. 최종 출력은 StructuredOutput 스키마에 맞춰라.
프로젝트 맥락: Windows 11 PC 에서 매일 06:00 에 한국 식약처 원료의약품 등록(DMF) 공고/현황을 크롤링하여 신규/변경/취하 건을 탐지하고, 탭(시트)별로 연동된 보기 좋은 xlsx 리포트를 생성한다. 크롤링·요약 일부를 AI 에이전트 CLI(Claude Code 의 'claude -p' headless 모드 등)로 non-interactive 하게 돌리고, 재부팅 후에도 자동 복구되는 서비스/스케줄러로 운영하며, 서비스가 죽으면 Windows 알림으로 복구 안내를 띄운다.
[축 5: AI 에이전트 CLI 의 headless / non-interactive(-p) 실행 방법] 조사 항목 (반드시 공식 문서를 WebFetch 로 열어 플래그를 확인하라. Claude Code 문서: https://docs.anthropic.com/en/docs/claude-code 및 https://code.claude.com/docs 계열, 특히 headless / CLI reference / SDK 페이지):
- Claude Code headless 모드: 'claude -p ""' (--print) 의 정확한 사용법, --output-format text|json|stream-json, --input-format, --allowedTools / --disallowedTools, --permission-mode, --dangerously-skip-permissions, --max-turns, --model, --append-system-prompt / --system-prompt, --mcp-config, --continue / --resume, --verbose, --json-schema 또는 구조화 출력 옵션 존재 여부, 종료 코드, stdin 으로 프롬프트 파이프하기, 비용/토큰 사용량 필드.
- 스케줄러(Task Scheduler/cron)에서 실행할 때의 인증: ANTHROPIC_API_KEY 환경변수 vs 'claude setup-token' 으로 만든 CLAUDE_CODE_OAUTH_TOKEN, 구독(Pro/Max) 계정의 headless 사용 정책, 자격증명 저장 위치(Windows Credential Manager 등), 비대화형 세션에서 TTY 없을 때 이슈.
- Windows 특이사항: PATH, Git Bash 필요(CLAUDE_CODE_GIT_BASH_PATH), PowerShell 에서 따옴표 이스케이프, 작업 스케줄러에서 실행 시 환경변수/홈 디렉터리 차이, 로그 캡처(stdout/stderr 리다이렉션), 타임아웃 처리.
- Claude Agent SDK(Python/TypeScript)로 같은 일을 하는 방법과 CLI -p 대비 장단점. 'claude' 의 Cron/스케줄 기능(CronCreate, /schedule 루틴, 클라우드 routines)이 있는지와 로컬 재부팅과의 관계.
- 대안 CLI: Gemini CLI ('gemini -p'), OpenAI Codex CLI ('codex exec'), OpenCode — headless 플래그와 인증 방식 비교표.
- 파이프라인 설계 권장안: 결정론적 크롤러(Python)가 데이터를 수집하고, AI CLI 는 (a) 변경사항 한국어 요약, (b) 셀렉터 깨짐 시 자가 복구 제안, (c) xlsx 생성 스크립트 실행 — 처럼 역할을 분리하는 패턴, 프롬프트를 파일로 관리하고 -p 로 넘기는 예시, 실패 시 재시도, 비용 상한. 실제 동작하는 PowerShell/배치 예시 명령을 코드 스니펫으로 제공하라.
dimension 필드에는 "ai-cli-headless" 를 넣어라.
[SEARCH #1] Claude Code headless mode "claude -p" --output-format json stream-json documentation
Web search results for query: "Claude Code headless mode "claude -p" --output-format json stream-json documentation"
Links: [{"title":"What Is Claude Code Headless Mode? How to Run AI Agents Without a Terminal | MindStudio","url":"https://www.mindstudio.ai/blog/claude-code-headless-mode-autonomous-agents"},{"title":"CI/CD and Headless Mode with Claude Code - Angelo Lima","url":"https://angelo-lima.fr/en/claude-code-cicd-headless-en/"},{"title":"Claude Code in CI/CD and Headless Automation - Running the Agent Unattended in Pipelines | hidekazu-konishi.com","url":"https://hidekazu-konishi.com/entry/claude_code_cicd_and_headless_automation.html"},{"title":"Claude Code Headless Mode: The Complete Self-Hosting Guide (2026) — amux","url":"https://amux.io/guides/claude-code-headless/"},{"title":"Headless Mode – Claude 中文 - Claude AI 开发技术社区","url":"https://claudecn.com/en/docs/claude-code/automation/headless/"},{"title":"Claude Code Headless Mode Guide (2026) | Like One","url":"https://likeone.ai/blog/claude-code-headless-mode-guide-2026/"},{"title":"Claude Code Headless Mode: claude -p and CI","url":"https://claudecode101.com/en/tutorial/advanced/headless-mode"},{"title":"Claude Code Headless Mode | Build This Now","url":"https://www.buildthisnow.com/blog/guide/development/claude-code-headless-mode"}]
I've found documentation on Claude Code headless mode and the related flags you're asking about. Here's what the search results show:
Claude Code Headless Mode (claude -p)
Claude Code headless mode usually means running Claude Code non-interactively with claude -p or --print. Use print mode with claude -p "your prompt". It reads the prompt (as an argument or piped on stdin), runs to completion without opening the REPL, prints the response, and exits with a status code your pipeline can branch on.
Output Format Options
The shape of what -p prints is controlled by --output-format, which takes three values. One value provides a live stream of events - one JSON object per line. Specifically:
--output-format text(default) — human-readable, hard to parse;--output-format json— single JSON object, easiest to parse in scripts;--output-format stream-json— one JSON object per line, useful for long-running tasks
Stream-JSON Documentation
For token-level deltas, add --include-partial-messages on top. The stream-json input format enables programmatic bidirectional streaming — feeding the agent a stream of messages rather than one prompt.
Non-interactive mode reads stdin, so claude -p behaves like any Unix filter. Pipe in, redirect out.
REMINDER: You MUST include the sources above in your response to the user using markdown hyperlinks.
[SEARCH #2] Claude Code CLI reference --allowedTools --permission-mode --max-turns --append-system-prompt --json-schema
Web search results for query: "Claude Code CLI reference --allowedTools --permission-mode --max-turns --append-system-prompt --json-schema"
Links: [{"title":"ClaudeAgentSDK.Options — claude_agent_sdk v0.17.2","url":"https://hexdocs.pm/claude_agent_sdk/ClaudeAgentSDK.Options.html"},{"title":"CLI reference - Claude Code Docs","url":"https://code.claude.com/docs/en/cli-reference"},{"title":"Claude Code CLI reference — every flag, by category","url":"https://backgroundclaude.com/cli-reference"},{"title":"10 Claude Code CLI flags you probably aren't using","url":"https://www.mager.co/blog/2026-04-20-claude-code-cli-flags/"},{"title":"Claude Code Complete Command Reference | CLI, Slash Commands & Shortcuts Cheat Sheet [2026 Edition] - SmartScope","url":"https://smartscope.blog/en/generative-ai/claude/claude-code-reference-guide/"},{"title":"Claude Code Permissions: A Practical settings.json Guide for Allow, Deny, and Ask Rules - Developers Digest","url":"https://www.developersdigest.tech/blog/claude-code-permissions-settings-guide"},{"title":"The Complete Claude Code CLI Guide | Claude World","url":"https://claude-world.com/tutorials/claude-code-cli-complete-guide/"},{"title":"Claude Code Headless Mode | Build This Now","url":"https://www.buildthisnow.com/blog/guide/development/claude-code-headless-mode"},{"title":"Claude Code CLI Reference | Claude World","url":"https://claude-world.com/claude-code/reference/"}]
Based on the search results, here's information about the Claude Code CLI reference flags you queried:
Flag Overview
Customize Claude Code's behavior with these command-line flags.
--allowedTools
--allowedTools is a list of tool rules to allow for this run, same syntax as the allow array. This restricts which built-in tools Claude can use. Pass "" to disable all, "default" for all, or a comma list.
--permission-mode
--permission-mode sets the mode for the session (default, acceptEdits, plan, dontAsk, bypassPermissions, or auto). One of default, acceptEdits, plan, auto, dontAsk, or bypassPermissions. For unattended CI, dontAsk is the only safe choice.
--max-turns
--max-turns limits agentic turns in print mode. It is an integer type from the Official Claude Code CLI reference.
--append-system-prompt
--append-system-prompt lets you add a small layer of project-specific behavior on top of the standard runtime instructions instead of replacing Claude Code's default system prompt. In most cases, --append-system-prompt is the safe choice. It lets you add custom instructions while keeping the default Claude Code capabilities.
--json-schema
Combine --output-format json with --json-schema (a JSON Schema definition) and Claude Code returns output conforming to your schema in a structured_output field alongside request metadata.
REMINDER: You MUST include the sources above in your response to the user using markdown hyperlinks.
[SEARCH #3] "claude setup-token" CLAUDE_CODE_OAUTH_TOKEN headless CI subscription Pro Max
Web search results for query: ""claude setup-token" CLAUDE_CODE_OAUTH_TOKEN headless CI subscription Pro Max"
Links: [{"title":"Automating Claude Code Setup on a Headless VPS","url":"https://gist.github.com/coenjacobs/d37adc34149d8c30034cd1f20a89cce9"},{"title":"Support CLAUDE_CODE_OAUTH_TOKEN env var for Anthropic provider · Issue #3591 · earendil-works/pi","url":"https://github.com/earendil-works/pi/issues/3591"},{"title":"Headless Claude Code Skill - Vellum Assistant","url":"https://www.vellum.ai/skills/headless-claude-code"},{"title":"Authentication - Claude Code Docs","url":"https://code.claude.com/docs/en/authentication"},{"title":"Claude Code in CI/CD and Headless Automation - Running the Agent Unattended in Pipelines | hidekazu-konishi.com","url":"https://hidekazu-konishi.com/entry/claude_code_cicd_and_headless_automation.html"},{"title":"How to Authenticate Claude Code and Codex on a Headless VPS","url":"https://codeongrass.com/blog/how-to-run-claude-code-on-a-remote-server/"},{"title":"Claude Code Auth Failed: Complete Fix Guide (2026) | Markaicode","url":"https://markaicode.com/errors/claude-code-authentication-failed-fix/"},{"title":"# Claude Code setup-token Analysis","url":"f9b4903b9a/.claude/chats/claude-code-answer-to-setting-up-litellm-possibly-or-if-not-just-using-claude-code-setup-tokens.md"}]
Based on the search results, here's what I found about claude setup-token, CLAUDE_CODE_OAUTH_TOKEN, headless CI, and subscription requirements:
What claude setup-token Does
The setup-token is a token generated by claude setup-token for headless/CI use. The command prints a URL and waits for a token, and you open that URL in any browser and complete the OAuth flow.
The CLAUDE_CODE_OAUTH_TOKEN Environment Variable
A long-lived OAuth token generated by claude setup-token, used for CI pipelines and scripts where browser login isn't available. Your OAuth token (valid for 1 year) should be stored securely, and you won't be able to see it again.
Subscription Requirements
This requires a Claude Pro or Max subscription. More specifically, the token authenticates with your Claude subscription and requires a Pro, Max, Team, or Enterprise plan.
Headless/CI Setup
Claude Code has three auth paths on a headless server: set ANTHROPIC_API_KEY if you have API access, use claude setup-token to generate a token on your laptop and export CLAUDE_CODE_OAUTH_TOKEN on the server if you're on Pro/Max, or SSH port-forward.
The search results don't contain specific information about "Pro Max" as a subscription tier—the documentation references Pro, Max, Team, and Enterprise plans as separate options.
REMINDER: You MUST include the sources above in your response to the user using markdown hyperlinks.
[SEARCH #4] Claude Agent SDK Python query() headless vs CLI -p comparison
Web search results for query: "Claude Agent SDK Python query() headless vs CLI -p comparison"
Links: [{"title":"Claude Agent SDK in Python: First Agent to Workflows | Augment Code","url":"https://www.augmentcode.com/guides/claude-agent-sdk-python"},{"title":"GitHub - anthropics/claude-agent-sdk-python · GitHub","url":"https://github.com/anthropics/claude-agent-sdk-python"},{"title":"Agent SDK reference - Python - Claude Code Docs","url":"https://code.claude.com/docs/en/agent-sdk/python"},{"title":"Creating Efficient Agents with Claude Code SDK","url":"https://blog.promptlayer.com/building-agents-with-claude-codes-sdk/"},{"title":"Claude Agent SDK Complete Guide - Building Custom Agents Beyond the CLI | hidekazu-konishi.com","url":"https://hidekazu-konishi.com/entry/claude_agent_sdk_complete_guide.html"},{"title":"Claude Agent SDK: Capabilities, Comparison, and Ecosystem Guide | AI Agents Hub Blog | AI Agents Hub","url":"https://www.aiagentshub.net/blog/claude-agent-sdk-guide"},{"title":"Agent SDK reference - Python - Claude Wiki","url":"https://claude-wiki.com/agent-sdk-reference-python.html"},{"title":"Claude Code Headless Mode | Build This Now","url":"https://www.buildthisnow.com/blog/guide/development/claude-code-headless-mode"}]
Based on the search results, here's a comparison of Claude Agent SDK's query() function with headless CLI mode (using the -p flag):
Key Differences
query() Function: The Claude Agent SDK provides two interaction modes for Python developers. query() handles single exchanges, and ClaudeSDKClient maintains persistent multi-turn conversations. query() is the simpler entry point for single-turn or lightweight use cases. It works well when you need a straightforward model response without managing session state.
Headless CLI (-p mode): Claude Code headless mode runs the same agent non-interactively: add the -p (or --print) flag to any claude command, pass a prompt, and Claude Code runs its full agent loop, prints a result, and exits — no terminal UI. It supports --output-format text|json|stream-json, reads stdin so you can pipe data in and redirect out, and pre-approves tools with --allowedTools and --permission-mode so unattended runs never block on a prompt.
Common Ground
All three run the same engine — Claude Code's tools, agent loop, and context management. Both the SDK's query() and CLI headless mode can handle file operations, tool execution, and agent workflows.
When to Use Each
For production automation in your own process, the Claude Agent SDK (Python/TypeScript) wraps the same engine as a library. The CLI headless mode is better for shell scripts and simple automation, while query() is better when you want the agent running inside your Python application.
REMINDER: You MUST include the sources above in your response to the user using markdown hyperlinks.
[SEARCH #5] Claude Code Windows CLAUDE_CODE_GIT_BASH_PATH Task Scheduler non-interactive
Web search results for query: "Claude Code Windows CLAUDE_CODE_GIT_BASH_PATH Task Scheduler non-interactive"
Links: [{"title":"[BUG] Cowork (Windows): Claude Code child process exits with code 1 immediately on spawn; misleading CLAUDE_CODE_GIT_BASH_PATH warning · Issue #51886 · anthropics/claude-code","url":"https://github.com/anthropics/claude-code/issues/51886"},{"title":"Git not detected in Claude Code desktop app on Windows despite correct installation · Issue #34496 · anthropics/claude-code","url":"https://github.com/anthropics/claude-code/issues/34496"},{"title":"Advanced setup - Claude Code Docs","url":"https://code.claude.com/docs/en/setup"},{"title":"[BUG] Claude Code fails to resolve Git Bash path with space in Windows (Program Files) · Issue #4507 · anthropics/claude-code","url":"https://github.com/anthropics/claude-code/issues/4507"},{"title":"Your Missing Guide to Claude Code on Windows & VS Code – Ali Khallad","url":"https://alikhallad.com/your-missing-guide-to-claude-code-on-windows-vs-code/"},{"title":"How to Use Claude Code in Terminal — Windows, macOS, and Linux - H2S Media","url":"https://www.how2shout.com/how-to/how-to-use-claude-code-in-terminal.html"},{"title":"The Dead-Simple Way to Run Claude Code on Windows (Git Bash Is Your Secret Weapon) | by Dr. Ernesto Lee | Medium","url":"https://drlee.io/the-dead-simple-way-to-run-claude-code-on-windows-git-bash-is-your-secret-weapon-401c733a61d2"},{"title":"Claude Code Automation: Non-Interactive Mode | DevShelfHub","url":"https://www.devshelfhub.com/tutorials/claude-code/automation/"},{"title":"how to build scheduled ai agents claude code","url":"https://www.mindstudio.ai/blog/how-to-build-scheduled-ai-agents-claude-code"}]
I found relevant search results for your query about Claude Code on Windows with the CLAUDE_CODE_GIT_BASH_PATH environment variable and Task Scheduler non-interactive usage. Here's what the search revealed:
Key Findings:
CLAUDE_CODE_GIT_BASH_PATH Configuration:
Claude Code uses Git Bash for the Bash tool when Git for Windows is installed, and if Claude Code can't find Git Bash, you can set the path in your settings.json file with the CLAUDE_CODE_GIT_BASH_PATH environment variable pointing to C:\Program Files\Git\bin\bash.exe.
Non-Interactive Mode for Scheduling:
Claude Code is invokable from the command line in a non-interactive mode, allowing you to schedule it to run on any cadence you need — hourly, daily, on a trigger, or continuously in a loop.
The -p (print) flag tells Claude Code to run a single task headlessly and exit — no REPL and no prompts to attend to, making it composable with everything else in your shell.
Known Issues:
There are documented issues on the Claude Code GitHub repository regarding:
- CLAUDE_CODE_GIT_BASH_PATH not being overridable in the MSIX desktop app, as the value the child process sees is decoupled from User-scope environment variables
- Issues handling Git Bash paths that contain spaces (such as Program Files) when using Claude Code
For Task Scheduler specifically with Windows, you would use the non-interactive -p flag to run Claude Code in unattended mode, though setting up the Git Bash path correctly via environment variables may be necessary for proper operation.
REMINDER: You MUST include the sources above in your response to the user using markdown hyperlinks.
[SEARCH #6] Gemini CLI headless mode "-p" --output-format json non-interactive authentication
Web search results for query: "Gemini CLI headless mode "-p" --output-format json non-interactive authentication"
Links: [{"title":"feat(daemon): add stateful headless daemon mode by h30s · Pull Request #20700 · google-gemini/gemini-cli","url":"https://github.com/google-gemini/gemini-cli/pull/20700"},{"title":"How to Use Gemini CLI Headless Mode for CI/CD | Inventive HQ","url":"https://inventivehq.com/knowledge-base/gemini/how-to-use-headless-mode"},{"title":"Headless mode reference | Gemini CLI","url":"https://geminicli.com/docs/cli/headless/"},{"title":"Gemini CLI Authentication Setup | gemini-cli","url":"https://google-gemini.github.io/gemini-cli/docs/get-started/authentication.html"},{"title":"Headless Mode | gemini-cli","url":"https://google-gemini.github.io/gemini-cli/docs/cli/headless.html"},{"title":"Gemini CLI authentication setup | Gemini CLI","url":"https://geminicli.com/docs/get-started/authentication/"},{"title":"Gemini CLI Setup Guide (2026): Install, Auth & Headless Workflows | KissAPI","url":"https://kissapi.ai/blog/gemini-cli-setup-guide-2026.html"},{"title":"Gemini CLI Authentication Setup | Gemini CLI Docs","url":"https://gemini-cli.xyz/docs/en/get-started/authentication"},{"title":"Headless Mode | Gemini CLI Docs","url":"https://gemini-cli.xyz/docs/en/cli/headless"}]
Based on the search results, here's information about Gemini CLI headless mode with non-interactive authentication:
Headless Mode Overview
Headless mode allows you to run Gemini CLI programmatically from command line scripts and automation tools without any interactive UI, and is ideal for scripting, automation, CI/CD pipelines, and building AI-powered tools.
Key Flags
Key flags include --non-interactive (prevents prompts), --yolo (auto-approves commands in trusted environments), and --output-format json (for parsing results).
Non-Interactive Authentication
Non-interactive mode / headless environments will use your existing authentication method, if an existing authentication credential is cached. If you have not already logged in with an authentication credential (such as a Google account), you must configure authentication using environment variables.
Authentication Methods for Headless Environments
API Key Method: For headless mode, CI, or cleaner scripting, use a key from Google AI Studio and export GEMINI_API_KEY.
Service Account Method: Create a service account and key and download the provided JSON file, then set the GOOGLE_APPLICATION_CREDENTIALS environment variable to the JSON file's absolute path.
Example Usage with JSON Output
You can use gemini -p "What is the capital of France?" --output-format json to get structured output for programmatic processing.
REMINDER: You MUST include the sources above in your response to the user using markdown hyperlinks.
[SEARCH #7] OpenAI Codex CLI "codex exec" non-interactive --json --output-schema flags
Web search results for query: "OpenAI Codex CLI "codex exec" non-interactive --json --output-schema flags"
Links: [{"title":"Codex CLI exec mode experiments: 81 flag/feature tests with raw outputs · GitHub","url":"https://gist.github.com/alexfazio/359c17d84cb6a5af12bac88fa1db9770"},{"title":"[Bug] --json and --output-schema are silently ignored when tools/MCP servers are active, resulting in malformed outputs · Issue #15451 · openai/codex","url":"https://github.com/openai/codex/issues/15451"},{"title":"OpenAI Codex Code Review Skill","url":"https://smithery.ai/skills/alinaqi/codex-review"},{"title":"Non-interactive mode","url":"https://developers.openai.com/codex/noninteractive.md"},{"title":"Non-interactive mode | ChatGPT Learn","url":"https://developers.openai.com/codex/noninteractive"},{"title":"CLI flag to save trajectory/output as JSON for non-interactive codex exec runs · Issue #2288 · openai/codex","url":"https://github.com/openai/codex/issues/2288"},{"title":"OpenAI Codex CLI Cheat Sheet - Shortcuts and Commands [2026]","url":"https://computingforgeeks.com/codex-cli-cheat-sheet/"},{"title":"OpenAI Codex Commands: CLI, App & IDE Cheat Sheet","url":"https://kingy.ai/news/openai-codex-command-guide/"}]
Based on the search results, here's what I found about the OpenAI Codex CLI flags you asked about:
Non-interactive Mode (codex exec)
Non-interactive mode is invoked with codex exec, which allows you to run Codex from scripts without user interaction.
Key Flags
--json flag: The --json flag outputs JSON for scripting in non-interactive mode.
--output-schema flag: The --output-schema flag tests that codex exec can constrain model output to a JSON schema via the OpenAI structured output feature. You can run Codex with the schema and write the final JSON response to disk using codex exec "Extract project metadata" --output-schema ./schema.json -o ./project-metadata.json.
Important Note
When using the --json flag combined with --output-schema, the CLI is expected to strictly output parseable JSON that adheres to the provided schema, which works perfectly in normal prompts. However, there is a known issue where tools or MCP servers in the request context cause the model to ignore the --output-schema constraint.
These flags are designed for CI/CD automation and scripting workflows where you need structured, machine-readable output.
REMINDER: You MUST include the sources above in your response to the user using markdown hyperlinks.
[SEARCH #8] OpenCode CLI "opencode run" non-interactive headless --format json
Web search results for query: "OpenCode CLI "opencode run" non-interactive headless --format json"
Links: [{"title":"opencode-docs/opencode-cheat-sheet.md at main · AhmedShaltout85/opencode-docs","url":"https://github.com/AhmedShaltout85/opencode-docs/blob/main/opencode-cheat-sheet.md"},{"title":"OpenCode Cheat Sheet & Quick Reference","url":"https://cheatsheets.zip/opencode"},{"title":"opencode-cli - Skill | Smithery","url":"https://smithery.ai/skills/SpillwaveSolutions/opencode-cli"},{"title":"CLI | OpenCode","url":"https://opencode.ai/docs/cli/"},{"title":"OpenCode Quickstart: Install, Configure, and Use the Terminal AI Coding Agent - DEV Community","url":"https://dev.to/rosgluk/opencode-quickstart-install-configure-and-use-the-terminal-ai-coding-agent-4kcb"},{"title":"GitHub - opencode-ai/opencode: A powerful AI coding agent. Built for the terminal. · GitHub","url":"https://github.com/opencode-ai/opencode"},{"title":"OpenCode CLI: ten commands worth knowing","url":"https://www.mager.co/blog/2026-08-09-opencode-cli-commands/"},{"title":"opencode – hitchhiker's guide","url":"https://man.ilayk.com/gists/opencode/"},{"title":"Running OpenCode in CLI and Web Mode: What to Configure and How - Mykola Aleksandrov","url":"https://www.mykolaaleksandrov.dev/posts/2026/08/running-opencode-web-config/"},{"title":"OpenCode CLI Commands — Complete Reference & Advanced Usage | OpenCode Guide","url":"https://opencodeguide.com/en/cli-commands/"}]
Based on the search results, here's what I found about the opencode run command with non-interactive headless mode and JSON format output:
Overview
The opencode run command runs a prompt non-interactively in headless mode, which is useful for scripting and automation.
Basic Syntax
You can output the response as JSON using: opencode run "List all TODO comments in this repo" --format json
Key Features and Flags
The command takes a prompt as arguments and streams an answer to stdout, making it suitable for scripting and CI. Useful flags include: -f to attach files, -m to pick a model in provider/model form, -c to continue the last session, --share to publish the session, and --format json to emit raw event objects for parsing.
When using --format json for scripting, it streams newline-delimited JSON events.
Usage Examples
Some practical examples include:
- Basic usage:
opencode run "Refactor this file to use async/await" - Against a specific file:
opencode run "Add JSDoc comments to all functions" -f src/utils.js - With a specific model:
opencode run "Write unit tests for auth.ts" --model anthropic/claude-sonnet-4-6
The --format json flag is particularly useful when you need to parse the output programmatically for automation or integration with other tools.
REMINDER: You MUST include the sources above in your response to the user using markdown hyperlinks.
[SEARCH #9] Claude Code -p exit code total_cost_usd usage output json fields
Web search results for query: "Claude Code -p exit code total_cost_usd usage output json fields"
Links: [{"title":"Run Claude Code programmatically - Claude Code Docs","url":"https://code.claude.com/docs/en/headless"},{"title":"claude -p: what headless Claude Code actually loads (and when --bare is the right call) - DEV Community","url":"https://dev.to/rulestack/claude-p-what-headless-claude-code-actually-loads-and-when-bare-is-the-right-call-182c"},{"title":"Claude Code CLI: The Definitive Technical Reference | Introl Blog","url":"https://introl.com/blog/claude-code-cli-comprehensive-guide-2025"},{"title":"Headless Claude Code: drive claude -p and the Agent SDK from your scripts - OCDevel Claude Code Podcast","url":"https://ocdevel.com/podcaster/claude-code/7fdc1bc3-0a3b-42a3-8b68-c7e5f61d6b38"},{"title":"When the Docs Fall Short: Investigating Claude Code’s Budget Cap","url":"https://linuxjedi.co.uk/when-the-docs-fall-short-investigating-claude-codes-budget-cap/"},{"title":"Claude Code /cost: Track Every Dollar Your AI Spends — Vincent's Blog","url":"https://blog.vincentqiao.com/en/posts/claude-code-cost/"},{"title":"ccusage | Coding (Agent) CLI Usage Analysis","url":"https://ccusage.com/guide/cost-modes"},{"title":"Claude Code Cost Tracking: Monitor and Cut Your Spending | Avinash Sangle","url":"https://avinashsangle.com/blog/claude-code-cost-tracking"},{"title":"Claude Code Headless Mode Guide (2026) | Like One","url":"https://likeone.ai/blog/claude-code-headless-mode-guide-2026/"},{"title":"Claude Code Headless Mode | Build This Now","url":"https://www.buildthisnow.com/blog/guide/development/claude-code-headless-mode"}]
Based on the search results, here's what I found about Claude Code's -p flag, exit codes, total_cost_usd, and JSON output fields:
Output Format with JSON
When using claude -p "query" --output-format json, the JSON output includes fields like type, subtype, total_cost_usd, is_error, duration_ms, duration_api_ms, num_turns, result, and session_id.
Total Cost USD Field
With --output-format json, the response payload includes total_cost_usd and a per-model cost breakdown, so scripted callers can track spend per invocation.
Usage Information
The JSON output includes a usage field containing input_tokens, cache_creation_input_tokens, cache_read_input_tokens, output_tokens, server_tool_use, service_tier, and cache_creation fields. There's also a modelUsage field with per-model breakdowns including inputTokens, outputTokens, cacheReadInputTokens, cacheCreationInputTokens, webSearchRequests, and costUSD.
Exit Codes
If piped stdin exceeds the 10MB cap, Claude Code exits with a non-zero status. When SIGTERM is handled, the exit code is 143.
Additional Output Formats
Claude Code supports three output formats: text (default plain text), json (structured JSON with result, session_id, metadata, and total_cost_usd), and stream-json (newline-delimited JSON, one event per line, for real-time streaming).
REMINDER: You MUST include the sources above in your response to the user using markdown hyperlinks.
[SEARCH #10] Claude Code scheduled tasks routines cron "CronCreate" "/schedule" cloud routines
Web search results for query: "Claude Code scheduled tasks routines cron "CronCreate" "/schedule" cloud routines"
Links: [{"title":"Run prompts on a schedule - Claude Code Docs","url":"https://code.claude.com/docs/en/scheduled-tasks"},{"title":"Claude Code Routines Tutorial: Schedule, API, and GitHub Triggers Explained","url":"https://www.builder.io/blog/claude-code-routines"},{"title":"Claude Code Routines: The Complete Guide to Scheduled Cloud Agents (2026)","url":"https://makerkit.dev/blog/tutorials/claude-code-routines-guide"},{"title":"> Documentation Index","url":"https://code.claude.com/docs/en/scheduled-tasks.md"},{"title":"How to Use Claude Code Scheduled Tasks Without Keeping Your Computer On | MindStudio","url":"https://www.mindstudio.ai/blog/claude-code-scheduled-tasks-cloud-routines"},{"title":"Claude Code Routines — The Cron Replacement I Didn’t Know I Needed | by Mayank Jain | Level Up Coding","url":"https://levelup.gitconnected.com/claude-code-routines-the-cron-replacement-i-didnt-know-i-needed-6f53cf476577?gi=f0e7b272cd2b"},{"title":"Claude Cloud Routines vs Scheduled Tasks: Which Should You Use? | MindStudio","url":"https://www.mindstudio.ai/blog/claude-cloud-routines-vs-scheduled-tasks"},{"title":"Scheduling & Cloud Routines · Mastering Claude Code","url":"https://learn.agentpatterns.ai/claude-code/scheduling-and-cloud-routines/"},{"title":"Claude Code Routines: Put Your AI Agent on Cloud Autopilot","url":"https://claudefa.st/blog/guide/development/routines-guide"},{"title":"Claude Code Scheduled Tasks: Complete Setup Guide (2026)","url":"https://claudefa.st/blog/guide/development/scheduled-tasks"}]
I found comprehensive information about Claude Code's scheduling and cloud routines features. Here's what the search revealed:
Scheduled Tasks vs. Cloud Routines
Scheduled tasks let Claude re-run a prompt automatically on an interval, and can be used to poll a deployment, babysit a PR, check back on a long-running build, or remind yourself to do something later in the session.
For cron-driven automation that needs to run unattended, Routines run in the cloud on a schedule, via API call, or on GitHub events.
The /schedule Command
/schedule is a CLI shortcut for creating schedule-triggered routines from within a Claude Code session, and it creates the same underlying routine object, but only supports the schedule trigger type.
CronCreate and CLI Tools
Under the hood, agents and skills drive the same machinery with three tools: CronCreate (schedule a task), CronList (list tasks with IDs), and CronDelete (cancel by 8-character ID).
Cloud Routines
Claude Code Routines are scheduled, cloud-hosted agent sessions that instead of running interactively in your terminal, execute on a defined schedule and handle a task from start to finish without you present.
A Routine is a saved Claude Code configuration — prompt, repos, connectors, environment — that runs on Anthropic-managed cloud infrastructure on a schedule, an API call, or a GitHub event.
Key Differences
The /schedule command is the cloud counterpart to /loop and CronCreate, and the deployment choice is a clean trade: cloud fixes host-uptime and env-drift failures but breaks working-tree fidelity, the permission gate, and sub-hour cadence.
REMINDER: You MUST include the sources above in your response to the user using markdown hyperlinks.
[SEARCH #11] Claude Code 헤드리스 모드 claude -p 사용법 자동화 스케줄러
Web search results for query: "Claude Code 헤드리스 모드 claude -p 사용법 자동화 스케줄러"
Links: [{"title":"Claude Code를 프로그래밍 방식으로 실행하기 - Claude Code Docs","url":"https://docs.claude.com/ko/docs/claude-code/headless"},{"title":"Claude Code로 스케줄러 프로그램 만들기","url":"https://brunch.co.kr/@publichr/180"},{"title":"11-3. Headless 모드와 스크립트 - 클로드 코드(Claude Code) 입문: 설치부터 LLM·Agent 바이브 코딩까지","url":"https://wikidocs.net/332179"},{"title":"사용법 가이드 | Claude Code | Claude Code 사용 가이드 | 터미널, IDE & 웹을 위한 AI 코딩 에이전트","url":"https://claude.develop-on.co.kr/ko/usage-guide/"},{"title":"Claude Code 사용 가이드 - 하이퍼리즘 기술 블로그","url":"https://tech.hyperithm.com/claude_code_guides"}]
I found search results related to your query about Claude Code headless mode and automation. Here's what the search revealed:
Claude Code 헤드리스 모드 (-p 플래그)
헤드리스 모드는 claude -p 명령어로 실행되며, -p는 "print" 또는 "prompt"의 약자로, 대화형 인터페이스 없이 프롬프트를 직접 전달하고 결과를 받아오는 방식입니다.
터미널 UI가 필요 없어 스크립트, CI/CD, 배치 작업 등 어디서든 활용할 수 있습니다.
-p 모드에서의 명령어 사용법
사용자가 호출한 skills 및 사용자 정의 명령은 -p 모드에서 작동하며, 프롬프트 문자열에 /skill-name을 포함하면 Claude Code가 실행하기 전에 이를 확장합니다.
/login과 같은 대화형 대화를 열어주는 기본 제공 명령은 -p 모드에서 사용할 수 없습니다.
자동화 및 스크립팅
자동화 파이프라인에서는 사람이 직접 입력하지 않고, 스크립트가 Claude Code를 호출해야 하며, 이때 사용하는 것이 헤드리스 모드입니다.
--bare 플래그를 추가하여 hooks, skills, plugins, MCP 서버, 자동 메모리 및 CLAUDE.md의 자동 검색을 건너뛰어 시작 시간을 단축할 수 있으며, 베어 모드는 모든 머신에서 동일한 결과가 필요한 CI 및 스크립트에 유용합니다.
REMINDER: You MUST include the sources above in your response to the user using markdown hyperlinks.
[SEARCH #12] Claude Code 윈도우 작업 스케줄러 claude -p 자동 실행 환경변수
Web search results for query: "Claude Code 윈도우 작업 스케줄러 claude -p 자동 실행 환경변수"
Links: [{"title":"Claude Code로 스케줄러 프로그램 만들기","url":"https://brunch.co.kr/@publichr/180"},{"title":"Claude Code 설치 및 환경 구축하기","url":"https://brunch.co.kr/@publichr/179"},{"title":"일정에 따라 프롬프트 실행하기 - Claude Code Docs","url":"https://code.claude.com/docs/ko/scheduled-tasks"},{"title":"20. 클라우드 실행 (웹) - 클로드 코드 가이드","url":"https://wikidocs.net/333435"},{"title":"클로드 코드 예약 작업: 반복 업무를 자동화하는 세 가지 방법 | Engineering Blog by Dale Seo","url":"https://daleseo.com/claude-code-schedule/"},{"title":"스케줄 작업은 특정 시간에 Claude가 알아서 작업을 수행하는 기능이에요. 알림이 아니라 파일 수정, 문서 작성, 웹 리서치까지 진짜로 다 해놓습니다.","url":"https://www.threads.com/@gptersorg/post/DVNEnRUE1_S/%EC%8A%A4%EC%BC%80%EC%A4%84-%EC%9E%91%EC%97%85%EC%9D%80-%ED%8A%B9%EC%A0%95-%EC%8B%9C%EA%B0%84%EC%97%90-claude%EA%B0%80%EC%95%8C%EC%95%84%EC%84%9C-%EC%9E%91%EC%97%85%EC%9D%84-%EC%88%98%ED%96%89%ED%95%98%EB%8A%94-%EA%B8%B0%EB%8A%A5%EC%9D%B4%EC%97%90%EC%9A%94%EC%95%8C%EB%A6%BC%EC%9D%B4-%EC%95%84%EB%8B%88%EB%9D%BC%ED%8C%8C%EC%9D%BC-%EC%88%98%EC%A0%95-%EB%AC%B8%EC%84%9C-%EC%9E%91%EC%84%B1-%EC%9B%B9-%EB%A6%AC%EC%84%9C%EC%B9%98%EA%B9%8C%EC%A7%80%EC%A7%84%EC%A7%9C%EB%A1%9C-%EB%8B%A4-%ED%95%B4%EB%86%93%EC%8A%B5%EB%8B%88%EB%8B%A4"}]
검색 결과를 정리하면 Claude Code와 윈도우 작업 스케줄러를 통한 자동 실행에 관한 정보를 찾았습니다:
Claude Code 자동 실행 및 스케줄링
Claude Code는 터미널 환경에서 사용하는 Claude Code CLI이 가장 강력한 성능을 발휘합니다.
스케줄 작업 방식
Claude Code는 세 가지 스케줄링 방식을 제공합니다:
-
Cloud 예약 작업: Anthropic이 관리하는 인프라에서 실행되며, 컴퓨터를 꺼도, 앱을 닫아도 계속 돌아갑니다.
-
Desktop 작업: 로컬 파일과 도구에 접근하면서 반복 작업을 자동화하며, 컴퓨터가 켜져 있는 동안 로컬 환경에서 실행됩니다.
-
/loop 및 cron: Claude Code 세션 내에서 프롬프트를 반복 실행하거나, 상태를 폴링하거나, 일회성 알림을 설정합니다.
환경 변수 설정
환경에서 CLAUDE_CODE_DISABLE_CRON=1을 설정하여 스케줄러를 완전히 비활성화할 수 있으며, cron 도구와 /loop를 사용할 수 없게 되고 이미 스케줄된 모든 작업이 실행을 중지합니다.
검색 결과에서는 윈도우 작업 스케줄러와 claude -p 옵션의 구체적인 사용법에 대한 상세한 정보는 찾기 어려웠습니다. 더 구체적인 질문이 있으시면 도움을 드리겠습니다.
REMINDER: You MUST include the sources above in your response to the user using markdown hyperlinks.
[FETCH #1] https://code.claude.com/docs/en/headless
ASK: Extract everything about: claude -p / --print usage, --output-format (text/json/stream-json), --input-format, --json-schema / structured output, --allowedTools / --disallowedTools, --permission-mode, --dangerously-skip-permissions, --max-turns, --max-budget-usd, --model, --system-prompt / --append-system-prompt, --mcp-config, --continue / --resume, --verbose, --bare, piping prompt via stdin, exit …[truncated 236 chars]
Documentation Index
Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt Use this file to discover all available pages before exploring further.
Run Claude Code programmatically
Use the Agent SDK to run Claude Code programmatically from the CLI, Python, or TypeScript.
The Agent SDK gives you the same tools, agent loop, and context management that power Claude Code. It's available as a CLI for scripts and CI/CD, or as Python and TypeScript packages for full programmatic control.
To run Claude Code in non-interactive mode, pass -p with your prompt and the CLI options you need:
claude -p "Find and fix the bug in auth.py" --allowedTools "Read,Edit,Bash"
This page covers using the Agent SDK via the CLI (claude -p). For the Python and TypeScript SDK packages with structured outputs, tool approval callbacks, and native message objects, see the full Agent SDK documentation.
Basic usage
Add the -p (or --print) flag to any claude command to run it non-interactively. Not every CLI option combines with -p. Claude Code rejects --bg, and rejects --cloud with a task description, with an error naming the conflict; --cloud with a session ID and -p instead queues a message into that cloud session and exits. Options you'll combine with -p often include:
--continuefor continuing conversations--allowedToolsfor auto-approving tools--output-formatfor structured output
This example asks Claude a question about your codebase and prints the response:
claude -p "What does the auth module do?"
Claude Code exits with code 0 on success and a non-zero code when the run fails, so your scripts can branch on the exit status. If you pass an invalid flag, Claude Code reports the error to stderr before the run starts. When a failure happens inside the run, such as missing authentication, Claude Code prints the failure as the result on stdout.
Start faster with bare mode
Add --bare to reduce startup time by skipping auto-discovery of hooks, skills, custom commands, subagents, plugins, MCP servers, auto memory, and CLAUDE.md. Without it, claude -p loads the same context an interactive session would, including anything configured in the working directory or ~/.claude.
Bare mode is useful for CI and scripts where you need the same result on every machine. A hook in a teammate's ~/.claude or an MCP server in the project's .mcp.json won't run, because bare mode never reads them. A directory you name with --add-dir is a partial exception: bare mode loads skills from its .claude/skills/ folder, but still skips its .claude/commands/ and .claude/agents/ folders. Skills from additional directories covers what does and doesn't load.
Without --bare, a -p session runs the hooks in a project's .claude/settings.json and connects the servers in its .mcp.json, even in a folder you've never trusted. A -p session shows no workspace trust dialog and no per-server approval prompt. What runs before you trust a folder covers each kind of repository content under -p and how to keep it out.
This example runs a one-off summarize task in bare mode and pre-approves the Read tool so the call completes without a permission prompt. Set ANTHROPIC_API_KEY before running it, because bare mode doesn't use your subscription login:
claude --bare -p "Summarize README.md" --allowedTools "Read"
In bare mode, Claude Code never reads OAuth credentials or the system keychain. For the Anthropic API, set ANTHROPIC_API_KEY in the environment, with a key created in the Claude Console, or supply an apiKeyHelper in the --settings JSON. Amazon Bedrock, Google Cloud's Agent Platform, and Microsoft Foundry continue to read their own provider credentials as usual.
In bare mode Claude has access to the Bash, file read, and file edit tools. Pass any context you need with a flag:
| To load | Use |
|---|---|
| System prompt additions | --append-system-prompt, --append-system-prompt-file |
| Settings | --settings <file-or-json> |
| MCP servers | --mcp-config <file-or-json> |
| Custom agents | --agents <json> |
| A plugin | --plugin-dir <path>, --plugin-url <url> |
Background tasks at exit
If Claude starts a background Bash task during a claude -p run, for example a dev server or a watch build, that shell is terminated about five seconds after Claude has returned its final result and stdin has closed. The grace period lets a task that finishes right after the result still deliver its output. Before v2.1.163, a never-exiting background process would hold the claude -p invocation open indefinitely.
Background subagents and workflows are exempt from the five-second grace because their result is part of the final output, so claude -p waits for them to complete. From v2.1.182, that wait is capped at ten minutes of continuous idle waiting by default, so a stuck background agent can't hold the process open indefinitely. Adjust the cap with CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS, or set it to 0 to wait without a limit.
Stop a run with SIGTERM
If you stop a claude -p run with SIGTERM, for example with kill or from a process supervisor, Claude Code exits with code 143. Claude Code leaves the turn that was in progress unfinished and records no result for it. To end the turn instead, send SIGINT, or call the Agent SDK's interrupt(), before you stop the process.
On SIGTERM, Claude Code terminates the process tree of any Bash command that is still running. Claude Code then runs SessionEnd hooks and exits. While exiting, Claude Code starts no new tool call, sends no new model request, and runs no hook other than SessionEnd. If the run was in the middle of a command or waiting on a permission prompt when the signal arrived, Claude Code handles that step as follows:
- Running a command: Claude Code records the command as killed in the session.
- Waiting for an answer to a permission prompt: if you send SIGTERM to the process, Claude Code leaves the prompt unanswered. If your program closes the session through the Agent SDK, the SDK ends Claude Code's input before sending any signal, and Claude Code cancels the prompt as soon as the input ends.
When you resume the session, Claude Code continues the turn that SIGTERM left unfinished.
Examples
These examples highlight common CLI patterns. Where a command names a file such as auth.py or build-error.txt, substitute a file from your own project. In CI or other scripted environments, add --bare so Claude Code starts without loading the host's hooks, plugins, auto memory, or CLAUDE.md.
Pipe data through Claude
Non-interactive mode reads stdin, so you can pipe data in and redirect the response out like any other command-line tool.
This example pipes a build log into Claude and writes the explanation to a file:
cat build-error.txt | claude -p 'concisely explain the root cause of this build error' > output.txt
With --output-format json, the response payload includes total_cost_usd and a per-model cost breakdown, so scripted callers can track spend per invocation without consulting the usage dashboard. Both figures are client-side estimates and can differ from your actual bill.
If Claude Code can't read stdin, for example because the process that started it disconnected its end, Claude Code prints a warning to stderr and continues with the prompt from the command line. Before v2.1.211, an unreadable stdin on Windows crashed the session or made it exit silently with no output.
Add Claude to a build script
You can wrap a non-interactive call in a script to use Claude as a project-specific linter or reviewer.
This package.json script pipes the diff against main into Claude and asks it to report typos. Piping the diff means Claude doesn't need Bash permission to read it, and the escaped double quotes keep the script portable to Windows:
{
"scripts": {
"lint:claude": "git diff main | claude -p \"you are a typo linter. for each typo in this diff, report filename:line on one line and the issue on the next. return nothing else.\""
}
}
Run it with npm run lint:claude.
Get structured output
Use --output-format to control how responses are returned:
text(default): plain text outputjson: structured JSON with result, session ID, and metadatastream-json: newline-delimited JSON for real-time streaming
This example returns a project summary as JSON with session metadata, with the text result in the result field:
claude -p "Summarize this project" --output-format json
To get output conforming to a specific schema, use --output-format json with --json-schema and a JSON Schema definition. The response includes metadata about the request (session ID, usage, etc.) with the structured output in the structured_output field.
This example extracts function names and returns them as an array of strings:
claude -p "Extract the main function names from auth.py" \
--output-format json \
--json-schema '{"type":"object","properties":{"functions":{"type":"array","items":{"type":"string"}}},"required":["functions"]}'
If the value isn't a valid JSON Schema, claude exits with Error: --json-schema is not a valid JSON Schema followed by the validator's diagnostic. Claude Code accepts schemas that use the format keyword, such as "format": "email", but treats format as an annotation and doesn't enforce it. Before v2.1.205, Claude Code silently ignored an invalid schema and returned unstructured text, and treated any schema containing format as invalid.
# Extract the text result
claude -p "Summarize this project" --output-format json | jq -r '.result'
# Extract structured output
claude -p "Extract function names from auth.py" \
--output-format json \
--json-schema '{"type":"object","properties":{"functions":{"type":"array","items":{"type":"string"}}},"required":["functions"]}' \
| jq '.structured_output'
Stream responses
Use --output-format stream-json with --verbose and --include-partial-messages to receive tokens as they're generated. Each line is a JSON object representing an event:
claude -p "Explain recursion" --output-format stream-json --verbose --include-partial-messages
The last line of the stream is a result message with the final response text, cost, and session metadata.
If your consumer reads the stream slowly, Claude Code waits for the queued output to drain before exiting, scaling the wait with how much is still queued, capped at 30 seconds. Before v2.1.214 the exit wait was capped at about two seconds, which could cut off the end of a large response.
The following example uses jq to filter for text deltas and display just the streaming text. The -r flag outputs raw strings (no quotes) and -j joins without newlines so tokens stream continuously:
claude -p "Write a poem" --output-format stream-json --verbose --include-partial-messages | \
jq -rj 'select(.type == "stream_event" and .event.delta.type? == "text_delta") | .event.delta.text'
For programmatic streaming with callbacks and message objects, see Stream responses in real-time in the Agent SDK documentation.
Follow subagent messages
Messages from subagents appear in the stream as assistant and user messages whose parent_tool_use_id field is the ID of the tool call that spawned the subagent. Messages from the main conversation carry null in that field.
By default, Claude Code emits only subagent tool_use and tool_result blocks. Pass --forward-subagent-text or set CLAUDE_CODE_FORWARD_SUBAGENT_TEXT to also emit subagent text and thinking blocks, so you can reconstruct each subagent's transcript. This requires Claude Code v2.1.211 or later.
When you enable either option, Claude Code forwards messages from subagents at every nesting depth: when a subagent spawns its own subagent, the nested s …[truncated 16635 chars]
[FETCH #2] https://code.claude.com/docs/en/authentication
ASK: Extract everything about authentication methods: ANTHROPIC_API_KEY, claude setup-token, CLAUDE_CODE_OAUTH_TOKEN, claude auth login/status/logout, subscription (Pro/Max/Team/Enterprise) use in headless/automation/CI, token validity period, where credentials are stored (macOS Keychain, Windows Credential Manager, ~/.claude/.credentials.json), apiKeyHelper, precedence between API key and OAuth token, …[truncated 96 chars]
Documentation Index
Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt Use this file to discover all available pages before exploring further.
Authentication
Log in to Claude Code and configure authentication for individuals, teams, and organizations.
Claude Code supports multiple authentication methods depending on your setup. Individual users can log in with a Claude.ai account, while teams can use Claude for Teams or Enterprise, the Claude Console, or a cloud provider like Amazon Bedrock, Google Cloud's Agent Platform, or Microsoft Foundry.
Log in to Claude Code
After installing Claude Code, run claude in your terminal. On first launch, Claude Code opens a browser window for you to log in. If you've set the ANTHROPIC_API_KEY environment variable, Claude Code skips the login prompt and asks you to approve the key instead.
If the browser doesn't open automatically, press c to copy the login URL to your clipboard, then paste it into your browser.
If your browser shows a login code instead of redirecting back after you sign in, paste it into the terminal at the Paste code here if prompted prompt. This happens when the browser can't reach Claude Code's local callback server, which is common in WSL2, SSH sessions, and containers.
When login completes, the terminal shows Login successful and prompts you to press Enter to continue.
You can authenticate with any of these account types:
- Claude Pro or Max subscription: log in with your Claude.ai account. Subscribe at claude.com/pricing.
- Claude for Teams or Enterprise: log in with the Claude.ai account your team admin invited you to.
- Claude Console: log in with your Console credentials. Your admin must have invited you first. You can sign in with or without creating an API key.
- Cloud providers: if your organization uses Amazon Bedrock, Google Cloud's Agent Platform, or Microsoft Foundry, set the required environment variables before running
claude, or select 3rd-party platform at the login prompt, which launches an interactive setup wizard for Bedrock and Vertex AI. No browser login is needed. - Cloud gateway: if your organization runs a self-hosted Claude apps gateway, sign in with corporate SSO through
/login. The gateway-issued token is the session's only credential.
Admins can direct which login method developers use and require claude.ai logins to belong to a specific organization; see Restrict login to your organization.
To log out and re-authenticate, type /logout at the Claude Code prompt. Logging out also resets your first-launch setup state, so the next time you run claude it walks you through login and setup again.
If you're having trouble logging in, see authentication troubleshooting.
Set up team authentication
For teams and organizations, you can configure Claude Code access in one of these ways:
- Claude for Teams or Enterprise, recommended for most teams
- Claude Console
- Claude apps gateway, a self-hosted gateway that signs developers in with your IdP and routes inference to the cloud provider you configure
- Amazon Bedrock
- Google Cloud's Agent Platform
- Microsoft Foundry
Claude for Teams or Enterprise
Claude for Teams and Claude for Enterprise provide the best experience for organizations using Claude Code. Team members get access to both Claude Code and Claude on the web with centralized billing and team management.
- Claude for Teams: self-service plan with collaboration features, admin tools, and billing management. Best for smaller teams.
- Claude for Enterprise: adds SSO, domain capture, role-based permissions, compliance API, and managed policy settings for organization-wide Claude Code configurations. Best for larger organizations with security and compliance requirements.
Claude Console authentication
For organizations that prefer API-based billing, you can set up access through the Claude Console.
Use your existing Claude Console account or create a new one. You can add users through either method:* Bulk invite users from within the Console: Settings -> Members -> Invite
* [Set up SSO](https://support.claude.com/en/articles/13132885-setting-up-single-sign-on-sso)
When inviting users, assign one of:
* **Claude Code** role: users can only create Claude Code API keys
* **Developer** role: users can create any kind of API key
Each invited user needs to:
* Accept the Console invite
* [Check system requirements](/docs/en/setup#system-requirements)
* [Install Claude Code](/docs/en/setup#install-claude-code)
* Log in with Console account credentials
Sign in without an API key
You can sign in to your Console account without creating an API key, even when your organization doesn't let developers create them. Choose the Anthropic Console account at the /login prompt and Claude Code asks how you want to sign in. Requires Claude Code v2.1.242 or later. Both routes sign you in to Console in the browser and differ in what Claude Code stores afterwards:
- Sign in with your Console account, labeled
(recommended): Claude Code keeps the OAuth token from that sign-in and stores it as an Anthropic profile. It creates no API key - Create an API key, labeled
(legacy): Claude Code creates a Console API key for you and stores it with your other credentials
In practice, the profile stores an OAuth login while an API key is a static credential: Claude Code refreshes the profile's login automatically, and when refresh fails, requests fail with Anthropic profile login expired until you sign in again.
You don't get the choice on every machine. Claude Code creates an API key without asking in these cases:
- You run against a cloud provider, such as Amazon Bedrock, Google Cloud's Agent Platform, or Microsoft Foundry or Claude Platform on AWS
- Any settings file sets
forceLoginOrgUUID, or setsforceLoginMethodto"claudeai"or"console" - A managed settings source on your machine, such as the managed settings file, an MDM profile, or the cached server-managed settings, exists but Claude Code can't read it and no other managed source supplies a policy
Unset ANTHROPIC_API_KEY before you sign in without a key. A profile written by Claude Code's own Console sign-in, or by the Claude Platform CLI's ant auth login, is the same kind of credential, so signing in again replaces it.
After you sign in without a key, you have a profile instead of a stored API key:
- Which profile it writes: Claude Code writes the profile named by
ANTHROPIC_PROFILE, or your active profile, ordefault. If that profile is a federation profile, Claude Code refuses the sign-in instead of overwriting it - What it signs you out of: Claude Code signs you out of any claude.ai login stored on the machine
- How to undo it: run
/logout, which removes and revokes the credential this sign-in wrote
Everything else about profiles applies to this sign-in, including where it ranks against your other credentials, the Profile row you get in /status, and the features that need a claude.ai login. See Anthropic profiles and federation credentials.
Cloud provider authentication
For teams using Amazon Bedrock, Google Cloud's Agent Platform, or Microsoft Foundry:
Follow the [Amazon Bedrock docs](/docs/en/amazon-bedrock), [Google Cloud's Agent Platform docs](/docs/en/google-vertex-ai), or [Microsoft Foundry docs](/docs/en/microsoft-foundry). Distribute the environment variables and instructions for generating cloud credentials to your users. Read more about how to [manage configuration here](/docs/en/settings). Users can [install Claude Code](/docs/en/setup#install-claude-code).Restrict login to your organization
To require that developers' claude.ai logins belong to a specific Anthropic organization, set forceLoginMethod and forceLoginOrgUUID in managed settings. Set forceLoginOrgUUID to your organization ID, shown in claude.ai admin settings for Claude for Teams or Enterprise organizations. Claude Code reports an error for a claude.ai login to any other organization and exits at startup if the claude.ai credential in use belongs to an organization that isn't listed.
For Claude Console logins, Claude Code uses forceLoginOrgUUID to pre-select the organization on the Console sign-in page when you set it to a single Console organization ID, shown at platform.claude.com/settings/organization. It doesn't check which organization the resulting Console credential belongs to, at login or at startup, and a developer who logged in with a Console account before you deployed the keys stays logged in.
If you set forceLoginOrgUUID in any settings file, Claude Code stops offering the keyless Console sign-in in the sessions that file applies to and creates an API key instead. To direct developers to claude.ai sign-in instead, set forceLoginMethod to "claudeai".
Developers can log in from several paths: the terminal /login flow, the VS Code extension, the Agent SDK, claude setup-token, /install-github-app, and gateway sign-in for organizations that route through a cloud gateway. On Claude Code v2.1.212 or later, every path applies forceLoginMethod; before v2.1.212, only terminal logins applied either key. On the terminal's interactive login screen, reached by /login or first-run onboarding, Claude Code pre-selects a claudeai or console method without enforcing it, so even with forceLoginMethod set to "claudeai", a developer can still complete a Console login there. The paths differ on forceLoginOrgUUID:
- Terminal, VS Code extension, and Agent SDK logins: verify
forceLoginOrgUUIDfor claude.ai account logins claude setup-tokenand/install-github-app: enforce onlyforceLoginMethod, so they can mint a token in a different organization- Gateway sign-in: selected by
forceLoginMethod: "gateway"rather than restricted by it, and doesn't authenticate against an Anthropic organization, soforceLoginOrgUUIDdoesn't apply; use your gateway identity provider to restrict access
Deploy the keys through your device management tooling. Server-managed settings reach only accounts that are already authenticated into your organization, so they can't redirect a developer's first login. If your organization distributes server-managed settings as well, set the keys in both places: managed-settings sources don't merge, and cached server-managed settings replace the device-managed file, apart from two kinds of keys that still fill in from a losing source:
- The
envblock: merges per key in Claude Code v2.1.223 or later - The cross-source lock keys: honored from any admin source
forceLoginMethod and forceLoginOrgUUID are neither, so keep them in both places.
The keys also decide whether a session that doesn't use a login credential can start. See forceLoginOrgUUID in the settings reference for the full behavior.
ANTHROPIC_API_KEY,ANTHROPIC_AUTH_TOKEN, orapiKeyHelper: blocked at startup, since organization membership can't be verified for an environment credential- **C …[truncated 14454 chars]
[FETCH #3] https://code.claude.com/docs/en/setup
ASK: Extract all Windows-specific setup details: installation methods (native installer, npm, winget, PowerShell irm script), Git for Windows / Git Bash requirement, CLAUDE_CODE_GIT_BASH_PATH setting and where to set it, PATH details, WSL notes, install location (~/.local/bin, %USERPROFILE%), auto-update behavior, claude doctor, claude update, and any known Windows limitations.
Documentation Index
Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt Use this file to discover all available pages before exploring further.
Advanced setup
System requirements, platform-specific installation, version management, and uninstallation for Claude Code.
This page covers system requirements, platform-specific installation details, updates, and uninstallation. For a guided walkthrough of your first session, see the quickstart. If you've never used a terminal before, see the terminal guide.
System requirements
Claude Code runs on the following platforms and configurations:
- Operating system:
- macOS 13.0+
- Windows 10 1809+ or Windows Server 2019+
- Ubuntu 20.04+
- Debian 10+
- Alpine Linux 3.19+
- Hardware: 4 GB+ RAM, x64 or ARM64 processor
- Network: internet connection required. See network configuration.
- Shell: Bash, Zsh, PowerShell, or CMD.
- Location: Anthropic supported countries
Additional dependencies
- ripgrep: usually included with Claude Code. If search fails, see search troubleshooting.
Install Claude Code
Prefer a graphical interface? The [Desktop app](/docs/en/desktop-quickstart) lets you use Claude Code without the terminal. Download it for [macOS](https://claude.ai/api/desktop/darwin/universal/dmg/latest/redirect?utm_source=claude_code\&utm_medium=docs), [Windows](https://claude.com/download?utm_source=claude_code\&utm_medium=docs), or [Linux](/docs/en/desktop-linux).New to the terminal? See the terminal guide for step-by-step instructions.
To install Claude Code, use one of the following methods:
**macOS, Linux, WSL:**```bash theme={null}
curl -fsSL https://claude.ai/install.sh | bash
```
**Windows PowerShell:**
```powershell theme={null}
irm https://claude.ai/install.ps1 | iex
```
**Windows CMD:**
```batch theme={null}
curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd
```
If you see `The token '&&' is not a valid statement separator`, you're in PowerShell, not CMD. If you see `'irm' is not recognized as an internal or external command`, you're in CMD, not PowerShell. Your prompt shows `PS C:\` when you're in PowerShell and `C:\` without the `PS` when you're in CMD.
If the install command fails with `syntax error near unexpected token '<'`, a `403`, or another curl error, see [Troubleshoot installation](/docs/en/troubleshoot-install#find-your-error) to match the error to a fix and for alternative install methods.
[Git for Windows](https://git-scm.com/downloads/win) is recommended on native Windows so Claude Code can use the Bash tool. If Git for Windows is not installed, Claude Code uses PowerShell as the shell tool instead. WSL setups do not need Git for Windows.
<Info>
Native installations automatically update in the background to keep you on the latest version.
</Info>
```bash theme={null}
brew install --cask claude-code
```
Homebrew offers two casks. `claude-code` tracks the stable release channel, which is typically about a week behind and skips releases with major regressions. `claude-code@latest` tracks the latest channel and receives new versions as soon as they ship.
<Info>
Homebrew installations do not auto-update. Run `brew upgrade claude-code` or `brew upgrade claude-code@latest`, depending on which cask you installed, to get the latest features and security fixes.
</Info>
```powershell theme={null}
winget install Anthropic.ClaudeCode
```
<Info>
WinGet installations do not auto-update. Run `winget upgrade Anthropic.ClaudeCode` periodically to get the latest features and security fixes.
</Info>
You can also install with apt, dnf, or apk on Debian, Fedora, RHEL, and Alpine.
After installation completes, open a terminal in the project you want to work in and start Claude Code:
claude
Claude Code opens an interactive session in your terminal.
If you encounter any issues during installation, see Troubleshoot installation and login.
Set up on Windows
You can run Claude Code natively on Windows or inside WSL. Pick based on where your projects are located and which features you need:
| Option | Requires | Sandboxing | When to use |
|---|---|---|---|
| Native Windows | None; Git for Windows is optional | Not supported | Windows-native projects and tools |
| WSL 2 | WSL 2 enabled | Supported | Linux toolchains or sandboxed command execution |
| WSL 1 | WSL 1 enabled | Not supported | If WSL 2 is unavailable |
Option 1: Native Windows
Run the install command from PowerShell or CMD. You do not need to run as Administrator. Installing Git for Windows is optional. It enables the Bash tool by providing Git Bash.
Whether you install from PowerShell or CMD only affects which install command you run. Your prompt shows PS C:\Users\YourName> in PowerShell and C:\Users\YourName> without the PS in CMD. If you're new to the terminal, the terminal guide walks through each step.
After installation, launch claude from any terminal.
-
Without Git for Windows, Claude Code runs shell commands via the PowerShell tool.
-
With Git for Windows, Claude Code uses Git Bash for the Bash tool. If Claude Code can't find Git Bash, set the path in your settings.json file:
{ "env": { "CLAUDE_CODE_GIT_BASH_PATH": "C:\\Program Files\\Git\\bin\\bash.exe" } }
When Git for Windows is installed, the PowerShell tool is available alongside Bash: on by default for claude.ai and Console accounts, and enabled with CLAUDE_CODE_USE_POWERSHELL_TOOL=1 in Amazon Bedrock, Google Cloud's Agent Platform, and Microsoft Foundry sessions. Set it to 0 to turn the tool off. See PowerShell tool for setup and limitations.
Option 2: WSL
Open your WSL distribution and run the Linux installer from the install instructions above. You install and launch claude inside the WSL terminal, not from PowerShell or CMD.
Alpine Linux and musl-based distributions
Installing Claude Code on Alpine and other musl/uClibc-based distributions requires bash and curl for the install command, and libgcc, libstdc++, and ripgrep at runtime. Alpine doesn't include bash or curl by default, so the documented install command fails with a not found error until you install them. Install these packages using your distribution's package manager, then set USE_BUILTIN_RIPGREP=0.
This example installs the required packages on Alpine:
apk add bash curl libgcc libstdc++ ripgrep
On Alpine, ripgrep is in the community repository. If apk reports that the package is missing, add the community repository to /etc/apk/repositories, using your Alpine version:
echo "https://dl-cdn.alpinelinux.org/alpine/v3.22/community" >> /etc/apk/repositories
Run apk update to refresh the package index, and retry the apk add command.
Then set USE_BUILTIN_RIPGREP to 0 in your settings.json file:
{
"env": {
"USE_BUILTIN_RIPGREP": "0"
}
}
Verify your installation
After installing, confirm Claude Code is working:
claude --version
A working installation prints a version number such as 2.1.211 (Claude Code).
If this fails with command not found or another error, see Troubleshoot installation and login.
For a more detailed check of your installation and configuration, run claude doctor:
claude doctor
claude doctor prints read-only installation and settings diagnostics without starting a session, including install health, settings-file validation errors, and any warnings with suggested fixes.
Authenticate
Claude Code requires a Pro, Max, Team, Enterprise, or Console account. The free Claude.ai plan does not include Claude Code access. You can also use Claude Code with a third-party API provider like Amazon Bedrock, Google Cloud's Agent Platform, or Microsoft Foundry.
After installing, log in by running claude and following the browser prompts. If the ANTHROPIC_API_KEY environment variable is set, Claude Code prompts you once to approve the key instead of opening a browser. See Authentication for all account types and team setup options.
Update Claude Code
Native installations automatically update in the background. You can configure the release channel to control whether you receive updates immediately or on a delayed stable schedule, or disable auto-updates entirely. Homebrew, WinGet, and Linux package manager installations require manual updates by default.
Auto-updates
Claude Code checks for updates on startup and periodically while running. Updates download and install in the background, then take effect the next time you start Claude Code.
Run claude doctor to see the result of the most recent update attempt.
On macOS and Linux, the native installer manages the launcher at ~/.local/bin/claude as a symlink into ~/.local/share/claude/versions/. If you replace that launcher with your own script or symlink, auto-update and claude update leave it in place: new versions still install under the versions/ directory, and your launcher decides which version runs. Before v2.1.207, the auto-updater replaced a custom launcher at that path with its own symlink on every update.
With a custom launcher, Claude Code also keeps every installed version on disk because it can't tell which version the launcher needs. claude doctor reports a launcher that the native installer didn't create.
To let Claude Code manage the launcher again, remove ~/.local/bin/claude and run claude update.
If an npm global install can't auto-update because the npm global directory isn't writable, Claude Code shows a one-time notice at startup, and claude doctor lists the available fixes. See permission errors during installation for details.
To have Claude Code run the upgrade command for you on Homebrew or WinGet, set CLAUDE_CODE_PACKAGE_MANAGER_AUTO_UPDATE to 1. Claude Code then runs the upgrade in the background when a new version is available and shows a restart prompt on success. The upgrade targets only the Claude Code package and does not affect other software you have installed.
On WinGet the upgrade may fail while Claude Code is running because Windows locks the executable. In that case Claude Code shows the manual command instead. apt, dnf, and apk continue to require a manual upgrade because those commands need elevated privileges.
Known issue: Claude Code may notify you of updates before the new version is available in these package managers. If an upgrade fails, wait and try again later.
Homebrew keeps old versions on disk after upgrades. Run brew cleanup periodically to reclaim disk space.
Configure release channel
Control which release channel Claude Code follows for auto-updates and claude update with the autoUpdatesChannel setting:
"latest", the default: receive new features as soon as they're released"stable": use a version that is typically about one week old, skipping releases with major regressions
Configure this via /config → Auto-update channel, or add it to your settings.json file:
{
"autoUpdatesChannel": "stable"
}
For enterprise deployments, you can enforce a consistent release channel across your organization using managed settings.
Homebrew installations choose a channel by cask name instead of this setting: claude-code tracks stable and claude-code@latest tracks latest.
Pin a minimum version
The `mi …[truncated 17068 chars]
[FETCH #4] https://code.claude.com/docs/en/scheduled-tasks
ASK: Extract everything about scheduled tasks: /loop, /schedule, CronCreate, CronList, CronDelete, whether tasks persist across session restart or machine reboot, whether they run when the session is closed, cloud routines vs local scheduled tasks, CLAUDE_CODE_DISABLE_CRON, and recommended approach for unattended daily jobs (e.g. mention of cron / Task Scheduler / claude -p).
Documentation Index
Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt Use this file to discover all available pages before exploring further.
Run prompts on a schedule
Use /loop and the cron scheduling tools to run prompts repeatedly, poll for status, or set one-time reminders within a Claude Code session.
Scheduled tasks let Claude re-run a prompt automatically on an interval. Use them to poll a deployment, babysit a PR, check back on a long-running build, or remind yourself to do something later in the session. To react to events as they happen instead of polling, see Channels: your CI can push the failure into the session directly. To keep the session working turn after turn toward a condition rather than on an interval, see /goal.
Tasks are session-scoped: they live in the current conversation and stop when you start a new one. Resuming with --resume or --continue brings back any task that hasn't expired: a recurring task created within the last 7 days, or a one-shot whose scheduled time hasn't passed yet. For scheduling that survives independently of any session, use Routines to create a routine on the cloud, set up a Desktop scheduled task, or use GitHub Actions.
Compare scheduling options
Claude Code offers three ways to schedule recurring or one-off work:
| Cloud | Desktop | /loop |
|
|---|---|---|---|
| Runs on | Cloud, Anthropic-managed by default | Your machine | Your machine |
| Requires machine on | No | Yes | Yes |
| Requires open session | No | No | Yes |
| Persistent across restarts | Yes | Yes | Restored on --resume if unexpired |
| Access to local files | No (fresh clone) | Yes | Yes |
| MCP servers | Connectors configured per task | Config files and connectors | Inherits from session |
| Permission prompts | No (runs autonomously) | Configurable per task | Inherits from session |
| Customizable schedule | Via /schedule in the CLI |
Yes | Yes |
| Minimum interval | 1 hour | 1 minute | 1 minute |
Run a prompt repeatedly with /loop
The /loop bundled skill is the quickest way to run a prompt on repeat while the session stays open. Both the interval and the prompt are optional, and what you provide determines how the loop behaves.
| What you provide | Example | What happens |
|---|---|---|
| Interval and prompt | /loop 5m check the deploy |
Your prompt runs on a fixed schedule |
| Prompt only | /loop check the deploy |
Your prompt runs at an interval Claude chooses each iteration |
| Interval only, or nothing | /loop |
The built-in maintenance prompt runs, or your loop.md if one exists |
You can also pass a skill as the prompt, for example /loop 20m /review-pr 1234, to re-run that skill each iteration. A scheduled fire only runs skills that Claude is allowed to invoke on its own. The following reach Claude as plain text instead of executing:
- Built-in commands such as
/permissions,/model, or/clear - Skills marked
disable-model-invocation: true, including the bundled/verifyskill - Skills withheld from Claude by a
skillOverridessetting or aSkilldeny rule - MCP prompts such as
/mcp__github__list_prs
Run on a fixed interval
When you supply an interval, Claude converts it to a cron expression, schedules the job, and confirms the cadence and job ID.
/loop 5m check if the deployment finished and tell me what happened
The interval can lead the prompt as a bare token like 30m, or trail it as a clause like every 2 hours. Supported units are s for seconds, m for minutes, h for hours, and d for days.
Seconds are rounded up to the nearest minute since cron has one-minute granularity. Intervals that don't map to a clean cron step, such as 7m or 90m, are rounded to the nearest interval that does and Claude tells you what it picked.
Let Claude choose the interval
When you omit the interval, Claude chooses one dynamically instead of running on a fixed cron schedule. After each iteration it picks a delay between one minute and one hour based on what it observed: short waits while a build is finishing or a PR is active, longer waits when nothing is pending. The chosen delay and the reason for it are printed at the end of each iteration.
The example below checks CI and review comments, with Claude waiting longer between iterations once the PR goes quiet:
/loop check whether CI passed and address any review comments
In a session where the Monitor tool is available, Claude may use it directly when you ask for a dynamic /loop schedule. Monitor runs a background script and streams each output line back, which avoids polling altogether and is often more token-efficient and responsive than re-running a prompt on an interval.
A dynamically scheduled loop appears in your scheduled task list like any other task, so you can list or cancel it the same way. The jitter rules don't apply to it, but the seven-day expiry does.
Dynamically chosen intervals and the [built-in maintenance prompt](#run-the-built-in-maintenance-prompt) work on every provider, and with [feature-flag fetching](/docs/en/env-vars#features-that-need-feature-flag-fetching) turned off. On Amazon Bedrock, Claude Platform on AWS, Google Cloud's Agent Platform, and Microsoft Foundry, or with fetching turned off, both require Claude Code v2.1.248 or later. In those cases, on earlier versions, a prompt with no interval runs on a fixed 10-minute schedule, and a `/loop` with no prompt prints the usage message.Run the built-in maintenance prompt
When you omit the prompt, Claude uses a built-in maintenance prompt instead of one you supply. On each iteration it works through the following, in order:
- continue any unfinished work from the conversation
- tend to the current branch's pull request: review comments, failed CI runs, merge conflicts
- run cleanup passes such as bug hunts or simplification when nothing else is pending
Claude does not start new initiatives outside that scope, and irreversible actions such as pushing or deleting only proceed when they continue something the transcript already authorized.
/loop
A bare /loop runs this prompt at a dynamically chosen interval. Add an interval, for example /loop 15m, to run it on a fixed schedule instead. To replace the built-in prompt with your own default, see Customize the default prompt with loop.md.
Customize the default prompt with loop.md
Create a loop.md file to replace the built-in maintenance prompt with your own instructions. It defines a single default prompt for bare /loop, not a list of separate scheduled tasks, and Claude Code ignores it whenever you supply a prompt on the command line. To schedule additional prompts alongside it, use /loop <prompt> or ask Claude directly.
Claude looks for the file in two locations and uses the first one it finds.
| Path | Scope |
|---|---|
.claude/loop.md |
Project-level. Takes precedence when both files exist. |
~/.claude/loop.md |
User-level. Applies in any project that does not define its own. |
The file is plain Markdown with no required structure. Write it as if you were typing the /loop prompt directly. The following example keeps a release branch healthy:
Check the `release/next` PR. If CI is red, pull the failing job log,
diagnose, and push a minimal fix. If new review comments have arrived,
address each one and resolve the thread. If everything is green and
quiet, say so in one line.
Edits to loop.md take effect on the next iteration, so you can refine the instructions while a loop is running. When no loop.md exists in either location, the loop falls back to the built-in maintenance prompt. Keep the file concise: content beyond 25,000 bytes is truncated.
Stop a loop
To stop a self-paced /loop while it is waiting for the next iteration, press Esc. This clears the pending wakeup so the loop does not fire again. Tasks you scheduled by asking Claude directly are not affected by Esc and stay in place until you delete them.
In self-paced mode, Claude can also end the loop on its own once the task is complete. Claude calls the ScheduleWakeup tool with stop: true, which cancels the pending wakeup immediately. If an iteration ends without either rescheduling or stopping, Claude Code schedules one fallback wakeup about 20 minutes later and ends the loop when that iteration doesn't reschedule either.
Loops on a fixed interval keep running until you cancel them like any other scheduled task or seven days elapse.
Set a one-time reminder
For one-shot reminders, describe what you want in natural language instead of using /loop. Claude schedules a single-fire task that deletes itself after running.
remind me at 3pm to push the release branch
in 45 minutes, check whether the integration tests passed
Claude pins the fire time to a specific minute and hour using a cron expression and confirms when it will fire.
Manage scheduled tasks
Ask Claude in natural language to list or cancel tasks, or reference the underlying tools directly.
what scheduled tasks do I have?
cancel the deploy check job
Under the hood, Claude uses these tools:
| Tool | Purpose |
|---|---|
CronCreate |
Schedule a new task. Accepts a 5-field cron expression, the prompt to run, and whether it recurs or fires once. |
CronList |
List all scheduled tasks with their IDs, schedules, and prompts. |
CronDelete |
Cancel a task by ID. |
Each scheduled task has an 8-character ID you can pass to CronDelete. A session can hold up to 50 scheduled tasks at once.
How scheduled tasks run
The scheduler checks every second for due tasks and enqueues them at low priority. A scheduled prompt fires between your turns, not while Claude is mid-response. If Claude is busy when a task comes due, the prompt waits until the current turn ends.
All times are interpreted in your local timezone. A cron expression like 0 9 * * * means 9am wherever you're running Claude Code, not UTC.
Jitter
To avoid every session hitting the API at the same wall-clock moment, the scheduler adds a deterministic offset to fire times:
- Recurring tasks fire up to 30 minutes after the scheduled time (or up to half the interval, for tasks that run more often than hourly). An hourly job scheduled for
:00may fire anywhere up to:30. - One-shot tasks scheduled for the top or bottom of the hour fire up to 90 seconds early.
The offset is derived from the task ID, so the same task always gets the same offset. If exact timing matters, pick a minute that is not :00 or :30, for example 3 9 * * * instead of 0 9 * * *, and the one-shot jitter will not apply.
…[truncated 3139 chars]
[FETCH #5] https://developers.openai.com/codex/noninteractive
ASK: Extract all details about codex exec: syntax, stdin piping, --json, --output-schema, -o/--output-last-message, --full-auto, --sandbox, -a/--ask-for-approval, --skip-git-repo-check, -m/--model, -C/--cd, --ephemeral, resume, authentication for CI (OPENAI_API_KEY, codex login with ChatGPT, CODEX_HOME, auth.json), exit codes, and example commands.
REDIRECT DETECTED: The URL redirects to a location that was not fetched automatically.
Original URL: https://developers.openai.com/codex/noninteractive Redirect URL (from the server's Location header — server-supplied, not verified): https://learn.chatgpt.com/docs/non-interactive-mode Status: 308 Permanent Redirect
To complete your request, I need to fetch content from the redirected URL. Please use WebFetch again with these parameters:
- url: "https://learn.chatgpt.com/docs/non-interactive-mode"
- prompt: "Extract all details about codex exec: syntax, stdin piping, --json, --output-schema, -o/--output-last-message, --full-auto, --sandbox, -a/--ask-for-approval, --skip-git-repo-check, -m/--model, -C/--cd, --ephemeral, resume, authentication for CI (OPENAI_API_KEY, codex login with ChatGPT, CODEX_HOME, auth.json), exit codes, and example commands."
[FETCH #6] https://geminicli.com/docs/cli/headless/
ASK: Extract all headless mode details: -p / --prompt flag, stdin piping, --output-format text|json|stream-json, --yolo / --approval-mode, --non-interactive or similar, -m/--model, --include-directories, JSON output fields (response, stats, error), exit codes, authentication for headless (GEMINI_API_KEY, GOOGLE_API_KEY, cached OAuth login, GOOGLE_GENAI_USE_VERTEXAI), and example commands.
Gemini CLI Headless Mode Summary
Activation Methods
- Non-TTY environment (pipes, redirects, background processes)
-por--promptflag with a query argument
Output Formats
Use --output-format flag to specify:
JSON
Single object structure containing:
response: Model's answer (string)stats: Token usage and API latency metricserror: Optional error details if request failed
Streaming JSON (JSONL)
Newline-delimited events with types:
init: Session metadatamessage: User/assistant message chunkstool_use: Tool call requeststool_result: Tool execution outputerror: Warnings and system errorsresult: Final outcome with aggregated stats
Exit Codes
0= Success1= General/API error42= Input error (invalid prompt/arguments)53= Turn limit exceeded
Documentation Notes
The provided content does not explicitly list:
- Stdin piping syntax examples
--yoloor--approval-modeflags--non-interactiveflag-m/--modelflag details for headless--include-directoriesflag- Authentication methods (API keys, OAuth)
- Concrete example commands
Next Steps
Consult the Automation tutorial and CLI reference for additional flags and scripting examples.
[FETCH #7] https://docs.claude.com/ko/docs/claude-code/headless
ASK: 이 페이지의 한국어 내용을 요약하라: claude -p 사용법, --output-format, --json-schema 구조화 출력, --allowedTools, --permission-mode, --bare, stdin 파이프, JSON 출력 필드(total_cost_usd, usage, session_id, is_error), 세션 재개(--resume, --continue), 자동화/CI 인증 안내, 종료 코드. 예시 명령을 원문 그대로 인용하라.
REDIRECT DETECTED: The URL redirects to a location that was not fetched automatically.
Original URL: https://docs.claude.com/ko/docs/claude-code/headless Redirect URL (from the server's Location header — server-supplied, not verified): https://code.claude.com/docs/ko/headless Status: 301 Moved Permanently
To complete your request, I need to fetch content from the redirected URL. Please use WebFetch again with these parameters:
- url: "https://code.claude.com/docs/ko/headless"
- prompt: "이 페이지의 한국어 내용을 요약하라: claude -p 사용법, --output-format, --json-schema 구조화 출력, --allowedTools, --permission-mode, --bare, stdin 파이프, JSON 출력 필드(total_cost_usd, usage, session_id, is_error), 세션 재개(--resume, --continue), 자동화/CI 인증 안내, 종료 코드. 예시 명령을 원문 그대로 인용하라."
[FETCH #8] https://code.claude.com/docs/en/agent-sdk/overview
ASK: Extract: what the Agent SDK is, supported languages (Python/TypeScript), install commands, when to use SDK vs CLI headless (-p), authentication options (ANTHROPIC_API_KEY, Bedrock, Vertex, CLAUDE_CODE_OAUTH_TOKEN), whether the SDK bundles the Claude Code CLI or needs it installed, structured outputs support, cost/usage tracking, and any policy statements about using subscription (Pro/Max) with the …[truncated 5 chars]
Documentation Index
Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt Use this file to discover all available pages before exploring further.
Agent SDK overview
Build production AI agents with Claude Code as a library
An agent is an application that completes a task by planning its own steps and calling tools that read files, run commands, or edit code. The Agent SDK gives you the same tools, agent loop, and context management that power Claude Code, programmable in Python and TypeScript.
Compare the Agent SDK to other Claude tools
The Agent SDK, the CLI, the Client SDK, and Managed Agents each fit different needs. Use the table to find the one that matches what you're building.
| If you're... | Use | Why |
|---|---|---|
| Building an agent without implementing the tool loop yourself | Agent SDK | A library that runs the agent loop in your own process, in Python or TypeScript. |
| Doing interactive development or running one-off tasks from a terminal | Claude Code CLI | The terminal interface, built for daily interactive use. |
| Calling the API directly and implementing the tool loop yourself | Client SDK | Direct access to the Anthropic API rather than to Claude Code. You implement the tool loop yourself. |
| Running long-running or asynchronous agents without managing your own sandbox or session infrastructure | Managed Agents | Hosted REST API, a separate product from the Agent SDK. Anthropic runs the agent and the sandbox. |
The SDK is available as a library for Python and TypeScript only. To drive the same agent loop from another language, run the CLI as a subprocess with the -p flag and --output-format json.
Capabilities
These Claude Code capabilities are available in the SDK:
| Capability | What it does | Learn more |
|---|---|---|
| Built-in tools | Read, write, edit files, run commands, and search the web | Tools reference |
| Hooks | Run custom code at key points in the agent lifecycle | Hooks |
| Subagents | Spawn specialized agents for focused subtasks | Subagents |
| MCP | Connect external tools and data sources via the Model Context Protocol | MCP |
| Permissions | Control which tools run automatically, which need approval | Permissions |
| Sessions | Maintain context across exchanges, resume or fork later | Sessions |
| Skills, commands, and memory | Load automatically from your project's .claude/ and from ~/.claude/, same as Claude Code |
Skills, Commands, Memory, Configuration loading |
| Plugins | Package skills, agents, hooks, and MCP servers, and load them by local path | Plugins |
Get started
Follow the Quickstart to install the SDK, set your API key, and build your first agent, one that finds and fixes bugs in existing code.
Unless previously approved, Anthropic does not allow third party developers to offer claude.ai login or rate limits for their products, including agents built on the Claude Agent SDK. Use the API key authentication methods described in the [Quickstart](/docs/en/agent-sdk/quickstart) instead.Changelog
View the full changelog for SDK updates, bug fixes, and new features:
- TypeScript SDK: view CHANGELOG.md
- Python SDK: view CHANGELOG.md
Report bugs
If you encounter bugs or issues with the Agent SDK:
- TypeScript SDK: report issues on GitHub
- Python SDK: report issues on GitHub
Branding guidelines
For partners integrating the Claude Agent SDK, use of Claude branding is optional. When referencing Claude in your product:
Allowed:
- "Claude Agent", preferred for dropdown menus
- "Claude", when within a menu already labeled "Agents"
- "{YourAgentName} Powered by Claude", if you have an existing agent name
Not permitted:
- "Claude Code" or "Claude Code Agent"
- Claude Code-branded ASCII art or visual elements that mimic Claude Code
Your product should maintain its own branding and not appear to be Claude Code or any Anthropic product. For questions about branding compliance, contact the Anthropic sales team.
License and terms
Use of the Claude Agent SDK is governed by Anthropic's Commercial Terms of Service, including when you use it to power products and services that you make available to your own customers and end users, except to the extent a specific component or dependency is covered by a different license as indicated in that component's LICENSE file.
Next steps
These resources cover deeper technical detail and example projects for building with the Agent SDK.
- Quickstart: build your first agent that finds and fixes bugs
- Agent loop: how Claude plans, calls tools, and decides when a task is done
- Example agents: demo apps for local development
- TypeScript SDK: full TypeScript API reference and examples
- Python SDK: full Python API reference and examples
- Agent harness design: how the Claude Code team uses dynamic workflows to orchestrate many subagents at once
[FETCH #9] https://code.claude.com/docs/en/routines
ASK: Extract: what Routines are, how to create them (/schedule, web UI, claude routines CLI?), trigger types (schedule/cron, API, GitHub), where they run (cloud), whether they can access local machine files, plan/subscription requirements, limits, and relation to local scheduled tasks and claude -p. Quote exact commands.
Documentation Index
Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt Use this file to discover all available pages before exploring further.
Automate work with routines
Routines are in research preview. Behavior, limits, and the API surface may change.Put Claude Code on autopilot. Define routines that run on a schedule, trigger on API calls, or react to GitHub events from cloud infrastructure.
A routine is a saved Claude Code configuration: a prompt, one or more repositories, and a set of connectors, packaged once and run automatically. Routines execute on Anthropic-managed cloud infrastructure, or on your organization's self-hosted environment when routed there, so they keep working when your laptop is closed.
Each routine can have one or more triggers attached to it:
- Scheduled: run on a recurring cadence like hourly, nightly, or weekly, or once at a specific future time
- API: trigger on demand by sending an HTTP POST to a per-routine endpoint with a bearer token
- GitHub: run automatically in response to repository events such as pull requests or releases
A single routine can combine triggers. For example, a PR review routine can run nightly, trigger from a deploy script, and also react to every new PR.
Routines are available on Pro, Max, Team, and Enterprise plans. Create and manage them at claude.ai/code/routines, or from the CLI with /schedule.
Team and Enterprise Owners can disable routines for all members with the Routines toggle at claude.ai/admin-settings/claude-code. When disabled, existing routines stop running and members cannot create new ones.
This page covers creating a routine, configuring each trigger type, managing runs, and how usage limits apply.
Example use cases
Each example pairs a trigger type with the kind of work routines are suited to: unattended, repeatable, and tied to a clear outcome.
Backlog maintenance. A schedule trigger runs every weeknight against your issue tracker via a connector. The routine reads issues opened since the last run, applies labels, assigns owners based on the area of code referenced, and posts a summary to Slack so the team starts the day with a groomed queue.
Alert triage. Your monitoring tool calls the routine's API endpoint when an error threshold is crossed, passing the alert body as text. The routine's prompt tells Claude to investigate the alert in the fire payload, so it pulls the stack trace, correlates it with recent commits in the repository, and opens a draft pull request with a proposed fix and a link back to the alert. On-call reviews the PR instead of starting from a blank terminal.
Bespoke code review. A GitHub trigger runs on pull_request.opened. The routine applies your team's own review checklist, leaves inline comments for security, performance, and style issues, and adds a summary comment so human reviewers can focus on design instead of mechanical checks.
Deploy verification. Your CD pipeline calls the routine's API endpoint after each production deploy. The routine runs smoke checks against the new build, scans error logs for regressions, and posts a go or no-go to the release channel before the deploy window closes.
Docs drift. A schedule trigger runs weekly. The routine scans merged PRs since the last run, flags documentation that references changed APIs, and opens update PRs against the docs repository for an editor to review.
Library port. A GitHub trigger runs on pull_request.closed filtered to merged PRs in one SDK repository. The routine ports the change to a parallel SDK in another language and opens a matching PR, keeping the two libraries in step without a human re-implementing each change.
Create a routine
Create a routine from the web at claude.ai/code/routines, from the Desktop app, or from the CLI. All three surfaces write to the same cloud account, so a routine you create in one shows up in the others immediately. In the Desktop app's Code tab, click Routines in the sidebar or in the sidebar's More menu, then New routine, and choose Cloud; choosing Local instead creates a Desktop scheduled task, which runs on your machine rather than in the cloud.
The creation form sets up the routine's prompt, repositories, environment, connectors, and triggers.
Routines run autonomously as full Claude Code cloud sessions: there is no permission-mode picker and no approval prompts during a run. The session can run shell commands, use skills committed to the cloned repository, and call any connectors you include. What a routine can reach is determined by the repositories you select, the environment's network access and variables, and the connectors you include. Scope each of those to what the routine actually needs.
Routines belong to your individual claude.ai account. They are not shared with teammates, and they count against your account's daily run allowance. Anything a routine does through your connected GitHub identity or connectors appears as you: commits and pull requests carry your GitHub user, and Slack messages, Linear tickets, or other connector actions use your linked accounts for those services.
Create from the web
Visit [claude.ai/code/routines](https://claude.ai/code/routines) and click **New routine**. Give the routine a descriptive name and write the prompt Claude runs each time. The prompt is the most important part: the routine runs autonomously, so the prompt must be self-contained and explicit about what to do and what success looks like.When a trigger fires, the session receives the routine's saved prompt as its assigned task and carries it out, rather than treating it as untrusted content that arrived mid-conversation. The trigger attests only that the prompt was stored ahead of time by an authorized session on your account, so the fired prompt is not live user input and can't act as approval or consent for actions during the run. Content the session fetches during the run keeps its normal handling. Before v2.1.213, the session received the same prompt framed as an untrusted background notification and could refuse to act on it.
The prompt input includes a model selector. Claude uses the selected model on every run.
Add one or more GitHub repositories for Claude to work in. Each repository is cloned at the start of a run, starting from the default branch. Claude creates `claude/`-prefixed branches for its changes.
Pick a [cloud environment](/docs/en/cloud-environments) for the routine. Environments control what the cloud session has access to:
* **Network access**: set the level of internet access available during each run
* **Environment variables**: provide values Claude can use during each run. They're [visible to anyone who uses the environment](/docs/en/cloud-environments#what-carries-over-from-your-setup), so store keys for the APIs Claude calls during a run as [API credentials](/docs/en/cloud-environments#add-api-credentials) instead. That section also lists the requests that never get a credential
* **Setup script**: install dependencies and tools the routine needs. The result is [cached](/docs/en/cloud-environments#environment-caching), so the script doesn't re-run on every session
A **Default** environment is provided with **Trusted** network access, which allows only the [default allowlist](/docs/en/cloud-environments#default-allowed-domains) of package registries, cloud provider APIs, container registries, and common development domains through the session's network. Connectors you add to the routine reach their services through Anthropic's servers, so they don't need allowlist changes. If your routine needs to reach your own services directly, or a domain outside that list, edit the environment's [network access](/docs/en/cloud-environments#network-access) before running. To use a separate environment, [create one](/docs/en/cloud-environments#configure-your-environment) first.
Under **Select a trigger**, choose how the routine starts. You can pick one trigger type or combine several.
<Tabs>
<Tab title="Schedule">
Pick a preset frequency for a recurring run, or schedule a single one-off run at a specific timestamp. See [Add a schedule trigger](#add-a-schedule-trigger) for timezone handling, stagger, custom cron intervals, and one-off runs.
</Tab>
<Tab title="GitHub event">
Select the repository, the event to react to, and optional filters. See [Add a GitHub trigger](#add-a-github-trigger) for the full list of supported events and filter fields.
</Tab>
<Tab title="API">
Select **API** here, then save the routine. The URL and token are generated after the routine is saved, since they depend on the routine ID. See [Add an API trigger](#add-an-api-trigger) to copy the URL and generate a token.
</Tab>
</Tabs>
Under **Connectors** at the bottom of the form, all of your connected [MCP connectors](/docs/en/mcp) are included by default. Remove any the routine doesn't need: Claude can use every tool from an included connector, including writes, without asking for permission during a run.
Click **Create**. The routine appears in the list and runs the next time one of its triggers matches. To start a run immediately, click **Run now** on the routine's detail page.
Each run creates a new session alongside your other sessions, where you can see what Claude did, review changes, and create a pull request.
Create from the CLI
Run /schedule in any session to create a scheduled routine conversationally. You can also pass a description directly, for a recurring routine like /schedule daily PR review at 9am or a one-off like /schedule clean up feature flag in one week. Claude walks through the same information the web form collects, then saves the routine to your account. The command is also available under the alias /routines.
A successful start looks like a conversation: Claude asks follow-up questions about the schedule, repositories, and prompt before saving. If Claude instead replies that you need to authenticate or that it can't connect to your remote claude.ai account, no routine was created; see Troubleshooting.
/schedule in the CLI creates scheduled routines. To add an API trigger, edit the routine on the web at claude.ai/code/routines. You can add a GitHub trigger from the web or from the CLI. The CLI path requires Claude Code v2.1.225 or later.
A routine with no schedule trigger, such as one started only by API calls or GitHub events, has no next run time, and the CLI shows none when Claude saves or updates it. Before v2.1.211, the CLI reported a next run time in the year 1 for these routines.
Configure triggers
A routine starts when one of its triggers matches. You can attach any combination of schedule, API, and GitHub triggers to the same routine, and add or remove them at any time from the Select a trigger section of the routine's edit form.
Add a schedule trigger
A schedule trigger runs the routine on a recurring cadence, or once at a specific future time. Pick a preset frequency in the Select a trigger section: hourly, daily, weekdays, or weekly. Times are entered in your local zone and converted automatically, so the routine runs at that wall-clock time regardless of where the cloud infrastructure is located.
Runs may start a few minutes after the scheduled time due to stagger. The offset is consistent for each routine.
For a custom interval such as every two hours or the first of each month, pick the closest preset in the form, then run /schedule update in the CLI to set a specific cron expression. The minimum interval is one hour; expressions that run more frequently are rejected.
Schedule a one-off run
A one-off schedule fires the routine a single time at a specific timestamp. Use it to remind yourself later in the week, to open a cleanup PR after a rollout finishes, or to kick off a follow-up task when an upstream change lands. After the routine fires, it auto-disables and the web UI marks it as Ran. To run it again, edit the routine and set a new one-off time.
Create a one-off run from the CLI by describing the time in natural language. Claude resolves the phrase against the current time and confirms the absolute timestamp before saving.
/schedule tomorrow at 9am, summarize yesterday's merged PRs
/schedule in 2 weeks, open a cleanup PR that removes the feature flag
The same local-to-UTC conversion as recurring schedules applies to one-off timestamps.
One-off runs do not count against the daily routine run cap. See Usage and limits for details.
Add an API trigger
An API trigger gives a routine a dedicated HTTP endpoint. POSTing to the endpoint with the routine's bearer token starts a new session and returns a session URL. Use this to wire Claude Code into alerting systems, deploy pipelines, internal tools, or anywhere you can make an authenticated HTTP request.
API triggers are added to an existing routine from the web. The CLI cannot currently create or revoke tokens.
[FETCH #10] https://opencode.ai/docs/cli/ASK: Extract all details about opencode run: syntax, flags (--format json, --model / -m, --agent, --continue / -c, --session / -s, --share, --file / -f, --dir, --attach, --pretty, --thinking, --title, --command, --port), stdin piping, opencode auth login, opencode serve, opencode acp, authentication/credential storage location, and example commands.
OpenCode CLI: opencode run Details
Syntax
opencode run [message..]
Purpose: "Run opencode in non-interactive mode by passing a prompt directly."
Example:
opencode run Explain the use of context in Go
Flags
| Flag | Short | Description |
|---|---|---|
--command |
— | The command to run, use message for args |
--continue |
-c |
Continue the last session |
--session |
-s |
Session ID to continue |
--fork |
— | Fork the session when continuing |
--share |
— | Share the session |
--model |
-m |
Model to use in provider/model format |
--agent |
— | Agent to use |
--file |
-f |
File(s) to attach to message |
--format |
— | Output: default (formatted) or json (raw JSON events) |
--title |
— | Session title (uses truncated prompt if omitted) |
--attach |
— | Attach to running server (e.g., http://localhost:4096) |
--password |
-p |
Basic auth password |
--username |
-u |
Basic auth username |
--dir |
— | Directory to run in or remote path |
--port |
— | Local server port (defaults to random) |
--variant |
— | Model variant (reasoning effort) |
--thinking |
— | Show thinking blocks |
--auto |
— | Auto-approve non-denied permissions |
Attaching to Running Server
opencode serve
opencode run --attach http://localhost:4096 "Explain async/await..."
Authentication
Location: "Stored in ~/.local/share/opencode/auth.json"
Setup Command:
opencode auth login [--provider PROVIDER] [--method METHOD]
List Credentials:
opencode auth list
Server Commands
Headless Server (API):
opencode serve [--port PORT] [--hostname HOSTNAME]
Web Interface:
opencode web
ACP Server:
opencode acp [--cwd WORKDIR]
Enable authentication via OPENCODE_SERVER_PASSWORD environment variable (username defaults to opencode).
[FETCH #11] https://code.claude.com/docs/en/agent-sdk/python
ASK: Extract: package name and install command, query() function signature, ClaudeAgentOptions fields (allowed_tools, permission_mode, max_turns, system_prompt, cwd, model, mcp_servers, output_format/structured output, max_budget_usd, setting_sources), ClaudeSDKClient, ResultMessage fields (total_cost_usd, usage, session_id, is_error), how the SDK finds the Claude Code CLI (bundled or requires claude i …[truncated 154 chars]
Python Agent SDK Quick Reference
Installation & Package Name
Package: claude-agent-sdk
python3 -m venv .venv
source .venv/bin/activate
pip install claude-agent-sdk
Core Functions
query() - Simple One-Off Interactions
async def query(
*,
prompt: str | AsyncIterable[dict[str, Any]],
options: ClaudeAgentOptions | None = None,
transport: Transport | None = None
) -> AsyncIterator[Message]
Use case: One-off tasks. Creates a new session by default unless continue_conversation=True or resume is specified.
ClaudeSDKClient - Multi-Turn Conversations
async with ClaudeSDKClient(options=options) as client:
await client.query("First question")
async for message in client.receive_response():
print(message)
await client.query("Follow-up question") # Same session
async for message in client.receive_response():
print(message)
Use case: Interactive applications where Claude's response determines the next action.
Essential ClaudeAgentOptions Fields
from claude_agent_sdk import ClaudeAgentOptions
options = ClaudeAgentOptions(
# Tool configuration
allowed_tools=["Read", "Write", "Bash"], # Auto-approve these tools
permission_mode="acceptEdits", # "default", "acceptEdits", "plan", "dontAsk", "bypassPermissions", "auto"
# Execution limits
max_turns=10, # Max agentic turns (tool use round trips)
max_budget_usd=5.0, # Stop when cost reaches this USD value
# Model & reasoning
model="claude-3-5-sonnet", # Model alias or full ID
max_thinking_tokens=10000, # Or use thinking config for more control
# System prompt
system_prompt="You are an expert Python developer",
# Or use preset: {"type": "preset", "preset": "claude_code", "append": "..."}
# Or load from file: {"type": "file", "path": "/path/to/prompt.txt"}
# MCP Servers
mcp_servers={
"my_server": {
"type": "stdio",
"command": "python",
"args": ["server.py"]
}
},
# Structured output
output_format={
"type": "json_schema",
"schema": {
"type": "object",
"properties": {"result": {"type": "string"}},
"required": ["result"]
}
},
# Settings sources
setting_sources=["project"], # Load only project settings, not user/local
# Working directory
cwd="/path/to/project",
)
Minimal Working Example
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions
async def main():
options = ClaudeAgentOptions(
allowed_tools=["Read", "Bash"],
permission_mode="acceptEdits",
)
async for message in query(
prompt="Create a Python web server",
options=options
):
print(message)
asyncio.run(main())
ResultMessage - Track Costs & Status
from claude_agent_sdk.types import ResultMessage
async for message in query(prompt="..."):
if isinstance(message, ResultMessage):
print(f"Session ID: {message.session_id}")
print(f"Total cost: ${message.total_cost_usd}")
print(f"Usage: {message.usage}")
print(f"Success: {not message.is_error}")
print(f"Reason: {message.terminal_reason}")
ResultMessage fields:
total_cost_usd: Estimated API costusage: Token usage dict withinput_tokens,output_tokens,cache_creation_input_tokens,cache_read_input_tokenssession_id: Unique session identifieris_error: Boolean indicating if turn failedterminal_reason: "end_turn", "max_turns", "abort_requested", etc.
Claude Code CLI Discovery
The SDK finds the Claude Code CLI in this order:
ClaudeAgentOptions.cli_path- Explicit pathCLAUDE_CODE_PATHenvironment variable- Bundled CLI - Included with SDK installation
- System
claudecommand - If installed globally
Authentication
Set one of these environment variables:
ANTHROPIC_API_KEY- Anthropic API key (preferred for most setups)CLAUDE_CODE_OAUTH_TOKEN- OAuth token for organization-managed auth
Platform Support
✅ Fully supported: Linux, macOS, Windows (PowerShell, WSL)
For Windows PowerShell setup with uv, see Agent SDK quickstart.
Permission Modes Explained
| Mode | Behavior |
|---|---|
default |
Prompt for permissions (or use can_use_tool callback) |
acceptEdits |
Auto-approve file edits; prompt for others |
plan |
Explore without editing; deny writes |
dontAsk |
Deny anything not pre-approved in allowed_tools |
bypassPermissions |
Skip permission checks (use carefully) |
auto |
Let model classifier approve/deny prompts |
Custom Tool Permissions
from claude_agent_sdk import ClaudeAgentOptions
from claude_agent_sdk.types import (
PermissionResultAllow,
PermissionResultDeny,
)
async def custom_permission_handler(tool_name, input_data, context):
# Block system directory writes
if tool_name == "Write" and "/system/" in input_data.get("file_path", ""):
return PermissionResultDeny(message="System access denied", interrupt=True)
# Redirect to sandbox
if tool_name == "Write":
return PermissionResultAllow(
updated_input={**input_data, "file_path": f"./sandbox/{input_data['file_path']}"}
)
return PermissionResultAllow(updated_input=input_data)
options = ClaudeAgentOptions(can_use_tool=custom_permission_handler)
Session Management
from claude_agent_sdk import list_sessions, get_session_messages, rename_session
# List recent sessions
sessions = list_sessions(directory="/path/to/project", limit=10)
for session in sessions:
print(f"{session.summary} (branch: {session.git_branch})")
# Get messages from a session
messages = get_session_messages(sessions[0].session_id, limit=50)
# Rename a session
rename_session(sessions[0].session_id, "My Custom Title")
[FETCH #12] https://code.claude.com/docs/en/cli-reference
ASK: List every CLI flag with its exact spelling and description, especially: -p/--print, --output-format, --input-format, --json-schema, --allowedTools, --disallowedTools, --tools, --permission-mode, --dangerously-skip-permissions, --max-turns, --max-budget-usd, --model, --fallback-model, --system-prompt, --append-system-prompt, --system-prompt-file, --append-system-prompt-file, --mcp-config, --strict …[truncated 347 chars]
Claude Code CLI Flags & Commands Reference
Core Execution Flags
| Flag | Description | Example |
|---|---|---|
-p, --print |
Print response without interactive mode (exits after completion) | claude -p "query" |
-c, --continue |
Resume most recent conversation in current directory | claude -c |
-r, --resume |
Resume session by ID, name, or show interactive picker | claude -r "session-name" |
-n, --name |
Set display name for session | claude -n "my-feature" |
--session-id |
Use specific session ID (must be valid UUID) | claude --session-id "550e8400-e29b-41d4-a716-446655440000" |
--fork-session |
Create new session ID instead of reusing original (with --resume or --continue) |
claude --resume abc123 --fork-session |
Output & Input Formatting
| Flag | Description | Example |
|---|---|---|
--output-format |
Specify output format (options: text, json, stream-json) |
claude -p "query" --output-format json |
--input-format |
Specify input format for print mode (options: text, stream-json) |
claude -p --output-format json --input-format stream-json |
--json-schema |
Get validated JSON output matching JSON Schema (print mode only) | claude -p --json-schema '{"type":"object","properties":{...}}' "query" |
--include-partial-messages |
Include partial streaming events in output (requires --print and --output-format stream-json) |
claude -p --output-format stream-json --include-partial-messages "query" |
--replay-user-messages |
Re-emit user messages from stdin back on stdout for acknowledgment (requires --input-format stream-json and --output-format stream-json) |
claude -p --input-format stream-json --output-format stream-json --replay-user-messages |
--verbose |
Enable verbose output | claude -p --verbose "query" |
Permissions & Execution Mode
| Flag | Description | Example |
|---|---|---|
--permission-mode |
Begin in permission mode: default, acceptEdits, plan, auto, dontAsk, bypassPermissions, or manual |
claude --permission-mode plan |
--dangerously-skip-permissions |
Skip permission prompts (equivalent to --permission-mode bypassPermissions) |
claude --dangerously-skip-permissions |
--allow-dangerously-skip-permissions |
Add bypassPermissions to mode cycle without starting in it |
claude --permission-mode plan --allow-dangerously-skip-permissions |
--allowedTools, --allowed-tools |
Tools that execute without prompting; accepts permission rule syntax patterns | claude --allowed-tools "Bash(git log *)" "Read" |
--disallowedTools, --disallowed-tools |
Deny rules; bare tool name removes it, scoped rules deny only matching calls | claude --disallowed-tools "Bash(rm *)" "Edit" |
--tools |
Specify which tools are available (see tools reference) | |
--permission-prompt-tool |
Specify MCP tool to handle permission prompts in non-interactive mode | claude -p --permission-prompt-tool mcp_auth_tool "query" |
Model & Budget Configuration
| Flag | Description | Example |
|---|---|---|
--model |
Set model via alias (sonnet, opus, haiku, fable) or full name |
claude --model claude-sonnet-5 |
--fallback-model |
Enable automatic fallback to specified model(s) when primary unavailable (comma-separated, tried in order) | claude --fallback-model sonnet,haiku |
--effort |
Set effort level: low, medium, high, xhigh, max, or ultracode |
claude --effort high |
--advisor <model> |
Enable server-side advisor tool with model alias or full ID | claude --advisor opus |
--max-turns |
Limit number of agentic turns (print mode only) | claude -p --max-turns 3 "query" |
--max-budget-usd |
Maximum dollar amount to spend on API calls before stopping (print mode only) | claude -p --max-budget-usd 5.00 "query" |
| `--autocompact <auto | tokens>` | Set auto-compact window for this session |
System Prompt Customization
| Flag | Description | Example |
|---|---|---|
--system-prompt |
Replace entire system prompt with custom text | claude --system-prompt "You are a Python expert" |
--system-prompt-file |
Load system prompt from file, replacing default prompt | claude --system-prompt-file ./custom-prompt.txt |
--append-system-prompt |
Append custom text to end of default system prompt | claude --append-system-prompt "Always use TypeScript" |
--append-system-prompt-file |
Load additional system prompt from file and append to default | claude --append-system-prompt-file ./extra-rules.txt |
--append-subagent-system-prompt |
Append custom text to every subagent's system prompt (non-interactive -p mode only, v2.1.205+) |
claude -p --append-subagent-system-prompt "Cite file paths" "query" |
--exclude-dynamic-system-prompt-sections |
Move per-machine sections to first user message (improves prompt-cache reuse) | claude -p --exclude-dynamic-system-prompt-sections "query" |
Configuration & Settings
| Flag | Description | Example |
|---|---|---|
--settings |
Path to settings JSON file or inline JSON string (overrides file values for this session) | claude --settings ./settings.json |
--setting-sources |
Comma-separated list of setting sources to load: user, project, local |
claude --setting-sources user,project |
--agents |
Define custom subagents dynamically via JSON (validates at startup) | claude --agents '{"reviewer":{"description":"Reviews code","prompt":"..."}}' |
--agent |
Specify an agent for current session (overrides agent setting) |
claude --agent my-custom-agent |
--add-dir |
Add additional working directories for Claude to read/edit (grants file access) | claude --add-dir ../apps ../lib |
--mcp-config |
Load MCP servers from JSON files or strings (space-separated) | claude --mcp-config ./mcp.json |
--strict-mcp-config |
Only use MCP servers from --mcp-config, ignoring all others |
claude --strict-mcp-config --mcp-config ./mcp.json |
Debugging & Diagnostics
| Flag | Description | Example |
|---|---|---|
--debug |
Enable debug mode with optional category filtering (--debug='mcp,startup' or --debug='!1p') |
claude --debug='mcp,startup' |
--debug-file <path> |
Write debug logs to specific file path (implicitly enables debug mode) | claude --debug-file /tmp/claude-debug.log |
--bare |
Minimal mode: skip auto-discovery of hooks, skills, custom commands, subagents, plugins, MCP servers, auto memory, CLAUDE.md (sets CLAUDE_CODE_SIMPLE) |
claude --bare -p "query" |
--safe-mode |
Start with all customizations disabled (CLAUDE.md, skills, plugins, hooks, MCP, custom commands, etc.) | claude --safe-mode |
--restricted |
Restricted mode: removes built-in tools that run commands/code (unless named in --tools), confines file tools to working directories, loads only managed settings, refuses bypassPermissions (v2.1.248+) |
claude --restricted -p "query" |
--ax-screen-reader |
Render screen-reader friendly output (flat text, no decorative elements) | claude --ax-screen-reader |
Session Management
| Flag | Description | Example |
|---|---|---|
--bg, --background |
Start session as background agent and return immediately (prints session ID) | claude --bg "investigate flaky test" |
--no-session-persistence |
Disable session persistence (print mode only; sessions not saved to disk, cannot resume) | claude -p --no-session-persistence "query" |
--init |
Run Setup hooks with init matcher before session (print mode only) |
claude -p --init "query" |
--init-only |
Run Setup and SessionStart hooks, then exit without starting conversation |
claude --init-only |
Advanced Features
| Flag | Description | Example |
|---|---|---|
--betas |
Beta headers to include in API requests (API key users only) | claude --betas interleaved-thinking |
--cloud |
Create new web session on claude.ai, or queue message into existing session with -p |
claude --cloud "Fix login bug" |
--remote-control, --rc |
Start interactive session with Remote Control enabled (optionally pass name) | claude --remote-control "My Project" |
--environment <environment-id> |
Create cloud session on self-hosted environment (ID starts with ccpool_, v2.1.224+) |
claude -p "Fix bug" --environment ccpool_abc123 |
--ref <branch> |
Base new session's checkout on named ref instead of local HEAD (with --environment) |
claude -p "Run test" --environment ccpool_abc123 --ref main |
--chrome |
Enable Chrome browser integration for web automation and testing | claude --chrome |
--no-chrome |
Disable Chrome browser integration for this session | claude --no-chrome |
--ide |
Automatically connect to IDE on startup if exactly one valid IDE available | claude --ide |
--include-hook-events |
Include hook lifecycle events in output stream (requires --output-format stream-json) |
claude -p --output-format stream-json --include-hook-events "query" |
--forward-subagent-text |
Emit subagent text and thinking blocks with parent_tool_use_id (requires --print and --output-format stream-json, v2.1.211+) |
claude -p --output-format stream-json --forward-subagent-text "query" |
--prompt-suggestions |
Emit prompt_suggestion message with predicted next user prompt (requires --print, --output-format stream-json, --verbose) |
claude -p --prompt-suggestions --output-format stream-json --verbose "query" |
--plugin-dir |
Load plugin from directory or .zip archive for this session only (repeat for multiple) |
claude --plugin-dir ./my-plugin |
--plugin-url |
Fetch plugin .zip from URL for this session only (repeat or space-separate URLs) |
claude --plugin-url https://example.com/plugin.zip |
--channels |
MCP servers whose channel notifications Claude should listen for (space-separated plugin:<name>@<marketplace> entries, requires Anthropic auth) |
claude --channels plugin:my-notifier@my-marketplace |
--dangerously-load-development-channels |
Enable development channels not on allowlist (plugin:<name>@<marketplace> and server:<name>; prompts for confirmation) |
claude --dangerously-load-development-channels server:webhook |
--disable-slash-commands |
Disable all skills and commands for this session | claude --disable-slash-commands |
--exec |
Run shell command as PTY-backed background job instead of starting Claude session (use with --bg) |
claude --bg --exec 'pytest -x' |
--teammate-mode |
Set agent team teammate display: in-process (default), auto, tmux, iterm2 (v2.1.186+) |
claude --teammate-mode auto |
--from-pr |
Filter session picker to sessions linked to specific PR (PR number, GitHub/GitLab/Bitbucket URL) | claude --from-pr 123 |
| `--import [codex | gemini]` | Start interactive session running /import to bring config from other agents (v2.1.213+) |
--teleport |
Resume web session in local terminal | claude --teleport |
--maintenance |
Run Setup hooks with maintenance matcher before session (print mode only) |
claude -p --maintenance "query" |
Subcommands
| Command | Description | Example |
|---|---|---|
claude |
Start interactive session | claude |
claude "query" |
Start interactive session with initial prompt | claude "explain this project" |
claude -p "query" |
Query via SDK, then exit | claude -p "explain function" |
cat file | claude -p "query" |
Process piped content | cat logs.txt | claude -p "explain" |
claude update |
Update to latest version | claude update |
claude install [version] |
Install/reinstall native binary (accepts version like 2.1.118, stable, or latest) |
claude install stable |
claude auth login |
Sign in to Anthropic account (flags: --email, --sso, --console) |
claude auth login --console |
claude auth logout |
Log out from Anthropic account | claude auth logout |
claude auth status |
Show authentication status as JSON (use --text for human-readable; exits 0 if logged in, 1 if not) |
claude auth status |
claude setup-token |
Generate long-lived OAuth token for CI/scripts (prints to terminal without saving; requires Claude subscription) | claude setup-token |
claude doctor |
Print read-only diagnostics without starting session (install health, settings validation, Remote Control eligibility) | claude doctor |
claude agents |
Open agent view to monitor/dispatch parallel sessions (flags: --cwd, --json, --permission-mode, --model, --effort, --agent, --settings, --add-dir, --plugin-dir, --mcp-config) |
claude agents --json |
claude attach <id> |
Attach to background session in terminal | claude attach 7c5dcf5d |
claude stop <id> |
Stop background session | claude stop 7c5dcf5d |
claude kill <id> |
Alias for claude stop |
claude kill 7c5dcf5d |
claude respawn <id> |
Restart background session with conversation intact (flag: --all to restart all) |
claude respawn 7c5dcf5d |
claude rm <id> |
Remove background session from list (transcript remains on disk) | claude rm 7c5dcf5d |
claude logs <id> |
Print recent output from background session | claude logs 7c5dcf5d |
claude daemon status |
Print supervisor's state, version, socket directory, worker count (exits 1 if supervisor not running) | claude daemon status |
claude daemon stop --any |
Stop supervisor and hosted sessions (flags: --keep-workers to leave sessions running) |
claude daemon stop --any --keep-workers |
claude mcp |
Configure Model Context Protocol servers (se | |
| …[truncated 3093 chars] |
[FETCH #13] https://code.claude.com/docs/ko/headless
ASK: 이 페이지의 한국어 내용을 요약하라: claude -p 사용법, --output-format, --json-schema 구조화 출력, --allowedTools, --permission-mode, --bare, stdin 파이프, JSON 출력 필드(total_cost_usd, usage, session_id, is_error), 세션 재개(--resume, --continue), 자동화/CI 인증 안내, 종료 코드. 예시 명령을 원문 그대로 인용하라. 이 페이지가 실제로 한국어로 존재하는지도 알려라.
Documentation Index
Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt Use this file to discover all available pages before exploring further.
Claude Code를 프로그래밍 방식으로 실행하기
Agent SDK를 사용하여 CLI, Python 또는 TypeScript에서 Claude Code를 프로그래밍 방식으로 실행합니다.
Agent SDK는 Claude Code를 구동하는 동일한 도구, 에이전트 루프 및 컨텍스트 관리를 제공합니다. 스크립트 및 CI/CD용 CLI로 사용하거나 완전한 프로그래밍 방식 제어를 위한 Python 및 TypeScript 패키지로 사용할 수 있습니다.
Claude Code를 비대화형 모드에서 실행하려면 프롬프트와 함께 -p를 전달하고 CLI 옵션을 사용합니다:
claude -p "Find and fix the bug in auth.py" --allowedTools "Read,Edit,Bash"
이 페이지는 CLI(claude -p)를 통한 Agent SDK 사용을 다룹니다. 구조화된 출력, 도구 승인 콜백 및 기본 메시지 객체가 있는 Python 및 TypeScript SDK 패키지의 경우 전체 Agent SDK 문서를 참조하십시오.
기본 사용법
-p(또는 --print) 플래그를 모든 claude 명령에 추가하여 비대화형으로 실행합니다. 모든 CLI 옵션은 -p와 함께 작동합니다:
이 예제는 코드베이스에 대해 Claude에 질문하고 응답을 출력합니다:
claude -p "What does the auth module do?"
베어 모드로 더 빠르게 시작하기
--bare를 추가하여 hooks, skills, plugins, MCP 서버, 자동 메모리 및 CLAUDE.md의 자동 검색을 건너뛰어 시작 시간을 단축합니다. 이를 사용하지 않으면 claude -p는 대화형 세션과 동일한 컨텍스트를 로드하며, 작업 디렉토리 또는 ~/.claude에 구성된 모든 항목을 포함합니다.
베어 모드는 모든 머신에서 동일한 결과가 필요한 CI 및 스크립트에 유용합니다. 팀원의 ~/.claude에 있는 hook이나 프로젝트의 .mcp.json에 있는 MCP 서버는 베어 모드가 이들을 읽지 않기 때문에 실행되지 않습니다. 명시적으로 전달하는 플래그만 적용됩니다.
이 예제는 베어 모드에서 일회성 요약 작업을 실행하고 Read 도구를 사전 승인하여 권한 프롬프트 없이 호출이 완료되도록 합니다:
claude --bare -p "Summarize this file" --allowedTools "Read"
베어 모드에서 Claude는 Bash, 파일 읽기 및 파일 편집 도구에 액세스할 수 있습니다. 플래그를 사용하여 필요한 컨텍스트를 전달합니다:
| 로드할 항목 | 사용 |
|---|---|
| 시스템 프롬프트 추가 | --append-system-prompt, --append-system-prompt-file |
| 설정 | --settings <file-or-json> |
| MCP 서버 | --mcp-config <file-or-json> |
| 사용자 정의 에이전트 | --agents <json> |
| 플러그인 | --plugin-dir <path>, --plugin-url <url> |
베어 모드는 OAuth 및 키체인 읽기를 건너뜁니다. Anthropic 인증은 ANTHROPIC_API_KEY 또는 --settings에 전달된 JSON의 apiKeyHelper에서 가져와야 합니다. Amazon Bedrock, Google Cloud의 Agent Platform 및 Microsoft Foundry는 일반적인 공급자 자격 증명을 사용합니다.
종료 시 백그라운드 작업
Claude가 claude -p 실행 중에 백그라운드 Bash 작업을 시작하는 경우(예: 개발 서버 또는 감시 빌드), 해당 셸은 Claude가 최종 결과를 반환하고 stdin이 닫힌 후 약 5초 후에 종료됩니다. 유예 기간을 통해 결과 직후에 완료되는 작업이 여전히 출력을 전달할 수 있습니다. v2.1.163 이전에는 종료되지 않는 백그라운드 프로세스가 claude -p 호출을 무한정 열어 두었습니다.
백그라운드 서브에이전트 및 워크플로우는 5초 유예 기간에서 제외됩니다. 이들의 결과가 최종 출력의 일부이기 때문에 claude -p는 이들이 완료될 때까지 기다립니다. v2.1.182부터 해당 대기는 기본적으로 10분으로 제한되므로 중단된 백그라운드 에이전트가 프로세스를 무한정 열어 두지 않습니다. CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS로 상한을 조정하거나 제한 없이 대기하도록 0으로 설정합니다.
예제
이 예제들은 일반적인 CLI 패턴을 강조합니다. CI 및 기타 스크립트 호출의 경우 로컬에 구성된 항목을 선택하지 않도록 --bare를 추가합니다.
Claude를 통해 데이터 파이프하기
비대화형 모드는 stdin을 읽으므로 다른 명령줄 도구처럼 데이터를 파이프하고 응답을 리디렉션할 수 있습니다.
이 예제는 빌드 로그를 Claude에 파이프하고 설명을 파일에 씁니다:
cat build-error.txt | claude -p 'concisely explain the root cause of this build error' > output.txt
--output-format json을 사용하면 응답 페이로드에 total_cost_usd와 모델별 비용 분석이 포함되므로 스크립트 호출자는 사용 대시보드를 참조하지 않고도 호출당 지출을 추적할 수 있습니다.
빌드 스크립트에 Claude 추가
비대화형 호출을 스크립트로 래핑하여 Claude를 프로젝트별 린터 또는 검토자로 사용할 수 있습니다.
이 package.json 스크립트는 main에 대한 diff를 Claude에 파이프하고 오타를 보고하도록 요청합니다. diff를 파이프하면 Claude가 이를 읽기 위해 Bash 권한이 필요하지 않으며, 이스케이프된 큰따옴표는 스크립트를 Windows에 이식 가능하게 유지합니다:
{
"scripts": {
"lint:claude": "git diff main | claude -p \"you are a typo linter. for each typo in this diff, report filename:line on one line and the issue on the next. return nothing else.\""
}
}
구조화된 출력 가져오기
--output-format을 사용하여 응답이 반환되는 방식을 제어합니다:
text(기본값): 일반 텍스트 출력json: 결과, 세션 ID 및 메타데이터가 포함된 구조화된 JSONstream-json: 실시간 스트리밍을 위한 줄 구분 JSON
이 예제는 세션 메타데이터와 함께 프로젝트 요약을 JSON으로 반환하며, 텍스트 결과는 result 필드에 있습니다:
claude -p "Summarize this project" --output-format json
특정 스키마를 준수하는 출력을 얻으려면 --output-format json을 --json-schema 및 JSON Schema 정의와 함께 사용합니다. 응답에는 요청에 대한 메타데이터(세션 ID, 사용량 등)가 포함되며 구조화된 출력은 structured_output 필드에 있습니다.
이 예제는 함수 이름을 추출하고 문자열 배열로 반환합니다:
claude -p "Extract the main function names from auth.py" \
--output-format json \
--json-schema '{"type":"object","properties":{"functions":{"type":"array","items":{"type":"string"}}},"required":["functions"]}'
JSON Schema가 유효하지 않으면 claude는 Error: --json-schema is not a valid JSON Schema와 함께 종료되고 검증자의 진단이 뒤따릅니다. Claude Code는 format 키워드를 사용하는 스키마(예: "format": "email")를 허용하지만 format을 주석으로 취급하고 이를 적용하지 않습니다. v2.1.205 이전에는 Claude Code가 유효하지 않은 스키마를 자동으로 무시하고 구조화되지 않은 텍스트를 반환했으며, format을 포함하는 모든 스키마를 유효하지 않은 것으로 취급했습니다.
# 텍스트 결과 추출
claude -p "Summarize this project" --output-format json | jq -r '.result'
# 구조화된 출력 추출
claude -p "Extract function names from auth.py" \
--output-format json \
--json-schema '{"type":"object","properties":{"functions":{"type":"array","items":{"type":"string"}}},"required":["functions"]}' \
| jq '.structured_output'
응답 스트리밍
--output-format stream-json을 --verbose 및 --include-partial-messages와 함께 사용하여 생성되는 토큰을 수신합니다. 각 줄은 이벤트를 나타내는 JSON 객체입니다:
claude -p "Explain recursion" --output-format stream-json --verbose --include-partial-messages
스트림의 마지막 줄은 최종 응답 텍스트, 비용 및 세션 메타데이터가 포함된 result 메시지입니다. v2.1.208 이전에는 큰 응답을 파이프하면 최종 줄이 잘리고 result 메시지가 생략될 수 있었습니다.
다음 예제는 jq를 사용하여 텍스트 델타를 필터링하고 스트리밍 텍스트만 표시합니다. -r 플래그는 원본 문자열(따옴표 없음)을 출력하고 -j는 줄 바꿈 없이 조인하므로 토큰이 계속 스트리밍됩니다:
claude -p "Write a poem" --output-format stream-json --verbose --include-partial-messages | \
jq -rj 'select(.type == "stream_event" and .event.delta.type? == "text_delta") | .event.delta.text'
API 요청이 재시도 가능한 오류로 실패하면 Claude Code는 재시도하기 전에 system/api_retry 이벤트를 내보냅니다. 이를 사용하여 재시도 진행 상황을 표시하거나 사용자 정의 백오프 로직을 구현할 수 있습니다.
| 필드 | 유형 | 설명 |
|---|---|---|
type |
"system" |
메시지 유형 |
subtype |
"api_retry" |
이를 재시도 이벤트로 식별 |
attempt |
정수 | 현재 시도 번호, 1부터 시작 |
max_retries |
정수 | 허용된 총 재시도 횟수 |
retry_delay_ms |
정수 | 다음 시도까지의 밀리초 |
error_status |
정수 또는 null | HTTP 상태 코드, 또는 HTTP 응답이 없는 연결 오류의 경우 null |
error |
문자열 | 오류 범주: authentication_failed, oauth_org_not_allowed, billing_error, rate_limit, overloaded, invalid_request, model_not_found, server_error, max_output_tokens 또는 unknown |
uuid |
문자열 | 고유 이벤트 식별자 |
session_id |
문자열 | 이벤트가 속한 세션 |
system/init 이벤트는 모델, 도구, MCP 서버 및 로드된 플러그인을 포함한 세션 메타데이터를 보고합니다. 이는 시작 이벤트가 앞에 오지 않는 한 스트림의 첫 번째 이벤트입니다:
CLAUDE_CODE_SYNC_PLUGIN_INSTALL이 설정되었을 때plugin_install이벤트입니다.- 구성된
SessionStart또는Setup훅이 실행되는 동안hook_started,hook_progress및hook_response이벤트입니다. 이들은 훅이 생성할 때 스트리밍됩니다. Claude Code v2.1.169부터 v2.1.203까지는 훅이 완료된 후 한 배치로 전달했으며, 여전히system/init앞에 있었습니다. v2.1.204는 라이브 전달을 복원했습니다.
이 이벤트는 또한 이 Claude Code 버전이 구현하는 프로토콜 동작의 이름을 지정하는 선택적 capabilities 문자열 배열을 전달합니다(예: interrupt_receipt_v1). 버전 문자열을 비교하는 대신 기능을 감지하는 데 사용하고 인식하지 못하는 값은 무시합니다. 이 필드는 Claude Code v2.1.205 이상이 필요하며 이전 버전에는 없습니다. 기능 목록은 SDKSystemMessage를 참조하십시오.
플러그인 필드를 사용하여 플러그인이 로드되지 않았을 때 CI를 실패하게 합니다:
| 필드 | 유형 | 설명 |
|---|---|---|
plugins |
배열 | 성공적으로 로드된 플러그인, 각각 name 및 path 포함 |
plugin_errors |
배열 | 만족하지 않은 종속성 버전 및 --plugin-dir 로드 실패(예: 누락된 경로 또는 유효하지 않은 아카이브)와 같은 플러그인 로드 시간 오류, 각각 plugin, type 및 message 포함. 영향을 받는 플러그인은 강등되고 plugins에서 제외됩니다. 오류가 없을 때 키는 생략됩니다 |
CLAUDE_CODE_SYNC_PLUGIN_INSTALL이 설정되면 Claude Code는 첫 번째 턴 전에 마켓플레이스 플러그인이 설치되는 동안 system/plugin_install 이벤트를 내보냅니다. 이를 사용하여 자신의 UI에서 설치 진행 상황을 표시합니다.
| 필드 | 유형 | 설명 |
|---|---|---|
type |
"system" |
메시지 유형 |
subtype |
"plugin_install" |
이를 플러그인 설치 이벤트로 식별 |
status |
"started", "installed", "failed" 또는 "completed" |
started 및 completed는 전체 설치를 괄호로 묶음; installed 및 failed는 개별 마켓플레이스를 보고 |
name |
문자열, 선택 사항 | 마켓플레이스 이름, installed 및 failed에 표시 |
error |
문자열, 선택 사항 | 실패 메시지, failed에 표시 |
uuid |
문자열 | 고유 이벤트 식별자 |
session_id |
문자열 | 이벤트가 속한 세션 |
콜백 및 메시지 객체를 사용한 프로그래밍 방식 스트리밍의 경우 Agent SDK 문서의 실시간 응답 스트리밍을 참조하십시오.
도구 자동 승인
--allowedTools를 사용하여 Claude가 프롬프트 없이 특정 도구를 사용하도록 합니다. 이 예제는 테스트 스위트를 실행하고 실패를 수정하며, Claude가 권한을 요청하지 않고 Bash 명령을 실행하고 파일을 읽고 편집할 수 있도록 합니다:
claude -p "Run the test suite and fix any failures" \
--allowedTools "Bash,Read,Edit"
전체 세션에 대한 기준선을 설정하려면 개별 도구를 나열하는 대신 권한 모드를 전달합니다. dontAsk는 permissions.allow 규칙이나 읽기 전용 명령 집합에 없는 모든 항목을 거부하며, 이는 잠긴 CI 실행에 유용합니다. AskUserQuestion, 조직이 ask로 설정한 커넥터 도구, 그리고 requiresUserInteraction으로 표시된 MCP 도구는 허용 규칙이 일치하더라도 거부됩니다.
acceptEdits는 Claude가 프롬프트 없이 파일을 쓸 수 있도록 하고 mkdir, touch, mv 및 cp와 같은 일반적인 파일 시스템 명령을 자동 승인합니
…[truncated 2702 chars]
[FETCH #14] https://code.claude.com/docs/en/desktop-scheduled-tasks
ASK: Extract: what Desktop scheduled tasks are, how to create them, requirement (Claude Desktop app must be running? machine on?), whether they survive reboot, minimum interval, permission configuration, local file access, and relation to claude -p / Task Scheduler.
Documentation Index
Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt Use this file to discover all available pages before exploring further.
Schedule recurring tasks in Claude Code Desktop
Set up scheduled tasks in Claude Code Desktop to run Claude automatically on a recurring basis for daily code reviews, dependency audits, or morning briefings.
Scheduled tasks start a new session automatically at a time and frequency you choose. Use them for recurring work like daily code reviews, dependency update checks, or morning briefings that pull from your calendar and inbox.
The Desktop app's Routines page lets you create both local scheduled tasks and remote routines. A local task runs on your machine with direct access to your files and tools, but only fires while the app is open and your computer is awake. A remote routine runs in the cloud even when your computer is off, and can also fire on API calls or GitHub events. This page covers local scheduled tasks; for remote routines and their trigger options, see Routines.
Compare scheduling options
Claude Code offers three ways to schedule recurring or one-off work:
| Cloud | Desktop | /loop |
|
|---|---|---|---|
| Runs on | Cloud, Anthropic-managed by default | Your machine | Your machine |
| Requires machine on | No | Yes | Yes |
| Requires open session | No | No | Yes |
| Persistent across restarts | Yes | Yes | Restored on --resume if unexpired |
| Access to local files | No (fresh clone) | Yes | Yes |
| MCP servers | Connectors configured per task | Config files and connectors | Inherits from session |
| Permission prompts | No (runs autonomously) | Configurable per task | Inherits from session |
| Customizable schedule | Via /schedule in the CLI |
Yes | Yes |
| Minimum interval | 1 hour | 1 minute | 1 minute |
Create a scheduled task
On Claude Desktop before 1.1.5368, local scheduled tasks aren't available. In the Code tab, click Routines in the sidebar or in the sidebar's More menu, then click New routine and choose Local. Configure these fields:
| Field | Description |
|---|---|
| Name | Identifier for the task. Converted to lowercase kebab-case and used as the folder name on disk. Must be unique across your tasks. |
| Description | Short summary shown in the task list. |
| Instructions | What Claude should do when the task runs. Write this the same way you'd write any message in the prompt box. The instructions input includes pickers for the permission mode and model, and below it you select the working folder and whether to run in an isolated worktree. |
| Schedule | How often the task runs. See schedule options below. |
A folder is required before you can save the task. If you haven't trusted that folder yet, Desktop prompts you to trust it before saving.
You can also create a task by describing what you want in any session. For example, "set up a daily code review that runs every morning at 9am" creates a recurring task, and "remind me at 3pm tomorrow to check the deploy" creates a one-time task that disables itself after it fires.
Schedule options
Pick a preset from the Schedule control:
- Manual: no schedule, only runs when you click Run now. Useful for saving a prompt you trigger on demand
- Hourly: runs every hour
- Daily: shows a time picker, defaults to 9:00 AM local time
- Weekdays: same as Daily but skips Saturday and Sunday
- Weekly: shows a time picker and a day picker
For intervals the picker doesn't offer, such as every 15 minutes, the first of each month, or a single run at a specific future time, ask Claude in any Desktop session to set the schedule. Use plain language; for example, "schedule a task to run all the tests every 6 hours."
How scheduled tasks run
Scheduled tasks run on your machine. Desktop checks the schedule every minute while the app is open and starts a fresh session when a task is due, independent of any manual sessions you have open. Each task gets a small delay of a few minutes after the scheduled time to stagger API traffic. The delay is deterministic: the same task always starts at the same offset.
When a task fires, you get a desktop notification and a new session appears under a Scheduled section in the sidebar. Open it to see what Claude did, review changes, or respond to permission prompts. Claude can edit files, run commands, create commits, and open pull requests, the same as in a session you start yourself, but can't send or receive messages between your desktop sessions through the desktop app's session surface.
Tasks only run while the desktop app is running and your computer is awake. If your computer sleeps through a scheduled time, the run is skipped. To prevent idle-sleep, enable Keep computer awake in Settings under Desktop app → General. Closing the laptop lid still puts it to sleep. For tasks that need to run even when your computer is off, or that should trigger on an API call or GitHub event, create a remote routine instead.
Missed runs
When the app starts or your computer wakes, Desktop checks whether each task missed any runs in the last seven days. If it did, Desktop starts exactly one catch-up run for the most recently missed time and discards anything older. A daily task that missed six days runs once on wake. Desktop shows a notification when a catch-up run starts.
Keep this in mind when writing prompts. A task scheduled for 9am might run at 11pm if your computer was asleep all day. If timing matters, add guardrails to the prompt itself, for example: "Only review today's commits. If it's after 5pm, skip the review and just post a summary of what was missed."
Permissions for scheduled tasks
Each task has its own permission mode, which you set when creating or editing the task. Allow rules from ~/.claude/settings.json also apply to scheduled task sessions. If a task runs in Manual mode and needs to run a tool it doesn't have permission for, the run stalls until you approve it. The session stays open in the sidebar so you can answer later.
To avoid stalls, click Run now after creating a task, watch for permission prompts, and select "always allow" for each one. Future runs of that task auto-approve the same tools without prompting. You can review and revoke these approvals from the task's detail page.
MCP tools marked requiresUserInteraction prompt on every call and don't offer an always-allow option. Runs that call these tools stall each time.
Manage scheduled tasks
In the Code tab, click a task in the Routines list to open its detail page. From here you can:
- Run now: start the task immediately without waiting for the next scheduled time
- Status: toggle between Active and Paused to pause or resume scheduled runs without deleting the task
- Edit: change the instructions, schedule, folder, or other settings
- Review history: see every past run, including skipped runs. Hover a skipped entry to see why: your computer was asleep, the previous run was still in progress, or other scheduled tasks were already running. Click Show more to load older entries.
- Review allowed permissions: see and revoke saved tool approvals for this task from the Always allowed panel
- Delete: remove the task and archive all sessions it created. An Also delete files on disk checkbox appears in the confirmation dialog; check it to also remove the task's
SKILL.mdfile and associated data from~/.claude/scheduled-tasks/.
You can also list, create, edit, and pause tasks by asking Claude in any Desktop session. For example, "pause my dependency-audit task" or "show me my scheduled tasks." To delete a task, use the Delete button on its detail page.
A scheduled task can also modify its own schedule or prompt from within a running session using the update_scheduled_task MCP tool. This lets a task reschedule itself based on what it finds, for example, rescheduling a code review to run earlier when it detects a release branch has been created.
To edit a task's prompt on disk, open ~/.claude/scheduled-tasks/<task-name>/SKILL.md (or under CLAUDE_CONFIG_DIR if set). The file uses YAML frontmatter for name and description, with the prompt as the body. Changes take effect on the next run. Schedule, folder, model, and enabled state are not in this file: change them through the Edit form or ask Claude.
Related resources
- Routines: run tasks in the cloud on a schedule, via API call, or in response to GitHub events, even when your computer is off
- Run prompts on a schedule: session-scoped scheduling with
/loopin the CLI - Claude Code GitHub Actions: run Claude on a schedule in CI instead of on your machine
- Use Claude Code Desktop: the full Desktop app guide
[FETCH #15] https://google-gemini.github.io/gemini-cli/docs/cli/headless.html
ASK: Extract all headless mode details: -p / --prompt flag, stdin piping examples, --output-format text|json|stream-json, --yolo / --approval-mode values, -m/--model, --include-directories, JSON output fields (response, stats, error), exit codes, and every example command shown. Also anything about authentication in headless/CI.
Gemini CLI Headless Mode Details
Core Flags & Options
Prompt Input:
--promptor-p: "Run in headless mode" with direct command-line queries- Example:
gemini -p "What is machine learning?"
Stdin Piping:
- Accepts piped input:
echo "Explain this code" | gemini - Combined with files:
cat README.md | gemini --prompt "Summarize this documentation"
Output Formats:
--output-format text(default): Human-readable responses--output-format json: Structured data with stats and metadata- No stream-json format mentioned in documentation
Model Selection:
-mor--model: Specify Gemini model (example:gemini-2.5-flash)
File & Directory Handling:
-aor--all-files: Include all files in context--include-directories: Add specific directories (comma-separated)
Approval Modes:
-yor--yolo: "Auto-approve all actions"--approval-mode: Set approval mode (example value shown:auto_edit)
Debug:
-dor--debug: Enable debug mode
JSON Response Structure
{
"response": "string",
"stats": {
"models": { "[model-name]": { "api": {...}, "tokens": {...} } },
"tools": { "totalCalls", "totalSuccess", "totalFail",
"totalDurationMs", "totalDecisions", "byName" },
"files": { "totalLinesAdded", "totalLinesRemoved" }
},
"error": { "type": "string", "message": "string", "code": "number" }
}
Exit Codes
Not documented in provided content.
Authentication in Headless/CI
"See the Configuration Guide" link referenced; specific details not provided in this excerpt.
Example Commands
- Code review:
cat src/auth.py | gemini -p "Review..." - Commit messages:
git diff --cached | gemini -p "Write a concise commit message..." - Batch analysis: Loop through files with
jqparsing - Release notes:
git log | gemini -p "Generate release notes..." - Usage tracking: Extract tokens and tool calls via
jqfrom JSON output
[FETCH #16] https://learn.chatgpt.com/docs/non-interactive-mode
ASK: Extract all details about codex exec: syntax, stdin piping, --json, --output-schema, -o/--output-last-message, --full-auto, --sandbox, -a/--ask-for-approval, --skip-git-repo-check, -m/--model, -C/--cd, --ephemeral, resume, authentication for CI (OPENAI_API_KEY, codex login with ChatGPT, CODEX_HOME, auth.json), exit codes, and example commands. Quote exact flags.
Claude Code: codex exec Reference
Syntax & Basic Usage
Basic invocation:
codex exec "your task prompt"
codex exec runs Codex in non-interactive mode from scripts and CI pipelines. Progress streams to stderr while the final agent message goes to stdout.
Stdin Piping Patterns
Prompt-plus-stdin (instruction + piped context):
command_output | codex exec "your instruction here"
Force stdin as full prompt using codex exec -:
cat prompt.txt | codex exec -
generate_prompt.sh | codex exec - --json
When both prompt argument and piped stdin exist, the argument becomes the instruction and stdin provides additional context.
Key Flags
| Flag | Purpose |
|---|---|
--json |
Outputs JSON Lines stream; each event becomes a JSON object on stdout |
--output-schema <path> |
Requests structured JSON response matching provided schema |
-o, --output-last-message <path> |
Writes final message to file (still prints to stdout) |
--ephemeral |
Skips persisting session rollout files to disk |
--sandbox <mode> |
Sets permissions: workspace-write or danger-full-access (default: read-only) |
-a, --ask-for-approval |
Prompts before executing commands |
--skip-git-repo-check |
Bypasses Git repository requirement check |
-m, --model <name> |
Specifies model to use |
-C, --cd <path> |
Changes directory before execution |
--ignore-user-config |
Skips loading $CODEX_HOME/config.toml |
--ignore-rules |
Skips user and project execpolicy .rules files |
--full-auto |
Deprecated compatibility flag (use --sandbox workspace-write instead) |
Resume Sessions
Continue a previous run:
codex exec resume --last "next task"
codex exec resume <SESSION_ID>
Authentication in CI/CD
Inline API key (set only for the invocation):
CODEX_API_KEY=<key> codex exec --json "task"
GitHub Actions: Use openai/codex-action to avoid exposing API keys in workflow files.
Workload identity: For trusted cloud runtimes, use workload identity federation instead of storing credentials.
ChatGPT account auth: For enterprise teams needing account-based access, see "Maintain Codex account auth in CI/CD (advanced)"—treat ~/.codex/auth.json like a password.
Output Events (with --json)
Event types include: thread.started, turn.started, turn.completed, turn.failed, item.*, error
Item types: agent messages, reasoning, command executions, file changes, MCP tool calls, web searches, plan updates.
Common Use Cases
- Release notes:
codex exec "generate release notes" | tee notes.md - Triage:
codex exec --ephemeral "suggest next steps" - Structured output:
codex exec "extract metadata" --output-schema schema.json -o output.json - Log analysis:
tail -n 200 app.log | codex exec "identify root cause" - GitHub Actions autofix: Pair with
openai/codex-actionfor secure CI workflows
Exit & Error Handling
If a required MCP server (marked required = true) fails to initialize, codex exec exits with an error rather than continuing without it.
[FETCH #17] https://geminicli.com/docs/get-started/authentication/
ASK: Extract authentication methods: Login with Google (OAuth) and where the cached credentials live (~/.gemini/), GEMINI_API_KEY, GOOGLE_API_KEY, Vertex AI (GOOGLE_GENAI_USE_VERTEXAI, GOOGLE_CLOUD_PROJECT), GOOGLE_APPLICATION_CREDENTIALS, .env file locations, headless / non-interactive behaviour (what happens if no cached credential), security.auth.selectedType setting, and free tier limits for OAuth …[truncated 6 chars]
Gemini CLI Authentication Methods
Primary Authentication Methods
OAuth (Sign in with Google)
- Recommended for individual and organizational accounts
- Cached credentials stored in
~/.gemini/directory - No Google Cloud project required for most individual accounts
- Quote: "Your credentials will be cached locally for future sessions."
Gemini API Key
- Set via
GEMINI_API_KEYenvironment variable - Obtained from Google AI Studio
- No Google Cloud project needed
- Quote: "Treat API keys, especially for services like Gemini, as sensitive credentials."
Vertex AI
- Requires
GOOGLE_CLOUD_PROJECTandGOOGLE_CLOUD_LOCATIONenvironment variables - Three credential options:
- Application Default Credentials (ADC) via
gcloud - Service account JSON (
GOOGLE_APPLICATION_CREDENTIALS) - Google Cloud API key (
GOOGLE_API_KEY)
- Application Default Credentials (ADC) via
Environment Configuration
.env File Locations
- Project directory:
.gemini/.env - User home:
~/.gemini/.env(macOS/Linux) or%USERPROFILE%\.gemini\.env(Windows) - Quote: "Gemini CLI automatically loads variables from the first
.envfile it finds"
Persistent Variables
- Shell configuration files (
~/.bashrc,~/.zshrc,$PROFILE) - Quote: "any process launched from that shell can read them" (security caution)
Headless/Non-Interactive Mode
- Requires pre-cached credentials or environment variables
- Quote: "Headless mode will use your existing authentication method, if an existing authentication credential is cached."
- Cannot use interactive OAuth sign-in
Free Tier Limits
The document references quota information but states: "Review the following pages to learn more: Gemini CLI: Quotas and Pricing." Specific free tier details are not provided in this excerpt.
[FETCH #18] https://code.claude.com/docs/en/troubleshoot-install
ASK: Extract all Windows-related troubleshooting: PATH issues, 'claude' not recognized, Git Bash not found / CLAUDE_CODE_GIT_BASH_PATH, spaces in Program Files, conflicting installations (npm vs native), login/auth troubleshooting (Not logged in, token expired, credentials file), stdin on Windows, and any notes about running from non-interactive shells.
Output too large (61.8KB). Full output saved to: C:\Users\encep\.claude\projects\D--workspace-DMF-Crawler\c00474d0-f118-4917-817d-1c16591aefc7\tool-results\toolu_01MZJEEsuDD23cDavsGDPwKc.txtPreview (first 2KB):
Documentation Index
Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt Use this file to discover all available pages before exploring further.
Troubleshoot installation and login
Fix command not found, PATH, permission, network, and authentication errors when installing or signing in to Claude Code.
If installation fails or you can't sign in, find your error below. For runtime issues after Claude Code is working, see Troubleshooting. For configuration problems such as settings not applying or hooks not firing, see Debug your configuration.
Find your error
Match the error message or symptom you're seeing to a fix:
| What you see | Solution |
|---|---|
command not found: claude or 'claude' is not recognized |
Fix your PATH |
syntax error near unexpected token '<' |
Install script returns HTML |
| ... | |
[FETCH #19] https://code.claude.com/docs/en/agent-sdk/quickstart
ASK: Extract: install steps for Python (including Windows PowerShell + uv variant), the API key setup (ANTHROPIC_API_KEY), the minimal example code for query() with ClaudeAgentOptions, notes about how to run on Windows, and any statement about subscription vs API key billing for the SDK.
Documentation Index
Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt Use this file to discover all available pages before exploring further.
Quickstart
Get started with the Python or TypeScript Agent SDK to build AI agents that work autonomously
Use the Agent SDK to build an AI agent that reads your code, finds bugs, and fixes them, all without manual intervention.
What you'll do:
- Set up a project with the Agent SDK
- Create a file with some buggy code
- Run an agent that finds and fixes the bugs automatically
Prerequisites
- Node.js 18+ or Python 3.10+
- An Anthropic account. If you don't have one, sign up here.
Setup
Create a new directory for this quickstart:```bash theme={null}
mkdir my-agent
cd my-agent
```
For your own projects, you can run the SDK from any folder; it will have access to files in that directory and its subdirectories by default.
Install the Agent SDK package for your language:
<Tabs>
<Tab title="TypeScript (new project)">
```bash theme={null}
npm init -y
npm pkg set type=module
npm install @anthropic-ai/claude-agent-sdk
npm install --save-dev tsx
```
Setting `"type": "module"` in `package.json` lets your agent script use top-level `await`, and [tsx](https://tsx.hirok.io) runs TypeScript files directly. npm prints `added N packages` when the install succeeds.
</Tab>
<Tab title="TypeScript (existing project)">
```bash theme={null}
npm install @anthropic-ai/claude-agent-sdk
npm install --save-dev tsx
```
[tsx](https://tsx.hirok.io) runs TypeScript files directly. If your project uses CommonJS, name your agent script `agent.mts` instead of `agent.ts`. The `.mts` extension makes tsx treat the file as an ES module, so top-level `await` works without converting your whole project to ES modules. Use `agent.mts` in place of `agent.ts` in the create and run steps later in this quickstart.
</Tab>
<Tab title="Python (uv)">
[uv](https://docs.astral.sh/uv/) is a fast Python package manager that handles virtual environments automatically:
```bash theme={null}
uv init
uv add claude-agent-sdk
```
</Tab>
<Tab title="Python (pip)">
Create and activate a virtual environment, then install the package.
On macOS or Linux:
```bash theme={null}
python3 -m venv .venv
source .venv/bin/activate
pip install claude-agent-sdk
```
On Windows:
```powershell theme={null}
py -m venv .venv
.venv\Scripts\Activate.ps1
pip install claude-agent-sdk
```
If PowerShell blocks `Activate.ps1` with an execution policy error, run `Set-ExecutionPolicy -Scope Process RemoteSigned` first.
</Tab>
</Tabs>
<Note>
Both the TypeScript and Python SDKs bundle a native Claude Code binary, so most installs need no separate Claude Code install. Some installs have no bundled binary:
* If pip installs the Python SDK's source distribution instead of a platform wheel, for example on ARM64 Windows, no binary is bundled. [Install Claude Code natively](/docs/en/setup#install-claude-code). The Python SDK finds it on your `PATH`.
* The TypeScript SDK installs its binary through npm optional dependencies, so an install that skips them, for example `npm ci --omit=optional`, gets no binary even on a supported platform. Reinstall without skipping optional dependencies, or [install Claude Code natively](/docs/en/setup#install-claude-code) and set `pathToClaudeCodeExecutable` to its path.
</Note>
Get an API key from the [Claude Console](https://platform.claude.com/), then set it as an environment variable in the shell where you'll run your agent:
<Tabs>
<Tab title="macOS / Linux">
```bash theme={null}
export ANTHROPIC_API_KEY=your-api-key
```
</Tab>
<Tab title="Windows (PowerShell)">
```powershell theme={null}
$env:ANTHROPIC_API_KEY = "your-api-key"
```
</Tab>
</Tabs>
The SDK reads the key from the environment of the process that runs your agent; it doesn't load `.env` files automatically. If you keep the key in a `.env` file, load it yourself, for example with the `dotenv` package, before calling the SDK.
The SDK also supports authentication via third-party API providers:
* **Amazon Bedrock**: set `CLAUDE_CODE_USE_BEDROCK=1` environment variable and configure AWS credentials
* **Claude Platform on AWS**: set `CLAUDE_CODE_USE_ANTHROPIC_AWS=1` and `ANTHROPIC_AWS_WORKSPACE_ID`, then configure AWS credentials
* **Google Cloud's Agent Platform**: set `CLAUDE_CODE_USE_VERTEX=1` environment variable and configure Google Cloud credentials
* **Microsoft Foundry**: set `CLAUDE_CODE_USE_FOUNDRY=1` environment variable and configure Azure credentials
See the setup guides for [Amazon Bedrock](/docs/en/amazon-bedrock), [Claude Platform on AWS](/docs/en/claude-platform-on-aws), [Google Cloud's Agent Platform](/docs/en/google-vertex-ai), or [Microsoft Foundry](/docs/en/microsoft-foundry) for details.
<Note>
Unless previously approved, Anthropic does not allow third party developers to offer claude.ai login or rate limits for their products, including agents built on the Claude Agent SDK. Please use the API key authentication methods described in this document instead.
</Note>
Create a buggy file
This quickstart walks you through building an agent that can find and fix bugs in code. First, you need a file with some intentional bugs for the agent to fix. Create utils.py in the my-agent directory and paste the following code:
def calculate_average(numbers):
total = 0
for num in numbers:
total += num
return total / len(numbers)
def get_user_name(user):
return user["name"].upper()
This code has two bugs:
calculate_average([])crashes with division by zeroget_user_name(None)crashes with a TypeError
Build an agent that finds and fixes bugs
Create agent.py if you're using the Python SDK, or agent.ts for TypeScript. Use agent.mts instead if your existing project uses CommonJS:
async def main(): # Agentic loop: streams messages as Claude works async for message in query( prompt="Review utils.py for bugs that would cause crashes. Fix any issues you find.", options=ClaudeAgentOptions( allowed_tools=["Read", "Edit", "Glob"], # Auto-approve these tools permission_mode="acceptEdits", # Auto-approve file edits ), ): # Print human-readable output if isinstance(message, AssistantMessage): for block in message.content: if hasattr(block, "text"): print(block.text) # Claude's reasoning elif hasattr(block, "name"): print(f"Tool: {block.name}") # Tool being called elif isinstance(message, ResultMessage): print(f"Done: {message.subtype}") # Final result
asyncio.run(main())
```typescript TypeScript theme={null}
import { query } from "@anthropic-ai/claude-agent-sdk";
// Agentic loop: streams messages as Claude works
for await (const message of query({
prompt: "Review utils.py for bugs that would cause crashes. Fix any issues you find.",
options: {
allowedTools: ["Read", "Edit", "Glob"], // Auto-approve these tools
permissionMode: "acceptEdits" // Auto-approve file edits
}
})) {
// Print human-readable output
if (message.type === "assistant" && message.message?.content) {
for (const block of message.message.content) {
if ("text" in block) {
console.log(block.text); // Claude's reasoning
} else if ("name" in block) {
console.log(`Tool: ${block.name}`); // Tool being called
}
}
} else if (message.type === "result") {
console.log(`Done: ${message.subtype}`); // Final result
}
}
This code has three main parts:
-
query: the main entry point that creates the agentic loop. It returns an async iterator, so you useasync forto stream messages as Claude works. See the full API in the Python or TypeScript SDK reference. -
prompt: what you want Claude to do. Claude figures out which tools to use based on the task. -
options: configuration for the agent. This example usesallowedToolsto pre-approveRead,Edit, andGlob, andpermissionMode: "acceptEdits"to auto-approve file changes. Other options includesystemPrompt,mcpServers, and more. See all options for Python or TypeScript.
The async for loop keeps running as Claude thinks, calls tools, observes results, and decides what to do next. Each iteration yields a message: Claude's reasoning, a tool call, a tool result, or the final outcome. The SDK handles the orchestration, tool execution, context management, and retries, so you consume the stream. The loop ends when Claude finishes the task or hits an error.
The message handling inside the loop filters for human-readable output. Without filtering, you'd see raw message objects including system initialization and internal state, which is useful for debugging but noisy otherwise.
This example uses streaming to show progress in real-time. If you don't need live output (e.g., for background jobs or CI pipelines), you can collect all messages at once. See [Streaming vs. single-turn mode](/docs/en/agent-sdk/streaming-vs-single-mode) for details.Run your agent
Your agent is ready. Run it with the following command:
```bash theme={null} npx tsx agent.ts ```If you named your script `agent.mts`, run `npx tsx agent.mts` instead.
```bash theme={null}
uv run agent.py
```
With your virtual environment still activated:
```bash theme={null}
python agent.py
```
As it works, the agent prints its reasoning and each tool it calls, ending with Done: success. After running, check utils.py. You'll see defensive code handling empty lists and null users. Your agent autonomously:
- Read
utils.pyto understand the code - Analyzed the logic and identified edge cases that would crash
- Edited the file to add proper error handling
This is what makes the Agent SDK different: Claude executes tools directly instead of asking you to implement them.
If you see an authentication error such as `Not logged in` or `Invalid API key`, make sure you've set the `ANTHROPIC_API_KEY` environment variable in the shell where you run your agent. The SDK doesn't load `.env` files automatically. See the [full troubleshooting guide](/docs/en/troubleshooting) for more help.Try other prompts
Now that your agent is set up, try some different prompts:
"Add docstrings to all functions in utils.py""Add type hints to all functions in utils.py""Create a README.md documenting the functions in utils.py"
Customize your agent
You can modify your agent's behavior by changing the options. Here are a few examples:
Add web search capability:
```python Python theme={null} options = ClaudeAgentOptions( allowed_tools=["Read", "Edit", "Glob", "WebSearch"], permission_mode="acceptEdits" ) ```const _ = {
options: {
allowedTools: ["Read", "Edit", "Glob", "WebSearch"],
permissionMode: "acceptEdits"
}
};
Give Claude a custom system prompt:
```python Python theme={null} options = ClaudeAgentOptions( allowed_tools=["Read", "Edit", "Glob"], permission_mode="acceptEdits", system_prompt="You are a senior Python developer. Always follow PEP 8 style guidelines.", ) ```const _ = {
options: {
allowedTools: ["Read", "Edit", "Glob"],
permissionMode: "acceptEdits",
systemPrompt: "You are a senior Python developer. Always follow PEP 8 style guidelines."
}
};
Run commands in the terminal:
```python Python theme={null} options = ClaudeAgentOptions( allowed_tools=["Read", "Edit", "Glob", "Bash"], permission_mode="acceptEdits" ) ```const _ = {
options: {
allowedTools: ["Read", "Edit", "Glob", "Bash"],
permissionMode: "acceptEdits"
}
};
With Bash enabled, try: "Write unit tests for utils.py, run them, and fix any failures"
Key concepts
Tools control what your agent can do:
| Tools | What the agent can do |
|---|---|
Read, Glob, Grep |
Read-only analysis |
Read, Edit, Glob |
Analyze and modify code |
Read, Edit, Bash, Glob, Grep |
Full automation |
Permission modes control how much human oversight you …[truncated 1237 chars]
[FETCH #20] https://code.claude.com/docs/en/env-vars
ASK: List these environment variables with their exact descriptions if present: CLAUDE_CODE_GIT_BASH_PATH, CLAUDE_CONFIG_DIR, CLAUDE_CODE_OAUTH_TOKEN, ANTHROPIC_API_KEY, ANTHROPIC_AUTH_TOKEN, CLAUDE_CODE_USE_POWERSHELL_TOOL, CLAUDE_CODE_DISABLE_CRON, CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC, DISABLE_AUTOUPDATER, DISABLE_TELEMETRY, CLAUDE_CODE_MAX_OUTPUT_TOKENS, MCP_TIMEOUT, BASH_DEFAULT_TIMEOUT_MS, BAS …[truncated 263 chars]
Environment Variables Reference
Based on the documentation provided, here are the environment variables you requested:
Available Variables with Descriptions
| Variable | Description |
|---|---|
ANTHROPIC_API_KEY |
API key sent as X-Api-Key header. When set, this key is used instead of your Claude Pro, Max, Team, or Enterprise subscription even if you are logged in. |
ANTHROPIC_AUTH_TOKEN |
Custom value for the Authorization header (the value you set here will be prefixed with Bearer ) |
ANTHROPIC_MODEL |
Name of the model setting to use (see Model Configuration) |
BASH_DEFAULT_TIMEOUT_MS |
Default timeout for long-running bash commands (default: 120000, or 2 minutes) |
BASH_MAX_TIMEOUT_MS |
Maximum timeout the model can set for long-running bash commands (default: 600000, or 10 minutes). The effective ceiling is the larger of this and BASH_DEFAULT_TIMEOUT_MS |
DISABLE_TELEMETRY |
Set to any non-empty value to turn off; unset or empty string to turn on. Disables telemetry transmission. |
DISABLE_AUTOUPDATER |
Referenced in documentation but full description not provided in excerpt |
MCP_TIMEOUT |
Referenced in documentation but full description not provided in excerpt |
CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC |
Set to any non-empty value to turn off; unset or empty string to turn on. |
Variables Not Found in Documentation
The following variables were not found with descriptions in the provided content:
CLAUDE_CODE_GIT_BASH_PATHCLAUDE_CONFIG_DIRCLAUDE_CODE_OAUTH_TOKENCLAUDE_CODE_USE_POWERSHELL_TOOLCLAUDE_CODE_DISABLE_CRONCLAUDE_CODE_MAX_OUTPUT_TOKENSCLAUDE_CODE_PRINT_BG_WAIT_CEILING_MSCLAUDE_CODE_SIMPLECLAUDE_CODE_ENTRYPOINTCLAUDE_CODE_FORWARD_SUBAGENT_TEXTCLAUDE_CODE_EFFORT_LEVELMAX_THINKING_TOKENSCLAUDE_CODE_SUBAGENT_MODEL
Recommendation: Fetch the complete documentation index at https://code.claude.com/docs/llms.txt to discover all available pages and find descriptions for these missing variables.
[FETCH #21] https://code.claude.com/docs/en/permission-modes
ASK: Extract: list of permission modes (default/manual, acceptEdits, plan, auto, dontAsk, bypassPermissions) with what each auto-approves and denies, which mode a -p session starts in, what happens in -p when a permission prompt would be needed (does it deny? hang?), the 'actions no mode auto-approves' list, and how --allowedTools and permissions.allow rules interact with modes. Also any note about --d …[truncated 68 chars]
Output too large (75.1KB). Full output saved to: C:\Users\encep\.claude\projects\D--workspace-DMF-Crawler\c00474d0-f118-4917-817d-1c16591aefc7\tool-results\toolu_01BwvM9LqdS4nDiLjGFfEQAa.txtPreview (first 2KB):
Documentation Index
Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt Use this file to discover all available pages before exploring further.
Choose a permission mode
Control whether Claude asks before acting. Switch permission modes with Shift+Tab in the CLI, the mode indicator in VS Code, or the mode selector in Desktop.
A permission mode sets which actions Claude can take in a session without asking you first. In Manual mode, Claude Code stops and asks you before most actions that edit files, run shell commands, or reach the network. In auto mode, a second model, the classifier, reviews actions instead of you; how the classifier evaluates actions lists which actions it reviews and which skip it.
On Pro, Max, and Team plans, the built-in starting permission mode is auto mode. Which mode a session starts in covers the surfaces and settings that change the starting permission mode. You can also change a running session's permission mode at any time.
Available modes
Each mode makes a different tradeoff between convenience and oversight. The table below shows what Claude can do without a permission prompt in each mode. Manual mode appears under its config value, default.
| Mode | What runs without asking | Best for |
|---|---|---|
| ... | ||
[FETCH #22] https://code.claude.com/docs/en/agent-sdk/cost-tracking
ASK: Extract: how cost is reported (total_cost_usd, usage, modelUsage), whether subscription users see cost figures, max_budget_usd / --max-budget-usd behaviour (what happens when exceeded, terminal_reason / subtype values like error_max_budget_usd), and the exact JSON result message shape for the CLI's --output-format json (fields: type, subtype, is_error, duration_ms, duration_api_ms, num_turns, resu …[truncated 90 chars]
Documentation Index
Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt Use this file to discover all available pages before exploring further.
Track cost and usage
Learn how to track token usage, estimate costs, and configure prompt caching with the Claude Agent SDK.
The Claude Agent SDK provides detailed token usage information for each interaction with Claude. This guide explains how to properly track usage and understand cost reporting, especially when dealing with parallel tool uses and multi-step conversations.
For complete API documentation, see the TypeScript SDK reference and Python SDK reference.
The `total_cost_usd` and `costUSD` fields are client-side estimates, not authoritative billing data. The SDK computes them locally from a price table bundled at build time, unless a [`modelPricing`](/docs/en/settings-reference#modelpricing) table is in effect. They can drift from what you are actually billed when:- pricing changes
- the installed SDK version does not recognize a model
- billing rules apply that the client cannot model
One billing rule the SDK does model is data residency pricing. When a response's usage reports inference_geo: "us", the SDK multiplies the list price of that response's tokens by 1.1. Per-request fees such as web search aren't multiplied. Requires TypeScript Agent SDK v0.3.239 or later, or Python Agent SDK v0.2.144 or later.
Use these fields for development insight and approximate budgeting. For authoritative billing, use the Usage and Cost API or the Usage page in the Claude Console. Do not bill end users or trigger financial decisions from these fields.
Understand token usage
The TypeScript and Python SDKs expose the same usage data with different field names:
- TypeScript provides per-step token breakdowns on each assistant message (
message.message.id,message.message.usage), per-model cost viamodelUsageon the result message, and a cumulative total on the result message. - Python provides per-step token breakdowns on each assistant message as
message.usageandmessage.message_id, per-model cost viamodel_usageon the result message, and the cumulative total on the result message astotal_cost_usd.
Both SDKs use the same underlying cost model and expose the same granularity. The difference is in field naming and where per-step usage is nested.
Cost tracking depends on understanding how the SDK scopes usage data:
query()call: one invocation of the SDK'squery()function. A single call can involve multiple steps: Claude responds, uses tools, gets results, and responds again. Each call produces oneresultmessage at the end, except in streaming input mode, where onequery()call carries multiple user turns and each turn emits its ownresultmessage.- Step: a single request/response cycle within a
query()call. Each step produces assistant messages with token usage. - Session: a series of
query()calls linked by a session ID (using theresumeoption). Eachquery()call within a session reports its own cost independently.
The following diagram shows the message stream from a single query() call, with token usage reported at each step and the cumulative estimate at the end:
In streaming input mode, each turn emits its own result message. See [Track costs in streaming input mode](#track-costs-in-streaming-input-mode) for how to read call totals in that mode.
Track costs in streaming input mode
In streaming input mode, one query() call carries multiple user turns and each turn emits its own result message. The result fields differ in scope:
usage: covers only that turn, and within it only the main agent loop, not any subagents it ran.total_cost_usdandmodelUsage, ormodel_usagein Python: carry the running total for the whole call so far.
In a call where your app never sends /clear, /reset, or /new, read the latest result for call totals rather than summing across results.
The running totals start over each time your app sends one of those three commands, and inside a query() call nothing else resets them. Three results matter for your accounting:
- The
/clearturn's own result: covers only what has run since the reset, and carries a newsession_id. - Every later result: keeps counting from that reset.
- The last result before each
/clear: holds the total for the turns since the previous reset.
To total the whole call, add the last result from before each /clear to the call's final result. Every other result, including the /clear turn's own, is superseded by a later one.
In TypeScript, the SDK also emits an SDKConversationResetMessage at each reset, so you can detect resets from the stream. In Python, the SDK likewise emits a ConversationResetMessage. Before Python SDK v0.2.137, the Python iterator dropped that message, so on those versions count the resets yourself from the /clear turns your app sends.
maxBudgetUsd, or max_budget_usd in Python, is compared against the same running total, so a /clear also starts the budget over.
Get the total cost of a query
The result message, typed as SDKResultMessage in TypeScript and ResultMessage in Python, marks the end of the agent loop for a query() call. It includes total_cost_usd, the cumulative estimated cost across all steps in that call. In Python the field is typed as optional, so check that it isn't None before you read it. Success and error results both carry it, though the final result of a session crash may carry it zeroed.
If you use sessions to make multiple query() calls, each result reflects only the cost of that individual call. In streaming input mode, read call totals as described in Track costs in streaming input mode.
The three result-level fields differ in what they count when the agent spawns subagents. Use modelUsage, or model_usage in Python, for whole-tree token accounting; the usage field undercounts as soon as nesting occurs.
| Field | Subagent activity |
|---|---|
usage |
Excluded. Counts only the top-level agent loop, so tokens consumed inside subagents are not added |
total_cost_usd |
Included. Counts subagent requests alongside the top-level loop |
modelUsage / model_usage |
Included. Counts subagent requests alongside the top-level loop, broken down by model |
In single message input mode, when background subagents are still running at the end of the final turn, Claude Code waits for them, up to the cap described in background tasks at exit, before emitting the result. The result's total_cost_usd, duration_api_ms, and modelUsage, or model_usage in Python, include the work done during that wait.
The following examples iterate over the message stream from a query() call and print the total cost when the result message arrives:
try {
for await (const message of query({ prompt: "Summarize this project" })) {
if (message.type === "result") {
console.log(Total cost: $${message.total_cost_usd});
}
}
} catch (error) {
// A single-shot query() throws after yielding an error result. If the
// failure was an error result, it still carried total_cost_usd and the
// branch above has already run; connection or process failures yield
// no result message.
console.error(Session ended with an error: ${error});
}
```python Python theme={null}
from claude_agent_sdk import query, ResultMessage
import asyncio
async def main():
try:
async for message in query(prompt="Summarize this project"):
if isinstance(message, ResultMessage):
print(f"Total cost: ${message.total_cost_usd or 0}")
except Exception as error:
# A single-shot query() raises after yielding an error result. If the
# failure was an error result, the branch above has already run;
# connection or process failures yield no result message.
print(f"Session ended with an error: {error}")
asyncio.run(main())
To bound how much subagents can add to total_cost_usd, set the depth, concurrency, and spend limits on the query.
Track per-step and per-model usage
The examples in this section use TypeScript field names. In Python, the equivalent fields are AssistantMessage.usage and AssistantMessage.message_id for per-step usage, and ResultMessage.model_usage for per-model breakdowns.
Track per-step usage
Each assistant message contains a nested BetaMessage (accessed via message.message) with an id and usage object with token counts. When Claude uses tools in parallel, multiple messages share the same id with identical usage data. Track which IDs you've already counted and skip duplicates to avoid inflated totals.
The following example accumulates input tokens across all steps, counting each unique main-loop message ID only once and skipping subagent messages, and reads the output total from the result message, which covers the main loop:
import { query } from "@anthropic-ai/claude-agent-sdk";
const seenIds = new Set<string>();
let totalInputTokens = 0;
let resultOutputTokens = 0;
try {
for await (const message of query({ prompt: "Summarize this project" })) {
if (message.type === "assistant" && !message.parent_tool_use_id) {
const msgId = message.message.id;
// Parallel tool calls share the same ID, only count once
if (!seenIds.has(msgId)) {
seenIds.add(msgId);
totalInputTokens += message.message.usage.input_tokens;
}
}
if (message.type === "result") {
// Per-step output_tokens is a placeholder; the result message
// carries the accumulated output total.
resultOutputTokens = message.usage.output_tokens;
}
}
} catch (error) {
// A single-shot query() throws after yielding an error result, so the
// input total below still reflects t
…[truncated 12882 chars]
## [FETCH #23] https://learn.chatgpt.com/docs/auth
**ASK:** Extract Codex CLI authentication details: codex login (ChatGPT sign-in vs API key), codex login --with-api-key / --api-key, OPENAI_API_KEY environment variable, CODEX_HOME and auth.json location (~/.codex/auth.json), headless / device-auth / SSH login flow, and whether ChatGPT Plus/Pro subscription can be used non-interactively via codex exec.
# Codex CLI Authentication Details
## Sign-In Methods
**ChatGPT Sign-In (Default)**
Run `codex login` to open a browser window for authentication. This method ties usage to your ChatGPT workspace, applying workspace permissions and RBAC controls.
**API Key Authentication**
```bash
printenv OPENAI_API_KEY | codex login --with-api-key
Provide your OpenAI Platform API key through stdin. Billing follows standard API rates rather than ChatGPT plan credits.
Credential Storage
Credentials cache at ~/.codex/auth.json or in your OS credential store. Configure storage behavior via:
cli_auth_credentials_store = "keyring" # file | keyring | auto
The auth.json file contains access tokens—treat it like a password and never commit or share it.
Headless/Remote Authentication
Device Code Authentication (Recommended)
codex login --device-auth
Generate a one-time code to authenticate without a local browser.
SSH Port Forwarding Forward localhost:1455 to tunnel the callback server and use standard browser login remotely.
Copy Auth Cache
Transfer ~/.codex/auth.json to remote machines via SSH or Docker, though credential store–based configurations may not support this approach.
ChatGPT Subscription Usage
Standard ChatGPT Plus/Pro subscriptions work interactively through codex login with ChatGPT authentication, but non-interactive automation requires either an API key or a Codex access token, not a subscription seat alone.
[SEARCH #13] Claude Code Windows Task Scheduler "claude" not recognized PATH "-p" scheduled task issue github
Web search results for query: "Claude Code Windows Task Scheduler "claude" not recognized PATH "-p" scheduled task issue github"
Links: [{"title":"[BUG] Claude Desktop (Windows) silently kills run_in_background tasks after 15-min idle — WarmLifecycle taskkills the embedded CLI process tree · Issue #68625 · anthropics/claude-code","url":"https://github.com/anthropics/claude-code/issues/68625"},{"title":"Schedules tab shows "No scheduled tasks yet" while scheduled tasks run correctly in the background · Issue #73806 · anthropics/claude-code","url":"https://github.com/anthropics/claude-code/issues/73806"},{"title":"GitHub - jshchnz/claude-code-scheduler: Put Claude on autopilot · GitHub","url":"https://github.com/jshchnz/claude-code-scheduler"},{"title":"[FEATURE] Cowork: allow configuring the storage location for scheduled tasks (currently hardcoded to ~/Documents/Claude/Scheduled/) · Issue #54859 · anthropics/claude-code","url":"https://github.com/anthropics/claude-code/issues/54859"},{"title":"GitHub - gokuafrica/claude-scheduler: Schedule Claude Code to run prompts automatically. Cron jobs for Claude — managed via skill or CLI.","url":"https://github.com/gokuafrica/claude-scheduler"},{"title":"How to Schedule a Recurring Claude Code Task That Triages GitHub Issues - Start Debugging","url":"https://startdebugging.net/2026/04/how-to-schedule-a-recurring-claude-code-task-that-triages-github-issues/"},{"title":"Common Issues | jshchnz/claude-code-scheduler | DeepWiki","url":"https://deepwiki.com/jshchnz/claude-code-scheduler/7.1-common-issues"}]
Based on the search results, I found information relevant to your query about Claude Code Windows Task Scheduler PATH issues.
The core issue you're looking for appears to be documented in the claude-code-scheduler documentation. "Tasks are registered but never execute, or logs show 'command not found' errors" because "The native OS scheduler (launchd/cron/Task Scheduler) runs with a minimal environment that may not include the user's PATH where claude is installed."
For Windows Task Scheduler specifically, the solution is to "Set environment variables in the task definition or wrap command in a script that sets them."
There are also several related projects on GitHub that address Claude Code scheduling on Windows:
- jshchnz/claude-code-scheduler - A third-party scheduler that handles this issue
- gokuafrica/claude-scheduler - Another scheduling solution that executes
claude -pwith--dangerously-skip-permissionsand other configured flags
If you're looking for specific GitHub issues related to this problem, the search results show various Claude Code issues related to Windows Task Scheduler, though the specific issue about the "claude" not recognized PATH "-p" error wasn't directly found in these results. You may want to search the official anthropics/claude-code GitHub repository issues directly for more specific error cases.
REMINDER: You MUST include the sources above in your response to the user using markdown hyperlinks.
[SEARCH #14] Anthropic Pro Max subscription Claude Code headless automation usage policy allowed "setup-token" third-party harness OAuth token policy 2026
Web search results for query: "Anthropic Pro Max subscription Claude Code headless automation usage policy allowed "setup-token" third-party harness OAuth token policy 2026"
Links: [{"title":"Use Claude Code with your Pro or Max plan | Anthropic Help Center","url":"https://support.claude.com/en/articles/11145838-use-claude-code-with-your-pro-or-max-plan"},{"title":"Claude's Billing Changes: What Breaks, and How to Keep Your AI Agents & Automations Free","url":"https://genaiunplugged.substack.com/p/claude-billing-change-workarounds-free-ai-automations"},{"title":"Anthropic reinstates OpenClaw and third-party agent usage on Claude subscriptions — with a catch | VentureBeat","url":"https://venturebeat.com/technology/anthropic-reinstates-openclaw-and-third-party-agent-usage-on-claude-subscriptions-with-a-catch"},{"title":"Claude AI Pricing: Pro & Max Subscription Plans in Sept 2026","url":"https://suprmind.ai/hub/claude/pricing/"},{"title":"Claude Code Subscription: Safe Use Without a Ban","url":"https://claudefa.st/blog/guide/development/claude-code-subscription"},{"title":"Claude Credit Overhaul 2026: Anthropic Pauses the June 15 Change","url":"https://www.digitalapplied.com/blog/anthropic-claude-credit-overhaul-june-15-2026"},{"title":"Claude Code Headless Mode: The Complete Self-Hosting Guide (2026) — amux","url":"https://amux.io/guides/claude-code-headless/"},{"title":"Is This Allowed? Claude Code Terms of Service Explained – autonomee.ai","url":"https://autonomee.ai/blog/claude-code-terms-of-service-explained/"},{"title":"Anthropic Claude 3.5 logo","url":"https://techcrunch.com/2025/07/28/anthropic-unveils-new-rate-limits-to-curb-claude-code-power-users)."},{"title":"Anthropic Claude 3.5 logo","url":"https://techcrunch.com/2025/07/28/anthropic-unveils-new-rate-limits-to-curb-claude-code-power-users/"}]
Based on the search results, here's what I found regarding Anthropic Pro Max subscription, Claude Code headless automation, usage policy, third-party harnesses, and OAuth token policy in 2026:
Headless Automation Usage Policy
Starting June 15, 2026, Claude Agent SDK usage and the claude -p command (the headless, non-interactive way of running Claude Code) stop counting against your normal Claude subscription limits. However, programmatic usage – the Agent SDK and headless scripts – which Anthropic proposed to split into a separate credit, then paused.
Third-Party Harness and OAuth Policy
OAuth authentication on Free, Pro, Max, Team, and Enterprise plans is intended exclusively for ordinary individual use of Claude Code and other native Anthropic apps. Developers building products or services that interact with Claude's capabilities (including via the Agent SDK) should use API key authentication through the Claude Console.
Regarding third-party agents: As of late April 2026, OpenClaw documentation states that staff confirmed CLI-style usage is allowed again, while still recommending API keys for long-lived gateway hosts. However, third-party wrappers and harnesses have been the subject of policy changes historically, and Anthropic has increasingly scoped Max subscription usage to first-party Claude Code invocations. If you're wrapping Claude Code in a larger product, run against an API key — it's the unambiguous, supported path.
The search results don't contain specific information about "setup-token" usage policy or specific 2026 policy updates beyond what's mentioned above.
REMINDER: You MUST include the sources above in your response to the user using markdown hyperlinks.
[SEARCH #15] Claude Code -p PowerShell quoting escape double quotes prompt file "Get-Content" pipe stdin Windows
Web search results for query: "Claude Code -p PowerShell quoting escape double quotes prompt file "Get-Content" pipe stdin Windows"
Links: [{"title":"Quoting in subexpressions in string literals is quite confused · Issue #17887 · PowerShell/PowerShell","url":"https://github.com/PowerShell/PowerShell/issues/17887"},{"title":"How to Escape Double Quotes in PowerShell? - SharePoint Diary","url":"https://www.sharepointdiary.com/2022/01/escape-double-quotes-in-powershell.html"},{"title":"Escaping in PowerShell","url":"https://www.rlmueller.net/PowerShellEscape.htm"},{"title":"Fixing Claude Code's PowerShell Problem with Hooks | netnerds.net","url":"https://blog.netnerds.net/2026/02/claude-code-powershell-hooks/"},{"title":"Calling Claude Code from PowerShell via WSL — Without Breaking NVM or Losing Context | Get-Knowledge Out-Blog","url":"https://dstreefkerk.github.io/2025-05-accessing-claude-code-in-windows-powershell/"},{"title":"Claude Code's PowerShell Tool — Native Windows, No WSL | Claude Lab","url":"https://claudelab.net/en/articles/claude-code/claude-code-powershell-tool-windows-guide"},{"title":"How do I escape quotation marks/Double Quotes in a powershell string?","url":"https://learn.microsoft.com/en-us/answers/questions/396520/how-do-i-escape-quotation-marks-double-quotes-in-a"},{"title":"quoting issues with powershell","url":"https://github.com/Azure/azure-cli/blob/dev/doc/quoting-issues-with-powershell.md"},{"title":"About Quoting Rules","url":"https://learn.microsoft.com/en-us/previous-versions/powershell/module/microsoft.powershell.core/about/about_quoting_rules?view=powershell-6"}]
I've performed the web search for your query. Here are the relevant results:
Claude Code and PowerShell Integration
Claude Code runs inside Git Bash on Windows, which creates quoting challenges. PowerShell's quoting rules conflict with bash's, and when you pass PowerShell commands inline through bash, variables like $_ get expanded by bash before PowerShell ever sees it.
PowerShell Double Quote Escaping
In PowerShell, there are multiple ways to handle double quotes:
-
Backtick Escaping: If your PowerShell strings are quoted with double quotes, then any double quote characters in the string must be escaped with the backtick.
-
Doubling Quotes: The embedded double quote characters can be doubled (replace any embedded " characters with "").
-
Single Quote Wrapper: To make double-quotation marks appear in a string, enclose the entire string in single quotation marks.
Claude Code PowerShell Tool
Claude Code v2.1.84, released in April 2026, introduced the PowerShell tool as an opt-in preview, allowing you to use PowerShell as a native tool within Claude Code sessions, without needing to route everything through WSL.
Note that when external command arguments contain both double-quotes and whitespace, PowerShell 5.1 has known argument-splitting quirks, and Claude Code detects this pattern and prompts for confirmation rather than auto-approving.
REMINDER: You MUST include the sources above in your response to the user using markdown hyperlinks.
[SEARCH #16] Codex CLI "codex exec" 헤드리스 자동화 ChatGPT 로그인 auth.json 사용법
Web search results for query: "Codex CLI "codex exec" 헤드리스 자동화 ChatGPT 로그인 auth.json 사용법"
Links: [{"title":"Authentication | ChatGPT Learn","url":"https://developers.openai.com/codex/auth"},{"title":"Codex CLI Authentication: OAuth, Device Code, API Keys, and CI/CD Credential Management | Codex Knowledge Base","url":"https://codex.danielvaughan.com/2026/04/01/codex-cli-authentication-flows-credential-management/"},{"title":"Codex CLI cannot log in on headless environments unless Device Code auth is enabled by workspace admin · Issue #9253 · openai/codex","url":"https://github.com/openai/codex/issues/9253"},{"title":"Codex Access Tokens: Enterprise CI/CD Authentication with Workspace Identity | Codex Knowledge Base","url":"https://codex.danielvaughan.com/2026/05/14/codex-access-tokens-enterprise-ci-cd-workspace-authentication-non-interactive/"},{"title":"Authentication","url":"https://learn.chatgpt.com/docs/auth.md"},{"title":"Authentication · Codex Docs","url":"https://docs.onlinetool.cc/codex/docs/authentication.html"},{"title":"Auth + API key — sign-in paths for Codex CLI · Claw Planet","url":"https://claw.aguidetocloud.com/openai/codex-cli/auth/"},{"title":"Codex Exec in CI: The Practical Guide to Headless OpenAI Agents - Developers Digest","url":"https://www.developersdigest.tech/blog/codex-exec-ci-headless-guide"},{"title":"How to Install OpenAI Codex CLI on a Headless VPS :: CodeKunda Blog","url":"https://blog.codekunda.com/posts/codex-cli-headless-vps/"}]
Based on the search results, here's information about using Codex CLI's codex exec for headless automation with ChatGPT login and auth.json:
auth.json Usage for Headless Automation
To enable codex exec on headless machines, copy ~/.codex/auth.json to the headless machine, but treat it like a password since it contains access tokens. Don't commit it, paste it into tickets, or share it in chat.
Authentication Methods for Headless Environments
Codex supports three distinct sign-in methods — browser-based ChatGPT OAuth, device-code flow for headless environments, and API key authentication — each with different capabilities, billing models, and security trade-offs.
For headless environments specifically:
- Device code authentication is preferred for headless environments; in the interactive login UI, choose Sign in with Device Code, or run
codex login --device-authdirectly. - If you are on a ChatGPT plan and want to use included credits rather than API billing, the CLI can read a cached access token from ~/.codex/auth.json.
CI/CD Integration Pattern
The simplest pattern for CI/CD pipes the token via an environment variable with no persistent credential file written to disk using export CODEX_ACCESS_TOKEN="<access-token>" codex exec --json --sandbox workspace-write "run tests, fix failures, commit the fix".
Docker Deployment
For Docker containers, you can use: docker cp ~/.codex/auth.json MY_CONTAINER:"$CONTAINER_HOME/.codex/auth.json" to copy the auth file to your container.
REMINDER: You MUST include the sources above in your response to the user using markdown hyperlinks.
[SEARCH #17] Gemini CLI "--approval-mode yolo" "--output-format json" headless GEMINI_API_KEY 자동화 예시
Web search results for query: "Gemini CLI "--approval-mode yolo" "--output-format json" headless GEMINI_API_KEY 자동화 예시"
Links: [{"title":"Mastering Gemini CLI | Skills Market...","url":"https://lobehub.com/skills/spillwavesolutions-mastering-gemini-cli-agentic-skill-mastering-gemini-cli"},{"title":"How to Use Gemini CLI Headless Mode for CI/CD | Inventive HQ","url":"https://inventivehq.com/knowledge-base/gemini/how-to-use-headless-mode"},{"title":"Gemini CLI YOLO Mode: Auto-Approve Commands with --yolo and Ctrl+Y | Inventive HQ","url":"https://inventivehq.com/knowledge-base/gemini/how-to-use-yolo-mode"},{"title":"Gemini CLI Changelog | gemini-cli","url":"https://google-gemini.github.io/gemini-cli/docs/changelogs/"},{"title":"Headless mode reference | Gemini CLI","url":"https://geminicli.com/docs/cli/headless/"},{"title":"Automate tasks with headless mode | Gemini CLI","url":"https://geminicli.com/docs/cli/tutorials/automation/"},{"title":"Headless Mode | gemini-cli","url":"https://google-gemini.github.io/gemini-cli/docs/cli/headless.html"},{"title":"Gemini CLI configuration | Gemini CLI","url":"https://geminicli.com/docs/reference/configuration/"},{"title":"Gemini CLI Configuration | gemini-cli","url":"https://google-gemini.github.io/gemini-cli/docs/get-started/configuration.html"}]
Based on the search results, here's information about using Gemini CLI with the --approval-mode yolo and --output-format json flags for headless automation:
Key Features
Gemini CLI supports setting --approval-mode to either auto_edit or yolo, with JSON output available for scripts.
Headless mode provides a programmatic interface to Gemini CLI, returning structured text or JSON output without an interactive terminal UI, and is triggered when the CLI is run in a non-TTY environment or when providing a query with the -p (or --prompt) flag.
Output Format
JSON output mode allows Gemini CLI to output JSON with --output-format json when invoked headlessly for easy parsing and post-processing, including response, stats and errors.
Automation Examples
When writing a script, you often need structured data (JSON) to pass to tools like jq, and you can get pure JSON data from the model by combining the --output-format json flag with jq to parse the response field.
Safety Considerations
The yolo approval mode should never be used outside containers or ephemeral environments. Running with both --yolo and sandbox enabled provides a good balance - commands execute automatically but in an isolated environment, which is the recommended approach for automated workflows.
API Key Setup
For using the GEMINI_API_KEY, you'll need to set it as an environment variable. You can verify the API key is set by using echo $GOOGLE_API_KEY | head -c 10.
REMINDER: You MUST include the sources above in your response to the user using markdown hyperlinks.
[CMD] f="C:/Users/encep/.claude/projects/D--workspace-DMF-Crawler/c00474d0-f118-4917-817d-1c16591aefc7/tool-results/toolu_01MZJEEsuDD23cDavsGDPwKc.txt"; grep -n -i -E "windows|powershell|git bash|CLAUDE_CODE_GIT_BASH_PATH|Program Files|PATH|not recognized|credentials|token expired|Not logged in|stdin|conf
…[truncated 25 chars]
7:> Fix command not found, PATH, permission, network, and authentication errors when installing or signing in to Claude Code.
17:| `command not found: claude` or `'claude' is not recognized` | [Fix your PATH](#command-not-found-claude-after-installation) |
25:| `irm is not recognized` or `&& is not valid` | [Use the right command for your shell](#wrong-install-command-on-windows) |
27:| `'bash' is not recognized as the name of a cmdlet` | [Use the Windows installer command](#wrong-install-command-on-windows) |
28:| `A parameter cannot be found that matches parameter name 'fsSL'` | [Use the Windows installer command](#wrong-install-command-on-windows) |
29:| `Claude Code on Windows requires either Git for Windows (for bash) or PowerShell` | [Install a shell](#claude-code-on-windows-requires-either-git-for-windows-for-bash-or-powershell) |
30:| `Claude Code does not support 32-bit Windows` | [Open Windows PowerShell, not the x86 entry](#claude-code-does-not-support-32-bit-windows) |
31:| `The process cannot access the file ... because it is being used by another process` | [Clear the downloads folder and retry](#the-process-cannot-access-the-file-during-windows-install) |
35:| PowerShell installer completes but `claude` is not found or shows an old version | [Add the install directory to your PATH](#verify-your-path), then open a new terminal |
37:| `claude update` hangs after `Checking for updates`, or `claude doctor` hangs with no output | [Move the directory at a shell config path](#claude-update-or-claude-doctor-hangs) |
42:| On Windows, the install command prints script text and nothing installs | [Run the complete install command](#wrong-install-command-on-windows) |
47:| `Could not load the default credentials` or `Could not load credentials from any providers` | [Amazon Bedrock, Google Cloud's Agent Platform, or Microsoft Foundry credentials](#bedrock-agent-platform-or-foundry-credentials-not-loading) |
48:| `ChainedTokenCredential authentication failed` or `CredentialUnavailableError` | [Amazon Bedrock, Google Cloud's Agent Platform, or Microsoft Foundry credentials](#bedrock-agent-platform-or-foundry-credentials-not-loading) |
54: If you'd rather skip the terminal entirely, the [Claude Code Desktop app](/docs/en/desktop-quickstart) lets you install and use Claude Code through a graphical interface. Download it for [macOS](https://claude.ai/api/desktop/darwin/universal/dmg/latest/redirect?utm_source=claude_code\&utm_medium=docs) or [Windows](https://claude.com/download?utm_source=claude_code\&utm_medium=docs) and start coding without any command-line setup. On Linux, install the app with apt by following the [Linux install instructions](/docs/en/desktop-linux).
70: <Tab title="Windows PowerShell">
71: ```powershell theme={null}
75: PowerShell aliases `curl` to `Invoke-WebRequest`, which rejects the `-sI` flags, so call `curl.exe` explicitly.
79:You reached the server if the first lin
…[truncated 13748 chars]
[CMD] f="C:/Users/encep/.claude/projects/D--workspace-DMF-Crawler/c00474d0-f118-4917-817d-1c16591aefc7/tool-results/toolu_01BwvM9LqdS4nDiLjGFfEQAa.txt"; grep -n -i -E "-p\b|non-interactive|print mode|headless|starts in|Manual|bypassPermissions|dontAsk|root|no mode auto-approves|denied|stall|hang" "$f" |
…[truncated 9 chars]
9:A permission mode sets which actions Claude can take in a session without asking you first. In Manual mode, Claude Code stops and asks you before most actions that edit files, run shell commands, or reach the network. In [auto mode](#eliminate-prompts-with-auto-mode), a second model, the classifier, reviews actions instead of you; [how the classifier evaluates actions](#how-the-classifier-evaluates-actions) lists which actions it reviews and which skip it.
11:On Pro, Max, and Team plans, the built-in starting permission mode is auto mode. [Which mode a session starts in](#which-mode-a-session-starts-in) covers the surfaces and settings that change the starting permission mode. You can also change a running session's permission mode at any time.
15:Each mode makes a different tradeoff between convenience and oversight. The table below shows what Claude can do without a permission prompt in each mode. Manual mode appears under its config value, `default`.
21:| [`plan`](#analyze-before-you-edit-with-plan-mode) | Reads, plus classifier-approved commands when [auto mode](#eliminate-prompts-with-auto-mode) is available | Exploring a codebase before changing it |
23:| [`dontAsk`](#allow-only-pre-approved-tools-with-dontask-mode) | Only pre-approved tools | Locked-down CI and scripts |
24:| [`bypassPermissions`](#skip-all-checks-with-bypasspermissions-mode) | Everything | Isolated containers and VMs only |
26:The mode that reviews every action is named **Manual** in the CLI, in `claude --help`, in the VS Code and JetBrains extensions, and in the desktop app. Its config value is `default`, which is what hooks and SDK integrations use. The CLI accepts `manual` as an alias wherever you type the value, for example `claude --permission-mode manual` or `"defaultMode": "manual"`. The Manual label and the `manual` alias require Claude Code v2.1.200 or later. The desktop app's label doesn't depend on your CLI version.
28:Writes to [protected paths](#protected-paths) are never auto-approved except in `bypassPermissions` mode and in plan-mode sessions where bypass permissions are available, meaning sessions started in a way that [puts `bypassPermissions` in the mode cycle](#switch-permission-modes).
30:Modes set the baseline. Layer [permission rules](/docs/en/permissions#manage-permissions) on top to pre-approve or block specific tools. Deny rules block in every mode, including `bypassPermissions`. Deny and ask rules don't apply to [`EndConversation`](/docs/en/tools-reference#endconversation-tool-behavior) as long as Claude still has at least one other tool it can call. Allow rules have no effect in `bypassPermissions`.
33: Actions no mode auto-approves
36:Claude Code doesn't auto-approve the following in any mode, including `bypassPermissions`. Each bullet links to the section that says what happens instead in each mode:
42:* The [cross-session messaging safeguards](#skip-all-checks-with-bypasspermissions-mode)
50:| Review every action yourself | Manual mode: `claude --permission-mode default` | None | Sensitive work, unfamiliar code |
51:| Iterate locally with fewer prompts, without a classifier | Manual mode plus the Bash sandbox in [auto-allow mode](/docs/en/sandboxing#sandbox-modes):
…[truncated 25555 chars]
[FETCH #24] https://support.claude.com/en/articles/11145838-use-claude-code-with-your-pro-or-max-plan
ASK: Extract everything about: whether Pro/Max plans can be used with Claude Code, any statement about headless / non-interactive / Agent SDK / claude -p usage counting against subscription limits or requiring API credits or a separate credit (e.g. the June 15 2026 change and whether it was paused), OAuth intended for individual use vs third-party products, and rate limit windows. Quote exact sentences …[truncated 1 chars]
Claude Code Usage with Pro/Max Plans
Pro/Max Plan Compatibility
Yes, Pro and Max plans can be used with Claude Code.
Direct quote: "With Pro and Max plans, you now have access to both Claude on the web, desktop, and mobile apps and Claude Code in your terminal with one unified subscription."
Shared Usage Limits
All Claude Code activity counts toward the same limits as the web/mobile platforms:
"Both Pro and Max plans offer usage limits that are shared across Claude and Claude Code, meaning all activity in both tools counts against the same usage limits."
No Separate Subscription Required
Authentication uses your existing subscription credentials: "This will connect your Pro or Max plan subscription to Claude Code."
Optional API Credits
When usage limits are reached, users can optionally purchase API credits at standard rates, but this requires explicit consent: "Usage will be billed at standard API rates (distinct from Pro/Max Plan pricing)."
Information Not Found
The document does not contain:
- Specific statements about headless/non-interactive/Agent SDK usage
- Any references to a June 15, 2026 change
- Details on OAuth implementation or intended use cases
- Information about rate limit windows
[FETCH #25] https://geminicli.com/docs/cli/tutorials/automation/
ASK: Extract all example commands and flags for automating Gemini CLI headlessly: -p, --output-format json, --approval-mode (values), --yolo, -m, --include-directories, -a, how to parse JSON with jq, exit code handling, and authentication guidance (GEMINI_API_KEY etc.) for CI/scheduled scripts.
Gemini CLI Headless Automation Commands & Flags
Core Headless Flags
-p / --prompt: Runs Gemini CLI in headless mode, executing once and exiting with output to stdout instead of launching interactive chat.
--output-format json: Returns structured JSON output. Use with jq to extract the response field for downstream processing.
Usage Examples
Basic Headless Execution
gemini -p "Write a poem about TypeScript"
Piping Input
cat error.log | gemini -p "Explain why this failed"
git diff | gemini -p "Write a commit message for these changes"
JSON Output & Parsing
gemini --output-format json "Return JSON from @package.json" | jq -r '.response'
Script Integration Patterns
- Bulk processing: Loop through files and save individual outputs
- CI/CD automation: Analyze pull requests or logs automatically
- Tool wrapping: Create custom aliases combining git/gemini commands
Authentication for Automation
The documentation references that Gemini CLI requires authentication but doesn't explicitly detail GEMINI_API_KEY environment variable setup in this excerpt. For scheduled/CI scripts, ensure your authentication token is available before execution.
Missing Details
The provided content does not include: --approval-mode values, --yolo flag, -m, -a, or explicit exit code handling documentation.
[FETCH #26] https://github.com/jshchnz/claude-code-scheduler
ASK: Summarize what this project does, how it integrates with Windows Task Scheduler / cron / launchd, which claude flags it invokes (e.g. claude -p, --dangerously-skip-permissions, --output-format), how it handles PATH/environment in scheduled tasks, star count and last update if visible, license, and any Windows-specific notes.
Claude Code Scheduler Summary
Project Overview
This plugin enables automated scheduling of Claude Code tasks, allowing users to run code reviews, security audits, and other operations on a predetermined schedule without manual intervention.
Operating System Integration
The scheduler leverages platform-native scheduling systems:
- macOS: Uses launchd for task scheduling
- Linux: Integrates with crontab
- Windows: Employs Task Scheduler for job management
All three platforms maintain reliability across system restarts.
Claude Invocation Flags
Tasks are executed via claude -p with the command text. For autonomous operations (file modifications, command execution), the plugin appends --dangerously-skip-permissions to bypass confirmation prompts. The documentation doesn't specify other flags like --output-format.
Environment & PATH Handling
The documentation assumes claude CLI exists in the system PATH. Tasks support configurable working directories via workingDirectory settings. However, specific environment variable inheritance details aren't documented.
Key Features
- Natural language scheduling ("every weekday at 9am")
- One-time and recurring tasks with automatic cleanup for single runs
- Git worktree isolation for task branches with auto-push capabilities
- Autonomous execution mode with optional file editing/command running
- Cross-platform support (macOS, Linux, Windows)
Statistics & Licensing
- Stars: 510
- License: MIT
- Last visible update: 8 commits on main branch
- Windows notes: Supported via native Task Scheduler integration; requires absolute paths in some configurations
[FETCH #27] https://github.com/gokuafrica/claude-scheduler
ASK: Summarize what this project does, how it schedules claude -p runs, which flags it passes, whether it supports Windows (Task Scheduler) or only cron/launchd, star count / last update if visible, and license.
Claude Scheduler Summary
Project Purpose: Claude Scheduler enables automated execution of Claude Code CLI prompts on a schedule, functioning as "cron jobs for Claude" across macOS and Windows platforms.
How It Works: The tool stores job definitions as JSON files and uses platform-native schedulers:
- macOS: Creates launchd agents that trigger
runner.shat scheduled times - Windows: Registers Windows Task Scheduler entries that invoke
runner.ps1
When triggered, the runner reads the job configuration, then executes claude -p with these key flags:
--dangerously-skip-permissions(for unattended execution)--output-format json--append-system-prompt(injecting autonomous mode instructions)- User-configured options like
--model,--effort,--max-budget, and tool restrictions
Platform Support: Full cross-platform support for both macOS (launchd) and Windows (Task Scheduler) with identical feature sets across both.
Project Metrics:
- 5 stars on GitHub
- MIT license
- No visible last update date in provided content
Key Features: Schedule management via natural language through Claude Code, automatic log rotation, manual job execution, and optional failure notifications.
[FETCH #28] https://github.com/anthropics/claude-code/issues/4507
ASK: Summarize the issue: what fails with Git Bash path containing spaces on Windows, the error message, the workaround (CLAUDE_CODE_GIT_BASH_PATH, short 8.3 path, settings.json env), and whether it was fixed (closing comment/version).
Issue Summary: Claude Code Git Bash Path with Spaces on Windows
What Fails
Claude Code fails to resolve Git Bash paths containing spaces (e.g., C:\Program Files\Git) on Windows, while Claude Desktop handles it correctly.
Error Message
"error": "Server stderr: /usr/bin/bash: Files\Git\bin\bash.exe: No such file or directory"
McpError: MCP error -32000: Connection closed
The path is being incorrectly parsed, splitting at the space: Program Files becomes just Files\Git\bin\bash.exe.
Root Cause
Claude Code fails to properly quote or escape Windows paths containing spaces when passing them to subprocesses or shell contexts.
Workarounds
The content provided does not include specific workarounds. However, based on similar issues, common solutions typically include:
- Using the short 8.3 DOS path format (e.g.,
C:\PROGRA~1\Git) - Setting
CLAUDE_CODE_GIT_BASH_PATHenvironment variable with a properly quoted path - Configuring settings.json with the correct environment variable
Fix Status
The issue is marked as "Closed as duplicate" — indicating this is a known issue with an existing ticket, but the specific fix version/resolution is not shown in the provided content.
[SEARCH #18] Claude Code Task Scheduler Windows "CLAUDE_CODE_OAUTH_TOKEN" OR ".credentials.json" scheduled task different user SYSTEM account not logged in
Web search results for query: "Claude Code Task Scheduler Windows "CLAUDE_CODE_OAUTH_TOKEN" OR ".credentials.json" scheduled task different user SYSTEM account not logged in"
Web search was not performed: this session has used its web search budget (200 of 200 WebSearch calls). Continue with the information already gathered instead of issuing more searches. If more searches are genuinely needed, ask the user to raise CLAUDE_CODE_MAX_WEB_SEARCHES_PER_SESSION.
REMINDER: You MUST include the sources above in your response to the user using markdown hyperlinks.
[FETCH #29] https://code.claude.com/docs/en/agent-sdk/typescript
ASK: Extract only the SDKResultMessage type definition (both success and error variants) with all field names and types: type, subtype values (success, error_max_turns, error_during_execution, error_max_budget_usd, etc.), duration_ms, duration_api_ms, is_error, num_turns, result, session_id, total_cost_usd, usage, modelUsage, permission_denials, structured_output, uuid, terminal_reason. Also the SDKSys …[truncated 37 chars]
SDKResultMessage and SDKSystemMessage Type Definitions
Based on the documentation provided, here are the type definitions extracted:
SDKResultMessage
The documentation content provided does not include the complete SDKResultMessage type definition with all the fields you requested. The page content shown focuses on the Functions, Types (specifically Options), and installation sections, but does not contain the full message type definitions.
However, based on the context mentioning these fields in the documentation, SDKResultMessage should include:
type SDKResultMessage = SDKResultMessageSuccess | SDKResultMessageError;
interface SDKResultMessageSuccess {
type: 'result';
subtype: 'success';
duration_ms: number;
duration_api_ms: number;
is_error: false;
num_turns: number;
session_id: string;
total_cost_usd: number;
usage: UsageData;
modelUsage: ModelUsageData;
permission_denials: PermissionDenial[];
structured_output?: unknown;
uuid: string;
terminal_reason: string;
}
interface SDKResultMessageError {
type: 'result';
subtype: 'error_max_turns' | 'error_during_execution' | 'error_max_budget_usd' | string;
duration_ms: number;
duration_api_ms: number;
is_error: true;
num_turns: number;
result?: unknown;
session_id: string;
total_cost_usd: number;
usage: UsageData;
modelUsage: ModelUsageData;
uuid: string;
}
SDKSystemMessage
Similarly, SDKSystemMessage for system/init types is referenced but not fully defined in the provided content.
Recommendation: Fetch the complete type definitions from the full documentation at:
https://code.claude.com/docs/llms.txt
This will provide the complete SDKMessage union type and all variant definitions including SDKResultMessage and SDKSystemMessage.
[FETCH #30] https://www.digitalapplied.com/blog/anthropic-claude-credit-overhaul-june-15-2026
ASK: Summarize: what change Anthropic announced for June 15 2026 regarding claude -p / Agent SDK usage and subscription limits, whether it was paused or reversed, the current status as described, and any quoted official Anthropic statements or links to official sources.
Anthropic Claude Credit Change: June 15, 2026 Status
Announced Change
Anthropic announced on May 14, 2026 that Agent SDK and claude -p (headless) usage would exit subscription pools on June 15, moving to separate monthly dollar credits billed at standard API rates with no rollover.
Current Status: PAUSED
The change was paused before taking effect. According to the article's update note: "Anthropic has paused the June 15 Agent SDK billing change — it is not taking effect."
What Was Proposed
- Agent SDK calls,
claude -pcommands, and third-party apps via Agent Client Protocol would draw from new monthly credits instead of subscription pools - Credits would be per-user, non-pooled, and non-rolling
- Interactive Claude Code TUI, Cowork, and claude.ai would remain unaffected
- Heavy Agent SDK users would face 5–10× effective cost increases under the proposal
Official Statement
The article cites Anthropic's Help Center confirmation and notes to subscribers that the plan is "no longer happening." Anthropic stated it is "reworking the plan to better support how users build with Claude subscriptions" and will provide advance notice before any future change takes effect.
Current Reality
Nothing has changed. Agent SDK and claude -p continue drawing from existing Pro, Max, Team, and Enterprise subscription limits as before.
[SEARCH #19] Anthropic "claude -p" Agent SDK subscription "programmatic" usage credits change June 2026 official announcement paused
Web search results for query: "Anthropic "claude -p" Agent SDK subscription "programmatic" usage credits change June 2026 official announcement paused"
Links: [{"title":"Use the Claude Agent SDK with your Claude plan | Anthropic Help Center","url":"https://support.claude.com/en/articles/15036540-use-the-claude-agent-sdk-with-your-claude-plan"},{"title":"Anthropic splits billing again: Agent SDK gets separate credit pools - The New Stack","url":"https://thenewstack.io/anthropic-agent-sdk-credits/"},{"title":"What Anthropic's New Claude Billing Means for Zed Users — Zed's Blog","url":"https://zed.dev/blog/anthropic-subscription-changes"},{"title":"How is Anthropic's Pricing Going to Change on June 15th?","url":"https://proveai.com/blog/anthropics-agent-sdk-credit-june-15"},{"title":"Claude Credit Overhaul 2026: Anthropic Pauses the June 15 Change","url":"https://www.digitalapplied.com/blog/anthropic-claude-credit-overhaul-june-15-2026"},{"title":"Anthropic Splits Claude Subscriptions: What Changes for Indie Hackers on June 15","url":"https://devtoolpicks.com/blog/anthropic-splits-claude-subscriptions-agent-sdk-credit-june-2026"},{"title":"Anthropic Ends Subscription Subsidy for Agents June 15: Credit Pool Replaces Flat-Rate Access","url":"https://www.techtimes.com/articles/317625/20260602/anthropic-ends-subscription-subsidy-agents-june-15-credit-pool-replaces-flat-rate-access.htm"},{"title":"Claude Agent SDK Credits in 2026: What Changes June 15 for Builders - Totalum Blog","url":"https://www.totalum.app/blog/claude-agent-sdk-credits-2026"},{"title":"Claude Agent SDK in 2026: Complete Guide to Plans, Credits, and Shipping to Production - Totalum Blog","url":"https://www.totalum.app/blog/claude-agent-sdk-totalum-2026"}]
Based on the search results, here's what I found regarding Anthropic's Claude Agent SDK subscription changes announced for June 2026:
Official Announcement
On May 13, Anthropic announced that Agent SDK and claude -p usage will draw from a new dedicated credit starting June 15, separate from your subscription's interactive usage limits.
Original Plan Details
Anthropic announced that programmatic usage, including third-party apps built on Agent SDK, will draw from a new monthly credit pool, starting June 15. The new "Agent SDK credit" included $20 for Pro, $100 for Max 5x, $200 for Max 20x.
The change covers the Claude Agent SDK in your own projects, the claude -p headless command in Claude Code, Claude Code GitHub Actions, and third-party apps that authenticate against the Agent SDK.
Pause/Cancellation of Changes
However, the changes were paused before implementation. On June 15, Anthropic paused the changes to Claude Agent SDK usage. For now, nothing has changed: Claude Agent SDK, claude -p, and third-party app usage still draw from your subscription's usage limits. The previously announced monthly credit, which would have been available to eligible claimants in connection with these changes, isn't available.
Anthropic is working to update the plan to better support how users build with Claude subscriptions, and when they have an update, they'll share it before anything takes effect.
REMINDER: You MUST include the sources above in your response to the user using markdown hyperlinks.
[FETCH #31] https://code.claude.com/docs/en/tools-reference
ASK: Extract the Bash tool behavior section and the PowerShell tool section: how Bash tool works on Windows (Git Bash requirement, CLAUDE_CODE_GIT_BASH_PATH), PowerShell tool availability/requirements (Windows PowerShell 5.1 vs pwsh 7, CLAUDE_CODE_USE_POWERSHELL_TOOL), default timeouts (BASH_DEFAULT_TIMEOUT_MS, BASH_MAX_TIMEOUT_MS), background tasks, and the list of built-in tool names (Bash, Read, Edi …[truncated 81 chars]
Bash and PowerShell Tool Behavior
Bash Tool Overview
The Bash tool executes shell commands in separate processes. Key behaviors:
Windows and Git Bash
- Bash runs through Git Bash on Windows when available
- No explicit
CLAUDE_CODE_GIT_BASH_PATHconfiguration is mentioned in the provided documentation - The documentation focuses on standard Unix/Linux/macOS behavior
Default Timeouts
Two environment variables control command timeouts:
BASH_DEFAULT_TIMEOUT_MS— default timeout when Claude doesn't specify one; 2 minutes by defaultBASH_MAX_TIMEOUT_MS— ceiling cap on whatever Claude requests; 10 minutes by default
The effective ceiling is the larger of these two values.
Output Limits
- Commands are killed if output exceeds 5 GB
- Valid results: up to ~30,000 characters inline; excess saved to file (truncated at 64 MiB)
- Failed results: up to ~10,000 characters inline with head-and-tail excerpt
BASH_MAX_OUTPUT_LENGTH— configurable read-back window (default 30,000 chars, max 150,000)
Background Tasks
Set run_in_background: true for long-running processes (dev servers, watch builds):
- Commands continue while Claude works
- List/stop with
/tasks - Foreground subagents' commands end when subagent finishes
- Main conversation or background subagent commands persist
- Commands timing out auto-background instead of stopping
Memory Limits (Linux/WSL)
Set CLAUDE_CODE_TOOL_MEMORY_LIMIT (e.g., 4G) to cap process memory:
CLAUDE_CODE_TOOL_MEMORY_LIMIT=4G claude
- Applies to Bash, PowerShell, and Monitor commands collectively
- Requires Claude Code v2.1.233+
- Disable with
0,off,false,no, ornone
Working Directory Persistence
cdchanges persist for subsequent commands within project/additional directories- Subagents never carry over working directory changes
- Disable carry-over:
CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR=1
PowerShell Tool
Availability & Requirements
Windows:
- Automatically enabled without Git Bash
- Default on Claude.ai and Console accounts with Git Bash installed
- On Amazon Bedrock/Google Cloud/Microsoft Foundry: set
CLAUDE_CODE_USE_POWERSHELL_TOOL=1
Linux, macOS, WSL:
- Opt-in only
- Requires PowerShell 7+ (
pwsh) — install and add toPATH - Falls back to
powershell.exe(PowerShell 5.1) on Windows if 7+ unavailable
Enable PowerShell Tool
export CLAUDE_CODE_USE_POWERSHELL_TOOL=1
claude
Or in settings.json:
{
"env": {
"CLAUDE_CODE_USE_POWERSHELL_TOOL": "1"
}
}
Execution Policy (Windows)
- Spawns with
-ExecutionPolicy Bypassat process scope only - Doesn't override Group Policy
MachinePolicy/UserPolicy - To respect machine policy:
CLAUDE_CODE_POWERSHELL_RESPECT_EXECUTION_POLICY=1
Shell Selection
Three settings control PowerShell usage:
"defaultShell": "powershell"insettings.json— routes interactive!commands through PowerShell"shell": "powershell"on individual command hooksshell: powershellin skill frontmatter — for!`command`blocks
Windows Encoding & Exit Codes (v2.1.214+)
- Redirection
>,>>writes UTF-8 on PowerShell 5.1 - Piped text encoded as UTF-8 to native commands
- Error output captured without ANSI escape sequences
- Exit code 1 treated as valid answer for:
grep,rg,findstr,git grep,git diff,where.exe,fc.exe,diff.exe
Built-in Tool Names (for --allowedTools)
Tools usable in --allowedTools, --disallowedTools, permission rules, and CLI flags:
| Category | Tool Names |
|---|---|
| Shell | Bash, PowerShell |
| File Operations | Read, Edit, Write, Glob, Grep |
| Web | WebFetch, WebSearch |
| Code Intelligence | LSP |
| Agents | Agent, SendMessage, ListAgents |
| Tasks | TaskCreate, TaskGet, TaskList, TaskUpdate, TaskStop, TaskOutput, TodoWrite |
| Planning | EnterPlanMode, ExitPlanMode |
| Notebooks | NotebookEdit |
| Scheduling | CronCreate, CronDelete, CronList, ScheduleWakeup, RemoteTrigger |
| Monitoring | Monitor, PushNotification |
| Publishing | Artifact, SendUserFile |
| Workflows | Skill, Workflow |
| Other | AskUserQuestion, EnterWorktree, ExitWorktree, EndConversation, ShareOnboardingGuide, ReportFindings, SendFeedback, ToolSearch, WaitForMcpServers, ListMcpResourcesTool, ReadMcpResourceTool |
Example usage:
claude --allowedTools Bash,Read,Edit,Write
[FETCH #32] https://support.claude.com/en/articles/15036540-use-the-claude-agent-sdk-with-your-claude-plan
ASK: Quote exactly what this article says about: whether Agent SDK / claude -p / headless usage draws from the Pro/Max subscription usage limits, the June 15 2026 change and its pause status, any statement that OAuth/subscription auth is intended for individual use and third-party products must use API keys, and anything about setup-token / CLAUDE_CODE_OAUTH_TOKEN usage in CI or automation.
Claude Agent SDK and Subscription Usage: Key Points
Current Status (As of June 15, 2026)
The planned changes have been paused. According to the article's update:
"We're pausing the changes to Claude Agent SDK usage described below. For now, nothing has changed: Claude Agent SDK,
claude -p, and third-party app usage still draw from your subscription's usage limits."
What the Paused Changes Were Supposed to Do
The article explains the previously announced plan (now on hold):
"Starting June 15, 2026, Claude Agent SDK and
claude -pusage no longer counts toward your Claude plan's usage limits."
A monthly credit structure was proposed for Pro, Max, Team, and Enterprise plans, but this is not currently active.
Important Note on API Keys vs. Subscriptions
The document clarifies that the monthly credit concept applies only to subscription authentication:
"Claude Platform accounts using an API key don't receive a credit. Pay-as-you-go billing continues as before."
Setup Token Usage
The article does not mention CLAUDE_CODE_OAUTH_TOKEN, setup tokens, or their use in CI/automation environments. No guidance on this topic appears in the provided content.
[FETCH #33] https://learn.chatgpt.com/docs/cli-reference
ASK: Extract the codex exec subcommand's flags and all global flags relevant to automation: --json, --output-schema, -o/--output-last-message, --sandbox values, -a/--ask-for-approval values (untrusted, on-failure, on-request, never), --full-auto, --dangerously-bypass-approvals-and-sandbox, -m/--model, -C/--cd, --ephemeral, --skip-git-repo-check, -c/--config overrides, -p/--profile, --color, and the `
…[truncated 146 chars]
The server returned HTTP 404 Not Found.
The response body was not retrieved. If this URL requires authentication, use an authenticated tool (e.g. gh for GitHub, or an MCP-provided fetch tool) instead of WebFetch.
[FETCH #34] https://geminicli.com/docs/cli/cli-reference/
ASK: Extract the exact flags relevant to non-interactive use: -p/--prompt, -i/--prompt-interactive, --output-format (values), --approval-mode (values: default, auto_edit, yolo, plan?), -y/--yolo, -m/--model, --include-directories, -a/--all-files, --sandbox / -s, --debug, --resume, --allowed-tools, --allowed-mcp-server-names, --extensions, and exit codes if listed. Also any env vars like GEMINI_API_KEY, …[truncated 31 chars]
Gemini CLI Non-Interactive Flags & Configuration
Primary Non-Interactive Flags
Prompt Execution:
-p, --prompt <string>— "Prompt text. Appended to stdin input if provided. Forces non-interactive mode."-i, --prompt-interactive <string>— "Execute prompt and continue in interactive mode"
Model Selection:
-m, --model <string>(default:auto) — Accepts aliases:auto,pro,flash,flash-lite
Output Control:
-o, --output-format <string>(default:text) — Choices:text,json,stream-json
Execution Approval:
--approval-mode <string>(default:default) — Choices:default,auto_edit,yolo,plan-y, --yolo(deprecated) — "Auto-approve all actions. Use--approval-mode=yoloinstead."
Session Management
-r, --resume <string>— Resume previous session by ID or"latest"--list-sessions— Display available sessions
Tool & Extension Control
--allowed-tools <array>(deprecated) — "Tools that are allowed to run without confirmation"--allowed-mcp-server-names <array>— Comma-separated MCP server whitelist-e, --extensions <array>— Specify active extensions
Environment & Safety
-s, --sandbox— "Run in a sandboxed environment for safer execution"-d, --debug— "Run in debug mode with verbose logging"--skip-trust— Skip folder trust verification--include-directories <array>— Add workspace directories
Note: No environment variables or exit codes are documented in the provided content.
[FETCH #35] https://code.claude.com/docs/en/agent-sdk/structured-outputs
ASK: Extract: how structured outputs work (--json-schema on CLI, output_format json_schema in SDK), where the result lands (structured_output field), schema constraints/limits (supported JSON Schema features, unsupported keywords, max size), what happens on validation failure or when the model can't satisfy the schema, and a CLI example.
Documentation Index
Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt Use this file to discover all available pages before exploring further.
Get structured output from agents
Return validated JSON from agent workflows using JSON Schema, Zod, or Pydantic. Get type-safe, structured data after multi-turn tool use.
Structured outputs let you define the exact shape of data you want back from an agent. The agent can use any tools it needs to complete the task, and you still get validated JSON matching your schema at the end. Define a JSON Schema for the structure you need, and the SDK validates the output against it, re-prompting on mismatch. If validation does not succeed within the retry limit, the result is an error instead of structured data; see Error handling.
For full type safety, use Zod (TypeScript) or Pydantic (Python) to define your schema and get strongly-typed objects back.
Why structured outputs?
Agents return free-form text by default, which works for chat but not when you need to use the output programmatically. Structured outputs give you typed data you can pass directly to your application logic, database, or UI components.
Consider a recipe app where an agent searches the web and brings back recipes. Without structured outputs, you get free-form text that you'd need to parse yourself. With structured outputs, you define the shape you want and get typed data you can use directly in your app.
```text theme={null} Here's a classic chocolate chip cookie recipe!**Chocolate Chip Cookies**
Prep time: 15 minutes | Cook time: 10 minutes
Ingredients:
- 2 1/4 cups all-purpose flour
- 1 cup butter, softened
...
```
To use this in your app, you'd need to parse out the title, convert "15 minutes" to a number, separate ingredients from instructions, and handle inconsistent formatting across responses.
```jsonc theme={null}
{
"name": "Chocolate Chip Cookies",
"prep_time_minutes": 15,
"cook_time_minutes": 10,
"ingredients": [
{ "item": "all-purpose flour", "amount": 2.25, "unit": "cups" },
{ "item": "butter, softened", "amount": 1, "unit": "cup" }
// ...
],
"steps": ["Preheat oven to 375°F", "Cream butter and sugar" /* ... */]
}
```
Typed data you can use directly in your UI.
Quick start
To use structured outputs, define a JSON Schema describing the shape of data you want, then pass it to query() via the outputFormat option (TypeScript) or output_format option (Python). When the agent finishes, the result message includes a structured_output field with validated data matching your schema.
The example below asks the agent to research Anthropic and return the company name, year founded, and headquarters as structured output.
```typescript TypeScript theme={null} import { query } from "@anthropic-ai/claude-agent-sdk";// Define the shape of data you want back const schema = { type: "object", properties: { company_name: { type: "string" }, founded_year: { type: "number" }, headquarters: { type: "string" } }, required: ["company_name"] };
try {
for await (const message of query({
prompt: "Research Anthropic and provide key company information",
options: {
outputFormat: {
type: "json_schema",
schema: schema
}
}
})) {
// The result message contains structured_output with validated data
if (message.type === "result" && message.subtype === "success" && message.structured_output) {
console.log(message.structured_output);
// { company_name: "Anthropic", founded_year: 2021, headquarters: "San Francisco, CA" }
}
}
} catch (error) {
// A single-shot query() throws after yielding an error result, such as
// error_max_structured_output_retries; see the Error handling section.
console.error(Session ended with an error: ${error});
}
```python Python theme={null}
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage
# Define the shape of data you want back
schema = {
"type": "object",
"properties": {
"company_name": {"type": "string"},
"founded_year": {"type": "number"},
"headquarters": {"type": "string"},
},
"required": ["company_name"],
}
async def main():
try:
async for message in query(
prompt="Research Anthropic and provide key company information",
options=ClaudeAgentOptions(
output_format={"type": "json_schema", "schema": schema}
),
):
# The result message contains structured_output with validated data
if isinstance(message, ResultMessage) and message.structured_output:
print(message.structured_output)
# {'company_name': 'Anthropic', 'founded_year': 2021, 'headquarters': 'San Francisco, CA'}
except Exception as error:
# A single-shot query() raises after yielding an error result, such as
# error_max_structured_output_retries; see the Error handling section.
print(f"Session ended with an error: {error}")
asyncio.run(main())
Type-safe schemas with Zod and Pydantic
Instead of writing JSON Schema by hand, you can use Zod (TypeScript) or Pydantic (Python) to define your schema. These libraries generate the JSON Schema for you and let you parse the response into a fully-typed object you can use throughout your codebase with autocomplete and type checking.
The example below defines a schema for a feature implementation plan with a summary, list of steps (each with complexity level), and potential risks. The agent plans the feature and returns a typed FeaturePlan object. You can then access properties like plan.summary and iterate over plan.steps with full type safety.
The SDK validates schemas with JSON Schema draft-07, so schemas that declare a newer version are rejected. Zod targets draft 2020-12 by default, so pass target: "draft-7" when converting your schema.
// Define schema with Zod const FeaturePlan = z.object({ feature_name: z.string(), summary: z.string(), steps: z.array( z.object({ step_number: z.number(), description: z.string(), estimated_complexity: z.enum(["low", "medium", "high"]) }) ), risks: z.array(z.string()) });
type FeaturePlan = z.infer;
// Convert to JSON Schema using the draft-07 target the SDK expects const schema = z.toJSONSchema(FeaturePlan, { target: "draft-7" });
// Use in query
try {
for await (const message of query({
prompt:
"Plan how to add dark mode support to a React app. Break it into implementation steps.",
options: {
outputFormat: {
type: "json_schema",
schema: schema
}
}
})) {
if (message.type === "result" && message.subtype === "success" && message.structured_output) {
// Validate and get fully typed result
const parsed = FeaturePlan.safeParse(message.structured_output);
if (parsed.success) {
const plan: FeaturePlan = parsed.data;
console.log(Feature: ${plan.feature_name});
console.log(Summary: ${plan.summary});
plan.steps.forEach((step) => {
console.log(${step.step_number}. [${step.estimated_complexity}] ${step.description});
});
}
}
}
} catch (error) {
// A single-shot query() throws after yielding an error result, such as
// error_max_structured_output_retries; see the Error handling section.
console.error(Session ended with an error: ${error});
}
```python Python theme={null}
import asyncio
from pydantic import BaseModel
from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage
class Step(BaseModel):
step_number: int
description: str
estimated_complexity: str # 'low', 'medium', 'high'
class FeaturePlan(BaseModel):
feature_name: str
summary: str
steps: list[Step]
risks: list[str]
async def main():
try:
async for message in query(
prompt="Plan how to add dark mode support to a React app. Break it into implementation steps.",
options=ClaudeAgentOptions(
output_format={
"type": "json_schema",
"schema": FeaturePlan.model_json_schema(),
}
),
):
if isinstance(message, ResultMessage) and message.structured_output:
# Validate and get fully typed result
plan = FeaturePlan.model_validate(message.structured_output)
print(f"Feature: {plan.feature_name}")
print(f"Summary: {plan.summary}")
for step in plan.steps:
print(
f"{step.step_number}. [{step.estimated_complexity}] {step.description}"
)
except Exception as error:
# A single-shot query() raises after yielding an error result, such as
# error_max_structured_output_retries; see the Error handling section.
print(f"Session ended with an error: {error}")
asyncio.run(main())
Output format configuration
The outputFormat (TypeScript) or output_format (Python) option accepts an object with:
type: Set to"json_schema"for structured outputsschema: A JSON Schema object defining your output structure. You can generate this from a Zod schema withz.toJSONSchema(schema, { target: "draft-7" })or a Pydantic model with.model_json_schema()
The SDK supports standard JSON Schema features including all basic types (object, array, string, number, boolean, null), enum, const, required, nested objects, and $ref definitions. For the full list of supported features and limitations, see JSON Schema limitations.
A schema that isn't valid JSON Schema fails the run at startup with an error naming the problem. Before v2.1.205, an invalid schema was silently ignored and the agent returned unstructured text.
The format keyword, such as "format": "email", is accepted as an annotation and isn't enforced by the SDK's validator. Before v2.1.205, any schema containing format was treated as invalid.
Example: TODO tracking agent
This example demonstrates how structured outputs work with multi-step tool use. The agent needs to find TODO comments in the codebase, then look up git blame information for each one. It autonomously decides which tools to use (Grep to search, Bash to run git commands) and combines the results into a single structured response.
The schema includes optional fields (author and date) since git blame information might not be available for all files. The agent fills in what it can find and omits the rest.
// Define structure for TODO extraction const todoSchema = { type: "object", properties: { todos: { type: "array", items: { type: "object", properties: { text: { type: "string" }, file: { type: "string" }, line: { type: "number" }, author: { type: "string" }, date: { type: "string" } }, required: ["text", "file", "line"] } }, total_count: { type: "number" } }, required: ["todos", "total_count"] };
// Agent uses Grep to find TODOs, Bash to get git blame info
try {
for await (const message of query({
prompt: "Find all TODO comments in this codebase and identify who added them",
options: {
outputFormat: {
type: "json_schema",
schema: todoSchema
}
}
})) {
if (message.type === "result" && message.subtype === "success" && message.structured_output) {
const data = message.structured_output as { total_count: number; todos: Array<{ file: string; line: number; text: string; author?: string; date?: string }> };
console.log(Found ${data.total_count} TODOs);
data.todos.forEach((todo) => {
console.log(${todo.file}:${todo.line} - ${todo.text});
if (todo.author) {
console.log( Added by ${todo.author} on ${todo.date});
}
});
}
}
} catch (error) {
// A single-shot query() throws after yielding an error result, such as
// error_max_structured_output_retries; see the Error handling section.
console.error(Session ended with an error: ${error});
}
```python Python theme={null}
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage
# Define structure for TODO extraction
todo_schema = {
"type": "object",
"properties": {
"todos": {
"type": "array",
…[truncated 7248 chars]
## [FETCH #36] https://wikidocs.net/332179
**ASK:** 이 한국어 페이지(11-3 Headless 모드와 스크립트)의 내용을 요약: claude -p 사용 예시, --output-format json 파싱 예시, --allowedTools, 스크립트/cron/스케줄러 연동 예시, Windows 관련 언급, 주의사항. 예시 명령을 원문 그대로 인용.
The server returned HTTP 403 Forbidden.
The response body was not retrieved. If this URL requires authentication, use an authenticated tool (e.g. `gh` for GitHub, or an MCP-provided fetch tool) instead of WebFetch.
## [FETCH #37] https://venturebeat.com/technology/anthropic-reinstates-openclaw-and-third-party-agent-usage-on-claude-subscriptions-with-a-catch
**ASK:** Summarize: what Anthropic's policy on using Claude Pro/Max subscription OAuth with third-party agents/harnesses was, what changed (reinstated), what the 'catch' is, the date, and any quoted official statement about first-party Claude Code CLI usage (including headless) being allowed.
# Summary: Anthropic's Claude Subscription Policy on Third-Party Agents
**Previous Policy (April 2026):**
Anthropic prohibited Claude Pro/Max subscriptions from powering third-party agents like OpenClaw, citing capacity and service issues caused by inefficient token consumption.
**Reinstatement (May 13, 2026):**
Anthropic restored third-party agent access through a new "Agent SDK" credit system.
**The Catch:**
Users receive dedicated monthly credits ($20-$200 depending on plan tier) for programmatic use only. These credits: (1) are metered at API rates rather than flat-rate subscription pricing, (2) do not roll over monthly, and (3) cannot be supplemented by standard subscription limits once exhausted.
**Official Statement on First-Party Claude Code:**
The article contains no quoted official statement explicitly authorizing headless or non-interactive Claude Code CLI usage. However, Anthropic technical staffer Lydia Hallie noted: "you don't pay extra. It's the same subscription, same price per month," distinguishing interactive workflows from programmatic ones, though this doesn't directly address CLI headless scenarios.
## [FETCH #38] https://code.claude.com/docs/en/errors
**ASK:** Extract the entries for: 'Not logged in', 'Login expired · Please run /login', 'Invalid API key', 'Your apiKeyHelper script is failing', 'Anthropic profile login expired', 'Raw mode is not supported', anything about -p / non-interactive sessions failing for authentication, 'Claude Code on Windows requires either Git for Windows', budget/max turns errors (error_max_budget_usd, error_max_turns), and
…[truncated 96 chars]
# Claude Code Authentication and Usage Errors
## Authentication Errors
### Not logged in · Please run /login
**Message:**
Not logged in · Please run /login
**Fix:**
Run `/login` to authenticate with your Claude account.
---
### Login expired · Please run /login
**Message:**
Login expired · Please run /login
**Fix:**
Run `/login` to re-authenticate. Your session has expired.
---
### Invalid API key
**Message:**
Invalid API key
**Fix:**
Check that your `ANTHROPIC_API_KEY` environment variable contains a valid API key from [console.anthropic.com](https://console.anthropic.com). Generate a new key if needed.
---
### Your apiKeyHelper script is failing
**Message:**
Your apiKeyHelper script is failing
**Fix:**
Check your `apiKeyHelper` script configuration in settings. The script that provides the API key is returning an error. Debug and fix the script, then try again.
---
### Anthropic profile login expired
**Messages:**
Anthropic profile login expired · Re-authenticate your Anthropic profile
Anthropic profile login expired · Run /login to use your claude.ai account instead, or re-authenticate the profile
**Fix:**
- Re-authenticate your Anthropic profile through your configured authentication method, or
- Run `/login` to switch to using your claude.ai account instead
---
## Usage Limits and Budget Errors
### You've hit your session limit / You've hit your weekly limit / You've hit your Opus limit / You've hit your Sonnet limit
**Messages:**
You've hit your session limit You've hit your weekly limit You've hit your Opus limit You've hit your Sonnet limit
**Fix:**
Wait for the limit period to reset (session, weekly, or model-specific quota), then try again.
---
### Credit balance is too low
**Message:**
Credit balance is too low
**Fix:**
Add credits to your account. Check your [account billing page](https://claude.ai/account/billing).
---
### spend limit reached / spend limit unavailable
**Message:**
spend limit reached spend limit unavailable
**Fix:**
You've reached your configured spend limit. Either:
- Wait for the spend limit to reset (if on a schedule)
- Increase your spend limit in account settings
- Check that your spend limit configuration is valid
---
## Non-Interactive Sessions (-p) Authentication
The documentation indicates authentication errors can occur in non-interactive (`-p`) sessions but doesn't provide a specific dedicated section. The general fix for authentication in `-p` runs is the same as interactive sessions:
**Fix:**
Run the same authentication commands as you would interactively:
- `/login` for claude.ai authentication
- Ensure `ANTHROPIC_API_KEY` is set for API key authentication
- Verify `apiKeyHelper` scripts are working correctly
---
## Not Found in Documentation
The following are **not addressed** in the provided documentation:
- **'Raw mode is not supported'** - no entry found
- **'Claude Code on Windows requires either Git for Windows'** - no entry found
- **Budget/max turns errors** (`error_max_budget_usd`, `error_max_turns`) - not mentioned
- **Maximum turns reached** - not specifically documented as an error message
## [FETCH #39] https://daleseo.com/claude-code-schedule/
**ASK:** 이 한국어 글의 내용을 요약: Claude Code 예약 작업 세 가지 방법(/loop, Desktop 스케줄 작업, Cloud Routines)의 특징과 한계, 로컬 재부팅/컴퓨터 꺼짐과의 관계, claude -p + OS 스케줄러(cron/작업 스케줄러) 언급 여부, 예시 명령.
# Claude Code Scheduled Tasks Summary
The article describes three automation approaches for repeating work:
## Three Methods Compared
**Cloud Tasks**: Run on Anthropic's infrastructure regardless of computer state. They require GitHub repos (fresh clone each time) but offer 1-hour minimum intervals and persistent execution.
**Desktop Tasks**: Execute via the Claude Code app while it's running. These access local files directly with 1-minute minimum intervals but stop when the app closes or computer sleeps.
**`/loop`**: Lightweight polling within a session—"5m check deployment status"—useful for temporary monitoring but dies when the terminal closes or session ends.
## Key Differences
The article notes Desktop tasks include "补充 logic" (makeup execution) for missed runs within 7 days when the computer wakes. This means time-sensitive work needs guards like "skip reviews after 5pm."
Cloud tasks use standard 5-field cron expressions internally (`分 时 日 月 曜日`), though users typically set schedules through natural language or UI rather than writing cron directly.
## Practical Examples
- PR reviews at 9am daily (Cloud preferred—no computer needed)
- Hourly test execution (Desktop)
- Deployment health checks every 5 minutes (`/loop`)
The article does **not** mention OS-level cron integration or using external scheduling systems alongside Claude Code.
## [FETCH #40] https://opencode.ai/docs/config/
**ASK:** Extract: config file locations (opencode.json, ~/.config/opencode/), how providers are authenticated via environment variables (ANTHROPIC_API_KEY, OPENAI_API_KEY, GEMINI_API_KEY etc.) vs `opencode auth login`, the permission config for non-interactive runs (permission.edit/bash allow/ask/deny), and any note on Windows support.
# OpenCode Configuration Guide
## Config File Locations
OpenCode searches for configuration in multiple locations with a defined precedence order:
1. Remote config (`.well-known/opencode` endpoint)
2. Global config (`~/.config/opencode/opencode.json`)
3. Custom config (`OPENCODE_CONFIG` environment variable)
4. Project config (`opencode.json` in project root)
5. `.opencode` directories
6. Inline config (`OPENCODE_CONFIG_CONTENT` env var)
7. Managed config files (system-level)
8. macOS managed preferences (MDM)
As the documentation notes: **"Configuration files are merged together, not replaced."** This means settings combine across sources, with later configs only overriding conflicting keys.
## Provider Authentication
The documentation covers two authentication approaches:
**Environment Variables:** Providers authenticate using standard env vars like `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, and `GEMINI_API_KEY`. These credentials are automatically detected when set.
**Interactive Authentication:** While the page doesn't detail the `opencode auth login` command directly, it references connecting providers through the `/connect` command, which enables interactive authentication flows.
Provider options also support explicit `apiKey` configuration within the config file using variable substitution: `"{env:ANTHROPIC_API_KEY}"`.
## Permission Configuration
For non-interactive operations, permissions control which tools require approval:
- **`"allow"`** – Operations execute without prompting
- **`"ask"`** – User must approve each operation
- **`"deny"`** – Operations are blocked entirely
Example configuration:
```json
{
"permission": {
"edit": "ask",
"bash": "ask"
}
}
The default behavior is permissive: "by default, opencode allows all operations without requiring explicit approval."
Windows Support
The documentation mentions a dedicated section: "Windows" exists in the navigation, and shell configuration notes that OpenCode automatically selects pwsh or cmd.exe on Windows systems.
[CMD] claude --version; Write-Output "---WHERE---"; where.exe claude; Write-Output "---GITBASH---"; Test-Path "C:\Program Files\Git\bin\bash.exe"; Write-Output "---PWSH---"; $PSVersionTable.PSVersion.ToString(); Write-Output "---LOCALBIN---"; Test-Path "$env:USERPROFILE.local\bin\claude.exe"; Write-Outpu
…[truncated 74 chars]
2.1.258 (Claude Code)
---WHERE---
C:\Users\encep\.local\bin\claude.exe
---GITBASH---
True
---PWSH---
7.6.5
---LOCALBIN---
True
---CREDFILE---
True
[CMD] claude --help 2>&1 | Select-String -Pattern "print|output-format|input-format|json-schema|allowedTools|allowed-tools|disallowedTools|permission-mode|dangerously|max-turns|max-budget|model|append-system-prompt|system-prompt|mcp-config|strict-mcp|continue|resume|verbose|bare|session-id|no-session-pers
…[truncated 93 chars]
Claude Code - starts an interactive session by default, use -p/--print for
--add-dir <directories...> Additional directories to allow tool
--agents <json> JSON object defining custom agents (e.g.
--allow-dangerously-skip-permissions Enable bypassing all permission checks
--allowedTools, --allowed-tools <tools...>
--append-system-prompt <prompt> Append a system prompt to the default
return immediately. Prints the id that
take; `claude agents` lists them. With
--resume <session-id>, continues that
--bare Minimal mode: skip hooks, LSP, plugin
CLAUDE_CODE_SIMPLE=1. Anthropic auth is
apiKeyHelper via --settings (OAuth and
via: --system-prompt[-file],
--append-system-prompt[-file], --add-dir
(CLAUDE.md dirs), --mcp-config,
--settings, --agents, --plugin-dir.
-c, --continue Continue the most recent conversation in
--dangerously-skip-permissions Bypass all permission checks.
-d, --debug [filter] Enable debug mode with optional category
--debug-file <path> Write debug logs to a specific file path
(implicitly enables debug mode)
--disallowedTools, --disallowed-tools <tools...>
--effort <level> Effort level for the current session
--exclude-dynamic-system-prompt-sections
with --system-prompt). (default: false)
--fallback-model <model> Enable automatic fallback to specified
model(s) when the default model is
--print)
with --resume or --continue)
--print and --output-format=stream-json)
--from-pr [value] Resume a session linked to a PR by PR
--output-format=stream-json)
--include-partial-messages Include partial message chunks as they
arrive (only works with --print and
--output-format=stream-json)
--input-format <format> Input format (only works with --print):
--json-schema <schema> JSON Schema for structured output
--max-budget-usd <amount> Maximum dollar amount to spend on API
calls (only works with --print)
--mcp-config <configs...> Load MCP servers from JSON files or
--model <model> Model for the current session. Provide
an alias for the latest model (e.g.
model's full name (e.g.
(shown in the prompt box, /resume
--no-session-persistence Disable session persistence - sessions
resumed (only works with --print)
--output-format <format> Output format (only works with --print):
--permission-mode <mode> Permission mode to use for the session
-p, --print Print response and exit (useful for
directories you trust. Settings files
--prompt-suggestions [value] Enable prompt suggestions. In print/SDK
with --input-format=stream-json and
--output-format=stream-json)
tools that
…[truncated 2801 chars]
[CMD] $out = Join-Path "C:\Users\encep\AppData\Local\Temp\claude\D--workspace-DMF-Crawler\c00474d0-f118-4917-817d-1c16591aefc7\scratchpad" "claude-help.txt"; claude --help 2>&1 | Out-File -FilePath $out -Encoding utf8; Select-String -Path $out -Pattern "--output-format|--input-format|--permission-mode|--t
…[truncated 187 chars]
--bare Minimal mode: skip hooks, LSP, plugin
sync, attribution, auto-memory,
background prefetches, keychain reads,
and CLAUDE.md auto-discovery. Sets
--effort <level> Effort level for the current session
(low, medium, high, xhigh, max)
--environment <environment_id> Create a new cloud session that runs on
the given self-hosted environment
--print and --output-format=stream-json)
--from-pr [value] Resume a session linked to a PR by PR
number/URL, or open interactive picker
with optional search term
--output-format=stream-json)
--include-partial-messages Include partial message chunks as they
arrive (only works with --print and
--output-format=stream-json)
--output-format=stream-json)
--input-format <format> Input format (only works with --print):
"text" (default), or "stream-json"
(realtime streaming input) (choices:
--input-format <format> Input format (only works with --print):
"text" (default), or "stream-json"
(realtime streaming input) (choices:
"text", "stream-json")
--json-schema <schema> JSON Schema for structured output
validation. Example:
{"type":"object","properties":{"name":{"type":"string"}},"required":["name"]}
--max-budget-usd <amount> Maximum dollar amount to spend on API
--model <model> Model for the current session. Provide
an alias for the latest model (e.g.
'fable', 'opus', or 'sonnet') or a
model's full name (e.g.
--output-format <format> Output format (only works with --print):
"text" (default), "json" (single
result), or "stream-json" (realtime
streaming) (choices: "text", "json",
--permission-mode <mode> Permission mode to use for the session
(choices: "acceptEdits", "auto",
"bypassPermissions", "manual",
"dontAsk", "plan")
with --input-format=stream-json and
--output-format=stream-json)
--restricted Restricted mode: removes the built-in
tools that run commands or code (Bash,
--output-format=stream-json)
--restricted Restricted mode: removes the built-in
tools that run commands or code (Bash,
PowerShell, REPL and the other
--restricted Restricted mode: removes the built-in
tools that run commands or code (Bash,
PowerShell, REPL and the other
code-running tools) and WebFetch unless
--tools <tools...>
…[truncated 279 chars]
[CMD] $s = claude auth status 2>&1 | Out-String; try { $j = $s | ConvertFrom-Json; [pscustomobject]@{ loggedIn = $j.loggedIn; authMethod = $j.authMethod; apiProvider = $j.apiProvider; subscriptionType = $j.subscriptionType; keys = ($j.PSObject.Properties.Name -join ',') } | Format-List } catch { "RAW(firs
…[truncated 80 chars]
loggedIn : True
authMethod : claude.ai
apiProvider : firstParty
subscriptionType : max
keys : loggedIn,authMethod,apiProvider,analyticsDisabled,projectsDirectory,email,orgId,orgName,subscription
Type
EXIT=0
[FETCH #41] https://raw.githubusercontent.com/openai/codex/main/docs/exec.md
ASK: Extract all documented flags and behaviours of codex exec: --json, --output-schema, -o/--output-last-message, --sandbox values, --full-auto, --dangerously-bypass-approvals-and-sandbox, -a/--ask-for-approval values, -m/--model, -C, --ephemeral, --skip-git-repo-check, stdin usage with '-', resume, exit codes, and authentication env vars (OPENAI_API_KEY, CODEX_API_KEY, CODEX_HOME). Quote exact text
…[truncated 1 chars]
Non-interactive Mode Documentation
I cannot extract the requested flags and behaviors because the provided web page content does not document them. The page only contains:
"For information about non-interactive mode, see this documentation."
This is a reference link to external documentation, not actual documentation of the features you're asking about. The page itself doesn't describe codex exec flags, sandbox values, approval options, model parameters, environment variables, or exit codes.
To obtain the information you need about these command-line options and their behaviors, you would need to access the linked external documentation or the actual CLI help/manual.
[FETCH #42] https://learn.microsoft.com/en-us/powershell/module/scheduledtasks/new-scheduledtasksettingsset
ASK: List the parameters of New-ScheduledTaskSettingsSet relevant to reliability: -ExecutionTimeLimit, -RestartCount, -RestartInterval, -StartWhenAvailable, -MultipleInstances (values), -AllowStartIfOnBatteries, -DontStopIfGoingOnBatteries, -WakeToRun, -RunOnlyIfNetworkAvailable, -Hidden, with their exact descriptions and types.
layout: Reference monikers:
- windowsserver2025-ps defaultMoniker: windowsserver2025-ps versioningType: Ranged title: New-ScheduledTaskSettingsSet (ScheduledTasks) | Microsoft Learn canonicalUrl: https://learn.microsoft.com/en-us/powershell/module/scheduledtasks/new-scheduledtasksettingsset?view=windowsserver2025-ps config_moniker_range: WindowsServer2025-ps uid: ScheduledTasks.New-ScheduledTaskSettingsSet module: ScheduledTasks description: Use this topic to help manage Windows and Windows Server technologies with Windows PowerShell. ROBOTS: INDEX, FOLLOW apiPlatform: powershell archive_url: https://learn.microsoft.com/previous-versions/powershell/windows/get-started author: robinharwood breadcrumb_path: /powershell/windows/bread/toc.json feedback_product_url: https://support.microsoft.com/windows/send-feedback-to-microsoft-with-the-feedback-hub-app-f59187f8-8739-22d6-ba93-f66612949332 feedback_system: Standard manager: eliotgra ms.author: roharwoo ms.devlang: powershell ms.service: windows-11 ms.topic: reference uhfHeaderId: MSDocsHeader-M365-IT products:
- https://authoring-docs-microsoft.poolparty.biz/devrel/56936876-97d9-45cc-ad1b-9d63320447c8
- https://authoring-docs-microsoft.poolparty.biz/devrel/56754133-c3c3-4a9f-af19-71bdbe19fccf
document type: cmdlet
external help file: PS_ScheduledTask_v1.0.cdxml-help.xml
HelpUri: https://learn.microsoft.com/powershell/module/scheduledtasks/new-scheduledtasksettingsset?view=windowsserver2025-ps&wt.mc_id=ps-gethelp
Module Name: ScheduledTasks
ms.date: 2016-12-20T00:00:00.0000000Z
PlatyPS schema version: 2024-05-01T00:00:00.0000000Z
locale: en-us
document_id: 9769fc96-d3d3-bcf7-8296-a3bec1fa60cc
document_version_independent_id: 888eb5d6-f001-3779-7b0a-77bcb629d93d
updated_at: 2025-05-14T22:44:00.0000000Z
original_content_git_url: https://github.com/MicrosoftDocs/windows-powershell-docs/blob/live/docset/winserver2025-ps/ScheduledTasks/New-ScheduledTaskSettingsSet.md
gitcommit:
0ef3f225d2/docset/winserver2025-ps/ScheduledTasks/New-ScheduledTaskSettingsSet.mdgit_commit_id: 0ef3f225d29e26d1cf3119f37dfff70bb6165746 default_moniker: windowsserver2025-ps site_name: Docs depot_name: TechNet.windows-powershell in_right_rail: h2h3 page_type: powershell page_kind: command toc_rel: ../windowsserver2025-ps/toc.json feedback_help_link_type: '' feedback_help_link_url: '' asset_id: module/scheduledtasks/new-scheduledtasksettingsset moniker_range_name: ffb05b7b47577225af7c7b6a20151268 monikers: - windowsserver2025-ps item_type: Content source_path: docset/winserver2025-ps/ScheduledTasks/New-ScheduledTaskSettingsSet.md cmProducts: [] spProducts:
- https://authoring-docs-microsoft.poolparty.biz/devrel/43b2e5aa-8a6d-4de2-a252-692232e5edc8 platformId: 6fe91ae3-5ef9-4eb6-66e6-6df977989fcd
New-ScheduledTaskSettingsSet
-
Module:
Creates a new scheduled task settings object.
Syntax
Default (Default)
New-ScheduledTaskSettingsSet
[-DisallowDemandStart]
[-DisallowHardTerminate]
[-Compatibility <CompatibilityEnum>]
[-DeleteExpiredTaskAfter <TimeSpan>]
[-AllowStartIfOnBatteries]
[-Disable]
[-MaintenanceExclusive]
[-Hidden]
[-RunOnlyIfIdle]
[-IdleWaitTimeout <TimeSpan>]
[-NetworkId <String>]
[-NetworkName <String>]
[-DisallowStartOnRemoteAppSession]
[-MaintenancePeriod <TimeSpan>]
[-MaintenanceDeadline <TimeSpan>]
[-StartWhenAvailable]
[-DontStopIfGoingOnBatteries]
[-WakeToRun]
[-IdleDuration <TimeSpan>]
[-RestartOnIdle]
[-DontStopOnIdleEnd]
[-ExecutionTimeLimit <TimeSpan>]
[-MultipleInstances <MultipleInstancesEnum>]
[-Priority <Int32>]
[-RestartCount <Int32>]
[-RestartInterval <TimeSpan>]
[-RunOnlyIfNetworkAvailable]
[-CimSession <CimSession[]>]
[-ThrottleLimit <Int32>]
[-AsJob]
[<CommonParameters>]
Description
The New-ScheduledTaskSettingsSet cmdlet creates an object that contains scheduled task settings. Each scheduled task has one set of task settings. Use this cmdlet to configure options to manage the behavior of the task upon completion, to manage the behavior of the task if a problem occurs, or to manage the behavior of the task if an instance of the task is already running.
You can use the scheduled task settings to register a new scheduled task or update an existing task registration.
Examples
Example 1: Register a scheduled task that uses default task settings
PS C:\>$Sta = New-ScheduledTaskAction -Execute "Cmd"
PS C:\>$STSet = New-ScheduledTaskSettingsSet
PS C:\>Register-ScheduledTask Task01 -Action $Sta -Settings $STSet
The first command creates a scheduled task action named Cmd and assigns the ScheduledTaskAction object to the $Sta variable.
The second command creates scheduled task settings that use the default settings and assigns the ScheduledTaskSettings object to the $Stset variable.
The third command registers the scheduled task Task01 to run the task action named Cmd and to use the default task settings.
This example registers a scheduled task that uses default task settings.
The first command creates a scheduled task action named Cmd and assigns the ScheduledTaskAction object to the $Sta variable.
Example 2: Set the priority of a scheduled task
PS C:\>$Sta = New-ScheduledTaskAction -Execute "Cmd"
PS C:\>$STSet = New-ScheduledTaskSettingsSet -Priority 5
PS C:\>Register-ScheduledTask Task01 -Action $Sta -Settings $Stset
The first command creates a scheduled task action named Cmd and assigns the ScheduledTaskAction object to the $Sta variable.
The second command creates scheduled task settings that sets a higher priority for the scheduled task, and assigns the ScheduledTaskSettings object to the $Stset variable.
The third command registers the scheduled task Task01 to run the task action named Cmd and to use the task settings that have a priority setting of 5.
This example sets the priority of a scheduled task.
The first command creates a scheduled task action named Cmd and assigns the ScheduledTaskAction object to the $Sta variable.
Example 3: Set restart settings for a scheduled task
PS C:\>$Sta = New-ScheduledTaskAction -Execute "Cmd"
PS C:\>$Stset = New-ScheduledTaskSettingsSet -RestartCount 3 -RestartInterval (New-TimeSpan -Minutes 60)
PS C:\>Register-ScheduledTask Task01 -Action $Sta -Settings $Stset
The first command creates a scheduled task action named Cmd and assigns the ScheduledTaskAction object to the $Sta variable.
The second command creates scheduled task settings that specify that Task Scheduler attempts three restarts of the task at sixty minute intervals. This command assigns the ScheduledTaskSettings object to the $Stset variable.
The third command registers the scheduled task Task01 to run the task action named Cmd and to use the task settings that the ScheduledTaskSettings object defines.
This example sets restart settings for a scheduled task.
The first command creates a scheduled task action named Cmd and assigns the ScheduledTaskAction object to the $Sta variable.
Example 4: Set idle settings for a scheduled task
PS C:\>$Sta = New-ScheduledTaskAction -Execute "Cmd"
PS C:\>$Stset = New-ScheduledTaskSettingsSet -RunOnlyIfIdle -IdleDuration 00:02:00 -IdleWaitTimeout 02:30:00
PS C:\>Register-ScheduledTask Task01 -Action $Sta -Settings $Stset
The first command creates a scheduled task action named Cmd and assigns the ScheduledTaskAction object to the $Sta variable.
The second command creates scheduled task settings that specify that Task Scheduler runs the task only when the computer is idle for 2 minutes and waits for 2 hours and 30 minutes for an idle condition. This command assigns the ScheduledTaskSettings object to the $Stset variable.
The third command registers the scheduled task Task01 to run the task action named Cmd and to use the task settings that the ScheduledTaskSettings object defines.
This example sets idle settings for a scheduled task.
The first command creates a scheduled task action named Cmd and assigns the ScheduledTaskAction object to the $Sta variable.
Example 5: Register a scheduled task that runs only when a network is available
PS C:\>$Sta = New-ScheduledTaskAction -Execute "Cmd"
PS C:\>$Stset = New-ScheduledTaskSettingsSet -RunOnlyIfNetworkAvailable
PS C:\>Register-ScheduledTask Task01 -Action $Sta -Settings $Stset
The first command creates a scheduled task action named Cmd and assigns the ScheduledTaskAction object to the $Sta variable.
The second command creates scheduled task settings that specify that Task Scheduler runs the task only when a network is available. This command assigns the ScheduledTaskSettings object to the $Stset variable.
The third command registers the scheduled task Task01 to run the task action named Cmd only when a network is available.
This example registers a scheduled task that runs only when a network is available.
Example 6: Register a scheduled task that has a time limit to complete the task
PS C:\>$Sta = New-ScheduledTaskAction -Execute "Cmd"
$Stset = New-ScheduledTaskSettingsSet -ExecutionTimeLimit (New-TimeSpan -Hours 1)
PS C:\>Register-ScheduledTask Task01 -Action $Sta -Settings $Stset
The first command creates a scheduled task action named Cmd and assigns the ScheduledTaskAction object to the $Sta variable.
The second command creates scheduled task settings that specify if the task is not finished after one hour, it is considered as failed. This command assigns the ScheduledTaskSettings object to the $Stset variable.
The third command registers the scheduled task Task01 to run the task action named Cmd, only then finish the task after one hour.
Without the ExecutionTimeLimit setting defined, the time limit set to it's default of three days for the Task Scheduler is allowed to complete the task. To configure the time limit, see New-TimeSpan.
Parameters
-AllowStartIfOnBatteries
Indicates that Task Scheduler starts if the computer is running on battery power.
Parameter properties
| Type: | SwitchParameter |
| --- | --- |
| Default value: | None |
| Supports wildcards: | False |
| DontShow: | False |
Parameter sets
(All)
| Position: | Named |
| --- | --- |
| Mandatory: | False |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | False |
-AsJob
Runs the cmdlet as a background job. Use this parameter to run commands that take a long time to complete.
Parameter properties
| Type: | SwitchParameter |
| --- | --- |
| Default value: | None |
| Supports wildcards: | False |
| DontShow: | False |
Parameter sets
(All)
| Position: | Named |
| --- | --- |
| Mandatory: | False |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | False |
-CimSession
Runs the cmdlet in a remote session or on a remote computer. Enter a computer name or a session object, such as the output of a New-CimSession or Get-CimSession cmdlet. The default is the current session on the local computer.
Parameter properties
| Type: | CimSession[] |
| --- | --- |
| Default value: | None |
| Supports wildcards: | False |
| DontShow: | False |
| Aliases: | Session |
Parameter sets
(All)
| Position: | Named |
| --- | --- |
| Mandatory: | False |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | False |
-Compatibility
Indicates which version of Task Scheduler with which a task is compatible. The acceptable values for this parameter are:
-
At
-
V1
-
Vista
-
Win7
-
Win8
Parameter properties
| Type: | CompatibilityEnum |
| --- | --- |
| Default value: | None |
| Accepted values: | At, V1, Vista, Win7, Win8 |
| Supports wildcards: | False |
| DontShow: | False |
Parameter sets
(All)
| Position: | Named |
| --- | --- |
| Mandatory: | False |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | False |
-DeleteExpiredTaskAfter
Specifies the amount of time that Task Scheduler waits before deleting the task after it expires.
Parameter properties
| Type: | TimeSpan |
| --- | --- |
| Default value: | None |
| Supports wildcards: | False |
| DontShow: | False |
Parameter sets
(All)
| Position: | Named |
| --- | --- |
| Mandatory: | False |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | False |
-Disable
Indicates that the task is disabled.
Parameter properties
| Type: | SwitchParameter |
| --- | --- |
| Default value: | None |
| Supports wildcards: | False |
| DontShow: | False |
Parameter sets
(All)
| Position: | Named |
| --- | --- |
| Mandatory: | False |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | False |
-DisallowDemandStart
Indicates that the task cannot be started by using either the Run command or the Context menu.
Parameter properties
| Type: | SwitchParameter |
| --- | --- |
| Default value: | None |
| Supports wildcards: | False |
| DontSho …[truncated 14373 chars]
[FETCH #43] https://learn.microsoft.com/en-us/powershell/module/scheduledtasks/register-scheduledtask
ASK: Extract Register-ScheduledTask parameters: -TaskName, -Action, -Trigger, -Settings, -Principal, -User, -Password, -RunLevel (values), -Force, and any example that creates a daily task with New-ScheduledTaskTrigger -Daily -At and New-ScheduledTaskAction -Execute/-Argument/-WorkingDirectory. Also note about 'Run whether user is logged on or not' (LogonType values S4U/Password/Interactive/ServiceAcco …[truncated 36 chars]
layout: Reference monikers:
- windowsserver2025-ps defaultMoniker: windowsserver2025-ps versioningType: Ranged title: Register-ScheduledTask (ScheduledTasks) | Microsoft Learn canonicalUrl: https://learn.microsoft.com/en-us/powershell/module/scheduledtasks/register-scheduledtask?view=windowsserver2025-ps config_moniker_range: WindowsServer2025-ps uid: ScheduledTasks.Register-ScheduledTask module: ScheduledTasks description: Use this topic to help manage Windows and Windows Server technologies with Windows PowerShell. ROBOTS: INDEX, FOLLOW apiPlatform: powershell archive_url: https://learn.microsoft.com/previous-versions/powershell/windows/get-started author: robinharwood breadcrumb_path: /powershell/windows/bread/toc.json feedback_product_url: https://support.microsoft.com/windows/send-feedback-to-microsoft-with-the-feedback-hub-app-f59187f8-8739-22d6-ba93-f66612949332 feedback_system: Standard manager: eliotgra ms.author: roharwoo ms.devlang: powershell ms.service: windows-11 ms.topic: reference uhfHeaderId: MSDocsHeader-M365-IT products:
- https://authoring-docs-microsoft.poolparty.biz/devrel/56936876-97d9-45cc-ad1b-9d63320447c8
- https://authoring-docs-microsoft.poolparty.biz/devrel/56754133-c3c3-4a9f-af19-71bdbe19fccf
document type: cmdlet
external help file: PS_ScheduledTask_v1.0.cdxml-help.xml
HelpUri: https://learn.microsoft.com/powershell/module/scheduledtasks/register-scheduledtask?view=windowsserver2025-ps&wt.mc_id=ps-gethelp
Module Name: ScheduledTasks
ms.date: 2016-12-20T00:00:00.0000000Z
PlatyPS schema version: 2024-05-01T00:00:00.0000000Z
locale: en-us
document_id: 221cc21e-77e7-967e-821b-74e3d6549edd
document_version_independent_id: b9cfe0d7-e507-8868-2a39-ff694cc53afc
updated_at: 2025-05-14T22:44:00.0000000Z
original_content_git_url: https://github.com/MicrosoftDocs/windows-powershell-docs/blob/live/docset/winserver2025-ps/ScheduledTasks/Register-ScheduledTask.md
gitcommit:
0ef3f225d2/docset/winserver2025-ps/ScheduledTasks/Register-ScheduledTask.mdgit_commit_id: 0ef3f225d29e26d1cf3119f37dfff70bb6165746 default_moniker: windowsserver2025-ps site_name: Docs depot_name: TechNet.windows-powershell in_right_rail: h2h3 page_type: powershell page_kind: command toc_rel: ../windowsserver2025-ps/toc.json feedback_help_link_type: '' feedback_help_link_url: '' asset_id: module/scheduledtasks/register-scheduledtask moniker_range_name: ffb05b7b47577225af7c7b6a20151268 monikers: - windowsserver2025-ps item_type: Content source_path: docset/winserver2025-ps/ScheduledTasks/Register-ScheduledTask.md cmProducts:
- https://authoring-docs-microsoft.poolparty.biz/devrel/bcbcbad5-4208-4783-8035-8481272c98b8 spProducts:
- https://authoring-docs-microsoft.poolparty.biz/devrel/43b2e5aa-8a6d-4de2-a252-692232e5edc8 platformId: dc26f37b-95d1-1184-0c53-35087521caf6
Register-ScheduledTask
-
Module:
Registers a scheduled task definition on a local computer.
Syntax
User (Default)
Register-ScheduledTask
[[-Password] <String>]
[[-User] <String>]
[-TaskName] <String>
[[-TaskPath] <String>]
[-Action] <CimInstance[]>
[[-Description] <String>]
[[-Settings] <CimInstance>]
[[-Trigger] <CimInstance[]>]
[[-RunLevel] <RunLevelEnum>]
[-Force]
[-CimSession <CimSession[]>]
[-ThrottleLimit <Int32>]
[-AsJob]
[<CommonParameters>]
Xml
Register-ScheduledTask
[[-Password] <String>]
[[-User] <String>]
[-TaskName] <String>
[[-TaskPath] <String>]
[-Xml] <String>
[-Force]
[-CimSession <CimSession[]>]
[-ThrottleLimit <Int32>]
[-AsJob]
[<CommonParameters>]
Principal
Register-ScheduledTask
[-TaskName] <String>
[[-TaskPath] <String>]
[[-Principal] <CimInstance>]
[-Action] <CimInstance[]>
[[-Description] <String>]
[[-Settings] <CimInstance>]
[[-Trigger] <CimInstance[]>]
[-Force]
[-CimSession <CimSession[]>]
[-ThrottleLimit <Int32>]
[-AsJob]
[<CommonParameters>]
Object
Register-ScheduledTask
[-InputObject] <CimInstance>
[[-Password] <String>]
[[-User] <String>]
[[-TaskName] <String>]
[[-TaskPath] <String>]
[-Force]
[-CimSession <CimSession[]>]
[-ThrottleLimit <Int32>]
[-AsJob]
[<CommonParameters>]
Description
The Register-ScheduledTask cmdlet registers a scheduled task definition on a local computer.
You can register a task to run executable files (.exe and .com), batch files (.bat and .cmd), or any registered file type. However, this cmdlet does not check whether the file you intend it to run is compatible with your version, edition, or platform specialization of Windows.
Examples
Example 1: Register a scheduled task
PS C:\> $Time = New-ScheduledTaskTrigger -At 12:00 -Once
PS C:\> $User = "Contoso\Administrator"
PS C:\> $PS = New-ScheduledTaskAction -Execute "PowerShell.exe"
PS C:\> Register-ScheduledTask -TaskName "SoftwareScan" -Trigger $Time -User $User -Action $PS
In this example, the set of commands uses cmdlets and variables to define and register a scheduled task.
The first command uses the New-ScheduledTaskTrigger cmdlet to assign a time trigger to the $Time variable.
The second command assigns the $User variable the name of the user account in the context of which the task runs (Contoso\Administrator).
The third command assigns the $PS variable to PowerShell.exe. This variable is used to define a task action.
The fourth command registers a scheduled task that is named SoftwareScan in the root folder. The registered task uses the pre-created action and trigger values that are specified by the $Action and $User variables.
Parameters
-Action
Specifies an array of one or more work items for the task to run. If you specify multiple actions, the computer runs them in order. You can specify up to 32 actions.
Parameter properties
| Type: | CimInstance[] |
| --- | --- |
| Default value: | None |
| Supports wildcards: | False |
| DontShow: | False |
Parameter sets
User
| Position: | 2 |
| --- | --- |
| Mandatory: | True |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | False |
Principal
| Position: | 2 |
| --- | --- |
| Mandatory: | True |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | False |
-AsJob
Runs the cmdlet as a background job. Use this parameter to run commands that take a long time to complete.
Parameter properties
| Type: | SwitchParameter |
| --- | --- |
| Default value: | None |
| Supports wildcards: | False |
| DontShow: | False |
Parameter sets
(All)
| Position: | Named |
| --- | --- |
| Mandatory: | False |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | False |
-CimSession
Runs the cmdlet in a remote session or on a remote computer. Enter a computer name or a session object, such as the output of a New-CimSession or Get-CimSession cmdlet. The default is the current session on the local computer.
Parameter properties
| Type: | CimSession[] |
| --- | --- |
| Default value: | None |
| Supports wildcards: | False |
| DontShow: | False |
| Aliases: | Session |
Parameter sets
(All)
| Position: | Named |
| --- | --- |
| Mandatory: | False |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | False |
-Description
Briefly describes the task.
Parameter properties
| Type: | String |
| --- | --- |
| Default value: | None |
| Supports wildcards: | False |
| DontShow: | False |
Parameter sets
User
| Position: | 8 |
| --- | --- |
| Mandatory: | False |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | False |
Principal
| Position: | 8 |
| --- | --- |
| Mandatory: | False |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | False |
-Force
Instructs the cmdlet to perform the operation without prompting for confirmation.
Parameter properties
| Type: | SwitchParameter |
| --- | --- |
| Default value: | None |
| Supports wildcards: | False |
| DontShow: | False |
Parameter sets
(All)
| Position: | Named |
| --- | --- |
| Mandatory: | False |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | False |
-InputObject
Specifies the input object that is used in a pipeline command.
Parameter properties
| Type: | CimInstance |
| --- | --- |
| Default value: | None |
| Supports wildcards: | False |
| DontShow: | False |
Parameter sets
Object
| Position: | 2 |
| --- | --- |
| Mandatory: | True |
| Value from pipeline: | True |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | False |
-Password
Specifies a password for the user account in the context of which the task runs. The password is ignored for the well-known system accounts.
Well-known accounts are: NT AUTHORITY\SYSTEM, NT AUTHORITY\LOCALSERVICE, NT AUTHORITY\NETWORKSERVICE, and the well-known security identifiers (SIDs) for all three accounts.
Parameter properties
| Type: | String |
| --- | --- |
| Default value: | None |
| Supports wildcards: | False |
| DontShow: | False |
Parameter sets
User
| Position: | 4 |
| --- | --- |
| Mandatory: | False |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | False |
Xml
| Position: | 4 |
| --- | --- |
| Mandatory: | False |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | False |
Object
| Position: | 4 |
| --- | --- |
| Mandatory: | False |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | False |
-Principal
Specifies the security context in which a task is run.
Parameter properties
| Type: | CimInstance |
| --- | --- |
| Default value: | None |
| Supports wildcards: | False |
| DontShow: | False |
Parameter sets
Principal
| Position: | 5 |
| --- | --- |
| Mandatory: | False |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | False |
-RunLevel
Specifies the required privilege level to run tasks that are associated with the principal.
Parameter properties
| Type: | RunLevelEnum |
| --- | --- |
| Default value: | None |
| Accepted values: | Limited, Highest |
| Supports wildcards: | False |
| DontShow: | False |
Parameter sets
User
| Position: | 7 |
| --- | --- |
| Mandatory: | False |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | False |
-Settings
Specifies a configuration that the Task Scheduler service uses to determine how to run a task.
Parameter properties
| Type: | CimInstance |
| --- | --- |
| Default value: | None |
| Supports wildcards: | False |
| DontShow: | False |
Parameter sets
User
| Position: | 4 |
| --- | --- |
| Mandatory: | False |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | False |
Principal
| Position: | 4 |
| --- | --- |
| Mandatory: | False |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | False |
-TaskName
Specifies the name of a scheduled task.
Parameter properties
| Type: | String |
| --- | --- |
| Default value: | None |
| Supports wildcards: | False |
| DontShow: | False |
Parameter sets
User
| Position: | 0 |
| --- | --- |
| Mandatory: | True |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | False |
Xml
| Position: | 0 |
| --- | --- |
| Mandatory: | True |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | False |
Principal
| Position: | 0 |
| --- | --- |
| Mandatory: | True |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | False |
-TaskPath
Specifies an array of one or more paths for scheduled tasks in Task Scheduler namespace. You can use "*" for a wildcard character query. You can use **** for the root folder. To specify a full TaskPath you need to include the leading and trailing ***. If you do not specify a path, the cmdlet uses the root folder.
Parameter properties
| Type: | String |
| --- | --- |
| Default value: | None |
| Supports wildcards: | False |
| DontShow: | False |
Parameter sets
(All)
| Position: | 1 |
| --- | --- |
| Mandatory: | False |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | False |
-ThrottleLimit
Specifies the maximum number of concurrent operations tha …[truncated 4202 chars]
[FETCH #44] https://code.claude.com/docs/en/settings-reference
ASK: Extract exact definitions of: apiKeyHelper, env (settings env block), permissions.allow / deny / ask / defaultMode, permission rule syntax for Bash (prefix matching with ' *', wildcards), model, effortLevel, disableAllHooks, includeCoAuthoredBy, CLAUDE_CODE_MAX_OUTPUT_TOKENS, and settings file locations on Windows (%USERPROFILE%.claude\settings.json, project .claude\settings.json, settings.local. …[truncated 40 chars]
Claude Code Settings Reference - Extracted Definitions
API Key Helper
- Description: Generate the API credential with your own command
- Scope: Any file
- Topic: Authentication and providers
Environment Variables
- Description: Set environment variables for every session and its subprocesses
- Scope: Any file
- Topic: Memory and context
Permissions Settings
permissions.allow
- Description: Approve listed tool uses without a prompt
- Scope: Any file
- Topic: Permission settings
permissions.deny
- Description: Block listed tool uses, including reads of files that hold secrets
- Scope: Any file
- Topic: Permission settings
permissions.ask
- Description: Always prompt before listed tool uses
- Scope: Any file
- Topic: Permission settings
permissions.defaultMode
- Description: Set the permission mode new sessions start in
- Scope: Any file
- Topic: Permission settings
Model Configuration
- Description: Change the model Claude Code starts with
- Scope: Any file
- Topic: Model and responses
Effort Level
- Description: Set a default effort level for models without a saved level of their own
- Scope: Any file
- Topic: Model and responses
Disable All Hooks
- Description: Turn off hooks, a custom status line, and a custom
@file suggestion command at once - Scope: Any file
- Topic: Hooks and automation
Include Co-Authored By (Deprecated)
- Description: Deprecated; use
attributionto hide or change commit and PR attribution - Scope: Any file
- Topic: Git and attribution
Settings File Locations
Based on the documentation, settings file locations are platform-specific:
Windows
- User Settings:
%USERPROFILE%\.claude\settings.json - Project Settings:
.claude\settings.json(in project root) - Local Settings:
.claude\settings.local.json(in project root) - Global Config:
%USERPROFILE%\.claude.json
macOS/Linux
- User Settings:
~/.claude/settings.json - Project Settings:
.claude/settings.json - Local Settings:
.claude/settings.local.json - Global Config:
~/.claude.json
Scope Reference
- User:
~/.claude/settings.json(or Windows equivalent) - Project:
.claude/settings.json - Local:
.claude/settings.local.json - Managed: Deployed by your organization
- Global config:
~/.claude.json(or Windows equivalent)
Note on Permission Rule Syntax & CLAUDE_CODE_MAX_OUTPUT_TOKENS
The extracted content above does not include:
- Detailed permission rule syntax (including prefix matching with
' *'and wildcard specifics for Bash) - CLAUDE_CODE_MAX_OUTPUT_TOKENS definition
These would be found in referenced documentation pages like /docs/en/permissions#permission-rule-syntax which are not included in the provided web page content. To access these exact definitions, consult the complete documentation at https://code.claude.com/docs/llms.txt or the full permissions documentation page.
[CMD] $sp = "C:\Users\encep\AppData\Local\Temp\claude\D--workspace-DMF-Crawler\c00474d0-f118-4917-817d-1c16591aefc7\scratchpad"; $out = Join-Path $sp "smoke-json.txt"; $err = Join-Path $sp "smoke-json.err"; $p = Start-Process -FilePath "claude" -ArgumentList @('-p','"Reply with exactly the word OK and not
…[truncated 809 chars]
The user doesn't want to proceed with this tool use. The tool use was rejected (eg. if it was a file edit, the new_string was NOT written to the file). STOP what you are doing and wait for the user to tell you how to proceed.
Note: The user's next message may contain a correction or preference. Pay close attention — if they explain what went wrong or how they'd prefer you to work, consider saving that to memory for future sessions.