Agent Runtime And Capabilities
This page is the map of the HPD Agent runtime. Use it when you know the first agent path and want to understand where the larger pieces fit.
The short version:
AgentConfig defines an agent.
AgentRuntimeBuilder composes the runtime and registers code agents.
AgentRuntime runs agents and their message turns.
Providers supply clients.
Tools and middleware shape what can happen during the turn.
Events describe what happened.
Sessions and threads decide where state lives.
Hosting exposes the same runtime over a process boundary.Runtime Loop
A normal message turn follows this shape:
user input
-> message-turn middleware
-> thread history and run context
-> model iteration
-> provider chat client
-> optional tool/function calls
-> function middleware and permissions
-> tool results
-> more iterations if needed
-> assistant result
-> events, thread projection, persistence, eval/telemetry hooksruntime.RunAsync(...) routes the input to the agent it names, or to the default agent, performs the turn, and returns an AgentTurnResult. During the same turn, the agent publishes events for text, tool calls, permissions, retries, errors, middleware, nested agents, workflows, audio, evaluation, and diagnostics.
The Runtime And Its Agents
An agent is an AgentConfig: a definition. The AgentRuntime runs agents. It is one per application or hosted runtime and holds what every agent shares: the session, agent, and content stores, providers and secrets, host services, the event composition, shared middleware, and the execution owner of each thread. See The Runtime And Its Agents for the full model.
var assistant = new AgentConfig()
.WithOpenAI("gpt-5-mini")
.WithInstructions("Summarize clearly.");
await using var runtime = await new AgentRuntimeBuilder()
.WithFileSessionStore("./sessions")
.AddAgent("assistant", assistant)
.BuildAsync(); // runtime started; no agent built yet
await runtime.RunAsync("Summarize the open issues.");
// the first run builds the assistant; leaving the scope disposes the runtimeThe runtime answers every runtime-wide question:
| Member | What it reads or does |
|---|---|
runtime.RunAsync(...) | Runs an input on the agent it names (agentId:), or on the default agent |
runtime.Subscribe<TEvent>(...) | Observes the events of every agent the runtime runs |
runtime.Agents | The definitions it runs: list, get, validate, and create, update, or delete stored ones |
runtime.Composition | What it can run agents with: providers, tool harnesses, middleware, events, and inputs |
runtime.Executions | Runs per thread or per agent, each with the agent that ran it and the models it called |
runtime.Content | Uploads and artifacts in each thread's scope |
runtime.SessionStore | The session store every agent runs against |
runtime.InspectCapabilitiesAsync(agentId) | What one agent exposes to its model once built |
BuildAsync() fixes the composition, registers the code agents, validates each definition against the composition, and runs the start hooks of the shared middleware once. It builds no agent: each agent is built from its definition and the runtime's shared parts the first time it runs or is inspected, then cached. Disposing the runtime runs the stop hooks of the shared middleware and disposes every built agent. Because the runtime runs for its whole lifetime, hosted HTTP/SSE clients, bot adapters, TUI runtimes, externally executed client tools, middleware response routing, background subagents, and other runtime-owned work all reach the same agents.
The start/stop middleware hooks run once per owner:
- Shared middleware registered on
AgentRuntimeBuilder:BeforeStartAsyncandAfterStartedAsyncrun duringBuildAsync();BeforeStopAsyncandAfterStoppedAsyncrun when the runtime is disposed. - Middleware an agent's definition declares: start hooks run when that agent is built, stop hooks when it is disposed.
- Message-turn, iteration, function, and thread hooks run inside each turn.
A run without a session starts an ordinary session with its main thread. AgentTurnResult.SessionId and ThreadId identify it, so the conversation can be continued:
var first = await runtime.RunAsync("Draft a release note.");
await runtime.RunAsync("Make it shorter.", sessionId: first.SessionId);One Runtime, Many Agents
The runtime knows two kinds of definition, both read through runtime.Agents as AgentDefinition values:
| Source | Examples | Editable |
|---|---|---|
Code | Agents registered with AddAgent(id, config), and harness subagents declared with FromConfig or FromParent | No |
Stored | Definitions in the agent store, created with runtime.Agents.CreateAsync(id, config), Studio, or HTTP | Yes |
A code agent lives in memory and is never written to the agent store. Its id is reserved: creating, updating, or deleting a stored agent with that id throws AgentDefinitionReadOnlyException. A code agent may carry process-local parts, such as a chat client instance, native functions, or delegates; AgentDefinition.Config is its portable part and AgentDefinition.ProcessLocal describes what that part leaves out. To edit one, store a copy of its portable part under a new id with runtime.Agents.CreateAsync(...); the process-local parts do not carry over. A stored agent has no process-local parts, and CreateAsync and UpdateAsync refuse a definition that has them (agent_definition_process_local).
One code agent is the default and runs inputs that name no agent: the only one registered, or the one registered with isDefault: true when there are several.
Any of them can answer a turn. Agents are independent of sessions and threads, so a thread keeps one history whichever agent answers:
var first = await runtime.RunAsync("Fix the failing test.");
await runtime.RunAsync("Review that change.", sessionId: first.SessionId, agentId: "reviewer");Each execution records the agent that ran it (ThreadExecutionStartedEvent.AgentId), and ThreadExecution.Models lists the provider and model pairs it called, in first-use order. The runtime builds every agent from its own definition plus the runtime's shared parts:
- The definition supplies instructions, model, harnesses, definition middleware, retry and error policy, PII protection, plan mode, goals, and its process-local parts.
- The runtime supplies stores, providers and secrets, host services, events, the execution owner, and every middleware registered on
AgentRuntimeBuilder, including permissions and the sandbox.
Shared middleware is one instance for every agent, started and stopped once with the runtime. It reads per-agent facts from the hook context. A middleware a definition implies or declares, such as retry from WithRetry(...), belongs to that agent only. Built agents are cached, reused across sessions and threads, and disposed with the runtime; their events reach runtime.Subscribe(...). Updating or deleting a stored definition through runtime.Agents retires its built agent, so the change takes effect on the next run, while a run already in progress finishes on the agent it started with.
Definitions are checked against runtime.Composition: at BuildAsync() for code agents, and on Validate, CreateAsync, and UpdateAsync for stored ones. A provider, harness, harness function, or middleware the composition does not have is refused with agent_provider_unknown, agent_provider_family_unsupported, agent_harness_unknown, agent_harness_function_unknown, or agent_middleware_unknown, naming the definition path.
Capability Map
| Capability | Use It For | Start Here |
|---|---|---|
| Providers and clients | Choosing model, audio, embedding, hosted-file, realtime, and other clients | Providers, Clients, And Secrets |
| Tools | Letting the model call C# functions | Tools, Functions, And Harnesses |
| Tool harnesses | Grouping related generated functions and capability metadata | Author A Tool Harness |
| Collapsed tools | Reducing model-facing tool overload with expandable containers | Collapsing And Containers |
| Client tools | Letting a UI, editor, app, or remote client execute a tool | Externally Executed Client Tools |
| Events | Rendering live output, timelines, traces, approvals, and diagnostics | Event Streams And Hierarchies |
| Sessions and threads | Durable conversation state, forks, replay, and thread-specific state | Sessions, Threads, And Events |
| Middleware | Cross-cutting runtime behavior around turns, iterations, tools, and threads | Middleware Lifecycle |
| Permissions | Interactive gates for tool/function execution and app-specific policy | Permissions Middleware |
| Content | Uploading bytes, preserving thread references, and resolving provider-facing content | Content Upload And Resolution |
| Subagents | Exposing specialist agents as tools with their own runtime policy | Subagents |
| Workflows | Explicit graph orchestration across agents and functions | Multi-Agent Overview |
| Hosting | HTTP commands, authoritative state, and resumable SSE for external clients | ASP.NET Core Hosting |
| Observability | Logging, OpenTelemetry, and usage tracking at agent and client layers | Logging And Telemetry |
| Evaluations | Batch, live, judge, safety, red-team, and report workflows | Evaluations Overview |
| Sandboxing | Environment-backed process placement, workspace binding, and isolation for command-capable tools | Sandboxing Overview |
Run Inputs And Outputs
The simplest input is a string:
var result = await runtime.RunAsync("Summarize this in one sentence.");
Console.WriteLine(result.Text);Use richer input events when the run needs multiple messages, binary content, explicit session/thread routing, or per-run configuration. UserMessagesInputEvent may also omit messages to resume an existing scoped thread with only run configuration; the thread must already have history.
AgentTurnResult.Text is the final concatenated assistant text. Do not treat it as the whole runtime record. Tool calls, permission prompts, retries, errors, reasoning, custom progress, audio artifacts, workflow node activity, and evaluation scores are event-stream concerns.
If the app needs a UI, trace, timeline, permission queue, or replay view, subscribe to events or use hosted streaming. See Render An Event Stream.
Extension Points
HPD has several extension points. Choose the one closest to the behavior you need:
| Need | Extension Point |
|---|---|
| Add or swap the model/audio/realtime backend | Provider or explicit client registration |
| Add one model-callable operation | [AIFunction] tool |
| Add a group of related operations | Tool harness |
| Hide and reveal a large tool surface | Collapsed harness |
| Add retrieval, policy, retry, formatting, telemetry, or content handling around the turn | Middleware |
| Add memory or dynamic context before the model call | Middleware plus app-owned storage or content storage |
| Store private runtime policy or progress | Middleware state |
| Ask the user or host for a decision during a run | Bidirectional events |
| Delegate to a specialist from the parent model | Subagent capability |
| Make the process deterministic and graph-shaped | Workflow |
| Serve clients outside the process | ASP.NET Core hosting |
Providers And Structured Output
Provider capabilities are not identical. Some providers expose response-format or JSON-schema options through provider config, and ONNX Runtime has HPD-owned structured tool calling that turns local model output into normal HPD function calls.
Treat structured output as a provider capability unless a higher-level HPD API is documented for your scenario. Check the provider page before promising typed JSON behavior in application code.
Start with:
State Model
HPD separates state into scopes:
| Scope | What Belongs There |
|---|---|
| Run | Per-call options, runtime middleware, temporary behavior |
| Thread | Conversation path, thread metadata, thread middleware state, thread event projection |
| Session | Session metadata, shared middleware state, thread tree, user/workspace grouping |
| Agent | Agent definition: instructions, clients, tools, definition middleware, process-local parts |
| Runtime | Stores, providers and secrets, shared middleware, events, the composition |
| Content | Uploaded or generated bytes and references, often scoped to a thread |
This is why thread-aware features such as compaction, audio projection, content upload, subagents, and permissions all need clear sessionId + threadId routing.
Trust Boundaries
Treat these as untrusted unless your application has verified them:
- user input
- model output
- function arguments selected by the model
- tool results from external systems
- retrieved documents and web content
- uploaded files
- custom events from clients
- stored session or thread data loaded from a backend
System instructions, permission policy, storage authorization, tenant checks, network controls, and sandbox configuration belong to the host application. HPD gives you hooks, stores, events, permissions, and sandboxing surfaces; your app still owns the product policy.
Use:
- Permissions Middleware for interactive tool gates
- Sandboxing Overview for process-execution boundaries
- Content Upload And Resolution for user bytes and provider-facing content
- Logging And Telemetry for sensitive-data choices
- LLM Judges And Safety and Red Team for review signals
What Not To Assume
Do not assume:
- every provider supports the same content, tool, response-format, or streaming features
AgentTurnResult.Textincludes everything important that happened- function permission also controls every resource a tool body will access
- local file stores are production storage
- canonical delivery and replay preserve the same composed event value
- middleware
OnErrorAsyncobserves every terminal non-cancellation failure but does not roll back side effects - a hosted client can respond to an old permission request after the run has moved on
The runtime is powerful because these concerns are explicit. Keep the boundary visible in app code and docs.