---
title: Send turns and wait for them
description: Send a message to a weft/thread session with s.Send, wait for the turn with Wait, WaitContext or Done, stream its events, read its outcome, and pass run options.
url: https://weftgo.dev/docs/sessions/turns/
type: how-to
sources:
  - weft/AGENTS.md:557-558 (block 8, Turns), 567 (Continue)
  - weft/thread/turn.go:102-172 (SendOption, As, RunOptions), 267 (Send), 1785-1823 (TurnOutcome), 1849 (Turn), 1929-2204 (Turn methods), 2183 (WaitIdle)
  - weft/thread/session.go:146 (Clock), 1509-1526 (Usage, Session.Usage), 1577 (Continue), 922 (SessionFromContext)
  - 'weft/thread/turn.go:240-247 (Send: the prompt entry is flushed before the run; at the end, success, failure or cancellation, the run''s new messages and a turn entry are appended); weft/thread/session.go:932-935 (Leaf); weft/thread/branch.go:47-67 (Branch: "" is the root; ErrBusy while a turn is in flight)'
  - 'scratch proof (weft v0.17.0): Fail(503) then Say(ok) with the same Send twice: the retry''s request carried user "where is order 1?" twice; with before := s.Leaf() ("" on a fresh session) and s.Branch(ctx, before) before the second Send, once'
  - weft/thread/session.go:1532-1536 (Summaries sums CompactionEntry.SummarizerUsage alone); weft/thread/compaction.go:795 (the accepted summary's usage)
  - weft/thread/errors.go:131 (ErrClosed), 141 (ErrNotPersisted), 150 (ErrNotRun), 156 (ErrDropped), 164 (ErrTurnPanicked), 171 (ErrCreateOnly), 177 (ErrReservedKey)
  - weft/thread/compaction.go:1306-1319 (the no-context-window warning)
  - weft/docs/adr/0011-thread-sessions.md (§4 turns, §7 per-step turns)
  - weft/docs/thread-operations.md (§7 errors, §8 the queue)
  - weft/CHANGELOG.md:3242 (resume context), 3848 (Continue), 3852 (Done, WaitContext, Outcome, WaitIdle), 3855 (errors), 3859 (Clock), 4064-4086 (model-visible changes), 5032 (Resume joins), 5305 (Send)
  - weft/thread/example_test.go ExampleSession_Send, ExampleSession_Usage
  - weft/thread/example_turn_test.go ExampleTurn_Events, ExampleRunOptions, ExampleTurn_Done, ExampleTurn_WaitContext
  - weft/thread/example_session_test.go ExampleSession_Continue
  - docs-site/examples/sessions/turns.go, sessions_test.go TestDemos/turns
---

# Send turns and wait for them

[`s.Send(ctx, msg, opts...)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Send) appends the message, runs the session's agent on the session's context plus that message, and returns a [`*thread.Turn`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Turn) at once. The prompt is appended and flushed to the storage before the run starts. [`turn.Wait()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Turn.Wait) blocks for the result, and [`turn.Outcome()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Turn.Outcome) names how the turn ended.

`sessions/turns.go`:

```go title="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](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/turns.go)

```text
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](#best-practices--gotchas)).

## Turns

A [turn](https://weftgo.dev/docs/reference/glossary/#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?](https://weftgo.dev/docs/sessions/busy-and-steering/)). A `Send` while approval requests are pending is queued behind the boundary ([Approvals in sessions](https://weftgo.dev/docs/sessions/approvals/)). A turn's entries carry the session's clock, so [`thread.Clock`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Clock) pins their times too.

## Send a turn

`Send` takes a [`weft.Message`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Message), usually [`weft.User(text)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#User), and [`thread.SendOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#SendOption) values. There are two: [`thread.As(p)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#As) overrides the busy policy for this one send ([busy policies](https://weftgo.dev/docs/sessions/busy-and-steering/#busy-policies)), and [`thread.RunOptions(opts...)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#RunOptions) carries extra run options into the turn's run:

```go title="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](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/turns.go)

```text
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`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#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](https://weftgo.dev/docs/sessions/tree/#identity)). The package example is [`ExampleRunOptions`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-RunOptions).

A tool that a turn runs can reach its session with [`thread.SessionFromContext(ctx)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#SessionFromContext); the complete example's `lookup_order` prints it.

### Run what Open restored

[`s.Continue(ctx)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Continue) 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?](https://weftgo.dev/docs/sessions/overview/#create-and-open) shows a restore and a `Continue`; the package example is [`ExampleSession_Continue`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-Session.Continue).

### 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)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.WaitIdle) 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`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-Session.Send).

## 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()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Turn.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)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Turn.WaitContext) | `Wait` bounded by `ctx`: nil and `ctx.Err()` as soon as `ctx` ends. The turn keeps running. |
| [`Done()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Turn.Done) | A channel closed when the turn ends, for a `select`. |
| [`Events()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Turn.Events) | The run's events in emission order. |
| [`Outcome()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Turn.Outcome) | How the turn ended, or `TurnRunning`. |
| [`ID()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Turn.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()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Turn.RunID) | `<session>-t<n>`, unique across a reopen; after an overflow re-run, the re-run's id. |
| [`Next()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Turn.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`:

```go title="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](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/turns.go)

```text
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`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-Turn.WaitContext) and [`ExampleTurn_Done`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-Turn.Done).

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

```go title="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](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/turns.go)

```text
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`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-Turn.Events).

### Read the outcome

[`thread.TurnOutcome`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/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

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](#best-practices--gotchas), not with a second identical `Send`.
- **[`thread.ErrNotRun`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/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`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrDropped)**: `ClearQueue` removed the message, or an interrupting send had to take it back.
- **[`thread.ErrTurnPanicked`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/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`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/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](https://weftgo.dev/docs/sessions/tree/#identity)).

## Usage

[`s.Usage()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Usage) returns the session's cost ledger, a [`thread.Usage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Usage), over every entry in the file, not only the leaf's path:

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

[sessions/turns.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/turns.go)

```text
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](https://weftgo.dev/docs/sessions/compaction/#best-practices--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`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-Session.Usage).

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

## Resume

A parked turn resumes after `Decide`, `Resume`, a `Send` or `Continue` ([Approvals in sessions](https://weftgo.dev/docs/sessions/approvals/)). 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

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

```go title="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)
}
```

[sessions/turns.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/turns.go)

[View on GitHub](https://github.com/weftgo/weftgo.dev/tree/main/docs-site/examples/sessions) · run it from `docs-site/examples`:

```sh
go run ./sessions turns
go test ./sessions
```

```text
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
```

## Best practices & gotchas

- **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 `SessionOption`s 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](https://weftgo.dev/docs/sessions/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`)

## See also

- [What happens when you send while a turn runs?](https://weftgo.dev/docs/sessions/busy-and-steering/)
- [What is a session?](https://weftgo.dev/docs/sessions/overview/)
- [Stream a run's events](https://weftgo.dev/docs/guides/streaming/): the events a turn forwards
- [Approvals in sessions](https://weftgo.dev/docs/sessions/approvals/): parked turns and `Next`

Symbols used: [`Session.Send`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Send) · [`Session.Continue`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Continue) · [`Session.WaitIdle`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.WaitIdle) · [`Session.Usage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Usage) · [`Session.Leaf`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Leaf) · [`Session.Branch`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Branch) · [`thread.Usage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Usage) · [`thread.Turn`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Turn) · [`Turn.Wait`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Turn.Wait) · [`Turn.WaitContext`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Turn.WaitContext) · [`Turn.Done`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Turn.Done) · [`Turn.Events`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Turn.Events) · [`Turn.Outcome`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Turn.Outcome) · [`Turn.ID`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Turn.ID) · [`Turn.RunID`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Turn.RunID) · [`Turn.Next`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Turn.Next) · [`thread.TurnOutcome`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#TurnOutcome) · [`thread.SendOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#SendOption) · [`thread.As`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#As) · [`thread.RunOptions`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#RunOptions) · [`thread.Clock`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Clock) · [`thread.SessionFromContext`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#SessionFromContext) · [`thread.ErrNotRun`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrNotRun) · [`thread.ErrDropped`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrDropped) · [`thread.ErrTurnPanicked`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrTurnPanicked) · [`thread.ErrNotPersisted`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrNotPersisted) · [`thread.ErrClosed`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrClosed) · [`thread.ErrCreateOnly`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrCreateOnly) · [`thread.ErrReservedKey`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrReservedKey) · [`weft.User`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#User) · [`weft.Message`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Message) · [`weft.Metadata`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Metadata) · [`weft.MaxSteps`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MaxSteps) · [`weft.Prompt`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Prompt) · [`weft.Tap`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Tap) · [`weft.MetadataFromContext`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MetadataFromContext) · [`weft.ErrInvalidRunOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrInvalidRunOption) · [`weft.RunError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunError) · [`weft.RunResult`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunResult) · [`wefttest.Script`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Script)
