Agent loop

Chat, code sessions, the kanban board and workflows all share one kernel: HetuAgentRunner.RunAsync. It composes Microsoft Agent Framework's ChatClientAgent, FunctionInvokingChatClient and ToolApprovalAgent directly, and only handles product events, history compression and result aggregation.

Order of a single run

  1. Resolve the model: a ModelId on the request creates that provider, otherwise the default chat model is used; if neither exists the run throws instead of silently substituting another model.
  2. Load tools: built-in / session tools first, then tools/list from the MCP servers bound to the session; the merged set refreshes the tool schemas and system prompt.
  3. Enter the loop (15 iterations by default): each iteration first drains steering into context, then compresses history per configuration, then calls the model.
  4. Handle output: prose and thinking stream out as events; tool calls go to the caller's decider, which either executes them or requests approval.
  5. Feed results back: tool results enter the context and are pushed to the UI; per-iteration prose, thinking, tools and usage accumulate into the run result.
  6. Finish: the run ends when no further tool calls arrive. At the iteration cap MAF automatically performs one final request without tools and marks iteration_limit. The caller persists messages, records usage and appends done.

Key parameters

ParameterDefaultMeaning
MaxIterations15Iteration cap; a value ≤ 0 falls back to 15 to prevent infinite loops
MaxToolCallsPerTurn5Per-turn tool budget; excess calls are skipped with an error result (the run continues and the model can retry in smaller batches)
ToolTimeout10 minutesDefault per-tool execution cap; the shorter of this and the tool's own Timeout wins, and it cancels the tool's own token
CompressHistorytrueSet false to skip history compression when debugging compression side effects
EnableToolstrueWhen off, no tool schemas are sent — plain conversation mode
CoreToolNamesnullWhen set, only these core tools are exposed; the rest follow session configuration

Mid-run steering

  • Injected at a fixed point — the start of each iteration — so it never interrupts a tool chain halfway and contradicts the context.
  • The injected text carries a fixed prefix (【运行中引导,请立即结合它调整当前工作】) so the model can tell it is a mid-run redirection.
  • Clicking "steer" while streaming queues the instruction in AgentSteeringHub; the next iteration picks it up. A pending plan/question wait is resolved first so the new instruction can take effect immediately.
  • Queue vs steer: a queued message is sent after the current turn; a steer changes the running turn immediately.

History compression boundaries

BehaviourImplementation
ScopeHistory compression stops before the current user message to preserve their exact request. Tool output produced by the active turn has a separate deterministic budget: old results are compacted while ToolCallId linkage and recent results are preserved
DeduplicationAlready-compressed slices are remembered in compressedIndexes; long sessions never re-compress the same slice
MethodCalls the full compression pipeline entry (LLM summary allowed, subject to pipeline mode and threshold)
Cost visibilityThe first iteration estimates system prompt and tool schema character cost and logs it, separating "heavy prompt" from "long history"

Tool loading and MCP

  • MCP servers that are missing, disabled or not stdio are skipped with a warning; a single server failing to load logs an error and continues the turn instead of breaking it.
  • Successfully loaded tools merge with built-ins; name conflicts resolve in favour of built-ins, and the merged schemas feed permission decisions.
  • MCP tools are registered at runtime only and never persisted; server configuration lives in settings.

Event outlets

OutletPurpose
IAgentLoopSink.OnEventAsyncStructured event passthrough: SSE writes frames verbatim, non-streaming callers may ignore it
IAgentLoopSink.OnSteeringAsyncCallback when a steer is accepted
Hooks.AfterToolResultAsync / AfterToolResultsAsyncPersist each result immediately, then run batch post-processing such as file-change tracking; later interaction waits cannot delay earlier history
Caller dutiesPersist messages, record usage (ILlmUsageRecorder) and append the done frame; code sessions persist only the terminal subagent frame (with the inner timeline entries) for replay

Failure and degradation

  • Model unavailable: throws, and the UI receives an error frame — no silent model substitution.
  • A single MCP server fails: that server is skipped, other tools keep working.
  • Cancellation: OperationCanceledException is not swallowed, and parsed tools that have not started never execute after cancellation; the caller decides whether it means "cancelled" or "requeue".
  • Tool protocol errors: textual <tool_call> markup is parsed across deltas. Truncated calls, malformed arguments and batches above the per-turn limit are rejected. Unrecognized text is preserved verbatim but never executed.
  • Compression failure: the pipeline degrades internally only (missing provider or a non-shorter result returns the original text).

Non-obvious but important

  • The iteration and tool limits are guard rails, not business rules: the former stops loops, the latter is enforced through the prompt so the model keeps judgement.
  • Steering is injected only at iteration boundaries; several clicks within one iteration are drained as one instruction.
  • Chat and code sessions differ in their permission decider and tool set, not in the kernel (code sessions bring work_* tools and a workspace scope).
  • Kanban and workflows reuse the same kernel, swapping the event outlet for run-step / node-event recording.
  • Identical read-only calls within one turn reuse the previous result; the same call failing twice in a row is skipped the third time to stop loops burning the iteration budget.
  • Consecutive read-only file tools (list dir / read file / glob / grep) run in parallel within a batch; remote SSH projects stay sequential to avoid sharing a runner.
  • MCP clients are pooled per connection config and handshake once per process; SSE content/thinking deltas are coalesced to ~60ms or 512 characters.
  • The work_task sub-agent also runs on the same kernel: read-only tool whitelist with a 12-iteration / 3-minute cap, so textual tool-call parsing, argument validation and truncation protection match the main session.

Debugging hints

  • Start with the [AgentLoop] and [Compression] log lines: the first shows iteration counts and tool loading, the second shows before/after sizes of history compression.
  • Suspect compression is changing behaviour? Turn CompressHistory off and reproduce.
  • Tool unexpectedly unavailable: check whether the MCP server is disabled or non-stdio, and whether the tool is denied by the permission mode or a project rule.