Agent runtime and model orchestration
The agent runtime turns an approved chat request into a controlled model run. It checks access and budget, selects a usable provider and model, builds the project context and allowed tools, streams work to the caller, keeps long chats within model limits, and stores the result. The same runtime also supports unattended test runs and subagent requests. See agent-and-chat for the wider chat lifecycle and agent-tools-memory-and-prompts for tool, memory, and prompt behavior.
Provider and model selection
Model selection resolves a concrete provider and model for the run. An explicit selection wins. Otherwise the runtime uses the project chat default and rejects the run when no default model is configured. Before creating the run, it checks the active user, project cloud access, the provider budget, and managed-model credit access when the selected provider requires it.
The model catalog combines project settings, project file settings, environment settings, and nao-managed models. Provider metadata describes the model's context size, cost, authentication needs, and inference controls. The runtime uses this description to create the right provider client and to translate common settings such as thinking effort, sampling, output limits, and service tiers into each provider's API. Custom model IDs use provider defaults when the catalog has no exact entry. Bedrock model IDs can inherit settings from a matching geographic model.
Provider adapters also protect the common run contract when provider APIs differ. They select the provider's endpoint and credential path, remove settings that a model cannot accept, clamp stale effort or budget values, and fit thinking budgets under output limits. Anthropic tool-result clearing applies only to external MCP results. Internal tool results remain available to the agent.
Managed models use nao's provider key. Each call carries a usage context that identifies the user, project, chat, run, and billing mode. Wallet-backed calls reserve and settle credits, while unbilled runs record usage without charging the organization wallet.
Background work has separate model choices. Administrators can pin models for tasks such as title generation and context compaction. When no task-specific choice exists, the runtime derives an annotation model from the active selection or the provider default.
References: apps/…/agent.ts• L321-445 apps/…/agent.ts• L501-534 apps/…/agent.ts• L968-989 apps/…/providers.ts• L295-377 apps/…/providers.ts• L436-579 apps/…/managed-ai.ts• L31-72 apps/…/managed-ai.ts• L253-337 apps/…/provider-meta.ts• L363-387 apps/…/provider-meta.ts• L1180-1251
Agent profiles
An agent profile defines the purpose and limits of a run while the runtime supplies the common loop. The profile chooses the tool set, prompt changes, message source, and any special step limit. The web analytics profile exposes the project analytics experience. The MCP profile uses the same analytics ability with tools that an MCP caller cannot render or use. The test-run profile answers unattended nao test prompts without memories and excludes tools that ask questions or change project state.
This separation lets chat, MCP, testing, onboarding, automation, and admin requests share one runtime without sharing the same permissions or output assumptions. The runtime builds tool context from the project and user before it creates the profile-specific tools. The context carries access limits, warehouse credentials, environment values, query state, and generated artifacts for the run.
References: apps/…/types.ts• L13-38 apps/…/test-run.ts• L1-17 apps/…/agent.ts• L265-318 apps/…/agent.ts• L369-428
Context and prompt assembly
Context assembly turns the stored chat and the current request into model-ready messages. It combines the project rules with the context that the selected tools need, then applies request-specific additions such as mentions, citations, skills, database references, story state, and attachments.
Mentioned skills can come from the project or from the user's personal skills. A project skill takes precedence when both use the same name. This keeps the prompt aligned with the skills the user is allowed to use.
The runtime keeps large or stale data out of the active turn. It marks older query results as superseded, collapses stored story output into reusable artifacts, expands trusted story references when needed, and replaces stored documents with paths that tools can read. Images are loaded as model-readable data. The final messages are converted to the provider format and sanitized before provider cache markers are added.
Tools extend this context with governed project actions. Search stays within allowed project, storage, and story paths. SQL can read the local database and files, while warehouse access follows project SQL policy or the semantic layer. Semantic queries use the governed metric definitions before they run. Story actions preserve query links and versions. File replacement is limited to editable storage and custom-story files, so project context and published story-library files remain read-only.
The prompt can include memories, user rules, connections, databases, project skills, personal skills, MCP servers, sandbox secrets, stories, chart support, access limits, and the active tool set. User-group restrictions are added after prompt selection so the model sees the limits that apply to this run.
References: apps/…/agent.ts• L278-323 apps/…/agent.ts• L680-837 apps/…/agent.ts• L882-955 apps/…/agent.ts• L1236-1265 apps/…/search.ts• L26-53 apps/…/execute-sql.ts• L32-112 apps/…/execute-semantic-query.ts• L10-37 apps/…/story.ts• L44-68 apps/…/str-replace.ts• L26-59
Tool result retention
Tool result retention controls how much prior tool output stays in provider context. The runtime allows Anthropic to clear only old MCP results after the context reaches a high input size. It keeps recent MCP results and protects internal results because later agent steps may need them.
The retention rule is part of provider setup rather than a change to the chat record. One-shot work such as compaction disables it, because clearing results would remove input that the summary needs. This keeps normal long runs smaller without changing the durable chat history.
References: apps/…/tool-result-clearing.ts• L9-29 apps/…/tool-result-clearing.ts• L31-78 apps/…/agent.ts• L539-565 apps/…/agent.ts• L612-658 apps/…/compaction-llm.ts• L26-40
Context compaction
Context compaction keeps a long conversation within the selected model's context window. Before each model step, the runtime measures the conversation, tool definitions, and reserved output against the model's known or default context size. When the load crosses the compaction limit, a summary model replaces older history while keeping the current user turn available.
The compaction model removes images and reasoning parts before it selects messages that fit its input budget. It reserves space for the summary and its instruction, then produces a bounded summary without provider tool-result clearing. This makes compaction a complete one-shot request rather than another agent step.
Compaction is applied during step preparation because each step rebuilds its input. The runtime keeps a marker in the chat so later turns can restore the summary. It also preserves story references through compaction. Start and finish events let the caller show that the context is being reduced.
References: apps/…/agent.ts• L612-642 apps/…/agent.ts• L811-814 apps/…/compaction-llm.ts• L14-70 apps/…/tool-result-clearing.ts• L48-68
Model loop and stop conditions
The model loop alternates between model output and tool work until it produces a usable answer or reaches a safety limit. Interactive profiles use shared stop conditions. A profile with maxSteps ends after that many steps instead of waiting for the interactive follow-up behavior.
The loop protects the chat from incomplete answers and repeated work. It can stop after a complete answer with follow-ups, a clarification or setup request, repeated invalid calls, repeated tool errors, duplicate work, or the maximum step count. An explicit stop aborts the run through its controller. The test-run profile uses its own step limit and removes tools that require user interaction or change project state.
References: apps/…/agent.ts• L539-610 apps/…/agent.ts• L1085-1107 apps/…/stop-conditions.ts• L5-116 apps/…/suggest-follow-ups.ts• L4-20 apps/…/types.ts• L21-37 apps/…/test-run.ts• L5-16
Progress streaming and persistence
Interactive runs expose a UI message stream instead of waiting for the full answer. The stream sends the assistant message start, new-chat metadata, model text, tool activity, query results, and compaction events. Provider-specific reasoning progress can be shown to the UI without changing the message data that the provider receives on replay.
When the stream finishes, the runtime settles tool parts and stores the assistant message with its source, provider, model, usage, stop reason, and error state. It also schedules memory extraction and title generation when the profile allows them. A stop request aborts the model call. The run manager then removes the active run, releases story edit locks, and releases waiters when the stream or background generation finishes.
This diagram shows how a chat request becomes a streamed and stored result.
flowchart LR
A[Chat request] --> B[Check access and resolve model]
B --> C[Build prompt and tools]
C --> D[Prepare step]
D --> E[Compact if needed]
E --> F[Model and tool loop]
F --> G[Stream progress]
F --> H[Apply stop conditions]
H --> D
G --> I[Persist settled answer]
References: apps/…/agent.ts• L43-107 apps/…/agent.ts• L19-72 apps/…/agent.ts• L351-428 apps/…/agent.ts• L683-782 apps/…/agent.ts• L945-1083 apps/…/providers.ts• L65-100 apps/…/agent-stream-disconnect.ts• L22-70
Subagent coordination
The MCP ask_nao tool starts the same agent runtime as a subagent for an external caller. It creates or continues a chat, resolves a requested model or the configured subagent model, and runs the MCP profile with the project's analytics context. The chat stores the work so a user can open, replay, share, or continue it in the nao UI.
Subagent model selection uses an explicit request first, then the project-pinned subagent model, the parent run's model, or the first available project model. The runtime checks budget and managed-model billing before it starts. The subagent carries the parent project, chat, and billing context while recording a distinct usage category.
The subagent runs to its profile step limit and yields a progress snapshot after each tool call. Each snapshot reports the selected model, active steps, and the status of each step. The final snapshot carries the report and duration. A bounded output setting limits the report, and an empty report produces a clear retry message. Internal tool results stay protected while external MCP results can use the provider's retention rule.
The MCP call waits briefly for a result. If the run continues past that time, it returns a running status and chat ID while the agent drains its stream in the background. The caller polls get_nao_answer until the run completes, needs clarification, or fails. If in-memory run state is gone, the result can be rebuilt from the persisted chat, although live query metadata is not recovered.
References: apps/…/sub-agent.ts• L30-74 apps/…/sub-agent.ts• L122-205 apps/…/sub-agent.ts• L267-357 apps/…/model.ts• L8-33 apps/…/model.ts• L36-70 apps/…/run.ts• L17-88 apps/…/run.ts• L90-157 apps/…/tool-result-clearing.ts• L31-46
Change checklist
When these files or sections are changed, remember to consider these:
- Changes to provider metadata must preserve the link between model capabilities, settings controls, provider option names, context limits, and cost records.
- Changes to managed-model calls must keep credit reservation, usage settlement, abort handling, and unbilled usage aligned.
- Changes to profile fields must preserve the shared runtime contract for tools, prompts, memory use, usage categories, and step limits.
- Changes to prompt preparation must preserve attachment handling, story references, stale query handling, access restrictions, tool-result retention, and compaction markers.
- Changes to skill access or mention expansion must preserve project-skill precedence, personal-skill fallback, and prompt visibility.
- Changes to SQL, semantic-query, search, story, or file-edit tool contracts must preserve the access boundary between project context, user files, stories, local data, and warehouse data.
- Changes to stream parts or stop behavior must remain compatible with UI replay, persisted messages, explicit aborts, story edit locks, and background waiters.
- Changes to subagent progress or report shape must stay compatible with MCP polling and persisted chat recovery.
- Changes to subagent model precedence or usage context must stay aligned with the caller's requested model, project settings, budget checks, and parent run identity.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| No project default or unresolved selected model | The run is rejected before model work starts | Resolve the selection and provider credentials before creating the run |
| User is inactive or project cloud access is not valid | The run is rejected before it can use project resources | Check user and project access during run creation |
| Stored inference settings do not match the selected model | The provider can reject the request or apply invalid controls | Derive controls from model capabilities and clamp stale effort or budget values |
| Managed call has no price, user, or billed organization | The call cannot be safely charged | Validate usage context and token pricing before execution |
| Context grows beyond the model window | The model cannot process the turn | Compact during step preparation and restore the saved summary on later turns |
| Provider clears an internal tool result | A later step can lose data produced by the agent itself | Protect every tool except clearable external MCP results |
| Raw warehouse SQL is used when project policy disables it | The query is rejected even when the database exists | Use the semantic layer or the allowed local database path |
| A story edit uses an unknown query or invalid filter template | The story can lose its chart link or return a warning instead of a valid interactive result | Preserve query IDs and fix template warnings before finishing |
| A file edit targets project context, a published story, or a binary document | The edit is rejected rather than changing protected or non-text data | Use only supported editable mounts and a text-safe edit path |
| Test or model repeats tool work | The run can waste steps or produce no answer | Apply profile step limits and shared invalid-call, error, and duplicate-work stops |
| Stream closes before persistence completes | The caller can miss progress or the chat can lack a settled answer | Settle tool parts and persist the final message in the stream finish path |
| Story edit locks are not renewed or released | A later run can be blocked from editing the same story | Renew locks while the run is active and release them on disposal |
| Subagent request names an unavailable model | The subagent cannot start | Match the request against the project's available models and report valid choices |
| Subagent reaches its step limit without a report | The caller receives no useful result | Return the explicit no-report fallback and ask for a narrower task |
Key files
| File | Why to read it |
|---|---|
| apps/…/agent.ts | Defines access checks, run creation, prompt assembly, step preparation, streaming, persistence, and background completion. |
| apps/…/providers.ts | Shows how provider clients and model-specific inference options are normalized. |
| apps/…/provider-meta.ts | Defines the provider catalog, model capabilities, context sizes, and cost metadata. |
| apps/…/tool-result-clearing.ts | Defines which provider tool results may be cleared and how internal results stay protected. |
| apps/…/managed-ai.ts | Shows managed-model eligibility, wallet reservation, and usage settlement. |
| apps/…/types.ts | Defines the profile contract shared by interactive and background runs. |
| apps/…/test-run.ts | Shows how an unattended test run narrows tools and disables user-dependent memory. |
| apps/…/execute-semantic-query.ts | Shows how governed metric requests become database queries. |
| apps/…/execute-sql.ts | Shows the access boundary between local data, warehouse data, and app data. |
| apps/…/story.ts | Shows how agent-created stories preserve versions, query links, and custom-story drafts. |
| apps/…/model.ts | Shows subagent model precedence and billing context. |
| apps/…/run.ts | Shows subagent step progress, bounded output, stop behavior, and usage tracking. |
| apps/…/compaction.ts | Defines the summary behavior used when chat context grows too large. |
| apps/…/compaction-llm.ts | Shows how the compaction request selects input and disables result clearing. |
| apps/…/stop-conditions.ts | Defines the shared safeguards that end an interactive model loop. |