OpenLegion · Docsllms.txt
Docs pages

Give your customers an assistant that works in your product

The Quickstart gives you an agent on /agent that answers one demo customer and calls one example tool. This guide takes the same files to an assistant your real customers use: signed in as themselves, each with their own workspace, working on their own data through your functions, and asking before it changes anything.

Every step edits a file npx openlegion init wrote. Keep npx openlegion dev running while you work: it pushes each change to test mode.

1. Who is signed in

openlegion/session.ts is a stand-in for your auth. Replace currentSession() with your own: the signed-in user, and the customer they belong to (an account, a team, an organization: whatever your product bills).

export async function currentSession(): Promise<Session | null> {
  const user = await getSignedInUser(); // your auth
  if (!user) return null; // the chat route answers 401
  return { user: user.id, customer: { id: user.accountId, name: user.accountName } };
}
  • customer.id is the customer's external_ref: their workspace is found by it, and every tool call made for them carries it.
  • user is the person chatting (subject in the API). Their messages and decisions are recorded as theirs.
  • Answering null refuses the chat. Never answer a fallback customer outside development.

2. One workspace per customer

openlegion/client.ts has workspaceFor(customer). It calls workspaces.create, which is create-or-get on external_ref, so it is safe to call on every request. Replace its in-memory map with a column on your customer's row:

export async function workspaceFor(customer: Customer): Promise<string> {
  const known = await db.accounts.getOpenLegionWorkspace(customer.id);
  if (known) return known;
  // time_zone is where this customer's schedules run ("every Monday at 9"). Without it they run in UTC.
  const zone = customer.timeZone ? { time_zone: customer.timeZone } : {};
  const ws = await openlegion().workspaces.create({ external_ref: customer.id, name: customer.name, template: template.slug, ...zone });
  await db.accounts.setOpenLegionWorkspace(customer.id, ws.id);
  return ws.id;
}

A workspace created with template: "your-slug" tracks the template: it runs whichever version you promote. "your-slug@3" pins version 3.

A workspace has a time zone, and its agents' schedules run in it: "every Monday at 9" is 9:00 there. It is UTC unless you pass time_zone (an IANA name such as Europe/London) when you create the workspace, so set timeZone on the customer your currentSession answers. workspaces.update(id, { time_zone }) changes it later.

Test mode holds at most 100 workspaces per organization, and an archived one still counts. Archiving returns a workspace's credits to your pool; only erasing frees its place. The 101st workspaces.create is refused with entitlement_denied (409), and its partner_message says "This organization holds 100 test workspaces, the most test mode allows. Erase one to make room." The customer you were making it for gets no workspace. A test suite that signs up a customer per test reaches 100 quickly, so erase the workspaces your tests made, for example after each run:

import { OpenLegion } from "@openlegion/platform";

/** Erase the test workspaces your tests made: their external_ref starts with `prefix`. */
export async function eraseTestWorkspaces(prefix: string): Promise<void> {
  // A test key with workspaces:read and data_rights, made for this and kept out of your app's env.
  const key = process.env.OPENLEGION_CLEANUP_KEY ?? "";
  if (!key.startsWith("olp_test_")) throw new Error("Erase test workspaces with a test key only.");
  const cleanup = new OpenLegion({ apiKey: key });
  // Ids first, erases after: an erased workspace can't be the cursor of the next page.
  const ids: string[] = [];
  for await (const ws of cleanup.workspaces.list({ limit: 100 })) {
    if (ws.external_ref.startsWith(prefix)) ids.push(ws.id); // archived workspaces are listed too
  }
  for (const id of ids) await cleanup.workspaces.delete(id);
}
  • Erasing needs the data_rights scope, and no key has it unless you make one for it on the console's Keys page: not the key npx openlegion init wrote. The Data rights starting point ticks it, with workspaces:read and nothing else. Without it the erase is refused with insufficient_scope (403). Make a test key with workspaces:read and data_rights for this one job, and keep it out of your app's .env.local: it can erase every workspace in test mode.
  • An erase can't be undone. workspaces.delete(id) deletes the workspace's content and frees its place as soon as it answers (202); workspace.erased follows once every row and file is gone. The console has no erase button.
  • Live mode's limit is your plan's, and its refusal is the same entitlement_denied.

3. Tools on your own data

openlegion/tools.ts holds your functions, as the agent's tools. Start from get_account, and add what your customers ask about. Every read is scoped by the customer the call was signed for:

import { defineTool, refuse } from "@openlegion/platform";
import { z } from "zod";

export const listInvoices = defineTool({
  description: "List the customer's invoices, newest first: number, amount, status and due date.",
  input: z.object({ status: z.enum(["open", "paid", "all"]).default("all") }),
  trust: "tool_verified",
  effect: "read",
  run: async ({ status }, ctx) => {
    const invoices = await db.invoices.list({ account: ctx.external_ref, status });
    return invoices.length > 0 ? { invoices } : refuse("This customer has no invoices yet.");
  },
});

Then list it in openlegion/template.ts: tools: { get_account: getAccount, list_invoices: listInvoices }.

  • The description is how the model chooses. Say what the tool returns, and when to use it.
  • refuse(message) is an answer, not an error. The model reads it and tells the customer. A tool that throws tells the model only that it failed; the error goes to your onError.
  • trust: tool_verified when the result is your own data, web_low when it carries other people's words (a support ticket's text, a review). A run that reads web_low content is tainted, and later tools see ctx.tainted.
  • effect: read, draft, write or egress (it sends something out of your product). Say what the tool really does: the policy decides on it.

More in Your functions as tools: what ctx carries, tainted runs, and the tools to guard.

4. Changes ask first

A tool that changes something your customer cares about should wait for a person's approval:

export const cancelSubscription = defineTool({
  description: "Cancel the customer's subscription at the end of the current period.",
  input: z.object({ reason: z.string().max(500) }),
  trust: "tool_verified",
  effect: "write",
  requiresApproval: true,
  run: async ({ reason }, ctx) => {
    const sub = await billing.cancelAtPeriodEnd(ctx.external_ref, { reason, idempotencyKey: ctx.action });
    return { cancelled: true, ends: sub.endsAt };
  },
});
  • The call is held as an action that requires_approval, and the run ends. When a person approves, a later run carries it out with exactly the input that was approved.
  • ctx.action stays the same when OpenLegion retries the same action: use it as your idempotency key.
  • Who may approve: a user joins as a member, and a member approves or rejects what their own conversation asked for. An owner or admin approves anything, including what a schedule or a background run asked for, and can read every conversation in the workspace, so tell your users if several share one. Make your customer's account owner an admin with sessions.create({ workspace, subject, role: "admin" }). To keep one tool's approvals for admins, set approver: "admin" on it.
  • Decide from your backend when the action.requires_approval webhook arrives, or from your own UI with approvals.decide, or in the chat: <AgentChat> draws a held call as a card to approve or reject.

More in Approvals and roles: the policy, an action's lifecycle, and each role.

5. The chat, where your customers are

app/agent/page.tsx is one page with <AgentChat>. Move it anywhere in your product: a side panel, a help page, a dashboard tab. It needs a thread id and the thread's history from your server, and never a key:

  • the browser talks only to your route (/api/openlegion/chat), and the route asks currentSession() whose workspace it is;
  • keep each message's tainted when you pass the history, and if you render replies as markdown, show no remote images in a tainted reply;
  • a refusal shows a sentence written for your customer, never OpenLegion's name or your plumbing. Put your own words per code in labels={{ refusals: { … } }}.

6. Starters your customers pick from

A template can describe several agents: agents in its spec, each with a key. Every workspace gets each of them, unless the agent is a blueprint: an agent no workspace has until one of your users makes one from it. That is a "start from one of these" screen: a Researcher, a Reporter, each with its own tools, model tier and schedules, made only for the customers who pick it.

export const assistants = defineTemplate({
  slug: "acme-assistants",
  name: "Acme assistants",
  tools: { get_account: getAccount, cancel_subscription: cancelSubscription },
  // Your own tools go to every agent unless you say which: here only the Assistant can cancel a subscription.
  toolAgents: { cancel_subscription: ["assistant"] },
  spec: {
    agents: [
      { key: "assistant", name: "Assistant", role: "Helps with your account", model_tier: "fast", tools: ["agent.finish", "files.read_attachment"] },
      // A blueprint: no workspace has a Researcher until one of your users makes one.
      { key: "researcher", blueprint: true, name: "Researcher", role: "Looks things up and writes what it found", model_tier: "reasoning", tools: ["agent.finish", "web.search", "web.fetch", "files.deliver"] },
    ],
    // A blueprint must be creatable, or nobody could ever make it. max: the agents a workspace's users may make.
    customizable: { agents: { creatable: ["researcher"], max: 3 } },
  },
});
  • The two lines are blueprint: true on the agent and its key in customizable.agents.creatable. A version is refused when a blueprint isn't creatable, when every agent is a blueprint (a new workspace would have no agent), or when a trigger names one.
  • List them with GET /template_agents: every agent of the workspace's version, each with blueprint and creatable. Your starters are the ones with blueprint: true. POST /agents makes one:
const ws = openlegion().workspace(workspace, { subject: session.user });
const starters = (await ws.templateAgents.list()).data.filter((t) => t.blueprint);
// Your user picks one. Leave name and role out and the new agent has the blueprint's.
const researcher = await ws.agents.create({ template_agent: "researcher" });
  • In React, useTemplateAgents() answers the same list as templateAgents, with agentLimit (how many have been made, and the most allowed), and useAgents().create({ template_agent }) makes one.
  • What POST /agents copies. The new agent has the blueprint's name and role, unless you pass your own where customizable lets them change, and its instructions, model tier, tools and schedules. It goes on following its blueprint: a version you promote later changes it in place, with the person's own changes on top.
  • Who may make one. Your server with its key, or a user with the owner or admin role; a member gets insufficient_role. A workspace's users may make customizable.agents.max agents (409 agent_limit_reached past it).
  • The platform's tools. Each agent's tools takes at most 64 of OpenLegion's own tool ids, and at most 15 of them resident. A resident tool, such as agent.finish, web.search or web.fetch, is sent with every step of every run. A deferred one, such as files.read_attachment or files.deliver, is named in a short index and loaded when the agent first calls it, and that first call runs at once. OpenLegion keeps at most 15 tools resident; Platform tools lists them and says which kind every tool is.
  • Your own tools. An agent's tools lists the platform's tools. Your own functions (the tools of defineTemplate) go to every agent of the template, a blueprint and the agents made from it included, unless toolAgents names the agents that get one. Above, the Researcher, and every agent made from it, can look an account up and can't cancel a subscription. A tool toolAgents leaves out is every agent's.

More in the template spec: agents and customizable.

7. Hear what happened

Your route's webhooks map gets OpenLegion's events for your app, signed and verified for you. Every run that ends fires exactly one of run.completed, run.failed and run.cancelled:

webhooks: {
  "run.failed": async (event) => {
    await alerts.notify(event.data.object?.id); // event.data.object.error.partner_message says what to do
  },
},

A delivery that doesn't get a 2xx within 5 seconds is retried for about 3 days, with the same event id each time: dedupe on it.

More in Webhooks: local testing with npx openlegion dev, the retry schedule, and an endpoint outside the kit.

8. Limits and money

  • Per run. The template's budget.run_credits is what one run may spend (a credit is $0.001). The quickstart's template sets 10, the least a fast-tier run may hold. Raise it when runs stop with run_budget_exhausted. Always set it: without it a run holds the ceiling of the dearest tier it may reach, 1,000 credits ($1.00) for frontier.
  • Per customer. Each workspace has a period cap and a daily cap: workspaces.limits.update(id, { period_credit_cap, daily_credit_cap }), or the template's default_limits for new workspaces. A one-off top-up is workspaces.creditGrants.create(id, { credits }).
  • Your pool. Workspaces spend from your organization's credit pool. In test mode a free monthly allowance funds it.
  • Which key. The key npx openlegion init wrote can read usage and a workspace's credits. It can't change a limit or grant credits: those two calls need the limits:write scope, which that key leaves out so that a leaked app key can't raise a cap. Make a key with limits:write on the console's Keys page (the starting point Your app's server is the init key with limits:write added) and use it for those calls (Keys and your team).

More in Credits, budgets and limits.

9. Ship it

  1. Deploy your app with its OpenLegion route.
  2. Wire it once. npx openlegion deploy --url https://your.app --prepare makes a connector and a webhook endpoint for your deployed app. In test mode, use a preview or staging deployment's URL: once you go live, your production deployment holds the live secrets, and a deployment holds one mode's. Each secret goes to your linked Vercel project's env, or to a file outside your project, and is never printed. In test mode it also makes your app's two keys, OPENLEGION_API_KEY and OPENLEGION_DATA_RIGHTS_KEY: you approve them once in your browser, and the terminal that ran the command sets them in Vercel without printing them (--no-data-rights leaves out the second). On another host, make them on the console's Keys page with the starting points Your app's server and Data rights. Redeploy, so your app runs with all of them.
  3. Push and promote. npx openlegion deploy --url https://your.app runs Test connection, pins your tools, and pushes and promotes your template. OpenLegion reads the template from your deployment through the connector, so CI needs no connector secret: run the same command from CI after each deploy, with a key from the console's starting point Your deploy pipeline (CI) in OPENLEGION_CLI_KEY. Every workspace tracking the template runs the new version from its next run. Rolling back is promoting an older version.
  4. Go live. Your organization starts in test mode only. The template you promoted needs default caps: default_limits in its spec, with a period_credit_cap or a daily_credit_cap. When the console's Go live page shows its five checks passed, an owner or admin requests live access; OpenLegion reviews it. Once it's approved, live mode starts empty: run npx openlegion deploy --url https://your.app --prepare --live --wait, have an owner or admin approve its code (it makes your app's live key and wires your production deployment), and fund your live pool. The steps are in Keys, your team and going live.

Reference: the API reference and the CLI reference.