Declaring a package
A package is its tools, events, observables, and tables, plus the contracts it consumes and the contracts it provides. Those are the seams the Runtime checks; everything else is internal to the package. Building a package starts with that list, and so does reading one.
- Tools are calls in.
- Events are signals out.
- Observables are calls in and signals out for a single value.
- Tables are calls in and signals out over a collection of values of one type.
- Contracts let packages be built independently without breaking each other.
In code, src/package.ts lists those seams with definePackage from
@peers-app/peers-sdk/define, and the peers-package command turns the declaration into the
package's manifest. The manifest is plain JSON in Peers IR, so the Runtime learns what a package
declares without running any of its code. The same declaration is bundled for the sandbox, so
each tool's handler is registered under its declared name.
Every installed package uses this declaration model and is built with peers-package.
Start from the package template, or move an
existing package's declarations and handlers into src/package.ts.
A package with only screens
A package can provide no contracts. Keep its navigation, routes, and UIs, and omit
pkg.provides(...). For your own package, replace the example IDs with permanent values
generated once with newid(), keeping the same package and screen IDs across the examples:
import { definePackage } from "@peers-app/peers-sdk/define";
const packageId = "00mvvggkdhnt1sz53wxx4bza2";
export default definePackage((pkg) => {
pkg.packageId = packageId;
pkg.version = "1.0.0";
pkg.appNavs = [
{ name: "Games", iconClassName: "bi-controller", navigationPath: "games" },
];
});
Register the route and UI in their usual separate bundles:
import type { IPeersPackageRoutes } from "@peers-app/peers-sdk";
const packageId = "00mvvggkdhnt1sz53wxx4bza2";
const screenId = "00mvvggkdh1oak7q3f544nds7";
declare const exportRoutes: (routes: IPeersPackageRoutes) => void;
exportRoutes({
routes: [{ packageId, peersUIId: screenId, path: `package-nav/${packageId}/games`, uiCategory: "screen" }],
});
import type { IPeersPackageUIs } from "@peers-app/peers-sdk";
import { zodAnyObject } from "@peers-app/peers-sdk";
const screenId = "00mvvggkdh1oak7q3f544nds7";
declare const exportUIs: (uis: IPeersPackageUIs) => void;
exportUIs({
uis: [{ peersUIId: screenId, propsSchema: zodAnyObject, content: () => <p>Choose a game</p> }],
});
Build with peers-package build and build the routes and UIs as usual. With no tables,
provided contracts, or background hooks, this package runs no worker. Its screens can still consume
other packages' contracts through hostContract; declare those dependencies with
pkg.consumes(...). See Routes and UI for the complete screen setup.
UI calls currently act as the signed-in user. Peers checks pkg.consumes(...) for calls
from provider code; it does not yet enforce those declarations on UI hostContract calls.
Older versions of Peers refuse packages that provide no contracts. Update all of a group's devices to the current Peers before promoting one to beta or stable. A contract you do declare must still have at least one member.
App icons
Each entry in pkg.appNavs is one app on the Apps screen:
a name, an optional displayName, a Bootstrap Icons class in
iconClassName, its navigationPath, and an optional color for its icon:
pkg.appNavs = [
{ name: "Games", iconClassName: "bi-controller", navigationPath: "games", color: "violet" },
];
color names a color from the Peers palette, APP_COLORS in the SDK: blue, teal, red,
amber, purple, orange, green, pink, violet or slate. Each looks the same in light and
dark mode, and the icon's glyph is readable on it in both. An app without a color gets one
picked from its package id and name, the same on every device. peers-package build warns about
a name outside the palette, and the app is drawn in its picked color.
Peers 0.33.8 and earlier refuse a package whose app nav has color, or any other key they don't
know, so the package doesn't load there. Add color once every device that runs your package has
a newer Peers. Newer versions leave out app-nav keys they don't know, so a package built with a
later SDK still loads.
Layout
News, for example:
news/src/
consts.ts ids
package.ts the contract and the declaration
data/feeds.ts schema + table
data/headlines.ts schema + table
tools/refresh.tool.ts definition + handler
tools/headlines.tool.ts definition + handler
logic/feed-xml.ts parsing (internal)
contracts/voice-skill.v2.ts a generated copy of Voice Hub's declaration
ui/news.ts the UI's client for the contract
ui/… screens and widgets
Tables
A table is defined once, from a zod schema. The manifest carries its fields as Peers IR, and the
package's handlers use the same definition with a call's ctx:
// data/headlines.ts
import { defineTable, z, zodPeerId } from "@peers-app/peers-sdk/define";
export const headlineSchema = z.object({
headlineId: zodPeerId.describe("Headline id."),
feedId: z.string().describe("Feed this story came from."),
title: z.string().describe("Story title."),
link: z.string().optional().describe("Story URL."),
});
export type IHeadline = z.infer<typeof headlineSchema>;
export const Headlines = defineTable({
name: "Headlines",
description: "Latest stories fetched for the saved feeds.",
primaryKeyName: "headlineId",
schema: headlineSchema,
});
In a handler, Headlines(ctx) has get(id), list(filter?, options?), count(filter?),
findOne(filter?), save(row, options?), and delete(id). list takes the same filters and paging
options as any Peers table (Headlines(ctx).list({ feedId }, { page: 1, pageSize: 20 }));
page numbers start at 1. save parses
the row with the schema first, so defaults apply and an invalid row is rejected in the package.
An optional field saved as null or undefined is stored unset, a field with a default gets
the default, and reads leave unset fields out (Empty values). save resolves
to the row as stored. Its second argument accepts these options, enabled by setting them to true:
weakInsert: seed a default row that yields to any real write, even an older edit from another device that hasn't synced yet. It has no effect when updating an existing row.insertOnly: create the row if missing; otherwise leave it untouched and return the stored row. Combine it withweakInsertwhen seeding defaults.saveAsSnapshot: reset the whole row to this value, replacing earlier field changes from other devices even if they haven't synced yet. Later writes still win.restoreIfDeleted: save a row whose id was deleted before; without it, that save is refused.
In a filter, a field set to undefined matches rows where that field is empty, as null does:
list({ tag: undefined }) lists the untagged rows. Anywhere else, in options and in rows, a
field left undefined is left out.
One reply can carry about 16 MB. A list too large for that fails with an error that says so:
page it (list(filter, { page, pageSize })), or keep large values out of rows read many at a
time.
Rows read from storage and passed to a table override follow the same empty-value rule,
including nested fields written by an older package build.
The manifest types each field from its schema: an enum or a string literal is string, a
number or boolean literal is number or boolean, zodPeerId is id, and zodFileId is id
with subType: "file" (File fields).
Enum and literal fields declared with .nullish(), with empty or nested array elements, or with
a transform keep any, so the host can accept every value the schema allows. The manifest also
describes nested objects and enum values (Schemas in the manifest).
List a table on a contract (tables in defineContract) to expose it to
other packages and the UI, or on pkg.tables to keep it private. Pass localOnly: true to keep its rows on each device,
declare indexes for the fields you query by, declare the fields that hold
file ids, make each row its owner's with
signedBy, and raise versionNumber when its fields
or indexes change.
Every call on a table goes through the package, its own handlers' and its consumers' alike: a
UI's or another package's save reaches the package's table and is parsed with its schema, so
defaults apply to them too
(Every call goes through the package).
Indexes
indexes lists the fields your queries filter or sort by, each index in order. A field is its
name, or { name, order: "DESC" } for descending. An index only speeds up reads; it doesn't
change what a query returns:
export const Headlines = defineTable({
// …
versionNumber: 2,
indexes: [{ fields: ["feedId", { name: "publishedAt", order: "DESC" }] }],
});
Adding, changing or removing an index is a schema change, so raise versionNumber.
One row per key. Add unique: true to an index only on a localOnly table. Remove duplicate
values before adding it: if existing rows already repeat a value, the table's calls fail until a
later version removes the index. On a synced
table, two devices could each save a row the other's unique index refuses. To keep one row per
key on a synced table, derive the row's id from the key with idFromKey (on a
signed table, declare signedKey instead). Two devices saving the same key
then write the same row, and sync merges it:
import { idFromKey } from "@peers-app/peers-sdk/define";
await Stores(ctx).save({ storeId: idFromKey(`store:${name}`), name });
Start the key with what it identifies (store:), so ids for different kinds of rows can't
collide.
To seed a default row for a key:
await Stores(ctx).save(
{ storeId: idFromKey(`store:${name}`), name },
{ weakInsert: true, insertOnly: true },
);
Use both flags: insertOnly preserves a row already stored on this device, while weakInsert
lets an edit from another device win when it arrives, even if it was made before this seed.
A signed table refuses weakInsert, so don't seed its rows: read a missing
row as its defaults.
File fields
Declare a field that holds a System Files id with zodFileId, or an array of
them, so Peers knows which files your rows use:
import { defineTable, z, zodFileId, zodPeerId } from "@peers-app/peers-sdk/define";
export const Members = defineTable({
name: "Members",
description: "Family members.",
primaryKeyName: "memberId",
versionNumber: 2,
schema: z.object({
memberId: zodPeerId,
name: z.string(),
avatarFileId: zodFileId.optional().describe("The member's photo."),
attachmentFileIds: z.array(zodFileId).optional(),
}),
});
A zodFileId is a peer id like any other: it validates, filters and reads the same way.
Keep a file's id in one of these fields for as long as the row needs its contents. After the last declared reference goes, each device starts its own retention period before freeing unused contents. A reference added later can fetch them again from another device that still has them. See file retention and availability.
- Top-level fields only. A file id inside an object field, in a plain string field, or in a package variable doesn't count as a use. To attach several files to a row with details about each, give them a table of their own, one row per file.
- Synced tables only. A
localOnlytable doesn't keep files. Put the reference in a synced table so the other devices know the file is used too. - Raise
versionNumberwhen you change a field tozodFileId: it changes the table's definition. If a stable contract exposes the table, publish the changed table in a new contract version too. - The build warns when a top-level field is named like a file id (
avatarFileId,fileIds) but isn't azodFileId, and when azodFileIdis nested in an object field.
Signed tables
In a group, any Writer's device can change any row of an ordinary table, including rows other
members wrote. When each row should belong to one member, declare the table signedBy a
field that holds the owner's user id (a required zodPeerId). Add signedKey when each owner
has one row per key, such as one row per branch:
export const Refs = defineTable({
name: "Refs",
description: "Each member's published branch tips.",
primaryKeyName: "refId",
schema: z.object({
refId: zodPeerId,
ownerUserId: zodPeerId.describe("The member whose ref this is."),
repoId: zodPeerId,
ref: z.string(),
oid: z.string().optional().describe("Empty once the owner removes the ref."),
}),
signedBy: "ownerUserId",
signedKey: ["repoId", "ref"],
});
Peers then enforces ownership on every device:
- Only the owner writes a row.
savesucceeds only whenownerUserIdis the signed-in user; a row naming anyone else is refused withWrite not authorized. Peers signs the row with the user's key as it's saved, whoever saves it: your handlers, a UI, or another package through your contract. Your code never handles keys. The signer is always the user of the device the save runs on: a tool that other members call on this device (remote tool calls) saves rows as this device's user, not as its caller. - Peers sets each row's id from its owner. So another member can't claim an owner's row
id, even on a device that hasn't got that row yet. (Ids are 25 characters: a member who
chooses part of your key, such as a repository they created, and spends heavily on computing
could find a row of theirs with the same id. That would hide your row on some devices until
you change its key, but never change it.)
- With
signedKey, the id comes from the owner and the key fields. Saving the same key again updates that row, and each member has their own row for a key. Pass a fresh id fromnewid()or the id fromRefs.rowId({ ownerUserId, repoId, ref })when saving.rowIdapplies your owner and key field schemas assavedoes, including transforms, and gives the id to use forget. A row's key can't change: save a row under the new key, and mark the old one. - Without
signedKey, give a new row an id fromnewid()as usual. Peers stores the row under an id made from that id and the owner, andsaveresolves to the row with its id. Use the returned row's id for later saves once that row is available on the device. - Either way, use the id of the row
savereturns, not one you chose, to link other rows to it.
- With
- Other members' devices verify it. A row reaching a device through sync is stored only
when its owner is a Writer (or above) in the group and the signature checks out against the
owner's key. A row that was changed after signing, signed by someone else, signed by a
member who has since left or is only a Reader, or stored under an id that isn't its owner's
is refused, and the row on record stays as it was. A device that has a version of a row
refuses an older version, so a copy served again can't roll it back. A device that hasn't
stored the row yet may accept an old copy served as current, though, until the owner saves
again. If your package depends on order (a branch tip that only moves forward), keep a
counter in the row and don't act on a lower count than this device already has. Signatures
apply only to the table and context where the owner saved the row. When an owner rotates
their signing key (Identity), Peers updates their rows' signatures
for the new key. Only
signatureandsignedAtchange, but your watchers see those rows change. - Rows aren't deleted. A delete can't be signed, so
deleteis refused on a signed table, locally and from sync. To remove something, have the owner save the row with a field that says so, such asdeleted: trueor an emptyoid, and have readers skip those rows.
Reads work as before. Peers adds signature, signedAt, signedContextId, signedTableId,
and signedIdSeed; leave these out of your table schema and let Peers manage them. Consumers
don't need to declare these fields in their contract schemas. All text in a row, including
strings and keys inside object and array fields, must be well-formed Unicode. save refuses a
row with an unpaired surrogate, such as text cut in the middle of an emoji.
In the personal context, local saves still require the signed-in owner and are signed, and
delete is still refused. Synced writes between your own devices are unchecked, as for other
personal data.
A signed table can't be localOnly, and its primary key is a zodPeerId other than the owner
field (for one row per owner, use signedKey: []). Each signedKey field is a required
string, id, number, or boolean (an enum or a literal is fine). Its save refuses
weakInsert: a row counts from when its owner signs it, so read a row the owner hasn't saved
yet as its defaults instead of seeding one. A table is signed from its first version or never,
with the same signedKey and primary key: a later version that adds, removes, or changes
signedBy, signedKey, or primaryKeyName fails to load wherever an earlier version was
installed. Add new columns as optional fields without defaults so existing rows keep verifying.
A device still on an earlier version holds back rows saved with the new columns, and takes
them as soon as it updates your package.
To sign rows an existing table holds,
declare a new signed table and have owners save their rows into it. In a group, a signed table
can't be deleted (the Data Explorer's Delete refuses it), and its rows stay when the package is
uninstalled.
Watching your own tables
A package can react to changes in its own tables, whoever made them: its own handlers, a UI or
another package through a contract, or another device through sync. Subscribe in
pkg.onStart:
pkg.onStart(async (ctx) => {
await Requests(ctx).subscribe(async ({ op, dataObject }) => {
if (op !== "delete" && dataObject.status === "pending") {
await runRequest(ctx, dataObject);
}
});
});
- Changes arrive one at a time, in the order they happened.
opisinsert,update, ordelete;sourceislocalfor a change made on this device andremotefor one synced from another;dataObjectis the row aslistreturns it. - The package's own writes arrive too, including the ones the handler makes, so make sure a handler's write doesn't set it off again.
- A handler that throws is logged, and later changes still arrive.
- A handler gets the same deadline as a tool call. Past it, the overrun is logged and later changes stop waiting for it, so start long work without awaiting it in the handler.
- The subscription lasts until you call the function
subscriberesolves to, or the worker stops. Changes made while the worker isn't running aren't replayed: subscribe first, then read what's already there. - This is for the package's own tables. A UI or another package subscribes to a contract
table's
dataChangedinstead (Using the contract from a UI).
Moving data from an old-style package
A package ported from the old host-backed style to /define gets new, empty tables: the new
tables are named after the package, the old ones after the table ids the old version chose. To
keep the data, the new version copies it once, on each device:
- Read the old table from the package's UI. The UI can still open it with the old table
definition (
getTableContainer().getTable(oldMetaData, oldSchema)). Save each row through the new table, keeping its id. - Copy only rows the new table doesn't have yet. On a synced table every device runs the
copy, and the copies merge because the ids match. Save each copied row with
{ weakInsert: true, insertOnly: true }:insertOnlyleaves a row this device already has alone, andweakInsertmakes the copy yield to any real write, so a device that copies late can't undo an edit made after another device's copy. Still let the device sync first, so it copies current rows. A row this device deleted since stays deleted: its save is refused as deleted, so count it as skipped. Pause the package's writes during the copy. - For a big table, compare ids before sending rows. Give the copy contract a Reader tool
that takes a page of ids and returns the ones the new table lacks, and send only those rows.
Once the first device's copy has synced, a later device only sends ids. Read the old table in
pages by id (
{ taskId: { $gt: lastId } }, sorted by id) rather than by page number, so rows syncing in meanwhile can't shift a page. Tasks copied about 29,000 rows this way in about 30 seconds, 300 per call; a device whose rows were already copied took about 10 seconds. - Skip a row that won't parse rather than failing its batch: count it, and name a few in the result so they can be looked at.
- Put the copy tool on a contract of its own. The later version that removes the copy then simply stops providing that contract. A tool on the package's main contract can't be removed once a stable release freezes that contract, only replaced by a stub.
- Parse old rows leniently. Rows read in the UI and sent to a tool come in their stored
form: an
anyfield (az.record, for one) is JSON text, and an empty field can benull. Give the copy tool a schema that dropsnulls, parses JSON text, and coerces dates (z.coerce.date()). - Copy into read-only tables through a tool. A table whose class refuses consumers' saves (read-only to its consumers) takes the copy through a tool of your own: the UI reads the old rows in pages and passes them to it in batches, and the tool saves them with the table's package-only write method.
- Record that the copy is done, for example in a
groupDeviceVar, and have background work wait for it. - Release the new version to the group, so devices switch together. Until a device switches, it keeps writing the old table. Its new rows carry over when it switches, but an edit it makes to a row another device already copied doesn't. Deletions from the old table don't remove copied rows either, so keep the switch short.
- Rehearse it in a throwaway group. Install the old version there, add rows with its screens, then reload the new build in that group and check the copied rows before the real group switches. Turn off Reload packages on page refresh on that device first, or a page load selects your folder's new build in whichever group is active (Avoid production folder reloads).
- Remove the copy code in a later version, once every device has run it. The old tables stay in storage; nothing reads them any more.
Package settings stored with deviceVar and the like don't carry over either: new-style
variables are named per package. Copy the ones worth keeping the same way. The exception is a
variable the old version already named <packageId>_<name> with its own package id. A new-style
variable <name> in the same scope is stored under that name, so the new version reads the old
value with no copy. For the group scopes, that holds when the old version wrote it in the same
group.
Mentionable rows
Give a table mentions to make its rows mentionable: < in any Peers editor finds them by
title, in every group, and a link to one shows its live title and opens your screen. Peers reads
the table itself for this; no package code runs. Add trigger: "#" to have # find them alone,
as a Labels package would. See Mentions.
mentions: { kind: "note", label: "Note", titleField: "title", route: "app?noteId={id}" },
Overriding table methods
To change what a table does, give it a class, as you would any table class. Extend
PackageTable for the table's schema and override a method; super reaches Peers:
class FeedsTable extends PackageTable<typeof feedSchema> {
async save(feed: z.input<typeof feedSchema>) {
return super.save({ ...feed, title: feed.title.trim() });
}
}
export const Feeds = defineTable({
name: "Feeds",
description: "RSS or Atom feeds shared with the group.",
primaryKeyName: "feedId",
schema: feedSchema,
tableClass: FeedsTable,
});
Feeds(ctx)returns aFeedsTable, and so does every consumer call through a contract, so an override is the logic every caller gets.this.ctxis that call's context.super.saveparses the row with the schema (defaults and transforms apply) and stores it;get,list,count,findOne, anddeletego straight to storage.dataChanged(event)sees each change on its way to one subscriber, withthis.ctxcarrying that subscriber. Return it, return a changed copy, or returnundefinedto drop it. By default it passes the change through.- Consumers can call the six standard methods. Other methods on the class stay private to the package.
- The class runs in the package's worker, like the rest of its code, never in the host.
A table can also be read-only to its consumers, when its rows must change through a tool. Timers
does this: a timer's row and its device schedule change together, in write-timer. Its class
refuses save and delete, and the package stores the rows it plans through a method of its own:
export class TimersTable extends PackageTable<typeof timerSchema> {
async save(): Promise<never> {
throw new Error("Timers change through the write-timer tool");
}
async delete(): Promise<never> {
throw new Error("Timers change through the write-timer tool");
}
/** The package's own write. */
write(timer: ITimer) {
return super.save(timer);
}
}
Tools
A tool's definition and its handler sit together:
// tools/refresh.tool.ts
import { AccessLevel, defineTool, z } from "@peers-app/peers-sdk/define";
export const refreshTool = defineTool({
name: "refresh",
usageDescription: "Fetch every saved feed and replace its headlines.",
accessLevel: AccessLevel.Writer,
timeoutMs: 90_000,
inputSchema: z.object({}),
outputSchema: z.object({
updated: z.number().describe("Feeds that were fetched."),
errors: z.array(z.string()).describe("Feeds that failed."),
}),
handler: async (args, ctx) => {
// ...
return { updated, errors };
},
});
- The handler gets the input as
inputSchemaparses it, and its ownctx: host calls made through it act for that call's caller. Calls run concurrently, so a handler that reads and then writes shared state runs that change through a small queue (Worker isolation). - An input with a
.default()or.catch()is optional in the manifest, including one wrapped with.refine(),.readonly(), or.brand(). The guest applies the fallback before the handler runs, so it also works for calls through the tools catalog. Az.preprocessthat fills in a missing value isn't visible to the manifest, so that input stays required. accessLevelis the level a caller needs (the manifest carries it assuggestedAccessLevel).timeoutMsis the call's deadline, up to 120 seconds.outputSchemadescribes the result for callers and the catalog; the result isn't parsed with it. Return every required output field yourself, including fields with schema defaults. The result is copied as JSON would carry it, so an optional field can be leftundefined.- An assistant's model sees a tool's inputs in full: nested objects and the values an enum
allows (Schemas in the manifest). An optional input sent as
null, as models often do, is left out before the handler sees it (Empty values). - A contract another package declares, such as Voice Skill, is implemented
from its declaration (below). One you have
only as IR can be declared with
inputFieldsandoutputFieldsinstead of schemas; such a tool's input reaches the handler as sent, so a call from another package can passnullfor an optional input.
Schemas in the manifest
The manifest describes each schema (a table's rows, a tool's input and output, an event's
payload, an observable's value) as a list of Peers IR fields. Each field has a name and a
type: string, number, boolean, id, Date, object, blob, or any. The rest say
more about the value:
| Key | Comes from | Means |
|---|---|---|
optional | .optional() or .nullish(); on a tool input, also .default() or .catch() | The value may be empty (Empty values). |
isArray | z.array(...) | The value is an array; type, fields, and enumValues describe each element. optional applies to the whole array. |
fields | z.object(...) | The object's own fields, nested up to 16 levels. |
enumValues | z.enum, z.nativeEnum, a literal, or a union of literals | The only values allowed. |
{
"name": "place",
"type": "object",
"fields": [
{ "name": "city", "type": "string" },
{ "name": "unit", "type": "string", "enumValues": ["F", "C"] },
{ "name": "zone", "type": "string", "optional": true }
]
}
- When a value arrives, the Runtime checks a table row, a tool's input, or an event payload
against
type,optional, andisArray, and an observable's value against itsvalueType. A tool's input is also checked against each top-level field'senumValues, before your handler runs. OtherwisefieldsandenumValuesdescribe values for consumers and for the models that call tools; the package's schema enforces them when it parses. So a row synced from a device running a newer version of the package isn't refused for a value the older schema doesn't list. - An object keeps keys its
fieldsdon't list. An object with no fields of its own (z.object({}).passthrough()) is opaque: its entry has nofields, and any keys pass. - Some schemas are described by type only: records (
z.record), unions of objects, tuples, lazy schemas, a value inside a transform or a preprocess, and arrays of arrays. - In a table row, a field described by type only is an
anyfield. Storage keeps an object in one as its JSON text, and reads hand that text back, not the object. For a map in a row, such as item names to numbers, usez.object({}).catchall(z.number()): it's anobjectfield, so it reads back as an object. - The IR can't say that an array's elements may be empty, and then lists no enum values for
them. For now, avoid
nullorundefinedelements and arrays of arrays in table rows and tool inputs: the Runtime refuses them even where the schema allows them. - An observable's entry carries the value's full shape as
value, beside thevalueTypethe Runtime checks (Observables). - Hand-written IR, for a contract defined elsewhere, can use the same keys.
peers-packagefails the build on a field key it doesn't know, so a typo doesn't go unnoticed. - A package built with an SDK that writes
fields,enumValues, orvalueneeds a Peers host from the same release or later; an older host refuses its manifest.
Empty values
A field in Peers has one empty value: missing. Wherever the manifest describes a value (a table
row, a tool's input and output, an event payload, an observable's value, and the objects nested
in them), null, undefined, and a field left out all mean the same:
- An optional field that's
nullorundefinedis left out, so your code doesn't receivenullfor one. The exception is a tool declared withinputFields: a call from another package reaches it as sent. - A field with a default gets the default when it's empty, where the schema parses the value: table saves, tool inputs, event emits, and observable writes. A tool's result and an observable's source aren't parsed, so give their fields with defaults a value yourself.
- A required field without a default can't be empty.
- A table row saved with an empty field reads back without it.
- Values the manifest doesn't describe field by field, such as those inside
z.record,z.unknown(), orz.any(), are left as they are,nulls included.
Declare a field that may be empty with .optional(). peers-package build refuses
.nullable() unless the field is also optional (as with .nullish()) and has no default,
because the field would never hold null. An observable's whole value may still be null
(Observables).
A tool can't tell "clear this field" from "leave it alone" by null versus a field left out.
When it needs to, take the fields to clear as an input, such as clear: z.array(z.string()).
Calling contracts
contractRef(contractId, version) names a contract the package calls. Declare it with
pkg.consumes(...) and call it from a handler with that call's ctx:
import { newid, SystemHttp, SystemScheduler } from "@peers-app/peers-sdk/define";
const page = await SystemHttp(ctx).tools.request({
requestId: newid(),
method: "GET",
url,
responseType: "text",
});
SystemHttp and SystemScheduler are typed references to System HTTP and
System Scheduler; SystemContractCatalog
lists every provider of a contract.
SystemIdentity exposes only getSession() to packages; the other System Identity tools
refuse package callers. SystemGroupMembers.getMembers() returns current membership of the
calling package's own context, with no group-id argument. SystemFiles saves and reads files
in that context (System Files). SystemNotifications notifies the
signed-in user or members of the package's group (Notifications).
All seven references are exported from @peers-app/peers-sdk/define and declared with
pkg.consumes(...).
import { SystemIdentity, SystemGroupMembers } from "@peers-app/peers-sdk/define";
// In the package declaration:
pkg.consumes(SystemIdentity);
pkg.consumes(SystemGroupMembers);
// Inside a tool handler, using that call's ctx:
const { userId } = await SystemIdentity(ctx).tools.getSession();
const { dataContextId, personal, members } = await SystemGroupMembers(ctx).tools.getMembers();
// members: [{ userId, name?, role, accessLevel }]
getSession() may have no userId while signed out. Membership includes the founder and
Readers; removed members and roles below Reader are omitted. Names are optional, from signed
user profiles. In the personal context, the list contains only that user. Use accessLevel
for permission comparisons and role for its display label. These are local-only contracts;
packages call them within a tool invocation, like System Scheduler.
Type your own references with the contract from
defineContract, imported with import type so none of the provider's code
comes along. A handler in News can reference its own contract this way:
import type { News } from "../package";
const NewsRef = contractRef<typeof News>(contractId, contractVersion);
await NewsRef(ctx).tools.refresh();
const latest = await NewsRef(ctx).tables.Headlines.list({}, { pageSize: 5 });
- Every tool and table is typed from the contract, and an id or version that doesn't match it is a compile error. A tool whose input has no required field can be called without one.
tableshas the same methods as the package's own table handle. Each call goes through the providing package's table (its class, if it has one), sosavetakes the schema's input and the provider's defaults and transforms apply.observablesreads a contract's observables as this call's caller:await Weather(ctx).observables.forecast.get(), and.set(value)on a writable one. An empty whole observable value isnullon the wire; check for it before using the result. To clear a writable whole value, declare a schema that allowsnulland passnull.- Tool input and saved rows are copied as JSON would carry them: a field left
undefinedis omitted. - A contract declared on its own is its own
reference:
VoiceSkill(ctx).observables.widget.get(), with nocontractRef. - Without the contract's types (another package's contract you don't have the source for), type
just the tools, with the provider's tool signatures (
IHttpConsumer["tools"]).
A package can call its own contract this way when the Runtime should check the caller again.
For example, Timer Controls calls Timers' write-timer through the Runtime for each change.
Calling every provider of a contract
A call through a reference uses the provider selected by pkg.consumes, including its
provider preferences; calls to the package's own provided contracts use that package. A hub
that works with every installed provider, the way Voice Hub works with every voice skill, declares
SystemContractCatalog too, lists the providers, and passes { providerPackageId } when it
calls the reference:
import { SystemContractCatalog } from "@peers-app/peers-sdk/define";
import { VoiceSkill } from "./contracts/voice-skill.v2";
const { providers } = await SystemContractCatalog(ctx).tools.listContractProviders({
contractId: VoiceSkill.contractId,
version: VoiceSkill.version,
});
for (const { packageId } of providers) {
const widget = await VoiceSkill(ctx, { providerPackageId: packageId }).observables.widget.get();
// ...
}
// The listing also includes the contracts each provider exposes.
// Call their tools as described under "Exposing your contracts through a hub's contract".
Declare the contract the providers serve with pkg.consumes(...) as well ({ optional: true }
when the package works with none installed). Tools and observables can pick a provider this way;
table calls can't yet, and fail if you pass one.
When each provider offers different tools, as they would to a command palette or an assistant, the providers expose their own contracts through the hub's (see "Exposing your contracts through a hub's contract").
Package-internal state
A package keeps its own state in persistent variables, declared at module scope the same way
as in any Peers code: deviceVar, userVar, groupVar, groupDeviceVar, and groupUserVar,
from @peers-app/peers-sdk/define. They need no ctx.
import { deviceVar } from "@peers-app/peers-sdk/define";
const refreshSchedule = deviceVar("refreshSchedule", { defaultValue: "" });
const scheduleId = refreshSchedule(); // read
refreshSchedule(next.scheduleId); // write
await refreshSchedule.loadingPromise; // wait until the background write settles
- Each is an observable.
v()reads,v(value)writes, andv.subscribe(fn)hears every change, including one made on another device (auserVarorgroupVarsynced in). - The Runtime loads every variable declared at module scope when the package's worker starts,
before the first call, so handlers can read them right away. A variable created later loads
when it's created; await its
loadingPromisebefore reading it. - A callable write updates the value at once and is saved in the background, in order.
loadingPromisewaits for it to settle; a failed background save is logged. When a handler depends on persistence, useawait writePackageVar(v, value)from/define: it returns the written value and rejects a failed save, even for an unchanged value.await readPackageVar(v)rereads storage and rejects read failures. Both retain the variable's value type. These helpers operate on package variables, and apply no observable schema; validate the value before writing when needed. v.delete()clears the stored value and goes back to the default. A storednullalso reads as the default.- The variables are the package's own: the Runtime prefixes each name with the package's id, so they never clash with another package's. They aren't part of any contract; to share a value, expose an observable instead.
- Outside a worker (in tests, or while
peers-packagereads the declaration) a variable is an in-memory observable that starts at its default.
Events
An event is a signal out. Define it with its payload schema, list it on a provided contract, and emit it from anywhere in the package:
import { defineEvent, z } from "@peers-app/peers-sdk/define";
export const finished = defineEvent({
name: "finished",
description: "A timer finished.",
payloadSchema: z.object({
title: z.string().describe("The timer's label."),
kind: z.string().default("timer").describe("What finished."),
}),
});
export const Timers = defineContract({ /* … */ events: [finished] });
await finished.emit({ title: "Tea" }); // no ctx
emitparses the payload with the schema first, so defaults apply and a bad payload fails in the package. It resolves once the host has accepted the event. An event without a payload is sent withemit().- It needs no
ctx: the package emits for itself, from a handler, a timer, or other background work. An event listed on two provided contracts goes out on both. - The payload is copied as it's sent, the way JSON would carry it:
undefinedfields are left out, andundefinedarray entries becomenull. Dates andUint8Arrays are kept. A value that can't be sent (a function, aMap, a cycle,NaN) failsemit. - The manifest describes the parsed payload: an optional field may be empty, and subscribers receive it left out (Empty values). A field with a transform accepts any value.
- Events aren't replayed: subscribers get the ones emitted while they're subscribed.
- Outside a worker,
emitchecks the payload the same way and sends nothing. - For a contract defined elsewhere, pass
payloadFields(Peers IR) instead of a schema, or list the IR event in the contract'seventsdirectly when the package doesn't emit it.
Observables
An observable is one value other packages and the UI can read, watch, and (when writable)
write. Define it over a source the package already uses: a package variable, or a plain
in-memory observable().
import { defineContract, defineObservable, groupVar, observable, z } from "@peers-app/peers-sdk/define";
const location = groupVar("location", { defaultValue: { query: "", unit: "F" } });
const conditions = observable<{ temp: number } | null>(null);
export const Weather = defineContract({
// contractId, version, name, description, tools …
observables: [
defineObservable({
name: "location",
description: "Saved city and display unit.",
schema: z.object({ query: z.string(), unit: z.enum(["F", "C"]) }),
writable: true,
source: location,
}),
defineObservable({
name: "conditions",
description: "The latest reading.",
schema: z.object({ temp: z.number() }).nullable(),
source: conditions,
}),
],
});
conditions({ temp: 71 }); // the package reads and writes the source as usual
- A package variable is stored; consumer reads and writes reach it through the package
worker. Changes from any side reach subscribers through that worker, including changes
synced from another device. It needs a
defaultValue, which consumers read while the variable is unset. - An in-memory observable is held by the package's worker. Reading it starts the worker,
which publishes the value before the read returns, and the package's changes reach
subscribers as they happen. The value starts over when the worker does. Use it for state
that doesn't need to outlive the worker, like what the package is doing right now.
- The worker publishes after the package's variables load, so a value derived from them starts out right.
- Each value is copied as it's published, like an event payload.
peers-packagefails the build when the source's starting value doesn't fit the value type. If the first publish still fails, the worker doesn't start; later failed publishes are logged.
- Consumer reads and writes run under the caller's authority. A write must fit the manifest's value type, then is parsed with the schema before the source takes it, for stored and in-memory observables alike. A stored write replies once its value is saved, and fails if the save does.
- The schema sets the value type the Runtime checks (
string,number,boolean,object,id, orany): an enum or string literal isstring, an array isobject, and a value that can benullorundefined, or that comes from a transform, isany. Values are JSON, so a schema with aDateanywhere in it is rejected. The manifest also carries the value's full shape asvalue: a nullable object, say, isanyto the Runtime and an optional object with its fields to readers (Schemas in the manifest). Fields of an object value follow Empty values. - For a contract defined elsewhere, pass
valueTypeinstead of a schema, or list the IR observable (with itspersistentVarbinding) in the contract'sobservablesdirectly.
The declaration
src/package.ts exports the package's own contract and default-exports the package's
definition:
import {
defineContract,
definePackage,
SystemHttp,
SystemScheduler,
} from "@peers-app/peers-sdk/define";
export const News = defineContract({
contractId,
version: 1,
name: "News",
description: "Headlines from a few RSS and Atom feeds.",
tables: [Feeds, Headlines],
tools: [refreshTool, headlinesTool],
});
export default definePackage((pkg) => {
pkg.packageId = packageId;
pkg.version = version;
pkg.provides(News);
pkg.provides(NewsVoiceSkill);
pkg.consumes(SystemHttp);
pkg.consumes(SystemScheduler, { optional: true });
pkg.network = { allowedHosts: ["feeds.bbci.co.uk", "feeds.npr.org"] };
pkg.appNavs = [{ name: "News", iconClassName: "bi bi-newspaper", navigationPath: "app" }];
});
defineContractdeclares a contract: its id (fromnewid()), version, name, description, and thetables,tools,observables, andeventsit exposes.alsoImplements: [1]keeps serving an older, frozen version's consumers with this version's handlers (Package contracts). It checks each member's kind and rejects a name used twice. The value and its member lists are frozen and typed read-only. Export it so the package's UI (and other packages) can reference it by type.pkg.provides(contract)provides it. A contract another package declares is provided the same way, once implemented: News'sNewsVoiceSkillis Voice Hub's Voice Skill declaration with News's widget, exposing News (below).pkg.consumes(ref, { optional })declares a dependency. Withoutoptionalit's required: the package installs but waits, with no tools, background work or screens running, until a package that provides the contract runs in the same group, and then starts by itself (Required contracts). News requires System HTTP, a contract Peers itself provides, and uses System Scheduler only when it's there.pkg.network,pkg.appNavs, andpkg.executionModeset the manifest fields of the same names.pkg.onStart(fn)runs background work when the worker starts (below).
Declaring a contract other packages implement
Some contracts have many providers: every voice skill provides Voice Skill, and Voice Hub works with each one. Declare such a contract on its own, with no handlers, in the package that owns it, and let each provider implement it. In this example a dashboard declares a Dashboard Card contract with a tool, an observable, and an event (Voice Skill is a real one, with an observable and an event):
// dashboard/src/contracts/dashboard-card.ts: no handlers, safe to import or copy
import {
AccessLevel,
declareContract,
declareObservable,
declareTool,
defineEvent,
z,
} from "@peers-app/peers-sdk/define";
// Exported, so providers can emit it.
export const cardAlert = defineEvent({
name: "alert",
description: "The card needs attention.",
payloadSchema: z.object({ title: z.string() }),
});
export const DashboardCard = declareContract({
contractId: "00mvokbnd4asry58e038t5yuj", // from newid()
version: 1,
name: "Dashboard Card",
tools: [
declareTool({
name: "summary",
usageDescription: "A one-line summary for the card.",
accessLevel: AccessLevel.Reader,
inputSchema: z.object({}),
outputSchema: z.object({ text: z.string() }),
}),
],
observables: [
declareObservable({
name: "card",
description: "The card's title and icon.",
schema: z.object({ title: z.string(), iconClassName: z.string().optional() }),
}),
],
events: [cardAlert],
});
declareToolanddeclareObservabletake whatdefineToolanddefineObservabletake, without the handler or the source. Events (defineEvent) and tables (defineTable, without atableClass) are listed as they are.declareContractchecks the same things asdefineContract, and refuses a member with a handler or a source.
A provider implements the declaration: a handler for each tool and a source for each observable, by name. The result is a contract to provide:
import { deviceVar, implementContract } from "@peers-app/peers-sdk/define";
// A generated copy of the dashboard's declaration (see below).
import { DashboardCard, type DashboardCardObservables } from "../contracts/dashboard-card.v1";
export const TasksCard = implementContract(DashboardCard, {
tools: {
summary: async (input, ctx) => {
// `input` is typed from the declared input schema, and the result from the output schema.
return { text: "3 tasks due today" };
},
},
observables: {
card: deviceVar<DashboardCardObservables["card"]>("card", {
defaultValue: { title: "Tasks", iconClassName: "bi-list-task" },
}),
},
});
// In definePackage:
pkg.provides(TasksCard);
- Handlers are typed from the declaration: the parsed input in, the declared output back. A
source must hold the declared value. A writable source must accept every value allowed by the
declaration; give its variable or
observable()that full value type. - A missing or unknown member fails the build, so an implementation can't drift from the declaration: its manifest shape comes from the declaration.
- A tool's entry may set this provider's deadline:
summary: { handler, timeoutMs: 90_000 }. Its access level andauthorityPropagationcome from the declaration. - A declared event is emitted with its own
emit(cardAlert.emit({ ... })), from any package that provides an implementation listing it. Export the declaration's events so providers can reach them.
Consumers use the declaration as the reference: pkg.consumes(DashboardCard, { optional: true }),
DashboardCard(ctx).tools.summary({}) in a handler, and hostContract(DashboardCard) in a UI.
A declaration holds no handlers or sources, so other packages can import it or copy it. Once a
stable package release freezes a contract version, its shape can't change (the Runtime refuses
a provider whose shape differs); descriptions may still change. Contracts from dev and beta
packages remain mutable. npx peers-package contract freeze records what a stable release froze,
so your build catches a change first
(Package lifecycle).
Exposing your contracts through a hub's contract
A package can only call contracts it declares with pkg.consumes, so a hub can't call a
provider's own contracts directly: it doesn't know them when it's built. Instead, a provider's
implementation of the hub's contract can name other contracts it provides. The hub contract's
consumers may then call those contracts' tools on that provider:
// News
pkg.provides(News);
pkg.provides(
implementContract(Hub, {
observables: { widget: observable({ peersUIId: newsWidgetId }) },
exposes: [News],
}),
);
- Each exposed contract must also be in
pkg.provides; the build fails otherwise. It takes the contract or its reference (contractRef(contractId, version)). exposesisn't part of the hub's contract. It belongs to this provider, so it doesn't freeze with the hub's contract, and a generated copy of the hub's contract doesn't carry it. Changing it takes a new release of your package.- The hub reaches only the exposed contracts' tools, each at its own access level. Their tables,
observables, and events still need
pkg.consumes. - Expose a small contract when your main one has tools a hub shouldn't reach, such as one your scheduler calls back.
Installing your package makes its exposed tools available to every package that consumes the hub's contract, including hubs installed later.
A hub lists each provider's exposed contracts with listContractProviders (see "Calling every
provider of a contract"). Each provider's exposes lists, per exposed contract, its name and
description, and the tools the current caller may run there, with each tool's description,
access level, and JSON Schema for its arguments. Then the hub calls the tool on that provider:
for (const provider of providers) {
for (const exposed of provider.exposes ?? []) {
// exposed.name, exposed.tools[i].name, .description, .inputSchema ...
}
}
// Later, the tool the user or model chose:
await contractRef(exposed.contractId, exposed.version)(ctx, {
providerPackageId: provider.packageId,
}).tools[toolName](args);
Such a call runs as the signed-in user, never with more than the user's own level, and fails when there's no signed-in user or when it names another device:
- The hub's consume ceiling on the hub's contract applies, if an admin set one. When several consumed hub contracts expose the same target on that provider, any eligible one may admit the call.
- If your package consumes or provides the target contract directly, its ordinary call rules apply instead, including its direct consume ceiling and provider restrictions.
- An ordinary calling tool caps it at that tool's own level; a calling tool declared
authorityPropagation: "preserve"passes the user's level through. - A call that names no provider, a provider that doesn't expose the contract, or one outside
the hub's
providerPackageIdsis refused as an undeclared consume. - The listing is a guide: the Runtime checks every call again.
Getting a declaration you don't have
From your package folder, fetch a registered contract from the running Peers:
peers contracts add 00muxgugn6xvs8f2r80ru205t@2
Add -c <groupId> for a group, or --device <deviceId> to read another device's contracts.
The file is written locally to src/contracts/<name>.v<version>.ts. Use --dir <folder> to
choose the package folder, --out-dir <folder> to change the output directory, and
--name <Name> to choose the export name.
If the contract isn't registered, or you're working offline, use
npx peers-package contract add <source> with one of:
- A declaration module and its export, such as
../voice-hub/src/contracts/voice-skill.ts#VoiceSkill. This needsesbuildin your package:npm install --save-dev esbuild. - A provider's
dist/package.bundle.jsordist/manifest.json. Add--contract <contractId>@<version>if it provides several contracts. - A JSON file previously saved from
getContractDefinition(the complete result, including tool access levels).
The offline command uses --root <folder> for the package folder. Both routes generate the
same file for the same contract. Check it in and regenerate it rather than edit it.
Both accept --check: it writes nothing and exits 1 if the file is missing or out of date,
including a file whose older generated format needs updating.
The file exports the declaration, its events, and types for observable values, event payloads, and table rows. It preserves declared types, descriptions, stored defaults, and tool access policy. Code-only validation such as regexes and computed defaults cannot be copied. For contracts with tables, use an up-to-date Peers host or generate from the provider's declaration module or built bundle.
Background work
pkg.onStart(fn) runs fn(ctx) each time the package's worker starts: after the package's
variables load, and before its in-memory observables publish, so a value fn sets is the first
one readers see. Weather loads its cached forecast into its forecast observable this way, and
follows the saved city:
export default definePackage((pkg) => {
// …
pkg.onStart(async (ctx) => {
forecast({ snapshot: await loadForecast(ctx), refreshing: false, error: "" });
location.subscribe(() => {
/* the saved city changed, here or synced from another device */
});
});
});
- The worker waits for
fn, and a failure fails its start (and every call to the package), so catch what can fail and don't await long-running work. Hooks run in the order they're added. ctxbelongs to no call. It reaches the package's own tables, and the package's variables, events, and observables work as usual. Calls to other contracts, System HTTP included, are refused outside a call.- Worker timers (
setTimeout,setInterval) can use the package's own tables and variables the same way, but not other contracts. To fetch or call other contracts on a timer, have a tool book its next run with System Scheduler: the scheduled tool runs as a call, with the access of the person signed in on the device, so a Reader's device can't run a Writer tool this way. Whether it also runs as that person depends on what made the schedule (Who a wake-up runs as). Weather'srefreshbooks the next refresh an hour out each time it runs, keeping the booking's id in agroupDeviceVarso the next refresh replaces it, and its widget callsrefresh({ ifStale: true })when it opens to start the cycle. - Workers start on first use, so
onStartruns when something first calls or reads the package on that device, not at install.
ctx.deviceId, on every ctx, is the id of the device the worker runs on. Use it to keep work
on one device, such as background work that needs tools or credentials only one machine has:
save the chosen device's id in a group variable, and start the work in onStart only where
ctx.deviceId matches. It says where the code runs, not who is calling, so never use it to
decide what a caller may do.
ctx.callerUserId is the user a call acts for: the signed-in user for a call from this device's
own screens, CLI or scheduled tools, and the member whose device called for a
remote tool call. Use it to record who did
something, such as who created a row. Don't use it to decide what the caller may do: Peers has
already checked the call against the member's access rules. For a contract event delivery it
identifies the subscriber, not the person who caused the event.
It's undefined in onStart, when no user identity is available, and on Peers versions before
it existed. Timers and watchOwnedTable callbacks have no caller of their own; a ctx captured
from an earlier call keeps that call's metadata. For local work on an older host, you can use
System Identity's getSession to learn the signed-in user. That fallback
can't identify a remote caller.
pkg.onStop(fn) runs fn() when the package's worker stops: when another version replaces
this one, when the package is turned off or removed, and when Peers quits.
let watcher: ChildProcess | undefined;
pkg.onStart(async (ctx) => {
watcher = startWatching(ctx);
});
pkg.onStop(() => {
watcher?.kill();
});
- It's for local cleanup: ending child processes, closing files, flushing a buffer.
fngets noctx, because the package's tables, variables, and events are refused once the worker is stopping. - The worker gets 5 seconds for its stop hooks, then it's ended. A crash or a forced kill runs
none, so check for leftovers in
onStartif they matter. - In a privileged package, ordinary child processes end with the worker whether or not
onStopends them (Provider execution modes).
Every call goes through the package
A package is the server for its contracts, and its consumers (UIs and other packages) are its clients. Every consumer call reaches the package's code in its worker, under the caller's authority, and everything sent back passes through it:
- Tables:
get,list,count,findOne,save, anddeleterun the table's class (Overriding table methods). Each change on its way to a subscriber passes through the class'sdataChanged, with that subscriber's context. - Observables: reads and writes go to the observable's source (or, for an IR declaration, the package variable it names). Values on their way to subscribers pass through unchanged.
- Events: emitted by the package's code; each payload on its way to a subscriber passes through the package unchanged.
- Subscriptions: subscribing and unsubscribing go to the package too. The package accepts every subscription; there's no hook to refuse one yet. A subscription carries on across the package's restarts and updates, and unsubscribing never starts the worker.
- Tools: run their handlers, as always.
If the package's worker can't start, its contract calls fail, as a request to a stopped server would. The package's own calls to its tables and variables go straight to Peers, and so does sync: a change that arrives from another device already went through the package on the device that made it.
Build with peers-package build; it generates the required guest API 3 manifest.
Rebuild older packages with peers-package before installing or updating them.
If Peers says the package needs a newer version of Peers, update Peers to use it.
Using the contract from a UI
A package's screens and widgets are clients of the Runtime, like the admin UI: they call the package's contract through the host, not the package's code. Give the UI a client for the contract in one place:
// ui/news.ts
import { hostContract } from "@peers-app/peers-sdk";
import { contractId, contractVersion } from "../consts";
import type { News } from "../package"; // types only: no handler code in the UI bundle
export const news = hostContract<typeof News>(contractId, contractVersion);
Then use it anywhere in the UI:
import { useRows, useTool } from "@peers-app/peers-ui";
function Feeds() {
const { rows: feeds } = useRows(news.tables.Feeds, {}, { pageSize: 50 });
const refresh = useTool(news.tools.refresh);
return (
<>
<button disabled={refresh.pending} onClick={() => refresh.run()}>Refresh</button>
{refresh.error && <div>Couldn't refresh.</div>}
{feeds.map((feed) => <div key={feed.feedId}>{feed.title}</div>)}
</>
);
}
- Typed from the contract.
tools,tables,events, andobservablesare all typed byimport type, which brings none of the package's code into the UI bundle. At runtime the client needs only the id and version, which must match the contract's (a mismatch doesn't compile).hostContract(contractRef<typeof News>(contractId, contractVersion))is the same client, from a reference. useTool(call, { onSuccess, onError })from@peers-app/peers-uiruns a tool and tracks it:run(input)resolves to the result, orundefinedwhen it fails (it never throws);pending,result, anderrordescribe the latest run;reset()clears state without cancelling calls or their callbacks. Callbacks run for each completion, including older overlapping runs. Callback failures are logged and do not change the tool's outcome; async callbacks are not awaited. It takes table writes too (useTool(news.tables.Feeds.save)) or any async function.runkeeps one identity across renders and calls the latest function; nothing updates after unmount.- Tables have the package's table methods and
dataChanged.subscribe(handler). Each call goes through the package's table, sosavetakes the schema's input and the package's defaults, transforms, and overrides apply, and each change reaches the UI through the table'sdataChanged. Events havesubscribe(handler). Observables are live local copies: read one withuseObservable(weather.observables.location)and write it by calling it with a value when declared writable. Read-only declarations expose aReadonlyObservable; only writable observables have a callable typeduseObservablesetter. A write the provider refuses is logged, and the copy reads the provider's value again. Writes made while disconnected wait for a connection (up to the client's timeout); writes to different observables have independent queues. A write still waiting for its reply when the connection is replaced is logged as failed, along with writes queued on that connection. Writes made while disconnected or after reconnecting can use the new connection, and the copy shows its value. A slow reread cannot replace a newer provider push. useRows(table, filter, options)from@peers-app/peers-uikeeps rows current. It reads on mount, and again when the table changes, after a reconnect, or when the filter or options change. It also reads once a remote subscription becomes live, covering changes missed during setup. Changes that arrive during a read cause one more read, not one per change.- Connection. Calls wait for the host connection (10 seconds by default). A tool or table
call still waiting for its reply when the connection is lost or replaced fails; the provider
may still have run it. Subscriptions and
observables wait as long as it takes and re-attach after a reconnect;
subscribe(handler, { onReconnect })reports when changes may have been missed, after the replacement subscription is live. The returned subscription'sreadypromise reports whether its initial attachment succeeded; unsubscribing before attachment resolves it tofalse. When the initial attachment fails, the next one that goes live after a reconnect callsonReconnect. Calls go to the active group unless the client names another (Screens that show any group); switching the active group reloads the window. - One client per contract.
hostContractwithout options returns the same client for the same contract id and version, even from a new reference. It isn't a hook, so it works in event handlers and plain functions too. - One provider.
hostContract(VoiceSkill, { providerPackageId })reaches that provider rather than the group's default, to show a widget for every installed skill, say. This applies to tools, tables, observables, and events. Handler references can't select a table's provider yet. - Initial observable values. A local copy starts empty. Await
client.observables.widget.loadingPromisebefore relying on its first value. It resolves after the initial read attempt (a failed read is logged), or when the client is disposed. - Disposal. Shared clients live for the window's lifetime. A client created with options is
independent; call
dispose()when its owner ends. Disposal cancels connection waits, ends subscriptions, and refuses new calls and observable writes; cached observable reads remain. - The renderer provides
@peers-app/peers-ui, like@peers-app/peers-sdk; list it as a peer dependency and a webpack external. - Access. A UI's calls act as the signed-in user today, as every UI call does (Local UI-to-host contracts).
- Files.
hostContract(SystemFiles)saves a file from a screen, anduseFileUrl(fileId)from@peers-app/peers-uigives a URL to show it, such as an<img src>(System Files).
Screens that show any group
A screen follows the user's active group. A screen can instead show any of the user's groups and let them switch inside it, as Threads does, without changing the active group, which reloads the app. Such a screen keeps one client per group:
// ui/client.ts
import { hostContract } from "@peers-app/peers-sdk";
import { contractId, contractVersion, packageId } from "../consts";
import type { News } from "../package";
const clients = new Map<string, ReturnType<typeof clientIn>>();
const clientIn = (groupId: string) =>
hostContract<typeof News>(contractId, contractVersion, {
dataContextId: async () => groupId,
providerPackageId: packageId,
});
/** News in one of the user's groups; Personal's id is the user's id. */
export function newsIn(groupId: string) {
let client = clients.get(groupId);
if (!client) clients.set(groupId, (client = clientIn(groupId)));
return client;
}
- Each group's own provider answers, and checks the user's role in that group. Your package must be installed and running there; otherwise calls fail as having no provider.
providerPackageIdkeeps the calls on your package where another package also provides the contract.- Clients with options aren't shared. Keep one per group, and
dispose()it when the user leaves the group. - Files in that group:
hostContract(SystemFiles, { dataContextId }).useFileUrlreads the active group's files only. - Notifications. Declare
opensAnyGroup: trueon the screen's route (Authoring routes):- Opening a notification from any of the user's groups, the active one included, then goes to
its link in place, with
groupId=<the notification's group>added, instead of switching the active group. That needs your package installed in the active group too; otherwise Peers switches groups first, as before. - Read
groupIdfrom the path (mainContentPath) and show that group. - A link without
groupIdmeans the active group: after such a switch, and in Peers versions that don't know the field.
- Opening a notification from any of the user's groups, the active one included, then goes to
its link in place, with
- Mentions. With
opensAnyGroup: true, a mention of one of your records in another group opens in place too, with itsgroupId(Mentions). - The user's groups. No contract lists them to a screen yet.
Opening a link
A UI opens a web page in the user's browser with openLink from @peers-app/peers-ui. It
takes http:, https:, and mailto: links, and shows the user why when a link can't be opened:
import { openLink } from "@peers-app/peers-ui";
<button onClick={() => openLink(pullRequest.url)}>Open in GitHub</button>;
Testing a UI
mockHostContract from @peers-app/peers-sdk/testing stands in for the host. The UI's own
client connects to it, with no signed-in user and no provider running:
import { mockHostContract } from "@peers-app/peers-sdk/testing";
import { News } from "../package"; // a test can import the contract itself
const host = mockHostContract(News, {
tables: { Feeds: [{ feedId: newid(), title: "NPR", url: "https://feeds.npr.org/1001/rss.xml" }] },
tools: { refresh: async () => ({ errors: [] }) },
});
// Render the screen; it reads and writes through `news` as usual.
await host.tables.Feeds.save(nextFeed); // the screen sees the change
host.tables.Feeds.rows; // what the screen saved
host.dispose();
- Tables hold rows in memory, and a UI's calls go through the table's class with a test
context, as on the host: a save runs the class's overrides and the schema, defaults
included, and observed changes reach subscribers through the class's
dataChanged. Delivery hooks stop when the last subscriber leaves or the mock host is disposed. The test context'scallOwnedTablereaches the mock's rows; its other calls fail.host.tablesare storage writes, with no class or schema in between, validated against the manifest's fields as host storage does; their changes still pass through the class. Filters are equality ({ feedId }) and$in({ status: { $in: ["running", "paused"] } }); a filter with other operators ($or,$matchWords) fails rather than guess. Equality tonullorundefinedmatches omitted optional fields, as in host storage. Paging andsortBywork; other query options, including text search, fail explicitly. - Tools answer with the fakes you pass, given the input as the tool's schema parses it. A tool without a fake fails when called, and a private tool refuses UI calls, as the host does. Access levels aren't checked.
- Observables start with the values you pass; others start as the host serves them, a
stored observable's default or the value an in-memory one's source holds. Set
host.observables.x(value)to push one, and read it to see what the UI wrote. Read-only ones refuse UI writes, as the host does. Every UI write must fit the manifest's value type first, including IR declarations; schema defaults and coercion cannot bypass that check. Schema declarations then parse the write, and the observable keeps the parsed value, as the package does.host.events.x.emit(payload)reaches subscribers. - A declared contract works too:
mockHostContract(VoiceSkill, { tools, observables }). The fakes stand in for its handlers, and its observables start empty unless you give them values. The mock is a single provider: a client made withproviderPackageIdreaches it whatever the id. onCall(call)runs before each answer: return a promise to delay it, or throw to fail it (an offline read, a refused save). It cannot replace the answer.- Values are copied using the isolated boundary's supported value types, including Dates and
Uint8Arrays. The helper also works in Jest's jsdom environment, withoutstructuredClone. One mock host runs at a time; dispose it after unmounting what you rendered. Disposing it rejects calls still waiting for an answer.
News's src/ui/ui-test-kit.mjs renders its screen and widget this way under node --test,
bundling them with esbuild so React and the SDK stay single copies.
Building
"scripts": {
"generate-manifest": "peers-package manifest",
"build:package": "peers-package build",
"dev:package": "peers-package build --watch"
}
peers-package manifestloadssrc/package.tsin Node and writesdist/manifest.json. It fails if the manifest doesn't validate, or if it changes a contract version a stable release froze (frozen-contracts.json).peers-package buildalso bundles the samesrc/package.tsfor the sandbox, with a generated entry that registers every tool's handler, and writesdist/package.bundle.js, the artifact the Runtime installs. Its summary prints the SDK version used for the build.peers-package contract add <source>generates a declaration of a contract the package implements or calls (above).peers-package contract freezerecords the contract versions a release provides as frozen, before you release it as stable;--checkonly checks (Package lifecycle).- A failed provider build preserves the last successful manifest and artifact. Watch mode
rebuilds both outputs, reloads the declaration's CommonJS dependencies, and updates its
bundler settings when
executionModechanges.
Pin @peers-app/peers-sdk in package.json to the Peers version your devices run (an exact
version, without ^ or ~). Import and reload warn when the folder's installed SDK is newer
than Peers; the warning does not fail the operation. Update Peers or pin the SDK and rebuild.
Use --root, --entry, and --out-dir to select the package root, declaration file, and
output directory. Entry and output paths are relative to the package root; the output directory
can also be outside the package.
The command uses the package's own esbuild (npm install --save-dev esbuild). The bundle uses
one copy of zod for the package and the SDK, defines process.env.NODE_ENV the way other
bundlers do, and strips comments. The sandbox rejects some text even inside a string or
comment (import(, <!--, -->, and a direct eval(), so the build fails with the place it
found one rather than leaving it to fail at install.
Testing
runPackageTool(tool, args, ctx) runs a tool the way the Runtime does: it parses the input,
then calls the handler. Pass a fake ctx that records or answers host calls.
startPackage(definition, ctx) starts the package's variables, events, onStart hooks, and
in-memory observables with a fake ctx, the way the worker start does. To test what ships,
evaluate dist/package.bundle.js's provider source with a fake registerContractTool,
registerHandler, onWorkerStart, and ctx, as News's tests do; the bundle throws if one of
the three functions is missing. Each provided contract registers its member handler under
contractMemberHandlerName(contractId, version) (from @peers-app/peers-sdk). Call it with
{ member: "table", name: "Feeds", operation: "save", args: [row] } to make a consumer's
call, which runs through the table's class.
What the sandbox provides
Sandboxed packages run ordinary isomorphic JavaScript. Besides the language itself, the sandbox provides the web platform basics that carry no authority:
URL,URLSearchParams,TextEncoder,TextDecoder,atob,btoa,structuredClonecrypto.getRandomValues,crypto.randomUUID,crypto.subtlesetTimeout,setInterval,clearTimeout,clearInterval,queueMicrotaskAbortController,AbortSignal,Event,EventTarget,DOMExceptionconsole,performance.now,Intl, the float typed arraysselfandglobal, both the package's own global object
Timers return numeric ids. A timer or microtask callback that throws or rejects is logged with
console.error instead of stopping the package. Package console output is recorded in the
device's logs, as it is for privileged packages: peers logs -p worker -s "<package name>".
Anything that carries authority stays behind a contract: the network (System HTTP), files,
processes, and other packages. There is no fetch, process, require, or Buffer.
WebCrypto keys are opaque frozen handles so Node's native key objects never enter the sandbox.
The standard crypto.subtle operations accept these handles. Keep them in memory;
structuredClone does not preserve their key identity. Copy extractable keys with
subtle.exportKey and subtle.importKey.
Code runs in strict mode, and the built-in prototypes are frozen, so a library that patches
Array.prototype or similar fails. Everything is bundled at build time; there is no runtime
module loading.
Related topics
- Getting started — create, import, and build a package.
- Package contracts — contracts, the Guest API, and isolated packages.
- Voice skills — the Voice Skill contract.
- Mentions — making a table's rows mentionable.
- System: Tables — filters, local-only tables, and reactivity.