Label, branch and fork a session
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:
shipped := s.Leaf() // the first turn's endif 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()))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: 12The 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).
Branch and fork
Section titled “Branch and fork”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).
Label an entry
Section titled “Label an entry”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:
for _, e := range s.Entries() { if l, ok := e.(thread.LabelEntry); ok { fmt.Fprintln(w, "label:", l.Name, "→", l.Entry) }}label: shipped → e_a3The package example is ExampleSession_Label.
Fork into a new session
Section titled “Fork into a new session”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:
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)fork: s_whatif of s_tree at e_a3 messages: 2fork run: s_whatif-t2 forked_from: s_tree#e_a3this 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
SetInfometadata, labels, custom entries, the turn ledger (its run ids continue after the copied turns, hencet2), 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
Forkrejects 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.
Keep application state and notes
Section titled “Keep application state and notes”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:
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())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.
Identity
Section titled “Identity”A session’s identity rides on every run it starts, as run metadata on every span and record:
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 itif 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)reserved key: trueweft.session.id = s_pubweft.turn = 1weft.public_id = pub_7f3aweft.session.title = Refund for order 1234meta: acme paid title: Refund for order 1234found by public id: s_pub| Key | Value |
|---|---|
weft.session.id | the session id, always |
weft.turn | the counter the run id <session>-t<n> was minted from, always |
weft.public_id | the session’s public id, when it was created with thread.PublicID |
weft.session.title | the 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_call | the parent session and delegating call, on a pool child |
weft.approval.actor | who decided, on a resume run that applies decisions; "" on every other run |
weft.turn.parent | since 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.branch | since 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.
Set a public id and metadata
Section titled “Set a public id and metadata”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:
_, 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))header option on Open: trueCreate 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.
Edit the title and metadata
Section titled “Edit the title and metadata”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.
Complete example
Section titled “Complete example”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).
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 on GitHub · run it from docs-site/examples:
go run ./sessions treego test ./sessionsuser: "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: 12label: shipped → e_a3fork: s_whatif of s_tree at e_a3 messages: 2fork run: s_whatif-t2 forked_from: s_tree#e_a3this session's leaf moved: falsecontext: 6 messages; last: Note: the customer is on the paid plan.reserved key: trueweft.session.id = s_pubweft.turn = 1weft.public_id = pub_7f3aweft.session.title = Refund for order 1234meta: acme paid title: Refund for order 1234found by public id: s_pubheader option on Open: truesessions/sessions_test.go also pins a branch’s context and a fork’s Parent.
Best practices & gotchas
Section titled “Best practices & gotchas”- Branch between turns.
Branch,CustomMessage,Compact,ApplyCompactionandUncompactfail withErrBusywhile a turn is in flight; wait for the turn first.Fork,Label,SetInfo,CustomandPindo not wait. (Source:thread/errors.go:8-15;thread/branch.go:67Branch 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:266Fork godoc) - Put filterable keys in
WithMetaatCreate.SetInfometadata reaches runs andMeta()but neverQuery.Meta. (Source:thread/storage.go:117-125;ExampleWithMeta) - Never put a
weft.key inSetInfo. It is rejected withErrReservedKey; identity is set once, in the header. (Source:thread/errors.go:172-177) - Look a public id up before you
Createwith it.Createwrites a second session under an id already in use;thread.List’sQuery.Metaonweft.public_idfinds the existing one toOpen. (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:244PublicID godoc) SummarizeLeftmakes 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: abranch_summaryentry records no usage, sos.Usage().Summariesdoes not count it. (Source:thread/branch.go:33-45;thread/session.go:1532-1536;ExampleSummarizeLeft)
See also
Section titled “See also”- What is a session?
- Keep long sessions inside the context window (compaction)
- Tag runs with metadata
- The session log format:
leaf,label,info,customandbranch_summaryentries
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