Repository navigation
refactor(agent-loop): add a shared turn engine and run --plain on it - #2097
Merged
Merged
Conversation
Introduce source/agent-loop/turn-engine.ts: one iterative, Ink-free agent loop that owns the model call, text tool-call parsing with the malformed retry, unknown-call partitioning, auto-compaction gated on the capped view, the nanocoder.retries guards, the final-turn wrap-up and abort handling. Frontends plug in through a TurnEngineAdapter for history, streaming, tool execution and end-of-turn decisions, and map the engine's result onto their own outcome. The --plain loop now runs on it. Its streaming, usage accounting, approval bail-out, tool log and walkthrough nudge move into the adapter unchanged. Add a contract spec that runs the same scenarios through plain and ACP, so the loops are checked against each other as the rest move over. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Contributor
No changeset foundThis PR does not add a changeset, so it will not appear in the changelog or trigger a release. If the change is user-facing, add one: pnpm changesetPick a bump (patch / minor / major) and write the changelog entry in our usual voice ("Added X... Thanks to @you. Closes #123."), then commit the generated If this PR is docs-only or a chore that needs no release note, you can ignore this — or run |
Contributor
|
nc-review could not produce a verdict this run (agent exit |
This was referenced Nov 11, 2026
jay23606
added a commit
to jay23606/nanocoder
that referenced
this pull request
Nov 12, 2026
…ano-Collective#2097) Introduce source/agent-loop/turn-engine.ts: one iterative, Ink-free agent loop that owns the model call, text tool-call parsing with the malformed retry, unknown-call partitioning, auto-compaction gated on the capped view, the nanocoder.retries guards, the final-turn wrap-up and abort handling. Frontends plug in through a TurnEngineAdapter for history, streaming, tool execution and end-of-turn decisions, and map the engine's result onto their own outcome. The --plain loop now runs on it. Its streaming, usage accounting, approval bail-out, tool log and walkthrough nudge move into the adapter unchanged. Add a contract spec that runs the same scenarios through plain and ACP, so the loops are checked against each other as the rest move over. Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
11 of 18 tasks
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.
First step of moving the four hand-written agent loops (TUI
conversation-loop.tsx,--plain, ACPrunTurn, the subagent executor) onto one engine. They have been drifting apart: fixes land in one copy and not the others. This PR adds the engine and moves--plain, the simplest loop, onto it. Nothing about how it behaves is meant to change.Design
source/agent-loop/turn-engine.tsexportsrunTurnEngine. It is a singleforloop over turns. State for each turn lives in local variables, the retry streaks live increateHeadlessRetryGuards, and nothing recurses. It does not import Ink or React (no-ink-fast-pathsstill passes).The engine owns, in this order for each iteration:
maxTurns; the last allowed turn offers no tools and adds the final-answer instruction)sessions.maxMessagesnanocoder.retriesguards: repeated identical calls (counted over every emitted call), empty turns, truncated turnsAdapter interface (
TurnEngineAdapter<S>):history.get/setsession.messages, React state). It is written at every step, so a throw keeps finished workgetSystemMessage()undefinedends the runprepareTurn(ctx)beginModelCall(ctx)reasoning()for the assistant message, andend()once the call settlesonModelResponse(res)partitionToolCalls(calls, prepared)compactOptionsonNotify,aggressiveCompact, provider and modelexecuteTools(calls, ctx){continue, results}or{stop, payload, results?}onFinalAnswer(ctx)finish, orcontinuewith messages to append (walkthrough or plan fallback)onMalformedRetry/onRejectedToolCalls/onEmptyRetry/onTruncatedRetry/onTruncatedGiveUpThe engine never renders anything and never builds a frontend's outcome. It returns a
TurnEngineResult(completed,aborted,model-error,no-response,no-system-message,guard-stop{guard, message, unrunToolCalls},max-turns,adapter-stop{payload}, each withmodelCalls). Each frontend maps that result onto its own shape:PlainConversationOutcomehere, andPromptResponsefor ACP next.Hooks for the TUI's extra behaviour (the interactive repeated-call prompt, compact-and-retry, nudges that depend on context, always parsing text when there are no native calls) are left out on purpose. They arrive with the TUI PRs, so this PR does not add surface that nothing uses yet.
--plainon the enginerunPlainConversationBodyis now an adapter plus aswitchover the result. Streaming and printing, usage accounting and/stats, the rollback offinalTexton a malformed turn, the rejected-call tool log, the approval bail-out (tool-approval-requiredwithautoAcceptWouldRun), the walkthrough nudge, and the--json/text status lines all move over as they were. Ignoring whitespace, the plain diff is +185/−405. Most of the raw diff is re-indentation into the adapter object (git diff -w).Behaviour: none intended. One corner case is unreachable in practice. If an abort lands while tools are running on the final allowed turn (that turn offers no tools, so the model would have to send native calls anyway), plain now reports
Abortedrather thanConversation exceeded N turns. This matches ACP, which already checked for an abort after tools.Tests
source/agent-loop/turn-engine.contract.spec.tsruns one set of scenarios through every frontend (plain and ACP today; subagents and the TUI join as they move over). Each runner reduces its frontend's outcome to the same observation: the requests sent, the tools offered, the tools executed, and whether the run completed, stopped or was cancelled. Scenarios cover a plain answer, an auto-approved tool, an empty-turn nudge and its cap, a malformed text call, an unknown tool, the repeated-call stop, continuing after truncation, an abort before the first turn, and the final-turn wrap-up. ACP passes all of them before moving over, so its migration (next PR) is checked against what it does today.source/agent-loop/turn-engine.spec.tscovers what only the engine sees: history written through the adapter, a model error vs an abort (andend()running on failure), no system message, no choices, an adapter stop recording its results,onFinalAnswercontinuing,unrunToolCallson a repeated stop, the max-turn ceiling, and the order of the rejected-call callback.source/plainspecs pass unmodified.tsc --noEmit,biome check,knip(both passes), and AVA oversource/agent-loop,source/plain,source/acp,source/subagentsandsource/hooks(1085 passed), plussource/config/no-ink-fast-paths.spec.ts.No changeset: this is a refactor with no user-visible change.
Next in the sequence
runTurnmoves onto the engine (stopReason mapping,stopWithNotice, plan fallback inonFinalAnswer, per-call permission inexecuteTools)processAssistantResponsesignature🤖 Generated with Claude Code