refactor: convert sendAIMessage from recursion to iterative while-loop#1337
Merged
Conversation
Replace recursive sendAIMessage with nested outer/inner while-loops: - outer loop handles restarts (notifications, goal continuation, stop hooks) - inner loop handles tool-call continuation - turnOffset gates depth-0 init and finally-equivalent cleanup - turnDepth replaces recursionDepth in maxTurns check Keep setImmediate yield before inner continue to let macrotasks (abort timers) fire between turns in mocked test scenarios. Rename agent.toolRecursion.test.ts → agent.toolLoop.test.ts. Closes #1324
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Convert the recursive
sendAIMessagemethod inaiManager.tsto an iterative nested while-loop design, eliminating stack growth that caused OOM at depth 2418+.Changes
outerloop handles restarts (notifications, goal continuation, stop hooks);innerloop handles tool-call continuationturnOffset(= initialrecursionDepth) gates depth-0 init and finally-equivalent cleanup — same semantics as the oldrecursionDepth === 0checksturnDepth(=turnOffset+ inner loop counter) replacesrecursionDepthin maxTurns checksetImmediatehack for stack growth (PR fix: yield event loop before sendAIMessage recursion to prevent OOM #1325) — while-loop doesn't grow stacksetImmediateyield before innercontinue— needed so macrotasks (abort timers) can fire between turns in mocked test scenarios where all async ops are microtaskstry/catch/finallybecametry/catchinside inner loop + sequential finally-equivalent code after itturnDepth++; continue inner;shouldRestart=true; turnOffset=0agent.toolRecursion.test.ts→agent.toolLoop.test.tsWhat stays the same
recursionDepthparam kept for backward compat)Verification
Closes #1324