Skip to Content
Motoko

The runtime

createAgentRuntime({
  agents, host, defaultModel?, onReport?,
  models | modelsFor,      // exactly one: one Models for every instance, or one per instance
  ports | portsFor,        // exactly one: one ports object, or ports per tool call
  closeIdleAfterMs?,       // close an instance idle this long; default never
  nestedApprovalTimeoutMs?, // how long a nested call waits for a decision; default an hour
  settings?,               // pi-durable's settings; the runtime sets `extensions`
  extensionsFor?,          // (scope) => AppExtension[]: the app's pi-durable extensions for an instance; default none
  telemetryFor?,           // (scope) => TelemetryContext: an instance's pi-telemetry; default pi's, which records nothing
  envFor?,                 // (scope) => pi-durable's env: builds an instance's ExecutionEnv; default none
  deliverReply?,           // (reply, signal) => Promise<void>: how an ask's answer reaches its asker
}): AgentRuntime
runtime.get(agent, name): AgentInstance       // lazily opened, one per scope per runtime
runtime.recover({ concurrency? })             // open the scopes the host lists as unfinished
runtime.inspect(): AgentRuntimeInspection     // what the runtime holds: { open, instances }
runtime.close()
instance.state                                // dormant · opening · open · closing · closed · lease_lost · failed
instance.open() · createSession({ model?, thinkingLevel?, maxTurns?, tools?, requiresApproval?, metadata?, requestId? })
instance.listSessions() · session(id)          // [{ id, createdAt, updatedAt, title?, metadata? }], oldest first
instance.resume() · refreshModels() · refreshExtensions() · close()
session.submit({ text, requestId, whenBusy?, replyTo?, metadata? })  // idempotent on requestId; replyTo makes an ask
session.continue({ requestId })                 // carries on a run that ended without an answer; idempotent
session.withdraw(submissionId)                  // { outcome: "withdrawn" | "already_placed" | "settled" }
session.events({ from?, signal? })              // AsyncIterable<{ cursor, event }>
session.approve([{ toolCallId, approved, comment? }])  // one commit: all of the batch, or none
session.reply({ toolCallId, token, text, isError? })  // { outcome: "applied" | "already_replied" }
session.abort()
session.compact({ instructions? })              // resolves once admitted; the stream shows it go
session.configure({ model?, thinkingLevel?, maxTurns?, tools?, requiresApproval?, metadata? })  // one commit; null puts back the agent's
session.settings()                              // { model, thinkingLevel, maxTurns?, tools, requiresApproval?, metadata? }
session.rename(title | null)                    // its title; null puts back its first message's
session.delete()                                // with its child sessions

A session is a pi-durable conversation. An input to a busy session waits, as whenBusy says: queue (the default, pi-durable's follow-up) waits for the run's answer and starts the next run; steer joins the run going on at the end of its current tool round, so the model reads it before its next reply; reject throws SessionBusyError instead. With no run going, each starts a run. Its stream lists what waits as queue events and marks a steer's user event (see wire). withdraw takes back an input still waiting, by the submissionId its submit gave; it rejects with InvalidRequestError for a submission the session does not hold, or an ask's. abort drops every input waiting, as pi-durable's abort does. A steer is stored as a motoko.steer entry rather than pi.user, whichever run it lands in, so the stream can tell an input that joined a run from one a failed run handed to the next. Any other input with metadata is stored as motoko.input (see Input metadata). pi-durable's steeringMode and followUpMode (in settings) say whether a boundary takes the first waiting steer or follow-up, or all of them. models is pi-durable's HarnessOptions["models"] (a Models, or a function returning the current one), passed as is. The static and the resolved forms are told apart by their option's name, never by typeof: a ports object may itself be callable, and models may be pi's function.

onReport receives an InstanceReport for failures that fail no call of the app's:

type InstanceReport =
  | { source: "pi"; scope: StorageScope; report: Report }   // pi-durable's Report, every field as pi gave it
  | { source: "runtime"; scope: StorageScope; error: unknown;
      kind: "listener_error" | "close_failed" | "lease_release_failed" | "arm_failed" | "models_failed"
        | "reopen_failed" | "erase_failed" }
  | { source: "runtime"; scope: StorageScope; error: unknown;
      kind: "ports_failed"; sessionId: string; toolCallId: string; toolName: string }
  | { source: "runtime"; scope: StorageScope;
      kind: "task_blocked"; sessionId: string; taskKind: string;
      reason: "missing_task" | "task_too_old" | "migration_failed" }
  | { source: "runtime"; scope: StorageScope; error: unknown;
      kind: "reply_failed"; sessionId: string; requestId: string;
      to: { scope, sessionId, toolCallId };  // the reply address, without its token
      attempt: number; gaveUp: boolean };

reply_failed is an ask whose reply deliverReply failed to deliver: it is tried again unless gaveUp. It is also reported, with gaveUp and attempt: 0, for an ask whose request was first submitted without a reply address, whose run's answer therefore reaches no one.

task_blocked is a task of the session sessionId that this open cannot run: no extension provides a definition of taskKind (missing_task), or the one that does is older than the task (task_too_old) or cannot migrate its state (migration_failed, which pi-durable reports too, with the error). It keeps its session busy until an open provides the definition again or the session is aborted (see App extensions). Each open reports a task once: one already blocked or sleeping when the instance opens, as it opens, and one that becomes blocked while it is open, then.

telemetryFor(scope) gives an instance its pi-telemetry TelemetryContext, which the runtime hands to pi-durable's HarnessOptions.telemetry each time the instance opens. It then receives pi-durable's content-free spans and metrics (pi.durable.submit, pi.durable.phase, ...) for that instance alone, so an app can tag them with the scope or send each caller's to its own exporter. A throw fails the open. The app imports pi-telemetry itself; core depends on none of it.

envFor(scope) gives an instance its execution environment: pi-durable's HarnessOptions.env, a function that builds the ExecutionEnv a tool call reads as api.env. The runtime hands it to the Harness each time the instance opens, so an app's shell tool, such as pi-durable's createBashTool(), runs in the working directory the app keeps for that scope:

envFor: (scope) => () => new NodeExecutionEnv({ cwd: join(workspaces, scope.kind, scope.name) }),

NodeExecutionEnv is pi-durable's, from @earendil-works/pi-durable/env/node; a sandbox supplies its own. A throw fails the open. Without envFor a call has no environment, and a tool that needs one, such as bash, fails it.