Skip to content

Run bounded child sessions with a pool

View as Markdown

pool.New(max) returns a *pool.Pool that admits at most max child runs at work at once. p.MustWrap turns an agent into a delegation tool, and p.Submit hands it work directly. Every child runs as a session of its own in the parent’s storage, each delegation leaves receipt entries in the parent, and the child’s cost lands in the parent’s Usage.Delegated.

sessions/pools.go wraps a research agent and lets the support agent call it:

sessions/pools.go
p := pool.New(4, childIDs()) // at most 4 child runs at work at once
researcher := weft.New(wefttest.Script(wefttest.Say("Order 1234 left the Leeds depot on Monday.")))
research := p.MustWrap("research", "Research an order in depth.", researcher)
support := weft.New(wefttest.Script(
wefttest.ToolCalls(wefttest.Call{Name: "research", ID: "call_1", Args: `{"prompt":"Trace order 1234."}`}),
wefttest.Say("Order 1234 left the depot on Monday."),
), research)
s, err := thread.Create(ctx, st, support, ctxWindow, ids("s_support", "a"), at(base))
if err != nil {
return thread.Usage{}, err
}
turn, err := s.Send(ctx, weft.User("Where is order 1234?"))
if err != nil {
return thread.Usage{}, err
}
res, err := turn.Wait()
if err != nil {
return thread.Usage{}, err
}
fmt.Fprintln(w, "reply:", res.Text())
for _, r := range pool.Receipts(s) {
fmt.Fprintf(w, "receipt %s: %s child %s call %s stop %q\n", r.ID, r.State, r.Child, r.Call, r.Stop)
}
u := s.Usage()
fmt.Fprintln(w, "output tokens: run", res.Usage.OutputTokens, "| turns", u.Turns.OutputTokens, "| delegated", u.Delegated.OutputTokens)

sessions/pools.go on GitHub

reply: Order 1234 left the depot on Monday.
receipt e_a3: done child c_1 call call_1 stop "Order 1234 left the Leeds depot on Monday."
output tokens: run 10 | turns 10 | delegated 5

The call waited for the child and read its answer. The receipt names the child session (c_1, minted by childIDs, a pool.IDs option that keeps the output stable) and the call that delegated. The child’s 5 output tokens are in Delegated, not in the run’s usage. ids, at and ctxWindow are the demos’ helpers for pinned ids, a pinned clock and a context window.

A pool is a bound on concurrent child runs, per Pool value: two pools are two bounds, and a process that wants one bound shares one Pool. The bound is the pool’s reason to exist, so pool.New panics when max is below 1.

  • A slot is held while a child works, not while it waits. A child holds one slot during its model calls and tool calls. A child waiting on a sync delegation of its own gives its slot up for the wait and queues for one again before it works again. A child parked at an approval holds none. That hand-off is why fan-out times depth is safe on any max, 1 included.
  • Admission is first in, first out, in the order work queued: Submit queues before it returns, a wrapped tool queues when it is called, and a parent taking its slot back queues behind whatever was already waiting.
  • Depth has its own bound. pool.MaxDepth(n) caps how deep a chain of delegations goes: 1 allows children, 2 children of children. The default is pool.DefaultMaxDepth, 8. Since waiting parents hold no slot, depth costs sessions and tokens, not capacity (ExampleMaxDepth). In thread 0.5.0 the bound doubled as the depth guard and a too-deep chain read SUBAGENT_CYCLE; since thread 0.9.0 depth is MaxDepth’s and reads SUBAGENT_DEPTH.
  • A child is a session. It is created in the parent’s storage with a header whose lineage names the parent session and, for a wrapped tool, the delegating call. A wrapped child also records the wrap’s name in its header metadata (pool_agent): the name is the resume key after a restart. The child inherits the parent’s approval policy through thread.InheritApprovals: request expiry, quorum, keyring, RequireSigned and clock.
  • A child’s events are its own. They are not weft.Nested events in the parent’s stream; read or tail the child session instead.
  • The pool changes nothing in the core. A wrapped tool is the core’s weft.Subagent under a tool-level weft.WrapTools middleware, plus session entries and pool-owned goroutines.

A pool is safe for concurrent use; the zero value is not usable. The package’s own API, in one place:

CallDoes
pool.New(max, opts...)A pool of max slots; options pool.MaxDepth, pool.IDs
p.Wrap(name, desc, agent, opts...)A delegation tool, (*weft.ToolDef, error); p.MustWrap panics instead
p.Submit(ctx, parent, agent, prompt)Start a child now; returns its *Receipt at once
p.Wait(ctx, parent, receiptID)Block until the delegation is settled or parked
p.Decide(ctx, parent, ds...)Record decisions over children’s requests and arm the children; does not wait
p.DecideSigned(ctx, parent, sd)Decide for one signed decision
p.Forward(ctx, parent, receiptID, msg)Steer a running child
p.Cancel(ctx, parent, receiptID)End one delegation
p.Register(sessionID, agent)Attach an agent to a child no wrap names, before Recover
p.Recover(ctx, parent)After a restart, make the parent’s ledger say what is true
p.Close(ctx)Cancel what runs, drain, take no more work
pool.Receipts(parent)The parent’s delegations, from its entries
pool.Children(ctx, parent), pool.Descendants(ctx, parent)The child sessions, direct or the whole subtree

There are two ways in. A wrapped tool lets the parent’s model delegate; Submit lets your code delegate. Both create the child session, write the acceptance receipt in the parent and queue the child before they return.

p.Wrap(name, description, agent, opts...) returns a subagent tool whose children the pool runs. Inside a session’s run, found through the run’s context (thread.SessionFromContext), the call is sync by default: it waits, and the result is the child’s answer. The tool’s input is the subagent schema, {"prompt": "..."}.

  • Wrap fails on a nil agent or an empty name, and with pool.ErrDuplicateWrap for a name the pool already wraps a different agent under: one name names one agent. Wrapping the same agent again returns another tool for it. MustWrap panics on those errors, for wiring where the arguments are the program’s own.
  • pool.ToolOptions(opts...) forwards weft tool options to the underlying subagent tool: Timeout, MaxResultBytes, a snippet. weft.RequireApproval gates the act of delegating, as on any tool.
  • A wrapped tool called outside any session, from a bare Generate, has no parent to receipt into. It falls back to the ordinary subagent path under a slot (TestWrapOutsideSession).

The package example is ExamplePool_Wrap.

pool.Async() makes the tool’s result an acceptance receipt instead of the child’s answer. The model reads one line, and the child runs on:

sessions/pools.go
p := pool.New(4, childIDs())
refunds := p.MustWrap("refunds", "Start a refund in the background.", refunder, pool.Async())
support := weft.New(wefttest.Script(
wefttest.ToolCalls(wefttest.Call{Name: "refunds", ID: "call_1", Args: `{"prompt":"Refund order 1234."}`}),
wefttest.Say("The refund has started."),
), refunds)
s, err := thread.Create(ctx, st, support, ctxWindow, ids("s_async", "a"), at(base))
if err != nil {
return pool.Receipt{}, err
}
turn, err := s.Send(ctx, weft.User("Refund order 1234."))
if err != nil {
return pool.Receipt{}, err
}
res, err := turn.Wait()
if err != nil {
return pool.Receipt{}, err
}
fmt.Fprintln(w, "the model read:", lastToolResult(res.Messages))
fmt.Fprintln(w, "reply:", res.Text())

sessions/pools.go on GitHub

the model read: background task accepted; receipt e_a3
reply: The refund has started.

The line background task accepted; receipt <id> is model-visible text, pinned by TestWrapAsyncGolden. The answer reaches the model only when your application delivers it in a later turn.

Async needs a parent session. Under a plain Generate, with no thread.Session on the context, the wrap takes the bare path before it checks Async: the call blocks until the child finishes, and the model reads the child’s answer instead of the receipt line.

p.Submit(ctx, parent, agent, prompt) is the same primitive, called by your code. It returns a *pool.Receipt at once, state accepted. The child runs on a pool-owned context: the submitting caller’s cancellation does not reach it, and only Cancel or Close end it. Its context still carries the delegating run’s values, so a weft.ParkAllExcept list and the run metadata bind it as they bind a sync child. parent and agent must not be nil. Called from inside a pool child’s run, Submit counts depth and ancestry from there and fails with pool.ErrDepth or pool.ErrCycle. Four submits on a pool of two:

sessions/pools.go
p := pool.New(2, childIDs())
var receipts []*pool.Receipt
for i := range 4 {
r, err := p.Submit(ctx, parent, wk.agent(), fmt.Sprintf("task %d", i+1))
if err != nil {
return 0, err
}
receipts = append(receipts, r) // returned at once, state accepted
}
<-wk.started
<-wk.started // two children are inside their tool; the other two queue
states := map[pool.State]int{}
for _, r := range pool.Receipts(parent) {
states[r.State]++
}
fmt.Fprintln(w, "running:", states[pool.Running], "accepted:", states[pool.Accepted])
close(wk.release)
for i, r := range receipts {
final, err := p.Wait(ctx, parent, r.ID)
if err != nil {
return 0, err
}
fmt.Fprintf(w, "task %d: %s\n", i+1, final.State)
}
if err := p.Close(ctx); err != nil {
return 0, err
}

sessions/pools.go on GitHub

running: 2 accepted: 2
task 1: done
task 2: done
task 3: done
task 4: done

Two children hold the slots; the other two wait in the pool’s queue, their receipts accepted. p.Wait blocks until a delegation is at rest: settled, or parked at an approval. A receipt no child of this pool is working returns at once, as it stands. TestPoolBound asserts that no more than two were ever at work at once; the package example is ExamplePool_Submit.

To watch a child live, tail its session: r.Child names it, and a storage with the thread.Watcher capability (jsonl, sqlite; thread.Memory has none) yields its entries as they land (ExamplePool_Submit_watch, Watch a session).

A child that reaches a weft.RequireApproval tool parks, and its request surfaces on the parent’s s.Pending(). Decide it through the pool:

sessions/pools.go
r := pool.Receipts(s)[0]
rest, err := p.Wait(ctx, s, r.ID) // at rest: settled, or parked at an approval
if err != nil {
return pool.Receipt{}, err
}
fmt.Fprintln(w, "receipt:", rest.State)
for _, req := range s.Pending() {
fmt.Fprintln(w, "pending:", req.CallID, req.Tool, "in", req.Child)
}
if err := p.Decide(ctx, s, thread.Approve(s.Pending()[0].CallID)); err != nil {
return pool.Receipt{}, err // Decide records and arms the child; it does not wait
}
final, err := p.Wait(ctx, s, r.ID)
if err != nil {
return pool.Receipt{}, err
}
fmt.Fprintf(w, "receipt: %s %q | delegated output tokens: %d\n", final.State, final.Stop, s.Usage().Delegated.OutputTokens)

sessions/pools.go on GitHub

receipt: parked
pending: c_1/call_r refund in c_1
receipt: done "Refunded order 1234." | delegated output tokens: 10

The request’s call id is namespaced, <child>/<call>, and Request.Child names the session it parks in. p.Decide records the decision in the parent first, through the parent’s own Decide (validation, quorum, audit and expiry live there), then runs the pump: every child whose pending calls now all hold a verdict is queued to resume. It returns once the decisions are recorded and the children queued; follow the child with p.Wait. The error joins every failure: the parent’s refusal (nothing recorded, nothing pumped), or per child, why it could not be armed. A RequireSigned parent refuses Decide with thread.ErrSignatureRequired; use p.DecideSigned (Sign approval decisions). p.Decide(ctx, parent) with no decisions is the pump alone, and always safe to call. The mechanism is in Nested approvals; the package example is ExamplePool_Decide.

p.Forward(ctx, parent, receiptID, msg) sends msg to the child’s session under the Steer policy. It is delivered at the run’s next drain point, or deferred to a follow-up turn when the run ends first (Steer into the running turn). Nothing is ever forwarded implicitly:

sessions/pools.go
r, err := p.Submit(ctx, s, converter, "Convert the totals.")
if err != nil {
return err
}
<-started // the child is mid-run, inside its tool
if _, err := p.Forward(ctx, s, r.ID, weft.User("Use euros, not dollars.")); err != nil {
return err
}
close(release)
final, err := p.Wait(ctx, s, r.ID)
if err != nil {
return err
}
fmt.Fprintln(w, "forwarded:", final.State, final.Stop)
_, err = p.Forward(ctx, s, r.ID, weft.User("Too late."))
var se *pool.StateError
fmt.Fprintln(w, "after the end:", errors.Is(err, pool.ErrNotRunning), errors.As(err, &se) && se.State == pool.Done)

sessions/pools.go on GitHub

forwarded: done Converted the totals to euros.
after the end: true true

A child that is not running refuses with a *pool.StateError naming its state: accepted (a steer now would run as the session’s first turn), parked (its fate is the decision) or settled. The returned *thread.Turn is the steer’s receipt turn (ExamplePool_Forward).

A child that has just taken its slot can refuse for a moment; retry. Forward needs the run’s turn in flight, not only its running receipt. Between taking the slot and sending its turn, the child refuses as the state it is leaving: accepted before its first turn, parked before a resume. The refusal changes nothing, and a retry a moment later steers. Once the send is under way, Forward waits for it, bounded by ctx. A refusal of this pool’s child never reads running; only an Orphan’s can (TestForwardRetriedFromTheReceiptSteers).

p.Cancel(ctx, parent, receiptID) ends one delegation:

sessions/pools.go
r, err = p.Submit(ctx, s, holder, "Wait for the warehouse.")
if err != nil {
return err
}
<-held
if err := p.Cancel(ctx, s, r.ID); err != nil { // cancels the run; Wait follows the settlement
return err
}
final, err = p.Wait(ctx, s, r.ID)
if err != nil {
return err
}
fmt.Fprintln(w, "canceled:", final.State, final.Settled())
fmt.Fprintln(w, "cancel again:", errors.Is(p.Cancel(ctx, s, r.ID), pool.ErrNotRunning))
fmt.Fprintln(w, "unknown receipt:", errors.Is(p.Cancel(ctx, s, "e_nope"), pool.ErrUnknownReceipt))

sessions/pools.go on GitHub

canceled: canceled true
cancel again: true
unknown receipt: true

What it does depends on where the child is:

  • Running: the run is canceled and the child records a canceled turn.
  • Queued for a slot: it never starts; the child session records no turn. In both cases the receipt settles canceled on the delegation’s goroutine. Cancel does not wait for that; Wait does. A sync delegation’s model reads SUBAGENT_CANCELED.
  • Parked: the child’s pending requests are denied in the child session, its run is not resumed, the receipt settles canceled before Cancel returns, and the mirrored requests leave the parent’s Pending.
  • Unsettled in the ledger with no child of this pool running: a previous process’s. It is recovered first, then canceled if recovery left it parked.
  • Still parking (its requests mirrored, perhaps its receipt reading parked): Cancel waits for the park to finish, bounded by ctx, then cancels it as a parked child. A running child that reaches its approval boundary before the cancel stops it does not park; it settles canceled.

A child that is itself a parent ends its own sync delegations first. Each parked or running grandchild is canceled and settles canceled in the child’s ledger, never resumed. The child waits for them at most 30 s. A grandchild still running past that, such as a handler that ignores its context with no Timeout, is settled canceled by the pool. Its stop names the bound, and its run is abandoned; Close’s drain still counts it. Async children the child submitted are not ended with it.

A settled receipt fails with a *pool.StateError (pool.ErrNotRunning under errors.Is); an id the ledger does not hold fails with pool.ErrUnknownReceipt (ExamplePool_Cancel).

The ledger is entries; the pool’s memory is not. A new process brings a parent’s delegations back with p.Recover(ctx, parent), once per parent session it takes over, after the agents are wrapped or registered. Here the first process parks a sync delegation and stops; the second opens the same files:

sessions/pools.go
// The second process: a new Storage, a new pool, the same agents
// wrapped under the same names.
st, err := jsonl.Open(sessions)
if err != nil {
return pool.Receipt{}, err
}
p := pool.New(4)
refunder := weft.New(wefttest.Script(wefttest.Say("Refunded order 1234.")), refundTool())
support := weft.New(wefttest.Script(wefttest.Say("Order 1234 is refunded.")),
p.MustWrap("refunds", "Run the refund flow.", refunder))
s, err := thread.Open(ctx, st, "s_refunds", support, ctxWindow, ids("", "b"), at(base))
if err != nil {
return pool.Receipt{}, err
}
if err := p.Recover(ctx, s); err != nil { // once per parent session, after the wraps
return pool.Receipt{}, err
}
req := s.Pending()[0]
fmt.Fprintln(w, "after Recover:", pool.Receipts(s)[0].State, "| pending", req.CallID)
if err := p.Decide(ctx, s, thread.Approve(req.CallID)); err != nil {
return pool.Receipt{}, err
}
final, err := p.Wait(ctx, s, pool.Receipts(s)[0].ID)
if err != nil {
return pool.Receipt{}, err
}
fmt.Fprintln(w, "receipt:", final.State, final.Stop)
if err := p.Close(ctx); err != nil {
return pool.Receipt{}, err
}
if err := s.Close(ctx); err != nil { // waits for the parent's own resume
return pool.Receipt{}, err
}
msgs := s.Context()
fmt.Fprintln(w, "parent:", msgs[len(msgs)-1].Text())

sessions/pools.go on GitHub

first process: pending 1 | receipt parked
after Recover: parked | pending c_1/call_r
receipt: done Refunded order 1234.
parent: Order 1234 is refunded.

For each unsettled receipt no child of this pool is working, Recover reads the child session and makes the ledger say what is true:

The childRecover
is parked at an approvalrebuilds the bridge (reopens the child under its agent), mirrors any request the parent lacks, records parked; the child resumes when decided. A child whose resume was under way when the process died is here too: its decisions are on file, so it resumes again, and an approved call whose result was not recorded runs again
finished its runsettles the receipt from the child’s own ledger, with its usage: done with its final text, or failed, capped, canceled with the recorded cause
never finished its first run (queued, or mid-run with no approval boundary on file)settles failed, saying so; the run is not started again
is gonesettles failed

A sync delegation’s call still parked in the parent is resolved with the settlement, and last the pump runs. A child whose agent the pool does not hold is reported with pool.ErrNoAgent and left for a later call. Wrapped children need nothing more than the same wraps under the same names. A Submit child, or a wrap renamed between runs, needs p.Register(childID, agent) first (ExamplePool_Register). Recover on a live session leaves alone the receipts this pool is working (ExamplePool_Recover).

A child’s first run is never started again, but its resume is. A resume that started and did not finish leaves the boundary resumable, with its decisions in force. The pump at the end of Recover resumes it, and an approved call whose result was not recorded runs again. The same holds at any depth: a grandchild resumes through its parent’s recovered delegation (TestNestedRestartMidApprovedCallRunsItAgain).

Nothing on file tells a call that never started from one cut off half-way. weft.Replay’s side-effect classes are the playground’s and do not gate a session resume. So a tool that must not run twice has to be idempotent itself. Key it by the call id from weft.CallFromContext, the session id (weft.session.id, which thread stamps on every run, read with weft.MetadataFromContext) and a business key for what the call acts on. 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:

sessions/idempotent.go
// refunds stands in for the payment side's ledger: one row per
// idempotency key. A real one is a table with a unique key, written in
// the same transaction as the refund itself.
type refunds struct {
mu sync.Mutex
done map[string]string // key → the result the first run returned
runs int // times the handler ran
paid int // refunds actually issued
}
// tool is a refund tool that pays each approved call once. A resume
// that runs the call again, after a crash cut the first run off, reads
// the recorded result instead of paying twice.
func (r *refunds) tool() *weft.ToolDef {
return weft.Tool("refund", "Refund an order. Requires a human decision.",
func(ctx context.Context, in struct {
OrderID string `json:"order_id"`
}) (string, error) {
call, _ := weft.CallFromContext(ctx)
// The call id is the same on every run of this call, so the
// run a resume repeats finds this entry. The session id keeps
// conversations apart but is the same on every turn, so within
// a session only the order id reliably tells operations apart:
// a later turn may reuse a call id (weft's Gemini adapter
// numbers call_0, call_1, … per step when the API sends none),
// and a later refund of the same order under a repeated id
// reads as done. Key by a refund request id instead when one
// order may be refunded twice.
session := weft.MetadataFromContext(ctx)["weft.session.id"]
key := session + "/" + call.CallID + "/" + in.OrderID
r.mu.Lock()
defer r.mu.Unlock()
r.runs++
if out, ok := r.done[key]; ok {
return out, nil
}
r.paid++
out := "Refunded order " + in.OrderID + "."
r.done[key] = out
return out, nil
},
weft.RequireApproval(),
)
}

sessions/idempotent.go on GitHub

TestIdempotentRefund resumes one parked call twice under one approval: the handler runs twice and pays once. TestIdempotentRefundPerSession sends the same call id and order on plain Generate runs under two session ids, stamped with weft.Metadata as thread stamps weft.session.id, and opens no thread session: two refunds.

Deleting a session deletes none of its children. pool.Children lists the direct ones, and pool.Descendants the whole subtree, deepest first:

sessions/pools.go
children, err := pool.Children(ctx, s)
if err != nil {
return err
}
all, err := pool.Descendants(ctx, s) // deepest first
if err != nil {
return err
}
fmt.Fprintln(w, "children:", children, "descendants:", all)
for _, id := range append(all, s.ID()) { // the parent last
if err := thread.Delete(ctx, st, id); err != nil {
return err
}
}
page, err := thread.List(ctx, st, thread.Query{})
if err != nil {
return err
}
fmt.Fprintln(w, "sessions left:", page.Total)

sessions/pools.go on GitHub

children: [c_1] descendants: [c_4 c_1]
sessions left: 0

Deleting in the order returned, the parent last, never leaves a child whose parent is already gone. Children lists the child of every receipt whose stored header names the parent as its lineage, and leaves out deleted ones. A child still running when its parent is deleted runs to its end and cannot record its settlement (the failure is logged). A Branch in the parent moves no child. A Fork copies the ledger but not the delegations: the fork’s copies of unsettled receipts are settled canceled, and Children does not list the origin’s children for the fork (ExampleDescendants).

p.Close(ctx) stops taking work and drains. Every queued or running child is canceled (a sync child’s parent model reads SUBAGENT_CANCELED), wrapped calls running outside any session are canceled too, and Close waits for all of them to settle their receipts and end. A child parked at an approval under a parent at rest is not canceled: its session is closed, its receipt stays parked, and a later pool resumes it. A sync grandchild parked under a child that Close cancels is canceled at its boundary, and settles canceled in that child’s ledger. A canceled child that is itself a parent waits for its own sync delegations under Cancel’s 30 s bound. ctx bounds the wait; a second Close returns nil. After Close, Submit, Decide, Recover and a wrapped tool’s call fail with pool.ErrClosed. Session.Close does not wait for pool children, so close pools before sessions (shutdown; ExamplePool_Close).

A delegation’s journey is a run of thread.PoolReceiptEntry entries in the parent (pool_receipt, "v": 4 on the wire: the format). pool.Receipts(parent) reads them back, in acceptance order, each at the state its entries record last. It reads the same after a restart as live: entries are the truth, and the pool holds no receipt state of its own. The first settlement a receipt records is its state for good. A session that never delegated returns nil.

A pool.Receipt is the handle and what is known:

FieldIs
IDthe acceptance entry’s id: the handle Wait, Cancel and Forward take
Statethe state the ledger records last, a pool.State
Childthe child session’s id
Callthe delegating tool call, for a wrapped tool; empty for a Submit
Stopon settlement, the child’s answer when done; the cause otherwise

r.Settled() reports whether the receipt reached a final state (ExampleReceipts).

*pool.StateError reports a receipt whose child is not in the state a call serves: Forward to a queued, parked or settled child, Cancel of a settled one. Its fields are Receipt (the id the call named), State, and Orphan (an unsettled receipt no child of this pool runs for, which Recover settles). Error names the receipt and its state; Is matches pool.ErrNotRunning.

accepted → running ⇄ parked → exactly one of done, failed, canceled, capped. A delegation canceled or failed before its child ever ran settles straight from accepted. The pool.State constants are the wire strings of the thread.PoolAccepted to thread.PoolCapped constants:

pool.Statethread constantWireMeans
pool.Acceptedthread.PoolAcceptedacceptedrecorded, and queued for a slot
pool.Runningthread.PoolRunningrunningthe slot is acquired and the child’s turn started (or the child waits, slotless, on a sync delegation of its own); written before the turn flies
pool.Parkedthread.PoolParkedparkedthe run ended at an approval boundary; no slot; the next running is its resume
pool.Donethread.PoolDonedoneran to its intended end; Stop is its answer, Usage its total cost
pool.Failedthread.PoolFailedfailedthe run failed, or the delegation could not proceed; Stop is the cause
pool.Canceledthread.PoolCanceledcanceledCancel, the pool’s Close, or for a sync child the delegating call’s own cancellation or timeout; never the submitting turn’s end, which an async child survives
pool.Cappedthread.PoolCappedcappeddied on a budget: weft.ErrMaxSteps or weft.ErrUsageLimit (the stop text says which)

State.Settled is true for the last four; an unknown state, a newer writer’s, is not settled. State.String returns the wire string. A receipt that stays accepted or running across a restart needs Recover.

A pool child is a session, not a tool-call child of the core’s weft.Subagent, so the core’s rule “a child’s usage is yours” does not reach it. Its usage is on neither the parent run’s RunResult.Usage nor StepRecord.SubagentUsage. It is on the settling receipt, and s.Usage() sums the settled receipts into thread.Usage.Delegated, the ledger’s third bucket beside Turns and Summaries (AGENTS rule 13’s one exception; TestDelegatedUsage).

A settlement’s Usage is the child session’s turns and summaries: every run it made for the delegation, the ones before a park included. That is why the async refund above reports 10 output tokens: the child’s model ran once to park and once to finish. It does not include the child’s own Delegated, and a session’s Delegated sums only its direct receipts, so a grandchild’s tokens are not in the root’s Delegated. For a nested tree, sum Usage().Delegated over the sessions pool.Descendants returns as well.

A budget such as weft.UsageLimit on the parent run does not see delegated work; a budget that must cover it reads Delegated, across the tree.

A child parks in its own session; the pool mirrors its requests onto the parent so the parent’s Pending shows them with their lineage:

  • The mirror. Each mirrored request is an approval_request entry in the parent with a namespaced call id (<child>/<call>), child naming the child session and wrapper the parent-side delegating call (empty for an async delegation). Pending() lists the mirrors and hides the parked wrapper call.
  • The wrapper is never decidable. A decision naming the delegating call fails with thread.ErrDelegated: approving it would run the delegation a second time, in a second child session. The parent’s decision chain keeps the same rule: no grant and no live Approver is consulted for a delegating call when it parks (TestChainNeverDecidesWrapper).
  • The replay. When a child resumes, the parent’s decisions for its pending calls are replayed into the child session, keeping the decider’s identity, with via parent. Only calls pending in the child now are replayed, so an earlier park’s decisions never are.
  • A re-park supersedes. A grandchild that parks again while the child waits on it mirrors its new request up the chain. The new request keeps the namespaced call id and names the new occurrence by its run. It supersedes the earlier one, and a decision recorded for the earlier one does not decide it.
  • The resolution. When the child ends, a sync delegation’s parked call resolves with the child’s outcome (via child): a resolve with the answer for a done child, a resolve_error otherwise. That resumes the parent: the parked turn’s Next is the continuation once Wait reports the receipt settled. A child that parks again mirrors its new requests and waits for the next Decide.
  • Decisions by other paths reach the children. The pool watches every parent it delegates from. A Session.Decide or DecideSigned used directly, an interrupting Send’s denial (the child resumes with DENIED: interrupted by a newer message), or a request lapsing past its expiry runs the pump on a pool goroutine. After a restart nothing is watched until the pool next touches the parent: Recover, Decide, DecideSigned or a new delegation.

thread.MirroredRequest is one mirror as the parent holds it. Request is the mirror: its CallID in the namespaced form, Child, and RunID the child run that parked. Wrapper is the delegating call, empty for async. Then Decisions (the decisions in force for this occurrence, in record order) and Decided (whether they reach an effective verdict under the parent’s Quorum, the moment the pool replays them). thread.InheritApprovals(parent) is the session option that gives a child the parent’s expiry, quorum, keyring, RequireSigned rule and clock; Submit and Wrap apply it.

NameKindMeaning
pool.Optiontypeconfigures a pool at New
pool.MaxDepth(n)optiondelegation depth; New panics below 1
pool.DefaultMaxDepthconst, 8the depth when MaxDepth is not given
pool.IDs(f)optionmints child session ids and every entry id inside each child; the parent’s ids stay its own. Called from many goroutines under session locks: safe for concurrent use, quick, never repeating
pool.WrapOptiontypeconfigures one wrapped tool: pool.Async, pool.ToolOptions
pool.ErrClosederrorwork handed to a closed pool
pool.ErrCycleerrorSubmit to an agent already running above the delegating run; a wrapped tool reports SUBAGENT_CYCLE
pool.ErrDeptherrorSubmit past MaxDepth; a wrapped tool reports SUBAGENT_DEPTH
pool.ErrDuplicateWraperrorWrap of a different agent under a name already in use
pool.ErrNoAgenterrorDecide, Recover, Cancel need to reopen a child and the pool holds no agent for it: wrap it again under its name, or Register it
pool.ErrNotRunningerrorwhat every *StateError matches
pool.ErrUnknownReceipterrorCancel, Forward, Wait with an id the parent’s ledger does not hold
pool.CodeSubagentDepthconstSUBAGENT_DEPTH, refused before any child is created; the core has no depth limit
pool.CodeSubagentCanceledconstSUBAGENT_CANCELED, a sync child the pool canceled; the parent’s own cancellation ends the parent’s run instead

What a delegating model reads is a contract (AGENTS rule 5), every string pinned by a test. Besides the child’s answer and the async receipt line:

ResultWhen
SUBAGENT_CYCLE: agent "<name>" is already running in this call chainthe agent is already running above the call; only for a real cycle
SUBAGENT_DEPTH: delegation depth <n> exceeds the pool's limit <m>the delegation would exceed MaxDepth (it used to read SUBAGENT_CYCLE)
SUBAGENT_FAILED: agent "<name>" failed at step <n>: <cause>the child’s run failed: the core’s text, byte for byte
SUBAGENT_FAILED: agent "<name>" failed: <cause>a failure outside a child run, or one Recover read from the ledger
SUBAGENT_FAILED: agent "<name>" parked at an approval the pool could not surface: <cause>the mirror could not be written on the parent
SUBAGENT_CANCELED: agent "<name>" was canceled before it finishedCancel or Close ended a sync child
DENIED: the delegation was canceled while awaiting approvalwhat a canceled, parked child’s model reads if its session is ever resumed
thread/pool: pool is closeda wrapped tool called after the pool’s Close: the model reads pool.ErrClosed’s text as the result

A delegating call is never re-executed by a decision: its result is the child’s answer, once. Arguments that do not decode as {"prompt": "..."} read thread/pool: decode "<name>" arguments: followed by encoding/json’s description, and leave no receipt.

The pool lives in another package, so thread exports what it needs to write its ledger and bridge approvals. An application delegates with Wrap and Submit, decides with Decide, DecideSigned and p.Decide, and never calls these. Go has no package-private export; this is the boundary (thread/poolplumbing.go:11-25), and it is still exported before the freeze (a known limit).

Method or functionWhat the pool uses it for
Session.AppendPoolReceiptone receipt entry per state; returns it stored, its id the receipt handle. Exactly one settlement per receipt is the caller’s contract, since Usage sums them
Session.AppendApprovalRequestsmirrored requests, one atomic batch; every request must name its Child
Session.MirroredRequeststhe mirrors in force, decided or not; expiry resolved first
Session.ReplayDecisionsin a child, record the parent’s decisions (via parent) and resume; idempotent
Session.ResolveDelegationresolve a delegating call with the child’s outcome (who thread/pool, via child)
Session.DenyMirroreddeny a child’s still-pending mirrors when its delegation ends
Session.CancelDelegatedin a parked child, deny every pending request and resume nothing
Session.WatchMirrorsbe told when the parent records a decision for a mirror
Session.MirrorWatchersthe owners holding a WatchMirrors notification on the session: the pools delegating from it, or handed it by Decide, DecideSigned or Recover. With several pools on one parent, each pool’s pump walks every receipt of the parent’s ledger and asks it to tell another pool’s child from one it cannot resume
Session.Storage, Session.Lineage, thread.SessionFromContextwhere to create children; a session’s parent; the session a run’s context carries
thread.WithLineage, thread.WithMeta, thread.InheritApprovalsthe child’s header options and inherited policy

thread.Request.Child names the session a mirrored request parks in.

sessions/pools.go wraps, bounds, delegates in the background, steers, cancels, recovers and cascades:

sessions/pools.go
package main
import (
"context"
"errors"
"fmt"
"io"
"path/filepath"
"sync"
"sync/atomic"
"github.com/weftgo/weft"
"github.com/weftgo/weft/thread"
"github.com/weftgo/weft/thread/jsonl"
"github.com/weftgo/weft/thread/pool"
"github.com/weftgo/weft/wefttest"
)
// demoPools is the page "Run bounded child sessions with a pool".
func demoPools(ctx context.Context, w io.Writer, dir string) error {
fmt.Fprintln(w, "== wrap")
if _, err := poolWrap(ctx, w); err != nil {
return err
}
fmt.Fprintln(w, "== bound")
if _, err := poolBound(ctx, w); err != nil {
return err
}
fmt.Fprintln(w, "== async")
if _, err := poolAsync(ctx, w); err != nil {
return err
}
fmt.Fprintln(w, "== forward and cancel")
if err := poolForwardCancel(ctx, w); err != nil {
return err
}
fmt.Fprintln(w, "== recover")
if _, err := poolRecover(ctx, w, dir); err != nil {
return err
}
fmt.Fprintln(w, "== cascade")
return poolCascade(ctx, w)
}
// childIDs mints the ids of the child sessions a pool creates, and
// the entry ids inside them: c_1, c_2, … It is safe for concurrent
// use and never repeats, as pool.IDs requires. An application leaves
// pool.IDs out and gets time-sortable random ids.
func childIDs() pool.Option {
var n atomic.Int64
return pool.IDs(func() string { return fmt.Sprintf("c_%d", n.Add(1)) })
}
// poolWrap: a sync delegation. The wrapped tool's child runs as a
// session of its own; the call waits for its answer. It returns the
// parent session's ledger for the test.
func poolWrap(ctx context.Context, w io.Writer) (thread.Usage, error) {
st := thread.Memory()
p := pool.New(4, childIDs()) // at most 4 child runs at work at once
researcher := weft.New(wefttest.Script(wefttest.Say("Order 1234 left the Leeds depot on Monday.")))
research := p.MustWrap("research", "Research an order in depth.", researcher)
support := weft.New(wefttest.Script(
wefttest.ToolCalls(wefttest.Call{Name: "research", ID: "call_1", Args: `{"prompt":"Trace order 1234."}`}),
wefttest.Say("Order 1234 left the depot on Monday."),
), research)
s, err := thread.Create(ctx, st, support, ctxWindow, ids("s_support", "a"), at(base))
if err != nil {
return thread.Usage{}, err
}
turn, err := s.Send(ctx, weft.User("Where is order 1234?"))
if err != nil {
return thread.Usage{}, err
}
res, err := turn.Wait()
if err != nil {
return thread.Usage{}, err
}
fmt.Fprintln(w, "reply:", res.Text())
for _, r := range pool.Receipts(s) {
fmt.Fprintf(w, "receipt %s: %s child %s call %s stop %q\n", r.ID, r.State, r.Child, r.Call, r.Stop)
}
u := s.Usage()
fmt.Fprintln(w, "output tokens: run", res.Usage.OutputTokens, "| turns", u.Turns.OutputTokens, "| delegated", u.Delegated.OutputTokens)
if err := s.Close(ctx); err != nil {
return thread.Usage{}, err
}
return u, p.Close(ctx)
}
// worker is a child agent whose one tool call blocks until release is
// closed, recording how many such calls are in flight at once.
type worker struct {
started chan struct{}
release chan struct{}
mu sync.Mutex
active int
peak int
tool *weft.ToolDef
}
func newWorker() *worker {
wk := &worker{started: make(chan struct{}, 16), release: make(chan struct{})}
wk.tool = weft.Tool("work", "Do one slow task.", func(ctx context.Context, _ struct{}) (string, error) {
wk.mu.Lock()
wk.active++
wk.peak = max(wk.peak, wk.active)
wk.mu.Unlock()
defer func() { wk.mu.Lock(); wk.active--; wk.mu.Unlock() }()
wk.started <- struct{}{}
select {
case <-wk.release:
return "finished", nil
case <-ctx.Done():
return "", ctx.Err()
}
})
return wk
}
// agent returns a fresh child agent: each child gets its own script.
func (wk *worker) agent() *weft.Agent {
return weft.New(wefttest.Script(
wefttest.ToolCalls(wefttest.Call{Name: "work", ID: "call_w"}),
wefttest.Say("done"),
), wk.tool)
}
// poolBound: four children on a pool of two. Two work, two wait in
// the pool's queue with an accepted receipt. It returns the peak
// number of children at work at once.
func poolBound(ctx context.Context, w io.Writer) (int, error) {
parent, err := thread.Create(ctx, thread.Memory(), weft.New(wefttest.Script()), ctxWindow, ids("s_batch", "a"), at(base))
if err != nil {
return 0, err
}
wk := newWorker()
p := pool.New(2, childIDs())
var receipts []*pool.Receipt
for i := range 4 {
r, err := p.Submit(ctx, parent, wk.agent(), fmt.Sprintf("task %d", i+1))
if err != nil {
return 0, err
}
receipts = append(receipts, r) // returned at once, state accepted
}
<-wk.started
<-wk.started // two children are inside their tool; the other two queue
states := map[pool.State]int{}
for _, r := range pool.Receipts(parent) {
states[r.State]++
}
fmt.Fprintln(w, "running:", states[pool.Running], "accepted:", states[pool.Accepted])
close(wk.release)
for i, r := range receipts {
final, err := p.Wait(ctx, parent, r.ID)
if err != nil {
return 0, err
}
fmt.Fprintf(w, "task %d: %s\n", i+1, final.State)
}
if err := p.Close(ctx); err != nil {
return 0, err
}
fmt.Fprintln(w, "at work at once, at most:", wk.peak)
return wk.peak, parent.Close(ctx)
}
// poolAsync: an async wrapped tool. The model reads a receipt line;
// the child parks at an approval, the application decides it through
// the pool and waits for the settlement. It returns the final receipt.
func poolAsync(ctx context.Context, w io.Writer) (pool.Receipt, error) {
st := thread.Memory()
refunder := weft.New(wefttest.Script(
refundCall("call_r", "1234"),
wefttest.Say("Refunded order 1234."),
), refundTool())
p := pool.New(4, childIDs())
refunds := p.MustWrap("refunds", "Start a refund in the background.", refunder, pool.Async())
support := weft.New(wefttest.Script(
wefttest.ToolCalls(wefttest.Call{Name: "refunds", ID: "call_1", Args: `{"prompt":"Refund order 1234."}`}),
wefttest.Say("The refund has started."),
), refunds)
s, err := thread.Create(ctx, st, support, ctxWindow, ids("s_async", "a"), at(base))
if err != nil {
return pool.Receipt{}, err
}
turn, err := s.Send(ctx, weft.User("Refund order 1234."))
if err != nil {
return pool.Receipt{}, err
}
res, err := turn.Wait()
if err != nil {
return pool.Receipt{}, err
}
fmt.Fprintln(w, "the model read:", lastToolResult(res.Messages))
fmt.Fprintln(w, "reply:", res.Text())
r := pool.Receipts(s)[0]
rest, err := p.Wait(ctx, s, r.ID) // at rest: settled, or parked at an approval
if err != nil {
return pool.Receipt{}, err
}
fmt.Fprintln(w, "receipt:", rest.State)
for _, req := range s.Pending() {
fmt.Fprintln(w, "pending:", req.CallID, req.Tool, "in", req.Child)
}
if err := p.Decide(ctx, s, thread.Approve(s.Pending()[0].CallID)); err != nil {
return pool.Receipt{}, err // Decide records and arms the child; it does not wait
}
final, err := p.Wait(ctx, s, r.ID)
if err != nil {
return pool.Receipt{}, err
}
fmt.Fprintf(w, "receipt: %s %q | delegated output tokens: %d\n", final.State, final.Stop, s.Usage().Delegated.OutputTokens)
if err := s.Close(ctx); err != nil {
return pool.Receipt{}, err
}
return final, p.Close(ctx)
}
// lastToolResult returns the content of the last tool result in msgs.
func lastToolResult(msgs []weft.Message) string {
out := ""
for _, m := range msgs {
for _, part := range m.Content {
if r, ok := part.(weft.ToolResultPart); ok {
out = r.Content
}
}
}
return out
}
// poolForwardCancel: steer a running child, then cancel another.
func poolForwardCancel(ctx context.Context, w io.Writer) error {
s, err := thread.Create(ctx, thread.Memory(), weft.New(wefttest.Script()), ctxWindow, ids("s_steer", "a"), at(base))
if err != nil {
return err
}
p := pool.New(2, childIDs())
convert, started, release := slowTool("convert")
converter := weft.New(wefttest.Script(
wefttest.ToolCalls(wefttest.Call{Name: "convert", ID: "call_c"}),
wefttest.Say("Converted the totals to euros."),
), convert)
r, err := p.Submit(ctx, s, converter, "Convert the totals.")
if err != nil {
return err
}
<-started // the child is mid-run, inside its tool
if _, err := p.Forward(ctx, s, r.ID, weft.User("Use euros, not dollars.")); err != nil {
return err
}
close(release)
final, err := p.Wait(ctx, s, r.ID)
if err != nil {
return err
}
fmt.Fprintln(w, "forwarded:", final.State, final.Stop)
_, err = p.Forward(ctx, s, r.ID, weft.User("Too late."))
var se *pool.StateError
fmt.Fprintln(w, "after the end:", errors.Is(err, pool.ErrNotRunning), errors.As(err, &se) && se.State == pool.Done)
hold, held, _ := slowTool("hold")
holder := weft.New(wefttest.Script(wefttest.ToolCalls(wefttest.Call{Name: "hold", ID: "call_h"})), hold)
r, err = p.Submit(ctx, s, holder, "Wait for the warehouse.")
if err != nil {
return err
}
<-held
if err := p.Cancel(ctx, s, r.ID); err != nil { // cancels the run; Wait follows the settlement
return err
}
final, err = p.Wait(ctx, s, r.ID)
if err != nil {
return err
}
fmt.Fprintln(w, "canceled:", final.State, final.Settled())
fmt.Fprintln(w, "cancel again:", errors.Is(p.Cancel(ctx, s, r.ID), pool.ErrNotRunning))
fmt.Fprintln(w, "unknown receipt:", errors.Is(p.Cancel(ctx, s, "e_nope"), pool.ErrUnknownReceipt))
if err := p.Close(ctx); err != nil {
return err
}
return s.Close(ctx)
}
// poolRecover: a sync delegation parks at an approval, the process
// stops, and a second process recovers it from the JSONL files.
// It returns the final receipt.
func poolRecover(ctx context.Context, w io.Writer, dir string) (pool.Receipt, error) {
sessions := filepath.Join(dir, "pool-sessions")
// The first process: the child parks, then pool and session close.
{
st, err := jsonl.Open(sessions)
if err != nil {
return pool.Receipt{}, err
}
p := pool.New(4, childIDs())
refunder := weft.New(wefttest.Script(refundCall("call_r", "1234")), refundTool())
support := weft.New(wefttest.Script(
wefttest.ToolCalls(wefttest.Call{Name: "refunds", ID: "call_1", Args: `{"prompt":"Refund order 1234."}`}),
), p.MustWrap("refunds", "Run the refund flow.", refunder))
s, err := thread.Create(ctx, st, support, ctxWindow, ids("s_refunds", "a"), at(base))
if err != nil {
return pool.Receipt{}, err
}
turn, err := s.Send(ctx, weft.User("Refund order 1234."))
if err != nil {
return pool.Receipt{}, err
}
res, err := turn.Wait()
if err != nil {
return pool.Receipt{}, err
}
fmt.Fprintln(w, "first process: pending", len(res.Pending), "| receipt", pool.Receipts(s)[0].State)
if err := p.Close(ctx); err != nil { // a parked child stays parked
return pool.Receipt{}, err
}
if err := s.Close(ctx); err != nil {
return pool.Receipt{}, err
}
}
// The second process: a new Storage, a new pool, the same agents
// wrapped under the same names.
st, err := jsonl.Open(sessions)
if err != nil {
return pool.Receipt{}, err
}
p := pool.New(4)
refunder := weft.New(wefttest.Script(wefttest.Say("Refunded order 1234.")), refundTool())
support := weft.New(wefttest.Script(wefttest.Say("Order 1234 is refunded.")),
p.MustWrap("refunds", "Run the refund flow.", refunder))
s, err := thread.Open(ctx, st, "s_refunds", support, ctxWindow, ids("", "b"), at(base))
if err != nil {
return pool.Receipt{}, err
}
if err := p.Recover(ctx, s); err != nil { // once per parent session, after the wraps
return pool.Receipt{}, err
}
req := s.Pending()[0]
fmt.Fprintln(w, "after Recover:", pool.Receipts(s)[0].State, "| pending", req.CallID)
if err := p.Decide(ctx, s, thread.Approve(req.CallID)); err != nil {
return pool.Receipt{}, err
}
final, err := p.Wait(ctx, s, pool.Receipts(s)[0].ID)
if err != nil {
return pool.Receipt{}, err
}
fmt.Fprintln(w, "receipt:", final.State, final.Stop)
if err := p.Close(ctx); err != nil {
return pool.Receipt{}, err
}
if err := s.Close(ctx); err != nil { // waits for the parent's own resume
return pool.Receipt{}, err
}
msgs := s.Context()
fmt.Fprintln(w, "parent:", msgs[len(msgs)-1].Text())
return final, nil
}
// poolCascade: deleting a parent deletes no child; Descendants lists
// the subtree deepest first, the order to delete in.
func poolCascade(ctx context.Context, w io.Writer) error {
st := thread.Memory()
p := pool.New(2, childIDs())
lookup := weft.New(wefttest.Script(wefttest.Say("Order 1234: Leeds depot.")))
research := weft.New(wefttest.Script(
wefttest.ToolCalls(wefttest.Call{Name: "lookup", ID: "call_l", Args: `{"prompt":"Find order 1234."}`}),
wefttest.Say("It is at the Leeds depot."),
), p.MustWrap("lookup", "Look an order up.", lookup))
support := weft.New(wefttest.Script(
wefttest.ToolCalls(wefttest.Call{Name: "research", ID: "call_r", Args: `{"prompt":"Where is order 1234?"}`}),
wefttest.Say("Order 1234 is at the Leeds depot."),
), p.MustWrap("research", "Research an order.", research))
s, err := thread.Create(ctx, st, support, ctxWindow, ids("s_tree", "a"), at(base))
if err != nil {
return err
}
turn, err := s.Send(ctx, weft.User("Where is order 1234?"))
if err != nil {
return err
}
if _, err := turn.Wait(); err != nil {
return err
}
if err := p.Close(ctx); err != nil {
return err
}
if err := s.Close(ctx); err != nil {
return err
}
children, err := pool.Children(ctx, s)
if err != nil {
return err
}
all, err := pool.Descendants(ctx, s) // deepest first
if err != nil {
return err
}
fmt.Fprintln(w, "children:", children, "descendants:", all)
for _, id := range append(all, s.ID()) { // the parent last
if err := thread.Delete(ctx, st, id); err != nil {
return err
}
}
page, err := thread.List(ctx, st, thread.Query{})
if err != nil {
return err
}
fmt.Fprintln(w, "sessions left:", page.Total)
return nil
}

View sessions/pools.go on GitHub

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

Terminal window
go run ./sessions pools
go test ./sessions
== wrap
reply: Order 1234 left the depot on Monday.
receipt e_a3: done child c_1 call call_1 stop "Order 1234 left the Leeds depot on Monday."
output tokens: run 10 | turns 10 | delegated 5
== bound
running: 2 accepted: 2
task 1: done
task 2: done
task 3: done
task 4: done
at work at once, at most: 2
== async
the model read: background task accepted; receipt e_a3
reply: The refund has started.
receipt: parked
pending: c_1/call_r refund in c_1
receipt: done "Refunded order 1234." | delegated output tokens: 10
== forward and cancel
forwarded: done Converted the totals to euros.
after the end: true true
canceled: canceled true
cancel again: true
unknown receipt: true
== recover
first process: pending 1 | receipt parked
after Recover: parked | pending c_1/call_r
receipt: done Refunded order 1234.
parent: Order 1234 is refunded.
== cascade
children: [c_1] descendants: [c_4 c_1]
sessions left: 0

Standard error carries 12 lines of WARN thread: no context window known for this session, one per child Session value that ran a turn: the pool creates each child without a thread.ContextWindow (gotchas).

  • Let one pool own a storage’s delegations. Recover treats an unsettled receipt no child of this pool is running as left by a dead process; with two live pools over the same sessions, a Recover or Cancel through one settles the other’s running work failed. (Source: docs/thread-operations.md §10; thread/pool/pool.go:176 Pool godoc)
  • Keep wrap names stable. The name is the resume key a restarted process finds the agent by. Renamed a wrap or used Submit? p.Register(childID, agent) before Recover. (Source: thread/pool/wrap.go:135 Wrap godoc; thread/pool/bridge.go:941)
  • Wrap and register before Recover, and call it once per parent the process takes over. A child whose agent the pool lacks is left for later with ErrNoAgent. (Source: thread/pool/recover.go:58 Recover godoc)
  • Recover never re-runs a child’s first run. A child that died mid-run with no approval boundary on file settles failed. A finished child’s answer is read back as its last assistant text, so a structured Output answer is not recovered as such. The cycle guard above a rebuilt child restarts at that child’s own agent (the depth limit still holds). (Source: CHANGELOG.md:4101; docs/thread-operations.md §10)
  • Make an approved tool idempotent. A child whose resume a crash cut off resumes again after Recover, and an approved call whose result was not recorded runs again, at any depth. Key the side effect 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/pool/recover.go:13-36 Recover godoc; thread/pool/twolevel_test.go:632 TestNestedRestartMidApprovedCallRunsItAgain)
  • Budgets on the parent run do not cover delegated work. Read s.Usage().Delegated, summed over pool.Descendants for a nested tree. (Source: AGENTS rule 13; thread/pool/pool.go:34-43, 1089-1090; thread/session.go:1535-1539)
  • Pool children get no context window. The pool creates children with lineage, inherited approvals, metadata and ids only, so each child Session value logs the no-window WARN at its first turn and never compacts on its own. (Source: thread/pool/pool.go:886-897; thread/compaction.go:1306-1319)
  • Close pools before sessions. Session.Close does not wait for pool children; a parked child stays parked across Close. (Source: docs/thread-operations.md §5; thread/pool/pool.go:629 Close godoc)
  • Cascade deletes yourself. Delete Descendants in the order returned, then the parent. (Source: thread/pool/pool.go:763; ExampleDescendants)
  • Default-deny reaches every child. A parent turn sent with thread.RunOptions(weft.ParkAllExcept(...)) binds its children, sync and async, on every turn they run; name a wrap’s tool in the list for the delegation itself to run. (Source: docs/thread-operations.md §10; CHANGELOG.md:3247)
  • Run an Async wrap inside a session turn. Called from a plain Generate, the tool ignores pool.Async(): it waits for the child and returns its answer, so the run is as slow as the child and nothing is receipted. Send the turn through s.Send instead. (Source: thread/pool/wrap.go:156-160, 178-184)
  • Do not decide the delegating call. Decide the child’s mirrored requests; the delegating call completes with the child’s answer, and deciding it fails with thread.ErrDelegated. (Source: thread/approval.go:73-83; TestWrapperNotDecidable)

Symbols used: pool.New · pool.Pool · Pool.Wrap · Pool.MustWrap · Pool.Submit · Pool.Wait · Pool.Decide · Pool.DecideSigned · Pool.Forward · Pool.Cancel · Pool.Register · Pool.Recover · Pool.Close · pool.Receipts · pool.Receipt · pool.State · pool.StateError · pool.Children · pool.Descendants · pool.Async · pool.ToolOptions · pool.MaxDepth · pool.IDs · thread.PoolReceiptEntry · thread.Usage · thread.MirroredRequest · thread.InheritApprovals · thread.ErrDelegated · Session.Pending · Session.Usage · thread.Watcher · thread.Approve · thread.Create · thread.Open · thread.Delete · thread.List · jsonl.Open · weft.Subagent · weft.WrapTools · weft.Nested · weft.UsageLimit · weft.RequireApproval · weft.ParkAllExcept · weft.CallFromContext · wefttest.Script