Steer a running turn
weft.Steering installs a steering source on one run: a function the loop calls at two fixed points to collect user messages typed while the run works. A delivered message joins the transcript as an ordinary user message, so the next model call, the run’s result and the next turn all see it. Use it when a user corrects or adds to a request while the agent is still running.
A source that drains an inbox without blocking, from steering/main.go:
// inbox holds what the user typed while the run was working. Its// SteerFunc drains it without blocking: the loop calls it between steps,// so a source that waited would stall the run.type inbox chan weft.Message
func (in inbox) steer(_ context.Context, at weft.SteerPoint) []weft.Message { var out []weft.Message for { select { case m := <-in: out = append(out, m) default: return out // nil when nothing arrived: the run goes on unchanged } }}Pass it as a run option:
run := agt.Stream(ctx, weft.Prompt("Where is order 1234?"), weft.Steering(typed.steer))for ev, err := range run.Events() { if err != nil { return err } switch ev := ev.(type) { case weft.StepStart: fmt.Fprintf(w, "step %d starts\n", ev.Index) case weft.ToolFinish: fmt.Fprintf(w, " seq %d: %s → %s\n", ev.Seq, ev.Name, ev.Content) case weft.StepFinish: fmt.Fprintf(w, "step %d finished: %s\n", ev.Index, ev.Reason) case weft.Steered: fmt.Fprintf(w, " seq %d: steered after step %d: %q\n", ev.Seq, ev.Step, ev.Messages[0].Text()) }}The lookup tool stands in for the user: while it runs, a message lands in the inbox. The loop drains it after step 0’s tool batch, emits a weft.Steered event, and step 1’s model call sees the correction.
Steer a run
Section titled “Steer a run”A source is a weft.SteerFunc: func(ctx context.Context, at weft.SteerPoint) []weft.Message. It returns the messages to deliver, or nil. It must not block: the loop calls it between steps, so a source that waits on a queue stalls the run. Drain what is there and return.
Steering is a run option only, with no agent-level form: the run it steers is the one its queue belongs to. A child run started by a Subagent tool does not inherit it; forwarding a steer to a child is your decision, made explicitly.
weft.SteerPoint tells the source where the run is:
| Field | Meaning |
|---|---|
RunID | The run being steered |
Step | The step that has finished |
Final | true when the run would otherwise end here; a non-empty return redirects it into one more step |
The loop checks a step’s possible ends in a fixed order after StepFinish (ADR 0019 §2):
| The step… | Drained? | What happens |
|---|---|---|
| left calls pending approval | no | The run ends at the approval boundary; a steer cannot resolve a parked call |
met a StopWhen condition | no | The intended end stays an end |
made tool calls (Final: false) | yes | Every call of the batch already has its result, so the call/result pairing cannot be split |
made no tool calls (Final: true) | yes | A delivery redirects the run into one more step instead of ending it |
When the drain is skipped, the source keeps its messages. Delivering them later, as a follow-up turn, is the caller’s decision. A max_tokens step with tool calls is not final: its calls all get error results and the loop continues, so it is an ordinary drain point (TestSteeringMaxTokensStepIsADrainPoint).
Delivered messages are appended to the transcript before the next step’s PrepareStep chain runs, so request rewrites see them. The Steered event carries Seq, Step and a copy of the messages, and sits between that step’s StepFinish and the next StepStart, numbered from the run’s Seq counter like a tool event. Nested wraps a child run’s Steered like any other child event. On the wire its type is steered, and recorded runs store it as the steered record.
A message with any role other than user fails the run with weft.ErrInvalidSteer: the model’s own turns come from the model. Nothing from that drain is appended; earlier steers stay on the partial transcript of the *weft.RunError. The complete example prints the error text.
The package example ExampleSteering steers after a tool batch with a scripted source.
Redirect a run that would end
Section titled “Redirect a run that would end”At a final point the model answered without calling a tool. A source that returns a message there gives the run one more step:
sent := falsefollowUp := func(_ context.Context, at weft.SteerPoint) []weft.Message { if at.Final && !sent { // the run would end here sent = true return []weft.Message{weft.User("And order 5678?")} } return nil}res, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?"), weft.Steering(followUp))The run takes two steps and res.Text() is the second answer. A redirect consumes a step and passes the same continuation checks as any continuation: MaxSteps, UsageLimit and DetectLoops. When a check fails, the run fails with its usual error, and the steer is on RunError.Result.Messages, delivered but unanswered. The complete example redirects a run built with weft.MaxSteps(1); it fails with weft.ErrMaxSteps and the steer is the last message.
Steer deterministically in tests
Section titled “Steer deterministically in tests”wefttest.NewSteers returns a *wefttest.Steers, a source keyed by step rather than by time or channel state. At(step, msgs...) registers the messages delivered at that step’s drain point and returns the source, so calls chain; registering no messages clears the step. Option() is the run option, weft.Steering over Steer. In steering/main_test.go:
// TestSteerRedirectsFinalStep steers a scripted run at step 0's drain// point. NewSteers is keyed by step, so the schedule is the same on every// run and under wefttest.Replay.func TestSteerRedirectsFinalStep(t *testing.T) { model := wefttest.Script( wefttest.Say("Order 1234 shipped yesterday."), wefttest.Say("Order 5678 is still pending."), ) agt := weft.New(model) src := wefttest.NewSteers().At(0, weft.User("And order 5678?")) res, err := agt.Generate(context.Background(), weft.Prompt("Where is order 1234?"), src.Option()) if err != nil { t.Fatal(err) } if res.NumSteps() != 2 { t.Fatalf("steps = %d, want 2: the steer redirects the final step", res.NumSteps()) } if got := model.LastRequest().LastText(); got != "And order 5678?" { t.Fatalf("step 1 was asked %q, want the steered message", got) }}The schedule the test ran is the schedule the file shows. Under wefttest.Replay a delivered steer is part of the next request’s transcript, so a steer that differs from the recording misses its fixture loudly instead of drifting.
Complete example
Section titled “Complete example”steering/main.go runs five cases against scripted models:
// Command steering runs the examples of the guide "Steer a running turn":// go run ./steering. Every model is scripted with wefttest, so it runs// offline; swap in a provider adapter for a real one.package main
import ( "context" "errors" "fmt" "io" "os"
"github.com/weftgo/weft" "github.com/weftgo/weft/wefttest")
// inbox holds what the user typed while the run was working. Its// SteerFunc drains it without blocking: the loop calls it between steps,// so a source that waited would stall the run.type inbox chan weft.Message
func (in inbox) steer(_ context.Context, at weft.SteerPoint) []weft.Message { var out []weft.Message for { select { case m := <-in: out = append(out, m) default: return out // nil when nothing arrived: the run goes on unchanged } }}
// steerAfterTools delivers a message the user typed while a tool ran.func steerAfterTools(ctx context.Context, w io.Writer) error { typed := make(inbox, 8) lookup := weft.Tool("lookup", "Look up an order.", func(_ context.Context, _ struct{}) (string, error) { typed <- weft.User("Sorry, I meant order 5678.") // the user types while the tool runs return "order 1234 shipped yesterday", nil }) model := wefttest.Script( wefttest.ToolCalls(wefttest.Call{Name: "lookup"}), wefttest.Say("Order 5678 is still pending."), ) agt := weft.New(model, lookup) run := agt.Stream(ctx, weft.Prompt("Where is order 1234?"), weft.Steering(typed.steer)) for ev, err := range run.Events() { if err != nil { return err } switch ev := ev.(type) { case weft.StepStart: fmt.Fprintf(w, "step %d starts\n", ev.Index) case weft.ToolFinish: fmt.Fprintf(w, " seq %d: %s → %s\n", ev.Seq, ev.Name, ev.Content) case weft.StepFinish: fmt.Fprintf(w, "step %d finished: %s\n", ev.Index, ev.Reason) case weft.Steered: fmt.Fprintf(w, " seq %d: steered after step %d: %q\n", ev.Seq, ev.Step, ev.Messages[0].Text()) } } res, err := run.Wait() if err != nil { return err } for _, m := range res.Messages { fmt.Fprintf(w, "%-9s %s\n", m.Role, describe(m)) } return nil}
// describe renders one transcript message on a line.func describe(m weft.Message) string { if t := m.Text(); t != "" { return t } for _, p := range m.Content { switch p := p.(type) { case weft.ToolCallPart: return "calls " + p.Name case weft.ToolResultPart: return "result: " + p.Content } } return ""}
// redirect steers at the final point: the run would end, the steer gives// it one more step.func redirect(ctx context.Context, w io.Writer) error { model := wefttest.Script( wefttest.Say("Order 1234 shipped yesterday."), wefttest.Say("Order 5678 is still pending."), ) agt := weft.New(model) sent := false followUp := func(_ context.Context, at weft.SteerPoint) []weft.Message { if at.Final && !sent { // the run would end here sent = true return []weft.Message{weft.User("And order 5678?")} } return nil } res, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?"), weft.Steering(followUp)) if err != nil { return err } fmt.Fprintf(w, "%d steps, answer: %s\n", res.NumSteps(), res.Text()) return nil}
// stopWhen shows a drain point that never comes: an intended end stays an// end, and the source keeps its message.func stopWhen(ctx context.Context, w io.Writer) error { submit := weft.Tool("submit", "Submit the answer.", func(_ context.Context, _ struct{}) (string, error) { return "submitted", nil }) model := wefttest.Script(wefttest.ToolCalls(wefttest.Call{Name: "submit"})) agt := weft.New(model, submit, weft.StopWhen(weft.HasToolCall("submit"))) typed := make(inbox, 1) typed <- weft.User("One more thing…") if _, err := agt.Generate(ctx, weft.Prompt("Answer and submit."), weft.Steering(typed.steer)); err != nil { return err } fmt.Fprintf(w, "messages left in the inbox: %d\n", len(typed)) return nil}
// invalid delivers an assistant message, which fails the run.func invalid(ctx context.Context, w io.Writer) error { model := wefttest.Script(wefttest.Say("Hello.")) agt := weft.New(model) fake := func(context.Context, weft.SteerPoint) []weft.Message { return []weft.Message{weft.Assistant("I already answered.")} } _, err := agt.Generate(ctx, weft.Prompt("Hi."), weft.Steering(fake)) fmt.Fprintf(w, "errors.Is(err, weft.ErrInvalidSteer): %t\n", errors.Is(err, weft.ErrInvalidSteer)) fmt.Fprintln(w, err) return nil}
// budget redirects on the last allowed step: the steer is delivered but// unanswered, on the partial transcript of the run error.func budget(ctx context.Context, w io.Writer) error { model := wefttest.Script(wefttest.Say("Order 1234 shipped yesterday.")) agt := weft.New(model, weft.MaxSteps(1)) src := wefttest.NewSteers().At(0, weft.User("And order 5678?")) _, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?"), src.Option()) var runErr *weft.RunError if !errors.As(err, &runErr) { return fmt.Errorf("want a *RunError, got %v", err) } msgs := runErr.Result.Messages last := msgs[len(msgs)-1] fmt.Fprintf(w, "errors.Is(err, weft.ErrMaxSteps): %t\n", errors.Is(err, weft.ErrMaxSteps)) fmt.Fprintf(w, "last message: %s %q\n", last.Role, last.Text()) return nil}
func run(ctx context.Context, w io.Writer) error { steps := []struct { title string fn func(context.Context, io.Writer) error }{ {"steer after the tool batch", steerAfterTools}, {"redirect a final step", redirect}, {"StopWhen is not a drain point", stopWhen}, {"non-user role", invalid}, {"redirect past MaxSteps", budget}, } for _, s := range steps { fmt.Fprintf(w, "== %s\n", s.title) if err := s.fn(ctx, w); err != nil { return fmt.Errorf("%s: %w", s.title, err) } } return nil}
func main() { if err := run(context.Background(), os.Stdout); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) }}View on GitHub · run it from docs-site/examples:
go run ./steeringgo test ./steering== steer after the tool batchstep 0 starts seq 2: lookup → order 1234 shipped yesterdaystep 0 finished: tool_calls seq 3: steered after step 0: "Sorry, I meant order 5678."step 1 startsstep 1 finished: stopuser Where is order 1234?assistant calls lookuptool result: order 1234 shipped yesterdayuser Sorry, I meant order 5678.assistant Order 5678 is still pending.== redirect a final step2 steps, answer: Order 5678 is still pending.== StopWhen is not a drain pointmessages left in the inbox: 1== non-user roleerrors.Is(err, weft.ErrInvalidSteer): trueweft: run failed at step 0: weft: steering delivered a message with a role other than user: role "assistant" at step 0== redirect past MaxStepserrors.Is(err, weft.ErrMaxSteps): truelast message: user "And order 5678?"Best practices & gotchas
Section titled “Best practices & gotchas”- Never block in the source. It runs on the loop’s goroutine between steps; drain a queue, do not wait on one. (Source:
weft/core/steer.go:5-7) - Treat a panic in the source as a crash. It fails the run like a panic in a
PrepareStepfunction: the run’s span ends and the loop re-panics. UnderGeneratethe panic reaches your caller; underStreamit panics the run’s own goroutine, which crashes the program. (Source:weft/core/steer.go:8-10,weft/core/run.go:784,TestSteeringPanicReachesCaller) - Do not reuse delivered messages. Ownership passes to the run, as with
weft.Messages; build fresh values for each delivery. (Source:weft/core/steer.go:12-15) - Forward steers to subagents yourself.
Steeringis a run option only, and a child run started by aSubagenttool does not inherit it. (Source: ADR 0019 §7,TestSteeringChildRunsDoNotInherit) - Steer through the message, not through
PrepareStep. A message added inPrepareStepreaches the model but notRunResult.Messages, the record or the next turn. (Source: ADR 0019 “Rejected”) - Use sessions for queue policy. The core only drains; who may steer, queued follow-ups and receipts belong to
weft/thread(thread.BusyPolicy,s.Steer). (Source: ADR 0019 Context,weft/thread/doc.go:96)
See also
Section titled “See also”- What happens when you send while a turn runs?
- What happens in one step?
- Stream a run’s events
- Require human approval for a tool
- Record a real conversation once, replay it forever
Symbols used: weft.Steering · weft.SteerFunc · weft.SteerPoint · weft.Steered · weft.ErrInvalidSteer · weft.ErrMaxSteps · weft.RunError · weft.MaxSteps · weft.StopWhen · weft.HasToolCall · weft.User · Agent.Stream · wefttest.NewSteers · wefttest.Steers · Steers.At · Steers.Option · Steers.Steer · wefttest.Script · ExampleSteering