@chia1104/motoko-cloudflare
Motoko in a Cloudflare Durable Object: an Agents SDK capability on the object's SQLite and alarm, serving its WebSockets.
Motoko in a Cloudflare Durable Object, as an Agents SDK capability. MotokoCapability runs one
instance, the one whose scope is the object ({ kind: agent.kind, name: <the object's name> }), on a
host made of the object's SQLite database (the store) and its alarm (the wake-up), through the
Lifecycle's job queue. It installs on an Agent or on a plain Durable Object with the Lifecycle,
beside the SDK's own capabilities: the scheduler, state and WebSockets share the one alarm with it,
and none overwrites another's.
Browsers reach the instance over the object's WebSockets, on the socket the Agents SDK's client
already opens. The capability serves Motoko's socket protocol there beside the app's own frames, and
@chia1104/motoko-client's webSocketTransport speaks it: its client follows a
session's wire events by cursor, folds them into a session view and makes the calls an app needs, and
its /react puts a hook on top. The same client runs over HTTP to a Node server, so the browser code
does not change with the host.
The Agents SDK and pi are peers: agents within one minor, >=0.34.0 <0.35.0 (each minor supports
one pi minor, and 0.34 supports pi ~1.6.0), and the @earendil-works/* packages at ~1.6.0.
pnpm add @chia1104/motoko-cloudflare @chia1104/motoko-core agents@~0.34.0 \
@earendil-works/pi-durable@~1.6.0 @earendil-works/pi-ai@~1.6.0 \
@earendil-works/chord@~1.6.0 @earendil-works/pi-schema@~1.6.0
# the browser's side
pnpm add @chia1104/motoko-clientThe object's class is SQLite-backed (new_sqlite_classes in its Wrangler migration) and addressed by
name (getByName, idFromName), since the name is half of its instance's scope.
Usage
The object, and the Worker that routes each user to their own:
// pi and the Agents SDK are the app's own dependencies: its models come from them directly.
import { createModels } from "@earendil-works/pi-ai/models";
import { Agent, routeAgentRequest } from "agents";
import { createAI } from "agents/models/pi-ai";
import type { AI } from "agents/models/pi-ai";
import * as z from "zod";
import { MotokoCapability } from "@chia1104/motoko-cloudflare";
import { defineAgent, defineTool } from "@chia1104/motoko-core";
import type { ToolContext } from "@chia1104/motoko-core";
// The Worker's bindings, from its Wrangler configuration.
interface Env extends Cloudflare.Env {
readonly AI: Ai;
readonly NOTES: DurableObjectNamespace<NotesAgent>;
}
// ─── The definition: no ports, no credentials. ────────────────────────────────
interface NotesPorts {
/** The object's own key-value storage, beside Motoko's tables. */
readonly notes: SyncKvStorage;
}
const readNote = defineTool({
name: "read_note",
description: "Read a note by its key",
tier: "read",
replay: "safe",
parameters: z.object({ key: z.string() }),
async execute({ key }, { ports }: ToolContext<NotesPorts>) {
return { text: ports.notes.get<string>(`note:${key}`) ?? "" };
},
});
const writeNote = defineTool({
name: "write_note",
description: "Write a note",
tier: "write",
parameters: z.object({ key: z.string(), text: z.string() }),
async execute({ key, text }, { ports }: ToolContext<NotesPorts>) {
ports.notes.put(`note:${key}`, text);
return { text: `Saved ${key}.` };
},
});
const notesAgent = defineAgent<NotesPorts>({
kind: "notes",
instructions: "You keep the user's notes. Ask before writing one.",
tools: [readNote, writeNote],
policy: { requiresApproval: ["write"] }, // write-tier calls wait for the user
});
// ─── One object per user: its instance's scope is { kind: "notes", name: <the object's name> }. ─
/** pi-ai model access over Workers AI and AI Gateway: the Worker holds no provider key. */
function modelsOf(ai: AI) {
const models = createModels();
models.setProvider(ai.provider);
return models;
}
export class NotesAgent extends Agent<Env> {
readonly #ai = createAI({ binding: this.env.AI });
readonly #model = this.#ai("@cf/deepseek-ai/deepseek-v4.1-flash-1017");
readonly motoko = new MotokoCapability<NotesPorts>({
agent: notesAgent,
models: modelsOf(this.#ai),
defaultModel: { provider: this.#model.provider, modelId: this.#model.id },
ports: { notes: this.ctx.storage.kv },
// Motoko's socket protocol on the agent's own WebSockets, beside the app's frames: no onMessage to write.
connections: this,
// Closes the instance once idle (no socket following a session), which also erases the sessions the user deleted.
closeIdleAfterMs: 60_000,
});
constructor(ctx: DurableObjectState, env: Env) {
super(ctx, env);
this.lifecycle.use(this.motoko);
}
// An RPC method of the app's, for its other Workers: the Agent starts its Lifecycle before each runs.
async ask(sessionId: string, text: string, requestId: string): Promise<string> {
const instance = await this.motoko.instance();
return (await instance.session(sessionId).submit({ text, requestId })).submissionId;
}
}
/** The signed-in user, by the app's own sign-in: a session cookie it verifies, say. Not Motoko's. */
declare function signedInUser(request: Request, env: Env): Promise<string | null>;
export default {
async fetch(request: Request, env: Env): Promise<Response> {
// Every connection to an object may make every call on its sessions, so the app lets each user reach their own
// object alone (`/agents/notes/<user>`), before the request reaches it.
const ownObjectOnly = async (incoming: Request, route: { readonly name: string }) => {
const user = await signedInUser(incoming, env);
if (user === null) return new Response("Unauthorized", { status: 401 });
if (route.name !== user) return new Response("Forbidden", { status: 403 });
return undefined;
};
const routed = await routeAgentRequest(request, env, {
onBeforeConnect: ownObjectOnly,
onBeforeRequest: ownObjectOnly,
});
return routed ?? new Response("Not found", { status: 404 });
},
};(examples/notes-agent.ts, typechecked with the package.)
The browser, with React:
// The browser side: the Agents SDK's socket to the user's NotesAgent, and Motoko's session over it.
import { useAgent } from "agents/react";
import { useState } from "react";
import { motokoClient, webSocketTransport } from "@chia1104/motoko-client";
import { useMotokoSession } from "@chia1104/motoko-client/react";
export function NotesSession({ user, sessionId }: { readonly user: string; readonly sessionId: string }) {
// The binding `NOTES` in kebab case, and the object named after the user: the routing Worker admits them alone.
const agent = useAgent({ agent: "notes", name: user });
// The socket's one client, the same at every render; over HTTP to a Node server it would be httpTransport's.
const motoko = motokoClient(webSocketTransport(agent));
// The session's view, folded from its events; after a reconnect it resumes from the last cursor it folded.
const { view, status, submit, decide } = useMotokoSession(motoko, sessionId);
const [draft, setDraft] = useState("");
return (
<section>
{status === "connecting" && <p>Connecting…</p>}
{status === "ended" && <p>This session is gone.</p>}
{view.items.map((item) => {
if (item.kind === "user" || item.kind === "assistant") {
return <p key={item.messageId}>{item.text}</p>;
}
if (item.kind !== "tool") return null;
const waiting = view.pendingApprovals.includes(item.toolCallId);
return (
<p key={item.toolCallId}>
{item.label}: {item.status}
{waiting && (
<>
<button onClick={() => void decide([{ toolCallId: item.toolCallId, approved: true }])}>Allow</button>
<button onClick={() => void decide([{ toolCallId: item.toolCallId, approved: false }])}>Deny</button>
</>
)}
</p>
);
})}
<form
onSubmit={(event) => {
event.preventDefault();
void submit(draft);
setDraft("");
}}
>
<input value={draft} onChange={(event) => setDraft(event.target.value)} />
</form>
</section>
);
}And without, over the SDK's AgentClient:
// Without React: the Agents SDK's AgentClient, and Motoko's client over it.
import { AgentClient } from "agents/client";
import { motokoClient, webSocketTransport } from "@chia1104/motoko-client";
import type { MotokoSessionState } from "@chia1104/motoko-client";
declare function render(state: MotokoSessionState): void;
const agent = new AgentClient({ agent: "notes", name: "ada", host: location.host });
// One client per socket: every caller of motokoClient(webSocketTransport(agent)) shares it.
const motoko = motokoClient(webSocketTransport(agent));
const { id } = await motoko.createSession();
const unfollow = motoko.follow(id, render);
await motoko.submit(id, { text: "Note that the milk is out.", requestId: crypto.randomUUID() });
// …and once the page is done with the session:
unfollow();(examples/browser/, typechecked with the DOM's globals by its own tsconfig.json.)