Skip to content

Label, branch and fork a session

View as Markdown

A session is a tree: s.Branch(ctx, entryID) moves the leaf back to any earlier entry so the next turn continues from there, s.Fork(ctx, entryID) copies the path up to an entry into a new, self-contained session, and s.Label(ctx, entryID, name) names an entry to come back to. Each is an appended entry or a new session; nothing is rewritten or deleted.

sessions/tree.go labels the end of the first turn, asks a second question, then branches back to the label, summarizing the abandoned turn:

sessions/tree.go
shipped := s.Leaf() // the first turn's end
if err := s.Label(ctx, shipped, "shipped"); err != nil {
return err
}
if err := send(ctx, s, "When was it delivered?"); err != nil {
return err
}
// Back to the label; the abandoned turn is summarized, not lost.
if err := s.Branch(ctx, shipped, thread.SummarizeLeft()); err != nil {
return err
}
if err := send(ctx, s, "Refund it instead."); err != nil {
return err
}
for _, m := range s.Context() {
fmt.Fprintf(w, "%s: %q\n", m.Role, m.Text())
}
path, err := s.Path(s.Leaf())
if err != nil {
return err
}
fmt.Fprintln(w, "path:", len(path), "entries; tree:", len(s.Entries()))

sessions/tree.go on GitHub

user: "Where is order 1234?"
assistant: "Order 1234 shipped on Tuesday."
user: "<weft-summary>\nThe user asked when order 1234 was delivered: Thursday.\n</weft-summary>"
user: "Refund it instead."
assistant: "I have started a refund for order 1234."
path: 7 entries; tree: 12

The second question and its answer are off the path: the model sees the summary in their place. The tree still holds them, so it has 12 entries against the path’s 7. In the demos, ids pins the ids for stable output and ctxWindow is thread.ContextWindow(128_000), the model’s context window (why).

s.Branch(ctx, e2): the session moves its leaf back to e2; the abandoned entries stay in the file.A session log holds e1 (user: Where is order 1042?), e2 (assistant: Shipped this morning.), e3 (user: And 5678?) and e4 (assistant: Still processing.). s.Branch(ctx, e2) appends a leaf entry pointing at e2; nothing is rewritten. The next write, e5 (user: Cancel 1042 instead.), attaches to e2, so the model's context is e1, e2, e5. e3 and e4 stay in the file, off the path.

Read the tree. s.Leaf() is the entry the next one attaches to ("" while the session is empty). s.Context() is what the model sees at the leaf: the message and custom-message entries on its path, branch summaries as marked summaries, the latest compaction applied, and weft.Repair last. s.Entries() is the whole tree in append order, abandoned branches included. s.Path(entryID) is one chain of parent links from a root to entryID, inclusive. Both return deep copies. Each entry is a sealed thread.Entry kind with a type discriminator on the wire (ExampleMessageEntry, ExampleSession_Path).

Branch appends a leaf entry pointing at entryID, and the model’s context is rebuilt from that path alone: nothing appended on the abandoned branch reaches it again. entryID may be any entry the session holds, on any branch; "" is the root, which restarts the conversation from nothing while the file keeps everything (the tree then has several roots). The context is rebuilt from the branch’s own path only; tools come from the agent, not the tree. Branching is a between-turns operation: while a turn runs it fails with thread.ErrBusy, because the turn’s transcript must land on the line it started on. A parked approval boundary is not a running turn, and branching away from it is the documented way out (ExampleSession_Branch). Branching back to the Leaf() taken before a failed turn is also how to retry it without its prompt twice in the context (Send turns › gotchas).

thread.SummarizeLeft(), the one thread.BranchOption, summarizes the branch being left (back to the common ancestor) into a branch_summary entry that the new branch’s context carries in its place. The summarizer runs under the session’s compaction chain, SummaryModel or the session’s own model, with the lock released; the navigation and the summary land in one batch. The example’s script answers the summary request with its third reply (ExampleSummarizeLeft).

A label is an appended thread.LabelEntry, a bookmark a UI lists and a later Branch or Fork can return to. It never enters the model’s context; entryID must be an entry the session holds and the name must not be empty. Read labels back from the tree:

sessions/tree.go
for _, e := range s.Entries() {
if l, ok := e.(thread.LabelEntry); ok {
fmt.Fprintln(w, "label:", l.Name, "→", l.Entry)
}
}

sessions/tree.go on GitHub

label: shipped → e_a3

The package example is ExampleSession_Label.

s.Fork(ctx, e2): a new session starts from e2; the original session is untouched.Session A holds e1, e2 and e3. s.Fork(ctx, e2) writes a new session B whose header names its parent, A#e2: B holds copies of e1 and e2 and continues with its own e3. Session A keeps its leaf and its entries; Fork never moves it. Runs in B carry weft.session.forked_from = A#e2.

Fork copies the path root → entryID into a new session in the same storage and returns it positioned at the end of that path; when the fork had to append settling entries (below), its leaf is the last of them, with the same context. The new file holds the whole copied path, the entries keeping their ids, and its header’s Parent names the session and entry it grew from:

sessions/tree.go
leaf := s.Leaf()
fork, err := s.Fork(ctx, shipped, ctxWindow, ids("s_whatif", "f"))
if err != nil {
return err
}
h, _, _, err := st.Load(ctx, fork.ID())
if err != nil {
return err
}
fmt.Fprintln(w, "fork:", fork.ID(), "of", h.Parent.Session, "at", h.Parent.Entry, "messages:", len(fork.Context()))
turn, err := fork.Send(ctx, weft.User("Send a replacement instead."))
if err != nil {
return err
}
if _, err := turn.Wait(); err != nil {
return err
}
fmt.Fprintln(w, "fork run:", turn.RunID(), "forked_from:", meta.of(turn.RunID())["weft.session.forked_from"])
fmt.Fprintln(w, "this session's leaf moved:", s.Leaf() != leaf)

sessions/tree.go on GitHub

fork: s_whatif of s_tree at e_a3 messages: 2
fork run: s_whatif-t2 forked_from: s_tree#e_a3
this session's leaf moved: false
  • Options configure the fork, as at Create: IDs, Clock, WithMeta, PublicID, the busy policy, compaction and approval options. Nothing is inherited from this session’s options or header, not its public id, with one exception: a fork of a session that requires signed decisions requires them too.
  • It inherits what the path records: the conversation, compactions and branch summaries, the title and SetInfo metadata, labels, custom entries, the turn ledger (its run ids continue after the copied turns, hence t2), grants, and an open approval boundary, which each session then resolves on its own.
  • It does not inherit work: the running turn, queued sends and steers (recorded as dropped in the fork), mirrored pool requests, or unsettled pool delegations (settled as canceled).
  • It works mid-turn and on a closed session: it snapshots under the lock and writes elsewhere, and never moves this session’s leaf. A leaf entry is a navigation, not a position, so Fork rejects one; fork the entry it points to.

The fork is durable when Fork returns; if its entries cannot be written, the half-made session is deleted again. Its runs carry weft.session.forked_from as <session>#<entry>. The package example is ExampleSession_Fork.

Two bookkeeping writes carry your own data. s.Custom(ctx, kind, data) appends opaque JSON state under a kind you choose: it survives every compaction and never enters the model’s context. s.CustomMessage(ctx, kind, msg) appends a message that is always in the context, a note the model must see:

sessions/tree.go
if err := s.Custom(ctx, "cart", json.RawMessage(`{"items":2}`)); err != nil { // app state: never in the context
return err
}
if err := s.CustomMessage(ctx, "note", weft.User("Note: the customer is on the paid plan.")); err != nil { // always in it
return err
}
fmt.Fprintln(w, "context:", len(s.Context()), "messages; last:", s.Context()[len(s.Context())-1].Text())

sessions/tree.go on GitHub

context: 6 messages; last: Note: the customer is on the paid plan.

Both reject an empty kind, and Custom rejects data that is not JSON. CustomMessage is a between-turns write: while a turn runs it fails with ErrBusy, because a message joining mid-run would land between the run’s own messages. To reach a running turn, steer (Steer into the running turn). Custom is not restricted.

A session’s identity rides on every run it starts, as run metadata on every span and record:

sessions/tree.go
s, err := thread.Create(ctx, st, agent, ctxWindow, ids("s_pub", "a"),
thread.PublicID("pub_7f3a"), // stamped on every run as weft.public_id
thread.WithMeta(map[string]string{"tenant": "acme"})) // header metadata: Query.Meta matches it
if err != nil {
return err
}
if err := s.SetInfo(ctx, "Refund for order 1234", map[string]string{"tier": "paid"}); err != nil {
return err
}
err = s.SetInfo(ctx, "", map[string]string{"weft.public_id": "pub_other"})
fmt.Fprintln(w, "reserved key:", errors.Is(err, thread.ErrReservedKey))
turn, err := s.Send(ctx, weft.User("How long does a refund take?"))
if err != nil {
return err
}
if _, err := turn.Wait(); err != nil {
return err
}
md := meta.of(turn.RunID())
for _, k := range []string{"weft.session.id", "weft.turn", "weft.public_id", "weft.session.title"} {
fmt.Fprintf(w, "%s = %s\n", k, md[k])
}
fmt.Fprintln(w, "meta:", s.Meta()["tenant"], s.Meta()["tier"], "title:", s.Title())
page, err := thread.List(ctx, st, thread.Query{Meta: map[string]string{"weft.public_id": "pub_7f3a"}})
if err != nil {
return err
}
fmt.Fprintln(w, "found by public id:", page.Sessions[0].ID)

sessions/tree.go on GitHub

reserved key: true
weft.session.id = s_pub
weft.turn = 1
weft.public_id = pub_7f3a
weft.session.title = Refund for order 1234
meta: acme paid title: Refund for order 1234
found by public id: s_pub
KeyValue
weft.session.idthe session id, always
weft.turnthe counter the run id <session>-t<n> was minted from, always
weft.public_idthe session’s public id, when it was created with thread.PublicID
weft.session.titlethe session’s title as the turn starts, once SetInfo named one
weft.session.forked_from<session>#<entry>, on a fork
weft.session.parent, weft.session.parent_callthe parent session and delegating call, on a pool child
weft.approval.actorwho decided, on a resume run that applies decisions; "" on every other run
weft.turn.parentsince 0.18.0, the turn whose line this turn continues, on the first turn after a navigation (Branch, Uncompact, a rollback) took the leaf off the newest line; "0" when that line holds no turn; absent on a linear turn
weft.session.branchsince 0.18.0, the branch the turn’s line descends from: the label on the entry the newest navigation went to, else that navigation’s leaf entry id; absent on a line no navigation made

Every run a session starts carries them: a send, a resume, an overflow re-run. The session’s keys win over a colliding key you pass with thread.RunOptions(weft.Metadata(...)); other keys pass through. Studio’s session page draws its tree view from weft.turn.parent and weft.session.branch (A session’s page). A key the session has no value for is stamped "", which the core reads as none: a turn sent from inside another session’s tool handler, or a pool child’s turn, never carries the enclosing run’s public id, title, fork origin or lineage as its own. The title is a label, not content, so it survives a content-off destination, and Studio titles the session with it.

thread.PublicID(id) sets an opaque, browser-safe handle for the session, stored as the header metadata key weft.public_id. It is exactly thread.WithMeta(map[string]string{"weft.public_id": id}), so thread.List’s Query.Meta finds the session by it. thread.WithMeta(meta) adds other header keys. Both are header options: Create and Fork write them, and Open fails with thread.ErrCreateOnly:

sessions/tree.go
_, err = thread.Open(ctx, st, "s_pub", agent, ctxWindow, thread.PublicID("pub_new"))
fmt.Fprintln(w, "header option on Open:", errors.Is(err, thread.ErrCreateOnly))

sessions/tree.go on GitHub

header option on Open: true

Create does not check that a public id is unused. Two Create calls with thread.PublicID("pub_x") both succeed, and thread.List then finds two sessions. Studio and the devtools panel scope a conversation by public id, so they show both sessions’ turns under it. Deciding or steering a turn from the panel asks your runtime.Sessions resolver for the public id, and a turn of the session it does not return is refused: the session resolver answered session <id> for public id <pub>, not the run's session <id> (app turns).

To reuse a session per conversation, look the id up first with thread.List(ctx, st, thread.Query{Meta: map[string]string{"weft.public_id": id}}) and Open the session it returns; Create only when it returns none.

The public id is fixed for the session’s life, and a fork does not inherit it. thread.WithLineage(parentSession, call) is the third header option, the pool lineage that s.Lineage() reads back; thread/pool sets it for its children (pools). The examples are ExamplePublicID and ExampleWithMeta.

To stamp your own pairs on every turn’s run, such as a tenant or a batch tag, pass thread.WithRunMetadata(kv) (since 0.18.0). They are the pairs weft.Metadata would stamp, on every span and record of each run. At Create and Fork they are written into the header (Header.RunMeta), so a reopened session keeps stamping them; at Open they are held over the stored pairs for that Session’s life, since the header is immutable. A fork takes its origin’s pairs, its own over them. The session’s identity keys always win, and a Send’s own thread.RunOptions(weft.Metadata(...)) wins per key over the session’s. s.RunMeta() returns the pairs in force, a copy. ExampleWithRunMetadata creates a session with tenant=acme (its weft.turn=9 loses to the identity key), reopens it with batch=b7, and prints acme turn 1, then acme b7 turn 2.

s.SetInfo(ctx, title, meta) appends an info entry, never a rewrite of the header. s.Title() is the last info entry’s non-empty title, and s.Meta() the header’s metadata overlaid by every info entry’s, in append order. An empty title keeps the current one; a key set to "" blanks it, and there is no removal. A call that names neither a title nor a key writes nothing. Keys under the reserved weft. prefix are the session’s identity and belong to the header: SetInfo rejects them with thread.ErrReservedKey and writes nothing. List’s Query.Meta matches the header only, so a key SetInfo added never matches there, while runs read the merged Meta.

sessions/tree.go branches, labels, forks, keeps state and stamps identity. weft’s own thread/examples/session walks the same tree on disk, with a previewed compaction and a reopen (go run ./thread/examples/session in the weft repository).

sessions/tree.go
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"github.com/weftgo/weft"
"github.com/weftgo/weft/thread"
"github.com/weftgo/weft/wefttest"
)
// demoTree is the page "Label, branch and fork a session".
func demoTree(ctx context.Context, w io.Writer, _ string) error {
var meta runMeta
agent := weft.New(wefttest.Script(
wefttest.Say("Order 1234 shipped on Tuesday."),
wefttest.Say("It was delivered on Thursday."),
wefttest.Say("The user asked when order 1234 was delivered: Thursday."), // the branch summary
wefttest.Say("I have started a refund for order 1234."),
wefttest.Say("A replacement for order 1234 ships tomorrow."), // the fork's turn
), meta.tap())
st := thread.Memory()
s, err := thread.Create(ctx, st, agent, ctxWindow, ids("s_tree", "a"))
if err != nil {
return err
}
if err := send(ctx, s, "Where is order 1234?"); err != nil {
return err
}
shipped := s.Leaf() // the first turn's end
if err := s.Label(ctx, shipped, "shipped"); err != nil {
return err
}
if err := send(ctx, s, "When was it delivered?"); err != nil {
return err
}
// Back to the label; the abandoned turn is summarized, not lost.
if err := s.Branch(ctx, shipped, thread.SummarizeLeft()); err != nil {
return err
}
if err := send(ctx, s, "Refund it instead."); err != nil {
return err
}
for _, m := range s.Context() {
fmt.Fprintf(w, "%s: %q\n", m.Role, m.Text())
}
path, err := s.Path(s.Leaf())
if err != nil {
return err
}
fmt.Fprintln(w, "path:", len(path), "entries; tree:", len(s.Entries()))
for _, e := range s.Entries() {
if l, ok := e.(thread.LabelEntry); ok {
fmt.Fprintln(w, "label:", l.Name, "→", l.Entry)
}
}
leaf := s.Leaf()
fork, err := s.Fork(ctx, shipped, ctxWindow, ids("s_whatif", "f"))
if err != nil {
return err
}
h, _, _, err := st.Load(ctx, fork.ID())
if err != nil {
return err
}
fmt.Fprintln(w, "fork:", fork.ID(), "of", h.Parent.Session, "at", h.Parent.Entry, "messages:", len(fork.Context()))
turn, err := fork.Send(ctx, weft.User("Send a replacement instead."))
if err != nil {
return err
}
if _, err := turn.Wait(); err != nil {
return err
}
fmt.Fprintln(w, "fork run:", turn.RunID(), "forked_from:", meta.of(turn.RunID())["weft.session.forked_from"])
fmt.Fprintln(w, "this session's leaf moved:", s.Leaf() != leaf)
if err := fork.Close(ctx); err != nil {
return err
}
if err := s.Custom(ctx, "cart", json.RawMessage(`{"items":2}`)); err != nil { // app state: never in the context
return err
}
if err := s.CustomMessage(ctx, "note", weft.User("Note: the customer is on the paid plan.")); err != nil { // always in it
return err
}
fmt.Fprintln(w, "context:", len(s.Context()), "messages; last:", s.Context()[len(s.Context())-1].Text())
if err := s.Close(ctx); err != nil {
return err
}
return identity(ctx, w, st)
}
// send runs one turn and waits until the session is idle again.
func send(ctx context.Context, s *thread.Session, text string) error {
turn, err := s.Send(ctx, weft.User(text))
if err != nil {
return err
}
if _, err := turn.Wait(); err != nil {
return err
}
return s.WaitIdle(ctx)
}
// identity: the public id, the title and the metadata every run carries.
func identity(ctx context.Context, w io.Writer, st thread.Storage) error {
var meta runMeta
agent := weft.New(wefttest.Script(wefttest.Say("A refund takes three to five days.")), meta.tap())
s, err := thread.Create(ctx, st, agent, ctxWindow, ids("s_pub", "a"),
thread.PublicID("pub_7f3a"), // stamped on every run as weft.public_id
thread.WithMeta(map[string]string{"tenant": "acme"})) // header metadata: Query.Meta matches it
if err != nil {
return err
}
if err := s.SetInfo(ctx, "Refund for order 1234", map[string]string{"tier": "paid"}); err != nil {
return err
}
err = s.SetInfo(ctx, "", map[string]string{"weft.public_id": "pub_other"})
fmt.Fprintln(w, "reserved key:", errors.Is(err, thread.ErrReservedKey))
turn, err := s.Send(ctx, weft.User("How long does a refund take?"))
if err != nil {
return err
}
if _, err := turn.Wait(); err != nil {
return err
}
md := meta.of(turn.RunID())
for _, k := range []string{"weft.session.id", "weft.turn", "weft.public_id", "weft.session.title"} {
fmt.Fprintf(w, "%s = %s\n", k, md[k])
}
fmt.Fprintln(w, "meta:", s.Meta()["tenant"], s.Meta()["tier"], "title:", s.Title())
page, err := thread.List(ctx, st, thread.Query{Meta: map[string]string{"weft.public_id": "pub_7f3a"}})
if err != nil {
return err
}
fmt.Fprintln(w, "found by public id:", page.Sessions[0].ID)
if err := s.Close(ctx); err != nil {
return err
}
_, err = thread.Open(ctx, st, "s_pub", agent, ctxWindow, thread.PublicID("pub_new"))
fmt.Fprintln(w, "header option on Open:", errors.Is(err, thread.ErrCreateOnly))
return nil
}

View sessions/tree.go on GitHub

View on GitHub · run it from docs-site/examples:

Terminal window
go run ./sessions tree
go test ./sessions
user: "Where is order 1234?"
assistant: "Order 1234 shipped on Tuesday."
user: "<weft-summary>\nThe user asked when order 1234 was delivered: Thursday.\n</weft-summary>"
user: "Refund it instead."
assistant: "I have started a refund for order 1234."
path: 7 entries; tree: 12
label: shipped → e_a3
fork: s_whatif of s_tree at e_a3 messages: 2
fork run: s_whatif-t2 forked_from: s_tree#e_a3
this session's leaf moved: false
context: 6 messages; last: Note: the customer is on the paid plan.
reserved key: true
weft.session.id = s_pub
weft.turn = 1
weft.public_id = pub_7f3a
weft.session.title = Refund for order 1234
meta: acme paid title: Refund for order 1234
found by public id: s_pub
header option on Open: true

sessions/sessions_test.go also pins a branch’s context and a fork’s Parent.

  • Branch between turns. Branch, CustomMessage, Compact, ApplyCompaction and Uncompact fail with ErrBusy while a turn is in flight; wait for the turn first. Fork, Label, SetInfo, Custom and Pin do not wait. (Source: thread/errors.go:8-15; thread/branch.go:67 Branch godoc; thread/session.go:1327-1450; CHANGELOG.md:5187)
  • A fork is another session. It has its own writer, its own public id (or none) and its own id; a branch keeps one session and one context line. (Source: thread/branch.go:266 Fork godoc)
  • Put filterable keys in WithMeta at Create. SetInfo metadata reaches runs and Meta() but never Query.Meta. (Source: thread/storage.go:117-125; ExampleWithMeta)
  • Never put a weft. key in SetInfo. It is rejected with ErrReservedKey; identity is set once, in the header. (Source: thread/errors.go:172-177)
  • Look a public id up before you Create with it. Create writes a second session under an id already in use; thread.List’s Query.Meta on weft.public_id finds the existing one to Open. (Source: thread/session.go:507-549; thread/storage.go:117-125)
  • Keep the public id opaque. It is shown to browsers and stamped on every record; an email or a name does not belong there. (Source: thread/session.go:244 PublicID godoc)
  • SummarizeLeft makes a model call. It runs the session’s summary chain (SummaryModel, else the session’s model) before the branch lands, so it costs a request; in a scripted test it consumes a scripted reply. That request is on no ledger: a branch_summary entry records no usage, so s.Usage().Summaries does not count it. (Source: thread/branch.go:33-45; thread/session.go:1532-1536; ExampleSummarizeLeft)

Symbols used: Session.Branch · Session.Fork · Session.Label · Session.Leaf · Session.Context · Session.Entries · Session.Path · Session.Custom · Session.CustomMessage · Session.SetInfo · Session.Title · Session.Meta · Session.Lineage · thread.SummarizeLeft · thread.BranchOption · thread.Entry · thread.LabelEntry · thread.PublicID · thread.WithMeta · thread.WithLineage · thread.List · thread.Query · thread.ErrBusy · thread.ErrCreateOnly · thread.ErrReservedKey · thread.RunOptions · weft.Metadata · weft.MetadataFromContext · weft.Tap · weft.User · wefttest.Script