Skip to Content
Motoko

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:start and approval:request carry it. A tool it gives none is unknown, and every call of it waits for approval: no policy or rule lets it run without a decision, and a rule cannot name unknown.
  • Selection. Every extension is installed in the instance's registry. A session selects the extensions whose agents name its agent's kind, in the order extensionsFor lists them, then its agent's own, so the approval gate runs last and judges the arguments the call runs with: beforeTool hooks, prompt sections and afterTool hooks run in selection order, each beforeTool seeing the arguments the one before it returned. Leaving agents out names the instance's own agent alone, so a delegate's sub-agent runs an app extension only when agents names 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 tools choose 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 (its execute returns { sleep }) is recorded in runtime.calls before it parks, so its sleep raises no question and approve() refuses it, as a deferred call's does.
  • Hooks. An app's beforeTool hook may watch a call, give it other arguments or block it. It cannot make the call wait: only the gate parks a call before it runs, so a hook's sleep ends 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 TypeError for an extension named runtime:… 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 with tool_unavailable, and a task whose definition is gone is reported to onReport as task_blocked, with its session and taskKind. It stays blocked, the session busy, until the extension is back or the session is aborted.
  • Refreshing. instance.refreshExtensions() calls extensionsFor again 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, and tool_search finds 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 with tool_unavailable (an error whose message says Tool … 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 of extensionsFor, 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 calls extensionsFor anyway.
  • afterRun. A run whose session selects an afterRun hook answers, and its run:end goes out, before the tasks the hook asks for run. Until they end the session is busy: whenBusy: "reject" throws SessionBusyError, and an input that queues starts once they end. The stream says so: wrapup:start after the run's run:end, from pi.live.run.afterRun, which pi-durable sets in the commit that stores the answer, and wrapup:end once the tasks end, before the next run's run:start; the view's wrappingUp is true in 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 no afterRun hook sends none of these events to a reader from the session's start; a reader resumed from a cursor may get one wrapup: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. at is 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. locateInputs gives each input the index of its user message in messages: 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. index is undefined when messages does not hold the message: compaction summarized it, or an earlier hook dropped it. The inputs come back in the order given. steer is the user event'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. runInputs holds 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. metadata that is not a JSON object (finite numbers, plain objects, no undefined), or that comes with replyTo, rejects with InvalidRequestError and admits nothing.

On this page