Require human approval for a tool
weft.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 or weft.Deny. Nothing blocks in between, so the decision can arrive over any transport, hours later.
The refund tool in 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)How it works
Section titled “How it works”Approval is a run boundary (rule 12, ADR 0007). A call that needs a decision is parked: 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 and RunFinish.Pending.
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
Section titled “Require approval”RequireApproval is a tool option. ToolDef.RequiresApproval() reports whether a tool has it. Run the agent, then read what parked:
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)}pending c2: refund_order {"order_id":"1234","amount":40}pending c3: refund_order {"order_id":"1234","amount":900}lookup ran: order 1234 was deliveredlookup_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 with ID, Name and Args to show the person deciding.
Approve and deny
Section titled “Approve and deny”Resume by passing the parked transcript back with weft.Messages and one decision per call:
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}c2 refund_order → refunded $40.00 on order 1234 (approved: true)c3 refund_order → DENIED: over the refund limitBefore its first model call the resuming run settles every parked call:
- Approved calls run through the ordinary tool chain. The handler’s
weft.CallFromContextreportsCall.Approved == true. They emitToolStartandToolFinishin 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 seesDENIED: no decision.
The cause on a denied call’s error result is weft.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
Section titled “Resume an approval”The resume path, from docs/life-of-a-call.md:
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 = truedenied → DENIED: <reason>; undecided → DENIED: no decision │ ▼results complete the earlier tool message → first model call of this runThe 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).
Resolve
Section titled “Resolve”weft.Resolve(id, content) 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:
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),)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 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
Section titled “Link the resume to the parked run”weft.ResumeOf(res.ID) 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.


Name the decider
Section titled “Name the decider”Pass the approver as run metadata under the key weft.approval.actor, as the resume region does with weft.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) 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) 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 (approved by a grant, g_refunds) and ExampleDenyBy (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.
Park calls for one run
Section titled “Park calls for one run”weft.ParkOn(names...) 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:
// 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"))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.
Park all except
Section titled “Park all except”weft.ParkAllExcept(names...) 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:
// 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"))- The rule applies by name to the tool each call resolves to in its step’s dispatch snapshot, so a tool only a
weft.ToolSourcesupplies 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
RequireApprovaltool or aParkOnname parks whether or not it is listed here, and severalParkAllExceptoptions let through only the names all of them list. - With no names every call parks, except the agent’s own
weft.Outputsubmission,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. Both options change the run’s override fingerprint (weft.override.* on its span).
Park from a source
Section titled “Park from a source”weft.ParkSource(fn) gives the agent a park set that can change between runs (ADR 0030). The loop calls fn once per run, at its start, and merges the names it returns as a ParkOn would:
var mu sync.Mutexbreakpoints := []string{"refund_order"} // changed elsewhere, e.g. by an admin pageagt = 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 }),)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() returns the agent’s sources in order. The playground’s runtime.Breakpoints() is one (Breakpoints); the package example is ExampleParkSource.
Park from middleware
Section titled “Park from middleware”Tool middleware parks any call by returning an error that wraps weft.ErrApprovalRequired. Read Call.Approved to let the approved call through on resume:
// 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) }}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.
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
Section titled “Complete example”approvals/main.go parks, approves, denies, resolves, and parks per run and from middleware, all against scripted models:
// 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) }}View on GitHub · run it from docs-site/examples:
go run ./approvalsgo test ./approvals== park and resumepending c2: refund_order {"order_id":"1234","amount":40}pending c3: refund_order {"order_id":"1234","amount":900}lookup ran: order 1234 was deliveredc2 refund_order → refunded $40.00 on order 1234 (approved: true)c3 refund_order → DENIED: over the refund limitanswer: I refunded $40; the $900 refund was declined.== resolveq1 run_sql → count: 42answer: There are 42 orders.== park per runParkOn pending: [c2 refund_order]ParkAllExcept pending: [c2 refund_order]ParkSource pending: [c2 refund_order] sources: 1== park from middlewareran: 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 asks for the decision on standard input.
Best practices & gotchas
Section titled “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.IDand the call id that only the first request can claim. Make side-effecting handlers idempotent too, or useweft/thread, which records each decision and spends it on the resume that applies it (Approvals in sessions). (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;
HasToolCallfires 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
Section titled “See also”- What does a run return?:
Pendingon the result - Approvals in sessions:
threadadds persistence, grants and signed decisions - Add behaviour with middleware
- Continue a conversation
Symbols used: weft.RequireApproval · ToolDef.RequiresApproval · weft.Approve · weft.Deny · weft.Resolve · weft.ResolveError · weft.ResumeOf · weft.ParkOn · weft.ParkAllExcept · weft.ParkSource · Agent.ParkSources · weft.ErrApprovalRequired · weft.ErrApprovalDenied · weft.Call · weft.CallFromContext · weft.RunResult · weft.RunFinish · weft.ToolCallPart · weft.Messages · weft.Metadata · weft.WrapTools · weft.ToolCaller · weft.ToolSource · weft.ToolError · weft.Tool · weft.New · weft.Name · weft.Prompt · wefttest.Script