Skip to content

Reference

What you import and what you declare, exactly. The entry points, the primitives a plugin is made of, who calls what for whom and where, the events the log keeps, schedules, and a page for every plugin.

On this page 24

This page lists what Copilotz 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 says how it runs. Every plugin Copilotz ships has a page of its own, read from the plugin itself.

Install

Start a new app with npx copilotz@1.0.0-rc.70 init orders. The starter includes the compiler, a plugin, a web page and tests. Start an app.

To add the runtime to an existing project:

Terminal
npm install copilotz@next                      # Node 24+ (npm, pnpm, yarn)
bun add copilotz@next                          # Bun
deno add jsr:@copilotz/copilotz@^1.0.0-rc.70   # Deno 2.9+ (or `deno add npm:copilotz@next`)

Until 1.0, the release candidates are on npm's next tag, and a plain npm install copilotz or deno add jsr:@copilotz/copilotz gets an older version. At 1.0, stable installs drop @next and the version.

On Deno, map the name in deno.json ("copilotz": "jsr:@copilotz/copilotz@^1.0.0-rc.70"), 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 Copilotz's version (npm install @copilotz/work@next, deno add jsr:@copilotz/work@^1.0.0-rc.70): see Product packages.

Entry points

The same names on npm (copilotz/…) and JSR (@copilotz/copilotz/…).

ImportWhat it has
copilotzthe runtime: createRuntime, definePlugin, defineAction, the access helpers (people, inPerson, grant…), connect (the client)…
copilotz/stores/memorymemoryStore(): in memory, the reference every store is held to
copilotz/stores/sqlitesqliteStore({ path }): one file, on node:sqlite or bun:sqlite
copilotz/stores/postgrespostgresStore({ url, schema, tenant }) (a server, or PGlite in the process), postgresPool, copyTenant, exportTenant, dropTenant
copilotz/stores/latencywithLatency(store, ms): a store with round trips, to measure
copilotz/blobs/filesfileBlobs({ dir }): large values as files
copilotz/blobs/httphttpBlobs({ url, headers }): large values in a bucket (S3, GCS, R2…)
copilotz/blobs/gcsgcsBlobs({ bucket, prefix }): large values in Google Cloud Storage, as the instance's service account
copilotz/plugins/modelsmodels: language models, embeddings, transcription and images, with the models.dev catalog
copilotz/plugins/agentschat and its tool, history, memory, memoryExtraction, skills, routines, openapi, webTools
copilotz/plugins/agents/webtheir web front ends: chatWeb, memoryWeb, skillsWeb, routinesWeb
copilotz/plugins/agents/terminaltheir terminal front ends: chatTerminal, memoryTerminal
copilotz/plugins/agents/<name>one of them alone, <name> being chat, history, memory, skills, routines, openapi, webtools
copilotz/plugins/accessaccess (spaces, identity, contacts), googleSignIn, emailSignIn, passwordSignIn, email, devSignIn, accounts
copilotz/plugins/access/webspacesWeb, contactsWeb, accountsWeb
copilotz/plugins/access/terminalaccessTerminal
copilotz/plugins/access/<name>one of them alone, <name> being spaces, identity, contacts, google, email (with passwordSignIn), dev, accounts
copilotz/plugins/billingusage: the ledger, and the port an app's pricing plugs into (spending)
copilotz/plugins/billing/webusageWeb
copilotz/plugins/billing/terminalusageTerminal
copilotz/plugins/computecomputers (people's machines, where agents work), and googleToken (Google's tokens, for Cloud Storage's blobs)
copilotz/plugins/compute/webcomputersWeb
copilotz/plugins/compute/terminalcomputersTerminal
copilotz/plugins/compute/downloadscomputerDownloads: the computer program's release, served by the app (Node)
copilotz/plugins/compute/programstartPool: the computer program's pool mode, in a process of the app's own (for an app that hosts computers)
copilotz/plugins/interfacesterminalPlugin (the terminal's data), api, whatsapp, voice, mcp, webLines (site chats), maintenance
copilotz/plugins/interfaces/webwebShell (the web's root View), apiWeb, whatsappWeb
copilotz/plugins/interfaces/terminalterminalShell: the terminal's root View
copilotz/plugins/interfaces/<name>one of them alone, <name> being mcp, api, whatsapp, voice
copilotz/plugins/<theme>/contracteach theme's plugins' contracts (access, agents, models, interfaces, compute): shapes, and the little code with them, for plugins built on them
copilotz/webthe web host in the browser (web), its toolkit (Button, Markdown…), what a widget asks (display, surface, remind)
copilotz/web/wordsthe words alone, without the toolkit: defineWords, wordsOf, formatDate…
copilotz/web/pt-brptBR: every word of the web front ends and the sign-in page in Brazilian Portuguese, as a plugin of the page's
copilotz/web/serverthe page's server half: webPage (the page, as a plugin), widgetsOf, routePage (a route's own page in the app's look)
copilotz/web/widgetthe widget host: an app's web Views inside an outside assistant (MCP Apps, ChatGPT)
copilotz/web/themethemeOf(plugins): the app's theme, for the page's first paint
copilotz/web/exporttable and document files on a server or in a browser: exportFile, tablePdf, documentPdf, pdfImage, bars, barcodePng
copilotz/web/nodelisten (serves runtime.fetch on Node and Bun, sockets included), bundle (the browser's code, with esbuild)
copilotz/terminalthe terminal host, terminal({ runtime, me }), and its toolkit
copilotz/exportersotlp, exposition: metrics out, the OpenTelemetry way
copilotz/testingone test API for Deno, Node and Bun: test, tempDir, serve, spawn, testWho, ticketFor, openTo, boundaries, createWorker…
copilotz/testing/wordstesting a front end's words (pseudoWords, englishLeft), and listing them (wordsList)
copilotz/describedescribe(plugin): what a plugin declares, as JSON

The browser loads only copilotz/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 (copilotz/plugins/interfaces) loads every plugin in it. A plugin's own (copilotz/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 Copilotz at its version: @copilotz/work@1.0.0-rc.70 goes with copilotz@1.0.0-rc.70. Each has the same entry points, its plugins (@copilotz/work), their front ends (@copilotz/work/web) and their shapes, for plugins built on them (@copilotz/work/contract), with the same names on npm and JSR.

PackageWhat it has
@copilotz/workboards (kanban) and documents (shared Markdown with versions and merges); boardsWeb, documentsWeb
@copilotz/directorydirectory: many orgs behind one address; directoryWeb, the org switcher, the org's page, staff's console
@copilotz/billingcredits (plans, credits, budgets), stripe, stripeWebhook; creditsWeb
@copilotz/teamteam (agents people make), tiers (the models an org's agents think with); teamWeb, tiersWeb

They import Copilotz 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 Copilotz, 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.

TypeScript
{ kind: "agent", id: "north", for: { kind: "person", id: "ana" }, in: "launch" }
FieldWhat it says
kind, idwho acts
forwhom an agent works for: a person or a contact
inwhere the work is: an opaque id, as id is. To the access plugin it's a space. None: nowhere in particular
viawhose work trusted code was doing when it acted as someone else (ctx.as)
key, scopea person acting through a developer key, and what the key may use
originwhat set a person's work going, such as a routine

The kinds the runtime makes or checks:

KindWhoMade by
personsomeone with an account, signed in or through their keyidentity; a key's by api
agentan agent, working for someone (for)chat, for each turn
contactsomeone outside the org: a WhatsApp customer, a caller, an MCP chatcontacts
systemtrusted code, which no rule restricts; a named grant is one toothe runtime: no actor, ctx.as(), grant
maintenancethe maintenance key, for support's SQLthe maintenance plugin's routes
anonymousan HTTP request nobody is signed in to (id: "")runtime.fetch, when no who answers

Each way in says where its work is:

Way inWho, for whomWhere (in)
The webthe personthe page's space: a call says it
A chat's turnits agent, for whoever started itthe chat's space
WhatsAppthe customer (a contact), or a linked personthe number's space, or the space they're in
Voicethe caller (a contact), and its agent for itthe line's space
A web line, an MCP linethe visitor or conversation (a contact)the line's space; a tool, where its chat is
A developer keyits person, through itthe key's space
The terminalits personwhere they work (/space, /work)
A routinewhoever made it, set going by it (origin)the routine's space
Handing work to a spacethe same personthe 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).

From copilotz:

  • 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 fromallow askedWithout an allow
outside: runtime.call with an actor, the REST API, the socket, a View's handleryesrefused
code acting for an actor: ctx.call in an Action, a Processor or a toolyesruns: the Action is internal
a timer an actor setyesruns
a read calling an unrecorded Action (ReadContext.call)yesruns
the system, a grant, or code with no actornoruns

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:

HelperLets in
peoplea person, their key, their routines, and an agent working for a person
inPersonthe person themselves: never a key, an agent, a routine's run, or code acting for them
contactsa contact, and an agent working for one
peopleOrContactsboth

Say inPerson for what only the person decides: consent, keys, who's in a space, money, publishing. Say people for the rest. Copilotz'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.

TypeScript
import {
  type Actor,
  createRuntime,
  defineAction,
  definePlugin,
  inPerson,
  people,
  personOf,
} from "copilotz";
import { memoryStore } from "copilotz/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), with no via. The owner counts a grant's ops in copilotz.elevated.ops, by grant. A model never holds one: your code decides what leaves it. Copilotz's own are chat.hand-over, chat.hand-back and web.budget.

TypeScript
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.

FieldWhat it declares
nameits name
requiresthe plugins it builds on, by name: the runtime doesn't start without them
collectionsits 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
actionswhat can be done
eventsthe events it emits, beyond its collections' changes and its Actions' lifecycle
processorswhat happens when events happen
viewshow its data shows, by name; null removes an earlier plugin's View
resourcesconfiguration, by kind and name
adaptersimplementations of a port, by port and name
schedulesActions time calls (see Schedules)
checka startup check of the merged configuration it understands
guardthe rules: who reaches which documents
labelswhat reads reveal, carried to what the same job writes
workerskinds of worker: programs that do its work but aren't plugin code (a computer)
routesits HTTP, by URLPattern pathname
whowho 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 copilotz gen, the compiler writes the JSON Schema that checks writes through the MongoDB collection API.

TypeScript
import { defineCollection } from "copilotz";

interface Order {
  customerId: string;
  /** @minimum 1 */
  quantity: number;
}

export default defineCollection<Order>({ 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<typeof schema> 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.

FieldWhat it does
schemathe JSON Schema every write keeps to: inserts, replaces, and what updates set and leave
queriesnamed reads: a function, or { allow?, description?, input?, run } for actors from outside
vectorsfields holding embeddings, kept as the store's vectors and searched with nearest
indexeslists of scalar fields to find by ([["thread", "at"]]), made as the store opens
privatefields only trusted code reads: an actor's queries and Views get the documents without them
recordstrue: a ledger, appended to and never changed, whose documents are their own record
durablefalse: kept in the owner's memory, never in the store, with no events
eventsfalse: 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 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 copilotz gen, type the second parameter of run.

TypeScript
import { defineAction } from "copilotz";

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. A hand-written input always wins. With a hand-written mod.ts, supply input yourself.

FieldWhat it does
inputJSON Schema, inferred in run and allow. Omit it for an empty call or a compiler-generated input
allowwho may call it (see Who may call); falls back to the plugin's defaults.allow, then internal
run(ctx, input) => result: what it does
descriptionwhat it does, for people and for tools that list Actions
recordfalse: unrecorded. It runs inline in its caller's job, with no events and no commit of its own
privatefields its calls are recorded without, as dot paths, in its input and its result
atomictrue: it does only what commits with a transaction, so another's tx.call runs it there
asa named system grant for run, e.g. "inventory-adjust"
transactiontrue 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: <caller>.<action>#<n>.<inputHash>. The caller is the call's own id, <event>:<processor> in a Processor's delivery, and <caller>/<key> 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.

TypeScript
import { defineAction, people } from "copilotz";

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, copilotz.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.

TypeScript
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). 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.

TypeScript
import { type Actor, type AllowContext, people, personOf } from "copilotz";

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).

TypeScript
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.

TypeScript
import { defineAction, definePlugin, failure } from "copilotz";
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.

FieldWhat it does
onthe event types it handles
wherea 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
asa 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: "<grant>" runs it as { kind: "system", id: "<grant>", 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.

TypeScript
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 (<collection>.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 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 copilotz/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 and cookies. 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.
  • 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-<name> 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: "<action>" goes beyond what the actor it acts for may do. A string refuses it in the plugin's words for what it goes beyond: "<action>" goes beyond <string>. 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 <kind>:<secret>. 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.

FieldWhat it is
actorwho this runs for, carried into everything it causes. None: the system
inwhere 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
graphlink, 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, metricsworkers by kind and id; the outside fetch (a test's fake, if given); counters, histograms and gauges
resources, adaptersthe 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, signalthe 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). 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).

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 copilotz/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

TypeScript
const runtime = await createRuntime({ store, plugins });
OptionWhat it sets
storewhere it keeps everything: memory, SQLite or PostgreSQL
pluginsthe app: a list of plugins, which may nest
blobswhere large values live (the store, by default); blobThreshold: past how many bytes (16 KiB)
warnwhat's told at startup of what looks wrong (a schema naming no fields…): the console by default, once a message; false, nothing
cachethe owner's read cache ({ documents, queries }), or false
executorsexecutors in this process (1); transports and key for others to connect
metricswhere it records metrics (createMetrics)
clockwhat timers run on: the system's, or manualClock(start) in tests
fetchwhat ctx.fetch calls outside services with
browsershow much browsers may hold: sockets, tickets a minute, contacts' together
MethodWhat 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, describestops 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 copilotz:

  • Running many: runtimes(open), a pool of runtimes by id, each opened on first use and closed when idle (many orgs). createOwner and createExecutor place the owner and its executors apart (topology).
  • The client: connect(url, { key?, over?, plugins? }) reaches an app over its socket or its REST API (the REST API and the client).
  • 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).
  • Links and addresses: signLink, verifyLink, linksOf, clientAddress, callerOf…
  • Metrics: createMetrics, noMetrics (metrics).
  • 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.

EventWhenIts data
<collection>.created, .updated, .deleteda write changes a document, in its commit_id, doc; an update also changed, removed
action.starteda recorded call startsaction, input, inputHash, startedAt, attempt
action.completed, action.failedit endsaction, result or error, ms, attempt
action.retrieda call runs againattempt, after: failed or lost
processor.retried, processor.faileda delivery failed; the last one is the dead letterattempt or attempts, error; actor on the last
a declared eventcode emits itwhat 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).
  • Timers: an occurrence is the call <timer>@<due time>, 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 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.

TypeScript
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: <call>:timer.<n>, or <event>:<processor>:timer.<n> 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 <timer>@<due time>, 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(). copilotz.timer.lateness measures how late occurrences were called.

Models and providers

A model is "provider/model", with its settings next to it.

TypeScript
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. 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.

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 lists its Actions.

Table exports, PDF images and barcodes

APIWhat an app gives it
DataTable from copilotz/webformats 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 copilotz/webA React context. Its value is the app's record of named formats. A table's formats takes precedence.
DataTable.toolbarContent, showSinglePageSizeA 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, eanDigitsThe 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 copilotz/web/export, with no React or browser setup.

TypeScript
import { exportTableFile } from "copilotz/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 · A toolbar of your own · Printing a table · 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 Copilotz'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 Copilotz's values as defaults. The default fonts are served under /assets/copilotz/. 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 copilotz/web/server, with Screen to centre a card in the window). The web toolkit 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. 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 copilotz/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 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 lists them all, and reference/plugins.json has the same as data.

From the product packages:

Installing a computer covers what an app serves for computers.