Sub topic 3
How the agent loop works
This chapter explains what happens between the moment you send a task and the moment the agent says it is done. It assumes you can edit and run projects in VS Code, use Git for commits and diffs, run build and test commands in a terminal, and have used a chat-based AI assistant before. The previous chapters covered what agent mode is and how it differs from ask and edit modes. Here we look inside a single agent run.
The loop in one sentence
In agent mode, the model does not write one answer and stop. It repeats a cycle: decide what to do next, call a tool, read the result, and decide again. It keeps going until it judges the task finished, hits a limit, or waits for you.
The model never touches your files or terminal directly. It can only produce text, and some of that text is a structured request such as "call the tool read_file with this path". The editor extension runs the tool, then sends the result back to the model as new input. The extension is the hands. The model is the planner.
Stages of a single iteration
Each pass through the loop has the same stages.
- Plan. The model reads everything in its context and picks the next step. Early in a run this is often exploration, such as searching for the function you named. Later it is editing or checking.
- Act. The model emits a tool call. A tool call has a tool name and arguments, for example a file path and a range of lines.
- Gate. The extension checks whether the call needs your approval. Reading a file in the workspace usually does not. Running a terminal command usually does. Chapter 6 covers this in detail.
- Execute. The extension runs the tool and captures its output: file text, search matches, a diff, or the exit code and output of a command.
- Observe. The output is appended to the conversation. On the next pass the model sees it and can react to it.
The key property is that step 5 feeds step 1. The agent can find out that its edit broke a test and then fix it, because the failing test output is part of what it reads next.
What the model sees on each pass
The model has no memory between calls. On every pass, the extension sends the whole working context again. That context typically includes:
- A system prompt from the tool vendor describing the agent's role and the available tools.
- Your custom instructions files, if any.
- Your messages and any attachments, selections, or open files you added.
- Every earlier tool call and its result in this conversation.
- The model's own earlier messages.
Two consequences follow.
First, the context grows with every iteration. A long run that reads many large files and prints long test logs fills the model's context window, which is the maximum amount of text it can consider at once. Tools handle overflow differently. Some summarize older turns and some drop them. In either case the agent may lose details it saw earlier. Chapter 14 covers this failure mode.
Second, results from tools are as important as your prompt. A command that prints 5,000 lines of logs pushes useful information out of focus. Prefer commands with focused output, such as running one test file instead of the full suite.
A worked trace
Suppose you send the task prompt from the spine for this tutorial:
Add input validation to the createUser function in src/users.ts.
Reject empty names and malformed email addresses with a clear error.
Add unit tests for both cases next to the existing tests, then run `npm test` and fix any failures.
Do not change the public function signature.A plausible run looks like this. Exact tool names and wording differ between editors.
| Pass | Model decision | Tool call | Observation |
|---|---|---|---|
| 1 | Find the function | Search for `createUser` | Matches in `src/users.ts` and `src/users.test.ts` |
| 2 | Read the implementation | Read `src/users.ts` | The function has no checks |
| 3 | Read existing tests for style | Read `src/users.test.ts` | Tests use a `describe` block |
| 4 | Add validation | Edit `src/users.ts` | Diff applied, no errors reported |
| 5 | Add tests | Edit `src/users.test.ts` | Diff applied |
| 6 | Verify | Run `npm test` (needs approval) | Two tests fail |
| 7 | Diagnose | Read the failure output, edit the regex | Diff applied |
| 8 | Verify again | Run `npm test` | All tests pass |
| 9 | Finish | None | Final message summarizing changes |
Passes 6 to 8 are the part that distinguishes agent mode from edit mode. The prompt told the agent to run the tests and fix failures, so the loop closed on a real check. Without a verification step in the prompt, the agent would often stop after pass 5 and claim success based only on its own reading of the code.
How the loop ends
A run can end in several ways. Knowing which one occurred tells you what to do next.
| Ending | What you see | What to do |
|---|---|---|
| Model finishes | A final message with no tool call | Review the diff and check the claims |
| Waiting for approval | A confirmation prompt in the chat | Read the exact command or edit, then approve or deny |
| Iteration limit | A message asking whether to continue | Check progress. Continue only if it is converging |
| Context overflow | Warnings, or the agent repeating earlier work | Start a fresh session with a short summary |
| Tool error | Repeated failed calls | Fix the cause, such as a missing dependency |
| You stop it | Run cancelled | Inspect partial edits, then undo or continue |
Many tools cap the number of tool calls per request. In VS Code this is a setting that, when reached, asks whether to continue. Treat that prompt as a checkpoint, not a formality.
Failure patterns inside the loop
Because the loop feeds on its own output, errors can compound. Watch for these patterns.
- Thrashing. The agent makes an edit, a test fails, it reverts, the test fails differently, and so on. Each pass adds noise to the context. Stop it after two or three cycles and give it a hint, or diagnose the failure yourself.
- Confident but unverified. The final message says "all tests pass" but no test command appears in the tool calls. Check the tool call list, not the summary.
- Scope drift. While fixing one failing test, the agent edits unrelated files. Your constraint line in the prompt and a clean Git state make this easy to spot and revert.
- Wrong assumption early. If pass 2 misreads the code, every later pass builds on the error. Early passes matter most, so watch the first few tool calls.
- Stale context. If you edit a file by hand during a run, the agent may still hold the old text and overwrite your change. Avoid editing files the agent is working on.
Practical habits that follow from the loop
- Give the loop a way to check itself. Name the command that proves the work is done. A test command, a type check, or a linter all work.
- Keep observations small. Ask for targeted runs, and ask the agent to avoid printing large files.
- Commit first. A clean working tree turns the final diff into the exact record of what the run changed.
- Read the tool calls, not only the summary. The sequence of calls is the honest record of what happened.
- Split large tasks. Several short runs with review between them keep the context small and your control high.
Exercise
You ask the agent to "refactor the billing module and make sure it works." The run ends with a message saying all tests pass, but you see no terminal command in the list of tool calls. What went wrong, and how would you rewrite the prompt?
Show answer
The agent never ran a verification step, so the claim that tests pass came from its own reading of the code and was not observed from a tool result. Rewrite the prompt to name the check and the constraint, for example: "Refactor the billing module in src/billing/ without changing exported function signatures. Run npm test -- billing after your edits and fix any failures. Report the command output."
Exercise
A long agent run starts re-reading files it already read and contradicts a decision it made earlier. Which property of the loop explains this, and what is a sensible response?
Show answer
The context grows with every pass, and when it nears the context window limit the tool may summarize or drop older turns, so the model loses earlier details. Stop the run, review and commit or undo the current changes, and start a new session with a short summary of the goal, the decisions made, and the remaining work.