Skip to content

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:

text
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:

text
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 hooks

runtime.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.

csharp
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 runtime

The runtime answers every runtime-wide question:

MemberWhat 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.AgentsThe definitions it runs: list, get, validate, and create, update, or delete stored ones
runtime.CompositionWhat it can run agents with: providers, tool harnesses, middleware, events, and inputs
runtime.ExecutionsRuns per thread or per agent, each with the agent that ran it and the models it called
runtime.ContentUploads and artifacts in each thread's scope
runtime.SessionStoreThe 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: BeforeStartAsync and AfterStartedAsync run during BuildAsync(); BeforeStopAsync and AfterStoppedAsync run 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:

csharp
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:

SourceExamplesEditable
CodeAgents registered with AddAgent(id, config), and harness subagents declared with FromConfig or FromParentNo
StoredDefinitions in the agent store, created with runtime.Agents.CreateAsync(id, config), Studio, or HTTPYes

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:

csharp
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 ​

CapabilityUse It ForStart Here
Providers and clientsChoosing model, audio, embedding, hosted-file, realtime, and other clientsProviders, Clients, And Secrets
ToolsLetting the model call C# functionsTools, Functions, And Harnesses
Tool harnessesGrouping related generated functions and capability metadataAuthor A Tool Harness
Collapsed toolsReducing model-facing tool overload with expandable containersCollapsing And Containers
Client toolsLetting a UI, editor, app, or remote client execute a toolExternally Executed Client Tools
EventsRendering live output, timelines, traces, approvals, and diagnosticsEvent Streams And Hierarchies
Sessions and threadsDurable conversation state, forks, replay, and thread-specific stateSessions, Threads, And Events
MiddlewareCross-cutting runtime behavior around turns, iterations, tools, and threadsMiddleware Lifecycle
PermissionsInteractive gates for tool/function execution and app-specific policyPermissions Middleware
ContentUploading bytes, preserving thread references, and resolving provider-facing contentContent Upload And Resolution
SubagentsExposing specialist agents as tools with their own runtime policySubagents
WorkflowsExplicit graph orchestration across agents and functionsMulti-Agent Overview
HostingHTTP commands, authoritative state, and resumable SSE for external clientsASP.NET Core Hosting
ObservabilityLogging, OpenTelemetry, and usage tracking at agent and client layersLogging And Telemetry
EvaluationsBatch, live, judge, safety, red-team, and report workflowsEvaluations Overview
SandboxingEnvironment-backed process placement, workspace binding, and isolation for command-capable toolsSandboxing Overview

Run Inputs And Outputs ​

The simplest input is a string:

csharp
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:

NeedExtension Point
Add or swap the model/audio/realtime backendProvider or explicit client registration
Add one model-callable operation[AIFunction] tool
Add a group of related operationsTool harness
Hide and reveal a large tool surfaceCollapsed harness
Add retrieval, policy, retry, formatting, telemetry, or content handling around the turnMiddleware
Add memory or dynamic context before the model callMiddleware plus app-owned storage or content storage
Store private runtime policy or progressMiddleware state
Ask the user or host for a decision during a runBidirectional events
Delegate to a specialist from the parent modelSubagent capability
Make the process deterministic and graph-shapedWorkflow
Serve clients outside the processASP.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:

ScopeWhat Belongs There
RunPer-call options, runtime middleware, temporary behavior
ThreadConversation path, thread metadata, thread middleware state, thread event projection
SessionSession metadata, shared middleware state, thread tree, user/workspace grouping
AgentAgent definition: instructions, clients, tools, definition middleware, process-local parts
RuntimeStores, providers and secrets, shared middleware, events, the composition
ContentUploaded 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:

What Not To Assume ​

Do not assume:

  • every provider supports the same content, tool, response-format, or streaming features
  • AgentTurnResult.Text includes 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 OnErrorAsync observes 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.

Built for production .NET agent applications.