Skip to content

Agent Loop

A coding agent is not “one prompt, one answer.” One user turn can contain several model steps. Each step sends the current messages and tool definitions to the provider; whenever the assistant returns tool calls, CodeN executes them, appends tool messages, and requests the model again. The turn finishes only when no tools are requested and the Stop Hook does not require more work.

user input
→ hook: UserPromptSubmit (can block)
→ model request (tool definitions + context)
→ if tool_calls: execute each tool → fill results back
→ request the model again (same turn)
→ until the model stops calling tools → hook: Stop (can demand more work)
→ return the final answer

Each model request plus its tool-execution sequence forms one turn; the default maxSteps is 80, and hitting it throws runtime.step_limit.

Behavior Detail
Tool execution Executed sequentially in returned order; unfinished calls are repaired as runtime.interrupted errors on resume
Tool results Truncated to 50000 characters before entering context; error results carry an isError flag back to the model
Input changes After a PreToolUse hook updates input, schema, path, risk, and permissions are re-validated
Retries Network/5xx/429 errors retry up to 3 times with 250ms exponential backoff (0.8–1.2 jitter), honoring Retry-After
Context errors A 413 or context-length error triggers one emergency compaction; still over limit throws context.exhausted
Thinking level The snapshot taken at turn start applies to that turn’s tool loop and retries
  • Input budget = contextWindow − reservedOutputTokens − safetyMargin (default 128000 − 8192 − 4096).
  • When the estimate exceeds 80% of the budget, CodeN keeps the current interaction and the preceding complete interaction verbatim. The current session model reads all older history, including any previous compaction summary, and produces one structured handoff summary capped at min(2048, reservedOutputTokens).
  • A summary is committed only when it is non-empty, contains no tool call, reduces the replaced context, and leaves the projected request within the hard input budget. A failed automatic attempt leaves history unchanged and is not repeated during the same user turn.
  • /compact runs the same model-driven flow immediately and reports failure explicitly. A failed emergency compaction raises context.exhausted; /new clears the summary to start a fresh conversation.
  • Semantic compaction remains lossy. Keep durable project rules and critical state in project instruction files rather than relying only on conversation history.
  • Normal completion: model output has no tool_calls; a Stop hook returning decision: "block" injects feedback and asks the model to continue (still bounded by maxSteps).
  • Failure: throws CodeNError, triggers the Notification hook (attention_required) and the turn.failed event; SessionEnd closes the session.
  • Every effective turn ends with a usage summary of token counts.