Run bounded child sessions with a pool
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:
p := pool.New(4, childIDs()) // at most 4 child runs at work at onceresearcher := 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)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 5The 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.
How a pool works
Section titled “How a pool works”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:
Submitqueues 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 ispool.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 readSUBAGENT_CYCLE; since thread 0.9.0 depth isMaxDepth’s and readsSUBAGENT_DEPTH. - A child is a session. It is created in the parent’s storage with a header whose
lineagenames 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 throughthread.InheritApprovals: request expiry, quorum, keyring,RequireSignedand clock. - A child’s events are its own. They are not
weft.Nestedevents 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.Subagentunder a tool-levelweft.WrapToolsmiddleware, 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:
| Call | Does |
|---|---|
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 |
Delegate with a pool
Section titled “Delegate with a pool”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.
Wait for the child’s answer
Section titled “Wait for the child’s answer”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": "..."}.
Wrapfails on a nil agent or an empty name, and withpool.ErrDuplicateWrapfor 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.MustWrappanics 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.RequireApprovalgates 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.
Delegate in the background
Section titled “Delegate in the background”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:
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())the model read: background task accepted; receipt e_a3reply: 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:
p := pool.New(2, childIDs())var receipts []*pool.Receiptfor 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 queuestates := 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}running: 2 accepted: 2task 1: donetask 2: donetask 3: donetask 4: doneTwo 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).
Decide a child’s approvals
Section titled “Decide a child’s approvals”A child that reaches a weft.RequireApproval tool parks, and its request surfaces on the parent’s s.Pending(). Decide it through the pool:
r := pool.Receipts(s)[0]rest, err := p.Wait(ctx, s, r.ID) // at rest: settled, or parked at an approvalif 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)receipt: parkedpending: c_1/call_r refund in c_1receipt: done "Refunded order 1234." | delegated output tokens: 10The 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.
Steer a running child
Section titled “Steer a running child”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:
r, err := p.Submit(ctx, s, converter, "Convert the totals.")if err != nil { return err}<-started // the child is mid-run, inside its toolif _, 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.StateErrorfmt.Fprintln(w, "after the end:", errors.Is(err, pool.ErrNotRunning), errors.As(err, &se) && se.State == pool.Done)forwarded: done Converted the totals to euros.after the end: true trueA 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).
Cancel a delegation
Section titled “Cancel a delegation”p.Cancel(ctx, parent, receiptID) ends one delegation:
r, err = p.Submit(ctx, s, holder, "Wait for the warehouse.")if err != nil { return err}<-heldif 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))canceled: canceled truecancel again: trueunknown receipt: trueWhat 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
canceledon the delegation’s goroutine.Canceldoes not wait for that;Waitdoes. A sync delegation’s model readsSUBAGENT_CANCELED. - Parked: the child’s pending requests are denied in the child session, its run is not resumed, the receipt settles
canceledbeforeCancelreturns, and the mirrored requests leave the parent’sPending. - 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):Cancelwaits for the park to finish, bounded byctx, then cancels it as a parked child. A running child that reaches its approval boundary before the cancel stops it does not park; it settlescanceled.
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).
Recover after a restart
Section titled “Recover after a restart”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:
// 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())first process: pending 1 | receipt parkedafter Recover: parked | pending c_1/call_rreceipt: 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 child | Recover |
|---|---|
| is parked at an approval | rebuilds 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 run | settles 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 gone | settles 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).
Make an approved tool idempotent
Section titled “Make an approved tool idempotent”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:
// 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(), )}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.
Delete a parent and its children
Section titled “Delete a parent and its children”Deleting a session deletes none of its children. pool.Children lists the direct ones, and pool.Descendants the whole subtree, deepest first:
children, err := pool.Children(ctx, s)if err != nil { return err}all, err := pool.Descendants(ctx, s) // deepest firstif 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)children: [c_1] descendants: [c_4 c_1]sessions left: 0Deleting 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).
Close the pool
Section titled “Close the pool”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).
Receipts
Section titled “Receipts”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:
| Field | Is |
|---|---|
ID | the acceptance entry’s id: the handle Wait, Cancel and Forward take |
State | the state the ledger records last, a pool.State |
Child | the child session’s id |
Call | the delegating tool call, for a wrapped tool; empty for a Submit |
Stop | on 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.
Receipt states
Section titled “Receipt states”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.State | thread constant | Wire | Means |
|---|---|---|---|
pool.Accepted | thread.PoolAccepted | accepted | recorded, and queued for a slot |
pool.Running | thread.PoolRunning | running | the 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.Parked | thread.PoolParked | parked | the run ended at an approval boundary; no slot; the next running is its resume |
pool.Done | thread.PoolDone | done | ran to its intended end; Stop is its answer, Usage its total cost |
pool.Failed | thread.PoolFailed | failed | the run failed, or the delegation could not proceed; Stop is the cause |
pool.Canceled | thread.PoolCanceled | canceled | Cancel, 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.Capped | thread.PoolCapped | capped | died 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.
Nested approvals
Section titled “Nested approvals”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_requestentry in the parent with a namespaced call id (<child>/<call>),childnaming the child session andwrapperthe 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 liveApproveris 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
viaparent. 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 (
viachild): a resolve with the answer for adonechild, aresolve_errorotherwise. That resumes the parent: the parked turn’sNextis the continuation onceWaitreports the receipt settled. A child that parks again mirrors its new requests and waits for the nextDecide. - Decisions by other paths reach the children. The pool watches every parent it delegates from. A
Session.DecideorDecideSignedused directly, an interruptingSend’s denial (the child resumes withDENIED: 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,DecideSignedor 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.
Limits and errors
Section titled “Limits and errors”| Name | Kind | Meaning |
|---|---|---|
pool.Option | type | configures a pool at New |
pool.MaxDepth(n) | option | delegation depth; New panics below 1 |
pool.DefaultMaxDepth | const, 8 | the depth when MaxDepth is not given |
pool.IDs(f) | option | mints 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.WrapOption | type | configures one wrapped tool: pool.Async, pool.ToolOptions |
pool.ErrClosed | error | work handed to a closed pool |
pool.ErrCycle | error | Submit to an agent already running above the delegating run; a wrapped tool reports SUBAGENT_CYCLE |
pool.ErrDepth | error | Submit past MaxDepth; a wrapped tool reports SUBAGENT_DEPTH |
pool.ErrDuplicateWrap | error | Wrap of a different agent under a name already in use |
pool.ErrNoAgent | error | Decide, 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.ErrNotRunning | error | what every *StateError matches |
pool.ErrUnknownReceipt | error | Cancel, Forward, Wait with an id the parent’s ledger does not hold |
pool.CodeSubagentDepth | const | SUBAGENT_DEPTH, refused before any child is created; the core has no depth limit |
pool.CodeSubagentCanceled | const | SUBAGENT_CANCELED, a sync child the pool canceled; the parent’s own cancellation ends the parent’s run instead |
Result codes
Section titled “Result codes”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:
| Result | When |
|---|---|
SUBAGENT_CYCLE: agent "<name>" is already running in this call chain | the 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 finished | Cancel or Close ended a sync child |
DENIED: the delegation was canceled while awaiting approval | what a canceled, parked child’s model reads if its session is ever resumed |
thread/pool: pool is closed | a 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.
Session plumbing
Section titled “Session plumbing”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 function | What the pool uses it for |
|---|---|
Session.AppendPoolReceipt | one 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.AppendApprovalRequests | mirrored requests, one atomic batch; every request must name its Child |
Session.MirroredRequests | the mirrors in force, decided or not; expiry resolved first |
Session.ReplayDecisions | in a child, record the parent’s decisions (via parent) and resume; idempotent |
Session.ResolveDelegation | resolve a delegating call with the child’s outcome (who thread/pool, via child) |
Session.DenyMirrored | deny a child’s still-pending mirrors when its delegation ends |
Session.CancelDelegated | in a parked child, deny every pending request and resume nothing |
Session.WatchMirrors | be told when the parent records a decision for a mirror |
Session.MirrorWatchers | the 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.SessionFromContext | where to create children; a session’s parent; the session a run’s context carries |
thread.WithLineage, thread.WithMeta, thread.InheritApprovals | the child’s header options and inherited policy |
thread.Request.Child names the session a mirrored request parks in.
Complete example
Section titled “Complete example”sessions/pools.go wraps, bounds, delegates in the background, steers, cancels, recovers and cascades:
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 on GitHub · run it from docs-site/examples:
go run ./sessions poolsgo test ./sessions== wrapreply: 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== boundrunning: 2 accepted: 2task 1: donetask 2: donetask 3: donetask 4: doneat work at once, at most: 2== asyncthe model read: background task accepted; receipt e_a3reply: The refund has started.receipt: parkedpending: c_1/call_r refund in c_1receipt: done "Refunded order 1234." | delegated output tokens: 10== forward and cancelforwarded: done Converted the totals to euros.after the end: true truecanceled: canceled truecancel again: trueunknown receipt: true== recoverfirst process: pending 1 | receipt parkedafter Recover: parked | pending c_1/call_rreceipt: done Refunded order 1234.parent: Order 1234 is refunded.== cascadechildren: [c_1] descendants: [c_4 c_1]sessions left: 0Standard 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).
Best practices & gotchas
Section titled “Best practices & gotchas”- Let one pool own a storage’s delegations.
Recovertreats an unsettled receipt no child of this pool is running as left by a dead process; with two live pools over the same sessions, aRecoverorCancelthrough one settles the other’s running workfailed. (Source:docs/thread-operations.md§10;thread/pool/pool.go:176Pool 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)beforeRecover. (Source:thread/pool/wrap.go:135Wrap 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 withErrNoAgent. (Source:thread/pool/recover.go:58Recover godoc) Recovernever re-runs a child’s first run. A child that died mid-run with no approval boundary on file settlesfailed. A finished child’s answer is read back as its last assistant text, so a structuredOutputanswer 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 byweft.CallFromContext’s call id, the session id (weft.session.idinweft.MetadataFromContext) and a business key for what the call acts on, such as the order id. The call id is the same on every run of one call, so the run a resume repeats finds the first run’s entry. The session id keeps conversations apart, but it is the same on every turn of one session. Within a session only the business key reliably tells operations apart, because a later turn may reuse a call id (weft’s Gemini adapter, for one, numbers callscall_0,call_1, … per step when the API sends no id): keyed by the order id, a later turn’s refund of the same order under a repeated call id reads as already done. Name the operation itself, such as a refund request id, when one order may be refunded twice. (Source:thread/pool/recover.go:13-36Recover godoc;thread/pool/twolevel_test.go:632TestNestedRestartMidApprovedCallRunsItAgain) - Budgets on the parent run do not cover delegated work. Read
s.Usage().Delegated, summed overpool.Descendantsfor 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
Sessionvalue logs the no-windowWARNat 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.Closedoes not wait for pool children; a parked child stays parked acrossClose. (Source:docs/thread-operations.md§5;thread/pool/pool.go:629Close godoc) - Cascade deletes yourself. Delete
Descendantsin 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
Asyncwrap inside a session turn. Called from a plainGenerate, the tool ignorespool.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 throughs.Sendinstead. (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)
See also
Section titled “See also”- Delegate to a subagent: the core’s
weft.Subagent, which the pool builds on - Approvals in sessions
- Operate sessions in production
- The session log format
- Package thread/pool on pkg.go.dev
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