Skip to content

feat: add three-layer agent loop protection#2

Merged
Jonnytoshen merged 3 commits into
mainfrom
feat/agent-fuse
May 21, 2026
Merged

feat: add three-layer agent loop protection#2
Jonnytoshen merged 3 commits into
mainfrom
feat/agent-fuse

Conversation

@Jonnytoshen

Copy link
Copy Markdown
Owner

Summary

Adds three layers of protection to the agent loop to prevent runaway execution, API failures, and budget overruns.

Changes

New files

  • src/loop-detection.ts — Tool call history tracker with a 30-entry sliding window and three detectors:
    • generic_repeat: same tool + same args repeated N times
    • ping_pong: two different calls alternating
    • global_circuit_breaker: any call repeated without result change
    • Three-level response: warning (5×) → inject nudge message, critical (8×) → halt, breaker (10×) → force stop
  • src/retry.ts — Step-level retry utilities: calculateDelay (exponential backoff), isRetryable, sleep
  • src/mock-model.ts — Offline mock model for testing all three protection layers without a live API key

Modified files

  • src/agent-loop.ts
    • Integrated loop detection (detect / recordCall / recordResult)
    • Step-level retry loop (up to MAX_RETRIES = 3) with exponential backoff
    • Token budget tracking via BudgetState (caller-owned, accumulated across steps)
    • MAX_STEPS bumped 10 → 15 to accommodate retry headroom
    • Switched type to LanguageModelV3 from @ai-sdk/provider
  • src/index.ts
    • Pass budget to agentLoop; auto-select mock model when DASHSCOPE_API_KEY is absent
    • Rename askQuestionask
    • Add in-app test hints for the three protection scenarios
  • package.json — Add @ai-sdk/provider; bump @ai-sdk/openai and ai

Testing

Start the agent without an API key to use the mock model:

pnpm start

Then try the prompts suggested on startup:

  • 测试死循环 — triggers loop detection
  • 测试重试 — triggers retry logic
  • 测试预算 — triggers token budget cutoff

- Loop detection: track tool call history with a sliding window,
  inject warning messages at 5 repeats, halt at 8 (critical) or
  10 (global circuit breaker)
- Step-level retry: exponential backoff up to MAX_RETRIES=3 for
  retryable API errors (rate limit, timeout, network)
- Token budget: accumulate input+output tokens across steps and
  force-stop when the limit is exceeded (default 15,000)
Copilot AI review requested due to automatic review settings May 21, 2026 06:49
@Jonnytoshen Jonnytoshen merged commit e5f283e into main May 21, 2026
1 check failed
@Jonnytoshen Jonnytoshen deleted the feat/agent-fuse branch May 21, 2026 06:50
@Jonnytoshen Jonnytoshen removed the request for review from Copilot May 21, 2026 07:13
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.

1 participant