Skip to Content
Motoko

API

motokoClient(transport: MotokoTransport): MotokoClient  // one per transport, shared by every caller
webSocketTransport(socket: MotokoSocket): MotokoTransport  // one per socket
httpTransport({ baseUrl, fetch?, headers?, paths? }): MotokoTransport
interface MotokoSocket {                                 // AgentClient, useAgent's socket, or a WebSocket
  readyState: number; send(data: string): void;
  addEventListener(type: "open" | "close" | "message", listener: (event: Event) => void): void;
  removeEventListener(type: "open" | "close" | "message", listener: (event: Event) => void): void;
}
interface HttpTransportOptions {
  baseUrl: string;                                       // motokoHandler's basePath: "/motoko", or a full URL
  fetch?: (input: string, init: RequestInit) => Promise<Response>;  // default: the global fetch
  headers?: HttpHeaders | (() => HttpHeaders | Promise<HttpHeaders>);  // a function is asked for each request
  paths?: {                                              // below baseUrl, for the app's own routes
    call?(call: { method, params }): string;             // default: "/call"
    events?(sessionId: string): string;                  // default: "/sessions/:sessionId/events"
  };
}

client.follow(sessionId, listener: (state: MotokoSessionState) => void): () => void  // returns the unfollow
client.sessionState(sessionId): MotokoSessionState  // the same object until it changes
client.createSession({ requestId? }?): Promise<SessionInfo>  // requestId: a fresh one by default
client.startSession({ text, requestId? }): Promise<{ session, submissionId }>  // one requestId for both calls
client.listSessions(): Promise<SessionInfo[]>       // { id, createdAt, updatedAt, title?, metadata? }, oldest first
client.watchSessions(listener: (state: MotokoSessionsState) => void): () => void  // lists for its first watcher
client.sessionsState(): MotokoSessionsState        // the same object until it changes
client.submit(sessionId, { text, requestId, whenBusy?, replyTo? }): Promise<{ submissionId, title? }>  // whenBusy: queue · steer · reject
client.continue(sessionId, { requestId? }?): Promise<{ submissionId }>  // carries on a run; requestId: a fresh one by default
client.withdraw(sessionId, submissionId): Promise<{ outcome }>  // withdrawn · already_placed · settled
client.approve(sessionId, decisions: ApprovalDecision[]): Promise<ApprovalOutcome[]>
client.reply(sessionId, { toolCallId, token, text, isError? }): Promise<{ outcome }>  // applied · already_replied
client.abort(sessionId): Promise<void>
client.compact(sessionId, instructions?): Promise<void>  // view.compaction: running, or why it failed
client.renameSession(sessionId, title | null): Promise<SessionInfo>  // null puts back the first message's
client.deleteSession(sessionId): Promise<void>
client.close(): void                                // pending calls reject; the follows stop
interface MotokoSessionState {
  view: AgentSessionView;                           // motoko-wire's, folded with applyEvent
  cursor?: Cursor;                                  // right after the last event folded
  status: "connecting" | "live" | "ended";          // the follow's; the run's is view.status
  error?: MotokoError;                              // why it ended
}
interface MotokoSessionsState {
  sessions?: readonly SessionInfo[];                // oldest first; absent until a listing answers
  loading: boolean;                                 // a listing is under way
  error?: MotokoError;                              // why the last listing failed, until one answers
}
class MotokoError extends Error { code: MotokoErrorCode | "connection_closed" }
isBusy(view) · canContinue(view) · delegateOf(item)  // wire's, with the view's types: AgentSessionView, SessionViewItem, ...

// @chia1104/motoko-client/react
useMotokoSession(client: MotokoClient, sessionId: string): MotokoSessionState & {
  submit(text, { requestId?, whenBusy? }?): Promise<{ submissionId, title? }>  // requestId: a fresh one by default
  continue({ requestId? }?): Promise<{ submissionId }>  // carries on a run that ended without an answer
  withdraw(submissionId): Promise<{ outcome }>     // an input waiting in view.queued
  decide(decisions: ApprovalDecision[]): Promise<ApprovalOutcome[]>
  abort(): Promise<void>
  compact(instructions?): Promise<void>
}
useMotokoSessions(client: MotokoClient): MotokoSessionsState & {
  refresh(): Promise<void>                          // lists again
  create({ requestId? }?): Promise<SessionInfo>
  start(text, { requestId? }?): Promise<{ session, submissionId }>
  rename(sessionId, title | null): Promise<SessionInfo>
  remove(sessionId): Promise<void>
}

Every follower of a session shares one follow. Once the last one leaves, the client keeps the follow and its state for five seconds, then stops it. A follower who comes back meanwhile, as a remounted component or React's StrictMode does, picks the follow up where it is instead of replaying the session from its start. A follow the server ended is not kept. A listener that throws is reported as uncaught, as an EventTarget's listener is, and the others still hear the state. Each result is parsed with wire's callSchemas, so a call resolves with what its schema says or rejects. A call the server refuses rejects with a MotokoError whose code is the call error's (session_busy, session_owned, reply_not_pending, forbidden and the others of the call protocol). A call whose reply cannot come rejects with connection_closed: it was sent but not answered, so it may or may not have run, and submit or createSession with the same requestId again is safe, as is reply again. The client retries no call itself: when to try again, and whether to, is the app's. createSession sends a fresh requestId unless it is given one, so a forwarded call tried again never makes a second session; to retry it from the app, pick the ID before the first call:

const requestId = crypto.randomUUID();
const create = () => motoko.createSession({ requestId });
const session = await create().catch((error: unknown) => {
  if (error instanceof MotokoError && error.code === "connection_closed") return create();
  throw error;
});

A request ID is all createSession takes: what a session runs with stays the server's to choose, so no client can loosen the approval gate.

The session list

watchSessions keeps the instance's sessions for a sidebar, and useMotokoSessions reads them in React. The first watcher lists them, as does the first after all have left, so a remounted list shows the sessions it knew while it lists them again. listSessions, from anywhere, lists them again too. The client's own createSession, startSession, renameSession and deleteSession change the list as their calls answer, so nothing lists again after one. A created session takes its place oldest first, whatever order the creates answer in. The client's submit to a session with no title yet titles it with the title the server answers it with, whatever order its submits answer in. This holds while a listing sent before the call is under way: its answer may not show the call yet, so the client applies the call to it again. The answer or failure of a listing sent before the one shown is dropped. Another client's changes, such as another tab's, show at the next listing, and so do a name the server gave and each session's updatedAt: nothing pushes them. A listing that fails keeps the sessions known and sets error until one answers.

A session's title is the name renameSession gave it, or else the start of its first message; a session with neither has none, so a list shows something else for it, such as when it was made. renameSession refuses a title that is blank or longer than 100 characters on one line (invalid_request), and null puts back the first message's. The server may name sessions too (see core's Listing and naming sessions). metadata is the server's, as it filed the session; the list hands it back as it is.

startSession({ text }) is a new chat's first message: it creates the session, then submits text to it, with one requestId for both, since a session's submissions are keyed apart from the instance's sessions. After connection_closed at either step, starting again with the same requestId gets the session the first call made and its one submission:

function Sidebar({ client, open }: { readonly client: MotokoClient; readonly open: (id: string) => void }) {
  const { sessions, start } = useMotokoSessions(client);
  return (
    <>
      <ul>
        {sessions?.map(({ id, createdAt, title }) => (
          <li key={id}>{title ?? new Date(createdAt).toLocaleString()}</li>
        ))}
      </ul>
      <button onClick={() => void start("Hello").then(({ session }) => open(session.id))}>Say hello</button>
    </>
  );
}

submit with replyTo makes the submission an ask, and reply answers a deferred call (see core's Deferred tools). Both are for the app's server code, which delivers one instance's answer to another: a browser has no reply address to give, nor a token to reply with.

motokoClient keeps one client per transport, and webSocketTransport one transport per socket, so motokoClient(webSocketTransport(agent)) in a component's render is the same client every time. An httpTransport is a new one at each call: make it once, outside render.

On this page