Delegate tasks to an independent Gemini session via Gemini CLI.
The default entry point of Gemini CLI is gemini(interactive REPL). Automated invocation goes through headless mode, which is triggered in two cases:
- Running in non-TTY environment (e.g. CI, piped stdin,
run_in_background) - Explicitly passing
-p/--prompt
Under headless, Gemini does not enter interactive prompts and prints the final result to stdout. To get parseable output, additionally combine --output-format json or stream-json。
Prerequisites
- Install Gemini CLI and complete authentication (the first run of
geminiwill guide you through login) - It is recommended to run in the target project directory; Gemini will use the current working directory as the workspace root
- When cross-directory access is needed, use
--include-directoriesto explicitly add
Invocation methods
New session (default)
gemini -p "你的任务描述" --output-format json --approval-mode auto_edit --model pro
-p, --promptForce non-interactive mode; essential for automated invocation--output-format jsonMake stdout a parseable single-object result- By default
--approval-mode=defaultwill confirm before write operations; change coding tasks toauto_editfor unsupervised scriptsyolo --modelIt is recommended to pass explicitly:auto(default) /pro/flash/flash-lite
--output-format json return schema(official headless reference + measured):
{
"session_id": "ca7b5fa6-...",
"response": "模型的最终回答文本",
"stats": {
"models": { "<model-id>": { "api": {"...": "..."}, "tokens": {"...": "..."}, "roles": {"main": {"...": "..."}, "subagent": {"...": "..."}} } },
"tools": { "totalCalls": 0, "totalSuccess": 0, "totalFail": 0, "byName": {"...": "..."} },
"files": { "totalLinesAdded": 0, "totalLinesRemoved": 0 }
},
"error": { "...": "可选;请求失败时才有" }
}
- In automation, take
responseas the final answer session_idis at the top level, so when you need to continue, directly save this value and feed it to-r, without having to extract it yourself from the event streamstats.modelsGrouped by the actual model ID used;prowill internally deriveflash-levelsubagentto share tool calls, so multiple models are often seen here- If
errorfield appears, treat it as a failure together with a non-zero exit code
Event stream output (stream-json)
gemini -p "你的任务描述" --output-format stream-json --model pro
stream-json outputs newline-delimited JSON (JSONL), one event per line. Officially defined event types:
type |
Meaning |
|---|---|
init |
Session metadata, including session ID and the model used |
message |
User / assistant message fragments |
tool_use |
Tool call requests and parameters |
tool_result |
Tool execution results |
error |
Non-fatal warnings or system errors |
result |
Final result event, aggregating stats and token usage for each model |
- Automation scriptsUse
resultevent as the terminal state, and get the final output and aggregate metrics from it messageis only suitable for real-time display; do not treat intermediate fragments as the final answererroris a non-fatal warning; actual failures are determined by the exit code- Append more when you need to debug more internal details
--debug
Continue a specified session
gemini -p "后续提问" -r "<session-id>" --output-format json --model flash
gemini -p "后续提问" --resume 5 --output-format json --model flash
- When a script needs to deterministically bind to a certain session, save and reuse the session ID or index number, which is more stable than
latestis more stable - Sessions for different tasks in the current directory do not interfere with each other
Continue the most recent session (shortcut)
gemini -p "后续提问" -r latest --output-format json --model flash
- For automated invocation, put the prompt in
-p;do notUsinggemini -r latest "prompt"this pure positional-argument form—in a TTY environment, positional arguments default to interactive mode (gemini --help:query ... Runs in interactive mode by default; use -p/--prompt for non-interactive.), and the script will hang waiting for input -r, --resumeacceptslatest, a session index number (see--list-sessionsbelow), or a full session ID- Provide only
-r latestwithout-pto enter interactive mode for the most recent session
List / delete local sessions
gemini --list-sessions
gemini --delete-session 3
- When you need to select a historical session in a script, use
--list-sessionsto get the index number and session ID --delete-sessionto delete by index number; before running, first--list-sessionsto confirm the match and avoid accidental deletion
Piped input / stdin
Two ways to write it; choose one:
# A. stdin 当上下文,-p 给明确指令(追加到 stdin 内容之后)
cat logs.txt | gemini -p "Explain the failure in these logs" --output-format json --model flash
# B. stdin 就是 prompt 本体,不传 -p;non-TTY 管道会自动进入 headless
cat ./prompt.md | gemini --output-format json --model pro
-pmust take a string argument; writing-palone will reportNot enough arguments following: p, and the parser will swallow the next flag as the prompt value- When you want the prompt to be driven entirely by stdin,do not pass
-p, and go directly with pattern B. The pipe itself is non-TTY, so the CLI automatically enters headless mode - Pattern A is suitable for combinations where "context goes through stdin and instructions go through
-p"; pattern B is suitable for scenarios where the complete prompt has already been assembled into stdin
Interactive appends one sentence (-i)
gemini -i "先帮我看下这个项目的结构"
-i, --prompt-interactivewillfirst execute the prompt once, and thenstay in the interactive REPL- Suitable for scenarios where you "ask one question and then continue the manual conversation"; do not use it in scripts or CI
gemini CLI parameters
Output and results
| Flag | Description |
|---|---|
-p, --prompt TEXT |
Non-interactive mode;json / stream-json output all depend on it |
-i, --prompt-interactive TEXT |
After executing the prompt once, continue into the interactive REPL |
-o, --output-format FORMAT |
text(default) / json / stream-json |
-d, --debug |
Turn on debug mode; outputs more detailed logs to stderr |
Session management
| Flag | Description |
|---|---|
-r, --resume TARGET |
Resume session:latest / index number (e.g. 5) / full session ID |
--list-sessions |
List the sessions in the current project that can be resumed and exit |
--delete-session INDEX |
Delete a session by index number |
Permissions and tool boundaries
| Flag | Description |
|---|---|
--approval-mode MODE |
default / auto_edit / yolo / plan |
-y, --yolo |
Deprecated; equivalent to --approval-mode=yolo |
-s, --sandbox |
Execute in a sandbox environment, adding an extra layer of isolation |
--allowed-mcp-server-names LIST |
Which MCP servers are allowed (use commas or repeat the flag for multiple values) |
--policy FILES |
Policy Engine policy file/directory (can be passed multiple times) to refine the tool allowlist |
--admin-policy FILES |
Administrator-level policy, with higher priority |
--allowed-tools LIST |
Deprecated; use instead --policy / Policy Engine |
--approval-mode tiers:
default: require a second confirmation before write operations, suitable for interaction;Do not use in scripts, otherwise it will get stuck at the confirmation promptauto_edit: automatically allow file edits, other sensitive actions still require confirmation, suitable for most coding tasksyolo: automatically allow all actions; use only in fully trusted automationplan: read-only planning mode, does not execute write actions, best for code review / diagnosis / recon
Model and context
| Flag | Description |
|---|---|
-m, --model MODEL |
auto(default) / pro / flash / flash-lite, or pass the full model name directly |
--include-directories DIRS |
Additional directories added to the workspace (comma-separated or repeated) |
--screen-reader |
Screen reader accessibility mode |
Model alias notes:
auto(default): resolves according to the preview switch and CLI version; the actual ID may be a preview version such asgemini-2.5-pro/gemini-3-pro-preview/gemini-3.1-pro-preview; in automation,do not rely on a specific model IDpro: the mastermind for complex reasoning / multi-file coding; the CLI will also internally dispatchflash-level subagents to share tool calls (instats.models.*.rolesyou can see the two rolesmain/subagent)flash: fast and balancedflash-lite: fastest, most lightweight- These aliases'specific model IDs will drift with CLI versions; just recognize the alias, do not put literals like
gemini-2.5-*into script assertions
Runtime environment
| Flag | Description |
|---|---|
-w, --worktree [NAME] |
Start in an independent git worktree;experimental feature, requires settings to enable experimental.worktrees: true |
-e, --extensions NAMES |
Load only the specified Gemini extensions |
-l, --list-extensions |
List all extensions and exit |
--acp |
Start in ACP (Agent Code Pilot) mode |
--experimental-acp |
Deprecated; use --acp instead |
Exit codes
In headless mode, Gemini returns standard exit codes, and scripts can directly use them to determine success or failure:
| Exit code | Meaning |
|---|---|
0 |
Success |
1 |
General error or API failure |
42 |
Input error (invalid prompt or parameter) |
53 |
Exceeded turn limit |
It is recommended that scripts check both signals:
- Exit code is
0and there is noerrorfield in the json → success - Non-
0exit code → handle by category according to the table above (especially42means your own prompt / flag combination has a problem,53means the task ran too deep and needs to be broken down or retried)
Subcommands
In addition to the main command, Gemini CLI also has several management subcommands:
| Subcommand | Description |
|---|---|
gemini update |
Upgrade to the latest version |
gemini extensions <...> |
Manage extensions:install / uninstall / list / enable / disable / link / update |
gemini mcp <...> |
Manage MCP servers:add / remove / list, supports stdio and http |
gemini skills <...> |
Manage agent skills:install / link / enable / disable / list |
gemini hooks <...> |
Manage Gemini CLI hooks |
These subcommands are generallynot used in the delegation flow, and belong to environment configuration. When encountering a missing extension or MCP server, remind the user to install it first with the corresponding subcommand.
Multi-turn conversation
- First
gemini -p "..." --output-format json ...to get the result; if you need to follow up later, record the session ID or index - For follow-ups use
gemini -p "..." -r <session-id>, or in the same directory use-p "..." -r latest - Create a new session for each different task; multiple sessions do not interfere with each other
- To locate an existing session, first
gemini --list-sessionsto check the index and ID
Model and approval-mode selection
Explicitly specify --modelaccording to the risk surface --approval-mode:
| Task complexity | model | Applicable scenarios |
|---|---|---|
| High | pro |
Architecture design, complex refactoring, multi-file coding |
| Medium | flash |
Single-file feature implementation, bug fixes, general analysis |
| Low | flash-lite |
Simple Q&A, code explanation, quick follow-up questions |
| Risk surface | approval-mode | Use cases |
|---|---|---|
| High (non-rollbackable / multi-step write actions) | default interaction |
Don't use in scripts, it will hang on confirmation |
| Medium (standard coding tasks) | auto_edit |
File edits allowed, other sensitive actions still require confirmation |
| Low (sandbox / fully controlled) | yolo |
Allow everything, only use in isolated environments or fully trusted tasks |
| Read-only | plan |
Code review, diagnosis, recon, test gap checks |
Recommended parameter combinations
| Scenario | model | approval-mode | Other flags |
|---|---|---|---|
| Complex coding | pro |
auto_edit |
--output-format json |
| General coding | flash |
auto_edit |
--output-format json |
| Read-only Q&A / analysis | flash |
plan |
--output-format json |
| Code review | flash |
plan |
--output-format json |
| Challenge-style review | pro |
plan |
--output-format json |
| Quick Q&A | flash-lite |
default |
--output-format json |
| Toolchain consuming event stream | flash or pro |
Depends on the task | --output-format stream-json |
| Isolated execution | pro |
auto_edit |
--worktree feature-x(experimental feature) |
| Looser in sandbox | flash or pro |
yolo |
--sandbox |
Usage rules
- For automated calls, use
-p+--output-format jsonby default: get a stable, parseable single-object result; only switch tostream-json - Always pass
--modelexplicitly: the defaultautowill drift with the preview flag, so specifypro/flash/flash-lite - Always pass
--approval-modeexplicitly: the defaultdefaultwill hang on interactive confirmation; scripts should at least useauto_edit, and read-only tasks should useplan - Don't use
--yolothis old flag: the equivalent is--approval-mode=yolo, the latter has clearer semantics - Don't use
--allowed-tools: officially deprecated, switch to Policy Engine configuration - Always run in the target project directory: first
cd /path/to/project, if you need to cross directories then use--include-directories - Default for coding tasks is
auto_edit, default for review tasks isplan: write actions should match the risk surface as much as possible, rather than one-size-fits-allyolo - Keep the conversation continuous: when following up, use
-p "..." -r latestor-p "..." -r <session-id>; don't start a new session every turn -r latestis good for "continue the previous task"; for scripts crossing directories or running for a long time, binding a session ID is more stable- When reporting results to the user, prefer the
responsefield:--output-format json, the final answer is inresponse;stream-json, undertype == "result"the terminal state is the lastmessagefragment as the terminal state, don't treat intermediate - Judge success or failure by exit code, not just stdout:
0success /1general error or API failure /42input error (prompt or flag has a problem) /53exceeded turn limit;errorevents are non-fatal warnings, don't mix them with exit codes - When stacking high-risk actions with
--sandbox:yoloto allow full permissions, at least configure a sandbox as a fallback --worktreeis an experimental feature: you need to first enable it in settingsexperimental.worktrees: true; if you're not sure whether it's enabled, use a regular git worktree +cdfor more reliability-pmode, do not rely on interactive slash commands:/skills reloadsuch as these only take effect in the REPL; for automation, just describe the task in natural language- There are two correct ways to pass a long prompt via stdin:
cat prompt.md | gemini --output-format json --model pro(pure stdin-driven, do not pass-p) orcat ctx.md | gemini -p "指令" --output-format json --model pro(stdin as context,-pprovides the instructions).Do not write bare-p, it will reportNot enough arguments following: p - Do not pass prompts to automation via positional arguments:
gemini "..."orgemini -r latest "..."default to interactive mode under a TTY; scripts should either use-p, or rely on a non-TTY pipe to trigger headless
Prompt References
Load the corresponding reference on demand based on the task type; do not stuff all default prompts into the main context at once:
- Coding / diagnosis / planning / narrow fixes: read references/task-prompt-recipes.md
- Code review / adversarial review / test gap checks: read references/review-prompt-recipes.md
- Delegated handoff / independent worker / continuing the same session: read references/delegation-prompt-recipes.md
These references provide default prompt templates that can be reused directly or lightly modified; prefer to copy the closest template, then delete the blocks you don't need.
Examples
Coding task
cd /path/to/project && gemini -p \
"Implement a REST API for TODO items with CRUD endpoints. Use Express.js." \
--output-format json \
--approval-mode auto_edit \
--model pro
Suitable for delegating an entire implementation in one go; the result is returned as a JSON object via stdout.
Continue the most recent session
cd /path/to/project && gemini -p \
"Continue from the current state. Add unit tests for the new endpoints and report only the final outcome." \
-r latest \
--output-format json \
--approval-mode auto_edit \
--model flash
Suitable for scenarios like "continue the task from just now" where you don't want to manually save the session ID.
Continue a specified session
# 先列出现有会话拿到索引 / ID
gemini --list-sessions
# 再按 ID 续接
cd /path/to/project && gemini -p \
"Pick up where we left off and finish the remaining test coverage." \
-r "019d32fc-..." \
--output-format json \
--approval-mode auto_edit \
--model flash
Suitable when a script needs to explicitly bind to a certain session, or to avoid latest ambiguity when multiple sessions coexist.
Code review
cd /path/to/project && gemini -p \
"Review git diff HEAD~1. Focus on correctness, regression risk, and missing tests. Findings first." \
--output-format json \
--approval-mode plan \
--model flash
plan mode, Gemini will not perform write actions, suitable for PR review / diagnosis / recon.
Event stream output to an upper-layer tool
cd /path/to/project && gemini -p \
"Review the current diff and stream progress plus a final verdict." \
--output-format stream-json \
--approval-mode plan \
--model flash
Suitable for an upper-layer agent or script to consume intermediate events as JSONL, with the last result event as the final answer.
Piping in a long prompt
# 1. 把复杂 prompt 写进文件
cat > /tmp/task-prompt.md <<'PROMPT_EOF'
请在当前仓库完成以下任务:
1. 先阅读 README 和 tests
2. 只修改与 issue 直接相关的文件
3. 先补测试,再改实现,最后运行验证
PROMPT_EOF
# 2. 从 stdin 喂给 Gemini;不传 -p,让 non-TTY 管道自动进入 headless
cat /tmp/task-prompt.md | gemini \
--output-format json \
--approval-mode auto_edit \
--model pro
Suitable for multi-paragraph Markdown constraints, script-assembled prompts, or any task description that already exceeds one screen. Notedo not write bare -p——-p must be followed by a string; if you want stdin to be the prompt entirely, just omit -p。
Piping in logs
cat logs.txt | gemini -p \
"Explain the failure in these logs. Return root cause, evidence, and the smallest safe next step." \
--output-format json \
--approval-mode plan \
--model flash
-p prompt text will be appended to the end of stdin, suitable for the combination of "context via stdin, instructions via -p".
Isolated worktree execution (experimental feature)
cd /path/to/project && gemini -p \
"Implement the fix in an isolated worktree, run the most relevant tests, and summarize the final result." \
--output-format json \
--approval-mode auto_edit \
--model pro \
--worktree fix-login-timeout
First confirm that in settings experimental.worktrees: true is enabled; otherwise this flag will report an error.
Relaxing permissions in the sandbox
cd /path/to/project && gemini -p \
"Apply and verify the upgrade plan end-to-end." \
--output-format json \
--approval-mode yolo \
--sandbox \
--model pro
yolo when granting full permissions, at least configure --sandbox as a fallback, to prevent Gemini from performing irreversible write actions to the host environment.