Skip to content

ASP.NET Core Hosting ​

HPD Agent hosting exposes sessions, threads, stored agent definitions, authoritative runtime state, input submission, resumable committed events, content, and middleware response endpoints through ASP.NET Core minimal APIs.

The core hosting model is:

text
AddHPDAgentRuntime(...) hosts one AgentRuntime, built from a runtime recipe that registers its agents
MapHPDAgent(...) maps the complete HTTP surface for that runtime
MapHPDAgentRuntimeApi(...) maps the application runtime surface
MapHPDAgentClientToolProvidersApi(...) maps client-tool attachment routes
MapHPDAgentAdministrationApi(...) maps stored definitions and administration
agentId + sessionId + threadId selects the agent and thread an input runs on

AddHPDAgentRuntime(name, configure) takes a name and a runtime recipe. configure is an Action<AgentRuntimeBuilder>: the same recipe a console app writes, with the runtime's agents (AddAgent(id, config)) and its stores, secrets, permissions, sandbox, and shared middleware. Hosting applies the application's generated provider, event, and input composition and its service provider to the builder, runs the recipe once, and calls BuildAsync() to build one AgentRuntime, which serves every session and thread of that registration. Agent settings such as the provider, instructions, and harnesses belong on each agent's AgentConfig. Stored agents are created through the administration API.

The name selects the runtime when its endpoints are mapped and keys its services. It is not an agent id: agents are only the ones the recipe registers and the ones stored in the runtime's agent store.

Use Hosted Runtimes And Agents for the lifecycle difference between the runtime, an agent definition, a session, and a thread, and The Runtime And Its Agents for code and stored agents.

Minimal Setup ​

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

var builder = WebApplication.CreateBuilder(args);

var assistant = new AgentConfig()
    .WithOpenAI(model: "gpt-5-mini")
    .WithInstructions("You are a concise helpful assistant.");

builder.Services.AddHPDAgentRuntime("assistant", runtime => runtime
    .AddAgent("assistant", assistant));

var app = builder.Build();

app.MapGroup("/hpd").MapHPDAgentRuntimeApi("assistant");

app.Run();

When the host starts, hosting builds the assistant runtime. Its one code agent, assistant, is its default agent. MapHPDAgentRuntimeApi maps the application-facing session, thread, execution, capability, composition, content, streaming, runtime-state, and middleware-response routes.

Agents And The Default Agent ​

The recipe registers the runtime's code agents. One registered code agent is the default agent, the one that runs inputs that name no agent. With several, mark exactly one isDefault: true:

csharp
builder.Services.AddHPDAgentRuntime("support", runtime => runtime
    .WithFileSessionStore("App_Data/support/sessions")
    .AddAgent("assistant", assistant, isDefault: true)
    .AddAgent("planner", planner));

A recipe that registers no code agent hosts a runtime that serves only stored agents:

csharp
builder.Services.AddHPDAgentRuntime("studio", runtime => runtime
    .WithFileSessionStore("App_Data/studio/sessions")
    .WithAgentStore(new JsonAgentStore("App_Data/studio/agents")));

That runtime has no default agent, so every input names its agent. An input or fork that names none returns 400 with the validation code AgentIdRequired.

Definitions From Files And Configuration ​

A definition read from JSON or YAML, or bound from an IConfiguration section, is registered like any other code agent. The recipe overload that takes the application's IServiceProvider reaches the generated ProviderComposition, which binds provider-specific payloads in the definition:

csharp
using HPD.Agent.Providers;
using HPD.Agent.Serialization;

builder.Services.AddHPDAgentRuntime("assistant", (services, runtime) =>
{
    var providers = services.GetRequiredService<ProviderComposition>();
    runtime
        .WithFileSessionStore("App_Data/assistant/sessions")
        // JSON or YAML, read when the host starts. Relative paths in it resolve against its directory.
        .AddAgent(
            "assistant",
            HpdAgentConfigSerializer.ReadFileWithSource("agents/assistant.yaml", providers)!,
            isDefault: true)
        // Bound from an IConfiguration section.
        .AddAgent("reviewer", HpdAgentConfigSerializer.Deserialize(
            builder.Configuration.GetSection("Agents:Reviewer"), providers)!);
});

The file or section holds the whole definition, including its clients.Chat provider and model. A file without provider-specific payloads can also be read with HpdAgentConfigSerializer.ReadFileWithSource(path) in the plain recipe.

The Unnamed Runtime ​

Each registration has an unnamed overload, AddHPDAgentRuntime(runtime => ...). MapHPDAgent() and the other mapping methods without a name map it.

Route Prefix ​

Compose the prefix with normal ASP.NET routing:

csharp
var hpd = app.MapGroup("/api/hpd");
hpd.MapHPDAgentRuntimeApi("assistant");

With this prefix, a sessions request becomes POST /api/hpd/sessions.

MapHPDAgent(...) is the complete composite mapping. It includes the runtime, client-tool, and stored-definition surfaces. Its HPDAgentEndpointOptions overload sets a RoutePrefix and turns individual surfaces off with flags such as MapAgents, MapClientToolProviders, or MapContent:

csharp
app.MapHPDAgent("assistant", options =>
{
    options.RoutePrefix = "/api/hpd";
    options.MapClientToolProviders = false;
});

Mapping Surfaces And Authorization ​

Map each surface onto a separate route group so it can receive independent authorization:

csharp
builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("AgentUser", policy => policy.RequireAuthenticatedUser());
    options.AddPolicy("AgentAdmin", policy => policy.RequireRole("AgentAdmin"));
});

var app = builder.Build();

app.UseAuthentication();
app.UseAuthorization();

var hpd = app.MapGroup("/hpd");

hpd.MapHPDAgentRuntimeApi("assistant")
   .RequireAuthorization("AgentUser");

hpd.MapGroup("/client-tools")
   .MapHPDAgentClientToolProvidersApi()
   .RequireAuthorization("AgentUser");

hpd.MapGroup("/admin")
   .MapHPDAgentAdministrationApi("assistant")
   .RequireAuthorization("AgentAdmin");

RequireAuthorization(...) is standard ASP.NET Core endpoint metadata. You must also register authentication and authorization services, define the named policies, and add the corresponding middleware. The HPD library does not choose an authentication scheme.

MapHPDAgentClientToolProvidersApi() includes the development attachment route, which does not require an IClientToolProviderConnectionAuthorizer. Production application-gateway deployments should map MapAuthorizedHPDClientToolProviderConnection(...) instead.

Named Runtimes ​

Use named registrations when one ASP.NET Core app needs independent storage, policies, or API boundaries:

csharp
builder.Services.AddHPDAgentRuntime("support", runtime => runtime
    .AddAgent("assistant", new AgentConfig()
        .WithOpenAI(model: "gpt-5-mini")
        .WithInstructions("You help with support requests.")));

builder.Services.AddHPDAgentRuntime("research", runtime => runtime
    .AddAgent("researcher", new AgentConfig()
        .WithOpenAI(model: "gpt-5-mini")
        .WithInstructions("You help with research tasks.")));

app.MapGroup("/support-agent").MapHPDAgentRuntimeApi("support");
app.MapGroup("/research-agent").MapHPDAgentRuntimeApi("research");

The registration name selects the server-side runtime. The URL prefix is whatever you configure. Agent ids come from the recipe, and the same agent id can appear in several runtimes. When a definition has no Name, its name is its agent id. Stored agents are created through that runtime's POST /agents route.

Hosted Runtime Contents ​

Each registration builds one AgentRuntime from its own recipe. That runtime owns:

  • the session store
  • the agent store
  • the content store
  • its code agents: the agents the recipe adds with AddAgent(...), one of which is the default agent, and harness subagents declared in code
  • the stored agents in its agent store

Configure stores in the recipe, exactly as a console app does:

csharp
builder.Services.AddHPDAgentRuntime("assistant", runtime => runtime
    .AddAgent("assistant", definition)
    .WithFileSessionStore("App_Data/assistant/sessions")
    .WithAgentStore(new JsonAgentStore("App_Data/assistant/agents")));

WithFileSessionStore(path) selects a segmented FileSessionStore and a file-backed content store beside it. WithSessionStore(store), WithAgentStore(store) or WithAgentStore(path), and WithContentStore(store) supply any implementation. With no store configured, the runtime creates and owns in-memory session, agent, and content stores. Code agents are never written to the agent store; it holds only stored agents.

In-memory is a valid implementation, not an error; deployment policy decides whether an ephemeral store is acceptable.

To use the same store objects across runtimes, pass the same instances to each recipe.

HPD Base-Backed Stores ​

For restart-durable session journals and stored agent definitions, use HPD-Agent.Stores.HpdBase with HPD Base. The example below selects HPD Base's SQLite provider and writes its database to data/hpd-agent.db:

csharp
using HPD.Agent.Serialization;
using HPD.Agent.Stores.HpdBase;
using HPD.Base;
using HPD.Base.Sqlite;

if (!AgentEventCompositionHost.TryGetDefaultApplication(out var events))
    throw new InvalidOperationException("A generated application event composition is required.");

builder.Services.AddHPDBase(hpd => hpd
    .AddHpdAgentStores()
    .UseStore(SqliteStore.Configure(options =>
    {
        options.DataSource = "data/hpd-agent.db";
    })));

builder.Services.AddHpdBaseAgentStore();
builder.Services.AddHpdBaseSessionStore(events.Codec);

builder.Services.AddHPDAgentRuntime("assistant", runtime => runtime
    .AddAgent("assistant", definition));

var app = builder.Build();

A runtime uses the session and agent stores registered in the application's services unless its recipe names others with WithSessionStore or WithAgentStore.

HPD Base is the storage layer; SQLite is the concrete provider selected here. HPD Agent's adapter translates its session and agent-store contracts into HPD Base collections, while HPD Base handles persistence through the selected provider. The first startup may create or update the schema for the registered collections. Keep the database file in persistent application storage and include it in the application's backup plan.

This SQLite setup stores session metadata, thread records, canonical event blocks and identities, progressive thread deltas, and stored agent definitions. It does not store uploaded content or generated artifacts: those use the agent's separate IContentStore.

The HPD Base session store must use the same AgentEventCodec as the host's event composition. Use this path when restart durability, centralized storage, or HPD Base-backed backup and inspection matter; use WithFileSessionStore(path) for a simple local filesystem deployment.

SQLite is the provider shown in the current HPD Agent setup. Other HPD Base providers can be selected through the same UseStore(...) boundary as they become available; the HPD Agent store adapters are designed to sit above that provider choice.

This package covers ISessionStore and IAgentStore. HPD Base adapters for evaluation scores/runs (IScoreStore) and datasets (IDatasetStore) are provided separately by HPD-Agent.Evaluations.HpdBase; see Datasets and Reports. The packages do not currently provide an HPD Base IContentStore adapter. Configure a file-backed or application-provided content store when uploaded or generated content must survive restarts.

Created-resource Location headers include the mapped route prefix. Content uploads use the agent's content store, scoped to the thread. Without a configured content store it is in-memory, so do not treat uploaded content as durable unless a durable content store is configured.

Runtime Lifetime ​

Each registration hosts one AgentRuntime. A hosted service builds it when the host starts and disposes it when the host stops, so shared middleware start and stop hooks run once per process. Building validates every code agent's definition against the runtime's validation limits (set with WithDefinitionValidationLimits(...)) and against the runtime's composition: a provider, harness, harness function, or middleware the composition does not have fails the host's start with a ValidationException whose errors start with agent_provider_unknown, agent_provider_family_unsupported, agent_harness_unknown, agent_harness_function_unknown, or agent_middleware_unknown. Building builds no agent; each agent is built the first time it runs or is inspected, then cached.

That one runtime serves every session and thread. Different threads run concurrently; one thread runs one input at a time. An input's agentId selects the answering agent on the same runtime: a code agent the recipe registered, a harness subagent declared in code, or a stored agent. An input that names no agent runs on the default agent; in a runtime without one it returns 400 AgentIdRequired. An unknown agentId, including the runtime's own name, returns 404. Runtime requests never synthesize or persist a definition.

The recipe is applied once, to the runtime, and is not stored in /agents. Shared middleware, stores, secrets, and provider authentication registered in the recipe belong to the runtime and reach every agent it runs. Settings that shape an agent, such as WithOpenAI(...) or WithInstructions(...), are AgentConfig methods and belong to the definition they are called on; a stored agent carries its own clients.Chat and instructions. An updated stored agent takes effect on its next run.

Code that needs the runtime in-process resolves HPDAgentHost from dependency injection. The first registration is available unkeyed; every registration is also keyed by its name:

csharp
using HPD.Agent.Hosting.Lifecycle;

app.MapPost("/summarize", async (HPDAgentHost host, string text) =>
{
    var result = await host.Runtime.RunAsync(text, agentId: "summarizer");
    return result.Text;
});

host.Runtime is the registration's AgentRuntime, host.Store its session store, host.Options its transport options, and host.IsStarted reports whether the hosted service has built the runtime. host.Name is the registration name. Reading host.Runtime before the host starts throws InvalidOperationException. Named runtimes resolve with [FromKeyedServices("research")] HPDAgentHost host.

Adapters that host a runtime without AddHPDAgentRuntime(...), such as bots and the TUI, construct the handle directly. new HPDAgentHost(runtime) hosts a runtime that is already built; new HPDAgentHost(name, build) takes a Func<CancellationToken, Task<AgentRuntime>> and builds the runtime when StartAsync() is called. Either way the host disposes the runtime when it is disposed:

csharp
await using var host = new HPDAgentHost("assistant", ct => new AgentRuntimeBuilder()
    .WithFileSessionStore("App_Data/assistant/sessions")
    .AddAgent("assistant", assistant)
    .BuildAsync(ct));

await host.StartAsync();

Transport behavior is set with HPDAgentHostTransportOptions:

csharp
builder.Services.AddHPDAgentRuntime(
    "assistant",
    runtime => runtime.AddAgent("assistant", definition),
    new HPDAgentHostTransportOptions { AllowRecursiveThreadDelete = true });

AllowRecursiveThreadDelete permits DELETE …/threads/{id}?recursive=true. Without it, a recursive delete of a thread that has children returns 400 RecursiveDeleteDisabled, and a childless thread is still deleted.

Runtime Scope ​

Runtime routes name the thread:

text
/sessions/{sessionId}/threads/{threadId}/...

That scope is used by HTTP input, state, cancellation, resumable SSE, thread executions, and the bidirectional response route. Input names the agent that runs it in its body. TUI hosted runtimes and bot adapters should map their UI or platform identity into the same runtime scope before sending input or responses.

Each thread has one active execution at a time, owned through the session store's execution controller. A user message sent to a busy thread joins the running turn or starts the next one; other work on a busy thread returns 409 ThreadExecutionActive.

Hosted clients should load /state to restore activeExecution and pendingRequests, then open /events?after={sequence}. A client without local projection starts at sequence zero and rebuilds the complete conversation incrementally. See Hosted Lifecycle And Recovery.

Built for production .NET agent applications.