Skip to content

The Runtime And Its Agents ​

The runtime runs agents; an agent is a definition.

An agent is an AgentConfig: its name, instructions, model, tools, and policies. It is the same type whether it is written in code, read from a JSON or YAML file, kept in the agent store, or edited in Studio. You never build or hold an agent object.

The AgentRuntime runs agents. There is one per application or hosted runtime. It 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) and answers every runtime-wide question.

text
AgentConfig            one agent's definition: data, plus process-local parts only code can supply
AgentRuntimeBuilder    composes the runtime and registers code agents
AgentRuntime           runs agents and owns everything they share
  .RunAsync(...)       runs an input on the agent it names, or on the default agent
  .Subscribe(...)      observes the events of every agent it runs
  .Agents              the definitions it runs: code and stored
  .Composition         what it can run agents with
  .Executions          the runs on each thread, with the agent and models each used
  .Content             uploads and artifacts
  .SessionStore        the session store every agent runs against

Define Agents, Build A Runtime ​

Write each agent with AgentConfig and its With... methods. Each method sets members of the definition and returns the same AgentConfig, so the calls chain. Register the agents on an AgentRuntimeBuilder, together with the runtime-wide settings, and await BuildAsync():

csharp
using HPD.Agent;
using HPD.Agent.Providers.Anthropic;
using HPD.Agent.Providers.OpenAI;

var reviewer = new AgentConfig { Name = "Reviewer" }
    .WithAnthropic("claude-sonnet-4-5")
    .WithInstructions("Review diffs. Point out bugs before style.")
    .WithRetry(retry => retry.ModelRetries.MaxRetries = 2);

var planner = new AgentConfig { Name = "Planner" }
    .WithOpenAI("gpt-5-mini")
    .WithInstructions("Plan releases as numbered steps.");

await using var runtime = await new AgentRuntimeBuilder()
    .WithFileSessionStore("./sessions")
    .AddAgent("reviewer", reviewer, isDefault: true)
    .AddAgent("planner", planner)
    .BuildAsync();

var review = await runtime.RunAsync("Review the change in PR 42.");
await runtime.RunAsync("Plan the release.", sessionId: review.SessionId, agentId: "planner");

The settings divide by owner:

On AgentConfig (one agent)On AgentRuntimeBuilder (every agent)
Name, instructions, provider and model (WithOpenAI, WithAnthropic, WithProvider, ...)Session, agent, content, and skill stores
Tool harnesses and tools (WithToolHarness<T>, WithTool<T>, WithNativeFunction)Host services (WithServiceProvider), provider registry, secrets
Retry, circuit breaker, function timeout, error formatting and tracking, PII protectionLogging, telemetry, tracing
Permission overrides (RequirePermissionFor, DisablePermissionFor)Shared middleware (WithMiddleware(instance)), permissions (WithPermissions), sandbox, client tools, evaluators
Middleware a definition declares (WithMiddleware<T>(config))Event composition, durability, and subscriptions
Goals, plan mode, user questions, compaction, reasoning, audio, MCP, OpenAPIDefinition validation limits, model catalog, tool harness catalogs
Process-local parts: a chat client instance, client wrappers, native functions, delegatesAgents (AddAgent)

A setting on the definition belongs to that agent only. When the runtime builds an agent, it derives the parts the definition implies, such as RetryMiddleware from WithRetry(...), PIIMiddleware from WithPIIProtection(...), or the plan tools from WithPlanMode(...), from that definition alone. Retry configured for the reviewer never runs for the planner, and a stored agent with the same settings gets the same parts. A shared middleware instance registered on the runtime builder runs for every agent, unless the agent's definition declares or implies a middleware of the same type, which takes its place for that agent.

BuildAsync() is the only way to build a runtime. A builder builds one runtime.

Code Agents And Stored Agents ​

The runtime knows two kinds of definition. runtime.Agents reads both as AgentDefinition values:

Code agentStored agent
Comes fromAddAgent(id, config), a harness subagent, or a workflow nodeThe agent store: runtime.Agents.CreateAsync(id, config), POST /agents, or Studio
SourceCodeStored
LivesIn memory, for the runtime's lifetimeIn the agent store
EditableNo: read-onlyYes: UpdateAsync, DeleteAsync
Process-local partsAllowedRefused

A code agent is never written to the agent store. Its id is reserved: creating, updating, or deleting a stored agent with that id throws AgentDefinitionReadOnlyException, and the HTTP routes answer 409 agent_definition_read_only. AddAgent keeps its own copy of the definition (AgentConfig.Clone()), so later changes to the AgentConfig object do not reach the runtime. A definition read from a file registers the same way; pass the LoadedAgentConfig from HpdAgentConfigSerializer.ReadFileWithSource(...) so relative paths in it resolve against the file's directory:

csharp
var writer = HpdAgentConfigSerializer.ReadFileWithSource("agents/writer.yaml")!;

var builder = new AgentRuntimeBuilder().AddAgent("writer", writer);

A stored agent is created, changed, and deleted while the runtime runs. Updating or deleting one retires its built agent, so the next run builds from the new definition, while a run already in progress finishes on the agent it started with.

csharp
foreach (var definition in await runtime.Agents.ListAsync())
    Console.WriteLine($"{definition.Id} ({definition.Source}){(definition.IsDefault ? " default" : "")}");

await runtime.Agents.CreateAsync("summarizer", new AgentConfig { Name = "Summarizer" }
    .WithOpenAI("gpt-5-mini")
    .WithInstructions("Summarize in three bullets."));

await runtime.RunAsync("Summarize the incident report.", agentId: "summarizer");

ListAsync returns code agents first (the default agent, then the others by id), then stored agents by id. GetAsync(id) returns one definition or null. Validate(config) returns the errors that would keep a definition from being stored, without reading storage.

Process-Local Parts ​

Some parts of a code agent cannot be serialized: a chat client instance (WithChatClient), client wrappers (UseChatClientMiddleware and the other families), a chat options delegate (WithOptionsConfiguration), native functions (WithNativeFunction), harness instances (WithToolHarness<T>(instance)), capability sources (AddCapabilitySource, MCP, and OpenAPI sources), retry and detector delegates, and a literal API key passed to a provider method. They are process-local parts of the definition. Every agent the runtime builds from the definition gets them, and they never leave the process.

AgentDefinition.Config is a code agent's portable part: an independent copy with the process-local parts left out, so a definition can always be serialized and sent over HTTP. AgentDefinition.ProcessLocal describes each part the portable part leaves out, without running user code and without secret values:

csharp
var reviewer = await runtime.Agents.GetAsync("reviewer");

foreach (var part in reviewer!.ProcessLocal)
    Console.WriteLine($"{part.Path} [{part.Kind}] {part.Description}");
// clients.Chat.override [client] ...
// functions[0] [function] ...

Each ProcessLocalPart has a Path (such as clients.Chat.override or functions[0]), a Kind (one of the ProcessLocalPartKinds values: client, clientMiddleware, chatOptions, credential, function, capabilitySource, mcpOptions, audio, harnessInstance, harnessContext, harnessDependency, harnessMiddlewareOverride, skillSource, skillStore, retryStrategy, errorDetector, piiDetector, imageStrategy), a one-line Description, and Details such as the type, provider, model, or method. A credential reports its provider and that a literal key is set, never the key. A stored agent's list is empty.

Copies of a definition follow two rules. AgentConfig.Clone() copies everything and keeps the process-local parts by reference. AgentConfig.ToPortable() is the copy that can leave the process; it throws an AgentRunConfigurationException with the code RuntimeOnlyProviderConfiguration, naming the path, when a process-local part is set. Serializing a definition with HpdAgentConfigSerializer refuses the same way.

Duplicate A Code Agent As A Stored Agent ​

A code agent is read-only. To edit one, store a copy of its portable part under a new id:

csharp
var source = await runtime.Agents.GetAsync("reviewer");

await runtime.Agents.CreateAsync("reviewer-draft", source!.Config);

foreach (var part in source.ProcessLocal)
    Console.WriteLine($"Not copied: {part.Path} ({part.Description})");

The copy is a stored agent. The process-local parts do not carry over, so a code agent whose chat client is an instance needs a provider on the copy before it can run. CreateAsync and UpdateAsync refuse a definition that still carries process-local parts with an AgentDefinitionProcessLocalException whose errors start with agent_definition_process_local and name each path. Studio's Duplicate as stored agent does the same and lists the parts that stay behind.

The Default Agent ​

The default agent runs inputs that name no agent:

  • When one code agent is registered, it is the default.
  • When several code agents are registered, exactly one must be registered with isDefault: true. None marked, or more than one, and BuildAsync() throws InvalidOperationException.
  • A runtime with no code agents has no default agent. Every input names its agent; an input that names none throws NoDefaultAgentException (an InvalidOperationException), and the hosted input route returns 400 AgentIdRequired.

A hosted runtime follows the same rule: its default agent is one of the code agents its AddHPDAgentRuntime(...) recipe registers, and the runtime's name is not an agent id. A multi-agent workflow's first node is the default agent of the workflow's runtime.

An input that names an agent runs that agent, whichever agent ran the thread before: a thread keeps one history, and any agent can answer a turn. Control input aimed at a running execution, such as a permission response, reaches the agent that runs that execution.

When Agents Are Built ​

text
BuildAsync()
  1. the composition is fixed           providers, tool harnesses, middleware, events, inputs
  2. every AddAgent is registered       code-owned, read-only, id reserved; one is the default
  3. every code definition is checked   against its limits and the composition, without building an agent
  4. shared middleware start            BeforeStartAsync and AfterStartedAsync, once
first RunAsync or InspectCapabilitiesAsync for an agent id
  5. that agent is built                from its definition and the runtime's shared parts, then cached
runtime.Agents.UpdateAsync or DeleteAsync (stored agents only)
  6. the built agent is retired         the next use builds the new definition
DisposeAsync()
  7. shared middleware stop; every built agent is disposed

No agent is built that is never used. The default agent is built lazily like the others.

Mistakes surface at three points:

WhenWhat failsHow
BuildAsync()A code definition's shape or limits; a provider, harness, harness function, or middleware the composition does not have; MCP declarations; an ambiguous default agentValidationException whose Errors start with their codes, or InvalidOperationException
First use of an agentBuilding the agent: a provider rejecting its options, a missing harness dependency, a skill that references a harness outside the composition, a skill store selectionruntime.RunAsync(...) throws the build error unchanged; runtime.InspectCapabilitiesAsync(agentId) wraps it in AgentBuildFailedException (500 agent_build_failed over HTTP)
A run that needs a clientA missing credential, model, or provider configurationA typed setup exception implementing IClientSetupFailure

Credentials are resolved when a run first needs a provider client, so a runtime builds without one.

What The Runtime Can Run With ​

runtime.Composition is what the runtime was built with, captured once by BuildAsync(). Reading it never builds an agent and never reads storage.

MemberContents
ProvidersProviderDescriptor: key, display name, aliases, client families, documentation link, the secret names it reads, and models when the runtime has a model catalog
ToolHarnessesToolHarnessDescriptor: exact activation identity, name, description, inherited harness identities, the functions it declares (name, description, whether it needs approval), and its settings type
MiddlewareMiddlewareDescriptor: identity, name, settings type, and whether it keeps session or thread state
EventsThe runtime's event catalog and its digest
InputsThe runtime's input catalog and its digest

The providers are those of the application's generated provider composition, one per referenced provider package. The harnesses and middleware are the generated registrations loaded in the process, plus the assemblies WithToolHarnessCatalogFrom<T>() adds. Provider models come from the catalog given to WithProviderModelCatalog(...), or WithModelsDev(...) from HPD-Agent.ModelsDev; without one, each provider's model list is empty.

csharp
foreach (var provider in runtime.Composition.Providers)
    Console.WriteLine($"{provider.Key}: {string.Join(", ", provider.Families)}");

foreach (var harness in runtime.Composition.ToolHarnesses)
    Console.WriteLine($"{harness.Identity} ({harness.Functions.Count} functions)");

Definitions Are Checked Against The Composition ​

Every definition is checked against the composition: each code agent at BuildAsync(), a stored agent on Validate, CreateAsync, and UpdateAsync, and every agent again when it is built.

PathRuleError code
clients.{Family}.provider.keyA provider of the composition, by key or alias, ignoring case, unless the family has a process-local clientagent_provider_unknown
clients.{Family}.provider.keyThat provider implements the familyagent_provider_family_unsupported
toolHarnesses[i].nameThe exact activation identity (Assembly:Namespace:Name) of a harness of the compositionagent_harness_unknown
toolHarnesses[i].functions[j]A function, skill, subagent, workflow, or capability source the harness declaresagent_harness_function_unknown
middlewares[i].nameA middleware of the compositionagent_middleware_unknown

Each error starts with its code (the AgentCompositionErrorCodes constants), names the path, and ends with Did you mean '...'? when a valid name is close, such as a harness's class name for its identity:

text
agent_harness_unknown: 'toolHarnesses[0].name' names harness 'GitHarness', which is not the exact activation identity of a harness of the runtime's composition. Did you mean 'MyApp:MyApp.Tools:GitHarness'?

Harness references match exact identities only; WithToolHarness<T>() writes T's identity for you. Over HTTP, a refused definition is 400 with validation errors keyed by these codes.

Each Run Records The Models It Used ​

runtime.Executions reads each thread's runs as ThreadExecution values. ThreadExecution.AgentId is the agent that ran it, and ThreadExecution.Models lists the distinct ThreadExecutionModel(ProviderKey, ModelId) pairs of its model calls and provider operations, in the order the run first used them. A run that switches models through AgentRunConfig.Clients lists each one. Hosted ThreadExecutionDto values carry the same list as models.

csharp
var runs = await runtime.Executions.QueryAsync(new ThreadExecutionQuery("reviewer", SessionId: null, MaxCount: 10));

foreach (var run in runs)
    Console.WriteLine($"{run.ThreadExecutionId}: {string.Join(", ", run.Models.Select(m => $"{m.ProviderKey}/{m.ModelId}"))}");

Where Runtimes Come From ​

  • Console and services: new AgentRuntimeBuilder()...BuildAsync(), as above.
  • ASP.NET Core: AddHPDAgentRuntime(name, runtime => ...) applies the recipe, agents included, to the registration's AgentRuntimeBuilder. HPDAgentHost.Runtime is that runtime. See Hosted Runtimes And Agents.
  • Subagents: a harness subagent runs on its parent's runtime. SubAgent.FromConfig(...) registers its definition as a code agent; SubAgent.FromAgentId(...) names any agent the runtime knows: a code agent or a stored agent. See Subagents.
  • Multi-agent workflows: each workflow builds one runtime on its first execution and registers every node definition under its node id, so node ids are agent ids. A WorkflowHostBinding adjusts each node definition with ConfigureAgent(identity, definition) and the workflow's runtime with ConfigureRuntime(workflowName, builder). See Build A Workflow.

Built for production .NET agent applications.