@camstack/addon-pipeline-orchestrator 1.0.4 → 1.0.6

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.
package/dist/index.js CHANGED
@@ -4631,63 +4631,7 @@ function _instanceof(cls, params = {}) {
4631
4631
  return inst;
4632
4632
  }
4633
4633
  //#endregion
4634
- //#region ../types/dist/index.mjs
4635
- /**
4636
- * Deep wiring healthcheck — snapshot of active reachability probes across
4637
- * every declared capability + widget of every installed plugin, on every
4638
- * node. Produced by the backend `WiringHealthService` and surfaced via
4639
- * `GET /health/wiring`, the tRPC `health.wiring` query, and the boot-gate.
4640
- *
4641
- * Unlike `/health` (process liveness), this reflects whether each cap/widget
4642
- * is actually *reachable* over the real cap-dispatch path. See spec
4643
- * `docs/superpowers/specs/2026-05-23-deep-healthcheck-design.md`.
4644
- */
4645
- /** What kind of target a probe addressed. */
4646
- var wiringProbeKindSchema = _enum([
4647
- "singleton",
4648
- "device",
4649
- "widget"
4650
- ]);
4651
- /** Result of probing a single (cap|widget [, device]) target. */
4652
- var wiringProbeResultSchema = object({
4653
- capName: string(),
4654
- kind: wiringProbeKindSchema,
4655
- deviceId: number().optional(),
4656
- reachable: boolean(),
4657
- latencyMs: number(),
4658
- error: string().optional()
4659
- });
4660
- /** Per-addon roll-up of cap + widget probe results. */
4661
- var wiringAddonHealthSchema = object({
4662
- addonId: string(),
4663
- caps: array(wiringProbeResultSchema).readonly(),
4664
- widgets: array(wiringProbeResultSchema).readonly()
4665
- });
4666
- /** Per-node roll-up. */
4667
- var wiringNodeHealthSchema = object({
4668
- nodeId: string(),
4669
- addons: array(wiringAddonHealthSchema).readonly()
4670
- });
4671
- object({
4672
- /** True only when every probed target is reachable. */
4673
- ok: boolean(),
4674
- /** True when at least one target is unreachable. */
4675
- degraded: boolean(),
4676
- checkedAt: string(),
4677
- nodes: array(wiringNodeHealthSchema).readonly(),
4678
- summary: object({
4679
- total: number(),
4680
- reachable: number(),
4681
- unreachable: number()
4682
- })
4683
- });
4684
- var MODEL_FORMATS = [
4685
- "onnx",
4686
- "coreml",
4687
- "openvino",
4688
- "tflite",
4689
- "pt"
4690
- ];
4634
+ //#region ../types/dist/sleep-D7JeS58T.mjs
4691
4635
  var EventCategory = /* @__PURE__ */ function(EventCategory) {
4692
4636
  EventCategory["SystemBoot"] = "system.boot";
4693
4637
  EventCategory["SystemAddonsReady"] = "system.addons-ready";
@@ -4985,6 +4929,18 @@ var EventCategory = /* @__PURE__ */ function(EventCategory) {
4985
4929
  */
4986
4930
  EventCategory["PipelineEngineMetricsSnapshot"] = "pipeline.engine-metrics-snapshot";
4987
4931
  /**
4932
+ * Per-node detection-engine runtime-provisioning transition. Emitted by
4933
+ * the detection-pipeline provider on every state change of its lazy
4934
+ * engine-provisioning machine (idle → installing → verifying → ready,
4935
+ * or → failed with a `nextRetryAt`). Payload is the
4936
+ * `EngineProvisioningState` snapshot; `event.source.nodeId` carries the
4937
+ * node. The Pipeline page subscribes to drive a live "installing
4938
+ * OpenVINO… / ready" indicator per node without polling
4939
+ * `pipelineExecutor.getEngineProvisioning`. Telemetry-grade (D8): the UI
4940
+ * also reads the cap snapshot on mount / reconnect. Phase 2.
4941
+ */
4942
+ EventCategory["PipelineEngineProvisioning"] = "pipeline.engine-provisioning";
4943
+ /**
4988
4944
  * Cluster topology snapshot. Carries the same payload returned by
4989
4945
  * `nodes.topology` (every reachable node + addons + processes).
4990
4946
  * Emitted by the hub on any agent / addon lifecycle change
@@ -6025,7 +5981,7 @@ function makeSourceBrokerId(deviceId, camStreamId) {
6025
5981
  * Zod schema for StreamSourceEntry — the canonical stream descriptor
6026
5982
  * exposed by ICameraDevice.getStreamSources() and consumed by the broker.
6027
5983
  */
6028
- var StreamSourceEntrySchema = object({
5984
+ var StreamSourceEntrySchema$1 = object({
6029
5985
  id: string(),
6030
5986
  label: string(),
6031
5987
  protocol: _enum([
@@ -6247,140 +6203,6 @@ var ProfileRtspEntrySchema = object({
6247
6203
  codec: string().optional(),
6248
6204
  resolution: CamStreamResolutionSchema.optional()
6249
6205
  });
6250
- /**
6251
- * Numeric day-of-week: 0 = Sunday … 6 = Saturday (matches `Date.getDay`).
6252
- * Named `RecordingWeekday` to avoid collision with the string-union
6253
- * `Weekday` exported from `interfaces/timezones.ts`.
6254
- */
6255
- var RecordingWeekdaySchema = number().int().min(0).max(6);
6256
- var HHMM = /^([01]\d|2[0-3]):[0-5]\d$/;
6257
- var RecordingScheduleSchema = discriminatedUnion("kind", [object({ kind: literal("always") }), object({
6258
- kind: literal("timeOfDay"),
6259
- start: string().regex(HHMM),
6260
- end: string().regex(HHMM),
6261
- /** Restrict to these weekdays; omit = every day. */
6262
- days: array(RecordingWeekdaySchema).optional()
6263
- })]);
6264
- var RecordingModeSchema = _enum([
6265
- "continuous",
6266
- "onMotion",
6267
- "onAudioThreshold"
6268
- ]);
6269
- /**
6270
- * First-class, authoritative per-camera storage mode — the netta choice the UI
6271
- * reads directly (never inferred from `rules`):
6272
- * - `off` — not recording.
6273
- * - `events` — record only around triggers (motion / audio threshold),
6274
- * with pre/post-buffer.
6275
- * - `continuous` — record 24/7 within the schedule.
6276
- *
6277
- * `mode` compiles one-way to the internal `rules[]` consumed by the policy
6278
- * engine (see `compileRules`); `rules[]` is never authored directly anymore.
6279
- */
6280
- var RecordingStorageModeSchema = _enum([
6281
- "off",
6282
- "events",
6283
- "continuous"
6284
- ]);
6285
- /** Which detectors trigger an `events`-mode recording. */
6286
- var RecordingTriggersSchema = object({
6287
- motion: boolean().optional(),
6288
- audioThresholdDbfs: number().optional()
6289
- });
6290
- /**
6291
- * Mode of a single recording band — the recorder per-band vocabulary.
6292
- *
6293
- * Distinct from `RecordingStorageModeSchema` (which carries `off`): a band is
6294
- * only ever `continuous` or `events`; "off" is expressed by the absence of a
6295
- * covering band, not by a band value.
6296
- */
6297
- var RecordingBandModeSchema = _enum(["continuous", "events"]);
6298
- /**
6299
- * Triggers for an `events`-mode band. Identical shape to
6300
- * `RecordingTriggersSchema` — reuse that schema as the band trigger type so the
6301
- * two never drift.
6302
- */
6303
- var RecordingBandTriggersSchema = RecordingTriggersSchema;
6304
- /**
6305
- * A single mode-per-band window — the canonical recorder band shape, the
6306
- * single source of truth re-used by `addon-pipeline/recorder`.
6307
- *
6308
- * `days` lists the weekdays the band covers (empty = every day, matching the
6309
- * band engine's `applies` rule). `start`/`end` are `HH:MM`; an `end <= start`
6310
- * span wraps past midnight (handled by the band engine).
6311
- */
6312
- var RecordingBandSchema = object({
6313
- days: array(RecordingWeekdaySchema),
6314
- start: string().regex(HHMM),
6315
- end: string().regex(HHMM),
6316
- mode: RecordingBandModeSchema,
6317
- triggers: RecordingBandTriggersSchema.optional(),
6318
- preBufferSec: number().min(0).optional(),
6319
- postBufferSec: number().min(0).optional()
6320
- });
6321
- var RecordingRuleSchema = object({
6322
- schedule: RecordingScheduleSchema,
6323
- mode: RecordingModeSchema,
6324
- /** Seconds of footage to retain BEFORE a trigger (applied at keep/discard). */
6325
- preBufferSec: number().min(0).default(0),
6326
- /** Keep recording until this many seconds after the last trigger. */
6327
- postBufferSec: number().min(0).default(0),
6328
- /** Each new trigger restarts the post-buffer window. */
6329
- resetTimeoutOnNewEvent: boolean().default(true),
6330
- /** onAudioThreshold only — dBFS level that counts as a trigger. */
6331
- thresholdDbfs: number().optional()
6332
- });
6333
- /**
6334
- * Per-device retention overrides. Every field is optional; an unset or `0`
6335
- * value inherits the node-wide recorder default. Only footage-lifetime limits
6336
- * live per-camera: `maxAgeDays` and `maxSizeGb`. The disk-occupancy threshold
6337
- * (when the volume is too full to keep recording) is NOT a per-camera concern —
6338
- * it belongs to the StorageLocation (`StorageLocation.config.minFreePercent`),
6339
- * shared by every camera writing to that volume.
6340
- */
6341
- var RecordingRetentionSchema = object({
6342
- maxAgeDays: number().min(0).optional(),
6343
- maxSizeGb: number().min(0).optional()
6344
- });
6345
- /**
6346
- * The full per-camera recording intent — the wire shape of a RecordingTarget.
6347
- *
6348
- * `mode` is the authoritative storage choice; `schedule`/`triggers`/`pre`/`post`
6349
- * are its mode-specific parameters. `rules` is a DEPRECATED authoring input kept
6350
- * only for transition + migration (`migrateRulesToMode`); the policy engine
6351
- * consumes the compiled output of `compileRules(config)`, never `rules` directly.
6352
- */
6353
- var RecordingConfigSchema = object({
6354
- enabled: boolean(),
6355
- /** Authoritative storage mode. Absent on legacy targets → derived once via
6356
- * `migrateRulesToMode`, then persisted. */
6357
- mode: RecordingStorageModeSchema.optional(),
6358
- profiles: array(CamProfileSchema).optional(),
6359
- segmentSeconds: number().int().positive().optional(),
6360
- /** Shared recording time-bands for `events` & `continuous` — record only when
6361
- * the wall-clock falls inside one of these windows. Omit or empty = always.
6362
- * `continuous` compiles to one rule per band; `events` to band × trigger. */
6363
- schedules: array(RecordingScheduleSchema).optional(),
6364
- /** Legacy single-band predecessor of `schedules`. Read-compat only — it is
6365
- * normalized into `schedules` on read and never written going forward. (Not
6366
- * tagged `@deprecated`: the normalization paths must read it cast-free.) */
6367
- schedule: RecordingScheduleSchema.optional(),
6368
- /** `events`-mode only — which detectors trigger a recording. */
6369
- triggers: RecordingTriggersSchema.optional(),
6370
- /** `events`-mode only — seconds retained before / after a trigger. */
6371
- preBufferSec: number().min(0).optional(),
6372
- postBufferSec: number().min(0).optional(),
6373
- /** DEPRECATED authoring input; retained for migration/transition. */
6374
- rules: array(RecordingRuleSchema).optional(),
6375
- /**
6376
- * AUTHORITATIVE mode-per-band recording model (recorder). When present it
6377
- * is the single source of truth; the legacy `mode`/`schedules`/`schedule`/
6378
- * `triggers`/`rules` fields above are kept for READ-COMPAT only and are
6379
- * derived into bands once via `migrateConfigToBands`.
6380
- */
6381
- bands: array(RecordingBandSchema).optional(),
6382
- retention: RecordingRetentionSchema.optional()
6383
- });
6384
6206
  var ReadinessTimeoutError = class extends Error {
6385
6207
  capName;
6386
6208
  scope;
@@ -6730,770 +6552,1116 @@ function randomGeneration() {
6730
6552
  if (typeof crypto !== "undefined" && crypto.randomUUID) return crypto.randomUUID();
6731
6553
  return Math.random().toString(36).slice(2, 14);
6732
6554
  }
6733
- /**
6734
- * `StorageLocationType` — an addon-declared id that identifies the *kind* of
6735
- * storage a location serves. Defined here (not in `capabilities/storage.cap.ts`)
6736
- * so the persisted record schema and the consumer-facing cap can both consume it
6737
- * without forming a circular import. The `storage` cap re-exports it
6738
- * verbatim for back-compat.
6739
- *
6740
- * This Zod schema is the **authoritative source** for `StorageLocationType`.
6741
- * The TS alias in `./storage.ts` re-exports `z.infer<typeof
6742
- * StorageLocationTypeSchema>` so the wire surface (cap) and the legacy
6743
- * `IStorageProvider` interface stay in lockstep.
6744
- *
6745
- * The type is now an **open string** (not a closed enum) — addons declare
6746
- * their own location kinds via `StorageLocationDeclaration.id`. The regex
6747
- * enforces a safe id format: lowercase-start, alphanumeric + hyphens.
6748
- */
6749
- var StorageLocationTypeSchema = string().regex(/^[a-z][a-zA-Z0-9-]*$/);
6750
- /**
6751
- * Persisted record for a storage location instance. Operators can register
6752
- * multiple instances for multi-cardinality types (e.g. two `backups`
6753
- * locations with different `providerId`s). Cardinality is now declared per
6754
- * location via `StorageLocationDeclaration.cardinality` the static
6755
- * `STORAGE_LOCATION_CARDINALITY` map has been removed.
6756
- *
6757
- * `id` is a stable namespaced string of the form `<type>:<slug>`.
6758
- * The default location for a type uses `id === <type>:default` by
6759
- * convention (the bare type ref like `'backups'` resolves to it).
6760
- *
6761
- * `isSystem: true` marks a location as orchestrator-seeded and
6762
- * undeletable. The bootstrap-installed defaults (one per type) carry
6763
- * this flag; operator-added locations don't. Editing the config of
6764
- * a system location is allowed (path migration, provider swap) but
6765
- * deleting it is rejected at the cap level.
6766
- */
6767
- var StorageLocationSchema = object({
6768
- id: string().regex(/^[a-z][a-zA-Z0-9-]*:[a-zA-Z0-9-]+$/),
6769
- type: string(),
6770
- displayName: string().min(1),
6771
- providerId: string().min(1),
6772
- config: record(string(), unknown()),
6773
- /**
6774
- * Cluster node this location physically lives on. REQUIRED for node-local
6775
- * providers (filesystem — the path exists on one node's disk), null/absent
6776
- * for node-agnostic providers (S3/SFTP/WebDAV, reachable from any node).
6777
- * `'hub'` is the hub node. Validated against the provider's `nodeLocal`
6778
- * flag at upsert time, not here (the schema is provider-agnostic).
6779
- */
6780
- nodeId: string().optional(),
6781
- isDefault: boolean().default(false),
6782
- isSystem: boolean().default(false),
6783
- createdAt: number(),
6784
- updatedAt: number()
6785
- });
6786
- /**
6787
- * Reference accepted by consumer-facing `api.storage.*` calls.
6788
- * Either:
6789
- * - a `StorageLocationType` (e.g. `'backups'`) orchestrator resolves to the default of that type
6790
- * - a fully-qualified id (e.g. `'backups:nas-01'`) addresses a specific instance
6791
- *
6792
- * The orchestrator's `resolveRef(ref)` handles both cases.
6793
- */
6794
- var StorageLocationRefSchema = union([StorageLocationTypeSchema, string().regex(/^[a-z][a-zA-Z0-9-]*:[a-zA-Z0-9-]+$/)]);
6795
- /**
6796
- * `StorageLocationDeclaration` a single storage-location entry declared by
6797
- * an addon in its `package.json` under `camstack.storageLocations`.
6798
- *
6799
- * Design intent:
6800
- * - **Addon declares its needs** — each addon describes the logical storage
6801
- * slots it requires (e.g. `recordings`, `recordingsLow`) without caring
6802
- * about the physical path.
6803
- * - **Kernel aggregates** — at boot the kernel collects declarations from all
6804
- * installed addons, deduplicates by `id`, and exposes the union via the
6805
- * storage-locations settings surface.
6806
- * - **Orchestrator seeds** for every declared `id` the orchestrator ensures
6807
- * at least one instance named `<id>:default` is present, using
6808
- * `defaultsTo` to inherit the resolved root from another location when the
6809
- * declaration is a derivative slot (e.g. `recordingsLow` defaults to
6810
- * `recordings`).
6811
- * - **ids are global** — `id` values are shared across the entire deployment;
6812
- * two addons declaring the same `id` must agree on `cardinality` (validated
6813
- * at kernel aggregation time, not here).
6814
- */
6815
- var StorageLocationDeclarationSchema = object({
6816
- /**
6817
- * Global location identifier, e.g. `recordings` or `recordingsLow`.
6818
- * Must start with a lowercase letter and may contain letters, digits, and
6819
- * hyphens.
6820
- */
6821
- id: string().regex(/^[a-z][a-zA-Z0-9-]*$/, { message: "id must start with a lowercase letter and contain only letters, digits, or hyphens" }),
6822
- /** Human-readable name shown in the admin UI. */
6823
- displayName: string().min(1, { message: "displayName must not be empty" }),
6824
- /** Optional longer explanation of what data this location stores. */
6825
- description: string().optional(),
6826
- /**
6827
- * `single` — exactly one instance of this location is allowed system-wide
6828
- * (e.g. `logs`, `models`). The operator can edit it but not add more.
6829
- * `multi` — the operator may register several instances (e.g. a second
6830
- * `recordings` on a NAS for disk tiering); one is the default at any time.
6831
- */
6832
- cardinality: _enum(["single", "multi"]),
6833
- /**
6834
- * When set, the default instance for this location inherits its resolved
6835
- * root from the named location's default instance. Useful for derivative
6836
- * slots (e.g. `recordingsLow` → `recordings`) so operators only need to
6837
- * configure the primary location.
6838
- */
6839
- defaultsTo: string().optional()
6840
- });
6841
- var DecoderStatsSchema = object({
6842
- inputFps: number(),
6843
- outputFps: number(),
6844
- avgDecodeTimeMs: number(),
6845
- droppedFrames: number()
6846
- });
6847
- var DecoderSessionConfigSchema = object({
6848
- codec: string(),
6849
- maxFps: number().default(0),
6850
- outputFormat: _enum([
6851
- "jpeg",
6852
- "rgb",
6853
- "bgr",
6854
- "yuv420",
6855
- "gray"
6856
- ]).default("jpeg"),
6857
- scale: number().default(1),
6858
- width: number().optional(),
6859
- height: number().optional(),
6555
+ var DeviceType = /* @__PURE__ */ function(DeviceType) {
6556
+ DeviceType["Camera"] = "camera";
6557
+ DeviceType["Hub"] = "hub";
6558
+ DeviceType["Light"] = "light";
6559
+ DeviceType["Siren"] = "siren";
6560
+ DeviceType["Switch"] = "switch";
6561
+ DeviceType["Sensor"] = "sensor";
6562
+ DeviceType["Thermostat"] = "thermostat";
6563
+ DeviceType["Button"] = "button";
6564
+ /** Generic stateless event emitter carries a device's EXACT declared
6565
+ * event vocabulary verbatim (no normalization). Installed with the
6566
+ * `event-emitter` cap. Sources: HA `event.*` entities (structured) and
6567
+ * HA bus events (e.g. `zha_event`, generic). */
6568
+ DeviceType["EventEmitter"] = "event-emitter";
6569
+ /** Firmware/software update entity current vs available version,
6570
+ * updatable flag, update state, and an install action. Installed with
6571
+ * the `update` cap. Sources: Homematic firmware-update channels (and
6572
+ * reusable by other providers, e.g. HA `update.*` entities). */
6573
+ DeviceType["Update"] = "update";
6574
+ DeviceType["Generic"] = "generic";
6575
+ /** Generic notification delivery target (HA `notify.<service>`, future
6576
+ * Telegram / Discord / ntfy / SMTP, …). One device per delivery
6577
+ * endpoint; the `notifier` cap defines the send surface. */
6578
+ DeviceType["Notifier"] = "notifier";
6579
+ /** Pre-recorded action sequence with optional parameters
6580
+ * (HA `script.*`). Runnable via `script-runner` cap. */
6581
+ DeviceType["Script"] = "script";
6582
+ /** Automation rule (HA `automation.*`) — enable/disable + manual
6583
+ * trigger surface exposed via `automation-control` cap. */
6584
+ DeviceType["Automation"] = "automation";
6585
+ /** Door / smart lock device (HA `lock.*`). `lock-control` cap. */
6586
+ DeviceType["Lock"] = "lock";
6587
+ /** Window covering, blinds, garage door, valve, etc. (HA `cover.*`,
6588
+ * `valve.*`). `cover` cap with sub-roles for variant. */
6589
+ DeviceType["Cover"] = "cover";
6590
+ /** Pipe / water / gas valve with open/close/stop and optional
6591
+ * position (HA `valve.*`). `valve` cap — a cover-sibling actuator
6592
+ * modelled on the same open/closed lifecycle. */
6593
+ DeviceType["Valve"] = "valve";
6594
+ /** Humidifier / dehumidifier with on/off + target humidity + mode
6595
+ * (HA `humidifier.*`). `humidifier` cap — a climate-family actuator
6596
+ * modelled on the same target / mode lifecycle. */
6597
+ DeviceType["Humidifier"] = "humidifier";
6598
+ /** Water heater / boiler with target temperature + operation mode +
6599
+ * away mode (HA `water_heater.*`). `water-heater` cap a
6600
+ * climate-family actuator. */
6601
+ DeviceType["WaterHeater"] = "water-heater";
6602
+ /** Ceiling / standing / exhaust fan (HA `fan.*`). `fan-control` cap. */
6603
+ DeviceType["Fan"] = "fan";
6604
+ /** Audio / video playback endpoint (HA `media_player.*`). Disjoint from
6605
+ * the camera surface — those use `Camera`. `media-player` cap. */
6606
+ DeviceType["MediaPlayer"] = "media-player";
6607
+ /** Security panel / alarm system (HA `alarm_control_panel.*`).
6608
+ * `alarm-panel` cap. */
6609
+ DeviceType["AlarmPanel"] = "alarm-panel";
6610
+ /** Generic user-settable input (HA `number` / `input_number` / `select`
6611
+ * / `input_select` / `text` / `input_text` / `input_datetime`).
6612
+ * Sub-type via `DeviceRole`: NumericControl / SelectControl /
6613
+ * TextControl / DateTimeControl. */
6614
+ DeviceType["Control"] = "control";
6615
+ /** Person / device-tracker presence (HA `person.*`, `device_tracker.*`).
6616
+ * `presence` cap. */
6617
+ DeviceType["Presence"] = "presence";
6618
+ /** Weather provider (HA `weather.*`). Tier-3, low MVP priority.
6619
+ * `weather` cap. */
6620
+ DeviceType["Weather"] = "weather";
6621
+ /** Robot vacuum (HA `vacuum.*`). Tier-3. `vacuum-control` cap. */
6622
+ DeviceType["Vacuum"] = "vacuum";
6623
+ /** Robotic lawn mower (HA `lawn_mower.*`). Tier-3.
6624
+ * `lawn-mower-control` cap. */
6625
+ DeviceType["LawnMower"] = "lawn-mower";
6626
+ /** Physical HA device group parent container for entity-children
6627
+ * adopted from a single HA device entry. Not renderable as a
6628
+ * standalone device; exists only to anchor child entities. */
6629
+ DeviceType["Container"] = "container";
6630
+ /** Single still-image entity (HA `image.*`). Read-only display of an
6631
+ * `entity_picture` signed URL the browser loads directly. `image` cap. */
6632
+ DeviceType["Image"] = "image";
6633
+ return DeviceType;
6634
+ }({});
6635
+ var DeviceFeature = /* @__PURE__ */ function(DeviceFeature) {
6636
+ DeviceFeature["BatteryOperated"] = "battery-operated";
6637
+ DeviceFeature["Rebootable"] = "rebootable";
6860
6638
  /**
6861
- * Identifier of the camera this decoder session serves. Optional
6862
- * because the cap is generic (any caller could request decode), but
6863
- * stream-broker passes it so decoder logs include `deviceId` for
6864
- * per-camera filtering when diagnosing failures (e.g. node-av
6865
- * sendPacket errors on a single hung camera).
6639
+ * Device supports an on-demand re-sync of its derived spec with its
6640
+ * upstream source drives the generic Re-sync button. The owning
6641
+ * provider implements the action via the `device-adoption.resync` cap.
6866
6642
  */
6867
- deviceId: number().int().nonnegative().optional(),
6643
+ DeviceFeature["Resyncable"] = "resyncable";
6644
+ DeviceFeature["NativeSnapshot"] = "native-snapshot";
6645
+ DeviceFeature["DoorbellButton"] = "doorbell-button";
6646
+ DeviceFeature["TwoWayAudio"] = "two-way-audio";
6647
+ DeviceFeature["PanTiltZoom"] = "pan-tilt-zoom";
6868
6648
  /**
6869
- * Free-form tag for log scoping. Stream-broker uses
6870
- * `broker:<deviceId>/<profile>`. Decoder session logger surfaces it
6871
- * on every line so `grep tag=broker:5/high` filters one camera
6872
- * profile cleanly.
6649
+ * Camera supports the on-firmware autotrack subsystem (subject-
6650
+ * following). Distinct from `PanTiltZoom` because not every PTZ
6651
+ * camera ships autotrack the admin UI uses this flag to gate
6652
+ * the autotrack toggle / settings card without re-deriving from
6653
+ * the cap registry. Mirrors `ptz-autotrack` cap registration:
6654
+ * driver sets this feature when probe confirms the firmware
6655
+ * surface, and registers the cap in the same code path.
6873
6656
  */
6874
- tag: string().optional(),
6657
+ DeviceFeature["PtzAutotrack"] = "ptz-autotrack";
6875
6658
  /**
6876
- * Where the session delivers decoded frames (Phase 5 / D9):
6659
+ * Accessory exposes a "trigger on motion" toggle the parent camera's
6660
+ * motion detection automatically activates this device. Mirrors
6661
+ * `motion-trigger` cap registration: drivers set this feature in the
6662
+ * same code path that calls `ctx.registerNativeCap(motionTriggerCapability, ...)`.
6877
6663
  *
6878
- * - `'callback'` (default) the legacy pixel path: decoded frames are
6879
- * buffered as `DecodedFrame`s and drained via `pullFrames`.
6880
- * - `'shm'` the shared-memory frame plane: decoded frames are written
6881
- * into an OS shared-memory ring and drained as zero-pixel
6882
- * `FrameHandle`s via `pullHandles`. A session is one mode or the
6883
- * other — `pullFrames` returns nothing for an `'shm'` session and
6884
- * `pullHandles` returns nothing for a `'callback'` session.
6885
- */
6886
- frameSink: _enum(["callback", "shm"]).default("callback")
6887
- });
6888
- var EncodeProfileSchema = object({
6889
- video: object({
6890
- codec: _enum([
6891
- "h264",
6892
- "h265",
6893
- "copy"
6894
- ]),
6895
- profile: _enum([
6896
- "baseline",
6897
- "main",
6898
- "high"
6899
- ]).optional(),
6900
- width: number().int().positive().optional(),
6901
- height: number().int().positive().optional(),
6902
- fps: number().positive().optional(),
6903
- bitrateKbps: number().int().positive().optional(),
6904
- gopFrames: number().int().positive().optional(),
6905
- bf: number().int().min(0).optional(),
6906
- preset: _enum([
6907
- "ultrafast",
6908
- "superfast",
6909
- "veryfast",
6910
- "faster",
6911
- "fast",
6912
- "medium"
6913
- ]).optional(),
6914
- tune: _enum([
6915
- "zerolatency",
6916
- "film",
6917
- "animation"
6918
- ]).optional()
6919
- }),
6920
- audio: union([literal("passthrough"), object({
6921
- codec: _enum([
6922
- "opus",
6923
- "aac",
6924
- "pcmu",
6925
- "pcma",
6926
- "copy"
6927
- ]),
6928
- bitrateKbps: number().int().positive().optional(),
6929
- sampleRateHz: number().int().positive().optional(),
6930
- channels: union([literal(1), literal(2)]).optional()
6931
- })]),
6932
- /**
6933
- * ffmpeg input-side args, inserted between the fixed global flags
6934
- * (`-hide_banner -loglevel error`) and `-i pipe:0`. Free-text array
6935
- * — the widget surfaces a textarea + suggestion chips for the most-
6936
- * used demuxer/format options.
6937
- */
6938
- inputArgs: array(string()).optional(),
6939
- /**
6940
- * ffmpeg output-side args, inserted between the encode block and
6941
- * the final `-f <muxer> pipe:1`. Use for muxer options, bitstream
6942
- * filters, codec-specific overrides. Free-text array.
6664
+ * Used by admin UI (gate the in-hero `MotionTriggerToggle` against a
6665
+ * fast scalar without binding fetch), notifier rules, and `listAll`
6666
+ * filters that want "all devices with on-motion behaviour".
6943
6667
  */
6944
- outputArgs: array(string()).optional()
6945
- });
6946
- /**
6947
- import { errMsg } from '@camstack/types'
6948
- * Extract a human-readable message from an unknown error value.
6949
- * Replaces the ubiquitous `errMsg(err)` pattern.
6950
- */
6951
- function errMsg(err) {
6952
- if (err instanceof Error) return err.message;
6953
- if (typeof err === "string") return err;
6954
- return String(err);
6668
+ DeviceFeature["MotionTrigger"] = "motion-trigger";
6669
+ /** Light supports rgb-triplet color via `color` cap. */
6670
+ DeviceFeature["LightColorRgb"] = "light-color-rgb";
6671
+ /** Light supports HSV color via `color` cap. */
6672
+ DeviceFeature["LightColorHsv"] = "light-color-hsv";
6673
+ /** Light supports color-temperature (mired) via `color` cap. */
6674
+ DeviceFeature["LightColorMired"] = "light-color-mired";
6675
+ /** Thermostat supports a `heat_cool` dual setpoint (targetLow +
6676
+ * targetHigh). Gates the range slider UI. */
6677
+ DeviceFeature["ClimateDualSetpoint"] = "climate-dual-setpoint";
6678
+ /** Thermostat exposes target humidity and/or current humidity
6679
+ * readings. Gates the humidity controls. */
6680
+ DeviceFeature["ClimateHumidity"] = "climate-humidity";
6681
+ /** Thermostat exposes a fan-mode selector. */
6682
+ DeviceFeature["ClimateFanMode"] = "climate-fan-mode";
6683
+ /** Thermostat exposes preset modes (eco / away / sleep / vendor). */
6684
+ DeviceFeature["ClimatePreset"] = "climate-preset";
6685
+ /** Cover exposes intermediate position control (0..100). Gates the
6686
+ * position slider UI. */
6687
+ DeviceFeature["CoverPositionable"] = "cover-positionable";
6688
+ /** Cover exposes slat-tilt control. Gates the tilt slider UI. */
6689
+ DeviceFeature["CoverTilt"] = "cover-tilt";
6690
+ /** Valve exposes intermediate position control (0..100). Gates the
6691
+ * position slider / drag surface UI. */
6692
+ DeviceFeature["ValvePositionable"] = "valve-positionable";
6693
+ /** Fan exposes a speed-percentage setter. Gates the speed slider UI. */
6694
+ DeviceFeature["FanSpeed"] = "fan-speed";
6695
+ /** Fan exposes a preset mode selector. */
6696
+ DeviceFeature["FanPreset"] = "fan-preset";
6697
+ /** Fan exposes blade direction (forward/reverse) — typical of
6698
+ * ceiling fans. */
6699
+ DeviceFeature["FanDirection"] = "fan-direction";
6700
+ /** Fan exposes an oscillation toggle. */
6701
+ DeviceFeature["FanOscillating"] = "fan-oscillating";
6702
+ /** Lock requires a PIN code on lock/unlock. Gates the code-entry
6703
+ * field on the UI lock-controls panel. */
6704
+ DeviceFeature["LockPinRequired"] = "lock-pin-required";
6705
+ /** Lock supports a latch-release ("open door") action distinct from
6706
+ * unlock. Mirrors HA `LockEntityFeature.OPEN` (bit 1) in
6707
+ * `supported_features`. Gates the Open Door button in the UI. */
6708
+ DeviceFeature["LockOpen"] = "lock-open";
6709
+ /** Media player exposes a seek-to-position surface. */
6710
+ DeviceFeature["MediaPlayerSeek"] = "media-player-seek";
6711
+ /** Media player exposes a volume-level setter. */
6712
+ DeviceFeature["MediaPlayerVolume"] = "media-player-volume";
6713
+ /** Media player exposes a mute toggle distinct from volume=0. */
6714
+ DeviceFeature["MediaPlayerMute"] = "media-player-mute";
6715
+ /** Media player exposes a shuffle toggle. */
6716
+ DeviceFeature["MediaPlayerShuffle"] = "media-player-shuffle";
6717
+ /** Media player exposes a repeat mode (off / all / one). */
6718
+ DeviceFeature["MediaPlayerRepeat"] = "media-player-repeat";
6719
+ /** Media player exposes a source / input selector. */
6720
+ DeviceFeature["MediaPlayerSelectSource"] = "media-player-select-source";
6721
+ /** Media player exposes a play-arbitrary-media surface (URL / id). */
6722
+ DeviceFeature["MediaPlayerPlayMedia"] = "media-player-play-media";
6723
+ /** Media player exposes next-track. */
6724
+ DeviceFeature["MediaPlayerNext"] = "media-player-next";
6725
+ /** Media player exposes previous-track. */
6726
+ DeviceFeature["MediaPlayerPrevious"] = "media-player-previous";
6727
+ /** Media player exposes stop distinct from pause. */
6728
+ DeviceFeature["MediaPlayerStop"] = "media-player-stop";
6729
+ /** Alarm panel requires a PIN code on arm/disarm. */
6730
+ DeviceFeature["AlarmPinRequired"] = "alarm-pin-required";
6731
+ /** Presence device carries GPS coordinates (lat/lng/accuracy) in
6732
+ * addition to a textual location. */
6733
+ DeviceFeature["PresenceGps"] = "presence-gps";
6734
+ /** Notifier accepts an inline / URL image attachment. */
6735
+ DeviceFeature["NotifierImage"] = "notifier-image";
6736
+ /** Notifier accepts a priority hint (high/normal/low). */
6737
+ DeviceFeature["NotifierPriority"] = "notifier-priority";
6738
+ /** Notifier accepts a free-form `data` payload for platform-specific
6739
+ * fields. */
6740
+ DeviceFeature["NotifierData"] = "notifier-data";
6741
+ /** Notifier supports interactive action buttons / callbacks. */
6742
+ DeviceFeature["NotifierActions"] = "notifier-actions";
6743
+ /** Notifier supports per-call recipient targeting (multi-user). */
6744
+ DeviceFeature["NotifierRecipients"] = "notifier-recipients";
6745
+ /** Script runner accepts a variables map on each run invocation. */
6746
+ DeviceFeature["ScriptVariables"] = "script-variables";
6747
+ /** Automation `trigger` accepts a skipCondition flag — fires the
6748
+ * automation's actions while bypassing its condition block. */
6749
+ DeviceFeature["AutomationSkipCondition"] = "automation-skip-condition";
6750
+ return DeviceFeature;
6751
+ }({});
6752
+ /**
6753
+ * Semantic role a device plays within its parent. Populated by driver
6754
+ * addons when creating accessory devices (Reolink siren/floodlight/
6755
+ * PIR/chime/autotrack/doorbell, ONVIF relay outputs, …). Used by the
6756
+ * admin UI to pick icons, labels, and widgets — a `Switch` with
6757
+ * `role: Floodlight` renders as a bulb with a brightness slider,
6758
+ * whereas a `Switch` with `role: Siren` renders as a klaxon.
6759
+ *
6760
+ * Undefined for top-level devices (cameras, NVRs, hubs). Persisted in
6761
+ * sqlite as a nullable TEXT column — old rows keep working unchanged.
6762
+ */
6763
+ var DeviceRole = /* @__PURE__ */ function(DeviceRole) {
6764
+ DeviceRole["Siren"] = "siren";
6765
+ DeviceRole["Floodlight"] = "floodlight";
6766
+ DeviceRole["Spotlight"] = "spotlight";
6767
+ DeviceRole["PirSensor"] = "pir-sensor";
6768
+ DeviceRole["Chime"] = "chime";
6769
+ DeviceRole["Autotrack"] = "autotrack";
6770
+ DeviceRole["Nightvision"] = "nightvision";
6771
+ DeviceRole["PrivacyMask"] = "privacy-mask";
6772
+ DeviceRole["Doorbell"] = "doorbell";
6773
+ /** Virtual HA toggle (input_boolean.*) — distinguishable from a
6774
+ * real Switch device for UI rendering / export adapters. */
6775
+ DeviceRole["BinaryHelper"] = "binary-helper";
6776
+ /** Generic motion / occupancy / moving event source. Distinct from
6777
+ * the camera accessory PirSensor role: that one is a camera child;
6778
+ * this is a standalone HA / 3rd-party motion sensor. */
6779
+ DeviceRole["MotionSensor"] = "motion-sensor";
6780
+ DeviceRole["ContactSensor"] = "contact-sensor";
6781
+ DeviceRole["LeakSensor"] = "leak-sensor";
6782
+ DeviceRole["SmokeSensor"] = "smoke-sensor";
6783
+ DeviceRole["COSensor"] = "co-sensor";
6784
+ DeviceRole["GasSensor"] = "gas-sensor";
6785
+ DeviceRole["TamperSensor"] = "tamper-sensor";
6786
+ DeviceRole["VibrationSensor"] = "vibration-sensor";
6787
+ DeviceRole["ConnectivitySensor"] = "connectivity-sensor";
6788
+ DeviceRole["SoundSensor"] = "sound-sensor";
6789
+ /** Fallback for `binary_sensor` without a known `device_class`. */
6790
+ DeviceRole["BinarySensor"] = "binary-sensor";
6791
+ DeviceRole["TemperatureSensor"] = "temperature-sensor";
6792
+ DeviceRole["HumiditySensor"] = "humidity-sensor";
6793
+ DeviceRole["AmbientLightSensor"] = "ambient-light-sensor";
6794
+ DeviceRole["PressureSensor"] = "pressure-sensor";
6795
+ DeviceRole["PowerSensor"] = "power-sensor";
6796
+ DeviceRole["EnergySensor"] = "energy-sensor";
6797
+ DeviceRole["VoltageSensor"] = "voltage-sensor";
6798
+ DeviceRole["CurrentSensor"] = "current-sensor";
6799
+ DeviceRole["AirQualitySensor"] = "air-quality-sensor";
6800
+ /** Battery level (numeric % via `sensor` OR low-bool via
6801
+ * `binary_sensor` — the cap distinguishes via the value type). */
6802
+ DeviceRole["BatterySensor"] = "battery-sensor";
6803
+ /** Fallback for `sensor` numeric without a known `device_class`. */
6804
+ DeviceRole["NumericSensor"] = "numeric-sensor";
6805
+ /** String / enum state (HA `sensor` with `state_class: enum` or
6806
+ * `attributes.options`). */
6807
+ DeviceRole["EnumSensor"] = "enum-sensor";
6808
+ /** Date / timestamp state (HA `sensor` with `device_class: timestamp`
6809
+ * or `date`). The slice carries the raw ISO string verbatim (hosted on
6810
+ * the `enum-sensor` cap); the UI renders it locale-formatted. */
6811
+ DeviceRole["DateTimeSensor"] = "datetime-sensor";
6812
+ /** Last-resort fallback when nothing else matches. */
6813
+ DeviceRole["GenericSensor"] = "generic-sensor";
6814
+ DeviceRole["NumericControl"] = "numeric-control";
6815
+ DeviceRole["SelectControl"] = "select-control";
6816
+ DeviceRole["TextControl"] = "text-control";
6817
+ DeviceRole["DateTimeControl"] = "datetime-control";
6818
+ /** Mobile push notifier (HA `notify.mobile_app_*`) — supports
6819
+ * rich features (image, priority, channel routing). */
6820
+ DeviceRole["MobilePushNotifier"] = "mobile-push-notifier";
6821
+ /** Chat / messaging service (HA `notify.telegram_*`,
6822
+ * `notify.discord_*`, etc.). */
6823
+ DeviceRole["MessagingNotifier"] = "messaging-notifier";
6824
+ /** Email-based delivery (HA `notify.smtp`, etc.). */
6825
+ DeviceRole["EmailNotifier"] = "email-notifier";
6826
+ /** Fallback when the notifier service name doesn't match a known
6827
+ * pattern. */
6828
+ DeviceRole["GenericNotifier"] = "generic-notifier";
6829
+ return DeviceRole;
6830
+ }({});
6831
+ /**
6832
+ * Generic types for capability definitions.
6833
+ *
6834
+ * A capability is defined with Zod schemas for methods, events, and settings.
6835
+ * TypeScript types are inferred via z.infer<> — zero duplication.
6836
+ *
6837
+ * Pattern:
6838
+ * 1. Define Zod schemas for data, methods, settings
6839
+ * 2. Export const capabilityDef = { ... } satisfies CapabilityDefinition
6840
+ * 3. Export type IProvider = InferProvider<typeof capabilityDef>
6841
+ * 4. Addon implements IProvider
6842
+ * 5. Registry auto-mounts tRPC router from definition.methods
6843
+ */
6844
+ /**
6845
+ * Output schema shared by the contribution + live methods.
6846
+ *
6847
+ * Mirrors the `ConfigUISchemaWithValues` shape (sections[] + optional
6848
+ * tabs[]) without importing from `../interfaces/config-ui.js` — a
6849
+ * concrete-but-lenient Zod object keeps tRPC output inference happy
6850
+ * (using `z.unknown()` here collapses unrelated router branches to
6851
+ * `unknown` when the generator re-inlines the huge AppRouter type).
6852
+ *
6853
+ * `.passthrough()` on sections/fields accepts whatever FormBuilder
6854
+ * extensions the caller adds (showWhen, displayScale, …) without
6855
+ * rebuilding every time a new field kind is introduced.
6856
+ */
6857
+ var ContributionSectionSchema = object({
6858
+ id: string(),
6859
+ title: string(),
6860
+ description: string().optional(),
6861
+ style: _enum(["card", "accordion"]).optional(),
6862
+ defaultCollapsed: boolean().optional(),
6863
+ columns: union([
6864
+ literal(1),
6865
+ literal(2),
6866
+ literal(3),
6867
+ literal(4)
6868
+ ]).optional(),
6869
+ tab: string().optional(),
6870
+ location: _enum(["settings", "top-tab"]).optional(),
6871
+ order: number().optional(),
6872
+ fields: array(any())
6873
+ });
6874
+ object({
6875
+ tabs: array(object({
6876
+ id: string(),
6877
+ label: string(),
6878
+ icon: string(),
6879
+ order: number().optional()
6880
+ })).optional(),
6881
+ sections: array(ContributionSectionSchema)
6882
+ }).nullable();
6883
+ object({ deviceId: number() }), object({ deviceId: number() }), object({
6884
+ deviceId: number(),
6885
+ patch: record(string(), unknown())
6886
+ }), object({ success: literal(true) });
6887
+ object({ deviceId: number() }), unknown().nullable();
6888
+ /** Shorthand to define a method schema */
6889
+ function method(input, output, options) {
6890
+ return {
6891
+ input,
6892
+ output,
6893
+ kind: options?.kind ?? "query",
6894
+ auth: options?.auth ?? "protected",
6895
+ ...options?.access !== void 0 ? { access: options.access } : {},
6896
+ timeoutMs: options?.timeoutMs
6897
+ };
6955
6898
  }
6956
- var YAMNET_TO_MACRO = {
6957
- mapping: {
6958
- Speech: "speech",
6959
- "Child speech, kid speaking": "speech",
6960
- Conversation: "speech",
6961
- "Narration, monologue": "speech",
6962
- Babbling: "speech",
6963
- Whispering: "speech",
6964
- "Speech synthesizer": "speech",
6965
- Humming: "speech",
6966
- Rapping: "speech",
6967
- Singing: "speech",
6968
- Choir: "speech",
6969
- "Child singing": "speech",
6970
- Shout: "scream",
6971
- Bellow: "scream",
6972
- Yell: "scream",
6973
- Screaming: "scream",
6974
- "Children shouting": "scream",
6975
- Whoop: "scream",
6976
- "Crying, sobbing": "crying",
6977
- "Baby cry, infant cry": "crying",
6978
- Whimper: "crying",
6979
- "Wail, moan": "crying",
6980
- Groan: "crying",
6981
- Laughter: "laughter",
6982
- "Baby laughter": "laughter",
6983
- Giggle: "laughter",
6984
- Snicker: "laughter",
6985
- "Belly laugh": "laughter",
6986
- "Chuckle, chortle": "laughter",
6987
- Music: "music",
6988
- "Musical instrument": "music",
6989
- Guitar: "music",
6990
- Piano: "music",
6991
- Drum: "music",
6992
- "Drum kit": "music",
6993
- "Violin, fiddle": "music",
6994
- Flute: "music",
6995
- Saxophone: "music",
6996
- Trumpet: "music",
6997
- Synthesizer: "music",
6998
- "Pop music": "music",
6999
- "Rock music": "music",
7000
- "Hip hop music": "music",
7001
- "Classical music": "music",
7002
- Jazz: "music",
7003
- "Electronic music": "music",
7004
- "Background music": "music",
7005
- Dog: "dog",
7006
- Bark: "dog",
7007
- Yip: "dog",
7008
- Howl: "dog",
7009
- "Bow-wow": "dog",
7010
- Growling: "dog",
7011
- "Whimper (dog)": "dog",
7012
- Cat: "cat",
7013
- Purr: "cat",
7014
- Meow: "cat",
7015
- Hiss: "cat",
7016
- Caterwaul: "cat",
7017
- Bird: "bird",
7018
- "Bird vocalization, bird call, bird song": "bird",
7019
- "Chirp, tweet": "bird",
7020
- Squawk: "bird",
7021
- Crow: "bird",
7022
- Owl: "bird",
7023
- "Pigeon, dove": "bird",
7024
- Animal: "animal",
7025
- "Domestic animals, pets": "animal",
7026
- "Livestock, farm animals, working animals": "animal",
7027
- Horse: "animal",
7028
- "Cattle, bovinae": "animal",
7029
- Pig: "animal",
7030
- Sheep: "animal",
7031
- Goat: "animal",
7032
- Frog: "animal",
7033
- Insect: "animal",
7034
- Cricket: "animal",
7035
- Alarm: "alarm",
7036
- "Alarm clock": "alarm",
7037
- "Smoke detector, smoke alarm": "alarm",
7038
- "Fire alarm": "alarm",
7039
- Buzzer: "alarm",
7040
- "Civil defense siren": "alarm",
7041
- "Car alarm": "alarm",
7042
- Siren: "siren",
7043
- "Police car (siren)": "siren",
7044
- "Ambulance (siren)": "siren",
7045
- "Fire engine, fire truck (siren)": "siren",
7046
- "Emergency vehicle": "siren",
7047
- Foghorn: "siren",
7048
- Doorbell: "doorbell",
7049
- "Ding-dong": "doorbell",
7050
- Knock: "doorbell",
7051
- Tap: "doorbell",
7052
- Glass: "glass_breaking",
7053
- Shatter: "glass_breaking",
7054
- "Chink, clink": "glass_breaking",
7055
- "Gunshot, gunfire": "gunshot",
7056
- "Machine gun": "gunshot",
7057
- Explosion: "gunshot",
7058
- Fireworks: "gunshot",
7059
- Firecracker: "gunshot",
7060
- "Artillery fire": "gunshot",
7061
- "Cap gun": "gunshot",
7062
- Boom: "gunshot",
7063
- Vehicle: "vehicle",
7064
- Car: "vehicle",
7065
- Truck: "vehicle",
7066
- Bus: "vehicle",
7067
- Motorcycle: "vehicle",
7068
- "Car passing by": "vehicle",
7069
- "Vehicle horn, car horn, honking": "vehicle",
7070
- "Traffic noise, roadway noise": "vehicle",
7071
- Train: "vehicle",
7072
- Aircraft: "vehicle",
7073
- Helicopter: "vehicle",
7074
- Bicycle: "vehicle",
7075
- Skateboard: "vehicle",
7076
- Fire: "fire",
7077
- Crackle: "fire",
7078
- Water: "water",
7079
- Rain: "water",
7080
- Raindrop: "water",
7081
- "Rain on surface": "water",
7082
- Stream: "water",
7083
- Waterfall: "water",
7084
- Ocean: "water",
7085
- "Waves, surf": "water",
7086
- "Splash, splatter": "water",
7087
- Wind: "wind",
7088
- Thunderstorm: "wind",
7089
- Thunder: "wind",
7090
- "Wind noise (microphone)": "wind",
7091
- "Rustling leaves": "wind",
7092
- Door: "door",
7093
- "Sliding door": "door",
7094
- Slam: "door",
7095
- "Cupboard open or close": "door",
7096
- "Walk, footsteps": "footsteps",
7097
- Run: "footsteps",
7098
- Shuffle: "footsteps",
7099
- Crowd: "crowd",
7100
- Chatter: "crowd",
7101
- Cheering: "crowd",
7102
- Applause: "crowd",
7103
- "Children playing": "crowd",
7104
- "Hubbub, speech noise, speech babble": "crowd",
7105
- Telephone: "telephone",
7106
- "Telephone bell ringing": "telephone",
7107
- Ringtone: "telephone",
7108
- "Telephone dialing, DTMF": "telephone",
7109
- "Busy signal": "telephone",
7110
- Engine: "engine",
7111
- "Engine starting": "engine",
7112
- Idling: "engine",
7113
- "Accelerating, revving, vroom": "engine",
7114
- "Light engine (high frequency)": "engine",
7115
- "Medium engine (mid frequency)": "engine",
7116
- "Heavy engine (low frequency)": "engine",
7117
- "Lawn mower": "engine",
7118
- Chainsaw: "engine",
7119
- Hammer: "tools",
7120
- Jackhammer: "tools",
7121
- Sawing: "tools",
7122
- "Power tool": "tools",
7123
- Drill: "tools",
7124
- Sanding: "tools",
7125
- Silence: "silence"
7126
- },
7127
- preserveOriginal: false
7128
- };
7129
- var APPLE_SA_TO_MACRO = {
7130
- mapping: {
7131
- speech: "speech",
7132
- child_speech: "speech",
7133
- conversation: "speech",
7134
- whispering: "speech",
7135
- singing: "speech",
7136
- humming: "speech",
7137
- shout: "scream",
7138
- yell: "scream",
7139
- screaming: "scream",
7140
- crying: "crying",
7141
- baby_crying: "crying",
7142
- sobbing: "crying",
7143
- laughter: "laughter",
7144
- baby_laughter: "laughter",
7145
- giggling: "laughter",
7146
- music: "music",
7147
- guitar: "music",
7148
- piano: "music",
7149
- drums: "music",
7150
- dog_bark: "dog",
7151
- dog_bow_wow: "dog",
7152
- dog_growling: "dog",
7153
- dog_howl: "dog",
7154
- cat_meow: "cat",
7155
- cat_purr: "cat",
7156
- cat_hiss: "cat",
7157
- bird: "bird",
7158
- bird_chirp: "bird",
7159
- bird_squawk: "bird",
7160
- animal: "animal",
7161
- horse: "animal",
7162
- cow_moo: "animal",
7163
- insect: "animal",
7164
- alarm: "alarm",
7165
- smoke_alarm: "alarm",
7166
- fire_alarm: "alarm",
7167
- car_alarm: "alarm",
7168
- siren: "siren",
7169
- police_siren: "siren",
7170
- ambulance_siren: "siren",
7171
- doorbell: "doorbell",
7172
- door_knock: "doorbell",
7173
- knocking: "doorbell",
7174
- glass_breaking: "glass_breaking",
7175
- glass_shatter: "glass_breaking",
7176
- gunshot: "gunshot",
7177
- explosion: "gunshot",
7178
- fireworks: "gunshot",
7179
- car: "vehicle",
7180
- truck: "vehicle",
7181
- motorcycle: "vehicle",
7182
- car_horn: "vehicle",
7183
- vehicle_horn: "vehicle",
7184
- traffic: "vehicle",
7185
- fire: "fire",
7186
- fire_crackle: "fire",
7187
- water: "water",
7188
- rain: "water",
7189
- ocean: "water",
7190
- splash: "water",
7191
- wind: "wind",
7192
- thunder: "wind",
7193
- thunderstorm: "wind",
7194
- door: "door",
7195
- door_slam: "door",
7196
- sliding_door: "door",
7197
- footsteps: "footsteps",
7198
- walking: "footsteps",
7199
- running: "footsteps",
7200
- crowd: "crowd",
7201
- chatter: "crowd",
7202
- cheering: "crowd",
7203
- applause: "crowd",
7204
- telephone_ring: "telephone",
7205
- ringtone: "telephone",
7206
- engine: "engine",
7207
- engine_starting: "engine",
7208
- lawn_mower: "engine",
7209
- chainsaw: "engine",
7210
- hammer: "tools",
7211
- jackhammer: "tools",
7212
- drill: "tools",
7213
- power_tool: "tools",
7214
- silence: "silence"
7215
- },
7216
- preserveOriginal: false
7217
- };
7218
- var _macroLookup = /* @__PURE__ */ new Map();
7219
- for (const [k, v] of Object.entries(YAMNET_TO_MACRO.mapping)) _macroLookup.set(k.toLowerCase(), v);
7220
- for (const [k, v] of Object.entries(APPLE_SA_TO_MACRO.mapping)) _macroLookup.set(k.toLowerCase(), v);
7221
- var DeviceType = /* @__PURE__ */ function(DeviceType) {
7222
- DeviceType["Camera"] = "camera";
7223
- DeviceType["Hub"] = "hub";
7224
- DeviceType["Light"] = "light";
7225
- DeviceType["Siren"] = "siren";
7226
- DeviceType["Switch"] = "switch";
7227
- DeviceType["Sensor"] = "sensor";
7228
- DeviceType["Thermostat"] = "thermostat";
7229
- DeviceType["Button"] = "button";
7230
- /** Generic stateless event emitter carries a device's EXACT declared
7231
- * event vocabulary verbatim (no normalization). Installed with the
7232
- * `event-emitter` cap. Sources: HA `event.*` entities (structured) and
7233
- * HA bus events (e.g. `zha_event`, generic). */
7234
- DeviceType["EventEmitter"] = "event-emitter";
7235
- /** Firmware/software update entity — current vs available version,
7236
- * updatable flag, update state, and an install action. Installed with
7237
- * the `update` cap. Sources: Homematic firmware-update channels (and
7238
- * reusable by other providers, e.g. HA `update.*` entities). */
7239
- DeviceType["Update"] = "update";
7240
- DeviceType["Generic"] = "generic";
7241
- /** Generic notification delivery target (HA `notify.<service>`, future
7242
- * Telegram / Discord / ntfy / SMTP, …). One device per delivery
7243
- * endpoint; the `notifier` cap defines the send surface. */
7244
- DeviceType["Notifier"] = "notifier";
7245
- /** Pre-recorded action sequence with optional parameters
7246
- * (HA `script.*`). Runnable via `script-runner` cap. */
7247
- DeviceType["Script"] = "script";
7248
- /** Automation rule (HA `automation.*`) enable/disable + manual
7249
- * trigger surface exposed via `automation-control` cap. */
7250
- DeviceType["Automation"] = "automation";
7251
- /** Door / smart lock device (HA `lock.*`). `lock-control` cap. */
7252
- DeviceType["Lock"] = "lock";
7253
- /** Window covering, blinds, garage door, valve, etc. (HA `cover.*`,
7254
- * `valve.*`). `cover` cap with sub-roles for variant. */
7255
- DeviceType["Cover"] = "cover";
7256
- /** Pipe / water / gas valve with open/close/stop and optional
7257
- * position (HA `valve.*`). `valve` cap a cover-sibling actuator
7258
- * modelled on the same open/closed lifecycle. */
7259
- DeviceType["Valve"] = "valve";
7260
- /** Humidifier / dehumidifier with on/off + target humidity + mode
7261
- * (HA `humidifier.*`). `humidifier` cap — a climate-family actuator
7262
- * modelled on the same target / mode lifecycle. */
7263
- DeviceType["Humidifier"] = "humidifier";
7264
- /** Water heater / boiler with target temperature + operation mode +
7265
- * away mode (HA `water_heater.*`). `water-heater` cap a
7266
- * climate-family actuator. */
7267
- DeviceType["WaterHeater"] = "water-heater";
7268
- /** Ceiling / standing / exhaust fan (HA `fan.*`). `fan-control` cap. */
7269
- DeviceType["Fan"] = "fan";
7270
- /** Audio / video playback endpoint (HA `media_player.*`). Disjoint from
7271
- * the camera surface — those use `Camera`. `media-player` cap. */
7272
- DeviceType["MediaPlayer"] = "media-player";
7273
- /** Security panel / alarm system (HA `alarm_control_panel.*`).
7274
- * `alarm-panel` cap. */
7275
- DeviceType["AlarmPanel"] = "alarm-panel";
7276
- /** Generic user-settable input (HA `number` / `input_number` / `select`
7277
- * / `input_select` / `text` / `input_text` / `input_datetime`).
7278
- * Sub-type via `DeviceRole`: NumericControl / SelectControl /
7279
- * TextControl / DateTimeControl. */
7280
- DeviceType["Control"] = "control";
7281
- /** Person / device-tracker presence (HA `person.*`, `device_tracker.*`).
7282
- * `presence` cap. */
7283
- DeviceType["Presence"] = "presence";
7284
- /** Weather provider (HA `weather.*`). Tier-3, low MVP priority.
7285
- * `weather` cap. */
7286
- DeviceType["Weather"] = "weather";
7287
- /** Robot vacuum (HA `vacuum.*`). Tier-3. `vacuum-control` cap. */
7288
- DeviceType["Vacuum"] = "vacuum";
7289
- /** Robotic lawn mower (HA `lawn_mower.*`). Tier-3.
7290
- * `lawn-mower-control` cap. */
7291
- DeviceType["LawnMower"] = "lawn-mower";
7292
- /** Physical HA device group — parent container for entity-children
7293
- * adopted from a single HA device entry. Not renderable as a
7294
- * standalone device; exists only to anchor child entities. */
7295
- DeviceType["Container"] = "container";
7296
- /** Single still-image entity (HA `image.*`). Read-only display of an
7297
- * `entity_picture` signed URL the browser loads directly. `image` cap. */
7298
- DeviceType["Image"] = "image";
7299
- return DeviceType;
7300
- }({});
7301
- var DeviceFeature = /* @__PURE__ */ function(DeviceFeature) {
7302
- DeviceFeature["BatteryOperated"] = "battery-operated";
7303
- DeviceFeature["Rebootable"] = "rebootable";
6899
+ var StaticDirOutputSchema = object({ staticDir: string() });
6900
+ var VersionOutputSchema = object({ version: string() });
6901
+ method(_void(), StaticDirOutputSchema), method(_void(), VersionOutputSchema);
6902
+ /**
6903
+ * device-ops — device-scoped cap that unifies the per-IDevice operations
6904
+ * previously routed through the `.device-ops` Moleculer bridge service.
6905
+ *
6906
+ * Each worker that hosts live `IDevice` instances auto-registers a native
6907
+ * provider for this cap (per device) backed by its local
6908
+ * `DeviceRegistry`. Hub-side callers reach it transparently through
6909
+ * `ctx.fetchDevice(id).deviceOps.*` — the DeviceProxy injects
6910
+ * `deviceId` + `nodeId` and dispatches through the standard cap-router,
6911
+ * so there's no parallel bridge path anymore.
6912
+ *
6913
+ * The surface is intentionally small — every method corresponds to a
6914
+ * single action on the live `IDevice` (or `ICameraDevice` for
6915
+ * `getStreamSources`). Richer orchestration (enable/disable with
6916
+ * integration plumbing, bulk updates) stays in the `device-manager` cap;
6917
+ * `device-ops` is the per-device primitive the device-manager routes to.
6918
+ */
6919
+ var StreamSourceEntrySchema = object({
6920
+ id: string(),
6921
+ label: string(),
6922
+ protocol: _enum([
6923
+ "rtsp",
6924
+ "rtmp",
6925
+ "annexb",
6926
+ "http-mjpeg",
6927
+ "webrtc",
6928
+ "custom"
6929
+ ]),
6930
+ url: string().optional(),
6931
+ resolution: object({
6932
+ width: number(),
6933
+ height: number()
6934
+ }).optional(),
6935
+ fps: number().optional(),
6936
+ bitrate: number().optional(),
6937
+ codec: string().optional(),
6938
+ profileHint: CamProfileSchema.optional(),
6939
+ sdp: string().optional()
6940
+ });
6941
+ var ConfigEntrySchema$1 = object({
6942
+ key: string(),
6943
+ value: unknown()
6944
+ });
6945
+ var RawStateResultSchema = object({
6946
+ /** Originating provider id, e.g. 'homeassistant' | 'reolink' | 'hikvision'. */
6947
+ source: string(),
6948
+ /** Opaque, DISPLAY-SAFE upstream blob (no secrets/PII). */
6949
+ data: record(string(), unknown())
6950
+ });
6951
+ method(object({ deviceId: number() }), array(StreamSourceEntrySchema)), method(object({ deviceId: number() }), array(ConfigEntrySchema$1)), method(object({
6952
+ deviceId: number(),
6953
+ values: record(string(), unknown())
6954
+ }), _void(), { kind: "mutation" }), method(object({
6955
+ deviceId: number(),
6956
+ action: string().min(1),
6957
+ input: unknown()
6958
+ }), unknown(), { kind: "mutation" }), method(object({ deviceId: number() }), _void(), { kind: "mutation" }), method(object({ deviceId: number() }), unknown().nullable()), method(object({ deviceId: number() }), RawStateResultSchema.nullable(), { auth: "protected" });
6959
+ /**
6960
+ * Promise-based timer helpers — used everywhere the codebase needs to
6961
+ * wait, back off, or schedule a retry. Before these helpers landed, each
6962
+ * call site re-implemented `new Promise(r => setTimeout(r, ms))` inline,
6963
+ * with subtle variations (some swallowing cancellation, some not). Two
6964
+ * shapes cover every observed use case:
6965
+ *
6966
+ * - {@link sleep} for a plain, uncancellable wait — the default choice.
6967
+ * - {@link sleepCancellable} for a wait that wakes early when an
6968
+ * abort signal trips, used by long-running pollers whose teardown
6969
+ * must stop a pending backoff promptly.
6970
+ */
6971
+ /**
6972
+ * Resolve after `ms` milliseconds. Never rejects, never cancels. The
6973
+ * sleep cannot be interrupted; for a wakeable variant use
6974
+ * {@link sleepCancellable}.
6975
+ *
6976
+ * `ms <= 0` resolves on the next microtask via `setTimeout(0)`, which
6977
+ * still gives the event loop a chance to drain — useful for breaking
6978
+ * up tight async loops without changing call-site semantics.
6979
+ */
6980
+ function sleep$1(ms) {
6981
+ return new Promise((resolve) => setTimeout(resolve, Math.max(0, ms)));
6982
+ }
6983
+ //#endregion
6984
+ //#region ../types/dist/err-msg-IQTHeDzc.mjs
6985
+ /**
6986
+ import { errMsg } from '@camstack/types'
6987
+ * Extract a human-readable message from an unknown error value.
6988
+ * Replaces the ubiquitous `errMsg(err)` pattern.
6989
+ */
6990
+ function errMsg(err) {
6991
+ if (err instanceof Error) return err.message;
6992
+ if (typeof err === "string") return err;
6993
+ return String(err);
6994
+ }
6995
+ //#endregion
6996
+ //#region ../types/dist/index.mjs
6997
+ /**
6998
+ * Deep wiring healthcheck — snapshot of active reachability probes across
6999
+ * every declared capability + widget of every installed plugin, on every
7000
+ * node. Produced by the backend `WiringHealthService` and surfaced via
7001
+ * `GET /health/wiring`, the tRPC `health.wiring` query, and the boot-gate.
7002
+ *
7003
+ * Unlike `/health` (process liveness), this reflects whether each cap/widget
7004
+ * is actually *reachable* over the real cap-dispatch path. See spec
7005
+ * `docs/superpowers/specs/2026-05-23-deep-healthcheck-design.md`.
7006
+ */
7007
+ /** What kind of target a probe addressed. */
7008
+ var wiringProbeKindSchema = _enum([
7009
+ "singleton",
7010
+ "device",
7011
+ "widget"
7012
+ ]);
7013
+ /** Result of probing a single (cap|widget [, device]) target. */
7014
+ var wiringProbeResultSchema = object({
7015
+ capName: string(),
7016
+ kind: wiringProbeKindSchema,
7017
+ deviceId: number().optional(),
7018
+ reachable: boolean(),
7019
+ latencyMs: number(),
7020
+ error: string().optional()
7021
+ });
7022
+ /** Per-addon roll-up of cap + widget probe results. */
7023
+ var wiringAddonHealthSchema = object({
7024
+ addonId: string(),
7025
+ caps: array(wiringProbeResultSchema).readonly(),
7026
+ widgets: array(wiringProbeResultSchema).readonly()
7027
+ });
7028
+ /** Per-node roll-up. */
7029
+ var wiringNodeHealthSchema = object({
7030
+ nodeId: string(),
7031
+ addons: array(wiringAddonHealthSchema).readonly()
7032
+ });
7033
+ object({
7034
+ /** True only when every probed target is reachable. */
7035
+ ok: boolean(),
7036
+ /** True when at least one target is unreachable. */
7037
+ degraded: boolean(),
7038
+ checkedAt: string(),
7039
+ nodes: array(wiringNodeHealthSchema).readonly(),
7040
+ summary: object({
7041
+ total: number(),
7042
+ reachable: number(),
7043
+ unreachable: number()
7044
+ })
7045
+ });
7046
+ var MODEL_FORMATS = [
7047
+ "onnx",
7048
+ "coreml",
7049
+ "openvino",
7050
+ "tflite",
7051
+ "pt"
7052
+ ];
7053
+ /**
7054
+ * Numeric day-of-week: 0 = Sunday … 6 = Saturday (matches `Date.getDay`).
7055
+ * Named `RecordingWeekday` to avoid collision with the string-union
7056
+ * `Weekday` exported from `interfaces/timezones.ts`.
7057
+ */
7058
+ var RecordingWeekdaySchema = number().int().min(0).max(6);
7059
+ var HHMM = /^([01]\d|2[0-3]):[0-5]\d$/;
7060
+ var RecordingScheduleSchema = discriminatedUnion("kind", [object({ kind: literal("always") }), object({
7061
+ kind: literal("timeOfDay"),
7062
+ start: string().regex(HHMM),
7063
+ end: string().regex(HHMM),
7064
+ /** Restrict to these weekdays; omit = every day. */
7065
+ days: array(RecordingWeekdaySchema).optional()
7066
+ })]);
7067
+ var RecordingModeSchema = _enum([
7068
+ "continuous",
7069
+ "onMotion",
7070
+ "onAudioThreshold"
7071
+ ]);
7072
+ /**
7073
+ * First-class, authoritative per-camera storage mode — the netta choice the UI
7074
+ * reads directly (never inferred from `rules`):
7075
+ * - `off` — not recording.
7076
+ * - `events` — record only around triggers (motion / audio threshold),
7077
+ * with pre/post-buffer.
7078
+ * - `continuous` — record 24/7 within the schedule.
7079
+ *
7080
+ * `mode` compiles one-way to the internal `rules[]` consumed by the policy
7081
+ * engine (see `compileRules`); `rules[]` is never authored directly anymore.
7082
+ */
7083
+ var RecordingStorageModeSchema = _enum([
7084
+ "off",
7085
+ "events",
7086
+ "continuous"
7087
+ ]);
7088
+ /** Which detectors trigger an `events`-mode recording. */
7089
+ var RecordingTriggersSchema = object({
7090
+ motion: boolean().optional(),
7091
+ audioThresholdDbfs: number().optional()
7092
+ });
7093
+ /**
7094
+ * Mode of a single recording band — the recorder per-band vocabulary.
7095
+ *
7096
+ * Distinct from `RecordingStorageModeSchema` (which carries `off`): a band is
7097
+ * only ever `continuous` or `events`; "off" is expressed by the absence of a
7098
+ * covering band, not by a band value.
7099
+ */
7100
+ var RecordingBandModeSchema = _enum(["continuous", "events"]);
7101
+ /**
7102
+ * Triggers for an `events`-mode band. Identical shape to
7103
+ * `RecordingTriggersSchema` — reuse that schema as the band trigger type so the
7104
+ * two never drift.
7105
+ */
7106
+ var RecordingBandTriggersSchema = RecordingTriggersSchema;
7107
+ /**
7108
+ * A single mode-per-band window — the canonical recorder band shape, the
7109
+ * single source of truth re-used by `addon-pipeline/recorder`.
7110
+ *
7111
+ * `days` lists the weekdays the band covers (empty = every day, matching the
7112
+ * band engine's `applies` rule). `start`/`end` are `HH:MM`; an `end <= start`
7113
+ * span wraps past midnight (handled by the band engine).
7114
+ */
7115
+ var RecordingBandSchema = object({
7116
+ days: array(RecordingWeekdaySchema),
7117
+ start: string().regex(HHMM),
7118
+ end: string().regex(HHMM),
7119
+ mode: RecordingBandModeSchema,
7120
+ triggers: RecordingBandTriggersSchema.optional(),
7121
+ preBufferSec: number().min(0).optional(),
7122
+ postBufferSec: number().min(0).optional()
7123
+ });
7124
+ var RecordingRuleSchema = object({
7125
+ schedule: RecordingScheduleSchema,
7126
+ mode: RecordingModeSchema,
7127
+ /** Seconds of footage to retain BEFORE a trigger (applied at keep/discard). */
7128
+ preBufferSec: number().min(0).default(0),
7129
+ /** Keep recording until this many seconds after the last trigger. */
7130
+ postBufferSec: number().min(0).default(0),
7131
+ /** Each new trigger restarts the post-buffer window. */
7132
+ resetTimeoutOnNewEvent: boolean().default(true),
7133
+ /** onAudioThreshold only — dBFS level that counts as a trigger. */
7134
+ thresholdDbfs: number().optional()
7135
+ });
7136
+ /**
7137
+ * Per-device retention overrides. Every field is optional; an unset or `0`
7138
+ * value inherits the node-wide recorder default. Only footage-lifetime limits
7139
+ * live per-camera: `maxAgeDays` and `maxSizeGb`. The disk-occupancy threshold
7140
+ * (when the volume is too full to keep recording) is NOT a per-camera concern —
7141
+ * it belongs to the StorageLocation (`StorageLocation.config.minFreePercent`),
7142
+ * shared by every camera writing to that volume.
7143
+ */
7144
+ var RecordingRetentionSchema = object({
7145
+ maxAgeDays: number().min(0).optional(),
7146
+ maxSizeGb: number().min(0).optional()
7147
+ });
7148
+ /**
7149
+ * The full per-camera recording intent — the wire shape of a RecordingTarget.
7150
+ *
7151
+ * `mode` is the authoritative storage choice; `schedule`/`triggers`/`pre`/`post`
7152
+ * are its mode-specific parameters. `rules` is a DEPRECATED authoring input kept
7153
+ * only for transition + migration (`migrateRulesToMode`); the policy engine
7154
+ * consumes the compiled output of `compileRules(config)`, never `rules` directly.
7155
+ */
7156
+ var RecordingConfigSchema = object({
7157
+ enabled: boolean(),
7158
+ /** Authoritative storage mode. Absent on legacy targets → derived once via
7159
+ * `migrateRulesToMode`, then persisted. */
7160
+ mode: RecordingStorageModeSchema.optional(),
7161
+ profiles: array(CamProfileSchema).optional(),
7162
+ segmentSeconds: number().int().positive().optional(),
7163
+ /** Shared recording time-bands for `events` & `continuous` record only when
7164
+ * the wall-clock falls inside one of these windows. Omit or empty = always.
7165
+ * `continuous` compiles to one rule per band; `events` to band × trigger. */
7166
+ schedules: array(RecordingScheduleSchema).optional(),
7167
+ /** Legacy single-band predecessor of `schedules`. Read-compat only — it is
7168
+ * normalized into `schedules` on read and never written going forward. (Not
7169
+ * tagged `@deprecated`: the normalization paths must read it cast-free.) */
7170
+ schedule: RecordingScheduleSchema.optional(),
7171
+ /** `events`-mode only — which detectors trigger a recording. */
7172
+ triggers: RecordingTriggersSchema.optional(),
7173
+ /** `events`-mode only seconds retained before / after a trigger. */
7174
+ preBufferSec: number().min(0).optional(),
7175
+ postBufferSec: number().min(0).optional(),
7176
+ /** DEPRECATED authoring input; retained for migration/transition. */
7177
+ rules: array(RecordingRuleSchema).optional(),
7178
+ /**
7179
+ * AUTHORITATIVE mode-per-band recording model (recorder). When present it
7180
+ * is the single source of truth; the legacy `mode`/`schedules`/`schedule`/
7181
+ * `triggers`/`rules` fields above are kept for READ-COMPAT only and are
7182
+ * derived into bands once via `migrateConfigToBands`.
7183
+ */
7184
+ bands: array(RecordingBandSchema).optional(),
7185
+ retention: RecordingRetentionSchema.optional()
7186
+ });
7187
+ /**
7188
+ * `StorageLocationType` — an addon-declared id that identifies the *kind* of
7189
+ * storage a location serves. Defined here (not in `capabilities/storage.cap.ts`)
7190
+ * so the persisted record schema and the consumer-facing cap can both consume it
7191
+ * without forming a circular import. The `storage` cap re-exports it
7192
+ * verbatim for back-compat.
7193
+ *
7194
+ * This Zod schema is the **authoritative source** for `StorageLocationType`.
7195
+ * The TS alias in `./storage.ts` re-exports `z.infer<typeof
7196
+ * StorageLocationTypeSchema>` so the wire surface (cap) and the legacy
7197
+ * `IStorageProvider` interface stay in lockstep.
7198
+ *
7199
+ * The type is now an **open string** (not a closed enum) — addons declare
7200
+ * their own location kinds via `StorageLocationDeclaration.id`. The regex
7201
+ * enforces a safe id format: lowercase-start, alphanumeric + hyphens.
7202
+ */
7203
+ var StorageLocationTypeSchema = string().regex(/^[a-z][a-zA-Z0-9-]*$/);
7204
+ /**
7205
+ * Persisted record for a storage location instance. Operators can register
7206
+ * multiple instances for multi-cardinality types (e.g. two `backups`
7207
+ * locations with different `providerId`s). Cardinality is now declared per
7208
+ * location via `StorageLocationDeclaration.cardinality` — the static
7209
+ * `STORAGE_LOCATION_CARDINALITY` map has been removed.
7210
+ *
7211
+ * `id` is a stable namespaced string of the form `<type>:<slug>`.
7212
+ * The default location for a type uses `id === <type>:default` by
7213
+ * convention (the bare type ref like `'backups'` resolves to it).
7214
+ *
7215
+ * `isSystem: true` marks a location as orchestrator-seeded and
7216
+ * undeletable. The bootstrap-installed defaults (one per type) carry
7217
+ * this flag; operator-added locations don't. Editing the config of
7218
+ * a system location is allowed (path migration, provider swap) but
7219
+ * deleting it is rejected at the cap level.
7220
+ */
7221
+ var StorageLocationSchema = object({
7222
+ id: string().regex(/^[a-z][a-zA-Z0-9-]*:[a-zA-Z0-9-]+$/),
7223
+ type: string(),
7224
+ displayName: string().min(1),
7225
+ providerId: string().min(1),
7226
+ config: record(string(), unknown()),
7304
7227
  /**
7305
- * Device supports an on-demand re-sync of its derived spec with its
7306
- * upstream sourcedrives the generic Re-sync button. The owning
7307
- * provider implements the action via the `device-adoption.resync` cap.
7228
+ * Cluster node this location physically lives on. REQUIRED for node-local
7229
+ * providers (filesystem — the path exists on one node's disk), null/absent
7230
+ * for node-agnostic providers (S3/SFTP/WebDAV, reachable from any node).
7231
+ * `'hub'` is the hub node. Validated against the provider's `nodeLocal`
7232
+ * flag at upsert time, not here (the schema is provider-agnostic).
7308
7233
  */
7309
- DeviceFeature["Resyncable"] = "resyncable";
7310
- DeviceFeature["NativeSnapshot"] = "native-snapshot";
7311
- DeviceFeature["DoorbellButton"] = "doorbell-button";
7312
- DeviceFeature["TwoWayAudio"] = "two-way-audio";
7313
- DeviceFeature["PanTiltZoom"] = "pan-tilt-zoom";
7234
+ nodeId: string().optional(),
7235
+ isDefault: boolean().default(false),
7236
+ isSystem: boolean().default(false),
7237
+ createdAt: number(),
7238
+ updatedAt: number()
7239
+ });
7240
+ /**
7241
+ * Reference accepted by consumer-facing `api.storage.*` calls.
7242
+ * Either:
7243
+ * - a `StorageLocationType` (e.g. `'backups'`) → orchestrator resolves to the default of that type
7244
+ * - a fully-qualified id (e.g. `'backups:nas-01'`) → addresses a specific instance
7245
+ *
7246
+ * The orchestrator's `resolveRef(ref)` handles both cases.
7247
+ */
7248
+ var StorageLocationRefSchema = union([StorageLocationTypeSchema, string().regex(/^[a-z][a-zA-Z0-9-]*:[a-zA-Z0-9-]+$/)]);
7249
+ /**
7250
+ * `StorageLocationDeclaration` — a single storage-location entry declared by
7251
+ * an addon in its `package.json` under `camstack.storageLocations`.
7252
+ *
7253
+ * Design intent:
7254
+ * - **Addon declares its needs** — each addon describes the logical storage
7255
+ * slots it requires (e.g. `recordings`, `recordingsLow`) without caring
7256
+ * about the physical path.
7257
+ * - **Kernel aggregates** — at boot the kernel collects declarations from all
7258
+ * installed addons, deduplicates by `id`, and exposes the union via the
7259
+ * storage-locations settings surface.
7260
+ * - **Orchestrator seeds** — for every declared `id` the orchestrator ensures
7261
+ * at least one instance named `<id>:default` is present, using
7262
+ * `defaultsTo` to inherit the resolved root from another location when the
7263
+ * declaration is a derivative slot (e.g. `recordingsLow` defaults to
7264
+ * `recordings`).
7265
+ * - **ids are global** — `id` values are shared across the entire deployment;
7266
+ * two addons declaring the same `id` must agree on `cardinality` (validated
7267
+ * at kernel aggregation time, not here).
7268
+ */
7269
+ var StorageLocationDeclarationSchema = object({
7314
7270
  /**
7315
- * Camera supports the on-firmware autotrack subsystem (subject-
7316
- * following). Distinct from `PanTiltZoom` because not every PTZ
7317
- * camera ships autotrack — the admin UI uses this flag to gate
7318
- * the autotrack toggle / settings card without re-deriving from
7319
- * the cap registry. Mirrors `ptz-autotrack` cap registration:
7320
- * driver sets this feature when probe confirms the firmware
7321
- * surface, and registers the cap in the same code path.
7271
+ * Global location identifier, e.g. `recordings` or `recordingsLow`.
7272
+ * Must start with a lowercase letter and may contain letters, digits, and
7273
+ * hyphens.
7322
7274
  */
7323
- DeviceFeature["PtzAutotrack"] = "ptz-autotrack";
7275
+ id: string().regex(/^[a-z][a-zA-Z0-9-]*$/, { message: "id must start with a lowercase letter and contain only letters, digits, or hyphens" }),
7276
+ /** Human-readable name shown in the admin UI. */
7277
+ displayName: string().min(1, { message: "displayName must not be empty" }),
7278
+ /** Optional longer explanation of what data this location stores. */
7279
+ description: string().optional(),
7324
7280
  /**
7325
- * Accessory exposes a "trigger on motion" toggle the parent camera's
7326
- * motion detection automatically activates this device. Mirrors
7327
- * `motion-trigger` cap registration: drivers set this feature in the
7328
- * same code path that calls `ctx.registerNativeCap(motionTriggerCapability, ...)`.
7329
- *
7330
- * Used by admin UI (gate the in-hero `MotionTriggerToggle` against a
7331
- * fast scalar without binding fetch), notifier rules, and `listAll`
7332
- * filters that want "all devices with on-motion behaviour".
7281
+ * `single` exactly one instance of this location is allowed system-wide
7282
+ * (e.g. `logs`, `models`). The operator can edit it but not add more.
7283
+ * `multi` the operator may register several instances (e.g. a second
7284
+ * `recordings` on a NAS for disk tiering); one is the default at any time.
7333
7285
  */
7334
- DeviceFeature["MotionTrigger"] = "motion-trigger";
7335
- /** Light supports rgb-triplet color via `color` cap. */
7336
- DeviceFeature["LightColorRgb"] = "light-color-rgb";
7337
- /** Light supports HSV color via `color` cap. */
7338
- DeviceFeature["LightColorHsv"] = "light-color-hsv";
7339
- /** Light supports color-temperature (mired) via `color` cap. */
7340
- DeviceFeature["LightColorMired"] = "light-color-mired";
7341
- /** Thermostat supports a `heat_cool` dual setpoint (targetLow +
7342
- * targetHigh). Gates the range slider UI. */
7343
- DeviceFeature["ClimateDualSetpoint"] = "climate-dual-setpoint";
7344
- /** Thermostat exposes target humidity and/or current humidity
7345
- * readings. Gates the humidity controls. */
7346
- DeviceFeature["ClimateHumidity"] = "climate-humidity";
7347
- /** Thermostat exposes a fan-mode selector. */
7348
- DeviceFeature["ClimateFanMode"] = "climate-fan-mode";
7349
- /** Thermostat exposes preset modes (eco / away / sleep / vendor). */
7350
- DeviceFeature["ClimatePreset"] = "climate-preset";
7351
- /** Cover exposes intermediate position control (0..100). Gates the
7352
- * position slider UI. */
7353
- DeviceFeature["CoverPositionable"] = "cover-positionable";
7354
- /** Cover exposes slat-tilt control. Gates the tilt slider UI. */
7355
- DeviceFeature["CoverTilt"] = "cover-tilt";
7356
- /** Valve exposes intermediate position control (0..100). Gates the
7357
- * position slider / drag surface UI. */
7358
- DeviceFeature["ValvePositionable"] = "valve-positionable";
7359
- /** Fan exposes a speed-percentage setter. Gates the speed slider UI. */
7360
- DeviceFeature["FanSpeed"] = "fan-speed";
7361
- /** Fan exposes a preset mode selector. */
7362
- DeviceFeature["FanPreset"] = "fan-preset";
7363
- /** Fan exposes blade direction (forward/reverse) typical of
7364
- * ceiling fans. */
7365
- DeviceFeature["FanDirection"] = "fan-direction";
7366
- /** Fan exposes an oscillation toggle. */
7367
- DeviceFeature["FanOscillating"] = "fan-oscillating";
7368
- /** Lock requires a PIN code on lock/unlock. Gates the code-entry
7369
- * field on the UI lock-controls panel. */
7370
- DeviceFeature["LockPinRequired"] = "lock-pin-required";
7371
- /** Lock supports a latch-release ("open door") action distinct from
7372
- * unlock. Mirrors HA `LockEntityFeature.OPEN` (bit 1) in
7373
- * `supported_features`. Gates the Open Door button in the UI. */
7374
- DeviceFeature["LockOpen"] = "lock-open";
7375
- /** Media player exposes a seek-to-position surface. */
7376
- DeviceFeature["MediaPlayerSeek"] = "media-player-seek";
7377
- /** Media player exposes a volume-level setter. */
7378
- DeviceFeature["MediaPlayerVolume"] = "media-player-volume";
7379
- /** Media player exposes a mute toggle distinct from volume=0. */
7380
- DeviceFeature["MediaPlayerMute"] = "media-player-mute";
7381
- /** Media player exposes a shuffle toggle. */
7382
- DeviceFeature["MediaPlayerShuffle"] = "media-player-shuffle";
7383
- /** Media player exposes a repeat mode (off / all / one). */
7384
- DeviceFeature["MediaPlayerRepeat"] = "media-player-repeat";
7385
- /** Media player exposes a source / input selector. */
7386
- DeviceFeature["MediaPlayerSelectSource"] = "media-player-select-source";
7387
- /** Media player exposes a play-arbitrary-media surface (URL / id). */
7388
- DeviceFeature["MediaPlayerPlayMedia"] = "media-player-play-media";
7389
- /** Media player exposes next-track. */
7390
- DeviceFeature["MediaPlayerNext"] = "media-player-next";
7391
- /** Media player exposes previous-track. */
7392
- DeviceFeature["MediaPlayerPrevious"] = "media-player-previous";
7393
- /** Media player exposes stop distinct from pause. */
7394
- DeviceFeature["MediaPlayerStop"] = "media-player-stop";
7395
- /** Alarm panel requires a PIN code on arm/disarm. */
7396
- DeviceFeature["AlarmPinRequired"] = "alarm-pin-required";
7397
- /** Presence device carries GPS coordinates (lat/lng/accuracy) in
7398
- * addition to a textual location. */
7399
- DeviceFeature["PresenceGps"] = "presence-gps";
7400
- /** Notifier accepts an inline / URL image attachment. */
7401
- DeviceFeature["NotifierImage"] = "notifier-image";
7402
- /** Notifier accepts a priority hint (high/normal/low). */
7403
- DeviceFeature["NotifierPriority"] = "notifier-priority";
7404
- /** Notifier accepts a free-form `data` payload for platform-specific
7405
- * fields. */
7406
- DeviceFeature["NotifierData"] = "notifier-data";
7407
- /** Notifier supports interactive action buttons / callbacks. */
7408
- DeviceFeature["NotifierActions"] = "notifier-actions";
7409
- /** Notifier supports per-call recipient targeting (multi-user). */
7410
- DeviceFeature["NotifierRecipients"] = "notifier-recipients";
7411
- /** Script runner accepts a variables map on each run invocation. */
7412
- DeviceFeature["ScriptVariables"] = "script-variables";
7413
- /** Automation `trigger` accepts a skipCondition flag — fires the
7414
- * automation's actions while bypassing its condition block. */
7415
- DeviceFeature["AutomationSkipCondition"] = "automation-skip-condition";
7416
- return DeviceFeature;
7417
- }({});
7418
- /**
7419
- * Semantic role a device plays within its parent. Populated by driver
7420
- * addons when creating accessory devices (Reolink siren/floodlight/
7421
- * PIR/chime/autotrack/doorbell, ONVIF relay outputs, …). Used by the
7422
- * admin UI to pick icons, labels, and widgets — a `Switch` with
7423
- * `role: Floodlight` renders as a bulb with a brightness slider,
7424
- * whereas a `Switch` with `role: Siren` renders as a klaxon.
7425
- *
7426
- * Undefined for top-level devices (cameras, NVRs, hubs). Persisted in
7427
- * sqlite as a nullable TEXT column — old rows keep working unchanged.
7428
- */
7429
- var DeviceRole = /* @__PURE__ */ function(DeviceRole) {
7430
- DeviceRole["Siren"] = "siren";
7431
- DeviceRole["Floodlight"] = "floodlight";
7432
- DeviceRole["Spotlight"] = "spotlight";
7433
- DeviceRole["PirSensor"] = "pir-sensor";
7434
- DeviceRole["Chime"] = "chime";
7435
- DeviceRole["Autotrack"] = "autotrack";
7436
- DeviceRole["Nightvision"] = "nightvision";
7437
- DeviceRole["PrivacyMask"] = "privacy-mask";
7438
- DeviceRole["Doorbell"] = "doorbell";
7439
- /** Virtual HA toggle (input_boolean.*) — distinguishable from a
7440
- * real Switch device for UI rendering / export adapters. */
7441
- DeviceRole["BinaryHelper"] = "binary-helper";
7442
- /** Generic motion / occupancy / moving event source. Distinct from
7443
- * the camera accessory PirSensor role: that one is a camera child;
7444
- * this is a standalone HA / 3rd-party motion sensor. */
7445
- DeviceRole["MotionSensor"] = "motion-sensor";
7446
- DeviceRole["ContactSensor"] = "contact-sensor";
7447
- DeviceRole["LeakSensor"] = "leak-sensor";
7448
- DeviceRole["SmokeSensor"] = "smoke-sensor";
7449
- DeviceRole["COSensor"] = "co-sensor";
7450
- DeviceRole["GasSensor"] = "gas-sensor";
7451
- DeviceRole["TamperSensor"] = "tamper-sensor";
7452
- DeviceRole["VibrationSensor"] = "vibration-sensor";
7453
- DeviceRole["ConnectivitySensor"] = "connectivity-sensor";
7454
- DeviceRole["SoundSensor"] = "sound-sensor";
7455
- /** Fallback for `binary_sensor` without a known `device_class`. */
7456
- DeviceRole["BinarySensor"] = "binary-sensor";
7457
- DeviceRole["TemperatureSensor"] = "temperature-sensor";
7458
- DeviceRole["HumiditySensor"] = "humidity-sensor";
7459
- DeviceRole["AmbientLightSensor"] = "ambient-light-sensor";
7460
- DeviceRole["PressureSensor"] = "pressure-sensor";
7461
- DeviceRole["PowerSensor"] = "power-sensor";
7462
- DeviceRole["EnergySensor"] = "energy-sensor";
7463
- DeviceRole["VoltageSensor"] = "voltage-sensor";
7464
- DeviceRole["CurrentSensor"] = "current-sensor";
7465
- DeviceRole["AirQualitySensor"] = "air-quality-sensor";
7466
- /** Battery level (numeric % via `sensor` OR low-bool via
7467
- * `binary_sensor` — the cap distinguishes via the value type). */
7468
- DeviceRole["BatterySensor"] = "battery-sensor";
7469
- /** Fallback for `sensor` numeric without a known `device_class`. */
7470
- DeviceRole["NumericSensor"] = "numeric-sensor";
7471
- /** String / enum state (HA `sensor` with `state_class: enum` or
7472
- * `attributes.options`). */
7473
- DeviceRole["EnumSensor"] = "enum-sensor";
7474
- /** Date / timestamp state (HA `sensor` with `device_class: timestamp`
7475
- * or `date`). The slice carries the raw ISO string verbatim (hosted on
7476
- * the `enum-sensor` cap); the UI renders it locale-formatted. */
7477
- DeviceRole["DateTimeSensor"] = "datetime-sensor";
7478
- /** Last-resort fallback when nothing else matches. */
7479
- DeviceRole["GenericSensor"] = "generic-sensor";
7480
- DeviceRole["NumericControl"] = "numeric-control";
7481
- DeviceRole["SelectControl"] = "select-control";
7482
- DeviceRole["TextControl"] = "text-control";
7483
- DeviceRole["DateTimeControl"] = "datetime-control";
7484
- /** Mobile push notifier (HA `notify.mobile_app_*`) — supports
7485
- * rich features (image, priority, channel routing). */
7486
- DeviceRole["MobilePushNotifier"] = "mobile-push-notifier";
7487
- /** Chat / messaging service (HA `notify.telegram_*`,
7488
- * `notify.discord_*`, etc.). */
7489
- DeviceRole["MessagingNotifier"] = "messaging-notifier";
7490
- /** Email-based delivery (HA `notify.smtp`, etc.). */
7491
- DeviceRole["EmailNotifier"] = "email-notifier";
7492
- /** Fallback when the notifier service name doesn't match a known
7493
- * pattern. */
7494
- DeviceRole["GenericNotifier"] = "generic-notifier";
7495
- return DeviceRole;
7496
- }({});
7286
+ cardinality: _enum(["single", "multi"]),
7287
+ /**
7288
+ * When set, the default instance for this location inherits its resolved
7289
+ * root from the named location's default instance. Useful for derivative
7290
+ * slots (e.g. `recordingsLow` → `recordings`) so operators only need to
7291
+ * configure the primary location.
7292
+ */
7293
+ defaultsTo: string().optional()
7294
+ });
7295
+ var DecoderStatsSchema = object({
7296
+ inputFps: number(),
7297
+ outputFps: number(),
7298
+ avgDecodeTimeMs: number(),
7299
+ droppedFrames: number()
7300
+ });
7301
+ var DecoderSessionConfigSchema = object({
7302
+ codec: string(),
7303
+ maxFps: number().default(0),
7304
+ outputFormat: _enum([
7305
+ "jpeg",
7306
+ "rgb",
7307
+ "bgr",
7308
+ "yuv420",
7309
+ "gray"
7310
+ ]).default("jpeg"),
7311
+ scale: number().default(1),
7312
+ width: number().optional(),
7313
+ height: number().optional(),
7314
+ /**
7315
+ * Identifier of the camera this decoder session serves. Optional
7316
+ * because the cap is generic (any caller could request decode), but
7317
+ * stream-broker passes it so decoder logs include `deviceId` for
7318
+ * per-camera filtering when diagnosing failures (e.g. node-av
7319
+ * sendPacket errors on a single hung camera).
7320
+ */
7321
+ deviceId: number().int().nonnegative().optional(),
7322
+ /**
7323
+ * Free-form tag for log scoping. Stream-broker uses
7324
+ * `broker:<deviceId>/<profile>`. Decoder session logger surfaces it
7325
+ * on every line so `grep tag=broker:5/high` filters one camera
7326
+ * profile cleanly.
7327
+ */
7328
+ tag: string().optional(),
7329
+ /**
7330
+ * Where the session delivers decoded frames (Phase 5 / D9):
7331
+ *
7332
+ * - `'callback'` (default) — the legacy pixel path: decoded frames are
7333
+ * buffered as `DecodedFrame`s and drained via `pullFrames`.
7334
+ * - `'shm'` — the shared-memory frame plane: decoded frames are written
7335
+ * into an OS shared-memory ring and drained as zero-pixel
7336
+ * `FrameHandle`s via `pullHandles`. A session is one mode or the
7337
+ * other `pullFrames` returns nothing for an `'shm'` session and
7338
+ * `pullHandles` returns nothing for a `'callback'` session.
7339
+ */
7340
+ frameSink: _enum(["callback", "shm"]).default("callback")
7341
+ });
7342
+ var EncodeProfileSchema = object({
7343
+ video: object({
7344
+ codec: _enum([
7345
+ "h264",
7346
+ "h265",
7347
+ "copy"
7348
+ ]),
7349
+ profile: _enum([
7350
+ "baseline",
7351
+ "main",
7352
+ "high"
7353
+ ]).optional(),
7354
+ width: number().int().positive().optional(),
7355
+ height: number().int().positive().optional(),
7356
+ fps: number().positive().optional(),
7357
+ bitrateKbps: number().int().positive().optional(),
7358
+ gopFrames: number().int().positive().optional(),
7359
+ bf: number().int().min(0).optional(),
7360
+ preset: _enum([
7361
+ "ultrafast",
7362
+ "superfast",
7363
+ "veryfast",
7364
+ "faster",
7365
+ "fast",
7366
+ "medium"
7367
+ ]).optional(),
7368
+ tune: _enum([
7369
+ "zerolatency",
7370
+ "film",
7371
+ "animation"
7372
+ ]).optional()
7373
+ }),
7374
+ audio: union([literal("passthrough"), object({
7375
+ codec: _enum([
7376
+ "opus",
7377
+ "aac",
7378
+ "pcmu",
7379
+ "pcma",
7380
+ "copy"
7381
+ ]),
7382
+ bitrateKbps: number().int().positive().optional(),
7383
+ sampleRateHz: number().int().positive().optional(),
7384
+ channels: union([literal(1), literal(2)]).optional()
7385
+ })]),
7386
+ /**
7387
+ * ffmpeg input-side args, inserted between the fixed global flags
7388
+ * (`-hide_banner -loglevel error`) and `-i pipe:0`. Free-text array
7389
+ * the widget surfaces a textarea + suggestion chips for the most-
7390
+ * used demuxer/format options.
7391
+ */
7392
+ inputArgs: array(string()).optional(),
7393
+ /**
7394
+ * ffmpeg output-side args, inserted between the encode block and
7395
+ * the final `-f <muxer> pipe:1`. Use for muxer options, bitstream
7396
+ * filters, codec-specific overrides. Free-text array.
7397
+ */
7398
+ outputArgs: array(string()).optional()
7399
+ });
7400
+ var YAMNET_TO_MACRO = {
7401
+ mapping: {
7402
+ Speech: "speech",
7403
+ "Child speech, kid speaking": "speech",
7404
+ Conversation: "speech",
7405
+ "Narration, monologue": "speech",
7406
+ Babbling: "speech",
7407
+ Whispering: "speech",
7408
+ "Speech synthesizer": "speech",
7409
+ Humming: "speech",
7410
+ Rapping: "speech",
7411
+ Singing: "speech",
7412
+ Choir: "speech",
7413
+ "Child singing": "speech",
7414
+ Shout: "scream",
7415
+ Bellow: "scream",
7416
+ Yell: "scream",
7417
+ Screaming: "scream",
7418
+ "Children shouting": "scream",
7419
+ Whoop: "scream",
7420
+ "Crying, sobbing": "crying",
7421
+ "Baby cry, infant cry": "crying",
7422
+ Whimper: "crying",
7423
+ "Wail, moan": "crying",
7424
+ Groan: "crying",
7425
+ Laughter: "laughter",
7426
+ "Baby laughter": "laughter",
7427
+ Giggle: "laughter",
7428
+ Snicker: "laughter",
7429
+ "Belly laugh": "laughter",
7430
+ "Chuckle, chortle": "laughter",
7431
+ Music: "music",
7432
+ "Musical instrument": "music",
7433
+ Guitar: "music",
7434
+ Piano: "music",
7435
+ Drum: "music",
7436
+ "Drum kit": "music",
7437
+ "Violin, fiddle": "music",
7438
+ Flute: "music",
7439
+ Saxophone: "music",
7440
+ Trumpet: "music",
7441
+ Synthesizer: "music",
7442
+ "Pop music": "music",
7443
+ "Rock music": "music",
7444
+ "Hip hop music": "music",
7445
+ "Classical music": "music",
7446
+ Jazz: "music",
7447
+ "Electronic music": "music",
7448
+ "Background music": "music",
7449
+ Dog: "dog",
7450
+ Bark: "dog",
7451
+ Yip: "dog",
7452
+ Howl: "dog",
7453
+ "Bow-wow": "dog",
7454
+ Growling: "dog",
7455
+ "Whimper (dog)": "dog",
7456
+ Cat: "cat",
7457
+ Purr: "cat",
7458
+ Meow: "cat",
7459
+ Hiss: "cat",
7460
+ Caterwaul: "cat",
7461
+ Bird: "bird",
7462
+ "Bird vocalization, bird call, bird song": "bird",
7463
+ "Chirp, tweet": "bird",
7464
+ Squawk: "bird",
7465
+ Crow: "bird",
7466
+ Owl: "bird",
7467
+ "Pigeon, dove": "bird",
7468
+ Animal: "animal",
7469
+ "Domestic animals, pets": "animal",
7470
+ "Livestock, farm animals, working animals": "animal",
7471
+ Horse: "animal",
7472
+ "Cattle, bovinae": "animal",
7473
+ Pig: "animal",
7474
+ Sheep: "animal",
7475
+ Goat: "animal",
7476
+ Frog: "animal",
7477
+ Insect: "animal",
7478
+ Cricket: "animal",
7479
+ Alarm: "alarm",
7480
+ "Alarm clock": "alarm",
7481
+ "Smoke detector, smoke alarm": "alarm",
7482
+ "Fire alarm": "alarm",
7483
+ Buzzer: "alarm",
7484
+ "Civil defense siren": "alarm",
7485
+ "Car alarm": "alarm",
7486
+ Siren: "siren",
7487
+ "Police car (siren)": "siren",
7488
+ "Ambulance (siren)": "siren",
7489
+ "Fire engine, fire truck (siren)": "siren",
7490
+ "Emergency vehicle": "siren",
7491
+ Foghorn: "siren",
7492
+ Doorbell: "doorbell",
7493
+ "Ding-dong": "doorbell",
7494
+ Knock: "doorbell",
7495
+ Tap: "doorbell",
7496
+ Glass: "glass_breaking",
7497
+ Shatter: "glass_breaking",
7498
+ "Chink, clink": "glass_breaking",
7499
+ "Gunshot, gunfire": "gunshot",
7500
+ "Machine gun": "gunshot",
7501
+ Explosion: "gunshot",
7502
+ Fireworks: "gunshot",
7503
+ Firecracker: "gunshot",
7504
+ "Artillery fire": "gunshot",
7505
+ "Cap gun": "gunshot",
7506
+ Boom: "gunshot",
7507
+ Vehicle: "vehicle",
7508
+ Car: "vehicle",
7509
+ Truck: "vehicle",
7510
+ Bus: "vehicle",
7511
+ Motorcycle: "vehicle",
7512
+ "Car passing by": "vehicle",
7513
+ "Vehicle horn, car horn, honking": "vehicle",
7514
+ "Traffic noise, roadway noise": "vehicle",
7515
+ Train: "vehicle",
7516
+ Aircraft: "vehicle",
7517
+ Helicopter: "vehicle",
7518
+ Bicycle: "vehicle",
7519
+ Skateboard: "vehicle",
7520
+ Fire: "fire",
7521
+ Crackle: "fire",
7522
+ Water: "water",
7523
+ Rain: "water",
7524
+ Raindrop: "water",
7525
+ "Rain on surface": "water",
7526
+ Stream: "water",
7527
+ Waterfall: "water",
7528
+ Ocean: "water",
7529
+ "Waves, surf": "water",
7530
+ "Splash, splatter": "water",
7531
+ Wind: "wind",
7532
+ Thunderstorm: "wind",
7533
+ Thunder: "wind",
7534
+ "Wind noise (microphone)": "wind",
7535
+ "Rustling leaves": "wind",
7536
+ Door: "door",
7537
+ "Sliding door": "door",
7538
+ Slam: "door",
7539
+ "Cupboard open or close": "door",
7540
+ "Walk, footsteps": "footsteps",
7541
+ Run: "footsteps",
7542
+ Shuffle: "footsteps",
7543
+ Crowd: "crowd",
7544
+ Chatter: "crowd",
7545
+ Cheering: "crowd",
7546
+ Applause: "crowd",
7547
+ "Children playing": "crowd",
7548
+ "Hubbub, speech noise, speech babble": "crowd",
7549
+ Telephone: "telephone",
7550
+ "Telephone bell ringing": "telephone",
7551
+ Ringtone: "telephone",
7552
+ "Telephone dialing, DTMF": "telephone",
7553
+ "Busy signal": "telephone",
7554
+ Engine: "engine",
7555
+ "Engine starting": "engine",
7556
+ Idling: "engine",
7557
+ "Accelerating, revving, vroom": "engine",
7558
+ "Light engine (high frequency)": "engine",
7559
+ "Medium engine (mid frequency)": "engine",
7560
+ "Heavy engine (low frequency)": "engine",
7561
+ "Lawn mower": "engine",
7562
+ Chainsaw: "engine",
7563
+ Hammer: "tools",
7564
+ Jackhammer: "tools",
7565
+ Sawing: "tools",
7566
+ "Power tool": "tools",
7567
+ Drill: "tools",
7568
+ Sanding: "tools",
7569
+ Silence: "silence"
7570
+ },
7571
+ preserveOriginal: false
7572
+ };
7573
+ var APPLE_SA_TO_MACRO = {
7574
+ mapping: {
7575
+ speech: "speech",
7576
+ child_speech: "speech",
7577
+ conversation: "speech",
7578
+ whispering: "speech",
7579
+ singing: "speech",
7580
+ humming: "speech",
7581
+ shout: "scream",
7582
+ yell: "scream",
7583
+ screaming: "scream",
7584
+ crying: "crying",
7585
+ baby_crying: "crying",
7586
+ sobbing: "crying",
7587
+ laughter: "laughter",
7588
+ baby_laughter: "laughter",
7589
+ giggling: "laughter",
7590
+ music: "music",
7591
+ guitar: "music",
7592
+ piano: "music",
7593
+ drums: "music",
7594
+ dog_bark: "dog",
7595
+ dog_bow_wow: "dog",
7596
+ dog_growling: "dog",
7597
+ dog_howl: "dog",
7598
+ cat_meow: "cat",
7599
+ cat_purr: "cat",
7600
+ cat_hiss: "cat",
7601
+ bird: "bird",
7602
+ bird_chirp: "bird",
7603
+ bird_squawk: "bird",
7604
+ animal: "animal",
7605
+ horse: "animal",
7606
+ cow_moo: "animal",
7607
+ insect: "animal",
7608
+ alarm: "alarm",
7609
+ smoke_alarm: "alarm",
7610
+ fire_alarm: "alarm",
7611
+ car_alarm: "alarm",
7612
+ siren: "siren",
7613
+ police_siren: "siren",
7614
+ ambulance_siren: "siren",
7615
+ doorbell: "doorbell",
7616
+ door_knock: "doorbell",
7617
+ knocking: "doorbell",
7618
+ glass_breaking: "glass_breaking",
7619
+ glass_shatter: "glass_breaking",
7620
+ gunshot: "gunshot",
7621
+ explosion: "gunshot",
7622
+ fireworks: "gunshot",
7623
+ car: "vehicle",
7624
+ truck: "vehicle",
7625
+ motorcycle: "vehicle",
7626
+ car_horn: "vehicle",
7627
+ vehicle_horn: "vehicle",
7628
+ traffic: "vehicle",
7629
+ fire: "fire",
7630
+ fire_crackle: "fire",
7631
+ water: "water",
7632
+ rain: "water",
7633
+ ocean: "water",
7634
+ splash: "water",
7635
+ wind: "wind",
7636
+ thunder: "wind",
7637
+ thunderstorm: "wind",
7638
+ door: "door",
7639
+ door_slam: "door",
7640
+ sliding_door: "door",
7641
+ footsteps: "footsteps",
7642
+ walking: "footsteps",
7643
+ running: "footsteps",
7644
+ crowd: "crowd",
7645
+ chatter: "crowd",
7646
+ cheering: "crowd",
7647
+ applause: "crowd",
7648
+ telephone_ring: "telephone",
7649
+ ringtone: "telephone",
7650
+ engine: "engine",
7651
+ engine_starting: "engine",
7652
+ lawn_mower: "engine",
7653
+ chainsaw: "engine",
7654
+ hammer: "tools",
7655
+ jackhammer: "tools",
7656
+ drill: "tools",
7657
+ power_tool: "tools",
7658
+ silence: "silence"
7659
+ },
7660
+ preserveOriginal: false
7661
+ };
7662
+ var _macroLookup = /* @__PURE__ */ new Map();
7663
+ for (const [k, v] of Object.entries(YAMNET_TO_MACRO.mapping)) _macroLookup.set(k.toLowerCase(), v);
7664
+ for (const [k, v] of Object.entries(APPLE_SA_TO_MACRO.mapping)) _macroLookup.set(k.toLowerCase(), v);
7497
7665
  /**
7498
7666
  * Accessory device helpers — shared across drivers.
7499
7667
  *
@@ -7684,74 +7852,6 @@ object({
7684
7852
  });
7685
7853
  DeviceType.Sensor;
7686
7854
  /**
7687
- * Generic types for capability definitions.
7688
- *
7689
- * A capability is defined with Zod schemas for methods, events, and settings.
7690
- * TypeScript types are inferred via z.infer<> — zero duplication.
7691
- *
7692
- * Pattern:
7693
- * 1. Define Zod schemas for data, methods, settings
7694
- * 2. Export const capabilityDef = { ... } satisfies CapabilityDefinition
7695
- * 3. Export type IProvider = InferProvider<typeof capabilityDef>
7696
- * 4. Addon implements IProvider
7697
- * 5. Registry auto-mounts tRPC router from definition.methods
7698
- */
7699
- /**
7700
- * Output schema shared by the contribution + live methods.
7701
- *
7702
- * Mirrors the `ConfigUISchemaWithValues` shape (sections[] + optional
7703
- * tabs[]) without importing from `../interfaces/config-ui.js` — a
7704
- * concrete-but-lenient Zod object keeps tRPC output inference happy
7705
- * (using `z.unknown()` here collapses unrelated router branches to
7706
- * `unknown` when the generator re-inlines the huge AppRouter type).
7707
- *
7708
- * `.passthrough()` on sections/fields accepts whatever FormBuilder
7709
- * extensions the caller adds (showWhen, displayScale, …) without
7710
- * rebuilding every time a new field kind is introduced.
7711
- */
7712
- var ContributionSectionSchema = object({
7713
- id: string(),
7714
- title: string(),
7715
- description: string().optional(),
7716
- style: _enum(["card", "accordion"]).optional(),
7717
- defaultCollapsed: boolean().optional(),
7718
- columns: union([
7719
- literal(1),
7720
- literal(2),
7721
- literal(3),
7722
- literal(4)
7723
- ]).optional(),
7724
- tab: string().optional(),
7725
- location: _enum(["settings", "top-tab"]).optional(),
7726
- order: number().optional(),
7727
- fields: array(any())
7728
- });
7729
- object({
7730
- tabs: array(object({
7731
- id: string(),
7732
- label: string(),
7733
- icon: string(),
7734
- order: number().optional()
7735
- })).optional(),
7736
- sections: array(ContributionSectionSchema)
7737
- }).nullable();
7738
- object({ deviceId: number() }), object({ deviceId: number() }), object({
7739
- deviceId: number(),
7740
- patch: record(string(), unknown())
7741
- }), object({ success: literal(true) });
7742
- object({ deviceId: number() }), unknown().nullable();
7743
- /** Shorthand to define a method schema */
7744
- function method(input, output, options) {
7745
- return {
7746
- input,
7747
- output,
7748
- kind: options?.kind ?? "query",
7749
- auth: options?.auth ?? "protected",
7750
- ...options?.access !== void 0 ? { access: options.access } : {},
7751
- timeoutMs: options?.timeoutMs
7752
- };
7753
- }
7754
- /**
7755
7855
  * Alarm-panel cap. Models HA `alarm_control_panel.*` on
7756
7856
  * `DeviceType.AlarmPanel`. State follows HA's canonical lifecycle
7757
7857
  * across disarmed / armed_(home|away|night|vacation|custom_bypass) /
@@ -9566,6 +9666,24 @@ var DetectorOutputSchema = object({
9566
9666
  inferenceMs: number(),
9567
9667
  modelId: string()
9568
9668
  });
9669
+ var EngineProvisioningSchema = object({
9670
+ runtimeId: _enum([
9671
+ "onnx",
9672
+ "openvino",
9673
+ "coreml"
9674
+ ]).nullable(),
9675
+ device: string().nullable(),
9676
+ state: _enum([
9677
+ "idle",
9678
+ "installing",
9679
+ "verifying",
9680
+ "ready",
9681
+ "failed"
9682
+ ]),
9683
+ progress: number().optional(),
9684
+ error: string().optional(),
9685
+ nextRetryAt: number().optional()
9686
+ });
9569
9687
  var PipelineStepInputSchema = lazy(() => object({
9570
9688
  addonId: string(),
9571
9689
  modelId: string(),
@@ -9665,6 +9783,15 @@ var pipelineExecutorCapability = {
9665
9783
  kind: "mutation",
9666
9784
  auth: "admin"
9667
9785
  }),
9786
+ /**
9787
+ * Per-node detection-engine provisioning snapshot. Returns the live
9788
+ * state of the lazy runtime-provisioning machine on `nodeId`
9789
+ * (idle / installing / verifying / ready / failed). The UI pairs this
9790
+ * one-shot query with the `pipeline.engine-provisioning` live event
9791
+ * (emitted on every transition) to drive a per-node "engine ready?"
9792
+ * indicator without polling. Phase 2.
9793
+ */
9794
+ getEngineProvisioning: method(object({ nodeId: string() }), EngineProvisioningSchema),
9668
9795
  getVideoPipelineSteps: method(_void(), record(string(), object({
9669
9796
  modelId: string(),
9670
9797
  settings: record(string(), unknown()).readonly()
@@ -12049,9 +12176,6 @@ method(LogEntrySchema, _void(), { kind: "mutation" }), method(object({
12049
12176
  limit: number().optional(),
12050
12177
  tags: record(string(), string()).optional()
12051
12178
  }), array(LogEntrySchema).readonly());
12052
- var StaticDirOutputSchema = object({ staticDir: string() });
12053
- var VersionOutputSchema = object({ version: string() });
12054
- method(_void(), StaticDirOutputSchema), method(_void(), VersionOutputSchema);
12055
12179
  /**
12056
12180
  * Zod schemas for persisted record types.
12057
12181
  *
@@ -13541,7 +13665,10 @@ var AgentAddonConfigSchema = object({
13541
13665
  modelId: string(),
13542
13666
  settings: record(string(), unknown()).readonly()
13543
13667
  });
13544
- var AgentPipelineSettingsSchema = object({ addonDefaults: record(string(), AgentAddonConfigSchema).readonly() });
13668
+ var AgentPipelineSettingsSchema = object({
13669
+ addonDefaults: record(string(), AgentAddonConfigSchema).readonly(),
13670
+ maxCameras: number().int().nonnegative().nullable().default(null)
13671
+ });
13545
13672
  var CameraPipelineForAgentSchema = object({
13546
13673
  steps: array(PipelineStepInputSchema).readonly(),
13547
13674
  audio: object({
@@ -13643,6 +13770,133 @@ var GlobalMetricsSchema = object({
13643
13770
  * capability providers.
13644
13771
  */
13645
13772
  var CapabilityBindingsSchema = record(string(), string());
13773
+ /** Source block — always present; derives from the stream catalog. */
13774
+ var CameraSourceStatusSchema = object({ streams: array(object({
13775
+ camStreamId: string(),
13776
+ codec: string(),
13777
+ width: number(),
13778
+ height: number(),
13779
+ fps: number(),
13780
+ kind: string()
13781
+ })).readonly() });
13782
+ /** Assignment block — always present (orchestrator-local, no remote call). */
13783
+ var CameraAssignmentStatusSchema = object({
13784
+ detectionNodeId: string().nullable(),
13785
+ decoderNodeId: string().nullable(),
13786
+ audioNodeId: string().nullable(),
13787
+ pinned: object({
13788
+ detection: boolean(),
13789
+ decoder: boolean(),
13790
+ audio: boolean()
13791
+ }),
13792
+ reasons: object({
13793
+ detection: string().optional(),
13794
+ decoder: string().optional(),
13795
+ audio: string().optional()
13796
+ })
13797
+ });
13798
+ /** Broker block — null when the broker stage is unreachable or inactive. */
13799
+ var CameraBrokerStatusSchema = object({
13800
+ profiles: array(object({
13801
+ profile: string(),
13802
+ status: string(),
13803
+ codec: string(),
13804
+ width: number(),
13805
+ height: number(),
13806
+ subscribers: number(),
13807
+ inFps: number(),
13808
+ outFps: number()
13809
+ })).readonly(),
13810
+ webrtcSessions: number(),
13811
+ rtspRestream: boolean()
13812
+ });
13813
+ /** Shared-memory ring statistics within the decoder block. */
13814
+ var CameraDecoderShmSchema = object({
13815
+ framesWritten: number(),
13816
+ getFrameHits: number(),
13817
+ getFrameMisses: number(),
13818
+ budgetMb: number()
13819
+ });
13820
+ /** Decoder block — null when the decoder stage is unreachable or inactive. */
13821
+ var CameraDecoderStatusSchema = object({
13822
+ nodeId: string(),
13823
+ formats: array(string()).readonly(),
13824
+ sessionCount: number(),
13825
+ shm: CameraDecoderShmSchema
13826
+ });
13827
+ /** Motion block — null when motion detection is not active for this device. */
13828
+ var CameraMotionStatusSchema = object({
13829
+ enabled: boolean(),
13830
+ fps: number()
13831
+ });
13832
+ /** Detection provisioning sub-block. */
13833
+ var CameraDetectionProvisioningSchema = object({
13834
+ state: _enum([
13835
+ "idle",
13836
+ "installing",
13837
+ "verifying",
13838
+ "ready",
13839
+ "failed"
13840
+ ]),
13841
+ error: string().optional()
13842
+ });
13843
+ /** Detection phase — derived from the runner's engine phase. */
13844
+ var CameraDetectionPhaseSchema = _enum([
13845
+ "idle",
13846
+ "watching",
13847
+ "active"
13848
+ ]);
13849
+ /** Detection block — null when no detection node is assigned or reachable. */
13850
+ var CameraDetectionStatusSchema = object({
13851
+ nodeId: string(),
13852
+ engine: object({
13853
+ backend: string(),
13854
+ device: string()
13855
+ }),
13856
+ phase: CameraDetectionPhaseSchema,
13857
+ configuredFps: number(),
13858
+ actualFps: number(),
13859
+ queueDepth: number(),
13860
+ avgInferenceMs: number(),
13861
+ provisioning: CameraDetectionProvisioningSchema
13862
+ });
13863
+ /** Audio block — null when no audio node is assigned or reachable. */
13864
+ var CameraAudioStatusSchema = object({
13865
+ nodeId: string(),
13866
+ enabled: boolean()
13867
+ });
13868
+ /** Recording block — null when no recording cap is active for this device. */
13869
+ var CameraRecordingStatusSchema = object({
13870
+ mode: _enum([
13871
+ "off",
13872
+ "continuous",
13873
+ "events"
13874
+ ]),
13875
+ active: boolean(),
13876
+ storageBytes: number()
13877
+ });
13878
+ /**
13879
+ * Aggregated per-camera pipeline status — server-composed, single call.
13880
+ *
13881
+ * The `assignment` and `source` blocks are always present.
13882
+ * Every other block is `null` when the stage is inactive or unreachable
13883
+ * during the bounded parallel fan-out in the orchestrator implementation.
13884
+ *
13885
+ * See spec: `docs/superpowers/specs/2026-06-24-camera-status-aggregator-cap.md`
13886
+ */
13887
+ var CameraStatusSchema = object({
13888
+ deviceId: number(),
13889
+ assignment: CameraAssignmentStatusSchema,
13890
+ source: CameraSourceStatusSchema,
13891
+ broker: CameraBrokerStatusSchema.nullable(),
13892
+ decoder: CameraDecoderStatusSchema.nullable(),
13893
+ motion: CameraMotionStatusSchema.nullable(),
13894
+ detection: CameraDetectionStatusSchema.nullable(),
13895
+ audio: CameraAudioStatusSchema.nullable(),
13896
+ recording: CameraRecordingStatusSchema.nullable(),
13897
+ /** Unix timestamp (ms) when this snapshot was composed server-side. */
13898
+ fetchedAt: number()
13899
+ });
13646
13900
  /**
13647
13901
  * Pipeline Orchestrator capability — global load balancer + camera dispatcher.
13648
13902
  *
@@ -13812,10 +14066,29 @@ var pipelineOrchestratorCapability = {
13812
14066
  * `success: false` indicates the nodeId wasn't in the store (no-op).
13813
14067
  * Refuses to remove `hub` (the orchestrator always co-resides with it).
13814
14068
  */
13815
- removeAgentSettings: method(object({ agentNodeId: string() }), object({
13816
- success: boolean(),
13817
- removed: boolean()
13818
- }), {
14069
+ removeAgentSettings: method(object({ agentNodeId: string() }), object({
14070
+ success: boolean(),
14071
+ removed: boolean()
14072
+ }), {
14073
+ kind: "mutation",
14074
+ auth: "admin"
14075
+ }),
14076
+ /**
14077
+ * Set the per-node camera cap for one agent.
14078
+ *
14079
+ * `maxCameras: 0` and `maxCameras: null` are both treated as unlimited
14080
+ * by the load balancer (0 is stored as-is; the balancer treats ≤0 as
14081
+ * unlimited alongside null). Pass `null` to clear an existing cap.
14082
+ * Note: the admin UI normalises 0→null before calling this method, so
14083
+ * `maxCameras: 0` only reaches the store via direct SDK or CLI calls.
14084
+ * Changes take effect immediately on the next dispatch cycle — cameras
14085
+ * currently assigned over-cap are left in place (no forced eviction),
14086
+ * but new assignments obey the updated cap.
14087
+ */
14088
+ setAgentMaxCameras: method(object({
14089
+ agentNodeId: string(),
14090
+ maxCameras: number().int().nonnegative().nullable()
14091
+ }), object({ success: literal(true) }), {
13819
14092
  kind: "mutation",
13820
14093
  auth: "admin"
13821
14094
  }),
@@ -13859,6 +14132,29 @@ var pipelineOrchestratorCapability = {
13859
14132
  deviceId: number(),
13860
14133
  agentNodeId: string().optional()
13861
14134
  }), CameraPipelineConfigSchema),
14135
+ /**
14136
+ * Server-composed aggregated status for a single camera.
14137
+ *
14138
+ * Fans out in parallel (bounded, per-stage graceful degradation) to
14139
+ * broker / decoder / motion / detection / audio / recording source caps
14140
+ * via `ctx.api`. A stage whose source errors or times out becomes `null`
14141
+ * in the returned payload — one slow agent never breaks the whole call.
14142
+ *
14143
+ * Intended for "on open / on camera select" snapshots. Live deltas
14144
+ * keep arriving from the existing ~1Hz events the UI already subscribes to.
14145
+ */
14146
+ getCameraStatus: method(object({ deviceId: number() }), CameraStatusSchema),
14147
+ /**
14148
+ * Server-composed aggregated status for multiple cameras in one call.
14149
+ *
14150
+ * `deviceIds` defaults to all cameras currently tracked by the
14151
+ * orchestrator's assignment map when omitted.
14152
+ *
14153
+ * Runs per-device composition in parallel (bounded). Use this to
14154
+ * populate the cluster assignments table and the pipeline flow overview
14155
+ * rail without issuing N parallel browser round-trips.
14156
+ */
14157
+ getCameraStatuses: method(object({ deviceIds: array(number()).optional() }), array(CameraStatusSchema).readonly()),
13862
14158
  /** List every template the operator has saved. */
13863
14159
  listTemplates: method(_void(), array(PipelineTemplateSchema).readonly()),
13864
14160
  /** Create a new named preset from a given CameraPipelineConfig. */
@@ -14355,7 +14651,7 @@ method(object({
14355
14651
  }), _void(), {
14356
14652
  kind: "mutation",
14357
14653
  auth: "admin"
14358
- }), method(object({ addonId: string() }), array(SavedDeviceRowSchema)), method(object({ addonId: string().optional() }), array(DeviceInfoSchema)), method(object({ deviceId: number() }), DeviceInfoSchema.nullable()), method(object({ parentDeviceId: number() }), array(DeviceInfoSchema)), method(object({ deviceId: number() }), array(StreamSourceEntrySchema)), method(object({ deviceId: number() }), array(ConfigEntrySchema)), method(object({ deviceId: number() }), ConfigUISchemaOutput), method(object({
14654
+ }), method(object({ addonId: string() }), array(SavedDeviceRowSchema)), method(object({ addonId: string().optional() }), array(DeviceInfoSchema)), method(object({ deviceId: number() }), DeviceInfoSchema.nullable()), method(object({ parentDeviceId: number() }), array(DeviceInfoSchema)), method(object({ deviceId: number() }), array(StreamSourceEntrySchema$1)), method(object({ deviceId: number() }), array(ConfigEntrySchema)), method(object({ deviceId: number() }), ConfigUISchemaOutput), method(object({
14359
14655
  deviceId: number(),
14360
14656
  values: record(string(), unknown())
14361
14657
  }), object({ success: literal(true) }), {
@@ -15075,7 +15371,20 @@ var DiskSpaceInfoSchema = object({
15075
15371
  var PidResourceStatsSchema = object({
15076
15372
  pid: number(),
15077
15373
  cpu: number(),
15078
- memory: number()
15374
+ memory: number(),
15375
+ /**
15376
+ * Private (anonymous) resident bytes — the per-process V8 heap + native
15377
+ * allocations NOT shared with other processes (Linux RssAnon). This is the
15378
+ * "real" per-runner cost; summing it across runners is meaningful, unlike
15379
+ * `memory` (RSS), which double-counts the shared mmap'd framework code.
15380
+ * Undefined where /proc is unavailable (e.g. macOS).
15381
+ */
15382
+ privateBytes: number().optional(),
15383
+ /**
15384
+ * Shared file-backed resident bytes (Linux RssFile) — mmap'd framework/lib
15385
+ * code shared copy-on-write across runners. Undefined on macOS.
15386
+ */
15387
+ sharedBytes: number().optional()
15079
15388
  });
15080
15389
  var AddonInstanceSchema = object({
15081
15390
  addonId: string(),
@@ -15124,6 +15433,17 @@ var KillProcessResultSchema = object({
15124
15433
  reason: string().optional(),
15125
15434
  signal: _enum(["SIGTERM", "SIGKILL"]).optional()
15126
15435
  });
15436
+ var DumpHeapSnapshotInputSchema = object({
15437
+ /** The addon whose runner should dump a heap snapshot. */
15438
+ addonId: string() });
15439
+ var DumpHeapSnapshotResultSchema = object({
15440
+ success: boolean(),
15441
+ /** Path of the written .heapsnapshot inside the runner's container/host. */
15442
+ path: string().optional(),
15443
+ /** Process pid that was signalled. */
15444
+ pid: number().optional(),
15445
+ reason: string().optional()
15446
+ });
15127
15447
  var SystemMetricsSchema = object({
15128
15448
  cpuPercent: number(),
15129
15449
  memoryPercent: number(),
@@ -15137,6 +15457,9 @@ var SystemMetricsSchema = object({
15137
15457
  method(_void(), SystemResourceSnapshotSchema), method(_void(), SystemResourceSnapshotSchema.nullable()), method(_void(), SystemMetricsSchema), method(object({ dirPath: string() }), DiskSpaceInfoSchema), method(_void(), MetricsGpuInfoSchema.nullable()), method(_void(), number().nullable()), method(object({ pids: array(number()) }), array(PidResourceStatsSchema)), method(_void(), array(AddonInstanceSchema).readonly()), method(object({ addonId: string() }), PidResourceStatsSchema.nullable()), method(_void(), array(NodeProcessSchema).readonly()), method(KillProcessInputSchema, KillProcessResultSchema, {
15138
15458
  kind: "mutation",
15139
15459
  auth: "admin"
15460
+ }), method(DumpHeapSnapshotInputSchema, DumpHeapSnapshotResultSchema, {
15461
+ kind: "mutation",
15462
+ auth: "admin"
15140
15463
  });
15141
15464
  var PtzPresetSchema = object({
15142
15465
  id: string(),
@@ -15503,63 +15826,6 @@ method(object({
15503
15826
  auth: "admin"
15504
15827
  });
15505
15828
  /**
15506
- * device-ops — device-scoped cap that unifies the per-IDevice operations
15507
- * previously routed through the `.device-ops` Moleculer bridge service.
15508
- *
15509
- * Each worker that hosts live `IDevice` instances auto-registers a native
15510
- * provider for this cap (per device) backed by its local
15511
- * `DeviceRegistry`. Hub-side callers reach it transparently through
15512
- * `ctx.fetchDevice(id).deviceOps.*` — the DeviceProxy injects
15513
- * `deviceId` + `nodeId` and dispatches through the standard cap-router,
15514
- * so there's no parallel bridge path anymore.
15515
- *
15516
- * The surface is intentionally small — every method corresponds to a
15517
- * single action on the live `IDevice` (or `ICameraDevice` for
15518
- * `getStreamSources`). Richer orchestration (enable/disable with
15519
- * integration plumbing, bulk updates) stays in the `device-manager` cap;
15520
- * `device-ops` is the per-device primitive the device-manager routes to.
15521
- */
15522
- var StreamSourceEntrySchema$1 = object({
15523
- id: string(),
15524
- label: string(),
15525
- protocol: _enum([
15526
- "rtsp",
15527
- "rtmp",
15528
- "annexb",
15529
- "http-mjpeg",
15530
- "webrtc",
15531
- "custom"
15532
- ]),
15533
- url: string().optional(),
15534
- resolution: object({
15535
- width: number(),
15536
- height: number()
15537
- }).optional(),
15538
- fps: number().optional(),
15539
- bitrate: number().optional(),
15540
- codec: string().optional(),
15541
- profileHint: CamProfileSchema.optional(),
15542
- sdp: string().optional()
15543
- });
15544
- var ConfigEntrySchema$1 = object({
15545
- key: string(),
15546
- value: unknown()
15547
- });
15548
- var RawStateResultSchema = object({
15549
- /** Originating provider id, e.g. 'homeassistant' | 'reolink' | 'hikvision'. */
15550
- source: string(),
15551
- /** Opaque, DISPLAY-SAFE upstream blob (no secrets/PII). */
15552
- data: record(string(), unknown())
15553
- });
15554
- method(object({ deviceId: number() }), array(StreamSourceEntrySchema$1)), method(object({ deviceId: number() }), array(ConfigEntrySchema$1)), method(object({
15555
- deviceId: number(),
15556
- values: record(string(), unknown())
15557
- }), _void(), { kind: "mutation" }), method(object({
15558
- deviceId: number(),
15559
- action: string().min(1),
15560
- input: unknown()
15561
- }), unknown(), { kind: "mutation" }), method(object({ deviceId: number() }), _void(), { kind: "mutation" }), method(object({ deviceId: number() }), unknown().nullable()), method(object({ deviceId: number() }), RawStateResultSchema.nullable(), { auth: "protected" });
15562
- /**
15563
15829
  * camera-credentials — device-scoped cap exposing the camera's network
15564
15830
  * + auth surface in a vendor-neutral shape.
15565
15831
  *
@@ -19242,6 +19508,12 @@ Object.freeze({
19242
19508
  addonId: null,
19243
19509
  access: "view"
19244
19510
  },
19511
+ "metricsProvider.dumpHeapSnapshot": {
19512
+ capName: "metrics-provider",
19513
+ capScope: "system",
19514
+ addonId: null,
19515
+ access: "create"
19516
+ },
19245
19517
  "metricsProvider.getAddonStats": {
19246
19518
  capName: "metrics-provider",
19247
19519
  capScope: "system",
@@ -19698,6 +19970,12 @@ Object.freeze({
19698
19970
  addonId: null,
19699
19971
  access: "view"
19700
19972
  },
19973
+ "pipelineExecutor.getEngineProvisioning": {
19974
+ capName: "pipeline-executor",
19975
+ capScope: "system",
19976
+ addonId: null,
19977
+ access: "view"
19978
+ },
19701
19979
  "pipelineExecutor.getGlobalPipelineConfig": {
19702
19980
  capName: "pipeline-executor",
19703
19981
  capScope: "system",
@@ -19902,6 +20180,18 @@ Object.freeze({
19902
20180
  addonId: null,
19903
20181
  access: "view"
19904
20182
  },
20183
+ "pipelineOrchestrator.getCameraStatus": {
20184
+ capName: "pipeline-orchestrator",
20185
+ capScope: "system",
20186
+ addonId: null,
20187
+ access: "view"
20188
+ },
20189
+ "pipelineOrchestrator.getCameraStatuses": {
20190
+ capName: "pipeline-orchestrator",
20191
+ capScope: "system",
20192
+ addonId: null,
20193
+ access: "view"
20194
+ },
19905
20195
  "pipelineOrchestrator.getCameraStepOverrides": {
19906
20196
  capName: "pipeline-orchestrator",
19907
20197
  capScope: "system",
@@ -19986,6 +20276,12 @@ Object.freeze({
19986
20276
  addonId: null,
19987
20277
  access: "create"
19988
20278
  },
20279
+ "pipelineOrchestrator.setAgentMaxCameras": {
20280
+ capName: "pipeline-orchestrator",
20281
+ capScope: "system",
20282
+ addonId: null,
20283
+ access: "create"
20284
+ },
19989
20285
  "pipelineOrchestrator.setCameraPipelineForAgent": {
19990
20286
  capName: "pipeline-orchestrator",
19991
20287
  capScope: "system",
@@ -21485,30 +21781,6 @@ object({
21485
21781
  bootAttempts: number(),
21486
21782
  schemaVersion: literal(1)
21487
21783
  });
21488
- /**
21489
- * Promise-based timer helpers — used everywhere the codebase needs to
21490
- * wait, back off, or schedule a retry. Before these helpers landed, each
21491
- * call site re-implemented `new Promise(r => setTimeout(r, ms))` inline,
21492
- * with subtle variations (some swallowing cancellation, some not). Two
21493
- * shapes cover every observed use case:
21494
- *
21495
- * - {@link sleep} for a plain, uncancellable wait — the default choice.
21496
- * - {@link sleepCancellable} for a wait that wakes early when an
21497
- * abort signal trips, used by long-running pollers whose teardown
21498
- * must stop a pending backoff promptly.
21499
- */
21500
- /**
21501
- * Resolve after `ms` milliseconds. Never rejects, never cancels. The
21502
- * sleep cannot be interrupted; for a wakeable variant use
21503
- * {@link sleepCancellable}.
21504
- *
21505
- * `ms <= 0` resolves on the next microtask via `setTimeout(0)`, which
21506
- * still gives the event loop a chance to drain — useful for breaking
21507
- * up tight async loops without changing call-site semantics.
21508
- */
21509
- function sleep$1(ms) {
21510
- return new Promise((resolve) => setTimeout(resolve, Math.max(0, ms)));
21511
- }
21512
21784
  //#endregion
21513
21785
  //#region src/pipeline-resolver.ts
21514
21786
  function applyStepPatch(base, patch) {
@@ -22016,7 +22288,10 @@ var StoredAgentAddonConfigSchema = object({
22016
22288
  modelId: string(),
22017
22289
  settings: record(string(), unknown()).readonly()
22018
22290
  });
22019
- var StoredAgentPipelineSettingsSchema = object({ addonDefaults: record(string(), StoredAgentAddonConfigSchema).readonly() });
22291
+ var StoredAgentPipelineSettingsSchema = object({
22292
+ addonDefaults: record(string(), StoredAgentAddonConfigSchema).readonly(),
22293
+ maxCameras: number().int().nonnegative().nullable().default(null)
22294
+ });
22020
22295
  var AgentSettingsMapSchema = record(string(), StoredAgentPipelineSettingsSchema);
22021
22296
  var StoredCameraStepOverridePatchSchema = object({
22022
22297
  enabled: boolean().optional(),
@@ -22061,10 +22336,26 @@ function computeCapacityScore(load) {
22061
22336
  return load.attachedCameras * Math.max(load.avgInferenceFps, 0) + Math.max(load.queueDepthTotal, 0);
22062
22337
  }
22063
22338
  /**
22339
+ * Returns true when the node has remaining capacity.
22340
+ * A node is eligible iff `cap` is unlimited (null/absent/<=0) OR
22341
+ * its `attachedCameras` count is strictly less than the cap.
22342
+ * Pins count toward the cap via `attachedCameras`.
22343
+ */
22344
+ function isEligible(node, caps) {
22345
+ const cap = caps?.[node.nodeId];
22346
+ if (cap === null || cap === void 0 || cap <= 0) return true;
22347
+ return node.attachedCameras < cap;
22348
+ }
22349
+ /**
22064
22350
  * Run the two-level camera balancer.
22065
22351
  *
22066
- * L1 (manual affinity): if `preferredAgent` names an online node, return it.
22067
- * L2 (capacity): compute capacity scores and pick the lowest.
22352
+ * L1 (manual affinity): if `preferredAgent` names an online node AND that
22353
+ * node is under its `maxCameras` cap, return it. If the node is online but at
22354
+ * or over cap, return `{kind:'pending'}` — a pinned camera is never silently
22355
+ * over-assigned.
22356
+ *
22357
+ * L2 (capacity): filter to eligible nodes and pick the lowest capacity score.
22358
+ * If all nodes are at/over cap, return `{kind:'pending'}`.
22068
22359
  *
22069
22360
  * Returns `null` when no runners are online. The orchestrator decides how to
22070
22361
  * react — typically by logging and deferring the assignment until a runner
@@ -22073,19 +22364,32 @@ function computeCapacityScore(load) {
22073
22364
  function balance(input) {
22074
22365
  const online = input.nodes.filter((n) => n.nodeId.length > 0);
22075
22366
  if (online.length === 0) return null;
22367
+ const eligible = online.filter((n) => isEligible(n, input.nodeCaps));
22076
22368
  if (input.preferredAgent) {
22077
- const match = online.find((n) => n.nodeId === input.preferredAgent);
22078
- if (match) return {
22079
- agentNodeId: match.nodeId,
22080
- reason: "manual",
22081
- score: computeCapacityScore(match)
22082
- };
22369
+ const pinnedOnline = online.find((n) => n.nodeId === input.preferredAgent);
22370
+ if (pinnedOnline) {
22371
+ if (eligible.some((n) => n.nodeId === pinnedOnline.nodeId)) return {
22372
+ kind: "assigned",
22373
+ agentNodeId: pinnedOnline.nodeId,
22374
+ reason: "manual",
22375
+ score: computeCapacityScore(pinnedOnline)
22376
+ };
22377
+ return {
22378
+ kind: "pending",
22379
+ reason: "over-cap"
22380
+ };
22381
+ }
22083
22382
  }
22084
- const best = online.map((node) => ({
22383
+ if (eligible.length === 0) return {
22384
+ kind: "pending",
22385
+ reason: "over-cap"
22386
+ };
22387
+ const best = eligible.map((node) => ({
22085
22388
  node,
22086
22389
  score: computeCapacityScore(node)
22087
22390
  })).toSorted((a, b) => a.score - b.score)[0];
22088
22391
  return {
22392
+ kind: "assigned",
22089
22393
  agentNodeId: best.node.nodeId,
22090
22394
  reason: "capacity",
22091
22395
  score: best.score
@@ -22504,6 +22808,139 @@ var PipelineWatchdog = class {
22504
22808
  }
22505
22809
  };
22506
22810
  //#endregion
22811
+ //#region src/camera-status/compose-camera-status.ts
22812
+ function mapAssignment(input) {
22813
+ return {
22814
+ detectionNodeId: input.detectionNodeId,
22815
+ decoderNodeId: input.decoderNodeId,
22816
+ audioNodeId: input.audioNodeId,
22817
+ pinned: {
22818
+ detection: input.pinned.detection,
22819
+ decoder: input.pinned.decoder,
22820
+ audio: input.pinned.audio
22821
+ },
22822
+ reasons: {
22823
+ detection: input.reasons.detection,
22824
+ decoder: input.reasons.decoder,
22825
+ audio: input.reasons.audio
22826
+ }
22827
+ };
22828
+ }
22829
+ function mapSource(sourceResult) {
22830
+ if (sourceResult === null) return { streams: [] };
22831
+ return { streams: sourceResult.streams.map((s) => ({
22832
+ camStreamId: s.camStreamId,
22833
+ codec: s.codec,
22834
+ width: s.width,
22835
+ height: s.height,
22836
+ fps: s.fps,
22837
+ kind: s.kind
22838
+ })) };
22839
+ }
22840
+ function mapBroker(brokerResult) {
22841
+ if (brokerResult === null) return null;
22842
+ return {
22843
+ profiles: brokerResult.profiles.map((p) => ({
22844
+ profile: p.profile,
22845
+ status: p.status,
22846
+ codec: p.codec,
22847
+ width: p.width,
22848
+ height: p.height,
22849
+ subscribers: p.subscribers,
22850
+ inFps: p.inFps,
22851
+ outFps: p.outFps
22852
+ })),
22853
+ webrtcSessions: brokerResult.webrtcSessions,
22854
+ rtspRestream: brokerResult.rtspRestream
22855
+ };
22856
+ }
22857
+ function mapDecoderShm(shm) {
22858
+ return {
22859
+ framesWritten: shm.framesWritten,
22860
+ getFrameHits: shm.getFrameHits,
22861
+ getFrameMisses: shm.getFrameMisses,
22862
+ budgetMb: shm.budgetMb
22863
+ };
22864
+ }
22865
+ function mapDecoder(decoderResult) {
22866
+ if (decoderResult === null) return null;
22867
+ return {
22868
+ nodeId: decoderResult.nodeId,
22869
+ formats: [...decoderResult.formats],
22870
+ sessionCount: decoderResult.sessionCount,
22871
+ shm: mapDecoderShm(decoderResult.shm)
22872
+ };
22873
+ }
22874
+ function mapMotion(motionResult) {
22875
+ if (motionResult === null) return null;
22876
+ return {
22877
+ enabled: motionResult.enabled,
22878
+ fps: motionResult.fps
22879
+ };
22880
+ }
22881
+ function mapProvisioning(p) {
22882
+ if (p.error !== void 0) return {
22883
+ state: p.state,
22884
+ error: p.error
22885
+ };
22886
+ return { state: p.state };
22887
+ }
22888
+ function mapDetection(detectionResult) {
22889
+ if (detectionResult === null) return null;
22890
+ const phase = detectionResult.phase;
22891
+ return {
22892
+ nodeId: detectionResult.nodeId,
22893
+ engine: {
22894
+ backend: detectionResult.engine.backend,
22895
+ device: detectionResult.engine.device
22896
+ },
22897
+ phase,
22898
+ configuredFps: detectionResult.configuredFps,
22899
+ actualFps: detectionResult.actualFps,
22900
+ queueDepth: detectionResult.queueDepth,
22901
+ avgInferenceMs: detectionResult.avgInferenceMs,
22902
+ provisioning: mapProvisioning(detectionResult.provisioning)
22903
+ };
22904
+ }
22905
+ function mapAudio(audioResult) {
22906
+ if (audioResult === null) return null;
22907
+ return {
22908
+ nodeId: audioResult.nodeId,
22909
+ enabled: audioResult.enabled
22910
+ };
22911
+ }
22912
+ function mapRecording(recordingResult) {
22913
+ if (recordingResult === null) return null;
22914
+ return {
22915
+ mode: recordingResult.mode,
22916
+ active: recordingResult.active,
22917
+ storageBytes: recordingResult.storageBytes
22918
+ };
22919
+ }
22920
+ /**
22921
+ * Pure function that composes a `CameraStatus` from per-stage fetch results.
22922
+ *
22923
+ * - `assignment` is always built from orchestrator-local data (never null).
22924
+ * - `source` always present: defaults to `{ streams: [] }` when sourceResult is null.
22925
+ * - Every other block is null when its stage result is null (graceful degradation).
22926
+ * - `fetchedAt` is stamped exactly as provided — never calls `Date.now()`.
22927
+ * - No mutation of the input.
22928
+ */
22929
+ function composeCameraStatus(input) {
22930
+ return {
22931
+ deviceId: input.deviceId,
22932
+ assignment: mapAssignment(input),
22933
+ source: mapSource(input.sourceResult),
22934
+ broker: mapBroker(input.brokerResult),
22935
+ decoder: mapDecoder(input.decoderResult),
22936
+ motion: mapMotion(input.motionResult),
22937
+ detection: mapDetection(input.detectionResult),
22938
+ audio: mapAudio(input.audioResult),
22939
+ recording: mapRecording(input.recordingResult),
22940
+ fetchedAt: input.fetchedAt
22941
+ };
22942
+ }
22943
+ //#endregion
22507
22944
  //#region src/index.ts
22508
22945
  var PHASE_MODE_VALUES = new Set([
22509
22946
  "disabled",
@@ -23261,8 +23698,7 @@ var PipelineOrchestratorAddon = class PipelineOrchestratorAddon extends BaseAddo
23261
23698
  });
23262
23699
  return {
23263
23700
  success: true,
23264
- agentNodeId: "",
23265
- reason: "capacity"
23701
+ kind: "pending"
23266
23702
  };
23267
23703
  }
23268
23704
  }
@@ -23272,14 +23708,22 @@ var PipelineOrchestratorAddon = class PipelineOrchestratorAddon extends BaseAddo
23272
23708
  const preferredAgent = typeof pipelinePin === "string" && pipelinePin !== "auto" ? pipelinePin : legacyPreferred;
23273
23709
  const decision = balance({
23274
23710
  nodes: await this.collectAgentLoad({ onlyEnabled: true }),
23275
- preferredAgent
23711
+ preferredAgent,
23712
+ nodeCaps: this.buildNodeCaps()
23276
23713
  });
23277
- const targetNodeId = decision?.agentNodeId ?? await this.localRunnerNodeId();
23278
- if (!targetNodeId) throw new Error(`dispatchCamera: no runner available for ${runnerConfig.deviceId}`);
23714
+ if (!decision) throw new Error(`dispatchCamera: no runner available for ${runnerConfig.deviceId}`);
23715
+ if (decision.kind === "pending") {
23716
+ this.ctx.logger.warn("camera left pending — all nodes at maxCameras", { tags: { deviceId: runnerConfig.deviceId } });
23717
+ return {
23718
+ success: true,
23719
+ kind: "pending"
23720
+ };
23721
+ }
23722
+ const targetNodeId = decision.agentNodeId;
23279
23723
  await this.attachOn(targetNodeId, runnerConfig);
23280
23724
  if (targetNodeId === this.localNodeId) this.pipelineWatchdog?.register(this.buildWatchdogCamera(runnerConfig, String(runnerConfig.deviceId)));
23281
- const reason = decision?.reason ?? "capacity";
23282
- const pinned = decision?.reason === "manual";
23725
+ const reason = decision.reason;
23726
+ const pinned = decision.reason === "manual";
23283
23727
  this.recordAssignment(runnerConfig.deviceId, targetNodeId, reason, pinned);
23284
23728
  const decoderNodeId = await this.resolveDecoderNode(runnerConfig.deviceId, targetNodeId);
23285
23729
  this.ctx.logger.info("dispatchCamera", {
@@ -23289,12 +23733,13 @@ var PipelineOrchestratorAddon = class PipelineOrchestratorAddon extends BaseAddo
23289
23733
  },
23290
23734
  meta: {
23291
23735
  reason,
23292
- score: decision?.score ?? "n/a",
23736
+ score: decision.score,
23293
23737
  decoderNodeId
23294
23738
  }
23295
23739
  });
23296
23740
  return {
23297
23741
  success: true,
23742
+ kind: "assigned",
23298
23743
  agentNodeId: targetNodeId,
23299
23744
  reason
23300
23745
  };
@@ -23368,10 +23813,13 @@ var PipelineOrchestratorAddon = class PipelineOrchestratorAddon extends BaseAddo
23368
23813
  if (cached) {
23369
23814
  const decision = balance({
23370
23815
  nodes: await this.collectAgentLoad({ onlyEnabled: true }),
23371
- preferredAgent: null
23816
+ preferredAgent: null,
23817
+ nodeCaps: this.buildNodeCaps()
23372
23818
  });
23373
- const targetNodeId = decision?.agentNodeId ?? await this.localRunnerNodeId();
23374
- if (targetNodeId) {
23819
+ if (!decision) this.ctx.logger.warn("unassignPipeline: no runner available, leaving unassigned", { tags: { deviceId: input.deviceId } });
23820
+ else if (decision.kind === "pending") this.ctx.logger.warn("camera left pending — all nodes at maxCameras", { tags: { deviceId: input.deviceId } });
23821
+ else {
23822
+ const targetNodeId = decision.agentNodeId;
23375
23823
  if (current && current.agentNodeId !== targetNodeId) await this.detachOn(current.agentNodeId, input.deviceId).catch((err) => {
23376
23824
  const msg = errMsg(err);
23377
23825
  this.ctx.logger.debug("unassignPipeline detach-old failed", {
@@ -23380,7 +23828,7 @@ var PipelineOrchestratorAddon = class PipelineOrchestratorAddon extends BaseAddo
23380
23828
  });
23381
23829
  });
23382
23830
  if (!current || current.agentNodeId !== targetNodeId) await this.attachOn(targetNodeId, cached);
23383
- const reason = decision?.reason === "manual" ? "capacity" : decision?.reason ?? "capacity";
23831
+ const reason = decision.reason === "manual" ? "capacity" : decision.reason;
23384
23832
  this.recordAssignment(input.deviceId, targetNodeId, reason, false);
23385
23833
  this.ctx.logger.info("unassignPipeline: re-dispatched via auto", {
23386
23834
  tags: {
@@ -23391,7 +23839,6 @@ var PipelineOrchestratorAddon = class PipelineOrchestratorAddon extends BaseAddo
23391
23839
  });
23392
23840
  return { success: true };
23393
23841
  }
23394
- this.ctx.logger.warn("unassignPipeline: no runner available, leaving unassigned", { tags: { deviceId: input.deviceId } });
23395
23842
  }
23396
23843
  if (current) {
23397
23844
  await this.detachOn(current.agentNodeId, input.deviceId).catch((err) => {
@@ -23409,15 +23856,21 @@ var PipelineOrchestratorAddon = class PipelineOrchestratorAddon extends BaseAddo
23409
23856
  async rebalance() {
23410
23857
  if (!this.ctx) throw new Error("PipelineOrchestrator: rebalance called before initialize");
23411
23858
  const loads = await this.collectAgentLoad({ onlyEnabled: true });
23859
+ const nodeCaps = this.buildNodeCaps();
23412
23860
  let migrated = 0;
23413
23861
  for (const [deviceId, config] of this.cameraConfigs) {
23414
23862
  const current = this.assignments.get(deviceId);
23415
23863
  if (current?.pinned) continue;
23416
23864
  const decision = balance({
23417
23865
  nodes: loads,
23418
- preferredAgent: await this.readPreferredAgent(deviceId)
23866
+ preferredAgent: await this.readPreferredAgent(deviceId),
23867
+ nodeCaps
23419
23868
  });
23420
23869
  if (!decision) continue;
23870
+ if (decision.kind === "pending") {
23871
+ this.ctx.logger.warn("camera left pending — all nodes at maxCameras", { tags: { deviceId } });
23872
+ continue;
23873
+ }
23421
23874
  if (current && current.agentNodeId === decision.agentNodeId) continue;
23422
23875
  if (current) await this.detachOn(current.agentNodeId, deviceId).catch((err) => {
23423
23876
  const msg = errMsg(err);
@@ -23555,15 +24008,6 @@ var PipelineOrchestratorAddon = class PipelineOrchestratorAddon extends BaseAddo
23555
24008
  nodeId
23556
24009
  });
23557
24010
  }
23558
- async localRunnerNodeId() {
23559
- const api = this.ctx.api;
23560
- if (!api) return null;
23561
- try {
23562
- return (await api.pipelineRunner.getLocalLoad.query({ nodeId: this.localNodeId }))?.nodeId ?? this.localNodeId;
23563
- } catch {
23564
- return this.localNodeId;
23565
- }
23566
- }
23567
24011
  /**
23568
24012
  * Enumerate every runner-capable node currently known (populated via
23569
24013
  * AgentOnline/AgentOffline events). Used to populate the `enabledNodes`
@@ -23718,6 +24162,18 @@ var PipelineOrchestratorAddon = class PipelineOrchestratorAddon extends BaseAddo
23718
24162
  return null;
23719
24163
  }
23720
24164
  }
24165
+ /**
24166
+ * Build a per-node camera cap map from the persisted agent settings.
24167
+ * Returns `null` for nodes where `maxCameras` is null (unlimited).
24168
+ * Used by every `balance()` call so the balancer can honour operator-set
24169
+ * per-node maximums without polling the store on each decision.
24170
+ */
24171
+ buildNodeCaps() {
24172
+ const blob = this.agentSettingsState.get();
24173
+ const caps = {};
24174
+ for (const [nodeId, settings] of Object.entries(blob)) caps[nodeId] = settings.maxCameras ?? null;
24175
+ return caps;
24176
+ }
23721
24177
  async readAudioNodePin(deviceId) {
23722
24178
  if (!this.ctx?.settings) return null;
23723
24179
  try {
@@ -23860,13 +24316,19 @@ var PipelineOrchestratorAddon = class PipelineOrchestratorAddon extends BaseAddo
23860
24316
  for (const { deviceId, config } of affected) {
23861
24317
  const decision = balance({
23862
24318
  nodes: loads,
23863
- preferredAgent: null
24319
+ preferredAgent: null,
24320
+ nodeCaps: this.buildNodeCaps()
23864
24321
  });
23865
24322
  if (!decision) {
23866
24323
  this.ctx.logger.error("Failover: no online runner", { tags: { deviceId } });
23867
24324
  this.assignments.delete(deviceId);
23868
24325
  continue;
23869
24326
  }
24327
+ if (decision.kind === "pending") {
24328
+ this.ctx.logger.warn("camera left pending — all nodes at maxCameras", { tags: { deviceId } });
24329
+ this.assignments.delete(deviceId);
24330
+ continue;
24331
+ }
23870
24332
  try {
23871
24333
  await this.attachOn(decision.agentNodeId, config);
23872
24334
  this.recordAssignment(deviceId, decision.agentNodeId, "failover", false);
@@ -24346,7 +24808,10 @@ var PipelineOrchestratorAddon = class PipelineOrchestratorAddon extends BaseAddo
24346
24808
  }
24347
24809
  async setAgentAddonDefaults(input) {
24348
24810
  let existing = (await this.readAgentSettingsMap())[input.agentNodeId];
24349
- if (!existing) existing = await this.seedAgentSettingsFromCatalog(input.agentNodeId) ?? void 0;
24811
+ if (!existing) {
24812
+ await this.seedAgentSettingsFromCatalog(input.agentNodeId);
24813
+ existing = (await this.readAgentSettingsMap())[input.agentNodeId];
24814
+ }
24350
24815
  if (!existing) await this.writeAgentSettings(input.agentNodeId, { addonDefaults: { ...input.defaults } });
24351
24816
  else await this.writeAgentSettings(input.agentNodeId, {
24352
24817
  ...existing,
@@ -24384,6 +24849,22 @@ var PipelineOrchestratorAddon = class PipelineOrchestratorAddon extends BaseAddo
24384
24849
  removed: true
24385
24850
  };
24386
24851
  }
24852
+ async setAgentMaxCameras(input) {
24853
+ const existing = (await this.readAgentSettingsMap())[input.agentNodeId];
24854
+ const next = existing ? {
24855
+ ...existing,
24856
+ maxCameras: input.maxCameras
24857
+ } : {
24858
+ addonDefaults: {},
24859
+ maxCameras: input.maxCameras
24860
+ };
24861
+ await this.writeAgentSettings(input.agentNodeId, next);
24862
+ this.ctx.logger.info("agentSettings.maxCameras updated", {
24863
+ tags: { nodeId: input.agentNodeId },
24864
+ meta: { maxCameras: input.maxCameras }
24865
+ });
24866
+ return { success: true };
24867
+ }
24387
24868
  async getCameraSettings(input) {
24388
24869
  return (await this.readCameraSettingsMap())[String(input.deviceId)] ?? null;
24389
24870
  }
@@ -24513,6 +24994,204 @@ var PipelineOrchestratorAddon = class PipelineOrchestratorAddon extends BaseAddo
24513
24994
  this.ctx.logger.info("template deleted", { meta: { templateId: input.id } });
24514
24995
  return { success: true };
24515
24996
  }
24997
+ /**
24998
+ * Races a promise against a timeout. Returns `null` on timeout OR rejection.
24999
+ * Never throws — individual stage failures become `null` in the aggregate.
25000
+ *
25001
+ * @param p The stage fetch promise.
25002
+ * @param ms Timeout in milliseconds.
25003
+ */
25004
+ boundedStage(p, ms) {
25005
+ let timer;
25006
+ const timeout = new Promise((resolve) => {
25007
+ timer = setTimeout(() => resolve(null), ms);
25008
+ });
25009
+ return Promise.race([p, timeout]).catch(() => null).finally(() => {
25010
+ if (timer !== void 0) clearTimeout(timer);
25011
+ });
25012
+ }
25013
+ /**
25014
+ * Server-composed aggregated status for a single camera.
25015
+ *
25016
+ * Fans out in parallel (bounded, per-stage graceful degradation) to
25017
+ * broker / decoder / motion / detection / audio / recording source caps
25018
+ * via `ctx.api`. A stage whose source errors or times out becomes `null`
25019
+ * in the returned payload — one slow agent never breaks the whole call.
25020
+ */
25021
+ async getCameraStatus(input) {
25022
+ const { deviceId } = input;
25023
+ const api = this.ctx.api;
25024
+ const STAGE_TIMEOUT_MS = 3e3;
25025
+ const pipelineAssignment = this.assignments.get(deviceId) ?? null;
25026
+ const detectionNodeId = pipelineAssignment?.agentNodeId ?? null;
25027
+ const decoderPinRaw = (api ? await this.ctx.settings?.readDeviceStore(deviceId).catch(() => ({})) ?? {} : {})["decoderNodeId"];
25028
+ const decoderPinned = typeof decoderPinRaw === "string" && decoderPinRaw !== "auto";
25029
+ const decoderNodeId = detectionNodeId ? await this.resolveDecoderNode(deviceId, detectionNodeId).catch(() => null) : null;
25030
+ const audioAssignment = this.audioAssignments.get(deviceId) ?? null;
25031
+ const audioNodeId = audioAssignment?.nodeId ?? null;
25032
+ const audioPinned = audioAssignment?.pinned ?? false;
25033
+ const pinned = {
25034
+ detection: pipelineAssignment?.pinned ?? false,
25035
+ decoder: decoderPinned,
25036
+ audio: audioPinned
25037
+ };
25038
+ const reasons = {
25039
+ detection: pipelineAssignment?.reason,
25040
+ decoder: decoderPinned ? "manual" : "co-located",
25041
+ audio: audioPinned ? "manual" : void 0
25042
+ };
25043
+ const allSlotsFetch = api ? api.streamBroker.listAllProfileSlots.query() : null;
25044
+ const sourceFetch = api && allSlotsFetch ? this.boundedStage(allSlotsFetch.then((slots) => {
25045
+ return { streams: slots.filter((s) => s.deviceId === deviceId).map((s) => ({
25046
+ camStreamId: s.sourceCamStreamId ?? s.brokerId,
25047
+ codec: s.codec ?? "",
25048
+ width: s.resolution?.width ?? 0,
25049
+ height: s.resolution?.height ?? 0,
25050
+ fps: 0,
25051
+ kind: s.profile
25052
+ })) };
25053
+ }), STAGE_TIMEOUT_MS) : Promise.resolve(null);
25054
+ const WEBRTC_KINDS = new Set([
25055
+ "webrtc-browser",
25056
+ "webrtc-mobile",
25057
+ "webrtc-whep"
25058
+ ]);
25059
+ const brokerFetch = api && allSlotsFetch ? this.boundedStage(allSlotsFetch.then(async (slots) => {
25060
+ const deviceSlots = slots.filter((s) => s.deviceId === deviceId);
25061
+ if (deviceSlots.length === 0) return {
25062
+ profiles: [],
25063
+ webrtcSessions: 0,
25064
+ rtspRestream: false
25065
+ };
25066
+ const [statsAndClients, rtspEntry] = await Promise.all([Promise.all(deviceSlots.map(async (slot) => {
25067
+ return {
25068
+ slot,
25069
+ stats: await api.streamBroker.getBrokerStats.query({ brokerId: slot.brokerId }).catch(() => null),
25070
+ clients: await api.streamBroker.listClients.query({ brokerId: slot.brokerId }).catch(() => null)
25071
+ };
25072
+ })), api.streamBroker.getAllRtspEntries.query({}).catch(() => null)]);
25073
+ return {
25074
+ profiles: statsAndClients.map(({ slot, stats, clients }) => ({
25075
+ profile: slot.profile,
25076
+ status: slot.status,
25077
+ codec: stats?.codec ?? slot.codec ?? "",
25078
+ width: slot.resolution?.width ?? 0,
25079
+ height: slot.resolution?.height ?? 0,
25080
+ subscribers: clients?.encodedSubscribers ?? 0,
25081
+ inFps: stats?.inputFps ?? 0,
25082
+ outFps: stats?.decodeFps ?? 0
25083
+ })),
25084
+ webrtcSessions: statsAndClients.reduce((total, { clients }) => {
25085
+ if (!clients) return total;
25086
+ return total + clients.encoded.filter((c) => WEBRTC_KINDS.has(c.attribution.kind)).length;
25087
+ }, 0),
25088
+ rtspRestream: rtspEntry?.some((e) => {
25089
+ return e.brokerId.split("/")[0] === String(deviceId) && e.enabled;
25090
+ }) ?? false
25091
+ };
25092
+ }), STAGE_TIMEOUT_MS) : Promise.resolve(null);
25093
+ const decoderFetch = decoderNodeId ? Promise.resolve({
25094
+ nodeId: decoderNodeId,
25095
+ formats: [],
25096
+ sessionCount: 0,
25097
+ shm: {
25098
+ framesWritten: 0,
25099
+ getFrameHits: 0,
25100
+ getFrameMisses: 0,
25101
+ budgetMb: 0
25102
+ }
25103
+ }) : Promise.resolve(null);
25104
+ const motionResult = (() => {
25105
+ const config = this.cameraConfigs.get(deviceId);
25106
+ if (!config) return null;
25107
+ return {
25108
+ enabled: config.motionSources.includes("analyzer") || config.motionSources.includes("onboard"),
25109
+ fps: config.motionFps
25110
+ };
25111
+ })();
25112
+ const detectionFetch = api && detectionNodeId ? this.boundedStage(Promise.all([api.pipelineExecutor.getEngineProvisioning.query({ nodeId: detectionNodeId }).catch(() => null), api.pipelineExecutor.getSelectedEngine.query({ nodeId: detectionNodeId }).catch(() => null)]).then(async ([provisioning, engine]) => {
25113
+ const metrics = await api.pipelineRunner.getCameraMetrics.query({
25114
+ deviceId,
25115
+ nodeId: detectionNodeId
25116
+ }).catch(() => null);
25117
+ const phase = (() => {
25118
+ const p = metrics?.phase;
25119
+ if (p === "active") return "active";
25120
+ if (p === "idle") return "idle";
25121
+ return "watching";
25122
+ })();
25123
+ return {
25124
+ nodeId: detectionNodeId,
25125
+ engine: {
25126
+ backend: engine?.backend ?? "",
25127
+ device: engine?.device ?? ""
25128
+ },
25129
+ phase,
25130
+ configuredFps: metrics?.configuredFps ?? 0,
25131
+ actualFps: metrics?.actualFps ?? 0,
25132
+ queueDepth: metrics?.queueDepth ?? 0,
25133
+ avgInferenceMs: metrics?.avgInferenceTimeMs ?? 0,
25134
+ provisioning: {
25135
+ state: provisioning?.state ?? "idle",
25136
+ ...provisioning?.error !== void 0 ? { error: provisioning.error } : {}
25137
+ }
25138
+ };
25139
+ }), STAGE_TIMEOUT_MS) : Promise.resolve(null);
25140
+ const audioResult = audioNodeId ? {
25141
+ nodeId: audioNodeId,
25142
+ enabled: true
25143
+ } : null;
25144
+ function isRecordingStatus(v) {
25145
+ return v !== null && typeof v === "object" && "activeMode" in v && (v.activeMode === "off" || v.activeMode === "continuous" || v.activeMode === "events") && "enabled" in v && typeof v.enabled === "boolean" && "storageBytes" in v && typeof v.storageBytes === "number";
25146
+ }
25147
+ const recordingFetch = api ? this.boundedStage(api.recording.getStatus.query({ deviceId }).then((rawStatus) => {
25148
+ if (!isRecordingStatus(rawStatus)) return null;
25149
+ return {
25150
+ mode: rawStatus.activeMode,
25151
+ active: rawStatus.enabled && rawStatus.activeMode !== "off",
25152
+ storageBytes: rawStatus.storageBytes
25153
+ };
25154
+ }).catch(() => null), STAGE_TIMEOUT_MS) : Promise.resolve(null);
25155
+ const [sourceResult, brokerResult, decoderResult, detectionResult, recordingResult] = await Promise.all([
25156
+ sourceFetch,
25157
+ brokerFetch,
25158
+ decoderFetch,
25159
+ detectionFetch,
25160
+ recordingFetch
25161
+ ]);
25162
+ return composeCameraStatus({
25163
+ deviceId,
25164
+ fetchedAt: Date.now(),
25165
+ detectionNodeId,
25166
+ decoderNodeId,
25167
+ audioNodeId,
25168
+ pinned,
25169
+ reasons,
25170
+ sourceResult,
25171
+ brokerResult,
25172
+ decoderResult,
25173
+ motionResult,
25174
+ detectionResult,
25175
+ audioResult,
25176
+ recordingResult
25177
+ });
25178
+ }
25179
+ /**
25180
+ * Server-composed aggregated status for multiple cameras in one call.
25181
+ *
25182
+ * `deviceIds` defaults to all cameras currently tracked by the
25183
+ * orchestrator's assignment map when omitted.
25184
+ *
25185
+ * v1: `Promise.all` over per-device composition (no concurrency cap).
25186
+ * Note: for large fleets (hundreds of cameras) this may fan out many
25187
+ * parallel calls. A concurrency limiter (p-limit / semaphore) should be
25188
+ * added if latency measurements show it's necessary — deliberately
25189
+ * deferred per the YAGNI constraint in the spec.
25190
+ */
25191
+ async getCameraStatuses(input) {
25192
+ const ids = input.deviceIds !== void 0 && input.deviceIds.length > 0 ? input.deviceIds : [...this.assignments.keys()];
25193
+ return Promise.all(ids.map((deviceId) => this.getCameraStatus({ deviceId })));
25194
+ }
24516
25195
  /** Read the templates map from the addon store via the durable handle. */
24517
25196
  async readTemplatesMap() {
24518
25197
  const raw = await this.templatesState.get();
@@ -24543,7 +25222,11 @@ var PipelineOrchestratorAddon = class PipelineOrchestratorAddon extends BaseAddo
24543
25222
  return;
24544
25223
  }
24545
25224
  const all = await this.readAgentSettingsMap();
24546
- all[nodeId] = settings;
25225
+ const existing = all[nodeId];
25226
+ all[nodeId] = {
25227
+ addonDefaults: settings.addonDefaults,
25228
+ maxCameras: settings.maxCameras !== void 0 ? settings.maxCameras ?? null : existing?.maxCameras ?? null
25229
+ };
24547
25230
  await this.agentSettingsState.set(all);
24548
25231
  }
24549
25232
  /** Read the `cameraSettings` map (keyed on `deviceId` as string) via the durable handle. */
@@ -24753,12 +25436,15 @@ var PipelineOrchestratorAddon = class PipelineOrchestratorAddon extends BaseAddo
24753
25436
  }
24754
25437
  let agent = (await this.readAgentSettingsMap())[nodeId];
24755
25438
  if (!agent || Object.keys(agent.addonDefaults ?? {}).length === 0) {
24756
- const seeded = await this.seedAgentSettingsFromCatalog(nodeId);
24757
- if (!seeded) {
25439
+ if (!await this.seedAgentSettingsFromCatalog(nodeId)) {
24758
25440
  await sleep$1(2e3);
24759
25441
  continue;
24760
25442
  }
24761
- agent = seeded;
25443
+ agent = (await this.readAgentSettingsMap())[nodeId];
25444
+ }
25445
+ if (!agent) {
25446
+ await sleep$1(2e3);
25447
+ continue;
24762
25448
  }
24763
25449
  const engine = await this.readDetectionPipelineEngine(nodeId) ?? catalog.selectedEngine;
24764
25450
  return {
@@ -25665,7 +26351,8 @@ var PipelineOrchestratorAddon = class PipelineOrchestratorAddon extends BaseAddo
25665
26351
  };
25666
26352
  let dispatchedNodeId = null;
25667
26353
  try {
25668
- dispatchedNodeId = (await this.dispatchCamera(runnerConfig)).agentNodeId;
26354
+ const result = await this.dispatchCamera(runnerConfig);
26355
+ if (result.kind === "assigned") dispatchedNodeId = result.agentNodeId;
25669
26356
  } catch (err) {
25670
26357
  const msg = errMsg(err);
25671
26358
  log.error("dispatchCamera failed", { meta: { error: msg } });