Pikku Addons
What to reach for and why. For how to call it, run this once, from the addon with yarn pikku (there is usually no global pikku): yarn pikku doc addon wireAddon wireRemoteAddon ref refHTTP refChannel refCLI pikkuAddonServices pikkuAddonWireServices pikkuAddonConfig defineHTTPRoutes wireHTTPRoutes. Depth: references/openapi.md, references/addon-package-manifest.md.
An addon is a reusable function package shared across projects: functions, services, secrets and variables in one self-contained NPM package. See pikku-concepts for the core mental model.
Is it an addon?
- Functions another project should reuse → addon.
npx @pikku/cli new addon <name>. - An OpenAPI spec, a spec URL or a catalogue name is an addon: generate it, never hand-write the client functions. Follow
references/openapi.md, section 'Build with an OpenAPI addon':pikku addons search <words> --openapi(skip it when you were given the spec or the name),pikku addons add <name|url|path> --auth none, thenpikku meta grep <addon> <words>andpikku meta functions get <addon>:<function>, one write,pikku all,pikku check. Use--auth noneonly for an API that takes no key; if the spec has operations without an id, their names areget,get2, ... andfunctions getshows the fields to tell them apart. - A screen shows the addon's data as the addon returns it → call the addon function itself. Name it in
wireAddon({ expose: [...], auth: true })and the frontend callsrpc.invoke('todos:listTodos', …)(over HTTP,POST /rpc/todos:listTodoswith{ "data": … }), still behind the session. Useref('todos:listTodos')on an HTTP or MCP wiring only when the addon needs a route of its own. - The app needs the data narrowed, typed or combined, or adds a permission of its own → write an app function that calls it. A flag the upstream sends as
"0", a total summed from several calls, one field out of fifty. Name it for what the screen means (getMyProfile), not the upstream operation (usersRetrieveInfo), and give it anoutput:schema of only what the app uses. OpenAPI-generated outputs mirror the upstream's loose, oversized payloads, and the wrapper is where they become the app's own shape. - Never write an app function that calls
rpc.invokeand only copies the addon's schema. It is a second name and a second schema for the same thing, and it drifts. A wrapper that enforces ownership or another permission may return the result unchanged; that is how a protected addon function is exposed to a screen without exposing it directly. - An agent tool → just another
ref()intools. Seepikku-agent.
Working on one
Discover first (pikku meta … --json, pikku info functions --verbose, pikku info tags --verbose). Find the source that owns the behaviour; do not start from generated output, .pikku, node_modules, vendored packages or build artifacts. Make the smallest source change, never hand-edit SDKs, schema output or typegen, validate narrowly first, then pikku all when functions, wirings, schemas or clients may have changed. If validation fails, fix the source cause and rerun.
Security rules
auth,tagsandscopesonwireAddononly ever tighten.auth: falseis not honoured, because it would weaken the wiring's own gate: the addon-level setting can require a session but never waive one. The same package wired twice under two namespaces is governed by the union of both instances' scopes and tags.- Nothing in an addon is reachable over
/rpcuntil the wiring opts in, and it can only open what the addon itself declaredexpose: true. An OpenAPI-generated addon declares every operation, so list the ones the frontend needs. scopesonwireAddongate every function at once, and a wiring carries middleware, not permissions. A rule on one addon function lives in thepermissionsof an app function that calls it.- An addon called with the user's own credential is already limited upstream, so a data-aware
pikkuPermissionrepeating that check (may they read _this_ invoice?) adds nothing. A session-onlypikkuAuth(a role, a tier) is still worth it: it can be checked before any input exists, so the functions a user can't call drop out of the tools an MCP client, an agent or a workflow is offered, instead of failing upstream when called. - An addon reads only the secrets it declared. Its
SecretServiceandCredentialServiceare scoped: literalgetSecret('X')calls andwireSecretdefinitions, which the CLI collects intodeclaredSecrets. Anything else throwsAccess denied to secret key: Xat runtime. The same holds for credentials, and a scoped addon can never callgetAllUsers(). - A _generic_ addon whose secret names arrive as data (
@pikku/addon-graphreadsgetSecret(auth.credential), the name coming off the workflow node) declares nothing and is scoped to nothing. Only the consuming app can widen it: secretOverrides: grant and rename.secretGrants: grant as-is.globalSecrets: grant everything, with a written reason.- Grants name the secret as the addon reads it, not as your project stores it. Scoping is checked _before_ the override map renames anything, so an overridden secret is granted by its addon-side key: an override's key grants and its value does not.
globalSecretsandglobalCredentialstake the _reason_, not a boolean, because every grant is enumerated in the deploy manifest (unscopedSecretAddons,grantedSecretAddons). PrefersecretGrants. UseglobalSecretsonly when no static list can exist, and never for an addon that performs outbound requests, where an unrestricted secret read is an exfiltration primitive.- A grant naming a secret your project does not declare is a build error from
pikku all, resolved through the override map first:Secret grant 'STIRPE_KEY' in addon 'graph' (@pikku/addon-graph) targets a secret that does not exist. Available secrets: ….
What an addon must not do
pikku validate fails an addon that reaches past the services it is given. An addon is installed into other people's apps, so the host, not the addon, decides where files live, which processes run and what the environment holds. Each of these is a validate error with a fix that stays inside Pikku:
- No
fs(node:fs,fs/promises,fs-extra,require('fs')). Use thecontentservice: keyed, project-scoped, with signed reads and writes. - No
child_process(execa,cross-spawn,shelljs,Bun.spawn,Bun.$). Use the Supervisor, which owns the process, its lifecycle and its output. Type-only imports fromnode:child_processare fine. - No
process.env, including{ ...process.env },const { env } = processandglobalThis.process.env(also throughglobalandself). Use thevariablesservice for values andsecretsfor secrets, declared as above. - No
process.argv(Bun.argv,Deno.args,globalThis.process.argv,commander,yargs,minimist,parseArgs). Expose apikkuCLI command, which receives typed input.
start.ts, server.ts, **/bin/**, **/scripts/** and tests are exempt. Anywhere else, a one-line // oxlint-disable-next-line <rule> -- reason is the only way out. Do not set lint.enforce* to "off" to make an addon pass. These keys apply to apps and addons, not to library packages: a library or developer-tool package that pikku validate checks sets the key it cannot meet to "off" in its own pikku.config.json.
Writing an addon
- Inside an addon, import from
#pikku/addon/functionand#pikku/addon/setup, never#pikku/function. The generated tree roots at.pikku/addon/, and inside the addon#pikku/functionnames a leaf that does not exist. - Declare zod schemas in a file that never imports
#pikku.pikku allloads the file that declares each schema to convert it, and at runtime#pikkuresolves through the package'simports, into adistthe first build has not written yet. Inline, every schema fails withCould not convert Zod schema … Cannot find module …/dist/.pikku/…and the addon never builds from clean. Use a sibling<fn>.schemas.ts, which is what--openapigenerates. - Export
pikkuAddonServices(...)as it is. A cast around it (as unknown as CreateSingletonServices<...>,<T>,!) hides the factory from the inspector, which would leave it unregistered and the addon's workflows failing at runtime; the build fails withPKU564instead. Fix the type the cast was hiding.satisfiesand parentheses are fine. - An addon never falls back to its own logger, variables or secrets; the consuming app supplies them.
secretsandvariablesarrive typed against the addon's own declarations, and a secret is aSecretValue:.reveal()is the only way to the plaintext (seepikku-services). pikkuAddonWireServicesis only for functions that need per-request services.- There is no
addon()helper;ref()covers local and addon functions (ref('todos:addTodo'),ref('myLocalFunc')) and proxies the call via RPC at runtime.refHTTP,refChannelandrefCLIare for an addon that publishes wiring contracts rather than bare functions: they carry its route and config metadata.
Building
- Use
yarn pikku, notnpx pikku: a scaffolded addon carries@pikku/clias a devDependency, and building against a different CLI than it declares is how generated output ends up disagreeing with the packaged one.npx @pikku/cli new addonis the exception: it runs before the addon and its CLI exist. yarn buildis prebuild (pikku all) thentsc && pikku dist.yarn pikku validatechecks that the published file set holds together. Leavepikku distout and the addon installs fine and fails to typecheck in every app that depends on it, because it copies whattsccannot emit: the generated*.gen.jsonmeta and the hand-writtentypes/*.d.ts.- A
remote: truefunction's input and output must be exported zod schemas. Apps usingwireRemoteAddonbuild against the SDK, not the source. Generics (pikkuSessionlessFunc<In, Out>) or a return type declared insrc/fail codegen with PKU922. Non-remote functions can keep generics. - In an addon,
pikku allpacks the SDK on every run, at the package.json version, into.pikku/sdk/and<scope>-<name>-<version>.sdk.tgz. It carries only the remote RPCs, theexpose: trueworkflows and the types they reach. Changing a publishedremote: truecontract needs a newversionon the function;yarn pikku versions checkenforces that.
Calling another addon
- Declare it in the addon's package.json (not pikku.config.json), by alias and range:
"pikku": { "uses": { "stripe": "@pikkustudio/addon-stripe@^0.12.0" } }. - Call it typed:
rpc.invoke('stripe:charge', …),rpc.startWorkflow('stripe:refund', …). Never castrpcor call by the package name; the alias is the only name that works. pikku allin the addon typesstripe:*from the dependency's SDK. A package in the same workspace is read from its own<outDir>/sdk, so runpikku allthere first; anything else is fetched from the registry and pinned inpikku-addons.lock.- The app wiring your addon maps the alias with
usesonwireAddon, local or remote alike:uses: { stripe: 'payments' }, wherepaymentsis the name it wired the dependency under. - At runtime an unmapped alias, or the wired name called directly, throws
AddonNotUsedError(403) for invoke, workflows and agents.
| Code | pikku all fails when |
| ------ | ------------------------------------------------------------------- |
| PKU338 | the workspace SDK is missing |
| PKU354 | the version or mapped instance is outside the range |
| PKU348 | an alias the addon declared is not mapped |
| PKU347 | it is mapped to a name not wired, or wired from another package |
| PKU355 | uses maps a name the addon did not declare |
| PKU356 | the addon's pikku.uses entry is malformed (alias, type, no range) |
Database tables
An addon may ship tables. It must never create them: it runs inside the consumer, against the consumer's database, so a boot-time CREATE TABLE puts a second authority on a schema the consumer's migrations own. It declares instead, and the consumer's pikku db generate creates them with its own.
- Declare them in the addon's
db/tables.ts, withdefineTablesfrom@pikku/core/db: the same columns, constraints and annotations an app uses. No SQL per dialect, and no database is needed to publish. - Every table name starts with the name the consumer wires the addon under, snake-cased (
wireAddon({ name: 'labels' })ownslabelsLabel, which islabels_label).pikku db generaterefuses an addon table without its prefix, and a table name declared twice (by the app and an addon, or by two addons). declareOnlyis refused in an addon: an addon creates what it declares. A reference to a table the consumer owns (user.id) is allowed.pikku allpublishes the declaration as plain JSON in<outDir>/db/pikku-db-meta.gen.jsonon every build, and writes{}when the addon has no tables, because a consumer reads an absent file as a package that cannot say. (pikku db exportwrites the same file on demand.) An addon that still shipsdb/postgres|sqlite|mysqlSQL and nodb/tables.tsfails the export, in one line.- The consumer resolves it through the package name, so it must be exported and packed:
"exports": { "./.pikku/db/pikku-db-meta.gen.json": "./dist/.pikku/addon/db/pikku-db-meta.gen.json" }, "files": ["dist"]. - An unresolvable artifact stops
db generate. Absence means the package was built with an older CLI, orexports/filesdo not carry it; the error names both causes. An artifact in the old SQL-per-dialect shape is refused too: rebuild or upgrade the addon. verifiers/db-schemaruns this end to end on sqlite, postgres and mysql. Copy its addonpackage.jsonanddb/tables.tswhen wiring a new one.
Consuming an addon
- When the CLI cannot tell you, report it; do not dig for it.
pikku doc,pikku metaandpikku addons searchare the source of truth for how Pikku is called and what this project has. If one fails, or lacks a fact you need, runpikku report "<the exact command and what was missing>"once, then carry on from what you do know. Do not readnode_modules,distor.pikkuto work around it: the report is how the gap gets fixed. - Which addon? Search the registry first:
pikku addons search <terms>. Run it from the app's package, with the vendor name (slack) or what the user wants to do (send a text message,spreadsheet). It lists matching addons, marks eachwiredorinstalledwhen this project already has it, and ends in a verdict: wiredorinstalled: use that one; do not add a second addon for the same job. Say which you used.exact: one clear match;pikku addons add <name>installs and wires it.several: no clear winner and none in the project. The user chose the service, so ask which one, naming at most four (first-party first). When the request says to decide and build without asking, take the first result, build with it, and say in your final message which addon you picked and why.none: try one shorter word;--openapialso searches the OpenAPI catalogue (every API with a spec; each row shows its auth and price), and--authlesskeeps only the ones that need no key and are free (add one with--auth none); otherwise ask for the service name or an OpenAPI spec. Never hand-write a vendor client to get past a miss.- Learn an addon's functions from the CLI, never from files. Once the addon is wired and
pikku allhas run, from the package that wires it:pikku meta grep <name> <words for what you want>ranks that addon's functions (pikku meta grep slack post messageputsslack:chatPostMessagefirst), andpikku meta functions get <name>:<function>prints its input and output fields, required ones without a?. That is the whole lookup; a step is thenawait workflow.do('Post to Slack', 'slack:chatPostMessage', { ... }).pikku meta functionslists which addons are wired. The addon'snode_modulesfolder, itsdist/.pikkuand this project's.pikkuhold the same facts in a form that costs many reads to piece together, and they are generated: nothing there is yours to read or edit. - After
wireAddon, runyarn pikku allto generate types for its functions. - Use the addon's functions as workflow steps; do not rebuild them. Once
wireAddonis in andpikku allhas run, each of the addon's functions is addressed<name>:<function>, where<name>is thenamegiven towireAddon. In a workflow, call one as a step:await workflow.do('Post to Slack', 'slack:chatPostMessage', input); The step is the call: do not write a function of your own that doesrpc.invoke("<name>:<function>")to reach the addon, because then no workflow step names it and the workflow records nothing for it. When the input needs data from earlier steps, build it in the workflow body from those results (the body may use plain object literals) and pass it straight to the addon step.pikku meta grep <name>lists what the addon offers (beforepikku allit matches nothing) andpikku meta functions get <name>:<function>gives the input and output shapes. The addon reads its own secrets (pikku addons addprints which to fill in), so a function of your own that wraps the vendor's API is the wrong layer, and a wired addon that no step calls does nothing. - In a workspace, add the addon to the dependencies of the package whose file calls
wireAddon, not the repo root. Codegen resolves from the package that wires it first and the project root second, and a remote addon'sdevDependenciescheck reads that same manifest. If codegen reports PKU340, the dependency is missing from the package its message names: do not add it at the root to paper over it.verifiers/addon-workspaceis that layout. - If the addon ships tables,
pikku db generateadds them to the app's own declaration and writes them into theapp-tablesmigrations, after Better Auth's and the runtime's, so an addon table may referenceuseror a runtime table.pikku db migrateapplies them. Re-runninggeneratewrites nothing once covered, and only the delta after an upgrade; a column or table the addon drops waits for--allowDestructive, like the app's own. AwireRemoteAddonaddon contributes no schema: its tables belong to the deployment that runs its functions. - A
wireRemoteAddonwhosepackagecarries a range ('@scope/name@^1.4.0') is not installed at all:pikku alldownloads its SDK into.pikku/remoteand pins it inpikku-addons.lock(commit the lock). If codegen reports PKU338 for one, runpikku all, not an install. To move to a newer SDK, edit the range by hand (pikku updateprints the file:line and the new literal; it never rewrites source), then runpikku all.
Studio screens
An addon declares the screens it adds to Pikku Studio with definePlugin, in src/screens.ts (npx @pikku/cli new addon <name> --ui scaffolds one). It replaces defineScreens, which no longer exists.
- A screen is a lazy
componentor anapp, never both.navis optional: without it the screen is routed but not listed. scopesonly hide the screen; they are NOT access control. The addon's functions must enforce the same scopes.replaces: truetakes over the core screen at the same path (first-party addons only; Studio enforces that).- Titles are message keys in the addon's
messages/{locale}.json, found by convention next to itspackage.json; there is no field for them. - The inspector reads every field statically, so each must be a literal.
- A key missing from another locale's catalog is a warning.
defaultChat: falsehides Studio's general Chat tab on the screen, so the screen'sagentis its only chat.agents/andskills/ship in the package: afileslist must name both folders; a root glob such as**/*.mddoes not count.package.jsoncarries astudioblock,{ "addon": "<name>", "ui": "./src", "messages": "./messages/{locale}.json" }. Studio only links a package withstudio.addon, the<addon>in an agent's scopeagent:<addon>:<name>.--uiscaffolds it.- Optional
widgets(own components, by id),things(cards, by kind) andarrangedScreens(screens Studio lays out from widgets, by id; nocomponent/app/nav). ImportdefinePluginfrom#pikku/addon/screensso tsc checks them against the addon's functions andmessages/en.jsonkeys. - A slot
{ widget, from, span?, compact?, copy? }:widgetis the addon's own or a core widget (typed byWidgetRegistry, filled by Studio);fromis a key of thesourcefunction's output. source(and an action'srun) names a function of the addon or a project RPC'<namespace>:<function>'(e.g.'console:listAgents'), whose output is untyped. An action'srunmay also be'go:/<path>'to send the viewer there. A project RPC needs nopikku.usesentry.- Sources return data only:
{ variant, values }. Words are message keys incopy, per variant (slot: the widget's texts; thing:name,compact,lead?,primary?: { label, draft? }). Never return or declare plain text: text is always a declared key or an explicitly marked dynamic value.{placeholders}are not typed againstvalues. - Copy entries nest (
status: { text: key },tags: { 0: key }); a value naming a variant is worded by that variant's$(why_timeout: { $: key });figures: [{ variant, value?: { n, unit } }]are worded by{ label, note?, value? }. Share copy through a top-levelconst ... as constin the same file and spread it; the inspector does not follow function calls or imports (PKU345). actions: { id: { run, label, confirm?, destructive? } };destructive: truerequiresconfirm. Arranged screens also takeredirect({ variant: screenId | '/path' }) andpoll(ms or{ fast, slow }).
| Code | pikku all fails when |
| ------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| PKU345 | a field is not a literal (call, import, a variable other than a same-file top-level const, bad value), a malformed RPC or go: name, or a destructive action without confirm |
| PKU357 | two screens of the addon use the same path |
| PKU358 | a title, agent frontmatter, widget, thing, arranged screen, slot copy (nested, $, figure) or action key is missing from messages/en.json |
| PKU359 | nav.badge names no function of the addon |
| PKU365 | agent is neither a name nor studio:<name>, or a name has no non-empty agents/<name>.md, or no frontmatter title and description |
| PKU366 | package.json files leaves out agents/ while a screen names a valid (no PKU365) non-studio: agent, or skills/ while the addon has a skills/<name>/SKILL.md |
Not in `pikku doc` yet
- Scaffold:
npx @pikku/cli new addon <name> [--display-name Stripe --category Payments --dir addons]writespackage.json(exports.pikku/*+dist/),pikku.config.json(addon: true),tsconfig.json(#pikkupath mapping),src/services.ts,src/functions/,types/application-types.d.ts. wireAddonexposeas a list: PKU343 on unknown or undeclared names.definePluginfrom@pikku/core/addon, default-exported:{ title, screens: [...] }. Each screen:path,title(message key, also the nav label),scope('studio'→/<path>,'team'→/<team>/<path>,'project'→/<team>/<project>[/<target>]/<path>),component: () => import('./screens/X.js')orapp,nav: { area, icon, order, badge },needsApp(project screens only, default false),scopes,layout: 'bare'(renders without the shell),replaces,agent.nav.areais'rail','team','project'or'account'.badgenames one of the addon's functions that returns a count.agent: 'name'makes that agent answer in Studio's chat panel (a second tab beside the general chat) while the screen is open. It resolves toagents/<name>.mdat the addon's package root: the agent's instructions, naming the skills it follows (plain foldersskills/<name>/SKILL.md). The file starts with frontmatter whosetitleanddescriptionare message keys inmessages/en.json. The name matches/^[a-z][a-z0-9-]*$/.agent: 'studio:<name>'picks an agent Studio ships;pikku allonly checks the format and looks up no file.