# Reference This page lists what Pairz gives you to import, and what a plugin may declare. It says what each piece is, not why it's built that way: [the architecture](architecture.md) says how it runs. Every plugin Pairz ships has [a page of its own](reference/plugins.md), read from the plugin itself. ## Install Start a new app with `npx pairz@1.0.0-rc.82 init orders`. The starter includes the compiler, a plugin, a web page and tests. [Start an app](guides/the-compiler.md#start-an-app). To add the runtime to an existing project: ```sh npm install pairz@next # Node 24+ (npm, pnpm, yarn) bun add pairz@next # Bun deno add jsr:@pairz/pairz@^1.0.0-rc.82 # Deno 2.9+ (or `deno add npm:pairz@next`) ``` Until 1.0, the release candidates are on npm's `next` tag, and a plain `npm install pairz` or `deno add jsr:@pairz/pairz` gets an older version. At 1.0, stable installs drop `@next` and the version. On Deno, map the name in `deno.json` (`"pairz": "jsr:@pairz/pairz@^1.0.0-rc.82"`), and the imports read the same everywhere. 3 pieces need a package of their own, installed beside it: `esbuild` to bundle the page's code on Node (`bundle`), `@electric-sql/pglite` for PostgreSQL in the process, and `@types/react` for the front ends' types. A product's plugins are packages of their own too, at Pairz's version (`npm install @pairz/work@next`, `deno add jsr:@pairz/work@^1.0.0-rc.82`): see [Product packages](#product-packages). ## Entry points The same names on npm (`pairz/…`) and JSR (`@pairz/pairz/…`). | Import | What it has | | ----------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | | `pairz` | the runtime: `createRuntime`, `definePlugin`, `defineAction`, the access helpers (`people`, `inPerson`, `grant`…), `connect` (the client)… | | `pairz/stores/memory` | `memoryStore()`: in memory, the reference every store is held to | | `pairz/stores/sqlite` | `sqliteStore({ path })`: one file, on `node:sqlite` or `bun:sqlite` | | `pairz/stores/postgres` | `postgresStore({ url, schema, tenant })` (a server, or PGlite in the process), `postgresPool`, `copyTenant`, `exportTenant`, `dropTenant` | | `pairz/stores/latency` | `withLatency(store, ms)`: a store with round trips, to measure | | `pairz/blobs/files` | `fileBlobs({ dir })`: large values as files | | `pairz/blobs/http` | `httpBlobs({ url, headers })`: large values in a bucket (S3, GCS, R2…) | | `pairz/blobs/gcs` | `gcsBlobs({ bucket, prefix })`: large values in Google Cloud Storage, as the instance's service account | | `pairz/plugins/models` | `models`: language models, embeddings, transcription and images, with the models.dev catalog | | `pairz/plugins/agents` | `chat` and its `tool`, `history`, `memory`, `memoryExtraction`, `skills`, `routines`, `openapi`, `webTools` | | `pairz/plugins/agents/web` | their web front ends: `chatWeb`, `memoryWeb`, `skillsWeb`, `routinesWeb` | | `pairz/plugins/agents/terminal` | their terminal front ends: `chatTerminal`, `memoryTerminal` | | `pairz/plugins/agents/` | one of them alone, `` being `chat`, `history`, `memory`, `skills`, `routines`, `openapi`, `webtools` | | `pairz/plugins/access` | `access` (`spaces`, `identity`, `contacts`), `googleSignIn`, `emailSignIn`, `passwordSignIn`, `email`, `devSignIn`, `accounts` | | `pairz/plugins/access/web` | `spacesWeb`, `contactsWeb`, `accountsWeb` | | `pairz/plugins/access/terminal` | `accessTerminal` | | `pairz/plugins/access/` | one of them alone, `` being `spaces`, `identity`, `contacts`, `google`, `email` (with `passwordSignIn`), `dev`, `accounts` | | `pairz/plugins/billing` | `usage`: the ledger, and the port an app's pricing plugs into (`spending`) | | `pairz/plugins/billing/web` | `usageWeb` | | `pairz/plugins/billing/terminal` | `usageTerminal` | | `pairz/plugins/compute` | `computers` (people's machines, where agents work), and `googleToken` (Google's tokens, for Cloud Storage's blobs) | | `pairz/plugins/compute/web` | `computersWeb` | | `pairz/plugins/compute/terminal` | `computersTerminal` | | `pairz/plugins/compute/downloads` | `computerDownloads`: the computer program's release, served by the app (Node) | | `pairz/plugins/compute/program` | `startPool`: the computer program's pool mode, in a process of the app's own (for an app that hosts computers) | | `pairz/plugins/interfaces` | `terminalPlugin` (the terminal's data), `api`, `whatsapp`, `voice`, `mcp`, `webLines` (site chats), `maintenance` | | `pairz/plugins/interfaces/web` | `webShell` (the web's root View), `apiWeb`, `whatsappWeb` | | `pairz/plugins/interfaces/terminal` | `terminalShell`: the terminal's root View | | `pairz/plugins/interfaces/` | one of them alone, `` being `mcp`, `api`, `whatsapp`, `voice` | | `pairz/plugins//contract` | each theme's plugins' contracts (`access`, `agents`, `models`, `interfaces`, `compute`): shapes, and the little code with them, for plugins built on them | | `pairz/web` | the web host in the browser (`web`), its toolkit (`Button`, `Markdown`…), what a widget asks (`display`, `surface`, `remind`) | | `pairz/web/words` | the words alone, without the toolkit: `defineWords`, `wordsOf`, `formatDate`… | | `pairz/web/pt-br` | `ptBR`: every word of the web front ends and the sign-in page in Brazilian Portuguese, as a plugin of the page's | | `pairz/web/server` | the page's server half: `webPage` (the page, as a plugin), `widgetsOf`, `routePage` (a route's own page in the app's look) | | `pairz/web/widget` | the widget host: an app's web Views inside an outside assistant (MCP Apps, ChatGPT) | | `pairz/web/theme` | `themeOf(plugins)`: the app's theme, for the page's first paint | | `pairz/web/export` | table and document files on a server or in a browser: `exportFile`, `tablePdf`, `documentPdf`, `pdfImage`, `bars`, `barcodePng` | | `pairz/web/node` | `listen` (serves `runtime.fetch` on Node and Bun, sockets included), `bundle` (the browser's code, with esbuild) | | `pairz/terminal` | the terminal host, `terminal({ runtime, me })`, and its toolkit | | `pairz/exporters` | `otlp`, `exposition`: metrics out, the OpenTelemetry way | | `pairz/testing` | one test API for Deno, Node and Bun: `test`, `tempDir`, `serve`, `spawn`, `testWho`, `ticketFor`, `openTo`, `boundaries`, `createWorker`… | | `pairz/testing/words` | testing a front end's words (`pseudoWords`, `englishLeft`), and listing them (`wordsList`) | | `pairz/describe` | `describe(plugin)`: what a plugin declares, as JSON | The browser loads only `pairz/web`, the front ends under `…/web`, and what they import. Every other entry point is for the process that runs the runtime, or the terminal. A theme's entry point (`pairz/plugins/interfaces`) loads every plugin in it. A plugin's own (`pairz/plugins/interfaces/mcp`) loads that plugin and what it imports, and nothing else: the same plugin, with less code in the server's memory. ## Product packages What a product does its own way, rather than what every app needs, is a package of its own, released with Pairz at its version: `@pairz/work@1.0.0-rc.82` goes with `pairz@1.0.0-rc.82`. Each has the same entry points, its plugins (`@pairz/work`), their front ends (`@pairz/work/web`) and their shapes, for plugins built on them (`@pairz/work/contract`), with the same names on npm and JSR. | Package | What it has | | ------------------ | ------------------------------------------------------------------------------------------------------------ | | `@pairz/work` | `boards` (kanban) and `documents` (shared Markdown with versions and merges); `boardsWeb`, `documentsWeb` | | `@pairz/directory` | `directory`: many orgs behind one address; `directoryWeb`, the org switcher, the org's page, staff's console | | `@pairz/billing` | `credits` (plans, credits, budgets), `stripe`, `stripeWebhook`; `creditsWeb` | | `@pairz/team` | `team` (agents people make), `tiers` (the models an org's agents think with); `teamWeb`, `tiersWeb` | They import Pairz by its entry points alone, as an app's own plugins would. Their collections, Actions, events, Views and resources keep the names they had inside Pairz, so an app's data stays as it is. ## Who, for whom, where Every call runs as an actor. The actor says who acts, for whom an agent works, and where the work is. The runtime carries it into everything the call causes: nested calls, tools, the Processors its events wake, its timers, and the Views observed for it. Every event records it. ```ts { kind: "agent", id: "north", for: { kind: "person", id: "ana" }, in: "launch" } ``` | Field | What it says | | -------------- | ----------------------------------------------------------------------------------------------------------- | | `kind`, `id` | who acts | | `for` | whom an agent works for: a person or a contact | | `in` | where the work is: an opaque id, as `id` is. To the access plugin it's a space. None: nowhere in particular | | `via` | whose work trusted code was doing when it acted as someone else (`ctx.as`) | | `key`, `scope` | a person acting through a developer key, and what the key may use | | `origin` | what set a person's work going, such as a routine | The kinds the runtime makes or checks: | Kind | Who | Made by | | ------------- | ------------------------------------------------------------------- | ------------------------------------------ | | `person` | someone with an account, signed in or through their key | `identity`; a key's by `api` | | `agent` | an agent, working for someone (`for`) | `chat`, for each turn | | `contact` | someone outside the org: a WhatsApp customer, a caller, an MCP chat | `contacts` | | `system` | trusted code, which no rule restricts; a named grant is one too | the runtime: no actor, `ctx.as()`, `grant` | | `maintenance` | the maintenance key, for support's SQL | the maintenance plugin's routes | | `anonymous` | an HTTP request nobody is signed in to (`id: ""`) | `runtime.fetch`, when no `who` answers | Each way in says where its work is: | Way in | Who, for whom | Where (`in`) | | ----------------------- | -------------------------------------------- | ------------------------------------------- | | The web | the person | the page's space: a call says it | | A chat's turn | its agent, for whoever started it | the chat's space | | WhatsApp | the customer (a contact), or a linked person | the number's space, or the space they're in | | Voice | the caller (a contact), and its agent for it | the line's space | | A web line, an MCP line | the visitor or conversation (a contact) | the line's space; a tool, where its chat is | | A developer key | its person, through it | the key's space | | The terminal | its person | where they work (`/space`, `/work`) | | A routine | whoever made it, set going by it (`origin`) | the routine's space | | Handing work to a space | the same person | the new space | A host calling for someone says where too: `runtime.call(action, input, { actor: { ...ana, in } })`, or a client's `call(action, input, { in })`. What a page says is recorded, never proved, and a person's own reach isn't narrowed by it. An agent's reach is: its person's reach, within the spaces the agent is a member of, within `in` and what `in` draws on. In the person's own Personal space, their agents reach all they do, and what they write elsewhere for them there is theirs (no labels from there). Tools that take a space (`in`) work there: check it with `workIn` from the agents' contract. The access plugin keeps that rule ([design](../design/work.md)). From `pairz`: - **`personOf(actor)`:** the person whose work this is, the one acting or the one found along `for`, then `via`. Read it instead of `ctx.actor.id`, which for an agent is the agent's. - **`principalOf(actor)`:** the person or contact the work is for. - **`whereOf(actor)`:** its `in`, if it has one. - **`onBehalf(actor)`:** whether a person's work is done for them rather than by them: through a key, set going by a routine, or by code acting as them for an agent. ## Who may call: `allow` An Action's `allow(actor, input, ctx)` says who may call it. It may return a boolean or a promise of one. The runtime asks it wherever an actor calls. `ctx.db` reads as the caller, before any grant. When checking an agent and its principal, each check reads as the actor being checked, in the caller's place. The table uses the Action's own rule or the default its plugin declares. | Where the call comes from | `allow` asked | Without an `allow` | | --------------------------------------------------------------------------------- | ------------- | ---------------------------- | | outside: `runtime.call` with an actor, the REST API, the socket, a View's handler | yes | refused | | code acting for an actor: `ctx.call` in an Action, a Processor or a tool | yes | runs: the Action is internal | | a timer an actor set | yes | runs | | a read calling an unrecorded Action (`ReadContext.call`) | yes | runs | | the system, a grant, or code with no actor | no | runs | For an agent, it's asked twice: of the agent, then of whom it works for (`allows`). So a tool never calls what its agent's person couldn't. A key also calls only what its scope lists, from outside (`inScope`). Which documents a call then reaches is the rules' business, not `allow`'s. The helpers say what they mean for an agent: | Helper | Lets in | | ------------------ | -------------------------------------------------------------------------------------- | | `people` | a person, their key, their routines, and an agent working for a person | | `inPerson` | the person themselves: never a key, an agent, a routine's run, or code acting for them | | `contacts` | a contact, and an agent working for one | | `peopleOrContacts` | both | Say `inPerson` for what only the person decides: consent, keys, who's in a space, money, publishing. Say `people` for the rest. Pairz's own Actions do the same, and each plugin's page shows who may call each of its Actions. `chat.send` and `chat.attach` have a rule of their own: people and contacts writing as themselves, never an agent. ```ts import { type Actor, createRuntime, defineAction, definePlugin, inPerson, people, personOf, } from "pairz"; import { memoryStore } from "pairz/stores/memory"; const notes = definePlugin({ name: "notes", collections: { note: { schema: { type: "object", properties: { text: { type: "string" } } } } }, actions: { "note.add": defineAction({ input: { type: "object", properties: { text: { type: "string" } }, required: ["text"] }, allow: people, // a person, their key, or an agent working for one run: (ctx, { text }) => ctx.db.collection("note").insertOne({ text, by: personOf(ctx.actor) }), }), "note.clear": defineAction({ input: { type: "object" }, allow: inPerson, // the person themselves, never on their behalf run: (ctx) => ctx.db.collection("note").deleteMany({}), }), }, }); const runtime = await createRuntime({ store: memoryStore(), plugins: [notes] }); const ana: Actor = { kind: "person", id: "ana", in: "launch" }; const north: Actor = { kind: "agent", id: "north", for: ana, in: "launch" }; for (const [who, actor] of [["ana", ana], ["north for ana", north]] as const) { for (const action of ["note.add", "note.clear"]) { const outcome = await runtime.call(action, { text: "Call Bruno" }, { actor }) .then(() => "ok", (error) => error.code); console.log(`${who}, ${action}: ${outcome}`); } } await runtime.close(); ``` It prints: ``` ana, note.add: ok ana, note.clear: ok north for ana, note.add: ok north for ana, note.clear: forbidden ``` **Going beyond is a named grant.** Trusted code that must do what its actor couldn't acts as the system, for one reason: `ctx.as(grant("availability"))`. What it does is recorded as the grant, `via` whose work it was and `in` where. A Processor that acts on its own, for nobody, declares its grant ([`as`](#processors)), with no `via`. The owner counts a grant's ops in `pairz.elevated.ops`, by grant. A model never holds one: your code decides what leaves it. Pairz's own are `chat.hand-over`, `chat.hand-back` and `web.budget`. ```ts run: async (input, ctx) => await ctx.as(grant("availability")).call("slots.all", { in: ctx.in }), ``` Queries and events have an `allow` too, asked only from outside. A query declared as a bare function uses its plugin's default, or is the system's when there is none. No actor emits an event without `allow` from outside, and a key emits none. ## A plugin A plugin is a plain object. `definePlugin` only types it. | Field | What it declares | | ------------- | -------------------------------------------------------------------------------------------- | | `name` | its name | | `requires` | the plugins it builds on, by name: the runtime doesn't start without them | | `collections` | its collections, and indexes it adds to another's (`{ usage: { indexes: [["tags.app"]] } }`) | | `defaults` | `{ allow }` supplies the rule for this plugin's Actions and named queries that omit one | | `actions` | what can be done | | `events` | the events it emits, beyond its collections' changes and its Actions' lifecycle | | `processors` | what happens when events happen | | `views` | how its data shows, by name; `null` removes an earlier plugin's View | | `resources` | configuration, by kind and name | | `adapters` | implementations of a port, by port and name | | `schedules` | Actions time calls (see [Schedules](#schedules)) | | `check` | a startup check of the merged configuration it understands | | `guard` | the rules: who reaches which documents | | `labels` | what reads reveal, carried to what the same job writes | | `workers` | kinds of worker: programs that do its work but aren't plugin code (a computer) | | `routes` | its HTTP, by `URLPattern` pathname | | `who` | who a request is, by a credential it knows | Plugins merge in order. Collections, Actions, events, Processors and kinds of worker are unique: a second of one name stops the runtime from starting. Resources and schedules patch: a later plugin's entry merges into an earlier one's (JSON Merge Patch: objects merge, `null` removes, the rest replaces). A later View, adapter or route replaces an earlier one of its name. Every plugin's `guard` restricts together, the first `who` that answers wins, and the last `labels` is the one. ### Collections Give `defineCollection` the type of one document. In a plugin assembled by `pairz gen`, the compiler writes the JSON Schema that checks writes through the MongoDB collection API. ```ts import { defineCollection } from "pairz"; interface Order { customerId: string; /** @minimum 1 */ quantity: number; } export default defineCollection({ indexes: [["customerId"]] }); ``` Queries and reads of `ctx.db.collection("order")` see `Order & { _id: string }`. Leave `_id` to the runtime. An explicit schema wins, and `Infer` names its document type. Use `string` with `/** @format date-time */` for timestamps. The compiler refuses `Date` because documents travel as JSON. [A collection from its type](guides/the-compiler.md#a-collection-from-its-type). | Field | What it does | | --------- | ------------------------------------------------------------------------------------------- | | `schema` | the JSON Schema every write keeps to: inserts, replaces, and what updates set and leave | | `queries` | named reads: a function, or `{ allow?, description?, input?, run }` for actors from outside | | `vectors` | fields holding embeddings, kept as the store's vectors and searched with `nearest` | | `indexes` | lists of scalar fields to find by (`[["thread", "at"]]`), made as the store opens | | `private` | fields only trusted code reads: an actor's queries and Views get the documents without them | | `records` | `true`: a ledger, appended to and never changed, whose documents are their own record | | `durable` | `false`: kept in the owner's memory, never in the store, with no events | | `events` | `false`: its writes record no events | `ctx.db.collection(name)` has `insertOne`, `insertMany`, `find` (a cursor), `findOne`, `countDocuments`, `updateOne`, `updateMany`, `replaceOne`, `deleteOne`, `deleteMany`, `aggregate`, `nearest(vector, { filter, limit })` and `query(name, params)`. - **Filters:** `$eq`, `$ne`, `$gt`, `$gte`, `$lt`, `$lte`, `$in`, `$nin`, `$exists`, `$elemMatch`, `$and`, `$or`, `$nor`, `$not`, and `$regex` with `$options` `i` (ignore case) and `s` (`.` matches line breaks): the part of JavaScript's patterns every store reads alike, matched in linear time, so any caller may send one. Escape text meant literally (`RegExp.escape(text)`). A pattern ignores case, not accents: search a folded copy of the field for that. The [stores' README](../stores/README.md#text-patterns) has what's in the subset, its limits, and the folded copy. - **Updates:** `$set`, `$setOnInsert` (only when an upsert makes the document), `$unset`, `$inc`, `$mul`, `$min`, `$max`, `$push` and `$addToSet` (each with `$each`), `$pull`; `upsert`. An update needs its operators: one with none is refused, as MongoDB refuses it (`replaceOne` replaces a document). It's checked against the schema as MongoDB's `$jsonSchema` validator checks with `validationLevel: "strict"`: what it sets must fit each field, it can't set a field the schema doesn't allow or unset a required one, and the documents it leaves (an upsert's new one too) must be valid. What fails changes nothing (`invalid`, naming the field). - **Where it differs from MongoDB's `"strict"`:** a document that wasn't valid before (stored before its schema said what it says now) may still be updated, as long as the update adds nothing wrong to it; MongoDB would refuse until the update made it valid. Every store can tell that alike, PostgreSQL's single-statement updates included, which never see the document. There's no `"moderate"` level: fix such documents (a migration) rather than leave updates unchecked. - **A schema failure names its field:** `detail.field`, a dot path (`price`, `meta.a`, or the required field that's missing). A write from outside (REST, the socket, a View's handler) says it to its caller, as a public failure, so a form shows it by its field; plugin code's is its own to say. - **`$push` and `$addToSet` take `$each`;** other modifiers (`$slice`, `$sort`, `$position`) are refused, not ignored. - **Finds:** `sort`, `limit`, `skip`, and `projection` (`{ name: 1 }` keeps fields, `{ data: 0 }` leaves them out), applied before any large value is loaded. - **Aggregates:** `$match`, `$group` (with `$sum`, `$count`, `$avg`, `$min`, `$max`), `$sort`, `$skip`, `$limit`, run in the store. - **Unanswered writes:** `{ writeConcern: { w: 0 } }` sends a write with the next op or the commit, so it costs no round trip of its own. Plugin code runs any named query, as whoever it acts for, under the rules. From outside, `runtime.query("message.history", params, { actor })` runs only a query whose `allow` lets them in. A query is named under a collection, usually the one it reads. A plugin whose queries read only other plugins' collections (reports) declares a collection of its own to name them under: one that holds no documents costs nothing. **Secrets** go in a `private` field: a token, an API key, an SMTP password. No event holds it, so the log keeps the document without it (an update's `changed` may name the field, never its value). An actor's queries and Views read the document without it, and REST and the socket never read, filter by or write it. Actions and Processors read it. A path names the same field in every document, so settings kept as key and value documents (`{ _id: "smtp_pass", value }`) keep their secrets in a collection of their own, with `private: ["value"]`, beside the one for the rest. An Action whose input or result holds a secret says so in its own `private`: the log keeps its call without it, and a result that had one is kept whole apart (`sys.results`), so a retry answers with all of it. Maintenance SQL goes around all of this: it reads the store as it is, and records each write's statement and params, so a secret is written through an Action, never through SQL. ### Actions An Action names something a caller can do. In a plugin built by `pairz gen`, type the second parameter of `run`. ```ts import { defineAction } from "pairz"; export default defineAction({ description: "Calculate an order line's total in cents.", run: (_ctx, input: { /** @minimum 1 */ quantity: number; /** @integer */ unitPrice: number; }) => input.quantity * input.unitPrice, }); ``` The generator puts the JSON Schema in the plugin's `mod.ts`. Each caller gets the same input check, and tools see the field descriptions. The app needs `typescript` as a devDependency to generate the schema. The annotation also types the input in `allow(actor, input, ctx)`. Generation refuses `Date`; use `string` with `/** @format date-time */` for a JSON timestamp. [An Action’s input from its type](guides/the-compiler.md#an-actions-input-from-its-type). A hand-written `input` always wins. With a hand-written `mod.ts`, supply `input` yourself. | Field | What it does | | ------------- | --------------------------------------------------------------------------------------------------------------------- | | `input` | JSON Schema, inferred in `run` and `allow`. Omit it for an empty call or a compiler-generated input | | `allow` | who may call it (see [Who may call](#who-may-call-allow)); falls back to the plugin's `defaults.allow`, then internal | | `run` | `(ctx, input) => result`: what it does | | `description` | what it does, for people and for tools that list Actions | | `record` | `false`: unrecorded. It runs inline in its caller's job, with no events and no commit of its own | | `private` | fields its calls are recorded without, as dot paths, in its input and its result | | `atomic` | `true`: it does only what commits with a transaction, so another's `tx.call` runs it there | | `as` | a named system grant for `run`, e.g. `"inventory-adjust"` | | `transaction` | `true` runs the whole Action in one transaction and allows `tx.call` to join it | Every recorded call is on the record (`action.started`, then `action.completed` or `action.failed`), retryable by id, and everything it causes is its caller's, where its caller is. Queries, Views and startup checks may call unrecorded Actions, read-only. One that acts as someone else (`ctx.as`) reads as them there too, as when an Action calls it; a startup check, which reads nothing, refuses. #### Nested calls and retries Code calls another Action with `ctx.call(action, input)`, or `tx.call` in a transaction. A recorded nested call is kept under an id that names its caller, the Action, how many calls of it with the same input the caller made before, and its input's hash: `.#.`. The caller is the call's own id, `:` in a Processor's delivery, and `/` in `ctx.branch(key)`. An unrecorded Action's calls are its caller's. A call retried with its id (`runtime.call(…, { id })`, a timer's occurrence, a Processor's delivery after a failure or a restart) has `ctx.retry` true. Each nested call that completed answers its recorded result without running again, and one that didn't complete runs. ```ts import { defineAction, people } from "pairz"; export default defineAction({ allow: people, input: { type: "object", properties: { order: { type: "string" } }, required: ["order"], } as const, run: async (ctx, { order }) => { // Refused for some callers. On a retry, the calls after it are found either way. await ctx.call("discount.apply", { order }).catch(() => null); await ctx.call("inventory.reserve", { order }); return ctx.call("invoice.create", { order }); }, }); ``` - **Calls of other Actions or inputs don't move it.** One refused or allowed on the retry, one added, or calls that start in another order (each after a read) leave it where the retry finds it. - **Identical calls are matched in the order they're made.** The same call twice is two calls, `#1` and `#2`; a retry answers both from their records and runs a third if the code makes one. An identical call made earlier takes the lower number. So code that calls a failed Action again itself (a retry loop of its own) charges twice when its caller is retried: the first call failed, so it runs again, and the second answers from its record. Let the failure fail the caller, and retry the caller. - **Refusals.** A call a synchronous `allow` refuses takes no number and records nothing: the same call made next (through a grant, `ctx.as(grant(…)).call(…)`) takes the number, and a retry finds it whichever way the permission went. A call an asynchronous `allow` refuses keeps the number it took before waiting, so the same call made after it as a fallback can run once more on a retry whose permission went the other way. So can it under a rule that answers at once on one attempt and after a wait on another (a cached answer), even with no change in permission. Who makes a call isn't part of it: calls that differ only by who makes them (`ctx.as(person).call(…)` for each of several people) must carry that difference in their input (`{ order, by: person.id }`), or a retry can answer one person's call from another's record. - **A changed input is a new call:** the hash covers the whole input, private fields too. Keep a nested call's input the same across attempts: a time or a random id in it comes from the caller's input, not from the clock. - **Processors are apart.** Two Processors handling one event never share a call's record or a timer. A Processor's name is part of its calls' ids, and its position is kept by name: renamed, a Processor replays the log from the start, and its nested calls run again for every event it replays. To rename one, let it catch up first (its lag 0, `pairz.processor.lag`), then deploy the new name with `start: "now"`. - **`ctx.branch(key)`** keeps identical calls of concurrent work apart (each of a step's tool calls), when they may start in another order. - **Names.** `:` and `/` join a caller's parts, and no name is checked for them: a Processor named `a/k` and Processor `a`'s branch `k` name the same caller, and so can an event id and a Processor name with `:` in them. Keep `/` and `:` out of Processor names, branch keys and the event ids you give. - **The id is the log's, not an API.** Read a call's `cause` and `data.action`, not the id's parts. #### Actions with no parameters Omit `input` to accept either `runtime.call("order.expire")` or `runtime.call("order.expire", {})`. Extra fields, arrays and `null` fail the input check. Tools see a closed, empty object schema. ```ts const expire = defineAction({ run: (ctx) => ctx.db.collection("order").updateMany( { status: "draft", expires: { $lt: new Date().toISOString() } }, { $set: { status: "expired" } }, ), }); ``` #### One permission check for Actions and queries A plugin can set `defaults: { allow: people }` in `definePlugin`, or in the default export of its `plugin.ts`. `people` lets in a signed-in person and what acts for them (their keys, agents and routines); use `inPerson` for the person themselves only (see [Who may call](#who-may-call-allow)). This applies to its own Actions and named queries, including bare query functions. An explicit `allow` replaces the default. Plugin code calling a collection's query directly keeps the existing query rules. A query's `allow` controls callers from outside. For inventory staff, put the check in the plugin's `lib/`. Each permission document names the person, module and space. Its collection's guard controls who can read or change it. ```ts import { type Actor, type AllowContext, people, personOf } from "pairz"; export const canUse = (module: string) => async (actor: Actor, _: unknown, ctx: AllowContext) => people(actor) && !!ctx.in && !!await ctx.db.collection("permission").findOne({ person: personOf(actor), module, in: ctx.in, }); ``` #### A grant and a transaction for the whole Action Consider issuing one unit of a product. With an explicit check, grant and transaction the Action reads like this (`input` is the schema shown below). ```ts const issue = defineAction({ input, allow: people, run: async (ctx, { product }) => { if (ctx.actor && !await canUse("inventory")(ctx.actor, {}, ctx)) { throw forbidden("Inventory access required"); } return ctx.as(grant("inventory-adjust")).transaction(async (tx) => { const { matchedCount } = await tx.db.collection("product").updateOne( { _id: product, in: ctx.in, stock: { $gte: 1 } }, { $inc: { stock: -1 } }, ); if (!matchedCount) throw failure("invalid", "No stock here.", { public: true }); await tx.db.collection("movement").insertOne({ product, quantity: -1, in: ctx.in }); }); }, }); ``` With the same schema and stock rule, the plugin can share its admission check. TypeScript infers `product` as a string. For a schema kept in its own variable, use `as const` to keep its literals. ```ts import { defineAction, definePlugin, failure } from "pairz"; import { canUse } from "./lib/can-use.ts"; const input = { type: "object", properties: { product: { type: "string" } }, required: ["product"], additionalProperties: false, } as const; const issue = defineAction({ input, as: "inventory-adjust", transaction: true, run: async (ctx, { product }) => { const { matchedCount } = await ctx.db.collection("product").updateOne( { _id: product, in: ctx.in, stock: { $gte: 1 } }, { $inc: { stock: -1 } }, ); if (!matchedCount) throw failure("invalid", "No stock here.", { public: true }); await ctx.db.collection("movement").insertOne({ product, quantity: -1, in: ctx.in }); }, }); export const inventory = definePlugin({ name: "inventory", defaults: { allow: canUse("inventory") }, actions: { "stock.issue": issue }, }); ``` The literal in `as` declares the grant, just as `grant("inventory-adjust")` names it in code. The Action's lifecycle events name the caller. Its writes name the system grant, with the caller in `via`, the place in `in`, and the Action's call id as their cause. `transaction: true` opens a transaction on a direct call and joins an existing one through `tx.call`. A throw rolls back the writes. A recorded failure still has its own failure record. Nested `ctx.transaction` joins it. Inside it, `ctx.call` can call Actions declaring either `transaction: true` or `atomic: true`. Streams, fetches and worker calls are refused there. Use `atomic: true` alone to let an Action join a caller's transaction while keeping ordinary calls as they were. A read-only query or View can't start a transactional Action. A transaction also holds writes to collections declared `durable: false`: its reads see them, and they take effect only when the durable commit does, so a failed write rolls back both kinds (with `transaction: true` and `ctx.transaction` alike). A declared grant's reads are asked of the labels (`elevate`) on every path (a direct call, a named query, a watched query), and a `ctx.record` append is kept as the identity that made it, the grant included. ### Processors What happens when events happen: ordered per key, at least once, from a durable cursor. | Field | What it does | | ------- | ----------------------------------------------------------------------------------------------- | | `on` | the event types it handles | | `where` | a MongoDB filter on the event's data: the owner never dispatches the events it skips | | `key` | `(event) => key`: events of one key run in order, and different keys run at once | | `as` | a named grant it runs as, on its own authority, instead of as the event's actor | | `start` | `"now"`: new, it starts at the log's end. Without it, a new Processor starts at the first event | | `run` | `(ctx, event) => …`, as the event's actor (or its grant), where the event was | **`as: ""`** runs it as `{ kind: "system", id: "", in }`, for nobody: with no `via`, where the event was. Use it for what the app's own rules decide when an event happens, whoever's event it is. Its writes and calls are on the record as the grant, each caused by the event it handled, and the owner holds its deliveries to the grant. It reads as the grant too, past every rule: it no longer reads as the event's actor. To read as them, say so: `ctx.as(event.actor).db.collection(…)`. What the event says is still its actor's (a customer's message, an agent's reply): decide on it by the app's rules, and never do what it asks because it asks. A name that isn't one (empty, not a string) stops the runtime from starting. ```ts processors: { "order.flag": { on: "order.created", as: "order-review", run: async (ctx, event) => { const order = event.data.doc as { _id: string; total: number }; if (order.total > 10_000) await ctx.call("order.hold", { order: order._id }); }, }, }, ``` **`start: "now"`** is for a Processor added to an app whose log already holds events it shouldn't act on, such as one that sends messages. With no position of its own yet, it starts at the log's end, and that position is saved before anything is delivered to it, so a crash before its first delivery doesn't move it later. It covers the first run only. A saved position is never moved: after downtime, a Processor still gets every event it missed, at least once. So an effect that mustn't happen late checks `event.at` itself. Each store has its own log, so in a pool of runtimes each starts at its own end, when it's first opened with the Processor. ### Events a plugin declares `events: { "booking.confirmed": { schema, description?, allow? } }`. Code emits one with `ctx.emit(type, data)`, in the job's commit. Emitting a type nobody declared fails, so every event is in some plugin's contract. `allow` says who may emit it from outside (`runtime.emit`, a View's handler). The runtime's own events (`.created`, `action.…`, `processor.…`) can't be declared. ### Views How data shows in one place, found by name: `(item, ctx) => what it shows`. Text for a model, Ink elements in the terminal, React in the browser. A name says what it shows (`booking`, `tool:book`, `context:today`), and a place prefixes it where the same thing shows in several (`llm.message`, `web.message`, `terminal.message`). The shells ask for their own default when a name has no View (`web.default`, `terminal.default`). - **Reads** inside a View return at once, as `{ status: "loading" }` or `{ status: "ready", value }`. The runtime runs the View again until a pass reads nothing new. - **`ctx.show(name, item, hints?)`** shows exactly the View it names. Observed, the shown View is a part that runs again on its own. - **A handler writes with the View's collections:** `ctx.db.collection(name)` has `insertOne`, `updateOne` (an update document, or the fields to set), `replaceOne` and `deleteOne`, each a write of the viewer's own, as REST and the socket write it: a rule must speak for the collection's writes, the schema checks it, and it's recorded as theirs. A View writes nothing while it renders, nor when it's rendered once. - **`ctx.call`** and **`ctx.emit`** act from a handler, as the actor looking. A handler that needs what the View didn't read (suggestions as someone types) calls an unrecorded Action (`record: false`, with an `allow`) that runs the query and returns it: nothing goes on record. It reads as Actions do, private fields included, so it returns only what its caller may see. - **`runtime.render(name, item, { viewer?, hints? })`** renders once, as the system. Code renders with `ctx.render`, as its actor: a turn renders its agent's prompt, the `llm.thread` View, that way. - **`runtime.observe(name, item, { actor?, viewer?, hints?, part? })`** keeps one live: it runs again when a commit changes a document it read. Its `ready` is the first output, and `close()` stops it. [How Views run](architecture/views.md) is in the architecture. ### Resources and adapters - **Resources** are configuration as named plain objects, by kind: `agents`, `tools`, `provider`, `shared`, `theme`. The runtime gives them no meaning. A plugin reads the kinds it understands, and a later plugin patches an earlier one's entries, so an app changes one agent's `effort` without redefining it. - **Adapters** are implementations of a port, by port and name: `llm.openai`, `embeddings.hash`, `email.resend`, `email.smtp`, `email.sendmail`. A later plugin's adapter of a name replaces an earlier one's. ### Routes and `who` `runtime.fetch(request)` answers HTTP: its own paths (`POST /connect`, the socket at `/oxian`, the REST API at `/api/`) and plugins' routes. Hosts only listen: `Deno.serve(runtime.fetch)`, or `listen(runtime.fetch)` from `pairz/web/node`. - **A route** is `(request, ctx) => Response`, keyed by a `URLPattern` pathname (`/hooks/whatsapp/:name`). Its `ctx` has `runtime` (trusted code), `actor` (who the request is), `params`, `cookies` and `upgrade`. Routes deal with HTTP, and Actions do the work. A thrown `failure`'s code answers as its status: 400, 401, 403, 404, 429, else 500. - **A route's WebSocket:** `ctx.upgrade({ protocol? })` takes the request's upgrade and gives `{ socket, response }`. The route answers with `response` as it is, and `socket` is a browser's `WebSocket` for events, `send`, `close` and `bufferedAmount`. `protocol` is the one the route speaks of those the request offers. A request that isn't an upgrade, or doesn't offer `protocol`, throws `invalid` (400). `Deno.serve(runtime.fetch)` and `listen` complete it. Under `listen`, a message is 256 KiB at most, and the socket closes (1009) when more than 1 MiB waits to reach a slow client. - **`who`** is `(request, ctx) => actor`, from a credential its plugin knows (a session's cookie, a key in `Authorization`). The runtime asks each plugin's in order, and the first that answers wins. A request nobody's `who` answers is `{ kind: "anonymous", id: "" }`. - **Cookies** are set and read by plain name through `ctx.cookies`, and the runtime names them (`__Host-` wherever they're Secure). ### Rules: `guard` and `labels` - **`guard(actor, { collection, access, write?, filter, direct? }, ctx)`** returns the filter an actor's documents must match. Reads and deletes reach only what matches it. Inserts, and what updates leave, must match it. `true` restricts nothing, and `undefined` means the collection has no rule. `write` says which write it's asked about (`"insert"`, `"update"`, `"replace"`, `"delete"`); a rule may throw to refuse one. The owner asks it on every op an actor's work makes. A collection no rule speaks for never reaches an outsider's own reads and writes (REST, the socket, a View's handler). - **`byCollection({ sale: …, item: … })`** makes a plugin's guard of a rule per collection, answering nothing (`undefined`) for any other. - **`labels`** carries what a job read (a document's space) to what it then writes, so an answer drawn from a space not everyone sees is marked. Work done for someone from their own Personal space carries nothing: it's theirs. - **`labels.elevate(actor, allow, ctx)`** is asked when trusted code goes beyond the actor it acts for (`ctx.as`, an Action's `as`), with that actor and the Action's `allow`. `true` lets it go on. `false` refuses it: `"" goes beyond what the actor it acts for may do`. A string refuses it in the plugin's words for what it goes beyond: `"" goes beyond `. Code acting for nobody (a Processor's `as`) isn't asked. The access plugin declares both, for the collections its `shared` resource names. ### Workers `workers: { computer: { admit, ready?, gone?, workloads } }` declares a kind of worker that connects to the owner as executors do, presenting `:`. `admit`, `ready` and `gone` name Actions. Plugin code sends one jobs with `ctx.workers.dispatch(kind, id, workload, input)`, or `ctx.workers.call` for one JSON answer. One that isn't connected fails with `offline`. ### Startup checks `check(merged)` gets the merged `resources`, `adapters`, `views` (their names) and `actions`, and `call` for other plugins' unrecorded Actions (`models.check`). What it throws stops `createRuntime`, so a wrong model fails at start, not on the first turn. ## Contexts What plugin code gets. `Context` is an Action's, a Processor's and a tool's. | Field | What it is | | --------------------------------------- | ----------------------------------------------------------------------------------------------------------- | | `actor` | who this runs for, carried into everything it causes. None: the system | | `in` | where the work is: its actor's `in`. None: nowhere in particular | | `db.collection(name)` | the collection API. Each write commits on its own | | `call(action, input)` | calls an Action as `actor`, asking its `allow` | | `as(actor?)` | this context acting as someone else, or as the system (`as()`), or as a grant. Trusted code only | | `transaction(tx => …)` | several writes, events and timers, atomic; `tx.call(action, input)` runs an atomic Action in it | | `emit(type, data, { id? })` | commits a declared event | | `schedule(action, input, when)` | has time call an Action, and returns the timer's id; `unschedule(id)` removes it | | `record(collection, doc)` | appends to a ledger with the job's next write, kept even if the job fails | | `stream(channel)` | live frames for subscribers, never stored (tokens being written) | | `render(name, item)` | renders a View | | `graph` | `link`, `unlink` and `edges` between documents | | `branch(key)` | this context with its calls and timers named apart, for identical calls of work run at once | | `cancel(target)`, `disconnect(actor)` | stops a running call or delivery; ends an actor's browsers | | `workers`, `fetch`, `metrics` | workers by kind and id; the outside `fetch` (a test's fake, if given); counters, histograms and gauges | | `resources`, `adapters` | the merged configuration | | `describe()` | what the app declares, as `runtime.describe()`: its collections, Actions and Views by name, and resources | | `kept(key, work)` | what a rule works out, kept until a commit changes what it read. Only the owner keeps it; here it just runs | | `event`, `scheduled`, `retry`, `signal` | the event a Processor handles; the timer that called; whether this ran before; when to stop | A call another plugin may not offer, because this one doesn't `require` it, asks first: `if (ctx.describe().actions["register.clear"]) await ctx.call("register.clear", {})`. Calling an Action nobody declares fails with `invalid` ("Unknown action"), and that's a bug, not a way to ask. `ctx.as(other)` records what it does as `other`, `via` the actor it acted for, and stays where the work is unless `other` says where (`in`, or `in: undefined` for nowhere). `ctx.transaction` holds the store's writer: an op in it that fails, a write the rules refuse included, ends it and rolls it back, and one whose code sends no op for 5 seconds after its last answer rolls back too ([one writer](architecture/the-owner.md)). `tx.call` brings another plugin's atomic Action into it: its reads and writes are the transaction's, its own `ctx.transaction` joins it, and its failure rolls it all back ([another plugin's work in a transaction](architecture/the-owner.md#another-plugins-work-in-a-transaction)). The others are narrower: - **`ReadContext`** (a query's, a rule's): reads, never writes, with `actor`, `in`, `record`, `kept`, and `call` for unrecorded Actions. - **`ViewContext`:** reads that answer at once, `show`, and from handlers `call` and `emit`, with `actor`, `in`, `viewer` and `hints`. - **`ToolContext`** (chat's, in `pairz/plugins/agents`): a `Context`, so its `in` is where its chat is, plus `agent`, `thread`, `trigger`, `callId` (the idempotency key for what it does outside), and `ask` and `answer` to wait for a person's reply. ## The runtime ```ts const runtime = await createRuntime({ store, plugins }); ``` | Option | What it sets | | ----------- | --------------------------------------------------------------------------------------------------------------------------------- | | `store` | where it keeps everything: memory, SQLite or PostgreSQL | | `plugins` | the app: a list of plugins, which may nest | | `blobs` | where large values live (the store, by default); `blobThreshold`: past how many bytes (16 KiB) | | `warn` | what's told at startup of what looks wrong (a schema naming no fields…): the console by default, once a message; `false`, nothing | | `cache` | the owner's read cache (`{ documents, queries }`), or `false` | | `executors` | executors in this process (1); `transports` and `key` for others to connect | | `metrics` | where it records metrics (`createMetrics`) | | `clock` | what timers run on: the system's, or `manualClock(start)` in tests | | `fetch` | what `ctx.fetch` calls outside services with | | `browsers` | how much browsers may hold: sockets, tickets a minute, contacts' together | | Method | What it does | | --------------------------------------------------- | --------------------------------------------------------------------------------- | | `call(action, input, { id?, actor? })` | runs an Action; with `id`, a retry answers from the log | | `query(name, params, { actor? })` | runs a collection's named query | | `emit(type, data, { id?, actor? })` | commits a declared event | | `observe(name, item, options)` | keeps a View live | | `render(name, item, { viewer?, hints? })` | renders a View once, as the system | | `subscribe(listener)` | hears committed events and live frames as they happen | | `fetch(request)` | answers HTTP | | `bytes(collection, filter, field, { actor? })` | a value's `size` and `read(start, end)`; for an actor, only where a rule speaks | | `idle()` | resolves when no delivery or timer is pending and observed Views caught up | | `close({ drain? })` | stops, giving running work `drain` ms (5 s) to finish | | `cancel`, `disconnect`, `wake`, `stats`, `describe` | stops a call; ends an actor's browsers; fires due timers; counts; what's declared | Without `actor`, a call runs as the system. An actor's `in` says where. Nothing resets a runtime in place: its cache, Processors' cursors and timers all follow its store. To start over (a test against a running server), close it, empty its store (a new memory store, a new SQLite file, a dropped schema) and create another. In a pool of `runtimes()`, `close(id)` then `get(id)` starts one over, its `open` making the empty store: `get` waits until it has closed. The rest of `pairz`: - **Running many:** `runtimes(open)`, a pool of runtimes by id, each opened on first use and closed when idle ([many orgs](guides/many-orgs.md)). `createOwner` and `createExecutor` place the owner and its executors apart ([topology](architecture/topology.md)). - **The client:** `connect(url, { key?, over?, plugins? })` reaches an app over its socket or its REST API ([the REST API and the client](guides/rest-and-the-client.md)). - **Errors:** `failure(code, message, { public?, status? })`, `forbidden`, `invalid`, `isPublic`. Only a public error's words reach a caller outside. Over REST a failure answers a 4xx with its code (422 for an app's own, or the `status` it says), and an error with no code a 500 ([errors](guides/rest-and-the-client.md#errors)). - **Links and addresses:** `signLink`, `verifyLink`, `linksOf`, `clientAddress`, `callerOf`… - **Metrics:** `createMetrics`, `noMetrics` ([metrics](operations/metrics.md)). - **Time:** `manualClock`, `systemClock`. - **Checks:** `validator(schema)`, a JSON Schema check as the runtime runs them. ## Events The log records what happened, with no bookkeeping tables beside it. Every event has its `type`, `data`, `cause`, commit time (`at`) and actor, with `for` and `in`. | Event | When | Its data | | ---------------------------------------------- | -------------------------------------------------- | ------------------------------------------------------ | | `.created`, `.updated`, `.deleted` | a write changes a document, in its commit | `_id`, `doc`; an update also `changed`, `removed` | | `action.started` | a recorded call starts | `action`, `input`, `inputHash`, `startedAt`, `attempt` | | `action.completed`, `action.failed` | it ends | `action`, `result` or `error`, `ms`, `attempt` | | `action.retried` | a call runs again | `attempt`, `after`: `failed` or `lost` | | `processor.retried`, `processor.failed` | a delivery failed; the last one is the dead letter | `attempt` or `attempts`, `error`; `actor` on the last | | a declared event | code emits it | what its schema says | - **Collection writes:** the document after the write, the last version for a delete, without private fields. A write that changes nothing records nothing. `sys.` collections never record. - **Action calls:** `started` costs no commit of its own: it lands in the call's earliest commit, ahead of all its effects. An Action's `private` fields stay out of both `input` and `result`. - **Retries:** `runtime.call(action, input, { id })` is retryable. An id that completed answers its recorded result without running. One still running is joined. Otherwise the call runs again. An id reused for another action or input is refused (`id_conflict`). A call whose executor died fails with `executor_lost`. A nested call's id names its caller, the Action, its number among identical calls and its input, so a retry finds it wherever it's made ([nested calls and retries](#nested-calls-and-retries)). - **Timers:** an occurrence is the call `@`, and a failed one runs again as that same call. - **Causes:** every event names its cause, so the log is a tree you walk from any event back to the request that started it. - **Large values:** strings over 16 KiB are stored once, by the hash of their content, and documents and events hold a reference in their place. Plugin code never sees one, and a `$blob` key in what it writes is refused. - **Outside effects** (payments, emails): write the intent first, call out with its id as the idempotency key, then write the result. [The log and its Processors](architecture/events.md) are in the architecture. ## Schedules Time is a caller of Actions. A timer is a document in `sys.timers` naming an Action, its input and when to call it. ```ts schedules: { "usage.close": { cron: "10 0 * * *", call: "usage.close", input: {} }, heartbeat: { every: "5m", call: "health.check" }, "notes.migrate": { once: true, call: "notes.migrate", retries: 5 }, } ``` - **Declared:** by a cron expression (in a `timezone`, UTC by default) or `every` so long (`30s`, `15m`, `2h`, `1d`, or milliseconds), with `retries` (2). They patch like resources, and `null` removes one. At start the owner makes the timers what the plugins declare. A schedule calling an unknown Action, with input its Action refuses, or with a bad cron expression stops the runtime from starting. Declared ones run as the system. - **Run once:** `once: true` runs as soon as the owner starts with it (a deploy) and never again while it's declared as it is: its timer stays, without a time, as the record that it ran. Declared otherwise (another input), it runs again. One that didn't finish, its retries spent, gets another go each time the owner starts, until it's done. For migrations of what's kept: its Action must be safe to run again, as the owner may stop in the middle of it. Only the owner holding the store runs timers, so instances started together run it once. - **From code:** `ctx.schedule(action, input, { at | cron | every, id?, retries? })` sets a timer with the call's writes, and `ctx.unschedule(id)` removes it. In a transaction, `tx.schedule` commits with the rest. Scheduling an id again replaces its timer. Without an `id`, a timer is named by its place among the timers its caller set: `:timer.`, or `::timer.` for a Processor's, apart from another Processor's. A retry that sets the same timers in the same order replaces them rather than adding more. One that sets another first, or skips one, replaces the timer the first attempt set under that number, and the first attempt's timer under the next number stays, so it can fire twice. Give a timer an `id` when a retry may set it in another order. A declared timer can't be changed from code. - **As whom:** a timer set by an actor runs as them, where they were, and its call asks `allow`. - **Once:** the owner claims what's due in one commit and calls each occurrence as `@`, so an occurrence called twice runs once. A recurring timer that missed several times fires once, then keeps its beat. - **Retries:** a failed occurrence tries again after 10 s, 30 s, 90 s…, up to an hour apart. `action.failed` stays on record for Processors to answer. - **The clock is a port:** `createRuntime({ clock })`. `manualClock(start)` moves only when a test says so (`advance`, `set`). A host whose clock only rings, like a Durable Object's alarm, calls `runtime.wake()`. `pairz.timer.lateness` measures how late occurrences were called. ## Models and providers A model is `"provider/model"`, with its settings next to it. ```ts resources: { provider: { openai: { apiKey }, // the catalog knows its protocol and address deepseek: { apiKey }, // OpenAI-compatible, at api.deepseek.com local: { adapter: "openai-compatible", baseURL: "http://localhost:11434/v1" }, chatgpt: { adapter: "openai", catalog: "openai", headers: () => oauthHeaders() }, }, model: { cheap: { model: "openai/gpt-5.4-mini", effort: "low" } }, // aliases agents: { lead: { instructions, model: "openai/gpt-6.1-sol", effort: "low" }, // A list is tried in order when a model fails before writing anything. north: { instructions, model: ["chatgpt/gpt-6.1-sol", "anthropic/claude-opus-5-5"], effort: "low" }, }, history: { summarizer: "cheap" }, memory: { embedder: { model: "openai/text-embedding-3-small", dimensions: 512 }, extractor: "cheap" }, } ``` - **A `provider`** is an account or an endpoint: `baseURL`, `apiKey` (the provider's usual auth header), `headers` (added last; a function computes them per request, hearing whom the call is for), `adapter` (the protocol: `openai`, `openai-compatible`, `anthropic`, `gemini`, or a plugin's own), `catalog` (whose entries its models use, `false` for none), `options`, `tags`, `silence` and `retry`. - **The catalog** is a snapshot of [models.dev](https://models.dev). It fills in what a provider leaves out: its protocol and address, and each model's prices, limits and how its reasoning is controlled. - **Settings** sit next to a model, per port: `effort`, `maxTokens` and `temperature` for language models, `dimensions` for embeddings, and `options` (sent as they are) for all. Settings where a model is used win over an alias's, and a list entry's win over its list's. - **`effort`** is one scale for every provider: `none`, `minimal`, `low`, `medium`, `high`, `xhigh`, `max`. A level a model doesn't take stops the runtime from starting. - **Checked at start:** chat checks every agent's model, history its summarizer, memory its embedder and extractor, so a missing provider or a wrong effort fails `createRuntime`, not a turn. - **People's plans first:** a provider with `harness` is a person's plan that runs other providers' models (`claude-plan`, `chatgpt`): `harness: { order, serves, plan }`, where `serves` maps API ids (`"anthropic/claude-opus-5-5"`, or every one of a provider's, `"anthropic/*"`) to its own names (`"*"`: the same). A list given `harnesses` (a person's plans, in their order) runs each model on those that serve it first, model by model, then its own entries: `{ model: [opus, sol], harnesses: ["chatgpt"] }` tries `chatgpt/…sol`, then the Anthropic and OpenAI APIs. An entry naming a plan stands for its model on plans only. `models.check` answers what a list would try, in order. The tiers plugin gives each turn's chain its person's plans: see [Agents on people's own plans](guides/agents-on-peoples-plans.md#plans-first). Action inputs name models and never carry keys, because inputs are recorded. A plugin adds an adapter under `adapters.llm`, `adapters.embeddings`, `adapters.transcription` or `adapters.image`, named by the protocol it speaks. The [models page](reference/plugins/models.md) lists its Actions. ## Table exports, PDF images and barcodes | API | What an app gives it | | --------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `DataTable` from `pairz/web` | `formats` adds or replaces named serializers. `exportChoices` chooses a menu with custom names, `exportName` the file's base name, and `exportAll` all matching rows available to the table. `footerRows` holds totals by column key. | | `TableExportFormats` from `pairz/web` | A React context. Its `value` is the app's record of named formats. A table's `formats` takes precedence. | | `DataTable.toolbarContent`, `showSinglePageSize` | A React node places controls beside the built-ins. `toolbar={false}` hides the toolbar. The page-size flag also works on `Pagination`. | | `exportFile(format, sheet, name, options?)` | Gives `{ file, type, content }`. A `TableExportFormat` supplies `label`, `extension`, MIME `type` and `serialize(sheet, name, options)` returning text or bytes. Use `exportTableFile` with `options.formats` for custom names or raw scalar cells. Use `downloadTableFile` to save the file in a browser. | | `TableExportOptions` (DataTable’s `tableExportOptions`) | `csv` sets `quote`, `delimiter`, `lineEnding`, `finalNewline` and `header`. `json` takes `"records"` or `"table"`. `tableName` names the SQL table. `values: "raw"` reads a table's field values in place of column text. `pdf` holds `TablePdfOptions`. | | `tableSheet(columns, rows, footerRows?, values?)` | Pass the chosen columns in order. Gives `{ headers, keys, rows, footerRows }` for the serializers, with untitled columns omitted. Sheets made by hand need only `headers` and `rows`. | | `exportTableFile("pdf", sheet, name, { pdf })` | The file's content holds PDF bytes. Set `size`, `orientation`, `title`, `titleLines`, `subtitle`, `headerImage`, `columns` (width in points and alignment by key or in exported order), `fontSize`, `headerColor`, `headerText` and `stripeColor`. Totals come from the sheet. | | `pdfImage(bytesOrDataUrl)` | Resolves to a reusable `PdfImage`. In `drawDocumentPdf` draw `{ image, x, y, width, height }`. In a table header use `{ image, width, height }`. | | `ProductBarcode`, `barcodeBars(value, width?, options?)`, `barcodePng(value, options?)` | SVG, vector bars or PNG bytes. Each takes `format` of `"code128"` (default), `"code39"`, `"ean8"` or `"ean13"`. The same options work on a `drawDocumentPdf` barcode. `barcodePng` is async. | | `code128`, `code39`, `ean8`, `ean13`, `eanDigits` | The first four give alternating bar and space widths in modules. `code39(value, { check: true })` includes Mod 43. `eanDigits(value, length)` (8 or 13) completes or verifies an EAN. | An Action can make the same product file as the screen. The file functions live in `pairz/web/export`, with no React or browser setup. ```ts import { exportTableFile } from "pairz/web/export"; const stock = { headers: ["Product", "Units"], rows: [["Coffee", 12]], footerRows: [["Total", 12]], }; const file = exportTableFile("sql", stock, "stock-count", { tableName: "products" }); // stock-count.sql, with one INSERT into products per row, including the total. ``` The toolkit guide has examples of a custom file format, toolbar buttons, an invoice with a logo, and product labels. [Exporting a table](guides/the-web-toolkit.md#exporting-a-table) · [A toolbar of your own](guides/the-web-toolkit.md#a-toolbar-of-your-own) · [Printing a table](guides/the-web-toolkit.md#printing-a-table) · [Images and barcodes in a document](guides/the-web-toolkit.md#images-and-barcodes-in-a-document). ## The web's look and words - **The theme:** the web host owns a vocabulary of tokens and its defaults, which are Pairz's look. An app rebrands with a `theme` resource (`{ radius, font, logo, tokens, light, dark }`), applied from the first paint. `tokens` are the same on light and dark screens (sizes, radii); `light` and `dark` are each screen's colours. Besides the theme's own (`primary`, `border`…), each toolkit piece has tokens for its sizes and surfaces (`button-height`, `table-stripe`), with Pairz's values as defaults. The default fonts are served under `/assets/pairz/`. A theme's own come from Google Fonts or from the app's `page.assets`. - **The toolkit:** front ends compose the host's pieces (`Button`, `DataTable`, `DateRangePicker`, `Dialog`, `Stack`, `Grid`…) and write no CSS: the theme is their look. An app's own components, made of them, live in `lib/`. A route's own page uses them too (`routePage` from `pairz/web/server`, with `Screen` to centre a card in the window). [The web toolkit](guides/the-web-toolkit.md) shows every piece and lists every token. - **Words:** every word the web front ends show is English by key (`chat.send`), and an app changes any with a `words` resource. The keys and their English are in [WORDS.md](https://github.com/pairzhq/pairz/blob/main/hosts/web/WORDS.md). Blanks are `{name}`. Plurals are an object by the language's plural categories, chosen by `{count}`. Dates, numbers and currency follow the page's language, `page: { lang: "pt-BR" }`. - **Brazilian Portuguese** comes in the box: `ptBR` from `pairz/web/pt-br`, first among the page's plugins (`web({ plugins: [ptBR, webShell, …] })`), says every one of those words and the sign-in page's. The app's own plugins after it still have the last word. - **Your own front end** says its words the same way: `const say = defineWords("acme", { … })`, then `say("key", { name })`. [Serving on the web](guides/serving-on-the-web.md) shows the page, its theme and the sign-in page's words. ## Plugins Each plugin's page is read from the plugin itself: what it keeps, who may call each Action, where it shows, what it needs, and what it builds on. [The index](reference/plugins.md) lists them all, and `reference/plugins.json` has the same as data. - **Models:** [`models`](reference/plugins/models.md). - **Agents:** [`chat`](reference/plugins/chat.md) ([web](reference/plugins/chat-web.md), [terminal](reference/plugins/chat-terminal.md)), [`history`](reference/plugins/history.md), [`memory`](reference/plugins/memory.md) ([web](reference/plugins/memory-web.md), [terminal](reference/plugins/memory-terminal.md)) with [`memoryExtraction`](reference/plugins/memory-extraction.md), [`skills`](reference/plugins/skills.md) ([web](reference/plugins/skills-web.md)), [`routines`](reference/plugins/routines.md) ([web](reference/plugins/routines-web.md)), [`openapi`](reference/plugins/openapi.md), [`webTools`](reference/plugins/webTools.md). - **Access:** [`spaces`](reference/plugins/spaces.md) ([web](reference/plugins/spaces-web.md), [terminal](reference/plugins/spaces-terminal.md)), [`identity`](reference/plugins/identity.md), [`contacts`](reference/plugins/contacts.md) ([web](reference/plugins/contacts-web.md)), [`googleSignIn`](reference/plugins/google-sign-in.md), [`emailSignIn`](reference/plugins/email-sign-in.md), [`email`](reference/plugins/email.md), [`passwordSignIn`](reference/plugins/password-sign-in.md), [`devSignIn`](reference/plugins/dev-sign-in.md), [`accounts`](reference/plugins/accounts.md) ([web](reference/plugins/accounts-web.md)). - **Computers:** [`computers`](reference/plugins/computers.md) ([web](reference/plugins/computers-web.md), [terminal](reference/plugins/computers-terminal.md)). - **Billing:** [`usage`](reference/plugins/usage.md) ([web](reference/plugins/usage-web.md), [terminal](reference/plugins/usage-terminal.md)). - **The doors:** [`webPage`](reference/plugins/web-page.md), [`webShell`](reference/plugins/web-shell.md), [`webLines`](reference/plugins/web-lines.md), [`terminalPlugin`](reference/plugins/terminal.md), [`terminalShell`](reference/plugins/terminal-shell.md), [`api`](reference/plugins/api.md) ([web](reference/plugins/api-web.md)), [`mcp`](reference/plugins/mcp.md), [`whatsapp`](reference/plugins/whatsapp.md) ([web](reference/plugins/whatsapp-web.md)), [`voice`](reference/plugins/voice.md), [`maintenance`](reference/plugins/maintenance.md). From the [product packages](#product-packages): - **`@pairz/work`:** [`boards`](reference/plugins/boards.md) ([web](reference/plugins/boards-web.md)), [`documents`](reference/plugins/documents.md) ([web](reference/plugins/documents-web.md)). - **`@pairz/team`:** [`team`](reference/plugins/team.md) ([web](reference/plugins/team-web.md)), [`tiers`](reference/plugins/tiers.md) ([web](reference/plugins/tiers-web.md)). - **`@pairz/directory`:** [`directory`](reference/plugins/directory.md) ([web](reference/plugins/directory-web.md)) and what each org gets of it, [`directory.member`](reference/plugins/directory-member.md). - **`@pairz/billing`:** [`credits`](reference/plugins/credits.md) ([web](reference/plugins/credits-web.md)), [`stripe`](reference/plugins/stripe.md), [`stripeWebhook`](reference/plugins/stripe-webhook.md). [Installing a computer](guides/installing-a-computer.md) covers what an app serves for computers. --- Source: https://pairz.ai/docs/reference