Skip to content

Guard against runaway agents

View as Markdown

Three options stop an agent that will not stop by itself. weft.UsageLimit caps tokens, weft.MaxSteps caps model calls, and weft.DetectLoops stops a model that repeats the same tool calls. A breach fails the run with a *weft.RunError that matches its sentinel with errors.Is and keeps the transcript up to the breach on .Result.

One guard per agent, in cookbook/budgets/main.go:

cookbook/budgets/main.go
researcher = weft.New(researchScript, weft.Name("researcher"), search,
weft.UsageLimit(weft.Usage{InputTokens: 25})) // a token budget, subagents included
worker = weft.New(workScript, weft.Name("worker"), record,
weft.MaxSteps(2)) // a step budget (the default is 10)
poller = weft.New(pollScript, weft.Name("poller"), poll,
weft.DetectLoops(3), // three identical steps in a row is a loop
weft.MaxSteps(12))

cookbook/budgets/main.go on GitHub

The shape comes from the weft-arena scenario rw.budget-guards. Three agents run away in three different ways:

AgentRunawayGuardSentinel
researcherone long search per step, until the input tokens pile upUsageLimit(weft.Usage{InputTokens: 25})weft.ErrUsageLimit
workerwants a third step when two are allowedMaxSteps(2)weft.ErrMaxSteps
pollerpolls the same job with the same arguments, foreverDetectLoops(3)weft.ErrLoopDetected

Every guard is a budget checked at the continuation point (rule 13): after a step’s tools ran, when the loop would call the model again. The step that crosses the line finishes, its tool calls included, and the next model call never happens. A step that ends the run, with a final answer or a park, succeeds even past a budget: a budget stops further spend, it does not discard finished work.

Each run fails the same way. Branch on the sentinel, never on the error text, and read the partial result off the error:

cookbook/budgets/main.go
_, err := agt.Generate(ctx, weft.Prompt("Keep going until you are done."))
var re *weft.RunError
if !errors.As(err, &re) {
return fmt.Errorf("%s: want a *weft.RunError, got %v", agt.Name(), err)
}
partial := re.Result // the transcript up to the breach
fmt.Fprintf(w, "%s: %v: matches its sentinel: %t; kept %d steps, %d messages, %d input tokens\n",
agt.Name(), err, errors.Is(err, sentinel),
len(partial.Steps), len(partial.Messages), partial.Usage.InputTokens)

cookbook/budgets/main.go on GitHub

RunError.Result holds what a successful run would: the steps so far, the transcript, the usage. Feed partial.Messages back with weft.Messages to continue under a larger budget, or store it for a person to read.

The researcher’s scripted model reports 10 input tokens per call. After step 2 the run has spent 30 against a limit of 25, so the loop fails it before step 3: run exceeded its usage limit (input 30/25, output 15/0). A field left zero in the Usage is unlimited, which is why the output side reads /0 and never trips. Usage.Total() is not a separate limit; set both fields to bound the total.

The limit counts the run’s own model calls and every subagent’s, because a child’s usage is in res.Usage. It counts a child after the child returns: the parent checks only between its own steps, so a running child is bounded by its own agent’s UsageLimit and MaxSteps, not the parent’s (usage limit). There is no default: the right number depends on the workload. The package example ExampleUsageLimit breaches an output-token limit after one step.

MaxSteps is the default budget: 10 model calls when you set nothing. The worker’s model wants a third step, so the run fails with ErrMaxSteps after two, and record_step ran twice. MaxSteps is the safety net, not the intended end; use weft.StopWhen for the end you expect. As a run option it may only lower the agent’s value: a raise fails the run with ErrInvalidRunOption before any model call.

DetectLoops(n) fails the run when n consecutive steps request the same set of tool calls: the same names with the same arguments, in any order. The poller’s third identical poll_job call trips it, long before its MaxSteps(12). Results are not part of the signature, so a tool whose output carries a timestamp cannot hide a loop; varying arguments are not a loop. It is off by default, and values below 2 are ignored. The package example ExampleDetectLoops is the same check in a dozen lines.

All three runs are recorded failed, and each names what stopped it. The program reads that back from the local sink:

  • stopped_by and error_type read usage_limit, max_steps and loop_detected. In the runs list, filter with ?status=failed and ?stopped_by=max_steps to find every run a budget ended.
  • On the run page, the header’s stop chip says it in words (“usage limit reached”, “max steps reached”, “loop detected”) and links the step where it fired, with the kind chip [max_steps] beside the status.
  • That last step is the one that crossed the line: its tool calls ran, and no model call follows. The header’s token counts are the figures UsageLimit compared.
The worker's failed run in Studio: the header reads failed with the max_steps kind and "max steps reached"; both steps called record_step, and no model call follows the secondThe worker's failed run in Studio: the header reads failed with the max_steps kind and "max steps reached"; both steps called record_step, and no model call follows the second
The worker's run: failed with the max_steps kind and "max steps reached" in the header; record_step ran in both steps and no model call follows.
FeatureWhat it does hereGuide
weft.UsageLimitcaps the researcher’s input tokensHow does a run stop?
weft.MaxStepscaps the worker’s model callsHow does a run stop?
weft.DetectLoopsstops the poller’s repeated callHow does a run stop?
*weft.RunError and sentinelsthe failure and the partial transcriptTool errors are data, run errors are yours
stopped_by, error_typename the guard in the recordFind runs
cookbook/budgets/main.go
// Command budgets is the recipe "Guard against runaway agents":
// go run ./cookbook/budgets. Three runaway agents, one guard each: a
// researcher whose token spend passes UsageLimit, a worker that wants
// more steps than MaxSteps allows, and a poller that repeats one call
// under DetectLoops. Each run fails with its sentinel inside a
// *weft.RunError that keeps the partial transcript. The models are
// scripted with wefttest, so it runs offline; the runs are recorded to
// the local sink ($WEFT_DB, else ./.weft/weft.db).
package main
import (
"context"
"errors"
"fmt"
"io"
"os"
"strings"
"sync/atomic"
"github.com/weftgo/weft"
"github.com/weftgo/weft/otel"
"github.com/weftgo/weft/wefttest"
)
type QueryInput struct {
Query string `json:"query" jsonschema:"search terms"`
}
type StepInput struct {
N int `json:"n" jsonschema:"the step number"`
}
type JobInput struct {
JobID string `json:"job_id" jsonschema:"the job id"`
}
// calls counts each tool's handler runs, by tool name.
type calls struct{ search, record, poll atomic.Int32 }
// repeat returns n identical turns of one tool call.
func repeat(n int, name, args string) []wefttest.Turn {
turns := make([]wefttest.Turn, n)
for i := range turns {
turns[i] = wefttest.ToolCalls(wefttest.Call{Name: name, Args: args})
}
return turns
}
// runaways builds the three agents. Each scripted model would go on
// for longer than its guard allows.
func runaways(c *calls) (researcher, worker, poller *weft.Agent) {
search := weft.Tool("search_docs", "Search the internal docs; returns long passages.",
func(_ context.Context, in QueryInput) (string, error) {
c.search.Add(1)
return in.Query + ": " + strings.Repeat("the platform stores events in order. ", 20), nil
})
record := weft.Tool("record_step", "Record that a step happened.",
func(_ context.Context, in StepInput) (string, error) {
c.record.Add(1)
return fmt.Sprintf("step %d recorded", in.N), nil
})
poll := weft.Tool("poll_job", "Check a batch job's status.",
func(_ context.Context, _ JobInput) (string, error) {
c.poll.Add(1)
return "status: pending; poll again with the same job_id", nil
})
researchScript := wefttest.Script(
wefttest.ToolCalls(wefttest.Call{Name: "search_docs", Args: `{"query":"alpha"}`}),
wefttest.ToolCalls(wefttest.Call{Name: "search_docs", Args: `{"query":"beta"}`}),
wefttest.ToolCalls(wefttest.Call{Name: "search_docs", Args: `{"query":"gamma"}`}),
wefttest.ToolCalls(wefttest.Call{Name: "search_docs", Args: `{"query":"delta"}`}),
wefttest.Say("done"),
)
workScript := wefttest.Script(
wefttest.ToolCalls(wefttest.Call{Name: "record_step", Args: `{"n":1}`}),
wefttest.ToolCalls(wefttest.Call{Name: "record_step", Args: `{"n":2}`}),
wefttest.ToolCalls(wefttest.Call{Name: "record_step", Args: `{"n":3}`}),
wefttest.Say("done"),
)
pollScript := wefttest.Script(repeat(6, "poll_job", `{"job_id":"J-7"}`)...)
researcher = weft.New(researchScript, weft.Name("researcher"), search,
weft.UsageLimit(weft.Usage{InputTokens: 25})) // a token budget, subagents included
worker = weft.New(workScript, weft.Name("worker"), record,
weft.MaxSteps(2)) // a step budget (the default is 10)
poller = weft.New(pollScript, weft.Name("poller"), poll,
weft.DetectLoops(3), // three identical steps in a row is a loop
weft.MaxSteps(12))
return researcher, worker, poller
}
// guard runs one agent and reports how its guard stopped it.
func guard(ctx context.Context, w io.Writer, agt *weft.Agent, sentinel error) error {
_, err := agt.Generate(ctx, weft.Prompt("Keep going until you are done."))
var re *weft.RunError
if !errors.As(err, &re) {
return fmt.Errorf("%s: want a *weft.RunError, got %v", agt.Name(), err)
}
partial := re.Result // the transcript up to the breach
fmt.Fprintf(w, "%s: %v: matches its sentinel: %t; kept %d steps, %d messages, %d input tokens\n",
agt.Name(), err, errors.Is(err, sentinel),
len(partial.Steps), len(partial.Messages), partial.Usage.InputTokens)
row, err := otel.LocalDB().Run(ctx, re.Result.ID)
if err != nil {
return err
}
fmt.Fprintf(w, " recorded: status=%s stopped_by=%s error_type=%s\n", row.Status, row.StoppedBy, row.ErrorType)
return nil
}
func run(ctx context.Context, w io.Writer) error {
defer otel.Install(otel.Local(""))()
c := &calls{}
researcher, worker, poller := runaways(c)
if err := guard(ctx, w, researcher, weft.ErrUsageLimit); err != nil {
return err
}
if err := guard(ctx, w, worker, weft.ErrMaxSteps); err != nil {
return err
}
if err := guard(ctx, w, poller, weft.ErrLoopDetected); err != nil {
return err
}
fmt.Fprintf(w, "handler runs: search_docs=%d record_step=%d poll_job=%d\n",
c.search.Load(), c.record.Load(), c.poll.Load())
return nil
}
func main() {
if err := run(context.Background(), os.Stdout); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}

View cookbook/budgets/main.go on GitHub

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

Terminal window
go run ./cookbook/budgets
go test ./cookbook/budgets
researcher: weft: run failed at step 2: weft: run exceeded its usage limit (input 30/25, output 15/0): matches its sentinel: true; kept 3 steps, 7 messages, 30 input tokens
recorded: status=failed stopped_by=usage_limit error_type=usage_limit
worker: weft: run failed at step 2: weft: run exceeded the maximum number of steps: matches its sentinel: true; kept 2 steps, 5 messages, 20 input tokens
recorded: status=failed stopped_by=max_steps error_type=max_steps
poller: weft: run failed at step 2: weft: the model repeated the same tool calls too many times: 3 identical steps in a row: matches its sentinel: true; kept 3 steps, 7 messages, 30 input tokens
recorded: status=failed stopped_by=loop_detected error_type=loop_detected
handler runs: search_docs=3 record_step=2 poll_job=3

The tests also pin that each breach matches its own sentinel and no other, and that no tool ran past its budget.

  • Set DetectLoops yourself. It is off by default; without it a stuck model spends the whole MaxSteps budget. The CLI scaffold writes DetectLoops(5). (Source: weft/core/agent.go:180-187)
  • Expect the crossing step to finish. Guards run at the continuation point, so the step that crosses a limit still executes its tool calls. Put a hard per-call bound on the tool itself. (Source: AGENTS.md rule 13)
  • Match with errors.Is. The sentinels are exported for this; the message text is not a contract. (Source: weft/core/errors.go:18-19)
  • Set both token fields to bound a total. A zero field is unlimited, and Usage.Total() is not a limit of its own. (Source: weft/core/agent.go:114-125)
  • Use StopWhen for the intended end. MaxSteps failing is a runaway surfaced, never a quiet success. (Source: weft/core/agent.go:100-108)

Symbols used: weft.UsageLimit · weft.Usage · Usage.Total · weft.MaxSteps · weft.DetectLoops · weft.StopWhen · weft.RunError · weft.ErrUsageLimit · weft.ErrMaxSteps · weft.ErrLoopDetected · weft.ErrInvalidRunOption · weft.Messages · Agent.Name · otel.Install · otel.LocalDB · obsdb.RunRow · wefttest.Script