App extensions
extensionsFor(scope) gives an instance the app's own pi-durable extensions: tools, prompt sections,
hooks, wraps and tasks that use the app's resources, which an agent definition, importable by a
client, cannot hold. It may be async. The runtime calls it each time the instance opens, before the
instance's Harness opens, so work the instance resumes runs with the extensions it ran with. A throw
or rejection fails the open: the call that opened the instance rejects with that error, nothing of
the instance runs, and a call waiting at the gate keeps waiting for a later open.
import { createToolSearchExtension } from "@earendil-works/pi-durable/tool-search";
const runtime = createAgentRuntime({
// ...
extensionsFor: (scope) => [
{ extension: createToolSearchExtension(), tier: () => "read" },
{ extension: mcpTools(scope), tier: (name) => (name.startsWith("mcp_github_") ? "network" : undefined) },
{ extension: traces(scope), agents: ["notes", "researcher"] },
],
});- Tiers.
tier(toolName)gives each of the extension's tools its tier, which the agent's policy and a session's rule judge as they judge the agent's own tools;tool:startandapproval:requestcarry it. A tool it gives none isunknown, and every call of it waits for approval: no policy or rule lets it run without a decision, and a rule cannot nameunknown. - Selection. Every extension is installed in the instance's registry. A session selects the
extensions whose
agentsname its agent's kind, in the orderextensionsForlists them, then its agent's own, so the approval gate runs last and judges the arguments the call runs with:beforeToolhooks, prompt sections andafterToolhooks run in selection order, eachbeforeToolseeing the arguments the one before it returned. Leavingagentsout names the instance's own agent alone, so a delegate's sub-agent runs an app extension only whenagentsnames its kind. A hook meant for every session, such as tracing, names the sub-agents' kinds too; a sub-agent of the instance's own kind runs what a top-level session runs. - Tools. A session's
toolschoose among its agent's own tools; the app's stay on. To give sessions other app tools, run them as another agent. A call of an app tool that parks on its own work (itsexecutereturns{ sleep }) is recorded inruntime.callsbefore it parks, so its sleep raises no question andapprove()refuses it, as a deferred call's does. - Hooks. An app's
beforeToolhook may watch a call, give it otherargumentsorblockit. It cannot make the call wait: only the gate parks a call before it runs, so a hook'ssleepends the call as blocked, with an error saying an app hook cannot make a call wait, and nothing asks about it. A hook that needs something awaits it. pi-durable runs the whole chain again at every wake, registry change and decision, so the gate, which runs after every app hook, memoizes the arguments it sees when it first parks a call: an approved call runs with those, through a decision and a restart, however a hook rewrites it later (with the time, say), or if it gives none. A call that never parks runs with what the chain gives it. A gated call is asked about with them (approval:request.args, see "Durable approval"), and one approved before it reached the gate, asked about with the model's arguments, ends blocked when a hook rewrites them. - Names. The open fails with a
TypeErrorfor an extension namedruntime:…or like another, a tool named like an agent's (the instance's agent's or a sub-agent's its delegates reach) or like another extension's, or a wrap of an agent's tool. pi-durable runs the last extension that provides or wraps a tool of a name, so any of those would run something in an agent's tool's place, past its ports. - Stable names. While a session may still have work of an extension, a call waiting at the gate
or a task its hook asked for, keep giving that extension, its tools and its tasks under the same
names: register a tool whose backend is down, and fail in its
execute. When the instance opens without it, a call waiting at the gate for its tool ends withtool_unavailable, and a task whose definition is gone is reported toonReportastask_blocked, with its session andtaskKind. It stays blocked, the session busy, until the extension is back or the session is aborted. - Refreshing.
instance.refreshExtensions()callsextensionsForagain and puts what it lists in place while the instance stays open, for an app whose tools change, such as an MCP server that connects. An extension of a name already installed replaces the installed one, and a new one is added: the next model request offers their tools, also in a run already under way, andtool_searchfinds their deferred ones. One it no longer lists is no longer selected but stays installed until the instance closes, so a task its hook asked for runs to its end. A call waiting at the gate for a tool the refresh drops ends withtool_unavailable(anerrorwhose message saysTool … is not available): at once when the refresh installs any extension, as pi-durable then asks every waiting call again, else when its decision comes. A call of it that parked on its own work ends so too, when it wakes. Top-level sessions follow the refresh; a delegate's child session keeps the selection it stored when it was made, so a refresh adds nothing to it. A refresh is refused, and changes nothing, for what an open is refused for: a throw ofextensionsFor, the names above, and pi-durable's own errors, such as two tasks of one name. For pi-durable's, an extension the refresh no longer lists counts too, as it is still installed. Refreshes take effect one at a time, in call order. One called while the instance opens waits for the open; one called while it is not open does nothing, as its next open callsextensionsForanyway. afterRun. A run whose session selects anafterRunhook answers, and itsrun:endgoes out, before the tasks the hook asks for run. Until they end the session is busy:whenBusy: "reject"throwsSessionBusyError, and an input that queues starts once they end. The stream says so:wrapup:startafter the run'srun:end, frompi.live.run.afterRun, which pi-durable sets in the commit that stores the answer, andwrapup:endonce the tasks end, before the next run'srun:start; the view'swrappingUpistruein between (see wire). A hook that asks for no task still sends a short wrap-up. A restart or a resume from any cursor shows the wrap-up still going on. An agent with noafterRunhook sends none of these events to a reader from the session's start; a reader resumed from a cursor may get onewrapup:end, since it may hold a wrap-up that is over.- Nested calls. A call a tool makes through pi-durable's
executeTool(), such as a code mode script's, passes the gate too, and is asked about and decided under the call that made it (see "Durable approval").
A session whose tools an earlier Motoko stored, as pi-durable's list of exactly those tools, runs
none of the app's until configure({ tools }) sets them again.
Input metadata
submit({ metadata }) stores a JSON object on the input's entry, as it is, for the app's hooks: what
the app works out for the turn when the input arrives, such as drafts, memory or the time. A hook
reads the inputs of the run going on with runInputs, in entry order, and finds each one's user
message in the request with locateInputs:
runInputs(api: HookApi, context: Context): Promise<readonly RunInput[]> // [] with no run going
interface RunInput { entryId: number; at: number; steer: boolean; metadata?: JsonObject }
locateInputs(messages: readonly Message[], inputs: readonly RunInput[]): readonly LocatedInput[]
interface LocatedInput extends RunInput { index: number | undefined }const volatile = defineExtension({
name: "volatile",
hooks: [
hook(GenerationTask, {
async beforeRequest({ messages }, api, context) {
const next = [...messages];
// From the last, so each insert leaves the places before it as they are.
for (const { index, metadata } of locateInputs(messages, await runInputs(api, context)).toReversed()) {
if (index !== undefined && metadata !== undefined) next.splice(index + 1, 0, contextMessage(metadata));
}
return { messages: next };
},
}),
],
});- Where.
atis the timestamp of the input's user message. A boundary gives the inputs it places one time, so inputs in a row may share it.locateInputsgives each input theindexof its user message inmessages: the user message of its time, matched from the end, as the run's inputs are the newest user messages, so an earlier run's of the same time is not taken. Inputs that share a time take that time's messages in entry order.indexisundefinedwhenmessagesdoes not hold the message: compaction summarized it, or an earlier hook dropped it. The inputs come back in the order given.steeris theuserevent's: the input joined the run after one of its tool rounds. - Which. The run's inputs start at pi-durable's
run.first; a continue's are those of the failed run it carries on, then its own. - Durable. The metadata is committed with its input, so every request of the run, and a run resumed after a restart, reads the same. A hook that puts it in each request puts it in the same place, and the provider's prefix cache holds. Nothing the hook adds is stored, and the stream shows no metadata.
- Cache.
runInputsholds only the current run's inputs. When the next run starts, the context a hook put after an earlier run's input leaves the request, so the provider's prefix cache breaks from the previous run's input onward. An app that needs its context to stay across runs puts it in the input's own content instead. - When. An input that waits in the queue carries the metadata of its
submit, not of the moment its run starts; a steer carries its own. - Refused.
metadatathat is not a JSON object (finite numbers, plain objects, noundefined), or that comes withreplyTo, rejects withInvalidRequestErrorand admits nothing.