---
title: Require human approval for a tool
description: Park a tool call with weft.RequireApproval, ParkOn or middleware, end the run with the call pending, and resume with Approve, Deny or Resolve.
url: https://weftgo.dev/docs/guides/approvals/
type: how-to
sources:
  - weft/core/tool.go:597-601 (RequiresApproval), 607-621 (RequireApproval), 776-780 (Call.Approved)
  - weft/core/run.go:118-123 (Approve), 145-152 (Deny), 175-197 (Resolve, ResolveError), 209-223 (ResumeOf), 306-318 (ParkOn), 335-370 (ParkAllExcept), 382-415 (ParkSource, ParkSources), 700-706 (RunResult.Pending), 826-827 and 898-905 (weft.override.park_on, park_all_except)
  - weft/core/errors.go:86-96 (ErrApprovalRequired, ErrApprovalDenied)
  - weft/core/loop.go:352 (Resolve on a call that is not pending)
  - weft/core/events.go:66-70 (a parked call has ToolStart and no ToolFinish), 150-167 (RunFinish.Pending, StoppedBy)
  - weft/docs/adr/0007-approval-boundary.md
  - weft/docs/adr/0030-a-dynamic-park-source.md
  - weft/docs/adr/0030-a-dynamic-park-source.md:43-45 (a resume reads the sources again; an approved call still runs once)
  - weft/core/loop.go:407-415 (sources read once per run, before resolvePending), 1451-1457 (the approved calls run with approved=true), 1752-1753 (a park rule skips a call whose Call.Approved is set)
  - weft/docs/life-of-a-call.md:132-147 (Resuming an approval)
  - weft/AGENTS.md:42, 82, 128-129, 171-182 (block 4a), 710-714 (rule 12)
  - weft/README.md:258-276 (Approval)
  - weft/examples/approval/main.go
  - weft/example_test.go:1016 (ExampleParkOn), 1040 (ExampleParkAllExcept)
  - weft/core/example_test.go:471 (ExampleResumeOf), 1264 (ExampleParkSource)
  - weft/CHANGELOG.md:338, 479, 3206, 6030, 6080, 6437, 6655
  - 'scratch proof (weft v0.17.0): two Generate calls with Messages(parked.Messages...) and Approve(id) for one parked refund each succeeded, and the refund handler ran 2 times'
  - weft/thread/approval.go:728-731 (a decision is spent by the resume that applies it), 1327-1361 (a spent decision is not in force)
  - docs-site/examples/approvals/main.go, main_test.go TestApprovals, TestParkedEvents, TestNoDecision, TestResolveNotPending, TestDenyDoesNotRun
  - 'weft v0.20.2: core/run.go:125-135 (ApproveBy: the classes, reporting only, weft.tool.approved_by and weft.grant.id each absent when empty, ids and enums, the last decision wins), 154-162 (DenyBy: grant, else approval); facade.go:1367-1397 (the facade''s ApproveBy, DenyBy); core/example_test.go:496-521 (ExampleApproveBy); core/onion_example_test.go:75-91 (ExampleDenyBy)'
---

# Require human approval for a tool

[`weft.RequireApproval()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RequireApproval) marks a tool whose calls never run without a decision. When the model calls it, the run ends successfully with the call on `res.Pending`; you resume with a second run that carries the transcript and [`weft.Approve`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Approve) or [`weft.Deny`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Deny). Nothing blocks in between, so the decision can arrive over any transport, hours later.

The refund tool in `approvals/main.go`:

```go title="approvals/main.go"
refund := weft.Tool("refund_order", "Refund an order. Requires a human decision.",
	refundHandler,
	weft.RequireApproval(), // calls park until someone decides
)
agt := weft.New(model, weft.Name("refund-desk"), lookupTool(), refund)
```

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

## How it works

Approval is a run boundary ([rule 12](https://github.com/weftgo/weft/blob/v0.20.2/AGENTS.md#the-rules-do-not-break-these-tests-pin-them), [ADR 0007](https://github.com/weftgo/weft/blob/v0.20.2/docs/adr/0007-approval-boundary.md)). A call that needs a decision is [parked](https://weftgo.dev/docs/reference/glossary/#park): it is not executed, and the step's other calls run normally. After they finish, the run ends successfully with the parked calls on [`RunResult.Pending`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunResult) and `RunFinish.Pending`.

> **Diagram:** The model calls refund_order, a tool built with RequireApproval(). The call gets a ToolStart but is not executed and gets no ToolFinish; the step's other calls run. The run then ends successfully, err is nil, with the parked call on res.Pending and RunFinish.Pending. Later, over any transport, a decision arrives and a new run resumes: agt.Generate(ctx, weft.Messages(res.Messages...), weft.Approve(id)). An approved call runs with Call.Approved set; weft.Deny(id, why) gives the model the result DENIED: why; a call with no decision gets DENIED: no decision. The results complete the earlier tool message and the loop continues with the next model call.

The next run resumes with the transcript and a decision per call. The transcript is the only state, so the core needs no persistence: store `res.Messages` wherever the decision waits. If the run's context is canceled while calls are parked, cancellation wins: the run fails with the context error and the parked calls ride on `RunError.Result.Pending`, still resumable.

Approval is a policy and UX seam, not a security boundary. A per-call prompt does not contain a compromised prompt or a malicious tool; a sandbox around the tool does.

## Require approval

`RequireApproval` is a tool option. [`ToolDef.RequiresApproval()`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#ToolDef.RequiresApproval) reports whether a tool has it. Run the agent, then read what parked:

```go title="approvals/main.go"
res, err := agt.Generate(ctx, weft.Prompt("Refund order 1234: $40, then $900."))
if err != nil {
	return nil, err
}
for _, pc := range res.Pending { // the run ended successfully, with work parked
	fmt.Fprintf(w, "pending %s: %s %s\n", pc.ID, pc.Name, pc.Args)
}
```

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

```text
pending c2: refund_order {"order_id":"1234","amount":40}
pending c3: refund_order {"order_id":"1234","amount":900}
lookup ran: order 1234 was delivered
```

`lookup_order` ran in the same step; its result is already in the transcript. A parked call emits a `ToolStart` and no `ToolFinish`, and `RunFinish.StoppedBy` reads `parked`. Each pending entry is a [`weft.ToolCallPart`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolCallPart) with `ID`, `Name` and `Args` to show the person deciding.

## Approve and deny

Resume by passing the parked transcript back with [`weft.Messages`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Messages) and one decision per call:

```go title="approvals/main.go"
res, err := agt.Generate(ctx,
	weft.Messages(parked.Messages...), // the transcript is the only state
	weft.Approve("c2"),
	weft.Deny("c3", "over the refund limit"),
	weft.ResumeOf(parked.ID), // links this run to the parked one in the record
	weft.Metadata(map[string]string{"weft.approval.actor": "ops-7"}),
)
if err != nil {
	return err
}
```

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

```text
c2 refund_order → refunded $40.00 on order 1234 (approved: true)
c3 refund_order → DENIED: over the refund limit
```

Before its first model call the resuming run settles every parked call:

- **Approved** calls run through the ordinary tool chain. The handler's [`weft.CallFromContext`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#CallFromContext) reports `Call.Approved == true`. They emit `ToolStart` and `ToolFinish` in the new run.
- **Denied** calls never run and emit no event. The model sees the error result `DENIED: <reason>`.
- **Undecided** calls are denied with the reason `no decision`: the model sees `DENIED: no decision`.

The cause on a denied call's error result is [`weft.ErrApprovalDenied`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrApprovalDenied). It is a tool error, data for the model, never a run error. `Approve` and `Deny` ignore ids that are not pending, so a stale id in a decision list is harmless.

### Resume an approval

The resume path, from [`docs/life-of-a-call.md`](https://github.com/weftgo/weft/blob/v0.20.2/docs/life-of-a-call.md#resuming-an-approval):

```text
Generate(Messages(res.Messages...), Approve(id), Deny(id, reason))
        │
        ▼
repair, exempting the last assistant message's unresolved calls
        │
        ▼
approved → the tool-call chain, Call.Approved = true
denied   → DENIED: <reason>;  undecided → DENIED: no decision
        │
        ▼
results complete the earlier tool message → first model call of this run
```

The results complete the earlier step's tool message in the assistant's call order, even when a new `weft.Prompt` follows the transcript. Order matters for Gemini, which matches function responses by name and position. A transcript fed back with no decision at all is repaired like any other: each unresolved call gets `no result recorded: the call was interrupted`.

Resumed calls belong to no step of the new run: they are not a `StepRecord`, and their `Call.Step` is `0`. Key audit lines on `CallID`.

A resume is not idempotent. The core keeps no record of decisions, so resuming the same parked transcript twice with `Approve(id)` runs the approved call twice, and both runs succeed. A retried HTTP request or a double-click is enough ([gotcha](#best-practices--gotchas)).

## Resolve

[`weft.Resolve(id, content)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Resolve) resumes a parked call with a result computed outside the process: a person runs the query in production and pastes what happened. The handler never runs:

```go title="approvals/main.go"
res, err := agt.Generate(ctx,
	weft.Messages(parked.Messages...),
	weft.Resolve("q1", "count: 42"), // the handler never runs; this is the result
	weft.ResumeOf(parked.ID),
)
```

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

The model reads `count: 42` as `run_sql`'s result. The content becomes the call's `ToolResultPart` verbatim, capped by `MaxResultBytes` as any result is. [`weft.ResolveError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ResolveError) does the same with the result marked as an error.

A resolved call follows the denied path: no `ToolStart` or `ToolFinish`, no `execute_tool` span, and `Call.Approved` is never set. `Resolve` composes with `Approve` and `Deny` in one resuming call; the last option for an id wins.

Unlike `Approve` and `Deny`, `Resolve` on a call that is not pending fails the run at step 0 with `resolve: call "<id>" is not pending in this run's transcript`. It carries a result the caller expects the model to see, and dropping it silently is what the error model forbids.

## Link the resume to the parked run

[`weft.ResumeOf(res.ID)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ResumeOf) names the run a resume continues. A transcript carries no run id, so the core cannot infer it. It changes nothing the model sees and nothing the loop does: the decisions resume the calls with or without it.

What it changes is the record. The resuming run's `invoke_agent` span and `run_start` record carry `weft.resumed_from`, and every run fed decisions carries `weft.resume.calls`: each parked call as `<call id>=approved|denied|resolved|no_decision`, in call order. Studio's run row shows `resumed_from`, and the parked run shows `resumed_by`. `weft/thread` and `weft/runtime` pass it on every resume; an app resuming a plain `Generate` passes it itself. Empty values are ignored, the last `ResumeOf` wins, and a subagent's child run does not inherit it. The package example is [`ExampleResumeOf`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#example-ResumeOf).

![An incident run parked in Studio: the header reads parked, three calls decided, resumed in the next run; step 0 read the metrics and step 1's restart_service, delete_logs and scale_service calls are pending](https://weftgo.dev/docs/_astro/studio-run-parked.light.Dmtk6MhA.webp)

*A parked run in Studio: three calls decided, and &quot;resumed in&quot; linking the run that carried the decisions.*

## Name the decider

Pass the approver as run metadata under the key `weft.approval.actor`, as the resume region does with [`weft.Metadata`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Metadata). It rides on every span and record of the resuming run, like any caller pair.

To name what decided, rather than who, resume with [`weft.ApproveBy(callID, by, grantID)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ApproveBy) instead of `Approve`. `by` is the decider's class (`weft/thread` uses `user`, `grant`, `approver`, `quorum` and `policy`) and `grantID` the standing permission that decided, if one did. It is reporting only: the call resumes exactly as with `Approve`, and its `execute_tool` span carries `weft.tool.approved_by` and `weft.grant.id`, each absent when empty. Both are ids and enums, never a person's name, so put an opaque class in `by`. [`weft.DenyBy(callID, reason, by, grantID)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#DenyBy) is `Deny` naming what refused: with `by` `grant` the span reads `weft.tool.denied_by` `grant` and `weft.grant.id`, and any other `by`, or a plain `Deny`, reads `approval`. The last decision for an id wins, as with `Approve`. `weft/thread` passes `ApproveBy` on every resume it runs, and `DenyBy` when a deny grant matched. The package examples [`ExampleApproveBy`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#example-ApproveBy) (approved by a grant, `g_refunds`) and [`ExampleDenyBy`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#example-DenyBy) (`DENIED: refunds are closed`) show both.

A denied call, by `Deny` or by no decision, gets a zero-length `execute_tool` span marked `weft.tool.denied` with `weft.tool.denied_kind` `denied` or `no_decision`. The span never carries the reason: that is the transcript's. The run's `invoke_agent` span counts denied calls in `weft.run.denied`. See [Tag runs with metadata](https://weftgo.dev/docs/guides/metadata/).

## Park calls for one run

[`weft.ParkOn(names...)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ParkOn) is a run option that parks calls to the named tools exactly as if they were built with `RequireApproval`. It reaches a run without touching the agent, which is immutable after `weft.New`:

```go title="approvals/main.go"
// This run alone: park refund_order as if it were built with RequireApproval.
res, err := agt.Generate(ctx, weft.Prompt("Refund order 1234."), weft.ParkOn("refund_order"))
```

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

Names are not validated: a name no tool carries parks nothing. With no names nothing parks. The set covers this run only; a subagent's child run does not inherit it. The package example is [`ExampleParkOn`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-ParkOn).

### Park all except

[`weft.ParkAllExcept(names...)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ParkAllExcept) turns `ParkOn` around: you list what may run, and every other call parks. Use it where a list of tools to park cannot be complete:

```go title="approvals/main.go"
// Default-deny: only lookup_order runs unasked; every other call parks.
res, err = agt.Generate(ctx, weft.Prompt("Refund order 1234."), weft.ParkAllExcept("lookup_order"))
```

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

- The rule applies by name to the tool each call resolves to in its step's dispatch snapshot, so a tool only a `weft.ToolSource` supplies parks like any other.
- It reaches runs started inside this run: a subagent's child applies the same rule to its own tools. A child that parks makes the delegating call's result `SUBAGENT_PENDING`; the parent does not park.
- Park rules only add up. A `RequireApproval` tool or a `ParkOn` name parks whether or not it is listed here, and several `ParkAllExcept` options let through only the names all of them list.
- With no names every call parks, except the agent's own `weft.Output` submission, `submit_output`: it is the run's answer, not a side effect.
- An approved call runs once even when the resume carries the rule again; the next call to the tool parks again.

The package example is [`ExampleParkAllExcept`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-ParkAllExcept). Both options change the run's override fingerprint (`weft.override.*` on its span).

## Park from a source

[`weft.ParkSource(fn)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ParkSource) gives the agent a park set that can change between runs ([ADR 0030](https://github.com/weftgo/weft/blob/v0.20.2/docs/adr/0030-a-dynamic-park-source.md)). The loop calls `fn` once per run, at its start, and merges the names it returns as a `ParkOn` would:

```go title="approvals/main.go"
var mu sync.Mutex
breakpoints := []string{"refund_order"} // changed elsewhere, e.g. by an admin page
agt = weft.New(script(), lookupTool(), refund,
	weft.ParkSource(func(context.Context) []string { // read once per run, at its start
		mu.Lock()
		defer mu.Unlock()
		return slices.Clone(breakpoints) // answer from memory, never the network
	}),
)
```

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

`fn` runs on the loop's goroutine before the first model call, so it must return promptly: read a cached set, never the network. A nil or empty answer parks nothing. A panic is contained, parks nothing and is reported as one Debug line. Several `ParkSource` options add up.

A resume is its own run, so the loop reads the sources again, before the decided calls run. A call you approve still runs once, as under `ParkOn`: the approved calls skip the park check, and only later calls are matched against the new answer.

The answer is behaviour, not configuration: it adds no `weft.override.*` attribute, and a source that answers nothing leaves the run byte-identical to one without it. A subagent's child run reads its own agent's sources. [`agt.ParkSources()`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.ParkSources) returns the agent's sources in order. The playground's `runtime.Breakpoints()` is one ([Breakpoints](https://weftgo.dev/docs/observe/playground/breakpoints/)); the package example is [`ExampleParkSource`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#example-ParkSource).

## Park from middleware

Tool middleware parks any call by returning an error that wraps [`weft.ErrApprovalRequired`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrApprovalRequired). Read `Call.Approved` to let the approved call through on resume:

```go title="approvals/main.go"
// parkLargeRefunds parks any refund over $100 until a person approves it.
// An approved call comes back through the chain with Call.Approved set.
func parkLargeRefunds(next weft.ToolCaller) weft.ToolCaller {
	return func(ctx context.Context, tc weft.ToolCallPart) (string, error) {
		if info, _ := weft.CallFromContext(ctx); tc.Name == "refund_order" && !info.Approved {
			var in RefundInput
			if err := json.Unmarshal(tc.Args, &in); err == nil && in.Amount > 100 {
				return "", fmt.Errorf("refund of $%.2f: %w", in.Amount, weft.ErrApprovalRequired)
			}
		}
		return next(ctx, tc)
	}
}
```

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

Registered with `weft.WrapTools(parkLargeRefunds)`, the $40 refund runs and the $900 one parks; after `Approve`, it runs with `approved: true`. The `RequireApproval`, `ParkOn` and `ParkAllExcept` check sits at the base of the chain, inside every middleware, so an outer `mw.Allow` can deny first and `mw.Audit` sees the attempt. A parking middleware such as `parkLargeRefunds` parks at its own position in `WrapTools` order: middleware listed inside it never sees the parked call. See [Add behaviour with middleware](https://weftgo.dev/docs/guides/middleware/).

`agt.CallTool` on a `RequireApproval` tool returns an error wrapping `ErrApprovalRequired` instead of parking: outside the loop there is no run to end.

## Complete example

`approvals/main.go` parks, approves, denies, resolves, and parks per run and from middleware, all against scripted models:

```go title="approvals/main.go"
// Command approvals runs the examples of the guide "Require human approval
// for a tool": go run ./approvals. Every model is scripted with wefttest,
// so it runs offline; swap in a provider adapter for a real one.
package main

import (
	"context"
	"encoding/json"
	"fmt"
	"io"
	"os"
	"slices"
	"sync"

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

type RefundInput struct {
	OrderID string  `json:"order_id" jsonschema:"the order to refund"`
	Amount  float64 `json:"amount" jsonschema:"amount in dollars"`
}

type LookupInput struct {
	OrderID string `json:"order_id" jsonschema:"the order to look up"`
}

func lookupTool() *weft.ToolDef {
	return weft.Tool("lookup_order", "Look up an order by ID.",
		func(_ context.Context, in LookupInput) (string, error) {
			return "order " + in.OrderID + " was delivered", nil
		})
}

func refundHandler(ctx context.Context, in RefundInput) (string, error) {
	call, _ := weft.CallFromContext(ctx)
	return fmt.Sprintf("refunded $%.2f on order %s (approved: %t)", in.Amount, in.OrderID, call.Approved), nil
}

// refundAgent: the model looks order 1234 up and asks for two refunds in
// one step, then answers once it sees the results.
func refundAgent() *weft.Agent {
	model := wefttest.Script(
		wefttest.ToolCalls(
			wefttest.Call{ID: "c1", Name: "lookup_order", Args: `{"order_id":"1234"}`},
			wefttest.Call{ID: "c2", Name: "refund_order", Args: `{"order_id":"1234","amount":40}`},
			wefttest.Call{ID: "c3", Name: "refund_order", Args: `{"order_id":"1234","amount":900}`},
		),
		wefttest.Say("I refunded $40; the $900 refund was declined."),
	)
	refund := weft.Tool("refund_order", "Refund an order. Requires a human decision.",
		refundHandler,
		weft.RequireApproval(), // calls park until someone decides
	)
	agt := weft.New(model, weft.Name("refund-desk"), lookupTool(), refund)
	return agt
}

// park runs the first turn and prints what parked.
func park(ctx context.Context, w io.Writer, agt *weft.Agent) (*weft.RunResult, error) {
	res, err := agt.Generate(ctx, weft.Prompt("Refund order 1234: $40, then $900."))
	if err != nil {
		return nil, err
	}
	for _, pc := range res.Pending { // the run ended successfully, with work parked
		fmt.Fprintf(w, "pending %s: %s %s\n", pc.ID, pc.Name, pc.Args)
	}
	fmt.Fprintln(w, "lookup ran:", res.Steps[0].Results[0].Content)
	return res, nil
}

// resume decides both parked calls and resumes the run.
func resume(ctx context.Context, w io.Writer, agt *weft.Agent, parked *weft.RunResult) error {
	res, err := agt.Generate(ctx,
		weft.Messages(parked.Messages...), // the transcript is the only state
		weft.Approve("c2"),
		weft.Deny("c3", "over the refund limit"),
		weft.ResumeOf(parked.ID), // links this run to the parked one in the record
		weft.Metadata(map[string]string{"weft.approval.actor": "ops-7"}),
	)
	if err != nil {
		return err
	}
	printResults(w, res, "refund_order")
	fmt.Fprintln(w, "answer:", res.Text())
	return nil
}

// printResults prints every result of the named tool in the transcript.
func printResults(w io.Writer, res *weft.RunResult, name string) {
	for _, m := range res.Messages {
		for _, p := range m.Content {
			if r, ok := p.(weft.ToolResultPart); ok && r.Name == name {
				fmt.Fprintf(w, "%s %s → %s\n", r.CallID, r.Name, r.Content)
			}
		}
	}
}

// resolve: a human runs the query and pastes what happened.
func resolve(ctx context.Context, w io.Writer) error {
	runSQL := weft.Tool("run_sql", "Run a read-only SQL query. A human executes it.",
		func(_ context.Context, in struct {
			SQL string `json:"sql"`
		}) (string, error) {
			return "", &weft.ToolError{Code: "NOT_EXECUTED", Message: "this tool only runs through a human"}
		},
		weft.RequireApproval(),
	)
	model := wefttest.Script(
		wefttest.ToolCalls(wefttest.Call{ID: "q1", Name: "run_sql", Args: `{"sql":"SELECT COUNT(*) FROM orders"}`}),
		wefttest.Say("There are 42 orders."),
	)
	agt := weft.New(model, weft.Name("sql-desk"), runSQL)
	parked, err := agt.Generate(ctx, weft.Prompt("How many orders are there?"))
	if err != nil {
		return err
	}
	res, err := agt.Generate(ctx,
		weft.Messages(parked.Messages...),
		weft.Resolve("q1", "count: 42"), // the handler never runs; this is the result
		weft.ResumeOf(parked.ID),
	)
	if err != nil {
		return err
	}
	printResults(w, res, "run_sql")
	fmt.Fprintln(w, "answer:", res.Text())
	return nil
}

// parkPerRun: tools without RequireApproval, parked by run options and by
// a ParkSource.
func parkPerRun(ctx context.Context, w io.Writer) error {
	refund := weft.Tool("refund_order", "Refund an order.", refundHandler)
	script := func() *wefttest.Model {
		return wefttest.Script(
			wefttest.ToolCalls(
				wefttest.Call{ID: "c1", Name: "lookup_order", Args: `{"order_id":"1234"}`},
				wefttest.Call{ID: "c2", Name: "refund_order", Args: `{"order_id":"1234","amount":40}`},
			),
			wefttest.Say("Refunded."),
		)
	}
	agt := weft.New(script(), lookupTool(), refund)

	// This run alone: park refund_order as if it were built with RequireApproval.
	res, err := agt.Generate(ctx, weft.Prompt("Refund order 1234."), weft.ParkOn("refund_order"))
	if err != nil {
		return err
	}
	fmt.Fprintln(w, "ParkOn pending:", names(res.Pending))

	agt = weft.New(script(), lookupTool(), refund)
	// Default-deny: only lookup_order runs unasked; every other call parks.
	res, err = agt.Generate(ctx, weft.Prompt("Refund order 1234."), weft.ParkAllExcept("lookup_order"))
	if err != nil {
		return err
	}
	fmt.Fprintln(w, "ParkAllExcept pending:", names(res.Pending))

	var mu sync.Mutex
	breakpoints := []string{"refund_order"} // changed elsewhere, e.g. by an admin page
	agt = weft.New(script(), lookupTool(), refund,
		weft.ParkSource(func(context.Context) []string { // read once per run, at its start
			mu.Lock()
			defer mu.Unlock()
			return slices.Clone(breakpoints) // answer from memory, never the network
		}),
	)
	res, err = agt.Generate(ctx, weft.Prompt("Refund order 1234."))
	if err != nil {
		return err
	}
	fmt.Fprintln(w, "ParkSource pending:", names(res.Pending), "sources:", len(agt.ParkSources()))
	return nil
}

// parkLargeRefunds parks any refund over $100 until a person approves it.
// An approved call comes back through the chain with Call.Approved set.
func parkLargeRefunds(next weft.ToolCaller) weft.ToolCaller {
	return func(ctx context.Context, tc weft.ToolCallPart) (string, error) {
		if info, _ := weft.CallFromContext(ctx); tc.Name == "refund_order" && !info.Approved {
			var in RefundInput
			if err := json.Unmarshal(tc.Args, &in); err == nil && in.Amount > 100 {
				return "", fmt.Errorf("refund of $%.2f: %w", in.Amount, weft.ErrApprovalRequired)
			}
		}
		return next(ctx, tc)
	}
}

// parkFromMiddleware: the small refund runs, the large one parks.
func parkFromMiddleware(ctx context.Context, w io.Writer) error {
	refund := weft.Tool("refund_order", "Refund an order.", refundHandler)
	model := wefttest.Script(
		wefttest.ToolCalls(
			wefttest.Call{ID: "c1", Name: "refund_order", Args: `{"order_id":"1234","amount":40}`},
			wefttest.Call{ID: "c2", Name: "refund_order", Args: `{"order_id":"5678","amount":900}`},
		),
		wefttest.Say("Both refunds are done."),
	)
	agt := weft.New(model, refund, weft.WrapTools(parkLargeRefunds))
	res, err := agt.Generate(ctx, weft.Prompt("Refund both orders."))
	if err != nil {
		return err
	}
	fmt.Fprintln(w, "ran:", res.Steps[0].Results[0].Content)
	fmt.Fprintln(w, "pending:", names(res.Pending))
	res, err = agt.Generate(ctx, weft.Messages(res.Messages...), weft.Approve("c2"), weft.ResumeOf(res.ID))
	if err != nil {
		return err
	}
	printResults(w, res, "refund_order")
	return nil
}

func names(calls []weft.ToolCallPart) []string {
	out := make([]string, len(calls))
	for i, c := range calls {
		out[i] = c.ID + " " + c.Name
	}
	return out
}

func run(ctx context.Context, w io.Writer) error {
	fmt.Fprintln(w, "== park and resume")
	agt := refundAgent()
	parked, err := park(ctx, w, agt)
	if err != nil {
		return err
	}
	if err := resume(ctx, w, agt, parked); err != nil {
		return err
	}
	fmt.Fprintln(w, "== resolve")
	if err := resolve(ctx, w); err != nil {
		return err
	}
	fmt.Fprintln(w, "== park per run")
	if err := parkPerRun(ctx, w); err != nil {
		return err
	}
	fmt.Fprintln(w, "== park from middleware")
	return parkFromMiddleware(ctx, w)
}

func main() {
	if err := run(context.Background(), os.Stdout); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}
```

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

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

```sh
go run ./approvals
go test ./approvals
```

```text
== park and resume
pending c2: refund_order {"order_id":"1234","amount":40}
pending c3: refund_order {"order_id":"1234","amount":900}
lookup ran: order 1234 was delivered
c2 refund_order → refunded $40.00 on order 1234 (approved: true)
c3 refund_order → DENIED: over the refund limit
answer: I refunded $40; the $900 refund was declined.
== resolve
q1 run_sql → count: 42
answer: There are 42 orders.
== park per run
ParkOn pending: [c2 refund_order]
ParkAllExcept pending: [c2 refund_order]
ParkSource pending: [c2 refund_order] sources: 1
== park from middleware
ran: refunded $40.00 on order 1234 (approved: false)
pending: [c2 refund_order]
c1 refund_order → refunded $40.00 on order 1234 (approved: false)
c2 refund_order → refunded $900.00 on order 5678 (approved: true)
```

The tests in `approvals/main_test.go` also pin `DENIED: no decision`, the parked call's events, and `Resolve` failing on an id that is not pending. weft's own [`examples/approval`](https://github.com/weftgo/weft/tree/v0.20.2/examples/approval) asks for the decision on standard input.

## Best practices & gotchas

- **Decide every pending call.** An undecided call is denied with `DENIED: no decision`, and the model reads it. (Source: ADR 0007 §3, `weft/core/run.go:139-152`)
- **Resume each park once.** The core does not remember that a park was decided, so a second resume of the same transcript runs the approved call again. Record the decision before you resume, for example a row keyed on `res.ID` and the call id that only the first request can claim. Make side-effecting handlers idempotent too, or use `weft/thread`, which records each decision and spends it on the resume that applies it ([Approvals in sessions](https://weftgo.dev/docs/sessions/approvals/#how-it-works)). (Source: `weft/core/run.go:118-123`, ADR 0007; scratch test)
- **Pass `ResumeOf(res.ID)` on every resume.** The core cannot infer the link, and without it Studio cannot show which run decided which park. (Source: `weft/core/run.go:209-223`, CHANGELOG 0.16.0)
- **Put an opaque id in `weft.approval.actor`, never an email.** It is metadata, so it survives a content-off destination. (Source: CHANGELOG.md:338)
- **Treat approval as policy, not security.** A malicious tool or a compromised prompt is contained by a sandbox, not by a prompt to a person. (Source: ADR 0007, "Not a security boundary")
- **Do not stop a run on an approval-gated tool's result.** Stop conditions do not see resumed calls; `HasToolCall` fires on the step that issued the call. (Source: ADR 0007, Consequences)
- **Return promptly from a `ParkSource`.** It runs before the first model call on the loop's goroutine. (Source: `weft/core/run.go:395-400`, ADR 0030)

## See also

- [What does a run return?](https://weftgo.dev/docs/concepts/runs/): `Pending` on the result
- [Approvals in sessions](https://weftgo.dev/docs/sessions/approvals/): `thread` adds persistence, grants and signed decisions
- [Add behaviour with middleware](https://weftgo.dev/docs/guides/middleware/)
- [Continue a conversation](https://weftgo.dev/docs/guides/conversations/)

Symbols used: [`weft.RequireApproval`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RequireApproval) · [`ToolDef.RequiresApproval`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#ToolDef.RequiresApproval) · [`weft.Approve`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Approve) · [`weft.Deny`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Deny) · [`weft.Resolve`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Resolve) · [`weft.ResolveError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ResolveError) · [`weft.ResumeOf`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ResumeOf) · [`weft.ParkOn`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ParkOn) · [`weft.ParkAllExcept`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ParkAllExcept) · [`weft.ParkSource`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ParkSource) · [`Agent.ParkSources`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.ParkSources) · [`weft.ErrApprovalRequired`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrApprovalRequired) · [`weft.ErrApprovalDenied`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrApprovalDenied) · [`weft.Call`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Call) · [`weft.CallFromContext`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#CallFromContext) · [`weft.RunResult`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunResult) · [`weft.RunFinish`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunFinish) · [`weft.ToolCallPart`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolCallPart) · [`weft.Messages`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Messages) · [`weft.Metadata`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Metadata) · [`weft.WrapTools`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#WrapTools) · [`weft.ToolCaller`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolCaller) · [`weft.ToolSource`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolSource) · [`weft.ToolError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolError) · [`weft.Tool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Tool) · [`weft.New`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#New) · [`weft.Name`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Name) · [`weft.Prompt`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Prompt) · [`wefttest.Script`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Script)
