---
title: How does a run stop?
description: A run ends successfully at its intended end — a final answer, a StopWhen condition, or pending approvals — and fails with a sentinel error when a safety budget runs out or its context is canceled.
url: https://weftgo.dev/docs/concepts/budgets-and-stopping/
type: concept
sources:
  - weft/AGENTS.md:71-74 (StopWhen, MaxSteps, UsageLimit, DetectLoops), 136-139 (cancel with a cause), rules 8, 11, 13
  - weft/docs/agent-loop-deep-dive.md:498-650 (stopping)
  - weft/core/agent.go:100-141 (MaxSteps, UsageLimit), 180-196 (DetectLoops, MaxModelRetries), 537-600 (StopCondition, StopFunc, StopWhen, HasToolCall, StepCountIs)
  - weft/core/agent.go:577-588 (HasToolCall checks last.ToolCalls by name only, never the result)
  - 'weft/core/run.go:668-687 (StepRecord: Text, ToolCalls, Results), 714-721 (RunResult.Text: the last assistant message''s text parts, "" after a HasToolCall stop with no text beside the call)'
  - 'scratch proof (weft v0.17.0, docs a9 fix): a script calling submit_answer with {"answer":"42"} under StopWhen(HasToolCall("submit_answer")) gave err nil, res.Text() "", a last message with role tool, and res.Steps[len-1].ToolCalls[0].Args {"answer":"42"} beside Results[0].Content "submitted 42"'
  - 'weft/core/output.go:101-112 (output_submitted: a submit_output result with IsError false)'
  - weft/core/model.go:42-49 (StopReason)
  - weft/core/loop.go:849 (guard runs before the next model call), 1102-1116 (the UsageLimit compare on res.Usage, children included)
  - 'scratch proof (weft v0.17.0, docs a8 fix): a lead with UsageLimit{OutputTokens 6} and one research delegation to a child scripted for 6 tool steps and an answer (MaxSteps 20). The child made all 7 model calls, then the lead failed ErrUsageLimit (input 80/0, output 40/6). The same child with its own UsageLimit{OutputTokens 6} made 2 calls; the lead then failed (input 30/0, output 15/6)'
  - weft/core/errors.go:20-39 (ErrMaxSteps, ErrUsageLimit, ErrModelRetriesExceeded, ErrLoopDetected)
  - weft/core/cancel.go:5-26 (CancelCause)
  - weft/core/loop.go:734-754 (max_tokens with calls), 788-865 (the exits and the continuation point), 1096-1183 (guard, stepSignature)
  - weft/core/observe.go:809-859 (weft.run.stopped_by values, weft.cancel.cause)
  - weft/core/events.go:148-167 (RunFinish.StoppedBy)
  - weft/core/manifest.go:230-242 (stopName)
  - weft/CHANGELOG.md:339, 340, 6289, 6308, 6624, 6638
  - 'weft/core/tool.go:192-221 (decodeInput: an omitted field decodes to its zero value; required is not checked); scratch proof (docs a10 fix): Output[Verdict] with {"reason":"x"} ended in 1 step with Approved false and err nil'
  - weft/core/stoppedby_test.go:208 (ExampleCancelCause)
  - docs-site/examples/concepts/budgets.go, concepts_test.go TestStopNames, TestCancelCauseOnSpan, TestMaxStepsRaiseRefused
---

# How does a run stop?

A run stops in one of two ways. It **ends successfully** at its intended end: the model answers without calling a tool, a [`weft.StopWhen`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#StopWhen) condition matches, or calls are waiting for approval. It **fails** with a sentinel error, such as `ErrMaxSteps`, when a safety budget runs out ([`weft.MaxSteps`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MaxSteps), [`weft.UsageLimit`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#UsageLimit), [`weft.MaxModelRetries`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MaxModelRetries), [`weft.DetectLoops`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#DetectLoops)) or its context is canceled. Reaching a budget is never a quiet success.

The intended end, from `concepts/budgets.go`: the run is over once the model calls `submit`:

```go title="concepts/budgets.go"
submit := weft.Tool("submit", "Submit the final answer.",
	func(ctx context.Context, in SubmitInput) (string, error) { return "recorded", nil })
agt := weft.New(model, submit, weft.StopWhen(weft.HasToolCall("submit")))
for ev, err := range agt.Stream(ctx, weft.Prompt("Answer, then submit.")).Events() {
	if err != nil {
		return err
	}
	if fin, ok := ev.(weft.RunFinish); ok {
		fmt.Fprintln(w, "stopped by:", fin.StoppedBy, "after", fin.Steps, "step(s)")
	}
}
```

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

```text
stopped by: has_tool_call:submit after 1 step(s)
```

The step that called `submit` runs its tools, then the run ends without another model call.

## How it works

After each step's tool calls have run, the loop asks, in order: are calls pending approval? Does a `StopWhen` condition match? Did the model make no tool calls? Any yes ends the run with `RunFinish`, so a final answer that also matches a condition reports the condition. One exception: when a steering source delivers a message at what would be the final step, the run takes one more step instead of ending ([Steer a running turn](https://weftgo.dev/docs/guides/steering/)); pending approvals and `StopWhen` ends are never redirected. Otherwise the loop has reached the continuation point, where it would spend more, and checks the budgets there: `MaxModelRetries`, then `UsageLimit`, then `DetectLoops`, first breach wins. `MaxSteps` bounds the loop itself.

Budgets fail only at the continuation point. A step that ends the run succeeds even if it overshot a budget, because a budget's job is to stop further spend, not to discard finished work.

## What stopped a run

Every run records what ended it. [`RunFinish.StoppedBy`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunFinish) and the `invoke_agent` span's `weft.run.stopped_by` attribute carry the same value:

| Value | Ended by | Outcome |
|---|---|---|
| `final_answer` | A step with no tool calls | success |
| `has_tool_call:<names>`, `step_count_is:<n>`, `output_submitted` | That `StopWhen` condition | success |
| a custom condition's `String()`, else `custom` | A custom `StopWhen` condition | success |
| `parked` | Calls pending approval | success |
| `max_steps`, `usage_limit`, `loop_detected`, `model_retries_exceeded` | That budget | failure (span only) |
| `canceled` | The run's `ctx` | failure (span only) |

A failed run has no `RunFinish`, so the failure values exist only on the span. A run that failed for another reason, such as a model error, has no `stopped_by`; its span's `error.type` names the cause.

## Stop when

[`weft.StopWhen(conds...)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#StopWhen) adds stop conditions; the run ends when any one matches. Without it, a run ends when the model replies without requesting tools. A [`weft.StopCondition`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#StopCondition) is one method, `Stop(steps []StepRecord) bool`, called after a step's tool calls have run with every step so far; the last element is the step just finished.

- [`weft.HasToolCall(names...)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#HasToolCall) matches once the step just finished called any named tool: the final-answer-tool pattern. It checks only the call, not its result, so a `submit` call that failed (bad arguments, a handler error) ends the run too, successfully, with the `INVALID_INPUT` or error result as the last message and no step left for the model to repair it. `weft.Output[T]` ends only on a valid submission. After such a stop, `res.Text()` holds only text the model wrote beside the call, often `""`: the answer is the call's arguments on `res.Steps[len(res.Steps)-1].ToolCalls`, and the handler's return on that step's `Results`.
- [`weft.StepCountIs(n)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#StepCountIs) matches after `n` steps, successfully, where reaching `MaxSteps` is a failure.
- [`weft.StopFunc`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#StopFunc) adapts an ordinary `func([]StepRecord) bool`, the `http.HandlerFunc` shape; its `Stop` method calls the function. Conditions see `StepRecord.Results`, so a custom one can wait for a tool's result.

The built-ins implement `fmt.Stringer`, which is how the manifest and `StoppedBy` name them; give a custom condition a `String()` method to name it too. `weft.Output[T]` registers its own condition, `output_submitted` ([Get structured output from a run](https://weftgo.dev/docs/guides/structured-output/)).

## Max steps

[`weft.MaxSteps(n)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MaxSteps) is the safety budget behind `ErrMaxSteps`: the most model calls a run may make, 10 by default. When the model still requests tools after the last allowed step, the run fails with [`weft.ErrMaxSteps`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrMaxSteps), the whole transcript (the last step's tool results included) on the `RunError`:

```go title="concepts/budgets.go"
agt := weft.New(model, checkOrder(), weft.MaxSteps(3))
_, err := agt.Generate(ctx, weft.Prompt("Tell me when order 1234 ships."))
var re *weft.RunError
if errors.As(err, &re) && errors.Is(err, weft.ErrMaxSteps) {
	fmt.Fprintln(w, err)
	fmt.Fprintln(w, "kept:", re.Result.NumSteps(), "steps,", len(re.Result.Messages), "messages")
}
```

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

```text
weft: run failed at step 3: weft: run exceeded the maximum number of steps
kept: 3 steps, 7 messages
```

Use `StopWhen` for the end you intend and `MaxSteps` for the one you do not. Values below 1 are ignored. As a run option `weft.MaxSteps` may only lower the agent's value; a raise fails with `ErrInvalidRunOption` before any model call. If the run is canceled during its last step's tools, it fails with the cancellation, not `ErrMaxSteps`: the cause wins over the budget.

## Usage limit

`weft.UsageLimit(max)` bounds a run's total tokens: its own model calls plus every [subagent's](https://weftgo.dev/docs/reference/glossary/#subagent), as `RunResult.Usage` sums them. A field left zero is unlimited, and there is no default limit. Past the limit, the run fails with [`weft.ErrUsageLimit`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrUsageLimit), wrapped with the numbers:

```go title="concepts/budgets.go"
researcher := weft.New(researchModel, weft.Name("researcher"))
lead := weft.New(leadModel,
	weft.Subagent("research", "Research a topic in depth.", researcher),
	weft.UsageLimit(weft.Usage{OutputTokens: 8}), // the run's own calls plus every subagent's
)
_, err := lead.Generate(ctx, weft.Prompt("Why are shipments late?"))
var re *weft.RunError
if errors.As(err, &re) && errors.Is(err, weft.ErrUsageLimit) {
	fmt.Fprintln(w, err)
	fmt.Fprintln(w, "own step:", re.Result.Steps[0].Usage.OutputTokens,
		"output tokens; with the subagent:", re.Result.Usage.OutputTokens)
}
```

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

```text
weft: run failed at step 0: weft: run exceeded its usage limit (input 20/0, output 10/8)
own step: 5 output tokens; with the subagent: 10
```

The lead's own model call spent 5 output tokens, under the limit; the research subagent's 5 more pushed the run over.

The limit counts a child's usage but cannot stop a running child. A delegation is one tool call in one of the lead's steps, and the lead checks its limit only before its next model call. The child runs to its own end first, bounded by its own agent's `MaxSteps` and `UsageLimit`, and every delegation of that step runs. A lead with `UsageLimit{OutputTokens: 6}` delegated once to a child that made 7 model calls; only then did the lead fail with `output 40/6`. The same child with its own `UsageLimit{OutputTokens: 6}` stopped after 2 calls.

`Usage.Total()` is not a separate limit: to bound the total, set both fields. A `thread/pool` child is a session, not a tool-call child: its usage is not on the parent run's `Usage`, so `UsageLimit` does not cover it ([Run bounded child sessions with a pool](https://weftgo.dev/docs/sessions/pools/)).

## Model retries

[`weft.MaxModelRetries(n)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MaxModelRetries) bounds how many `RETRY` results one tool may produce in a run since its last successful result, 3 by default. Past it, the run fails with [`weft.ErrModelRetriesExceeded`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrModelRetriesExceeded): a model that cannot correct itself is a failure, not an endless loop. The count is per tool name; a successful result for the tool resets it, other error results neither count nor reset it, and calls resumed under `Approve` do not count. [Ask the model to retry](https://weftgo.dev/docs/concepts/errors/#ask-the-model-to-retry) shows the `RETRY` side.

## Detect loops

`weft.DetectLoops(repeats)` fails a run with [`weft.ErrLoopDetected`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrLoopDetected) when `repeats` consecutive steps request the same set of tool calls: the same names with the same raw argument bytes, in any order. It is off by default, and values below 2 are ignored.

```go title="concepts/budgets.go"
agt := weft.New(model, checkOrder(), weft.DetectLoops(3))
_, err := agt.Generate(ctx, weft.Prompt("Tell me when order 1234 ships."))
fmt.Fprintln(w, err)
```

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

```text
weft: run failed at step 2: weft: the model repeated the same tool calls too many times: 3 identical steps in a row
```

Results are not part of the comparison, so a tool whose output carries a timestamp cannot hide a loop. Different arguments are not a loop: a corrected retry has a different signature.

## Stop reasons

Each model call ends with a [`weft.StopReason`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#StopReason), recorded on `StepRecord.StopReason`, on `StepFinish.Reason`, and for the last step on `RunResult.StopReason`:

| Constant | Value | Meaning |
|---|---|---|
| [`weft.StopEndTurn`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#StopEndTurn) | `stop` | The model finished its turn. |
| [`weft.StopToolCalls`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#StopToolCalls) | `tool_calls` | The model stopped to call tools. |
| [`weft.StopMaxTokens`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#StopMaxTokens) | `max_tokens` | The output hit the token limit. |

When the provider's own reason did not map exactly (`refusal`, `content_filter`, …), it is kept beside the mapped one in `StepRecord.RawStopReason`.

## Truncation is visible

A `max_tokens` finish never passes silently:

- **Text only:** the run succeeds with `RunResult.StopReason` set to `StopMaxTokens`. The caller decides what truncated text means.
- **With tool calls:** none of the calls runs, because an intact-looking call may be the first of several the model never finished. Each gets the error result `tool call <name> was not executed: the response hit the output token limit`, and the loop continues so the model retries with a full budget.

```go title="concepts/budgets.go"
cut := wefttest.Raw( // the response hit max_tokens after one tool call
	weft.ModelToolCall{ID: "call_1", Name: "check_order", Args: json.RawMessage(`{"order_id":"1234"}`)},
	weft.ModelFinish{Reason: weft.StopMaxTokens},
)
agt := weft.New(wefttest.Script(cut, wefttest.Say("Order 1234 is still processing.")), checkOrder())
res, err := agt.Generate(ctx, weft.Prompt("Is order 1234 ready?"))
if err != nil {
	return err
}
fmt.Fprintln(w, res.Steps[0].Results[0].Content)
fmt.Fprintln(w, "steps:", res.NumSteps(), "final stop reason:", res.StopReason)
```

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

```text
tool call check_order was not executed: the response hit the output token limit
steps: 2 final stop reason: stop
```

The same rule makes long tool results visible: a result past `MaxResultBytes` ends with a marker naming the bytes cut.

## Cancel with a cause

A canceled `ctx` fails the run with a `*RunError` matching `context.Canceled` (or `context.DeadlineExceeded`). No event follows the cancellation, and the partial transcript is on `RunError.Result`. To say *why* the run was canceled, cancel through `context.WithCancelCause` with a [`weft.CancelCause`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#CancelCause):

```go title="concepts/budgets.go"
ctx, cancel := context.WithCancelCause(ctx)
cancel(weft.CancelCause("app.shutdown")) // e.g. on SIGTERM

_, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?"))
fmt.Fprintln(w, "context.Canceled:", errors.Is(err, context.Canceled))
fmt.Fprintln(w, "cause:", context.Cause(ctx))
```

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

```text
context.Canceled: true
cause: context canceled: app.shutdown
```

The run's error is unchanged, still the context's. Its `invoke_agent` span records `weft.cancel.cause` = `app.shutdown` beside `weft.run.stopped_by` = `canceled`, so Studio shows who canceled it. The loop records any cause with a `Kind() string` method, so a layer may bring its own type; a deadline reads `deadline`, and a cancel with no cause records none.

`CancelCause` is a string type, a short, low-cardinality dotted name. [`Kind()`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#CancelCause.Kind) returns it, [`Error()`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#CancelCause.Error) returns `context canceled: <name>`, and [`Is`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#CancelCause.Is) reports it as `context.Canceled`. weft's own layers pass theirs: `weft/thread` cancels a turn with `thread.interrupted` or `thread.closed`, and `weft/runtime` with `studio.cancel` or `app.shutdown`. The core example [`ExampleCancelCause`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#example-CancelCause) is this snippet.

Cancellation wins everywhere, at the approval boundary too: a run canceled while calls are parked fails with the cancellation error, and the parked calls stay resumable on `RunError.Result.Pending`.

## Complete example

`concepts/budgets.go` runs each way a run stops:

```go title="concepts/budgets.go"
package main

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"io"

	"github.com/weftgo/weft"
	"github.com/weftgo/weft/wefttest"
)

// SubmitInput is the submit tool's input.
type SubmitInput struct {
	Answer string `json:"answer" jsonschema:"the final answer"`
}

// CheckInput is the check_order tool's input.
type CheckInput struct {
	OrderID string `json:"order_id"`
}

// checkOrder is a tool the scripted models below call again and again.
func checkOrder() *weft.ToolDef {
	return weft.Tool("check_order", "Check an order's status.",
		func(ctx context.Context, in CheckInput) (string, error) { return "still processing", nil })
}

// stopOnSubmit ends the run on its intended end: the submit call.
func stopOnSubmit(ctx context.Context, w io.Writer, model weft.Model) error {
	submit := weft.Tool("submit", "Submit the final answer.",
		func(ctx context.Context, in SubmitInput) (string, error) { return "recorded", nil })
	agt := weft.New(model, submit, weft.StopWhen(weft.HasToolCall("submit")))
	for ev, err := range agt.Stream(ctx, weft.Prompt("Answer, then submit.")).Events() {
		if err != nil {
			return err
		}
		if fin, ok := ev.(weft.RunFinish); ok {
			fmt.Fprintln(w, "stopped by:", fin.StoppedBy, "after", fin.Steps, "step(s)")
		}
	}
	return nil
}

// exhaustSteps runs into the step budget.
func exhaustSteps(ctx context.Context, w io.Writer, model weft.Model) error {
	agt := weft.New(model, checkOrder(), weft.MaxSteps(3))
	_, err := agt.Generate(ctx, weft.Prompt("Tell me when order 1234 ships."))
	var re *weft.RunError
	if errors.As(err, &re) && errors.Is(err, weft.ErrMaxSteps) {
		fmt.Fprintln(w, err)
		fmt.Fprintln(w, "kept:", re.Result.NumSteps(), "steps,", len(re.Result.Messages), "messages")
	}
	return nil
}

// overBudget runs a lead agent whose subagent pushes the run past its
// token budget.
func overBudget(ctx context.Context, w io.Writer, leadModel, researchModel weft.Model) error {
	researcher := weft.New(researchModel, weft.Name("researcher"))
	lead := weft.New(leadModel,
		weft.Subagent("research", "Research a topic in depth.", researcher),
		weft.UsageLimit(weft.Usage{OutputTokens: 8}), // the run's own calls plus every subagent's
	)
	_, err := lead.Generate(ctx, weft.Prompt("Why are shipments late?"))
	var re *weft.RunError
	if errors.As(err, &re) && errors.Is(err, weft.ErrUsageLimit) {
		fmt.Fprintln(w, err)
		fmt.Fprintln(w, "own step:", re.Result.Steps[0].Usage.OutputTokens,
			"output tokens; with the subagent:", re.Result.Usage.OutputTokens)
	}
	return nil
}

// repeating runs a model that asks for the same call every step.
func repeating(ctx context.Context, w io.Writer, model weft.Model) error {
	agt := weft.New(model, checkOrder(), weft.DetectLoops(3))
	_, err := agt.Generate(ctx, weft.Prompt("Tell me when order 1234 ships."))
	fmt.Fprintln(w, err)
	return nil
}

// truncated runs a step whose tool call was cut off by the output-token
// limit.
func truncated(ctx context.Context, w io.Writer) error {
	cut := wefttest.Raw( // the response hit max_tokens after one tool call
		weft.ModelToolCall{ID: "call_1", Name: "check_order", Args: json.RawMessage(`{"order_id":"1234"}`)},
		weft.ModelFinish{Reason: weft.StopMaxTokens},
	)
	agt := weft.New(wefttest.Script(cut, wefttest.Say("Order 1234 is still processing.")), checkOrder())
	res, err := agt.Generate(ctx, weft.Prompt("Is order 1234 ready?"))
	if err != nil {
		return err
	}
	fmt.Fprintln(w, res.Steps[0].Results[0].Content)
	fmt.Fprintln(w, "steps:", res.NumSteps(), "final stop reason:", res.StopReason)
	return nil
}

// cancelled runs an agent under a context cancelled with a cause. opts
// are added to the agent (the test passes a recording TracerProvider).
func cancelled(ctx context.Context, w io.Writer, opts ...weft.Option) error {
	agt := weft.New(wefttest.Script(wefttest.Say("never sent")), opts...)
	ctx, cancel := context.WithCancelCause(ctx)
	cancel(weft.CancelCause("app.shutdown")) // e.g. on SIGTERM

	_, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?"))
	fmt.Fprintln(w, "context.Canceled:", errors.Is(err, context.Canceled))
	fmt.Fprintln(w, "cause:", context.Cause(ctx))
	return nil
}

// checking scripts n steps that each call check_order; distinct makes the
// arguments differ from step to step.
func checking(n int, distinct bool) *wefttest.Model {
	turns := make([]wefttest.Turn, 0, n+1)
	for i := range n {
		id := "1234"
		if distinct {
			id = fmt.Sprintf("1234-%d", i)
		}
		turns = append(turns, wefttest.ToolCalls(wefttest.Call{Name: "check_order", Args: `{"order_id":"` + id + `"}`}))
	}
	turns = append(turns, wefttest.Say("Order 1234 shipped."))
	return wefttest.Script(turns...)
}

// demoBudgets runs each way a run stops.
func demoBudgets(ctx context.Context, w io.Writer) error {
	submit := wefttest.Script(
		wefttest.ToolCalls(wefttest.Call{Name: "submit", Args: `{"answer":"Order 1234 shipped."}`}),
		wefttest.Say("never reached: StopWhen ended the run"),
	)
	if err := stopOnSubmit(ctx, w, submit); err != nil {
		return err
	}
	if err := exhaustSteps(ctx, w, checking(3, true)); err != nil {
		return err
	}
	lead := wefttest.Script(
		wefttest.ToolCalls(wefttest.Call{Name: "research", Args: `{"prompt":"shipping delays this week"}`}),
		wefttest.Say("never reached: the budget stopped the run"),
	)
	research := wefttest.Script(wefttest.Say("Port congestion."))
	if err := overBudget(ctx, w, lead, research); err != nil {
		return err
	}
	if err := repeating(ctx, w, checking(3, false)); err != nil {
		return err
	}
	if err := truncated(ctx, w); err != nil {
		return err
	}
	return cancelled(ctx, w)
}
```

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

Run it from `docs-site/examples`:

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

```text
stopped by: has_tool_call:submit after 1 step(s)
weft: run failed at step 3: weft: run exceeded the maximum number of steps
kept: 3 steps, 7 messages
weft: run failed at step 0: weft: run exceeded its usage limit (input 20/0, output 10/8)
own step: 5 output tokens; with the subagent: 10
weft: run failed at step 2: weft: the model repeated the same tool calls too many times: 3 identical steps in a row
tool call check_order was not executed: the response hit the output token limit
steps: 2 final stop reason: stop
context.Canceled: true
cause: context canceled: app.shutdown
```

## Best practices & gotchas

- **Give every agent an intended end.** A final-answer tool with `StopWhen(HasToolCall(...))` ends on purpose; relying on `MaxSteps` turns the end into an error. (Source: deep dive §4, `weft/core/agent.go:100-108`)
- **Check the final tool's result, or use `weft.Output[T]`.** `HasToolCall("submit")` fires on a `submit` call with bad arguments: `err` is nil, the run took one step, and the last message is `INVALID_INPUT: tool "submit": field …`. When the final answer must be valid, use `weft.Output[T]`, whose `output_submitted` condition waits for a submission without an error and lets the model repair a bad one first. Otherwise check the last result's `IsError` yourself. Valid means it decodes: a field the submission leaves out arrives as its zero value, so check required fields after `GenerateAs` ([structured output](https://weftgo.dev/docs/guides/structured-output/#best-practices--gotchas)). (Source: `weft/core/agent.go:577-588`, `weft/core/output.go:101-112`)
- **Do not read a final-answer tool's answer with `res.Text()`.** The run ends on the tool message, so `res.Text()` is the text beside the call, usually `""`. Read the last step's `ToolCalls` or `Results`, or use `weft.Output[T]` with `weft.GenerateAs`. (Source: `weft/core/run.go:714-721`, `weft/core/agent.go:577-588`)
- **Expect a budget to overshoot by one step, and a step to hold whole child runs.** Limits are checked after a step, so the run that breaches `UsageLimit` has already spent the step that breached it. A step that delegates includes each child's whole run, so the overshoot can be several child runs. Bound each child with its own `UsageLimit` and `MaxSteps`. (Source: AGENTS.md rule 13, `weft/core/agent.go:114-125`; `weft/core/loop.go:849, 1102-1116`)
- **Set both `UsageLimit` fields to bound the total.** `Total()` is not a limit of its own. (Source: `weft/core/agent.go:122-124`)
- **Consider `DetectLoops` where a model may repeat itself.** It is off by default, so a model stuck on the same calls spends steps until `MaxSteps`. (Source: `weft/core/agent.go:180-187`)
- **Check `res.StopReason` on success.** `StopMaxTokens` there means the answer was cut off, and the run still returned nil. (Source: AGENTS.md rule 8)
- **Cancel with a `CancelCause` in your own shutdown paths.** A plain `cancel()` leaves the record without a reason. (Source: `weft/core/observe.go:845-859`)

## See also

- [Guard against runaway agents](https://weftgo.dev/docs/examples/budget-guards/)
- [Get structured output from a run](https://weftgo.dev/docs/guides/structured-output/)
- [Tool errors are data, run errors are yours](https://weftgo.dev/docs/concepts/errors/)
- [Change an agent's configuration for one run](https://weftgo.dev/docs/guides/run-options/)
- [Require human approval for a tool](https://weftgo.dev/docs/guides/approvals/)

Symbols used: [`weft.StopWhen`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#StopWhen) · [`weft.StopCondition`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#StopCondition) · [`weft.StopFunc`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#StopFunc) · [`weft.HasToolCall`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#HasToolCall) · [`weft.StepCountIs`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#StepCountIs) · [`weft.MaxSteps`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MaxSteps) · [`weft.UsageLimit`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#UsageLimit) · [`weft.MaxModelRetries`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MaxModelRetries) · [`weft.DetectLoops`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#DetectLoops) · [`weft.ErrMaxSteps`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrMaxSteps) · [`weft.ErrUsageLimit`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrUsageLimit) · [`weft.ErrModelRetriesExceeded`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrModelRetriesExceeded) · [`weft.ErrLoopDetected`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrLoopDetected) · [`weft.StopReason`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#StopReason) · [`weft.CancelCause`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#CancelCause) · [`weft.RunFinish`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunFinish) · [`weft.Subagent`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Subagent) · [`weft.RunError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunError) · [`wefttest.Raw`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Raw)
