Skip to content

Support desk with human approval

View as Markdown

A support agent that may issue refunds needs a person between the model’s request and the money. Mark the refund tool with weft.RequireApproval: the run ends successfully with the call on res.Pending, you store the transcript as JSON, and any later process resumes it with weft.Approve, weft.Deny or weft.Resolve. The refund handler runs once per resume, after the decision, or never.

The desk agent in cookbook/supportdesk/main.go:

cookbook/supportdesk/main.go
// newDesk builds the support agent. Build it once per process: the
// resuming process builds its own and gets the same tools.
func newDesk(model weft.Model, sh *shop) *weft.Agent {
lookup := weft.Tool("lookup_order", "Look up an order by id: item, amount and delivery status.",
func(_ context.Context, in OrderInput) (Order, error) {
o, ok := sh.orders[in.OrderID]
if !ok {
return Order{}, weft.Errorf("ORDER_NOT_FOUND", "no order %q", in.OrderID)
}
return o, nil
})
refund := weft.Tool("issue_refund", "Refund an order. A human approves every refund before it runs.",
func(_ context.Context, in RefundInput) (string, error) {
sh.refunds.Add(1)
return fmt.Sprintf("refund of %.2f issued for order %s", in.Amount, in.OrderID), nil
},
weft.RequireApproval(), // the call parks; the run ends with it on res.Pending
)
return weft.New(model,
weft.Name("support-desk"),
weft.Instructions("You are a customer support agent. Look the order up first. "+
"Refund a damaged item in full with issue_refund; a human approves refunds. "+
"When the case is handled, submit your resolution."),
weft.Output[Resolution](), // the run ends on a valid submit_output call
weft.MaxSteps(8),
lookup, refund,
)
}

cookbook/supportdesk/main.go on GitHub

The shape comes from the weft-arena scenarios rw.support-desk and rw.ops-human-loop. A customer reports a broken espresso machine. The agent looks the order up, asks for a full refund, and later submits a typed Resolution. Between the request and the refund there is a person, and that person’s decision may arrive in another process, hours later.

Approval is a run boundary (rule 12, ADR 0007). Nothing blocks while the decision waits. The parked run is finished, and its transcript is the only state:

  1. Run 1 calls lookup_order, then issue_refund. The refund parks, the run ends with RunFinish.StoppedBy reading parked, and res.Pending holds the call.
  2. The app stores the run id, the pending call ids and res.Messages as one JSON value.
  3. A person approves. A fresh process decodes the JSON, builds its own agent and runs again with the transcript and the decision.
  4. Run 2 executes the approved call before its first model call, then the model submits the resolution.

Run the request and read what parked. Every part of a weft.Message carries a type discriminator, so the transcript round-trips through encoding/json losslessly. The resume decodes it and passes one decision per pending call:

cookbook/supportdesk/main.go
var t ticket
if err := json.Unmarshal(stored, &t); err != nil { // every part carries its "type"
return "", "", err
}
decisions := []weft.RunOption{
weft.Messages(t.Messages...), // the transcript is the only state
weft.ResumeOf(t.RunID), // links the two runs in the record
weft.Metadata(map[string]string{"app": "support", "weft.approval.actor": "agent-7"}),
}
for _, id := range t.Pending {
decisions = append(decisions, weft.Approve(id))
}
out, res, err := weft.GenerateAs[Resolution](ctx, newDesk(model, sh), decisions...)

cookbook/supportdesk/main.go on GitHub

weft.GenerateAs returns the decoded Resolution from the last valid submit_output call. weft.ResumeOf changes nothing the model sees. It links the two runs in the record, so Studio’s parked run names the run that resumed it. The weft.approval.actor key names the person who decided, on every span and record of the resuming run.

The package example ExampleRequireApproval is the same boundary in a dozen lines: one parked call, one Approve, one answer.

The second half of the program is an incident. An on-call agent checks a failing service’s metrics, then asks in one step to restart it, delete its logs and scale it to 10 replicas. Two tools are built with RequireApproval. The third, scale_service, is gated by a change-freeze middleware that parks large scale-ups only:

cookbook/supportdesk/main.go
// changeFreeze parks any scale-up above 5 replicas until a person
// decides. An approved call comes back through the chain with
// Call.Approved set, and passes.
func changeFreeze(next weft.ToolCaller) weft.ToolCaller {
return func(ctx context.Context, tc weft.ToolCallPart) (string, error) {
if c, _ := weft.CallFromContext(ctx); tc.Name == "scale_service" && !c.Approved {
var in ScaleInput
if json.Unmarshal(tc.Args, &in) == nil && in.Replicas > 5 {
return "", fmt.Errorf("change freeze: scale-ups above 5 replicas need a human: %w", weft.ErrApprovalRequired)
}
}
return next(ctx, tc)
}
}

cookbook/supportdesk/main.go on GitHub

Returning an error that wraps weft.ErrApprovalRequired parks the call exactly as RequireApproval does. On resume the approved call comes back through the chain with Call.Approved set, so the middleware lets it pass.

The person decides each call differently. The transcript crosses JSON first, as in the desk:

cookbook/supportdesk/main.go
res, err := newSRE(second, in).Generate(ctx,
weft.Messages(msgs...),
weft.Approve("a1"), // runs now, once, with Call.Approved set
weft.Deny("a2", "compliance hold: logs must be retained for 90 days"),
weft.Resolve("a3", "on-call scaled checkout-api to 8 replicas (cluster cap)"), // the handler never runs
weft.ResumeOf(parked.ID),
)

cookbook/supportdesk/main.go on GitHub

  • Approve runs the restart now, once.
  • Deny never runs delete_logs. The model sees DENIED: compliance hold: logs must be retained for 90 days.
  • Resolve never runs scale_service. The text you pass is the call’s result: on-call did the work by hand and reports what happened.

Resolve is the strict one. On an id that is not pending it fails the run at step 0, where Approve and Deny ignore unknown ids.

Both runs are recorded by otel.Install(otel.Local("")). Open them with weft studio on the same database, or embed Studio as Run Studio shows. The program reads back what the runs list shows:

  • The parked run’s status row reads stopped_by=parked, and its resumed_by names the resume. In the runs list, the parked status filter finds runs waiting for a decision.
  • The resume carries weft.resumed_from and weft.resume.calls (rf1=approved) on its invoke_agent span. On the run page, the parked call shows a ToolStart and no ToolFinish in run 1, and its result in run 2.
  • In the incident, the denied delete_logs call has a zero-length execute_tool span marked weft.tool.denied. The resolved scale_service call has no span at all: its handler never ran.
The support desk's parked run in Studio: the header reads parked, one call decided and resumed in the next run; step 0 looked order 1002 up and step 1's issue_refund call is pendingThe support desk's parked run in Studio: the header reads parked, one call decided and resumed in the next run; step 0 looked order 1002 up and step 1's issue_refund call is pending
The desk's parked run on Studio's run page: parked, one call decided, with a link to the run that resumed it; issue_refund waits as pending.
FeatureWhat it does hereGuide
weft.RequireApprovalparks every issue_refund, restart_service and delete_logs callRequire human approval for a tool
Middleware returning ErrApprovalRequiredparks scale_service above 5 replicas onlyAdd behaviour with middleware
weft.Messages over JSONcarries the parked transcript to another processContinue a conversation
Approve, Deny, Resolve, ResumeOfsettle each parked call and link the runsRequire human approval for a tool
weft.Output and GenerateAsthe desk’s typed ResolutionGet structured output from a run
otel.Install(otel.Local(""))records both runs for StudioRecord every run with otel.Install

cookbook/supportdesk/main.go runs the desk and the incident against scripted models:

cookbook/supportdesk/main.go
// Command supportdesk is the recipe "Support desk with human approval":
// go run ./cookbook/supportdesk. A support agent's refund parks for a
// human, the parked transcript is stored as JSON, and a fresh agent value
// resumes it with Approve. The second half is an on-call incident with
// three gated actions decided three ways: Approve, Deny and Resolve.
// Every model is 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"
"encoding/json"
"fmt"
"io"
"os"
"strings"
"sync/atomic"
"github.com/weftgo/weft"
"github.com/weftgo/weft/otel"
"github.com/weftgo/weft/wefttest"
)
// Resolution is the desk's structured outcome, submitted with
// submit_output when the case is handled.
type Resolution struct {
Action string `json:"action" jsonschema:"what was done: refunded, replaced, declined or escalated"`
OrderID string `json:"order_id" jsonschema:"the order id"`
Refunded bool `json:"refunded" jsonschema:"whether a refund was issued"`
Note string `json:"note" jsonschema:"one sentence for the customer"`
}
// Order is what lookup_order returns; a struct output reaches the model
// as JSON.
type Order struct {
OrderID string `json:"order_id"`
Item string `json:"item"`
Amount float64 `json:"amount"`
Status string `json:"status"`
}
type OrderInput struct {
OrderID string `json:"order_id" jsonschema:"the order id, e.g. 1002"`
}
type RefundInput struct {
OrderID string `json:"order_id" jsonschema:"the order id"`
Amount float64 `json:"amount" jsonschema:"amount to refund"`
Reason string `json:"reason" jsonschema:"why"`
}
// shop is the desk's backend: the orders it knows and how many refunds
// it has issued.
type shop struct {
orders map[string]Order
refunds atomic.Int32
}
func newShop() *shop {
return &shop{orders: map[string]Order{
"1002": {OrderID: "1002", Item: "espresso machine", Amount: 249.90, Status: "delivered"},
}}
}
// newDesk builds the support agent. Build it once per process: the
// resuming process builds its own and gets the same tools.
func newDesk(model weft.Model, sh *shop) *weft.Agent {
lookup := weft.Tool("lookup_order", "Look up an order by id: item, amount and delivery status.",
func(_ context.Context, in OrderInput) (Order, error) {
o, ok := sh.orders[in.OrderID]
if !ok {
return Order{}, weft.Errorf("ORDER_NOT_FOUND", "no order %q", in.OrderID)
}
return o, nil
})
refund := weft.Tool("issue_refund", "Refund an order. A human approves every refund before it runs.",
func(_ context.Context, in RefundInput) (string, error) {
sh.refunds.Add(1)
return fmt.Sprintf("refund of %.2f issued for order %s", in.Amount, in.OrderID), nil
},
weft.RequireApproval(), // the call parks; the run ends with it on res.Pending
)
return weft.New(model,
weft.Name("support-desk"),
weft.Instructions("You are a customer support agent. Look the order up first. "+
"Refund a damaged item in full with issue_refund; a human approves refunds. "+
"When the case is handled, submit your resolution."),
weft.Output[Resolution](), // the run ends on a valid submit_output call
weft.MaxSteps(8),
lookup, refund,
)
}
// ticket is what the app stores while a refund waits for a person: the
// parked run's id, the calls to decide, and the transcript.
type ticket struct {
RunID string `json:"run_id"`
Pending []string `json:"pending"`
Messages []weft.Message `json:"messages"`
}
// deskTurn runs the customer's request until the refund parks, and
// returns the ticket as the JSON the app would store.
func deskTurn(ctx context.Context, w io.Writer, sh *shop) ([]byte, error) {
model := wefttest.Script(
wefttest.ToolCalls(wefttest.Call{ID: "lk1", Name: "lookup_order", Args: `{"order_id":"1002"}`}),
wefttest.ToolCalls(wefttest.Call{ID: "rf1", Name: "issue_refund", Args: `{"order_id":"1002","amount":249.9,"reason":"arrived broken"}`}),
)
res, err := newDesk(model, sh).Generate(ctx,
weft.Prompt("Hi, my order 1002 arrived broken. I'd like a full refund please."),
weft.Metadata(map[string]string{"app": "support"}))
if err != nil {
return nil, err
}
fmt.Fprintln(w, "looked up:", res.Steps[0].Results[0].Content)
t := ticket{RunID: res.ID, Messages: res.Messages}
for _, pc := range res.Pending {
fmt.Fprintf(w, "parked: %s %s %s\n", pc.ID, pc.Name, pc.Args)
t.Pending = append(t.Pending, pc.ID)
}
fmt.Fprintln(w, "refunds issued before a decision:", sh.refunds.Load())
return json.Marshal(t)
}
// deskResume is the process that picks the ticket up after a person
// approved it: a fresh model and agent, the transcript decoded from JSON.
func deskResume(ctx context.Context, w io.Writer, sh *shop, stored []byte) (parkedID, resumeID string, err error) {
model := wefttest.Script(
wefttest.ToolCalls(wefttest.Call{ID: "so1", Name: "submit_output",
Args: `{"action":"refunded","order_id":"1002","refunded":true,"note":"Your refund of 249.90 is on its way."}`}),
)
var t ticket
if err := json.Unmarshal(stored, &t); err != nil { // every part carries its "type"
return "", "", err
}
decisions := []weft.RunOption{
weft.Messages(t.Messages...), // the transcript is the only state
weft.ResumeOf(t.RunID), // links the two runs in the record
weft.Metadata(map[string]string{"app": "support", "weft.approval.actor": "agent-7"}),
}
for _, id := range t.Pending {
decisions = append(decisions, weft.Approve(id))
}
out, res, err := weft.GenerateAs[Resolution](ctx, newDesk(model, sh), decisions...)
if err != nil {
return "", "", err
}
for _, r := range resultsOf(res, "issue_refund") {
fmt.Fprintf(w, "%s %s → %s\n", r.CallID, r.Name, r.Content)
}
fmt.Fprintf(w, "resolution: %+v\n", out)
fmt.Fprintln(w, "refunds issued after approval:", sh.refunds.Load())
return t.RunID, res.ID, nil
}
// infra counts what the on-call agent's gated handlers really did.
type infra struct {
restarts, deletes, scales atomic.Int32
}
type ServiceInput struct {
Service string `json:"service" jsonschema:"the service, e.g. checkout-api"`
}
type RestartInput struct {
Service string `json:"service" jsonschema:"the service"`
Env string `json:"env" jsonschema:"environment, e.g. prod"`
}
type DeleteLogsInput struct {
Service string `json:"service" jsonschema:"the service"`
Days int `json:"older_than_days" jsonschema:"age threshold in days"`
}
type ScaleInput struct {
Service string `json:"service" jsonschema:"the service"`
Replicas int `json:"replicas" jsonschema:"desired replica count"`
}
// changeFreeze parks any scale-up above 5 replicas until a person
// decides. An approved call comes back through the chain with
// Call.Approved set, and passes.
func changeFreeze(next weft.ToolCaller) weft.ToolCaller {
return func(ctx context.Context, tc weft.ToolCallPart) (string, error) {
if c, _ := weft.CallFromContext(ctx); tc.Name == "scale_service" && !c.Approved {
var in ScaleInput
if json.Unmarshal(tc.Args, &in) == nil && in.Replicas > 5 {
return "", fmt.Errorf("change freeze: scale-ups above 5 replicas need a human: %w", weft.ErrApprovalRequired)
}
}
return next(ctx, tc)
}
}
func newSRE(model weft.Model, in *infra) *weft.Agent {
metrics := weft.Tool("get_metrics", "Error rate and latency for a service.",
func(_ context.Context, s ServiceInput) (string, error) {
return s.Service + ": error rate 23%, p99 4.1s, 3 replicas", nil
})
restart := weft.Tool("restart_service", "Restart a service. Needs human approval.",
func(_ context.Context, r RestartInput) (string, error) {
in.restarts.Add(1)
return r.Service + " restarted in " + r.Env, nil
}, weft.RequireApproval())
deleteLogs := weft.Tool("delete_logs", "Delete a service's logs older than N days. Needs human approval.",
func(_ context.Context, _ DeleteLogsInput) (string, error) {
in.deletes.Add(1)
return "deleted", nil
}, weft.RequireApproval())
scale := weft.Tool("scale_service", "Set a service's replica count.",
func(_ context.Context, s ScaleInput) (string, error) {
in.scales.Add(1)
return fmt.Sprintf("%s scaled to %d", s.Service, s.Replicas), nil
})
return weft.New(model, weft.Name("sre"), weft.MaxSteps(8),
weft.WrapTools(changeFreeze),
metrics, restart, deleteLogs, scale)
}
// incident: three gated actions in one step, decided three ways after
// the transcript crossed JSON.
func incident(ctx context.Context, w io.Writer) error {
in := &infra{}
first := wefttest.Script(
wefttest.ToolCalls(wefttest.Call{ID: "m1", Name: "get_metrics", Args: `{"service":"checkout-api"}`}),
wefttest.ToolCalls(
wefttest.Call{ID: "a1", Name: "restart_service", Args: `{"service":"checkout-api","env":"prod"}`},
wefttest.Call{ID: "a2", Name: "delete_logs", Args: `{"service":"checkout-api","older_than_days":30}`},
wefttest.Call{ID: "a3", Name: "scale_service", Args: `{"service":"checkout-api","replicas":10}`},
),
)
parked, err := newSRE(first, in).Generate(ctx,
weft.Prompt("checkout-api is failing. Check its metrics, then restart it in prod, delete its logs older than 30 days and scale it to 10 replicas."))
if err != nil {
return err
}
var names []string
for _, pc := range parked.Pending {
names = append(names, pc.ID+" "+pc.Name)
}
fmt.Fprintln(w, "parked:", strings.Join(names, ", "))
stored, err := json.Marshal(parked.Messages)
if err != nil {
return err
}
var msgs []weft.Message
if err := json.Unmarshal(stored, &msgs); err != nil {
return err
}
second := wefttest.Script(wefttest.Say("Restarted checkout-api. Log deletion was refused (compliance hold). On-call scaled it to 8 replicas."))
res, err := newSRE(second, in).Generate(ctx,
weft.Messages(msgs...),
weft.Approve("a1"), // runs now, once, with Call.Approved set
weft.Deny("a2", "compliance hold: logs must be retained for 90 days"),
weft.Resolve("a3", "on-call scaled checkout-api to 8 replicas (cluster cap)"), // the handler never runs
weft.ResumeOf(parked.ID),
)
if err != nil {
return err
}
for _, name := range []string{"restart_service", "delete_logs", "scale_service"} {
for _, r := range resultsOf(res, name) {
fmt.Fprintf(w, "%s %s → %s\n", r.CallID, r.Name, r.Content)
}
}
fmt.Fprintf(w, "handlers ran: restart=%d delete=%d scale=%d\n", in.restarts.Load(), in.deletes.Load(), in.scales.Load())
fmt.Fprintln(w, "answer:", res.Text())
return nil
}
// resultsOf returns every result of the named tool in the transcript.
func resultsOf(res *weft.RunResult, name string) []weft.ToolResultPart {
var out []weft.ToolResultPart
for _, m := range res.Messages {
for _, p := range m.Content {
if r, ok := p.(weft.ToolResultPart); ok && r.Name == name {
out = append(out, r)
}
}
}
return out
}
func run(ctx context.Context, w io.Writer) error {
defer otel.Install(otel.Local(""))() // record both runs: Studio reads them back
fmt.Fprintln(w, "== support desk")
sh := newShop()
stored, err := deskTurn(ctx, w, sh)
if err != nil {
return err
}
parkedID, resumeID, err := deskResume(ctx, w, sh, stored)
if err != nil {
return err
}
// What Studio shows: the parked run names the run that resumed it.
db := otel.LocalDB()
parked, err := db.Run(ctx, parkedID)
if err != nil {
return err
}
fmt.Fprintf(w, "recorded: parked run stopped_by=%s, resumed_by is the resume: %t\n",
parked.StoppedBy, parked.ResumedBy == resumeID)
fmt.Fprintln(w, "== ops incident")
return incident(ctx, w)
}
func main() {
if err := run(context.Background(), os.Stdout); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}

View cookbook/supportdesk/main.go on GitHub

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

Terminal window
go run ./cookbook/supportdesk
go test ./cookbook/supportdesk
== support desk
looked up: {"order_id":"1002","item":"espresso machine","amount":249.9,"status":"delivered"}
parked: rf1 issue_refund {"order_id":"1002","amount":249.9,"reason":"arrived broken"}
refunds issued before a decision: 0
rf1 issue_refund → refund of 249.90 issued for order 1002
resolution: {Action:refunded OrderID:1002 Refunded:true Note:Your refund of 249.90 is on its way.}
refunds issued after approval: 1
recorded: parked run stopped_by=parked, resumed_by is the resume: true
== ops incident
parked: a1 restart_service, a2 delete_logs, a3 scale_service
a1 restart_service → checkout-api restarted in prod
a2 delete_logs → DENIED: compliance hold: logs must be retained for 90 days
a3 scale_service → on-call scaled checkout-api to 8 replicas (cluster cap)
handlers ran: restart=1 delete=0 scale=0
answer: Restarted checkout-api. Log deletion was refused (compliance hold). On-call scaled it to 8 replicas.

The tests also pin that the refund runs once after one approval and one resume, and that the change freeze lets a 4-replica scale-up through. weft’s own examples/approval is the smallest version of this program: one refund, a decision read from standard input, and the resume.

  • Store the run id with the transcript. The core cannot infer which run a resume continues; without ResumeOf Studio cannot link the parked run to its decision. (Source: weft/core/run.go:209-223)
  • Pass a decision for every pending call. With at least one decision present, an undecided call is denied with DENIED: no decision. A transcript fed back with no decision at all is not a resume: the parked call is repaired as no result recorded: the call was interrupted. (Source: weft/core/loop.go:120-128, weft/core/repair.go:16, test TestNoDecisionAtAll)
  • Let ErrApprovalRequired through your own middleware. A tool middleware that rewrites every error turns a park into an ordinary error result. mw.MapErrors passes it through for this reason. (Source: weft/core/mw/tool.go:104 godoc)
  • Resuming does not consume the stored ticket. The transcript is the only resume state, so two processes that resume the same ticket both run issue_refund. Resume it once (mark the ticket decided, or keep the conversation in weft/thread, whose writer lease admits one writer), and make the refund handler idempotent. (Source: weft/core/run.go:118-123, weft/core/loop.go:327-353, AGENTS.md T1)
  • Build a fresh agent in the resuming process. An agent holds no run state, so a new value with the same tools resumes the transcript. (Source: AGENTS.md block 2, weft/examples/approval/main.go)
  • Treat approval as policy, not security. It is a UX and policy seam; a sandbox around the tool contains a compromised prompt or tool. (Source: ADR 0007)

Symbols used: weft.RequireApproval · weft.Approve · weft.Deny · weft.Resolve · weft.ResumeOf · weft.ErrApprovalRequired · weft.CallFromContext · weft.Messages · weft.Message · weft.Metadata · weft.Output · weft.GenerateAs · weft.Errorf · weft.WrapTools · weft.ToolCaller · weft.Tool · weft.New · otel.Install · otel.Local · otel.LocalDB · obsdb.RunRow · wefttest.Script