Skip to Content
Motoko

Deferred tools

A deferred tool's call starts work elsewhere, typically another instance's run, and waits for its reply. It holds no process while it waits: it parks, so an idle close, a restart or an evicted Durable Object loses nothing.

import { defineDeferredTool } from "@chia1104/motoko-core";
import type { DeferredContext } from "@chia1104/motoko-core";

const askTeammate = defineDeferredTool({
  name: "ask_teammate",
  description: "Ask a teammate's agent a question; it answers when its own run ends.",
  tier: "read",
  parameters: z.object({ teammate: z.string(), sessionId: z.string(), question: z.string() }),
  timeoutMs: 60 * 60_000, // an hour; default 24 hours
  async start({ teammate, sessionId, question }, { ports, requestId, replyTo }: DeferredContext<TeamPorts>) {
    // An ask: the teammate's instance answers to `replyTo` when the run this starts ends.
    await ports.team.submit(teammate, sessionId, { text: question, requestId, replyTo });
  },
});

The call runs in this order:

  1. It passes the approval gate like any call: a gated tier asks before start ever runs.
  2. It memoizes a token and its deadline, and records both in runtime.calls in one commit. From then on its sleep is its own, not the gate's: it raises no question, and approve() refuses it.
  3. It resolves its ports, as an app tool's call does, and runs start with a DeferredContext: ports, signal, scope, sessionId, toolCallId, requestId and replyTo. replyTo is the reply address, { scope, sessionId, toolCallId, token }. A start that throws ends the call with its message as an error result.
  4. It parks until a reply arrives or the deadline passes. The stream shows reply:wait with the deadline, and the view shows the call awaiting_reply until it runs again and ends.
  5. Woken, it returns the reply's text as its result, an error result if the reply says isError, or No reply came in time. once the deadline passed.

start may run again: a crash before the park reruns the call, with the same requestId and the same reply address. So the work it starts must be idempotent by requestId, as submit is. The requestId is made of the scope, the session and the call, so it is unique across instances. cancel(args, context), when the tool has one, runs with the same context when the call is stopped while it waits (its session is aborted), and may run more than once.

session.reply({ toolCallId, token, text, isError? }) answers the call. It reopens a closed instance, and takes a child session's call too, since a sub-agent may make a deferred call. In one commit it checks the token, in constant time, delivers the reply and records it. A reply may come before the park, while start still runs: it is kept, and the park wakes at once. A second reply, also after the call ended, is already_replied, so a delivery may be retried. Everything else is ReplyNotPendingError (reply_not_pending): a wrong token, a call with no reply record, one that ended without a reply, or passed its deadline. Nothing tells these apart, so a guess learns nothing.

Asks

An ask is a submission with replyTo: the asked instance delivers the answer of the run it starts to that address. submit refuses replyTo with InvalidRequestError (invalid_request) on a runtime without deliverReply, or with whenBusy: "reject" or "steer", since an ask always queues: its answer is the answer of a run of its own. It refuses an ask with metadata the same way. Its asker waits for that answer, so withdraw refuses an ask's submission the same way.

The asked side keeps a courier for each ask, a background task of the asked session:

  • submit creates the courier in one commit, and records it in the session's runtime.asks document by request ID. Then it submits, notifying the courier when the submission settles. A retry with the same request ID finds the courier and returns the first submission.
  • The courier submits the same ask itself, in the commit that parks it on the settlement. So a crash between the two commits of submit loses nothing: the courier makes the submission.
  • Once the run ends, the courier reads its answer as a delegate's call does (the last reply's text, or why there is none, such as aborted), and calls deliverReply({ to, text, isError }, signal).
  • deliverReply resolving means done: the reply was delivered, or refused for good. Map reply_not_pending and session_not_found to resolving. A rejection is reported as reply_failed, and the courier sleeps before it tries again: 1 second, doubling, at most 5 minutes. It gives up a day after its first try, with a last report.
  • Deleting the asked session aborts its courier, which sends nothing: the asker's deadline ends its call. Aborting the asker stops its call, not the asked run; the reply that comes later is refused, and the courier ends.

deliverReply is the app's way to reach the asker's home: session.reply of the same runtime, a client of the cluster (forwarding takes the call to the home), or a Durable Object's stub (asks between objects).

On this page