The agent loop is the repeated cycle of "ask the model, act on its answer, ask again." It is implemented in @m31a/core; the terminal UI and headless CLI are consumers of the event stream it produces.
The main source files for this page are:
| File | Responsibility |
|---|---|
packages/core/src/prompts/promptProvider.ts | Assembles the system prompt. |
packages/core/src/core/m31aChat.ts | Owns history, retries, request construction, and recording. |
packages/core/src/core/turn.ts | Converts one streamed model response into typed events. |
packages/core/src/core/nvidiaNimContentGenerator.ts | Maps M31A requests to OpenAI-compatible NIM calls. |
packages/core/src/scheduler/scheduler.ts | Validates, confirms, and runs tool calls. |
packages/core/src/services/chatRecordingService.ts | Writes the durable session record. |
1. Prompt assembly
Config builds an AgentLoopContext containing the tool registry, policy engine, hook system, skill manager, model config service, and services. The system instruction is produced by PromptProvider.getCoreSystemPrompt() in packages/core/src/prompts/promptProvider.ts.
The provider composes optional sections, each gated by runtime state:
- Preamble and core mandates — interactive versus headless, approval mode, the configured context filenames, and whether topic narration is enabled.
- Agent contexts — names and descriptions from the agent registry, only when the
invoke_agenttool is available. - Agent skills — names, descriptions, and locations from the skill manager. The full skill body is loaded later through
activate_skill, not here. - Primary workflows versus planning workflow — mutually exclusive based on whether the mode is
plan. - Operational guidelines and sandbox — shell efficiency settings and the detected sandbox mode.
- Git, YOLO, task tracker, and hook context — included when relevant.
M31A_SYSTEM_MD can replace this composition with a system prompt template from disk; M31A_WRITE_SYSTEM_MD can write the assembled prompt back to a file. The final step (snippets.renderFinalShell) appends hierarchical memory (global, extension, project, user-project) and the active topic. See Context lifecycle for where those strings come from.
The tool list is not written into the system prompt as a schema dump; it is sent as the request's tools field. The prompt only names tools and workflows so the model knows when to use them.
2. Request construction
M31aChat.sendMessageStream() in packages/core/src/core/m31aChat.ts serializes requests with a sendPromise, so a second prompt waits for the first stream to finish. Before sending, it:
- Closes any unanswered model tool call or tool response left by an interrupt, using synthetic turns so the outbound history stays well formed.
- Records the user message through
ChatRecordingService(unless the input is itself a function response, which is recorded as a tool call instead). - Resolves the
ModelConfigKeythroughconfig.modelConfigService.getResolvedConfig(), and applies model selection and availability rules. - Scrubs internal fields, coalesces consecutive roles, and strips tool-call ID prefixes;
ensureTerminalUserTurn()guarantees the final outbound item is a user turn.
These transformations are deliberately applied only to the outbound payload: the persistent history in AgentChatHistory is not rewritten. See Model resolution for how the concrete model ID is chosen.
BeforeModel and BeforeToolSelection hooks run at this point. A hook may change the model, config, or tool selection, force confirmation, or block the request entirely. Thinking effort (model.thinkingEffort) is mapped to a thinkingConfig for the main model role.
3. The NIM request
NvidiaNimContentGenerator in packages/core/src/core/nvidiaNimContentGenerator.ts posts to the OpenAI-compatible endpoint:
POST {baseUrl}/chat/completions
Authorization: Bearer $NVIDIA_API_KEYThe default base URL is https://integrate.api.nvidia.com/v1 and the default model is nvidia/nemotron-3-ultra-550b-a55b. The generator:
- converts M31A contents into
system,user,assistant, andtoolmessages; - converts M31A tool declarations into OpenAI
type: functionentries withtool_choice: "auto"; - uses
max_tokens(notmax_completion_tokens) and addsstream_options.include_usagewhen streaming; - maps thinking config to per-family
reasoning_effort,reasoning_budget, orchat_template_kwargs, depending on the model family; - extracts reasoning fields such as
reasoning_contentinto parts markedthought: true, and replays required reasoning fields on later tool turns; - reconstructs sparse streamed
tool_callsdeltas and emits a terminal chunk carrying the finish reason and usage metadata.
Custom OpenAI-compatible providers reuse this generator; see Custom provider.
4. Streaming and turn events
Turn.run() in packages/core/src/core/turn.ts consumes the async generator and yields typed events to the UI or headless runner:
| Event | Meaning |
|---|---|
Content | User-visible text from the model. |
Thought | Parsed reasoning text when thoughts are included. |
ToolCallRequest | The model asked for a tool; includes a normalized call ID. |
Citation | Citations collected across the stream. |
Finished | A finish reason and usage metadata arrived. |
Retry, Error, InvalidStream | Recovery and failure paths. |
AgentExecutionStopped, AgentExecutionBlocked | A hook halted the run. |
UserCancelled | The abort signal fired. |
Function calls are looked up in the tool registry. tool.build(args) produces a display title and description for the UI, and the request is queued in pendingToolCalls. A call ID is normalized to the form name__id so history consolidation can trace it.
When a model response is empty or thinking-only, a retry can append a one-shot nudge message to the end of the conversation rather than editing the system prompt, preserving prefix caching.
5. The tool loop
Tool calls are handed to the Scheduler in packages/core/src/scheduler/:
evaluateBeforeToolHook()firesBeforeTool, which can block, force confirmation, or modify arguments.checkPolicy()asks the policy engine forallow,deny, orask_user. Client-initiated calls are treated as implicitly confirmed; headless runs cannot satisfyask_userand fail instead.resolveConfirmation()handles interactive approval, including sandbox expansion requests.updatePolicy()turns "always allow" choices into in-memory and optionally persisted policy rules.ToolExecutorruns the invocation withAfterToolhook processing and returns aToolResult.- Results become function-response parts in the next outbound request, and
M31aChat.recordToolCalls()writes full call metadata to the session record.
Read Tool execution and Policy evaluation for the details and precedence.
6. Persistence and continuation
ChatRecordingService appends metadata, messages, tool calls, thoughts, token summaries, and patches to a JSONL session file under the project temp directory. Subagent sessions are nested under the parent session ID. Recording scheduled tool calls before execution means an interrupted process still leaves a durable trace.
On resume, M31aChat rebuilds history from the persisted record using the canonical converter, which preserves tool calls and thoughts. Compression can then collapse older tool output while protecting the most recent turns.
7. End-to-end view
prompt assembly
-> resolve model config
-> BeforeModel / BeforeToolSelection hooks
-> POST /chat/completions (stream)
-> Turn.run() yields content, thoughts, tool requests
-> Scheduler: BeforeTool -> policy -> confirmation -> execute -> AfterTool
-> append tool responses, record tool calls
-> next request (repeat) or final answer
-> ChatRecordingService flushes the JSONL recordNext steps
- Read Context lifecycle for what enters the prompt.
- Read Session storage for the on-disk format.
- Try Review a diff to see the loop in practice.