@camstack/develop 0.1.2 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,445 @@
1
+ ---
2
+ name: camstack-addon
3
+ description: Create or change a CamStack addon (plugin) — a device provider, notifier, storage or log destination, pipeline stage, exporter, a builtin, or any new `camstack.addons[]` manifest entry. Covers the silent wiring misses (vite entries, `super({})`), forked vs in-process behaviour, the two per-device settings stores, custom actions, device-page widgets, `camstack deploy` and its traps (installs, may not respawn, ships what is built), and how to prove the new code is the code running. Use for "new addon", "add a provider", "my addon change has no effect", "the addon is running but nothing happens".
4
+ ---
5
+
6
+ # Creating or changing an addon
7
+
8
+ Written from doing it. Every step below exists because skipping it produced a
9
+ failure that compiled, passed tests, and broke at runtime or left the docs
10
+ lying. Long-form: `docs/architecture/addon-lifecycle.md` (processes, boot,
11
+ crashes) and `docs/architecture/addon-custom-actions.md`.
12
+
13
+ > Skill names with no file in this pack (`camstack-ui`, `camstack-ui-admin`,
14
+ > `camstack-server-change`, `camstack-diagnose`, `camstack-publish-ci`) are
15
+ > server-repository skills under `.claude/skills/`; this text stands on its own.
16
+
17
+ ## Tooling (prefer this over hand-copying)
18
+
19
+ ```bash
20
+ camstack develop scaffold addon <name> [--kind empty|provider|notifier|osd|post-analysis]
21
+ camstack develop extend <existing-addon> --entry <new-id>
22
+ camstack develop find-example <topic>
23
+ camstack develop validate <name-or-path>
24
+ ```
25
+
26
+ Nx equivalent (same idea): `nx g @camstack/nx-plugin:addon <name>`.
27
+ The develop scaffold also writes `vite.config.ts` `entries` — the miss that
28
+ fails only at runtime.
29
+
30
+ ## 1. Decide where it lives
31
+
32
+ - **A builtin** (`packages/system/src/builtins/<name>/`) if the kernel cannot
33
+ function without it, or it must exist on every node with no install step.
34
+ Builtins ship inside the `@camstack/server` closure.
35
+ - **Its own package** (`packages/addon-<name>/`) otherwise. Install is then the
36
+ opt-in, and it updates via `camstack deploy` independently of the framework.
37
+
38
+ Read `docs/architecture/addon-lifecycle.md` first if you are unsure.
39
+
40
+ ## 2. Write the addon
41
+
42
+ ```
43
+ packages/<pkg>/src/<path>/
44
+ <name>.addon.ts the BaseAddon subclass
45
+ <name>-<thing>.ts the provider implementation
46
+ index.ts barrel, re-exporting the addon class
47
+ __tests__/
48
+ ```
49
+
50
+ Rules that bite:
51
+
52
+ - **Providers must not log if they sit on the logging path.** A
53
+ `log-destination` that logs feeds itself. See `loki-destination.ts`.
54
+ - **`write`-style hot methods must not throw.** `LogManager` fans one entry to
55
+ every destination; throwing takes the siblings down.
56
+ - Keep behavioural capability metadata OUT of the manifest — it belongs in the
57
+ `*.cap.ts` (D4).
58
+ - Emit only through `ctx.eventBus` with the `EventCategory` enum
59
+ (D11).
60
+ - Never `console.log` — use `ctx.logger`.
61
+
62
+ ### Rules that bite at RUNTIME, not at build time
63
+
64
+ - **A `BaseAddon` subclass must call `super({})`** (or `super(defaults)`).
65
+ Without it `resolveConfig` throws `Cannot convert undefined or null to
66
+ object` at init — build, tests and `check-addon-entries` all pass, the node
67
+ lists the addon as running, and the boot log says the builtin "failed to
68
+ initialize — skipping", sometimes followed by a misleading "Package
69
+ directory missing". Call one of its caps to prove it is alive.
70
+ - **`ctx.kernel.devices`** (create / register / remove / list) is on EVERY
71
+ addon, not only on `BaseDeviceProvider`. An addon that owns devices it
72
+ declares itself (an integration's panel, a synthetic device) reconciles them
73
+ with `DeclaredDevices` (`packages/types/src/device/declared-device.ts`) —
74
+ never a private `ensure…Device` (`scripts/check-declared-device-single-owner.ts`).
75
+ - **A settings collection is declared before it is queried.** The SQLite
76
+ backend refuses an undeclared collection (`declareCollection` in `init()`);
77
+ the in-memory test store auto-creates buckets and hides the miss, so pin the
78
+ path with a spec on the real backend.
79
+ - **Device state in a FORKED addon can go stale.** A `device.state-changed`
80
+ push does not reliably reach forked children, so a consumer of
81
+ `proxy.state.<cap>.value` reconciles with `refresh()` on a timer.
82
+ - **Device providers:** emit motion on every tick the camera reports, not only
83
+ on the rising edge — the pipeline's motion phase is keepalive-driven and
84
+ expires without it. Write the cap slice on the edge only.
85
+ - **Two per-device settings stores.** A forked addon reads its per-device
86
+ config from `<addonId>:addon-devices` (one blob per device);
87
+ `addonSettingsRaw.updateDevice` writes a DIFFERENT table. The UI path
88
+ (`applyDeviceSettingsPatch`) is right. A script fixing one device writes
89
+ `settingsBackend.set {collection:"<addonId>:addon-devices", key, value}`,
90
+ which REPLACES the blob — read it with `settingsBackend.query` and merge first.
91
+ - **Bundle pure-JS dependencies** (put them in `devDependencies`); runtime
92
+ `dependencies` are for true natives only, because the installer runs
93
+ `npm install` on a node only when runtime dependencies remain.
94
+ - **A forked addon serving its own HTTP** goes through the hub's
95
+ `/addon/:addonId/*` bridge, which does not compress (`server/backend/src/main.ts`);
96
+ own the encoding end to end and never add compression to a byte-stream route.
97
+ - **Secrets** — any password, token or key field, `secretStatePaths`, a
98
+ credential for a spawned child: the `camstack-secrets` skill. Never read a
99
+ credential from the environment.
100
+
101
+ ## 3. Wire it — the four places, one of which is silent
102
+
103
+ | # | Place | What happens if you miss it |
104
+ | --- | --- | --- |
105
+ | 1 | `camstack.addons[]` in the package's `package.json` | the addon does not exist |
106
+ | 2 | **`vite.config.ts` `entries` map** | **everything compiles and the addon fails at runtime** |
107
+ | 3 | `src/index.ts` re-export | consumers and tests cannot import it |
108
+ | 4 | `packages/system/src/index.ts` (builtins only) | same |
109
+
110
+ Number 2 is the one. A manifest `entry` is just a string — nothing resolves it at
111
+ build time. `scripts/check-addon-entries.ts` now catches it; run it.
112
+
113
+ Manifest fields worth knowing: `protected: true` blocks uninstall ·
114
+ `execution.placement: 'agent-only' | 'any-node'` (default `hub-only`) ·
115
+ `execution.group` co-locates into one process (D2)
116
+ · `instanceMode` · `storageLocations` · `icon` / `color`.
117
+
118
+ **`icon` is a promise the hub must keep.** It is an asset PATH inside the
119
+ package (`assets/icon.svg`, or `assets/<addonId>/icon.svg` when one package ships
120
+ several addons — `@camstack/system` does this for every builtin), and the folder
121
+ must be in `files` or `npm pack` drops it. The Admin UI requests
122
+ `/api/addon-assets/<addonId>/<icon>` only for an addon that declares one
123
+ (`addon-admin-ui/src/lib/addon-icons.ts`); everything else draws a glyph with no
124
+ request, so never build that URL by hand or guess an id. House style: 24-unit
125
+ `viewBox`, no fill, `stroke-width="2"`, round caps/joins, a fixed stroke colour
126
+ (the `<img>` cannot inherit `currentColor`), legible at 16 px.
127
+ `scripts/check-addon-icons-shipped.ts` fails CI on a declared icon that is
128
+ missing or unshipped.
129
+
130
+ **`description` is not optional in practice** — it is what
131
+ `docs/reference/addons.md` and the Admin UI show. An addon with no description
132
+ documents itself as `—`.
133
+
134
+ ## 4. Opt-in, if it should be off by default
135
+
136
+ There is **no `enabled` flag on a manifest**, and **no `enabled` setting in an
137
+ addon's own config either** (D777): the capability toggle is the ONE enable. A
138
+ private "master switch" is a second truth that can say "off" while the toggle
139
+ says "on". The scaffolds do not generate one; do not add one. The real
140
+ mechanisms:
141
+
142
+ 1. **Config-default inertness** — an empty required field (a URL, a token) in
143
+ the addon's own settings, which the provider treats as inert. Register the
144
+ provider anyway, so the UI can show it and the operator can configure it.
145
+ This is what `loki-logging` does.
146
+ 2. **Capability toggle** — `addons.setCapabilityProviderEnabled({ capName,
147
+ addonId, enabled })`, the Enable/Disable control the UI already shows.
148
+ Collection caps only; persisted **globally** under
149
+ `capabilities.collection.<cap>`, not per node. It refuses a provider that is
150
+ not registered yet, so never call it from `onInitialize` (the providers it
151
+ returns register only after it returns) — retry in the background, as
152
+ `loki-logging/retire-enabled-flag.ts` does.
153
+ 3. **A separate npm package** — installing it is the opt-in.
154
+
155
+ Prefer 1 for "needs configuring first", and 2 for an on/off choice.
156
+
157
+ ## 5. Verify
158
+
159
+ ```bash
160
+ npm run codegen # only if you touched a *.cap.ts
161
+ npx tsx scripts/check-addon-entries.ts
162
+ npm run typecheck && npm run test # typecheck = code + specs vs the pinned debt (D695)
163
+ npm run typecheck -w packages/<pkg> # your package raw: a NEW addon has no pinned debt, so it must be clean
164
+ npm run docs:check
165
+ ```
166
+
167
+ Then **actually build it** and confirm the entry was emitted:
168
+
169
+ ```bash
170
+ npm run build -w packages/<pkg> && ls packages/<pkg>/dist/<path>/
171
+ ```
172
+
173
+ ## 6. Documentation
174
+
175
+ `docs/reference/{addons,packages,capabilities,guards}.md` regenerate from the
176
+ manifests on commit — do not describe your addon in prose a table covers. The
177
+ rest (sessions entry, an ADR for a rejected alternative, a package
178
+ `AGENTS.md` for traps a future session will hit — see
179
+ `docs/addons/addon-provider-reolink.md`) follows the `camstack-docs`
180
+ ladder. `npm run docs:check` fails on a dead path.
181
+
182
+ ## 7. Ship it — and prove the new code is the code running
183
+
184
+ An addon runs from its DEPLOYED copy under `<dataDir>/addons/@camstack/<name>/`
185
+ (in a workspace dev hub, the data dir under `server/backend`), never from
186
+ `packages/<name>/dist`. Editing and rebuilding has **no runtime effect** until
187
+ you deploy. A **builtin** travels inside `@camstack/server` instead — the
188
+ `camstack-server-change` skill (D16).
189
+
190
+ ```bash
191
+ camstack deploy packages/addon-<name> # to the hub; or: camstack deploy <name>
192
+ camstack deploy packages/addon-<name> -n <nodeId> # to one agent — one node at a time
193
+ camstack deploy packages/addon-<name> --no-verify # then poll /health yourself (below)
194
+ ```
195
+
196
+ Auth comes from `camstack login` (cached per server) or `--token` /
197
+ `--token-file` / `$CAMSTACK_TOKEN`; `-s <url>` names the hub. Full reference:
198
+ `docs/architecture/update-and-release.md` §"Deploying an addon during
199
+ development", which also has the stale-addon detector to run after a rebase.
200
+
201
+ Traps, each of which has cost a session:
202
+
203
+ - **`deploy` INSTALLS, it does not only update.** Deploying a package that is
204
+ not installed on the target hot-loads it — a second provider on a singleton
205
+ can break a working one. Check the target's addons first
206
+ (`nodes.getNodeAddons`; `addons.list` can be a stale cache).
207
+ - **It ships what is BUILT in that package, committed or not** — including
208
+ another agent's work in the same tree. "Do not deploy" in one brief does not
209
+ stop a sibling from deploying the same package; keep must-not-ship changes
210
+ out of the built tree.
211
+ - **It may not respawn the runner.** The new dist can land while the old
212
+ module keeps running. Confirm a fresh process (a new PID / boot line for the
213
+ addon) or call `addons.restartAddon({ addonId })`.
214
+ - **A multi-manifest package may come back partly unregistered.** After the
215
+ deploy, check `capabilities.listCapabilities` (or `getCapability`) for every
216
+ cap the package provides; a cap with no provider → `addons.restartAddon`.
217
+ - **The post-deploy health probe races the restart** and reports
218
+ `1/1 target(s) failed` after a successful install — use `--no-verify` and
219
+ poll `/health` yourself.
220
+ - **`-n <nodeId>` accepts an id that does not exist** and still prints
221
+ `✓ Deployed`. Verify on the node. `nodes.deployAddon` does not ship bundles —
222
+ the CLI's `-n` is the channel.
223
+ - **Agents run their own copy.** A hub deploy does not update an agent's copy
224
+ of a hub-only addon, and enabling a feature on a node whose code lacks it
225
+ shows as "Cannot register provider for undeclared capability" — version
226
+ skew, roll the enablement back.
227
+ - **Repeated rapid deploys of media addons** (stream broker, providers)
228
+ degrade the hub. One deploy, then verify; a restart only if needed.
229
+ - **The hub auto-updater** applies newly published npm versions on its
230
+ schedule and can replace a CLI-deployed build whose version differs; deploy
231
+ after the version-bump commit, and check `addons.setAddonAutoUpdate` for
232
+ framework packages.
233
+ - **admin-ui** deploys need no hub restart, but a browser keeps the old PWA
234
+ bundle until a hard reload; a blank page with a "MIME type text/html" module
235
+ error is a stale service worker.
236
+ - **Never hand-edit the node's addon manifest** (`<dataDir>/addons/manifest.json`):
237
+ an entry whose directory is gone kills the runner and everything co-located.
238
+ "Required and cannot be uninstalled" comes from `protected: true` in the
239
+ installed `package.json`.
240
+
241
+ **Proof the change is live**: grep the deployed bundle for a string that is
242
+ new in this build, then exercise the behaviour (call the cap, press the
243
+ button, watch the new log line) — the `camstack-diagnose` skill. A deployed
244
+ bundle is not the running code until the process restarted.
245
+
246
+ ## Extending (second entry in one package)
247
+
248
+ Multi-entry packages (auth, cloudflare, …) need a new id, source file, manifest
249
+ row, **and** vite `entries` key. Prefer:
250
+
251
+ ```bash
252
+ camstack develop extend <package> --entry <new-id>
253
+ ```
254
+
255
+ ## Operator buttons (custom actions)
256
+
257
+ An addon-owned RPC on the `addons.custom` bridge, rendered by the settings form
258
+ as a button — no bespoke admin page. Read
259
+ `docs/architecture/addon-custom-actions.md`
260
+ BEFORE adding one.
261
+
262
+ The trap it exists to prevent: there are **two** registration paths, and which
263
+ one applies depends on whether the addon runs in-process or forked — which is
264
+ not a property of the source. Populate BOTH the `customActions` named export of
265
+ the entry module AND the `customActions` returned by `onInitialize`, or the
266
+ bridge answers 404 with your code visibly present in the built bundle.
267
+
268
+ ## A UI surface on a DEVICE page (widgets)
269
+
270
+ Your addon has an editor, a panel, a canvas — richer than a form — and it
271
+ belongs on the camera's own page. Read this before writing any of it, because
272
+ one of the available mechanisms **silently does nothing**, and choosing between
273
+ the other two is a judgement call with a rule
274
+ (D526).
275
+
276
+ ### What the device page actually asks
277
+
278
+ `getDeviceSettingsAggregate` is **binding-driven** (`device-aggregation.ts`,
279
+ D12): it walks the `(cap, provider)`
280
+ pairs bound to THIS device and asks each. Cap names are shared across vendors
281
+ and a device belongs to exactly one integration, so a contribution may only come
282
+ from a provider bound to it. For each binding it either derives the section from
283
+ a `deviceConfig` cap (D14) or, when the
284
+ cap sets `exposesDeviceSettings`, asks the provider —
285
+ `registry.getProviderByAddon(capName, entry.providerAddonId)`, the ADDON's
286
+ provider, never the per-device native.
287
+
288
+ **There is no addon-level route into that page.** That is deliberate, not an
289
+ omission.
290
+
291
+ ### The trap
292
+
293
+ Declaring a `type: 'widget'` field in your addon's `deviceSettingsSchema()`
294
+ looks right and is valid everywhere you can check it: the hub returns the
295
+ section, `ConfigFormField` renders `type:'widget'` via `WidgetField`, your
296
+ component is in the shipped bundle. **Nothing appears**, because that method
297
+ feeds only **Cluster → Pipeline → Device Overrides**, whose addon set is a
298
+ hand-written list:
299
+
300
+ ```ts
301
+ // packages/addon-admin-ui/src/components/pipeline/pipeline-panel-addons.ts
302
+ export const PIPELINE_CLUSTER_DEVICE_ADDONS = [
303
+ 'pipeline-orchestrator', 'motion-wasm', 'audio-analyzer', 'detection-pipeline',
304
+ ] as const
305
+ ```
306
+
307
+ Its own comment says addons not on it "fall off silently". **That list is a
308
+ defect** — an addon declaring a valid schema is ignored with no log line — but
309
+ adding yours is still the wrong fix: that page is for per-camera detection
310
+ tuning, not for your feature.
311
+
312
+ ### Pick by ownership, not by example
313
+
314
+ Both real mechanisms hang the widget off a **capability** bound to the device.
315
+ Which one you use is decided by ONE question, and it is not "which did I see
316
+ first" — neither is canonical:
317
+
318
+ > **Would another vendor implement this capability, without changing it?**
319
+
320
+ - **Yes — the cap is GENERIC.** Let the framework derive the section. Any other
321
+ answer means the same section gets hand-written once per vendor and diverges
322
+ at the first edit.
323
+ - **No — the cap is OWNED**, meaning one addon implements it *and* that addon
324
+ owns the device. Declare the section yourself.
325
+
326
+ Answer it about the capability, not about today's fleet. A cap with one
327
+ implementer right now can still be generic: `navigation` and `consumables` are
328
+ dreame-only today and another robot vendor would implement either untouched, so
329
+ both are generic. `consumables` says so in its own definition — `status.empty`
330
+ plus `status.itemArray` make it a device-link synthesize target, so it can
331
+ appear on a device no dreame provider owns at all.
332
+
333
+ ### A GENERIC cap — the framework derives the section
334
+
335
+ ```ts
336
+ deviceConfig: {
337
+ ui: { kind: 'widget', widgetId: 'host/your-widget', tab: 'streaming', label: '…' },
338
+ }
339
+ ```
340
+
341
+ The framework emits the structural section out of the binding entry — **no
342
+ provider call, so it cannot fail** — and the widget self-persists through the
343
+ cap's own mutations. `motion-zones`, `privacy-mask`, `ptz`, `ptz-autotrack`,
344
+ `navigation` and `consumables` all do this, and all six are correct. Register
345
+ the component in `HOST_WIDGETS`
346
+ (`packages/ui-library/src/widgets/host-widgets.ts`).
347
+
348
+ **Weigh the cost honestly before minting a cap for this.** A new cap is a
349
+ framework change: `npm run codegen`, the two hand-edits in
350
+ `packages/types/src/capabilities/index.ts`, and it reaches a node only inside a
351
+ published `@camstack/server` (D16).
352
+ `camstack deploy <your-addon>` will NOT make the widget appear, and neither will
353
+ deploying `admin-ui` — the cap carrying the section does not exist there yet.
354
+
355
+ ### An OWNED cap — your addon returns the section
356
+
357
+ The cap sets `exposesDeviceSettings: true` and the provider RETURNS a
358
+ `ConfigUISchema` containing the widget field. `recording`
359
+ (`recorder/recording-device-settings.ts`) and `camera-grid-layout`
360
+ (`system/src/builtins/camera-grid/grid-layout-native-provider.ts`, section built in
361
+ `grid-device-settings.ts`) are the two:
362
+
363
+ ```ts
364
+ sections: [{ id: '…', tab: 'recording', location: 'top-tab', order: 10,
365
+ fields: [{ type: 'widget', widgetId: 'host/recording-panel' }] }]
366
+ ```
367
+
368
+ What that buys, and nothing else does: the ADDON picks the section, tab,
369
+ location and order, and it can decline PER DEVICE — `recording` returns `null`
370
+ for anything that is not a camera, so the tab never appears there.
371
+
372
+ `recording` is also the example worth remembering, because it LOOKS generic and
373
+ is not: "record this camera" sounds like something several addons could offer,
374
+ and only the recorder ever does.
375
+
376
+ Three things bite here:
377
+
378
+ - **Return the WIRE shape.** Run your schema through `hydrateSchema(schema, {})`
379
+ — a widget stores no values, but the aggregation expects the hydrated form.
380
+ - **A `deviceNative` cap needs the contribution on BOTH providers — one
381
+ builder, two registrations.** There are two paths and they reach different
382
+ objects:
383
+ - the DEVICE PAGE resolves with
384
+ `registry.getProviderByAddon(capName, entry.providerAddonId)`
385
+ (`device-aggregation.ts`), which reads the ADDON-level provider map only.
386
+ No addon-level provider ⇒ the section is dropped and **nothing is logged**.
387
+ - a DIRECT cap call carries a `deviceId`, so `child-cap-dispatch` answers it
388
+ from the DEVICE-scoped provider and THROWS when the method is missing there
389
+ (the singleton fallback exists only for a collection cap's list method).
390
+
391
+ Both were measured on the live hub on 2026-09-17, one after the other: the
392
+ wrapper alone gave HTTP 500 on the direct call; the native alone gave a device
393
+ aggregate of 30 sections with ours absent and no error anywhere. Build the
394
+ provider ONCE in a factory and register it twice — as the native
395
+ (`registerNativeCap`, typed `InferProvider`, which a native registration
396
+ happily accepts as a superset) and as the addon's own provider from
397
+ `onInitialize`. Worked example:
398
+ `packages/system/src/builtins/camera-grid/grid-layout-native-provider.ts`.
399
+ `getDeviceSettingsContribution` must return the WIRE shape — run the schema
400
+ through `hydrateSchema(schema, {})`; a widget stores no values.
401
+ - **`deviceConfig` and `exposesDeviceSettings` are mutually exclusive**
402
+ (`capability-definition.ts`). Remove one as you add the other.
403
+
404
+ **Neither shape avoids the capability.** `exposesDeviceSettings` on a cap you do
405
+ not own is not an option: the caps a device-owning addon typically already has
406
+ bound (`device-status`, `feature-probe`, `stream-catalog`, `device-ops`) are
407
+ SHARED across dozens of providers, and flipping that flag makes the aggregation
408
+ call `getDeviceSettingsContribution` on every one of them. Fleet-wide blast
409
+ radius to render one panel.
410
+
411
+ Two more that bite either way:
412
+
413
+ - **`topTab: true` needs a known tab.** A `topTab` widget must name a tab in
414
+ `WELL_KNOWN_TAB_MAP` (`packages/types/src/interfaces/config-ui.ts`) or the UI
415
+ renders the raw tab id as the label. Use an existing tab unless you also add
416
+ the entry — and note that the tab's label, icon and position in the bar are a
417
+ `@camstack/types` constant, so they are a framework publish whichever
418
+ mechanism declares the section.
419
+ - **If the addon owns the device, make the cap `deviceNative`** and register it
420
+ from the device class, so the widget asks *the camera* through the ordinary
421
+ device proxy.
422
+
423
+ ### Diagnosing which failure you have
424
+
425
+ ```bash
426
+ node scripts/hub/hub.mjs GET addonSettings.getDeviceSettings '{"addonId":"…","deviceId":N}'
427
+ node scripts/hub/hub.mjs GET deviceManager.getBindings '{"deviceId":N}'
428
+ ```
429
+
430
+ If the first returns your section and the second does not list your cap, the
431
+ data is fine and **nobody is asking** — you are on the wrong mechanism. Grepping
432
+ the deployed bundle for your widget id proves only that the code shipped; it
433
+ says nothing about whether anything requests it. On the day this was diagnosed,
434
+ three checks out of four said "fine"; only "who ASKS" told the truth.
435
+
436
+ ## Done-gate
437
+
438
+ ```
439
+ ADDON DONE — <addonId>
440
+ wiring: manifest + vite entries + index re-export; check-addon-entries ok
441
+ checks: typecheck / tests / build emitted <dist path>
442
+ deployed: <nodes> — fresh runner; caps registered
443
+ proved: <the call / log line observed>
444
+ docs: <files | none needed: reason>
445
+ ```
@@ -0,0 +1,218 @@
1
+ ---
2
+ name: camstack-capability
3
+ description: Add or change a CamStack capability (`*.cap.ts`) end to end — decide whether one is needed at all, pick its cardinality (singleton, collection, device-native, wrapper, internal, node-hosted), codegen and the two hand-edits it cannot do, registerProvider and the manifest, provider selection through bindings, CAP_INPUT_DEFAULTS, a capability-driven UI, typed routing errors, and what must be published for it to reach a running hub. Use for "new cap", "add a method", "add a field to a cap", "two addons implement the same cap", "No procedure found on path", "provider not available".
4
+ ---
5
+
6
+ # Adding or changing a capability
7
+
8
+ A capability is a typed contract between addons, defined once in
9
+ `packages/types/src/capabilities/<name>.cap.ts`. The long-form reference is
10
+ `docs/architecture/capabilities.md`; the inventory is the generated
11
+ `docs/reference/capabilities.md` and `docs/reference/api.md`. Read the first
12
+ before you design anything.
13
+
14
+ > Skill names with no file in this pack (`camstack-ui`, `camstack-ui-admin`,
15
+ > `camstack-server-change`, `camstack-diagnose`, `camstack-publish-ci`) are
16
+ > server-repository skills under `.claude/skills/`; this text stands on its own.
17
+
18
+ ## Tooling
19
+
20
+ ```bash
21
+ camstack develop scaffold cap <name> [--scope system|device] [--mode singleton|collection]
22
+ camstack develop list-caps
23
+ camstack develop who-provides <cap-name>
24
+ ```
25
+
26
+ The scaffold writes a stub only. You still hand-edit the index + run codegen.
27
+
28
+ ## 0. Do you need one?
29
+
30
+ A new capability is a **framework change**: codegen, a publish of the server
31
+ closure, and an update of every node before anyone can call it. Check first:
32
+
33
+ - **Enumerating providers of an existing collection?**
34
+ `addons.listCapabilityProviders({ capName })` works even for `internal` caps.
35
+ - **An addon's own configuration?** `globalSettingsSchema()` plus the existing
36
+ `addon-settings` cap; the settings panel already renders it.
37
+ - **Enable / disable a provider?** `addons.setCapabilityProviderEnabled` (the
38
+ toggle is the ONE enable — D777).
39
+ - **A field on an existing method?** Additive output fields need only the
40
+ providing addon redeployed (the router passes output through structurally).
41
+ A new INPUT field is different: the hub validates input against ITS copy of
42
+ the schema and strips unknown keys, so it needs the server update too (§6).
43
+
44
+ A new capability is right when there is genuinely new state or behaviour that
45
+ several addons implement or call.
46
+
47
+ ## 1. Pick the cardinality — it decides everything downstream
48
+
49
+ | Archetype | Declare | Who answers a call |
50
+ | --- | --- | --- |
51
+ | **singleton** | `mode: 'singleton'` | one active provider (§4 selection) |
52
+ | **collection** | `mode: 'collection'` | every enabled provider; a caller may pin one with `addonId` (global) or `provider` (device collection, required — D554) |
53
+ | **device-native** | `scope: 'device'`, registered from the device class | the provider owning that device (`ctx.registerNativeCap`) |
54
+ | **wrapper** | `kind: 'wrapper'` (+ `defaultActive` **and** `deviceTypes`) | a provider bound per device via `deviceManager.getBindings` / `setBinding` |
55
+ | **internal** | `internal: true` (+ `mount: { kind: 'skip' }` for no route at all) | in-process consumers only; without `skip` it is still a full tRPC router whose un-annotated methods floor to `admin` (D240) |
56
+ | **node-hosted** (one per node, called with `{nodeId}`) | `mode: 'singleton'` — **never `'per-node'`** | the pinned node's provider |
57
+
58
+ `per-node` is a declared enum value that codegen does **not** wire:
59
+ `scripts/generate-capability-router-types.ts` matches only
60
+ `singleton|collection`, so a `per-node` cap is silently missing from
61
+ `ALL_CAPABILITY_DEFINITIONS` and every call answers "provider not available".
62
+ Route a node-hosted cap with a pin instead: codegen injects a `nodeId` selector
63
+ into every method of a remote-capable singleton, and `nodePin(id)`
64
+ (`packages/types/src/cap-call-context.ts`) carries the same pin out of band.
65
+
66
+ The mount is **derived** from scope and mode. Set `mount` only for
67
+ `server-provided` (also needs a factory in `buildServerProviders`), `hub-only`
68
+ or `skip`.
69
+
70
+ ## 2. Define it
71
+
72
+ ```ts
73
+ export const fooCapability = {
74
+ name: 'foo', // kebab-case — scripts/check-cap-name-kebab.ts
75
+ scope: 'system', // or 'device'
76
+ mode: 'singleton', // or 'collection'
77
+ methods: { … }, // method(input, output, { auth, access })
78
+ } as const satisfies CapabilityDefinition
79
+ export type IFooProvider = InferProvider<typeof fooCapability>
80
+ ```
81
+
82
+ - **Auth tier on every method.** Omitted = `protected` (reachable by every
83
+ signed-in non-admin). Every tier is pinned in
84
+ `scripts/method-tier-baseline.json`; accept a deliberate change with
85
+ `npx tsx scripts/check-method-tiers.ts --update` and read the diff. A method
86
+ naming a device keeps the id in a TOP-LEVEL `deviceId`-style field or the
87
+ scope gate cannot see it (`docs/architecture/capabilities.md` §"A
88
+ system-scope method that names a device").
89
+ - **Export coverage.** A cap either exports to the ecosystems or is a written
90
+ exception: `npx tsx scripts/check-export-coverage.ts`. Both checks run in
91
+ the pre-commit hook when a `*.cap.ts` is staged.
92
+ - Behavioural metadata (`kind`, `defaultActive`, `mode`) lives here and only
93
+ here (D4). The manifest lists the cap by `name` (plus `optional`,
94
+ `dependsOn`), nothing else.
95
+ - Device state: `status: { schema, kind }`, `runtimeState` including
96
+ `lastFetchedAt: z.number()`. A camera-config cap uses the `deviceConfig`
97
+ archetype with an honest, camera-probed `getOptions` — the UI is derived from
98
+ it (D14). `deviceConfig` and `exposesDeviceSettings` are mutually exclusive.
99
+ - A `z.enum` in a cap is a second declaration of a union (it reaches the
100
+ generated client): when removing a member, grep both.
101
+
102
+ ## 3. Hand-edits, then codegen
103
+
104
+ In `packages/types/src/capabilities/index.ts`:
105
+
106
+ 1. a value re-export of the capability and its types;
107
+ 2. a member of the **`AnyCapability` union** (it produces `CapabilityName`).
108
+
109
+ `scripts/check-capability-union-complete.ts` (inside codegen) refuses a miss.
110
+
111
+ ```bash
112
+ npm run codegen # routers, mounts, proxies, hooks, access maps, CAP_INPUT_DEFAULTS, addon-api.ts…
113
+ ```
114
+
115
+ Skipping it is silent drift; `codegen:check` catches it later, not in time.
116
+ Codegen rebuilds a stale `types`/`system` dist itself; if `addon-api.ts` did not
117
+ change when your method is new, the dist was stale — rebuild and rerun. Its
118
+ guard failures are findings, not noise.
119
+
120
+ **Defaults:** a Zod `.default()` on an INPUT runs only where the router parses
121
+ it. A call from an addon through `ctx.api` never reaches the router, so codegen
122
+ emits `CAP_INPUT_DEFAULTS` (`scripts/generate-cap-input-defaults.ts`) and the
123
+ local link merges them. Only TOP-LEVEL defaults are carried — a nested default
124
+ arrives `undefined` on the addon path. Prefer top-level defaults.
125
+
126
+ ## 4. Implement, register, select
127
+
128
+ - System scope: return it from `onInitialize` / `ctx.registerProvider(capName,
129
+ impl)`. Device scope: `ctx.registerNativeCap(cap, impl)` from a `BaseDevice`
130
+ subclass. Providers are flat — no nested sub-objects.
131
+ - **Declare it in the manifest** of the same package
132
+ (`camstack.addons[].capabilities`) —
133
+ `scripts/check-registered-caps-declared.ts` fails a registered-but-undeclared
134
+ cap. A builtin that registers in `onInitialize` is no exception.
135
+ - **Agents:** an agent declares capabilities from a hand-curated array in
136
+ `server/backend/src/agent/main.ts`. A cap that must exist on agents goes
137
+ there too; nothing else teaches it.
138
+ - **Two addons implement the same cap?** Both register unconditionally — never
139
+ gate registration behind a private setting. Choose with the binding:
140
+ singleton → `capabilities.setActiveSingleton({ capability, addonId, nodeId? })`
141
+ (persisted as `capabilities.singleton.<cap>` / `capabilities.singletonNode.<cap>.<node>`;
142
+ System → Capabilities in the UI); collection → the enable toggle or
143
+ `capabilities.setCollectionEnabledProviders`; wrapper → the device binding.
144
+ Resolution order for a singleton: per-node override → cluster default → the
145
+ first provider on that node. Two entries on a singleton in
146
+ `capabilities.listCapabilities` is the tell of a silent duplicate.
147
+ - **Consuming another addon's cap:** only `ctx.api.<cap>.<method>` — never an
148
+ import, never `ctx.capabilities` (local process only). In kernel/builtin
149
+ code that needs one addon's provider: `registry.getProviderByAddon(cap, addonId)`.
150
+ - **Never hand-write an interface over a cap.** Type against the generated
151
+ client and narrow it:
152
+ `type FooClient = Pick<import('../generated/addon-api.js').AddonApi['foo'], 'get' | 'set'>`
153
+ (precedent: `SettingsStoreClient` in `settings-store.cap.ts`). A hand-written
154
+ copy keeps compiling after a method is removed and fails at runtime as
155
+ `No procedure found on path`.
156
+
157
+ ## 5. UI and errors that follow from the cap
158
+
159
+ - **The UI is derived from the cap, never hard-coded.** To make something
160
+ appear in an admin list, register the cap that drives the page (a collection
161
+ rendered by the generic page — e.g. `network-access` on Remote Access); never
162
+ add a hand-written card. Device-page UI goes through the device aggregate:
163
+ `deviceConfig` (generic cap) or `exposesDeviceSettings` with the three
164
+ injected methods (owned cap) — never a parallel tab system. Decision rule and
165
+ traps: the `camstack-addon` skill, "A UI surface on a DEVICE page".
166
+ - **"Absent" only from an answered query** (D315): ask
167
+ `capabilities.getCapability` / `useCapabilityPresence`, never infer absence
168
+ from `(data ?? [])`, and never throw the literal "provider not available"
169
+ from an accessor — substring matchers mistake it for absence.
170
+ - **Routing errors say WHY.** A dispatch failure carries cap, method, node and
171
+ device plus a typed reason (`CapRouteError` in
172
+ `packages/system/src/kernel/transport/cap-route.ts`: `no-provider`,
173
+ `node-offline`, …), never an opaque "not available".
174
+
175
+ ## 6. Spec it, ship it, verify it
176
+
177
+ Spec in `server/backend/src/__tests__/cap-routers/` — the router builder does
178
+ not re-validate OUTPUT, so the test pins the shape.
179
+
180
+ **What must be published.** The hub reads `ALL_CAPABILITY_DEFINITIONS` from
181
+ **`@camstack/system`**, which bundles the cap definitions — and nx-affected
182
+ does NOT mark `@camstack/system` changed for an edit under `packages/types`.
183
+ So a cap change always force-publishes it with the server:
184
+
185
+ ```bash
186
+ gh workflow run "Publish Packages" --ref main -f bump=patch -f scope=affected \
187
+ -f include_dependents=false -f force_packages=@camstack/system,@camstack/server
188
+ ```
189
+
190
+ Then the server-side chain — publish → `applyServerUpdate` on the hub AND every
191
+ agent → one more restart for builtins → verify — is the `camstack-server-change`
192
+ skill; CI mechanics are `camstack-publish-ci`. Then `camstack deploy` the
193
+ providing addon (its provider must have the method).
194
+
195
+ Two 404s, two causes:
196
+ - `No procedure found on path "<cap>.<method>"` → the node still runs the old
197
+ closure (server update missing).
198
+ - `method '<m>' not found on provider …` → the providing addon is stale
199
+ (deploy it).
200
+
201
+ Verify on the running node: `capabilities.getCapability({ name })` lists the
202
+ provider, and a real call of the new method answers. A new INPUT field is
203
+ verified by a call that USES it — a save that "succeeds" while the hub strips
204
+ the field is the failure mode.
205
+
206
+ ## 7. Done-gate — paste it before "done"
207
+
208
+ ```
209
+ CAPABILITY DONE — <cap>.<method>
210
+ archetype: <singleton|collection|device-native|wrapper|internal|node-hosted>
211
+ hand-edits: index.ts re-export + AnyCapability union — yes
212
+ codegen: npm run codegen — clean; method tiers / export coverage — <accepted diff | unchanged>
213
+ manifest: declared in <package>/package.json (+ agent main.ts array: <yes|n/a>)
214
+ spec: <spec file> — <result>
215
+ shipped: <"not shipped" | published system+server X.Y.Z, applied on <nodes>, addon deployed>
216
+ verified: <the call and its answer, or "not deployed">
217
+ docs: camstack-docs gate — <files | none needed: reason>
218
+ ```