Skip to content

Save Sessions And State ​

Persistence lets sessions, threads, agent definitions, and content survive process restarts.

Default Stores ​

HPD Agent supplies in-memory storage automatically when your app leaves storage at its defaults.

StoreDefaultHolds
SessionInMemorySessionStoreSessions, threads, and their event history
ContentInMemoryContentStoreUploads and generated artifacts
AgentInMemoryAgentStoreStored agent definitions

The runtime keeps the agents you register with AddAgent in memory and never writes them to the agent store. The agent store holds stored agents: definitions created at run time through runtime.Agents or the hosted agent routes, which the runtime can run and stored subagents can name. ASP.NET Core hosting supplies all three defaults per hosting profile. In-memory data lasts for the life of the process. Configure durable implementations for the data you want to keep across restarts.

Add Program.cs ​

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

var dataRoot = Path.Combine(Directory.GetCurrentDirectory(), ".hpd-data");

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

await using var runtime = await new AgentRuntimeBuilder()
    .WithFileSessionStore(Path.Combine(dataRoot, "sessions"))
    .WithAgentStore(Path.Combine(dataRoot, "agents"))
    .WithContentStore(new LocalFileContentStore(Path.Combine(dataRoot, "content")))
    .AddAgent("assistant", assistant)
    .BuildAsync();

var sessionId = "getting-started-persistence";
if (await runtime.SessionStore.LoadSessionAsync(sessionId) is null)
    await runtime.CreateSessionAsync(sessionId);
const string threadId = "main";

var result = await runtime.RunAsync(
    "Remember that my workspace name is Northstar.",
    sessionId,
    threadId);

Console.WriteLine(result.Text);
Console.WriteLine($"Saved session: {sessionId}");

Run it:

bash
dotnet run

Run it again and inspect the .hpd-data folder. The stores contain the durable state created by the run.

bash
find .hpd-data -maxdepth 3 -type f

You Succeeded If ​

You should see files under .hpd-data/sessions. .hpd-data/agents stays empty until you store an agent, and .hpd-data/content fills as the runtime stores uploads or artifacts.

What Happens ​

WithFileSessionStore(path) creates a segmented FileSessionStore from the application's generated event codec.

The session store saves session metadata and canonical thread journals. Messages, thread metadata, run lifecycle, and thread-scoped middleware state are projected from committed events. Explicitly configuring a session store enables canonical commit before hosted or replayable publication.

CreateSessionAsync(...) returns the new session ID and creates the default main thread. It throws when the session already exists, so the sample creates the session only on the first run and continues it on later runs.

runtime.SessionStore is the store the runtime runs against, the configured one or the in-memory store it owns. Read, search, and update session and thread data through its extensions:

csharp
var store = runtime.SessionStore;
var recent = await store.SearchSessionsAsync(new SessionSearch { Metadata = { ["user"] = "u-123" }, Take = 20 });
await store.UpdateSessionAsync(sessionId, new Dictionary<string, object?> { ["title"] = "Q3 analysis" });
await store.UpdateThreadAsync(sessionId, "main", name: "Analysis", tags: ["keep"]);

Search returns the most recently active sessions first. A null metadata value removes that key. Deleting and forking go through the runtime (DeleteSessionAsync, DeleteThreadAsync, ForkThreadAsync) because they check for active executions.

WithAgentStore(path) creates a JsonAgentStore.

The agent store saves stored agents: definitions created, updated, and deleted while the application runs. This matters for hosted agents, stored subagents, and systems where users edit or select agent definitions at runtime. The assistant registered with AddAgent is a code agent: it is read-only, lives in memory, and is never written to the store. To store a definition, create it through runtime.Agents and run it by id:

csharp
if (await runtime.Agents.GetAsync("reviewer") is null)
{
    await runtime.Agents.CreateAsync("reviewer", new AgentConfig()
        .WithOpenAI(model: "gpt-5-mini")
        .WithInstructions("Review the previous answer for accuracy and tone."));
}

var review = await runtime.RunAsync(
    "Review your last answer.",
    sessionId,
    threadId,
    agentId: "reviewer");

CreateAsync(...) validates the definition and refuses one with process-local parts, such as a chat client instance or a native function, because those cannot be serialized. A stored id cannot reuse a code agent's id.

WithContentStore(...) configures framework-managed content storage for uploads, artifacts, and internal content references.

LocalFileContentStore stores content bytes on disk. With WithFileSessionStore(path), content defaults to a local file store under path/content. The explicit content store in this example uses a separate directory.

Local Store Or Hosted Store ​

Use the file session store and JSON agent store for local development, samples, tests, and filesystem-oriented deployments.

For production hosting, place the same store responsibilities behind the storage layer you want to operate:

  • session and thread metadata
  • canonical thread journals, descriptors, indexes, and semantic projections
  • session-scoped and thread-scoped middleware state
  • agent definitions, if users can create or select agents at runtime
  • content bytes, hosted-file references, and metadata needed to resolve attachments

Treat local file stores as a development default unless your deployment model is designed around that filesystem. Production apps should make explicit choices for retention, backup, tenant boundaries, authorization, encryption, and content lifecycle.

FileSessionStore uses segmented journals, sparse indexes, lightweight descriptors, and rebuildable projections. See Canonical Thread Journal for the store contract and physical layout.

HPD Base Stores ​

HPD Agent currently provides HPD Base-backed implementations for these storage contracts:

DataContractImplementation and packageRegistration
Sessions, threads, and canonical event journalsISessionStoreHpdBaseSessionStore in HPD-Agent.Stores.HpdBaseAddHpdBaseSessionStore(eventCodec)
Stored agent definitionsIAgentStoreHpdBaseAgentStore in HPD-Agent.Stores.HpdBaseAddHpdBaseAgentStore()
Evaluation scores and runsIScoreStoreHpdBaseScoreStore in HPD-Agent.Evaluations.HpdBaseAddHpdBaseEvaluationStore()
Evaluation datasetsIDatasetStoreHpdBaseDatasetStore in HPD-Agent.Evaluations.HpdBaseAddHpdBaseDatasetStore(...)

The session and agent stores are configured in the ASP.NET hosting guide. Evaluation store setup, including the required dataset input codecs, is in Datasets and Reports. Use the same HPD Base application/provider configuration for the collections required by each package. The session adapter must receive the same AgentEventCodec as the host's event composition.

The hosting example currently selects HPD Base's SQLite provider and stores its database in a local .db file. HPD Agent's adapters define how sessions, threads, agent definitions, and evaluation records map to HPD Base collections; the selected HPD Base provider supplies the underlying persistence. The SQLite file must live on persistent storage if data should survive redeployments, and should be included in backups. Other HPD Base providers can use the same adapter layer when available.

These adapters do not currently provide an HPD Base implementation for IContentStore; content should use the documented file store or an application-provided implementation. See Content Upload and Resolution.

Next ​

Next: expose the runtime over HTTP in ASP.NET Hosting.

Optional: add behavior around the turn in Middleware.

Go deeper: see Sessions, Threads, And Events and Content Upload And Resolution.

Built for production .NET agent applications.