Skip to content

Approvals in sessions

View as Markdown

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:

sessions/approvals.go
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())

sessions/approvals.go on GitHub

turn: parked | pending calls: 1
pending: call_1 refund {"order_id":"1234"} | tool requires approval | request e_a4
resumed: Refund issued for order 1234. | run: s_refund-t2

The 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.

Approval: a gated call parks, the run ends with RunFinish.Pending, and the next run resumes with weft.Approve or weft.Deny.The model calls refund_order, a tool built with RequireApproval(). The call gets a ToolStart but is not executed and gets no ToolFinish; the step's other calls run. The run then ends successfully, err is nil, with the parked call on res.Pending and RunFinish.Pending. Later, over any transport, a decision arrives and a new run resumes: agt.Generate(ctx, weft.Messages(res.Messages...), weft.Approve(id)). An approved call runs with Call.Approved set; weft.Deny(id, why) gives the model the result DENIED: why; a call with no decision gets DENIED: no decision. The results complete the earlier tool message and the loop continues with the next model call.
The core's boundary, which a session drives: run 1 parks, and the resume run is the session's own, started by Decide or Resume.
  • A parked call is a request. Each becomes an approval_request entry (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. A thread.Request is its view; Reason is tool requires approval for a RequireApproval tool and middleware required approval when 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 turn parked; the session resumes at once and the parked turn’s Next is that resume.
  • Decisions are entries. Decide writes approval_decision entries; when every pending call of the boundary has one, the session resumes with the core’s Approve, Deny, Resolve or ResolveError (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 Branch back to a decided boundary, or a Fork of 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’s started entry 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 Send while approvals pend queues behind the boundary; only the resume resolves it. Compaction is held too: Compact fails with thread.ErrAwaitingApproval and the trigger stands down (compaction). A Branch away 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).

A thread.Decision is one call’s outcome. Build it with a constructor; set Who yourself:

ConstructorKindWhat the model sees
thread.Approve(id)OutcomeApprovethe tool’s own result; it runs with Call.Approved set
thread.ApproveAlways(id)OutcomeApprove, Always: truethe same, and a grant for these exact arguments (grants)
thread.Deny(id, reason)OutcomeDenyDENIED: <reason>, as an error result
thread.Resolve(id, content)OutcomeResolvecontent, verbatim; the handler never runs
thread.ResolveError(id, content)OutcomeResolveErrorcontent, 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:

sessions/approvals.go
_, 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())

sessions/approvals.go on GitHub

one call, two verdicts: true
not pending: true
call_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):

ErrorWhen
thread.ErrInvalidDecisionno decisions, a decision without an outcome, or two decisions for one call
thread.ErrNotPendinga call that is not pending, raised before any of the batch lands or runs
thread.ErrExpireda request past its expiry (expiry)
thread.ErrSignatureRequiredthe session requires signed decisions
thread.ErrDelegateda call that delegates to a thread/pool child; decide the child’s request instead (pools)
  • Who is the caller’s declaration, verified by nobody, and the identity Quorum counts for unsigned decisions. The run that applies the decision carries it as the weft.approval.actor metadata pair on every span and record, to every destination and through content-off; on a Quorum(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.
  • Via names the channel and the session fills it: user for Decide and signed for DecideSigned, whatever the field holds. Its own paths record grant, approver (an Approver’s answer may name its own), expiry, interrupt, and the pool’s child and parent.
  • Next follows the flow. Decide returns the resume’s Turn when it completed the boundary, and nil, nil otherwise. The parked turn’s Next is the same Turn, whichever path armed it. After a restart the parked Turn value is gone; use what Decide returns (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 interrupting Send) are the exception: they resolve with their own stated reason even beside an approval.
  • Decisions are durable when Decide returns under thread.FsyncOnFlush, as are Grant, Revoke and Pin.

The package example is ExampleSession_Decide.

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:

sessions/approvals.go
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)

sessions/approvals.go on GitHub

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).

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:

sessions/approvals.go
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
}

sessions/approvals.go on GitHub

Refund 1234. → "Refunded 1234." pending: 0
Refund 5678. → "" pending: 1
Refund 5678 again. → "Refunded 5678 again." pending: 0
Refund 9999. → "Order 9999 cannot be refunded." pending: 0
Refund 1299. → "" pending: 1

The model saw DENIED: order 9999 is under review for the refused call. The grant’s fields:

  • Tool is matched exactly and must not be empty: a grant for every tool is a policy this shape does not have.
  • Args are thread.Arg predicates, every one of which must match; none matches any arguments. Each has a Pointer, an RFC 6901 JSON pointer such as /order_id, and one test: Equals, Prefix or Glob (tried in that order on a hand-made Arg with several).
  • Deny makes it a standing refusal; Reason is then the model-visible text, denied by grant when empty, or a note on an approval grant.
  • Expiry lapses it (zero: never), strictly after the time. MaxUses bounds 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 as float64. Pointer "" is the whole arguments document; no arguments read as {}.
  • thread.ArgPrefix(pointer, prefix): a plain string prefix. End it with the separator, or /ws matches /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* matches go 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.

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:

sessions/approvals.go
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()))
}

sessions/approvals.go on GitHub

Deploy to staging. → "Staging is live." pending: 0
notify: deploy {"env":"prod"} parked as e_a14
Now prod. → "" pending: 1
  • The timeout must be positive; Create and Open fail 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 Request the Approver gets has no ID, Nonce or Created: the chain asks before the request is persisted. It must not call back into the same session; the turn is still running.
  • OnRequest runs after the request entry is durable, once per parked call, in call order, synchronously on the runner, before the parking turn’s Wait returns. A slow fn holds the session, so hand the request to a queue and return. It may call Pending or Request; 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:

sessions/approvals.go
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())

sessions/approvals.go on GitHub

after alice: false <nil> | pending: 1
after 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:

sessions/approvals.go
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)

sessions/approvals.go on GitHub

expires: 2026-10-18T09:10:00Z
too late: true
call_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).

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:

sessions/approvals.go
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)
}
}

sessions/approvals.go on GitHub

request: call_1 deploy | tool requires approval
step: park parked
step: expiry denied | request expired at 2026-10-18T09:10:00Z
decision: call_1 deny via expiry | expired: no decision before 2026-10-18T09:10:00Z
step: resume started | 1 call(s) to resolve
step: resume completed

An audit entry’s Step is one of:

StepWritten 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).

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:

Terminal window
go run ./thread/examples/approvals
== a session parks a gated call
parked: deploy as call_1
== the process restarts; the pending request survived
pending after reopen: 1
unsigned: true
== the UI asks for a challenge and signs a decision
challenge: call call_1 key k1
resumed: Deployed. The change is live.
== a replayed signature fails closed
replay: thread: decision signature replayed: nonce already decided call "call_1"
== the audit trail
request call_1 on deploy
audit park parked
decision call_1 approve via signed
audit resume started (1 call(s) to resolve)
audit resume completed
audit signed refused (replayed)

With -serve addr the same gate runs as a small web app whose parked turns are decided from the devtools panel.

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:

sessions/approvals.go
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 sessions/approvals.go on GitHub

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

Terminal window
go run ./sessions approvals
go test ./sessions
== decide
turn: parked | pending calls: 1
pending: call_1 refund {"order_id":"1234"} | tool requires approval | request e_a4
resumed: Refund issued for order 1234. | run: s_refund-t2
call_1: refunded 1234 (error: false)
== deny, resolve, resolve_error
one call, two verdicts: true
not pending: true
call_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.
== grants
Refund 1234. → "Refunded 1234." pending: 0
Refund 5678. → "" pending: 1
Refund 5678 again. → "Refunded 5678 again." pending: 0
Refund 9999. → "Order 9999 cannot be refunded." pending: 0
Refund 1299. → "" pending: 1
call_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)
== approver
Deploy to staging. → "Staging is live." pending: 0
notify: deploy {"env":"prod"} parked as e_a14
Now prod. → "" pending: 1
== quorum
after alice: false <nil> | pending: 1
after bob: Prod is live.
== expiry
expires: 2026-10-18T09:10:00Z
too late: true
call_1: DENIED: expired: no decision before 2026-10-18T09:10:00Z (error: true)
request: call_1 deploy | tool requires approval
step: park parked
step: expiry denied | request expired at 2026-10-18T09:10:00Z
decision: call_1 deny via expiry | expired: no decision before 2026-10-18T09:10:00Z
step: resume started | 1 call(s) to resolve
step: resume completed
== resume
decided; 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.

  • Follow Next after Wait. A call a grant or the Approver decided still ends its turn parked; the answer is on the resume. (Source: thread/turn.go:1213-1252; Turn.Next godoc)
  • Notify from OnRequest, not from your Send caller. It fires once per parked call after the request is durable, before Wait returns; keep it quick. (Source: thread/approval.go:268-287)
  • Put an opaque id in Who. It rides every span and record as weft.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. Under Quorum an unsigned approval is whatever name the caller wrote; use RequireSigned and 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 started entry and before the approved call’s result is recorded leaves its decision in force, and the next resume (Resume, Continue, a Send under AutoResume, or Recover) runs it again. Key it by weft.CallFromContext’s call id, the session id (weft.session.id in weft.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 calls call_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 ErrNotPending after ErrExpired. Once a path has denied a lapsed request, every later decide or Request for it reads ErrNotPending. (Source: thread/approval.go:313-326 RequestExpiry godoc)
  • Branch away to abandon a boundary. Until it resolves, Compact fails with ErrAwaitingApproval and a plain Send queues behind it. (Source: thread/compaction.go:123-126; Session.Decide godoc; ADR 0021 amendment 2026-09-29)

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