Skip to main content

Packages

Peers packages are how the app loads extensible behavior: tables and tools (and related metadata) on the server/runtime side, routes for URL mapping in the browser, and UI bundles for React screens. The desktop app and PWA install package versions from a package's release source (updateUrl), a local build, or synced updates, then each device chooses which version to run within a group (or personal space), using group-level defaults on IPackage when the device has no override.

When a package version record syncs to a device, Peers also downloads that version’s package, routes, and UI bundle files into the local content-addressed cache. Downloading those bytes does not activate the version — activation still follows group defaults and this device’s pin / follow settings.

At a high level, a package contributes:

  • Runtime manifest and provider — isolated table, contract, tool, and navigation declarations, plus provider source that Electron and headless can run in a supervised container.
  • Routes — small bundle that registers URL paths before UI loads.
  • UI — lazy-loaded React components registered by peersUIId.

Package lifecycle​

Packages follow a three-phase lifecycle: dev → beta → stable. Disk updates create dev versions; promotion to beta or stable is explicit, in the Versions UI or with peers packages promote. Dev records sync to the group but never auto-activate on other devices unless those devices opt in.

When you activate a different version on this device, routes and UI bundles reload without a full page refresh.

See Package lifecycle for development workflow, per-device pin/follow settings, and releasing to the group. See Package lifecycle design for design rationale and remaining roadmap work.

Creating a new package​

Creating or cloning a package from the desktop app requires git, Node.js, and npm on your machine. Peers looks them up through your login shell so tools installed via nvm, Homebrew, or fnm work even when the app was opened from Finder or the Dock. If those tools are truly missing, the create dialog explains how to install Node.js from nodejs.org and restart Peers.

The fastest way to start a new package is from the Peers app (Packages → Create), which clones the peers-package-template, patches IDs, builds bundles, starts a Git repository on main with one commit, registers the Packages record, and provisions a per-package author signing key in your personal space. A package made from the template needs the latest Peers release; an older app refuses to install it, so update Peers first.

You can also scaffold on disk and import:

git clone https://github.com/peers-app/peers-package-template.git ~/peers/packages/my-app
cd ~/peers/packages/my-app
rm -rf .git && git init && git symbolic-ref HEAD refs/heads/main
# fill in src/consts.ts and peers.packageId in package.json (see Set up IDs below)
# update README.md's title and first paragraph, then:
npm install && npm run build

Then import the directory: open Packages → Create in Peers and select it, or run peers packages import ~/peers/packages/my-app.

Importing an existing package directory​

If the target directory already exists and contains a valid package.json with peers.packageId, create/import does not re-clone the template. It:

  1. Validates the manifest package ID
  2. Recovers the signing public key before saving the package. The target Packages row takes precedence; if it is absent, Peers searches your personal context, then groups, for the same package ID's first nonblank publishPublicKey. It can also recover the key from metadata cached alongside your personal signing secret, or through host decryption of an older encrypted secret. A new keypair is created only when both the public key and signing secret are missing; established keys are never silently rotated.
  3. Creates or updates the Packages row (name, description, optional remoteRepo)
  4. Persists packageLocalPath_<packageId> for that data context
  5. Installs the on-disk dev bundles

If those bundles match the package's existing dev PackageVersions row, import reuses that row instead of writing a new one. If Packages.activePackageVersionId is empty, as it is after deleting and re-importing a package, import sets it to that version and activates it on this device. Deleting a package removes only its Packages row; its version rows and bundle files remain so a later import can reuse them.

This is the supported path for monorepo apps under official-packages/ (for example Groceries).

From a terminal, peers packages import <path> imports a folder; it fails rather than scaffolding when the folder is missing. After a rebuild, peers packages reload <packageId> installs the new bundles and exits 1 with the load error if the new version does not run, while the previous version keeps running. peers packages get <packageId> shows the running version and the last error, and peers packages uninstall <packageId> removes the package. See Packages.

Importing the same local package by name into Personal or another group reuses its publisher identity. Deleting the package leaves your personal signing secret and its cached public key intact, so re-importing after uninstall also preserves that identity. Import fails without changing keys if the available public keys disagree, or if an existing secret has no recoverable public key.

Share your package's source through Peers​

With the Git package installed in a group, share your package's source with its members instead of (or as well as) GitHub. In the package's folder, once it's a Git working copy with a commit:

peers git share -c <groupId>

That creates a repository in the group, adds a peers remote, pushes the current branch, and records the peers:// URL as the package's source (if it has none, and you're an Admin of the group), so the package's details show it. Members clone it with git clone <url> (or peers git clone <name> -c <groupId>), push their own branches, and build and import it like any package folder. See Git for shared branches and maintainers.

Project structure​

The template starts as a small shared list, with one table, one tool, and one screen:

my-app/
├── src/
│ ├── consts.ts # Package, contract, and screen IDs
│ ├── package.ts # The contract and the package's declaration
│ ├── data/items.ts # A table: zod schema + defineTable
│ ├── tools/add-item.tool.ts # A tool: definition + handler
│ ├── ui/
│ │ ├── client.ts # The screen's client for the contract
│ │ └── app.tsx # The screen
│ ├── routes.ts # URL path registrations (eager)
│ ├── uis.ts # React component registry (lazy)
│ └── app.test.mjs # Tests for the tool and the screen
├── webpack.routes.config.js
├── webpack.uis.config.js
├── README.md # Its first paragraph is the package's description in Peers
└── package.json

src/package.ts declares what the package is: the tables, tools, observables, and events of the contracts it provides, and the contracts it consumes. Declaring a package covers each of them.

The build produces three output bundles:

BundleBuilt fromPurpose
package.bundle.jssrc/package.ts, by peers-package buildThe manifest Peers reads, and the package's code for the sandbox
routes.bundle.jssrc/routes.tsURL path mappings (loaded eagerly at startup)
uis.bundle.jssrc/uis.tsReact components (loaded lazily on navigation)

Peers reads a package's manifest without running its code, and runs the code in a supervised sandbox worker on Electron and headless hosts (a package can instead run as a privileged Node process; see below). Screens and widgets run in the app's window and reach the package through its contracts. See Routes and UI for how those bundles are loaded and why they are split.

Upgrade every peer that syncs a group before using a package's tables there; older hosts store package tables under a different name.

Set up IDs​

The template ships with placeholder IDs in src/consts.ts:

export const packageId = "<package-id>";
export const packageName = "<package-name>";
export const contractId = "<contract-id>";
export const contractVersion = 1;
export const appScreenId = "<app-screen-id>";

Replace the three ID placeholders with values generated by newid() from @peers-app/peers-sdk. All Peers IDs must be exactly 25 alphanumeric characters. You can generate IDs with the CLI:

peers new-id      # one id; `peers new-id 3` prints three

peers new-id runs locally, so the app needn't be running.

Update packageName to your package's display name and set peers.packageId in package.json to match packageId. Update the title and first paragraph in README.md too; Peers shows that paragraph as the package's description. The desktop creator fills in the IDs and name automatically.

Build and run​

npm install
npm run build

This produces dist/package.bundle.js, dist/routes.bundle.js, and dist/uis.bundle.js. Import the directory once with peers packages import <path>. After subsequent builds, install the new bundles and reload the UI:

peers packages reload <packageId>
peers ui reload
peers ui screenshot # prints the path of a PNG of the Peers window

Open the printed file to check what your package's screen looks like (an agent can open it too); peers ui inspect --text shows the visible text instead.

During development, npm run dev rebuilds all three bundles as you change files. After a change to the package itself, peers packages reload <packageId> installs the new build. npm test runs the template's tests, the tool against a fake host and the screen against mockHostContract, without a running host (Testing).

Webpack externals​

The renderer provides React, @peers-app/peers-sdk, @peers-app/peers-ui, and zod as globals. The route and UI webpack configs list them as externals so they are not bundled. The package's own code is not a webpack entry: peers-package build bundles it, with @peers-app/peers-sdk/define and any other libraries it imports.

Provider execution modes​

pkg.executionMode accepts exactly "sandbox" or "privileged". Omission keeps the SES sandbox: no ambient process, require, filesystem, or subprocess access. The field applies only to the package's code; routes and UI do not gain Node access. Privileged providers are supported in Electron and headless. The PWA runs sandbox providers in browser workers while the app is open. A privileged provider shows “This package runs only on desktop or headless” on the PWA. Packages with only screens and no provider load on every host.

PWA workers pause when the browser freezes the page and stop when it closes. System Scheduler restores overdue schedules at startup and catches up when the page resumes. System HTTP reaches only sites that accept requests from a browser there; see System HTTP in a browser.

A privileged provider is trusted device code. It runs in its own Node process as the same OS account as Peers, without root/admin elevation, in the user's home directory. It inherits Peers' environment; in the desktop app, PATH is the one the user's login shell sets, so tools installed with Homebrew and the like are found. It can access the filesystem, network, and subprocesses directly. Existing host bridge checks still apply to ordinary contract, table, pvar, and event calls, but direct OS access bypasses sandbox and network-policy confinement. There are no granular permissions or additional consent gate in this mode.

A privileged package imports Node built-ins as usual, and peers-package build bundles it for Node:

// src/tools/platform.tool.ts
import { platform } from "node:os";
import { AccessLevel, defineTool, z } from "@peers-app/peers-sdk/define";

export const platformTool = defineTool({
name: "platform",
usageDescription: "The operating system this device runs.",
accessLevel: AccessLevel.Reader,
inputSchema: z.object({}),
outputSchema: z.object({ platform: z.string() }),
handler: () => ({ platform: platform() }),
});
// src/package.ts: list platformTool in the contract's tools, then
export default definePackage((pkg) => {
// …
pkg.executionMode = "privileged";
});

Use Node built-ins only in a privileged package; a sandboxed package cannot load them.

Both IIFE and bundled CommonJS providers work, including bundles whose entrypoint has a leading #!/usr/bin/env node shebang. Node provides require, module, exports, __filename, and __dirname; the synthetic filename is .peers-isolate-provider.cjs in the user's home directory. It is not the author's package directory. Bundle dependencies into the source: the artifact format does not distribute package-directory assets or node_modules. Native modules and external files are not automatically installed on devices. The provider uses the Node version shipped with its host (Electron's embedded Node on desktop). What the provider and its child processes write to standard output and standard error is recorded in the device's logs, as process worker with the package's name as the source (peers logs -p worker -s "<package name>"), and also goes to the host's output. Very long lines are cut, and more than 100 lines a second are dropped and counted. Contract traffic uses a separate channel, so logging doesn't interfere with it.

A privileged provider can keep working after a tool call returns: a timer or a child process's output can write the package's own tables and pvars and emit its events, and consumers of a contract-exposed table see those writes through dataChanged as usual. A declared package starts when its contract is first used, including table reads and subscriptions. Starting it at activation isn't supported yet.

Startup stays lazy, with one session per package/data context. Normal deadlines still apply: Electron and headless allow 30 seconds for startup/evaluation and, by default, each tool call; a tool can declare timeoutMs up to 120 seconds. A timed-out call is rejected while the process and its state keep running; the session is terminated only when it then fails a liveness ping, or crashes, and the next invocation starts a fresh one. Startup and evaluation timeouts still terminate the session. Switching modes requires normal version replacement, which stops the previous session. Invalid replacements retain the old registration.

Activation follows existing device/group version selection, pin, and follow rules. A version that becomes active on several devices can therefore run privileged code on each of them. Downloading a version does not activate it.

Stopping a provider, on replacement, removal, or shutdown, first runs its pkg.onStop hooks (Background work), then ends the provider and the processes it started (on Windows, its process tree). Ordinary child processes, such as a long-running watch command, end with it. A process that detaches itself on purpose (spawned with detached: true, or a daemon such as a tmux server) keeps running: end it in onStop if it should stop. If Peers itself is killed, the provider ends its processes as soon as it loses its connection to Peers. Stopping can't undo filesystem, network, or other OS side effects. On Windows, a provider crash can leave child processes running; check for leftovers when the package next starts.

Building the package declaration​

Declare the package in src/package.ts with definePackage from @peers-app/peers-sdk/define, then build it with:

npx peers-package build

The build writes dist/manifest.json and dist/package.bundle.js from that declaration and prints the SDK version it used. Pin @peers-app/peers-sdk to the Peers version your devices run; import and reload warn, without failing, when the folder's SDK is newer. The manifest describes the package's tables, provided and consumed contracts, navigation, and permissions. Peers reads it without running your code; the bundle also contains the code that serves those declarations in the package's worker. Edit the declaration and rebuild when either changes.

Declaring a package covers the authoring APIs and build options. A package can contain only screens and provide no contracts. Build routes and UI separately as described above. The platform assigns versionTag and contract devTag when you promote a version; don't set them in code.

Author signing keys​

Each package has an Ed25519 author keypair used to sign non-dev publish artifacts:

  • Public key — stored on the Packages.publishPublicKey field (TOFU anchor for verifiers), with a recovery copy in the signing pvar's description. The versioned peers-package-signing-key:v1:<packageId>:<publicKey> marker is bound to that package ID and validated before use; the human-readable description is retained.
  • Secret key — stored as a secret user pvar named packageSigningKey_<packageId> in your personal data context. Do not commit it or paste it into chat/logs.

Keys are created when a package is first registered (create or import) if both the established public key and signing secret are missing. Re-importing the same directory reuses the target's established public key. When the target Packages row is absent, importing reuses the same package ID's first nonblank public key from your personal context or groups.

Uninstalling from any or all contexts leaves the personal signing pvar intact. Its cached public key lets a later import restore the same publisher identity even when every Packages row has been deleted. Imports lazily add this metadata to older pvars without changing or re-encrypting their stored secret value.

For legacy encrypted secrets without metadata, Node hosts (Electron and headless) use their existing user-secret decryption to recover only the public key for the importer. SDK hosts can supply the optional resolveSigningPublicKey(encryptedSecret) create/import callback for this recovery. If decryption is unavailable or fails, an established or cached public key can still be reused. A disagreement between established, cached, or recovered keys fails the import before any signing-key or package writes. An existing unreadable secret is never replaced automatically; if no public key is recoverable, restore publishPublicKey or unlock the secret before importing.

Explicitly deleting packageSigningKey_<packageId> removes your local author signing secret. If every installed copy of the package is also deleted, the next import generates a new publisher identity and restores the pvar's deterministic ID even if it was previously deleted. If an established public key remains in another context, Peers retains that identity without generating replacement keys; restore the matching secret to publish under it.

  • Declaring a package — definePackage, tables, tools, contracts, the peers-package build, and what the sandbox provides.
  • Routes and UI — how routes and UI bundles work, how to author them, and why to prefer route-based rendering.
  • Package lifecycle — develop, release, and run versions (dev / beta / stable).
  • Package contracts — versioned interfaces, validation, and worker isolation.
  • Voice skills — how a package becomes voice-addressable and contributes a widget.
  • System HTTP — host-mediated HTTPS, allowlists, and credential refs.
  • System Scheduler — device-local wake-ups of a package's own tool.
  • System Files — save and read files, such as images, in the package's context.
  • Package lifecycle design — design doc and shipped vs planned work.
  • System: Tables — how Peers models data with tables and reactivity.