Calls and session events over HTTP
motokoHandler(runtime, options), of @chia1104/motoko-node/http, serves the
call protocol as a Fetch handler,
(request: Request, context) => Promise<Response>. It uses nothing of Node, so it mounts in any
runtime and framework that speaks Request and Response, such as Hono on Node, Bun or Deno, or a
Next.js route handler, and in Node's http through nodeListener. Its two routes are under
basePath:
| Route | Request | Answer |
|---|---|---|
POST {basePath}/call | { method, params } as application/json | { result } or { error: CallError } |
GET {basePath}/sessions/:sessionId/events | the cursor to resume after: Last-Event-ID or ?from= | the session's wire events, as SSE |
A browser calls them with @chia1104/motoko-client's httpTransport, the same client
that talks to a Durable Object over its socket. It reads a follow's stream with fetch rather than
EventSource, so a follow sends the app's headers, such as Authorization, and it reconnects with
Last-Event-ID set to the client's cursor.
Calls
The handler parses a call's body with wire's callSchemas and runs it with core's runCall, or
with the app's override of its method (see The app's own handling of a call).
A call that fails is answered with its CallError and this status, which statusOf(code) answers too:
code | Status |
|---|---|
invalid_request | 400 |
invalid_cursor | 400 |
forbidden | 403 |
session_not_found | 404 |
session_busy | 409 |
session_owned | 409 |
approval_not_pending | 409 |
reply_not_pending | 409 |
internal | 500 |
instance_closed | 503 |
lease_held | 503 |
Four refusals of the handler's own also carry invalid_request. A path that is not a route is 404.
The wrong method is 405, with Allow. A call whose body is not application/json is 415, which
means a cross-site form cannot post a call without a CORS preflight. A call whose body is longer
than maxBodyBytes (default 1 MiB) is 413: the handler refuses a longer Content-Length before
reading any of it, and a body sent without one once it streams past the cap, then cancels the rest
unread. An error that is not one of the runtime's, such as a throw in resolve, goes to onError.
Its request is answered internal with the message Internal error, so no detail of it reaches the
client.
Following a session
GET .../events answers text/event-stream. It sends the session's events after the cursor, then
each new event as it comes. Each event is one message without an event name, so EventSource
delivers it to onmessage:
id: 1.0.9.f0421efc541e40d7.1
data: {"sessionId":"1","cursor":"1.0.9.f0421efc541e40d7.1","event":{"type":"run:start"}}
data is wire's followedEventSchema, and id is the cursor right after the event. So the
browser's lastEventId is always the cursor of the last event the client received. The stream
carries two other frames:
event: ended, withdataasfollowEndedSchema({ sessionId, error }), when the server stops following the session: it was deleted (session_not_found), or it cannot be read. The stream closes after it. Close the EventSource onended. Otherwise the browser reconnects, and the reconnect is answered 404.: heartbeat, a comment line everyheartbeatMs(default 15 000), so a proxy keeps a quiet stream open. EventSource ignores comments.heartbeatMsis from 1 to 2 147 483 647, the delayssetIntervalkeeps;motokoHandlerthrows aTypeErrorfor another, which would send a heartbeat about every millisecond.
A stream that closes without ended means that the instance closed: the server shut down, or lost
the instance's lease. EventSource reconnects with Last-Event-ID, and whatever serves the instance
then resumes the client after its last event.
The cursor comes from the Last-Event-ID header, which EventSource sends when it reconnects, or from
the from query parameter, which a client sets for its first connection, since EventSource cannot set
headers. When a request has both, Last-Event-ID wins: EventSource reconnects to the URL it opened, so
its from is older. With neither, the stream starts at the session's start. Resuming follows core's
cursor rules: exact while the cursor's run is in this process's log, and from
committed state anywhere else.
Before the stream starts, the handler answers these with a call error and its status: a cursor that
is not one of the session's (400 invalid_cursor), a session that does not exist (404), and an
instance this process cannot open (503 lease_held). EventSource does not reconnect after a
refusal. A delegate's child session exists while its parent does, so it is followed as any session
is, though listSessions leaves it out.
The body is read only as fast as the client takes it. When the client goes away (request.signal
aborts, or the body is cancelled), the handler stops the session's reader, so the instance closes
once idle (closeIdleAfterMs).
Who may do what
Two of the app's functions decide, as on the Cloudflare socket:
resolve(request, context)authenticates. It answers the instance the request is for,{ agent, name }, or aResponseto refuse, such as a 401, which is sent as it is before anything runs. Its answer may carry more of the app's fields, such as the signed-in user, andauthorizeandsessionOptionsget all of it astarget.contextis whatever the app called the handler with.authorize(request, call, target)decides each request thatresolvelet through: every call, and every follow.callis anHttpCall, one of wire'sCalls or a follow,{ method: "follow", params: { sessionId, from? } }, whichmethodtells apart. Any answer buttrueis 403forbidden, and nothing runs. Withoutauthorize, the handler allows every call. To make a caller read-only, refuse each call whosecallSchemas[call.method].writesis true. A follow writes nothing.
An app whose own middleware already signed the caller in hands that to the handler as its second
argument, so resolve reads it instead of the request again. The handler's type follows resolve's:
const handler = motokoHandler(runtime, {
basePath: "/motoko",
resolve: (_request, { user }: { readonly user: User }) => ({ agent: assistant, name: user.id, user }),
});
// Hono, behind the app's sign-in middleware:
app.all("/motoko/*", requireUser, (c) => handler(c.req.raw, { user: c.get("user") }));Without a second argument, context is undefined and the handler takes the request alone, as
nodeListener calls it. A forwarded request reaches the home as a request: the home's route builds
its own context from it, as for any other request, and its resolve runs again.
What a session runs with is the server's to choose as well: a createSession call carries only its
request ID. sessionOptions(target) answers the options of each session createSession makes, as
core's createSession takes them without requestId (model, thinkingLevel, maxTurns, tools,
requiresApproval, metadata), such as a model by the user's plan, or as its metadata the project
the request's route names. It is asked for each createSession, a retry's too, whose first session
stands as it was made. A throw is answered internal, goes to
onError, and makes no session. Without it, a session runs with the agent's defaults.
CORS is the app's: answer preflight requests before the handler, which answers OPTIONS with 405.
The app's own handling of a call
calls takes over some calls, by method, for an app whose services do more around one, such as filing
each new session in its own tables, or refusing what its own rules forbid. Each override gets the
call's params as the handler parsed them, once authorize let the call through, and { target, request, run }. run(params?) runs the call on the instance as the handler would have, with other params if it
is given them. What the override answers is the call's result, typed by the method:
const handler = motokoHandler(runtime, {
basePath: "/motoko",
resolve: (_request, { user }: { readonly user: User }) => ({ agent: assistant, name: user.id, user }),
calls: {
// File each new chat under the user's project, in the app's own table.
createSession: async (_params, { target, run }) => {
const session = await run();
await chats.insert({ sessionId: session.id, userId: target.user.id, projectId: target.user.projectId });
return session;
},
// Refused as the runtime refuses a call: 400 `invalid_request`.
deleteSession: async (params, { run }) => {
if (await chats.isArchived(params.sessionId)) throw new InvalidRequestError("Archived chats are kept");
return run();
},
},
});An override that does not call run answers by itself, and nothing runs on the instance. A rejection
is answered as one of the call's: one of core's errors with its code (InvalidRequestError from
@chia1104/motoko-core answers invalid_request), anything else internal, through onError. In a
cluster, a call whose run finds its instance held by another node is forwarded there, and the
override runs again on that node, so what it does before run must be safe to do twice.
The app's own routes
An app that serves Motoko from controllers of its own, with its own paths, DTOs and services, uses
what the handler is made of. Core's runCall runs a call and callErrorOf reads what it rejects
with; statusOf(code) is the status the handler answers that with; and
sessionEventStream(instance, sessionId, options) is a follow's answer, the text/event-stream
Response above, with its heartbeat, its ended frame and its reader stopped once signal aborts.
from is the cursor as the client sent it, Last-Event-ID or a query parameter. Before the stream
starts, it rejects with a TypeError for a heartbeatMs the handler would refuse, such as NaN from
an unset variable. It rejects with core's InvalidCursorError for a cursor that is not the session's,
SessionNotFoundError for a session the instance does not hold, and what opening the instance
rejects with, such as LeaseHeldError, each answered by its code:
import { callErrorOf, runCall } from "@chia1104/motoko-core";
import { sessionEventStream, statusOf } from "@chia1104/motoko-node/http";
import { callSchemas } from "@chia1104/motoko-wire";
/** The runtime's errors as the client reads a call's; any other is the app's own. */
function refusal(error: unknown): Response {
const known = callErrorOf(error);
if (known === undefined) throw error;
return Response.json({ error: known }, { status: statusOf(known.code) });
}
// Hono: the app's controller of a chat's messages, and of its events. The body is the protocol's, `{ method, params }`.
app.post("/api/chats/:id/messages", requireUser, async (c) => {
const { params } = await c.req.json<{ params: unknown }>();
const input = callSchemas.submit.params.safeParse(params);
if (!input.success) return c.json({ error: { code: "invalid_request", message: input.error.message } }, 400);
// The app's services go here, around the call.
const instance = runtime.get(assistant, c.get("user").id);
return runCall(instance, { method: "submit", params: input.data }).then((result) => c.json({ result }), refusal);
});
app.get("/api/chats/:id/events", requireUser, (c) =>
sessionEventStream(runtime.get(assistant, c.get("user").id), c.req.param("id"), {
from: c.req.header("last-event-id") ?? c.req.query("from"),
signal: c.req.raw.signal,
}).catch(refusal),
);The client's httpTransport sends each call and follow to the app's paths with its paths option,
and reads the answers as the handler's: a call's { result } or { error }, and a follow's stream.
On a framework of Node's own req and res, such as Express, nodeListener writes the Response:
nodeListener((request) => sessionEventStream(instance, id, { from, signal: request.signal }))(req, res).
Forwarding is the handler's: an app's own route answers an instance held by another node 503
lease_held.
Node's http
nodeListener(handler) is a request listener for http.createServer or https.createServer. It
turns each IncomingMessage into a Request whose body streams from the socket and whose signal
aborts when the client disconnects. It writes each Response with Node's pipeline, which reads the
body only as the socket drains, and cancels the body if the client goes away first. A handler that
rejects is answered 500, and the error goes to onError. motokoHandler answers its own errors.
A follow does not end on its own, so server.close() alone waits for it forever. Call
server.closeAllConnections() too, as the example does: each client then reconnects to the next
process after its last cursor.