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.
| Store | Default | Holds |
|---|---|---|
| Session | InMemorySessionStore | Sessions, threads, and their event history |
| Content | InMemoryContentStore | Uploads and generated artifacts |
| Agent | InMemoryAgentStore | Stored 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
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:
dotnet runRun it again and inspect the .hpd-data folder. The stores contain the durable state created by the run.
find .hpd-data -maxdepth 3 -type fYou 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:
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:
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:
| Data | Contract | Implementation and package | Registration |
|---|---|---|---|
| Sessions, threads, and canonical event journals | ISessionStore | HpdBaseSessionStore in HPD-Agent.Stores.HpdBase | AddHpdBaseSessionStore(eventCodec) |
| Stored agent definitions | IAgentStore | HpdBaseAgentStore in HPD-Agent.Stores.HpdBase | AddHpdBaseAgentStore() |
| Evaluation scores and runs | IScoreStore | HpdBaseScoreStore in HPD-Agent.Evaluations.HpdBase | AddHpdBaseEvaluationStore() |
| Evaluation datasets | IDatasetStore | HpdBaseDatasetStore in HPD-Agent.Evaluations.HpdBase | AddHpdBaseDatasetStore(...) |
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.