Practical notes: When Should an Agent Loop Stop? DeepSeek Harness and Pi Give
Operable walkthrough of Practical notes: When Should an Agent Loop Stop? DeepSeek Harness and Pi Give: contracts, checks, and drop-in code slots for teams shipping this pattern.
This article is published in English.
Sources: When Should an Agent Loop Stop? DeepSeek Harness and Pi Give Two Completely Different Answers
The following notes reconstruct a practical path around “When Should an Agent Loop Stop? DeepSeek Harness and Pi Give Two Completely Different Answers”. Emphasis stays on contracts, checks, and drop-in code placeholders rather than motivational framing. When working through the Overview stage, write down the contract first: required inputs, success signal, and what happens on partial failure. That checklist keeps later code changes honest. Record timings and token or query cost next to functional results. Cost visibility early prevents surprise bills when the path moves from demo to shared environments.
Opening: the question nobody asks until it breaks something
The Opening the question nobody stage works best when treated as a measurable surface. Capture one golden transcript, one failure case, and the rollback note before expanding scope. Keep configuration outside application code. Environment files, secret stores, and feature flags belong in one place operators can audit without reading the whole graph. Expose tools with narrow schemas and explicit side-effect labels. Hosts need to know which calls mutate state before they auto-approve.
504 Gateway Timeout
Part 1 — What “stopping” actually is (it’s not one thing)
The Part 1 What stopping stage works best when treated as a measurable surface. Capture one golden transcript, one failure case, and the rollback note before expanding scope. Document the happy path and the recovery path together. Retries, human gates, and dead-letter handling are part of the product, not later polish. Expose tools with narrow schemas and explicit side-effect labels. Hosts need to know which calls mutate state before they auto-approve.
Model Request
↓
Assistant Response
↓
Tool Calls
↓
Tool Results
↓
Model reviews results
↓
Turn End
↓
Agent Idle
↓
Follow-up / Goal / Scheduler
↓
Next Turn
Part 2 — Why this matters now, not later
The Part 2 Why this stage works best when treated as a measurable surface. Capture one golden transcript, one failure case, and the rollback note before expanding scope. Prefer small, testable units over sprawling scripts. When a step fails, the failure should point at a single responsibility rather than a tangled pipeline. Expose tools with narrow schemas and explicit side-effect labels. Hosts need to know which calls mutate state before they auto-approve. The Part 2 Why this stage works best when treated as a measurable surface. Capture one golden transcript, one failure case, and the rollback note before expanding scope. Record timings and token or query cost next to functional results. Cost visibility early prevents surprise bills when the path moves from demo to shared environments.
Part 3 — How it actually works: taking the machine apart
For the Part 3 How it stage, define the inputs, the owner of the step, and the exit criteria before changing code. Operators should be able to re-run the step from a known checkpoint without guessing hidden state. Keep configuration outside application code. Environment files, secret stores, and feature flags belong in one place operators can audit without reading the whole graph. Authenticate at the gateway and re-authorize at the data plane. A bearer token alone is not a tenancy boundary.
Assistant:
"I've created PR #1234."
model stopped ≠ turn stopped
3.2 Layer two: the tool batch finishes
For the 3 2 Layer two stage, define the inputs, the owner of the step, and the exit criteria before changing code. Operators should be able to re-run the step from a known checkpoint without guessing hidden state. Document the happy path and the recovery path together. Retries, human gates, and dead-letter handling are part of the product, not later polish. Authenticate at the gateway and re-authorize at the data plane. A bearer token alone is not a tenancy boundary.
# Illustrative example — conceptual pseudocode, not an official API
while has_more_tool_calls:
response = call_model()
tools = parse_tool_calls(response)
execute_tools(tools)
Model
↓
create_pr()
↓
200 OK
↓
PR #1234
Goal
└─ Goal Round
└─ Turn
├─ Step
│ ├─ Model Request
│ └─ Tool Calls
├─ Step
│ ├─ Model Request
│ └─ Tool Calls
└─ ...
3.3 So when does a turn actually end?
For the 3 3 So when stage, define the inputs, the owner of the step, and the exit criteria before changing code. Operators should be able to re-run the step from a known checkpoint without guessing hidden state. Prefer small, testable units over sprawling scripts. When a step fails, the failure should point at a single responsibility rather than a tangled pipeline. Authenticate at the gateway and re-authorize at the data plane. A bearer token alone is not a tenancy boundary. For the 3 3 So when stage, define the inputs, the owner of the step, and the exit criteria before changing code. Operators should be able to re-run the step from a known checkpoint without guessing hidden state. Record timings and token or query cost next to functional results. Cost visibility early prevents surprise bills when the path moves from demo to shared environments.
3.4 The boolean trap: shouldContinue()
When working through the 3 4 The boolean stage, write down the contract first: required inputs, success signal, and what happens on partial failure. That checklist keeps later code changes honest. Keep configuration outside application code. Environment files, secret stores, and feature flags belong in one place operators can audit without reading the whole graph. Log tool name, args hash, latency, and outcome for every call. Debugging agent loops without that trail wastes hours.
Plugin A → false
Plugin B → true
Plugin C → false
shouldContinue(): boolean
3.5 The cost of this design
When working through the 3 5 The cost stage, write down the contract first: required inputs, success signal, and what happens on partial failure. That checklist keeps later code changes honest. Document the happy path and the recovery path together. Retries, human gates, and dead-letter handling are part of the product, not later polish. Log tool name, args hash, latency, and outcome for every call. Debugging agent loops without that trail wastes hours.
Prompt → Search → Answer
3.6 Pi’s answer: keep the loop small, split “continue” into two APIs
When working through the 3 6 Pi s stage, write down the contract first: required inputs, success signal, and what happens on partial failure. That checklist keeps later code changes honest. Prefer small, testable units over sprawling scripts. When a step fails, the failure should point at a single responsibility rather than a tangled pipeline. Log tool name, args hash, latency, and outcome for every call. Debugging agent loops without that trail wastes hours. When working through the 3 6 Pi s stage, write down the contract first: required inputs, success signal, and what happens on partial failure. That checklist keeps later code changes honest. Record timings and token or query cost next to functional results. Cost visibility early prevents surprise bills when the path moves from demo to shared environments.
// Illustrative example — conceptual pseudocode, not an official API
while (true) {
while (hasMoreToolCalls || pendingMessages.length > 0) {
callModel();
executeTools();
}
const followUps = await getFollowUpMessages();
if (followUps.length > 0) {
pendingMessages = followUps;
continue;
}
break;
}
Inner Loop
↓
More tools? More steering?
↓
No
↓
Outer Loop
↓
Any follow-up?
↓
No
↓
Agent End
Steering = you are changing my direction right now
Follow-up = you were about to let me stop, but I'm giving you one more thing
3.7 Laying DSH and Pi side by side
The 3 7 Laying DSH stage works best when treated as a measurable surface. Capture one golden transcript, one failure case, and the rollback note before expanding scope. Keep configuration outside application code. Environment files, secret stores, and feature flags belong in one place operators can audit without reading the whole graph. Expose tools with narrow schemas and explicit side-effect labels. Hosts need to know which calls mutate state before they auto-approve.
DSH Pi
Goal Outer Loop
↓ │
Goal Round Follow-up Queue
↓ │
Turn ▼
↓ Inner Loop
Step │
↓ Steering + Tool Calls
Model ↔ Tools ↔ Inbox │
↓ ▼
Turn-Stopping turn_end
↓ │
Turn End ▼
agent_end
3.8 Pi’s quieter but very useful addition: shouldStopAfterTurn
The 3 8 Pi s stage works best when treated as a measurable surface. Capture one golden transcript, one failure case, and the rollback note before expanding scope. Document the happy path and the recovery path together. Retries, human gates, and dead-letter handling are part of the product, not later polish. Expose tools with narrow schemas and explicit side-effect labels. Hosts need to know which calls mutate state before they auto-approve.
shouldStopAfterTurn() ≠ killEverything()
Agent
↓
fix bug
↓
run tests
↓
tests pass
↓
turn_end
↓
shouldStopAfterTurn = true
↓
agent_end
3.9 DSH’s more state-machine-like posture
The 3 9 DSH s stage works best when treated as a measurable surface. Capture one golden transcript, one failure case, and the rollback note before expanding scope. Prefer small, testable units over sprawling scripts. When a step fails, the failure should point at a single responsibility rather than a tangled pipeline. Expose tools with narrow schemas and explicit side-effect labels. Hosts need to know which calls mutate state before they auto-approve. The 3 9 DSH s stage works best when treated as a measurable surface. Capture one golden transcript, one failure case, and the rollback note before expanding scope. Record timings and token or query cost next to functional results. Cost visibility early prevents surprise bills when the path moves from demo to shared environments.
3.10 Why “why it stopped” matters more than it sounds
For the 3 10 Why why stage, define the inputs, the owner of the step, and the exit criteria before changing code. Operators should be able to re-run the step from a known checkpoint without guessing hidden state. Keep configuration outside application code. Environment files, secret stores, and feature flags belong in one place operators can audit without reading the whole graph. Authenticate at the gateway and re-authorize at the data plane. A bearer token alone is not a tenancy boundary.
Agent stopped.
Agent stopped because:
- task completed?
- user cancelled?
- token limit hit?
- tool error?
- process crashed?
- blocked by policy?
- waiting on a human?
3.11 Pi deliberately doesn’t push all of this into core
For the 3 11 Pi deliberately stage, define the inputs, the owner of the step, and the exit criteria before changing code. Operators should be able to re-run the step from a known checkpoint without guessing hidden state. Document the happy path and the recovery path together. Retries, human gates, and dead-letter handling are part of the product, not later polish. Authenticate at the gateway and re-authorize at the data plane. A bearer token alone is not a tenancy boundary.
3.12 The price of that choice
For the 3 12 The price stage, define the inputs, the owner of the step, and the exit criteria before changing code. Operators should be able to re-run the step from a known checkpoint without guessing hidden state. Prefer small, testable units over sprawling scripts. When a step fails, the failure should point at a single responsibility rather than a tangled pipeline. Authenticate at the gateway and re-authorize at the data plane. A bearer token alone is not a tenancy boundary. For the 3 12 The price stage, define the inputs, the owner of the step, and the exit criteria before changing code. Operators should be able to re-run the step from a known checkpoint without guessing hidden state. Record timings and token or query cost next to functional results. Cost visibility early prevents surprise bills when the path moves from demo to shared environments.
3.13 Tools that get a vote: concludesTurn
When working through the 3 13 Tools that stage, write down the contract first: required inputs, success signal, and what happens on partial failure. That checklist keeps later code changes honest. Keep configuration outside application code. Environment files, secret stores, and feature flags belong in one place operators can audit without reading the whole graph. Log tool name, args hash, latency, and outcome for every call. Debugging agent loops without that trail wastes hours.
3.14 Even the AND/OR choice encodes a design philosophy
When working through the 3 14 Even the stage, write down the contract first: required inputs, success signal, and what happens on partial failure. That checklist keeps later code changes honest. Document the happy path and the recovery path together. Retries, human gates, and dead-letter handling are part of the product, not later polish. Log tool name, args hash, latency, and outcome for every call. Debugging agent loops without that trail wastes hours.
Tool A → concludesTurn = true
Tool B → false
Tool C → false
3.15 Concurrency adds yet another layer
When working through the 3 15 Concurrency adds stage, write down the contract first: required inputs, success signal, and what happens on partial failure. That checklist keeps later code changes honest. Prefer small, testable units over sprawling scripts. When a step fails, the failure should point at a single responsibility rather than a tangled pipeline. Log tool name, args hash, latency, and outcome for every call. Debugging agent loops without that trail wastes hours. When working through the 3 15 Concurrency adds stage, write down the contract first: required inputs, success signal, and what happens on partial failure. That checklist keeps later code changes honest. Record timings and token or query cost next to functional results. Cost visibility early prevents surprise bills when the path moves from demo to shared environments.
A = create PR
B = inspect dependency graph
C = run security scan
3.16 max-tokens: the textbook counterexample to "just retry"
The 3 16 max-tokens the stage works best when treated as a measurable surface. Capture one golden transcript, one failure case, and the rollback note before expanding scope. Keep configuration outside application code. Environment files, secret stores, and feature flags belong in one place operators can audit without reading the whole graph. Budget tokens per turn and per session. Agentic tools expand context aggressively; hard caps keep demos from becoming surprise invoices.
Model:
"I'm about to call deploy_production with
{ ... half-finished JSON ...
3.17 The read-only vs. side-effecting split
The 3 17 The read-only stage works best when treated as a measurable surface. Capture one golden transcript, one failure case, and the rollback note before expanding scope. Document the happy path and the recovery path together. Retries, human gates, and dead-letter handling are part of the product, not later polish. Expose tools with narrow schemas and explicit side-effect labels. Hosts need to know which calls mutate state before they auto-approve.
Part 4 — What most people get wrong
The Part 4 What most stage works best when treated as a measurable surface. Capture one golden transcript, one failure case, and the rollback note before expanding scope. Prefer small, testable units over sprawling scripts. When a step fails, the failure should point at a single responsibility rather than a tangled pipeline. Expose tools with narrow schemas and explicit side-effect labels. Hosts need to know which calls mutate state before they auto-approve. The Part 4 What most stage works best when treated as a measurable surface. Capture one golden transcript, one failure case, and the rollback note before expanding scope. Record timings and token or query cost next to functional results. Cost visibility early prevents surprise bills when the path moves from demo to shared environments.
DISCOVERED → MODIFIED → TESTING → PR_CREATED → CI_RUNNING →
WAITING_REVIEW → CHANGES_REQUESTED → MERGED → DEPLOYING → OBSERVING → VERIFIED
Part 5 — the judgment
For the Part 5 the judgment stage, define the inputs, the owner of the step, and the exit criteria before changing code. Operators should be able to re-run the step from a known checkpoint without guessing hidden state. Keep configuration outside application code. Environment files, secret stores, and feature flags belong in one place operators can audit without reading the whole graph. Authenticate at the gateway and re-authorize at the data plane. A bearer token alone is not a tenancy boundary.
Part 6 — What this actually changes in practice
For the Part 6 What this stage, define the inputs, the owner of the step, and the exit criteria before changing code. Operators should be able to re-run the step from a known checkpoint without guessing hidden state. Document the happy path and the recovery path together. Retries, human gates, and dead-letter handling are part of the product, not later polish. Authenticate at the gateway and re-authorize at the data plane. A bearer token alone is not a tenancy boundary.
Current side-effect state: UNKNOWN
Can it be resolved against external facts? YES
→ query the PR
→ query the branch
→ query the commit
→ query remote state
PR exists → continue the existing workflow
PR absent → retry creation
Goal:
all v1 imports removed
AND unit tests pass
AND integration tests pass
AND PR created
Conclusion: the sentence worth keeping
For the Conclusion the sentence worth stage, define the inputs, the owner of the step, and the exit criteria before changing code. Operators should be able to re-run the step from a known checkpoint without guessing hidden state. Prefer small, testable units over sprawling scripts. When a step fails, the failure should point at a single responsibility rather than a tangled pipeline. Authenticate at the gateway and re-authorize at the data plane. A bearer token alone is not a tenancy boundary. For the Conclusion the sentence worth stage, define the inputs, the owner of the step, and the exit criteria before changing code. Operators should be able to re-run the step from a known checkpoint without guessing hidden state. Record timings and token or query cost next to functional results. Cost visibility early prevents surprise bills when the path moves from demo to shared environments.
If you’d like to show your appreciation, you can support me through:
When working through the If you d like stage, write down the contract first: required inputs, success signal, and what happens on partial failure. That checklist keeps later code changes honest. Keep configuration outside application code. Environment files, secret stores, and feature flags belong in one place operators can audit without reading the whole graph. Log tool name, args hash, latency, and outcome for every call. Debugging agent loops without that trail wastes hours.
Operational checklist
For the Operational checklist stage, define the inputs, the owner of the step, and the exit criteria before changing code. Operators should be able to re-run the step from a known checkpoint without guessing hidden state.
Treat this stage as a contract between inputs and validated outputs. Name the artifacts, define success checks, and refuse silent partial completion.
Authenticate at the gateway and re-authorize at the data plane. A bearer token alone is not a tenancy boundary.
Checkpoint after expensive steps. Resume should not re-bill the same LLM call when an operator retries a later node.
Pin dependency versions and record the image digest that ran the demo. Reproducibility beats tribal knowledge.
Document the happy path and the recovery path together. Retries, human gates, and dead-letter handling are part of the product, not later polish.
Before promoting the stack, freeze versions, capture a golden transcript for the critical path, and confirm rollback steps. Shared environments need rate limits, tenancy checks, and a clear owner for secret rotation. Prefer boring reliability over clever one-off demos.
Batch note for a95f0d36f035: keep provider keys out of the repo, set a per-session token ceiling, and store transcripts next to the eval fixtures so later model swaps stay comparable.
For the hardening note 0 stage, define the inputs, the owner of the step, and the exit criteria before changing code. Operators should be able to re-run the step from a known checkpoint without guessing hidden state. Prefer small, testable units over sprawling scripts. When a step fails, the failure should point at a single responsibility rather than a tangled pipeline.
Hardening detail 0/816: measure wall time, error class, and token spend for this note, then decide whether to keep the change based on a fixed question set rather than anecdote.
When working through the hardening note 1 stage, write down the contract first: required inputs, success signal, and what happens on partial failure. That checklist keeps later code changes honest. Record timings and token or query cost next to functional results. Cost visibility early prevents surprise bills when the path moves from demo to shared environments.
Hardening detail 1/816: measure wall time, error class, and token spend for this note, then decide whether to keep the change based on a fixed question set rather than anecdote.
The hardening note 2 stage works best when treated as a measurable surface. Capture one golden transcript, one failure case, and the rollback note before expanding scope. Document the happy path and the recovery path together. Retries, human gates, and dead-letter handling are part of the product, not later polish.
Hardening detail 2/816: measure wall time, error class, and token spend for this note, then decide whether to keep the change based on a fixed question set rather than anecdote.
For the hardening note 3 stage, define the inputs, the owner of the step, and the exit criteria before changing code. Operators should be able to re-run the step from a known checkpoint without guessing hidden state. Treat this stage as a contract between inputs and validated outputs. Name the artifacts, define success checks, and refuse silent partial completion.
Hardening detail 3/816: measure wall time, error class, and token spend for this note, then decide whether to keep the change based on a fixed question set rather than anecdote.