# Extensions

Orbik is open source and complete on its own: with no extension loaded every limit is unlimited,
every agent runs, and the edition is `community`. An **extension** is how a deployment adds to it
without changing it — plans and their limits, billing, an admin back office, metering, more pages
in the web app. Orbik's own cloud is built this way, from a separate private repository that
includes this one; nothing of it is in this repository.

There are two halves, one for the server processes and one for the web app:

| | Where | What it can do |
|---|---|---|
| Server extensions | `ORBIK_EXTENSIONS`, loaded by the API, the worker, the scheduler, `grant:crawl-budget` and `check:models` | plan limits, events, the edition and its features, API routes, scheduler loops, worker agents, agents in the catalog with their tools and runtimes, the email sender, making accounts from its own routes, Google sign-in for new accounts |
| Web extensions | the `@orbik/web-extensions` package the web app imports | rail items, pages, settings sections, banners, items in the workspace header, notes under Ask answers, agents' pages, account pages, account menu items, the `/signup` page, the foot of the sign-in and signup pages, notices in the create-workspace wizard |

The rule that keeps the two repositories honest: **core starts and serves every page with no
extension loaded**, and core never imports an extension. ESLint enforces the second
(`eslint.boundary.mjs`): an import from `backend/`, `agents/`, `frontend/` or `packages/` that
resolves outside this repository, names an `@orbik/` package this repository does not define, or
names `orbik-cloud`, fails the lint. The loader imports extensions by a name it reads at run time,
which no rule sees; that is the one door.

## Server extensions

`ORBIK_EXTENSIONS` is a comma-separated list of modules. Each entry is a package name, resolved the
way any import is (so a package the deployment's root depends on is found), or a path, resolved
against the process's working directory. Set the same list for every process. A module that fails
to import or register stops the process: a deployment that enforces plans must not come up
without them and serve everything unlimited.

A module's default export is `{ name, register(host) }`:

```js
export default {
  name: "acme-plans",
  async register(host) {
    // Every process.
    host.setPlanLimits(async ({ ownerId, workspaceId }) => planFor(ownerId, workspaceId));
    host.on("ai.call.finished", ({ call }) => meter(call));

    if (host.process === "api") {
      host.setEdition("cloud");
      host.addFeatures("billing");
      host.addRoutes((http) => billingRouter(http));
      host.checkGoogleSignup(async ({ email }) => refuseDisposable(email));
      host.setEmailSender(async ({ to, subject, text }) => sendWithProvider(to, subject, text));
    }
    if (host.process === "scheduler") host.addLoop(createUsageReporter(host.database));
    if (host.process === "worker") host.addAgent({ name: "acme-export", version: 1, handlers: { "acme-export.run": runExport } });
  },
};
```

`host.process` is `api`, `worker`, `scheduler` or `script`. `host.database`, `host.config` (the
process's parsed configuration) and `host.logger` are handed over too. A method that belongs to
another process throws, so an extension checks `host.process` first.

### Plan limits

`host.setPlanLimits(resolve)` — one extension per deployment. `resolve({ ownerId, workspaceId })`
returns the limits of one workspace, whoever is acting in it; `ownerId` is its owner, so a
deployment whose plans belong to accounts can answer by owner alone, and one whose plans belong to
workspaces by `workspaceId`. The one question that is no workspace's, how many workspaces an
account may own, is asked with `workspaceId: null`. Every field is a ceiling, and `null` (or
leaving it out) means none:

| Field | Enforced by |
|---|---|
| `monthlyCrawlPages` | the crawl budget, which keeps one month per workspace, in the API and every crawl the worker makes. `0` means the plan includes no crawling (how a deployment pauses a workspace): the API refuses to start a crawl with `403 CRAWL_NOT_INCLUDED`, as it refuses one in a month whose pages are spent with `409 CRAWL_BUDGET_SPENT`, and `statusFor` reports the two apart (`state`: `not-included`, `spent`). A month's ceiling is fixed when the month is first touched; with none the month is unlimited and still counts `consumed`. To change the current month (a mid-month upgrade, pages bought), `createCrawlBudget({ database }).grant({ workspaceId, pages, reason })` from `@orbik/crawl-budget` adds to it, and `statusFor({ workspaceId })` reads it; a call naming a `userId` instead, as before budgets were per workspace, throws. |
| `maxWorkspaces` | creating a workspace, asked with `workspaceId: null`: `403 PLAN_LIMIT_REACHED` |
| `maxMembersPerWorkspace` | inviting and accepting: `409 MEMBER_LIMIT_REACHED` |
| `agents` | a list of agent slugs, or `null` for all. Starting a run in the API (`403 PLAN_LIMIT_REACHED`), and any run the worker executes, which fails with `PLAN_LIMIT_REACHED` |
| `aiCalls` | `false` refuses every model and embedding call made for the workspace before anything is sent: `PLAN_LIMIT_REACHED` |
| `reasoningCalls` | `false` refuses every call but embeddings (agent runs, chats, short texts) the same way, while crawled pages are still indexed and MCP search still answers: for an allowance of model usage that is spent. `aiCalls: false` wins over it |

Answers are cached for 30 seconds in each process, per workspace and per account. An extension
that changes a plan calls `host.forgetLimits({ workspaceId })` to drop one workspace's answer,
`host.forgetLimits({ ownerId })` for an account's and all of its workspaces', or
`host.forgetLimits()` for all of them, in the process that calls it; the others catch up within
the 30 seconds. A malformed answer (a negative count, a list of numbers) throws rather than being read
as unlimited.

### Events

`host.on(event, handler)` — told after the fact; a handler that throws is logged and ignored, so an
extension never fails the action it is told about.

| Event | Where | Payload |
|---|---|---|
| `account.created` | API | `{ user: { id, email }, via }`: `setup`, `invite`, `access-request` or `google` for an account core made, or the `via` an extension's route gave `http.accounts.create` |
| `access.requested` | API | `{ request: { id, email } }`, the first time an address asks for access on the Request access page |
| `workspace.created` | API | `{ workspace: { id, name, websiteUrl, ownerId }, userId }` |
| `workspace.deleted` | API | `{ workspace: { id, name, websiteUrl, ownerId }, userId }`, after every record core keeps of it is gone; remove what the extension stored about it |
| `workspace.owner.changed` | API | `{ workspace: { id, name, websiteUrl, ownerId }, previousOwnerId }`, after `http.workspaces.transferOwnership` changed its owner; `ownerId` is the new one |
| `ai.call.finished` | API, worker | `{ call }`: the `ai_calls` row as written — workspace, run, agent, model, usage, `costUsd`, status |
| `ai.catalog.findings.changed` | scheduler, `check:models` | `{ provider, findings, previous, checkedAt }`, when the day's comparison of the provider's model list with the model catalog finds something other than the last check found (an empty `findings` when the catalog has caught up); the first check that finds nothing tells nobody. Each finding is `{ kind: "not-listed", model, name, tier }`, a tier's model the provider no longer lists, or `{ kind: "newer", model, name, createdAt, family, tier, catalogModel }`, a listed model newer than a tier's in its family. For telling someone once that the catalog needs a model added ([ai-execution.md](https://orbik.io/docs/architecture/ai-execution.md#keeping-the-catalog-current)) |

### API

- `host.setEdition(name)` and `host.addFeatures(...names)` — what `GET /v1/edition` reports. The web
  app shows a slot only when the feature it names is listed.
- `host.addRoutes((http) => router)` — mounted after every core route and before the 404 handler,
  so none can shadow a core route. `http` carries `database`, `config`, `logger`, `AppError`,
  `requireAuthentication`, `csrfProtection` and `requireWorkspaceAccess(userId, workspaceId,
  { role })`, the same ones core's routes are built from, and:
  - `accounts`, for a route that makes accounts. Orbik has no self-service signup; a deployment
    that offers one builds it here. `accounts.findByEmail(email)`; `accounts.create({ email,
    passwordHash, googleSub, via })` makes an active account (an argon2id `passwordHash`, or a
    Google `googleSub`, or both), keeps the address canonical and unique (a taken one is
    `409 ACCOUNT_EXISTS`) and tells extensions `account.created` with `via` (lowercase letters,
    digits and dashes); `accounts.signIn(request, user)` signs the browser in to it as login does
    (a new session identifier, a new CSRF token) and answers the session, to send back as JSON.
  - `workspaces.create({ userId, name, websiteUrl, idempotencyKey })` and
    `workspaces.startSetup({ userId, workspaceId })`, for a deployment whose staff prepare
    workspaces for people. Nobody needs to be signed in, and neither asks who is calling: the route
    calling them decides who may. Both act as the account `userId` and keep every rule the web
    app's own buttons do. `create` is `POST /v1/workspaces`: it validates the same way, counts
    against `maxWorkspaces`, selects the workspace for that account, tells extensions
    `workspace.created`, and answers `{ workspace, created }`; the same key again answers the same
    workspace with `created: false` (`409 IDEMPOTENCY_CONFLICT` for other details). `startSetup`
    does Home's first steps with their defaults: it asks for the website's first crawl, chooses the
    standard Library folders and sets the knowledge agent to work, which writes the Library once
    the crawl is in. A step already done is left as it is, so calling it again after a failure
    finishes the rest. It needs the plan to have crawl pages (`403 CRAWL_NOT_INCLUDED`,
    `409 CRAWL_BUDGET_SPENT`), so set the workspace's plan first, and call `host.forgetLimits` if
    the process may have asked for its limits before that. It spends crawl pages and AI usage.
  - `workspaces.transferOwnership({ workspaceId, fromUserId, toUserId })`, for a deployment that
    lets a workspace change hands. No route of Orbik's own changes an owner, and this checks
    nobody's permission: the route calling it decides who may. The workspace keeps everything in
    it, its other members included; the previous owner keeps no access (no member row, the invites
    they issued revoked, their MCP tokens and OAuth grants released). It refuses with
    `409 OWNER_CHANGED` when `fromUserId` does not own the workspace, `404 ACCOUNT_NOT_FOUND` when
    there is no active account `toUserId`, and `409 OWNER_CHANGE_CONFLICT` when the new owner has a
    workspace made with the same creation key. It answers `{ workspace, transferred }`; calling it
    again after a failure finishes what was left, with `transferred: false` and no second event.
    `maxWorkspaces` is not checked. The process that transfers asks for the workspace's limits
    again at once; another may use the previous owner's answer for up to 90 seconds. What members
    can read of the workspace's past (runs, the AI call log) the new owner can read too.
  - `sendEmail({ to, subject, text, html? })`, the install's mail (SMTP, or an extension's
    sender), or null when it has none.
  - `rateLimit({ keyPrefix, points, durationSeconds, keyFromRequest? })`, middleware that allows
    `points` requests per key (the client's address by default) per window, kept in the database
    as core's own limits are, and answers `429 RATE_LIMITED` beyond them.
- Routes under `/v1/hooks/` are for other software's servers, such as a payment provider's
  webhook: no CORS check, no JSON requirement and no body parsing, so the route reads the raw body
  itself (`express.raw()`) and authenticates by signature, never by session.
- `host.checkGoogleSignup(check)` — one extension per deployment. Without it, signing in with
  Google (`GOOGLE_CLIENT_ID`) only signs in to an account that exists, and an address with none is
  sent back to the sign-in page with "no account". With it, `check({ email, request })` runs for
  such an address, and when it returns the account is made (no password; `account.created` with
  `via: "google"`). Throw an error with a 4xx `status` and a `code` to refuse it: the person is sent
  back to the sign-in page with a general "cannot sign up here".
- `host.setEmailSender(send)` — one extension per deployment; replaces SMTP. `send({ to, subject,
  text, html? })`.

### Scheduler and worker

- `host.addLoop({ start, stop })` — started and stopped with the scheduler's own loops.
- `host.addAgent({ name, version, handlers })` — validated as a core agent is; its job types are
  queued and claimed like any other. A name already taken is refused. This is a queue agent, a set
  of job handlers; an agent a person sees in the catalog, runs and schedules is the next section's.

### Agents

An extension can add agents to the catalog: listed by `GET /v1/agents`, started from the API,
put to work on a schedule, executed by the worker, refused outside a plan's `agents` exactly as a
core agent is, and recorded in `agent_runs`, `agent_run_events` and `ai_calls` like one.

- `host.addAgentDefinitions(...definitions)` — every process. A definition has the shape
  `parseAgentDefinition` in `@orbik/protocol` accepts, the shape of core's own in
  `packages/agent-definitions/src/`. `modelTiers` says which tiers of the model catalog its runs may
  use (the default alone when left out); one that allows more gets a Model setting on its setup
  (`PUT /v1/workspaces/:id/agents/:slug/model`), which its runs follow ([ai-execution.md](https://orbik.io/docs/architecture/ai-execution.md#models-the-catalog-tiers-and-routes)).
- `host.addTools(...tools)` — every process (definitions are checked against them wherever the
  catalog is read; only the worker calls them). A tool is `{ name, description, inputSchema,
  parseInput(input, errors), handler(input, context) }`: `name` is namespaced (`acme.listIssues`),
  `parseInput` pushes a message onto `errors` for anything it refuses and returns the parsed input,
  and `handler` gets `{ database, retrieval, scope, signal, readingBudget }`, where `scope` is the
  run's own (`workspaceId`, `siteId`, `agentSlug`, `runId`) and never something the model wrote.
  Throw `ToolError` from `@orbik/tools` to refuse with a code. An extension's tools are given only
  to the definitions that name them, and are not served over MCP.
- `host.addRuntime(requirement, build)` — worker only. A **plain-code runtime**: code that
  executes a definition itself, chosen for any definition whose `runtimeRequirements` names
  `requirement`; a definition that names no plain-code runtime is executed by the model, with its
  tools. `build(collaborators)` is called once when the worker starts, with what core's own
  plain-code runtimes get: `config`, `database`, `logger`, `retrieval` (the index, or null with
  `retrievalReason` saying why), `writeText` and `writeStructured` (a short text, or one object of
  a fixed shape, from the model; recorded in `ai_calls` with the run they belong to, and never
  throwing: they answer `{ skipped, reason }` or `{ failed, reason }` instead) and `AgentError`.
  It returns `{ run(request) }`.

`run({ definition, input, tools, signal, isCancelled, trace, modelTier })` is an async generator. It yields
the run's events (`AGENT_EVENT_TYPES` in `@orbik/protocol`: `started`, `progress` with a `message`,
`tool-started` and `tool-completed` with a `tool`, `completed` with the `result`) and returns
`{ result, usage }`. `tools` is the run's registry (`tools.invoke(name, input, signal)`), holding
the tools the definition names. Pass `trace`, with `agentSlug` and `agentVersion` added, to
`writeText` and `writeStructured`, so the call log names the run. `modelTier` is the tier the run
was given, held to the definition's `modelTiers`; `writeText` and `writeStructured` do not take it,
and are routed by their capability alone (`fast` work on the smallest tier, the rest on the default). To fail the run with a code and a
message a person can act on, throw `new AgentError({ code, message, retryable: false })`; anything
else is recorded as `UNEXPECTED_ERROR`.

The API, the worker and the scheduler add these to their catalog right after loading extensions
(`extendAgentCatalog` in `@orbik/agent-definitions`), each definition checked as a core one is. A
malformed definition, a slug or tool name core already has, a tool no one provides, or a runtime
requirement core already runs stops the process, as a failed extension does. In the web app such
an agent has the generic agent page at `/workspaces/:id/agents/<slug>` (its summary, a Run button
and its runs). An `agentPages` entry in the web extension lists it in the Agents overview and may
give it a page of its own ([Web extensions](#web-extensions)). Remove an agent a schedule names
and the scheduler disables that schedule (`AGENT_NOT_AVAILABLE`) rather than fail it every week.

```js
host.addAgentDefinitions({
  slug: "acme-page-count", version: 1, name: "Page count", summary: "Counts the crawled pages.",
  instructions: "Plain code.", tools: ["acme.pageCount"], capability: "fast",
  inputSchema: { type: "object" }, outputSchema: { type: "object" },
  runtimeRequirements: ["acme-page-count", "crawl-dataset"],
});
host.addTools(pageCountTool);
if (host.process === "worker") {
  host.addRuntime("acme-page-count", ({ writeText, AgentError }) => ({
    async *run({ definition, tools, signal, trace }) {
      yield { type: "started" };
      const { pages } = await tools.invoke("acme.pageCount", {}, signal);
      if (!pages) throw new AgentError({ code: "NOT_CRAWLED", message: "Crawl the site first.", retryable: false });
      const summary = await writeText({ system: "…", prompt: `Pages: ${pages}`, signal,
        trace: { ...trace, agentSlug: definition.slug, agentVersion: definition.version } });
      const result = { pages, summary: summary.text ?? null };
      yield { type: "completed", result };
      return { result, usage: null };
    },
  }));
}
```

## Web extensions

The web app imports `@orbik/web-extensions` and renders its exports. In this repository the package
(`packages/web-extensions`) exports them all empty, and the app renders exactly as it would without
them. A deployment's package may leave any of them out.

| Export | Rendered |
|---|---|
| `railItems: [{ id, name, icon, path, feature? }]` | in the workspace rail, after Sources and the agents and before Settings, linking to `/workspaces/:id/<path>` |
| `pages: { [path]: { title, Component, feature? } }` | at `/workspaces/:id/<path>` by the app's one catch-all route; a core page at the same address always wins |
| `settingsSections: [{ id, title, description?, Component, feature? }]` | at the end of a workspace's Settings navigation, each its own page at `/workspaces/:id/settings/extensions/<id>` |
| `banners: [{ id, Component, feature? }]` | above every page of a workspace |
| `headerItems: [{ id, Component, feature? }]` | in the workspace header on every page of a workspace, after the theme switch and before the account menu, in the order listed: something compact that is always in view, such as an icon-sized control that opens a popover, for a deployment that meters usage to say what is left. Each sits in a box the controls' height (2rem) that does not shrink, so the header keeps its height and the workspace's name gives way first on a phone; keep it narrow. One that renders nothing leaves no gap |
| `answerNotes: [{ id, Component, feature? }]` | under each finished answer in the Ask panel, the Library chat's and the brand chat's, on the quiet line that holds Copy, in small muted text: what an answer cost, for a deployment that meters usage. Not while an answer is being written, nor under one that failed before it had a run. The component also gets `runId`, the run behind the answer; `model`, the model that answered the latest of the run's reasoning calls to come back, as the AI call log names it (the one the provider fell back to, when it did), or null when none did; and `costUsd`, what the run's model calls cost at list price in US dollars, the sum of `costUsd` on its `ai_calls` rows, embeddings included, 0 when none was priced. The API carries `model` and `costUsd` on the turn ([library.md](https://orbik.io/docs/architecture/library.md#ask-a-chat-over-the-index)), so a note needs no request of its own; both are null for a reader whose role does not read the AI call log. One that renders nothing leaves no gap |
| `agentPages: { [slug]: { name, icon?, Component?, feature? } }` | an agent a server extension added to the catalog ([Agents](#agents)), in the Agents overview and the workspace's agent lists, linking to `/workspaces/:id/agents/<slug>`; with a `Component` that page is the extension's (it gets `agentSlug` too), without one the generic agent page. A slug core has a page for keeps core's |
| `accountPages: { [path]: { Component, feature? } }` | at `/account/<path>` (core's own `/account/password` keeps its address, which leads to Settings → Account), about the signed-in account rather than a workspace, for anyone signed in (a person with no workspace yet included), in the Admin page's frame; the component draws the page, heading included, and gets `path` and `api` |
| `signupPage: { Component, feature? }` | at `/signup`, in place of the Request access form, for someone signed out; the sign-in page's "Need an account?" then says **Create one**. For a deployment whose server extension makes accounts (`http.accounts`, above). The component gets `api` (`api.fetch(path, { signsIn: true })` for a request whose answer is the session of an account it signed in, so the app's session follows), `ui`, the pieces the sign-in pages are built from: `AuthPanel`, `AuthField`, `AuthError`, `AuthPanelFoot`, `AuthDivider`, `GoogleSignInButton`, `Button`, `Input`, `Link`, the `AUTH_LINK` class, and `googleSignIn`, whether the install offers Continue with Google, and `query`, the address's query as Next's `searchParams` gives it (`{ name: value }`, an array for a name given more than once). It is rendered on the server too, so read the address from `query`, never `window`; leave the form's fields uncontrolled, so what is typed before the page's JavaScript runs is kept; and keep the submit button disabled until then |
| `authFooter: { Component, feature? }` | at the bottom of `/login` and `/signup`, in small muted text, outside `main`: links to a deployment's terms, a copyright line. Rendered on the server too. The component gets `api` only |
| `userMenuItems: [{ id, label, href, icon?, feature? }]` | in the account menu, before Documentation and the source link; `href` is a path in the app (`/account/billing`) or an `https://` address, opened in a new tab |
| `workspaceCreateNotices: [{ id, Component, feature? }]` | in the create-workspace wizard (`/workspaces/new`), above its buttons, on both steps (the name, then the website), to tell the person something before a workspace is made: what it will cost, a limit reached. The component gets `api` only and renders nothing when it has nothing to say; it sits inside the wizard's form, so a button in it needs `type="button"` |
| `crawlBudgetLink: { label, path, feature? }` | on a source's crawl page (the website's is what the Crawler page was), beside "this month's crawl pages are spent" and "this workspace's plan includes no crawl pages": where more crawl pages are got. `path` is under the workspace, as a rail item's, or an `https://` address, opened in a new tab. Without it the page offers nothing to press |

Components are client components and receive `workspaceId` (on a workspace's pages) and `api` — the app's own client
(`api.fetch(path, init)`), so requests carry the session, the CSRF token and the error envelope as
a core page's do. An entry naming a `feature` is shown only when `GET /v1/edition` lists it.

A deployment supplies its own package under the same name, and the web app's dependency resolves to
it. In a pnpm workspace that includes this repository, leave `packages/web-extensions` out of the
workspace and put the deployment's package, named `@orbik/web-extensions`, in it:

```yaml
# pnpm-workspace.yaml of the private repository
packages:
  - orbik/frontend
  - orbik/backend
  - orbik/agents
  - orbik/packages/*
  - "!orbik/packages/web-extensions"
  - cloud/*
```

Next compiles the package with the app (`transpilePackages` names it), so it may be JSX.

In such a workspace the dependencies are installed at its root, above this repository, so set
`NEXT_WORKSPACE_ROOT` to that root (an absolute path, or one relative to `frontend/`) for every
`next` command the web app runs there. It becomes the app's `outputFileTracingRoot`, which is the
root Turbopack resolves modules from and the most it compiles: left at this repository, `next dev`
cannot find `next` itself, nor a deployment's package beside `orbik/`. Unset, it is this
repository, as before.

`NEXT_DIST_DIR` (optional, default `.next`) is the directory, relative to `frontend/`, that `next
build` writes the web app into and `next start` serves it from. A deployment that builds on the
machine it serves from can build into a fresh one (`.next-<release>`, which git ignores) while the
running server keeps serving the old, then restart the server with the new value: set the same
value for the build and for the server that serves it.

## A private repository around this one

The shape Orbik's own cloud uses, and the one this seam was built for:

```
orbik-cloud/
  orbik/          this repository, as a git submodule pinned to a commit
  cloud/api/      a server extension: plans, billing, metering
  cloud/web/      @orbik/web-extensions: billing pages, upgrade prompts
  infra/          the deployment's own configuration
```

Its root `package.json` depends on `cloud/api`, so `ORBIK_EXTENSIONS=@acme/cloud-api` resolves from
any process; upgrading core is a submodule bump.

## Checking a change to the seam

There are no automated tests in this repository. To see an extension work, write a throwaway one
outside the repository and name it by its absolute path in `ORBIK_EXTENSIONS` for a scratch API,
worker and scheduler. To see web slots, point `frontend/node_modules/@orbik/web-extensions` at a
throwaway package for a dev server, and put the link back afterwards. Keep the package inside this
repository, in a git-ignored place such as `frontend/node_modules/.throwaway/`: the dev server
compiles nothing outside it, and from there `react` and `lucide-react` resolve as the app's do. Both were done for idea 030
(`.devbar/open/030-open-source-core-and-cloud-layer.md`).
