Skip to Content
Motoko

Models and ports per caller

A multi-user server must never let one user's keys or capabilities serve another. A run is durable: it can be carried on after a restart, when no request and no caller object exist any more. So what decides credentials and ports is resolved from durable identity only, the instance's scope and the session, never from a request. As in the Cloudflare Agents SDK, an instance is its caller's own:

The rule: the scope is the credential boundary. Give each caller their own instance (runtime.get(agent, userId), or a name the app derives from the caller and nothing a client can choose), resolve modelsFor from scope alone and portsFor from scope and sessionId, and never route one caller's request to another caller's instance. Within an instance every session shares its models; portsFor may narrow per session, and a session's own tool selection (below) takes a tool away from it altogether. Give each caller's Models an authContext that exposes no environment, or a provider falls back to the server's own key for a caller who has none.

import type { AuthContext, Credential, CredentialStore } from "@earendil-works/pi-ai";
import { createModels } from "@earendil-works/pi-ai/models";
import { anthropicProvider } from "@earendil-works/pi-ai/providers/anthropic";
import * as z from "zod";

import { createAgentRuntime, defineAgent, defineTool } from "@chia1104/motoko-core";
import type { AgentHost, ToolContext } from "@chia1104/motoko-core";

// A host whose storage outlives an instance, such as processHost of a SQLite or Postgres store.
declare const host: AgentHost;

// ─── The app's own tables (a database in a real server) ───────────────────────

const apiKeys = new Map<string, string>(); // user id → that user's Anthropic key
const webGrants = new Set<string>(); // "<user>/<session>" pairs allowed to search the web

// ─── A definition: no ports, no credentials ───────────────────────────────────

interface AssistantPorts {
  readonly user: string;
  /** Present only in sessions the user granted web search. */
  readonly web?: { search(query: string): Promise<string> };
}

const webSearch = defineTool({
  name: "web_search",
  description: "Search the web",
  tier: "read",
  replay: "safe",
  parameters: z.object({ query: z.string() }),
  async execute({ query }, { ports }: ToolContext<AssistantPorts>) {
    if (ports.web === undefined) return { text: "Web search is not enabled in this conversation." };
    return { text: await ports.web.search(query) };
  },
});

const assistant = defineAgent<AssistantPorts>({
  kind: "assistant",
  instructions: "You are a helpful assistant.",
  tools: [webSearch],
  model: { provider: "anthropic", modelId: "claude-sonnet-5" },
});

// ─── One user's model access ──────────────────────────────────────────────────

/** The user's key, read from the app's table at every model request. */
function userCredentials(user: string): CredentialStore {
  const read = async (): Promise<Credential | undefined> => {
    const key = apiKeys.get(user);
    return key === undefined ? undefined : { type: "api_key", key };
  };
  return {
    read,
    list: async () => (apiKeys.has(user) ? [{ providerId: "anthropic", type: "api_key" }] : []),
    async modify(_providerId, change) {
      const next = await change(await read());
      if (next?.type === "api_key" && next.key !== undefined) apiKeys.set(user, next.key);
      return next ?? (await read());
    },
    delete: async () => void apiKeys.delete(user),
  };
}

// No environment variables or files: a user without a key never falls back to the server's own.
const noAmbientAuth: AuthContext = { env: async () => undefined, fileExists: async () => false };

// ─── The runtime: one instance per user, so the scope is the credential boundary ─

const runtime = createAgentRuntime({
  agents: [assistant],
  host,
  // Resolved when the user's instance opens (also after a restart) and before each submit.
  modelsFor: (scope) => {
    const models = createModels({ credentials: userCredentials(scope.name), authContext: noAmbientAuth });
    models.setProvider(anthropicProvider());
    return models;
  },
  // Resolved for every tool call, right before it runs: a grant withdrawn reaches the next call.
  portsFor: async ({ scope, sessionId }) => ({
    user: scope.name,
    ...(webGrants.has(`${scope.name}/${sessionId}`) && {
      web: { search: async (query: string) => `Results for ${query}` },
    }),
  }),
  // A user who went quiet gives back their Harness and lease after ten minutes.
  closeIdleAfterMs: 10 * 60_000,
});

/** A request handler: the authenticated user reaches their own instance and nobody else's. */
export async function handleMessage(userId: string, sessionId: string, text: string, requestId: string) {
  const session = runtime.get(assistant, userId).session(sessionId);
  return session.submit({ text, requestId });
}

// The user adds a key, or grants web search to a session: nothing to reopen, the next request or
// call reads the tables.
apiKeys.set("user-42", "sk-ant-...");
webGrants.add("user-42/1");

console.log("open instances:", runtime.inspect().open);

(examples/per-caller.ts, typechecked with the package.)

modelsFor(scope) returns what models would be for that one instance, a Models or pi's function returning one, and may be async (keys usually live in a database). pi-durable reads HarnessOptions.models synchronously at every model request, so the runtime does the async lookup beforehand and hands pi-durable the newest result:

  • It resolves when the instance opens, before anything runs, so a run resumed after a restart or an idle close runs on the credentials of now; again before every submit, continue, approve, compact and resume; and on instance.refreshModels().
  • A key the user adds or removes while the instance is open: build the Models with a pi-ai CredentialStore that reads the app's table (as the example does), and there is nothing to do: pi-ai resolves credentials at every request, so the next request uses the new key, or, once it is gone, fails with the provider's "not configured" error and ends its run with run:end code: "no_credentials". A change that needs another Models (a provider registered only when the user has a key) reaches the next submit, approve or resume on its own; call refreshModels() to reach a run already going at its next request.
  • A throw or rejection is reported as models_failed and held: every model request of the instance then fails with ModelsUnavailableError, which ends the run it serves (run:end with reason: "error", code: "faulted" and the error's message, which names no cause; pi-durable reports the faulted generation too). Reads, sessions and approvals keep working, and the next resolution that succeeds restores model access. The newest resolution decides, failed or not, so stale credentials are never used after a failed lookup.
  • A run resumed after a restart whose credentials can no longer be resolved (the user deleted their keys, or the lookup fails) ends that way: with an error the client sees, its committed state kept, and nothing sent on anyone else's credentials. A later input runs once the lookup succeeds.

A key the app holds for a while. The app keeps the caller's key where its CredentialStore reads it, such as in server memory for a while. A run that finds none, after the key expired or the server restarted, ends no_credentials with its committed state kept, so the client can tell it from other failures and ask the user for the key. Once the app holds the key again, session.continue() carries the run on and answers the user's message.

portsFor({ scope, sessionId, toolCallId, toolName, signal }) returns one tool call's ports, and may be async. It runs per call, right before the call executes: after its approval, if it needed one, and again for a replay-safe call a restart reruns. Per call rather than per run because it is the one point every execution passes through, live or resumed, and because a call can wait for days for an approval: a grant withdrawn meanwhile, or between two runs, is seen by the next call without reopening anything. A lookup per call is the cost; an app that needs it cheaper caches by scope and session itself. A throw or rejection fails that call alone, before it runs: the model reads Tool `<name>` could not run: the app could not provide what it needs for this call (PortsUnavailableError, without the cause), the run goes on, and the cause is reported as ports_failed with the session and call.