Skip to content

Steer a running turn

View as Markdown

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:

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

steering/main.go on GitHub

Pass it as a run option:

steering/main.go
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())
}
}

steering/main.go on GitHub

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.

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:

FieldMeaning
RunIDThe run being steered
StepThe step that has finished
Finaltrue 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 approvalnoThe run ends at the approval boundary; a steer cannot resolve a parked call
met a StopWhen conditionnoThe intended end stays an end
made tool calls (Final: false)yesEvery call of the batch already has its result, so the call/result pairing cannot be split
made no tool calls (Final: true)yesA 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.

At a final point the model answered without calling a tool. A source that returns a message there gives the run one more step:

steering/main.go
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))

steering/main.go on GitHub

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.

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:

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

steering/main_test.go on GitHub

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.

steering/main.go runs five cases against scripted models:

steering/main.go
// 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 steering/main.go on GitHub

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

Terminal window
go run ./steering
go test ./steering
== steer after the tool batch
step 0 starts
seq 2: lookup → order 1234 shipped yesterday
step 0 finished: tool_calls
seq 3: steered after step 0: "Sorry, I meant order 5678."
step 1 starts
step 1 finished: stop
user Where is order 1234?
assistant calls lookup
tool result: order 1234 shipped yesterday
user Sorry, I meant order 5678.
assistant Order 5678 is still pending.
== redirect a final step
2 steps, answer: Order 5678 is still pending.
== StopWhen is not a drain point
messages left in the inbox: 1
== non-user role
errors.Is(err, weft.ErrInvalidSteer): true
weft: run failed at step 0: weft: steering delivered a message with a role other than user: role "assistant" at step 0
== redirect past MaxSteps
errors.Is(err, weft.ErrMaxSteps): true
last message: user "And order 5678?"
  • 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 PrepareStep function: the run’s span ends and the loop re-panics. Under Generate the panic reaches your caller; under Stream it 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. Steering is a run option only, and a child run started by a Subagent tool does not inherit it. (Source: ADR 0019 §7, TestSteeringChildRunsDoNotInherit)
  • Steer through the message, not through PrepareStep. A message added in PrepareStep reaches the model but not RunResult.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)

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