# Loops and Autonomous Runs in Gemini CLI
Some coding work is just the same step on repeat until a condition is met: fix the code, run the tests, read the failure, fix again. Gemini CLI can run that whole cycle for you in an agentic loop, editing files and executing commands until the task is genuinely done or a guardrail stops it. This lesson is about running that loop deliberately, unattended, and safely.
When you give Gemini CLI a task, it does not answer once and quit. It plans, calls tools (read file, write file, run shell command), observes the result, and decides the next action. That observe-then-act cycle repeats until the model believes the goal is met.
This is the ReAct pattern (reason + act) wired into a real shell. The important shift for you: you are no longer promptingpromptingPrompt engineering is the practice of designing and refining text inputs to guide large language models toward accurate, relevant, and reliable outputs.Voir la définition complète → for text. You are handing over a goal and a set of tools, then letting the agent iterate against real feedback from your machine.
A single request is right when the output is the answer: "explain this function," "write a regex." A loop is right when success is defined by an external check the agent cannot fake:
The distinction is whether there is a verifiable stop condition. If there is, a loop beats a chat, because the agent grades its own work against reality.
Interactive mode is the REPL you already know. For automation you want non-interactive mode: one command, no back-and-forth, exit when done. Use the -p (prompt) flag.
gemini -p "Run the test suite with 'npm test'. If anything fails, \
read the output, fix the code, and re-run until all tests pass. \
Do not modify test files." --model gemini-2.5-flashThe agent now owns the full loop. It runs npm test, parses failures, edits source, and re-runs, cycling until green or until a guardrail trips.
Two flags matter most here:
--model picks the tier. ReachReachThe number of unique people exposed to your message in a given period. Unlike impressions, reach counts each person once, no matter how often they see it.Voir la définition complète → for Flash on tight, well-scoped loops (fast, cheap iteration). Move to Pro when the reasoning is genuinely hard: tangled failures, architecture decisions, ambiguous specs.--yolo auto-approves tool calls so the loop never pauses for confirmation. Powerful and dangerous. More on containing it below.Because it is a plain command, non-interactive mode drops straight into CI, cron, or a Git hook. That is what "autonomous" means in practice: no human in the REPL.
There is no built-in Gemini CLI scheduler. You wire it into the tools you already run. That is a feature, not a gap: the CLI stays a composable Unix citizen.
A nightly dependency-and-test sweep via cron:
# 2:00 AM daily: attempt upgrades, keep tests green, open a PR
0 2 * * * cd /srv/app && gemini -p "$(cat prompts/nightly-deps.txt)" \
--yolo --model gemini-2.5-flash >> logs/nightly.log 2>&1Or a GitHub Actions job triggered on a schedule or on issue labels, letting Gemini CLI triage and draft a fix branch. The pattern is identical: an external trigger fires a non-interactive run, and the run does the looping.
For the official flag reference and configuration, see the Gemini CLI documentation.
Here is a clean, contained autonomous run you can adapt. It caps the work, forbids risky moves, and produces a reviewable result instead of silently pushing to main.
#!/usr/bin/env bash
set -euo pipefail
BRANCH="auto/fix-build-$(date +%Y%m%d-%H%M)"
git switch -c "$BRANCH"
gemini --yolo --model gemini-2.5-flash -p '
Goal: make the build and tests pass.
Steps:
1. Run "npm run build" and "npm test".
2. If either fails, read the error, make the smallest fix, re-run.
3. Repeat until both succeed.
Rules:
- Never edit files under /tests or /node_modules.
- Never touch package.json versions.
- If unresolved after 8 attempts, stop and summarize what remains.
'
# Human review gate: agent branched, we decide the merge.
git push -u origin "$BRANCH"
echo "Review the PR before merging: $BRANCH"Read what makes this safe rather than reckless:
build and test, not by the model's opinion.That last point is the whole philosophy. Autonomy is for the labor. The merge is still yours.
An agentic loop terminates for one of four reasons. Design for all of them.
1. Success. The verifiable condition is met (tests green, files processed). This is the happy path.
2. Attempt or turn limit. You told it to stop after N tries. Always set this. Loops without a ceiling are how you discover a runaway at 3 AM.
3. Cost or token cap. The run hits a budget you set (next section).
4. Hard error the agent cannot recover from. Missing credentials, a command that does not exist, a permission wall.
The dangerous case is none of the above: the agent thinks it is making progress but is looping through the same broken fix. That is why "smallest fix, re-run" plus an attempt cap beats an open-ended "keep going." Bound every dimension: attempts, time, and money.
An unattended loop that calls a model on every turn can quietly rack up spend. Three layers of defense, from cheapest to firmest:
Pick the model to match the job. Flash handles most iterate-until-green loops at a fraction of Pro's cost. Do not send a linter-fix loop to Pro.
Bound the loop in the prompt. Fewer attempts means fewer turns means fewer tokenstokensA token is the basic unit of text that language models process, often a word fragment, whole word, or punctuation mark rather than a single character.Voir la définition complète →. A tight, specific goal converges faster than a vague one.
Enforce the ceiling at the account level. When you run through the paid Gemini API or Vertex AI, set budgets and alerts in the platform, not just in your prompt. In Google Cloud, budgets and alerts on Vertex AI will notify you (or cut off spend) regardless of what the agent decides. This is your real backstop: prompt-level limits can be reasoned around by a confused agent, but a billing cap cannot.
A practical rule: never run --yolo on a paid key without a hard budget alert configured first. The prompt cap protects you from logic errors. The billing cap protects you from everything else.
Vérification des acquis
1. According to the lesson, what fundamentally distinguishes a task suited for an agentic loop from one suited for a single request?
2. The lesson describes Gemini CLI's default behavior as following the ReAct pattern. What does this pattern fundamentally involve?
3. Why does the lesson frame working with a loop as a conceptual shift away from ordinary prompting?
4. Select ALL correct answers. Which tasks are good candidates for an agentic loop according to the lesson's reasoning?
Sélectionnez toutes les réponses correctes.
5. Select ALL correct answers about non-interactive mode in Gemini CLI as described in the lesson.
Sélectionnez toutes les réponses correctes.
The scarier an autonomous run's powers, the more it needs a gate between "agent finished" and "change is live." A review gate is any checkpoint where a human or an automated check must approve before the work propagates.
Layer these from least to most trusting:
The default. The CLI pauses before each write or shell command and asks. Great for exploration, useless for unattended runs because nobody is there to say yes.
Before you reachreachThe number of unique people exposed to your message in a given period. Unlike impressions, reach counts each person once, no matter how often they see it.Voir la définition complète → for --yolo, contain the blast radius. Run the agent with sandboxing enabled so tool calls execute inside an isolated container, not directly on your machine. Even a confused loop cannot reachreachThe number of unique people exposed to your message in a given period. Unlike impressions, reach counts each person once, no matter how often they see it.Voir la définition complète → files or networks outside the box. Enable it and confine the working directory:
gemini --sandbox --yolo -p "$(cat prompts/refactor.txt)"Combine sandboxing with a scratch git checkout and the agent literally cannot harm anything you care about.
As in the worked example: autonomous runs write to a feature branch and open a pull request. Your existing CI (tests, security scans) runs on the PR, and a human approves the merge. This is the sweet spot for most teams: full autonomy inside the loop, full control at the boundary.
Do not trust the agent's "I'm done." Let your pipelinepipelineAll active sales opportunities across the stages of the sales process, together with their combined potential value and probability of closing.Voir la définition complète → decide. The agent's job is to produce a branch that passes CI. If CI fails, the PR does not merge, full stop. This turns your existing test and lint infrastructure into the arbiter of autonomous work, which is exactly what it is good at.
The other classic loop is not "until a condition," it is "for every item." Same mechanics, different shape.
gemini --yolo --model gemini-2.5-flash -p '
For every *.py file under /src:
- Add type hints to all public functions.
- Run "mypy" on the file after editing.
- If mypy errors, fix and re-check that file before moving on.
Skip files that already pass mypy cleanly. Report a table of files
changed and files skipped when finished.
'Notice the per-item verification (mypy after each edit). That keeps the batch honest: the agent proves each file before advancing, instead of editing all 40 and hoping. When a batch is large and independent, this is dramatically better than 40 separate chat sessions, because the agent carries context and its own quality checks forward.
For structured, repeatable pipelines beyond ad-hoc CLI runs (multiple specialized agents, richer orchestration, evaluation), graduate to the Agent Development Kit (ADK). The CLI is the fast path; ADK is where production loops with proper testing and deployment live.
Autonomy is not free, so do not reachreachThe number of unique people exposed to your message in a given period. Unlike impressions, reach counts each person once, no matter how often they see it.Voir la définition complète → for it reflexively:
The loop earns its keep exactly when the check is cheap and objective and the labor is tedious. That is most of the grind in a codebase, which is why this matters.
--sandbox, and let autonomous work land on a branch and PR so your existing CI is the objective judge and a human owns the merge.