Skip to content

refactor(agent-loop): add a shared turn engine and run --plain on it - #2097

Merged
will-lamerton merged 1 commit into
mainfrom
refactor/turn-engine-core
Nov 11, 2026
Merged

will-lamerton merged 1 commit into
mainfrom
refactor/turn-engine-core

Conversation

@will-lamerton

Copy link
Copy Markdown
Member

First step of moving the four hand-written agent loops (TUI conversation-loop.tsx, --plain, ACP runTurn, 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.ts exports runTurnEngine. It is a single for loop over turns. State for each turn lives in local variables, the retry streaks live in createHeadlessRetryGuards, and nothing recurses. It does not import Ink or React (no-ink-fast-paths still passes).

The engine owns, in this order for each iteration:

  1. the abort check and the turn ceiling (maxTurns; the last allowed turn offers no tools and adds the final-answer instruction)
  2. the request: the system message plus history capped to sessions.maxMessages
  3. the model call, with the frontend's stream sinks attached, and counting model calls (a call that throws counts too)
  4. XML/JSON text tool-call parsing on the fallback path, and the malformed-call nudge and retry
  5. partitioning unknown or unusable calls, and recording the assistant message (an empty one is never recorded)
  6. auto-compaction, gated on the capped view (the fix(tui): gate auto-compact on the capped history the request sends #2066 rule), adopted only when compaction actually ran
  7. the nanocoder.retries guards: repeated identical calls (counted over every emitted call), empty turns, truncated turns
  8. handing the valid calls to the adapter, appending the results, and the abort check after tools

Adapter interface (TurnEngineAdapter<S>):

member purpose
history.get/set where the conversation lives (a local array, session.messages, React state). It is written at every step, so a throw keeps finished work
getSystemMessage() read every turn; undefined ends the run
prepareTurn(ctx) the tools, the available names and the mode overrides for this turn
beginModelCall(ctx) stream callbacks for one call, reasoning() for the assistant message, and end() once the call settles
onModelResponse(res) per-call usage and stats
partitionToolCalls(calls, prepared) which emitted calls can run (the plain and ACP variants differ)
compactOptions onNotify, aggressiveCompact, provider and model
executeTools(calls, ctx) approval routing, hook and plugin gates, and execution. It returns {continue, results} or {stop, payload, results?}
onFinalAnswer(ctx) a content-only turn: finish, or continue with messages to append (walkthrough or plan fallback)
onMalformedRetry / onRejectedToolCalls / onEmptyRetry / onTruncatedRetry / onTruncatedGiveUp notifications, used for status lines and the tool log

The 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 with modelCalls). Each frontend maps that result onto its own shape: PlainConversationOutcome here, and PromptResponse for 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.

--plain on the engine

runPlainConversationBody is now an adapter plus a switch over the result. Streaming and printing, usage accounting and /stats, the rollback of finalText on a malformed turn, the rejected-call tool log, the approval bail-out (tool-approval-required with autoAcceptWouldRun), 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 Aborted rather than Conversation exceeded N turns. This matches ACP, which already checked for an abort after tools.

Tests

  • New source/agent-loop/turn-engine.contract.spec.ts runs 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.
  • New source/agent-loop/turn-engine.spec.ts covers what only the engine sees: history written through the adapter, a model error vs an abort (and end() running on failure), no system message, no choices, an adapter stop recording its results, onFinalAnswer continuing, unrunToolCalls on a repeated stop, the max-turn ceiling, and the order of the rejected-call callback.
  • No existing spec was changed. All 85 source/plain specs pass unmodified.
  • Ran tsc --noEmit, biome check, knip (both passes), and AVA over source/agent-loop, source/plain, source/acp, source/subagents and source/hooks (1085 passed), plus source/config/no-ink-fast-paths.spec.ts.

No changeset: this is a refactor with no user-visible change.

Next in the sequence

  1. ACP runTurn moves onto the engine (stopReason mapping, stopWithNotice, plan fallback in onFinalAnswer, per-call permission in executeTools)
  2. The subagent executor moves onto the engine
  3. TUI step 1: recursion becomes the engine behind the existing processAssistantResponse signature
  4. TUI step 2: thin out the parameters and the React plumbing

🤖 Generated with Claude Code

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]>
@github-actions

Copy link
Copy Markdown
Contributor

No changeset found

This 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 changeset

Pick 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 .changeset/*.md file.

If this PR is docs-only or a chore that needs no release note, you can ignore this — or run pnpm changeset --empty to record that intentionally.

@github-actions

Copy link
Copy Markdown
Contributor

nc-review could not produce a verdict this run (agent exit 1). This is a problem with the review agent, not with your pull request. A maintainer can retry with /re-review.

@will-lamerton
will-lamerton merged commit b8db0ba into main Nov 11, 2026
19 checks passed
@will-lamerton
will-lamerton deleted the refactor/turn-engine-core branch November 11, 2026 16:05
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]>
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