Approvals in sessions
In a session, a tool call that needs approval parks as a durable request entry, written with the turn that parked it. s.Pending() lists the undecided requests, after a restart too, and s.Decide(ctx, thread.Approve(id)) records the decision and resumes the conversation on its own. The core’s approval boundary (weft.RequireApproval, Require human approval) is unchanged; the session makes it durable.
sessions/approvals.go parks a refund, restarts the process by reopening the JSONL file, and approves:
s, err := thread.Create(ctx, st, agent, ids("s_refund", "a"))if err != nil { return err}parked, err := s.Send(ctx, weft.User("Refund order 1234."))if err != nil { return err}res, err := parked.Wait() // the run ends successfully, parkedif err != nil { return err}fmt.Fprintln(w, "turn:", parked.Outcome(), "| pending calls:", len(res.Pending))if err := s.Close(ctx); err != nil { // the process stops return err}
s, err = thread.Open(ctx, st, "s_refund", agent, ids("", "b")) // and starts againif err != nil { return err}for _, r := range s.Pending() { // requests are entries: they survive the restart fmt.Fprintln(w, "pending:", r.CallID, r.Tool, string(r.Args), "|", r.Reason, "| request", r.ID)}resume, err := s.Decide(ctx, thread.Approve("call_1")) // recorded, then resumedif err != nil { return err}res, err = resume.Wait()if err != nil { return err}fmt.Fprintln(w, "resumed:", res.Text(), "| run:", resume.RunID())turn: parked | pending calls: 1pending: call_1 refund {"order_id":"1234"} | tool requires approval | request e_a4resumed: Refund issued for order 1234. | run: s_refund-t2The parked turn ended successfully with the call on res.Pending. The request survived the restart because it is an entry; Decide completed the boundary, so the session started the resume run, s_refund-t2, and returned its *thread.Turn.
How it works
Section titled “How it works”- A parked call is a request. Each becomes an
approval_requestentry (call id, tool, arguments and their SHA-256, run id, reason, optional expiry) in the same append as the turn entry that ends the turn (the step messages were already written as they joined), so no window exists where the turn is durable and the request is not. Athread.Requestis its view;Reasonistool requires approvalfor aRequireApprovaltool andmiddleware required approvalwhen the tool chain parked it. - The decision chain runs first. Before a call parks, the session asks, in order: the grants, then an optional live
Approver, then it parks. Every step writes an audit entry, automatic approvals included. The chain runs after the core run has ended at the boundary, so a call a grant or the Approver decides still ends its turnparked; the session resumes at once and the parked turn’sNextis that resume. - Decisions are entries.
Decidewritesapproval_decisionentries; when every pending call of the boundary has one, the session resumes with the core’sApprove,Deny,ResolveorResolveError(AutoResume, on by default). The resume runs on the deciding call’s context for cancellation and takes the parked turn’s context values for every key that context lacks. - A decision belongs to one occurrence. Call ids repeat across turns (ADR 0021 §1); the request entry’s id and the run that parked it do not. Decisions fold per parked run, never per bare call id, and a decision is spent by the resume that applies it: after a
Branchback to a decided boundary, or aForkof one, the calls are pending again and need new decisions. A resume that finished never runs an approved call twice on one approval. A crash after a resume’sstartedentry and before an approved call’s result is recorded leaves that call’s decision in force, so the next resume runs it again (after a crash). - The boundary holds the session. A plain
Sendwhile approvals pend queues behind the boundary; only the resume resolves it. Compaction is held too:Compactfails withthread.ErrAwaitingApprovaland the trigger stands down (compaction). ABranchaway from the boundary is the documented way out.
Approval is a policy seam, not a security boundary (AGENTS rule 12). A decision that crosses a process boundary should be signed (Sign approval decisions).
Decide
Section titled “Decide”A thread.Decision is one call’s outcome. Build it with a constructor; set Who yourself:
| Constructor | Kind | What the model sees |
|---|---|---|
thread.Approve(id) | OutcomeApprove | the tool’s own result; it runs with Call.Approved set |
thread.ApproveAlways(id) | OutcomeApprove, Always: true | the same, and a grant for these exact arguments (grants) |
thread.Deny(id, reason) | OutcomeDeny | DENIED: <reason>, as an error result |
thread.Resolve(id, content) | OutcomeResolve | content, verbatim; the handler never runs |
thread.ResolveError(id, content) | OutcomeResolveError | content, marked as an error |
Its CallID names the pending call, Kind the outcome, Reason a deny’s text and Content a resolve’s payload. The thread.Outcome values are stored bytes: approve, deny, resolve, resolve_error. A decision entry with any other value never resolves a call. One Decide can carry a whole batch, here three calls parked by one step:
_, err = s.Decide(ctx, thread.Approve("call_a"), thread.Deny("call_a", "twice"))fmt.Fprintln(w, "one call, two verdicts:", errors.Is(err, thread.ErrInvalidDecision))_, err = s.Decide(ctx, thread.Approve("call_9"))fmt.Fprintln(w, "not pending:", errors.Is(err, thread.ErrNotPending))
no := thread.Deny("call_a", "over the refund limit")no.Who = "agent-7" // an opaque id for the audit trailif _, err := s.Decide(ctx, no, thread.Resolve("call_b", "refunded by hand: ticket 88"), // the handler never runs thread.ResolveError("call_c", "the payment provider is down"),); err != nil { return err}res, err := parked.Next().Wait() // the resume the decisions startedif err != nil { return err}results(w, s)fmt.Fprintln(w, "answer:", res.Text())one call, two verdicts: truenot pending: truecall_a: DENIED: over the refund limit (error: true)call_b: refunded by hand: ticket 88 (error: false)call_c: the payment provider is down (error: true)answer: One refund was denied, one done by hand, one failed.The batch is validated whole and recorded in one atomic append; on any error none of it is recorded and no run starts on its account. Expired requests are denied first, on every call, and those denials stand and can start the resume even when Decide then returns an error (expiry):
| Error | When |
|---|---|
thread.ErrInvalidDecision | no decisions, a decision without an outcome, or two decisions for one call |
thread.ErrNotPending | a call that is not pending, raised before any of the batch lands or runs |
thread.ErrExpired | a request past its expiry (expiry) |
thread.ErrSignatureRequired | the session requires signed decisions |
thread.ErrDelegated | a call that delegates to a thread/pool child; decide the child’s request instead (pools) |
Whois the caller’s declaration, verified by nobody, and the identityQuorumcounts for unsigned decisions. The run that applies the decision carries it as theweft.approval.actormetadata pair on every span and record, to every destination and through content-off; on aQuorum(n > 1)resume it names every approver that counted toward the quorum, sorted and comma-joined (since 0.18.0; before, the last signer alone). Put an opaque id in it, never an email or a name.Vianames the channel and the session fills it:userforDecideandsignedforDecideSigned, whatever the field holds. Its own paths recordgrant,approver(an Approver’s answer may name its own),expiry,interrupt, and the pool’schildandparent.Nextfollows the flow.Decidereturns the resume’sTurnwhen it completed the boundary, andnil, nilotherwise. The parked turn’sNextis the sameTurn, whichever path armed it. After a restart the parkedTurnvalue is gone; use whatDecidereturns (ExampleTurn_Next).- Split verdicts deny. A deny beside an approve, an approve beside a resolve (either order), or two resolves fold to a deny with the pinned reason
conflicting decisions. A deny alone resolves. The session’s own denials (expiry, an interruptingSend) are the exception: they resolve with their own stated reason even beside an approval. - Decisions are durable when
Decidereturns underthread.FsyncOnFlush, as areGrant,RevokeandPin.
The package example is ExampleSession_Decide.
Resume by hand
Section titled “Resume by hand”With thread.AutoResume(false) the session records decisions as they arrive and waits; s.Resume(ctx) starts the resume now, denying every undecided call with the core’s no decision text:
s, err := thread.Create(ctx, thread.Memory(), agent, ids("s_resume", "a"), thread.AutoResume(false))if err != nil { return err}parked, err := s.Send(ctx, weft.User("Deploy to both regions."))if err != nil { return err}if _, err := parked.Wait(); err != nil { return err}turn, err := s.Decide(ctx, thread.Approve("call_eu"))fmt.Fprintln(w, "decided; resumed on its own:", turn != nil, err)resume, err := s.Resume(ctx) // the undecided call is deniedif err != nil { return err}if _, err := resume.Wait(); err != nil { return err}results(w, s)decided; resumed on its own: false <nil>call_eu: deployed to eu (error: false)call_us: DENIED: no decision (error: true)Resume with no open boundary fails with ErrNotPending. A second Resume while the first is armed or running returns that same turn: one boundary resumes once. Expired requests are denied first, as on every path (ExampleSession_Resume).
Grants
Section titled “Grants”A thread.Grant approves future calls without asking, or with Deny refuses them. s.Grant(ctx, g) appends it as an entry; s.Revoke(ctx, grantID) ends it with another:
err = s.Grant(ctx, thread.Grant{ // every refund whose order id starts with "12" Tool: "refund", Args: []thread.Arg{thread.ArgPrefix("/order_id", "12")},})if err != nil { return err}err = s.Grant(ctx, thread.Grant{ // a standing refusal Tool: "refund", Deny: true, Reason: "order 9999 is under review", Args: []thread.Arg{thread.ArgEquals("/order_id", []byte(`"9999"`))},})if err != nil { return err}if _, err := ask("Refund 1234."); err != nil { // the prefix grant approves it return err}parked, err := ask("Refund 5678.") // no grant matches: it parksif err != nil { return err}if _, err := s.Decide(ctx, thread.ApproveAlways("call_2")); err != nil { // approve, and grant these exact args return err}if _, err := settle(parked); err != nil { return err}if _, err := ask("Refund 5678 again."); err != nil { // the minted grant approves it return err}if _, err := ask("Refund 9999."); err != nil { // the deny-grant refuses it return err}for _, e := range s.Entries() { // revoke the prefix grant: an appended entry if g, ok := e.(thread.GrantEntry); ok && len(g.Args) == 1 && g.Args[0].Prefix == "12" { if err := s.Revoke(ctx, g.ID); err != nil { return err } }}if _, err := ask("Refund 1299."); err != nil { // parks again return err}Refund 1234. → "Refunded 1234." pending: 0Refund 5678. → "" pending: 1Refund 5678 again. → "Refunded 5678 again." pending: 0Refund 9999. → "Order 9999 cannot be refunded." pending: 0Refund 1299. → "" pending: 1The model saw DENIED: order 9999 is under review for the refused call. The grant’s fields:
Toolis matched exactly and must not be empty: a grant for every tool is a policy this shape does not have.Argsarethread.Argpredicates, every one of which must match; none matches any arguments. Each has aPointer, an RFC 6901 JSON pointer such as/order_id, and one test:Equals,PrefixorGlob(tried in that order on a hand-madeArgwith several).Denymakes it a standing refusal;Reasonis then the model-visible text,denied by grantwhen empty, or a note on an approval grant.Expirylapses it (zero: never), strictly after the time.MaxUsesbounds how often a session grant matches (0: unlimited), counted from its audit entries, within one turn too; a deny-grant’s matches count as well.
Build the predicates with their constructors:
thread.ArgEquals(pointer, value): JSON equality. Strings and booleans exactly, arrays and objects deeply (key order never matters); two integers compare digit for digit, and once either side has a fraction or an exponent both compare asfloat64. Pointer""is the whole arguments document; no arguments read as{}.thread.ArgPrefix(pointer, prefix): a plain string prefix. End it with the separator, or/wsmatches/ws-evil. An empty prefix matches nothing.thread.ArgGlob(pointer, glob):*matches any run,?one code point, every other character itself. There is no escape, and*spans separators:go test*matchesgo test ./...and anything after it on the line.
Array indexes in a pointer are strict (/01 is not /1). The chain consults session grants newest first, from the next boundary on. A match writes a StepGrant audit entry whose GrantID names the grant, which is one way to find the id Revoke needs; the other is the thread.GrantEntry in s.Entries().
Approve and always allow. thread.ApproveAlways(id) approves the call and mints a session grant for the tool plus the call’s exact arguments, so the next such call never parks. The grant is minted only when the call’s effective verdict is approve: with the decision when one approval resolves it, with the completing approval under Quorum, never beside a denial. Always on a deny or a resolve records the decision and nothing else. A richer grant (a glob, a prefix) is s.Grant’s to make (ExampleSession_Grant).
Shared grants. thread.WithGrantStore(gs) adds an application-wide scope behind the thread.GrantStore interface you implement. Its one method, Grants(ctx) ([]SharedGrant, error), returns the live grants in the order they are tried, first match wins. The chain calls it after the session’s own grants, once per gated call per turn that no session grant matched, on the runner goroutine, holding no session lock; the turn waits for the answer, so answer from memory. An error reads as no match, with a warning. Each thread.SharedGrant is an ID for the audit trail plus the Grant; its expiry, uses and revocation are the store’s to enforce. The store must be safe for concurrent use.
s.Grant is an in-process, unsigned call: whoever can call it can pre-approve, under RequireSigned too.
Approvers, quorum and expiry
Section titled “Approvers, quorum and expiry”A live approver. thread.WithApprover(a, timeout) sets the chain’s “ask now” step, a thread.Approver: consulted after grants and before parking, under a context with timeout as its deadline. It returns a Decision and true, or false to decline, and the call parks. thread.OnRequest(fn) is told when a request parks:
approver := func(ctx context.Context, r thread.Request) (thread.Decision, bool) { if !strings.Contains(string(r.Args), `"staging"`) { return thread.Decision{}, false // not mine to decide: the call parks } d := thread.Approve(r.CallID) d.Who = "ci-bot" return d, true}s, err := thread.Create(ctx, thread.Memory(), agent, ids("s_deploy", "a"), thread.WithApprover(approver, 2*time.Second), // asked before a call parks, bounded thread.OnRequest(func(r thread.Request) { // after the request is durable fmt.Fprintln(w, "notify:", r.Tool, string(r.Args), "parked as", r.ID) }))if err != nil { return err}for _, q := range []string{"Deploy to staging.", "Now prod."} { turn, err := s.Send(ctx, weft.User(q)) if err != nil { return err } res, err := settle(turn) if err != nil { return err } fmt.Fprintf(w, "%s → %q pending: %d\n", q, res.Text(), len(s.Pending()))}Deploy to staging. → "Staging is live." pending: 0notify: deploy {"env":"prod"} parked as e_a14Now prod. → "" pending: 1- The timeout must be positive;
CreateandOpenfail otherwise. A timeout or a panic reads as a decline, audited. Before thread 0.9.0 the timeout was a separate option; it is now this required argument. - The
Requestthe Approver gets has noID,NonceorCreated: the chain asks before the request is persisted. It must not call back into the same session; the turn is still running. OnRequestruns after the request entry is durable, once per parked call, in call order, synchronously on the runner, before the parking turn’sWaitreturns. A slowfnholds the session, so hand the request to a queue and return. It may callPendingorRequest; it must not wait for the turn that calls it. A panic is contained and logged.
The package example is ExampleWithApprover.
Quorum. thread.Quorum(n) needs approvals from n distinct approver identities before a call resolves:
s, err := thread.Create(ctx, thread.Memory(), agent, ids("s_quorum", "a"), thread.Quorum(2))if err != nil { return err}parked, err := s.Send(ctx, weft.User("Deploy to prod."))if err != nil { return err}if _, err := parked.Wait(); err != nil { return err}approve := func(who string) (*thread.Turn, error) { d := thread.Approve("call_1") d.Who = who // unsigned: a declared identity return s.Decide(ctx, d)}resume, err := approve("alice")fmt.Fprintln(w, "after alice:", resume != nil, err, "| pending:", len(s.Pending()))resume, err = approve("bob")if err != nil { return err}res, err := resume.Wait()if err != nil { return err}fmt.Fprintln(w, "after bob:", res.Text())after alice: false <nil> | pending: 1after bob: Prod is live.Values below 2 mean one decision resolves. A deny resolves alone, and conflicting decisions deny with conflicting decisions. An identity depends on the door: a signed approval is its key, whatever Who it carries; an unsigned approval is its Who, which one caller can write twice under two names; a grant’s approval is one identity of its own. A grant or an Approver’s single approval under Quorum(2) leaves the boundary waiting for the second identity. A quorum that must hold against the deciding process needs RequireSigned and one key per approver (ExampleQuorum).
Expiry. thread.RequestExpiry(d) gives every request a lifetime: strictly past Created + d it takes no decision. The demo moves the session’s clock (thread.Clock) instead of sleeping:
c := &clock{t: base}s, err := thread.Create(ctx, thread.Memory(), agent, ids("s_expiry", "a"), thread.Clock(c.now), thread.RequestExpiry(10*time.Minute))if err != nil { return err}parked, err := s.Send(ctx, weft.User("Deploy to prod."))if err != nil { return err}if _, err := parked.Wait(); err != nil { return err}fmt.Fprintln(w, "expires:", s.Pending()[0].Expiry.Format(time.RFC3339))
c.advance(11 * time.Minute) // nobody decided in time_, err = s.Decide(ctx, thread.Approve("call_1"))fmt.Fprintln(w, "too late:", errors.Is(err, thread.ErrExpired))if _, err := parked.Next().Wait(); err != nil { // the expiry's denial resumed the boundary return err}results(w, s)expires: 2026-10-18T09:10:00Ztoo late: truecall_1: DENIED: expired: no decision before 2026-10-18T09:10:00Z (error: true)Nothing fires on a timer. An expired request is denied with its stated reason the next time the session looks at the boundary: a Decide, DecideSigned, Request, Resume, a Send, or the runner’s own pickup. Those denials stand even when the call that found them returns ErrExpired, and when they complete the boundary the resume starts; reach it through the parked turn’s Next, or Resume.
ErrExpired answers only the path that finds the lapse. Once one path has denied the request, it is no longer pending: a later Decide, DecideSigned or Request for it fails with ErrNotPending. The runner’s pickup runs right after a parked turn’s Wait returns, so it can be that first path. A retry after ErrExpired reads ErrNotPending too. Values of d at or below zero, the default, mean requests never expire (ExampleRequestExpiry).
The audit trail
Section titled “The audit trail”s.Audit() returns every request, chain step, decision, grant and revocation the session recorded, in order, as thread.ApprovalRequestEntry, thread.ApprovalAuditEntry, thread.ApprovalDecisionEntry, thread.GrantEntry and thread.GrantRevokedEntry. The expiry session above:
for _, e := range s.Audit() { switch e := e.(type) { case thread.ApprovalRequestEntry: fmt.Fprintln(w, "request:", e.CallID, e.Tool, "|", e.Reason) case thread.ApprovalAuditEntry: // Detail is prose for a human, never parsed line := "step: " + e.Step + " " + e.Outcome if e.Detail != "" { line += " | " + e.Detail } fmt.Fprintln(w, line) case thread.ApprovalDecisionEntry: fmt.Fprintln(w, "decision:", e.CallID, e.Outcome, "via", e.Via, "|", e.Reason) }}request: call_1 deploy | tool requires approvalstep: park parkedstep: expiry denied | request expired at 2026-10-18T09:10:00Zdecision: call_1 deny via expiry | expired: no decision before 2026-10-18T09:10:00Zstep: resume started | 1 call(s) to resolvestep: resume completedAn audit entry’s Step is one of:
| Step | Written when |
|---|---|
StepGrant (grant) | a live grant decided; GrantID names it, GrantShared marks a store’s |
StepApprover (approver) | the Approver was consulted: decided, declined or timed out |
StepPark (park) | the request persisted and the turn ended pending |
StepExpiry (expiry) | an expired request was denied |
StepResume (resume) | twice per resume: started before the run, listing the decisions it applies, then completed or failed |
StepSigned (signed) | a signed decision was refused; no decision beside it (signed approvals) |
A started entry with no second entry after it is a resume that never finished: a crash, or a run still in flight. Detail is prose for a human and never parsed; what the session reads back lives in typed fields. The trail is an index of the session’s log, not tamper-evidence: entries are plain appended lines, unsigned and unchained, so whoever can write the storage can change them. Put tamper-evidence in the storage, such as an append-only volume or a signed export (ExampleSession_Audit).
The approvals example
Section titled “The approvals example”weft ships thread/examples/approvals: it parks a call, restarts by reopening the JSONL file, decides signed, resumes, replays a rejected signature and prints the audit trail, offline, its output pinned by its test. From the weft repository:
go run ./thread/examples/approvals== a session parks a gated callparked: deploy as call_1== the process restarts; the pending request survivedpending after reopen: 1unsigned: true== the UI asks for a challenge and signs a decisionchallenge: call call_1 key k1resumed: Deployed. The change is live.== a replayed signature fails closedreplay: thread: decision signature replayed: nonce already decided call "call_1"== the audit trailrequest call_1 on deployaudit park parkeddecision call_1 approve via signedaudit resume started (1 call(s) to resolve)audit resume completedaudit signed refused (replayed)With -serve addr the same gate runs as a small web app whose parked turns are decided from the devtools panel.
Complete example
Section titled “Complete example”sessions/approvals.go decides across a restart, decides a batch, grants, consults an approver, needs a quorum, lets a request expire and resumes by hand:
package main
import ( "context" "errors" "fmt" "io" "strings" "sync" "time"
"github.com/weftgo/weft" "github.com/weftgo/weft/thread" "github.com/weftgo/weft/thread/jsonl" "github.com/weftgo/weft/wefttest")
// demoApprovals is the page "Approvals in sessions".func demoApprovals(ctx context.Context, w io.Writer, dir string) error { steps := []func(context.Context, io.Writer, string) error{ approvalsDecide, approvalsOutcomes, approvalsGrant, approvalsApprover, approvalsQuorum, approvalsExpiry, approvalsResume, } for _, step := range steps { if err := step(ctx, w, dir); err != nil { return err } } return nil}
// refundTool refunds an order, and only after a decision.func refundTool() *weft.ToolDef { return weft.Tool("refund", "Refund an order.", func(ctx context.Context, in struct { OrderID string `json:"order_id"` }) (string, error) { return "refunded " + in.OrderID, nil }, weft.RequireApproval())}
// refundCall is a model turn asking to refund one order.func refundCall(id, order string) wefttest.Turn { return wefttest.ToolCalls(wefttest.Call{Name: "refund", ID: id, Args: `{"order_id":"` + order + `"}`})}
// results prints every tool result the session's context holds,// leaving out the calls still pending (the context shows those// repaired, as interrupted).func results(w io.Writer, s *thread.Session) { pending := map[string]bool{} for _, r := range s.Pending() { pending[r.CallID] = true } for _, m := range s.Context() { for _, p := range m.Content { if r, ok := p.(weft.ToolResultPart); ok && !pending[r.CallID] { fmt.Fprintf(w, "%s: %s (error: %v)\n", r.CallID, r.Content, r.IsError) } } }}
// settle waits for a turn and, while the session resumed its boundary,// for each resume after it (Turn.Next); it returns the last result.func settle(t *thread.Turn) (*weft.RunResult, error) { res, err := t.Wait() if err != nil { return nil, err } if next := t.Next(); next != nil { return settle(next) } return res, nil}
// approvalsDecide: a parked call survives a restart, and Decide// records the decision and resumes.func approvalsDecide(ctx context.Context, w io.Writer, dir string) error { fmt.Fprintln(w, "== decide") agent := weft.New(wefttest.Script( refundCall("call_1", "1234"), wefttest.Say("Refund issued for order 1234."), ), refundTool()) st, err := jsonl.Open(dir) if err != nil { return err } s, err := thread.Create(ctx, st, agent, ids("s_refund", "a")) if err != nil { return err } parked, err := s.Send(ctx, weft.User("Refund order 1234.")) if err != nil { return err } res, err := parked.Wait() // the run ends successfully, parked if err != nil { return err } fmt.Fprintln(w, "turn:", parked.Outcome(), "| pending calls:", len(res.Pending)) if err := s.Close(ctx); err != nil { // the process stops return err }
s, err = thread.Open(ctx, st, "s_refund", agent, ids("", "b")) // and starts again if err != nil { return err } for _, r := range s.Pending() { // requests are entries: they survive the restart fmt.Fprintln(w, "pending:", r.CallID, r.Tool, string(r.Args), "|", r.Reason, "| request", r.ID) } resume, err := s.Decide(ctx, thread.Approve("call_1")) // recorded, then resumed if err != nil { return err } res, err = resume.Wait() if err != nil { return err } fmt.Fprintln(w, "resumed:", res.Text(), "| run:", resume.RunID()) results(w, s) return s.Close(ctx)}
// approvalsOutcomes: Deny, Resolve and ResolveError in one batch; the// parked turn's Next is the resume.func approvalsOutcomes(ctx context.Context, w io.Writer, _ string) error { fmt.Fprintln(w, "== deny, resolve, resolve_error") agent := weft.New(wefttest.Script( wefttest.ToolCalls( wefttest.Call{Name: "refund", ID: "call_a", Args: `{"order_id":"1111"}`}, wefttest.Call{Name: "refund", ID: "call_b", Args: `{"order_id":"2222"}`}, wefttest.Call{Name: "refund", ID: "call_c", Args: `{"order_id":"3333"}`}, ), wefttest.Say("One refund was denied, one done by hand, one failed."), ), refundTool()) s, err := thread.Create(ctx, thread.Memory(), agent, ids("s_batch", "a")) if err != nil { return err } parked, err := s.Send(ctx, weft.User("Refund orders 1111, 2222 and 3333.")) if err != nil { return err } if _, err := parked.Wait(); err != nil { return err } _, err = s.Decide(ctx, thread.Approve("call_a"), thread.Deny("call_a", "twice")) fmt.Fprintln(w, "one call, two verdicts:", errors.Is(err, thread.ErrInvalidDecision)) _, err = s.Decide(ctx, thread.Approve("call_9")) fmt.Fprintln(w, "not pending:", errors.Is(err, thread.ErrNotPending))
no := thread.Deny("call_a", "over the refund limit") no.Who = "agent-7" // an opaque id for the audit trail if _, err := s.Decide(ctx, no, thread.Resolve("call_b", "refunded by hand: ticket 88"), // the handler never runs thread.ResolveError("call_c", "the payment provider is down"), ); err != nil { return err } res, err := parked.Next().Wait() // the resume the decisions started if err != nil { return err } results(w, s) fmt.Fprintln(w, "answer:", res.Text()) return s.Close(ctx)}
// approvalsGrant: a grant approves future calls without asking;// ApproveAlways mints one for the exact arguments; Revoke ends one.func approvalsGrant(ctx context.Context, w io.Writer, _ string) error { fmt.Fprintln(w, "== grants") agent := weft.New(wefttest.Script( refundCall("call_1", "1234"), wefttest.Say("Refunded 1234."), refundCall("call_2", "5678"), wefttest.Say("Refunded 5678."), refundCall("call_3", "5678"), wefttest.Say("Refunded 5678 again."), refundCall("call_4", "9999"), wefttest.Say("Order 9999 cannot be refunded."), refundCall("call_5", "1299"), ), refundTool()) s, err := thread.Create(ctx, thread.Memory(), agent, ids("s_grant", "a")) if err != nil { return err } ask := func(prompt string) (*thread.Turn, error) { turn, err := s.Send(ctx, weft.User(prompt)) if err != nil { return nil, err } res, err := settle(turn) // a grant decides in the chain: the turn parks, the resume follows at once if err != nil { return nil, err } fmt.Fprintf(w, "%s → %q pending: %d\n", prompt, res.Text(), len(s.Pending())) return turn, nil } err = s.Grant(ctx, thread.Grant{ // every refund whose order id starts with "12" Tool: "refund", Args: []thread.Arg{thread.ArgPrefix("/order_id", "12")}, }) if err != nil { return err } err = s.Grant(ctx, thread.Grant{ // a standing refusal Tool: "refund", Deny: true, Reason: "order 9999 is under review", Args: []thread.Arg{thread.ArgEquals("/order_id", []byte(`"9999"`))}, }) if err != nil { return err } if _, err := ask("Refund 1234."); err != nil { // the prefix grant approves it return err } parked, err := ask("Refund 5678.") // no grant matches: it parks if err != nil { return err } if _, err := s.Decide(ctx, thread.ApproveAlways("call_2")); err != nil { // approve, and grant these exact args return err } if _, err := settle(parked); err != nil { return err } if _, err := ask("Refund 5678 again."); err != nil { // the minted grant approves it return err } if _, err := ask("Refund 9999."); err != nil { // the deny-grant refuses it return err } for _, e := range s.Entries() { // revoke the prefix grant: an appended entry if g, ok := e.(thread.GrantEntry); ok && len(g.Args) == 1 && g.Args[0].Prefix == "12" { if err := s.Revoke(ctx, g.ID); err != nil { return err } } } if _, err := ask("Refund 1299."); err != nil { // parks again return err } results(w, s) return s.Close(ctx)}
// deployTool deploys, and only after a decision.func deployTool() *weft.ToolDef { return weft.Tool("deploy", "Deploy the service.", func(ctx context.Context, in struct { Env string `json:"env"` }) (string, error) { return "deployed to " + in.Env, nil }, weft.RequireApproval())}
// deployCall is a model turn asking to deploy to env.func deployCall(id, env string) wefttest.Turn { return wefttest.ToolCalls(wefttest.Call{Name: "deploy", ID: id, Args: `{"env":"` + env + `"}`})}
// approvalsApprover: the live step decides what it can; OnRequest// reports what parks.func approvalsApprover(ctx context.Context, w io.Writer, _ string) error { fmt.Fprintln(w, "== approver") agent := weft.New(wefttest.Script( deployCall("call_1", "staging"), wefttest.Say("Staging is live."), deployCall("call_2", "prod"), ), deployTool()) approver := func(ctx context.Context, r thread.Request) (thread.Decision, bool) { if !strings.Contains(string(r.Args), `"staging"`) { return thread.Decision{}, false // not mine to decide: the call parks } d := thread.Approve(r.CallID) d.Who = "ci-bot" return d, true } s, err := thread.Create(ctx, thread.Memory(), agent, ids("s_deploy", "a"), thread.WithApprover(approver, 2*time.Second), // asked before a call parks, bounded thread.OnRequest(func(r thread.Request) { // after the request is durable fmt.Fprintln(w, "notify:", r.Tool, string(r.Args), "parked as", r.ID) })) if err != nil { return err } for _, q := range []string{"Deploy to staging.", "Now prod."} { turn, err := s.Send(ctx, weft.User(q)) if err != nil { return err } res, err := settle(turn) if err != nil { return err } fmt.Fprintf(w, "%s → %q pending: %d\n", q, res.Text(), len(s.Pending())) } return s.Close(ctx)}
// approvalsQuorum: Quorum(2) needs two distinct approvers.func approvalsQuorum(ctx context.Context, w io.Writer, _ string) error { fmt.Fprintln(w, "== quorum") agent := weft.New(wefttest.Script(deployCall("call_1", "prod"), wefttest.Say("Prod is live.")), deployTool()) s, err := thread.Create(ctx, thread.Memory(), agent, ids("s_quorum", "a"), thread.Quorum(2)) if err != nil { return err } parked, err := s.Send(ctx, weft.User("Deploy to prod.")) if err != nil { return err } if _, err := parked.Wait(); err != nil { return err } approve := func(who string) (*thread.Turn, error) { d := thread.Approve("call_1") d.Who = who // unsigned: a declared identity return s.Decide(ctx, d) } resume, err := approve("alice") fmt.Fprintln(w, "after alice:", resume != nil, err, "| pending:", len(s.Pending())) resume, err = approve("bob") if err != nil { return err } res, err := resume.Wait() if err != nil { return err } fmt.Fprintln(w, "after bob:", res.Text()) return s.Close(ctx)}
// clock is a session clock the demo moves by hand.type clock struct { mu sync.Mutex t time.Time}
func (c *clock) now() time.Time { c.mu.Lock(); defer c.mu.Unlock(); return c.t }
func (c *clock) advance(d time.Duration) { c.mu.Lock(); defer c.mu.Unlock(); c.t = c.t.Add(d) }
// approvalsExpiry: a request past its expiry takes no decision and is// denied with the stated reason.func approvalsExpiry(ctx context.Context, w io.Writer, _ string) error { fmt.Fprintln(w, "== expiry") agent := weft.New(wefttest.Script(deployCall("call_1", "prod"), wefttest.Say("The deploy request lapsed.")), deployTool()) c := &clock{t: base} s, err := thread.Create(ctx, thread.Memory(), agent, ids("s_expiry", "a"), thread.Clock(c.now), thread.RequestExpiry(10*time.Minute)) if err != nil { return err } parked, err := s.Send(ctx, weft.User("Deploy to prod.")) if err != nil { return err } if _, err := parked.Wait(); err != nil { return err } fmt.Fprintln(w, "expires:", s.Pending()[0].Expiry.Format(time.RFC3339))
c.advance(11 * time.Minute) // nobody decided in time _, err = s.Decide(ctx, thread.Approve("call_1")) fmt.Fprintln(w, "too late:", errors.Is(err, thread.ErrExpired)) if _, err := parked.Next().Wait(); err != nil { // the expiry's denial resumed the boundary return err } results(w, s) for _, e := range s.Audit() { switch e := e.(type) { case thread.ApprovalRequestEntry: fmt.Fprintln(w, "request:", e.CallID, e.Tool, "|", e.Reason) case thread.ApprovalAuditEntry: // Detail is prose for a human, never parsed line := "step: " + e.Step + " " + e.Outcome if e.Detail != "" { line += " | " + e.Detail } fmt.Fprintln(w, line) case thread.ApprovalDecisionEntry: fmt.Fprintln(w, "decision:", e.CallID, e.Outcome, "via", e.Via, "|", e.Reason) } } return s.Close(ctx)}
// approvalsResume: with AutoResume off the caller drives the resume.func approvalsResume(ctx context.Context, w io.Writer, _ string) error { fmt.Fprintln(w, "== resume") agent := weft.New(wefttest.Script( wefttest.ToolCalls( wefttest.Call{Name: "deploy", ID: "call_eu", Args: `{"env":"eu"}`}, wefttest.Call{Name: "deploy", ID: "call_us", Args: `{"env":"us"}`}, ), wefttest.Say("The EU region is live."), ), deployTool()) s, err := thread.Create(ctx, thread.Memory(), agent, ids("s_resume", "a"), thread.AutoResume(false)) if err != nil { return err } parked, err := s.Send(ctx, weft.User("Deploy to both regions.")) if err != nil { return err } if _, err := parked.Wait(); err != nil { return err } turn, err := s.Decide(ctx, thread.Approve("call_eu")) fmt.Fprintln(w, "decided; resumed on its own:", turn != nil, err) resume, err := s.Resume(ctx) // the undecided call is denied if err != nil { return err } if _, err := resume.Wait(); err != nil { return err } results(w, s) return s.Close(ctx)}View on GitHub · run it from docs-site/examples:
go run ./sessions approvalsgo test ./sessions== decideturn: parked | pending calls: 1pending: call_1 refund {"order_id":"1234"} | tool requires approval | request e_a4resumed: Refund issued for order 1234. | run: s_refund-t2call_1: refunded 1234 (error: false)== deny, resolve, resolve_errorone call, two verdicts: truenot pending: truecall_a: DENIED: over the refund limit (error: true)call_b: refunded by hand: ticket 88 (error: false)call_c: the payment provider is down (error: true)answer: One refund was denied, one done by hand, one failed.== grantsRefund 1234. → "Refunded 1234." pending: 0Refund 5678. → "" pending: 1Refund 5678 again. → "Refunded 5678 again." pending: 0Refund 9999. → "Order 9999 cannot be refunded." pending: 0Refund 1299. → "" pending: 1call_1: refunded 1234 (error: false)call_2: refunded 5678 (error: false)call_3: refunded 5678 (error: false)call_4: DENIED: order 9999 is under review (error: true)== approverDeploy to staging. → "Staging is live." pending: 0notify: deploy {"env":"prod"} parked as e_a14Now prod. → "" pending: 1== quorumafter alice: false <nil> | pending: 1after bob: Prod is live.== expiryexpires: 2026-10-18T09:10:00Ztoo late: truecall_1: DENIED: expired: no decision before 2026-10-18T09:10:00Z (error: true)request: call_1 deploy | tool requires approvalstep: park parkedstep: expiry denied | request expired at 2026-10-18T09:10:00Zdecision: call_1 deny via expiry | expired: no decision before 2026-10-18T09:10:00Zstep: resume started | 1 call(s) to resolvestep: resume completed== resumedecided; resumed on its own: false <nil>call_eu: deployed to eu (error: false)call_us: DENIED: no decision (error: true)Stderr also carries the no-window WARN line once per Session value that runs a turn (compaction). sessions/sessions_test.go also pins that Decide returns the parked turn’s Next, that Quorum(2) resumes only on the second identity, and that a request expires strictly after its expiry.
Best practices & gotchas
Section titled “Best practices & gotchas”- Follow
NextafterWait. A call a grant or the Approver decided still ends its turnparked; the answer is on the resume. (Source:thread/turn.go:1213-1252;Turn.Nextgodoc) - Notify from
OnRequest, not from yourSendcaller. It fires once per parked call after the request is durable, beforeWaitreturns; keep it quick. (Source:thread/approval.go:268-287) - Put an opaque id in
Who. It rides every span and record asweft.approval.actor, through content-off. (Source:thread/approval.go:157-166) - Anchor globs and end prefixes with a separator.
*spans separators and a prefix is a plain string prefix. (Source:thread/grants.go:78-102) - Do not count unsigned
Whos as people. UnderQuoruman unsigned approval is whatever name the caller wrote; useRequireSignedand a key per approver when it matters. (Source:thread/approval.go:296-311; ADR 0021 §5) - Touch an idle session to expire its requests. Expiry is lazy; nothing fires on a timer. (Source:
thread/approval.go:313-326; thread-operations §11) - Make an approved tool idempotent when it must not run twice. A crash after a resume’s
startedentry and before the approved call’s result is recorded leaves its decision in force, and the next resume (Resume,Continue, aSendunderAutoResume, orRecover) runs it again. Key it byweft.CallFromContext’s call id, the session id (weft.session.idinweft.MetadataFromContext) and a business key for what the call acts on, such as the order id. The call id is the same on every run of one call, so the run a resume repeats finds the first run’s entry. The session id keeps conversations apart, but it is the same on every turn of one session. Within a session only the business key reliably tells operations apart, because a later turn may reuse a call id (weft’s Gemini adapter, for one, numbers callscall_0,call_1, … per step when the API sends no id): keyed by the order id, a later turn’s refund of the same order under a repeated call id reads as already done. Name the operation itself, such as a refund request id, when one order may be refunded twice. (Source:thread/approval.go:1127-1130, 1327-1335; the example) - Expect
ErrNotPendingafterErrExpired. Once a path has denied a lapsed request, every later decide orRequestfor it readsErrNotPending. (Source:thread/approval.go:313-326RequestExpiry godoc) - Branch away to abandon a boundary. Until it resolves,
Compactfails withErrAwaitingApprovaland a plainSendqueues behind it. (Source:thread/compaction.go:123-126;Session.Decidegodoc; ADR 0021 amendment 2026-09-29)
See also
Section titled “See also”- Sign approval decisions
- Require human approval for a tool: the core boundary under the session
- What happens when you send while a turn runs?: a steer never decides a parked call
- Run bounded child sessions with a pool: a child’s parked call surfaces in its parent’s
Pending
Symbols used: Session.Pending · Session.Decide · Session.Resume · Session.Grant · Session.Revoke · Session.Audit · Turn.Next · thread.Decision · thread.Request · thread.Approve · thread.ApproveAlways · thread.Deny · thread.Resolve · thread.ResolveError · thread.Grant · thread.Arg · thread.ArgPrefix · thread.ArgEquals · thread.ArgGlob · thread.WithApprover · thread.OnRequest · thread.Quorum · thread.RequestExpiry · thread.AutoResume · thread.Clock · thread.ApprovalAuditEntry · jsonl.Open · weft.RequireApproval · wefttest.Script