SuperAPI AI Directory

gemini-agent

Agents & models

View repository

Updated 10-15 17:24

About this skill

Gemini Agent

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

  1. Install Gemini CLI and complete authentication (the first run of gemini will guide you through login)
  2. It is recommended to run in the target project directory; Gemini will use the current working directory as the workspace root
  3. When cross-directory access is needed, use --include-directories to explicitly add

Invocation methods

New session (default)

gemini -p "你的任务描述" --output-format json --approval-mode auto_edit --model pro
  • -p, --prompt Force non-interactive mode; essential for automated invocation
  • --output-format json Make stdout a parseable single-object result
  • By default --approval-mode=default will confirm before write operations; change coding tasks to auto_editfor unsupervised scripts yolo
  • --model It 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 response as the final answer
  • session_id is 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 stream
  • stats.models Grouped by the actual model ID used;pro will internally derive flash -level subagent to share tool calls, so multiple models are often seen here
  • If error field 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 result event as the terminal state, and get the final output and aggregate metrics from it
  • message is only suitable for real-time display; do not treat intermediate fragments as the final answer
  • error is 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 latest is 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 notUsing gemini -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, --resume accepts latest, a session index number (see --list-sessionsbelow), or a full session ID
  • Provide only -r latest without -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-sessions to get the index number and session ID
  • --delete-session to delete by index number; before running, first --list-sessions to 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
  • -p must take a string argument; writing -p alone will report Not 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-interactive willfirst 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 prompt
  • auto_edit: automatically allow file edits, other sensitive actions still require confirmation, suitable for most coding tasks
  • yolo: automatically allow all actions; use only in fully trusted automation
  • plan: 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 as gemini-2.5-pro / gemini-3-pro-preview / gemini-3.1-pro-preview ; in automation,do not rely on a specific model ID
  • pro: the mastermind for complex reasoning / multi-file coding; the CLI will also internally dispatch flash -level subagents to share tool calls (instats.models.*.roles you can see the two roles main / subagent )
  • flash: fast and balanced
  • flash-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 0 and there is no error field in the json → success
  • Non- 0 exit code → handle by category according to the table above (especially 42 means your own prompt / flag combination has a problem,53 means 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

  1. First gemini -p "..." --output-format json ... to get the result; if you need to follow up later, record the session ID or index
  2. For follow-ups use gemini -p "..." -r <session-id>, or in the same directory use -p "..." -r latest
  3. Create a new session for each different task; multiple sessions do not interfere with each other
  4. To locate an existing session, first gemini --list-sessions to 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

  1. For automated calls, use -p + --output-format jsonby default: get a stable, parseable single-object result; only switch to stream-json
  2. Always pass --modelexplicitly: the default auto will drift with the preview flag, so specify pro / flash / flash-lite
  3. Always pass --approval-modeexplicitly: the default default will hang on interactive confirmation; scripts should at least use auto_edit, and read-only tasks should use plan
  4. Don't use --yolo this old flag: the equivalent is --approval-mode=yolo, the latter has clearer semantics
  5. Don't use --allowed-tools: officially deprecated, switch to Policy Engine configuration
  6. Always run in the target project directory: first cd /path/to/project, if you need to cross directories then use --include-directories
  7. Default for coding tasks is auto_edit, default for review tasks is plan: write actions should match the risk surface as much as possible, rather than one-size-fits-all yolo
  8. Keep the conversation continuous: when following up, use -p "..." -r latest or -p "..." -r <session-id>; don't start a new session every turn
  9. -r latest is good for "continue the previous task"; for scripts crossing directories or running for a long time, binding a session ID is more stable
  10. When reporting results to the user, prefer the response field:--output-format json , the final answer is in response;stream-json , under type == "result" the terminal state is the last message fragment as the terminal state, don't treat intermediate
  11. Judge success or failure by exit code, not just stdout:0 success / 1 general error or API failure / 42 input error (prompt or flag has a problem) / 53 exceeded turn limit;error events are non-fatal warnings, don't mix them with exit codes
  12. When stacking high-risk actions with --sandbox:yolo to allow full permissions, at least configure a sandbox as a fallback
  13. --worktree is an experimental feature: you need to first enable it in settings experimental.worktrees: true; if you're not sure whether it's enabled, use a regular git worktree + cd for more reliability
  14. -p mode, do not rely on interactive slash commands:/skills reload such as these only take effect in the REPL; for automation, just describe the task in natural language
  15. 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) or cat ctx.md | gemini -p "指令" --output-format json --model pro(stdin as context,-p provides the instructions).Do not write bare -p, it will report Not enough arguments following: p
  16. Do not pass prompts to automation via positional arguments:gemini "..." or gemini -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:

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.