Skip to content

Add runaway-loop guard to the agent loop (#97) - #106

Merged
ananmouaz merged 1 commit into
mainfrom
feat/agent-loop-guard-97
Jul 1, 2026
Merged

ananmouaz merged 1 commit into
mainfrom
feat/agent-loop-guard-97

Conversation

@ananmouaz

Copy link
Copy Markdown
Owner

Closes #97.

What

An opt-in agent guardrail on UseChatController: maxIdenticalToolCalls (default 0 = off) halts the agent loop with a typed AgentLoopException when the model keeps requesting the same tool call — identical toolName and JSON-encoded args — after it has already run that many times in a turn. Instead of looping up to maxSteps and burning tokens on a runaway self-call, the turn ends with error set to AgentLoopException.

Why this shape

The controller already had two of the three guardrails from #97:

  • Token ceiling → existing tokenBudget.
  • Tool-error containment → existing arg-validation path feeds a typed error ToolResultPart back to the model.

The missing piece was runaway-loop detection, added here. It's opt-in (like tokenBudget) so existing behavior is byte-for-byte unchanged until you set it.

Details

  • Per-turn signature counts (toolName(jsonEncode(args))), cleared on submit / regenerate / edit.
  • Detection happens in _onStreamDone before re-prompting; the count is incremented for the calls actually executed.
  • AgentLoopException is exported via the client barrel.

Verification

  • flutter test packages/flutter_ai_client — 39 pass, incl. 2 new tests (guard trips with AgentLoopException; disabled-by-default path unaffected)
  • flutter analyze clean · dart format clean repo-wide

Version

flutter_ai_client 0.2.2 (additive; no core constraint change)

🤖 Generated with Claude Code

New opt-in UseChatController(maxIdenticalToolCalls:) halts the agent loop
with a typed AgentLoopException when the model keeps requesting the same
tool call (identical name + JSON args) after it has already run that many
times in one turn — instead of looping to maxSteps and burning tokens.

0 (the default) disables it, so existing behavior is unchanged. Complements
the existing tokenBudget token ceiling and per-call arg-validation
containment. Signatures are tracked per turn and cleared on submit/
regenerate/edit.

Closes #97

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@ananmouaz
ananmouaz merged commit 1b75b2a into main Jul 1, 2026
4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Agent guardrails: cost/iteration ceilings, loop detection, tool-error containment

1 participant