Thread History And Forking
Threads let one session hold multiple replayable paths. A thread can be created directly, forked from a message id or the pre-message root, updated for UI metadata, listed with thread-tree information, and deleted subject to graph-integrity and active-mutation rules.
There are two public ways to work with threads:
- Direct in-process
AgentRuntimeAPIs, where your code calls methods on the runtime, which owns the session store. - ASP.NET Core hosted APIs, where clients use HTTP routes and DTOs exposed by
MapHPDAgent(...).
Direct Runtime API
Use direct APIs when your application owns the AgentRuntime:
var sessionId = await runtime.CreateSessionAsync("review-session");
await runtime.RunAsync(
"Draft the first answer.",
sessionId: sessionId,
threadId: "main");
var fork = await runtime.ForkThreadAsync(
sessionId,
sourceThreadId: "main",
newThreadId: "short-answer",
fromMessageId: messageId,
new ThreadForkOptions { Name = "Short answer", Tags = ["draft"] });
var forkId = fork.Target.ThreadId;
await runtime.CreateThreadAsync(
sessionId,
threadId: "notes",
name: "Notes",
description: "Scratch thread",
tags: ["scratch"],
metadata: new Dictionary<string, object?> { ["owner"] = "u-1" });Direct APIs use the runtime's in-memory session store unless AgentRuntimeBuilder configures another. CreateSessionAsync(...) creates an initial thread named main for convenience. CreateThreadAsync(...) and ForkThreadAsync(...) write the name, description, tags, and metadata with the new thread, so it is never visible without them. CreateThreadAsync(...) throws ThreadExistsException when the session already has that thread id, and SessionNotFoundException when the session does not exist. Retrying a fork with the same ThreadForkOptions.OperationId returns the same fork; retrying it with a different name, description, tags, metadata, or compaction throws thread_fork_operation_payload_conflict. When RunAsync(...) omits threadId, a one-thread session uses its sole thread, while an empty session creates main. Multiple threads make the omitted ID ambiguous. ForkThreadAsync(...) returns a ThreadForkResult; use fork.Target.ThreadId for the new thread id. It can also accept ThreadForkOptions for programmatic fork behavior such as fork compaction.
Branch Navigation
GetThreadGraphAsync(sessionId) returns a ThreadGraph: the session's thread descriptors and its fork groups. A fork group is one branch choice. It gathers a source thread and the forks that diverge from the same message, so a UI can show "‹ 2 / 3 ›" on that message:
var graph = await runtime.GetThreadGraphAsync(sessionId);
foreach (var group in graph?.ForkGroups ?? [])
{
foreach (var member in group.Members)
Console.WriteLine($"{group.Id}: {member.Thread.Key.ThreadId} at message {member.ChoiceMessageIndex}");
}A fork of a fork that branches at a message both share is grouped under the thread that first held that message, so every branch at one point of the conversation appears together. Each member's ChoiceMessageId and ChoiceMessageIndex name the message in that branch where the control belongs. The graph covers one session and reads only forks and their lineage in full. The hosted GET /sessions/{sessionId}/thread-graph route and the TUI return the same groups.
ASP.NET Core Hosted Routes
Thread routes are scoped by sessionId and threadId; threads belong to no agent. Only fork names an agent, with an optional agentId in its body, because that agent's definition supplies the fork's compaction defaults; omitted, the default agent's. In process, ThreadForkOptions.AgentId does the same.
| Operation | Route |
|---|---|
| List threads | GET /sessions/{sessionId}/threads |
| Get thread | GET /sessions/{sessionId}/threads/{threadId} |
| Create thread | POST /sessions/{sessionId}/threads |
| Fork thread | POST /sessions/{sessionId}/threads/{threadId}/fork |
| Update thread | PATCH /sessions/{sessionId}/threads/{threadId} |
| Delete thread | DELETE /sessions/{sessionId}/threads/{threadId}?recursive=false |
| Observe thread events | GET /sessions/{sessionId}/threads/{threadId}/events?after={appliedCursor} |
Hosted Create A Thread
Creating a thread accepts a CreateThreadRequest with a thread id plus optional name, description, tags, and metadata. If the thread id is blank, the service can generate one.
Creating a thread with an existing id returns a conflict. A thread created this way starts as its own path rather than a fork from another thread.
Hosted Fork From A Message
Forking accepts a ForkThreadRequest:
{
"newThreadId": "try-short-answer",
"fromMessageId": "message-id-to-fork-from",
"name": "Short answer",
"description": "A shorter response path",
"tags": ["draft"],
"metadata": {
"uiColor": "green"
}
}fromMessageId is optional. A string is an inclusive committed-message fork point; null creates a root fork before any source messages. If a supplied message id is not present on the source thread, the hosted API returns a validation error.
The new thread records its source thread and fork point. Persistent thread-scoped middleware state is copied to the new thread when the fork is committed and then evolves independently.
Hosted Update Thread Metadata
Thread updates accept optional name, description, tags, and metadata. Metadata is merged: values add or overwrite keys, and null removes keys.
Use thread metadata for UI labels, filters, annotations, and runtime hints that belong to a single path.
Delete Threads
main is not protected. It can be deleted when it has no children and no conflicting thread operation. Deleting the last thread leaves the session intact with zero threads. The next in-process run that omits a thread ID creates a fresh main thread.
DeleteThreadAsync throws ThreadHasChildrenException, with the ChildThreadIds, when the thread has forks and recursive is false. It throws ThreadExecutionActiveException, with the ThreadExecutionId, when the thread or a descendant has a live execution; nothing is deleted.
In the hosted API, deleting a thread with children returns 400 HasChildren unless recursive=true. Recursive deletion must also be enabled by server configuration; when it is disabled, a recursive delete of a thread with children returns 400 RecursiveDeleteDisabled. A thread with a live execution returns 409 ThreadExecutionActive.
Read Thread Events
Hosted clients open the thread observation route with their last successfully applied position. The SSE stream first yields canonical catch-up events and then remains attached for future commits. The cursor is the journal sequence number; for example, after=41 continues after sequence 41. Omitting after starts at sequence zero, where complete reconstruction begins.
In-process consumers use ISessionStore.ReadThreadEventsAsync(...) for finite, bounded cursor reads or ObserveThreadEventsAsync(...) for catch-up plus future commits. Both surfaces decode the same canonical AgentEvent values in ascending sequence order.
Thread descriptors, lists, and existence checks use storage-native metadata and do not project the complete journal. Full semantic reconstruction is an explicit projection operation.
For UI projection guidance, see Render An Event Stream. For storage and observation guarantees, see Canonical Thread Journal.
Thread History Compaction
Thread-history compaction appends THREAD_HISTORY_COMPACTION_CHECKPOINT to the journal. The journal keeps every source event, and the history projection applies the checkpoint, so clients can retain, collapse, or mark compacted ranges during hydration.
For the full model, see Compaction.
Forking After Compaction
Forking uses a message id from the thread. Use projected thread messages as the source of forkable message ids.
Fork And Compact
Fork compaction uses the shared compaction engine during the pre-commit fork hook. The target is compacted after source projection and before its initial journal is saved.
The source thread is unchanged. The target thread starts with the compacted semantic history and a THREAD_HISTORY_COMPACTION_CHECKPOINT describing the fork result.
Hosted ForkThreadRequest.Compaction accepts the same inherit, disabled, or enabled union as ThreadForkOptions.Compaction. Omitting it inherits the server-side configuration.
The middleware hook for this phase is BeforeThreadForkCommitAsync. It receives the source thread, the in-memory target thread, the fork point, and ThreadForkOptions. This is the place for middleware that needs to change the target thread before it becomes durable. After the fork is committed, durable thread events such as THREAD_CREATED with fork metadata and later THREAD_UPDATED changes describe the committed thread state; they are not mutation hooks.