---
title: Guard against runaway agents
description: 'Stop three kinds of runaway agent with weft.UsageLimit, weft.MaxSteps and weft.DetectLoops, and read what each failure keeps: a *weft.RunError with its sentinel and the partial transcript.'
url: https://weftgo.dev/docs/examples/budget-guards/
type: how-to
sources:
  - weft/core/agent.go:100-108 (MaxSteps, default 10), 114-125 (UsageLimit, checked after each step), 180-187 (DetectLoops, off by default)
  - weft/core/errors.go:18-39 (ErrMaxSteps, ErrUsageLimit, ErrLoopDetected), 186-196 (RunError)
  - 'weft/core/loop.go:849, 1102-1116 (guard at the continuation point: a child''s usage is compared once its delegating call returns)'
  - weft/obsdb/db.go:574 (RunRow.StoppedBy), 600 (RunRow.ErrorType)
  - weft/studio/api.go:1117-1137 (the stopped_by filter)
  - weft/studio/web/src/lib/stopped-by.ts:19-53 (the stop chip's words)
  - 'weft/AGENTS.md:714-726 (rule 13: budgets fail at the continuation point)'
  - weft/example_test.go:621 (ExampleUsageLimit), 671 (ExampleDetectLoops)
  - weft/core/wefttest/model.go:32-37 (scripted turns report 10 input and 5 output tokens)
  - 'weft-arena/internal/suites/realworld.go: rwBudgetGuards (inspiration only)'
  - docs-site/examples/cookbook/budgets/main.go, main_test.go TestBudgets, TestEachGuardKeepsThePartialTranscript
---

# Guard against runaway agents

Three options stop an agent that will not stop by itself. [`weft.UsageLimit`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#UsageLimit) caps tokens, [`weft.MaxSteps`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MaxSteps) caps model calls, and [`weft.DetectLoops`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#DetectLoops) stops a model that repeats the same tool calls. A breach fails the run with a [`*weft.RunError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#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`:

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

## How it works

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

| Agent | Runaway | Guard | Sentinel |
|---|---|---|---|
| `researcher` | one long search per step, until the input tokens pile up | `UsageLimit(weft.Usage{InputTokens: 25})` | `weft.ErrUsageLimit` |
| `worker` | wants a third step when two are allowed | `MaxSteps(2)` | `weft.ErrMaxSteps` |
| `poller` | polls the same job with the same arguments, forever | `DetectLoops(3)` | `weft.ErrLoopDetected` |

Every guard is a [budget](https://weftgo.dev/docs/reference/glossary/#budget) checked at the continuation point ([rule 13](https://github.com/weftgo/weft/blob/v0.20.2/AGENTS.md#the-rules-do-not-break-these-tests-pin-them)): 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.

## Read what a breach keeps

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

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

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

## Usage limit

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](https://weftgo.dev/docs/concepts/budgets-and-stopping/#usage-limit)). There is no default: the right number depends on the workload. The package example [`ExampleUsageLimit`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-UsageLimit) breaches an output-token limit after one step.

## Max steps

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

## Loop detection

`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`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-DetectLoops) is the same check in a dozen lines.

## What to look at in Studio

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](https://weftgo.dev/docs/observe/studio/runs/), filter with `?status=failed` and `?stopped_by=max_steps` to find every run a budget ended.
- On the [run page](https://weftgo.dev/docs/observe/studio/run-page/#the-header), 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 second](https://weftgo.dev/docs/_astro/studio-run-budget.light.D5XQQkYV.webp)

*The worker's run: failed with the max_steps kind and &quot;max steps reached&quot; in the header; record_step ran in both steps and no model call follows.*

## The weft features it combines

| Feature | What it does here | Guide |
|---|---|---|
| `weft.UsageLimit` | caps the researcher's input tokens | [How does a run stop?](https://weftgo.dev/docs/concepts/budgets-and-stopping/) |
| `weft.MaxSteps` | caps the worker's model calls | [How does a run stop?](https://weftgo.dev/docs/concepts/budgets-and-stopping/) |
| `weft.DetectLoops` | stops the poller's repeated call | [How does a run stop?](https://weftgo.dev/docs/concepts/budgets-and-stopping/) |
| `*weft.RunError` and sentinels | the failure and the partial transcript | [Tool errors are data, run errors are yours](https://weftgo.dev/docs/concepts/errors/) |
| `stopped_by`, `error_type` | name the guard in the record | [Find runs](https://weftgo.dev/docs/observe/studio/runs/) |

## The program

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

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

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

```sh
go run ./cookbook/budgets
go test ./cookbook/budgets
```

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

## Best practices & gotchas

- **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`)

## See also

- [How does a run stop?](https://weftgo.dev/docs/concepts/budgets-and-stopping/): every budget and stop condition
- [Survive flaky infrastructure](https://weftgo.dev/docs/examples/flaky-infrastructure/): `MaxModelRetries`, the fourth guard
- [Tool errors are data, run errors are yours](https://weftgo.dev/docs/concepts/errors/)
- [Find runs: the runs list, search and filters](https://weftgo.dev/docs/observe/studio/runs/)

Symbols used: [`weft.UsageLimit`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#UsageLimit) · [`weft.Usage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Usage) · [`Usage.Total`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Usage.Total) · [`weft.MaxSteps`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MaxSteps) · [`weft.DetectLoops`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#DetectLoops) · [`weft.StopWhen`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#StopWhen) · [`weft.RunError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunError) · [`weft.ErrUsageLimit`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrUsageLimit) · [`weft.ErrMaxSteps`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrMaxSteps) · [`weft.ErrLoopDetected`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrLoopDetected) · [`weft.ErrInvalidRunOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrInvalidRunOption) · [`weft.Messages`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Messages) · [`Agent.Name`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.Name) · [`otel.Install`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Install) · [`otel.LocalDB`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#LocalDB) · [`obsdb.RunRow`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#RunRow) · [`wefttest.Script`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Script)
