Skip to content

Send turns and wait for them

View as Markdown

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:

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 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())

sessions/turns.go on GitHub

answer: Order 1234 shipped on Tuesday.
receipt: e_a1 run: s_turns-t1 outcome: answered

The 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:

  1. Send captures its settings: the agent, the extra run options and the busy policy.
  2. 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.
  3. The run starts with weft.Messages set to the session’s context and weft.RunID set to <session>-t<n>. Each step’s messages are appended as they join the run’s transcript.
  4. 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.
  5. 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 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:

sessions/turns.go
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))

sessions/turns.go on GitHub

tenant: acme session: s_acme turn: 1
refused: true

RunOptions 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 through s.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.

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 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.

A Turn is the receipt and the handle of one accepted Send; it is safe for concurrent use. Its methods:

MethodReturns
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:

sessions/turns.go
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
}

sessions/turns.go on GitHub

gave up waiting: true outcome: running
done: 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.

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:

sessions/turns.go
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())

sessions/turns.go on GitHub

tool: lookup_order {"order_id":"5678"}
result: order 5678 is processing
steps: 2
answer: Order 5678 is still processing. run: s_turns-t2

The package example is ExampleTurn_Events.

thread.TurnOutcome tells apart the ends Wait reports alike. Its String method returns the name in the second column:

OutcomeNameWait returns
TurnRunningrunning(not ended: queued, running, or a steer waiting for its fate)
TurnAnsweredansweredthe result
TurnParkedparkedthe result, with RunResult.Pending; Next is the resume once one is armed
TurnDelivereddeliverednil, nil: a steer the running turn drained
TurnDeferreddeferrednil, nil: a steer that became a follow-up turn, Next
TurnDroppeddroppedan error wrapping ErrDropped
TurnFailedfailedthe error: the run failed, could not start, or its end was not persisted
TurnCanceledcanceledthe error: its context ended, an Interrupt or Rollback felled it, or the session closed first

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; Result carries the partial transcript. A canceled run’s cause is context.Canceled. The prompt and the steps that finished stay on the session’s path, so retry from before the turn, not with a second identical Send.
  • thread.ErrNotRun: the run never started. The Send’s context ended first (the error also wraps context.Canceled or context.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: ClearQueue removed the message, or an interrupting send had to take it back.
  • thread.ErrTurnPanicked: the session’s own turn machinery panicked, including your IDs or Clock function. 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:

sessions/turns.go
u := s.Usage()
fmt.Fprintln(w, "turn tokens:", u.Turns.InputTokens, "in,", u.Turns.OutputTokens, "out")

sessions/turns.go on GitHub

turn tokens: 30 in, 15 out
  • Turns sums 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.
  • Summaries sums the summarizer usage of every compaction, in its own bucket. It counts only each stored summary’s call: rejected retries, failed compactions and SummarizeLeft summaries are not counted (compaction gotchas).
  • Delegated sums what settled thread/pool children cost. It is never part of Turns, and never part of a run’s RunResult.Usage (AGENTS rule 13).

The package example is ExampleSession_Usage.

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 Send after 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; a SummarizeLeft branch 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.

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.

sessions/turns.go sends, streams, bounds a wait and passes run options:

sessions/turns.go
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 sessions/turns.go on GitHub

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

Terminal window
go run ./sessions turns
go test ./sessions
answer: Order 1234 shipped on Tuesday.
receipt: e_a1 run: s_turns-t1 outcome: answered
tool: lookup_order {"order_id":"5678"}
result: order 5678 is processing
steps: 2
answer: Order 5678 is still processing. run: s_turns-t2
the tool ran in session: s_turns
turn tokens: 30 in, 15 out
gave up waiting: true outcome: running
done: Exported 42 orders. <nil>
tenant: acme session: s_acme turn: 1
refused: true
  • Cancel the Send’s context to stop a turn, not the wait’s. WaitContext and Done only stop you waiting. (Source: thread/turn.go:2154 WaitContext godoc)
  • Call WaitIdle before reading state that compaction may change. Wait returns before the between-turn compaction; a test or a tool that prints the tree waits for idle. (Source: thread/turn.go:2183 WaitIdle godoc)
  • Give every session a context window. Each Session value (from Create, Open or Fork) logs one WARN, thread: no context window known for this session, at its first turn unless thread.ContextWindow or thread.ModelWindows gives it a window, and its automatic compaction stays off. thread.NoAutoCompact() turns compaction off and silences it. The demos pass ctxWindow, 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 are SessionOptions at Create or Open. (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-172 RunOptions godoc)
  • Treat ErrNotPersisted as 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. Take before := s.Leaf() before the Send, and on failure call s.Branch(ctx, before) and then Send again; the failed attempt keeps its own branch in the tree (Branch and fork). (Source: thread/turn.go:240-247 Send godoc; thread/session.go:932-935; thread/branch.go:47-67; scratch proof in sources)
  • Treat ErrLocked as retry, ErrStale and ErrClosed as reopen. ErrLocked clears when the other writer closes; a stale or closed Session value never writes again, so thread.Open the session anew. A queued Turn that Close ended with ErrClosed is still in the file and runs after the reopen, so check s.Queue() rather than send it again. (Source: thread/doc.go Errors; docs/thread-operations.md §7; thread/session.go:1643-1649)
  • Keep IDs and Clock functions trivial. Both may run under the session’s lock, so calling the Session from them deadlocks; Clock must also be safe for concurrent use. A panic in either ends the turn with ErrTurnPanicked. (Source: thread/session.go:116-145; thread/errors.go:164)

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