A governed agent stack: every seam on one run
Governance in weft is middleware on its two seams, not a separate layer. weft.WrapModel wraps every model call and weft.WrapTools every tool call; in both lists the first entry is the outermost. A token limiter, a cache, an audit log, an allowlist, a rate limiter and a PII scrubber are each a closure at one of them, and recording has its own content policy on the observability pipeline.
The stack in cookbook/governed/main.go:
opts := append(tools(), weft.Name("payments"), weft.MaxSteps(8), weft.WrapModel( // first listed = outermost tokenLimit(2048), // refuse before the provider bills c.middleware, // a hit never reaches the provider ), weft.WrapTools( // first listed = outermost mw.Audit(audit), // sees every call, denied ones included mw.Allow(func(call weft.Call) bool { return call.Name != "wire_transfer" }), rateLimit(20*time.Millisecond), mw.MapErrors(nil), // a raw error becomes INTERNAL; its text stays the cause Audit logs scrubPII, // innermost: masks results and errors before any layer above sees them ),)agt := weft.New(model, opts...)How it works
Section titled “How it works”The shape comes from the weft-arena scenario rw.governed-enterprise. A payments agent looks a customer up, then asks in one step to wire money, refund an order and export a report. Every call passes the stack:
model call: tokenLimit → cache → providertool call: Audit → Allow → rateLimit → MapErrors → scrubPII → (approval check) → handlermw.Auditis outermost, so it logs every call, the onesmw.Allowrefuses included.mw.Allowrefuseswire_transfer. The handler never runs, and the model seesDENIED: tool "wire_transfer" is not allowed.rateLimitspaces the calls that pass, across every run of the agent.mw.MapErrors(nil)turnsexport_report’s raw database error intoINTERNAL: tool "export_report" failedand keeps the original as the cause, whichmw.Auditlogs.scrubPIIis innermost, so no layer above it, and not the model, sees an e-mail address.issue_refundis built withweft.RequireApproval. Its check sits at the base of the chain, inside every middleware, so the call parks after passing the stack, and runs on resume.
Seams are the product
Section titled “Seams are the product”The governance features other frameworks ship as processors need no processor layer here (README, ADR 0006). Each is a closure at one of the two seams, carrying its own dependencies and policy instead of importing yours. Package mw stays a reference set, and the patterns live as tested examples:
| Pattern | Seam | In weft |
|---|---|---|
| PII scrub | tool | an example: Example_piiScrubMiddleware |
| Allowlist | tool | shipped: mw.Allow(permit) |
| Token limiter | model | an example: Example_tokenLimitMiddleware; weft.UsageLimit covers the measured side |
| Response cache | model | an example: Example_responseCacheMiddleware; invalidation is the caller’s policy |
| Rate limit | tool | an example: Example_rateLimitMiddleware |
A named mw middleware ships only when a pattern needs a dependency or a policy stance weft should own. Rate limiting is the precedent: it stays an example because golang.org/x/time would be the module’s first dependency. The README says to revisit that when a consumer asks for one by name. This recipe’s versions of the four patterns follow.
Token limiter
Section titled “Token limiter”A token limiter refuses a model call before the provider bills it, when the transcript the request carries is over budget. Bytes stand in for tokens here: the real count arrives with the step’s finish, and by then weft.UsageLimit covers it.
// tokenLimit refuses a model call before the provider bills it when the// request's transcript is over budget, bytes standing in for tokens.// weft.UsageLimit covers the measured side, after each step.func tokenLimit(maxBytes int) weft.ModelMiddleware { return func(next weft.Model) weft.Model { return limited{next, maxBytes} }}
type limited struct { next weft.Model max int}
func (m limited) Info() weft.ModelInfo { return weft.InfoOf(m.next) }
func (m limited) Stream(ctx context.Context, req weft.ModelRequest) iter.Seq2[weft.ModelEvent, error] { n := 0 for _, msg := range req.Messages { n += len(msg.Text()) } if n > m.max { return func(yield func(weft.ModelEvent, error) bool) { yield(nil, fmt.Errorf("token limit: request transcript is %d bytes, over the %d-byte budget", n, m.max)) } } return m.next.Stream(ctx, req)}The refusal is a model failure, so the run fails at step 0 with token limit: request transcript is 2700 bytes, over the 2048-byte budget inside a *weft.RunError. Forwarding Info keeps the provider and model name on the run’s record.
Response cache
Section titled “Response cache”A response cache is model middleware keyed on the weft.ModelRequest: the same system prompt, messages and tool names replay the recorded events without a provider call.
// cache replays a recorded answer for a request it has seen: the system// prompt, the messages and the tool names are the key, so any change// misses. The mutex is there because one Agent serves concurrent runs.type cache struct { mu sync.Mutex seen map[string][]weft.ModelEvent hits int}
func (c *cache) middleware(next weft.Model) weft.Model { return cached{next, c} }
type cached struct { next weft.Model c *cache}
func (m cached) Info() weft.ModelInfo { return weft.InfoOf(m.next) }
func (m cached) Stream(ctx context.Context, req weft.ModelRequest) iter.Seq2[weft.ModelEvent, error] { names := make([]string, len(req.Tools)) for i, td := range req.Tools { names[i] = td.Name } b, _ := json.Marshal(struct { System string Messages []weft.Message Tools []string }{req.System, req.Messages, names}) sum := sha256.Sum256(b) key := hex.EncodeToString(sum[:8])
m.c.mu.Lock() events, ok := m.c.seen[key] if ok { m.c.hits++ } m.c.mu.Unlock() if ok { return func(yield func(weft.ModelEvent, error) bool) { for _, ev := range events { if !yield(ev, nil) { return } } } } return func(yield func(weft.ModelEvent, error) bool) { var got []weft.ModelEvent for ev, err := range m.next.Stream(ctx, req) { if err != nil { yield(nil, err) // a failure is never cached return } got = append(got, ev) if !yield(ev, nil) { return } } m.c.mu.Lock() m.c.seen[key] = got m.c.mu.Unlock() }}Invalidation is yours: here any change to the request misses. A failed stream is never stored. The map has a mutex because one agent serves concurrent runs, and the cache is shared by all of them. In the program the same question asked twice makes one provider call.
PII scrub
Section titled “PII scrub”A scrubber on the tool seam masks what the model, and so every transcript downstream, is shown. It scrubs both channels, because the loop renders an error’s text into the transcript too:
var email = regexp.MustCompile(`[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}`)
// scrubPII masks e-mail addresses in what a tool returns, on both// channels: the loop renders an error's text into the transcript too.// The errors the loop itself reads pass through untouched: rewriting// ErrApprovalRequired would stop a RequireApproval call from parking.func scrubPII(next weft.ToolCaller) weft.ToolCaller { return func(ctx context.Context, tc weft.ToolCallPart) (string, error) { out, err := next(ctx, tc) if err != nil { if errors.Is(err, weft.ErrApprovalRequired) || ctx.Err() != nil { return "", err } var te *weft.ToolError if errors.As(err, &te) { // keep the code the model branches on return "", &weft.ToolError{Code: te.Code, Message: email.ReplaceAllString(te.Message, "[redacted]")} } return "", errors.New(email.ReplaceAllString(err.Error(), "[redacted]")) } return email.ReplaceAllString(out, "[redacted]"), nil }}Two choices differ from weft’s own example. The errors the loop reads itself, weft.ErrApprovalRequired and the context errors, pass through untouched: rewriting them would stop a RequireApproval call from parking. A *weft.ToolError from the handler keeps its code (for example ORDER_NOT_FOUND), so the model can still branch on it. The cause chain is dropped on purpose: a scrubber that keeps the original reachable is no scrubber.
Rate limit
Section titled “Rate limit”A limiter on the tool seam spaces calls at least an interval apart, with nothing but the standard library:
// rateLimit spaces tool calls at least interval apart, across every run// of the agent, with the standard library alone. A call waiting for its// slot gives up when its ctx ends.func rateLimit(interval time.Duration) weft.ToolMiddleware { var mu sync.Mutex var next time.Time // the next free slot reserve := func() time.Duration { mu.Lock() defer mu.Unlock() now := time.Now() if next.Before(now) { next = now // idle time is never banked } wait := next.Sub(now) next = next.Add(interval) return wait } return func(call weft.ToolCaller) weft.ToolCaller { return func(ctx context.Context, tc weft.ToolCallPart) (string, error) { if wait := reserve(); wait > 0 { t := time.NewTimer(wait) defer t.Stop() select { case <-t.C: case <-ctx.Done(): return "", ctx.Err() } } return call(ctx, tc) } }}A slot in the past is pulled up to now, so idle time is never banked and the calls after a quiet stretch are still spaced. A call waiting for its slot gives up when its ctx ends. The limiter’s state is shared by every run of the agent, so it bounds the agent’s total call rate.
Park a refund and record with a content policy
Section titled “Park a refund and record with a content policy”The refund parks inside the stack; the program resumes it with weft.Approve, and the approved call passes the stack again, mw.Audit logging it under step 0 of the resuming run. See Support desk with human approval for the boundary itself.
What the model sees and what is recorded are different policies. The customer’s prompt carries a card number, and the model needs it. The record does not: the local sink’s content policy redacts it on every content field it is given before it is written (a tools record is capped, never redacted).
var card = regexp.MustCompile(`\b(?:\d[ -]?){12,15}\d\b`)
// redactCards is the local sink's content policy: it runs on every// content field before it is recorded, never on what the model sees.func redactCards(_ weft.ContentKind, s string) string { return card.ReplaceAllString(s, "[card]")}defer otel.Install( otel.Local(""), // the local sink; content on otel.Content(otel.ContentConfig{Redact: redactCards}),)()otel.Content sets the pipeline-wide default for destinations with content on, and otel.Local is one. Redact sees the content fields of events and deltas; in a transcript record, every text, reasoning, tool-argument and tool-result part, never file parts, ids, names, roles, signatures or hashes; a prompt record’s text; each stop sequence of a request record; bridged app log lines; and, in dev only, raw wire bodies (otel.RawBodies). It never runs on what the model is sent. The program reads the parked run’s transcript back from the local sink: [card] is there and the number is not.
What to look at in Studio
Section titled “What to look at in Studio”- The audit line per call. The program prints them: the denied transfer, the
pending=truerefund, the export with itscause, and the approved refund in the resuming run. - Problem counters. The run page counts the denied transfer under
deniedand the export undertool_errors, readINTERNAL ← plain error:MapErrorshid a plain Go error (the attribute records*errors.errorString); see Read a run in Studio. - The redacted transcript. Studio reads what the sink stored, so the run’s prompt shows
[card]. A destination with content off stores no transcript at all; see Control what content leaves the process. - The resume link. The resuming run names the parked one, as in the support desk.
![The governed payments run in Studio, parked: the header counts one INTERNAL tool error and one denied call, the prompt shows the card number redacted as [card], and step 1's wire_transfer reads DENIED, issue_refund pending and export_report INTERNAL](/docs/_astro/studio-run-governed.light.ILXOS4Na.webp)
![The governed payments run in Studio, parked: the header counts one INTERNAL tool error and one denied call, the prompt shows the card number redacted as [card], and step 1's wire_transfer reads DENIED, issue_refund pending and export_report INTERNAL](/docs/_astro/studio-run-governed.dark.DylfHInT.webp)
The weft features it combines
Section titled “The weft features it combines”| Feature | What it does here | Guide |
|---|---|---|
weft.WrapModel, weft.WrapTools | the two seams, outermost first | Add behaviour with middleware |
mw.Audit, mw.Allow, mw.MapErrors | the shipped reference middleware | Add behaviour with middleware |
weft.RequireApproval | parks the refund inside the stack | Require human approval for a tool |
weft.UsageLimit | the measured token budget beside the limiter | How does a run stop? |
otel.Content with Redact | what the record keeps | Control what content leaves the process |
The program
Section titled “The program”// Command governed is the recipe "A governed agent stack: every seam on// one run": go run ./cookbook/governed. A payments agent runs inside a// token limiter and a response cache on the model seam, and an audit// log, an allowlist, a rate limiter, a PII scrubber and an error mapper// on the tool seam. A refund waits for a human, and the local sink's// content policy redacts card numbers from what is recorded. The models// are scripted with wefttest, so it runs offline; the runs are recorded// to the local sink ($WEFT_DB, else ./.weft/weft.db).package main
import ( "bytes" "context" "crypto/sha256" "encoding/hex" "encoding/json" "errors" "fmt" "io" "iter" "log/slog" "os" "regexp" "slices" "strings" "sync" "time"
"github.com/weftgo/weft" "github.com/weftgo/weft/mw" "github.com/weftgo/weft/otel" "github.com/weftgo/weft/wefttest")
// ---- the model seam ----
// tokenLimit refuses a model call before the provider bills it when the// request's transcript is over budget, bytes standing in for tokens.// weft.UsageLimit covers the measured side, after each step.func tokenLimit(maxBytes int) weft.ModelMiddleware { return func(next weft.Model) weft.Model { return limited{next, maxBytes} }}
type limited struct { next weft.Model max int}
func (m limited) Info() weft.ModelInfo { return weft.InfoOf(m.next) }
func (m limited) Stream(ctx context.Context, req weft.ModelRequest) iter.Seq2[weft.ModelEvent, error] { n := 0 for _, msg := range req.Messages { n += len(msg.Text()) } if n > m.max { return func(yield func(weft.ModelEvent, error) bool) { yield(nil, fmt.Errorf("token limit: request transcript is %d bytes, over the %d-byte budget", n, m.max)) } } return m.next.Stream(ctx, req)}
// cache replays a recorded answer for a request it has seen: the system// prompt, the messages and the tool names are the key, so any change// misses. The mutex is there because one Agent serves concurrent runs.type cache struct { mu sync.Mutex seen map[string][]weft.ModelEvent hits int}
func (c *cache) middleware(next weft.Model) weft.Model { return cached{next, c} }
type cached struct { next weft.Model c *cache}
func (m cached) Info() weft.ModelInfo { return weft.InfoOf(m.next) }
func (m cached) Stream(ctx context.Context, req weft.ModelRequest) iter.Seq2[weft.ModelEvent, error] { names := make([]string, len(req.Tools)) for i, td := range req.Tools { names[i] = td.Name } b, _ := json.Marshal(struct { System string Messages []weft.Message Tools []string }{req.System, req.Messages, names}) sum := sha256.Sum256(b) key := hex.EncodeToString(sum[:8])
m.c.mu.Lock() events, ok := m.c.seen[key] if ok { m.c.hits++ } m.c.mu.Unlock() if ok { return func(yield func(weft.ModelEvent, error) bool) { for _, ev := range events { if !yield(ev, nil) { return } } } } return func(yield func(weft.ModelEvent, error) bool) { var got []weft.ModelEvent for ev, err := range m.next.Stream(ctx, req) { if err != nil { yield(nil, err) // a failure is never cached return } got = append(got, ev) if !yield(ev, nil) { return } } m.c.mu.Lock() m.c.seen[key] = got m.c.mu.Unlock() }}
// ---- the tool seam ----
var email = regexp.MustCompile(`[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}`)
// scrubPII masks e-mail addresses in what a tool returns, on both// channels: the loop renders an error's text into the transcript too.// The errors the loop itself reads pass through untouched: rewriting// ErrApprovalRequired would stop a RequireApproval call from parking.func scrubPII(next weft.ToolCaller) weft.ToolCaller { return func(ctx context.Context, tc weft.ToolCallPart) (string, error) { out, err := next(ctx, tc) if err != nil { if errors.Is(err, weft.ErrApprovalRequired) || ctx.Err() != nil { return "", err } var te *weft.ToolError if errors.As(err, &te) { // keep the code the model branches on return "", &weft.ToolError{Code: te.Code, Message: email.ReplaceAllString(te.Message, "[redacted]")} } return "", errors.New(email.ReplaceAllString(err.Error(), "[redacted]")) } return email.ReplaceAllString(out, "[redacted]"), nil }}
// rateLimit spaces tool calls at least interval apart, across every run// of the agent, with the standard library alone. A call waiting for its// slot gives up when its ctx ends.func rateLimit(interval time.Duration) weft.ToolMiddleware { var mu sync.Mutex var next time.Time // the next free slot reserve := func() time.Duration { mu.Lock() defer mu.Unlock() now := time.Now() if next.Before(now) { next = now // idle time is never banked } wait := next.Sub(now) next = next.Add(interval) return wait } return func(call weft.ToolCaller) weft.ToolCaller { return func(ctx context.Context, tc weft.ToolCallPart) (string, error) { if wait := reserve(); wait > 0 { t := time.NewTimer(wait) defer t.Stop() select { case <-t.C: case <-ctx.Done(): return "", ctx.Err() } } return call(ctx, tc) } }}
type CustomerInput struct { CustomerID string `json:"customer_id" jsonschema:"the customer id"`}
type WireInput struct { ToAccount string `json:"to_account" jsonschema:"IBAN"` Amount float64 `json:"amount" jsonschema:"amount in EUR"`}
type RefundInput struct { OrderID string `json:"order_id" jsonschema:"the order id"` Amount float64 `json:"amount" jsonschema:"amount in EUR"`}
// tools are the payments agent's four tools.func tools() []weft.Option { getCustomer := weft.Tool("get_customer", "Customer record by id.", func(_ context.Context, in CustomerInput) (map[string]string, error) { return map[string]string{"id": in.CustomerID, "name": "Jane Doe", "email": "jane.doe@example.com", "plan": "pro"}, nil }) wire := weft.Tool("wire_transfer", "Send money to an account.", func(_ context.Context, _ WireInput) (string, error) { return "sent", nil }) refund := weft.Tool("issue_refund", "Refund an order. A human approves every refund.", func(_ context.Context, in RefundInput) (string, error) { return fmt.Sprintf("refunded %.2f EUR on order %s", in.Amount, in.OrderID), nil }, weft.RequireApproval()) export := weft.Tool("export_report", "Account report for a customer.", func(_ context.Context, _ CustomerInput) (string, error) { return "", errors.New("pq: connection refused (host 10.0.4.7, user reports_rw)") }) return []weft.Option{getCustomer, wire, refund, export}}
// newAgent builds the governed agent. audit receives one line per tool// call; c is the response cache, shared by every run of the agent.func newAgent(model weft.Model, audit *slog.Logger, c *cache) *weft.Agent { opts := append(tools(), weft.Name("payments"), weft.MaxSteps(8), weft.WrapModel( // first listed = outermost tokenLimit(2048), // refuse before the provider bills c.middleware, // a hit never reaches the provider ), weft.WrapTools( // first listed = outermost mw.Audit(audit), // sees every call, denied ones included mw.Allow(func(call weft.Call) bool { return call.Name != "wire_transfer" }), rateLimit(20*time.Millisecond), mw.MapErrors(nil), // a raw error becomes INTERNAL; its text stays the cause Audit logs scrubPII, // innermost: masks results and errors before any layer above sees them ), ) agt := weft.New(model, opts...) return agt}
// auditLogger writes mw.Audit's lines without the fields that change// from run to run (time, run id, duration).func auditLogger(w io.Writer) *slog.Logger { return slog.New(slog.NewTextHandler(w, &slog.HandlerOptions{ ReplaceAttr: func(_ []string, a slog.Attr) slog.Attr { switch a.Key { case slog.TimeKey, slog.LevelKey, "run", "dur": return slog.Attr{} } return a }, }))}
var card = regexp.MustCompile(`\b(?:\d[ -]?){12,15}\d\b`)
// redactCards is the local sink's content policy: it runs on every// content field before it is recorded, never on what the model sees.func redactCards(_ weft.ContentKind, s string) string { return card.ReplaceAllString(s, "[card]")}
func run(ctx context.Context, w io.Writer) error { defer otel.Install( otel.Local(""), // the local sink; content on otel.Content(otel.ContentConfig{Redact: redactCards}), )()
var audit bytes.Buffer c := &cache{seen: map[string][]weft.ModelEvent{}} model := wefttest.Script( wefttest.ToolCalls(wefttest.Call{ID: "c1", Name: "get_customer", Args: `{"customer_id":"7"}`}), wefttest.ToolCalls( wefttest.Call{ID: "c2", Name: "wire_transfer", Args: `{"to_account":"FR76-0001","amount":500}`}, wefttest.Call{ID: "c3", Name: "issue_refund", Args: `{"order_id":"A-1","amount":59}`}, wefttest.Call{ID: "c4", Name: "export_report", Args: `{"customer_id":"7"}`}, ), wefttest.Say("Refunded 59 EUR. The wire transfer is not allowed and the report failed."), wefttest.Say("We open at 9:00."), ) agt := newAgent(model, auditLogger(&audit), c)
start := time.Now() parked, err := agt.Generate(ctx, weft.Prompt("Customer 7 paid with card 4242 4242 4242 4242. Wire 500 EUR to FR76-0001, refund order A-1 and export the report.")) if err != nil { return err } fmt.Fprintln(w, "== run 1") for _, st := range parked.Steps { for _, r := range st.Results { fmt.Fprintf(w, "%s → %s\n", r.Name, r.Content) } } for _, pc := range parked.Pending { fmt.Fprintln(w, "parked:", pc.ID, pc.Name) } fmt.Fprintln(w, "rate limiter spaced the calls:", time.Since(start) >= 2*20*time.Millisecond)
run1Audit := audit.Len() // run 1's audit lines end here fmt.Fprintln(w, "== run 2: the refund approved") res, err := agt.Generate(ctx, weft.Messages(parked.Messages...), weft.Approve("c3"), weft.ResumeOf(parked.ID)) if err != nil { return err } for _, m := range res.Messages { for _, p := range m.Content { if r, ok := p.(weft.ToolResultPart); ok && r.CallID == "c3" { fmt.Fprintf(w, "%s → %s\n", r.Name, r.Content) } } } fmt.Fprintln(w, "answer:", res.Text())
fmt.Fprintln(w, "== audit") // One step's calls log as they finish, so their order varies between // runs: print each run's lines sorted. for _, part := range []string{audit.String()[:run1Audit], audit.String()[run1Audit:]} { lines := strings.Split(strings.TrimSpace(part), "\n") slices.Sort(lines) fmt.Fprintln(w, strings.Join(lines, "\n")) }
fmt.Fprintln(w, "== content policy") sent := strings.Contains(model.Requests()[0].Messages[0].Text(), "4242 4242 4242 4242") bodies, err := otel.LocalDB().Transcript(ctx, parked.ID) if err != nil { return err } var recorded string for _, b := range bodies { recorded += string(b) } fmt.Fprintln(w, "the model saw the card:", sent) fmt.Fprintln(w, "the record holds the card:", strings.Contains(recorded, "4242 4242"), "holds [card]:", strings.Contains(recorded, "[card]"))
fmt.Fprintln(w, "== cache and token limit") for range 2 { if _, err := agt.Generate(ctx, weft.Prompt("When do you open?")); err != nil { return err } } fmt.Fprintln(w, "provider calls:", len(model.Requests()), "cache hits:", c.hits) _, err = agt.Generate(ctx, weft.Prompt(strings.Repeat("too long ", 300))) fmt.Fprintln(w, "oversized prompt:", err) return nil}
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 ./cookbook/governedgo test ./cookbook/governed== run 1get_customer → {"email":"[redacted]","id":"7","name":"Jane Doe","plan":"pro"}wire_transfer → DENIED: tool "wire_transfer" is not allowedexport_report → INTERNAL: tool "export_report" failedparked: c3 issue_refundrate limiter spaced the calls: true== run 2: the refund approvedissue_refund → refunded 59.00 EUR on order A-1answer: Refunded 59 EUR. The wire transfer is not allowed and the report failed.== auditmsg="tool call" step=0 call=c1 tool=get_customer result_bytes=62msg="tool call" step=1 call=c2 tool=wire_transfer err="DENIED: tool \"wire_transfer\" is not allowed"msg="tool call" step=1 call=c3 tool=issue_refund pending=truemsg="tool call" step=1 call=c4 tool=export_report err="INTERNAL: tool \"export_report\" failed" cause="pq: connection refused (host 10.0.4.7, user reports_rw)"msg="tool call" step=0 call=c3 tool=issue_refund result_bytes=31== content policythe model saw the card: truethe record holds the card: false holds [card]: true== cache and token limitprovider calls: 4 cache hits: 1oversized prompt: weft: run failed at step 0: model stream: token limit: request transcript is 2700 bytes, over the 2048-byte budgetThe audit logger drops the time, the level, the run id and the duration, and the program prints each run’s lines sorted: calls of one step log as they finish, so their order varies. The lines are then stable. The tests also pin that no e-mail address or database detail reaches the transcript, and that a scrubber which rewrites every error stops the refund from parking.
Best practices & gotchas
Section titled “Best practices & gotchas”- Pass
ErrApprovalRequiredand context errors through any middleware that rewrites errors. Turned into a plain error, a park becomes an ordinary error result and the refund never waits for a person.mw.MapErrorspasses them through; weft’s ownExample_piiScrubMiddlewarerewrites every error and would not. (Source:weft/core/mw/tool.go:104godoc, testTestNaiveScrubberBreaksParking) - Order the tool chain on purpose. First listed is outermost:
mw.Auditoutsidemw.Allowlogs refused calls, and a scrubber innermost hides PII from every layer above it. (Source: AGENTS.md rule 10) - Put
mw.MapErrorsoutside the scrubber to keep a cause. The scrubber drops the cause chain;MapErrorsoutside it keeps the scrubbed raw error as the causemw.Auditlogs. (Source:weft/core/mw/tool.go:53, 95 godoc) - Share middleware state safely. A cache or a limiter built once is used by every concurrent run of the agent: guard it with a mutex. (Source:
weft/core/mw/governance_test.go:111-117) - Redact in the pipeline, scrub in the chain.
otel.Content’sRedactshapes only what is recorded; tool middleware shapes what the model sees. Each needs its own rule. (Source:weft/otel/options.go:22-54)
See also
Section titled “See also”- Add behaviour with middleware (the two seams): the seams and the shipped middleware
- Control what content leaves the process: per-destination content, redaction, content kinds
- Require human approval for a tool
- Design principles: the rules weft keeps
Symbols used: weft.WrapModel · weft.WrapTools · weft.ModelMiddleware · weft.ToolMiddleware · weft.ToolCaller · weft.ModelRequest · weft.ModelEvent · weft.InfoOf · weft.ToolError · weft.ErrApprovalRequired · weft.RequireApproval · weft.Approve · weft.UsageLimit · weft.ContentKind · mw.Audit · mw.Allow · mw.MapErrors · otel.Install · otel.Local · otel.Content · otel.ContentConfig · otel.LocalDB · wefttest.Script