Send turns and wait for them
s.Send(ctx, msg, opts...) appends the message, runs the session’s agent on the session’s context plus that message, and returns a *thread.Turn at once. The prompt is appended and flushed to the storage before the run starts. turn.Wait() blocks for the result, and turn.Outcome() names how the turn ended.
sessions/turns.go:
s, err := thread.Create(ctx, thread.Memory(), agent, ctxWindow, ids("s_turns", "a"))if err != nil { return err}turn, err := s.Send(ctx, weft.User("Where is order 1234?")) // the prompt is durable when Send returnsif err != nil { return err}res, err := turn.Wait()if err != nil { return err}fmt.Fprintln(w, "answer:", res.Text())fmt.Fprintln(w, "receipt:", turn.ID(), "run:", turn.RunID(), "outcome:", turn.Outcome())answer: Order 1234 shipped on Tuesday.receipt: e_a1 run: s_turns-t1 outcome: answeredThe receipt is the prompt entry’s id; the run id is <session>-t<n>. ids pins the ids for stable output, and ctxWindow gives the session its model’s context window (gotchas).
A turn is one accepted Send and the run it starts. In order:
Sendcaptures its settings: the agent, the extra run options and the busy policy.- It appends the prompt entry and flushes it (thread rule T4). The entry carries the run id minted for the turn, so a reopened session never mints it again.
- The run starts with
weft.Messagesset to the session’s context andweft.RunIDset to<session>-t<n>. Each step’s messages are appended as they join the run’s transcript. - At the end, success, failure or cancellation, a turn entry closes the ledger: run id, stop reason, usage, steps, the error text, pending approval calls. It lands in one atomic batch under
context.WithoutCancel, so a caller who walks away still leaves a complete session. - Then the session runs its between-turn work, the automatic compaction when one is due, and the next queued send.
One run per session at a time: a Send that meets a running turn follows the busy policy (What happens when you send while a turn runs?). A Send while approval requests are pending is queued behind the boundary (Approvals in sessions). A turn’s entries carry the session’s clock, so thread.Clock pins their times too.
Send a turn
Section titled “Send a turn”Send takes a weft.Message, usually weft.User(text), and thread.SendOption values. There are two: thread.As(p) overrides the busy policy for this one send (busy policies), and thread.RunOptions(opts...) carries extra run options into the turn’s run:
turn, err := s.Send(ctx, weft.User("Hi."), thread.RunOptions( weft.Metadata(map[string]string{"tenant": "acme"}), weft.MaxSteps(4), ))if err != nil { return err}if _, err := turn.Wait(); err != nil { return err}md := meta.of(turn.RunID())fmt.Fprintln(w, "tenant:", md["tenant"], "session:", md["weft.session.id"], "turn:", md["weft.turn"])
_, err = s.Send(ctx, weft.User("Hi."), thread.RunOptions(weft.Prompt("something else")))fmt.Fprintln(w, "refused:", errors.Is(err, weft.ErrInvalidRunOption))tenant: acme session: s_acme turn: 1refused: trueRunOptions takes budgets, taps, thinking, metadata and the rest of the run options. Three things are the session’s own, and Send rejects an option that would set one with an error wrapping weft.ErrInvalidRunOption, before anything is written:
- the transcript and the run id:
weft.Messages,weft.Prompt,weft.RunID; - the steering source,
weft.Steering: the session owns the steer queue; - approval decisions,
weft.Approve,weft.Deny,weft.Resolve,weft.ResolveError: decisions go throughs.Decide.
The options bind every run the session starts on the turn’s behalf: the resume of a boundary it parked, its overflow re-run, and the follow-up a steer aimed at it becomes. They are process state, not entries: a reopened session’s restored sends run without them. The session’s identity metadata (weft.session.id, weft.turn) wins over a colliding key you pass (identity). The package example is ExampleRunOptions.
A tool that a turn runs can reach its session with thread.SessionFromContext(ctx); the complete example’s lookup_order prints it.
Run what Open restored
Section titled “Run what Open restored”s.Continue(ctx) starts the work a session holds but is not running, and returns the first turn that will run, or nil when nothing waits. After Open that is the steers and sends a stopped writer had accepted; it also runs sends queued behind an approval boundary that has since been decided. Restored work runs under Continue’s ctx, since the Send that accepted it is gone. Without Continue the same work starts with the next Send, Decide or Resume. A closed session fails with ErrClosed. What is a session? shows a restore and a Continue; the package example is ExampleSession_Continue.
Wait for the session to be idle
Section titled “Wait for the session to be idle”Wait returns when the turn is decided: its entries have landed. The session may still be between items, running the automatic compaction or handing off to the next queued send. s.WaitIdle(ctx) blocks until nothing is in progress, and returns ctx.Err() if ctx ends first. A caller that only sends the next message need not call it: the Send queues behind that work. Idle is not empty: sends held by an open approval boundary and steers restored by Open are still queued when it returns. The package example is ExampleSession_Send.
Wait for a turn
Section titled “Wait for a turn”A Turn is the receipt and the handle of one accepted Send; it is safe for concurrent use. Its methods:
| Method | Returns |
|---|---|
Wait() | The run’s *weft.RunResult and error once the turn ends. Safe from any number of goroutines, any number of times, during or after Events. |
WaitContext(ctx) | Wait bounded by ctx: nil and ctx.Err() as soon as ctx ends. The turn keeps running. |
Done() | A channel closed when the turn ends, for a select. |
Events() | The run’s events in emission order. |
Outcome() | How the turn ended, or TurnRunning. |
ID() | The receipt id: the prompt entry; for a send accepted while busy, the id its prompt will take; for a steer, its receipt entry; for a resume, its turn entry. |
RunID() | <session>-t<n>, unique across a reopen; after an overflow re-run, the re-run’s id. |
Next() | The turn that continues this one: the resume of a parked boundary, or the follow-up a deferred steer became; otherwise nil. |
Bound a wait, then select on Done:
turn, err := s.Send(ctx, weft.User("Export my order history."))if err != nil { return err}<-started
short, cancel := context.WithTimeout(ctx, 20*time.Millisecond)defer cancel()_, err = turn.WaitContext(short) // bounds the wait, not the turnfmt.Fprintln(w, "gave up waiting:", errors.Is(err, context.DeadlineExceeded), "outcome:", turn.Outcome())
close(release) // the export finishesselect {case <-turn.Done(): res, err := turn.Wait() // returns at once fmt.Fprintln(w, "done:", res.Text(), err)case <-ctx.Done(): return ctx.Err()}if err := s.WaitIdle(ctx); err != nil { // the between-turn work too return err}gave up waiting: true outcome: runningdone: Exported 42 orders. <nil>Giving up the wait changes nothing for the turn. To stop the turn, cancel the context its Send was given. The package examples are ExampleTurn_WaitContext and ExampleTurn_Done.
Stream a turn’s events
Section titled “Stream a turn’s events”Events yields the run’s events as the session observes them. Unlike the core’s Run, a Turn’s events may be ranged more than once, and breaking out of the range cancels nothing: the session drives the run. A failed run delivers its error once, as the last element. A turn with no run of its own, a steer or a turn that never started, yields nothing:
turn, err = s.Send(ctx, weft.User("And order 5678?"))if err != nil { return err}for ev, err := range turn.Events() { if err != nil { // a failed run: once, as the last element return err } switch ev := ev.(type) { case weft.ToolStart: fmt.Fprintln(w, "tool:", ev.Name, ev.Args) case weft.ToolFinish: fmt.Fprintln(w, "result:", ev.Content) case weft.RunFinish: fmt.Fprintln(w, "steps:", ev.Steps) }}res, err = turn.Wait() // the same end, at onceif err != nil { return err}fmt.Fprintln(w, "answer:", res.Text(), "run:", turn.RunID())tool: lookup_order {"order_id":"5678"}result: order 5678 is processingsteps: 2answer: Order 5678 is still processing. run: s_turns-t2The package example is ExampleTurn_Events.
Read the outcome
Section titled “Read the outcome”thread.TurnOutcome tells apart the ends Wait reports alike. Its String method returns the name in the second column:
| Outcome | Name | Wait returns |
|---|---|---|
TurnRunning | running | (not ended: queued, running, or a steer waiting for its fate) |
TurnAnswered | answered | the result |
TurnParked | parked | the result, with RunResult.Pending; Next is the resume once one is armed |
TurnDelivered | delivered | nil, nil: a steer the running turn drained |
TurnDeferred | deferred | nil, nil: a steer that became a follow-up turn, Next |
TurnDropped | dropped | an error wrapping ErrDropped |
TurnFailed | failed | the error: the run failed, could not start, or its end was not persisted |
TurnCanceled | canceled | the error: its context ended, an Interrupt or Rollback felled it, or the session closed first |
Errors
Section titled “Errors”The error Wait returns says what kind of end it was. Match with errors.Is and errors.As:
*weft.RunError: the run started and failed, as the core reports it;Resultcarries the partial transcript. A canceled run’s cause iscontext.Canceled. The prompt and the steps that finished stay on the session’s path, so retry from before the turn, not with a second identicalSend.thread.ErrNotRun: the run never started. TheSend’s context ended first (the error also wrapscontext.Canceledorcontext.DeadlineExceeded), the prompt entry could not be written, or a resume’s boundary was gone. No model was called.thread.ErrClosed: the session closed before the turn ran.thread.ErrDropped:ClearQueueremoved the message, or an interrupting send had to take it back.thread.ErrTurnPanicked: the session’s own turn machinery panicked, including yourIDsorClockfunction. The panic is contained and the session keeps working. Tool and model panics are run errors instead.thread.ErrNotPersisted: the run ended but the batch carrying its turn entry was refused. Its usage is in no ledger; the step messages that landed are in the tree. When the run succeeded, the result rides beside the error. Treat it as a storage incident.
Two more sentinels refuse a call before it writes: thread.ErrCreateOnly for a header option passed to Open, and thread.ErrReservedKey for a weft. key passed to SetInfo (identity).
s.Usage() returns the session’s cost ledger, a thread.Usage, over every entry in the file, not only the leaf’s path:
u := s.Usage()fmt.Fprintln(w, "turn tokens:", u.Turns.InputTokens, "in,", u.Turns.OutputTokens, "out")turn tokens: 30 in, 15 outTurnssums every turn entry: every run the session made, abandoned branches included, since those tokens were spent. A turn that overflowed and re-ran counts both attempts.Summariessums the summarizer usage of every compaction, in its own bucket. It counts only each stored summary’s call: rejected retries, failed compactions andSummarizeLeftsummaries are not counted (compaction gotchas).Delegatedsums what settledthread/poolchildren cost. It is never part ofTurns, and never part of a run’sRunResult.Usage(AGENTS rule 13).
The package example is ExampleSession_Usage.
What the model sees
Section titled “What the model sees”A session’s context is a transcript the model reads, so its shape is a model-visible contract (AGENTS rule 5). Changes to it are listed under “Model-visible changes” in the CHANGELOG. Those in thread 0.9.0:
- After a mixed tool batch resumes, the model sees one complete tool message for the step, not the partial one with the parked call unanswered.
- A step whose write failed is no longer shown to the next turn as an interrupted call beside a duplicated message.
- A retried
Sendafter a failed prompt flush shows the user message once. - No text changed in approval results; a request that expired or was interrupted after it already held an approval is denied with the expiry or interrupt reason, not “conflicting decisions”.
- A recorded trim shows the same stubs under any options; a custom
Trimmer’s stubs reach the model; the first summary survives a trim; a truncated summary is never shown;BeforeCompact’s edits shape the summarizer’s input; aSummarizeLeftbranch summary is built from the compacted view. - A context is never built across a broken parent link (the file is refused); a salvaged session’s context starts at the orphaned entry.
Resume
Section titled “Resume”A parked turn resumes after Decide, Resume, a Send or Continue (Approvals in sessions). The resume runs on the arming call’s context for cancellation, and takes the parked turn’s context values for every key the arming context lacks, so a park rule or metadata that rode the parked turn binds the resumed steps whoever decides. A second Resume while one is in flight joins it: the armed resume, not the transcript’s dangling tail, is what makes it idempotent.
Complete example
Section titled “Complete example”sessions/turns.go sends, streams, bounds a wait and passes run options:
package main
import ( "context" "errors" "fmt" "io" "time"
"github.com/weftgo/weft" "github.com/weftgo/weft/thread" "github.com/weftgo/weft/wefttest")
// demoTurns is the page "Send turns and wait for them".func demoTurns(ctx context.Context, w io.Writer, _ string) error { var inSession string // what the tool sees; printed after the turn lookup := weft.Tool("lookup_order", "Look up an order by ID.", func(ctx context.Context, in struct { OrderID string `json:"order_id"` }) (string, error) { inSession = thread.SessionFromContext(ctx).ID() // the session whose turn runs this call return "order " + in.OrderID + " is processing", nil }) agent := weft.New(wefttest.Script( wefttest.Say("Order 1234 shipped on Tuesday."), wefttest.ToolCalls(wefttest.Call{ID: "call_1", Name: "lookup_order", Args: `{"order_id":"5678"}`}), wefttest.Say("Order 5678 is still processing."), ), lookup)
s, err := thread.Create(ctx, thread.Memory(), agent, ctxWindow, ids("s_turns", "a")) if err != nil { return err } turn, err := s.Send(ctx, weft.User("Where is order 1234?")) // the prompt is durable when Send returns if err != nil { return err } res, err := turn.Wait() if err != nil { return err } fmt.Fprintln(w, "answer:", res.Text()) fmt.Fprintln(w, "receipt:", turn.ID(), "run:", turn.RunID(), "outcome:", turn.Outcome())
turn, err = s.Send(ctx, weft.User("And order 5678?")) if err != nil { return err } for ev, err := range turn.Events() { if err != nil { // a failed run: once, as the last element return err } switch ev := ev.(type) { case weft.ToolStart: fmt.Fprintln(w, "tool:", ev.Name, ev.Args) case weft.ToolFinish: fmt.Fprintln(w, "result:", ev.Content) case weft.RunFinish: fmt.Fprintln(w, "steps:", ev.Steps) } } res, err = turn.Wait() // the same end, at once if err != nil { return err } fmt.Fprintln(w, "answer:", res.Text(), "run:", turn.RunID()) fmt.Fprintln(w, "the tool ran in session:", inSession)
u := s.Usage() fmt.Fprintln(w, "turn tokens:", u.Turns.InputTokens, "in,", u.Turns.OutputTokens, "out") if err := s.Close(ctx); err != nil { return err }
if err := waitBounded(ctx, w); err != nil { return err } return runOptions(ctx, w)}
// waitBounded waits for a long turn three ways.func waitBounded(ctx context.Context, w io.Writer) error { work, started, release := slowTool("export") agent := weft.New(wefttest.Script( wefttest.ToolCalls(wefttest.Call{Name: "export", ID: "call_1"}), wefttest.Say("Exported 42 orders."), ), work) s, err := thread.Create(ctx, thread.Memory(), agent, ctxWindow, ids("s_wait", "a")) if err != nil { return err } turn, err := s.Send(ctx, weft.User("Export my order history.")) if err != nil { return err } <-started
short, cancel := context.WithTimeout(ctx, 20*time.Millisecond) defer cancel() _, err = turn.WaitContext(short) // bounds the wait, not the turn fmt.Fprintln(w, "gave up waiting:", errors.Is(err, context.DeadlineExceeded), "outcome:", turn.Outcome())
close(release) // the export finishes select { case <-turn.Done(): res, err := turn.Wait() // returns at once fmt.Fprintln(w, "done:", res.Text(), err) case <-ctx.Done(): return ctx.Err() } if err := s.WaitIdle(ctx); err != nil { // the between-turn work too return err } return s.Close(ctx)}
// runOptions passes per-run options into one turn.func runOptions(ctx context.Context, w io.Writer) error { var meta runMeta agent := weft.New(wefttest.Script(wefttest.Say("Hello, Acme.")), meta.tap()) s, err := thread.Create(ctx, thread.Memory(), agent, ctxWindow, ids("s_acme", "a")) if err != nil { return err } turn, err := s.Send(ctx, weft.User("Hi."), thread.RunOptions( weft.Metadata(map[string]string{"tenant": "acme"}), weft.MaxSteps(4), )) if err != nil { return err } if _, err := turn.Wait(); err != nil { return err } md := meta.of(turn.RunID()) fmt.Fprintln(w, "tenant:", md["tenant"], "session:", md["weft.session.id"], "turn:", md["weft.turn"])
_, err = s.Send(ctx, weft.User("Hi."), thread.RunOptions(weft.Prompt("something else"))) fmt.Fprintln(w, "refused:", errors.Is(err, weft.ErrInvalidRunOption)) return s.Close(ctx)}View on GitHub · run it from docs-site/examples:
go run ./sessions turnsgo test ./sessionsanswer: Order 1234 shipped on Tuesday.receipt: e_a1 run: s_turns-t1 outcome: answeredtool: lookup_order {"order_id":"5678"}result: order 5678 is processingsteps: 2answer: Order 5678 is still processing. run: s_turns-t2the tool ran in session: s_turnsturn tokens: 30 in, 15 outgave up waiting: true outcome: runningdone: Exported 42 orders. <nil>tenant: acme session: s_acme turn: 1refused: trueBest practices & gotchas
Section titled “Best practices & gotchas”- Cancel the
Send’s context to stop a turn, not the wait’s.WaitContextandDoneonly stop you waiting. (Source:thread/turn.go:2154WaitContext godoc) - Call
WaitIdlebefore reading state that compaction may change.Waitreturns before the between-turn compaction; a test or a tool that prints the tree waits for idle. (Source:thread/turn.go:2183WaitIdle godoc) - Give every session a context window. Each
Sessionvalue (fromCreate,OpenorFork) logs oneWARN,thread: no context window known for this session, at its first turn unlessthread.ContextWindoworthread.ModelWindowsgives it a window, and its automatic compaction stays off.thread.NoAutoCompact()turns compaction off and silences it. The demos passctxWindow,thread.ContextWindow(128_000). (Source:thread/compaction.go:1306-1319;thread/session.go:425-432) - Pass per-turn run settings through
RunOptions. The transcript, the run id, the steering source and approval decisions are the session’s own and are refused; session-level settings areSessionOptions atCreateorOpen. (Source:thread/turn.go:139-215) - Do not rely on run options after a restart. Restored sends and boundaries run without them; pass what must survive as entries or session options. (Source:
thread/turn.go:139-172RunOptions godoc) - Treat
ErrNotPersistedas a storage incident. The model answered and the storage did not keep the turn’s end. (Source:thread/errors.go:133-141;docs/thread-operations.md§7) - Close every Session that wrote. Until it closes no other Session can write that session; a forgotten one holds its lease for the life of the process. (Source: AGENTS.md T2;
docs/thread-operations.md§4) - Retry a failed turn from the leaf before it, not with the same
Send. The failed turn’s prompt stays on the path, so sending it again puts it in the model’s context twice. Takebefore := s.Leaf()before theSend, and on failure calls.Branch(ctx, before)and thenSendagain; the failed attempt keeps its own branch in the tree (Branch and fork). (Source:thread/turn.go:240-247Send godoc;thread/session.go:932-935;thread/branch.go:47-67; scratch proof insources) - Treat
ErrLockedas retry,ErrStaleandErrClosedas reopen.ErrLockedclears when the other writer closes; a stale or closed Session value never writes again, sothread.Openthe session anew. A queued Turn thatCloseended withErrClosedis still in the file and runs after the reopen, so checks.Queue()rather than send it again. (Source:thread/doc.goErrors;docs/thread-operations.md§7;thread/session.go:1643-1649) - Keep
IDsandClockfunctions trivial. Both may run under the session’s lock, so calling the Session from them deadlocks;Clockmust also be safe for concurrent use. A panic in either ends the turn withErrTurnPanicked. (Source:thread/session.go:116-145;thread/errors.go:164)
See also
Section titled “See also”- What happens when you send while a turn runs?
- What is a session?
- Stream a run’s events: the events a turn forwards
- Approvals in sessions: parked turns and
Next
Symbols used: Session.Send · Session.Continue · Session.WaitIdle · Session.Usage · Session.Leaf · Session.Branch · thread.Usage · thread.Turn · Turn.Wait · Turn.WaitContext · Turn.Done · Turn.Events · Turn.Outcome · Turn.ID · Turn.RunID · Turn.Next · thread.TurnOutcome · thread.SendOption · thread.As · thread.RunOptions · thread.Clock · thread.SessionFromContext · thread.ErrNotRun · thread.ErrDropped · thread.ErrTurnPanicked · thread.ErrNotPersisted · thread.ErrClosed · thread.ErrCreateOnly · thread.ErrReservedKey · weft.User · weft.Message · weft.Metadata · weft.MaxSteps · weft.Prompt · weft.Tap · weft.MetadataFromContext · weft.ErrInvalidRunOption · weft.RunError · weft.RunResult · wefttest.Script