@camstack/types 0.1.40 → 0.1.41
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/addon/base-addon.d.ts +12 -0
- package/dist/addon/base-addon.d.ts.map +1 -1
- package/dist/addon/durable-state.d.ts +33 -0
- package/dist/addon/durable-state.d.ts.map +1 -0
- package/dist/capabilities/accessories.cap.d.ts +56 -8
- package/dist/capabilities/accessories.cap.d.ts.map +1 -1
- package/dist/capabilities/advanced-notifier.cap.d.ts +4 -0
- package/dist/capabilities/advanced-notifier.cap.d.ts.map +1 -1
- package/dist/capabilities/air-quality-sensor.cap.d.ts +56 -0
- package/dist/capabilities/air-quality-sensor.cap.d.ts.map +1 -0
- package/dist/capabilities/alarm-panel.cap.d.ts +154 -0
- package/dist/capabilities/alarm-panel.cap.d.ts.map +1 -0
- package/dist/capabilities/ambient-light-sensor.cap.d.ts +39 -0
- package/dist/capabilities/ambient-light-sensor.cap.d.ts.map +1 -0
- package/dist/capabilities/automation-control.cap.d.ts +65 -0
- package/dist/capabilities/automation-control.cap.d.ts.map +1 -0
- package/dist/capabilities/battery.cap.d.ts +30 -1
- package/dist/capabilities/battery.cap.d.ts.map +1 -1
- package/dist/capabilities/binary.cap.d.ts +40 -0
- package/dist/capabilities/binary.cap.d.ts.map +1 -0
- package/dist/capabilities/brightness.cap.d.ts +3 -2
- package/dist/capabilities/brightness.cap.d.ts.map +1 -1
- package/dist/capabilities/broker.cap.d.ts +291 -0
- package/dist/capabilities/broker.cap.d.ts.map +1 -0
- package/dist/capabilities/button.cap.d.ts +27 -0
- package/dist/capabilities/button.cap.d.ts.map +1 -0
- package/dist/capabilities/camera-credentials.cap.d.ts +1 -0
- package/dist/capabilities/camera-credentials.cap.d.ts.map +1 -1
- package/dist/capabilities/camera-streams.cap.d.ts +147 -10
- package/dist/capabilities/camera-streams.cap.d.ts.map +1 -1
- package/dist/capabilities/capability-definition.d.ts +15 -0
- package/dist/capabilities/capability-definition.d.ts.map +1 -1
- package/dist/capabilities/carbon-monoxide.cap.d.ts +33 -0
- package/dist/capabilities/carbon-monoxide.cap.d.ts.map +1 -0
- package/dist/capabilities/climate-control.cap.d.ts +183 -0
- package/dist/capabilities/climate-control.cap.d.ts.map +1 -0
- package/dist/capabilities/color.cap.d.ts +186 -0
- package/dist/capabilities/color.cap.d.ts.map +1 -0
- package/dist/capabilities/connectivity.cap.d.ts +37 -0
- package/dist/capabilities/connectivity.cap.d.ts.map +1 -0
- package/dist/capabilities/consumables.cap.d.ts +105 -0
- package/dist/capabilities/consumables.cap.d.ts.map +1 -0
- package/dist/capabilities/contact.cap.d.ts +41 -0
- package/dist/capabilities/contact.cap.d.ts.map +1 -0
- package/dist/capabilities/control.cap.d.ts +167 -0
- package/dist/capabilities/control.cap.d.ts.map +1 -0
- package/dist/capabilities/cover.cap.d.ts +104 -0
- package/dist/capabilities/cover.cap.d.ts.map +1 -0
- package/dist/capabilities/custom-actions.d.ts +6 -0
- package/dist/capabilities/custom-actions.d.ts.map +1 -1
- package/dist/capabilities/decoder.cap.d.ts +1 -1
- package/dist/capabilities/device-adoption.cap.d.ts +203 -0
- package/dist/capabilities/device-adoption.cap.d.ts.map +1 -0
- package/dist/capabilities/device-discovery.cap.d.ts +44 -143
- package/dist/capabilities/device-discovery.cap.d.ts.map +1 -1
- package/dist/capabilities/device-manager.cap.d.ts +469 -0
- package/dist/capabilities/device-manager.cap.d.ts.map +1 -1
- package/dist/capabilities/device-ops.cap.d.ts +30 -0
- package/dist/capabilities/device-ops.cap.d.ts.map +1 -1
- package/dist/capabilities/device-provider.cap.d.ts +36 -0
- package/dist/capabilities/device-provider.cap.d.ts.map +1 -1
- package/dist/capabilities/device-status.cap.d.ts +1 -0
- package/dist/capabilities/device-status.cap.d.ts.map +1 -1
- package/dist/capabilities/doorbell.cap.d.ts +1 -0
- package/dist/capabilities/doorbell.cap.d.ts.map +1 -1
- package/dist/capabilities/enum-sensor.cap.d.ts +60 -0
- package/dist/capabilities/enum-sensor.cap.d.ts.map +1 -0
- package/dist/capabilities/event-emitter.cap.d.ts +79 -0
- package/dist/capabilities/event-emitter.cap.d.ts.map +1 -0
- package/dist/capabilities/fan-control.cap.d.ts +100 -0
- package/dist/capabilities/fan-control.cap.d.ts.map +1 -0
- package/dist/capabilities/feature-probe.cap.d.ts +1 -0
- package/dist/capabilities/feature-probe.cap.d.ts.map +1 -1
- package/dist/capabilities/flood.cap.d.ts +37 -0
- package/dist/capabilities/flood.cap.d.ts.map +1 -0
- package/dist/capabilities/gas.cap.d.ts +34 -0
- package/dist/capabilities/gas.cap.d.ts.map +1 -0
- package/dist/capabilities/humidifier.cap.d.ts +82 -0
- package/dist/capabilities/humidifier.cap.d.ts.map +1 -0
- package/dist/capabilities/humidity-sensor.cap.d.ts +43 -0
- package/dist/capabilities/humidity-sensor.cap.d.ts.map +1 -0
- package/dist/capabilities/image.cap.d.ts +44 -0
- package/dist/capabilities/image.cap.d.ts.map +1 -0
- package/dist/capabilities/index.d.ts +93 -12
- package/dist/capabilities/index.d.ts.map +1 -1
- package/dist/capabilities/integrations.cap.d.ts +12 -0
- package/dist/capabilities/integrations.cap.d.ts.map +1 -1
- package/dist/capabilities/intercom.cap.d.ts +49 -9
- package/dist/capabilities/intercom.cap.d.ts.map +1 -1
- package/dist/capabilities/lawn-mower-control.cap.d.ts +83 -0
- package/dist/capabilities/lawn-mower-control.cap.d.ts.map +1 -0
- package/dist/capabilities/lock-control.cap.d.ts +92 -0
- package/dist/capabilities/lock-control.cap.d.ts.map +1 -0
- package/dist/capabilities/media-player.cap.d.ts +201 -0
- package/dist/capabilities/media-player.cap.d.ts.map +1 -0
- package/dist/capabilities/motion-trigger.cap.d.ts +1 -0
- package/dist/capabilities/motion-trigger.cap.d.ts.map +1 -1
- package/dist/capabilities/motion-zones.cap.d.ts +1 -0
- package/dist/capabilities/motion-zones.cap.d.ts.map +1 -1
- package/dist/capabilities/native-object-detection.cap.d.ts +1 -0
- package/dist/capabilities/native-object-detection.cap.d.ts.map +1 -1
- package/dist/capabilities/network-quality.cap.d.ts +5 -0
- package/dist/capabilities/network-quality.cap.d.ts.map +1 -1
- package/dist/capabilities/notifier.cap.d.ts +173 -0
- package/dist/capabilities/notifier.cap.d.ts.map +1 -0
- package/dist/capabilities/numeric-sensor.cap.d.ts +52 -0
- package/dist/capabilities/numeric-sensor.cap.d.ts.map +1 -0
- package/dist/capabilities/osd.cap.d.ts +1 -0
- package/dist/capabilities/osd.cap.d.ts.map +1 -1
- package/dist/capabilities/pipeline-analytics.cap.d.ts +69 -22
- package/dist/capabilities/pipeline-analytics.cap.d.ts.map +1 -1
- package/dist/capabilities/pipeline-executor.cap.d.ts +2 -2
- package/dist/capabilities/pipeline-orchestrator.cap.d.ts +1 -1
- package/dist/capabilities/pipeline-runner.cap.d.ts +2 -2
- package/dist/capabilities/platform-probe.cap.d.ts +25 -0
- package/dist/capabilities/platform-probe.cap.d.ts.map +1 -1
- package/dist/capabilities/power-meter.cap.d.ts +65 -0
- package/dist/capabilities/power-meter.cap.d.ts.map +1 -0
- package/dist/capabilities/presence.cap.d.ts +79 -0
- package/dist/capabilities/presence.cap.d.ts.map +1 -0
- package/dist/capabilities/pressure-sensor.cap.d.ts +43 -0
- package/dist/capabilities/pressure-sensor.cap.d.ts.map +1 -0
- package/dist/capabilities/privacy-mask.cap.d.ts +1 -0
- package/dist/capabilities/privacy-mask.cap.d.ts.map +1 -1
- package/dist/capabilities/ptz-autotrack.cap.d.ts +1 -0
- package/dist/capabilities/ptz-autotrack.cap.d.ts.map +1 -1
- package/dist/capabilities/ptz.cap.d.ts +1 -0
- package/dist/capabilities/ptz.cap.d.ts.map +1 -1
- package/dist/capabilities/reboot.cap.d.ts +1 -0
- package/dist/capabilities/reboot.cap.d.ts.map +1 -1
- package/dist/capabilities/recording.cap.d.ts +238 -32
- package/dist/capabilities/recording.cap.d.ts.map +1 -1
- package/dist/capabilities/restreamer.cap.d.ts +2 -2
- package/dist/capabilities/schemas/orchestrator-metrics.d.ts +2 -2
- package/dist/capabilities/schemas/streaming-shared.d.ts +64 -1
- package/dist/capabilities/schemas/streaming-shared.d.ts.map +1 -1
- package/dist/capabilities/script-runner.cap.d.ts +62 -0
- package/dist/capabilities/script-runner.cap.d.ts.map +1 -0
- package/dist/capabilities/settings-store.cap.d.ts +25 -0
- package/dist/capabilities/settings-store.cap.d.ts.map +1 -1
- package/dist/capabilities/smoke.cap.d.ts +38 -0
- package/dist/capabilities/smoke.cap.d.ts.map +1 -0
- package/dist/capabilities/snapshot-provider.cap.d.ts +1 -1
- package/dist/capabilities/snapshot.cap.d.ts +1 -0
- package/dist/capabilities/snapshot.cap.d.ts.map +1 -1
- package/dist/capabilities/storage-evictable.cap.d.ts +54 -0
- package/dist/capabilities/storage-evictable.cap.d.ts.map +1 -0
- package/dist/capabilities/storage-provider.cap.d.ts +31 -186
- package/dist/capabilities/storage-provider.cap.d.ts.map +1 -1
- package/dist/capabilities/storage.cap.d.ts +35 -226
- package/dist/capabilities/storage.cap.d.ts.map +1 -1
- package/dist/capabilities/stream-broker.cap.d.ts +309 -25
- package/dist/capabilities/stream-broker.cap.d.ts.map +1 -1
- package/dist/capabilities/stream-catalog.cap.d.ts +3 -0
- package/dist/capabilities/stream-catalog.cap.d.ts.map +1 -1
- package/dist/capabilities/stream-params.cap.d.ts +27 -26
- package/dist/capabilities/stream-params.cap.d.ts.map +1 -1
- package/dist/capabilities/switch.cap.d.ts +1 -0
- package/dist/capabilities/switch.cap.d.ts.map +1 -1
- package/dist/capabilities/tamper.cap.d.ts +33 -0
- package/dist/capabilities/tamper.cap.d.ts.map +1 -0
- package/dist/capabilities/temperature-sensor.cap.d.ts +51 -0
- package/dist/capabilities/temperature-sensor.cap.d.ts.map +1 -0
- package/dist/capabilities/update.cap.d.ts +49 -0
- package/dist/capabilities/update.cap.d.ts.map +1 -0
- package/dist/capabilities/vacuum-control.cap.d.ts +229 -0
- package/dist/capabilities/vacuum-control.cap.d.ts.map +1 -0
- package/dist/capabilities/valve.cap.d.ts +93 -0
- package/dist/capabilities/valve.cap.d.ts.map +1 -0
- package/dist/capabilities/vibration.cap.d.ts +33 -0
- package/dist/capabilities/vibration.cap.d.ts.map +1 -0
- package/dist/capabilities/water-heater.cap.d.ts +78 -0
- package/dist/capabilities/water-heater.cap.d.ts.map +1 -0
- package/dist/capabilities/weather.cap.d.ts +76 -0
- package/dist/capabilities/weather.cap.d.ts.map +1 -0
- package/dist/capabilities/webrtc-session.cap.d.ts +95 -1
- package/dist/capabilities/webrtc-session.cap.d.ts.map +1 -1
- package/dist/constants.d.ts +0 -2
- package/dist/constants.d.ts.map +1 -1
- package/dist/device/base-device-provider.d.ts +11 -0
- package/dist/device/base-device-provider.d.ts.map +1 -1
- package/dist/device/base-device.d.ts +52 -0
- package/dist/device/base-device.d.ts.map +1 -1
- package/dist/device/device-context.d.ts +29 -0
- package/dist/device/device-context.d.ts.map +1 -1
- package/dist/device/device-link-transform.d.ts +6 -0
- package/dist/device/device-link-transform.d.ts.map +1 -0
- package/dist/device/device-management.d.ts +116 -4
- package/dist/device/device-management.d.ts.map +1 -1
- package/dist/device/device-type.d.ts +214 -3
- package/dist/device/device-type.d.ts.map +1 -1
- package/dist/device/device.d.ts +25 -0
- package/dist/device/device.d.ts.map +1 -1
- package/dist/device/index.d.ts +5 -1
- package/dist/device/index.d.ts.map +1 -1
- package/dist/device/path-util.d.ts +13 -0
- package/dist/device/path-util.d.ts.map +1 -0
- package/dist/device/schema-fields.d.ts +12 -0
- package/dist/device/schema-fields.d.ts.map +1 -0
- package/dist/device/source-info.d.ts +87 -0
- package/dist/device/source-info.d.ts.map +1 -0
- package/dist/device/system-mirror.d.ts +6 -2
- package/dist/device/system-mirror.d.ts.map +1 -1
- package/dist/encode-profile.d.ts +126 -0
- package/dist/encode-profile.d.ts.map +1 -0
- package/dist/enums/event-category.d.ts +64 -6
- package/dist/enums/event-category.d.ts.map +1 -1
- package/dist/generated/addon-api.d.ts +12345 -8129
- package/dist/generated/addon-api.d.ts.map +1 -1
- package/dist/generated/cap-status-types.d.ts +85 -1
- package/dist/generated/cap-status-types.d.ts.map +1 -1
- package/dist/generated/capability-router-map.d.ts +133 -7
- package/dist/generated/capability-router-map.d.ts.map +1 -1
- package/dist/generated/device-local-state.d.ts +117 -0
- package/dist/generated/device-local-state.d.ts.map +1 -1
- package/dist/generated/device-proxy.d.ts +124 -5
- package/dist/generated/device-proxy.d.ts.map +1 -1
- package/dist/generated/method-access-map.d.ts +1 -1
- package/dist/generated/method-access-map.d.ts.map +1 -1
- package/dist/generated/provider-kind-map.d.ts +1 -1
- package/dist/generated/provider-kind-map.d.ts.map +1 -1
- package/dist/generated/system-proxy.d.ts +9 -7
- package/dist/generated/system-proxy.d.ts.map +1 -1
- package/dist/{index-DnpdVFKv.js → index-BSA_TBea.js} +4170 -728
- package/dist/index-BSA_TBea.js.map +1 -0
- package/dist/{index-C2zzIDdX.mjs → index-Bpj3ScIH.mjs} +4563 -1121
- package/dist/index-Bpj3ScIH.mjs.map +1 -0
- package/dist/index.d.ts +21 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1323 -116
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1637 -430
- package/dist/index.mjs.map +1 -1
- package/dist/interfaces/addon-data-plane.d.ts +76 -0
- package/dist/interfaces/addon-data-plane.d.ts.map +1 -0
- package/dist/interfaces/addon.d.ts +60 -0
- package/dist/interfaces/addon.d.ts.map +1 -1
- package/dist/interfaces/advanced-notifier.d.ts +4 -0
- package/dist/interfaces/advanced-notifier.d.ts.map +1 -1
- package/dist/interfaces/capability.d.ts +42 -1
- package/dist/interfaces/capability.d.ts.map +1 -1
- package/dist/interfaces/config-ui.d.ts +70 -6
- package/dist/interfaces/config-ui.d.ts.map +1 -1
- package/dist/interfaces/device-capabilities/camera.d.ts +2 -1
- package/dist/interfaces/device-capabilities/camera.d.ts.map +1 -1
- package/dist/interfaces/event-bus.d.ts +49 -3
- package/dist/interfaces/event-bus.d.ts.map +1 -1
- package/dist/interfaces/kernel-abstractions.d.ts +10 -1
- package/dist/interfaces/kernel-abstractions.d.ts.map +1 -1
- package/dist/interfaces/network-quality.d.ts +8 -0
- package/dist/interfaces/network-quality.d.ts.map +1 -1
- package/dist/interfaces/pipeline-executor-capability.d.ts +2 -2
- package/dist/interfaces/pipeline-orchestrator-capability.d.ts +2 -1
- package/dist/interfaces/pipeline-orchestrator-capability.d.ts.map +1 -1
- package/dist/interfaces/pipeline-runner-capability.d.ts +7 -0
- package/dist/interfaces/pipeline-runner-capability.d.ts.map +1 -1
- package/dist/interfaces/recording-config.d.ts +91 -0
- package/dist/interfaces/recording-config.d.ts.map +1 -0
- package/dist/interfaces/rtp-egress.d.ts +2 -3
- package/dist/interfaces/rtp-egress.d.ts.map +1 -1
- package/dist/interfaces/storage-location-declaration.d.ts +34 -0
- package/dist/interfaces/storage-location-declaration.d.ts.map +1 -0
- package/dist/interfaces/storage-location.d.ts +18 -74
- package/dist/interfaces/storage-location.d.ts.map +1 -1
- package/dist/interfaces/storage.d.ts +15 -4
- package/dist/interfaces/storage.d.ts.map +1 -1
- package/dist/interfaces/stream-broker.d.ts +18 -3
- package/dist/interfaces/stream-broker.d.ts.map +1 -1
- package/dist/interfaces/timezones.d.ts +59 -0
- package/dist/interfaces/timezones.d.ts.map +1 -0
- package/dist/node.d.ts +3 -0
- package/dist/node.d.ts.map +1 -1
- package/dist/node.js +50 -8
- package/dist/node.js.map +1 -1
- package/dist/node.mjs +51 -9
- package/dist/node.mjs.map +1 -1
- package/dist/storage/filesystem-storage-provider.d.ts +2 -1
- package/dist/storage/filesystem-storage-provider.d.ts.map +1 -1
- package/dist/stream-selection.d.ts +85 -0
- package/dist/stream-selection.d.ts.map +1 -0
- package/dist/types/detection.d.ts +3 -3
- package/dist/types/io.d.ts +1 -1
- package/dist/types/io.d.ts.map +1 -1
- package/dist/util/location-match.d.ts +15 -0
- package/dist/util/location-match.d.ts.map +1 -0
- package/dist/utils/canonical-hash.d.ts +20 -0
- package/dist/utils/canonical-hash.d.ts.map +1 -0
- package/dist/utils/export-reconciler.d.ts +101 -0
- package/dist/utils/export-reconciler.d.ts.map +1 -0
- package/dist/utils/sleep.d.ts +36 -0
- package/dist/utils/sleep.d.ts.map +1 -0
- package/package.json +1 -1
- package/dist/capabilities/recording-engine.cap.d.ts +0 -477
- package/dist/capabilities/recording-engine.cap.d.ts.map +0 -1
- package/dist/index-C2zzIDdX.mjs.map +0 -1
- package/dist/index-DnpdVFKv.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index-BSA_TBea.js","sources":["../src/health/wiring-health.ts","../src/types/models.ts","../src/interfaces/config-ui.ts","../src/capabilities/schemas/streaming-shared.ts","../src/interfaces/recording-config.ts","../src/interfaces/storage-location.ts","../src/interfaces/storage-location-declaration.ts","../src/interfaces/stream-broker.ts","../src/encode-profile.ts","../src/utils/err-msg.ts","../src/catalogs/audio-classmap.ts","../src/device/device-type.ts","../src/device/accessory.ts","../src/device/device-profile.ts","../src/capabilities/device-status.cap.ts","../src/capabilities/feature-probe.cap.ts","../src/capabilities/air-quality-sensor.cap.ts","../src/capabilities/capability-definition.ts","../src/capabilities/alarm-panel.cap.ts","../src/capabilities/ambient-light-sensor.cap.ts","../src/capabilities/audio-metrics.cap.ts","../src/capabilities/automation-control.cap.ts","../src/capabilities/battery.cap.ts","../src/capabilities/binary.cap.ts","../src/capabilities/brightness.cap.ts","../src/capabilities/streaming-engine.cap.ts","../src/capabilities/stream-broker.cap.ts","../src/capabilities/camera-streams.cap.ts","../src/capabilities/carbon-monoxide.cap.ts","../src/capabilities/climate-control.cap.ts","../src/capabilities/color.cap.ts","../src/capabilities/connectivity.cap.ts","../src/capabilities/consumables.cap.ts","../src/capabilities/contact.cap.ts","../src/capabilities/control.cap.ts","../src/capabilities/cover.cap.ts","../src/device/source-info.ts","../src/capabilities/device-discovery.cap.ts","../src/capabilities/doorbell.cap.ts","../src/capabilities/enum-sensor.cap.ts","../src/capabilities/event-emitter.cap.ts","../src/capabilities/fan-control.cap.ts","../src/capabilities/flood.cap.ts","../src/capabilities/gas.cap.ts","../src/capabilities/humidifier.cap.ts","../src/capabilities/humidity-sensor.cap.ts","../src/capabilities/image.cap.ts","../src/capabilities/lawn-mower-control.cap.ts","../src/capabilities/lock-control.cap.ts","../src/capabilities/media-player.cap.ts","../src/capabilities/schemas/detection-shared.ts","../src/capabilities/motion-detection.cap.ts","../src/capabilities/schemas/orchestrator-metrics.ts","../src/capabilities/pipeline-executor.cap.ts","../src/capabilities/zones.cap.ts","../src/capabilities/pipeline-runner.cap.ts","../src/capabilities/motion.cap.ts","../src/capabilities/motion-trigger.cap.ts","../src/capabilities/mask-shape.ts","../src/capabilities/motion-zones.cap.ts","../src/capabilities/native-object-detection.cap.ts","../src/capabilities/notifier.cap.ts","../src/capabilities/numeric-sensor.cap.ts","../src/capabilities/power-meter.cap.ts","../src/capabilities/presence.cap.ts","../src/capabilities/pressure-sensor.cap.ts","../src/capabilities/privacy-mask.cap.ts","../src/capabilities/ptz-autotrack.cap.ts","../src/capabilities/script-runner.cap.ts","../src/capabilities/smoke.cap.ts","../src/capabilities/stream-params.cap.ts","../src/capabilities/switch.cap.ts","../src/capabilities/tamper.cap.ts","../src/capabilities/temperature-sensor.cap.ts","../src/capabilities/update.cap.ts","../src/capabilities/vacuum-control.cap.ts","../src/capabilities/valve.cap.ts","../src/capabilities/vibration.cap.ts","../src/capabilities/water-heater.cap.ts","../src/capabilities/weather.cap.ts","../src/capabilities/zone-analytics.cap.ts","../src/capabilities/schemas/zone-rule.ts","../src/capabilities/zone-rules.cap.ts","../src/capabilities/device-provider.cap.ts","../src/capabilities/addon-settings.cap.ts","../src/capabilities/alerts.cap.ts","../src/capabilities/storage.cap.ts","../src/capabilities/storage-provider.cap.ts","../src/capabilities/storage-evictable.cap.ts","../src/capabilities/backup.cap.ts","../src/capabilities/settings-store.cap.ts","../src/capabilities/log-destination.cap.ts","../src/capabilities/admin-ui.cap.ts","../src/schemas/auth-records.ts","../src/capabilities/sso-bridge.cap.ts","../src/capabilities/oauth-integration.cap.ts","../src/capabilities/user-passkeys.cap.ts","../src/capabilities/smtp-provider.cap.ts","../src/capabilities/device-adoption.cap.ts","../src/capabilities/broker.cap.ts","../src/capabilities/mqtt-broker.cap.ts","../src/capabilities/device-export.cap.ts","../src/capabilities/addon-pages.cap.ts","../src/capabilities/addon-pages-source.cap.ts","../src/capabilities/addon-widgets-source.cap.ts","../src/capabilities/addon-widgets.cap.ts","../src/capabilities/addon-routes.cap.ts","../src/capabilities/decoder.cap.ts","../src/capabilities/restreamer.cap.ts","../src/capabilities/webrtc.cap.ts","../src/capabilities/webrtc-session.cap.ts","../src/capabilities/pipeline-orchestrator.cap.ts","../src/capabilities/audio-analyzer.cap.ts","../src/capabilities/audio-analysis.cap.ts","../src/capabilities/audio-codec.cap.ts","../src/capabilities/embedding-encoder.cap.ts","../src/capabilities/device-manager.cap.ts","../src/capabilities/device-state.cap.ts","../src/capabilities/auth-provider.cap.ts","../src/capabilities/network-access.cap.ts","../src/capabilities/turn-provider.cap.ts","../src/capabilities/snapshot.cap.ts","../src/capabilities/snapshot-provider.cap.ts","../src/capabilities/notification-output.cap.ts","../src/capabilities/advanced-notifier.cap.ts","../src/capabilities/detection-pipeline.cap.ts","../src/capabilities/camera-pipeline-config.cap.ts","../src/capabilities/pipeline-analytics.cap.ts","../src/capabilities/metrics-provider.cap.ts","../src/capabilities/ptz.cap.ts","../src/capabilities/events.cap.ts","../src/capabilities/recording.cap.ts","../src/capabilities/device-ops.cap.ts","../src/capabilities/camera-credentials.cap.ts","../src/capabilities/reboot.cap.ts","../src/capabilities/button.cap.ts","../src/capabilities/osd.cap.ts","../src/capabilities/accessories.cap.ts","../src/capabilities/intercom.cap.ts","../src/capabilities/stream-catalog.cap.ts","../src/capabilities/platform-probe.cap.ts","../src/capabilities/local-network.cap.ts","../src/capabilities/mesh-network.cap.ts","../src/capabilities/user-management.cap.ts","../src/capabilities/system.cap.ts","../src/capabilities/network-quality.cap.ts","../src/capabilities/toast.cap.ts","../src/capabilities/nodes.cap.ts","../src/capabilities/integrations.cap.ts","../src/capabilities/addons.cap.ts","../src/capabilities/index.ts"],"sourcesContent":["/**\n * Deep wiring healthcheck — snapshot of active reachability probes across\n * every declared capability + widget of every installed plugin, on every\n * node. Produced by the backend `WiringHealthService` and surfaced via\n * `GET /health/wiring`, the tRPC `health.wiring` query, and the boot-gate.\n *\n * Unlike `/health` (process liveness), this reflects whether each cap/widget\n * is actually *reachable* over the real cap-dispatch path. See spec\n * `docs/superpowers/specs/2026-05-23-deep-healthcheck-design.md`.\n */\nimport { z } from 'zod'\n\n/** What kind of target a probe addressed. */\nexport const wiringProbeKindSchema = z.enum(['singleton', 'device', 'widget'])\nexport type WiringProbeKind = z.infer<typeof wiringProbeKindSchema>\n\n/** Result of probing a single (cap|widget [, device]) target. */\nexport const wiringProbeResultSchema = z.object({\n capName: z.string(),\n kind: wiringProbeKindSchema,\n deviceId: z.number().optional(),\n reachable: z.boolean(),\n latencyMs: z.number(),\n error: z.string().optional(),\n})\nexport type WiringProbeResult = z.infer<typeof wiringProbeResultSchema>\n\n/** Per-addon roll-up of cap + widget probe results. */\nexport const wiringAddonHealthSchema = z.object({\n addonId: z.string(),\n caps: z.array(wiringProbeResultSchema).readonly(),\n widgets: z.array(wiringProbeResultSchema).readonly(),\n})\nexport type WiringAddonHealth = z.infer<typeof wiringAddonHealthSchema>\n\n/** Per-node roll-up. */\nexport const wiringNodeHealthSchema = z.object({\n nodeId: z.string(),\n addons: z.array(wiringAddonHealthSchema).readonly(),\n})\nexport type WiringNodeHealth = z.infer<typeof wiringNodeHealthSchema>\n\n/** Full snapshot returned by every surface. */\nexport const wiringHealthSnapshotSchema = z.object({\n /** True only when every probed target is reachable. */\n ok: z.boolean(),\n /** True when at least one target is unreachable. */\n degraded: z.boolean(),\n checkedAt: z.string(),\n nodes: z.array(wiringNodeHealthSchema).readonly(),\n summary: z.object({\n total: z.number(),\n reachable: z.number(),\n unreachable: z.number(),\n }),\n})\nexport type WiringHealthSnapshot = z.infer<typeof wiringHealthSnapshotSchema>\n","import type { LabelDefinition, ClassMapDefinition } from './labels.js'\n\nexport const MODEL_FORMATS = ['onnx', 'coreml', 'openvino', 'tflite', 'pt'] as const\nexport type ModelFormat = (typeof MODEL_FORMATS)[number]\nexport type ModelOutputFormat = 'yolo' | 'ssd' | 'embedding' | 'classification' | 'ocr' | 'segmentation'\n\nexport interface ModelFormatEntry {\n readonly url: string\n readonly sizeMB: number\n /** Whether this format is a directory bundle (e.g., .mlpackage) rather than a single file */\n readonly isDirectory?: boolean\n /**\n * For directory formats: list of files relative to the directory root.\n * The downloader fetches each file from `{url}/{file}` and saves to `{modelDir}/{file}`.\n * If omitted for a directory format, the downloader probes HuggingFace API (slower).\n */\n readonly files?: readonly string[]\n /** Runtime(s) that can use this format. If omitted, inferred from ModelFormat key */\n readonly runtimes?: readonly ('node' | 'python')[]\n}\n\n/**\n * Extra file that must be downloaded alongside the model (e.g., labels JSON, dict.txt).\n * The downloader fetches from `url` and saves to `{modelsDir}/{filename}`.\n */\nexport interface ModelExtraFile {\n readonly url: string\n readonly filename: string\n readonly sizeMB: number\n}\n\nexport interface ModelCatalogEntry {\n readonly id: string\n readonly name: string\n readonly description: string\n readonly formats: Partial<Readonly<Record<ModelFormat, ModelFormatEntry>>>\n readonly inputSize: { readonly width: number; readonly height: number }\n readonly labels: readonly LabelDefinition[]\n readonly inputLayout?: 'nchw' | 'nhwc'\n readonly inputNormalization?: 'zero-one' | 'imagenet' | 'none'\n readonly preprocessMode?: 'letterbox' | 'resize'\n /**\n * Auxiliary files required at runtime (labels JSON, charset dict, etc.).\n * Downloaded into the same modelsDir alongside the model file.\n */\n readonly extraFiles?: readonly ModelExtraFile[]\n}\n\nexport interface DetectionModel {\n readonly id: string\n readonly name: string\n readonly labels: readonly string[]\n readonly inputSize: { readonly width: number; readonly height: number }\n}\n\nexport interface ModelDownloadOptions {\n readonly url: string\n readonly fallbackUrls?: readonly string[]\n readonly destDir: string\n readonly filename?: string\n readonly expectedSha256?: string\n readonly onProgress?: (downloaded: number, total: number) => void\n}\n\nexport interface ModelDownloadResult {\n readonly filePath: string\n readonly downloadedBytes: number\n readonly fromCache: boolean\n}\n\nexport interface CustomModelMetadata {\n readonly name: string\n readonly inputSize: { readonly width: number; readonly height: number }\n readonly labels: readonly LabelDefinition[]\n readonly classMap?: ClassMapDefinition\n readonly inputLayout?: 'nchw' | 'nhwc'\n readonly inputNormalization?: 'zero-one' | 'imagenet' | 'none'\n readonly outputFormat: ModelOutputFormat\n}\n","import type { ModelCatalogEntry, ModelFormat, ModelOutputFormat, CustomModelMetadata } from '../types/models.js'\n\n/**\n * Configuration UI Schema -- declarative form definition for any element.\n *\n * Used by addons to declare their settings UI. The admin UI collects schemas\n * from all active addons, merges tabs with the same ID, and renders responsive forms.\n *\n * Layout hierarchy: Tab → Section → Field\n * Multiple addons can contribute sections to the same tab.\n */\n\n// --- Well-Known Tabs ─────────────────────────────────────────────────\n\n/** Predefined tab identifiers that addons reference by ID. */\nexport type WellKnownTabId =\n | 'overview'\n | 'general'\n | 'image'\n | 'light'\n | 'motion'\n | 'audio'\n | 'snapshot'\n | 'osd'\n | 'alarms'\n | 'pipeline'\n | 'stream-broker'\n | 'streaming'\n | 'ptz'\n | 'consumables'\n | 'zones'\n | 'live-stats'\n | 'recording'\n | 'notifications'\n | 'network'\n | 'storage'\n | 'engine'\n | 'scheduler'\n | 'decoder'\n | 'advanced'\n\nexport interface WellKnownTab {\n readonly id: WellKnownTabId\n readonly label: string\n readonly icon: string\n readonly order: number\n}\n\n/** Predefined tabs with standard label, icon, and sort order.\n *\n * Pipeline (renamed Orchestrator in the UI) holds the four\n * pipeline-orchestrator sections: General, Object Detection, Audio,\n * and Cluster Assignment. Motion stays its own tab.\n * `streaming` remains for older payloads that haven't been retagged. */\nexport const WELL_KNOWN_TABS: readonly WellKnownTab[] = [\n { id: 'overview', label: 'Overview', icon: 'layout-dashboard', order: -10 },\n { id: 'general', label: 'General', icon: 'settings', order: 0 },\n { id: 'image', label: 'Image', icon: 'image', order: 5 },\n { id: 'light', label: 'Light', icon: 'lightbulb', order: 7 },\n { id: 'motion', label: 'Motion', icon: 'activity', order: 10 },\n { id: 'audio', label: 'Audio', icon: 'mic', order: 12 },\n { id: 'alarms', label: 'Alarms', icon: 'bell-ring', order: 13 },\n { id: 'snapshot', label: 'Snapshot', icon: 'camera', order: 15 },\n { id: 'osd', label: 'OSD', icon: 'type', order: 18 },\n { id: 'stream-broker', label: 'Stream Broker', icon: 'radio', order: 20 },\n { id: 'streaming', label: 'Streaming', icon: 'video', order: 35 },\n { id: 'ptz', label: 'PTZ', icon: 'move', order: 40 },\n { id: 'consumables', label: 'Consumables', icon: 'recycle', order: 44 },\n { id: 'pipeline', label: 'Detection Pipeline', icon: 'cpu', order: 39 },\n { id: 'zones', label: 'Detection', icon: 'shapes', order: 38 },\n { id: 'live-stats', label: 'Live Stats', icon: 'activity', order: 39 },\n { id: 'recording', label: 'Recording', icon: 'circle-dot', order: 40 },\n // Pipeline-page tabs — `engine` co-locates `detection-pipeline`'s\n // vision-engine section + `audio-analyzer`'s audio-engine section\n // (same modality of choice, different pipelines). `scheduler` and\n // `decoder` group the runner / decoder addon settings under their\n // own tabs so the pipeline page bar stays manageable.\n { id: 'engine', label: 'Inference Engine', icon: 'zap', order: 41 },\n { id: 'scheduler', label: 'Scheduler', icon: 'list-checks', order: 42 },\n { id: 'decoder', label: 'Decoder', icon: 'film', order: 43 },\n { id: 'notifications', label: 'Notifications', icon: 'bell', order: 50 },\n { id: 'network', label: 'Network', icon: 'globe', order: 60 },\n { id: 'storage', label: 'Storage', icon: 'hard-drive', order: 70 },\n { id: 'advanced', label: 'Advanced', icon: 'wrench', order: 100 },\n] as const\n\n/** Lookup map for well-known tabs by ID. */\nexport const WELL_KNOWN_TAB_MAP: Readonly<Record<WellKnownTabId, WellKnownTab>> =\n Object.fromEntries(WELL_KNOWN_TABS.map(t => [t.id, t])) as Record<WellKnownTabId, WellKnownTab>\n\n// --- Tab Declaration ─────────────────────────────────────────────────\n\n/**\n * Custom tab declaration by an addon.\n * Use well-known tab IDs when possible. Custom tabs are for addon-specific UI.\n */\nexport interface ConfigTabDeclaration {\n /** Unique tab identifier. Use WellKnownTabId for standard tabs. */\n readonly id: string\n /** Display label (ignored for well-known tabs — their label is used). */\n readonly label: string\n /** Icon identifier (ignored for well-known tabs — their icon is used). */\n readonly icon: string\n /** Sort order within the tab bar. Lower = left. */\n readonly order?: number\n}\n\n// --- Schema Definition ───────────────────────────────────────────────\n\nexport interface ConfigUISchema {\n /**\n * Tabs contributed by this addon.\n * Multiple addons can reference the same tab ID — the UI merges them.\n * For well-known tabs, label/icon from WELL_KNOWN_TABS takes precedence.\n * Omit to use only well-known tabs referenced by sections.\n */\n readonly tabs?: readonly ConfigTabDeclaration[]\n readonly sections: readonly ConfigSection[]\n}\n\nexport interface ConfigSection {\n readonly id: string\n readonly title: string\n readonly description?: string\n readonly style?: 'card' | 'accordion'\n readonly defaultCollapsed?: boolean\n readonly columns?: 1 | 2 | 3 | 4\n /** Which tab this section belongs to. Default: 'general'. */\n readonly tab?: string\n /**\n * Where the section is rendered in the device page. Default\n * `'settings'` keeps the section under the device Settings panel\n * (existing behavior). `'top-tab'` hoists the section into a\n * top-level device tab (sibling of Live / Streams / Recordings /\n * Settings) keyed by the section's `tab` value. Multiple addons\n * targeting the same `(tab, location: 'top-tab')` pair render\n * inside the same top tab in `order` sequence — used for the\n * Zones tab where orchestrator (geometry CRUD) + motion-wasm\n * (motion rules) + detection-pipeline (detection rules) all\n * contribute to one operator surface.\n */\n readonly location?: 'settings' | 'top-tab'\n /** Sort order within the tab. Lower = top. */\n readonly order?: number\n /**\n * When true, every field in this section saves immediately on change\n * (no Save button needed). Per-field `immediate: false` overrides this.\n */\n readonly immediate?: boolean\n readonly fields: readonly ConfigField[]\n}\n\n// --- Field Types ---\n\nexport type ConfigField =\n | ConfigTextField\n | ConfigNumberField\n | ConfigBooleanField\n | ConfigSelectField\n | ConfigMultiSelectField\n | ConfigTimezoneField\n | ConfigDateTimeField\n | ConfigColorField\n | ConfigPasswordField\n | ConfigTextAreaField\n | ConfigSliderField\n | ConfigTagsField\n | ConfigGroupField\n | ConfigSubTabsField\n | ConfigSeparatorField\n | ConfigInfoField\n | ConfigQrCodeField\n | ConfigObjectArrayField\n | ConfigEditableArrayField\n | ConfigModelSelectorField\n | ConfigStorageLocationField\n | ConfigProbeField\n | ConfigButtonField\n | ConfigPipelineEditorField\n | ConfigNodeSelectField\n | ConfigNodeMultiSelectField\n | ConfigWidgetField\n | ConfigAddonActionSelectField\n | ConfigAddonActionButtonField\n | ConfigDeviceActionButtonField\n\nexport interface ConfigFieldBase {\n readonly key: string\n readonly label: string\n readonly description?: string\n readonly required?: boolean\n readonly disabled?: boolean\n readonly placeholder?: string\n /** Default value used when the current value is undefined */\n readonly default?: unknown\n readonly span?: 1 | 2 | 3 | 4\n readonly showWhen?: ConfigCondition\n // Settings-redesign cleanup: `scope?: 'device' | 'global'` removed.\n // In the three-level model, a field's scope is determined by WHICH\n // schema it lives in — `getAddonSettings / getGlobalSettings /\n // getDeviceSettings` — not by a field-level marker. The keys are\n // disjoint across levels by invariant, so a scope marker is\n // redundant.\n /**\n * Save behavior when value changes.\n * - true: save immediately on change (toggles, selects, checkboxes)\n * - false (default): debounce 2 seconds for text/number inputs before saving\n *\n * The UI FormBuilder reads this flag and applies debounce accordingly.\n */\n readonly immediate?: boolean\n /**\n * Declares that changes to this field can only take effect after the\n * owning addon is (re)started — the field is bound at boot time and\n * cannot be hot-reloaded from `onConfigChanged()`. Example: Python\n * inference-pool `concurrency` (pool threads are allocated at pool\n * spawn). The UI surfaces a \"Restart required\" hint, and the\n * framework auto-restarts the addon after the update lands on a flag\n * transition — see `BaseAddon.updateGlobalSettings` /\n * `updateAddonSettings`.\n */\n readonly requiresRestart?: boolean\n /**\n * Override the default placement of this field.\n * Moves it to a different tab and/or section than its parent section.\n * Useful for placing a single setting in a shared tab (e.g., 'advanced').\n */\n readonly placement?: {\n /** Target tab ID (well-known or custom). */\n readonly tab?: string\n /** Target section ID within the tab. Created if it doesn't exist. */\n readonly section?: string\n }\n /**\n * Device-aggregator metadata — only meaningful when this field is part of\n * a `ConfigUISchemaWithValues` merged by `deviceManager.getDeviceSettingsAggregate`\n * / `getDeviceLiveInfoAggregate`.\n *\n * - `readonlyField: true` — render as display-only, no mutation handler\n * - `source: 'live'` — the value comes from the fast-poll live\n * aggregator; the UI re-queries it on its own\n * cadence and swaps the value in place. Default:\n * 'settings' (slow, cached, invalidated on save)\n * - `writerCapName` — when editable, the capability whose provider\n * accepts the mutation via\n * `deviceManager.updateDeviceField`.\n * - `writerAddonId` — when editable, the addon id of the provider\n * for `writerCapName`. Ignored for\n * `readonlyField: true`.\n * - `minRole` — minimum user role required to edit this\n * field. UI uses it to disable the input and\n * show a lock icon; the server still enforces\n * cap-level auth (`admin` for the aggregator\n * writers today). Default: 'admin'.\n *\n * The aggregator tags fields with `writerCapName` + `writerAddonId` before\n * returning them — providers produce clean schemas; provenance is injected\n * based on which (cap, provider) contributed the section.\n *\n * Named `readonlyField` instead of `readonly` to avoid colliding with the\n * TS modifier already implied by the interface fields.\n */\n readonly readonlyField?: boolean\n readonly source?: 'settings' | 'live'\n readonly writerCapName?: string\n readonly writerAddonId?: string\n readonly minRole?: 'viewer' | 'admin'\n /**\n * Optional inline action icons shown on the right of the field\n * control. Each action is a compact icon button that dispatches\n * through the same `onAction(action, key)` handler the button-field\n * type uses — keeps the action pipeline single-sourced. Common use:\n * readonly URL field with a \"regenerate\" icon, probe field with a\n * \"copy\" shortcut, etc.\n */\n readonly actions?: readonly FieldInlineAction[]\n /**\n * Declare this field as a *collection* of its underlying primitive.\n * When set, the stored value is an array (`T[]`) instead of a scalar\n * (`T`), and the form renderer shows:\n * - `min` initial instances (empty slots if no value stored yet)\n * - an `+ Add` button when the current count < `max`\n * - a remove icon on each instance when the current count > `min`\n * - an item counter badge (e.g. `2/3`) next to the section header\n *\n * Applies uniformly to every scalar-valued field type (text, number,\n * boolean, select, color, probe, password, textarea, slider, tags,\n * model-selector, storage-location). Structural fields (separator,\n * info, button) and group fields ignore this flag.\n *\n * Probe fields hit `testCreationField` / settings-contribution\n * probing per-index — the handler receives the full array and an\n * `index` hint so it can resolve just that slot.\n */\n readonly multiple?: ConfigFieldMultiple\n}\n\n/**\n * Array-widget metadata for a `ConfigFieldBase`. See `multiple` on\n * `ConfigFieldBase` for the activation semantics.\n */\nexport interface ConfigFieldMultiple {\n /** Minimum item count — always rendered, no remove button when count == min. */\n readonly min: number\n /** Maximum item count — Add button hidden when count == max. */\n readonly max: number\n /** Label for the \"add\" affordance. Default: \"Add\". */\n readonly addLabel?: string\n /** Template for each item's label (${n} = 1-based index). Default: none. */\n readonly itemLabel?: string\n /**\n * Default value each newly-added instance starts with. Falls back to\n * the field-level `default`, then to the empty string for string\n * fields or `null` for everything else.\n */\n readonly itemDefault?: unknown\n}\n\n/** Inline action icon attached to any ConfigField. */\nexport interface FieldInlineAction {\n /** Action identifier forwarded to the FormBuilder `onAction` handler. */\n readonly action: string\n /** Lucide icon name (e.g. 'refresh-cw', 'copy', 'external-link'). */\n readonly icon: string\n /** Tooltip shown on hover. */\n readonly tooltip: string\n /** Visual variant — `danger` flags destructive actions in red. */\n readonly variant?: 'default' | 'danger' | 'primary'\n /** Optional confirmation prompt before dispatching. */\n readonly confirmMessage?: string\n}\n\nexport interface ConfigCondition {\n field: string\n equals?: unknown\n notEquals?: unknown\n in?: unknown[]\n notIn?: unknown[]\n /**\n * For `multiselect` / `tags` / array-valued fields: matches when the\n * referenced field's array value INCLUDES the given primitive. Example:\n * `{ field: 'motionSources', includes: 'analyzer' }` shows the\n * dependent field only when the analyzer source is selected.\n */\n includes?: unknown\n /** Inverse of `includes` — show when the field's array value does NOT\n * contain the given primitive. */\n notIncludes?: unknown\n}\n\nexport interface ConfigTextField extends ConfigFieldBase {\n type: 'text'\n maxLength?: number\n pattern?: string\n inputType?: 'text' | 'url' | 'email'\n}\n\nexport interface ConfigNumberField extends ConfigFieldBase {\n type: 'number'\n min?: number\n max?: number\n step?: number\n unit?: string\n}\n\nexport interface ConfigBooleanField extends ConfigFieldBase {\n type: 'boolean'\n style?: 'switch' | 'checkbox'\n}\n\nexport interface ConfigSelectField extends ConfigFieldBase {\n type: 'select'\n options: readonly ConfigOption[]\n dependsOn?: Record<string, unknown>\n}\n\nexport interface ConfigMultiSelectField extends ConfigFieldBase {\n type: 'multiselect'\n options: readonly ConfigOption[]\n maxItems?: number\n}\n\n/**\n * Friendly timezone picker. The stored value is an IANA timezone id\n * (e.g. 'Europe/Rome'); the renderer mounts the shared\n * `<TimezoneSelector>` from `@camstack/ui-library`, grouping the curated\n * `TIMEZONES` catalogue by region. DST is implied by the chosen zone —\n * there is no separate DST control. Consumers (device providers) resolve\n * the id via `findTimezone(id)` to obtain the standard offset + DST rule.\n */\nexport interface ConfigTimezoneField extends ConfigFieldBase {\n readonly type: 'timezone'\n}\n\n/**\n * Editable local date-time picker. The stored value is a string in the\n * native `datetime-local` shape `YYYY-MM-DDTHH:MM` (local wall-clock, no\n * seconds, no zone). The renderer mounts an `<input type=\"datetime-local\">`\n * with the standard form-field chrome. Consumers that need a fully-zoned\n * timestamp append `:00` seconds + a zone designator on the save path.\n */\nexport interface ConfigDateTimeField extends ConfigFieldBase {\n readonly type: 'datetime'\n}\n\nexport interface ConfigColorField extends ConfigFieldBase {\n type: 'color'\n presets?: string[]\n}\n\n/** Select a single cluster node from the live topology. Options are\n * populated dynamically by the UI via useClusterNodes — no server-side\n * option list needed. */\nexport interface ConfigNodeSelectField extends ConfigFieldBase {\n type: 'node-select'\n /** When true, include offline nodes (greyed out). Default: false. */\n showOffline?: boolean\n}\n\n/** Select multiple cluster nodes from the live topology. */\nexport interface ConfigNodeMultiSelectField extends ConfigFieldBase {\n type: 'node-multiselect'\n showOffline?: boolean\n maxItems?: number\n}\n\nexport interface ConfigPasswordField extends ConfigFieldBase {\n type: 'password'\n showToggle?: boolean\n}\n\nexport interface ConfigTextAreaField extends ConfigFieldBase {\n type: 'textarea'\n rows?: number\n maxLength?: number\n /**\n * When true, the stored value is a JSON-serializable object/array and\n * the UI shows it as pretty-printed JSON, with parse-on-save semantics.\n * `hydrateSchema` takes care of stringifying on the way out; the\n * FormBuilder is expected to parse before emitting the patch.\n *\n * Used by `zodEntriesToConfigUI` when the Zod schema is an\n * array/object — falls back gracefully when the FormBuilder hasn't\n * implemented parse-on-save yet (the field still renders the JSON\n * string instead of `[object Object],…`).\n */\n isJson?: boolean\n}\n\nexport interface ConfigSliderField extends ConfigFieldBase {\n type: 'slider'\n min: number\n max: number\n step?: number\n showValue?: boolean\n unit?: string\n default?: number\n /** Display scale factor: displayed = stored / displayScale. E.g., displayScale=1000 shows ms as seconds. */\n displayScale?: number\n /** When true, allows a \"not set\" state where the value is null (e.g., \"Auto\" mode) */\n nullable?: boolean\n /** Label shown when the value is null (default: \"Auto\") */\n nullLabel?: string\n /**\n * When true, render +/− stepper buttons flanking the numeric input.\n * Each click increments/decrements by `step` (default 1) and clamps\n * to `[min, max]`. Pairs with `showValue` so the operator can fine-\n * tune from the keyboard / pointer without scrubbing the slider.\n */\n showStepper?: boolean\n}\n\nexport interface ConfigTagsField extends ConfigFieldBase {\n type: 'tags'\n suggestions?: string[]\n maxTags?: number\n}\n\nexport interface ConfigGroupField extends ConfigFieldBase {\n type: 'group'\n fields: readonly ConfigField[]\n style?: 'card' | 'inline' | 'accordion'\n defaultCollapsed?: boolean\n}\n\n/** Visual separator between fields */\nexport interface ConfigSeparatorField {\n type: 'separator'\n key: string\n}\n\n// --- Sub-tabs Field ---\n//\n// Renders a nested tab strip inside a section. Each sub-tab carries its\n// own list of `ConfigField`s. Values are flat across all sub-tabs (the\n// outer save controller treats them like any other field key) — the\n// sub-tabs are purely a layout primitive, not a save scope. Use when a\n// section needs to host many fields that fall into clearly separable\n// categories (e.g. one sub-tab per camera stream source).\n\n/** A single sub-tab inside a `ConfigSubTabsField`. */\nexport interface ConfigSubTabDefinition {\n readonly id: string\n readonly label: string\n readonly icon?: string\n /** Short text shown next to the label (e.g. live status / counter). */\n readonly badge?: string\n readonly fields: readonly ConfigField[]\n}\n\nexport interface ConfigSubTabsField extends ConfigFieldBase {\n type: 'sub-tabs'\n /** Tab definitions; rendered in array order. The first tab is active by default. */\n tabs: readonly ConfigSubTabDefinition[]\n}\n\n/**\n * Read-only QR code — renders an arbitrary string as a scannable QR\n * image via the shared `<QrCode>` component in `@camstack/ui-library`.\n *\n * Use for per-device pairing surfaces (HomeKit `X-HM://…` URI, OAuth\n * device-flow user code, etc.). When `value` is empty / absent the\n * renderer skips the field — addons that haven't materialised the\n * pairing payload yet (cold start, unpublished accessory) can return\n * the field unconditionally without rendering noise.\n */\nexport interface ConfigQrCodeField extends ConfigFieldBase {\n type: 'qr-code'\n /** The string encoded as the QR. Empty/absent → field renders nothing. */\n value?: string\n /** Optional caption shown above or beside the QR. */\n caption?: string\n /** Pixel size of the rendered QR (square). Default 192. */\n size?: number\n /** Alt text for accessibility. Defaults to the label. */\n alt?: string\n}\n\n/** Read-only informational text */\nexport interface ConfigInfoField {\n type: 'info'\n key: string\n label: string\n content: string\n variant?: 'info' | 'warning' | 'success' | 'danger'\n /**\n * Rendering mode for `content`. Default `'text'` keeps the legacy\n * \"plain string with auto-newlines\" behaviour. `'html'` interprets\n * `content` as inline HTML (sanitised in the renderer to a small\n * allowlist: a, ul, ol, li, strong, em, code, br) so addons can ship\n * clickable links and bulleted steps without inventing markdown.\n *\n * HTML mode is for addon-authored copy that lives in the bundle (no\n * user-supplied input flows here), so the surface stays narrow.\n */\n format?: 'text' | 'html'\n /** Same semantics as `ConfigFieldBase.showWhen` — lets info banners\n * conditionally appear (e.g. \"Cloudflare API token instructions\"\n * only when mode === 'custom'). */\n showWhen?: ConfigCondition\n}\n\n/**\n * Read-only structured table for diagnostic data. Renders as a row-per-\n * entry list with column headers. Use when a section needs to surface\n * multiple parallel records (live sessions, socket-pool entries, recent\n * doorbell presses, …) — replaces the older \"joined-string in an info\n * field\" pattern that lost structure on long entries.\n *\n * Columns describe how to render each cell. Each entry in `value` is a\n * record keyed by the column `key`. Missing keys render as em-dash.\n *\n * NOT editable — the FormBuilder ignores the field for save patches.\n */\nexport interface ConfigObjectArrayField {\n type: 'object-array'\n key: string\n label: string\n description?: string\n /**\n * Column definitions in render order. The `kind` hint controls cell\n * formatting:\n * - `text` (default): plain string; null/undefined → em-dash\n * - `monospace`: monospace font (good for IPs, sessionIds)\n * - `status`: small colored dot + label, value should be one of\n * 'ok' | 'warn' | 'danger' | 'idle' | 'unknown'\n * - `duration`: number of ms, formatted as \"1m 23s\"\n * - `timestamp`: number (ms epoch), formatted as locale time\n */\n columns: ReadonlyArray<{\n readonly key: string\n readonly label: string\n readonly kind?: 'text' | 'monospace' | 'status' | 'duration' | 'timestamp'\n /** Optional fixed width hint (CSS values: '120px', '20%', etc). */\n readonly width?: string\n }>\n /** Rows. Empty array renders `emptyMessage`. */\n value: ReadonlyArray<Record<string, unknown>>\n /** Shown when `value` is empty. Default: \"No entries\". */\n emptyMessage?: string\n}\n\nexport interface ConfigOption {\n value: string\n label: string\n description?: string\n icon?: string\n}\n\n// --- Editable Array Field ---\n\n/**\n * Editable array of records. Each row exposes the fields declared in\n * `itemFields`; the form renderer reuses the standard scalar field\n * components (text / number / select / password / boolean) for each\n * cell. Add/Remove row buttons mutate `value` (the FormBuilder picks\n * up the new array via the standard onChange flow).\n *\n * Use for \"configure N items\" cases — e.g. a backup-sftp addon\n * exposing a list of remote destinations the operator can add or\n * remove. Don't use for fixed-cardinality data; a flat group of\n * fields reads better.\n *\n * Constraints inside `itemFields`:\n * - Only scalar field types are supported (text/number/select/\n * multiselect/password/boolean/textarea/color/tags/slider). Nested\n * groups, sub-tabs, probes, button actions, and other arrays are\n * intentionally rejected — they conflate row-state with section-\n * state and the FormBuilder's flat onChange contract can't carry\n * the nesting cleanly. Build a custom-renderer if you need that.\n * - Field `key`s are scoped to the row (no global collisions with\n * the surrounding section).\n * - `showWhen` inside a row references siblings within the same row.\n */\nexport interface ConfigEditableArrayField extends ConfigFieldBase {\n readonly type: 'editable-array'\n /** Per-row schema. Same shape as section.fields, scalar-only. */\n readonly itemFields: readonly ConfigField[]\n /** Default values used when the operator clicks \"Add\". */\n readonly defaultItem?: Record<string, unknown>\n /** Minimum number of rows allowed. Remove disabled below this count. */\n readonly minRows?: number\n /** Maximum number of rows allowed. Add disabled at this count. */\n readonly maxRows?: number\n /** Label for the \"Add\" button. Defaults to \"Add\". */\n readonly addLabel?: string\n /** Shown when the array is empty. Default: \"No entries\". */\n readonly emptyMessage?: string\n /**\n * Optional template for each row's title (e.g. \"{displayName}\" or\n * \"{host}:{port}\"). Resolved against the row's values; missing keys\n * collapse to an em-dash. Falls back to `Row N` when not provided.\n */\n readonly rowTitleTemplate?: string\n}\n\n// --- Model Selector Field ---\n\nexport interface ConfigModelSelectorField extends ConfigFieldBase {\n type: 'model-selector'\n /** Filter models by type */\n modelType?: string\n /** Allow user to enter a custom local path or URL (default: true) */\n allowCustomPath?: boolean\n /** Allow file upload via UI (default: true) */\n allowUpload?: boolean\n /** Accepted file extensions for upload (default: ['.onnx']) */\n acceptExtensions?: string[]\n /** URL to model conversion documentation/guide */\n conversionGuideUrl?: string\n /** Brief text explaining what models are compatible */\n compatibilityNote?: string\n /** Legacy: inline catalog entries */\n catalog?: readonly ModelCatalogEntry[]\n allowCustom?: boolean\n acceptFormats?: readonly ModelFormat[]\n allowConversion?: boolean\n requiredMetadata?: readonly (keyof CustomModelMetadata)[]\n outputFormatHint?: ModelOutputFormat\n}\n\n// --- Probe Field ---\n\n/** Result of probing a single field value (returned by IDeviceProvider.testField) */\nexport interface FieldProbeResult {\n status: 'ok' | 'error'\n /** Labels to display as chips (e.g. \"1920×1080\", \"H.265\", \"25fps\") */\n labels?: readonly string[]\n /** Error message when status is 'error' */\n error?: string\n /**\n * Optional values the provider suggests applying to other form fields\n * after a successful probe. The form-builder merges these into the\n * working snapshot ONLY for fields the operator hasn't filled yet,\n * never overwriting user input. Typical use: a host-probe that\n * autodetects the camera model and proposes it as the device `name`.\n */\n suggestedValues?: Readonly<Record<string, unknown>>\n}\n\n/**\n * A probeable input field. Renders as a text input with a test button.\n * The provider implements the actual probing logic via IDeviceProvider.testField.\n *\n * UX states:\n * - idle: muted icon, no labels\n * - probing: spinner icon\n * - ok: green check icon + provider-returned labels as chips\n * - error: red icon + error message\n */\nexport interface ConfigProbeField extends ConfigFieldBase {\n type: 'probe'\n /** Input type hint for the text input (default: 'url') */\n inputType?: 'url' | 'text'\n}\n\n// --- Storage Location Selector Field ---\n\nimport type { StorageLocationType } from './storage.js'\n\nexport interface ConfigStorageLocationField extends ConfigFieldBase {\n type: 'storage-location'\n /** Which location type this field selects a provider for */\n locationType: StorageLocationType\n /** Show available space indicator next to each provider option */\n showAvailableSpace?: boolean\n}\n\nexport interface ConfigButtonField extends ConfigFieldBase {\n type: 'button'\n /** Button label text */\n buttonLabel: string\n /** Visual variant */\n variant?: 'default' | 'danger' | 'primary'\n /** tRPC action identifier — the form handler calls this action when pressed */\n action: string\n /** Confirmation prompt before executing (optional) */\n confirmMessage?: string\n}\n\n/**\n * Select whose options are pulled from a customAction on an addon at\n * render time. Generalises the \"user pastes a token, server returns\n * the list of zones / buckets / dirs they can pick from\" UX pattern\n * across every addon that integrates with an external API.\n *\n * Wiring at render time (admin-ui side):\n * 1. Collect `paramsFromForm` keys from the current form values.\n * 2. Merge with `paramsStatic`.\n * 3. Call `trpc.addons.custom({addonId, action, input}).query()`.\n * 4. Map each result item via `mapOption` → `{value, label, description?}`.\n * 5. If `refreshOn` is set, re-fetch when any listed form key changes.\n *\n * Example (cloudflare-tunnel zone picker):\n * { type: 'addon-action-select',\n * key: 'zoneId', label: 'Zone',\n * addonId: 'cloudflare-tunnel',\n * action: 'listZones',\n * paramsFromForm: { token: 'apiToken' },\n * refreshOn: ['apiToken'],\n * mapOption: { value: 'id', label: 'name' } }\n */\nexport interface ConfigAddonActionSelectField extends ConfigFieldBase {\n type: 'addon-action-select'\n addonId: string\n action: string\n /** Map form-value keys → action input keys. */\n paramsFromForm?: Readonly<Record<string, string>>\n /** Static params merged into the action input. */\n paramsStatic?: Readonly<Record<string, unknown>>\n /** Form keys that trigger an options refresh when changed. */\n refreshOn?: readonly string[]\n /** Map a result row to the dropdown option shape. */\n mapOption: {\n readonly value: string\n readonly label: string\n readonly description?: string\n }\n /** Optional message shown when the form is missing required params (e.g. token). */\n emptyParamsMessage?: string\n /** Optional message shown when the action returns no results. */\n emptyResultsMessage?: string\n}\n\n/**\n * Button that invokes an addon customAction. Used for \"Verify token /\n * Test connection / Refresh credentials\" affordances inside addon\n * settings panels. The form renderer surfaces success + error inline.\n */\nexport interface ConfigAddonActionButtonField extends ConfigFieldBase {\n type: 'addon-action-button'\n addonId: string\n action: string\n /** Visible label. */\n buttonLabel: string\n /** Visual variant. */\n variant?: 'default' | 'primary' | 'danger'\n /** Map form-value keys → action input keys. */\n paramsFromForm?: Readonly<Record<string, string>>\n /** Static params merged into the action input. */\n paramsStatic?: Readonly<Record<string, unknown>>\n /** Toast/inline success message template. `{key}` placeholders are\n * resolved against the action result. */\n successMessage?: string\n /** Confirmation prompt before executing. */\n confirmMessage?: string\n}\n\n/**\n * Button that invokes a DEVICE custom action (the device equivalent of\n * `addon-action-button`). The deviceId comes from the form context, so it is\n * NOT a field. The form renderer dispatches it via\n * `trpc.deviceManager.runDeviceAction({ deviceId, action, input })`.\n */\nexport interface ConfigDeviceActionButtonField extends ConfigFieldBase {\n type: 'device-action-button'\n action: string\n buttonLabel: string\n variant?: 'default' | 'primary' | 'danger'\n /** Map form-value keys → action input keys. */\n paramsFromForm?: Readonly<Record<string, string>>\n /** Static params merged into the action input. */\n paramsStatic?: Readonly<Record<string, unknown>>\n successMessage?: string\n confirmMessage?: string\n}\n\n/**\n * Describes an async resolver that the form renderer should call to\n * fetch deferred-load data a field depends on (e.g. the addon catalog\n * for a pipeline-editor, a dynamic options list for a select, …).\n *\n * The renderer dispatches through `client.trpc[capName][methodName]\n * .query(input)` — the field declares WHICH cap + method + input to\n * call, and the renderer stays oblivious to the endpoint naming.\n * Results are cached client-side keyed by `(capName, methodName,\n * input)` so two fields pointing at the same resolver deduplicate\n * automatically.\n *\n * Not an endpoint to arbitrary HTTP — the tRPC proxy gates it to the\n * server's declared cap surface + each cap's auth rules, same as\n * every other `.query()` call the UI makes.\n */\nexport interface AsyncResolverRef {\n /** tRPC cap namespace (e.g. `pipelineExecutor`, `pipelineOrchestrator`). */\n readonly capName: string\n /** Method on that cap — must be a `.query()` (no mutations via resolvers). */\n readonly methodName: string\n /** Input payload passed verbatim; serialised into the React Query key. */\n readonly input?: Readonly<Record<string, unknown>>\n}\n\n/**\n * Camera pipeline editor field (stateless-pipeline Phase 6, option B).\n *\n * The FormBuilder renders this as the rich `PipelineBuilder` composite\n * (step tree + engine picker + template picker) instead of a flat\n * input. `value` is always a fully-resolved `CameraPipelineConfig` —\n * when the camera has no persisted pipeline, the contributor\n * (orchestrator) fills it with the cluster default server-side so\n * the renderer stays dumb about nullability.\n *\n * `nodeId` names the runner node whose addon catalog powers the\n * editor. It's exposed explicitly (rather than buried inside the\n * resolver) for diagnostics, UI labels, and cache keying. The\n * catalog itself isn't embedded — `catalogResolver` tells the\n * renderer how to lazy-load it via the shared resolver hook, which\n * React Query caches once per `(capName, methodName, input)`. That\n * way 50 cameras assigned to the same node don't each trigger 50\n * catalog fetches.\n *\n * Templates are NOT described by a resolver — they're a hub-wide\n * library fetched in one place by the editor directly.\n */\nexport interface ConfigPipelineEditorField extends ConfigFieldBase {\n type: 'pipeline-editor'\n /** Runner node whose catalog powers the editor. */\n readonly nodeId: string\n /** The camera this field edits — used by the renderer to fetch per-camera settings. */\n readonly deviceId: number\n /** How to fetch the addon catalog for this node. */\n readonly catalogResolver: AsyncResolverRef\n}\n\n/**\n * Generic widget field — addon-contributed widget mounted by the\n * shared `<WidgetSlot>` runtime via the `WidgetRegistry`.\n *\n * The form-builder reads `widgetId` as the public widget identifier\n * (`<addonId>/<stableId>`) and forwards `widgetConfig` as `props.config`\n * to the widget. Widget fields go through the generic `WidgetRegistry`\n * without any per-type renderer registration in admin-ui.\n *\n * `key` is the form-field's unique identifier (kept distinct from the\n * widget identifier so the same widget can be mounted twice in the\n * same form). `widgetId` is the public id resolved against the\n * WidgetRegistry.\n *\n * Field carries no stored value — the widget owns its own state via\n * DeviceProxy / runtime-state hooks. Placed in\n * `ConfigFieldWithValue` only so the discriminated-union round-trip\n * through `hydrateSchema` stays homogeneous (`value: null`).\n */\nexport interface ConfigWidgetField extends ConfigFieldBase {\n readonly type: 'widget'\n /** `<addonId>/<stableId>` — resolved via the WidgetRegistry. */\n readonly widgetId: string\n /** Per-instance config payload forwarded to the widget as `props.config`. */\n readonly widgetConfig?: Readonly<Record<string, unknown>>\n}\n\n\n// IConfigurable is no longer a separate interface — config methods are part of ICamstackAddon.\n\n// ---------------------------------------------------------------------------\n// Schema + values fused (\"hydrated\") for the new three-level settings API\n// ---------------------------------------------------------------------------\n//\n// `ConfigUISchemaWithValues` is the shape returned by the new\n// `getAddonSettings() / getGlobalSettings() / getDeviceSettings()` family of\n// methods on `ICamstackAddon`. Each leaf field carries its *current* value\n// inline so the admin UI form builder can render in one pass without having\n// to cross-reference a separate `values` object.\n//\n// Hydration rule (applied by `hydrateSchema` below):\n// value = storedValues[key] ?? field.default ?? null\n//\n// `value` is NEVER `undefined` — consumers can rely on `in` / `??` without\n// surprises. Fields that don't carry a value (separator, info) are returned\n// unchanged.\n\n/** A `ConfigField` with its current value attached inline. */\nexport type ConfigFieldWithValue =\n | (ConfigTextField & { readonly value: unknown })\n | (ConfigNumberField & { readonly value: unknown })\n | (ConfigBooleanField & { readonly value: unknown })\n | (ConfigSelectField & { readonly value: unknown })\n | (ConfigMultiSelectField & { readonly value: unknown })\n | (ConfigTimezoneField & { readonly value: unknown })\n | (ConfigDateTimeField & { readonly value: unknown })\n | (ConfigColorField & { readonly value: unknown })\n | (ConfigPasswordField & { readonly value: unknown })\n | (ConfigTextAreaField & { readonly value: unknown })\n | (ConfigSliderField & { readonly value: unknown })\n | (ConfigTagsField & { readonly value: unknown })\n | (ConfigGroupFieldWithValue)\n | (ConfigSubTabsFieldWithValue)\n | ConfigSeparatorField\n | ConfigInfoField\n | ConfigQrCodeField\n | ConfigObjectArrayField\n | (ConfigEditableArrayField & { readonly value: unknown })\n | (ConfigModelSelectorField & { readonly value: unknown })\n | (ConfigStorageLocationField & { readonly value: unknown })\n | (ConfigProbeField & { readonly value: unknown })\n | (ConfigButtonField) // buttons are actions, not values\n | (ConfigPipelineEditorField & { readonly value: unknown })\n | (ConfigNodeSelectField & { readonly value: unknown })\n | (ConfigNodeMultiSelectField & { readonly value: unknown })\n | ConfigWidgetField // widgets manage their own state; no form value\n | (ConfigAddonActionSelectField & { readonly value: unknown })\n | ConfigAddonActionButtonField // buttons are actions, not values\n | ConfigDeviceActionButtonField // buttons are actions, not values\n\n/** Recursive version of `ConfigGroupField` with hydrated child fields. */\nexport interface ConfigGroupFieldWithValue extends ConfigFieldBase {\n readonly type: 'group'\n readonly fields: readonly ConfigFieldWithValue[]\n readonly style?: 'card' | 'inline' | 'accordion'\n readonly defaultCollapsed?: boolean\n readonly value?: undefined // groups don't carry their own value\n}\n\n/** Hydrated sibling of `ConfigSubTabDefinition` — fields inside each\n * sub-tab carry their resolved values. */\nexport interface ConfigSubTabDefinitionWithValue {\n readonly id: string\n readonly label: string\n readonly icon?: string\n readonly badge?: string\n readonly fields: readonly ConfigFieldWithValue[]\n}\n\n/** Recursive version of `ConfigSubTabsField` with hydrated child fields. */\nexport interface ConfigSubTabsFieldWithValue extends ConfigFieldBase {\n readonly type: 'sub-tabs'\n readonly tabs: readonly ConfigSubTabDefinitionWithValue[]\n readonly value?: undefined // sub-tabs are layout, not a value\n}\n\nexport interface ConfigSectionWithValues extends Omit<ConfigSection, 'fields'> {\n /**\n * Array kept mutable (not `readonly`) to stay assignable to the Zod-inferred\n * wire shape produced by `DEVICE_SETTINGS_CONTRIBUTION_METHODS.getDeviceSettingsContribution.output`.\n * Consumers treat it as immutable by convention — mutation is never\n * expected and would be a bug.\n */\n fields: ConfigFieldWithValue[]\n}\n\nexport interface ConfigUISchemaWithValues {\n /** See `ConfigSectionWithValues.fields` — kept mutable for Zod wire compat. */\n tabs?: ConfigTabDeclaration[]\n sections: ConfigSectionWithValues[]\n}\n\n// ---------------------------------------------------------------------------\n// `hydrateSchema` — backend-side helper\n// ---------------------------------------------------------------------------\n\n/**\n * Field types that never carry a value (separator, info, button). Used by\n * `hydrateSchema` to skip the `value` injection for structural-only fields.\n */\nfunction isValuelessField(\n field: ConfigField,\n): field is ConfigSeparatorField | ConfigInfoField | ConfigQrCodeField | ConfigButtonField | ConfigObjectArrayField | ConfigWidgetField | ConfigAddonActionButtonField | ConfigDeviceActionButtonField {\n return field.type === 'separator'\n || field.type === 'info'\n || field.type === 'qr-code'\n || field.type === 'button'\n || field.type === 'object-array'\n || field.type === 'widget'\n || field.type === 'addon-action-button'\n || field.type === 'device-action-button'\n}\n\n/**\n * Merge a `ConfigUISchema` with a raw `values` record into a\n * `ConfigUISchemaWithValues`. Used by every `get*Settings` backend endpoint\n * before returning to the admin UI. Groups are walked recursively.\n *\n * For each leaf field:\n * - structural fields (`separator`, `info`, `button`) pass through unchanged\n * - other fields get `value = values[key] ?? field.default ?? null`\n *\n * Unknown keys in `values` (keys not declared in the schema) are silently\n * ignored — they don't contribute to the output. Missing keys fall back to\n * the schema default or `null`. This mirrors the old backend behaviour where\n * `FormBuilder` rendered `values[key] ?? field.default`.\n */\nexport function hydrateSchema(\n schema: ConfigUISchema,\n values: Record<string, unknown>,\n): ConfigUISchemaWithValues {\n return {\n ...(schema.tabs ? { tabs: [...schema.tabs] } : {}),\n sections: schema.sections.map((section) => ({\n ...section,\n fields: section.fields.map((field) => hydrateField(field, values)),\n })),\n }\n}\n\nfunction hydrateField(\n field: ConfigField,\n values: Record<string, unknown>,\n): ConfigFieldWithValue {\n // Structural fields (separator / info / button) pass through unchanged —\n // they carry no stored value.\n if (isValuelessField(field)) {\n return field\n }\n\n // Groups are recursive — hydrate their children but don't attach a top-level value.\n if (field.type === 'group') {\n const hydratedChildren = field.fields.map((child) => hydrateField(child, values))\n const out: ConfigGroupFieldWithValue = {\n ...field,\n fields: hydratedChildren,\n }\n return out\n }\n\n // Sub-tabs are recursive too — hydrate fields inside every sub-tab but\n // skip the top-level value (sub-tabs are layout, not a value).\n if (field.type === 'sub-tabs') {\n const hydratedTabs: ConfigSubTabDefinitionWithValue[] = field.tabs.map((tab) => ({\n ...tab,\n fields: tab.fields.map((child) => hydrateField(child, values)),\n }))\n const out: ConfigSubTabsFieldWithValue = {\n ...field,\n tabs: hydratedTabs,\n }\n return out\n }\n\n // Leaf valued field. After the guards above, `field` is narrowed to every\n // variant of ConfigField that extends ConfigFieldBase (i.e. has `key` +\n // optional `default`), so we can read them directly.\n const key: string = field.key\n const storedValue = Object.prototype.hasOwnProperty.call(values, key) ? values[key] : undefined\n const defaultValue = field.default\n\n // Multiple-mode: normalise to an array of `max(min, storedLen)` items.\n // Missing slots are padded with the field's `itemDefault` → `default`\n // → type-appropriate zero value so the renderer can always assume the\n // value is an array of exactly the right length.\n if (field.multiple) {\n const stored: readonly unknown[] = Array.isArray(storedValue)\n ? storedValue\n : (storedValue !== undefined && storedValue !== null ? [storedValue] : [])\n const itemFallback = field.multiple.itemDefault !== undefined\n ? field.multiple.itemDefault\n : (defaultValue !== undefined ? defaultValue : typeOf(field) === 'string' ? '' : null)\n const minCount = Math.max(field.multiple.min, stored.length)\n const items: unknown[] = []\n for (let i = 0; i < minCount; i++) {\n items.push(i < stored.length ? stored[i] : itemFallback)\n }\n return { ...field, value: items }\n }\n\n const rawValue: unknown = storedValue !== undefined\n ? storedValue\n : (defaultValue !== undefined ? defaultValue : null)\n\n // Secret masking: password fields NEVER carry the stored secret value\n // in the hydrated schema. The UI renders an empty input; the save path\n // only writes a new value when the operator actively types one.\n //\n // Why empty string (not a sentinel like '__unchanged__'):\n // - The form-controller compares effective[key] === newValue before\n // adding a key to pendingEdits. As long as the user has not typed\n // anything, the password field stays out of the pending set and is\n // never submitted to updateDeviceField — so the real secret is\n // preserved on every save of other fields.\n // - When the operator types a new password, it differs from '' and\n // enters pendingEdits normally. The save path receives the actual\n // new value and writes it.\n // - A write of '' (deliberate clear) is the only ambiguous case.\n // Clearing a password is a legitimate operator action (e.g. RTSP\n // camera with no password); we preserve that semantics rather than\n // silently blocking it.\n if (field.type === 'password') {\n return { ...field, value: '' }\n }\n\n // Textarea with `isJson: true` serialises the stored object/array as\n // pretty JSON so the human-editable input. The save path is\n // expected to `JSON.parse` before forwarding the patch to the writer.\n const value = (field.type === 'textarea' && field.isJson && rawValue !== null && typeof rawValue === 'object')\n ? JSON.stringify(rawValue, null, 2)\n : rawValue\n // Spread-with-added-value preserves the discriminated-union variant.\n const hydrated = { ...field, value }\n return hydrated\n}\n\n/**\n * Rough \"value family\" classifier used by `hydrateField`'s multiple\n * fallback to pick a sensible zero-value when no `itemDefault` / no\n * field `default` / no stored value is available.\n */\nfunction typeOf(field: ConfigField): 'string' | 'number' | 'boolean' | 'other' {\n switch (field.type) {\n case 'text':\n case 'textarea':\n case 'password':\n case 'color':\n case 'probe':\n case 'timezone':\n case 'datetime':\n return 'string'\n case 'number':\n case 'slider':\n return 'number'\n case 'boolean':\n return 'boolean'\n default:\n return 'other'\n }\n}\n","/** Shared Zod schemas used across streaming capabilities. */\n\nimport { z } from 'zod'\nimport type { FrameHandle } from '../../interfaces/frame-handle.js'\n\n// ── Broker profile slots ─────────────────────────────────────────────\n//\n// Camstack supports at most 3 system-wide quality profiles per device:\n// `high`, `mid`, `low`. Valid combinations: {high,mid,low}, {high,low},\n// {mid}. Every consumer (WebRTC, recording, pipeline, detection, frame\n// transport) addresses a device's stream via `${deviceId}/${profile}`;\n// the camera's physical cam-stream ids never leak past the broker.\n\nexport const CamProfileSchema = z.enum(['high', 'mid', 'low'])\nexport type CamProfile = z.infer<typeof CamProfileSchema>\n\n/** Canonical ordering. Hard-coded; never sorted. */\nexport const CAM_PROFILE_ORDER = ['high', 'mid', 'low'] as const\n\n// ── Published cam stream (broker-owned registry) ─────────────────────\n//\n// A camera's physical stream, published to the broker via\n// `streamBroker.publishCameraStream(...)`. The provider owns the\n// lifecycle (re-publishes on boot, retracts on removal). The broker\n// owns the registry: each entry is the pool of options an operator or\n// addon can assign to a profile slot.\n//\n// Two kinds:\n// - `pull-*`: the broker dials the URL (RTSP / RTMP / HTTP).\n// - `push-annexb`: the provider emits Annex-B packets. The broker\n// signals demand via `stream-broker.onCamStreamDemand` events so\n// push-capable cams (e.g. Reolink Baichuan) only wake when a\n// profile is actively consuming them.\n\nexport const CamStreamKindSchema = z.enum([\n 'pull-rtsp',\n 'pull-rtmp',\n 'pull-http',\n 'pull-rfc4571',\n 'push-annexb',\n /** Broker-spawned ffmpeg transcode plane — reads from a source cam-stream\n * and writes a re-encoded RTP plane. The broker routes demand signals to\n * the source broker; the transcode process is single-flighted per\n * identical EncodeProfile so multiple derived subscribers share one ffmpeg\n * process. */\n 'derived',\n])\nexport type CamStreamKind = z.infer<typeof CamStreamKindSchema>\n\nexport const CamStreamResolutionSchema = z.object({\n width: z.number().int().positive(),\n height: z.number().int().positive(),\n})\n\nexport const CameraStreamSchema = z.object({\n /** Stable, provider-assigned id unique within the (deviceId) scope. */\n camStreamId: z.string().min(1),\n deviceId: z.number().int().nonnegative(),\n kind: CamStreamKindSchema,\n /** Required for pull-* kinds. Ignored for push-annexb. */\n url: z.string().optional(),\n codec: z.string().optional(),\n resolution: CamStreamResolutionSchema.optional(),\n fps: z.number().positive().optional(),\n /** Human label surfaced in the Admin UI \"Camera Stream\" dropdown. */\n label: z.string().optional(),\n /**\n * Device-level features the publisher advertised (e.g. `battery-operated`).\n * The broker, snapshot orchestrator, and prebuffer manager all consult\n * this list to derive policy — relaxed stall watchdog for battery\n * cams, prebuffer off by default, longer snapshot rate-limit, etc.\n *\n * Single source of truth replacing per-stream flags like the\n * historical `allowStall`: if the publisher knows the camera is\n * battery-powered, every downstream service derives the right policy\n * from this list.\n */\n deviceFeatures: z.array(z.string()).optional(),\n /**\n * Whether this stream participates in the broker's automatic profile\n * assignment (`computeInitialAssignment`). Defaults to `true`. Publishers\n * use `false` when they want a stream to be SELECTABLE in the UI but not\n * picked by default — e.g. Reolink publishes its native Baichuan streams\n * as `autoEligible: true` (the recommended path) and its RTSP / RTMP\n * mirrors as `autoEligible: false` (still pickable per slot, just not\n * the auto choice). Manual `assignProfile` calls remain valid for\n * non-eligible streams.\n */\n autoEligible: z.boolean().optional(),\n /**\n * Transport-specific opaque metadata. The broker passes it through to\n * the source reader without inspecting it. Currently used by\n * `pull-rfc4571` streams to carry the upstream SDP (so the reader can\n * route RTP packets to the right depacketizer without an in-band\n * DESCRIBE phase). Other kinds typically leave it undefined.\n */\n metadata: z.record(z.string(), z.unknown()).optional(),\n})\nexport type CameraStream = z.infer<typeof CameraStreamSchema>\n\n// ── Profile slot view ────────────────────────────────────────────────\n//\n// Returned by the broker's `listAllProfileSlots` / the device-scoped\n// `camera-streams.getBrokerStreams`. Describes one of the up-to-3\n// system profile slots for a device: which cam stream is its source,\n// runtime status, and public addressing info.\n\nexport const ProfileSlotStatusSchema = z.enum([\n 'unassigned',\n 'idle',\n 'connecting',\n 'streaming',\n 'error',\n])\nexport type ProfileSlotStatus = z.infer<typeof ProfileSlotStatusSchema>\n\nexport const ProfileSlotSchema = z.object({\n deviceId: z.number().int().nonnegative(),\n profile: CamProfileSchema,\n /** Broker id the rest of the system addresses: `${deviceId}/${profile}`. */\n brokerId: z.string(),\n /** `null` when the profile is unassigned. */\n sourceCamStreamId: z.string().nullable(),\n status: ProfileSlotStatusSchema,\n resolution: CamStreamResolutionSchema.optional(),\n codec: z.string().optional(),\n preBufferSec: z.number().nonnegative().optional(),\n errorMessage: z.string().optional(),\n})\nexport type ProfileSlot = z.infer<typeof ProfileSlotSchema>\n\n// ── Canonical broker-id addressing ───────────────────────────────────\n//\n// Every consumer (WebRTC, recording, pipeline, detection …) addresses a\n// device stream as `${deviceId}/${profile}`. Build/parse it ONLY through\n// these helpers — never hand-concatenate the string and never address a\n// physical cam-stream id (`native:main`, `derived:…`, `adaptive`), which\n// stays broker-internal. Centralising the convention is what stops the\n// recurring \"wrong profile / wrong brokerId\" class of bug.\n\n/** The canonical consumer-facing broker id for a device profile. */\nexport function makeProfileBrokerId(deviceId: number, profile: CamProfile): string {\n return `${deviceId}/${profile}`\n}\n\n/**\n * The broker id keying a physical SOURCE stream: `${deviceId}/${camStreamId}`.\n * This is the broker's internal source key (`brokerIdFor` in the manager) — a\n * `camStreamId` like `native:main` — as opposed to the public profile alias\n * {@link makeProfileBrokerId}. Used to resolve a source's restream endpoint\n * (e.g. routing a transcode's ffmpeg input through the broker so it rides the\n * single source dial instead of opening a second camera connection).\n */\nexport function makeSourceBrokerId(deviceId: number, camStreamId: string): string {\n return `${deviceId}/${camStreamId}`\n}\n\n/**\n * Inverse of {@link makeProfileBrokerId}. Returns `null` when the string is\n * not a canonical `${deviceId}/${profile}` id — e.g. a broker-internal\n * cam-stream id (`5/native:main`), a derived/adaptive ref, or a malformed\n * value. So a caller can safely distinguish \"addresses a public profile\"\n * from \"addresses something broker-internal\".\n */\nexport function parseProfileBrokerId(\n brokerId: string,\n): { deviceId: number; profile: CamProfile } | null {\n const slash = brokerId.indexOf('/')\n if (slash <= 0) return null\n const idPart = brokerId.slice(0, slash)\n const profilePart = brokerId.slice(slash + 1)\n if (!/^\\d+$/.test(idPart)) return null\n const parsed = CamProfileSchema.safeParse(profilePart)\n if (!parsed.success) return null\n return { deviceId: Number(idPart), profile: parsed.data }\n}\n\n/**\n * The profile slots worth consuming/recording: ASSIGNED only\n * (`sourceCamStreamId != null`), DEDUPED by physical source so the same\n * camera encoder is never subscribed/recorded twice, ordered high→mid→low.\n * Optionally scoped to one `deviceId`. Pure; never mutates the input.\n *\n * Recording `main` and `mid` when both point at the same `sourceCamStreamId`\n * would dial the camera's internal stream twice for no benefit — this is the\n * dedup that prevents that.\n */\nexport function selectAssignedProfileSlots(\n slots: readonly ProfileSlot[],\n deviceId?: number,\n): ProfileSlot[] {\n const ordered = [...slots]\n .filter((s) => deviceId === undefined || s.deviceId === deviceId)\n .sort((a, b) => CAM_PROFILE_ORDER.indexOf(a.profile) - CAM_PROFILE_ORDER.indexOf(b.profile))\n const seenSources = new Set<string>()\n const out: ProfileSlot[] = []\n for (const s of ordered) {\n const src = s.sourceCamStreamId\n if (src === null) continue\n if (seenSources.has(src)) continue\n seenSources.add(src)\n out.push(s)\n }\n return out\n}\n\n/**\n * Zod schema for StreamSourceEntry — the canonical stream descriptor\n * exposed by ICameraDevice.getStreamSources() and consumed by the broker.\n */\nexport const StreamSourceEntrySchema = z.object({\n id: z.string(),\n label: z.string(),\n protocol: z.enum(['rtsp', 'rtmp', 'annexb', 'http-mjpeg', 'webrtc', 'custom']),\n url: z.string().optional(),\n resolution: z.object({ width: z.number(), height: z.number() }).readonly().optional(),\n fps: z.number().optional(),\n bitrate: z.number().optional(),\n codec: z.string().optional(),\n profileHint: CamProfileSchema.optional(),\n})\n\nexport const StreamSourceSchema = z.object({\n type: z.string(),\n url: z.string(),\n videoCodec: z.string().optional(),\n audioCodec: z.string().optional(),\n metadata: z.record(z.string(), z.unknown()).readonly().optional(),\n})\n\nexport const EncodedPacketSchema = z.object({\n type: z.enum(['video', 'audio']),\n data: z.instanceof(Uint8Array),\n pts: z.number(),\n dts: z.number(),\n keyframe: z.boolean(),\n codec: z.string(),\n})\n\nexport const DecodedFrameSchema = z.object({\n data: z.instanceof(Uint8Array),\n width: z.number(),\n height: z.number(),\n format: z.enum(['jpeg', 'rgb', 'bgr', 'yuv420', 'gray']),\n timestamp: z.number(),\n})\n\n/**\n * Wire schema for `FrameHandle` — a zero-pixel, serialisable reference to a\n * frame in a shared-memory ring (Phase 5 / D9). Mirrors the `FrameHandle` TS\n * interface in `interfaces/frame-handle.ts` field-for-field so a decoder cap\n * method (`pullHandles`) can carry handles over tRPC / Moleculer.\n *\n * The `satisfies` assertion below pins this schema to the interface: if a\n * field is added to / removed from `FrameHandle` without a matching schema\n * edit, `z.infer<typeof FrameHandleSchema>` stops being assignable to\n * `FrameHandle` and the build fails — no silent drift.\n */\nexport const FrameHandleSchema = z.object({\n shmId: z.string(),\n slot: z.number().int().nonnegative(),\n seq: z.number().int().nonnegative(),\n width: z.number().int().positive(),\n height: z.number().int().positive(),\n format: z.enum(['jpeg', 'rgb', 'bgr', 'yuv420', 'gray']),\n pts: z.number(),\n byteLength: z.number().int().nonnegative(),\n nodeId: z.string(),\n slotCount: z.number().int().positive(),\n})\n\n/**\n * Compile-time guard: `z.infer<typeof FrameHandleSchema>` must be assignable\n * to `FrameHandle` (and vice versa). The two `satisfies` checks fail to\n * compile on any field drift between the schema and the interface.\n */\ntype FrameHandleInferred = z.infer<typeof FrameHandleSchema>\nconst _frameHandleSchemaMatchesInterface = {} as FrameHandleInferred satisfies FrameHandle\nconst _frameHandleInterfaceMatchesSchema = {} as FrameHandle satisfies FrameHandleInferred\nvoid _frameHandleSchemaMatchesInterface\nvoid _frameHandleInterfaceMatchesSchema\n\n/**\n * Pixel format a frame-handle subscriber can request from the broker\n * (Phase 5 / D9). The packed, raster subset of `FrameFormat` — the formats a\n * `frameSink: 'shm'` decoder session can write into a `FrameRing` slot.\n * `jpeg` is excluded: a variable-length stream is not a fixed-stride ring\n * payload, and no decoded-frame consumer requests it over the shm plane.\n */\nexport const FrameHandleFormatSchema = z.enum(['rgb', 'bgr', 'yuv420', 'gray'])\nexport type FrameHandleFormat = z.infer<typeof FrameHandleFormatSchema>\n\n/**\n * Input for `stream-broker.subscribeFrames` (Phase 5 / D9). A consumer asks the\n * broker for a `FrameHandle` stream of one `format`; the broker maintains one\n * shared-memory ring per `(brokerId, format)` actually requested, so a `gray`\n * subscriber (motion) and an `rgb` subscriber (detection) each read the format\n * they asked for with no broker-side conversion.\n */\nexport const SubscribeFramesInputSchema = z.object({\n brokerId: z.string(),\n format: FrameHandleFormatSchema,\n /**\n * Optional reader-side cadence hint in frames per second. The broker does\n * NOT throttle — latest-wins ring reads drop frames implicitly for a slow\n * consumer. The value is echoed back in `SubscribeFramesResult.maxFps` so\n * the consumer can pace its own `pullFrameHandles` polling.\n */\n maxFps: z.number().positive().optional(),\n /** Short caller-identity tag (`motion`, `detection`, …) for diagnostics. */\n tag: z.string().optional(),\n})\nexport type SubscribeFramesInput = z.infer<typeof SubscribeFramesInputSchema>\n\n/**\n * Result of `stream-broker.subscribeFrames`. The consumer then polls\n * `pullFrameHandles({ subscriptionId, maxCount })` and feeds each returned\n * `FrameHandle` to a `FrameRingReader`.\n */\nexport const SubscribeFramesResultSchema = z.object({\n /** Opaque id the consumer passes to `pullFrameHandles` / `unsubscribeFrames`. */\n subscriptionId: z.string(),\n /** Reader-side cadence hint (frames/s) — echoes `SubscribeFramesInput.maxFps`. */\n maxFps: z.number().nonnegative(),\n})\nexport type SubscribeFramesResult = z.infer<typeof SubscribeFramesResultSchema>\n\n/**\n * Wire schema for a decoded audio chunk (Phase 5 / D9). Mirrors the\n * `DecodedAudioChunk` TS interface in `interfaces/stream-broker.ts`: PCM\n * sample bytes plus the track parameters a consumer needs to interpret them.\n *\n * Audio chunks are tiny (a ~500ms AudioCodecSession window is a few KB of\n * Float32 PCM), so unlike video frames they ship their bytes INLINE over\n * tRPC / Moleculer — no shared-memory plane. `data` is typed `Uint8Array`\n * (the wire-serialisable supertype of `Buffer`) to match `DecodedFrameSchema`\n * / `EncodedPacketSchema`'s precedent; a `Buffer` is assignable to it.\n */\nexport const DecodedAudioChunkSchema = z.object({\n data: z.instanceof(Uint8Array),\n sampleRate: z.number().int().positive(),\n channels: z.number().int().positive(),\n timestamp: z.number(),\n})\nexport type DecodedAudioChunkWire = z.infer<typeof DecodedAudioChunkSchema>\n\n/**\n * Input for `stream-broker.subscribeAudioChunks` (Phase 5 / D9). The\n * handle-free, ship-bytes-inline analogue of `subscribeFrames`: a consumer\n * asks the broker for the decoded audio-chunk stream of one broker; the\n * broker keeps a per-subscription bounded FIFO queue the consumer drains via\n * `pullAudioChunks`.\n */\nexport const SubscribeAudioChunksInputSchema = z.object({\n brokerId: z.string(),\n /** Short caller-identity tag (`audio-analyzer`, …) for `listClients`. */\n tag: z.string().optional(),\n})\nexport type SubscribeAudioChunksInput = z.infer<typeof SubscribeAudioChunksInputSchema>\n\n/** Result of `stream-broker.subscribeAudioChunks`. */\nexport const SubscribeAudioChunksResultSchema = z.object({\n /** Opaque id passed to `pullAudioChunks` / `unsubscribeAudioChunks`. */\n subscriptionId: z.string(),\n})\nexport type SubscribeAudioChunksResult = z.infer<typeof SubscribeAudioChunksResultSchema>\n\nexport const BrokerStatusSchema = z.enum(['idle', 'connecting', 'streaming', 'error', 'stopped'])\n\nexport const BrokerStatsSchema = z.object({\n status: BrokerStatusSchema,\n inputFps: z.number(),\n decodeFps: z.number(),\n encodedSubscribers: z.number(),\n decodedSubscribers: z.number(),\n uptimeMs: z.number(),\n bitrateKbps: z.number(),\n idrIntervalMs: z.number(),\n codec: z.string().optional(),\n totalBytes: z.number(),\n packetCount: z.number(),\n rtspClients: z.number(),\n pipeClients: z.number(),\n preBufferSec: z.number(),\n preBufferMs: z.number(),\n preBufferPackets: z.number(),\n /**\n * Moleculer node id of the decoder provider currently servicing this\n * stream's decoded subscribers. `null` until the deferred decoder is\n * created (no decoded clients yet, or codec not detected). Surfaces the\n * runtime decoder placement so the UI can show \"Decoder: <agent>\" without\n * a separate cap call per broker.\n */\n decoderNodeId: z.string().nullable(),\n /**\n * Detected audio track parameters from the RTSP DESCRIBE / SDP. `null`\n * when the stream has no audio track or the broker is in cold start.\n * `supported = false` means the codec was detected but the local\n * decoder pipeline cannot produce PCM chunks (e.g. AAC without the\n * AAC pipeline wired). Surfaced in the UI device-overview so operators\n * can pre-pick the audio-analysis model that matches the codec.\n */\n audio: z.object({\n codec: z.string(),\n sampleRate: z.number(),\n channels: z.number(),\n supported: z.boolean(),\n }).nullable().optional(),\n})\n\n/**\n * Exporter-facing \"profile restream\" entry. Returned by\n * `cameraStreams.getProfileRtspEntries` — one per ASSIGNED profile slot\n * (high/mid/low). `brokerId` is the PROFILE-keyed broker id\n * (`${deviceId}/${profile}`, e.g. `15/high`); its `url` is a broker\n * RTSP restream that aliases the profile's assigned source broker, so\n * every consumer dialling a profile converges on the same single pull.\n * `codec`/`resolution` describe the assigned SOURCE camStream (for the\n * `auto` resolution-closest pick). Distinct from `RtspRestreamEntry`\n * (raw per-camStream, live-view only).\n */\nexport const ProfileRtspEntrySchema = z.object({\n profile: CamProfileSchema,\n /** Profile-keyed broker id, format `${deviceId}/${profile}` (e.g. `\"15/high\"`). */\n brokerId: z.string(),\n url: z.string(),\n mutedUrl: z.string(),\n enabled: z.boolean(),\n codec: z.string().optional(),\n resolution: CamStreamResolutionSchema.optional(),\n})\nexport type ProfileRtspEntry = z.infer<typeof ProfileRtspEntrySchema>\n\n","import { z } from 'zod'\nimport { CamProfileSchema } from '../capabilities/schemas/streaming-shared.js'\n\n/**\n * Numeric day-of-week: 0 = Sunday … 6 = Saturday (matches `Date.getDay`).\n * Named `RecordingWeekday` to avoid collision with the string-union\n * `Weekday` exported from `interfaces/timezones.ts`.\n */\nexport const RecordingWeekdaySchema = z.number().int().min(0).max(6)\nexport type RecordingWeekday = z.infer<typeof RecordingWeekdaySchema>\n\nconst HHMM = /^([01]\\d|2[0-3]):[0-5]\\d$/\n\nexport const RecordingScheduleSchema = z.discriminatedUnion('kind', [\n z.object({ kind: z.literal('always') }),\n z.object({\n kind: z.literal('timeOfDay'),\n start: z.string().regex(HHMM),\n end: z.string().regex(HHMM),\n /** Restrict to these weekdays; omit = every day. */\n days: z.array(RecordingWeekdaySchema).optional(),\n }),\n])\nexport type RecordingSchedule = z.infer<typeof RecordingScheduleSchema>\n\nexport const RecordingModeSchema = z.enum(['continuous', 'onMotion', 'onAudioThreshold'])\nexport type RecordingMode = z.infer<typeof RecordingModeSchema>\n\nexport const RecordingRuleSchema = z.object({\n schedule: RecordingScheduleSchema,\n mode: RecordingModeSchema,\n /** Seconds of footage to retain BEFORE a trigger (applied at keep/discard). */\n preBufferSec: z.number().min(0).default(0),\n /** Keep recording until this many seconds after the last trigger. */\n postBufferSec: z.number().min(0).default(0),\n /** Each new trigger restarts the post-buffer window. */\n resetTimeoutOnNewEvent: z.boolean().default(true),\n /** onAudioThreshold only — dBFS level that counts as a trigger. */\n thresholdDbfs: z.number().optional(),\n})\nexport type RecordingRule = z.infer<typeof RecordingRuleSchema>\n\n/**\n * Per-device retention overrides. Every field is optional; an unset or `0`\n * value inherits the node-wide recorder default. Only footage-lifetime limits\n * live per-camera: `maxAgeDays` and `maxSizeGb`. The disk-occupancy threshold\n * (when the volume is too full to keep recording) is NOT a per-camera concern —\n * it belongs to the StorageLocation (`StorageLocation.config.minFreePercent`),\n * shared by every camera writing to that volume.\n */\nexport const RecordingRetentionSchema = z.object({\n maxAgeDays: z.number().min(0).optional(),\n maxSizeGb: z.number().min(0).optional(),\n})\nexport type RecordingRetention = z.infer<typeof RecordingRetentionSchema>\n\n/** The full per-camera recording intent — the wire shape of a RecordingTarget. */\nexport const RecordingConfigSchema = z.object({\n enabled: z.boolean(),\n profiles: z.array(CamProfileSchema).optional(),\n segmentSeconds: z.number().int().positive().optional(),\n rules: z.array(RecordingRuleSchema).optional(),\n retention: RecordingRetentionSchema.optional(),\n})\nexport type RecordingConfig = z.infer<typeof RecordingConfigSchema>\n","import { z } from 'zod'\n\n/**\n * `StorageLocationType` — an addon-declared id that identifies the *kind* of\n * storage a location serves. Defined here (not in `capabilities/storage.cap.ts`)\n * so the persisted record schema and the consumer-facing cap can both consume it\n * without forming a circular import. The `storage` cap re-exports it\n * verbatim for back-compat.\n *\n * This Zod schema is the **authoritative source** for `StorageLocationType`.\n * The TS alias in `./storage.ts` re-exports `z.infer<typeof\n * StorageLocationTypeSchema>` so the wire surface (cap) and the legacy\n * `IStorageProvider` interface stay in lockstep.\n *\n * The type is now an **open string** (not a closed enum) — addons declare\n * their own location kinds via `StorageLocationDeclaration.id`. The regex\n * enforces a safe id format: lowercase-start, alphanumeric + hyphens.\n */\nexport const StorageLocationTypeSchema = z.string().regex(/^[a-z][a-zA-Z0-9-]*$/)\n\n/**\n * `StorageLocationType` — TS alias for the open string schema above (`string`).\n * Re-exported by `./storage.ts` so the legacy `IStorageProvider` interface\n * keeps the same name without duplicating the schema.\n */\nexport type StorageLocationType = z.infer<typeof StorageLocationTypeSchema>\n\n/**\n * Persisted record for a storage location instance. Operators can register\n * multiple instances for multi-cardinality types (e.g. two `backups`\n * locations with different `providerId`s). Cardinality is now declared per\n * location via `StorageLocationDeclaration.cardinality` — the static\n * `STORAGE_LOCATION_CARDINALITY` map has been removed.\n *\n * `id` is a stable namespaced string of the form `<type>:<slug>`.\n * The default location for a type uses `id === <type>:default` by\n * convention (the bare type ref like `'backups'` resolves to it).\n *\n * `isSystem: true` marks a location as orchestrator-seeded and\n * undeletable. The bootstrap-installed defaults (one per type) carry\n * this flag; operator-added locations don't. Editing the config of\n * a system location is allowed (path migration, provider swap) but\n * deleting it is rejected at the cap level.\n */\nexport const StorageLocationSchema = z.object({\n id: z.string().regex(/^[a-z][a-zA-Z0-9-]*:[a-zA-Z0-9-]+$/),\n // Open string — the location's *kind* is an addon-declared id matching\n // `StorageLocationDeclaration.id`. All built-in ids are valid plain\n // strings, and addon-declared ids are admitted without schema changes.\n type: z.string(),\n displayName: z.string().min(1),\n providerId: z.string().min(1),\n config: z.record(z.string(), z.unknown()),\n isDefault: z.boolean().default(false),\n isSystem: z.boolean().default(false),\n createdAt: z.number(),\n updatedAt: z.number(),\n})\nexport type StorageLocation = z.infer<typeof StorageLocationSchema>\n\n/**\n * Reference accepted by consumer-facing `api.storage.*` calls.\n * Either:\n * - a `StorageLocationType` (e.g. `'backups'`) → orchestrator resolves to the default of that type\n * - a fully-qualified id (e.g. `'backups:nas-01'`) → addresses a specific instance\n *\n * The orchestrator's `resolveRef(ref)` handles both cases.\n */\nexport const StorageLocationRefSchema = z.union([\n StorageLocationTypeSchema,\n z.string().regex(/^[a-z][a-zA-Z0-9-]*:[a-zA-Z0-9-]+$/),\n])\nexport type StorageLocationRef = z.infer<typeof StorageLocationRefSchema>\n","import { z } from 'zod'\n\n/**\n * `StorageLocationDeclaration` — a single storage-location entry declared by\n * an addon in its `package.json` under `camstack.storageLocations`.\n *\n * Design intent:\n * - **Addon declares its needs** — each addon describes the logical storage\n * slots it requires (e.g. `recordings`, `recordingsLow`) without caring\n * about the physical path.\n * - **Kernel aggregates** — at boot the kernel collects declarations from all\n * installed addons, deduplicates by `id`, and exposes the union via the\n * storage-locations settings surface.\n * - **Orchestrator seeds** — for every declared `id` the orchestrator ensures\n * at least one instance named `<id>:default` is present, using\n * `defaultsTo` to inherit the resolved root from another location when the\n * declaration is a derivative slot (e.g. `recordingsLow` defaults to\n * `recordings`).\n * - **ids are global** — `id` values are shared across the entire deployment;\n * two addons declaring the same `id` must agree on `cardinality` (validated\n * at kernel aggregation time, not here).\n */\nexport const StorageLocationDeclarationSchema = z.object({\n /**\n * Global location identifier, e.g. `recordings` or `recordingsLow`.\n * Must start with a lowercase letter and may contain letters, digits, and\n * hyphens.\n */\n id: z.string().regex(/^[a-z][a-zA-Z0-9-]*$/, {\n message: 'id must start with a lowercase letter and contain only letters, digits, or hyphens',\n }),\n\n /** Human-readable name shown in the admin UI. */\n displayName: z.string().min(1, { message: 'displayName must not be empty' }),\n\n /** Optional longer explanation of what data this location stores. */\n description: z.string().optional(),\n\n /**\n * `single` — exactly one instance of this location is allowed system-wide\n * (e.g. `logs`, `models`). The operator can edit it but not add more.\n * `multi` — the operator may register several instances (e.g. a second\n * `recordings` on a NAS for disk tiering); one is the default at any time.\n */\n cardinality: z.enum(['single', 'multi']),\n\n /**\n * When set, the default instance for this location inherits its resolved\n * root from the named location's default instance. Useful for derivative\n * slots (e.g. `recordingsLow` → `recordings`) so operators only need to\n * configure the primary location.\n */\n defaultsTo: z.string().optional(),\n})\n\n/** Inferred TypeScript type for `StorageLocationDeclarationSchema`. */\nexport type StorageLocationDeclaration = z.infer<typeof StorageLocationDeclarationSchema>\n","\nimport { z } from 'zod'\nimport type { FrameFormat } from '../types/io.js'\nimport type { FrameHandle } from './frame-handle.js'\nimport type {\n SubscribeFramesInput,\n SubscribeFramesResult,\n SubscribeAudioChunksResult,\n} from '../capabilities/schemas/streaming-shared.js'\nimport type { BrokerConsumerAttribution } from '../capabilities/stream-broker.cap.js'\n\n// ── Zod schemas for wire-serializable decoder cap methods ──────────\n\nexport const DecoderStatsSchema = z.object({\n inputFps: z.number(),\n outputFps: z.number(),\n avgDecodeTimeMs: z.number(),\n droppedFrames: z.number(),\n})\n\nexport const DecoderSessionConfigSchema = z.object({\n codec: z.string(),\n maxFps: z.number().default(0),\n outputFormat: z.enum(['jpeg', 'rgb', 'bgr', 'yuv420', 'gray']).default('jpeg'),\n scale: z.number().default(1),\n width: z.number().optional(),\n height: z.number().optional(),\n /**\n * Identifier of the camera this decoder session serves. Optional\n * because the cap is generic (any caller could request decode), but\n * stream-broker passes it so decoder logs include `deviceId` for\n * per-camera filtering when diagnosing failures (e.g. node-av\n * sendPacket errors on a single hung camera).\n */\n deviceId: z.number().int().nonnegative().optional(),\n /**\n * Free-form tag for log scoping. Stream-broker uses\n * `broker:<deviceId>/<profile>`. Decoder session logger surfaces it\n * on every line so `grep tag=broker:5/high` filters one camera\n * profile cleanly.\n */\n tag: z.string().optional(),\n /**\n * Where the session delivers decoded frames (Phase 5 / D9):\n *\n * - `'callback'` (default) — the legacy pixel path: decoded frames are\n * buffered as `DecodedFrame`s and drained via `pullFrames`.\n * - `'shm'` — the shared-memory frame plane: decoded frames are written\n * into an OS shared-memory ring and drained as zero-pixel\n * `FrameHandle`s via `pullHandles`. A session is one mode or the\n * other — `pullFrames` returns nothing for an `'shm'` session and\n * `pullHandles` returns nothing for a `'callback'` session.\n */\n frameSink: z.enum(['callback', 'shm']).default('callback'),\n})\n\nexport type Unsubscribe = () => void\n\n/**\n * Discriminator for `StreamSource.type`. Values that the broker\n * understands today:\n *\n * - `'rtsp'` — pull mode. Broker connects to a `rtsp://` URL,\n * demuxes RTP, exposes raw RTP via `onVideoRtp`.\n * - `'rtmp'` — pull mode. Broker connects to a `rtmp://` URL,\n * demuxes flv into AnnexB packets. No source RTP\n * available (RTMP carries no RTP), so the WebRTC\n * path falls back to AnnexB → writeVideoNals.\n * Reserved — implementation pending.\n * - `'push'` — push mode. Provider addon delivers AnnexB packets\n * via `pushEncodedPacket()` (Reolink Baichuan,\n * Frigate event streams, etc.).\n * - `'push-rtp'` — push mode with raw RTP packets. Provider addon\n * delivers source RTP via `pushVideoRtp()` AND\n * AnnexB-equivalents via `pushEncodedPacket()` so\n * downstream consumers (decoder, restreamer) keep\n * working. Lets the WebRTC path use the H.265\n * repacketizer for push-mode H.265 streams. Reserved\n * — implementation pending.\n * - `'placeholder'` — silent black-image placeholder reader.\n *\n * String type instead of a literal union so addons remain free to\n * add new source types — the broker's switch statement falls through\n * to \"data is pushed externally\" for unknown values.\n */\nexport type StreamSourceType = 'rtsp' | 'rtmp' | 'push' | 'push-rtp' | 'rfc4571' | 'placeholder' | (string & {})\n\nexport interface StreamSource {\n readonly type: StreamSourceType\n /** Stream URL — required for pull-based sources (rtsp, rtmp). Not used for push sources. */\n readonly url: string\n readonly videoCodec?: string\n readonly audioCodec?: string\n readonly metadata?: Readonly<Record<string, unknown>>\n /**\n * Push-source flag — when true, a stall in the input stream is\n * treated as a valid suspension (battery cameras intentionally go\n * silent between motion events) rather than an error. The broker\n * stops emitting the black-image placeholder and pauses the watchdog\n * until the next packet arrives. Default: false (legacy behaviour —\n * stall is an error).\n */\n readonly allowStall?: boolean\n}\n\nexport interface StreamSourceOption {\n readonly id: string\n readonly label: string\n readonly source: StreamSource\n readonly resolution?: { readonly width: number; readonly height: number }\n readonly primary?: boolean\n}\n\nexport interface EncodedPacket {\n readonly type: 'video' | 'audio'\n readonly data: Buffer\n readonly pts: number\n readonly dts: number\n readonly keyframe: boolean\n readonly codec: string\n /**\n * `true` when the packet was synthesized by the broker's placeholder\n * pump (state-aware \"RECONNECTING\" / \"SLEEPING\" / etc. keyframes\n * pushed at 1Hz while no real RTP is flowing). Consumers that\n * accumulate per-stream codec state (sticky SPS/PPS, decoder config)\n * MUST treat these as throwaway: the placeholder is a different\n * resolution and parameter set than the live camera, so caching its\n * SPS/PPS and prepending them to real keyframes silently corrupts\n * the decoder state and freezes the WebRTC viewer on the last\n * placeholder until the consumer is re-created. Absent on packets\n * produced from real source data.\n */\n readonly isPlaceholder?: boolean\n}\n\n/**\n * Audio metadata declared by push-source providers before they emit the\n * first audio `EncodedPacket`. Mirrors the slice of an SDP audio track\n * the broker actually consumes — `codec` is canonical lowercase\n * ('aac' | 'opus' | 'pcmu' | 'pcma' | ...).\n *\n * `extraData` carries codec-specific config bytes (e.g. AAC\n * AudioSpecificConfig) when the codec needs them at decoder-init time.\n */\nexport interface PushAudioInfo {\n readonly codec: string\n readonly sampleRate: number\n readonly channels: number\n readonly extraData?: Uint8Array\n}\n\nexport interface DecodedFrame {\n readonly data: Buffer\n readonly width: number\n readonly height: number\n readonly format: FrameFormat\n readonly timestamp: number\n /** Wall-clock ms (Date.now) when the frame was committed to the shm ring.\n * Unlike `timestamp` (codec PTS), this is diff-able against Date.now() to\n * measure frame age (capture→processing). Absent on non-shm frame sources. */\n readonly capturedAt?: number\n}\n\nexport interface DecodedAudioChunk {\n readonly data: Buffer\n readonly sampleRate: number\n readonly channels: number\n readonly timestamp: number\n}\n\nexport interface AudioSubscribeOptions {\n /**\n * Caller identity tag (Phase 10). Surfaced by `listClients` so operators\n * can tell who's holding the broker open. Short and stable\n * (`audio-analyzer`, …). Missing tag → recorded as `'unknown'`.\n */\n readonly tag?: string\n}\n\nexport type BrokerStatus = 'idle' | 'connecting' | 'streaming' | 'error' | 'stopped'\n\nexport interface BrokerStats {\n readonly status: BrokerStatus\n readonly inputFps: number\n readonly decodeFps: number\n readonly encodedSubscribers: number\n readonly decodedSubscribers: number\n readonly uptimeMs: number\n /** Measured bitrate in kbps (averaged over 2s window) */\n readonly bitrateKbps: number\n /** Time between last two keyframes in ms (IDR interval) */\n readonly idrIntervalMs: number\n /** Detected video codec (h264, h265) */\n readonly codec?: string\n /** Total bytes received since broker start */\n readonly totalBytes: number\n /** Total encoded packets received since broker start */\n readonly packetCount: number\n /** Number of connected RTSP restream clients */\n readonly rtspClients: number\n /** Number of connected TCP pipe clients */\n readonly pipeClients: number\n /** Pre-buffer configured duration in seconds */\n readonly preBufferSec: number\n /** Pre-buffer actual buffered duration in ms */\n readonly preBufferMs: number\n /** Pre-buffer packet count */\n readonly preBufferPackets: number\n /**\n * Moleculer node id of the decoder provider currently servicing this\n * stream's decoded subscribers. `null` until the deferred decoder is\n * created (no decoded clients yet, or codec not detected).\n */\n readonly decoderNodeId: string | null\n /**\n * Detected audio track parameters from the RTSP DESCRIBE / SDP. Null\n * when the stream has no audio track or the broker is still in cold\n * start. `supported` reflects whether the local native + ffmpeg-based\n * decoder pipeline can produce PCM chunks for downstream consumers\n * (audio-analyzer). When `false`, the codec is detected but skipped.\n */\n readonly audio?: {\n readonly codec: string\n readonly sampleRate: number\n readonly channels: number\n readonly supported: boolean\n } | null\n}\n\nexport interface IStreamBroker {\n readonly deviceId: string\n readonly status: BrokerStatus\n readonly suspended: boolean\n start(source: StreamSource): Promise<void>\n stop(): Promise<void>\n /**\n * Push an encoded packet into the broker from an external source.\n *\n * Used by camera provider addons that deliver media data directly\n * (e.g. Reolink Baichuan protocol, Frigate event streams) instead\n * of exposing an RTSP URL for the broker to pull from.\n *\n * The broker fans out the packet to all consumers: pre-buffer, RTSP\n * restreamer, TCP pipe, decoder sessions, and encoded subscribers.\n */\n pushEncodedPacket(packet: EncodedPacket): void\n /**\n * Push-source audio metadata. Push providers (Reolink Baichuan,\n * Frigate, etc.) call this BEFORE the first audio EncodedPacket so\n * the broker can wire the audio-codec capability — RTSP sources get\n * the same data from the SDP audio track. Repeat calls update the\n * declared codec; calling with `null` retracts (broker tears down\n * any audio decode session).\n *\n * Typical Reolink Baichuan audio: AAC-LC 16 kHz mono. Cameras that\n * push G.711 should still call this so the broker can bypass the\n * codec cap for the supported native codecs.\n */\n pushAudioInfo?(info: PushAudioInfo | null): void\n /**\n * Push a raw video RTP packet from an external source (used by\n * `'push-rtp'`-typed sources, e.g. Reolink Baichuan adapter that\n * synthesizes RTP from its packetizer-friendly access units). The\n * broker fans out to `onVideoRtp` subscribers, including the\n * WebRTC server's H.265 repacketizer path.\n *\n * Sources that don't carry per-packet RTP MAY ignore this entirely\n * and call only `pushEncodedPacket`. Implementations are free to\n * be a no-op when no RTP subscribers exist.\n */\n pushVideoRtp?(rtpData: Buffer): void\n /**\n * Subscribe to AnnexB-encoded packets. The optional `attribution`\n * blob identifies the consumer in the broker's `listClients()` /\n * widget output (\"Alexa cam 54 / sessionId=...\", \"HAP iOS\", etc).\n * Callers that don't have identity context pass nothing and land\n * as `kind: 'unknown'`.\n */\n onEncodedData(\n callback: (packet: EncodedPacket) => void,\n attribution?: BrokerConsumerAttribution,\n ): Unsubscribe\n /**\n * Subscribe to source video RTP packets (raw on-wire bytes, before\n * depacketization). Used by the WebRTC server's H.265 path to feed\n * a packet-level repacketizer that preserves the original RTP header\n * layout — Chrome's HEVC depacketizer is sensitive to it.\n *\n * Sources that don't have an underlying RTP wire (e.g. Frigate event\n * streams that call `pushEncodedPacket`) MAY register zero callbacks\n * and emit nothing. `attribution` works the same as `onEncodedData`.\n */\n onVideoRtp(\n callback: (rtpData: Buffer) => void,\n attribution?: BrokerConsumerAttribution,\n ): Unsubscribe\n /**\n * Re-tag every subscriber whose attribution carries `sessionId` with the\n * supplied patch (e.g. a remote address discovered once ICE connects). The\n * stored attribution is replaced with a freshly merged object — never\n * mutated. Returns true when at least one entry matched.\n */\n updateConsumerAttributionBySession(\n sessionId: string,\n patch: Partial<BrokerConsumerAttribution>,\n ): boolean\n /**\n * Codec parameter sets harvested from the camera's SDP (sprop-vps /\n * sprop-sps / sprop-pps). Cameras like Reolink high-profile streams\n * publish VPS/SPS/PPS only via SDP — Chrome's HEVC decoder needs them\n * to initialise. Returns null when the broker hasn't connected yet\n * or the camera ships param sets in-band.\n */\n getSdpParameterSets(): ReadonlyArray<Buffer> | null\n /**\n * Subscribe to SDP-derived VPS/SPS/PPS deliveries. Fires once\n * synchronously if the broker already has them (late-subscriber\n * shape), and again every time `onVideoTrack` repopulates them on a\n * reader rebuild. Used by the WebRTC server's H.265 path so a\n * session created during the wake-up window — when\n * `getSdpParameterSets()` still returns null — can seed its\n * `H265Repacketizer` once the camera's first RTP+SDP arrive.\n */\n onSdpParameterSets(callback: (ps: ReadonlyArray<Buffer>) => void): Unsubscribe\n /**\n * Source type as configured at `start()` — see `StreamSourceType`\n * for the supported values. `null` before `start()` resolves.\n */\n getSourceType(): StreamSourceType | null\n /**\n * True when the broker can emit source RTP packets via\n * `onVideoRtp` — i.e. the source is RTSP (pull) or push-rtp.\n * RTMP and bare push (AnnexB-only) sources return false.\n * Routing decisions in the WebRTC server (e.g. \"use the H.265\n * repacketizer\") should consult this rather than string-comparing\n * the source type.\n */\n isRtpSource(): boolean\n /**\n * Open a decoded audio-chunk subscription (Phase 5 / D9) — the\n * serialisable replacement for the live-object `onDecodedAudioChunk`\n * callback. The broker registers a per-subscription bounded FIFO queue\n * and returns a `subscriptionId` the consumer polls via\n * `pullAudioChunks`. Reachable over tRPC (the\n * `stream-broker.subscribeAudioChunks` cap method) so a consumer in a\n * separate process can subscribe — chunk bytes travel inline on the RPC\n * wire (audio chunks are tiny, no shm needed).\n */\n subscribeAudioChunks(options?: AudioSubscribeOptions): SubscribeAudioChunksResult\n /**\n * Drain up to `maxCount` `DecodedAudioChunk`s for an audio-chunk\n * subscription, in FIFO arrival order.\n */\n pullAudioChunks(subscriptionId: string, maxCount: number): readonly DecodedAudioChunk[]\n /** Release an audio-chunk subscription. Returns `true` when it existed. */\n unsubscribeAudioChunks(subscriptionId: string): boolean\n /**\n * Open a shared-memory frame-handle subscription (Phase 5 / D9) — the\n * handle-based decoded-frame surface. The broker spins up a\n * `frameSink: 'shm'` decoder session producing the requested `format` and\n * returns a `subscriptionId` the consumer polls via `pullFrameHandles`.\n * Reachable over tRPC (the `stream-broker.subscribeFrames` cap method), so a\n * consumer in a separate process can subscribe — pixels travel through the\n * shm ring, never the RPC wire.\n */\n subscribeFrameHandles(\n input: Omit<SubscribeFramesInput, 'brokerId'>,\n ): Promise<SubscribeFramesResult>\n /** Drain up to `maxCount` `FrameHandle`s for a frame-handle subscription. */\n pullFrameHandles(subscriptionId: string, maxCount: number): readonly FrameHandle[]\n /** Release a frame-handle subscription. Returns `true` when it existed. */\n unsubscribeFrameHandles(subscriptionId: string): Promise<boolean>\n getStats(): BrokerStats\n getLocalStreamUrl(): string\n /**\n * Get the pre-buffer (current GOP from the last keyframe), for late-joining\n * consumers to start decoding immediately. Two mutually-exclusive forms by\n * source: AnnexB (`getPreBuffer`) for push/AnnexB sources (writeVideoNals\n * path); raw source RTP (`getRtpPreBuffer`) for RTP sources (RTSP) on the\n * repacketizer path. A given broker populates exactly ONE of them.\n */\n getPreBuffer(): readonly EncodedPacket[]\n /** Raw source-RTP pre-buffer (current GOP) — RTP sources only; [] otherwise. */\n getRtpPreBuffer(): readonly Buffer[]\n /** Set the pre-buffer duration in seconds (0 to disable, max 30). */\n setPreBufferDuration(seconds: number): void\n /** Get the current pre-buffer duration in seconds. */\n getPreBufferDuration(): number\n setPreBufferEnabled(enabled: boolean): void\n}\n\n/**\n * Manager for stream brokers — the server interacts with this interface,\n * while the concrete implementation lives in the addon-stream-broker package.\n */\n/** Per-broker RTSP restream entry (absorbed from the former rtsp-restream capability). */\nexport interface RtspRestreamEntry {\n readonly brokerId: string\n readonly url: string\n readonly mutedUrl: string\n readonly enabled: boolean\n}\n\n/** Flat cap-shaped broker record returned by `listBrokers()`. */\nexport interface BrokerListEntry {\n readonly brokerId: string\n readonly status: string\n readonly inputFps: number\n readonly decodeFps: number\n readonly encodedSubscribers: number\n readonly decodedSubscribers: number\n readonly uptimeMs: number\n readonly bitrateKbps: number\n readonly idrIntervalMs: number\n readonly codec?: string\n readonly totalBytes: number\n readonly packetCount: number\n readonly rtspClients: number\n readonly pipeClients: number\n readonly preBufferSec: number\n readonly preBufferMs: number\n readonly preBufferPackets: number\n}\n\n\n/**\n * Phase the runner's per-camera state machine occupies. `'idle'` is the\n * `detectionMode === 'disabled'` resting state — runner registered the\n * camera but never subscribed to detection frames. The other 4 are the\n * historical motion-gated states; their transitions are now driven by\n * `detectionMode` ('always-on' starts in 'active', 'on-motion' starts\n * in 'watching').\n */\nexport type CameraPhase = 'idle' | 'watching' | 'active' | 'paused' | 'load-shed'\n\nexport interface CameraDetectionConfig {\n readonly enabled: boolean\n readonly pipelineEnabled: boolean\n\n /** Motion sources that activate this camera's pipeline. At least one. */\n readonly motionSources: import('./pipeline-orchestrator-capability.js').OrchestrationMotionSources\n\n readonly motionStreamId: string\n readonly detectionStreamId: string\n\n readonly motionFps: number\n readonly detectionFps: number\n readonly motionCooldownMs: number\n\n readonly audioStreamId?: string\n\n /**\n * Operator-facing scheduling modes. Forwarded to `RunnerCameraConfig`;\n * the runner uses these to gate its substream subscribers + phase\n * machine. See `PipelinePhaseMode` for the semantics.\n */\n readonly detectionMode: import('../device/device-profile.js').PipelinePhaseMode\n readonly audioMode: import('../device/device-profile.js').PipelinePhaseMode\n /**\n * When true, the runner dynamically opens the WASM frame-diff analyzer\n * on onboard-motion events and tears it down after the cooldown window.\n * Has no effect when `motionSources` already includes `'analyzer'`.\n * Mirrors `audioMode`'s optional pattern — resolved with operator-wins →\n * default(true) in `resolveDeviceDetectionSettings`.\n */\n readonly onboardMotionDrivesAnalyzer: boolean\n}\n","import { z } from 'zod'\n\n/**\n * Shared video / audio encode profile schemas used by every consumer\n * that asks the stream broker to spawn a derived stream\n * (WebRTC, HAP, Alexa, custom addons).\n *\n * The schema is intentionally simple: typed common fields + two\n * free-text arrays (inputArgs / outputArgs). The composite UI widget\n * `stream-broker/ffmpeg-params` is the smart layer — it routes\n * codec-specific overrides into the right scope and handles\n * dependency gating, duplicate detection, and source-aware\n * suggestions before persistence.\n */\n\nexport const VideoEncodeSchema = z.object({\n codec: z.enum(['h264', 'h265', 'copy']),\n profile: z.enum(['baseline', 'main', 'high']).optional(),\n width: z.number().int().positive().optional(),\n height: z.number().int().positive().optional(),\n fps: z.number().positive().optional(),\n bitrateKbps: z.number().int().positive().optional(),\n gopFrames: z.number().int().positive().optional(),\n bf: z.number().int().min(0).optional(),\n preset: z.enum([\n 'ultrafast', 'superfast', 'veryfast', 'faster', 'fast', 'medium',\n ]).optional(),\n tune: z.enum(['zerolatency', 'film', 'animation']).optional(),\n})\nexport type VideoEncode = z.infer<typeof VideoEncodeSchema>\n\nexport const AudioEncodeSchema = z.union([\n z.literal('passthrough'),\n z.object({\n codec: z.enum(['opus', 'aac', 'pcmu', 'pcma', 'copy']),\n bitrateKbps: z.number().int().positive().optional(),\n sampleRateHz: z.number().int().positive().optional(),\n channels: z.union([z.literal(1), z.literal(2)]).optional(),\n }),\n])\nexport type AudioEncode = z.infer<typeof AudioEncodeSchema>\n\nexport const EncodeProfileSchema = z.object({\n video: VideoEncodeSchema,\n audio: AudioEncodeSchema,\n /**\n * ffmpeg input-side args, inserted between the fixed global flags\n * (`-hide_banner -loglevel error`) and `-i pipe:0`. Free-text array\n * — the widget surfaces a textarea + suggestion chips for the most-\n * used demuxer/format options.\n */\n inputArgs: z.array(z.string()).optional(),\n /**\n * ffmpeg output-side args, inserted between the encode block and\n * the final `-f <muxer> pipe:1`. Use for muxer options, bitstream\n * filters, codec-specific overrides. Free-text array.\n */\n outputArgs: z.array(z.string()).optional(),\n})\nexport type EncodeProfile = z.infer<typeof EncodeProfileSchema>\n\n/**\n * Reshape a publisher-advertised stream shape (a `CameraStream`, a broker\n * `ProfileSlot`, or anything else exposing `codec` + `resolution` + `fps`)\n * into an `EncodeProfile` suitable for the read-only \"Source (probed)\"\n * card of the `stream-broker/ffmpeg-params` widget.\n *\n * Returns `undefined` when nothing meaningful was advertised — the widget\n * then hides the card rather than showing a codec chip with no shape.\n * Audio is reported as `'passthrough'` because publishers don't carry\n * audio shape at this level; the widget renders that as a single chip.\n */\nexport function encodeProfileFromStreamShape(stream: {\n readonly codec?: string\n readonly resolution?: { readonly width: number; readonly height: number }\n readonly fps?: number\n}): EncodeProfile | undefined {\n // Canonicalize codec strings — publishers report `H.264` / `h264` /\n // `H.265` / `HEVC` interchangeably; the widget needs a single tag.\n const codecNorm = stream.codec?.toLowerCase().replace(/[.\\s-]/g, '')\n const codec: VideoEncode['codec'] =\n codecNorm === 'h265' || codecNorm === 'hevc' ? 'h265' : 'h264'\n const video: VideoEncode = {\n codec,\n ...(stream.resolution?.width !== undefined ? { width: stream.resolution.width } : {}),\n ...(stream.resolution?.height !== undefined ? { height: stream.resolution.height } : {}),\n ...(stream.fps !== undefined ? { fps: stream.fps } : {}),\n }\n if (video.width === undefined && video.height === undefined && video.fps === undefined) {\n return undefined\n }\n return { video, audio: 'passthrough' as const }\n}\n","/**\nimport { errMsg } from '@camstack/types'\n * Extract a human-readable message from an unknown error value.\n * Replaces the ubiquitous `errMsg(err)` pattern.\n */\nexport function errMsg(err: unknown): string {\n if (err instanceof Error) return err.message\n if (typeof err === 'string') return err\n return String(err)\n}\n","/**\n * Audio classification macro classes — maps 521 YAMNet labels into ~25 actionable categories.\n * Same pattern as COCO_TO_MACRO for video detection.\n *\n * Each macro class aggregates related fine-grained labels so the user\n * sees a manageable set of event types in settings, timelines, and notifications.\n */\nimport type { LabelDefinition, ClassMapDefinition } from '../types/labels.js'\n\n// ---------------------------------------------------------------------------\n// Macro class definitions\n// ---------------------------------------------------------------------------\n\nexport const AUDIO_MACRO_LABELS: readonly LabelDefinition[] = [\n { id: 'speech', name: 'Speech', icon: '🗣️' },\n { id: 'scream', name: 'Scream / Shout', icon: '😱' },\n { id: 'crying', name: 'Crying / Baby', icon: '😢' },\n { id: 'laughter', name: 'Laughter', icon: '😂' },\n { id: 'music', name: 'Music', icon: '🎵' },\n { id: 'dog', name: 'Dog', icon: '🐕' },\n { id: 'cat', name: 'Cat', icon: '🐈' },\n { id: 'bird', name: 'Bird', icon: '🐦' },\n { id: 'animal', name: 'Animal (other)', icon: '🐾' },\n { id: 'alarm', name: 'Alarm / Siren', icon: '🚨' },\n { id: 'doorbell', name: 'Doorbell / Knock', icon: '🔔' },\n { id: 'glass_breaking', name: 'Glass Breaking', icon: '💥' },\n { id: 'gunshot', name: 'Gunshot / Explosion', icon: '💣' },\n { id: 'vehicle', name: 'Vehicle', icon: '🚗' },\n { id: 'siren', name: 'Emergency Siren', icon: '🚑' },\n { id: 'fire', name: 'Fire / Smoke', icon: '🔥' },\n { id: 'water', name: 'Water', icon: '💧' },\n { id: 'wind', name: 'Wind / Weather', icon: '🌬️' },\n { id: 'door', name: 'Door', icon: '🚪' },\n { id: 'footsteps', name: 'Footsteps', icon: '👣' },\n { id: 'crowd', name: 'Crowd / Chatter', icon: '👥' },\n { id: 'telephone', name: 'Telephone', icon: '📞' },\n { id: 'engine', name: 'Engine / Motor', icon: '⚙️' },\n { id: 'tools', name: 'Tools / Construction', icon: '🔨' },\n { id: 'silence', name: 'Silence', icon: '🤫' },\n] as const\n\n// ---------------------------------------------------------------------------\n// YAMNet label → macro class mapping (by label name, case-insensitive)\n// ---------------------------------------------------------------------------\n\nexport const YAMNET_TO_MACRO: ClassMapDefinition = {\n mapping: {\n // Speech\n 'Speech': 'speech',\n 'Child speech, kid speaking': 'speech',\n 'Conversation': 'speech',\n 'Narration, monologue': 'speech',\n 'Babbling': 'speech',\n 'Whispering': 'speech',\n 'Speech synthesizer': 'speech',\n 'Humming': 'speech',\n 'Rapping': 'speech',\n 'Singing': 'speech',\n 'Choir': 'speech',\n 'Child singing': 'speech',\n\n // Scream / Shout\n 'Shout': 'scream',\n 'Bellow': 'scream',\n 'Yell': 'scream',\n 'Screaming': 'scream',\n 'Children shouting': 'scream',\n 'Whoop': 'scream',\n\n // Crying\n 'Crying, sobbing': 'crying',\n 'Baby cry, infant cry': 'crying',\n 'Whimper': 'crying',\n 'Wail, moan': 'crying',\n 'Groan': 'crying',\n\n // Laughter\n 'Laughter': 'laughter',\n 'Baby laughter': 'laughter',\n 'Giggle': 'laughter',\n 'Snicker': 'laughter',\n 'Belly laugh': 'laughter',\n 'Chuckle, chortle': 'laughter',\n\n // Music\n 'Music': 'music',\n 'Musical instrument': 'music',\n 'Guitar': 'music',\n 'Piano': 'music',\n 'Drum': 'music',\n 'Drum kit': 'music',\n 'Violin, fiddle': 'music',\n 'Flute': 'music',\n 'Saxophone': 'music',\n 'Trumpet': 'music',\n 'Synthesizer': 'music',\n 'Pop music': 'music',\n 'Rock music': 'music',\n 'Hip hop music': 'music',\n 'Classical music': 'music',\n 'Jazz': 'music',\n 'Electronic music': 'music',\n 'Background music': 'music',\n\n // Dog\n 'Dog': 'dog',\n 'Bark': 'dog',\n 'Yip': 'dog',\n 'Howl': 'dog',\n 'Bow-wow': 'dog',\n 'Growling': 'dog',\n 'Whimper (dog)': 'dog',\n\n // Cat\n 'Cat': 'cat',\n 'Purr': 'cat',\n 'Meow': 'cat',\n 'Hiss': 'cat',\n 'Caterwaul': 'cat',\n\n // Bird\n 'Bird': 'bird',\n 'Bird vocalization, bird call, bird song': 'bird',\n 'Chirp, tweet': 'bird',\n 'Squawk': 'bird',\n 'Crow': 'bird',\n 'Owl': 'bird',\n 'Pigeon, dove': 'bird',\n\n // Animal (other)\n 'Animal': 'animal',\n 'Domestic animals, pets': 'animal',\n 'Livestock, farm animals, working animals': 'animal',\n 'Horse': 'animal',\n 'Cattle, bovinae': 'animal',\n 'Pig': 'animal',\n 'Sheep': 'animal',\n 'Goat': 'animal',\n 'Frog': 'animal',\n 'Insect': 'animal',\n 'Cricket': 'animal',\n\n // Alarm / Siren\n 'Alarm': 'alarm',\n 'Alarm clock': 'alarm',\n 'Smoke detector, smoke alarm': 'alarm',\n 'Fire alarm': 'alarm',\n 'Buzzer': 'alarm',\n 'Civil defense siren': 'alarm',\n 'Car alarm': 'alarm',\n\n // Emergency Siren\n 'Siren': 'siren',\n 'Police car (siren)': 'siren',\n 'Ambulance (siren)': 'siren',\n 'Fire engine, fire truck (siren)': 'siren',\n 'Emergency vehicle': 'siren',\n 'Foghorn': 'siren',\n\n // Doorbell / Knock\n 'Doorbell': 'doorbell',\n 'Ding-dong': 'doorbell',\n 'Knock': 'doorbell',\n 'Tap': 'doorbell',\n\n // Glass Breaking\n 'Glass': 'glass_breaking',\n 'Shatter': 'glass_breaking',\n 'Chink, clink': 'glass_breaking',\n\n // Gunshot / Explosion\n 'Gunshot, gunfire': 'gunshot',\n 'Machine gun': 'gunshot',\n 'Explosion': 'gunshot',\n 'Fireworks': 'gunshot',\n 'Firecracker': 'gunshot',\n 'Artillery fire': 'gunshot',\n 'Cap gun': 'gunshot',\n 'Boom': 'gunshot',\n\n // Vehicle\n 'Vehicle': 'vehicle',\n 'Car': 'vehicle',\n 'Truck': 'vehicle',\n 'Bus': 'vehicle',\n 'Motorcycle': 'vehicle',\n 'Car passing by': 'vehicle',\n 'Vehicle horn, car horn, honking': 'vehicle',\n 'Traffic noise, roadway noise': 'vehicle',\n 'Train': 'vehicle',\n 'Aircraft': 'vehicle',\n 'Helicopter': 'vehicle',\n 'Bicycle': 'vehicle',\n 'Skateboard': 'vehicle',\n\n // Fire / Smoke\n 'Fire': 'fire',\n 'Crackle': 'fire',\n\n // Water\n 'Water': 'water',\n 'Rain': 'water',\n 'Raindrop': 'water',\n 'Rain on surface': 'water',\n 'Stream': 'water',\n 'Waterfall': 'water',\n 'Ocean': 'water',\n 'Waves, surf': 'water',\n 'Splash, splatter': 'water',\n\n // Wind / Weather\n 'Wind': 'wind',\n 'Thunderstorm': 'wind',\n 'Thunder': 'wind',\n 'Wind noise (microphone)': 'wind',\n 'Rustling leaves': 'wind',\n\n // Door\n 'Door': 'door',\n 'Sliding door': 'door',\n 'Slam': 'door',\n 'Cupboard open or close': 'door',\n\n // Footsteps\n 'Walk, footsteps': 'footsteps',\n 'Run': 'footsteps',\n 'Shuffle': 'footsteps',\n\n // Crowd\n 'Crowd': 'crowd',\n 'Chatter': 'crowd',\n 'Cheering': 'crowd',\n 'Applause': 'crowd',\n 'Children playing': 'crowd',\n 'Hubbub, speech noise, speech babble': 'crowd',\n\n // Telephone\n 'Telephone': 'telephone',\n 'Telephone bell ringing': 'telephone',\n 'Ringtone': 'telephone',\n 'Telephone dialing, DTMF': 'telephone',\n 'Busy signal': 'telephone',\n\n // Engine / Motor\n 'Engine': 'engine',\n 'Engine starting': 'engine',\n 'Idling': 'engine',\n 'Accelerating, revving, vroom': 'engine',\n 'Light engine (high frequency)': 'engine',\n 'Medium engine (mid frequency)': 'engine',\n 'Heavy engine (low frequency)': 'engine',\n 'Lawn mower': 'engine',\n 'Chainsaw': 'engine',\n\n // Tools / Construction\n 'Hammer': 'tools',\n 'Jackhammer': 'tools',\n 'Sawing': 'tools',\n 'Power tool': 'tools',\n 'Drill': 'tools',\n 'Sanding': 'tools',\n\n // Silence\n 'Silence': 'silence',\n },\n preserveOriginal: false,\n}\n\n// ---------------------------------------------------------------------------\n// Apple SoundAnalysis identifier → macro class mapping\n// Apple uses snake_case identifiers (e.g. 'dog_bark', 'siren')\n// ---------------------------------------------------------------------------\n\nexport const APPLE_SA_TO_MACRO: ClassMapDefinition = {\n mapping: {\n 'speech': 'speech', 'child_speech': 'speech', 'conversation': 'speech',\n 'whispering': 'speech', 'singing': 'speech', 'humming': 'speech',\n 'shout': 'scream', 'yell': 'scream', 'screaming': 'scream',\n 'crying': 'crying', 'baby_crying': 'crying', 'sobbing': 'crying',\n 'laughter': 'laughter', 'baby_laughter': 'laughter', 'giggling': 'laughter',\n 'music': 'music', 'guitar': 'music', 'piano': 'music', 'drums': 'music',\n 'dog_bark': 'dog', 'dog_bow_wow': 'dog', 'dog_growling': 'dog', 'dog_howl': 'dog',\n 'cat_meow': 'cat', 'cat_purr': 'cat', 'cat_hiss': 'cat',\n 'bird': 'bird', 'bird_chirp': 'bird', 'bird_squawk': 'bird',\n 'animal': 'animal', 'horse': 'animal', 'cow_moo': 'animal', 'insect': 'animal',\n 'alarm': 'alarm', 'smoke_alarm': 'alarm', 'fire_alarm': 'alarm', 'car_alarm': 'alarm',\n 'siren': 'siren', 'police_siren': 'siren', 'ambulance_siren': 'siren',\n 'doorbell': 'doorbell', 'door_knock': 'doorbell', 'knocking': 'doorbell',\n 'glass_breaking': 'glass_breaking', 'glass_shatter': 'glass_breaking',\n 'gunshot': 'gunshot', 'explosion': 'gunshot', 'fireworks': 'gunshot',\n 'car': 'vehicle', 'truck': 'vehicle', 'motorcycle': 'vehicle',\n 'car_horn': 'vehicle', 'vehicle_horn': 'vehicle', 'traffic': 'vehicle',\n 'fire': 'fire', 'fire_crackle': 'fire',\n 'water': 'water', 'rain': 'water', 'ocean': 'water', 'splash': 'water',\n 'wind': 'wind', 'thunder': 'wind', 'thunderstorm': 'wind',\n 'door': 'door', 'door_slam': 'door', 'sliding_door': 'door',\n 'footsteps': 'footsteps', 'walking': 'footsteps', 'running': 'footsteps',\n 'crowd': 'crowd', 'chatter': 'crowd', 'cheering': 'crowd', 'applause': 'crowd',\n 'telephone_ring': 'telephone', 'ringtone': 'telephone',\n 'engine': 'engine', 'engine_starting': 'engine', 'lawn_mower': 'engine', 'chainsaw': 'engine',\n 'hammer': 'tools', 'jackhammer': 'tools', 'drill': 'tools', 'power_tool': 'tools',\n 'silence': 'silence',\n },\n preserveOriginal: false,\n}\n\n// ---------------------------------------------------------------------------\n// Unified lookup — merges YAMNet + Apple SA mappings\n// ---------------------------------------------------------------------------\n\nconst _macroLookup = new Map<string, string>()\nfor (const [k, v] of Object.entries(YAMNET_TO_MACRO.mapping)) {\n _macroLookup.set(k.toLowerCase(), v)\n}\nfor (const [k, v] of Object.entries(APPLE_SA_TO_MACRO.mapping)) {\n _macroLookup.set(k.toLowerCase(), v)\n}\n\n/** Map a raw audio label (YAMNet or Apple SoundAnalysis) to its macro class. Returns null if unmapped. */\nexport function mapAudioLabelToMacro(label: string): string | null {\n return _macroLookup.get(label.toLowerCase()) ?? null\n}\n\n/** Get all macro class IDs */\nexport function getAudioMacroClassIds(): readonly string[] {\n return AUDIO_MACRO_LABELS.map(l => l.id)\n}\n","export enum DeviceType {\n Camera = 'camera',\n Hub = 'hub',\n Light = 'light',\n Siren = 'siren',\n Switch = 'switch',\n Sensor = 'sensor',\n Thermostat = 'thermostat',\n Button = 'button',\n /** Generic stateless event emitter — carries a device's EXACT declared\n * event vocabulary verbatim (no normalization). Installed with the\n * `event-emitter` cap. Sources: HA `event.*` entities (structured) and\n * HA bus events (e.g. `zha_event`, generic). */\n EventEmitter = 'event-emitter',\n /** Firmware/software update entity — current vs available version,\n * updatable flag, update state, and an install action. Installed with\n * the `update` cap. Sources: Homematic firmware-update channels (and\n * reusable by other providers, e.g. HA `update.*` entities). */\n Update = 'update',\n Generic = 'generic',\n\n // ── HA-targeted (also reusable for native integrations) ──────────────\n /** Generic notification delivery target (HA `notify.<service>`, future\n * Telegram / Discord / ntfy / SMTP, …). One device per delivery\n * endpoint; the `notifier` cap defines the send surface. */\n Notifier = 'notifier',\n /** Pre-recorded action sequence with optional parameters\n * (HA `script.*`). Runnable via `script-runner` cap. */\n Script = 'script',\n /** Automation rule (HA `automation.*`) — enable/disable + manual\n * trigger surface exposed via `automation-control` cap. */\n Automation = 'automation',\n /** Door / smart lock device (HA `lock.*`). `lock-control` cap. */\n Lock = 'lock',\n /** Window covering, blinds, garage door, valve, etc. (HA `cover.*`,\n * `valve.*`). `cover` cap with sub-roles for variant. */\n Cover = 'cover',\n /** Pipe / water / gas valve with open/close/stop and optional\n * position (HA `valve.*`). `valve` cap — a cover-sibling actuator\n * modelled on the same open/closed lifecycle. */\n Valve = 'valve',\n /** Humidifier / dehumidifier with on/off + target humidity + mode\n * (HA `humidifier.*`). `humidifier` cap — a climate-family actuator\n * modelled on the same target / mode lifecycle. */\n Humidifier = 'humidifier',\n /** Water heater / boiler with target temperature + operation mode +\n * away mode (HA `water_heater.*`). `water-heater` cap — a\n * climate-family actuator. */\n WaterHeater = 'water-heater',\n /** Ceiling / standing / exhaust fan (HA `fan.*`). `fan-control` cap. */\n Fan = 'fan',\n /** Audio / video playback endpoint (HA `media_player.*`). Disjoint from\n * the camera surface — those use `Camera`. `media-player` cap. */\n MediaPlayer = 'media-player',\n /** Security panel / alarm system (HA `alarm_control_panel.*`).\n * `alarm-panel` cap. */\n AlarmPanel = 'alarm-panel',\n /** Generic user-settable input (HA `number` / `input_number` / `select`\n * / `input_select` / `text` / `input_text` / `input_datetime`).\n * Sub-type via `DeviceRole`: NumericControl / SelectControl /\n * TextControl / DateTimeControl. */\n Control = 'control',\n /** Person / device-tracker presence (HA `person.*`, `device_tracker.*`).\n * `presence` cap. */\n Presence = 'presence',\n /** Weather provider (HA `weather.*`). Tier-3, low MVP priority.\n * `weather` cap. */\n Weather = 'weather',\n /** Robot vacuum (HA `vacuum.*`). Tier-3. `vacuum-control` cap. */\n Vacuum = 'vacuum',\n /** Robotic lawn mower (HA `lawn_mower.*`). Tier-3.\n * `lawn-mower-control` cap. */\n LawnMower = 'lawn-mower',\n /** Physical HA device group — parent container for entity-children\n * adopted from a single HA device entry. Not renderable as a\n * standalone device; exists only to anchor child entities. */\n Container = 'container',\n /** Single still-image entity (HA `image.*`). Read-only display of an\n * `entity_picture` signed URL the browser loads directly. `image` cap. */\n Image = 'image',\n}\n\nexport enum DeviceFeature {\n BatteryOperated = 'battery-operated',\n Rebootable = 'rebootable',\n /**\n * Device supports an on-demand re-sync of its derived spec with its\n * upstream source — drives the generic Re-sync button. The owning\n * provider implements the action via the `device-adoption.resync` cap.\n */\n Resyncable = 'resyncable',\n NativeSnapshot = 'native-snapshot',\n DoorbellButton = 'doorbell-button',\n TwoWayAudio = 'two-way-audio',\n PanTiltZoom = 'pan-tilt-zoom',\n /**\n * Camera supports the on-firmware autotrack subsystem (subject-\n * following). Distinct from `PanTiltZoom` because not every PTZ\n * camera ships autotrack — the admin UI uses this flag to gate\n * the autotrack toggle / settings card without re-deriving from\n * the cap registry. Mirrors `ptz-autotrack` cap registration:\n * driver sets this feature when probe confirms the firmware\n * surface, and registers the cap in the same code path.\n */\n PtzAutotrack = 'ptz-autotrack',\n /**\n * Accessory exposes a \"trigger on motion\" toggle — the parent camera's\n * motion detection automatically activates this device. Mirrors\n * `motion-trigger` cap registration: drivers set this feature in the\n * same code path that calls `ctx.registerNativeCap(motionTriggerCapability, ...)`.\n *\n * Used by admin UI (gate the in-hero `MotionTriggerToggle` against a\n * fast scalar without binding fetch), notifier rules, and `listAll`\n * filters that want \"all devices with on-motion behaviour\".\n */\n MotionTrigger = 'motion-trigger',\n\n // ── HA-targeted actuator sub-features (Phase C1 retroactive) ────────\n // Granular color-mode support — paired with `colorCapability`. A\n // bulb that supports multiple color modes sets all the corresponding\n // flags; a CCT-only tunable-white bulb sets only `LightColorMired`.\n\n /** Light supports rgb-triplet color via `color` cap. */\n LightColorRgb = 'light-color-rgb',\n /** Light supports HSV color via `color` cap. */\n LightColorHsv = 'light-color-hsv',\n /** Light supports color-temperature (mired) via `color` cap. */\n LightColorMired = 'light-color-mired',\n\n // Climate sub-surface gating — paired with `climateControlCapability`.\n\n /** Thermostat supports a `heat_cool` dual setpoint (targetLow +\n * targetHigh). Gates the range slider UI. */\n ClimateDualSetpoint = 'climate-dual-setpoint',\n /** Thermostat exposes target humidity and/or current humidity\n * readings. Gates the humidity controls. */\n ClimateHumidity = 'climate-humidity',\n /** Thermostat exposes a fan-mode selector. */\n ClimateFanMode = 'climate-fan-mode',\n /** Thermostat exposes preset modes (eco / away / sleep / vendor). */\n ClimatePreset = 'climate-preset',\n\n // ── HA-targeted actuator sub-features (Phase C2 retroactive) ────────\n\n /** Cover exposes intermediate position control (0..100). Gates the\n * position slider UI. */\n CoverPositionable = 'cover-positionable',\n /** Cover exposes slat-tilt control. Gates the tilt slider UI. */\n CoverTilt = 'cover-tilt',\n /** Valve exposes intermediate position control (0..100). Gates the\n * position slider / drag surface UI. */\n ValvePositionable = 'valve-positionable',\n /** Fan exposes a speed-percentage setter. Gates the speed slider UI. */\n FanSpeed = 'fan-speed',\n /** Fan exposes a preset mode selector. */\n FanPreset = 'fan-preset',\n /** Fan exposes blade direction (forward/reverse) — typical of\n * ceiling fans. */\n FanDirection = 'fan-direction',\n /** Fan exposes an oscillation toggle. */\n FanOscillating = 'fan-oscillating',\n /** Lock requires a PIN code on lock/unlock. Gates the code-entry\n * field on the UI lock-controls panel. */\n LockPinRequired = 'lock-pin-required',\n /** Lock supports a latch-release (\"open door\") action distinct from\n * unlock. Mirrors HA `LockEntityFeature.OPEN` (bit 1) in\n * `supported_features`. Gates the Open Door button in the UI. */\n LockOpen = 'lock-open',\n\n // ── HA-targeted actuator sub-features (Phase C3) ─────────────────────\n // Mirrors the pattern of `PanTiltZoom` / `PtzAutotrack`: each flag pairs\n // with a capability registration but gates a sub-control inside the\n // device's UI without requiring a binding fetch. Drivers set the flag\n // in the same code path that registers the cap when probe confirms the\n // sub-surface (e.g. HA reports `supported_features & SUPPORT_SEEK`).\n\n /** Media player exposes a seek-to-position surface. */\n MediaPlayerSeek = 'media-player-seek',\n /** Media player exposes a volume-level setter. */\n MediaPlayerVolume = 'media-player-volume',\n /** Media player exposes a mute toggle distinct from volume=0. */\n MediaPlayerMute = 'media-player-mute',\n /** Media player exposes a shuffle toggle. */\n MediaPlayerShuffle = 'media-player-shuffle',\n /** Media player exposes a repeat mode (off / all / one). */\n MediaPlayerRepeat = 'media-player-repeat',\n /** Media player exposes a source / input selector. */\n MediaPlayerSelectSource = 'media-player-select-source',\n /** Media player exposes a play-arbitrary-media surface (URL / id). */\n MediaPlayerPlayMedia = 'media-player-play-media',\n /** Media player exposes next-track. */\n MediaPlayerNext = 'media-player-next',\n /** Media player exposes previous-track. */\n MediaPlayerPrevious = 'media-player-previous',\n /** Media player exposes stop distinct from pause. */\n MediaPlayerStop = 'media-player-stop',\n /** Alarm panel requires a PIN code on arm/disarm. */\n AlarmPinRequired = 'alarm-pin-required',\n /** Presence device carries GPS coordinates (lat/lng/accuracy) in\n * addition to a textual location. */\n PresenceGps = 'presence-gps',\n /** Notifier accepts an inline / URL image attachment. */\n NotifierImage = 'notifier-image',\n /** Notifier accepts a priority hint (high/normal/low). */\n NotifierPriority = 'notifier-priority',\n /** Notifier accepts a free-form `data` payload for platform-specific\n * fields. */\n NotifierData = 'notifier-data',\n /** Notifier supports interactive action buttons / callbacks. */\n NotifierActions = 'notifier-actions',\n /** Notifier supports per-call recipient targeting (multi-user). */\n NotifierRecipients = 'notifier-recipients',\n /** Script runner accepts a variables map on each run invocation. */\n ScriptVariables = 'script-variables',\n /** Automation `trigger` accepts a skipCondition flag — fires the\n * automation's actions while bypassing its condition block. */\n AutomationSkipCondition = 'automation-skip-condition',\n}\n\nexport enum ChargingStatus {\n ChargingDC = 'charging-dc',\n ChargingSolar = 'charging-solar',\n NotCharging = 'not-charging',\n}\n\n/**\n * Semantic role a device plays within its parent. Populated by driver\n * addons when creating accessory devices (Reolink siren/floodlight/\n * PIR/chime/autotrack/doorbell, ONVIF relay outputs, …). Used by the\n * admin UI to pick icons, labels, and widgets — a `Switch` with\n * `role: Floodlight` renders as a bulb with a brightness slider,\n * whereas a `Switch` with `role: Siren` renders as a klaxon.\n *\n * Undefined for top-level devices (cameras, NVRs, hubs). Persisted in\n * sqlite as a nullable TEXT column — old rows keep working unchanged.\n */\nexport enum DeviceRole {\n // ── Switch-type accessories (camera-driven) ──────────────\n Siren = 'siren',\n Floodlight = 'floodlight',\n Spotlight = 'spotlight',\n PirSensor = 'pir-sensor',\n Chime = 'chime',\n Autotrack = 'autotrack',\n Nightvision = 'nightvision',\n PrivacyMask = 'privacy-mask',\n\n // ── Button-type accessories ──────────────────────────────\n Doorbell = 'doorbell',\n\n // ── Switch sub-roles (HA-driven) ─────────────────────────\n /** Virtual HA toggle (input_boolean.*) — distinguishable from a\n * real Switch device for UI rendering / export adapters. */\n BinaryHelper = 'binary-helper',\n\n // ── Sensor sub-roles — binary_sensor family ──────────────\n /** Generic motion / occupancy / moving event source. Distinct from\n * the camera accessory PirSensor role: that one is a camera child;\n * this is a standalone HA / 3rd-party motion sensor. */\n MotionSensor = 'motion-sensor',\n ContactSensor = 'contact-sensor',\n LeakSensor = 'leak-sensor',\n SmokeSensor = 'smoke-sensor',\n COSensor = 'co-sensor',\n GasSensor = 'gas-sensor',\n TamperSensor = 'tamper-sensor',\n VibrationSensor = 'vibration-sensor',\n ConnectivitySensor = 'connectivity-sensor',\n SoundSensor = 'sound-sensor',\n /** Fallback for `binary_sensor` without a known `device_class`. */\n BinarySensor = 'binary-sensor',\n\n // ── Sensor sub-roles — numeric ───────────────────────────\n TemperatureSensor = 'temperature-sensor',\n HumiditySensor = 'humidity-sensor',\n AmbientLightSensor = 'ambient-light-sensor',\n PressureSensor = 'pressure-sensor',\n PowerSensor = 'power-sensor',\n EnergySensor = 'energy-sensor',\n VoltageSensor = 'voltage-sensor',\n CurrentSensor = 'current-sensor',\n AirQualitySensor = 'air-quality-sensor',\n /** Battery level (numeric % via `sensor` OR low-bool via\n * `binary_sensor` — the cap distinguishes via the value type). */\n BatterySensor = 'battery-sensor',\n /** Fallback for `sensor` numeric without a known `device_class`. */\n NumericSensor = 'numeric-sensor',\n /** String / enum state (HA `sensor` with `state_class: enum` or\n * `attributes.options`). */\n EnumSensor = 'enum-sensor',\n /** Date / timestamp state (HA `sensor` with `device_class: timestamp`\n * or `date`). The slice carries the raw ISO string verbatim (hosted on\n * the `enum-sensor` cap); the UI renders it locale-formatted. */\n DateTimeSensor = 'datetime-sensor',\n /** Last-resort fallback when nothing else matches. */\n GenericSensor = 'generic-sensor',\n\n // ── Control sub-roles (input setters) ────────────────────\n NumericControl = 'numeric-control',\n SelectControl = 'select-control',\n TextControl = 'text-control',\n DateTimeControl = 'datetime-control',\n\n // ── Notifier sub-roles ───────────────────────────────────\n /** Mobile push notifier (HA `notify.mobile_app_*`) — supports\n * rich features (image, priority, channel routing). */\n MobilePushNotifier = 'mobile-push-notifier',\n /** Chat / messaging service (HA `notify.telegram_*`,\n * `notify.discord_*`, etc.). */\n MessagingNotifier = 'messaging-notifier',\n /** Email-based delivery (HA `notify.smtp`, etc.). */\n EmailNotifier = 'email-notifier',\n /** Fallback when the notifier service name doesn't match a known\n * pattern. */\n GenericNotifier = 'generic-notifier',\n}\n","/**\n * Accessory device helpers — shared across drivers.\n *\n * Many vendor-specific drivers register accessory child devices on\n * top of a parent (Reolink: siren / floodlight / PIR / autotrack /\n * chime; ONVIF: relay outputs; future: Tapo Hub child devices). Each\n * driver picks the right `DeviceType` + `DeviceRole` explicitly when\n * spawning, builds a name derived from the parent, and produces a\n * stableId tied to the parent so boot-restore can reconstruct the\n * relationship.\n *\n * Centralised `(kind → DeviceType)` mapping was dropped on purpose:\n * drivers may reasonably disagree on the right type for an accessory\n * (a Reolink PIR exposes a switch on/off + sensitivity, while a hypothetical\n * read-only motion-only sensor might be `DeviceType.Sensor`). Forcing\n * one canonical mapping was over-prescriptive and added a layer of\n * indirection without saving meaningful code at call sites — the\n * driver knows its own hardware best.\n */\nimport { DeviceRole } from './device-type.js'\n\n/**\n * Subset of `DeviceRole` values that drivers register as child\n * accessories of a parent device. Sourced verbatim from `DeviceRole`\n * — `AccessoryKind` is the alias drivers use when building accessory\n * children, so the call site reads as\n * `accessoryStableId(parent, AccessoryKind.Siren)` rather than\n * `accessoryStableId(parent, DeviceRole.Siren)` (which would imply\n * any role works, including non-accessory ones like Doorbell).\n */\nexport const AccessoryKind = {\n Siren: DeviceRole.Siren,\n Floodlight: DeviceRole.Floodlight,\n Spotlight: DeviceRole.Spotlight,\n PirSensor: DeviceRole.PirSensor,\n Chime: DeviceRole.Chime,\n Autotrack: DeviceRole.Autotrack,\n Nightvision: DeviceRole.Nightvision,\n PrivacyMask: DeviceRole.PrivacyMask,\n} as const\n\nexport type AccessoryKindValue = typeof AccessoryKind[keyof typeof AccessoryKind]\n\n/**\n * Default English label for each accessory kind. Drivers append this\n * to the parent's name — e.g. `\"Living Room Siren\"` for a camera named\n * `\"Living Room\"`. Localisation lives in the UI layer; the driver only\n * has to surface a stable English name.\n */\nexport const ACCESSORY_LABEL: Record<AccessoryKindValue, string> = {\n [AccessoryKind.Siren]: 'Siren',\n [AccessoryKind.Floodlight]: 'Floodlight',\n [AccessoryKind.Spotlight]: 'Spotlight',\n [AccessoryKind.PirSensor]: 'PIR',\n [AccessoryKind.Chime]: 'Chime',\n [AccessoryKind.Autotrack]: 'Autotracking',\n [AccessoryKind.Nightvision]: 'Night Vision',\n [AccessoryKind.PrivacyMask]: 'Privacy Mask',\n}\n\n/**\n * Canonical stableId for an accessory child. Format: `${parent}:${role}`\n * for single-instance accessories; drivers that need multiple instances\n * of the same kind (e.g. wireless chimes) pass an extra `index` token\n * which the helper appends as `:${index}`.\n *\n * The stableId is the persistence key the device-manager uses to\n * resolve `(addonId, stableId) → numeric id` across reboots, so it\n * MUST be stable across runs. Using the parent's stableId + the role\n * meets this — a driver can re-create children deterministically as\n * long as the parent's stableId is also stable (which the platform\n * already guarantees).\n */\nexport function accessoryStableId(\n parentStableId: string,\n kind: AccessoryKindValue,\n index?: number,\n): string {\n const base = `${parentStableId}:${kind}`\n return typeof index === 'number' ? `${base}:${index}` : base\n}\n","/**\n * Bindings × Modes contract\n * ─────────────────────────\n *\n * Two independent layers gate every analyzer phase (detection / audio):\n *\n * 1. **Bindings** (low-level wiring, escape hatch)\n * The cap-router decides whether the addon is MOUNTED for a\n * device at all. `setWrapperActive(deviceId, capName, false)`\n * fully dismounts the cap; nothing the cap exposes (provider\n * methods, runtime-state, events) is reachable. The operator\n * rarely touches this from the UI — it's the \"uninstall this\n * addon for this device\" button. Default: every wrapper bound.\n *\n * 2. **Modes** (operator-facing scheduling)\n * The `detectionMode` / `audioMode` selectors decide WHEN the\n * mounted cap actually fires. `'disabled'` is the runtime-level\n * off switch — the cap stays mounted, schema present, RPCs\n * callable, but the runner / orchestrator skip the substream\n * subscriber. The other 2 modes (`'always-on'`, `'on-motion'`)\n * drive when the subscribe + analyze cycle runs.\n *\n * **AND-gate semantics**: a phase fires iff `(binding bound) AND\n * (mode != 'disabled')`. Either layer disables → cap inactive.\n * Neither layer overrides the other; the operator picks whichever\n * lever maps to their intent.\n *\n * - \"I never want SW detection on this camera\" → unbind via\n * bindings UI (extreme — also disables the cap surface).\n * - \"Pause detection for now, keep wired\" → set\n * `detectionMode = 'disabled'`. Settings still surface; no\n * substream demand.\n * - \"Detection only when motion fires\" → `detectionMode = 'on-motion'`,\n * binding stays bound.\n *\n * Profile defaults populate modes when the operator hasn't picked.\n * Bindings are bound by their wrappers' `defaultActive: true` flag,\n * unaffected by the profile.\n *\n * ─────────────────────────\n *\n * DeviceProfile — declarative defaults applied to devices that match a\n * feature predicate.\n *\n * Solves the \"battery cams shouldn't run continuous analyzers\" problem\n * (and adjacent policy questions like low-bandwidth fallback) by\n * centralising the operator-facing defaults in ONE place. The profile\n * does NOT touch capability bindings — those stay as the low-level\n * wiring escape hatch. Instead the profile drives the per-device\n * pipeline behaviour through three operator-visible \"mode\" knobs that\n * the runner / orchestrator interpret directly.\n *\n * - `motionSources` — already a per-device setting today; the profile\n * just supplies a sensible default (`['onboard']` when firmware\n * motion is available; `[]` otherwise so a battery cam with no PIR\n * and no firmware push gates everything off until the operator opts\n * into `'analyzer'` SW motion).\n *\n * - `audioMode` (NEW) — selects when the audio classifier runs:\n * `'disabled'`, `'always-on'`, `'on-motion'`. Replaces the implicit\n * \"audio runs when wrapper bound\" behaviour. Wrappers stay bound;\n * the addon reads this mode at runtime to decide whether to\n * subscribe to the audio decoded stream.\n *\n * - `detectionMode` (NEW) — selects when object detection runs:\n * `'disabled'`, `'always-on'`, `'on-motion'`. Mirrors `audioMode`\n * and replaces the legacy `priority: 'default'|'always-on'` toggle\n * with explicit semantics.\n *\n * ─── Sticky-by-construction ───────────────────────────────────────────\n *\n * Nothing in the runtime re-applies a profile. Operator changes always\n * win because the persistence layer captures them as concrete entries\n * (config blob value); the profile is consulted only when no entry\n * exists yet. If a setting is absent from the blob the resolver falls\n * back to the profile's default, then the schema's static default.\n */\nimport type { DeviceFeature } from './device-type.js'\nimport { DeviceFeature as Feature } from './device-type.js'\n\n/**\n * Match clause: the profile applies to a device iff its `features`\n * array contains `hasFeature`. Single-feature gate keeps matching\n * cheap; the profile-stack iterates in order and the first match wins.\n */\nexport interface DeviceProfileMatch {\n readonly hasFeature: DeviceFeature\n}\n\n/**\n * When-mode selector for analyzer phases (audio classification, object\n * detection). `'disabled'` keeps the addon idle; `'always-on'` runs\n * continuously; `'on-motion'` activates only when the motion-gate is\n * open (firmware motion event OR analyzer-derived motion).\n */\nexport type PipelinePhaseMode =\n | 'disabled'\n | 'always-on'\n | 'on-motion'\n\n/**\n * Operator-facing settings the profile populates at creation time +\n * resolver fallback time. These are NOT tightly bound to a single\n * config schema field — the resolver (in pipeline-orchestrator) reads\n * them when computing the runner config, and persists operator changes\n * back to the same keys via the existing per-device store.\n */\nexport interface DeviceProfileDefaults {\n /** Default `motionSources` array when the operator hasn't picked\n * one. Empty array means \"no motion source\" — useful for battery\n * cams without firmware motion (operator opts into `'analyzer'`\n * explicitly to enable SW motion). PIR-sourced motion currently\n * flows through `'onboard'` because Reolink's accessory PIRs feed\n * the parent camera's firmware motion event channel. */\n readonly motionSources?: readonly ('onboard' | 'analyzer')[]\n readonly audioMode?: PipelinePhaseMode\n readonly detectionMode?: PipelinePhaseMode\n}\n\nexport interface DeviceProfile {\n readonly id: string\n readonly label: string\n readonly when: DeviceProfileMatch\n /**\n * Default phase modes + motion-source pick. Resolver reads these\n * when no operator value is persisted; profile never overrides a\n * concrete operator choice.\n */\n readonly defaults: DeviceProfileDefaults\n /**\n * Generic settings overrides (snapshot interval, pre-buffer flag,\n * etc.). Same sticky semantics as defaults — applied on first read,\n * operator override wins. Keys are dot-paths interpreted by the\n * per-driver / per-addon config schema.\n */\n readonly settings: Readonly<Record<string, unknown>>\n}\n\n/**\n * Heuristic check — `device.features?.includes(profile.when.hasFeature)`.\n */\nexport function deviceMatchesProfile(\n features: readonly string[] | undefined,\n profile: DeviceProfile,\n): boolean {\n if (!features || features.length === 0) return false\n return features.includes(profile.when.hasFeature)\n}\n\n/**\n * Battery-operated cameras default policy. The substream stays dialed\n * only when there's something for the runner to actually process —\n * audio is off, detection only runs on motion.\n *\n * `motionSources` is NOT in the profile defaults: the orchestrator's\n * resolver already prefers `'onboard'` whenever the device exposes a\n * native motion cap (firmware-driven motion), independent of profile.\n * Battery cams without firmware motion fall back to `[]` (no source) —\n * the operator must opt into `'analyzer'` SW motion explicitly.\n *\n * Object detection on motion: when motion fires, the runner attaches\n * the substream + runs detection until the motion gate closes, then\n * releases. Firmware idle-disconnect fires shortly after, the camera\n * goes back to sleep.\n */\nexport const BATTERY_DEVICE_PROFILE: DeviceProfile = {\n id: 'battery',\n label: 'Battery-operated camera',\n when: { hasFeature: Feature.BatteryOperated },\n defaults: {\n audioMode: 'disabled',\n detectionMode: 'on-motion',\n },\n settings: {\n 'snapshot.minRefreshIntervalSec': 3600,\n 'streamBroker.preBufferEnabled': false,\n },\n}\n\n/**\n * Profile registry — order matters when multiple profiles match the\n * same device (first match wins). Today there's only one entry.\n */\nexport const DEVICE_PROFILES: readonly DeviceProfile[] = [\n BATTERY_DEVICE_PROFILE,\n]\n\n/**\n * Resolve the profile that matches a device's features, or `null` when\n * no profile matches. First-match-wins.\n */\nexport function resolveDeviceProfile(\n features: readonly string[] | undefined,\n): DeviceProfile | null {\n for (const profile of DEVICE_PROFILES) {\n if (deviceMatchesProfile(features, profile)) return profile\n }\n return null\n}\n","import { z } from 'zod'\nimport { type CapabilityDefinition, type InferProvider } from './capability-definition.js'\n\n/**\n * Generic device-level status snapshot. Auto-registered by `BaseDevice`\n * for every device, regardless of provider — the kernel needs a uniform\n * cap-keyed slice for the basic device flags every consumer expects to\n * read across processes (the `online` flag in particular). Driver-specific\n * caps (`battery`, `doorbell`, …) carry their domain-specific state on\n * their own slices.\n *\n * Pattern is identical to `battery`: schema-bearing `runtimeState`,\n * empty `methods`, single change event. Reads land at\n * `runtimeState.getCapState('device-status')`; writes at\n * `runtimeState.setCapState('device-status', …)`. Cross-process\n * consumers reach the same data via the `device-state` cap router\n * (`getCapSlice({deviceId, capName: 'device-status'})`).\n */\nexport const DeviceStatusSchema = z.object({\n /**\n * Device-level liveness. Drivers flip via `markOnline(boolean)` on\n * `BaseDevice`. Provider semantics vary — RTSP aggregates broker\n * stream-health, Reolink reads firmware push events, ONVIF tracks\n * ping responses. This cap intentionally does NOT prescribe which\n * signal drives the flag.\n */\n online: z.boolean(),\n /** Ms epoch of the last `online` transition. Lets consumers tell\n * apart \"just came online\" from \"still online\". */\n lastChangedAt: z.number(),\n})\n\nexport type DeviceStatus = z.infer<typeof DeviceStatusSchema>\n\nexport const deviceStatusCapability = {\n name: 'device-status',\n scope: 'device',\n deviceNative: true,\n mode: 'singleton',\n methods: {},\n events: {\n /** Emitted when `online` transitions. Mirrors the semantics of\n * `battery.onStatusChanged`. */\n onStatusChanged: { data: z.object({\n deviceId: z.number(),\n status: DeviceStatusSchema,\n })},\n },\n status: {\n schema: DeviceStatusSchema,\n kind: 'push',\n },\n runtimeState: DeviceStatusSchema,\n} as const satisfies CapabilityDefinition\n\nexport type IDeviceStatusProvider = InferProvider<typeof deviceStatusCapability>\n","import { z } from 'zod'\nimport { type CapabilityDefinition, type InferProvider } from './capability-definition.js'\n\n/**\n * Per-device feature/identity probe slice. Holds the runtime-resolved\n * truth about what a device CAN do — which the kernel uses to:\n * 1. Reconcile accessory children (hub-children spawn siren/floodlight/PIR\n * based on what the firmware actually advertises).\n * 2. Compute the public `features: DeviceFeature[]` array surfaced via\n * `device-manager.listAll`.\n * 3. Decide which optional caps (PTZ, intercom, doorbell, battery, …)\n * to register on the device's capability surface.\n *\n * Auto-registered by `BaseDevice` for every device. Drivers populate the\n * slice from `onProbe()` (kernel calls it once after register, before\n * accessory reconciliation). Consumers read via:\n * `runtimeState.getCapState<FeatureProbeStatus>('feature-probe')`\n *\n * `flags` is an open record so each driver carries its own keys without\n * a centralized schema bottleneck — Reolink writes `hasPtz/hasIntercom`,\n * Hikvision writes `hasSupplementalLight/hasAlarmIo`, etc.\n *\n * Replaces the older driver-local `deviceCache.has*` blob: the per-device\n * config is for operator-edited overrides + UI snapshots; runtime probe\n * results belong in runtime-state where the kernel handles persistence,\n * cross-process mirroring, and reactive updates.\n */\nexport const FeatureProbeStatusSchema = z.object({\n /**\n * Driver-specific flag bag. Each driver picks its own key names — the\n * cap deliberately does NOT enforce a closed enum here. Reolink keys:\n * `hasPtz`, `hasIntercom`, `hasDoorbell`, `hasFloodlight`, `hasSiren`,\n * `hasPirSensor`, `hasAutotrack`, `hasBattery`. Hikvision keys:\n * `hasSupplementalLight`, `lightHasWhiteLight`, `hasAlarmIo`, `hasPtz`.\n */\n flags: z.record(z.string(), z.unknown()),\n /**\n * Coarse driver-classification — lets cross-process consumers tell apart\n * cameras / battery-cams / NVRs without re-running the probe. `null`\n * before the first probe completes.\n */\n deviceType: z.string().nullable(),\n /** Camera/firmware model string. `null` when the firmware doesn't expose it. */\n model: z.string().nullable(),\n /** Channel count for NVR/Hub devices; `1` for standalone cameras; `null` pre-probe. */\n channelCount: z.number().nullable(),\n /**\n * Ms epoch of the last SUCCESSFUL probe. `0` before the first probe\n * completes — drivers' `getAccessoryChildren()` should treat zero as\n * \"probe not done yet, return empty\" so accessories aren't spawned\n * before the firmware is queried.\n */\n lastProbedAt: z.number(),\n /**\n * Framework convention: every runtime-state slice carries this for the\n * createRuntimeStateBridge stale-check helper. We keep it in sync with\n * `lastProbedAt` on every write.\n */\n lastFetchedAt: z.number(),\n})\n\nexport type FeatureProbeStatus = z.infer<typeof FeatureProbeStatusSchema>\n\nexport const featureProbeCapability = {\n name: 'feature-probe',\n scope: 'device',\n deviceNative: true,\n mode: 'singleton',\n methods: {},\n events: {\n /** Fires whenever a fresh probe completes (kernel-driven `reprobe()`\n * or driver-initiated re-detect after a state change). */\n onProbeChanged: { data: z.object({\n deviceId: z.number(),\n status: FeatureProbeStatusSchema,\n })},\n },\n status: {\n schema: FeatureProbeStatusSchema,\n kind: 'push',\n },\n runtimeState: FeatureProbeStatusSchema,\n} as const satisfies CapabilityDefinition\n\nexport type IFeatureProbeProvider = InferProvider<typeof featureProbeCapability>\n","import { z } from 'zod'\nimport { type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\n\n/**\n * Multi-metric air-quality slice. Covers CO₂, total VOCs, particulate\n * matter at PM2.5 / PM10, and a derived AQI index — all optional so\n * a single-metric source populates only what it observes. Mirrors\n * the HA `sensor` device_class set (`co2`, `volatile_organic_compounds`,\n * `pm25`, `pm10`, `aqi`) collapsed into one cap because a typical\n * air-quality node reports several of these together; modelling them\n * as siblings keeps a single timestamp + one slice subscription.\n */\nexport const AirQualitySensorStatusSchema = z.object({\n /** Carbon dioxide concentration in ppm. */\n co2Ppm: z.number().min(0).optional(),\n /** Total volatile organic compounds in ppb. */\n vocPpb: z.number().min(0).optional(),\n /** Particulate matter ≤ 2.5 μm in µg/m³. */\n pm25: z.number().min(0).optional(),\n /** Particulate matter ≤ 10 μm in µg/m³. */\n pm10: z.number().min(0).optional(),\n /** Composite AQI value (typically 0..500). */\n aqi: z.number().optional(),\n /** Ms epoch when the slice was last updated. */\n lastFetchedAt: z.number(),\n /** Live display unit of the single metric this slice carries (e.g. HA\n * `attributes.unit_of_measurement` → 'ppm' / 'ppb' / 'µg/m³'). Each\n * upstream `sensor.*` entity surfaces ONE device_class, so one unit\n * per slice is unambiguous. */\n unit: z.string().optional(),\n /** Suggested decimal places for numeric display.\n * Populated live from the upstream source when provided (e.g. HA\n * `attributes.suggested_display_precision`). Falls back to\n * auto-formatting when absent. */\n precision: z.number().int().min(0).max(10).optional(),\n})\n\nexport type AirQualitySensorStatus = z.infer<typeof AirQualitySensorStatusSchema>\n\nexport const airQualitySensorCapability = {\n name: 'air-quality-sensor',\n scope: 'device',\n deviceNative: true,\n mode: 'singleton',\n deviceTypes: [DeviceType.Sensor],\n methods: {},\n status: {\n schema: AirQualitySensorStatusSchema,\n kind: 'push',\n },\n runtimeState: AirQualitySensorStatusSchema,\n} as const satisfies CapabilityDefinition\n\nexport type IAirQualitySensorProvider = InferProvider<typeof airQualitySensorCapability>\n","/**\n * Generic types for capability definitions.\n *\n * A capability is defined with Zod schemas for methods, events, and settings.\n * TypeScript types are inferred via z.infer<> — zero duplication.\n *\n * Pattern:\n * 1. Define Zod schemas for data, methods, settings\n * 2. Export const capabilityDef = { ... } satisfies CapabilityDefinition\n * 3. Export type IProvider = InferProvider<typeof capabilityDef>\n * 4. Addon implements IProvider\n * 5. Registry auto-mounts tRPC router from definition.methods\n */\n\nimport { z } from 'zod'\nimport { DeviceType } from '../device/device-type.js'\nimport type { ConfigUISchemaWithValues } from '../interfaces/config-ui.js'\n\n// ── Method & Event Schemas ───────────────────────────────────────────\n\n/**\n * tRPC procedure kind.\n * - 'query': read-only, no side effects\n * - 'mutation': write operation, side effects\n * - 'subscription': push-based real-time stream via WebSocket\n */\nexport type CapabilityMethodKind = 'query' | 'mutation' | 'subscription'\n\n/**\n * Auth level required to call a capability method.\n * `superAdmin` was removed — every destructive op is gated by `admin`\n * (the unscoped role) which the middleware lets through unconditionally.\n */\nexport type CapabilityMethodAuth = 'public' | 'protected' | 'admin'\n\n/**\n * Optional semantic role used by the admin UI's unified \"Integrations\"\n * page to group caps by what kind of external system they integrate\n * with. Caps without `providerKind` are infra-internal (decoders,\n * device providers, pipeline steps, …) and never surface there.\n *\n * - `broker` — message brokers (MQTT, future Kafka)\n * - `device-export` — outbound exporters (HomeKit, Alexa, HA-MQTT)\n * - `email` — email delivery relays (SMTP, future SendGrid)\n * - `mesh` — mesh-VPN providers (Tailscale, Headscale, …)\n * - `ingress` — public-ingress tunnels (Cloudflare Tunnel, …)\n */\nexport type ProviderKind =\n | 'broker'\n | 'device-export'\n | 'email'\n | 'mesh'\n | 'ingress'\n\n/**\n * Access flavour for a capability method. Drives the scope-access check\n * in `protectedProcedure`. Default inferred at codegen time:\n * - `kind: 'query'` → `view`\n * - `kind: 'mutation'` → `create`\n * - name match `^(delete|remove|revoke|destroy|drop|purge|clear|reset|forget)` → `delete`\n * An explicit `access` on the method options overrides the heuristic.\n */\nexport type CapabilityMethodAccess = 'view' | 'create' | 'delete'\n\n/** Schema pair for a single capability method: input + output + routing metadata. */\nexport interface CapabilityMethodSchema<\n TInput extends z.ZodType = z.ZodType,\n TOutput extends z.ZodType = z.ZodType,\n TKind extends CapabilityMethodKind = CapabilityMethodKind,\n> {\n readonly input: TInput\n readonly output: TOutput\n /** tRPC procedure kind. Default: 'query'. */\n readonly kind: TKind\n /** Auth level. Default: 'protected'. */\n readonly auth: CapabilityMethodAuth\n /** Per-method access flavour. When unset, codegen derives it from `kind` + name heuristic. */\n readonly access?: CapabilityMethodAccess\n /** Moleculer action timeout override (ms). Overrides broker global requestTimeout for this action only. */\n readonly timeoutMs?: number\n}\n\n/** Schema for a capability event (emitted to EventBus) */\nexport interface CapabilityEventSchema<\n TData extends z.ZodType = z.ZodType,\n> {\n readonly data: TData\n}\n\n// ── Status (live readable machine-state per device) ─────────────────\n//\n// A cap can declare a `status` block describing the MACHINE-READABLE\n// snapshot of the device's current state for this capability (battery\n// percentage, PTZ position, intercom talking flag, …). When present,\n// the provider interface gains `getStatus({ deviceId })` auto-injected\n// via `InferProvider`. Distinct from `getDeviceSettingsContribution`\n// which is the UI-schema for human-editable settings.\n\nexport type CapabilityStatusKind = 'push' | 'poll' | 'command-driven'\n\nexport interface CapabilityStatusSchema<TStatus extends z.ZodType = z.ZodType> {\n readonly schema: TStatus\n /** Documentation hint on update cadence — used by the aggregator and UI. */\n readonly kind?: CapabilityStatusKind\n}\n\n// ── Declarative UI contribution descriptor ──────────────────────────\n//\n// A pure-data descriptor for a Module-Federation-hosted UI surface. The\n// widget descriptor (`addon-widgets-source`) builds on this shape — the\n// React component is resolved via the ui-library registry at runtime,\n// so the descriptor stays free of any React coupling.\n\n/** How a contribution's component is resolved by the renderer. */\nexport type UiContributionKind = 'remote'\n\n/** One declarative UI piece — a Module-Federation widget. Pure data: no React. */\nexport interface UiContribution {\n /** Top-level host tab id. */\n readonly tab: string\n /** Optional sub-tab within `tab`. */\n readonly subTab?: string\n /** Human-readable tab/section label. */\n readonly label: string\n /** Ordering within (tab, subTab), ascending. Default 100. */\n readonly order?: number\n /** Always `'remote'` — the component is a Module Federation remote. */\n readonly kind: UiContributionKind\n /** The Module Federation remote descriptor. */\n readonly remote?: UiContributionRemote\n}\n\n/**\n * Module Federation remote descriptor for a `kind:'remote'`\n * {@link UiContribution}.\n *\n * `exposedModule` names the module the remote exposes (widget remotes\n * always expose `'./widgets'`). Widget remotes export that module as a\n * `Record<componentKey, Component>` map rather than a single default\n * component, so `componentKey` selects which entry to mount. When\n * `componentKey` is omitted the loader uses the module's `default`\n * export directly (single-component remotes).\n */\nexport interface UiContributionRemote {\n /** MF remote name — matches the `name` in the addon's `federation()` config. */\n readonly remoteName: string\n /** Exposed module path inside the remote (e.g. `'./widgets'`). */\n readonly exposedModule: string\n /** Key inside the exposed module's default-record map (the widget `stableId`). */\n readonly componentKey?: string\n}\n\n// ── Declarative settings bindings ───────────────────────────────────\n//\n// A cap's `settings.bindings` spec lets the device-manager auto-derive\n// both `getDeviceSettingsContribution` (UI schema with live values) and\n// `applyDeviceSettingsPatch` (patch → cap method dispatch) without the\n// provider implementing a single line of FormBuilder code. The provider\n// only implements the imperative cap methods; the framework wires up\n// the admin-UI form from these bindings.\n\n/** Supported field kinds in settings bindings. Deliberately limited — mirror FormBuilder primitives. */\nexport type CapSettingsFieldKind = 'boolean' | 'text' | 'number' | 'select'\n\n/** Scalar (single value) binding — target a single scalar path inside `status`. */\nexport interface CapSettingsScalarBinding {\n readonly kind: 'scalar'\n /** Dot-path into `status` where the current value lives. */\n readonly statusPath: string\n /** Cap method invoked when the field changes. Must exist in `methods`. */\n readonly method: string\n /** Name of the method's input arg that receives the new value. */\n readonly valueArg: string\n readonly field: {\n readonly label: string\n readonly kind: CapSettingsFieldKind\n readonly options?: readonly string[]\n }\n /** Optional section override (default: capability name). */\n readonly sectionId?: string\n readonly sectionTitle?: string\n}\n\n/** Array binding — target an array path in `status`, render one row per item. */\nexport interface CapSettingsArrayBinding {\n readonly kind: 'array'\n /** Dot-path into `status` pointing at an array. */\n readonly statusPath: string\n /** Field on each array item used as stable id (e.g. 'id'). */\n readonly idField: string\n /** Cap method invoked on any per-item field change. */\n readonly method: string\n /** Method input arg that receives the item id (e.g. 'overlayId'). */\n readonly idArg: string\n /** Method input arg that receives the patch object. */\n readonly patchArg: string\n readonly sectionId: string\n readonly sectionTitle: string\n readonly itemFields: Readonly<Record<string, CapSettingsItemField>>\n}\n\nexport interface CapSettingsItemField {\n /** Static string or per-item resolver (runs server-side at contribution time). */\n readonly label: string | ((item: Record<string, unknown>) => string)\n readonly kind: CapSettingsFieldKind\n /** Select options — static array or per-item resolver. */\n readonly options?: readonly string[] | ((item: Record<string, unknown>) => readonly string[])\n /** Visibility predicate — hide the field for items returning false. */\n readonly when?: (item: Record<string, unknown>) => boolean\n}\n\nexport type CapSettingsBinding = CapSettingsScalarBinding | CapSettingsArrayBinding\n\nexport interface CapabilitySettingsSpec {\n readonly bindings: readonly CapSettingsBinding[]\n}\n\n// ── Device-config archetype (D14) ───────────────────────────────────\n//\n// The camera-config caps (stream-params, motion-zones, ptz, …) share an\n// archetype: scope:'device', native, multi-vendor, status + runtimeState\n// + a `getOptions` availability descriptor + `set*` mutations. The\n// device-detail UI for such a cap is FULLY DERIVABLE from what the cap\n// declares — the framework derives the aggregate contribution and the\n// save routing, so no per-vendor contribution code is written.\n\n/**\n * `deviceConfig.ui` selects how the framework derives the device-detail\n * UI section for the cap:\n *\n * - `kind: 'derived-form'` — the section is a generated form. The\n * framework calls the cap's `getOptions` + `getStatus`, runs the\n * declared pure `buildSchema` reducer, and routes the flat form\n * patch back through the declared `applyPatch` reducer + `set*`\n * method. Used by `stream-params`.\n * - `kind: 'widget'` — the section is a single `type:'widget'`\n * ConfigField embedding a live React component (resolved host-side\n * by `widgetId`). The widget self-persists via the cap's own\n * mutations; the framework emits only the structural section.\n * Used by `motion-zones`, `ptz`, `ptz-autotrack`.\n */\nexport interface DeviceConfigDerivedFormUi {\n readonly kind: 'derived-form'\n /** Identifier of the registered pure derivation (see device-config-contribution.ts). */\n readonly builderId: string\n /** Tab id the generated section is placed under. */\n readonly tab: string\n}\nexport interface DeviceConfigWidgetUi {\n readonly kind: 'widget'\n /** Host widget id resolved by the admin-ui WidgetSlot. */\n readonly widgetId: string\n /** Tab id; with `topTab:true` the section is hoisted to its own device tab. */\n readonly tab: string\n readonly topTab?: boolean\n /** Section title + field label shown in the UI. */\n readonly label: string\n /** Section ordering within the tab. Default 0. */\n readonly order?: number\n}\nexport type DeviceConfigUiSpec = DeviceConfigDerivedFormUi | DeviceConfigWidgetUi\n\n/**\n * Marks a cap as a `deviceConfig` archetype. Presence of this block\n * tells the device-manager aggregator the cap's contribution is\n * framework-derived — the provider implements only the imperative cap\n * methods (`getOptions`, `getStatus`, `set*`), never the three\n * `DeviceSettingsContribution` methods.\n */\nexport interface DeviceConfigSpec {\n readonly ui: DeviceConfigUiSpec\n}\n\n// ── Capability Definition ────────────────────────────────────────────\n\n/**\n * Full definition of a capability — the single source of truth for the\n * functional contract (methods + events).\n *\n * Settings are NOT part of the capability definition — they belong to\n * the addon implementation. Each addon defines its own settings schema\n * via ICamstackAddon.getConfigSchema(), stored per-addon with optional\n * per-device overrides.\n */\nexport interface CapabilityDefinition<\n TName extends string = string,\n TMethods extends Record<string, CapabilityMethodSchema> = Record<string, CapabilityMethodSchema>,\n TEvents extends Record<string, CapabilityEventSchema> | undefined = Record<string, CapabilityEventSchema> | undefined,\n> {\n /** Unique capability name (kebab-case) */\n readonly name: TName\n /** system = global singleton/collection. device = per-device resolution. */\n readonly scope: 'system' | 'device'\n /**\n * Cardinality of active providers:\n * - `singleton` — exactly one active provider cluster-wide\n * (e.g. admin-ui, device-manager). User config can pick which addon\n * is active when multiple are registered.\n * - `collection` — every registered provider stays active\n * (e.g. decoder, notification-output).\n * - `per-node` — one active provider per node/agent. Every node that\n * hosts an addon for this cap runs its own independent provider;\n * consumers query `getProviderForNode(capName, nodeId)` instead of\n * `getSingleton(capName)`. Used for node-local probes\n * (platform-probe, metrics-provider, hwaccel-probe).\n */\n readonly mode: 'singleton' | 'collection' | 'per-node'\n /**\n * Provider registration kind — the single source of truth for whether\n * this capability's providers register as wrappers.\n *\n * - `'native'` / omitted — a plain provider; no wrapper registration.\n * - `'wrapper'` — the hub calls `registerWrapper(capName, addonId,\n * {defaultActive})` so the cap appears in\n * `device-manager.getBindings` / `listBindableCapsForDeviceType`\n * and can be auto-bound to devices.\n *\n * D4 (base-layer rework): moved here from the addon `package.json`\n * manifest and the runtime `ProviderRegistration`. The manifest now\n * declares only WHICH caps an addon provides. `ProviderRegistration\n * .kind` survives only as a deprecated, cross-checked hint.\n */\n readonly kind?: 'native' | 'wrapper'\n /**\n * Wrapper-only — when `true`, the wrapper is auto-bound for every\n * compatible device (claims the binding ahead of native providers).\n * Ignored unless `kind === 'wrapper'`. Default: `false`.\n */\n readonly defaultActive?: boolean\n /** True when this cap is registered PER-DEVICE via `ctx.registerNativeCap`\n * (the provider IS the device), so the tRPC layer must resolve it with\n * `requireDeviceScoped` → `getNativeProvider(capName, deviceId)`. Distinct\n * from `scope:'device'` SYSTEM caps (zones/recording/motion/events) whose\n * single provider dispatches on deviceId internally. Default: undefined/false. */\n readonly deviceNative?: boolean\n /** Method definitions: name → { input, output } Zod schemas */\n readonly methods: TMethods\n /** Event definitions: name → { data } Zod schema (optional) */\n readonly events?: TEvents\n /**\n * Typed machine-readable status snapshot. When present, the provider\n * interface gains `getStatus({ deviceId })` auto-injected via\n * `InferProvider`. Consumers poll via this method or subscribe via\n * `device-manager.subscribeDeviceStatusAggregate`. Distinct from\n * `getDeviceSettingsContribution` — that serves the UI editable-form\n * schema; `status` is the live readable state.\n */\n readonly status?: CapabilityStatusSchema\n\n /**\n * Per-device runtime-state slice owned by THIS cap. Persisted across\n * restarts under `device.state[capName]`. Every provider that\n * implements the cap inherits the same shape — drivers don't\n * redeclare it, they just write through `this.runtimeState\n * .setCapState('<capName>', value)`. Examples:\n *\n * - `batteryCapability.runtimeState`: `{ percentage, charging,\n * sleeping, lastUpdated }`. A Reolink Argus, a Frigate sensor\n * proxy, an ONVIF battery cam — every provider stores the\n * same shape under `state.battery`.\n * - `ptzCapability.runtimeState`: `{ pan, tilt, zoom }`.\n *\n * Caps without runtime state (pure-RPC like `reboot`) leave this\n * undefined; setCapState refuses to write to those slices.\n */\n readonly runtimeState?: import('zod').ZodObject<import('zod').core.$ZodLooseShape>\n /**\n * Declarative settings spec. When present, the device-manager's\n * settings aggregator auto-derives the ConfigUISchema and routes\n * patches back to the referenced imperative methods. The provider\n * implements ONLY the imperative methods — no manual FormBuilder\n * contribution code. Colocated with the cap for single-source-of-\n * truth ergonomics.\n */\n readonly settings?: CapabilitySettingsSpec\n /**\n * D14 device-config archetype. Mutually exclusive with\n * `exposesDeviceSettings` — a cap declares one or the other. When set,\n * the framework derives the device-detail contribution + save routing;\n * vendor providers carry NO contribution methods.\n */\n readonly deviceConfig?: DeviceConfigSpec\n /** For `scope: 'device'` caps — allowed device types. Omit → applies to every type. */\n readonly deviceTypes?: readonly DeviceType[]\n /**\n * When `true`, every provider of this capability MUST implement the\n * device-settings contribution surface — three extra methods appearing\n * automatically on the provider interface via `InferProvider`:\n *\n * - `getDeviceSettingsContribution({ deviceId })` → schema + values\n * for the device-details page (cached, slow cadence). Returns null\n * when the provider has nothing to contribute for the given device.\n * - `getDeviceLiveContribution({ deviceId })` → readonly live data\n * (status, counters). Returns null when not applicable. Polled ~2-3s.\n * - `applyDeviceSettingsPatch({ deviceId, patch })` → single-entry\n * mutation for field values returned by `getDeviceSettingsContribution`.\n * The provider owns the storage.\n *\n * The naming is intentionally distinct from the three-level addon API\n * (`getGlobalSettings` / `getDeviceSettings` / `getAddonSettings`) to\n * avoid collisions when an addon implements both surfaces on the same\n * class. The words \"Contribution\" and \"Patch\" signal these are aggregator\n * hooks, not persistent settings accessors.\n *\n * The `device-manager` aggregator enumerates bindings for the target\n * device, picks providers whose cap has this flag, and concatenates\n * the per-provider contributions into the single aggregate consumed\n * by `deviceManager.getDeviceSettingsAggregate`.\n */\n readonly exposesDeviceSettings?: boolean\n\n /**\n * Server-internal cap — registered for in-process consumption only.\n * NOT exposed via the SDK `System` proxy and NOT exposed via the\n * generated React hooks. Use this for collection caps whose\n * contributions are aggregated by another singleton cap (for example\n * `addon-pages-source` walked by the `addon-pages` aggregator) or for\n * declarative slots (`addon-routes`, `admin-ui`, `log-destination`,\n * `restreamer`, `streaming-engine`, `webrtc`) consumed by hub\n * builtins/addons via `capabilities.getCollection()` /\n * `getSingleton()`.\n *\n * Behaviour:\n * - cap-router codegen still emits a `createCapRouter_<Cap>` so the\n * router stays available for opt-in mounting (e.g. test harnesses);\n * `trpc.router.ts` simply does not reference it.\n * - system-proxy codegen skips it — `system.<cap>` is not minted.\n * - system-hooks codegen skips it — no `use<Cap><Method>` exports.\n * - The cap is still consumable internally via\n * `ctx.capabilities.getCollection()` / `getSingleton()` from\n * inside an addon.\n *\n * Default: `false` (cap is publicly mounted and exposed on the SDK\n * surface).\n */\n readonly internal?: boolean\n\n /**\n * Optional semantic role used by the admin UI's unified\n * \"Integrations\" page to group caps by what kind of external system\n * they integrate with. Omit for caps that are infra-internal\n * (decoders, providers, pipeline steps, …).\n *\n * See `ProviderKind` for the closed set of recognised values.\n */\n readonly providerKind?: ProviderKind\n\n /**\n * How the generated tRPC cap-router treats an input field named\n * `nodeId`:\n *\n * - `'routing'` (default): extract `nodeId` from the input and\n * route to that node via `createRemoteProxy`. Use when the cap\n * has a provider registered on every target node.\n *\n * - `'data'`: forward `nodeId` untouched to the local provider\n * as part of the method's input. Use when the cap has a\n * hub-centric provider that dispatches internally\n * (`broker.call('<addonId>.settings.<method>', ..., {nodeID})`).\n * `addon-settings` is the canonical example — one singleton on\n * the hub resolves `addonId` → worker nodeId by consulting the\n * cluster roster.\n */\n readonly nodeIdMode?: 'routing' | 'data'\n\n /**\n * For `mode: 'singleton'` caps with multiple possible provider addons —\n * the addon id that should be the DEFAULT active provider when no operator\n * preference (`setActiveSingleton`) is set. Makes active-provider selection\n * deterministic instead of registration-order-dependent. Ignored when an\n * operator preference exists (operator choice always wins) and for\n * non-singleton caps.\n */\n readonly preferredProvider?: string\n}\n\n/** Contract for the three methods added by `exposesDeviceSettings: true`. */\nexport interface DeviceSettingsContribution {\n readonly getDeviceSettingsContribution: (input: { readonly deviceId: number }) => Promise<ConfigUISchemaWithValues | null>\n readonly getDeviceLiveContribution: (input: { readonly deviceId: number }) => Promise<ConfigUISchemaWithValues | null>\n readonly applyDeviceSettingsPatch: (input: { readonly deviceId: number; readonly patch: Record<string, unknown> }) => Promise<{ readonly success: true }>\n}\n\n// ── DeviceSettingsContribution Zod schemas ──────────────────────────\n//\n// Zod-level counterparts to the TS interface above. Exposed so every\n// layer that walks a cap def's methods (Moleculer service factory,\n// tRPC cap-router codegen, remote-provider proxy builder) can treat\n// `exposesDeviceSettings: true` the same way it treats any other\n// method — just auto-spread these three into the methods map. The\n// interface stops being an implicit \"invisible surface\": every\n// provider of an `exposesDeviceSettings` cap exposes these three\n// actions as regular cap methods, reachable through Moleculer and\n// tRPC like everything else. No hidden in-process-only shortcuts.\n\n/**\n * Output schema shared by the contribution + live methods.\n *\n * Mirrors the `ConfigUISchemaWithValues` shape (sections[] + optional\n * tabs[]) without importing from `../interfaces/config-ui.js` — a\n * concrete-but-lenient Zod object keeps tRPC output inference happy\n * (using `z.unknown()` here collapses unrelated router branches to\n * `unknown` when the generator re-inlines the huge AppRouter type).\n *\n * `.passthrough()` on sections/fields accepts whatever FormBuilder\n * extensions the caller adds (showWhen, displayScale, …) without\n * rebuilding every time a new field kind is introduced.\n */\nconst ContributionSectionSchema = z.object({\n id: z.string(),\n title: z.string(),\n description: z.string().optional(),\n style: z.enum(['card', 'accordion']).optional(),\n defaultCollapsed: z.boolean().optional(),\n columns: z.union([z.literal(1), z.literal(2), z.literal(3), z.literal(4)]).optional(),\n tab: z.string().optional(),\n // Hoist the section into a top-level device tab (DeviceDetail\n // discovers these and renders one tab per unique `tab` id). Default\n // 'settings' keeps the section under the Config tab.\n location: z.enum(['settings', 'top-tab']).optional(),\n order: z.number().optional(),\n fields: z.array(z.any()),\n})\n\nconst ContributionTabSchema = z.object({\n id: z.string(),\n label: z.string(),\n icon: z.string(),\n order: z.number().optional(),\n})\n\nconst ContributionSchema = z.object({\n tabs: z.array(ContributionTabSchema).optional(),\n sections: z.array(ContributionSectionSchema),\n})\n\nconst ContributionOutputSchema = ContributionSchema.nullable()\n\nexport const DEVICE_SETTINGS_CONTRIBUTION_METHODS = {\n getDeviceSettingsContribution: {\n input: z.object({ deviceId: z.number() }),\n output: ContributionOutputSchema,\n kind: 'query',\n auth: 'protected',\n },\n getDeviceLiveContribution: {\n input: z.object({ deviceId: z.number() }),\n output: ContributionOutputSchema,\n kind: 'query',\n auth: 'protected',\n },\n applyDeviceSettingsPatch: {\n input: z.object({ deviceId: z.number(), patch: z.record(z.string(), z.unknown()) }),\n output: z.object({ success: z.literal(true) }),\n kind: 'mutation',\n auth: 'admin',\n },\n} as const satisfies Record<string, CapabilityMethodSchema>\n\n/**\n * Schema for the `getStatus` method auto-injected when a cap declares\n * `status`. The runtime shape of the output is the cap's own\n * `status.schema` — but at codegen time we need a concrete Zod to emit\n * a typed tRPC route, so we keep the output as `z.unknown().nullable()`\n * here and tighten it on the client side via the generated\n * `CapStatusTypeMap` (see `scripts/generate-cap-status-types.ts`).\n */\nexport const DEVICE_STATUS_METHOD = {\n getStatus: {\n input: z.object({ deviceId: z.number() }),\n output: z.unknown().nullable(),\n kind: 'query',\n auth: 'protected',\n },\n} as const satisfies Record<string, CapabilityMethodSchema>\n\n/**\n * Expand a cap def's methods map with every auto-injected method:\n * - `exposesDeviceSettings: true` → 3 contribution methods\n * - `status: {...}` → `getStatus`\n *\n * Callers walk `expandCapMethods(def)` instead of `def.methods` when\n * they need the effective runtime method surface (Moleculer actions,\n * proxy shape, tRPC router entries). The cap def stays the single\n * source of truth. Providers still declare their concrete `methods`\n * block; the expansion happens at every consumption point, so there's\n * no accidental divergence between the declared surface and what's\n * actually mounted.\n */\nexport function expandCapMethods(def: CapabilityDefinition): Record<string, CapabilityMethodSchema> {\n let out: Record<string, CapabilityMethodSchema> = def.methods\n if (def.exposesDeviceSettings) {\n out = { ...DEVICE_SETTINGS_CONTRIBUTION_METHODS, ...out }\n }\n if (def.status) {\n out = { ...DEVICE_STATUS_METHOD, ...out }\n }\n return out\n}\n\n// ── Type Inference Helpers ───────────────────────────────────────────\n\n/**\n * Infer the provider interface from a capability definition.\n *\n * All query/mutation methods return Promise<T> — this ensures consumers\n * can transparently call local or Moleculer-remote providers.\n * Providers may still implement methods as sync (return T); the Moleculer\n * action handler and tRPC router await the result either way.\n */\n/** Extract the status output type — or `never` when the cap has no status block. */\nexport type InferStatus<T extends CapabilityDefinition> =\n T extends { status: CapabilityStatusSchema<infer S> } ? z.infer<S> : never\n\n/** Contract for the `getStatus` method auto-injected when `status: {...}` is set. */\nexport interface DeviceStatusContribution<TStatus> {\n readonly getStatus: (input: { readonly deviceId: number }) => Promise<TStatus | null>\n}\n\nexport type InferProvider<T extends CapabilityDefinition> = {\n readonly [K in keyof T['methods']]: T['methods'][K] extends CapabilityMethodSchema<infer TIn, infer TOut>\n ? T['methods'][K]['kind'] extends 'subscription'\n ? (input: z.infer<TIn>, push: (value: z.infer<TOut>) => void) => (() => void) | void\n : (input: z.infer<TIn>) => Promise<z.infer<TOut>>\n : never\n} & (T['exposesDeviceSettings'] extends true ? DeviceSettingsContribution : Record<never, never>)\n & (T extends { status: CapabilityStatusSchema } ? DeviceStatusContribution<InferStatus<T>> : Record<never, never>)\n\n/**\n * Interface for native (per-device) providers — strips the\n * `DeviceSettingsContribution` surface that `exposesDeviceSettings: true`\n * bolts onto the system-level `InferProvider`.\n *\n * Native providers are registered via `DeviceContext.registerNativeCap`\n * and only serve the cap's device-scoped runtime methods for that single\n * device. They do NOT own per-device settings — those flow through the\n * addon's system-level provider's `applyDeviceSettingsPatch`, not\n * through the camera driver's native hook. Keeping the two surfaces\n * separate stops every device class (RtspCamera, OnvifCamera, …) from\n * having to stub out three unused methods.\n */\nexport type InferNativeProvider<T extends CapabilityDefinition> = {\n readonly [K in keyof T['methods']]: T['methods'][K] extends CapabilityMethodSchema<infer TIn, infer TOut>\n ? T['methods'][K]['kind'] extends 'subscription'\n ? (input: z.infer<TIn>, push: (value: z.infer<TOut>) => void) => (() => void) | void\n : (input: z.infer<TIn>) => Promise<z.infer<TOut>>\n : never\n} & (T extends { status: CapabilityStatusSchema }\n // Optional on native providers: not every driver can report status\n // (e.g. snapshot providers that only expose the fetch call). When\n // present the server-side aggregator uses it; when absent the cap's\n // status entry is reported as `null` in `getDeviceStatusAggregate`.\n ? Partial<DeviceStatusContribution<InferStatus<T>>>\n : Record<never, never>\n)\n\n/**\n * Infer event data types from a capability definition.\n * Returns a map of event name → data type.\n */\nexport type InferEvents<T extends CapabilityDefinition> =\n T['events'] extends Record<string, CapabilityEventSchema>\n ? { readonly [K in keyof T['events']]: T['events'][K] extends CapabilityEventSchema<infer TData> ? z.infer<TData> : never }\n : never\n\n/**\n * Infer the device-proxy facade interface for a device-scoped capability.\n *\n * Strips `deviceId` from every method's input so consumers of the client-side\n * proxy (bound to a specific device) don't have to pass it. The proxy layer\n * injects `deviceId` before forwarding to the tRPC/Moleculer action.\n *\n * Query/Mutation methods always return Promise<T>. Subscription methods keep\n * the push-based shape, without `deviceId` in the input payload.\n */\nexport type InferDeviceProxyCap<T extends CapabilityDefinition> = {\n readonly [K in keyof T['methods']]: T['methods'][K] extends CapabilityMethodSchema<infer TIn, infer TOut>\n ? T['methods'][K]['kind'] extends 'subscription'\n ? (input: Omit<z.infer<TIn>, 'deviceId'>, push: (value: z.infer<TOut>) => void) => (() => void) | void\n : (input: Omit<z.infer<TIn>, 'deviceId'>) => Promise<z.infer<TOut>>\n : never\n} & (T['status'] extends { schema: infer S }\n // Auto-injected `getStatus` mirrors the runtime emitted by the proxy\n // generator (see `scripts/generate-device-proxy.ts`). The schema is\n // tightened to the cap's status shape — `S` is the Zod schema, so\n // we resolve `z.infer<S>` here so consumers don't have to cast.\n ? { readonly getStatus: (input?: { deviceId?: number }) => Promise<S extends z.ZodType ? z.infer<S> | null : unknown> }\n : Record<never, never>)\n // When `exposesDeviceSettings: true`, mirror the three contribution\n // methods that `expandCapMethods()` injects at runtime + the cap-router\n // codegen surfaces. Without these here, the device-proxy codegen\n // (which textually parses the cap and includes those methods in its\n // `Pick<>` over `InferDeviceProxyCap`) hits a constraint mismatch.\n & (T['exposesDeviceSettings'] extends true\n ? {\n readonly getDeviceSettingsContribution: (input?: { deviceId?: number }) => Promise<unknown>\n readonly getDeviceLiveContribution: (input?: { deviceId?: number }) => Promise<unknown>\n readonly applyDeviceSettingsPatch: (input: { deviceId?: number; patch: Record<string, unknown> }) => Promise<{ readonly success: true }>\n }\n : Record<never, never>)\n\n/** Extract the capability name as a string literal type. */\nexport type InferName<T extends CapabilityDefinition> = T['name']\n\n/**\n * Infer the runtime-state slice TS shape from a cap definition.\n *\n * Lives inside the types package on purpose: `z.infer<>` is resolved\n * against THIS package's Zod version (built with Zod 4), so consumers\n * that resolve a different Zod major (e.g. core resolving Zod 3 from\n * the workspace root) still see the correct concrete shape — they\n * never need to call `z.infer` themselves.\n *\n * Falls back to `unknown` for caps without `runtimeState:` so call sites\n * can't accidentally narrow to `never` and lose property-access type\n * checking.\n */\nexport type InferRuntimeState<T extends CapabilityDefinition> =\n T extends { readonly runtimeState: infer R }\n ? R extends z.ZodType<infer Out>\n ? Out\n : R extends { readonly _output: infer Out }\n ? Out\n : unknown\n : unknown\n\n// ── Helpers ─────────────────────────────────────────────────────────\n\n/** Options for a capability method definition. */\nexport interface CapabilityMethodOptions<TKind extends CapabilityMethodKind = CapabilityMethodKind> {\n /** tRPC procedure kind. Default: 'query'. */\n readonly kind?: TKind\n /** Auth level. Default: 'protected'. */\n readonly auth?: CapabilityMethodAuth\n /** Per-method access flavour. When unset, codegen derives it from `kind` + name heuristic. */\n readonly access?: CapabilityMethodAccess\n /** Moleculer action timeout override (ms). Overrides broker global requestTimeout for this action only. */\n readonly timeoutMs?: number\n}\n\n/** Shorthand to define a method schema */\nexport function method<TIn extends z.ZodType, TOut extends z.ZodType, TKind extends CapabilityMethodKind = 'query'>(\n input: TIn,\n output: TOut,\n options?: CapabilityMethodOptions<TKind>,\n): CapabilityMethodSchema<TIn, TOut, TKind> {\n return {\n input,\n output,\n kind: (options?.kind ?? 'query') as TKind,\n auth: options?.auth ?? 'protected',\n ...(options?.access !== undefined ? { access: options.access } : {}),\n timeoutMs: options?.timeoutMs,\n }\n}\n\n/** Shorthand to define an event schema */\nexport function event<TData extends z.ZodType>(\n data: TData,\n): CapabilityEventSchema<TData> {\n return { data }\n}\n\n/** Type guard: does this cap declare the D14 device-config archetype? */\nexport function isDeviceConfigCap(\n def: CapabilityDefinition | undefined,\n): def is CapabilityDefinition & { deviceConfig: DeviceConfigSpec } {\n return def?.deviceConfig !== undefined\n}\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\n\n/**\n * Alarm-panel cap. Models HA `alarm_control_panel.*` on\n * `DeviceType.AlarmPanel`. State follows HA's canonical lifecycle\n * across disarmed / armed_(home|away|night|vacation|custom_bypass) /\n * arming / pending / triggered / disarming.\n *\n * Many panels require a PIN code on arm / disarm — the optional\n * `code` field on the methods passes it through to the upstream\n * service; it's NEVER persisted in the runtime slice or any event\n * payload. The presence of a required code is signalled by\n * `DeviceFeature.AlarmPinRequired` so the UI gates a code-entry\n * field without a slice fetch.\n *\n * `availableModes` mirrors HA's `supported_features`-derived arm\n * mode list — the UI renders only the buttons the panel accepts.\n */\n\nexport const AlarmStateSchema = z.enum([\n 'disarmed',\n 'armed_home',\n 'armed_away',\n 'armed_night',\n 'armed_vacation',\n 'armed_custom_bypass',\n 'arming',\n 'disarming',\n 'pending',\n 'triggered',\n])\nexport type AlarmState = z.infer<typeof AlarmStateSchema>\n\nexport const AlarmArmModeSchema = z.enum([\n 'home',\n 'away',\n 'night',\n 'vacation',\n 'custom_bypass',\n])\nexport type AlarmArmMode = z.infer<typeof AlarmArmModeSchema>\n\nexport const AlarmPanelStatusSchema = z.object({\n /** Current lifecycle state. */\n state: AlarmStateSchema,\n /** Subset of arm modes the panel accepts. UI renders one button per\n * mode in this list. */\n availableModes: z.array(AlarmArmModeSchema),\n /** Whether the panel requires a PIN on arm / disarm. Mirrors\n * `DeviceFeature.AlarmPinRequired` for slice consumers. */\n requiresCode: z.boolean(),\n /** Ms epoch when the slice was last updated. */\n lastChangedAt: z.number(),\n})\n\nexport type AlarmPanelStatus = z.infer<typeof AlarmPanelStatusSchema>\n\nexport const alarmPanelCapability = {\n name: 'alarm-panel',\n scope: 'device',\n deviceNative: true,\n mode: 'singleton',\n deviceTypes: [DeviceType.AlarmPanel],\n methods: {\n arm: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n mode: AlarmArmModeSchema,\n /** Optional PIN code. Required when `requiresCode === true`.\n * Passed through to the upstream service; never persisted. */\n code: z.string().min(1).optional(),\n }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n disarm: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n code: z.string().min(1).optional(),\n }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n /**\n * Force the panel into the `triggered` state — used by HA\n * automations to surface external sensor events through the panel\n * (e.g. a Reolink camera intrusion event firing the security\n * system). Provider rejects when the panel hardware doesn't\n * support a software-initiated trigger.\n */\n trigger: method(\n z.object({ deviceId: z.number().int().nonnegative() }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n },\n status: {\n schema: AlarmPanelStatusSchema,\n kind: 'push',\n },\n /**\n * Runtime-state slice — mirrored by the kernel. UI panel reads the\n * full slice; renders an arm button per `availableModes` entry and\n * a PIN field iff `requiresCode === true`.\n */\n runtimeState: AlarmPanelStatusSchema,\n} as const satisfies CapabilityDefinition\n\nexport type IAlarmPanelProvider = InferProvider<typeof alarmPanelCapability>\n","import { z } from 'zod'\nimport { type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\n\n/**\n * Ambient illuminance reading in lux. Drives Home Assistant `sensor`\n * entries with `device_class: illuminance`.\n */\nexport const AmbientLightSensorStatusSchema = z.object({\n /** Current illuminance in lux (lx). */\n lux: z.number().min(0),\n /** Ms epoch when the slice was last updated. */\n lastFetchedAt: z.number(),\n /** Live display unit from the upstream source (e.g. HA\n * `attributes.unit_of_measurement`). The UI prefers this over the\n * role's canonical unit. Absent → fall back to the canonical unit. */\n unit: z.string().optional(),\n /** Suggested decimal places for numeric display.\n * Populated live from the upstream source when provided (e.g. HA\n * `attributes.suggested_display_precision`). Falls back to\n * auto-formatting when absent. */\n precision: z.number().int().min(0).max(10).optional(),\n})\n\nexport type AmbientLightSensorStatus = z.infer<typeof AmbientLightSensorStatusSchema>\n\nexport const ambientLightSensorCapability = {\n name: 'ambient-light-sensor',\n scope: 'device',\n deviceNative: true,\n mode: 'singleton',\n deviceTypes: [DeviceType.Sensor],\n methods: {},\n status: {\n schema: AmbientLightSensorStatusSchema,\n kind: 'push',\n },\n runtimeState: AmbientLightSensorStatusSchema,\n} as const satisfies CapabilityDefinition\n\nexport type IAmbientLightSensorProvider = InferProvider<typeof ambientLightSensorCapability>\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\n\n/**\n * Per-class audio metrics aggregated over a sliding window.\n */\nconst AudioClassSummarySchema = z.object({\n className: z.string(),\n /** Number of windows (chunks) where this class was the top hit. */\n hits: z.number().int().nonnegative(),\n /** Mean score across those hits, clamped to [0,1]. */\n avgScore: z.number().min(0).max(1),\n /** Peak score in the window. */\n peakScore: z.number().min(0).max(1),\n})\n\n/**\n * Per-camera audio metrics snapshot — emitted by the analytics frame\n * handler on every `pipeline.audio-inference-result` event and\n * mirrored into the `audio-metrics` device-state slice. Symmetric\n * with `zone-analytics` snapshots for video — every consumer\n * (admin UI panel, automations, alert rules) reads via the\n * canonical `device.state.audioMetrics.value` reactive handle.\n *\n * Aggregates are computed over a rolling `windowSec` window\n * (default 60s). Past that window, classes drop out of `byClass`\n * and the level history shifts forward.\n */\nconst AudioMetricsSnapshotSchema = z.object({\n /** Wall-clock timestamp (ms) of the most recent audio window. */\n ts: z.number().int(),\n /** Sliding-window length (seconds) used for aggregation. */\n windowSec: z.number().int().positive(),\n /** Latest level reading from the most recent window. */\n level: z.object({\n rms: z.number(),\n dbfs: z.number(),\n }),\n /** Peak dBFS observed across the rolling window. */\n peakDbfs: z.number(),\n /** Mean dBFS across the rolling window. */\n avgDbfs: z.number(),\n /** Most recent above-threshold classification, or null on silence. */\n current: z.object({\n className: z.string(),\n score: z.number().min(0).max(1),\n timestamp: z.number().int(),\n }).nullable(),\n /** Per-class summary across the rolling window — keys are\n * `macroClass` strings (e.g. `dog_bark`, `speech`, `glass_break`). */\n byClass: z.array(AudioClassSummarySchema).readonly(),\n})\nexport type AudioMetricsSnapshot = z.infer<typeof AudioMetricsSnapshotSchema>\nexport type AudioClassSummary = z.infer<typeof AudioClassSummarySchema>\n\n/**\n * One sample on the audio-metrics history time-series. Captures the\n * subset of the live snapshot useful for charting: dB level, peak/avg\n * over the rolling window, and the dominant above-threshold class\n * (when any). Per-class hit breakdown lives on the snapshot but is\n * elided from the history sample to keep the buffer compact —\n * consumers needing class drill-down should pull `getCurrentSnapshot`.\n */\nconst AudioMetricsHistoryPointSchema = z.object({\n /** Wall-clock ms when this sample was recorded. */\n ts: z.number().int(),\n /** Instantaneous dBFS level at sample time. `null` for windows where\n * the source had no level reading (rare; happens at decode startup). */\n dbfs: z.number().nullable(),\n /** Rolling-window peak dBFS at sample time. Same window the live\n * snapshot reports. */\n peakDbfs: z.number(),\n /** Rolling-window mean dBFS at sample time. */\n avgDbfs: z.number(),\n /** Dominant above-threshold class at sample time, or null on silence. */\n topClass: z.string().nullable(),\n /** Score of the dominant class (`null` whenever `topClass` is null). */\n topScore: z.number().min(0).max(1).nullable(),\n})\nexport type AudioMetricsHistoryPoint = z.infer<typeof AudioMetricsHistoryPointSchema>\n\n/**\n * Audio-metrics history payload — a series of `AudioMetricsHistoryPoint`\n * samples capped at `maxPoints` (default 1024). When the requested\n * `windowSec / sampleEveryMs` would exceed the cap, the provider\n * subsamples by bucketed averaging and reports the effective sample\n * spacing on `effectiveSampleEveryMs` so the UI can label the x-axis.\n */\nconst AudioMetricsHistorySchema = z.object({\n points: z.array(AudioMetricsHistoryPointSchema).readonly(),\n /** Actual ms between adjacent samples after any subsampling. */\n effectiveSampleEveryMs: z.number().int().positive(),\n /** Wall-clock window covered by `points` (`points[N-1].ts - points[0].ts`),\n * or `0` when there's fewer than 2 samples. */\n windowMsActual: z.number().int().nonnegative(),\n})\nexport type AudioMetricsHistory = z.infer<typeof AudioMetricsHistorySchema>\n\n/**\n * Audio Metrics capability — sliding-window aggregates over the\n * pipeline audio inference results. Hosted by `addon-pipeline-analytics`\n * (same addon that owns `zone-analytics`); the runtime-state slice\n * gives operators a live read on dB level + dominant classes without\n * a custom event subscription.\n */\nexport const audioMetricsCapability = {\n name: 'audio-metrics',\n scope: 'device',\n mode: 'singleton',\n deviceTypes: [DeviceType.Camera],\n methods: {\n /** Latest snapshot for this device. Null until the analytics\n * pipeline has processed at least one audio window. */\n getCurrentSnapshot: method(\n z.object({ deviceId: z.number() }),\n AudioMetricsSnapshotSchema.nullable(),\n ),\n /**\n * Time-series view of recent audio-metrics samples. The provider\n * keeps an in-memory ring of ~1Hz samples (matching the slice-\n * write rate) capped at `MAX_HISTORY_POINTS_KEPT` (provider-side).\n * `windowSec` selects how far back to read; `sampleEveryMs`\n * downsamples by bucketed averaging when finer than the kept\n * granularity. Empty `points` array on freshly-booted providers\n * with no audio yet — same convention as `getCurrentSnapshot`.\n */\n getHistory: method(\n z.object({\n deviceId: z.number(),\n /** History window in seconds. Default 300 (5 minutes).\n * Provider clamps to its retention cap if larger. */\n windowSec: z.number().int().positive().optional(),\n /** Target sample interval in ms. Default 1000 (1 sample/second).\n * Provider clamps to natural sample rate if smaller, and\n * bucket-averages when bigger than the requested window\n * would produce more than `maxPoints` samples. */\n sampleEveryMs: z.number().int().positive().optional(),\n }),\n AudioMetricsHistorySchema,\n ),\n },\n /** Reactive runtime-state mirror — live `device.state.audioMetrics.value`. */\n runtimeState: AudioMetricsSnapshotSchema,\n} as const satisfies CapabilityDefinition\n\nexport type IAudioMetricsProvider = InferProvider<typeof audioMetricsCapability>\n\nexport {\n AudioMetricsSnapshotSchema,\n AudioClassSummarySchema,\n AudioMetricsHistoryPointSchema,\n AudioMetricsHistorySchema,\n}\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\n\n/**\n * Automation-control cap. Models HA `automation.*` entities on\n * `DeviceType.Automation`. An automation is a trigger+condition+\n * action rule that can be enabled / disabled and manually fired\n * via the `trigger` method.\n *\n * `trigger` accepts an optional `skipCondition` flag — when true,\n * the automation's action block runs WITHOUT evaluating its\n * condition block. Pair with `DeviceFeature.AutomationSkipCondition`\n * to gate the UI checkbox for the manual-trigger dialog.\n */\n\nexport const AutomationControlStatusSchema = z.object({\n /** Whether the automation is currently enabled. Disabled automations\n * ignore their trigger block — manual `trigger` still works. */\n enabled: z.boolean(),\n /** Whether the automation is currently executing its action block. */\n isRunning: z.boolean(),\n /** Ms epoch of the last successful run. 0 when never run. */\n lastTriggeredAt: z.number(),\n /** Failure description from the last completed run. Null on success\n * or when never run. */\n lastError: z.string().nullable(),\n /** Ms epoch when the slice was last updated. */\n lastChangedAt: z.number(),\n})\n\nexport type AutomationControlStatus = z.infer<typeof AutomationControlStatusSchema>\n\nexport const automationControlCapability = {\n name: 'automation-control',\n scope: 'device',\n deviceNative: true,\n mode: 'singleton',\n deviceTypes: [DeviceType.Automation],\n methods: {\n enable: method(\n z.object({ deviceId: z.number().int().nonnegative() }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n disable: method(\n z.object({ deviceId: z.number().int().nonnegative() }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n trigger: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n /** When true, fires the action block while bypassing the\n * automation's condition evaluation. Gated by\n * `DeviceFeature.AutomationSkipCondition`. */\n skipCondition: z.boolean().optional(),\n }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n },\n status: {\n schema: AutomationControlStatusSchema,\n kind: 'push',\n },\n /**\n * Runtime-state slice — mirrored by the kernel. UI automation tile\n * reads `enabled` (toggle) + `isRunning` (spinner) + `lastError`\n * (badge) directly.\n */\n runtimeState: AutomationControlStatusSchema,\n} as const satisfies CapabilityDefinition\n\nexport type IAutomationControlProvider = InferProvider<typeof automationControlCapability>\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\n\n/**\n * Battery status snapshot. Emitted by providers whose device is\n * battery-operated (cameras with `DeviceFeature.BatteryOperated`,\n * future sensor/button accessories). Consumers build their own \"low\n * battery\" alerting on top — the cap deliberately does NOT enforce a\n * threshold.\n */\nexport const BatteryStatusSchema = z.object({\n /** 0..100 inclusive. Firmware-reported. */\n percentage: z.number().min(0).max(100),\n /**\n * Charging source. `'dc'` covers wall/USB adapters; `'solar'` is\n * Reolink-specific for the Solar Panel 2 accessory (will become\n * common on other battery cams). `'none'` means running on battery\n * alone.\n */\n charging: z.enum(['dc', 'solar', 'none']),\n /**\n * True when the camera firmware has gone into low-power mode. Battery\n * providers MUST avoid polling during sleep — reading the battery\n * wakes the camera up and drains charge.\n */\n sleeping: z.boolean(),\n /** Ms epoch of the last observation. Lets consumers reason about freshness. */\n lastUpdated: z.number(),\n /**\n * True when the source is a BINARY low-battery indicator (HA\n * `binary_sensor` device_class=battery / `LOW_BAT`) that has no real\n * charge level — `percentage` is then a coarse stand-in (100 = normal,\n * sub-threshold = low). UI MUST render \"Normal\"/\"Low\" instead of a\n * misleading exact percentage. Absent/false → genuine 0–100 % reading.\n */\n binary: z.boolean().optional(),\n})\n\nexport type BatteryStatus = z.infer<typeof BatteryStatusSchema>\n\nexport const batteryCapability = {\n name: 'battery',\n scope: 'device',\n deviceNative: true,\n mode: 'singleton',\n deviceTypes: [DeviceType.Camera, DeviceType.Sensor, DeviceType.Button, DeviceType.Switch],\n methods: {\n /**\n * Explicitly wake the camera from low-power sleep ahead of a\n * streaming session start. Consumers that initiate a stream\n * against a sleeping battery cam (HomeKit Secure Video, Alexa\n * RTCSession, snapshot wrappers) call this with a short timeout\n * before establishing the media pipeline — the broker's own\n * passive wake-on-dial works but adds 5–7 seconds to first-frame,\n * during which the consumer renders a black screen. Pre-waking\n * compresses that gap.\n *\n * Returns `awoke: true` when the firmware acknowledged the wake\n * before `timeoutMs`. Returns `awoke: false` when it timed out OR\n * the cap surface is unavailable (no Baichuan / firmware\n * channel); the caller should still attempt the stream — the\n * passive broker wake remains as fallback.\n */\n wakeForStream: method(\n z.object({\n deviceId: z.number(),\n /** Bound on the wait. Sensible range 3000–10000ms. */\n timeoutMs: z.number().int().min(500).max(30_000).default(8_000),\n }),\n z.object({\n awoke: z.boolean(),\n durationMs: z.number(),\n }),\n { kind: 'mutation' },\n ),\n },\n events: {\n /**\n * Emitted whenever the cached status changes (firmware push OR\n * poll observes a delta). The DeviceEventPropagator mirrors this\n * event on the parent chain — subscribing to a camera's source\n * receives battery events from child accessories automatically.\n */\n onStatusChanged: { data: z.object({\n deviceId: z.number(),\n status: BatteryStatusSchema,\n })},\n },\n status: {\n schema: BatteryStatusSchema,\n kind: 'push',\n },\n /**\n * Runtime-state slice — every provider that registers this cap\n * stores the same shape under `device.runtimeState[battery]`.\n * Cross-provider uniformity: a Reolink Argus, a Frigate sensor\n * proxy, an ONVIF battery cam all read/write the same keys.\n * Consumers (BatteryBadge, snapshot wrapper sleep gate) read once\n * via `device.runtimeState.getCapState('battery')` regardless of\n * the underlying driver.\n */\n runtimeState: BatteryStatusSchema,\n} as const satisfies CapabilityDefinition\n\nexport type IBatteryProvider = InferProvider<typeof batteryCapability>\n","import { z } from 'zod'\nimport { type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\n\n/**\n * Generic boolean sensor — last-resort fallback when no domain-\n * specific binary cap fits (Home Assistant `binary_sensor` without a\n * known `device_class`, or a domain we haven't typed yet). Pure\n * pass-through: just the bool + timestamp. Push-driven.\n *\n * Prefer the typed alternatives (`contact`, `flood`, `smoke`,\n * `carbon-monoxide`, `gas`, `tamper`, `vibration`, `connectivity`,\n * `motion`) when the semantics match — export adapters render those\n * with the right HomeKit / Alexa display category.\n */\nexport const BinaryStatusSchema = z.object({\n on: z.boolean(),\n /** Ms epoch of the last transition. 0 if never observed. */\n lastChangedAt: z.number(),\n})\n\nexport type BinaryStatus = z.infer<typeof BinaryStatusSchema>\n\nexport const binaryCapability = {\n name: 'binary',\n scope: 'device',\n deviceNative: true,\n mode: 'singleton',\n deviceTypes: [DeviceType.Sensor],\n methods: {},\n status: {\n schema: BinaryStatusSchema,\n kind: 'push',\n },\n runtimeState: BinaryStatusSchema,\n} as const satisfies CapabilityDefinition\n\nexport type IBinaryProvider = InferProvider<typeof binaryCapability>\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\n\n/**\n * Dimmable-light brightness control. Co-exists with `switch` on the\n * same device — the switch toggles on/off, this cap sets the level\n * applied when the light is on. Drivers map their per-vendor dim\n * controls to this single-method surface.\n *\n * The cap is intentionally minimal: a single `setBrightness({deviceId,\n * percentage})` mutation plus the auto-injected `getStatus`. Drivers\n * that expose richer controls (color temperature, scenes, schedules)\n * should surface those via the device's `getSettingsUISchema()`\n * instead of bloating this cap.\n */\nexport const BrightnessStatusSchema = z.object({\n /** Current level as 0..100 inclusive. Firmware-reported. */\n percentage: z.number().min(0).max(100),\n /** Ms epoch of the last operator-driven change. Useful for UI freshness. */\n lastChangedAt: z.number(),\n})\n\nexport type BrightnessStatus = z.infer<typeof BrightnessStatusSchema>\n\nexport const brightnessCapability = {\n name: 'brightness',\n scope: 'device',\n deviceNative: true,\n mode: 'singleton',\n deviceTypes: [DeviceType.Light],\n methods: {\n setBrightness: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n percentage: z.number().min(0).max(100),\n }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n },\n events: {\n /**\n * Emitted whenever the brightness changes — operator action OR\n * firmware push. Subscribers (UI sliders, automation engines) react\n * without polling.\n */\n onBrightnessChanged: { data: z.object({\n deviceId: z.number(),\n percentage: z.number().min(0).max(100),\n lastChangedAt: z.number(),\n })},\n },\n status: {\n schema: BrightnessStatusSchema,\n kind: 'command-driven',\n },\n /**\n * Runtime-state slice — the last applied brightness level, mirrored\n * by the kernel. Read via `device.state.brightness.value` so UI\n * sliders surface the current level without polling the provider.\n */\n runtimeState: BrightnessStatusSchema,\n} as const satisfies CapabilityDefinition\n\nexport type IBrightnessProvider = InferProvider<typeof brightnessCapability>\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\n\nconst StreamFormatSchema = z.enum(['webrtc', 'hls', 'mjpeg', 'rtsp'])\n\nconst StreamInfoSchema = z.object({\n streamId: z.string(),\n format: StreamFormatSchema,\n url: z.string().nullable(),\n active: z.boolean(),\n})\n\nexport const streamingEngineCapability = {\n name: 'streaming-engine',\n scope: 'system',\n mode: 'singleton',\n internal: true,\n methods: {\n registerStream: method(\n z.object({ streamId: z.string(), sourceUrl: z.string(), codec: z.string().optional() }),\n z.void(),\n { kind: 'mutation' },\n ),\n unregisterStream: method(z.object({ streamId: z.string() }), z.void(), { kind: 'mutation' }),\n getStreamUrl: method(\n z.object({ streamId: z.string(), format: StreamFormatSchema }),\n z.string().nullable(),\n ),\n listStreams: method(z.void(), z.array(StreamInfoSchema)),\n },\n} as const satisfies CapabilityDefinition\n\nexport type IStreamingEngineProvider = InferProvider<typeof streamingEngineCapability>\n\nexport { StreamFormatSchema, StreamInfoSchema }\n","import { z } from 'zod'\nimport { method, event, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport {\n CameraStreamSchema, CamStreamKindSchema, CamStreamResolutionSchema,\n CamProfileSchema, ProfileSlotSchema, BrokerStatsSchema,\n SubscribeFramesInputSchema, SubscribeFramesResultSchema,\n FrameHandleSchema, DecodedAudioChunkSchema,\n SubscribeAudioChunksInputSchema, SubscribeAudioChunksResultSchema,\n} from './schemas/streaming-shared.js'\nimport { StreamFormatSchema } from './streaming-engine.cap.js'\nimport { EncodeProfileSchema } from '../encode-profile.js'\n\nconst RtspRestreamEntrySchema = z.object({\n brokerId: z.string(),\n url: z.string(),\n mutedUrl: z.string(),\n enabled: z.boolean(),\n /**\n * Source-stream codec / resolution for the camStream this entry serves\n * (the broker's \"high\"/\"mid\"/\"low\" profile slot for this device).\n * Used by exporter pickers (`pickPreferredRtspEntry`) to resolve\n * `streamPreference: 'auto'` to the slot whose source is closest to\n * the consumer's target — Alexa wants ~720p, HomeKit wants ~1080p,\n * and there's no point dialling the 4K slot for an Echo Show. Absent\n * when the source publisher never advertised the field; pickers fall\n * back to first-enabled in that case.\n */\n codec: z.string().optional(),\n resolution: z.object({\n width: z.number().int().positive(),\n height: z.number().int().positive(),\n }).optional(),\n})\n\nexport const BrokerRtspClientSchema = z.object({\n sessionId: z.string(),\n remoteAddr: z.string(),\n playing: z.boolean(),\n muted: z.boolean(),\n connectedAt: z.number(),\n lastRtpAt: z.number(),\n bytesSent: z.number(),\n})\n\nexport const BrokerDecodedClientSchema = z.object({\n tag: z.string(),\n subscribedAt: z.number(),\n maxFps: z.number(),\n framesDelivered: z.number(),\n framesDropped: z.number(),\n})\n\nexport const BrokerAudioClientSchema = z.object({\n tag: z.string(),\n subscribedAt: z.number(),\n chunksDelivered: z.number(),\n})\n\n/**\n * Identifies who is holding an encoded / raw-RTP subscription open on\n * the broker. Populated by the subscribing addon when it attaches —\n * defaults to `{ kind: 'unknown' }` for callers that haven't been\n * migrated. The widget surfaces every field that's set so an operator\n * can answer \"who is keeping cam X warm?\" without grepping logs.\n */\nexport const BrokerConsumerKindSchema = z.enum([\n 'alexa',\n 'homekit',\n 'webrtc-browser',\n 'webrtc-mobile',\n 'webrtc-whep',\n 'rtsp-listen',\n 'derived-broker',\n 'recording',\n 'pipeline',\n 'snapshot',\n 'warmup',\n 'unknown',\n])\nexport type BrokerConsumerKind = z.infer<typeof BrokerConsumerKindSchema>\n\nexport const BrokerConsumerAttributionSchema = z.object({\n kind: BrokerConsumerKindSchema,\n /**\n * Free-form label intended to disambiguate consumers OF THE SAME kind\n * on the same broker — e.g. user name, device alias. Should NOT repeat\n * the kind / cam / cam-stream / sessionId (those are surfaced by\n * dedicated fields). When empty the widget falls back to `${kind} ·\n * <sessionId tail>`.\n */\n label: z.string().optional(),\n /**\n * Which part of the encoded plane this subscription consumes:\n * - `'audio'` — audio packets only\n * - `'video'` — video packets only\n * - `'both'` — both video + audio (typical for AnnexB push paths\n * that don't split the source RTP)\n *\n * Missing field means \"unknown\" — older callers and the legacy\n * paths that haven't been migrated yet.\n */\n media: z.enum(['audio', 'video', 'both']).optional(),\n /**\n * Codec the consumer receives AFTER any per-session re-encoding. For\n * a WebRTC session this is the negotiated egress codec (e.g. `H264`,\n * `H265`, `Opus`, `Pcmu`); for an RTSP restreamer it mirrors the\n * source codec. Surfaced in the widget chip so operators see at a\n * glance whether a viewer is on H.264 (Echo) or H.265 (Safari).\n */\n targetCodec: z.string().optional(),\n /**\n * Whether the broker is re-encoding for this consumer:\n * - `'passthrough'` — bytes flow source→consumer without ffmpeg\n * - `'repacketize'` — RTP payload is re-packetized but NOT re-encoded\n * (preserves frames, just rebuilds headers; e.g.\n * the H.265 repacketizer path)\n * - `'transcode'` — a full encode/decode round (ffmpeg, libx264,\n * libav…); the most expensive path\n */\n transport: z.enum(['passthrough', 'repacketize', 'transcode']).optional(),\n /** Remote peer IP if the consumer terminates a network socket. */\n remoteAddr: z.string().optional(),\n /**\n * Server-read User-Agent of the originating client; enriched by the hub\n * from the tRPC request context (browser sessions).\n */\n userAgent: z.string().optional(),\n /** Authenticated user id (CamStack OAuth subject) when known. */\n userId: z.string().optional(),\n /** Higher-level session identifier (Alexa Echo sessionId, HAP session, …). */\n sessionId: z.string().optional(),\n /** Free-form key/value extras (e.g. clientHints from a WebRTC offer). */\n extra: z.record(z.string(), z.string()).optional(),\n}).readonly()\nexport type BrokerConsumerAttribution = z.infer<typeof BrokerConsumerAttributionSchema>\n\nexport const BrokerEncodedClientSchema = z.object({\n /** Stable id assigned on attach; used by `killClient`. */\n id: z.string(),\n /** Which broker fanout the subscriber rides — annexB encoded packets vs raw RTP. */\n channel: z.enum(['annexb', 'rtp']),\n attribution: BrokerConsumerAttributionSchema,\n subscribedAt: z.number(),\n /** Total packets delivered (annex-B EncodedPackets or RTP byte-buffers). */\n packetsDelivered: z.number(),\n})\nexport type BrokerEncodedClient = z.infer<typeof BrokerEncodedClientSchema>\n\nexport const BrokerClientsSchema = z.object({\n rtsp: z.array(BrokerRtspClientSchema).readonly(),\n decoded: z.array(BrokerDecodedClientSchema).readonly(),\n audio: z.array(BrokerAudioClientSchema).readonly(),\n encoded: z.array(BrokerEncodedClientSchema).readonly(),\n pipeClients: z.number(),\n /** Total encoded + raw-RTP callback subscriber count (sum of `encoded[].length`). */\n encodedSubscribers: z.number(),\n})\n\nexport type BrokerRtspClient = z.infer<typeof BrokerRtspClientSchema>\nexport type BrokerDecodedClient = z.infer<typeof BrokerDecodedClientSchema>\nexport type BrokerAudioClient = z.infer<typeof BrokerAudioClientSchema>\nexport type BrokerClients = z.infer<typeof BrokerClientsSchema>\n\nexport const PlaceholderReasonSchema = z.enum([\n 'reconnecting',\n 'sleeping',\n 'offline',\n 'disabled',\n 'waking',\n])\nexport type PlaceholderReason = z.infer<typeof PlaceholderReasonSchema>\n\n// ── getStreamWithCodec: shared codec-targeted read API ──────────────\n\nconst VideoCodecTargetSchema = z.enum(['h264', 'h265', 'copy'])\nexport type VideoCodecTarget = z.infer<typeof VideoCodecTargetSchema>\n\nconst AudioCodecTargetSchema = z.enum(['aac', 'opus', 'pcmu', 'copy', 'none'])\nexport type AudioCodecTarget = z.infer<typeof AudioCodecTargetSchema>\n\nexport const GetStreamWithCodecInputSchema = z.object({\n deviceId: z.number().int().nonnegative(),\n /** Target codec. `'copy'` = passthrough (no re-encode). */\n video: VideoCodecTargetSchema,\n /** Target audio codec. `'copy'` = passthrough. Defaults to `'aac'`. */\n audio: AudioCodecTargetSchema.optional(),\n /** Target a profile's assigned source camStream. Required to resolve a source. */\n profile: CamProfileSchema.optional(),\n /** Optional output resolution target. When set: drives the transcode\n * output scale (downscale toward WxH), and — when `profile` is absent —\n * selects the published source closest to this resolution. Ignored for\n * `video:'copy'` scaling (a copy can't be rescaled), but still used for\n * source selection. */\n targetResolution: z.object({ width: z.number().int().positive(), height: z.number().int().positive() }).optional(),\n /** Extra ffmpeg output flags appended verbatim by the consumer (in code).\n * Folded into the pipeline key so different args never share a child. */\n outputArgs: z.array(z.string()).optional(),\n /** Opt-in: carry transcoded audio over an RTP sidecar grafted into the\n * restreamer SDP (only for re-encoded audio targets — aac/opus/pcmu).\n * Default/absent = the live-verified video-only egress. */\n audioEgress: z.boolean().optional(),\n tag: z.string().optional(),\n})\nexport type GetStreamWithCodecInput = z.infer<typeof GetStreamWithCodecInputSchema>\n\nexport const RtpSourceSchema = z.object({\n url: z.string(),\n videoCodec: z.enum(['H264', 'H265']),\n audioCodec: z.string(),\n resolution: z.object({\n width: z.number().int().positive(),\n height: z.number().int().positive(),\n }),\n transcoded: z.boolean(),\n encoder: z.string(),\n pipelineKey: z.string(),\n})\nexport type RtpSource = z.infer<typeof RtpSourceSchema>\n\nexport const streamBrokerCapability = {\n name: 'stream-broker',\n scope: 'system',\n mode: 'singleton',\n exposesDeviceSettings: true,\n methods: {\n publishCameraStream: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n camStreamId: z.string().min(1),\n kind: CamStreamKindSchema,\n url: z.string().optional(),\n codec: z.string().optional(),\n resolution: CamStreamResolutionSchema.optional(),\n fps: z.number().positive().optional(),\n label: z.string().optional(),\n deviceFeatures: z.array(z.string()).optional(),\n autoEligible: z.boolean().optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n /** Required when kind === 'derived' — the source camStreamId the\n * derived broker reads its encoded plane from.\n * The runtime guard (broker manager, Task 10) enforces presence for\n * kind === 'derived'; the schema stays permissive so ts-morph emits\n * full field types instead of collapsing to ZodEffects. */\n sourceCamStreamId: z.string().min(1).optional(),\n /** Required when kind === 'derived' — the ffmpeg params for the\n * spawn. Reuses the same brokerId for identical params (single-flight).\n * Runtime guard in broker manager; schema is permissive (see above). */\n encodeProfile: EncodeProfileSchema.optional(),\n }),\n z.object({ success: z.literal(true) }),\n { kind: 'mutation', auth: 'admin' },\n ),\n retractCameraStream: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n camStreamId: z.string().min(1),\n }),\n z.object({ success: z.literal(true) }),\n { kind: 'mutation', auth: 'admin' },\n ),\n assignProfile: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n profile: CamProfileSchema,\n camStreamId: z.string().min(1),\n }),\n z.object({ success: z.literal(true) }),\n { kind: 'mutation', auth: 'admin' },\n ),\n unassignProfile: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n profile: CamProfileSchema,\n }),\n z.object({ success: z.literal(true) }),\n { kind: 'mutation', auth: 'admin' },\n ),\n listAllCameraStreams: method(\n z.void(),\n z.array(CameraStreamSchema).readonly(),\n ),\n listAllProfileSlots: method(\n z.void(),\n z.array(ProfileSlotSchema).readonly(),\n ),\n getBrokerStats: method(\n z.object({ brokerId: z.string() }),\n BrokerStatsSchema,\n ),\n listClients: method(\n z.object({ brokerId: z.string() }),\n BrokerClientsSchema,\n ),\n killClient: method(\n z.object({\n brokerId: z.string(),\n channel: z.enum(['rtsp', 'decoded', 'audio']),\n handle: z.string(),\n }),\n z.object({ killed: z.boolean() }),\n { kind: 'mutation', auth: 'admin' },\n ),\n restartProfile: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n profile: CamProfileSchema,\n }),\n z.object({ success: z.boolean() }),\n { kind: 'mutation', auth: 'admin' },\n ),\n /**\n * LEGACY / observability. Returns a raw per-broker restream URL for a\n * single stream. Prefer {@link getStreamWithCodec} for programmatic\n * CONSUMPTION — it is the single demand-counted entry that rides the\n * broker's one source dial and returns a codec-correct passthrough.\n */\n getStreamUrl: method(\n z.object({ streamId: z.string(), format: StreamFormatSchema }),\n z.object({ url: z.string() }),\n ),\n /**\n * Shared codec-targeted stream API — see Task #184. THE single public\n * stream-acquisition surface for programmatic consumers: single-dial\n * (rides the broker's one source pull) and passthrough-correct\n * (`videoCodec:'auto'` → `-c copy`, never a needless re-encode).\n * Resolution order: source-select → HW transcode → libx264/libx265.\n */\n getStreamWithCodec: method(\n GetStreamWithCodecInputSchema,\n RtpSourceSchema,\n { kind: 'mutation', auth: 'admin' },\n ),\n releaseStreamWithCodec: method(\n z.object({ pipelineKey: z.string() }),\n z.object({ released: z.boolean(), refcount: z.number().int().nonnegative() }),\n { kind: 'mutation', auth: 'admin' },\n ),\n /**\n * ── Decoded audio-chunk plane (Phase 5 / D9) ──────────────────────\n *\n * The serialisable replacement for the live-object `IStreamBroker.\n * onDecodedAudioChunk` callback path. Unlike the video frame plane,\n * audio chunks are tiny (a ~500ms PCM window is a few KB) so they ship\n * their bytes INLINE over tRPC — no shared-memory ring. A consumer:\n *\n * 1. `subscribeAudioChunks({ brokerId, tag })` — the broker registers\n * a per-subscription bounded FIFO queue and returns a\n * `subscriptionId`.\n * 2. polls `pullAudioChunks({ subscriptionId, maxCount })` — drains\n * `DecodedAudioChunk[]` in arrival order (FIFO, no latest-wins\n * drop: an audio gap is audible / breaks an analysis window). The\n * queue is generously sized; it only drops its oldest chunk if a\n * truly stalled consumer lets it overflow.\n * 3. `unsubscribeAudioChunks({ subscriptionId })` on teardown.\n */\n subscribeAudioChunks: method(\n SubscribeAudioChunksInputSchema,\n SubscribeAudioChunksResultSchema,\n { kind: 'mutation' },\n ),\n pullAudioChunks: method(\n z.object({\n subscriptionId: z.string(),\n maxCount: z.number().int().positive().default(8),\n }),\n z.array(DecodedAudioChunkSchema).readonly(),\n ),\n unsubscribeAudioChunks: method(\n z.object({ subscriptionId: z.string() }),\n z.object({ released: z.boolean() }),\n { kind: 'mutation' },\n ),\n /**\n * ── Shared-memory frame plane (Phase 5 / D9) ──────────────────────\n *\n * The handle-based replacement for the live-object `IStreamBroker.\n * onDecodedFrame` callback path. A consumer:\n *\n * 1. `subscribeFrames({ brokerId, format })` — the broker spins up\n * (or reuses) a `frameSink: 'shm'` decoder session producing that\n * `format` and returns a `subscriptionId`.\n * 2. polls `pullFrameHandles({ subscriptionId, maxCount })` — drains\n * zero-pixel `FrameHandle[]`; each handle is fed to a\n * `FrameRingReader` that opens the named shm segment and reads the\n * pixels back zero-copy.\n * 3. `unsubscribeFrames({ subscriptionId })` on teardown.\n *\n * The broker keeps one shm ring per `(brokerId, format)` actually\n * requested — no broker-side `sharp` conversion. fps throttling is\n * implicit (latest-wins ring reads drop frames for a slow consumer).\n */\n subscribeFrames: method(\n SubscribeFramesInputSchema,\n SubscribeFramesResultSchema,\n { kind: 'mutation' },\n ),\n pullFrameHandles: method(\n z.object({\n subscriptionId: z.string(),\n maxCount: z.number().int().positive().default(4),\n }),\n z.array(FrameHandleSchema).readonly(),\n ),\n unsubscribeFrames: method(\n z.object({ subscriptionId: z.string() }),\n z.object({ released: z.boolean() }),\n { kind: 'mutation' },\n ),\n setPreBufferDuration: method(\n z.object({ brokerId: z.string(), seconds: z.number().min(0).max(30) }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n getPreBufferInfo: method(\n z.object({ brokerId: z.string() }),\n z.object({ configuredSec: z.number(), bufferedMs: z.number(), packetCount: z.number() }),\n ),\n getRtspPort: method(z.void(), z.number()),\n /**\n * Enumeration surface — backs the admin RTSP-export picker and\n * `pickPreferredRtspEntry`. Lists every per-broker restream entry. NOT a\n * consumption API: programmatic readers use {@link getStreamWithCodec}.\n */\n getAllRtspEntries: method(\n z.object({ hostname: z.string().optional() }),\n z.array(RtspRestreamEntrySchema).readonly(),\n ),\n /**\n * LEGACY / observability. Resolves one broker's restream entry. Prefer\n * {@link getStreamWithCodec} for programmatic CONSUMPTION so the read is\n * demand-counted and rides the single source dial.\n */\n getRtspEntry: method(\n z.object({ brokerId: z.string(), hostname: z.string().optional() }),\n RtspRestreamEntrySchema.nullable(),\n ),\n regenerateRtspToken: method(\n z.object({ brokerId: z.string() }),\n z.string().nullable(),\n { kind: 'mutation', auth: 'admin' },\n ),\n setRtspEnabled: method(\n z.object({ brokerId: z.string(), enabled: z.boolean() }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n isRtspEnabled: method(\n z.object({ brokerId: z.string() }),\n z.boolean(),\n ),\n },\n events: {\n onCamStreamDemand: event(z.object({\n deviceId: z.number().int().nonnegative(),\n camStreamId: z.string(),\n profile: CamProfileSchema,\n })),\n onCamStreamIdle: event(z.object({\n deviceId: z.number().int().nonnegative(),\n camStreamId: z.string(),\n })),\n onRequestStreamSourceRefresh: event(z.object({\n deviceId: z.number().int().nonnegative(),\n camStreamId: z.string(),\n brokerId: z.string(),\n })),\n },\n} as const satisfies CapabilityDefinition\n\nexport type IStreamBrokerProvider = InferProvider<typeof streamBrokerCapability>\n\nexport { RtspRestreamEntrySchema }\n","import { z } from 'zod'\nimport { method, event, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\nimport {\n CameraStreamSchema,\n CamStreamResolutionSchema,\n ProfileSlotSchema,\n ProfileSlotStatusSchema,\n ProfileRtspEntrySchema,\n} from './schemas/streaming-shared.js'\nimport { RtspRestreamEntrySchema } from './stream-broker.cap.js'\n\n// ── pickStream request / response ─────────────────────────────────────\n//\n// `pickStream` is the consumer-facing \"given my decode constraints,\n// what's the best published stream I can dial?\" facade. It generalises\n// the H.264-bypass logic originally inlined in `addon-export-alexa`'s\n// `rtc-session.ts`: Echo only decodes H.264, so when a battery cam\n// publishes both `native:main` HEVC + `native:sub` H.264, the picker\n// returns the sub-stream and Alexa avoids a 3-6s `ffmpeg -c:v hevc →\n// libx264` transcode. Every other broker consumer hits the same problem\n// (HomeKit, browser fallbacks, WHEP), so this lives on the cap.\n\n/** Codec aliases the matcher treats as equivalent (canonical lowercase). */\nconst STREAM_CODEC_VALUES = ['h264', 'h265', 'hevc', 'av1', 'mjpeg', 'vp8', 'vp9'] as const\nexport const StreamCodecSchema = z.enum(STREAM_CODEC_VALUES)\nexport type StreamCodec = z.infer<typeof StreamCodecSchema>\n\nexport const PickStreamRequirementsSchema = z.object({\n /**\n * Codecs the consumer can decode without an intermediate transcode.\n * Match is case-insensitive against the camera stream's `codec`.\n * Default (omitted / empty array): no codec filter — useful when the\n * consumer just wants \"the highest-quality stream of any codec\".\n */\n acceptCodecs: z.array(StreamCodecSchema).readonly().optional(),\n /** Minimum vertical resolution. Streams shorter than this are dropped. */\n minHeight: z.number().int().positive().optional(),\n /** Minimum horizontal resolution. */\n minWidth: z.number().int().positive().optional(),\n /**\n * When true (default), `derived:*` streams (transcoded broker pipes)\n * are excluded — the caller wants a SOURCE stream the broker can\n * forward without a re-encode. Set false to allow derived in the\n * picker (useful for a \"best playable\" fallback).\n */\n excludeDerived: z.boolean().optional(),\n /**\n * Bypass gate. When set, the picker returns a hit ONLY IF the device\n * also exposes a non-derived stream in one of these (rejected) codecs.\n * Mirrors the Alexa \"bypass only when the natural path WOULD have\n * transcoded\" guard: if the device is already serving the consumer's\n * codec end-to-end, there's nothing to optimise.\n */\n requireSiblingCodec: z.array(StreamCodecSchema).readonly().optional(),\n}).readonly()\n\nexport const PickStreamPreferencesSchema = z.object({\n /**\n * Ordered list of provider prefixes (e.g. `['native:', 'rtsp:']`) the\n * picker prefers — earlier entries win ties. Defaults to\n * `['native:']`, mirroring Alexa's \"prefer the native dial path\".\n */\n preferredProviders: z.array(z.string()).readonly().optional(),\n /**\n * Resolution preference within the surviving candidates. `'highest'`\n * picks the tallest stream; `'lowest'` picks the shortest (used by\n * memory-constrained consumers / Apple Home guest sessions).\n */\n resolutionPreference: z.enum(['highest', 'lowest']).optional(),\n}).readonly()\n\nexport const PickedCamStreamSchema = z.object({\n camStreamId: z.string(),\n codec: z.string().optional(),\n resolution: CamStreamResolutionSchema.optional(),\n /** One-line explanation of why this stream won — for logs / debug UI. */\n reason: z.string(),\n})\nexport type PickedCamStream = z.infer<typeof PickedCamStreamSchema>\n\n\n/**\n * Camera streams — device-scoped facade over the system `stream-broker`.\n *\n * Mirrors the slice of broker state relevant to a single device:\n * - `getCameraStreams()`: the pool of physical streams published for\n * this device. UI uses it to populate the \"Camera Stream\" dropdown\n * under each quality section.\n * - `getBrokerStreams()`: the (up to 3) profile slots `high/mid/low`\n * with their current assignment + runtime status. UI uses it for\n * the WebRTC quality picker, recording target selection, etc.\n *\n * Registered for every camera device that has at least one published\n * cam stream. The provider is owned by the stream-broker addon; reads\n * go against the broker's in-memory registries. Mutations (assign /\n * unassign / publish / retract) do NOT live here — they stay on the\n * system `stream-broker` cap so cross-device / addon-driven flows keep\n * a single namespace.\n */\nexport const cameraStreamsCapability = {\n name: 'camera-streams',\n scope: 'device',\n mode: 'singleton',\n kind: 'wrapper',\n defaultActive: true,\n deviceTypes: [DeviceType.Camera],\n methods: {\n getCameraStreams: method(\n z.object({ deviceId: z.number().int().nonnegative() }),\n z.array(CameraStreamSchema).readonly(),\n ),\n getBrokerStreams: method(\n z.object({ deviceId: z.number().int().nonnegative() }),\n z.array(ProfileSlotSchema).readonly(),\n ),\n /**\n * Per-device RAW RTSP restream entries — one per published camStream\n * that has RTSP restream enabled (`native:main`, `rtsp:sub`, …).\n *\n * LIVE-VIEW ONLY. This is the surface the device-details stream\n * picker uses so an operator can hit each physical stream directly.\n * Programmatic / external consumers (HAP, Alexa, ha-mqtt, recording)\n * MUST use `getProfileRtspEntries` instead — picking from raw\n * variants makes two consumers of the same camera land on two\n * different physical pulls (e.g. Reolink `native:main` vs\n * `rtsp:main`) and trips the camera's concurrent-session limit.\n */\n getRtspEntries: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n /** Override hostname embedded in returned URLs. Defaults to the broker's bound address. */\n hostname: z.string().optional(),\n }),\n z.array(RtspRestreamEntrySchema).readonly(),\n ),\n /**\n * Per-device PROFILE RTSP restream entries — one per ASSIGNED\n * profile slot (high/mid/low). Each entry's `url` is a profile-keyed\n * broker restream that aliases the profile's assigned source broker,\n * so HAP / Alexa / recording / WebRTC all converge on the broker's\n * single on-demand pull for that profile. This is the supported\n * exporter-facing surface; the raw `getRtspEntries` is live-view\n * only. Returns `[]` for a device with no assigned profiles\n * (cold-start before first publish).\n */\n getProfileRtspEntries: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n /** Override hostname embedded in returned URLs. Defaults to the broker's bound address. */\n hostname: z.string().optional(),\n }),\n z.array(ProfileRtspEntrySchema).readonly(),\n ),\n /**\n * \"Best source stream for these decode constraints\". Returns the\n * camStreamId the caller should dial (or null when no stream\n * matches). See `PickStreamRequirementsSchema` for the filter shape\n * and `PickStreamPreferencesSchema` for the ranking inputs.\n *\n * Returning null instructs the caller to fall back to its existing\n * path (derived-broker transcode, profile-slot pick, etc.) — the\n * picker NEVER ranks `derived:*` candidates as a \"match\" because\n * its whole job is to avoid the transcode.\n */\n pickStream: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n requirements: PickStreamRequirementsSchema,\n preferences: PickStreamPreferencesSchema.optional(),\n }),\n PickedCamStreamSchema.nullable(),\n ),\n },\n events: {\n /** Fires on publishCameraStream / retractCameraStream. */\n onCamStreamsChanged: event(z.object({\n deviceId: z.number().int().nonnegative(),\n camStreams: z.array(CameraStreamSchema).readonly(),\n })),\n /** Fires on assignProfile / unassignProfile / runtime status change. */\n onProfileSlotsChanged: event(z.object({\n deviceId: z.number().int().nonnegative(),\n profileSlots: z.array(ProfileSlotSchema).readonly(),\n })),\n },\n /**\n * Per-device live stream-broker state. Persistent settings (RTSP\n * tokens, profile assignments, pre-buffer config, RTSP-enabled toggles,\n * streamingDebug) stay in the broker's addon store — they survive\n * restarts. The slice below carries ONLY what's truly runtime:\n *\n * - `online` — at least one profile slot is currently `'streaming'`.\n * Drivers without a firmware liveness signal (RTSP, ONVIF…) can\n * subscribe and mirror this into `state.deviceStatus.online`.\n * - `slotStatuses` — current `ProfileSlotStatus` per profile,\n * mirroring the runtime-mutable subset of `ProfileSlot`.\n * - `slotErrors` — last error message per profile (only set when the\n * corresponding slot is in `'error'`).\n * - `lastChangedAt` — freshness signal for consumers that want to\n * reason about how stale the slice is.\n *\n * Written by the stream-broker manager on every transition that\n * affects these aggregates. Read via `device.state.cameraStreams.<field>`\n * (BaseDevice proxy) or, cross-process, via\n * `device-state.getCapSlice({deviceId, capName: 'camera-streams'})`.\n * The cap's `onChanged` event fires automatically on each write so\n * subscribers get push semantics for free.\n */\n runtimeState: z.object({\n online: z.boolean(),\n slotStatuses: z.object({\n high: ProfileSlotStatusSchema.optional(),\n mid: ProfileSlotStatusSchema.optional(),\n low: ProfileSlotStatusSchema.optional(),\n }),\n slotErrors: z.object({\n high: z.string().optional(),\n mid: z.string().optional(),\n low: z.string().optional(),\n }),\n lastChangedAt: z.number(),\n }),\n} as const satisfies CapabilityDefinition\n\nexport type ICameraStreamsProvider = InferProvider<typeof cameraStreamsCapability>\n","import { z } from 'zod'\nimport { type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\n\n/**\n * Carbon-monoxide alarm sensor. Drives Home Assistant `binary_sensor`\n * entries with `device_class: carbon_monoxide`. Push-driven.\n */\nexport const CarbonMonoxideStatusSchema = z.object({\n detected: z.boolean(),\n /** Ms epoch of the last transition. 0 if never observed. */\n lastChangedAt: z.number(),\n})\n\nexport type CarbonMonoxideStatus = z.infer<typeof CarbonMonoxideStatusSchema>\n\nexport const carbonMonoxideCapability = {\n name: 'carbon-monoxide',\n scope: 'device',\n deviceNative: true,\n mode: 'singleton',\n deviceTypes: [DeviceType.Sensor],\n methods: {},\n status: {\n schema: CarbonMonoxideStatusSchema,\n kind: 'push',\n },\n runtimeState: CarbonMonoxideStatusSchema,\n} as const satisfies CapabilityDefinition\n\nexport type ICarbonMonoxideProvider = InferProvider<typeof carbonMonoxideCapability>\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\n\n/**\n * HVAC / climate control cap. Models the full surface of a HA\n * `climate.*` entity (thermostat, A/C, heat pump, dehumidifier)\n * with a single coherent slice — mode + fan + preset + target +\n * dual-setpoint range + humidity + read-only current readings.\n *\n * Operation modes (`HvacMode`) follow HA's canonical set; not every\n * device supports every mode — the provider rejects unsupported\n * values at runtime. Min/max/step bounds for the setpoint are surfaced\n * via `getOptions` on the provider — they are static per-device hardware\n * properties persisted in the device config blob.\n *\n * `fanMode` / `preset` are free-form strings because device vendors\n * use vastly different vocabularies (`auto`/`low`/`high` vs\n * `quiet`/`normal`/`turbo`; `eco`/`away`/`sleep` vs `home`/`night`).\n * The provider populates `availableFanModes` / `availablePresets`\n * on the slice so the UI renders a closed-list picker.\n *\n * Sub-surface gating paired with `DeviceFeature` flags:\n * - `ClimateDualSetpoint` — heat_cool dual-target range support\n * - `ClimateHumidity` — currentHumidity / targetHumidity surfaces\n * - `ClimateFanMode` — fan-mode selector\n * - `ClimatePreset` — preset selector\n */\n\nexport const HvacModeSchema = z.enum([\n 'off',\n 'heat',\n 'cool',\n 'auto',\n 'heat_cool',\n 'fan_only',\n 'dry',\n])\nexport type HvacMode = z.infer<typeof HvacModeSchema>\n\nexport const ClimateControlStatusSchema = z.object({\n /** Active HVAC mode. */\n mode: HvacModeSchema,\n /** Available HVAC modes the device accepts. Subset of HvacMode. */\n availableModes: z.array(HvacModeSchema),\n /** Active fan mode (`auto` / `low` / `medium` / `high` / `on` / `off`\n * / vendor-specific) — empty string when the device has no fan\n * surface. */\n fanMode: z.string(),\n /** Available fan modes the device accepts. */\n availableFanModes: z.array(z.string()),\n /** Active preset (`eco` / `away` / `sleep` / vendor-specific) —\n * empty string when no preset is active or the device has no\n * preset surface. */\n preset: z.string(),\n /** Available presets the device accepts. */\n availablePresets: z.array(z.string()),\n /** Single setpoint in Celsius. Used by single-target modes\n * (heat / cool / dry). Null when the device is in a range mode\n * (`heat_cool`) or has no setpoint at all (`fan_only`/`off`). */\n target: z.number().nullable(),\n /** Upper bound of the dual setpoint in Celsius. Populated only\n * in `heat_cool` mode. */\n targetHigh: z.number().nullable(),\n /** Lower bound of the dual setpoint in Celsius. Populated only\n * in `heat_cool` mode. */\n targetLow: z.number().nullable(),\n /** Target relative humidity (0..100). Null when the device has no\n * humidity control. */\n targetHumidity: z.number().min(0).max(100).nullable(),\n /** Current measured temperature in Celsius. Read-only — pushed by\n * the device's internal sensor. */\n currentTemp: z.number().nullable(),\n /** Current measured relative humidity (0..100). Read-only. */\n currentHumidity: z.number().min(0).max(100).nullable(),\n /** Ms epoch when the slice was last updated (push or command). */\n lastFetchedAt: z.number(),\n})\n\nexport type ClimateControlStatus = z.infer<typeof ClimateControlStatusSchema>\n\nexport const climateControlCapability = {\n name: 'climate-control',\n scope: 'device',\n deviceNative: true,\n mode: 'singleton',\n deviceTypes: [DeviceType.Thermostat],\n methods: {\n setMode: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n mode: HvacModeSchema,\n }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n setFanMode: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n fanMode: z.string().min(1),\n }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n setPreset: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n preset: z.string().min(1),\n }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n setTarget: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n target: z.number(),\n }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n setTargetRange: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n targetLow: z.number(),\n targetHigh: z.number(),\n }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n setTargetHumidity: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n targetHumidity: z.number().min(0).max(100),\n }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n },\n status: {\n schema: ClimateControlStatusSchema,\n kind: 'push',\n },\n /**\n * Runtime-state slice — mirrored by the kernel. UI thermostats read\n * the full slice via `device.state.climate-control.value` and refresh\n * on every push without re-querying the provider.\n */\n runtimeState: ClimateControlStatusSchema,\n} as const satisfies CapabilityDefinition\n\nexport type IClimateControlProvider = InferProvider<typeof climateControlCapability>\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\n\n/**\n * Color-light cap. Coexists with `switch` (on/off) and `brightness`\n * (level) on the same device — `switch` toggles the bulb, `brightness`\n * sets the dim level, this cap sets the chromaticity.\n *\n * Three mutually-exclusive color modes are modelled — a single\n * `setColor` mutation accepts whichever mode the caller wants and\n * the provider rejects modes the bulb doesn't support:\n * - `rgb` — direct red/green/blue triplet (0..255 each).\n * - `hsv` — hue/saturation/value (0..360 / 0..100 / 0..100).\n * - `mired` — color-temperature reciprocal in mireds (warm ≈ 500,\n * cool ≈ 150). Used by tunable-white bulbs.\n *\n * The slice carries the LAST-applied mode + its associated value;\n * the provider does NOT auto-convert between modes (e.g. setting\n * mireds zeroes out the rgb/hsv fields). UI surfaces a single\n * color picker that picks one mode per interaction.\n *\n * Sub-feature gating uses the granular `DeviceFeature.LightColorRgb`\n * / `LightColorHsv` / `LightColorMired` flags — a Hue full-color\n * bulb sets all three; a CCT-only tunable-white bulb sets only\n * `LightColorMired`. The UI uses these flags to decide which color\n * modes to expose in the picker without a slice fetch.\n */\n\nconst RgbTripletSchema = z.object({\n r: z.number().int().min(0).max(255),\n g: z.number().int().min(0).max(255),\n b: z.number().int().min(0).max(255),\n})\n\nconst HsvTripletSchema = z.object({\n /** Hue in degrees, 0..360. */\n h: z.number().min(0).max(360),\n /** Saturation as 0..100 inclusive. */\n s: z.number().min(0).max(100),\n /** Value/brightness as 0..100 inclusive. */\n v: z.number().min(0).max(100),\n})\n\nconst ColorInputSchema = z.discriminatedUnion('mode', [\n z.object({ mode: z.literal('rgb'), rgb: RgbTripletSchema }),\n z.object({ mode: z.literal('hsv'), hsv: HsvTripletSchema }),\n z.object({ mode: z.literal('mired'), mireds: z.number().int().min(50).max(1000) }),\n])\n\nexport const ColorStatusSchema = z.object({\n /** Active color mode — which of `rgb` / `hsv` / `mireds` reflects\n * the bulb's current state. */\n mode: z.enum(['rgb', 'hsv', 'mired']),\n /** Populated when `mode === 'rgb'`. */\n rgb: RgbTripletSchema.optional(),\n /** Populated when `mode === 'hsv'`. */\n hsv: HsvTripletSchema.optional(),\n /** Populated when `mode === 'mired'`. */\n mireds: z.number().int().optional(),\n /** Ms epoch of the last operator-driven change. */\n lastChangedAt: z.number(),\n})\n\nexport type ColorStatus = z.infer<typeof ColorStatusSchema>\nexport type ColorRgbTriplet = z.infer<typeof RgbTripletSchema>\nexport type ColorHsvTriplet = z.infer<typeof HsvTripletSchema>\nexport type ColorInput = z.infer<typeof ColorInputSchema>\n\nexport const colorCapability = {\n name: 'color',\n scope: 'device',\n deviceNative: true,\n mode: 'singleton',\n deviceTypes: [DeviceType.Light],\n methods: {\n setColor: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n color: ColorInputSchema,\n }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n },\n events: {\n /**\n * Emitted whenever the color changes — operator action OR firmware\n * push. Subscribers (UI color pickers, automation engines) react\n * without polling.\n */\n onColorChanged: { data: z.object({\n deviceId: z.number(),\n mode: z.enum(['rgb', 'hsv', 'mired']),\n rgb: RgbTripletSchema.optional(),\n hsv: HsvTripletSchema.optional(),\n mireds: z.number().int().optional(),\n lastChangedAt: z.number(),\n })},\n },\n status: {\n schema: ColorStatusSchema,\n kind: 'command-driven',\n },\n /**\n * Runtime-state slice — the last applied color, mirrored by the\n * kernel. Read via `device.state.color.value` so UI pickers surface\n * the current chromaticity without polling the provider.\n */\n runtimeState: ColorStatusSchema,\n} as const satisfies CapabilityDefinition\n\nexport type IColorProvider = InferProvider<typeof colorCapability>\n","import { z } from 'zod'\nimport { type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\n\n/**\n * Upstream-system connectivity sensor — distinct from `device-status`,\n * which is the kernel-managed online/offline flag for the device's\n * own transport. This cap surfaces an external entity's view of\n * whether the device is reachable (typical use: HA's\n * `binary_sensor` with `device_class: connectivity` for a remote\n * gateway or bridge). Push-driven.\n */\nexport const ConnectivityStatusSchema = z.object({\n /** True when the upstream system considers the entity connected. */\n connected: z.boolean(),\n /** Ms epoch of the last transition. 0 if never observed. */\n lastChangedAt: z.number(),\n})\n\nexport type ConnectivityStatus = z.infer<typeof ConnectivityStatusSchema>\n\nexport const connectivityCapability = {\n name: 'connectivity',\n scope: 'device',\n deviceNative: true,\n mode: 'singleton',\n deviceTypes: [DeviceType.Sensor],\n methods: {},\n status: {\n schema: ConnectivityStatusSchema,\n kind: 'push',\n },\n runtimeState: ConnectivityStatusSchema,\n} as const satisfies CapabilityDefinition\n\nexport type IConnectivityProvider = InferProvider<typeof connectivityCapability>\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\n\n/**\n * Generic device-consumables capability — surfaces a device's\n * maintenance items (vacuum filters/brushes, replaceable cartridges,\n * descaling cycles, …) with their remaining life and an optional\n * \"Replaced\" reset action. Device-agnostic: any provider that knows its\n * device tracks consumables can register it; the cap declares no\n * vocabulary of its own — the provider names each item verbatim.\n *\n * Like `childLayout`, the cap is INERT until a provider sets items: no\n * provider populates it by guessing (no HA inference). The UI renders a\n * \"No consumables reported\" placeholder when `items` is empty.\n */\n\n/** A single consumable item. Either a continuous `level` (remaining\n * life %) or a discrete `status` may be known — both may be null when a\n * provider only knows the item exists. `level` and `status` are not\n * mutually exclusive; a provider may report both. */\nexport const ConsumableItemSchema = z.object({\n /** Stable id, e.g. 'main-brush'. */\n key: z.string().min(1),\n /** Display name. */\n label: z.string().min(1),\n /** Remaining life % when known (0..100). */\n level: z.number().min(0).max(100).nullable(),\n /** Discrete state when known (binary mode). */\n status: z.enum(['ok', 'replace']).nullable(),\n /** Ms epoch of the last replace, when known. */\n lastResetAt: z.number().nullable(),\n /** Whether `reset()` is meaningful for this item. */\n resettable: z.boolean(),\n})\n\nexport const ConsumablesStatusSchema = z.object({\n items: z.array(ConsumableItemSchema),\n lastChangedAt: z.number(),\n})\n\nexport type ConsumableItem = z.infer<typeof ConsumableItemSchema>\nexport type ConsumablesStatus = z.infer<typeof ConsumablesStatusSchema>\n\nexport const consumablesCapability = {\n name: 'consumables',\n scope: 'device',\n deviceNative: true,\n mode: 'singleton',\n // Device-agnostic — any device may expose consumables, so the cap\n // binds on EVERY DeviceType. The list enumerates every enum member\n // (kept in sync with `device-type.ts`) rather than a subset, so a\n // provider on any device type — vacuums/mowers included — can register\n // it and no future device type silently fails to bind.\n deviceTypes: [\n DeviceType.Camera,\n DeviceType.Hub,\n DeviceType.Light,\n DeviceType.Siren,\n DeviceType.Switch,\n DeviceType.Sensor,\n DeviceType.Thermostat,\n DeviceType.Button,\n DeviceType.EventEmitter,\n DeviceType.Update,\n DeviceType.Generic,\n DeviceType.Notifier,\n DeviceType.Script,\n DeviceType.Automation,\n DeviceType.Lock,\n DeviceType.Cover,\n DeviceType.Valve,\n DeviceType.Humidifier,\n DeviceType.WaterHeater,\n DeviceType.Fan,\n DeviceType.MediaPlayer,\n DeviceType.AlarmPanel,\n DeviceType.Control,\n DeviceType.Presence,\n DeviceType.Weather,\n DeviceType.Vacuum,\n DeviceType.LawnMower,\n DeviceType.Container,\n DeviceType.Image,\n ],\n deviceConfig: {\n ui: { kind: 'widget', widgetId: 'host/consumables-panel', tab: 'consumables', topTab: true, label: 'Consumables', order: 5 },\n },\n methods: {\n /** Mark a consumable as replaced — resets its remaining life. Only\n * meaningful when the item's `resettable` is true. */\n reset: method(\n z.object({ deviceId: z.number().int().nonnegative(), key: z.string().min(1) }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n },\n status: {\n schema: ConsumablesStatusSchema,\n kind: 'push',\n },\n // Per the cap checklist, runtimeState carries the bridge helper's\n // freshness field. The status surface stays the plain schema; only the\n // persistent slice gains `lastFetchedAt` so future poll-backed\n // providers can use the runtime-state bridge unchanged.\n runtimeState: ConsumablesStatusSchema.extend({ lastFetchedAt: z.number() }),\n} as const satisfies CapabilityDefinition\n\nexport type IConsumablesProvider = InferProvider<typeof consumablesCapability>\n","import { z } from 'zod'\nimport { type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\n\n/**\n * Door / window / opening / garage / valve contact sensor. Boolean\n * \"is the entry currently open\" with the timestamp of the last\n * transition. Drives Home Assistant `binary_sensor` entries whose\n * `device_class` is `door`, `window`, `opening`, `garage`, or\n * `garage_door` — and any future native integration that needs\n * the same semantics.\n *\n * Push-driven: providers update the slice on transition events from\n * the upstream source (HA WebSocket `state_changed`, ZWave\n * `notification` …). Consumers read the slice; no polling.\n */\nexport const ContactStatusSchema = z.object({\n /** True when the entry is open; false when closed. */\n entryOpen: z.boolean(),\n /** Ms epoch of the last open↔closed transition. 0 if never observed. */\n lastChangedAt: z.number(),\n})\n\nexport type ContactStatus = z.infer<typeof ContactStatusSchema>\n\nexport const contactCapability = {\n name: 'contact',\n scope: 'device',\n deviceNative: true,\n mode: 'singleton',\n deviceTypes: [DeviceType.Sensor],\n methods: {},\n status: {\n schema: ContactStatusSchema,\n kind: 'push',\n },\n runtimeState: ContactStatusSchema,\n} as const satisfies CapabilityDefinition\n\nexport type IContactProvider = InferProvider<typeof contactCapability>\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\n\n/**\n * Unified user-settable input cap. Models HA's `number` /\n * `input_number` / `select` / `input_select` / `text` / `input_text`\n * / `input_datetime` domains as a single device-scoped cap on\n * `DeviceType.Control`.\n *\n * The slice is a discriminated union over four `kind` values that\n * mirror the corresponding `DeviceRole` sub-roles\n * (NumericControl / SelectControl / TextControl / DateTimeControl)\n * — the device's `role` and the slice's `kind` are populated in\n * lockstep at materialisation time. The UI reads `device.role`\n * (or equivalently the slice's `kind`) to render the correct input\n * widget (slider / dropdown / text field / date picker).\n *\n * The `select` branch carries its `options` list IN THE SLICE\n * (not in `sourceInfo`) because HA `select.*` entities can update\n * their options dynamically at runtime — the slice is the live\n * source of truth. Numeric `unit`/`min`/`max`/`step` also live IN\n * THE SLICE — populated live from the upstream source on each state\n * push (HA `attributes.unit_of_measurement` / `min` / `max` /\n * `step`). The slice is the single source of truth; there is no\n * separate `sourceInfo` or device-config blob for these values.\n */\n\nexport const ControlKindSchema = z.enum(['numeric', 'select', 'text', 'datetime'])\nexport type ControlKind = z.infer<typeof ControlKindSchema>\n\n/**\n * Status slice — flat object (the framework's `runtimeState` contract\n * requires a `ZodObject`, not a discriminated union). The `kind`\n * field discriminates the value type at the type level via the\n * `ControlNumericValue` / `ControlStringValue` aliases; consumers\n * narrow with a kind check.\n *\n * The `value` field is typed as `number | string`:\n * - `kind === 'numeric'` → `value` is `number`\n * - `kind === 'select' | 'text' | 'datetime'` → `value` is `string`\n *\n * The `options` array is populated only when `kind === 'select'`\n * (empty array for the other kinds). It lives in the slice because\n * HA `select.*` entities may update their options at runtime.\n *\n * The `unit`/`min`/`max`/`step` fields are meaningful for\n * `kind === 'numeric'` and are absent (undefined) for all other\n * kinds. They are populated live from HA attributes on each state\n * push — consistent with `options` and the sensor-unit approach.\n */\nexport const ControlStatusSchema = z.object({\n kind: ControlKindSchema,\n /** Current value. Numeric kind → number; select/text/datetime → string.\n * Datetime values are ISO 8601 strings (full timestamp, date-only,\n * or time-only — HA accepts all three forms). */\n value: z.union([z.number(), z.string()]),\n /** Acceptable values when `kind === 'select'`. Empty for other kinds. */\n options: z.array(z.string()),\n /** Ms epoch when the slice was last updated. */\n lastChangedAt: z.number(),\n /** Display unit-of-measurement (e.g. '°C', '%', 'lx').\n * Populated live from HA `attributes.unit_of_measurement` on each push.\n * Meaningful for `kind === 'numeric'`; absent for other kinds. */\n unit: z.string().optional(),\n /** Minimum allowed value. Populated live from HA `attributes.min`.\n * Meaningful for `kind === 'numeric'`; absent for other kinds. */\n min: z.number().optional(),\n /** Maximum allowed value. Populated live from HA `attributes.max`.\n * Meaningful for `kind === 'numeric'`; absent for other kinds. */\n max: z.number().optional(),\n /** Step increment. Populated live from HA `attributes.step`.\n * Meaningful for `kind === 'numeric'`; absent for other kinds. */\n step: z.number().optional(),\n /** Suggested decimal places for numeric display. Populated live from HA\n * `attributes.suggested_display_precision`, or derived from `step` when the\n * HA attribute is absent. Meaningful for `kind === 'numeric'`; absent for\n * other kinds. Falls back to auto-formatting when absent. */\n precision: z.number().int().min(0).max(10).optional(),\n /** Date-picker granularity for `kind === 'datetime'`. 'date' → date-only,\n * 'time' → time-only, 'datetime' → full timestamp. Absent for other kinds\n * (UI defaults to 'datetime'). Derived live from the device's HA domain\n * (date.* / time.* / datetime.*) or, for input_datetime, from the entity's\n * `has_date`/`has_time` attributes on each push. */\n format: z.enum(['date', 'time', 'datetime']).optional(),\n})\n\nexport type ControlStatus = z.infer<typeof ControlStatusSchema>\n\nconst ControlSetValueInputSchema = z.discriminatedUnion('kind', [\n z.object({ kind: z.literal('numeric'), value: z.number() }),\n z.object({ kind: z.literal('select'), value: z.string().min(1) }),\n z.object({ kind: z.literal('text'), value: z.string() }),\n z.object({ kind: z.literal('datetime'), value: z.string().min(1) }),\n])\n\nexport type ControlSetValueInput = z.infer<typeof ControlSetValueInputSchema>\n\nexport const controlCapability = {\n name: 'control',\n scope: 'device',\n deviceNative: true,\n mode: 'singleton',\n deviceTypes: [DeviceType.Control],\n methods: {\n setValue: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n control: ControlSetValueInputSchema,\n }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n },\n status: {\n schema: ControlStatusSchema,\n kind: 'push',\n },\n /**\n * Runtime-state slice — mirrored by the kernel. UI widgets (slider /\n * dropdown / text field / date picker) read the slice's discriminant\n * and value directly without polling the provider.\n */\n runtimeState: ControlStatusSchema,\n} as const satisfies CapabilityDefinition\n\nexport type IControlProvider = InferProvider<typeof controlCapability>\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\n\n/**\n * Window covering / blinds / garage door / valve cap. Models HA\n * `cover.*` entities — anything that moves between an open and a\n * closed state with optional intermediate positioning and tilt.\n *\n * State follows HA's canonical lifecycle: `open` / `opening` /\n * `closing` / `closed` / `stopped`. `position` (0 closed, 100 open)\n * and `tiltPosition` are nullable — some shutters only support\n * full open/close, some Venetian blinds add tilt but no slat\n * positioning, garage doors are usually positionless. Providers\n * populate only what the hardware reports.\n *\n * The cap intentionally does NOT split tilt into a sibling cap:\n * physical hardware that has tilt always has the main position\n * surface too, so the coupling stays inside one slice + one method\n * group rather than spreading across two registrations.\n *\n * Sub-surface gating paired with `DeviceFeature` flags:\n * - `CoverPositionable` — intermediate `position` slider\n * - `CoverTilt` — slat-tilt slider\n */\n\nexport const CoverStateSchema = z.enum([\n 'open',\n 'opening',\n 'closing',\n 'closed',\n 'stopped',\n])\nexport type CoverState = z.infer<typeof CoverStateSchema>\n\nexport const CoverStatusSchema = z.object({\n /** Lifecycle state of the cover. */\n state: CoverStateSchema,\n /** 0 = fully closed, 100 = fully open. Null when the device has\n * no intermediate position surface. */\n position: z.number().min(0).max(100).nullable(),\n /** 0 = closed slats, 100 = open slats. Null when no tilt support. */\n tiltPosition: z.number().min(0).max(100).nullable(),\n /** Ms epoch when the slice was last updated. */\n lastChangedAt: z.number(),\n})\n\nexport type CoverStatus = z.infer<typeof CoverStatusSchema>\n\nexport const coverCapability = {\n name: 'cover',\n scope: 'device',\n deviceNative: true,\n mode: 'singleton',\n deviceTypes: [DeviceType.Cover],\n methods: {\n open: method(\n z.object({ deviceId: z.number().int().nonnegative() }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n close: method(\n z.object({ deviceId: z.number().int().nonnegative() }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n stop: method(\n z.object({ deviceId: z.number().int().nonnegative() }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n setPosition: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n position: z.number().min(0).max(100),\n }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n setTiltPosition: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n tiltPosition: z.number().min(0).max(100),\n }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n },\n status: {\n schema: CoverStatusSchema,\n kind: 'push',\n },\n /**\n * Runtime-state slice — mirrored by the kernel. UI controls watch\n * the slice for live position changes during a move.\n */\n runtimeState: CoverStatusSchema,\n} as const satisfies CapabilityDefinition\n\nexport type ICoverProvider = InferProvider<typeof coverCapability>\n","import { z } from 'zod'\n\n/**\n * Identity envelope for a device's upstream-system metadata.\n *\n * Two jobs:\n *\n * 1. **Dispatch key.** `id` is the natural identifier the SOURCE system\n * uses to address this device (HA `entity_id`, Reolink MAC, ONVIF\n * WS-Discovery endpoint UUID, …). Provider code keeps a\n * `Map<sourceInfo.id, IDevice>` to route inbound push events in O(1)\n * without round-tripping through `stableId` / `id` mappings.\n *\n * 2. **Stability bridge.** `uniqueId` is the *immutable* upstream id when\n * one exists (HA `entity.unique_id`, Reolink MAC again — same as `id`\n * for vendors where MAC is the natural key). For systems where the\n * live dispatch key can be renamed (HA `entity_id` can be edited),\n * providers detect renames by matching `uniqueId` and patch `id`\n * in-place so dispatch keeps working.\n *\n * **Rendering metadata is NOT stored here.** Display fields (`unit`,\n * `precision`) live in the cap STATUS SLICE so they flow live with every\n * state push and are the single source of truth. The `device_class` tag is\n * an HA-specific input that is consumed at the discovery boundary\n * (`ha-domain-mapping`) to derive the CamStack `DeviceRole`; it is never\n * stored after that point.\n *\n * The `raw` escape hatch carries provider-specific attributes that don't\n * fit the structured slots (HA `attributes` whitelist, Reolink `deviceCache`\n * details, …). Providers control what lands here.\n */\nexport const SourceInfoSchema = z.object({\n // ── Identity (required) ─────────────────────────────────────────\n /** Live dispatch key — mutable when the source system allows rename. */\n id: z.string(),\n /** Source system tag — e.g. 'homeassistant' | 'reolink' | 'frigate'. */\n system: z.string(),\n\n // ── Stability (optional) ────────────────────────────────────────\n /** Immutable upstream identifier when available (HA `unique_id`, … ).\n * Used to detect rename when `id` changes. */\n uniqueId: z.string().optional(),\n\n // ── Free-form passthrough ───────────────────────────────────────\n /** Provider-specific extras that don't fit the structured slots.\n * Whitelist what goes here per provider — do NOT dump entire HA\n * attribute blobs (would explode the meta JSON column). */\n raw: z.record(z.string(), z.unknown()).optional(),\n})\n\nexport type SourceInfo = z.infer<typeof SourceInfoSchema>\n\n/**\n * Build the synthetic SourceInfo every existing provider falls back to\n * when no upstream value has been persisted. Keeps non-migrated providers\n * (Reolink / Hikvision / ONVIF / Frigate / RTSP) functional without code\n * changes — `id` reuses the CamStack stableId, `system` reuses the addon\n * id. Real upstream identity replaces this once a provider migrates and\n * calls `updateSourceInfo()` with concrete values.\n */\nexport function synthesizeSourceInfo(input: {\n stableId: string\n addonId: string\n}): SourceInfo {\n return {\n id: input.stableId,\n system: input.addonId,\n }\n}\n\n/**\n * Shallow-merge a partial patch over a prior SourceInfo. `undefined`\n * patch values are ignored (no field clobber); to clear a field\n * explicitly, providers omit it from the patch and rebuild from scratch\n * via `updateSourceInfo({})` cycles — uncommon enough that we don't\n * bother with a `null`-means-delete sentinel.\n *\n * The `raw` field is also shallow-merged: passing `raw: { foo: 1 }`\n * merges over existing `raw` keys instead of replacing the whole bag.\n */\nexport function mergeSourceInfo(prev: SourceInfo, patch: Partial<SourceInfo>): SourceInfo {\n const next: SourceInfo = { ...prev }\n for (const [k, v] of Object.entries(patch)) {\n if (v === undefined) continue\n if (k === 'raw' && typeof v === 'object' && v !== null) {\n next.raw = { ...(prev.raw ?? {}), ...(v as Record<string, unknown>) }\n continue\n }\n ;(next as Record<string, unknown>)[k] = v\n }\n return next\n}\n\n/**\n * Coerce common unit-of-measurement string variants to a canonical form\n * so the UI's display templates can rely on stable strings. Pure\n * passthrough for unknown units — kept conservative on purpose, the goal\n * is to normalise the long tail of HA `unit_of_measurement` values that\n * have multiple historical spellings (`'°C'` vs `'C'` vs `'celsius'`).\n *\n * Extend the map as we encounter real-world data. Returning the raw\n * input for unknown values is intentional: providers should never\n * lose information silently here.\n */\nexport function normalizeUnit(raw: string | null | undefined): string | undefined {\n if (raw == null) return undefined\n const trimmed = raw.trim()\n if (trimmed === '') return undefined\n const lower = trimmed.toLowerCase()\n // Temperature\n if (lower === '°c' || lower === 'c' || lower === 'celsius') return '°C'\n if (lower === '°f' || lower === 'f' || lower === 'fahrenheit') return '°F'\n if (lower === 'k' || lower === 'kelvin') return 'K'\n // Common percentages / illuminance / pressure\n if (lower === '%' || lower === 'percent' || lower === 'percentage') return '%'\n if (lower === 'lx' || lower === 'lux') return 'lx'\n if (lower === 'hpa' || lower === 'hectopascal') return 'hPa'\n if (lower === 'kpa') return 'kPa'\n if (lower === 'pa') return 'Pa'\n if (lower === 'mbar' || lower === 'millibar') return 'mbar'\n // Power / energy / current / voltage\n if (lower === 'w' || lower === 'watt') return 'W'\n if (lower === 'kw' || lower === 'kilowatt') return 'kW'\n if (lower === 'wh' || lower === 'watt-hour') return 'Wh'\n if (lower === 'kwh' || lower === 'kilowatt-hour') return 'kWh'\n if (lower === 'v' || lower === 'volt') return 'V'\n if (lower === 'a' || lower === 'amp' || lower === 'ampere') return 'A'\n if (lower === 'ma' || lower === 'milliampere') return 'mA'\n if (lower === 'va') return 'VA'\n // Air quality\n if (lower === 'ppm') return 'ppm'\n if (lower === 'ppb') return 'ppb'\n if (lower === 'µg/m³' || lower === 'ug/m3' || lower === 'µg/m3') return 'µg/m³'\n // Distance / speed / weight (passthrough common units)\n if (lower === 'km/h' || lower === 'kph') return 'km/h'\n if (lower === 'mph') return 'mph'\n if (lower === 'm/s') return 'm/s'\n if (lower === 'm') return 'm'\n if (lower === 'km') return 'km'\n if (lower === 'kg') return 'kg'\n if (lower === 'g') return 'g'\n return trimmed\n}\n\n/**\n * Key under which `SourceInfo` lives inside `DeviceMeta.metadata`. The\n * blob is a free-form `Record<string, unknown>` shared with hardware-\n * identity fields (`manufacturer`, `model`, `firmware`, …); SourceInfo\n * lives under a single nested key to keep it composable with those.\n */\nexport const SOURCE_INFO_METADATA_KEY = 'sourceInfo'\n\n/**\n * Extract a SourceInfo from a `DeviceMeta.metadata` blob, validating\n * with Zod. Returns `null` when the blob is missing or the nested\n * `sourceInfo` key fails validation — callers fall back to the\n * synthetic default in that case (see `synthesizeSourceInfo`).\n */\nexport function extractSourceInfoFromMetadata(\n metadata: Record<string, unknown> | null | undefined,\n): SourceInfo | null {\n if (!metadata) return null\n const raw = metadata[SOURCE_INFO_METADATA_KEY]\n if (!raw) return null\n const parsed = SourceInfoSchema.safeParse(raw)\n if (!parsed.success) return null\n return parsed.data\n}\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider, type InferNativeProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\nimport { SourceInfoSchema } from '../device/source-info.js'\nimport type { SourceInfo } from '../device/source-info.js'\n\n/**\n * device-discovery — device-scoped capability for parents that host /\n * enumerate child devices (Reolink Hub / NVR, ONVIF gateway, future\n * integrations). The parent advertises a list of discoverable children,\n * and the operator promotes a subset to real devices via `adoptDevice`.\n * Child lifecycle (kernel device create/remove, parent reference) is\n * owned by the framework so a single shared `<DiscoveryPanel />` can\n * drive any integration.\n *\n * Boundaries:\n * - The cap exposes ENUMERATION + ADOPT/RELEASE only. The protocol\n * used to discover children (CGI poll, mDNS, push from hub, ...)\n * is the integration's business; results land in `runtimeState`\n * so the panel can render without a fresh round-trip.\n * - `childNativeId` is integration-defined and must be stable across\n * reboots so re-discovery doesn't duplicate adopted children.\n * - `adoptDevice` returns the new `deviceId` so the UI can navigate\n * directly to the freshly-created child's settings page.\n */\n\n/**\n * Status enum for a discovered device. Mirrors the Reolink simpleEvent\n * lifecycle (`online` / `sleeping` / `offline`) — generic enough for\n * battery cams, awake cams, and unreachable cams alike.\n */\nexport const DiscoveredChildStatusSchema = z.enum(['online', 'sleeping', 'offline', 'unknown'])\nexport type DiscoveredChildStatus = z.infer<typeof DiscoveredChildStatusSchema>\n\n/**\n * Explicit type for the (now self-referential) discovered-child entry.\n * A `z.lazy` schema cannot cleanly self-infer, so the shape is declared\n * here and the schema below is annotated with it. The `children` /\n * `sourceInfo` / `capabilities` / `features` fields are optional: Hubs\n * (Reolink NVR enumerating flat camera channels) omit them entirely;\n * integrations (Home Assistant previewing a device with entity-children)\n * populate them so a shared adoption panel can render an accordion.\n */\nexport type DiscoveredChildDevice = {\n childNativeId: string\n name: string\n type: DeviceType\n status: DiscoveredChildStatus\n metadata: {\n model?: string\n serialNumber?: string\n uid?: string\n rtspChannel?: number\n isBattery?: boolean\n isDoorbell?: boolean\n isMultifocal?: boolean\n externalLocation?: string\n manufacturer?: string\n integration?: string\n }\n alreadyAdopted: boolean\n adoptedDeviceId: number | null\n // ── Shared adoption fields (optional; Hubs omit, integrations populate) ──\n capabilities?: readonly string[]\n features?: readonly string[]\n sourceInfo?: SourceInfo\n children?: readonly DiscoveredChildDevice[]\n}\n\nexport const DiscoveredChildDeviceSchema: z.ZodType<DiscoveredChildDevice> = z.lazy(() =>\n z.object({\n /** Stable, integration-defined identifier. Must be unique per parent and persistent across reboots. */\n childNativeId: z.string(),\n /** Friendly name as reported by the source (Reolink camera name, ONVIF profile, ...). */\n name: z.string(),\n /** DeviceType the child should be created with on adopt. */\n type: z.enum(DeviceType),\n status: DiscoveredChildStatusSchema,\n /** Free-form integration-specific metadata surfaced in the panel. */\n metadata: z\n .object({\n model: z.string().optional(),\n serialNumber: z.string().optional(),\n uid: z.string().optional(),\n /** Reolink: 0-based channel index inside the parent NVR/Hub. */\n rtspChannel: z.number().int().nonnegative().optional(),\n isBattery: z.boolean().optional(),\n isDoorbell: z.boolean().optional(),\n isMultifocal: z.boolean().optional(),\n externalLocation: z.string().optional(),\n /** Vendor / manufacturer name as reported by the source (HA device\n * `manufacturer`, …). Surfaced in the adoption modal's fuzzy search. */\n manufacturer: z.string().optional(),\n /** Integration / platform domain the candidate belongs to (HA\n * `entity_registry.platform`, e.g. `dreame_vacuum`). Surfaced in the\n * adoption modal's fuzzy search. */\n integration: z.string().optional(),\n })\n .default({}),\n /**\n * `true` when the framework already created a child device for this\n * `childNativeId` under the current parent. The panel uses it to\n * gate the Add/Remove button and surface the existing `deviceId`.\n */\n alreadyAdopted: z.boolean(),\n /** When `alreadyAdopted=true`, the framework-assigned child device id. */\n adoptedDeviceId: z.number().int().nonnegative().nullable(),\n /** Capability names the candidate advertises — integrations populate, Hubs omit. */\n capabilities: z.array(z.string()).readonly().optional(),\n /** Feature flags the candidate advertises — integrations populate, Hubs omit. */\n features: z.array(z.string()).readonly().optional(),\n /** Upstream-system identity + rendering hints for the candidate. */\n sourceInfo: SourceInfoSchema.optional(),\n /** Nested entity-children for accordion preview — integrations populate, Hubs omit. */\n children: z.array(DiscoveredChildDeviceSchema).readonly().optional(),\n }),\n)\n\n/**\n * Status block — populated by the integration after each\n * `refreshDiscovery` (or push-driven update). The runtime-state slice\n * is what the panel reads via the per-device proxy; `getStatus`\n * returns the same payload via the codegen'd auto-injection.\n */\nexport const DeviceDiscoveryStatusSchema = z.object({\n discovered: z.array(DiscoveredChildDeviceSchema),\n /** Wall-clock ms of the last successful enumeration. */\n lastDiscoveryAt: z.number().int().nonnegative().nullable(),\n /** Last error surfaced from the source (rendered as a banner). */\n lastError: z.string().nullable(),\n})\nexport type DeviceDiscoveryStatus = z.infer<typeof DeviceDiscoveryStatusSchema>\n\nexport const deviceDiscoveryCapability = {\n name: 'device-discovery',\n scope: 'device',\n deviceNative: true,\n mode: 'singleton',\n // Hub is the canonical parent. Other integrations (gateway-style)\n // can register against the cap by also targeting their root type.\n deviceTypes: [DeviceType.Hub],\n status: {\n schema: DeviceDiscoveryStatusSchema,\n kind: 'poll',\n },\n // Mirror status into the per-device runtime-state slice so the panel\n // hydrates from the kernel cache without a round-trip on every open.\n runtimeState: DeviceDiscoveryStatusSchema.extend({\n lastFetchedAt: z.number().int().nonnegative(),\n }),\n methods: {\n /**\n * Snapshot of the current `discovered` list. Returns the\n * runtime-state cache — call `refreshDiscovery` first if a\n * fresh round-trip to the source is required.\n */\n listDiscovered: method(\n z.object({ deviceId: z.number().int().nonnegative() }),\n z.array(DiscoveredChildDeviceSchema).readonly(),\n ),\n /**\n * Force the integration to re-enumerate and update the\n * runtime-state slice. Returns the freshly-enumerated list (also\n * available via `listDiscovered` post-call).\n */\n refreshDiscovery: method(\n z.object({ deviceId: z.number().int().nonnegative() }),\n z.array(DiscoveredChildDeviceSchema).readonly(),\n { kind: 'mutation', auth: 'admin' },\n ),\n /**\n * Promote a discovered entry to a real child device. The framework\n * creates the child via `kernel.devices.create()` with\n * `parentDeviceId = parent.id` and seeds the child's config from\n * `childInitialConfig` (driver-defined; usually carries channel +\n * uid + parent reference). Returns the kernel-assigned numeric id.\n */\n adoptDevice: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n childNativeId: z.string(),\n /** Optional override for the child's display name. */\n name: z.string().optional(),\n }),\n z.object({\n deviceId: z.number().int().nonnegative(),\n stableId: z.string(),\n }),\n { kind: 'mutation', auth: 'admin' },\n ),\n /**\n * Inverse of `adoptDevice`: removes the child device from the\n * kernel registry. The discovered entry remains in the\n * enumeration (status updates resume) so the operator can re-adopt\n * it later without a fresh refresh.\n */\n releaseDevice: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n childDeviceId: z.number().int().nonnegative(),\n }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n },\n} as const satisfies CapabilityDefinition\n\nexport type IDeviceDiscoveryProvider = InferProvider<typeof deviceDiscoveryCapability>\nexport type IDeviceDiscoveryNativeProvider = InferNativeProvider<typeof deviceDiscoveryCapability>\n","import { z } from 'zod'\nimport { type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\n\n/**\n * Doorbell button cap. Installed on a `DeviceType.Button` accessory\n * with `role: DeviceRole.Doorbell`. Emits an `onPressed` event every\n * time the firmware pushes a ring; status tracks the last press and\n * a pressCount since start (diagnostic).\n *\n * The DeviceEventPropagator re-emits `onPressed` on the camera parent\n * — subscribers listening at the camera level receive ring events\n * with `via[]` populated. No code on the parent needed.\n */\nexport const DoorbellStatusSchema = z.object({\n /** Ms epoch of the last press. null = never observed since this provider started. */\n lastPressedAt: z.number().nullable(),\n /** Counter since provider start. Resets on reboot. Useful for metrics/debug. */\n pressCountSinceStart: z.number(),\n})\n\nexport type DoorbellStatus = z.infer<typeof DoorbellStatusSchema>\n\nexport const DoorbellPressEventSchema = z.object({\n deviceId: z.number(),\n timestamp: z.number(),\n})\n\nexport type DoorbellPressEvent = z.infer<typeof DoorbellPressEventSchema>\n\nexport const doorbellCapability = {\n name: 'doorbell',\n scope: 'device',\n deviceNative: true,\n mode: 'singleton',\n deviceTypes: [DeviceType.Button],\n methods: {},\n events: {\n /**\n * Fires once per physical press. Reolink delivers via Baichuan\n * push (`ReolinkSimpleEvent.type === 'doorbell'`). There is no\n * release/duration — it's a pulse.\n */\n onPressed: { data: DoorbellPressEventSchema },\n },\n status: {\n schema: DoorbellStatusSchema,\n kind: 'push',\n },\n /**\n * Runtime-state slice — last press timestamp + lifetime press count.\n * Mirrored by the kernel and readable via\n * `device.state.doorbell.value`. UIs can show \"last ring 5m ago\"\n * without subscribing.\n */\n runtimeState: DoorbellStatusSchema,\n} as const satisfies CapabilityDefinition\n\nexport type IDoorbellProvider = InferProvider<typeof doorbellCapability>\n","import { z } from 'zod'\nimport { type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\n\n/**\n * Enum-state sensor — a string value picked from a finite option set.\n * Drives HA `sensor` entries with `state_class: enum` (HVAC action\n * states, weather conditions, contact-source channels, mode strings).\n * The option set is stable across observations; it is persisted in the\n * device config blob (via the control slice at adoption) and is NOT\n * stored in `sourceInfo`.\n */\n/** Locale-render shape for an ISO `value` carried by a `DateTimeSensor`-role\n * enum sensor: `date` (date-only), `time` (time-only), `datetime` (both). */\nexport const EnumSensorDateTimeFormatSchema = z.enum(['date', 'time', 'datetime'])\n\nexport type EnumSensorDateTimeFormat = z.infer<typeof EnumSensorDateTimeFormatSchema>\n\nexport const EnumSensorStatusSchema = z.object({\n value: z.string(),\n /**\n * Set for `DateTimeSensor`-role sensors so the UI renders the ISO `value`\n * as a locale date/time/datetime; absent for plain enum sensors. HA\n * `device_class=timestamp` → `'datetime'`, `device_class=date` → `'date'`,\n * a time-only sensor → `'time'`.\n */\n format: EnumSensorDateTimeFormatSchema.optional(),\n /** Ms epoch when the slice was last updated. */\n lastFetchedAt: z.number(),\n})\n\nexport type EnumSensorStatus = z.infer<typeof EnumSensorStatusSchema>\n\nexport const enumSensorCapability = {\n name: 'enum-sensor',\n scope: 'device',\n deviceNative: true,\n mode: 'singleton',\n deviceTypes: [DeviceType.Sensor],\n methods: {},\n status: {\n schema: EnumSensorStatusSchema,\n kind: 'push',\n },\n runtimeState: EnumSensorStatusSchema,\n} as const satisfies CapabilityDefinition\n\nexport type IEnumSensorProvider = InferProvider<typeof enumSensorCapability>\n","import { z } from 'zod'\nimport { type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\n\n/**\n * Generic stateless event emitter. Installed on a `DeviceType.EventEmitter`\n * device. Carries the device's EXACT declared event vocabulary verbatim\n * (NO normalization). Two shapes:\n * - structured source (HA `event.*` entity) → `eventTypes` is the fixed\n * declared vocabulary (e.g. ['press_short','press_long',...]).\n * - generic/legacy source (HA bus events, e.g. zha_event) → `eventTypes`\n * is [] (open) and `lastEvent.data` carries the complex payload.\n * `seq` is monotonic so two identical events still produce distinct slice writes.\n */\nexport const EventFireSchema = z.object({\n deviceId: z.number(),\n eventType: z.string(),\n data: z.record(z.string(), z.unknown()).nullable(),\n timestamp: z.number(),\n seq: z.number(),\n})\nexport type EventFire = z.infer<typeof EventFireSchema>\n\nexport const EventEmitterStatusSchema = z.object({\n eventTypes: z.array(z.string()),\n lastEvent: EventFireSchema.nullable(),\n eventCountSinceStart: z.number(),\n})\nexport type EventEmitterStatus = z.infer<typeof EventEmitterStatusSchema>\n\nexport const eventEmitterCapability = {\n name: 'event-emitter',\n scope: 'device',\n deviceNative: true,\n mode: 'singleton',\n deviceTypes: [DeviceType.EventEmitter],\n methods: {},\n events: { onEvent: { data: EventFireSchema } },\n status: { schema: EventEmitterStatusSchema, kind: 'push' },\n runtimeState: EventEmitterStatusSchema,\n} as const satisfies CapabilityDefinition\n\nexport type IEventEmitterProvider = InferProvider<typeof eventEmitterCapability>\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\n\n/**\n * Fan-control cap. Models HA `fan.*` entity-specific surfaces:\n * speed percentage, preset modes, ceiling-fan direction, and\n * oscillation. The on/off state lives on the existing `switch` cap\n * (Fan devices register `switch + fan-control`, mirroring the\n * Light pattern of `switch + brightness + color`).\n *\n * `availablePresets` mirrors HA's `preset_modes` attribute so the\n * UI renders a closed-list picker without a separate `getOptions`\n * round-trip. `direction` and `oscillating` are nullable — most\n * fans don't expose them.\n *\n * Sub-surface gating paired with `DeviceFeature` flags:\n * - `FanSpeed` — speed-percentage slider\n * - `FanPreset` — preset selector\n * - `FanDirection` — direction toggle (ceiling fans)\n * - `FanOscillating` — oscillation toggle\n */\n\nexport const FanDirectionSchema = z.enum(['forward', 'reverse'])\nexport type FanDirection = z.infer<typeof FanDirectionSchema>\n\nexport const FanControlStatusSchema = z.object({\n /** Active speed as 0..100 inclusive. Null when the device has no\n * speed surface (single-speed fan). */\n percentage: z.number().min(0).max(100).nullable(),\n /** Speed granularity the device accepts (HA `percentage_step`, e.g. 25 for\n * a 4-speed fan). Absent when unknown — the UI then falls back to step 1. */\n percentageStep: z.number().positive().optional(),\n /** Active preset mode (`auto` / `quiet` / `turbo` / vendor-specific)\n * — empty string when no preset is active or supported. */\n preset: z.string(),\n /** Available preset modes the device accepts. */\n availablePresets: z.array(z.string()),\n /** Ceiling-fan blade direction. Null when the device has no\n * direction surface. */\n direction: FanDirectionSchema.nullable(),\n /** Oscillation toggle. Null when the device has no oscillation\n * surface. */\n oscillating: z.boolean().nullable(),\n /** Ms epoch when the slice was last updated. */\n lastChangedAt: z.number(),\n})\n\nexport type FanControlStatus = z.infer<typeof FanControlStatusSchema>\n\nexport const fanControlCapability = {\n name: 'fan-control',\n scope: 'device',\n deviceNative: true,\n mode: 'singleton',\n deviceTypes: [DeviceType.Fan],\n methods: {\n setPercentage: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n percentage: z.number().min(0).max(100),\n }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n setPreset: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n preset: z.string().min(1),\n }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n setDirection: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n direction: FanDirectionSchema,\n }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n setOscillating: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n oscillating: z.boolean(),\n }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n },\n status: {\n schema: FanControlStatusSchema,\n kind: 'push',\n },\n /**\n * Runtime-state slice — mirrored by the kernel. UI fan speed\n * sliders read `percentage` for live updates.\n */\n runtimeState: FanControlStatusSchema,\n} as const satisfies CapabilityDefinition\n\nexport type IFanControlProvider = InferProvider<typeof fanControlCapability>\n","import { z } from 'zod'\nimport { type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\n\n/**\n * Water leak / moisture sensor. Boolean \"is liquid currently\n * detected\" with the timestamp of the last transition. Drives Home\n * Assistant `binary_sensor` entries with `device_class: moisture`,\n * and any future native flood sensor.\n *\n * Push-driven from the upstream source.\n */\nexport const FloodStatusSchema = z.object({\n /** True when leak is currently detected. */\n flooded: z.boolean(),\n /** Ms epoch of the last flooded↔dry transition. 0 if never observed. */\n lastChangedAt: z.number(),\n})\n\nexport type FloodStatus = z.infer<typeof FloodStatusSchema>\n\nexport const floodCapability = {\n name: 'flood',\n scope: 'device',\n deviceNative: true,\n mode: 'singleton',\n deviceTypes: [DeviceType.Sensor],\n methods: {},\n status: {\n schema: FloodStatusSchema,\n kind: 'push',\n },\n runtimeState: FloodStatusSchema,\n} as const satisfies CapabilityDefinition\n\nexport type IFloodProvider = InferProvider<typeof floodCapability>\n","import { z } from 'zod'\nimport { type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\n\n/**\n * Combustible-gas (LPG / methane / hydrogen) alarm sensor. Drives\n * Home Assistant `binary_sensor` entries with `device_class: gas`.\n * Push-driven.\n */\nexport const GasStatusSchema = z.object({\n detected: z.boolean(),\n /** Ms epoch of the last transition. 0 if never observed. */\n lastChangedAt: z.number(),\n})\n\nexport type GasStatus = z.infer<typeof GasStatusSchema>\n\nexport const gasCapability = {\n name: 'gas',\n scope: 'device',\n deviceNative: true,\n mode: 'singleton',\n deviceTypes: [DeviceType.Sensor],\n methods: {},\n status: {\n schema: GasStatusSchema,\n kind: 'push',\n },\n runtimeState: GasStatusSchema,\n} as const satisfies CapabilityDefinition\n\nexport type IGasProvider = InferProvider<typeof gasCapability>\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\n\n/**\n * Humidifier / dehumidifier cap. Models HA `humidifier.*` entities —\n * an on/off actuator with an optional target-humidity setpoint and an\n * optional vendor mode (`auto` / `normal` / `baby` / …).\n *\n * A climate-family sibling: the slice carries the on/off state, the\n * current + target relative humidity (0..100), the active mode and its\n * available set, plus HA's free-form `action` readout\n * (`humidifying` / `drying` / `idle` / `off`). `minHumidity` /\n * `maxHumidity` mirror HA's `min_humidity` / `max_humidity` attributes\n * (null → the UI falls back to a 0..100 range).\n *\n * Providers populate only what the hardware reports — `mode` and the\n * humidity fields stay null when the device has no such surface.\n */\n\nexport const HumidifierStatusSchema = z.object({\n /** Whether the humidifier is currently on. */\n on: z.boolean(),\n /** Current measured relative humidity (0..100). Null when not reported. */\n currentHumidity: z.number().min(0).max(100).nullable(),\n /** Target relative humidity (0..100). Null when no setpoint surface. */\n targetHumidity: z.number().min(0).max(100).nullable(),\n /** Active mode (`auto` / `normal` / `baby` / vendor). Null when the\n * device has no mode surface. */\n mode: z.string().nullable(),\n /** Available modes the device accepts. */\n availableModes: z.array(z.string()),\n /** HA `action` attribute, verbatim (`humidifying` / `drying` /\n * `idle` / `off`). Null when the device doesn't report it. */\n action: z.string().nullable(),\n /** HA `min_humidity` attribute. Null → UI uses 0. */\n minHumidity: z.number().nullable(),\n /** HA `max_humidity` attribute. Null → UI uses 100. */\n maxHumidity: z.number().nullable(),\n /** Ms epoch when the slice was last updated. */\n lastChangedAt: z.number(),\n})\n\nexport type HumidifierStatus = z.infer<typeof HumidifierStatusSchema>\n\nexport const humidifierCapability = {\n name: 'humidifier',\n scope: 'device',\n deviceNative: true,\n mode: 'singleton',\n deviceTypes: [DeviceType.Humidifier],\n methods: {\n setOn: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n on: z.boolean(),\n }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n setTargetHumidity: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n humidity: z.number().min(0).max(100),\n }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n setMode: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n mode: z.string().min(1),\n }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n },\n status: {\n schema: HumidifierStatusSchema,\n kind: 'push',\n },\n /**\n * Runtime-state slice — mirrored by the kernel. UI controls watch the\n * slice for live humidity / mode changes.\n */\n runtimeState: HumidifierStatusSchema,\n} as const satisfies CapabilityDefinition\n\nexport type IHumidifierProvider = InferProvider<typeof humidifierCapability>\n","import { z } from 'zod'\nimport { type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\n\n/**\n * Single-metric humidity reading. Drives Home Assistant `sensor`\n * entries with `device_class: humidity`.\n *\n * Unit normalisation: percent. The canonical display unit (`%`) is a\n * descriptor constant in the UI (ROLE_DESCRIPTOR), not stored in\n * `sourceInfo`.\n */\nexport const HumiditySensorStatusSchema = z.object({\n /** Current relative humidity, 0..100. */\n percent: z.number().min(0).max(100),\n /** Ms epoch when the slice was last updated. */\n lastFetchedAt: z.number(),\n /** Live display unit from the upstream source (e.g. HA\n * `attributes.unit_of_measurement`). The UI prefers this over the\n * role's canonical unit. Absent → fall back to the canonical unit. */\n unit: z.string().optional(),\n /** Suggested decimal places for numeric display.\n * Populated live from the upstream source when provided (e.g. HA\n * `attributes.suggested_display_precision`). Falls back to\n * auto-formatting when absent. */\n precision: z.number().int().min(0).max(10).optional(),\n})\n\nexport type HumiditySensorStatus = z.infer<typeof HumiditySensorStatusSchema>\n\nexport const humiditySensorCapability = {\n name: 'humidity-sensor',\n scope: 'device',\n deviceNative: true,\n mode: 'singleton',\n deviceTypes: [DeviceType.Sensor, DeviceType.Thermostat],\n methods: {},\n status: {\n schema: HumiditySensorStatusSchema,\n kind: 'push',\n },\n runtimeState: HumiditySensorStatusSchema,\n} as const satisfies CapabilityDefinition\n\nexport type IHumiditySensorProvider = InferProvider<typeof humiditySensorCapability>\n","import { z } from 'zod'\nimport { type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\n\n/**\n * Image display cap. Models HA `image.*` entities — a single still image\n * exposed by an integration (a snapshot, a chart, a generated picture).\n *\n * Read-only: there are no setters. The provider resolves the HA\n * `entity_picture` (a relative, signed-token path) into an ABSOLUTE URL\n * the browser loads directly — the token stays in the query string so no\n * auth header is required. The slice carries that URL plus the upstream\n * last-updated timestamp; the image changes when the entity state (a\n * timestamp) changes.\n */\nexport const ImageStatusSchema = z.object({\n /** Absolute signed URL the browser loads directly. Null when the\n * entity exposes no `entity_picture` (yet). */\n url: z.string().nullable(),\n /** Ms epoch of the upstream last-updated timestamp. Null at cold-start. */\n lastUpdated: z.number().nullable(),\n})\n\nexport type ImageStatus = z.infer<typeof ImageStatusSchema>\n\nexport const imageCapability = {\n name: 'image',\n scope: 'device',\n deviceNative: true,\n mode: 'singleton',\n deviceTypes: [DeviceType.Image],\n // Read-only — no service methods. Codegen still auto-injects `getStatus`\n // because `status` is set.\n methods: {},\n status: {\n schema: ImageStatusSchema,\n kind: 'push',\n },\n /**\n * Runtime-state slice — mirrored by the kernel. The UI reads `url`\n * directly and renders the still image.\n */\n runtimeState: ImageStatusSchema,\n} as const satisfies CapabilityDefinition\n\nexport type IImageProvider = InferProvider<typeof imageCapability>\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\n\n/**\n * Robotic lawn-mower cap. Models HA `lawn_mower.*` entities — anything\n * with a mowing lifecycle plus a dock action.\n *\n * Activity follows HA's canonical lawn-mower lifecycle: `idle` /\n * `mowing` / `paused` / `docked` / `error`. `batteryLevel` (0..100) is\n * nullable — some mowers don't report a battery percentage.\n *\n * `startMowing` begins a mowing run, `pause` halts it in place, and\n * `dock` sends the mower back to its charging station.\n */\n\nexport const LawnMowerActivitySchema = z.enum([\n 'idle',\n 'mowing',\n 'paused',\n 'docked',\n 'error',\n])\nexport type LawnMowerActivity = z.infer<typeof LawnMowerActivitySchema>\n\nexport const LawnMowerControlStatusSchema = z.object({\n /** Lifecycle activity of the mower. */\n activity: LawnMowerActivitySchema,\n /** 0..100 battery percentage. Null when the device has no battery\n * reading. */\n batteryLevel: z.number().min(0).max(100).nullable(),\n /** Ms epoch when the slice was last updated. */\n lastChangedAt: z.number(),\n})\n\nexport type LawnMowerControlStatus = z.infer<typeof LawnMowerControlStatusSchema>\n\nexport const lawnMowerControlCapability = {\n name: 'lawn-mower-control',\n scope: 'device',\n deviceNative: true,\n mode: 'singleton',\n deviceTypes: [DeviceType.LawnMower],\n methods: {\n startMowing: method(\n z.object({ deviceId: z.number().int().nonnegative() }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n pause: method(\n z.object({ deviceId: z.number().int().nonnegative() }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n dock: method(\n z.object({ deviceId: z.number().int().nonnegative() }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n },\n status: {\n schema: LawnMowerControlStatusSchema,\n kind: 'push',\n },\n /**\n * Runtime-state slice — mirrored by the kernel. UI controls watch the\n * slice for live activity + battery changes.\n */\n runtimeState: LawnMowerControlStatusSchema,\n} as const satisfies CapabilityDefinition\n\nexport type ILawnMowerControlProvider = InferProvider<typeof lawnMowerControlCapability>\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\n\n/**\n * Smart-lock cap. Models HA `lock.*` entities — anything with a\n * locked / unlocked binary state plus the four transient lifecycle\n * states (`locking` / `unlocking`) and the `jammed` failure state\n * that low-end deadbolts surface when the motor can't reach the\n * target position.\n *\n * Some HA locks require a PIN code on every lock/unlock operation\n * (workplace keypad locks, hospitality). The optional `code` field\n * on the methods passes it through to the upstream service — the\n * code is NEVER persisted in the runtime slice or any event payload.\n * Locks that REQUIRE a code set `DeviceFeature.LockPinRequired` so\n * the UI gates a code-entry field without a slice fetch.\n *\n * Locks that support a latch-release (\"open door\") action advertise\n * `DeviceFeature.LockOpen`. The `open` method triggers the latch\n * without a full lock/unlock cycle. Only available when the lock\n * reports `LockEntityFeature.OPEN` (bit value 1) in HA\n * `supported_features`.\n */\n\nexport const LockStateSchema = z.enum([\n 'locked',\n 'unlocked',\n 'locking',\n 'unlocking',\n 'jammed',\n])\nexport type LockState = z.infer<typeof LockStateSchema>\n\nexport const LockControlStatusSchema = z.object({\n /** Lifecycle state of the lock. `jammed` means the motor reported\n * failure to reach the target — operator intervention required. */\n state: LockStateSchema,\n /** Ms epoch when the slice was last updated. */\n lastChangedAt: z.number(),\n})\n\nexport type LockControlStatus = z.infer<typeof LockControlStatusSchema>\n\nexport const lockControlCapability = {\n name: 'lock-control',\n scope: 'device',\n deviceNative: true,\n mode: 'singleton',\n deviceTypes: [DeviceType.Lock],\n methods: {\n lock: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n /** Optional PIN code required by some keypad locks. NOT\n * persisted — passed directly to the upstream service. */\n code: z.string().min(1).optional(),\n }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n unlock: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n code: z.string().min(1).optional(),\n }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n open: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n },\n status: {\n schema: LockControlStatusSchema,\n kind: 'push',\n },\n /**\n * Runtime-state slice — mirrored by the kernel. UI lock buttons\n * read `state` and disable themselves during `locking`/`unlocking`\n * transitions.\n */\n runtimeState: LockControlStatusSchema,\n} as const satisfies CapabilityDefinition\n\nexport type ILockControlProvider = InferProvider<typeof lockControlCapability>\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\n\n/**\n * Media-player cap. Models HA `media_player.*` (Sonos, Chromecast,\n * Apple TV, Spotify, Roku, generic OTT receivers, …) on\n * `DeviceType.MediaPlayer`. Disjoint from the camera streaming\n * surface — those use `DeviceType.Camera` + the broker pipeline.\n *\n * The cap declares a wide method surface; not every backend supports\n * every method. Drivers signal sub-capability via the\n * `DeviceFeature.MediaPlayerXxx` flags (paired one-to-one with the\n * corresponding method) so the UI gates buttons without a slice\n * fetch — same pattern as `PanTiltZoom` for cameras.\n */\n\nexport const MediaPlayerStateSchema = z.enum([\n 'off',\n 'on',\n 'idle',\n 'playing',\n 'paused',\n 'buffering',\n 'standby',\n])\nexport type MediaPlayerState = z.infer<typeof MediaPlayerStateSchema>\n\nexport const MediaPlayerRepeatSchema = z.enum(['off', 'all', 'one'])\nexport type MediaPlayerRepeat = z.infer<typeof MediaPlayerRepeatSchema>\n\nconst MediaInfoSchema = z.object({\n /** Free-form media kind (`music`, `tvshow`, `movie`, `app`, `channel`,\n * `podcast`, …). */\n type: z.string(),\n /** Human-readable title. */\n title: z.string(),\n /** Optional artist / channel / station label. */\n artist: z.string().optional(),\n /** Optional album / season / show name. */\n album: z.string().optional(),\n /** Optional cover-art / thumbnail URL. */\n imageUrl: z.string().optional(),\n})\nexport type MediaInfo = z.infer<typeof MediaInfoSchema>\n\nexport const MediaPlayerStatusSchema = z.object({\n /** Playback lifecycle state. */\n state: MediaPlayerStateSchema,\n /** Volume as 0..100 inclusive. Null when the device has no volume\n * surface. Pair with `DeviceFeature.MediaPlayerVolume`. */\n volumeLevel: z.number().min(0).max(100).nullable(),\n /** Mute toggle distinct from volume=0. Null when no mute surface.\n * Pair with `DeviceFeature.MediaPlayerMute`. */\n isMuted: z.boolean().nullable(),\n /** Active source / input. Empty when no source surface. */\n source: z.string(),\n /** Selectable sources. Empty when no source surface.\n * Pair with `DeviceFeature.MediaPlayerSelectSource`. */\n availableSources: z.array(z.string()),\n /** Currently-playing media info. Null when nothing is playing. */\n currentMedia: MediaInfoSchema.nullable(),\n /** Current playback position in ms. Null when not seekable or\n * nothing is playing. Pair with `DeviceFeature.MediaPlayerSeek`. */\n positionMs: z.number().int().nonnegative().nullable(),\n /** Total duration of the current media in ms. Null when unknown\n * (live stream) or nothing is playing. */\n durationMs: z.number().int().nonnegative().nullable(),\n /** Shuffle toggle. Null when no shuffle surface.\n * Pair with `DeviceFeature.MediaPlayerShuffle`. */\n shuffle: z.boolean().nullable(),\n /** Repeat mode. Null when no repeat surface.\n * Pair with `DeviceFeature.MediaPlayerRepeat`. */\n repeat: MediaPlayerRepeatSchema.nullable(),\n /** Ms epoch when the slice was last updated. */\n lastChangedAt: z.number(),\n})\n\nexport type MediaPlayerStatus = z.infer<typeof MediaPlayerStatusSchema>\n\nexport const mediaPlayerCapability = {\n name: 'media-player',\n scope: 'device',\n deviceNative: true,\n mode: 'singleton',\n deviceTypes: [DeviceType.MediaPlayer],\n methods: {\n play: method(\n z.object({ deviceId: z.number().int().nonnegative() }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n pause: method(\n z.object({ deviceId: z.number().int().nonnegative() }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n stop: method(\n z.object({ deviceId: z.number().int().nonnegative() }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n next: method(\n z.object({ deviceId: z.number().int().nonnegative() }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n previous: method(\n z.object({ deviceId: z.number().int().nonnegative() }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n seek: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n positionMs: z.number().int().nonnegative(),\n }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n setVolume: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n volumeLevel: z.number().min(0).max(100),\n }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n setMute: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n muted: z.boolean(),\n }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n setShuffle: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n shuffle: z.boolean(),\n }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n setRepeat: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n repeat: MediaPlayerRepeatSchema,\n }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n selectSource: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n source: z.string().min(1),\n }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n playMedia: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n /** Media identifier / URL. */\n mediaId: z.string().min(1),\n /** Media kind (`music`, `tvshow`, `movie`, `app`, …) — provider\n * passes it through to the upstream service. */\n mediaType: z.string().min(1),\n }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n },\n status: {\n schema: MediaPlayerStatusSchema,\n kind: 'push',\n },\n /**\n * Runtime-state slice — mirrored by the kernel. UI players read the\n * full slice for live now-playing, volume, and progress updates\n * without polling.\n */\n runtimeState: MediaPlayerStatusSchema,\n} as const satisfies CapabilityDefinition\n\nexport type IMediaPlayerProvider = InferProvider<typeof mediaPlayerCapability>\n","/** Shared Zod schemas used across detection capabilities. */\n\nimport { z } from 'zod'\n\n/**\n * Canonical frame-format enum mirrored on `FrameFormat` in\n * `packages/types/src/types/io.ts`. Kept inline (vs imported) so the\n * Zod runtime schema and TypeScript type stay in sync at the call site\n * — adding a new format requires changing both this enum and the\n * `FrameFormat` type alias together.\n */\nexport const FrameFormatSchema = z.enum(['jpeg', 'rgb', 'bgr', 'yuv420', 'gray'])\n\nexport const FrameInputSchema = z.object({\n data: z.custom<Uint8Array>(),\n format: FrameFormatSchema,\n width: z.number(),\n height: z.number(),\n timestamp: z.number(),\n})\n\nexport const BoundingBoxSchema = z.object({\n x: z.number(),\n y: z.number(),\n w: z.number(),\n h: z.number(),\n})\n\nexport const SpatialDetectionSchema = z.object({\n class: z.string(),\n originalClass: z.string(),\n score: z.number(),\n bbox: BoundingBoxSchema,\n})\n\n/**\n * `data` carries the raw f32le bytes of the PCM samples (4 bytes per\n * sample, little-endian IEEE 754). `Uint8Array` is the wire-safe choice\n * because `@msgpack/msgpack` serialises it as a MsgPack `bin` type that\n * round-trips losslessly over the UDS transport. `Float32Array` is NOT\n * preserved — the encoder serialises it as `bin` (its raw bytes) but\n * the decoder returns `Uint8Array`, so treating a `Float32Array` as the\n * wire type causes receivers to read bytes as sample values, producing\n * wildly wrong RMS/dBFS results (~+43 dBFS instead of ≤0).\n *\n * Callers that need float arithmetic reconstruct the view with:\n * `new Float32Array(chunk.data.buffer, chunk.data.byteOffset, chunk.data.byteLength / 4)`\n */\nexport const AudioChunkInputSchema = z.object({\n data: z.instanceof(Uint8Array),\n sampleRate: z.number(),\n channels: z.number(),\n timestamp: z.number(),\n /** Originating device id — used by the classifier for per-camera concurrency tracking. */\n deviceId: z.number().optional(),\n})\n\nexport const AudioLevelSchema = z.object({\n rms: z.number(),\n dbfs: z.number(),\n})\n\nexport const AudioClassificationLabelSchema = z.object({\n /**\n * Primary display class. Depending on how the label was produced\n * this is either the macro category (e.g. `dog`) or the raw\n * backend label (e.g. `Dog bark`). Mirrors `class` on\n * `SpatialDetection`.\n */\n className: z.string(),\n /**\n * Raw backend-native label the classifier actually emitted (e.g.\n * `Dog bark` for YAMNet, `dog_bark` for Apple SoundAnalysis). For\n * macro-aggregated entries this is the top raw contributor. Mirrors\n * `originalClass` on `SpatialDetection`.\n */\n originalClass: z.string().optional(),\n score: z.number(),\n})\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { FrameInputSchema, BoundingBoxSchema } from './schemas/detection-shared.js'\n\nconst MotionRegionSchema = z.object({\n bbox: BoundingBoxSchema,\n pixelCount: z.number(),\n intensity: z.number(),\n})\n\nconst MotionAnalysisResultSchema = z.object({\n detected: z.boolean(),\n regionCount: z.number(),\n /** Regions passing minArea filter — used for pipeline triggering. */\n regions: z.array(MotionRegionSchema).readonly(),\n /** All raw regions from CCL before minArea filter — used for UI debug overlay. */\n rawRegions: z.array(MotionRegionSchema).readonly(),\n frameWidth: z.number(),\n frameHeight: z.number(),\n analysisMs: z.number(),\n})\n\nexport const motionDetectionCapability = {\n name: 'motion-detection',\n scope: 'device',\n mode: 'singleton',\n kind: 'wrapper',\n defaultActive: true,\n exposesDeviceSettings: true,\n methods: {\n analyze: method(\n z.object({ deviceId: z.number(), frame: FrameInputSchema }),\n MotionAnalysisResultSchema,\n { kind: 'mutation' },\n ),\n removeCamera: method(z.object({ deviceId: z.number() }), z.void(), { kind: 'mutation' }),\n reset: method(z.void(), z.void(), { kind: 'mutation' }),\n },\n events: {\n onMotion: { data: z.object({\n deviceId: z.number(),\n detected: z.boolean(),\n regionCount: z.number(),\n })},\n },\n} as const satisfies CapabilityDefinition\n\nexport type IMotionDetectionProvider = InferProvider<typeof motionDetectionCapability>\nexport type MotionRegion = z.infer<typeof MotionRegionSchema>\nexport type MotionAnalysisResult = z.infer<typeof MotionAnalysisResultSchema>\n\nexport { MotionRegionSchema, MotionAnalysisResultSchema }\n","/** Shared Zod schemas for the runtime pipeline orchestrator metrics. */\n\nimport { z } from 'zod'\n\nexport const OrchestratorMetricsSchema = z.object({\n activeCameras: z.number(),\n throttledCameras: z.number(),\n avgInferenceTimeMs: z.number(),\n queueDepth: z.number(),\n})\n\nexport const CameraMetricsSchema = z.object({\n detectionMode: z.enum(['disabled', 'always-on', 'on-motion']),\n configuredFps: z.number(),\n actualFps: z.number(),\n queueDepth: z.number(),\n avgInferenceTimeMs: z.number(),\n droppedFrames: z.number(),\n phase: z.enum(['idle', 'watching', 'active']),\n})\n\nexport const CameraMetricsWithDeviceIdSchema = CameraMetricsSchema.extend({\n deviceId: z.number(),\n})\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { FrameInputSchema, SpatialDetectionSchema } from './schemas/detection-shared.js'\nimport type { ConfigUISchema, ConfigField } from '../interfaces/config-ui.js'\nimport type { InferenceCapabilities, ModelAvailability } from '../interfaces/inference-capabilities.js'\nimport type { PipelineConfig } from '../types/pipeline.js'\nimport type { FrameResult, AudioResult } from '../types/detection.js'\n\n// ── Engine & device ──────────────────────────────────────────────\nconst ModelFormatSchema = z.enum(['onnx', 'coreml', 'openvino', 'tflite', 'pt'])\nconst PipelineSlotSchema = z.enum(['detector', 'cropper', 'classifier', 'refiner', 'audio-classifier'])\n\nconst PipelineEngineChoiceSchema = z.object({\n runtime: z.enum(['node', 'python']),\n backend: z.string(),\n format: ModelFormatSchema,\n device: z.string().optional(),\n})\n\nconst EngineDeviceInfoSchema = z.object({\n id: z.string(),\n label: z.string(),\n description: z.string().optional(),\n})\n\nconst AvailableEngineSchema = z.object({\n engine: PipelineEngineChoiceSchema,\n devices: z.array(EngineDeviceInfoSchema).readonly(),\n defaultDevice: z.string(),\n})\n\n// ── Pipeline step (recursive) ──\n// Zod v4's `ZodType` is invariant over its `Input`/`Output` generics, so the\n// canonical `z.lazy()` recursive pattern does not type-check cleanly against\n// the full `PipelineDefaultStep` TS interface. Use a zod-inferred type\n// instead — the resulting shape is structurally identical and still fully\n// typed for callers via `z.infer<typeof PipelineDefaultStepSchema>`.\n// Phase 7 (settings redesign): removed generic `confidence: number` field.\n// Each step declares its own thresholds via `configSchema` and persists\n// them inside `settings`. The runtime executor reads\n// `StepDefinition.defaultConfidence` from the step registry as the\n// hard-coded fallback threshold.\nexport type PipelineDefaultStepOutput = {\n readonly addonId: string\n readonly addonName: string\n readonly slot: 'detector' | 'cropper' | 'classifier' | 'refiner' | 'audio-classifier'\n readonly inputClasses: readonly string[]\n readonly outputClasses: readonly string[]\n readonly enabled: boolean\n readonly modelId: string\n readonly children: readonly PipelineDefaultStepOutput[]\n readonly engine?: {\n readonly runtime: 'node' | 'python'\n readonly backend: string\n readonly format: 'onnx' | 'coreml' | 'openvino' | 'tflite' | 'pt'\n readonly device?: string\n }\n readonly group?: string\n readonly settings?: Readonly<Record<string, unknown>>\n}\n\nconst PipelineDefaultStepSchema: z.ZodType<PipelineDefaultStepOutput> = z.lazy(() =>\n z.object({\n addonId: z.string(),\n addonName: z.string(),\n slot: PipelineSlotSchema,\n inputClasses: z.array(z.string()).readonly(),\n outputClasses: z.array(z.string()).readonly(),\n enabled: z.boolean(),\n modelId: z.string(),\n children: z.array(PipelineDefaultStepSchema).readonly(),\n engine: PipelineEngineChoiceSchema.optional(),\n group: z.string().optional(),\n settings: z.record(z.string(), z.unknown()).optional(),\n }),\n)\n\n// ── PipelineTemplate step (recursive) ──\n// Phase 7: same reasoning as `PipelineDefaultStepOutput` — no generic\n// `confidence` field. Templates created before Phase 7 are migrated on\n// load by `provider.ts::loadTemplates` which strips the obsolete key.\nexport type PipelineTemplateStepOutput = {\n readonly addonId: string\n readonly enabled: boolean\n readonly modelId: string\n readonly children: readonly PipelineTemplateStepOutput[]\n readonly settings?: Readonly<Record<string, unknown>>\n}\n\nconst PipelineTemplateStepSchema: z.ZodType<PipelineTemplateStepOutput> = z.lazy(() =>\n z.object({\n addonId: z.string(),\n enabled: z.boolean(),\n modelId: z.string(),\n children: z.array(PipelineTemplateStepSchema).readonly(),\n settings: z.record(z.string(), z.unknown()).optional(),\n }),\n)\n\nconst PipelineTemplateSchema = z.object({\n id: z.string(),\n name: z.string(),\n createdAt: z.string(),\n updatedAt: z.string(),\n engine: PipelineEngineChoiceSchema,\n steps: z.array(PipelineTemplateStepSchema).readonly(),\n})\n\n// ── PipelineSchema (returned by getSchema) ──\nconst PipelineModelOptionSchema = z.object({\n id: z.string(),\n name: z.string(),\n formats: z.record(\n z.string(),\n z.object({ downloaded: z.boolean(), sizeMB: z.number() }),\n ),\n})\n\nconst ConfigFieldBridge = z.custom<ConfigField>()\n\nconst PipelineAddonSchemaSchema = z.object({\n id: z.string(),\n name: z.string(),\n slot: PipelineSlotSchema,\n inputClasses: z.array(z.string()).readonly(),\n outputClasses: z.array(z.string()).readonly(),\n childSlots: z.array(PipelineSlotSchema).readonly(),\n models: z.array(PipelineModelOptionSchema).readonly(),\n defaultModelId: z.string(),\n // Per-format model override. Lets an addon declare \"on `coreml` prefer\n // apple-soundanalysis, on `onnx` prefer yamnet-onnx\". The orchestrator's\n // agent-seed routine uses this to pick a modelId that matches the\n // agent's active engine format.\n defaultModelIdByFormat: z.record(z.string(), z.string()).optional(),\n // Whether a freshly-seeded agent starts with this addon `enabled: true`.\n // Absent = true. Operator-controlled after first seed.\n enabledByDefault: z.boolean().optional(),\n defaultConfidence: z.number(),\n group: z.string().optional(),\n configSchema: z.array(ConfigFieldBridge).readonly().optional(),\n})\n\nconst PipelineSlotSchemaSchema = z.object({\n id: PipelineSlotSchema,\n label: z.string(),\n priority: z.number(),\n parentSlot: PipelineSlotSchema.nullable(),\n addons: z.array(PipelineAddonSchemaSchema).readonly(),\n})\n\nconst PipelineSchemaSchema = z.object({\n availableEngines: z.array(AvailableEngineSchema).readonly(),\n selectedEngine: PipelineEngineChoiceSchema,\n slots: z.array(PipelineSlotSchemaSchema).readonly(),\n})\n\n// ── Detection / inference ──\nconst DetectorOutputSchema = z.object({\n detections: z.array(SpatialDetectionSchema).readonly(),\n inferenceMs: z.number(),\n modelId: z.string(),\n})\n\n// ── Pipeline run input (UI-facing) ──\n// Phase 7: dropped generic `confidence`. Per-step thresholds live in\n// `settings` (each step declares its own field in `configSchema`); the\n// runtime executor falls back to `StepDefinition.defaultConfidence`\n// when settings don't override.\nexport type PipelineStepInputOutput = {\n readonly addonId: string\n readonly modelId: string\n readonly enabled: boolean\n readonly children?: readonly PipelineStepInputOutput[]\n readonly settings?: Readonly<Record<string, unknown>>\n}\n\nexport const PipelineStepInputSchema: z.ZodType<PipelineStepInputOutput> = z.lazy(() =>\n z.object({\n addonId: z.string(),\n modelId: z.string(),\n enabled: z.boolean().default(true),\n children: z.array(PipelineStepInputSchema).optional(),\n settings: z.record(z.string(), z.unknown()).optional(),\n }),\n)\n\n// ── Reference media ──\nconst ReferenceImageEntrySchema = z.object({\n filename: z.string(),\n stepIds: z.array(z.string()).readonly().optional(),\n})\n\nconst ReferenceImageBodySchema = z.object({\n base64: z.string(),\n filename: z.string(),\n})\n\nconst ReferenceAudioEntrySchema = z.object({\n filename: z.string(),\n sizeKb: z.number(),\n})\n\nconst ReferenceAudioBodySchema = z.object({\n base64: z.string(),\n})\n\n// Benchmark schemas (BenchmarkInputSchema, BenchmarkResultSchema,\n// BenchmarkHistoryEntrySchema, BenchmarkHistoryEntryInputSchema,\n// BenchmarkLatencyStatsSchema, PipelineRunInputSchema) moved to\n// `@camstack/addon-benchmark/src/benchmark-schemas.ts` (2026-04-14).\n// They describe a surface that belongs to the benchmark addon, not the\n// core pipeline-executor cap. `PipelineEngineChoiceSchema` below remains\n// exported because it's still referenced by other cap methods (runPipeline\n// output, getSelectedEngine).\n\nconst AudioBackendSchema = z.object({\n id: z.string(),\n name: z.string(),\n description: z.string(),\n available: z.boolean(),\n /**\n * Raw classifier labels this backend can emit (e.g. YAMNet's\n * 521-class set or Apple SoundAnalysis's 303-class set). Used by\n * the benchmark UI to populate the `enabledMicroClasses` filter\n * specific to the selected backend without a separate fetch.\n */\n rawLabels: z.array(z.string()).readonly().optional(),\n})\n\nconst AudioCapabilitiesSchema = z.object({\n activeBackend: z.string(),\n availableBackends: z.array(AudioBackendSchema).readonly(),\n sampleRate: z.number(),\n chunkDurationMs: z.number(),\n})\n\n// ── Download model result ────────────────────────────────────────────\nconst DownloadModelResultSchema = z.object({\n filePath: z.string(),\n sizeMB: z.number(),\n durationMs: z.number(),\n})\n\n/**\n * Wrapper carrying a single test run's result. Replaces the legacy\n * ad-hoc `{labels: [{className, originalClass, score}]}` shape with the\n * canonical `AudioResult` from the Phase 6 output rework: one\n * `AudioDetection` per class above `minScore`, top-N candidates in\n * `debug.alternateLabels['audio-classifier']`, per-source timings in\n * `debug.stepTimings`. The outer `success`/`error` fields stay so the\n * benchmark UI can still report a clean failure when the classifier\n * cap isn't available.\n */\nconst AudioTestResultSchema = z.object({\n success: z.boolean(),\n error: z.string().optional(),\n frame: z.custom<AudioResult>().optional(),\n})\n\n// ── Typed bridges to complex TS interfaces defined in `@camstack/types` ──\n// Use `z.custom<T>()` when the target interface is a deeply-nested discriminated\n// union (ConfigUISchema) or a recursive graph (PipelineConfig, PipelineRunResult,\n// InferenceCapabilities). `z.custom<T>()` provides full TS inference on the\n// client without forcing a duplicate Zod definition that would drift from the\n// canonical TS interface. Validation is structural at the tRPC transport layer\n// and the server-side provider guarantees the shape at emission time.\nconst PipelineConfigBridge = z.custom<PipelineConfig | null>()\nconst ConfigUISchemaBridge = z.custom<ConfigUISchema>()\nconst ConfigUISchemaNullableBridge = z.custom<ConfigUISchema | null>()\nconst InferenceCapabilitiesBridge = z.custom<InferenceCapabilities>()\nconst ModelAvailabilityListBridge = z.custom<readonly ModelAvailability[]>()\nexport const PipelineRunResultBridge = z.custom<FrameResult>()\n\n/**\n * Pipeline executor — detection engine + configuration + inference API.\n *\n * Merged from: pipeline-executor, pipeline-config, inference, detection-config.\n * Implemented by the detection-pipeline addon.\n *\n * Per-device surface (DeviceSettingsContribution + the \"is detection\n * enabled for this camera?\" toggle) lives on the paired\n * `detection-pipeline` cap (device-scoped, singleton, wrapper\n * defaultActive) — same split pattern used by stream-broker /\n * camera-streams and audio-analyzer / audio-analysis.\n */\nexport const pipelineExecutorCapability = {\n name: 'pipeline-executor',\n scope: 'system',\n mode: 'singleton',\n methods: {\n // ── Engine selection ─────────────────────────────────────────────\n // `setEngine` removed in Phase 6c — the stateless-pipeline model\n // picks engine per-camera, not per-node. `getSelectedEngine` is\n // kept read-only so the benchmark + models-page can still show the\n // executor's bootstrap engine; its semantics degrade to \"what the\n // executor would pick by default\" in the stateless world.\n getAvailableEngines: method(z.void(), z.array(PipelineEngineChoiceSchema)),\n getSelectedEngine: method(z.void(), PipelineEngineChoiceSchema),\n getDefaultSteps: method(PipelineEngineChoiceSchema, z.array(PipelineDefaultStepSchema)),\n /**\n * Re-run the platform probe for the inference engine and write the\n * detected runtime / backend / device back into the addon's own\n * global settings store. Returns the engine that was picked so the\n * UI can confirm without a second round-trip. Triggers the standard\n * `requiresRestart` auto-restart flow because all three fields are\n * marked restart-required. Replaces the legacy per-agent\n * `pipeline-orchestrator.reprobeAgentHwAccel` surface for the\n * engine dimension — each addon now owns its own probe.\n */\n reprobeEngine: method(z.void(), PipelineEngineChoiceSchema, { kind: 'mutation', auth: 'admin' }),\n\n // ── Video pipeline step configuration (phase 2c) ─────────────────\n // Per-addonId config the operator tunes on the Pipeline → agent\n // page. Replaces the orchestrator's per-agent\n // `setAgentAddonDefaults` mutation. No `enabled` flag — the cap\n // binding system (wrapper caps + setWrapperActive) decides whether\n // a step runs.\n getVideoPipelineSteps: method(\n z.void(),\n z.record(z.string(), z.object({\n modelId: z.string(),\n settings: z.record(z.string(), z.unknown()).readonly(),\n })),\n ),\n setVideoPipelineSteps: method(\n z.object({\n steps: z.record(z.string(), z.object({\n modelId: z.string(),\n settings: z.record(z.string(), z.unknown()).readonly(),\n })),\n }),\n z.object({ success: z.literal(true) }),\n { kind: 'mutation', auth: 'admin' },\n ),\n\n // ── Global pipeline configuration ────────────────────────────────\n // `setGlobalSteps` removed in Phase 6c — there is no \"global\n // pipeline\" in the stateless model (each camera carries its own\n // steps via the orchestrator's `pipelines/<deviceId>`).\n // `getGlobalSteps` is kept read-only as a benchmark fallback;\n // it returns null in fresh stateless deploys.\n getSchema: method(z.void(), PipelineSchemaSchema),\n getGlobalSteps: method(z.void(), z.array(PipelineDefaultStepSchema).readonly().nullable()),\n getGlobalPipelineConfig: method(z.void(), PipelineConfigBridge),\n getOrchestratorConfigSchema: method(z.void(), ConfigUISchemaBridge),\n\n // ── Templates ────────────────────────────────────────────────────\n listTemplates: method(z.void(), z.array(PipelineTemplateSchema).readonly()),\n saveTemplate: method(\n z.object({\n name: z.string(),\n steps: z.array(PipelineTemplateStepSchema).readonly(),\n engine: PipelineEngineChoiceSchema,\n }),\n PipelineTemplateSchema,\n { kind: 'mutation' },\n ),\n updateTemplate: method(\n z.object({\n id: z.string(),\n name: z.string().optional(),\n steps: z.array(PipelineTemplateStepSchema).readonly().optional(),\n }),\n PipelineTemplateSchema,\n { kind: 'mutation' },\n ),\n deleteTemplate: method(z.object({ id: z.string() }), z.void(), { kind: 'mutation' }),\n\n // ── Inference / detection ────────────────────────────────────────\n getCapabilities: method(z.void(), InferenceCapabilitiesBridge),\n getAddonModels: method(z.object({ addonId: z.string() }), ModelAvailabilityListBridge),\n downloadModel: method(\n z.object({ addonId: z.string(), modelId: z.string(), format: ModelFormatSchema }),\n DownloadModelResultSchema,\n { kind: 'mutation' },\n ),\n deleteModel: method(\n z.object({ addonId: z.string(), modelId: z.string(), format: ModelFormatSchema }),\n z.object({ success: z.literal(true) }),\n { kind: 'mutation' },\n ),\n // NOTE: onDownloadProgress / onPipelineProgress removed in Fase H.4.\n // Consumers subscribe via the generic `live.onEvent` core router with\n // `{category: 'model.download.progress'}` or `{category: 'pipeline.progress'}`\n // — the event bus already handles category filtering, no dedicated\n // pipeline-executor method needed.\n detect: method(\n z.object({ addonId: z.string(), frame: FrameInputSchema, config: z.record(z.string(), z.unknown()).optional() }),\n DetectorOutputSchema,\n ),\n // `runFrame` removed in Phase 4 — runtime dispatch now goes through\n // the stateless `runPipeline({engine, steps, frame, deviceId})` path.\n // The runner hydrates `steps` from the orchestrator's attach payload\n // (`pipelines[deviceId]`), so there is no longer an executor-side\n // global \"current pipeline\" for a legacy `runFrame` call to target.\n /**\n * Stateless single-frame execution. Callers (runner, benchmark) pass\n * the complete `engine` + `steps` tree; the executor holds no state\n * about cameras or saved pipelines.\n *\n * `engine` is optional during the migration window to preserve the\n * legacy call shape used by existing benchmark code; once all\n * callers pass it explicitly we make it required.\n *\n * Exactly one of `frame`, `imageBase64`, `referenceImage` must be\n * provided:\n * - `frame`: runtime dispatch path (runner → decoded broker frame).\n * Carries the raw buffer, dimensions, and format; the executor\n * uses it directly without base64 round-tripping.\n * - `imageBase64`: one-shot test path (benchmark ImageTab).\n * - `referenceImage`: named file from the reference-image store.\n */\n runPipeline: method(\n z.object({\n engine: PipelineEngineChoiceSchema.optional(),\n steps: z.array(PipelineStepInputSchema).min(1),\n frame: FrameInputSchema.optional(),\n imageBase64: z.string().optional(),\n /**\n * Binary JPEG bytes — preferred over `imageBase64` on internal\n * hops (hub → forked worker via Moleculer MsgPack) because it\n * skips the 33% base64 overhead + the per-call base64 decode on\n * the detection-pipeline worker. Callers can pass either; exactly\n * one of `frame`/`image`/`imageBase64`/`referenceImage` is required.\n */\n image: z.instanceof(Uint8Array).optional(),\n referenceImage: z.string().optional(),\n deviceId: z.number().optional(),\n sessionId: z.string().optional(),\n }),\n PipelineRunResultBridge,\n { kind: 'mutation' },\n ),\n\n /**\n * Batched run — N raw frames packed into one cap call. The provider\n * routes the batch through `SharedInferencePool.inferBatch`\n * (`MSG_INFER_BATCH = 0x03`) so the IPC framing and JSON response\n * envelope cost is amortised N:1 vs N concurrent `runPipeline`\n * calls. Single root step + uniform model assumed; trees with crop\n * children fall back to sequential execution.\n *\n * Used by `scripts/bench-batch-style.mts` for batch benchmarking —\n * N frames in one call to amortise per-call IPC overhead.\n */\n runPipelineBatch: method(\n z.object({\n engine: PipelineEngineChoiceSchema.optional(),\n steps: z.array(PipelineStepInputSchema).min(1),\n frames: z.array(FrameInputSchema).min(1).max(255),\n deviceId: z.number().optional(),\n sessionId: z.string().optional(),\n }),\n z.object({\n results: z.array(PipelineRunResultBridge).readonly(),\n }),\n { kind: 'mutation' },\n ),\n\n // ── Bench frame cache (Python pool-side) ──────────────────────────\n\n /**\n * Cache a raw frame inside the Python inference pool's memory.\n * Returns a numeric `frameId` that `inferCached` references —\n * subsequent calls send only 5 bytes through the pipe instead of\n * 1.2MB raw data, eliminating the pipe transfer bottleneck.\n */\n cacheFrameInPool: method(\n z.object({\n data: z.instanceof(Uint8Array),\n width: z.number().int().positive(),\n height: z.number().int().positive(),\n format: z.enum(['rgb', 'bgr', 'gray']),\n }),\n z.object({\n frameId: z.number(),\n width: z.number(),\n height: z.number(),\n }),\n { kind: 'mutation' },\n ),\n\n /**\n * Run inference on a previously cached frame. Sends only 5 bytes\n * (model_idx + frameId) through the IPC pipe — eliminates the\n * ~35ms per-call overhead of transferring 1.2MB raw data.\n */\n inferCached: method(\n z.object({\n stepId: z.string(),\n frameId: z.number().int(),\n }),\n z.record(z.string(), z.unknown()),\n { kind: 'mutation' },\n ),\n\n /**\n * Release a cached frame from the Python pool's memory.\n */\n uncacheFrame: method(\n z.object({ frameId: z.number().int() }),\n z.void(),\n { kind: 'mutation' },\n ),\n\n /** Returns the effective pool tuning (resolved from user overrides + backend defaults). */\n getEffectiveTuning: method(\n z.void(),\n z.object({\n batchMode: z.string(),\n windowMs: z.number(),\n maxBatchSize: z.number(),\n concurrency: z.number(),\n }),\n ),\n // ── Engine registry / management (stateless-pipeline spec) ────────\n /**\n * List every EngineFactory currently loaded in this executor's RAM,\n * with the models resident and a coarse \"in use\" marker derived from\n * ongoing inference activity. Used by the Pipeline page Engines tab.\n */\n listLoadedEngines: method(\n z.void(),\n z.array(z.object({\n engineKey: z.string(),\n engine: PipelineEngineChoiceSchema,\n modelsLoaded: z.array(z.string()).readonly(),\n inUseByCameras: z.array(z.number()).readonly(),\n /**\n * Origin of this resident factory.\n * - `runtime` — main camera-serving engine (no idle TTL).\n * - `warm-override` — benchmark/test override held in the warm\n * cache; auto-disposed after the idle TTL.\n */\n kind: z.enum(['runtime', 'warm-override']),\n /** Native pid of the underlying Python pool (null when no pool). */\n poolPid: z.number().nullable(),\n /** ms since this factory was last used (null when not warm-tracked). */\n idleMs: z.number().nullable(),\n /** Idle TTL after which `warm-override` factories self-evict (null when not applicable). */\n idleTtlMs: z.number().nullable(),\n })).readonly(),\n ),\n /** Warm up an engine without running a frame. No-op if already loaded. */\n spinEngine: method(\n z.object({ engine: PipelineEngineChoiceSchema }),\n z.object({ success: z.literal(true) }),\n { kind: 'mutation', auth: 'admin' },\n ),\n /**\n * Unload an engine from RAM. `force:true` unloads even when cameras\n * are actively using it (they re-spin on next frame). Default is\n * gated — returns `{success:false, reason}` when in use.\n */\n killEngine: method(\n z.object({\n engine: PipelineEngineChoiceSchema,\n force: z.boolean().optional(),\n }),\n z.object({ success: z.boolean(), reason: z.string().optional() }),\n { kind: 'mutation', auth: 'admin' },\n ),\n\n // ── Benchmarks & testing ─────────────────────────────────────────\n // Moved to `@camstack/addon-benchmark` as customActions (2026-04-14).\n // The addon exposes runBenchmark / runPipelineTest / listBenchmarkHistory /\n // saveBenchmarkResult / deleteBenchmarkResult / clearBenchmarkHistory via\n // `api.addons.custom.mutate({addonId: 'benchmark', action, input})` and\n // delegates the actual pipeline execution back to this cap's runPipeline.\n\n // ── Reference media ──────────────────────────────────────────────\n listReferenceImages: method(z.void(), z.array(ReferenceImageEntrySchema).readonly()),\n getReferenceImage: method(z.object({ filename: z.string() }), ReferenceImageBodySchema.nullable()),\n getReferenceAudioFiles: method(z.void(), z.array(ReferenceAudioEntrySchema).readonly()),\n getReferenceAudio: method(z.object({ filename: z.string() }), ReferenceAudioBodySchema.nullable()),\n getAudioCapabilities: method(z.void(), AudioCapabilitiesSchema),\n runAudioTest: method(\n z.object({\n addonId: z.string(),\n modelId: z.string(),\n filename: z.string().optional(),\n // Per-step settings (e.g. `enabledClasses`) sourced from the\n // audio-classifier step's `getConfigSchema()`. The provider\n // applies them to the classification result before returning.\n settings: z.record(z.string(), z.unknown()).optional(),\n }),\n AudioTestResultSchema,\n { kind: 'mutation' },\n ),\n\n // ── Detection wiring / metrics (from detection-config) ───────────\n getDetectionConfigSchema: method(z.void(), ConfigUISchemaNullableBridge),\n // NOTE: orchestratorStatus / cameraDetectionStatus removed in the\n // pipeline page redesign — UI reads runner metrics directly via\n // perNodePipeline.getLocalMetrics / getCameraMetrics, which forward\n // to the pipeline-runner cap on the target node.\n //\n // NOTE: listBrokers / brokerStatus used to live here too — removed in\n // Fase H.3. Frontends now call `streamBroker.listBrokers` directly and\n // filter by deviceId client-side (brokerId prefix match). The broker\n // collection lives in the stream-broker capability and there is no\n // reason for pipeline-executor to mirror it.\n //\n // NOTE: subscribeLive / subscribeAudioLive removed in Fase H.4.\n // Consumers use the generic `live.onEvent` / `live.onDeviceEvent`\n // with `{category: 'pipeline.progress' | 'pipeline.inference-result'\n // | 'pipeline.audio-inference-result'}`.\n\n // Per-device pipeline step CRUD (`getDevicePipelineSteps` /\n // `setDevicePipelineSteps` / `clearDevicePipelineSteps`) removed in\n // Phase 4b. The orchestrator owns per-camera pipeline content now\n // (`pipelineOrchestrator.{get,set}CameraPipeline` +\n // `pipelines/<deviceId>` in its addon store). The executor is\n // stateless w.r.t. cameras — it receives `steps` inline on every\n // `runPipeline` call.\n },\n} as const satisfies CapabilityDefinition\n\nexport type IPipelineExecutorProvider = InferProvider<typeof pipelineExecutorCapability>\n\nexport {\n PipelineEngineChoiceSchema,\n PipelineDefaultStepSchema,\n DetectorOutputSchema,\n // Schema types — consumed by pipeline-schema.ts to derive TS types\n PipelineSchemaSchema,\n PipelineAddonSchemaSchema,\n PipelineSlotSchemaSchema,\n PipelineModelOptionSchema,\n AvailableEngineSchema,\n PipelineTemplateSchema,\n PipelineTemplateStepSchema,\n EngineDeviceInfoSchema,\n}\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\n\n/**\n * Zone — pure geometry + identity. NO filtering behaviour.\n *\n * Zones describe **where** in the frame the operator wants to flag\n * something; consumer-owned {@link ZoneRule} arrays describe **how**\n * each pipeline stage uses them. Splitting the two means a single\n * polygon \"Driveway\" can simultaneously back a motion-exclude rule,\n * a detection-include rule on `['car']`, and an occupancy aggregate\n * — without three duplicated polygons.\n *\n * Owned by the orchestrator addon (provider) and mirrored into the\n * `zones` device-state slice on every mutation. Consumers\n * (motion-wasm, pipeline-executor, analytics, admin UI) read either\n * via `api.zones.listZones` (one-shot) or via `dev.state.zones` (live\n * mirror with `onChanged`).\n *\n * Coordinates are normalised fractions of the frame (0–1) so zones\n * survive resolution changes and stream profile switches.\n *\n * `kind` discriminates between full polygons (closed regions used\n * for intrusion / occupancy filters) and tripwires (open 2-point\n * line segments used for cross events). Onboard / firmware-reported\n * zones (Reolink, ONVIF) are out of scope for now — see the deferred\n * task list.\n */\nexport const ZoneKindEnum = z.enum(['polygon', 'tripwire'])\nexport type ZoneKind = z.infer<typeof ZoneKindEnum>\n\n/** Polygon vertex in fraction-of-frame coordinates (0–1). */\nexport const PolygonPointSchema = z.object({\n x: z.number(),\n y: z.number(),\n})\nexport type PolygonPoint = z.infer<typeof PolygonPointSchema>\n\n/** A camera detection zone — pure geometry/identity. */\nexport const ZoneSchema = z.object({\n id: z.string(),\n name: z.string(),\n kind: ZoneKindEnum.default('polygon'),\n /** Polygon vertices, fraction of frame (0–1). */\n polygon: z.array(PolygonPointSchema).readonly(),\n /** Visual color for UI rendering. */\n color: z.string().default('#3b82f6'),\n})\nexport type Zone = z.infer<typeof ZoneSchema>\n\n/**\n * Zones capability — per-camera CRUD over polygon detection zones.\n *\n * Provider lives in `addon-pipeline-orchestrator` (hub-only). Persists\n * to per-device settings and mirrors into the `zones` device-state\n * slice on every mutation, so downstream consumers can subscribe via\n * `dev.state.zones.onChanged`.\n *\n * The cap surface only handles geometry + identity; filtering\n * behaviour (per-class, include/exclude, threshold) lives in the\n * consumer addons' rule arrays — see `ZoneRuleSchema` exported from\n * `capabilities/schemas/zone-rule.js`.\n */\nexport const zonesCapability = {\n name: 'zones',\n scope: 'device',\n mode: 'singleton',\n deviceTypes: [DeviceType.Camera],\n methods: {\n listZones: method(\n z.object({ deviceId: z.number() }),\n z.array(ZoneSchema).readonly(),\n ),\n addZone: method(\n z.object({ deviceId: z.number(), zone: ZoneSchema }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n removeZone: method(\n z.object({ deviceId: z.number(), zoneId: z.string() }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n updateZone: method(\n z.object({ deviceId: z.number(), zone: ZoneSchema }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n },\n /**\n * Runtime-state slice — the live zone catalogue mirrored by the\n * orchestrator on every CRUD mutation. Consumers read via\n * `device.state.zones.value` / `.watch(...)` without round-tripping\n * the cap, and the codegen DeviceProxy auto-wires the reactive\n * handle. Slice shape is `{ zones: Zone[] }` so future extensions\n * (e.g. zone groupings) can sit alongside the polygon list.\n */\n runtimeState: z.object({\n zones: z.array(ZoneSchema).readonly(),\n }),\n} as const satisfies CapabilityDefinition\n\nexport type IZonesProvider = InferProvider<typeof zonesCapability>\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { CameraMetricsSchema, CameraMetricsWithDeviceIdSchema } from './schemas/orchestrator-metrics.js'\nimport { PipelineEngineChoiceSchema, PipelineStepInputSchema } from './pipeline-executor.cap.js'\nimport { MotionRegionSchema } from './motion-detection.cap.js'\nimport { ZoneSchema } from './zones.cap.js'\nimport type { ConfigField } from '../interfaces/config-ui.js'\n\n/**\n * Per-camera tunable ranges + defaults. Single source of truth used\n * by both the Zod data schema (validation + default fallback) and\n * the device settings UI (slider min/max/step). Touch one place and\n * both sides stay aligned.\n */\nconst motionCooldownMsField = { min: 0, max: 60_000, default: 30_000, step: 500 } as const\nconst motionFpsField = { min: 1, max: 30, default: 4, step: 1 } as const\nconst detectionFpsField = { min: 1, max: 30, default: 10, step: 1 } as const\n\n/**\n * Source enum for motion signals fed to the runner. Extensible — add\n * new variants here when new motion-trigger paths are wired in\n * (`wasm-cross-camera`, `event-bus-relay`, etc.). The runner uses\n * the variant for diagnostics + to route the cap-state event payload\n * (analyzer attaches detected `regions[]`; onboard does not — the\n * camera typically only reports a binary signal plus an optional\n * channel/AI class which lives in dedicated event channels).\n */\nexport const MotionSourceEnum = z.enum(['onboard', 'analyzer'])\nexport type MotionSource = z.infer<typeof MotionSourceEnum>\n\n/**\n * List of motion sources active on a camera. Empty array is valid:\n * \"no source\" — happens for battery cams without firmware motion when\n * the operator hasn't opted into the SW analyzer (would hold the\n * substream open continuously and defeat the sleep cycle). The runner\n * accepts the empty list as \"no motion-driven phase transitions\" and\n * relies on the operator-set `detectionMode` to drive activation\n * (`'always-on'`) — `'on-motion'` with no source effectively pins the\n * phase to `'watching'`, which is the desired battery-cam-without-\n * firmware behaviour.\n *\n * Single source of truth for the array shape — every consumer\n * (orchestrator, runner, settings UI, dispatch) imports from here.\n */\nexport const MotionSourcesSchema = z.array(MotionSourceEnum)\nexport type MotionSources = z.infer<typeof MotionSourcesSchema>\n\n/**\n * Input shape for `pipeline-runner.reportMotion` cap method. Exported\n * so cap-side consumers (the orchestrator forward, the runner addon's\n * cap implementation, tests) can reuse the type instead of redeclaring\n * the field set.\n */\nexport const ReportMotionInputSchema = z.object({\n deviceId: z.number(),\n detected: z.boolean(),\n source: MotionSourceEnum.default('analyzer'),\n regions: z.array(MotionRegionSchema).readonly().optional(),\n})\nexport type ReportMotionInput = z.infer<typeof ReportMotionInputSchema>\n\n/**\n * Camera assignment payload sent by `addon-pipeline-orchestrator` to a\n * specific runner instance via `attachCamera`. Carries everything the\n * runner needs to subscribe to the local broker and execute inference.\n *\n * Stateless-pipeline model: the full pipeline content (`engine`, `steps`,\n * optional `audio`) travels with the attach payload. The runner keeps it\n * in RAM for the lifetime of the attach — on rebalance, edit, or\n * restart the orchestrator re-sends the latest snapshot.\n *\n * `engine`/`steps`/`audio` are optional during the additive migration\n * window; once orchestrator + UI are migrated they become required.\n */\nconst RunnerCameraConfigSchema = z.object({\n deviceId: z.number(),\n /**\n * Operator-facing scheduling mode for the SW object detection\n * pipeline. Replaces the legacy 2-state `priority` toggle.\n *\n * - `'disabled'` — runner never subscribes to the substream for\n * detection; phase stays idle. Bindings stay\n * bound; this is the runtime-level off switch.\n * - `'always-on'` — phase starts in `'active'` and never falls\n * back to `'watching'`.\n * - `'on-motion'` — phase starts in `'watching'`; transitions to\n * `'active'` when a motion source fires; falls\n * back to `'watching'` after `motionCooldownMs`.\n */\n detectionMode: z.enum(['disabled', 'always-on', 'on-motion']).default('on-motion'),\n /** Audio scheduling mode — same values as `detectionMode`. The\n * audio-analyzer addon reads this to decide whether to subscribe\n * to the audio decoded stream. */\n audioMode: z.enum(['disabled', 'always-on', 'on-motion']).default('always-on'),\n motionCooldownMs: z.number().min(motionCooldownMsField.min).default(motionCooldownMsField.default),\n motionFps: z.number().min(motionFpsField.min).max(motionFpsField.max).default(motionFpsField.default),\n detectionFps: z.number().min(detectionFpsField.min).max(detectionFpsField.max).default(detectionFpsField.default),\n motionStreamId: z.string(),\n detectionStreamId: z.string(),\n /**\n * Motion sources that can activate the pipeline. At least one must\n * be present. Multiple sources OR-ed: any one firing arms the\n * cooldown timer and transitions watching → active. The same\n * `motionCooldownMs` applies to whichever source(s) fire — the\n * timer rearms on every `reportMotion(true)` and expires after the\n * window, returning the runner to `watching`.\n *\n * - `analyzer`: ML/frame-diff motion detection (motion-wasm or other\n * analyzer providers) running on decoded frames in this runner.\n * - `onboard`: camera-native motion pushes (Reolink Baichuan, ONVIF\n * analytics, Frigate motion). The provider emits ProviderMotion\n * events; the orchestrator forwards to `reportMotion`.\n */\n motionSources: MotionSourcesSchema.default(['analyzer']),\n pipelineEnabled: z.boolean().default(true),\n // ── Stateless-pipeline: content carried with the attach ───────────\n /** Engine choice for video steps (runtime+backend+format). */\n engine: PipelineEngineChoiceSchema.optional(),\n /** Ordered tree of video steps. Absent → runner skips video detection. */\n steps: z.array(PipelineStepInputSchema).readonly().optional(),\n /** Audio classification branch. `enabled:false` disables, null skips. */\n audio: z.object({\n engine: PipelineEngineChoiceSchema,\n modelId: z.string(),\n enabled: z.boolean(),\n }).nullable().optional(),\n /**\n * Per-camera detection zones (user + onboard) snapshot at dispatch\n * time. Forwarded so motion-wasm + pipeline-executor running on the\n * runner can apply include/exclude/monitor logic without an extra\n * round-trip to the hub. The orchestrator re-dispatches the camera\n * whenever its `zones` device-state slice changes, so the runner's\n * copy stays in sync. Empty array → no zone filtering.\n */\n zones: z.array(ZoneSchema).readonly().default([]),\n /**\n * When true (default) and the camera's `motionSources` contains only\n * `'onboard'`, the runner dynamically opens the same WASM frame-diff\n * motion-frames subscription on each `MotionOnMotionChanged\n * source:'onboard'` event and tears it down after `motionCooldownMs`.\n * This causes `runMotionAnalysis` to emit `MotionZonesRaw` /\n * `MotionAnalysis` during active-motion windows without the\n * substream being held open continuously.\n *\n * Set to `false` to disable the dynamic analyzer for this camera\n * (e.g. very low-bandwidth links where the extra substream is\n * undesirable). Has no effect when `motionSources` already includes\n * `'analyzer'` — the analyzer runs continuously in that case and\n * this gate is bypassed.\n */\n onboardMotionDrivesAnalyzer: z.boolean().default(true),\n})\n\n/**\n * Per-device settings UI fields the runner cap owns. Co-located with\n * the Zod data schema so a single change to defaults / ranges /\n * options propagates to both the wire contract AND the rendered UI.\n *\n * Consumers spread this into their own ConfigUISchema sections\n * (e.g. orchestrator's deviceSettingsSchema) instead of redeclaring\n * the fields. The ranges are read from the `*Field` constants above\n * so values stay in sync with `RunnerCameraConfigSchema`.\n *\n * Fields NOT included here are intentional — they're either internal\n * wire (motionStreamId, detectionStreamId) or live in a different\n * config surface (priority, motionStreamProfile/detectionStreamProfile\n * — the orchestrator transforms them into stream IDs before dispatch).\n */\nexport const RunnerCameraDeviceUIFields: readonly ConfigField[] = [\n {\n key: 'motionSources',\n type: 'multiselect',\n label: 'Motion Sources',\n default: ['analyzer'],\n options: [\n { value: 'analyzer', label: 'Frame-diff Analyzer (motion addon)' },\n { value: 'onboard', label: 'Camera Onboard Sensor' },\n ],\n },\n // Analyzer-only knobs — gated on `motionSources` containing the\n // `analyzer` (frame-diff) source. When the operator picks\n // `onboard`-only (camera-native VMD), running an analyzer pipeline\n // would burn CPU for no signal, so we hide the FPS / cooldown /\n // stream-profile tuning entirely. The dependent section header in\n // the orchestrator reads \"Frame-diff Analyzer\" → these fields\n // disappear together when the source isn't selected.\n {\n key: 'motionFps',\n type: 'slider',\n label: 'Motion FPS (analyzer)',\n min: motionFpsField.min,\n max: motionFpsField.max,\n step: motionFpsField.step,\n default: motionFpsField.default,\n showValue: true,\n unit: 'fps',\n showWhen: { field: 'motionSources', includes: 'analyzer' },\n },\n {\n key: 'detectionFps',\n type: 'slider',\n label: 'Detection FPS',\n min: detectionFpsField.min,\n max: detectionFpsField.max,\n step: detectionFpsField.step,\n default: detectionFpsField.default,\n showValue: true,\n unit: 'fps',\n },\n // Motion cooldown applies to BOTH analyzer and onboard sources —\n // every reportMotion(true) re-arms the cooldown regardless of the\n // emitting source, so the operator must be able to tune it for\n // onboard-only cameras too. Without this the field silently\n // disappeared when the user picked \"Camera Onboard Sensor\" only.\n {\n key: 'motionCooldownMs',\n type: 'slider',\n label: 'Motion Cooldown',\n description: 'Time without a fresh motion event before the active phase ends. Applies to all motion sources — every motion event re-arms the timer.',\n min: motionCooldownMsField.min,\n max: motionCooldownMsField.max,\n step: motionCooldownMsField.step,\n default: motionCooldownMsField.default,\n showValue: true,\n unit: 's',\n displayScale: 1000,\n },\n // Only meaningful for onboard-only cameras — when `motionSources`\n // contains `'analyzer'` the analyzer runs continuously already.\n {\n key: 'onboardMotionDrivesAnalyzer',\n type: 'boolean',\n label: 'Run motion analyzer on onboard motion',\n description: 'When onboard motion is detected, temporarily start the frame-diff analyzer to emit zone results. Stops after the motion cooldown window.',\n default: true,\n showWhen: { field: 'motionSources', includes: 'onboard' },\n },\n] as const\n\n/**\n * Runtime load summary returned by `getLocalLoad`. Used by the orchestrator's\n * load-balancing levels (L2 capacity-based, L3 hardware-aware) to decide\n * which agent should receive a new camera assignment.\n */\nconst RunnerLocalLoadSchema = z.object({\n /** Moleculer node id of this runner instance. */\n nodeId: z.string(),\n /** Total cameras currently attached (regardless of phase). */\n attachedCameras: z.number(),\n /** Cameras currently in `active` phase (running detection inference). */\n activeCameras: z.number(),\n /** Average inference FPS across all attached cameras. */\n avgInferenceFps: z.number(),\n /** Average inference latency in ms across all attached cameras. */\n avgInferenceTimeMs: z.number(),\n /** Total queue depth across motion + detection queues. */\n queueDepthTotal: z.number(),\n /** Hardware capability flags reported by this node. */\n hardware: z.object({\n hasGpu: z.boolean(),\n inferenceBackend: z.string().optional(),\n cpuCores: z.number().optional(),\n }),\n})\n\n/**\n * Aggregate runtime metrics for the runner's whole local pool. Mirrors the\n * legacy `OrchestratorMetricsSchema` shape so existing dashboards keep\n * working unchanged when they switch to reading from the runner cap.\n */\nconst RunnerLocalMetricsSchema = z.object({\n nodeId: z.string(),\n activeCameras: z.number(),\n throttledCameras: z.number(),\n avgInferenceTimeMs: z.number(),\n queueDepth: z.number(),\n})\n\n/**\n * Pipeline Runner capability — runtime detection workhorse.\n *\n * One instance per node. Receives camera assignments from\n * `addon-pipeline-orchestrator`, subscribes to the local stream-broker for\n * decoded frames, drains motion + detection queues, calls the local\n * `motion-detection` and `pipeline-executor` capabilities, and emits typed\n * `pipeline.inference-result` and `detection.motion-analysis` events on\n * the bus.\n *\n * Distinct from `pipeline-orchestrator` (the hub-side load balancer) — the\n * runner has zero knowledge of other agents, no global state, and never\n * makes assignment decisions itself.\n */\nexport const pipelineRunnerCapability = {\n name: 'pipeline-runner',\n scope: 'system',\n mode: 'singleton',\n methods: {\n // ── Camera lifecycle (called by orchestrator) ────────────────────\n /** Attach a camera to this runner. Subscribes to local broker. */\n attachCamera: method(RunnerCameraConfigSchema, z.object({ success: z.literal(true) }), { kind: 'mutation' }),\n /** Detach a camera. Unsubscribes from local broker, clears queues. */\n detachCamera: method(z.object({ deviceId: z.number() }), z.object({ success: z.literal(true) }), { kind: 'mutation' }),\n /**\n * Report an external motion event for a camera. Drives the runner's\n * phase machine: every `detected: true` clears + rearms the\n * cooldown timer (`motionCooldownMs`); when the timer expires the\n * camera returns to `watching`. `detected: false` is a no-op —\n * onboard sources never send an explicit clear, the timer is the\n * single closure path.\n *\n * `source` discriminates which motion path triggered the event so\n * the runner can attach the right metadata to the cap-state event\n * (analyzer carries `regions[]`, onboard does not). `regions` is\n * populated only for `source: 'analyzer'` — the analyzer's\n * frame-diff result. Always-on cameras silently ignore\n * reportMotion calls.\n */\n reportMotion: method(\n ReportMotionInputSchema,\n z.object({ success: z.literal(true) }),\n { kind: 'mutation' },\n ),\n\n // ── Observability (called by orchestrator + dashboards) ──────────\n /** Return load summary used by the orchestrator's load balancer. */\n getLocalLoad: method(z.void(), RunnerLocalLoadSchema),\n /** Return aggregate runtime metrics for this runner instance. */\n getLocalMetrics: method(z.void(), RunnerLocalMetricsSchema),\n /** Per-camera metrics for cameras attached to this runner. */\n getCameraMetrics: method(z.object({ deviceId: z.number() }), CameraMetricsSchema.nullable()),\n /** All per-camera metrics in one round-trip. */\n getAllCameraMetrics: method(z.void(), z.array(CameraMetricsWithDeviceIdSchema).readonly()),\n /** List the deviceIds currently attached to this runner. */\n getLocalCameras: method(z.void(), z.array(z.number()).readonly()),\n\n // NOTE: Phase 6 (settings redesign) removed `getTuning` / `setTuning`.\n // The four tuning fields are now exposed via the addon-level settings\n // API (`pipeline-runner.getAddonSettings / updateAddonSettings`) and\n // rendered in the admin UI via `NodeAddonsSettingsPanel` instead of\n // the dedicated `NodeTuningTab` that used to call these cap methods.\n },\n} as const satisfies CapabilityDefinition\n\nexport type IPipelineRunnerProvider = InferProvider<typeof pipelineRunnerCapability>\n\nexport { RunnerCameraConfigSchema, RunnerLocalLoadSchema, RunnerLocalMetricsSchema }\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\nimport { MotionRegionSchema } from './motion-detection.cap.js'\nimport { MotionSourceEnum } from './pipeline-runner.cap.js'\n\n/**\n * Hardware / firmware motion sensor cap — binary detected state plus\n * a timestamp of the last observation. Distinct from\n * `motion-detection.cap.ts` which owns the LOCAL ML motion pipeline;\n * `motion` is the lightweight readout from on-camera motion (Reolink\n * `GetMdState`, Baichuan push `type: motion`, ONVIF analytics).\n *\n * Native-motion providers also fan out to `detection.camera-native`\n * with `source: 'onboard'` so cross-cutting system services\n * (alert-center, advanced-notifier) can subscribe once and receive\n * motion from every camera.\n */\nexport const MotionStatusSchema = z.object({\n detected: z.boolean(),\n /** Ms epoch of the last detected-true observation. Null if never detected. */\n lastDetectedAt: z.number().nullable(),\n /**\n * Ms after which `detected` auto-reverts to false if no fresh push\n * arrives. Null means the provider leaves detected state until a\n * native \"clear\" event.\n */\n autoClearAfterMs: z.number().nullable(),\n})\n\nexport type MotionStatus = z.infer<typeof MotionStatusSchema>\n\n/**\n * Payload of `motion.onMotionChanged` event + the corresponding bus\n * event `EventCategory.MotionOnMotionChanged`. Single source of truth\n * — both the cap event surface and the bus payload type alias to this\n * schema.\n */\nexport const MotionOnMotionChangedDataSchema = z.object({\n deviceId: z.number(),\n detected: z.boolean(),\n timestamp: z.number(),\n source: MotionSourceEnum,\n regions: z.array(MotionRegionSchema).readonly().optional(),\n})\nexport type MotionOnMotionChangedData = z.infer<typeof MotionOnMotionChangedDataSchema>\n\nexport const motionCapability = {\n name: 'motion',\n scope: 'device',\n mode: 'singleton',\n deviceTypes: [DeviceType.Camera, DeviceType.Sensor],\n methods: {\n /**\n * Pull the current motion state synchronously. Convenience shortcut\n * for consumers that don't need the full status object; equivalent\n * to `getStatus()?.detected ?? false`. Will likely be folded into\n * `getStatus` once the auto-injected status surface lands in every\n * consumer.\n */\n isDetected: method(\n z.object({ deviceId: z.number() }),\n z.boolean(),\n ),\n },\n events: {\n /**\n * Fires every time the runner transitions a camera between\n * `watching` and `active` phases. `source` carries which motion\n * path drove the transition; `regions` is populated only for\n * `source: 'analyzer'` (frame-diff regions from the ML motion\n * detector) — onboard sources don't carry per-frame regions\n * here (camera-provided zones / AI metadata live in dedicated\n * channels: `detection.camera-native`, future zone capability).\n *\n * Consumers that want all motion pushes (even with `detected`\n * unchanged) should subscribe to the status subscription via\n * `device-manager.subscribeDeviceStatusAggregate` instead.\n */\n onMotionChanged: { data: MotionOnMotionChangedDataSchema },\n },\n status: {\n schema: MotionStatusSchema,\n kind: 'push',\n },\n /**\n * Runtime-state slice — the last observed motion snapshot, mirrored\n * by the kernel and readable cross-process via\n * `device.state.motion.value`. Reads never invoke the provider, so\n * UIs and other addons can poll the cached state safely.\n */\n runtimeState: MotionStatusSchema,\n} as const satisfies CapabilityDefinition\n\nexport type IMotionProvider = InferProvider<typeof motionCapability>\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\n\n/**\n * Motion-trigger toggle for accessory devices.\n *\n * \"Motion trigger\" means: when the parent camera detects motion, the\n * accessory activates automatically. The cap exposes a single boolean\n * — `enabled` — that drivers map to the vendor-specific firmware\n * action (Reolink: `setSirenOnMotion`, `setFloodlightOnMotion`; ONVIF\n * relay: schedule binding; …).\n *\n * The accessory still has its own `switch` cap for direct on/off; this\n * cap is independent. Toggling motion-trigger on does NOT necessarily\n * toggle the switch on — it just instructs the firmware to flip the\n * switch when motion fires.\n *\n * Driver-specific knobs (motion duration window, brightness while\n * triggered, schedule windows) live in the device's\n * `getSettingsUISchema()` instead of bloating this cap — same\n * principle as `switch` and `brightness` keeping their surface\n * minimal.\n */\nexport const MotionTriggerStatusSchema = z.object({\n enabled: z.boolean(),\n /** Ms epoch of the last operator-driven change. */\n lastChangedAt: z.number(),\n})\n\nexport type MotionTriggerStatus = z.infer<typeof MotionTriggerStatusSchema>\n\n/**\n * Persistent slice mirrored across restarts. The provider writes here\n * on every successful firmware fetch / setMotionTrigger push; the cap\n * router and admin-ui hero read straight from this snapshot via\n * `device.state.motionTrigger.value` instead of re-issuing a firmware\n * round-trip on every UI mount. `lastFetchedAt` lets the framework\n * helper (`createRuntimeStateBridge`) stale-check before deciding\n * whether to refresh from the camera.\n */\nexport const MotionTriggerRuntimeStateSchema = MotionTriggerStatusSchema.extend({\n /** Ms epoch of the last successful camera fetch (0 = never). */\n lastFetchedAt: z.number(),\n})\n\nexport type MotionTriggerRuntimeState = z.infer<typeof MotionTriggerRuntimeStateSchema>\n\nexport const motionTriggerCapability = {\n name: 'motion-trigger',\n scope: 'device',\n deviceNative: true,\n mode: 'singleton',\n deviceTypes: [DeviceType.Light, DeviceType.Siren, DeviceType.Switch],\n methods: {\n setMotionTrigger: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n enabled: z.boolean(),\n }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n },\n events: {\n onMotionTriggerChanged: { data: z.object({\n deviceId: z.number(),\n enabled: z.boolean(),\n lastChangedAt: z.number(),\n })},\n },\n status: {\n schema: MotionTriggerStatusSchema,\n kind: 'command-driven',\n },\n runtimeState: MotionTriggerRuntimeStateSchema,\n} as const satisfies CapabilityDefinition\n\nexport type IMotionTriggerProvider = InferProvider<typeof motionTriggerCapability>\n","import { z } from 'zod'\n\n/**\n * Shared geometry vocabulary for on-frame shape caps — privacy-mask,\n * motion-zones, and the detection zones/lines editor all speak this one\n * language so a single drawing-plane editor and the providers stay\n * decoupled from each cap's storage.\n *\n * All coordinates are normalized 0..1 of the camera frame (top-left\n * origin). Each cap composes the SUBSET of shape kinds it supports and\n * advertises it via `supportedShapes` in its `getOptions`.\n */\n\n/** A normalized 0..1 point (top-left origin). */\nexport const MaskPointSchema = z.object({\n x: z.number(),\n y: z.number(),\n})\n\n/** Axis-aligned rectangle (normalized 0..1). */\nexport const MaskRectShapeSchema = z.object({\n kind: z.literal('rect'),\n x: z.number(),\n y: z.number(),\n width: z.number(),\n height: z.number(),\n})\n\n/** Free polygon — an ordered list of normalized vertices (≥3). */\nexport const MaskPolygonShapeSchema = z.object({\n kind: z.literal('polygon'),\n points: z.array(MaskPointSchema),\n})\n\n/** Boolean cell grid — row-major, length === gridWidth*gridHeight. */\nexport const MaskGridShapeSchema = z.object({\n kind: z.literal('grid'),\n gridWidth: z.number(),\n gridHeight: z.number(),\n cells: z.array(z.boolean()),\n})\n\n/** Directed line / tripwire — an ordered list of normalized points (≥2). */\nexport const MaskLineShapeSchema = z.object({\n kind: z.literal('line'),\n points: z.array(MaskPointSchema),\n})\n\n/** The full shape vocabulary. Caps compose the subset they support. */\nexport const MaskShapeSchema = z.discriminatedUnion('kind', [\n MaskRectShapeSchema,\n MaskPolygonShapeSchema,\n MaskGridShapeSchema,\n MaskLineShapeSchema,\n])\n\n/** Every shape-kind discriminant, for `supportedShapes` advertisement. */\nexport const MaskShapeKindSchema = z.enum(['rect', 'polygon', 'grid', 'line'])\n\n/** Polygon vertex bounds when a cap supports 'polygon' (e.g. Hikvision {min:4,max:4}). */\nexport const MaskPolygonVerticesSchema = z.object({\n min: z.number(),\n max: z.number(),\n})\n\n/** Grid dimensions when a cap supports 'grid'. */\nexport const MaskGridDimsSchema = z.object({\n width: z.number(),\n height: z.number(),\n})\n\nexport type MaskPoint = z.infer<typeof MaskPointSchema>\nexport type MaskRectShape = z.infer<typeof MaskRectShapeSchema>\nexport type MaskPolygonShape = z.infer<typeof MaskPolygonShapeSchema>\nexport type MaskGridShape = z.infer<typeof MaskGridShapeSchema>\nexport type MaskLineShape = z.infer<typeof MaskLineShapeSchema>\nexport type MaskShape = z.infer<typeof MaskShapeSchema>\nexport type MaskShapeKind = z.infer<typeof MaskShapeKindSchema>\nexport type MaskPolygonVertices = z.infer<typeof MaskPolygonVerticesSchema>\nexport type MaskGridDims = z.infer<typeof MaskGridDimsSchema>\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferNativeProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\nimport { MaskGridShapeSchema, MaskShapeKindSchema, MaskGridDimsSchema } from './mask-shape.js'\n\n/**\n * Motion-zones share the same MaskShape vocabulary as privacy-mask — the\n * on-camera motion-detection mask is a single `grid` region (a row-major\n * boolean cell lattice the camera's onboard VMD evaluates). Composing it as\n * a region keeps one drawing-plane model across all geometry caps.\n */\n\n/** A motion-zone region — exactly one boolean cell grid today. */\nexport const MotionZoneRegionSchema = z.object({\n id: z.number(),\n enabled: z.boolean(),\n shape: MaskGridShapeSchema,\n})\n\n/** Current on-camera motion-detection state — master enable + sensitivity +\n * the grid region(s). */\nexport const MotionZoneStatusSchema = z.object({\n enabled: z.boolean(),\n sensitivity: z.number(),\n /** Grid region(s). Today exactly one `grid` shape. */\n regions: z.array(MotionZoneRegionSchema),\n lastFetchedAt: z.number(),\n})\n\n/** Per-camera availability — grid dims are fixed per camera model; the UI\n * sizes its editor from `grid`. */\nexport const MotionZoneOptionsSchema = z.object({\n maxRegions: z.number(),\n supportedShapes: z.array(MaskShapeKindSchema),\n grid: MaskGridDimsSchema,\n sensitivity: z.object({ min: z.number(), max: z.number(), step: z.number() }),\n})\n\n/** Partial change — every field optional. */\nexport const MotionZonePatchSchema = z.object({\n enabled: z.boolean().optional(),\n sensitivity: z.number().optional(),\n regions: z.array(MotionZoneRegionSchema).optional(),\n})\n\nexport type MotionZoneRegion = z.infer<typeof MotionZoneRegionSchema>\nexport type MotionZoneStatus = z.infer<typeof MotionZoneStatusSchema>\nexport type MotionZoneOptions = z.infer<typeof MotionZoneOptionsSchema>\nexport type MotionZonePatch = z.infer<typeof MotionZonePatchSchema>\n\nexport const motionZonesCapability = {\n name: 'motion-zones',\n scope: 'device',\n deviceNative: true,\n mode: 'singleton',\n deviceTypes: [DeviceType.Camera],\n deviceConfig: {\n ui: { kind: 'widget', widgetId: 'host/motion-zones-grid', tab: 'motion', label: 'Motion Zones' },\n },\n methods: {\n getOptions: method(z.object({ deviceId: z.number() }), MotionZoneOptionsSchema),\n setZone: method(\n z.object({ deviceId: z.number(), patch: MotionZonePatchSchema }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n },\n status: { schema: MotionZoneStatusSchema, kind: 'poll' },\n runtimeState: MotionZoneStatusSchema,\n} as const satisfies CapabilityDefinition\n\nexport type IMotionZonesProvider = InferNativeProvider<typeof motionZonesCapability>\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\n\n/**\n * On-camera AI object detection cap. Surfaces per-device the classes\n * the firmware can detect and the last-seen instance of each. The\n * provider also fan-outs these to the global `detection.camera-native`\n * event bus with `source: 'onboard'` so cross-cutting system services\n * (alert-center, advanced-notifier, recording-engine) can subscribe\n * once and receive events from every camera.\n *\n * Distinct from `motion-detection` (ML pipeline) and `motion` (hardware\n * PIR or firmware motion pulse): this cap is specifically the AI\n * classifier output coming FROM the camera, not the local pipeline.\n */\nexport const NativeObjectClassEnum = z.enum([\n 'person', 'vehicle', 'animal', 'face', 'package', 'other',\n])\n\nexport type NativeObjectClass = z.infer<typeof NativeObjectClassEnum>\n\nexport const NativeDetectionSchema = z.object({\n class: NativeObjectClassEnum,\n timestamp: z.number(),\n /** Firmware-provided confidence [0..1]. Reolink pushes don't carry it → undefined. */\n confidence: z.number().min(0).max(1).optional(),\n})\n\nexport type NativeDetection = z.infer<typeof NativeDetectionSchema>\n\nexport const NativeObjectDetectionStatusSchema = z.object({\n /**\n * Last observed instance per class. Missing entries mean the class\n * is supported but nothing has been seen since the provider started.\n *\n * MUST be a partial record: providers seed an empty `{}` on cold-start\n * and write one class at a time as detections arrive. In Zod 4\n * `z.record(enum, …)` is EXHAUSTIVE (requires every enum key), so a\n * partial write throws \"expected object, received undefined\" for every\n * unseen class. `z.partialRecord` keeps the enum-key narrowing while\n * allowing the sparse shape the providers actually write.\n */\n lastByClass: z.partialRecord(NativeObjectClassEnum, NativeDetectionSchema.nullable()),\n /** Classes the firmware is capable of detecting — enumerated at device register. */\n supportedClasses: z.array(NativeObjectClassEnum).readonly(),\n /**\n * Whether forwarding of onboard AI detections is enabled for this device.\n * Default true (on cold-start) — detections flow unconditionally before\n * the toggle is saved, so defaulting true preserves existing behaviour.\n */\n enabled: z.boolean(),\n})\n\nexport type NativeObjectDetectionStatus = z.infer<typeof NativeObjectDetectionStatusSchema>\n\nexport const NativeObjectDetectionRuntimeStateSchema = NativeObjectDetectionStatusSchema.extend({\n /** Required by createRuntimeStateBridge — epoch ms of last refresh. */\n lastFetchedAt: z.number(),\n})\n\nexport type NativeObjectDetectionRuntimeState = z.infer<typeof NativeObjectDetectionRuntimeStateSchema>\n\nexport const nativeObjectDetectionCapability = {\n name: 'native-object-detection',\n scope: 'device',\n deviceNative: true,\n mode: 'singleton',\n deviceTypes: [DeviceType.Camera],\n methods: {\n setEnabled: method(\n z.object({ deviceId: z.number(), enabled: z.boolean() }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n },\n events: {\n onDetected: { data: z.object({\n deviceId: z.number(),\n detection: NativeDetectionSchema,\n })},\n },\n status: {\n schema: NativeObjectDetectionStatusSchema,\n kind: 'push',\n },\n runtimeState: NativeObjectDetectionRuntimeStateSchema,\n} as const satisfies CapabilityDefinition\n\nexport type INativeObjectDetectionProvider = InferProvider<typeof nativeObjectDetectionCapability>\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\n\n/**\n * Notification delivery cap. Models HA `notify.<service>` plus future\n * native targets (Telegram / Discord / ntfy / SMTP, …). Designed at\n * the same structural level as a camera cap: rich multi-method\n * surface, full status diagnostics, explicit `supports` matrix so\n * the UI gates compose-form fields without probing the provider.\n *\n * One Notifier device per delivery endpoint — HA's `notify.mobile_app_*`\n * (one per phone), `notify.telegram_*` (one per chat target), etc.\n * The DeviceRole sub-role (MobilePushNotifier / MessagingNotifier /\n * EmailNotifier / GenericNotifier) discriminates the rendering style\n * of the compose form.\n *\n * Sub-feature support (image / priority / data / actions / multi-\n * recipient) is signaled by:\n * - the device's `DeviceFeature` bits — fast scalar check for list\n * filters and grid icons (DeviceFeature.NotifierImage etc.); AND\n * - the slice's `supports` block — authoritative read after device\n * detail is opened.\n */\n\nconst NotifierPrioritySchema = z.enum(['min', 'low', 'normal', 'high'])\nexport type NotifierPriority = z.infer<typeof NotifierPrioritySchema>\n\nconst NotifierActionSchema = z.object({\n /** Stable id used in the callback when the user taps the button. */\n id: z.string().min(1),\n /** User-visible button label. */\n title: z.string().min(1),\n /** Optional deep-link URI invoked on tap (rich notifiers only). */\n uri: z.url().optional(),\n /** Optional flag — when true, the action is destructive and the\n * client should render the button in a warning style. */\n destructive: z.boolean().optional(),\n})\nexport type NotifierAction = z.infer<typeof NotifierActionSchema>\n\nconst NotifierSupportsSchema = z.object({\n /** Inline / URL image attachment. Pair with `DeviceFeature.NotifierImage`. */\n image: z.boolean(),\n /** Priority hint. Pair with `DeviceFeature.NotifierPriority`. */\n priority: z.boolean(),\n /** Free-form platform-specific data block.\n * Pair with `DeviceFeature.NotifierData`. */\n data: z.boolean(),\n /** Interactive action buttons. Pair with `DeviceFeature.NotifierActions`. */\n actions: z.boolean(),\n /** Per-call recipient targeting (multi-user notifiers).\n * Pair with `DeviceFeature.NotifierRecipients`. */\n recipients: z.boolean(),\n})\nexport type NotifierSupports = z.infer<typeof NotifierSupportsSchema>\n\nexport const NotifierStatusSchema = z.object({\n /** Ms epoch of the most recent successful send. 0 if none yet. */\n lastSentAt: z.number(),\n /** Failure description from the most recent send attempt. Null on\n * success or when nothing has been sent yet. */\n lastError: z.string().nullable(),\n /** Number of deliveries currently buffered server-side (rate-limited\n * notifiers may queue). 0 when the provider sends synchronously. */\n queueDepth: z.number().int().nonnegative(),\n /** Per-feature capability matrix — authoritative source for the\n * compose-form field gating. */\n supports: NotifierSupportsSchema,\n})\n\nexport type NotifierStatus = z.infer<typeof NotifierStatusSchema>\n\nconst NotifierSendInputSchema = z.object({\n deviceId: z.number().int().nonnegative(),\n /** Optional title — many platforms render it bolder than the body. */\n title: z.string().optional(),\n /** Required message body. */\n body: z.string().min(1),\n /** Optional image URL or inline data URI (`data:image/...;base64,...`). */\n image: z.string().optional(),\n /** Priority hint — providers without priority support ignore the field. */\n priority: NotifierPrioritySchema.optional(),\n /** Channel / topic / tag the notifier should route through (Android\n * notification channel, Telegram chat id, ntfy topic, …). */\n channel: z.string().optional(),\n /** Optional list of recipient ids (multi-user notifiers). Empty /\n * omitted = the device's default recipient. */\n recipients: z.array(z.string()).optional(),\n /** Optional interactive action buttons. */\n actions: z.array(NotifierActionSchema).optional(),\n /** Free-form platform-specific payload — passed through to the\n * upstream service untouched. */\n data: z.record(z.string(), z.unknown()).optional(),\n})\n\nconst NotifierSendResultSchema = z.object({\n /** Provider-assigned id for the delivery. Used for `cancel`. */\n notificationId: z.string(),\n /** Ms epoch when the notifier accepted the send (not when delivered). */\n acceptedAt: z.number(),\n})\n\nexport type NotifierSendInput = z.infer<typeof NotifierSendInputSchema>\nexport type NotifierSendResult = z.infer<typeof NotifierSendResultSchema>\n\nexport const notifierCapability = {\n name: 'notifier',\n scope: 'device',\n deviceNative: true,\n mode: 'singleton',\n deviceTypes: [DeviceType.Notifier],\n methods: {\n send: method(\n NotifierSendInputSchema,\n NotifierSendResultSchema,\n { kind: 'mutation', auth: 'admin' },\n ),\n cancel: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n notificationId: z.string().min(1),\n }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n },\n events: {\n /**\n * Emitted after every send attempt — success or failure. Subscribers\n * (admin UI history pane, automation engines, retry workers) react\n * without polling the provider's `lastSentAt`.\n */\n onSent: { data: z.object({\n deviceId: z.number(),\n notificationId: z.string(),\n success: z.boolean(),\n error: z.string().nullable(),\n acceptedAt: z.number(),\n })},\n },\n status: {\n schema: NotifierStatusSchema,\n kind: 'command-driven',\n },\n /**\n * Runtime-state slice — diagnostics + supports matrix. UI compose\n * form reads `supports` to gate optional fields; history pane reads\n * `lastSentAt` / `lastError` / `queueDepth`.\n */\n runtimeState: NotifierStatusSchema,\n} as const satisfies CapabilityDefinition\n\nexport type INotifierProvider = InferProvider<typeof notifierCapability>\n","import { z } from 'zod'\nimport { type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\n\n/**\n * Generic numeric sensor — last-resort fallback when no typed numeric\n * cap fits (HA `sensor` whose `device_class` we don't have a typed cap\n * for: water flow, distance, weight, frequency, signal strength, …).\n *\n * The `unit` and `precision` fields carry the live display metadata that\n * the upstream source provides with each state push (HA\n * `attributes.unit_of_measurement` / `attributes.suggested_display_precision`).\n * The UI reads them directly from the slice — they are the single source\n * of truth for generic numeric rendering and do NOT live on `sourceInfo`.\n *\n * Prefer the typed alternatives (`temperature-sensor`, `humidity-sensor`,\n * `ambient-light-sensor`, `pressure-sensor`, `power-meter`,\n * `air-quality-sensor`, `battery`) when the metric matches — export\n * adapters render those with the right service / category. Generic\n * numeric values land here.\n */\nexport const NumericSensorStatusSchema = z.object({\n value: z.number(),\n /** Display unit-of-measurement (e.g. 'dBm', 's', 'rpm', 'steps').\n * Populated live from the upstream source on each state push.\n * Absent for unitless sensors. */\n unit: z.string().optional(),\n /** Suggested decimal places for numeric display.\n * Populated live from the upstream source when provided.\n * Falls back to auto-formatting when absent. */\n precision: z.number().int().min(0).max(10).optional(),\n /** Ms epoch when the slice was last updated. */\n lastFetchedAt: z.number(),\n})\n\nexport type NumericSensorStatus = z.infer<typeof NumericSensorStatusSchema>\n\nexport const numericSensorCapability = {\n name: 'numeric-sensor',\n scope: 'device',\n deviceNative: true,\n mode: 'singleton',\n deviceTypes: [DeviceType.Sensor],\n methods: {},\n status: {\n schema: NumericSensorStatusSchema,\n kind: 'push',\n },\n runtimeState: NumericSensorStatusSchema,\n} as const satisfies CapabilityDefinition\n\nexport type INumericSensorProvider = InferProvider<typeof numericSensorCapability>\n","import { z } from 'zod'\nimport { type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\n\n/**\n * Multi-metric electrical meter. One slice can carry any combination\n * of instantaneous power (W), cumulative energy (kWh), voltage (V),\n * and current (A) — all fields optional so a single-metric source\n * (HA `sensor` with `device_class: power`) populates only what it\n * has and aggregators (energy dashboards, billing exports) compose\n * across providers without needing one cap per metric.\n *\n * Trade-off acknowledged: a HomeKit export that wants to surface\n * \"power\" and \"energy\" as separate services has to crack open the\n * slice and emit two characteristics from one cap. Worth it to avoid\n * exploding the cap catalog with `power-w` / `energy-kwh` /\n * `voltage-v` / `current-a` quartets that always travel together\n * in real-world devices.\n */\nexport const PowerMeterStatusSchema = z.object({\n /** Instantaneous power draw in watts. */\n watts: z.number().optional(),\n /** Cumulative energy in kilowatt-hours since the meter was reset. */\n kwhTotal: z.number().optional(),\n /** Voltage in volts. */\n volts: z.number().optional(),\n /** Current in amperes. */\n amps: z.number().optional(),\n /** Apparent power in volt-amperes (W × power-factor reciprocal). */\n va: z.number().optional(),\n /** Power factor (0..1) if reported. */\n powerFactor: z.number().min(0).max(1).optional(),\n /** Ms epoch when the slice was last updated. */\n lastFetchedAt: z.number(),\n /** Live display unit of the single metric this slice carries (e.g. HA\n * `attributes.unit_of_measurement` → 'V' / 'A' / 'W' / 'kW' / 'kWh').\n * Each upstream `sensor.*` entity surfaces ONE device_class, so one\n * unit per slice is unambiguous. The UI prefers this over the role's\n * canonical unit so a 'kW' / 'Wh' feed renders verbatim. */\n unit: z.string().optional(),\n /** Suggested decimal places for numeric display.\n * Populated live from the upstream source when provided (e.g. HA\n * `attributes.suggested_display_precision`). Falls back to\n * auto-formatting when absent. */\n precision: z.number().int().min(0).max(10).optional(),\n})\n\nexport type PowerMeterStatus = z.infer<typeof PowerMeterStatusSchema>\n\nexport const powerMeterCapability = {\n name: 'power-meter',\n scope: 'device',\n deviceNative: true,\n mode: 'singleton',\n deviceTypes: [DeviceType.Sensor],\n methods: {},\n status: {\n schema: PowerMeterStatusSchema,\n kind: 'push',\n },\n runtimeState: PowerMeterStatusSchema,\n} as const satisfies CapabilityDefinition\n\nexport type IPowerMeterProvider = InferProvider<typeof powerMeterCapability>\n","import { z } from 'zod'\nimport { type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\n\n/**\n * Presence cap. Models HA `person.*` and `device_tracker.*` entities\n * on `DeviceType.Presence`. Read-only — no setters: presence is\n * derived from upstream signals (mobile-app location, router DHCP\n * lease, Bluetooth beacon, manual zone change) and pushed into the\n * slice.\n *\n * `state` follows HA's canonical values — `home` / `not_home` /\n * `<zone-name>` for any other named zone. The zone name is freeform\n * because users define arbitrary zones (`work`, `gym`, `school`).\n *\n * GPS coordinates are nullable — tracker types without location\n * (Bluetooth scanner, MQTT presence) omit them. The presence of\n * GPS data is signaled by `DeviceFeature.PresenceGps` for fast\n * UI map-pin rendering.\n */\n\nconst GpsLocationSchema = z.object({\n /** Latitude in decimal degrees, -90..90. */\n latitude: z.number().min(-90).max(90),\n /** Longitude in decimal degrees, -180..180. */\n longitude: z.number().min(-180).max(180),\n /** Reported accuracy in meters (lower = better). */\n accuracyMeters: z.number().nonnegative(),\n})\nexport type GpsLocation = z.infer<typeof GpsLocationSchema>\n\nexport const PresenceStatusSchema = z.object({\n /** `home` / `not_home` / any user-defined zone name. */\n state: z.string(),\n /** Optional textual location label (zone name, city, address). Null\n * when only the binary state is known. */\n location: z.string().nullable(),\n /** GPS coordinates when available. Null otherwise. */\n gps: GpsLocationSchema.nullable(),\n /** Optional battery level of the tracking device (0..100). Null\n * when not reported. */\n batteryPercent: z.number().min(0).max(100).nullable(),\n /** Ms epoch when the slice was last updated. */\n lastChangedAt: z.number(),\n})\n\nexport type PresenceStatus = z.infer<typeof PresenceStatusSchema>\n\nexport const presenceCapability = {\n name: 'presence',\n scope: 'device',\n deviceNative: true,\n mode: 'singleton',\n deviceTypes: [DeviceType.Presence],\n methods: {},\n status: {\n schema: PresenceStatusSchema,\n kind: 'push',\n },\n /**\n * Runtime-state slice — mirrored by the kernel. UI presence card\n * reads `state` + `location` for the text label; iff `gps !== null`\n * the map pin is rendered (use `DeviceFeature.PresenceGps` for the\n * pre-fetch fast-path check).\n */\n runtimeState: PresenceStatusSchema,\n} as const satisfies CapabilityDefinition\n\nexport type IPresenceProvider = InferProvider<typeof presenceCapability>\n","import { z } from 'zod'\nimport { type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\n\n/**\n * Atmospheric pressure reading in hectopascals. Drives Home Assistant\n * `sensor` entries with `device_class: pressure`.\n *\n * Unit normalisation: hPa. The canonical display unit (`hPa`) is a\n * descriptor constant in the UI (ROLE_DESCRIPTOR), not stored in\n * `sourceInfo`.\n */\nexport const PressureSensorStatusSchema = z.object({\n /** Current pressure in hPa. */\n hpa: z.number(),\n /** Ms epoch when the slice was last updated. */\n lastFetchedAt: z.number(),\n /** Live display unit from the upstream source (e.g. HA\n * `attributes.unit_of_measurement`). The UI prefers this over the\n * role's canonical unit. Absent → fall back to the canonical unit. */\n unit: z.string().optional(),\n /** Suggested decimal places for numeric display.\n * Populated live from the upstream source when provided (e.g. HA\n * `attributes.suggested_display_precision`). Falls back to\n * auto-formatting when absent. */\n precision: z.number().int().min(0).max(10).optional(),\n})\n\nexport type PressureSensorStatus = z.infer<typeof PressureSensorStatusSchema>\n\nexport const pressureSensorCapability = {\n name: 'pressure-sensor',\n scope: 'device',\n deviceNative: true,\n mode: 'singleton',\n deviceTypes: [DeviceType.Sensor],\n methods: {},\n status: {\n schema: PressureSensorStatusSchema,\n kind: 'push',\n },\n runtimeState: PressureSensorStatusSchema,\n} as const satisfies CapabilityDefinition\n\nexport type IPressureSensorProvider = InferProvider<typeof pressureSensorCapability>\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferNativeProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\nimport {\n MaskRectShapeSchema,\n MaskPolygonShapeSchema,\n MaskShapeKindSchema,\n MaskPolygonVerticesSchema,\n} from './mask-shape.js'\n\n/**\n * Privacy mask = up to `maxRegions` SHAPES the camera blanks out (NOT a\n * cell grid). Reolink `<shelterList>` zones are rectangles; Hikvision\n * ISAPI `<RegionCoordinatesList>` zones are free polygons (this camera:\n * exactly 4 vertices, not necessarily axis-aligned). The cap composes the\n * shared rect|polygon subset of the MaskShape vocabulary. All coords are\n * normalized 0..1 (top-left origin).\n */\n\n/** A privacy-mask region's geometry — rectangle or free polygon. */\nexport const PrivacyMaskShapeSchema = z.discriminatedUnion('kind', [\n MaskRectShapeSchema,\n MaskPolygonShapeSchema,\n])\n\n/** A single privacy-mask zone. */\nexport const PrivacyMaskRegionSchema = z.object({\n /** Slot id, 0-based. Stable across read/write. */\n id: z.number(),\n /** Whether this zone is active (blanked out by the camera). */\n enabled: z.boolean(),\n shape: PrivacyMaskShapeSchema,\n})\n\n/** Current on-camera privacy-mask state — master enable + zones. */\nexport const PrivacyMaskStatusSchema = z.object({\n enabled: z.boolean(),\n /** Active zones (normalized 0..1). Length ≤ maxRegions. */\n regions: z.array(PrivacyMaskRegionSchema),\n lastFetchedAt: z.number(),\n})\n\n/** Per-camera availability. */\nexport const PrivacyMaskOptionsSchema = z.object({\n /** Maximum number of supported zones. */\n maxRegions: z.number(),\n /** Shape kinds this camera accepts — Reolink: ['rect']; Hikvision: ['rect','polygon']. */\n supportedShapes: z.array(MaskShapeKindSchema),\n /** Polygon vertex bounds when 'polygon' is supported (Hikvision: {min:4,max:4}). */\n polygonVertices: MaskPolygonVerticesSchema.optional(),\n})\n\n/** Partial change — every field optional. */\nexport const PrivacyMaskPatchSchema = z.object({\n enabled: z.boolean().optional(),\n regions: z.array(PrivacyMaskRegionSchema).optional(),\n})\n\nexport type PrivacyMaskShape = z.infer<typeof PrivacyMaskShapeSchema>\nexport type PrivacyMaskRegion = z.infer<typeof PrivacyMaskRegionSchema>\nexport type PrivacyMaskStatus = z.infer<typeof PrivacyMaskStatusSchema>\nexport type PrivacyMaskOptions = z.infer<typeof PrivacyMaskOptionsSchema>\nexport type PrivacyMaskPatch = z.infer<typeof PrivacyMaskPatchSchema>\n\nexport const privacyMaskCapability = {\n name: 'privacy-mask',\n scope: 'device',\n deviceNative: true,\n mode: 'singleton',\n deviceTypes: [DeviceType.Camera],\n deviceConfig: {\n ui: { kind: 'widget', widgetId: 'host/privacy-mask-grid', tab: 'image', label: 'Privacy Mask' },\n },\n methods: {\n getOptions: method(z.object({ deviceId: z.number() }), PrivacyMaskOptionsSchema),\n setMask: method(\n z.object({ deviceId: z.number(), patch: PrivacyMaskPatchSchema }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n },\n status: { schema: PrivacyMaskStatusSchema, kind: 'poll' },\n runtimeState: PrivacyMaskStatusSchema,\n} as const satisfies CapabilityDefinition\n\nexport type IPrivacyMaskProvider = InferNativeProvider<typeof privacyMaskCapability>\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\n\n/**\n * `ptz-autotrack` — sibling cap of `ptz` that exposes the on-camera\n * smart-tracking subsystem (subject-following). Modeled separately\n * from `ptz` because:\n * - Not every PTZ-capable camera has autotrack (Reolink: yes;\n * Hikvision: model-dependent), so a single combined cap would\n * force every PTZ provider to surface `Unsupported` stubs on\n * half the methods.\n * - The cap's lifecycle is \"registered when probed-true\" — the\n * binding system can show / hide the UI affordance cleanly via\n * the standard `provider-registered` signal.\n * - Autotrack on/off is a device-state toggle (status), distinct\n * from PTZ's continuous control surface — a status-driven cap\n * fits the existing `setStatus` / `onStatusChanged` pattern\n * better than `ptz`'s discrete-action surface.\n *\n * Settings (cross-vendor consolidation, sourced from Reolink's\n * `setAutotrackingSettings` shape; expandable as Hikvision /\n * Dahua / others land):\n * - `targetType` — vendor target string (people /\n * vehicle / pet / `''` = camera default)\n * - `stopDelaySeconds` — how long to keep tracking a\n * stationary target before stopping\n * (0..300, default 30)\n * - `disappearDelaySeconds` — how long to wait before releasing a\n * target that has left the frame\n * (0..300, default 15)\n *\n * The driver is the source of truth for which settings keys it\n * actually honours; unsupported keys silently fall back to the\n * camera's defaults. Adding a new vendor's setting (e.g. Hikvision's\n * `trackingDuration`) extends the schema below and the\n * `setSettings` payload.\n */\n\nconst AutotrackTargetTypeSchema = z.string()\n .describe('Vendor target string (people/vehicle/pet); empty = camera default')\n\nexport const PtzAutotrackSettingsSchema = z.object({\n targetType: AutotrackTargetTypeSchema,\n stopDelaySeconds: z.number().int().min(0).max(300),\n disappearDelaySeconds: z.number().int().min(0).max(300),\n})\n\nexport type PtzAutotrackSettings = z.infer<typeof PtzAutotrackSettingsSchema>\n\n/**\n * One option the camera advertises as a valid `targetType`. Drivers\n * harvest this from their probe data; the UI renders these as the\n * `targetType` select options. Empty array = the camera doesn't\n * expose a target-type selector (auto-only).\n *\n * The `value` is the canonical wire string the cap accepts in\n * `setSettings({targetType})` — drivers use it verbatim when pushing\n * to firmware. The `label` is operator-facing English (translated\n * client-side if the UI supports i18n).\n */\nexport const PtzAutotrackTargetOptionSchema = z.object({\n value: z.string(),\n label: z.string(),\n})\n\nexport type PtzAutotrackTargetOption = z.infer<typeof PtzAutotrackTargetOptionSchema>\n\nexport const PtzAutotrackStatusSchema = z.object({\n /** True when autotrack is currently armed on the camera. */\n enabled: z.boolean(),\n /** Ms epoch of the last on/off transition (0 if never observed). */\n lastChangedAt: z.number(),\n /** Currently-applied settings the camera reports. Drivers fill\n * this from the firmware GET so the UI can echo what's *really*\n * active vs the operator-typed values in the settings form. */\n currentSettings: PtzAutotrackSettingsSchema.nullable(),\n /**\n * Target types the camera advertises. Driver-supplied — Reolink\n * exposes `people` / `vehicle` / `pet`, Hikvision exposes\n * `auto` / `human` / `vehicle` when the `<smartTrackingType>` knob\n * is supported. Empty array = vendor doesn't expose a selector\n * (treat as auto-only). The UI renders these as the `targetType`\n * field options without hardcoding a vendor-specific list.\n */\n supportedTargetTypes: z.array(PtzAutotrackTargetOptionSchema),\n})\n\nexport type PtzAutotrackStatus = z.infer<typeof PtzAutotrackStatusSchema>\n\n/**\n * Runtime-state slice owned by this cap. Persists the last-known\n * camera-derived snapshot across restarts, so cold-start callers\n * have a meaningful baseline even before the first refresh round-trip.\n *\n * Adds `lastFetchedAt` on top of the status shape so the framework\n * (or the provider) can stale-check before deciding whether to\n * round-trip the camera again.\n */\nexport const PtzAutotrackRuntimeStateSchema = PtzAutotrackStatusSchema.extend({\n /** Ms epoch of the last successful camera fetch (0 = never). */\n lastFetchedAt: z.number(),\n})\n\nexport type PtzAutotrackRuntimeState = z.infer<typeof PtzAutotrackRuntimeStateSchema>\n\nexport const ptzAutotrackCapability = {\n name: 'ptz-autotrack',\n scope: 'device',\n deviceNative: true,\n mode: 'singleton',\n deviceTypes: [DeviceType.Camera],\n deviceConfig: {\n ui: { kind: 'widget', widgetId: 'host/ptz-autotrack', tab: 'ptz', topTab: true, label: 'Auto-Tracking', order: 5 },\n },\n methods: {\n /**\n * Read the current on/off state + last-applied settings.\n * Drivers may serve from a cache + refresh on a schedule —\n * callers should NOT poll faster than ~5s.\n */\n getStatus: method(\n z.object({ deviceId: z.number() }),\n PtzAutotrackStatusSchema,\n ),\n /**\n * Arm or disarm autotrack. Resolves once the camera has\n * acknowledged the transition; the `onStatusChanged` event\n * fires shortly after with the live state.\n */\n setEnabled: method(\n z.object({ deviceId: z.number(), enabled: z.boolean() }),\n z.void(),\n { kind: 'mutation' },\n ),\n /**\n * Read settings (target type + delays). Mirrors the\n * `getStatus().currentSettings` payload but exposes it as a\n * standalone read for callers that want settings without the\n * status surface around them. `null` until the driver has\n * harvested the firmware state at least once.\n */\n getSettings: method(\n z.object({ deviceId: z.number() }),\n PtzAutotrackSettingsSchema.nullable(),\n ),\n /**\n * Update one or more settings. Partial — keys that aren't\n * supplied keep their last persisted value. The driver is\n * responsible for clamping vendor-specific ranges if narrower\n * than the cross-vendor max declared on the schema.\n */\n setSettings: method(\n z.object({\n deviceId: z.number(),\n settings: PtzAutotrackSettingsSchema.partial(),\n }),\n z.void(),\n { kind: 'mutation' },\n ),\n },\n events: {\n onStatusChanged: { data: z.object({\n deviceId: z.number(),\n status: PtzAutotrackStatusSchema,\n })},\n },\n status: {\n schema: PtzAutotrackStatusSchema,\n kind: 'command-driven',\n },\n /**\n * Persistent slice mirrored across restarts. The provider writes\n * here on every successful firmware fetch / settings push;\n * `getStatus` and `getSettings` then read this snapshot synchronously\n * with a stale-driven async refresh in the background. Keeps the\n * fetch / cache / fallback logic out of the four cap methods —\n * they become trampolines over `runtimeState`.\n */\n runtimeState: PtzAutotrackRuntimeStateSchema,\n} as const satisfies CapabilityDefinition\n\nexport type IPtzAutotrackProvider = InferProvider<typeof ptzAutotrackCapability>\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\n\n/**\n * Script-runner cap. Models HA `script.*` entities on\n * `DeviceType.Script`. A Script is a pre-recorded action sequence\n * that can be invoked imperatively — optionally with a variables\n * map when the script declares input fields.\n *\n * Variable-support is signalled by `DeviceFeature.ScriptVariables`\n * so the UI gates a \"with parameters\" form without a slice fetch.\n */\n\nexport const ScriptRunnerStatusSchema = z.object({\n /** Whether the script is currently executing. */\n isRunning: z.boolean(),\n /** Ms epoch of the last invocation start. 0 when never run. */\n lastRunAt: z.number(),\n /** Outcome of the last completed run. Null when never run or still\n * running. */\n lastRunSuccess: z.boolean().nullable(),\n /** Failure description from the last completed run. Null on success\n * or when never run. */\n lastError: z.string().nullable(),\n /** Ms epoch when the slice was last updated. */\n lastChangedAt: z.number(),\n})\n\nexport type ScriptRunnerStatus = z.infer<typeof ScriptRunnerStatusSchema>\n\nexport const scriptRunnerCapability = {\n name: 'script-runner',\n scope: 'device',\n deviceNative: true,\n mode: 'singleton',\n deviceTypes: [DeviceType.Script],\n methods: {\n run: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n /** Optional variables map — passed through to the upstream\n * script. Provider rejects when the script doesn't declare\n * input fields (gated by `DeviceFeature.ScriptVariables`). */\n variables: z.record(z.string(), z.unknown()).optional(),\n }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n /** Cancel a running script. Provider rejects when the script\n * isn't currently running. */\n stop: method(\n z.object({ deviceId: z.number().int().nonnegative() }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n },\n status: {\n schema: ScriptRunnerStatusSchema,\n kind: 'push',\n },\n /**\n * Runtime-state slice — mirrored by the kernel. UI script tile reads\n * `isRunning` to render a spinner during execution and surfaces\n * `lastError` / `lastRunSuccess` in the recent-runs panel.\n */\n runtimeState: ScriptRunnerStatusSchema,\n} as const satisfies CapabilityDefinition\n\nexport type IScriptRunnerProvider = InferProvider<typeof scriptRunnerCapability>\n","import { z } from 'zod'\nimport { type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\n\n/**\n * Smoke alarm sensor — boolean \"is smoke currently detected\" with\n * timestamp of the last transition. Drives Home Assistant\n * `binary_sensor` entries with `device_class: smoke`.\n *\n * Push-driven: a smoke event is critical, so the slice updates\n * immediately on the upstream signal. Auto-clearing back to false is\n * provider-controlled (some alarms latch until manually reset).\n */\nexport const SmokeStatusSchema = z.object({\n detected: z.boolean(),\n /** Ms epoch of the last transition. 0 if never observed. */\n lastChangedAt: z.number(),\n})\n\nexport type SmokeStatus = z.infer<typeof SmokeStatusSchema>\n\nexport const smokeCapability = {\n name: 'smoke',\n scope: 'device',\n deviceNative: true,\n mode: 'singleton',\n deviceTypes: [DeviceType.Sensor],\n methods: {},\n status: {\n schema: SmokeStatusSchema,\n kind: 'push',\n },\n runtimeState: SmokeStatusSchema,\n} as const satisfies CapabilityDefinition\n\nexport type ISmokeProvider = InferProvider<typeof smokeCapability>\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferNativeProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\n\n/** One of the camera's stream profiles. */\nexport const StreamProfileSchema = z.enum(['main', 'sub', 'ext'])\n\n/** The current encoding config of one stream profile. */\nconst StreamProfileConfigSchema = z.object({\n width: z.number(),\n height: z.number(),\n codec: z.enum(['h264', 'h265']),\n framerate: z.number(),\n bitrate: z.number(), // kbps\n bitrateMode: z.enum(['vbr', 'cbr']).optional(),\n encoderProfile: z.enum(['high', 'main', 'baseline']).optional(),\n gop: z.number().optional(),\n audio: z.boolean().optional(),\n})\n\nexport const StreamParamsStatusSchema = z.object({\n /** Per-profile current config. A profile absent = the camera doesn't have it. */\n main: StreamProfileConfigSchema.optional(),\n sub: StreamProfileConfigSchema.optional(),\n ext: StreamProfileConfigSchema.optional(),\n lastFetchedAt: z.number(),\n})\n\n/** What a profile CAN be set to — drives the UI selectors. */\nconst StreamProfileOptionsSchema = z.object({\n resolutions: z.array(z.object({ width: z.number(), height: z.number() })),\n codecs: z.array(z.enum(['h264', 'h265'])),\n framerates: z.array(z.number()),\n /** Allowed bitrate values (kbps). Empty if the camera takes a free range. */\n bitrates: z.array(z.number()),\n /** Optional [min,max] kbps when the camera accepts a continuous range. */\n bitrateRange: z.tuple([z.number(), z.number()]).optional(),\n supportsBitrateMode: z.boolean(),\n supportsEncoderProfile: z.boolean(),\n supportsGop: z.boolean(),\n /** Allowed GOP / keyframe-interval range, in seconds — drives the\n * I-frame-interval selector. Absent when the camera advertises GOP\n * support but no concrete range (callers then fall back to a free\n * numeric input). `{ min, max, step }` per the getOptions convention. */\n gop: z.object({ min: z.number(), max: z.number(), step: z.number() }).optional(),\n})\n\nexport const StreamParamsOptionsSchema = z.object({\n main: StreamProfileOptionsSchema.optional(),\n sub: StreamProfileOptionsSchema.optional(),\n ext: StreamProfileOptionsSchema.optional(),\n})\n\n/** A partial change to one profile — every field optional; a provider\n * ignores fields it doesn't support. */\nexport const StreamProfilePatchSchema = z.object({\n width: z.number().optional(),\n height: z.number().optional(),\n codec: z.enum(['h264', 'h265']).optional(),\n framerate: z.number().optional(),\n bitrate: z.number().optional(),\n bitrateMode: z.enum(['vbr', 'cbr']).optional(),\n encoderProfile: z.enum(['high', 'main', 'baseline']).optional(),\n gop: z.number().optional(),\n audio: z.boolean().optional(),\n})\n\nexport type StreamParamsStatus = z.infer<typeof StreamParamsStatusSchema>\nexport type StreamParamsOptions = z.infer<typeof StreamParamsOptionsSchema>\nexport type StreamProfile = z.infer<typeof StreamProfileSchema>\nexport type StreamProfilePatch = z.infer<typeof StreamProfilePatchSchema>\n\nexport const streamParamsCapability = {\n name: 'stream-params',\n scope: 'device',\n deviceNative: true,\n mode: 'singleton',\n deviceTypes: [DeviceType.Camera],\n deviceConfig: {\n ui: { kind: 'derived-form', builderId: 'stream-params', tab: 'streaming' },\n },\n methods: {\n getOptions: method(\n z.object({ deviceId: z.number() }),\n StreamParamsOptionsSchema,\n ),\n setProfile: method(\n z.object({\n deviceId: z.number(),\n profile: StreamProfileSchema,\n patch: StreamProfilePatchSchema,\n }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n /**\n * Build the `ConfigUISchema` (admin-ui `ConfigFormBuilder` input\n * shape) for this camera's stream-encoder settings — one section per\n * profile (main / sub / ext) with the resolution / codec / framerate\n * / bitrate / bitrate-mode / encoder-profile / GOP controls the\n * firmware actually exposes.\n *\n * Driven by `getOptions` (camera-probed availability) + `getStatus`\n * (current per-profile config); each field's `default` is seeded\n * from the live config so the form renders the camera state in one\n * pass. Returns `null` when the camera exposes no configurable\n * stream property — the renderer then shows the unsupported message.\n *\n * Output is `z.unknown().nullable()` — the same convention every\n * other `ConfigUISchema`-returning cap method uses (`device-ops`,\n * `device-manager`); `ConfigUISchema` is a TS-only type with no\n * companion Zod schema, and a concrete object would collapse\n * unrelated AppRouter branches to `unknown` during codegen.\n */\n getConfigSchema: method(\n z.object({ deviceId: z.number() }),\n z.unknown().nullable(),\n ),\n },\n status: {\n schema: StreamParamsStatusSchema,\n kind: 'poll',\n },\n runtimeState: StreamParamsStatusSchema,\n} as const satisfies CapabilityDefinition\n\nexport type IStreamParamsProvider = InferNativeProvider<typeof streamParamsCapability>\n\nexport { StreamProfileConfigSchema, StreamProfileOptionsSchema }\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\n\n/**\n * Generic on/off switch cap for accessory children (siren, floodlight,\n * spotlight, PIR toggle, chime silencer, autotrack enable, …). The cap\n * owns ONLY the boolean state — driver-specific settings (brightness,\n * sensitivity, schedule, duration) live on the device's own\n * `getSettingsUISchema()` surface.\n */\nexport const SwitchStatusSchema = z.object({\n on: z.boolean(),\n /** Ms epoch of the last state change. Useful for UI \"X minutes ago\". */\n lastChangedAt: z.number(),\n})\n\nexport type SwitchStatus = z.infer<typeof SwitchStatusSchema>\n\nexport const switchCapability = {\n name: 'switch',\n scope: 'device',\n deviceNative: true,\n mode: 'singleton',\n deviceTypes: [DeviceType.Switch, DeviceType.Siren, DeviceType.Light],\n methods: {\n setState: method(\n z.object({ deviceId: z.number(), on: z.boolean() }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n },\n events: {\n onStateChanged: { data: z.object({\n deviceId: z.number(),\n on: z.boolean(),\n lastChangedAt: z.number(),\n })},\n },\n status: {\n schema: SwitchStatusSchema,\n kind: 'command-driven',\n },\n /**\n * Runtime-state slice — the last applied on/off state, mirrored by\n * the kernel. Read via `device.state.switch.value`; UI toggles do\n * not need to re-query the provider after a setState mutation.\n */\n runtimeState: SwitchStatusSchema,\n settings: {\n bindings: [{\n kind: 'scalar',\n statusPath: 'on',\n method: 'setState',\n valueArg: 'on',\n field: { label: 'On', kind: 'boolean' },\n }],\n },\n} as const satisfies CapabilityDefinition\n\nexport type ISwitchProvider = InferProvider<typeof switchCapability>\n","import { z } from 'zod'\nimport { type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\n\n/**\n * Tamper / case-open detection sensor. Drives Home Assistant\n * `binary_sensor` entries with `device_class: tamper`. Push-driven.\n */\nexport const TamperStatusSchema = z.object({\n /** True when the device's tamper switch / case-open contact is\n * currently triggered. */\n tampered: z.boolean(),\n /** Ms epoch of the last transition. 0 if never observed. */\n lastChangedAt: z.number(),\n})\n\nexport type TamperStatus = z.infer<typeof TamperStatusSchema>\n\nexport const tamperCapability = {\n name: 'tamper',\n scope: 'device',\n deviceNative: true,\n mode: 'singleton',\n deviceTypes: [DeviceType.Sensor],\n methods: {},\n status: {\n schema: TamperStatusSchema,\n kind: 'push',\n },\n runtimeState: TamperStatusSchema,\n} as const satisfies CapabilityDefinition\n\nexport type ITamperProvider = InferProvider<typeof tamperCapability>\n","import { z } from 'zod'\nimport { type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\n\n/**\n * Single-metric temperature reading. Drives Home Assistant `sensor`\n * entries with `device_class: temperature` and any future native\n * thermometer.\n *\n * Unit normalisation: providers convert to Celsius before storing.\n * The slice value is always Celsius so cross-cap aggregators\n * (climate-control's `currentTemp`, energy analytics) can compose\n * without per-source unit fixups. The canonical display unit (`°C`) is\n * a descriptor constant in the UI (ROLE_DESCRIPTOR), not stored in\n * `sourceInfo`.\n *\n * Status `lastFetchedAt` lets staleness-aware consumers detect a\n * frozen feed (provider hung) distinct from a \"temperature hasn't\n * changed\" steady state.\n */\nexport const TemperatureSensorStatusSchema = z.object({\n /** Current temperature in Celsius. */\n celsius: z.number(),\n /** Ms epoch when the slice was last updated (push or poll). */\n lastFetchedAt: z.number(),\n /** Live display unit from the upstream source (e.g. HA\n * `attributes.unit_of_measurement`). The UI prefers this over the\n * role's canonical unit, so a Fahrenheit feed renders '°F' not '°C'.\n * Absent → the UI falls back to the role's canonical unit. */\n unit: z.string().optional(),\n /** Suggested decimal places for numeric display.\n * Populated live from the upstream source when provided (e.g. HA\n * `attributes.suggested_display_precision`). Falls back to\n * auto-formatting when absent. */\n precision: z.number().int().min(0).max(10).optional(),\n})\n\nexport type TemperatureSensorStatus = z.infer<typeof TemperatureSensorStatusSchema>\n\nexport const temperatureSensorCapability = {\n name: 'temperature-sensor',\n scope: 'device',\n deviceNative: true,\n mode: 'singleton',\n deviceTypes: [DeviceType.Sensor, DeviceType.Thermostat],\n methods: {},\n status: {\n schema: TemperatureSensorStatusSchema,\n kind: 'push',\n },\n runtimeState: TemperatureSensorStatusSchema,\n} as const satisfies CapabilityDefinition\n\nexport type ITemperatureSensorProvider = InferProvider<typeof temperatureSensorCapability>\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\n\n/**\n * Firmware/software update entity. Installed on a `DeviceType.Update` device.\n * Surfaces current vs available version, whether an update is available, the\n * update state, and an install action. Read-mostly and POLL-driven: backends\n * such as the Homematic CCU do not broadcast firmware-descriptor changes, so\n * the client re-queries `getStatus` (which reads the live descriptor) rather\n * than relying on push delivery. `installUpdate` triggers the install\n * (best-effort — providers throw if the backend rejects it).\n */\nexport const UpdateStatusSchema = z.object({\n currentVersion: z.string().nullable(),\n availableVersion: z.string().nullable(),\n /**\n * DEVICE-CAPABILITY flag: the entity supports firmware updates at all — NOT\n * a per-state \"an update is available right now\" flag. The canonical\n * \"update available\" signal is `availableVersion !== currentVersion` (which\n * is what the UI uses); HA's `state === 'on'` mirrors that same condition.\n */\n updatable: z.boolean(),\n state: z.string().nullable(), // e.g. 'UP_TO_DATE' / 'DELIVER_FIRMWARE_IMAGE' (provider-verbatim)\n inProgress: z.boolean(),\n})\nexport type UpdateStatus = z.infer<typeof UpdateStatusSchema>\n\nexport const updateCapability = {\n name: 'update',\n scope: 'device',\n deviceNative: true,\n mode: 'singleton',\n deviceTypes: [DeviceType.Update],\n methods: {\n installUpdate: method(z.void(), z.void(), { kind: 'mutation', auth: 'admin' }),\n },\n status: { schema: UpdateStatusSchema, kind: 'poll' },\n runtimeState: UpdateStatusSchema,\n} as const satisfies CapabilityDefinition\n\nexport type IUpdateProvider = InferProvider<typeof updateCapability>\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\n\n/**\n * Robot-vacuum cap. Models HA `vacuum.*` entities — anything with a\n * cleaning lifecycle plus a return-to-base / locate surface and an\n * optional fan-speed selector.\n *\n * State follows HA's canonical vacuum lifecycle: `idle` / `cleaning` /\n * `paused` / `returning` / `docked` / `error`. `batteryLevel`\n * (0..100) is nullable — some vacuums don't report a battery\n * percentage. `fanSpeed` is the current speed token (provider-verbatim,\n * e.g. `'standard'` / `'turbo'`) and `availableFanSpeeds` lists the\n * tokens the hardware accepts so the UI renders only supported choices.\n *\n * The `setFanSpeed` method takes the bare `speed` token — the provider\n * validates it against the vacuum's own list. `locate` triggers the\n * find-me chirp; `returnToBase` sends it home.\n *\n * Consumable / waste tanks: `cleanWater` / `dirtyWater` / `detergent` /\n * `dustBin` each carry a nullable `{ level (0..100 %), status ('ok' |\n * 'low' | 'full') }` reading. Native providers (e.g. Dreame, Roborock)\n * SHOULD populate whichever tanks the hardware has — leave a field `null`\n * only when the device has no such tank at all, and use a `TankStatus`\n * with both inner fields `null` when the tank exists but its level is\n * currently unknown. HA `vacuum.*` entities expose no per-tank telemetry,\n * so the HA provider leaves all four `null`.\n */\n\nexport const VacuumStateSchema = z.enum([\n 'idle',\n 'cleaning',\n 'paused',\n 'returning',\n 'docked',\n 'error',\n])\nexport type VacuumState = z.infer<typeof VacuumStateSchema>\n\n/**\n * One consumable / waste tank on a robot vacuum (clean-water, dirty-water,\n * detergent or dust-bin). A tank can report a numeric fill `level` (0..100),\n * a discrete `status` (binary-style hardware), or both. Both `null` means the\n * level is currently unknown; the OWNING field being `null` means the\n * hardware has no such tank at all.\n */\nexport const TankStatusSchema = z.object({\n /** Numeric fill 0..100 when the hardware reports a percentage; null otherwise. */\n level: z.number().min(0).max(100).nullable(),\n /** Discrete state when the hardware is binary-mode; null otherwise. */\n status: z.enum(['ok', 'low', 'full']).nullable(),\n})\nexport type TankStatus = z.infer<typeof TankStatusSchema>\n\nexport const VacuumControlStatusSchema = z.object({\n /** Lifecycle state of the vacuum. */\n state: VacuumStateSchema,\n /** 0..100 battery percentage. Null when the device has no battery\n * reading. */\n batteryLevel: z.number().min(0).max(100).nullable(),\n /** Current fan-speed token (provider-verbatim). Null when unknown or\n * the vacuum has no speed control. */\n fanSpeed: z.string().nullable(),\n /** Speed tokens the hardware accepts — drives the UI selector. */\n availableFanSpeeds: z.array(z.string()),\n /** Clean-water (mop) tank. Null when the hardware has no clean-water tank. */\n cleanWater: TankStatusSchema.nullable(),\n /** Dirty-water (recovery) tank. Null when the hardware has no dirty-water tank. */\n dirtyWater: TankStatusSchema.nullable(),\n /** Detergent tank. Null when the hardware has no detergent tank. */\n detergent: TankStatusSchema.nullable(),\n /** Dust bin. Null when the hardware has no dust bin. */\n dustBin: TankStatusSchema.nullable(),\n /** Ms epoch when the slice was last updated. */\n lastChangedAt: z.number(),\n})\n\nexport type VacuumControlStatus = z.infer<typeof VacuumControlStatusSchema>\n\nexport const vacuumControlCapability = {\n name: 'vacuum-control',\n scope: 'device',\n deviceNative: true,\n mode: 'singleton',\n deviceTypes: [DeviceType.Vacuum],\n methods: {\n start: method(\n z.object({ deviceId: z.number().int().nonnegative() }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n pause: method(\n z.object({ deviceId: z.number().int().nonnegative() }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n stop: method(\n z.object({ deviceId: z.number().int().nonnegative() }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n returnToBase: method(\n z.object({ deviceId: z.number().int().nonnegative() }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n locate: method(\n z.object({ deviceId: z.number().int().nonnegative() }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n setFanSpeed: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n speed: z.string().min(1),\n }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n },\n status: {\n schema: VacuumControlStatusSchema,\n kind: 'push',\n },\n /**\n * Runtime-state slice — mirrored by the kernel. UI controls watch the\n * slice for live state + battery + fan-speed changes.\n */\n runtimeState: VacuumControlStatusSchema,\n} as const satisfies CapabilityDefinition\n\nexport type IVacuumControlProvider = InferProvider<typeof vacuumControlCapability>\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\n\n/**\n * Pipe / water / gas valve cap. Models HA `valve.*` entities — anything\n * that moves between an open and a closed state with optional\n * intermediate positioning.\n *\n * State follows HA's canonical lifecycle: `open` / `opening` /\n * `closing` / `closed` / `stopped`. `position` (0 closed, 100 open) is\n * nullable — some valves only support full open/close, while others\n * report and accept an intermediate position. Providers populate only\n * what the hardware reports.\n *\n * Unlike `cover`, valves have no tilt surface — the cap is the strict\n * open/close + optional position subset of the cover lifecycle.\n *\n * Sub-surface gating paired with a `DeviceFeature` flag:\n * - `ValvePositionable` — intermediate `position` slider / drag\n */\n\nexport const ValveStateSchema = z.enum([\n 'open',\n 'opening',\n 'closing',\n 'closed',\n 'stopped',\n])\nexport type ValveState = z.infer<typeof ValveStateSchema>\n\nexport const ValveStatusSchema = z.object({\n /** Lifecycle state of the valve. */\n state: ValveStateSchema,\n /** 0 = fully closed, 100 = fully open. Null when the device has no\n * intermediate position surface. */\n position: z.number().min(0).max(100).nullable(),\n /** Ms epoch when the slice was last updated. */\n lastChangedAt: z.number(),\n})\n\nexport type ValveStatus = z.infer<typeof ValveStatusSchema>\n\nexport const valveCapability = {\n name: 'valve',\n scope: 'device',\n deviceNative: true,\n mode: 'singleton',\n deviceTypes: [DeviceType.Valve],\n methods: {\n open: method(\n z.object({ deviceId: z.number().int().nonnegative() }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n close: method(\n z.object({ deviceId: z.number().int().nonnegative() }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n stop: method(\n z.object({ deviceId: z.number().int().nonnegative() }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n setPosition: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n position: z.number().min(0).max(100),\n }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n },\n status: {\n schema: ValveStatusSchema,\n kind: 'push',\n },\n /**\n * Runtime-state slice — mirrored by the kernel. UI controls watch the\n * slice for live position changes during a move.\n */\n runtimeState: ValveStatusSchema,\n} as const satisfies CapabilityDefinition\n\nexport type IValveProvider = InferProvider<typeof valveCapability>\n","import { z } from 'zod'\nimport { type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\n\n/**\n * Vibration / shake / impact sensor. Drives Home Assistant\n * `binary_sensor` entries with `device_class: vibration`. Push-driven.\n */\nexport const VibrationStatusSchema = z.object({\n detected: z.boolean(),\n /** Ms epoch of the last transition. 0 if never observed. */\n lastChangedAt: z.number(),\n})\n\nexport type VibrationStatus = z.infer<typeof VibrationStatusSchema>\n\nexport const vibrationCapability = {\n name: 'vibration',\n scope: 'device',\n deviceNative: true,\n mode: 'singleton',\n deviceTypes: [DeviceType.Sensor],\n methods: {},\n status: {\n schema: VibrationStatusSchema,\n kind: 'push',\n },\n runtimeState: VibrationStatusSchema,\n} as const satisfies CapabilityDefinition\n\nexport type IVibrationProvider = InferProvider<typeof vibrationCapability>\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\n\n/**\n * Water heater / boiler cap. Models HA `water_heater.*` entities — a\n * climate-family actuator with a target temperature, an operation-mode\n * selector (`eco` / `electric` / `gas` / `heat_pump` / `high_demand` /\n * `performance` / `off`), and an optional away-mode toggle.\n *\n * The slice carries the current + target temperature, the active\n * operation mode (HA's `state`) and its available set (HA's\n * `operation_list`), the away flag (HA `away_mode` 'on'/'off' → bool,\n * null when unsupported), plus the `min_temp` / `max_temp` bounds.\n *\n * Providers populate only what the hardware reports — temperature and\n * away fields stay null when the device has no such surface.\n */\n\nexport const WaterHeaterStatusSchema = z.object({\n /** Current measured temperature. Null when not reported. */\n currentTemp: z.number().nullable(),\n /** Target temperature setpoint. Null when no setpoint surface. */\n targetTemp: z.number().nullable(),\n /** Active operation mode = HA `state` (`eco` / `electric` / `gas` /\n * `heat_pump` / `high_demand` / `performance` / `off`). Null when the\n * device reports an unknown state. */\n operationMode: z.string().nullable(),\n /** Available operation modes = HA `operation_list`. */\n availableModes: z.array(z.string()),\n /** Away mode (HA `away_mode` 'on'/'off' → bool). Null when the device\n * has no away surface. */\n away: z.boolean().nullable(),\n /** HA `min_temp` attribute. Null when not reported. */\n minTemp: z.number().nullable(),\n /** HA `max_temp` attribute. Null when not reported. */\n maxTemp: z.number().nullable(),\n /** Ms epoch when the slice was last updated. */\n lastChangedAt: z.number(),\n})\n\nexport type WaterHeaterStatus = z.infer<typeof WaterHeaterStatusSchema>\n\nexport const waterHeaterCapability = {\n name: 'water-heater',\n scope: 'device',\n deviceNative: true,\n mode: 'singleton',\n deviceTypes: [DeviceType.WaterHeater],\n methods: {\n setTargetTemp: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n temp: z.number().finite(),\n }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n setOperationMode: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n mode: z.string().min(1),\n }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n setAway: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n on: z.boolean(),\n }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n },\n status: {\n schema: WaterHeaterStatusSchema,\n kind: 'push',\n },\n /**\n * Runtime-state slice — mirrored by the kernel. UI controls watch the\n * slice for live temperature / mode / away changes.\n */\n runtimeState: WaterHeaterStatusSchema,\n} as const satisfies CapabilityDefinition\n\nexport type IWaterHeaterProvider = InferProvider<typeof waterHeaterCapability>\n","import { z } from 'zod'\nimport { type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\n\n/**\n * Weather provider cap. Models HA `weather.*` entities — a read-only\n * snapshot of the CURRENT conditions a weather integration reports.\n *\n * Read-only: there are no setters. The slice is populated from upstream\n * pushes (the HA weather entity's state + attributes) and rendered by\n * the UI as a sky scene + readouts.\n *\n * `condition` is the verbatim HA state string (`sunny` / `cloudy` /\n * `rainy` / `snowy` / `partlycloudy` / `pouring` / `lightning` /\n * `lightning-rainy` / `fog` / `windy` / `windy-variant` / `hail` /\n * `clear-night` / `exceptional` / …). The UI maps it to a glyph + tint;\n * unknown strings fall back to a neutral cloud.\n *\n * Every numeric reading is nullable — a given weather integration only\n * populates the metrics it actually provides.\n *\n * Forecast deferred — current conditions only for v1.\n */\nexport const WeatherStatusSchema = z.object({\n /** Verbatim HA condition state (`sunny`, `cloudy`, `rainy`, …). Null\n * when no condition has been reported yet. */\n condition: z.string().nullable(),\n /** Current temperature in the reported unit. Null when not provided. */\n temperature: z.number().nullable(),\n /** Temperature unit string (e.g. `°C` / `°F`). Null when not provided. */\n temperatureUnit: z.string().nullable(),\n /** Relative humidity (0..100). Null when not provided. */\n humidity: z.number().min(0).max(100).nullable(),\n /** Barometric pressure in the reported unit. Null when not provided. */\n pressure: z.number().nullable(),\n /** Pressure unit string (e.g. `hPa` / `inHg`). Null when not provided. */\n pressureUnit: z.string().nullable(),\n /** Wind speed in the reported unit. Null when not provided. */\n windSpeed: z.number().nullable(),\n /** Wind-speed unit string (e.g. `km/h` / `mph`). Null when not provided. */\n windSpeedUnit: z.string().nullable(),\n /** Wind bearing in degrees (0..360, meteorological). Null when not provided. */\n windBearing: z.number().nullable(),\n /** Ms epoch when the slice was last updated. */\n lastFetchedAt: z.number(),\n})\n\nexport type WeatherStatus = z.infer<typeof WeatherStatusSchema>\n\nexport const weatherCapability = {\n name: 'weather',\n scope: 'device',\n deviceNative: true,\n mode: 'singleton',\n deviceTypes: [DeviceType.Weather],\n // Read-only — no service methods. Codegen still auto-injects `getStatus`\n // because `status` is set.\n methods: {},\n status: {\n schema: WeatherStatusSchema,\n kind: 'push',\n },\n /**\n * Runtime-state slice — mirrored by the kernel. The UI reads the\n * current conditions directly from the slice on each weather push.\n */\n runtimeState: WeatherStatusSchema,\n} as const satisfies CapabilityDefinition\n\nexport type IWeatherProvider = InferProvider<typeof weatherCapability>\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\n\n/**\n * Per-zone occupancy aggregation produced by the analytics frame\n * processor on every inference result. Covers the full combinatorial\n * matrix the operator UI needs: total objects everywhere, total\n * objects per zone, single class everywhere, single class per zone,\n * objects outside any zone.\n *\n * Counts are derived from the analytics tracker (tracked detections\n * with stable trackIds), not raw detector hits — this filters out\n * one-off detector flickers and gives counts that match what the user\n * sees on the live overlay.\n *\n * Overlap policy: a detection that intersects two zones counts in\n * BOTH zones' `byClass` and `totalObjects` (count-in-each). The\n * `frame` aggregate de-duplicates trivially since it's frame-wide.\n * `unzoned` counts only detections that landed in zero zones.\n */\nconst PerScopeBreakdownSchema = z.object({\n /** Total tracked objects in this scope (frame / zone / unzoned). */\n totalObjects: z.number().int().nonnegative(),\n /** Per-class count. Keys are macro class names (e.g. `person`, `car`). */\n byClass: z.record(z.string(), z.number().int().nonnegative()),\n})\n\nconst ZoneScopeBreakdownSchema = PerScopeBreakdownSchema.extend({\n zoneId: z.string(),\n zoneName: z.string(),\n /** TrackIds of objects currently inside this zone — for cross-reference\n * with the per-track detail panel and live overlay. */\n trackIds: z.array(z.string()).readonly(),\n})\n\nexport const CameraOccupancySnapshotSchema = z.object({\n /** Frame timestamp of the inference result that produced this snapshot. */\n ts: z.number().int(),\n /** Frame width/height in pixels — let the UI normalize bbox coords. */\n frameWidth: z.number().int().nonnegative(),\n frameHeight: z.number().int().nonnegative(),\n /** Per-zone breakdown — one entry per defined zone (user + onboard). */\n zones: z.array(ZoneScopeBreakdownSchema).readonly(),\n /** Frame-wide aggregate (everywhere, regardless of zone membership). */\n frame: PerScopeBreakdownSchema,\n /** Detections that landed outside every zone. Empty when no zones defined. */\n unzoned: PerScopeBreakdownSchema,\n})\nexport type CameraOccupancySnapshot = z.infer<typeof CameraOccupancySnapshotSchema>\nexport type ZoneScopeBreakdown = z.infer<typeof ZoneScopeBreakdownSchema>\nexport type PerScopeBreakdown = z.infer<typeof PerScopeBreakdownSchema>\n\n/**\n * Time-series resolution. The history methods return one bucket per\n * step over the requested range. Smaller resolutions cost more\n * memory + bandwidth; bound to discrete steps so caller cannot ask\n * for arbitrary fractional buckets.\n */\nconst HistoryResolutionEnum = z.enum(['minute', '5min', 'hour'])\nexport type HistoryResolution = z.infer<typeof HistoryResolutionEnum>\n\nconst HistoryRangeSchema = z.object({\n /** Range start (epoch ms, inclusive). */\n from: z.number().int(),\n /** Range end (epoch ms, inclusive). Defaults to \"now\" at query time. */\n to: z.number().int(),\n resolution: HistoryResolutionEnum,\n})\n\nconst HistoryPointSchema = z.object({\n /** Bucket midpoint (epoch ms). */\n ts: z.number().int(),\n /** Object count averaged over the bucket (rounded to nearest integer). */\n count: z.number().int().nonnegative(),\n})\nexport type HistoryPoint = z.infer<typeof HistoryPointSchema>\n\n/**\n * Zone Analytics capability — spatial occupancy aggregations over\n * tracked detections. Hosted by `addon-pipeline-analytics`.\n *\n * Live snapshot is mirrored into the `zone-occupancy` device-state\n * slice on every frame; the cap method `getCurrentSnapshot` is a\n * direct read for callers that don't want to subscribe.\n *\n * History methods are sourced from a 60-minute rolling in-memory\n * ring of frame-level samples (sub-second resolution). Queries\n * outside the ring window return empty arrays — durable storage\n * is a follow-up (Step 4b: persisted samples → SQL store).\n *\n * Every history method takes an optional `className` filter:\n * - omitted → bucket count includes ALL classes in scope\n * - present → bucket count restricted to that class\n *\n * The `getZoneHistory` / `getCameraHistory` / `getUnzonedHistory`\n * triple covers the three spatial scopes (per-zone, frame-wide,\n * outside-any-zone). Crossing them with `className?` gives the full\n * combinatorial coverage the operator UI requested.\n */\nexport const zoneAnalyticsCapability = {\n name: 'zone-analytics',\n scope: 'device',\n mode: 'singleton',\n deviceTypes: [DeviceType.Camera],\n methods: {\n /** Latest computed occupancy snapshot for this camera. Null when\n * the analytics pipeline hasn't seen a frame for this device yet\n * (no inference result emitted since boot or since binding was\n * activated). */\n getCurrentSnapshot: method(\n z.object({ deviceId: z.number() }),\n CameraOccupancySnapshotSchema.nullable(),\n ),\n /** Time-series object count inside one zone. `className` optional —\n * omit to count every class in the zone. */\n getZoneHistory: method(\n z.object({\n deviceId: z.number(),\n zoneId: z.string(),\n className: z.string().optional(),\n }).extend(HistoryRangeSchema.shape),\n z.array(HistoryPointSchema).readonly(),\n ),\n /** Time-series frame-wide object count (everywhere). */\n getCameraHistory: method(\n z.object({\n deviceId: z.number(),\n className: z.string().optional(),\n }).extend(HistoryRangeSchema.shape),\n z.array(HistoryPointSchema).readonly(),\n ),\n /** Time-series count of objects outside every zone. */\n getUnzonedHistory: method(\n z.object({\n deviceId: z.number(),\n className: z.string().optional(),\n }).extend(HistoryRangeSchema.shape),\n z.array(HistoryPointSchema).readonly(),\n ),\n },\n /**\n * Runtime-state slice — the latest occupancy snapshot mirrored by\n * the analytics frame processor on every inference result. Consumers\n * read via `device.state.zoneAnalytics.value` and stay in sync\n * automatically; the explicit `getCurrentSnapshot` cap method is\n * still useful for one-off polls without a subscription.\n */\n runtimeState: CameraOccupancySnapshotSchema,\n} as const satisfies CapabilityDefinition\n\nexport type IZoneAnalyticsProvider = InferProvider<typeof zoneAnalyticsCapability>\n\nexport {\n CameraOccupancySnapshotSchema as _CameraOccupancySnapshotSchema,\n HistoryResolutionEnum,\n HistoryPointSchema,\n HistoryRangeSchema,\n ZoneScopeBreakdownSchema,\n PerScopeBreakdownSchema,\n}\n","import { z } from 'zod'\n\n/**\n * Per-stage gating mode applied to the zones a rule references.\n *\n * - `include`: the rule contributes to a **whitelist** for its stage.\n * When at least one `include` rule fires for a stage, only entities\n * inside one of those zones pass that stage.\n * - `exclude`: the rule contributes to a **blacklist** for its stage.\n * Entities inside one of those zones are dropped at that stage.\n *\n * `monitor`-style observation (count without filtering) is not a rule\n * mode — zones without any matching rule are observed naturally by\n * `zone-analytics` (live snapshot + history), so an \"I just want to\n * count, not filter\" use case needs no rule at all.\n */\nexport const ZoneRuleModeEnum = z.enum(['include', 'exclude'])\nexport type ZoneRuleMode = z.infer<typeof ZoneRuleModeEnum>\n\n/**\n * Per-consumer rule that references existing zones (geometry) and\n * defines how a specific pipeline stage should treat them. Each\n * consumer addon owns its own `ZoneRule[]` array in its per-device\n * settings:\n *\n * - `addon-motion-wasm` → `motionZoneRules: ZoneRule[]` (motion stage)\n * - `addon-detection-pipeline` → `detectionZoneRules: ZoneRule[]` (detection stage)\n * - future: notification rules, audio gating, etc.\n *\n * One rule applies to N zones (`zoneIds[]`) so the operator can\n * express \"ignore motion in ALL of {garden, street}\" with a single\n * rule. `classFilter` narrows the rule to specific object classes —\n * \"drop person detections in the street, but keep cars\" is one\n * `exclude` rule with `classFilter: ['person']`.\n *\n * `enabled` is a soft toggle — the operator can keep the rule\n * configured but inert without deleting it.\n */\nexport const ZoneRuleSchema = z.object({\n /** Stable rule id — survives edits, used by the UI for diffing. */\n id: z.string(),\n /** Optional human-readable label rendered in the rule editor. */\n name: z.string().optional(),\n /** Zones this rule targets. The rule's `mode` applies to ALL\n * listed zones (OR-set: a detection in any one of them counts).\n * At least one zone id required — a rule with no targets is a\n * configuration mistake and the form validator rejects it. */\n zoneIds: z.array(z.string()).min(1).readonly(),\n mode: ZoneRuleModeEnum,\n /**\n * Class names this rule applies to. Empty / undefined ⇒ rule\n * applies to every class. Class strings match the `macroClass`\n * field on detections (e.g. `person`, `car`, `dog`).\n */\n classFilter: z.array(z.string()).readonly().optional(),\n /**\n * Minimum bbox/mask overlap (0–1) with any of the rule's zones\n * required to consider an entity \"in the zone\". Defaults to the\n * consumer's stage default when omitted. Kept for back-compat with\n * existing per-rule overrides; new operators pick the value via\n * `bboxInclusionPct` (operator-friendly 0–100). Whichever field is\n * set, the lower-level engine reads it as a 0–1 fraction.\n */\n overlapThreshold: z.number().min(0).max(1).optional(),\n /**\n * Operator-friendly version of `overlapThreshold` — the percentage\n * of the detection's bbox that must lie inside the zone for the\n * rule to match. Documented default is 85%; the engine substitutes\n * that when the field is omitted (kept optional so existing rules\n * stored without it stay valid).\n *\n * When BOTH `overlapThreshold` and `bboxInclusionPct` are set on a\n * rule, the engine prefers `bboxInclusionPct` because it's the\n * field exposed in the UI. Internally both feed the same gate.\n */\n bboxInclusionPct: z.number().min(0).max(100).optional(),\n /**\n * When `true` and a detection has a segmentation mask, use the\n * mask for overlap instead of the bbox. Detection-stage only;\n * motion rules ignore this field.\n */\n preferMask: z.boolean().optional(),\n /**\n * Soft-toggle: `false` disables the rule without deleting it.\n * Defaults to `true` so operators creating a rule via the UI\n * see it active immediately.\n */\n enabled: z.boolean().default(true),\n})\nexport type ZoneRule = z.infer<typeof ZoneRuleSchema>\n\n/**\n * Convenience array schema — used by addon device-settings\n * contributions and runtime payloads (e.g. `RunnerCameraConfig`).\n */\nexport const ZoneRulesArraySchema = z.array(ZoneRuleSchema).readonly()\nexport type ZoneRules = z.infer<typeof ZoneRulesArraySchema>\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\nimport { ZoneRuleSchema } from './schemas/zone-rule.js'\n\n/**\n * Stages a {@link ZoneRule} can apply to. Discriminator on the rules\n * cap so a single CRUD surface backs every consumer; each stage has\n * its own dev-state mirror slice (`motion-zone-rules`,\n * `detection-zone-rules`, …) so consumer addons subscribe independently.\n *\n * Extend the enum here when a new gating consumer comes online (audio\n * gating, alert filtering, …) — no other surface needs to change.\n */\nexport const ZoneRuleStageEnum = z.enum(['motion', 'detection'])\nexport type ZoneRuleStage = z.infer<typeof ZoneRuleStageEnum>\n\n/**\n * Zone rules capability — per-camera CRUD over the {@link ZoneRule}\n * arrays that decide how each pipeline stage uses the polygon zones.\n *\n * Hosted by `addon-pipeline-orchestrator` alongside the zones provider\n * so the operator has a single hub-side source of truth for both\n * geometry and behaviour. Per-stage rules are stored under the\n * `zoneRules.<stage>` key in the orchestrator's per-device store and\n * mirrored to the device-state slice `<stage>-zone-rules` on every\n * mutation; consumer addons (analytics, motion-wasm, pipeline-executor)\n * subscribe to that slice and refresh their gating without\n * round-tripping the cap.\n *\n * Sets are bulk-replace — the operator UI sends the new rule list\n * wholesale, so reordering / batch enable-toggle / drag-drop CRUD lives\n * naturally in the rule editor without per-rule mutation chatter.\n */\nexport const zoneRulesCapability = {\n name: 'zone-rules',\n scope: 'device',\n mode: 'singleton',\n deviceTypes: [DeviceType.Camera],\n methods: {\n /** Read the full rule list for a given stage (empty when no rules\n * are defined yet). */\n listRules: method(\n z.object({ deviceId: z.number(), stage: ZoneRuleStageEnum }),\n z.array(ZoneRuleSchema).readonly(),\n ),\n /** Bulk-replace the rule list for one stage. The provider validates\n * each entry against {@link ZoneRuleSchema} (zoneIds non-empty,\n * thresholds in range) and rejects the whole patch if any entry\n * is invalid — partial writes are a configuration footgun. */\n setRules: method(\n z.object({\n deviceId: z.number(),\n stage: ZoneRuleStageEnum,\n rules: z.array(ZoneRuleSchema).readonly(),\n }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n },\n /**\n * Runtime-state slice — both stages mirrored together so consumers\n * see one reactive handle (`device.state.zoneRules.value`) instead\n * of two. Bulk-replace mutations on either stage write the full\n * `{motion, detection}` shape, so subscribers always get the\n * complete current set. Consumers that only care about one stage\n * just read the matching property.\n */\n runtimeState: z.object({\n motion: z.array(ZoneRuleSchema).readonly(),\n detection: z.array(ZoneRuleSchema).readonly(),\n }),\n} as const satisfies CapabilityDefinition\n\nexport type IZoneRulesProvider = InferProvider<typeof zoneRulesCapability>\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\nimport { SourceInfoSchema } from '../device/source-info.js'\n\nconst ProviderStatusSchema = z.object({\n connected: z.boolean(),\n deviceCount: z.number(),\n error: z.string().optional(),\n})\n\nconst DiscoveredDeviceSchema = z.object({\n externalId: z.string(),\n name: z.string(),\n type: z.string(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n})\n\n/**\n * Candidate handed back from discovery and accepted by\n * `adoptDiscoveredDevice`. Shape mirrors the in-process\n * `DiscoveredDevice` interface used by `DeviceDiscovery`.\n */\nconst DiscoveryCandidateSchema = z.object({\n stableId: z.string(),\n type: z.enum(DeviceType),\n suggestedName: z.string(),\n prefilledConfig: z.record(z.string(), z.unknown()),\n /**\n * Optional upstream-system identity (HA entity_id, vendor MAC, …).\n * Discovery pre-populates this for systems that know the upstream\n * identity ahead of adoption. Rendering metadata (unit, precision)\n * flows live through the cap STATUS SLICE after adoption.\n */\n sourceInfo: SourceInfoSchema.optional(),\n})\n\n/**\n * Flat device summary returned by `createDevice` / `adoptDiscoveredDevice`.\n * Mirrors `toDeviceShape()` output in `device-management.router.ts` so the\n * tRPC layer can pass it through without reshaping.\n */\nconst DeviceSummarySchema = z.object({\n id: z.number(),\n stableId: z.string(),\n addonId: z.string(),\n type: z.string(),\n name: z.string(),\n parentDeviceId: z.number().nullable(),\n online: z.boolean(),\n features: z.array(z.string()),\n config: z.record(z.string(), z.unknown()),\n /** Optional upstream-system identity (dispatch key + system tag).\n * See `SourceInfo`. Present when the device has a non-synthetic\n * source identifier (HA entities, vendor MAC, …); omitted when the\n * synthetic backfill is in effect. */\n sourceInfo: SourceInfoSchema.optional(),\n})\n\n/**\n * Result of a live field test (e.g. probing an RTSP URL during device\n * creation). Matches the UI-side `FieldProbeResult` in\n * `interfaces/config-ui.ts` — the admin `FormBuilder` renders the\n * returned `labels` as chips next to the input.\n */\nconst FieldProbeResultSchema = z.object({\n status: z.enum(['ok', 'error']),\n labels: z.array(z.string()).optional(),\n error: z.string().optional(),\n})\n\n/**\n * The output of `getChildCreationSchema` is a UI schema tree. We store\n * it as `unknown` at the capability layer — the router just passes it\n * through and the admin UI renders it via `FormBuilder`. The actual\n * type is `ConfigUISchema` (see `packages/types/src/interfaces/config-ui.ts`),\n * but we deliberately avoid a Zod mirror because the union is large and\n * not meant for runtime validation at this seam.\n */\nconst CreationSchemaOutputSchema = z.unknown()\n\nexport const deviceProviderCapability = {\n name: 'device-provider',\n scope: 'system',\n mode: 'collection',\n methods: {\n // ── Lifecycle + introspection ─────────────────────────────────────\n start: method(z.void(), z.void(), { kind: 'mutation' }),\n stop: method(z.void(), z.void(), { kind: 'mutation' }),\n getStatus: method(z.void(), ProviderStatusSchema),\n getDevices: method(z.void(), z.array(z.object({\n id: z.string(),\n name: z.string(),\n type: z.string(),\n }))),\n\n // ── Discovery + adoption (optional — see supportsDiscovery) ──────\n supportsDiscovery: method(z.object({}), z.boolean()),\n discoverDevices: method(\n z.object({}),\n z.array(DiscoveryCandidateSchema),\n { kind: 'mutation', auth: 'admin' },\n ),\n adoptDiscoveredDevice: method(\n z.object({ candidate: DiscoveryCandidateSchema }),\n DeviceSummarySchema,\n { kind: 'mutation', auth: 'admin' },\n ),\n\n // ── Manual creation (optional — see supportsManualCreation) ──────\n supportsManualCreation: method(z.object({}), z.boolean()),\n /**\n * Fetch the creation form schema for a given DeviceType. Returns\n * `null` when the provider does not support manually creating\n * devices of that type. The output is a `ConfigUISchema` — the\n * router type-asserts it at the boundary.\n */\n getChildCreationSchema: method(\n z.object({ type: z.enum(DeviceType) }),\n CreationSchemaOutputSchema,\n ),\n createDevice: method(\n z.object({\n type: z.enum(DeviceType),\n config: z.record(z.string(), z.unknown()),\n }),\n DeviceSummarySchema,\n { kind: 'mutation', auth: 'admin' },\n ),\n /**\n * Test a single field in the creation form before the device has\n * been persisted. Typical use: probing an RTSP URL entered by the\n * user. Providers that don't support field probing return\n * `{ success: true, message: 'Field test not supported' }`.\n *\n * `formValues` is the live snapshot of every field in the form at\n * the moment the user clicked Test — useful for probes that depend\n * on multiple fields together (e.g. Reolink autodetect needs host\n * + credentials + UID + transport mode in a single call). Optional\n * for backwards compatibility; providers free to ignore it.\n */\n testCreationField: method(\n z.object({\n type: z.enum(DeviceType),\n key: z.string(),\n value: z.unknown(),\n formValues: z.record(z.string(), z.unknown()).optional(),\n }),\n FieldProbeResultSchema,\n { kind: 'mutation', auth: 'admin' },\n ),\n },\n} as const satisfies CapabilityDefinition\n\nexport type IDeviceProvider = InferProvider<typeof deviceProviderCapability>\n\nexport {\n ProviderStatusSchema,\n DiscoveredDeviceSchema,\n DiscoveryCandidateSchema,\n DeviceSummarySchema,\n FieldProbeResultSchema,\n}\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\n\n// ── Zod schemas for ConfigUISchemaWithValues ─────────────────────────\n//\n// Same loose field typing as the addons.router.ts schemas — the\n// polymorphic discriminated-union schema would explode to ~14 variants\n// with nested group recursion. `z.any()` keeps runtime validation on\n// the outer structure while preserving assignability to the domain type.\n\nconst ConfigTabDeclarationSchema = z.object({\n id: z.string(),\n label: z.string(),\n icon: z.string(),\n order: z.number().optional(),\n})\n\nconst ConfigSectionWithValuesSchema = z.object({\n id: z.string(),\n title: z.string(),\n description: z.string().optional(),\n style: z.enum(['card', 'accordion']).optional(),\n defaultCollapsed: z.boolean().optional(),\n columns: z.union([z.literal(1), z.literal(2), z.literal(3), z.literal(4)]).optional(),\n tab: z.string().optional(),\n // Hoist the section into a top-level device tab. DeviceDetail\n // discovers these from the aggregate and renders one tab per unique\n // `tab` id; the default `'settings'` keeps the section under Config.\n location: z.enum(['settings', 'top-tab']).optional(),\n order: z.number().optional(),\n fields: z.array(z.any()),\n})\n\nconst SettingsSchemaWithValuesSchema = z.object({\n tabs: z.array(ConfigTabDeclarationSchema).optional(),\n sections: z.array(ConfigSectionWithValuesSchema),\n})\n\n/** Patch object — keys are field names, values are the new field values. */\nconst SettingsPatchSchema = z.record(z.string(), z.unknown())\n\n/** Standard success response for update operations. */\nconst SettingsUpdateResultSchema = z.object({\n success: z.literal(true),\n})\n\n/**\n * addon-settings — singleton gateway for three-level addon settings.\n *\n * Works like `device-manager`: a single hub-side provider that resolves\n * `addonId` to the target addon and delegates the call. For hub-local\n * addons the call is direct; for remote agents it proxies via the\n * per-addon Moleculer service.\n *\n * Replaces the `$addonHost` Moleculer service. Transport transparency\n * is handled by the provider implementation — callers (admin UI, other\n * addons via `ctx.api`) never know which node hosts the target addon.\n *\n * Three levels:\n * - **addon**: addon-scoped settings (installation config, API keys, …)\n * - **global**: settings applied to all devices by default\n * - **device**: per-device overrides\n *\n * Optional `nodeId` allows explicit node targeting. When absent the\n * provider resolves the addon's host node automatically.\n */\n/**\n * `addon-settings` is a **hub-centric** cap: the hub hosts the single\n * provider, and `nodeId` in the input is data for the hub provider's\n * internal dispatcher, not a routing hint for the cap-router. See\n * `CapabilityDefinition.nodeIdMode` for the contract.\n */\nexport const addonSettingsCapability = {\n name: 'addon-settings',\n scope: 'system',\n mode: 'singleton',\n nodeIdMode: 'data',\n methods: {\n // ── Global-level settings ─────────────────────────────────────────\n //\n // `overlay` — optional preview overlay. When present, the provider\n // hydrates the schema as if the overlay were merged on top of the\n // persisted store (without writing anything). Used by override-mode\n // UIs (benchmark tabs) to get cascade-aware option lists when the\n // operator tweaks an upstream field — e.g. changing engineRuntime\n // from 'python' to 'node' refetches with `overlay: {engineRuntime:\n // 'node'}` so the backend/device dropdowns re-derive.\n getGlobalSettings: method(\n z.object({\n addonId: z.string(),\n nodeId: z.string().optional(),\n overlay: z.record(z.string(), z.unknown()).optional(),\n cap: z.string().optional(),\n }),\n SettingsSchemaWithValuesSchema.nullable(),\n ),\n updateGlobalSettings: method(\n z.object({ addonId: z.string(), nodeId: z.string().optional(), patch: SettingsPatchSchema }),\n SettingsUpdateResultSchema,\n { kind: 'mutation', auth: 'admin' },\n ),\n\n // ── Device-level settings ─────────────────────────────────────────\n getDeviceSettings: method(\n z.object({ addonId: z.string(), deviceId: z.number(), nodeId: z.string().optional() }),\n SettingsSchemaWithValuesSchema.nullable(),\n ),\n updateDeviceSettings: method(\n z.object({ addonId: z.string(), deviceId: z.number(), nodeId: z.string().optional(), patch: SettingsPatchSchema }),\n SettingsUpdateResultSchema,\n { kind: 'mutation', auth: 'admin' },\n ),\n },\n} as const satisfies CapabilityDefinition\n\nexport type IAddonSettingsProvider = InferProvider<typeof addonSettingsCapability>\n\nexport {\n SettingsSchemaWithValuesSchema,\n ConfigSectionWithValuesSchema,\n ConfigTabDeclarationSchema,\n SettingsPatchSchema,\n SettingsUpdateResultSchema,\n}\n","/**\n * Alerts capability — collection-based internal alert system.\n *\n * Multiple providers can register. Each provider filters by EventBus category\n * and creates/updates alerts. The built-in Alert Center addon persists alerts\n * in the DB and serves them to the admin UI.\n */\n\nimport { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\n\n// ── Alert schemas ───────────────────────────────────────────────────\n\nexport const AlertSeveritySchema = z.enum(['info', 'success', 'warning', 'error'])\n\nexport const AlertStatusSchema = z.enum(['active', 'in-progress', 'completed', 'failed', 'dismissed'])\n\nexport const AlertSourceSchema = z.object({\n type: z.string(),\n id: z.string(),\n})\n\nexport const AlertSchema = z.object({\n id: z.string(),\n category: z.string(),\n severity: AlertSeveritySchema,\n title: z.string(),\n message: z.string(),\n status: AlertStatusSchema,\n progress: z.number().optional(),\n read: z.boolean(),\n createdAt: z.number(),\n updatedAt: z.number(),\n source: AlertSourceSchema.optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n})\n\n// ── Inferred types ─────────────────────────────────────────────────\n\nexport type AlertSeverity = z.infer<typeof AlertSeveritySchema>\nexport type AlertStatus = z.infer<typeof AlertStatusSchema>\nexport type Alert = z.infer<typeof AlertSchema>\n\n// ── Capability definition ──────────────────────────────────────────\n\nexport const alertsCapability = {\n name: 'alerts',\n scope: 'system',\n mode: 'singleton',\n methods: {\n emit: method(AlertSchema, z.void(), { kind: 'mutation' }),\n update: method(\n z.object({ alertId: z.string(), patch: AlertSchema.partial() }),\n z.void(),\n { kind: 'mutation' },\n ),\n list: method(\n z.object({ unreadOnly: z.boolean().optional(), limit: z.number().optional() }).optional(),\n z.array(AlertSchema).readonly(),\n ),\n getUnreadCount: method(z.void(), z.number()),\n markRead: method(z.object({ alertId: z.string() }), z.void(), { kind: 'mutation' }),\n markAllRead: method(z.void(), z.void(), { kind: 'mutation' }),\n dismiss: method(z.object({ alertId: z.string() }), z.void(), { kind: 'mutation' }),\n },\n} as const satisfies CapabilityDefinition\n\nexport type IAlertsProvider = InferProvider<typeof alertsCapability>\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport {\n StorageLocationSchema,\n StorageLocationRefSchema,\n StorageLocationTypeSchema,\n} from '../interfaces/storage-location.js'\nimport { StorageLocationDeclarationSchema } from '../interfaces/storage-location-declaration.js'\n\n// One entry of the `listProviders` output. Mirrors `ProviderInfoSchema` in\n// storage-provider.cap.ts: a discriminated union on `shouldSaveDiskSpace` so\n// the disk-space invariant (true ⇒ number, false ⇒ null) is enforced here too.\nconst ProviderListEntrySchema = z.discriminatedUnion('shouldSaveDiskSpace', [\n z.object({\n providerId: z.string().min(1),\n displayName: z.string().min(1),\n configSchema: z.unknown(),\n shouldSaveDiskSpace: z.literal(true),\n minFreePercent: z.number().min(0).max(100),\n }),\n z.object({\n providerId: z.string().min(1),\n displayName: z.string().min(1),\n configSchema: z.unknown(),\n shouldSaveDiskSpace: z.literal(false),\n minFreePercent: z.literal(null),\n }),\n])\n\n/**\n * `storage` — singleton consumer-facing capability owned by the\n * `storage-orchestrator` builtin (Task 4 of the storage-unification\n * refactor). All file I/O across the system flows through this cap;\n * the orchestrator resolves each `location` ref to a concrete\n * `StorageLocation` record and dispatches to the matching\n * `storage-provider` registrant.\n *\n * The `location` parameter on every primitive is a `StorageLocationRef`\n * — either a bare `StorageLocationType` (e.g. `'backups'`, resolves to\n * the default of that type) or a fully-qualified id (`'backups:nas-01'`,\n * addresses a specific instance). Both forms are normalised inside the\n * orchestrator's `resolveRef(ref)` step.\n *\n * Mode: `singleton` (was `collection` pre-Task-3). The cap-router mount\n * uses `requireSingleton(reg, 'storage')` — pointing at the orchestrator\n * once it lands.\n */\nexport const storageCapability = {\n name: 'storage',\n scope: 'system',\n mode: 'singleton',\n methods: {\n // ── Small-file primitives ────────────────────────────────────────\n // `location` is a ref (type or fully-qualified id). The orchestrator\n // resolves the ref to a concrete `StorageLocation` and dispatches.\n resolve: method(\n z.object({ location: StorageLocationRefSchema, relativePath: z.string() }),\n z.string(),\n ),\n write: method(\n z.object({ location: StorageLocationRefSchema, relativePath: z.string(), data: z.instanceof(Uint8Array) }),\n z.void(),\n { kind: 'mutation' },\n ),\n read: method(\n z.object({ location: StorageLocationRefSchema, relativePath: z.string() }),\n z.instanceof(Uint8Array),\n ),\n exists: method(\n z.object({ location: StorageLocationRefSchema, relativePath: z.string() }),\n z.boolean(),\n ),\n list: method(\n z.object({ location: StorageLocationRefSchema, prefix: z.string().optional() }),\n z.array(z.string()).readonly(),\n ),\n delete: method(\n z.object({ location: StorageLocationRefSchema, relativePath: z.string() }),\n z.void(),\n { kind: 'mutation' },\n ),\n getAvailableSpace: method(\n z.object({ location: StorageLocationRefSchema }),\n z.number().nullable(),\n ),\n\n // ── Chunked I/O ──────────────────────────────────────────────────\n // Same protocol as `storage-provider` but on the consumer side.\n // Sessions are owned by the orchestrator: it forwards each chunk\n // to the provider that backs the resolved location.\n beginUpload: method(\n z.object({ location: StorageLocationRefSchema, relativePath: z.string(), sizeBytes: z.number().optional() }),\n z.object({ uploadId: z.string() }),\n { kind: 'mutation' },\n ),\n writeChunk: method(\n z.object({ uploadId: z.string(), offset: z.number(), data: z.instanceof(Uint8Array) }),\n z.void(),\n { kind: 'mutation' },\n ),\n finalizeUpload: method(z.object({ uploadId: z.string() }), z.void(), { kind: 'mutation' }),\n abortUpload: method(z.object({ uploadId: z.string() }), z.void(), { kind: 'mutation' }),\n beginDownload: method(\n z.object({ location: StorageLocationRefSchema, relativePath: z.string() }),\n z.object({ downloadId: z.string(), sizeBytes: z.number() }),\n { kind: 'mutation' },\n ),\n readChunk: method(\n z.object({ downloadId: z.string(), offset: z.number(), length: z.number() }),\n z.instanceof(Uint8Array),\n ),\n endDownload: method(z.object({ downloadId: z.string() }), z.void(), { kind: 'mutation' }),\n\n // ── Location management ─────────────────────────────────────────\n // The orchestrator's authoritative surface for the admin-UI's\n // storage-locations page. Operators add/edit/test/remove location\n // instances here; `upsertLocation` and `deleteLocation` require\n // superAdmin auth.\n listLocations: method(\n z.object({ type: StorageLocationTypeSchema.optional() }),\n z.array(StorageLocationSchema).readonly(),\n ),\n getDefaultLocation: method(\n z.object({ type: StorageLocationTypeSchema }),\n StorageLocationSchema.nullable(),\n ),\n // The admin-UI Data screen renders one group per declared location\n // (header = `displayName`, \"+ Add\" shown only for `cardinality:\n // 'multi'`). Source: the kernel-aggregated `storageLocations`\n // declarations injected into the orchestrator via `setRegistry`.\n // No closed type enum in the UI — the screen is fully declaration-\n // driven.\n listLocationDeclarations: method(\n z.void(),\n z.array(StorageLocationDeclarationSchema).readonly(),\n ),\n upsertLocation: method(\n StorageLocationSchema.omit({ createdAt: true, updatedAt: true }),\n StorageLocationSchema,\n { kind: 'mutation', auth: 'admin' },\n ),\n deleteLocation: method(\n z.object({ id: z.string() }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n testLocation: method(\n z.object({ id: z.string() }),\n z.object({ ok: z.boolean(), error: z.string().optional() }),\n { auth: 'admin' },\n ),\n\n // ── Provider discovery ──────────────────────────────────────────\n // The admin-UI's \"Add location\" wizard shows one entry per\n // registered `storage-provider` collection cap. Each entry is the\n // provider's `getProviderInfo()` blob — stable, addon-driven, no\n // hard-coded list in the UI. The orchestrator gathers them by\n // walking the registry on every call (cheap; the list almost\n // never changes after boot).\n listProviders: method(\n z.void(),\n z.array(ProviderListEntrySchema).readonly(),\n ),\n\n // Validate a candidate config against a provider BEFORE persisting.\n // Used by the wizard so operators can preflight a connection\n // (e.g. SFTP credentials, S3 bucket access) without leaving an\n // orphan record behind on failure.\n testConfig: method(\n z.object({\n providerId: z.string(),\n config: z.record(z.string(), z.unknown()),\n }),\n z.object({ ok: z.boolean(), error: z.string().optional() }),\n { auth: 'admin' },\n ),\n },\n} as const satisfies CapabilityDefinition\n\nexport type IStorageCapProvider = InferProvider<typeof storageCapability>\n\nexport { StorageLocationTypeSchema }\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { StorageLocationSchema } from '../interfaces/storage-location.js'\n\n// ── Provider self-description ───────────────────────────────────────\n//\n// `getProviderInfo` returns a static description that the orchestrator\n// hands to the admin-UI's \"Add location\" wizard. Operators see one\n// entry per provider — its `displayName` and the `configSchema` that\n// drives the wizard form.\n//\n// `configSchema` mirrors `ConfigUISchemaWithValues` (sections[] +\n// optional tabs[]). Typed here as `z.unknown()` to avoid a hard import\n// from `interfaces/config-ui.ts` (which isn't a Zod schema). The admin\n// UI casts it back to the concrete TS interface at consumption time.\n\n// Disk-space management policy, declared per provider implementation so every\n// location resolves to a concrete value the recorder can always read. Modelled\n// as a discriminated union on `shouldSaveDiskSpace` so the invariant is\n// enforced at the schema level (and narrows downstream):\n// true → finite volume, `minFreePercent` is a concrete 0..100 threshold.\n// false → no local free-space concept (remote/object store), `minFreePercent`\n// is `null`.\nconst ProviderInfoSchema = z.discriminatedUnion('shouldSaveDiskSpace', [\n z.object({\n providerId: z.string().min(1),\n displayName: z.string().min(1),\n configSchema: z.unknown(),\n // Provider manages a finite volume → declares a default free-space threshold.\n shouldSaveDiskSpace: z.literal(true),\n minFreePercent: z.number().min(0).max(100),\n }),\n z.object({\n providerId: z.string().min(1),\n displayName: z.string().min(1),\n configSchema: z.unknown(),\n // No local free-space concept (remote/object store) → no threshold.\n shouldSaveDiskSpace: z.literal(false),\n minFreePercent: z.literal(null),\n }),\n])\n\nconst TestLocationResultSchema = z.object({\n ok: z.boolean(),\n error: z.string().optional(),\n})\n\n// ── Chunked upload protocol ─────────────────────────────────────────\n//\n// Large archives (backup snapshots, recordings) flow through a session:\n// beginUpload(location, relativePath, sizeBytes?) → uploadId\n// writeChunk(uploadId, offset, data) × N\n// finalizeUpload(uploadId) // commit\n// abortUpload(uploadId) // discard\n//\n// Each chunk is self-describing (`offset`) so providers can dedupe or\n// resume on disconnect. Providers SHOULD enforce a max chunk size and\n// reject malformed offsets.\n\nconst BeginUploadInputSchema = z.object({\n location: StorageLocationSchema,\n relativePath: z.string(),\n sizeBytes: z.number().optional(),\n})\nconst BeginUploadResultSchema = z.object({ uploadId: z.string() })\nconst WriteChunkInputSchema = z.object({\n uploadId: z.string(),\n offset: z.number(),\n data: z.instanceof(Uint8Array),\n})\nconst FinalizeUploadInputSchema = z.object({ uploadId: z.string() })\nconst AbortUploadInputSchema = z.object({ uploadId: z.string() })\n\n// ── Chunked download protocol ───────────────────────────────────────\n// Symmetric to upload: open-by-path returns a session + total size,\n// reader pulls byte ranges, end closes the session.\n\nconst BeginDownloadInputSchema = z.object({\n location: StorageLocationSchema,\n relativePath: z.string(),\n})\nconst BeginDownloadResultSchema = z.object({\n downloadId: z.string(),\n sizeBytes: z.number(),\n})\nconst ReadChunkInputSchema = z.object({\n downloadId: z.string(),\n offset: z.number(),\n length: z.number(),\n})\nconst EndDownloadInputSchema = z.object({ downloadId: z.string() })\n\n/**\n * storage-provider — collection capability for backend-specific storage\n * drivers.\n *\n * Multiple addons register against this cap (filesystem-storage,\n * sftp-storage, s3-storage, webdav-storage, …). The orchestrator\n * (singleton `storage` cap, owned by the storage-orchestrator builtin)\n * routes each call to the right provider by looking up\n * `location.providerId` and dispatching the inline `location` arg.\n *\n * Design notes:\n * - Stateless dispatch: every primitive carries its own `location`,\n * so providers don't keep per-location state across calls.\n * - Session-scoped uploads/downloads: the `uploadId`/`downloadId`\n * handles let the provider hold open file descriptors / streams\n * between chunks while keeping the cap surface RPC-friendly.\n * - `internal: true` — this cap is consumed only by the storage\n * orchestrator. Public consumers go through the `storage`\n * singleton cap; they never see `storage-provider` directly.\n */\nexport const storageProviderCapability = {\n name: 'storage-provider',\n scope: 'system',\n mode: 'collection',\n internal: true,\n methods: {\n /** Self-description for the \"Add location\" wizard. */\n getProviderInfo: method(z.void(), ProviderInfoSchema),\n\n /** Validate config + probe connectivity. Called on add and on edit. */\n testLocation: method(\n z.object({ config: z.record(z.string(), z.unknown()) }),\n TestLocationResultSchema,\n { auth: 'admin' },\n ),\n\n // ── Small-file primitives ────────────────────────────────────────\n // The location is passed inline so the orchestrator dispatches\n // without provider-side location state.\n resolve: method(\n z.object({ location: StorageLocationSchema, relativePath: z.string() }),\n z.string(),\n ),\n write: method(\n z.object({ location: StorageLocationSchema, relativePath: z.string(), data: z.instanceof(Uint8Array) }),\n z.void(),\n { kind: 'mutation' },\n ),\n read: method(\n z.object({ location: StorageLocationSchema, relativePath: z.string() }),\n z.instanceof(Uint8Array),\n ),\n exists: method(\n z.object({ location: StorageLocationSchema, relativePath: z.string() }),\n z.boolean(),\n ),\n list: method(\n z.object({ location: StorageLocationSchema, prefix: z.string().optional() }),\n z.array(z.string()).readonly(),\n ),\n delete: method(\n z.object({ location: StorageLocationSchema, relativePath: z.string() }),\n z.void(),\n { kind: 'mutation' },\n ),\n getAvailableSpace: method(\n z.object({ location: StorageLocationSchema }),\n z.number().nullable(),\n ),\n\n // ── Chunked upload ──────────────────────────────────────────────\n beginUpload: method(BeginUploadInputSchema, BeginUploadResultSchema, { kind: 'mutation' }),\n writeChunk: method(WriteChunkInputSchema, z.void(), { kind: 'mutation' }),\n finalizeUpload: method(FinalizeUploadInputSchema, z.void(), { kind: 'mutation' }),\n abortUpload: method(AbortUploadInputSchema, z.void(), { kind: 'mutation' }),\n\n // ── Chunked download ────────────────────────────────────────────\n beginDownload: method(BeginDownloadInputSchema, BeginDownloadResultSchema, { kind: 'mutation' }),\n readChunk: method(ReadChunkInputSchema, z.instanceof(Uint8Array)),\n endDownload: method(EndDownloadInputSchema, z.void(), { kind: 'mutation' }),\n },\n} as const satisfies CapabilityDefinition\n\nexport type IStorageProviderImpl = InferProvider<typeof storageProviderCapability>\n\nexport {\n ProviderInfoSchema,\n TestLocationResultSchema,\n BeginUploadInputSchema,\n BeginUploadResultSchema,\n WriteChunkInputSchema,\n FinalizeUploadInputSchema,\n AbortUploadInputSchema,\n BeginDownloadInputSchema,\n BeginDownloadResultSchema,\n ReadChunkInputSchema,\n EndDownloadInputSchema,\n}\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\n\n/**\n * `storage-evictable` — implemented by any addon that owns evictable data on a\n * storage location (recordings, event clips, thumbnails, …).\n *\n * The core `StoragePressureManager` (in storage-orchestrator) owns the TRIGGER:\n * it monitors free space per location and, on breach of a location's\n * `minFreePercent`, asks each evictable provider to free a share of the deficit.\n * The provider decides WHAT is expendable and does the deletion itself — core\n * never deletes data it doesn't understand. This inverts control so disk-space\n * arbitration is one cross-consumer concern, not re-implemented per addon.\n *\n * `internal: true` — consumed only by the orchestrator's pressure manager, never\n * a public client surface.\n */\n\nconst EvictableUsageSchema = z.object({\n /** Bytes this provider currently holds on the location (0 if none). */\n bytes: z.number().int().nonnegative(),\n})\nexport type EvictableUsage = z.infer<typeof EvictableUsageSchema>\n\nconst EvictResultSchema = z.object({\n /** Bytes actually reclaimed (only successfully-deleted data counts). */\n reclaimedBytes: z.number().int().nonnegative(),\n /** True when the provider has nothing left it is willing to drop on this location. */\n exhausted: z.boolean(),\n})\nexport type EvictResult = z.infer<typeof EvictResultSchema>\n\nexport const storageEvictableCapability = {\n name: 'storage-evictable',\n scope: 'system',\n mode: 'collection',\n internal: true,\n methods: {\n /** Bytes this provider holds on the given location — drives proportional fan-out. */\n getEvictableUsage: method(\n z.object({ locationId: z.string() }),\n EvictableUsageSchema,\n ),\n /**\n * Free approximately `targetBytes` of this provider's OWN least-valuable\n * data on the location (oldest footage, expired clips, …). Returns what it\n * actually reclaimed + whether it is now exhausted.\n */\n evict: method(\n z.object({ locationId: z.string(), targetBytes: z.number().int().positive() }),\n EvictResultSchema,\n { kind: 'mutation' },\n ),\n },\n} as const satisfies CapabilityDefinition\n\nexport type IStorageEvictableProvider = InferProvider<typeof storageEvictableCapability>\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\n\n/**\n * Per-destination metadata returned by `backup-destination.listDestinations`.\n * Defined here (not in `backup-destination.cap.ts`) because both caps need\n * it and `backup` is the foundation — the destination cap imports from us.\n */\n/**\n * Provider-side destination metadata. The addon returns a SHORT id\n * (`subId`) — orchestrator-internal-only routing prepends the addon's\n * manifest id to produce the externally-visible globally-unique id.\n *\n * Why split: the addon shouldn't have to know its own manifest id.\n * That id is owned by `package.json` and the kernel's registry; making\n * the addon repeat it leaks framework state into addon code and\n * breaks if the manifest is ever renamed.\n */\nconst BackupSubDestinationInfoSchema = z.object({\n /**\n * Sub-id within this addon. Convention `default` for single-\n * destination addons; addons that host many (S3 with N buckets)\n * pick stable per-bucket strings. The orchestrator stitches\n * `<manifestId>:<subId>` for the wire format.\n */\n subId: z.string(),\n displayName: z.string(),\n description: z.string().optional(),\n kind: z.string(),\n triggerSupported: z.boolean(),\n restoreSupported: z.boolean(),\n})\n\n/**\n * Orchestrator-side destination metadata. The orchestrator computes\n * `id = <addonId>:<subId>` from its provider lookup so consumers\n * (admin UI, restore flow) see one canonical key.\n *\n * Phase 4 (admin UI redesign) adds the per-destination policy fields\n * (`enabled`, `retentionCount`, `label`) so the destinations table can\n * render the joined view without a follow-up round-trip. The backend\n * already joins these in `listDestinations` — we now surface them on\n * the wire.\n *\n * `lastSuccessAt` / `lastSuccessSizeBytes` are computed from each\n * location's `manifests.json` (newest archive). Optional — locations\n * with no archives yet leave them undefined.\n */\nconst BackupDestinationInfoSchema = BackupSubDestinationInfoSchema.extend({\n /** `<addonId>:<subId>` — globally-unique dispatch key. */\n id: z.string(),\n /**\n * Manifest id of the owning addon. The Settings button on the\n * destination card opens that addon's `globalSettingsSchema` panel.\n */\n addonId: z.string(),\n /** Operator-toggled enable flag from the destination-policy table. */\n enabled: z.boolean(),\n /** Operator-defined retention count (archives kept per destination). */\n retentionCount: z.number(),\n /** Operator-defined display label (overrides storage location displayName). */\n label: z.string().optional(),\n /** Newest-archive timestamp from `manifests.json`, or undefined. */\n lastSuccessAt: z.number().optional(),\n /** Newest-archive size from `manifests.json`, or undefined. */\n lastSuccessSizeBytes: z.number().optional(),\n /** Per-destination cron expression. Empty = manual-only (no schedule). */\n cron: z.string().optional(),\n /** ms-epoch of next computed firing for this destination's cron, if any. */\n nextRunAt: z.number().optional(),\n /** ms-epoch of last successful scheduled run (mirrors policy.lastRunAt). */\n lastRunAt: z.number().optional(),\n})\n\n/**\n * Per-archive entry returned by `backup.listArchives({ destinationId })`.\n * Same shape the destination drill-in renders. Sourced from the per-\n * location `manifests.json` (no per-archive tarball read required).\n */\nconst BackupArchiveEntrySchema = z.object({\n id: z.string(),\n filename: z.string(),\n createdAt: z.number(),\n sizeBytes: z.number(),\n label: z.string().optional(),\n /** Top-level locations included in the archive (db, addons, tls, …). */\n locations: z.array(z.string()).readonly(),\n})\n\nconst BackupEntrySchema = z.object({\n id: z.string(),\n /** Addon id of the destination that owns this backup (e.g. `local-backup`, `s3-backup`). */\n destinationId: z.string().optional(),\n label: z.string().optional(),\n createdAt: z.number(),\n sizeBytes: z.number(),\n locations: z.array(z.string()).optional(),\n})\n\nconst ArchiveEntrySchema = z.object({\n path: z.string(),\n kind: z.enum(['file', 'dir', 'symlink']),\n sizeBytes: z.number(),\n mtime: z.number(),\n})\n\nconst ArchiveManifestSchema = z.object({\n archiveVersion: z.literal(1),\n createdAt: z.number(),\n dataDir: z.string(),\n locations: z.array(z.string()),\n entries: z.array(ArchiveEntrySchema),\n totalBytes: z.number(),\n totalFiles: z.number(),\n})\n\nconst LocationStatSchema = z.object({\n name: z.string(),\n sizeBytes: z.number(),\n fileCount: z.number(),\n present: z.boolean(),\n})\n\n/**\n * backup — singleton capability for backup management.\n *\n * Implemented by `local-backup` addon. Future providers (S3, rsync)\n * can replace it by registering the same capability.\n */\nexport const backupCapability = {\n name: 'backup',\n scope: 'system',\n mode: 'singleton',\n methods: {\n /**\n * Flat aggregate of every destination across every registered\n * `backup-destination` provider. This is the orchestrator-side\n * surface; it expands per-addon `listDestinations()` results into\n * one list the UI can render directly.\n */\n listDestinations: method(\n z.void(),\n z.array(BackupDestinationInfoSchema).readonly(),\n { auth: 'admin' },\n ),\n /**\n * Trigger a backup. Without `destinations` the orchestrator fans\n * out to every destination flagged as enabled in the routing\n * config; with it, only the listed addons receive the archive.\n */\n trigger: method(\n z.object({\n /** Subset of registered `backup-destination` addon ids to write to. */\n destinations: z.array(z.string()).optional(),\n locations: z.array(z.string()).optional(),\n label: z.string().optional(),\n }).optional(),\n z.array(BackupEntrySchema).readonly(),\n { kind: 'mutation', auth: 'admin' },\n ),\n /** Union of every destination's archives, each tagged with `destinationId`. */\n list: method(z.void(), z.array(BackupEntrySchema).readonly(), { auth: 'admin' }),\n /**\n * Pre-backup snapshot of the well-known locations on disk — sizes\n * + file counts. Powers the opt-in checklist that lets the\n * operator pick which subsections of state get archived.\n */\n listLocations: method(z.void(), z.array(LocationStatSchema).readonly(), { auth: 'admin' }),\n /**\n * Read the embedded `.camstack-backup-manifest.json` from a\n * previously-created archive. The manifest carries the full\n * file/dir listing with sizes + mtimes — the readdir snapshot\n * the UI shows in the \"Contents\" panel. Returns `null` when the\n * archive predates manifests (created before this feature\n * shipped).\n */\n getEntries: method(\n z.object({ destinationId: z.string(), backupId: z.string() }),\n ArchiveManifestSchema.nullable(),\n { auth: 'admin' },\n ),\n restore: method(\n z.object({\n destinationId: z.string(),\n backupId: z.string(),\n /**\n * Optional whitelist — only restore these top-level locations\n * from the archive. Default = every location the archive\n * carries (full restore). The boot-time apply hook reads\n * this list and skips entries whose path doesn't start with\n * any of them.\n */\n locations: z.array(z.string()).optional(),\n }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n delete: method(\n z.object({ destinationId: z.string(), backupId: z.string() }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n /**\n * List archives at a single destination. Reads the per-location\n * `manifests.json` and returns one entry per archive (newest\n * first). Powers the destinations-table drill-in in admin UI.\n */\n listArchives: method(\n z.object({ destinationId: z.string() }),\n z.array(BackupArchiveEntrySchema).readonly(),\n { auth: 'admin' },\n ),\n /**\n * Upsert a per-destination policy row. The `locationId` MUST be\n * the id of an existing `backups`-typed `StorageLocation`. Used\n * by the admin-UI destinations table (enable toggle + retention\n * input + optional label).\n */\n upsertDestinationPolicy: method(\n z.object({\n locationId: z.string(),\n enabled: z.boolean(),\n retentionCount: z.number().int().min(1).max(1000),\n label: z.string().optional(),\n /**\n * Per-destination cron expression. Empty string clears the\n * schedule (manual-only). Validated server-side via croner;\n * malformed expressions reject the upsert with an actionable\n * message.\n */\n cron: z.string().optional(),\n }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n\n /**\n * Validate a cron expression and peek the next N firing times.\n * Used by the admin-UI CronEditor to render a live \"next-run\"\n * preview as the operator edits the pattern.\n */\n previewSchedule: method(\n z.object({\n cron: z.string(),\n count: z.number().int().min(1).max(20).optional(),\n }),\n z.object({\n ok: z.boolean(),\n error: z.string().optional(),\n nextRuns: z.array(z.number()).readonly(),\n }),\n ),\n },\n} as const satisfies CapabilityDefinition\n\nexport type IBackupProvider = InferProvider<typeof backupCapability>\n\nexport {\n BackupEntrySchema,\n BackupSubDestinationInfoSchema,\n BackupDestinationInfoSchema,\n BackupArchiveEntrySchema,\n ArchiveEntrySchema,\n ArchiveManifestSchema,\n LocationStatSchema,\n}\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\n\n/**\n * Query filter for settings-store collections.\n */\nconst QueryFilterSchema = z.object({\n where: z.record(z.string(), z.unknown()).optional(),\n whereIn: z.record(z.string(), z.array(z.unknown())).optional(),\n whereBetween: z.record(z.string(), z.tuple([z.unknown(), z.unknown()])).optional(),\n orderBy: z.object({\n field: z.string(),\n direction: z.enum(['asc', 'desc']),\n }).optional(),\n limit: z.number().optional(),\n offset: z.number().optional(),\n})\n\n/** A single stored record: `{ id, data }`. */\nconst SettingsRecordSchema = z.object({\n id: z.string(),\n data: z.record(z.string(), z.unknown()),\n})\n\n/**\n * Column declaration for a structured (SQL-backed) collection.\n *\n * Logical types — the backend translates each to the matching SQLite\n * storage class and handles per-type marshaling:\n * - `TEXT` / `INTEGER` / `REAL` — native SQLite types, pass-through\n * - `JSON` — TEXT under the hood; serialised on write, parsed on read\n * - `BOOLEAN` — INTEGER 0/1 under the hood; coerced both directions\n */\nconst CollectionColumnSchema = z.object({\n name: z.string(),\n type: z.enum(['TEXT', 'INTEGER', 'REAL', 'JSON', 'BOOLEAN']),\n primaryKey: z.boolean().optional(),\n notNull: z.boolean().optional(),\n unique: z.boolean().optional(),\n})\n\nconst CollectionIndexSchema = z.object({\n name: z.string(),\n columns: z.array(z.string()).readonly(),\n unique: z.boolean().optional(),\n})\n\n/**\n * settings-store — singleton capability for addon-scoped persistence.\n *\n * Every method operates within a `collection`. An optional `namespace`\n * field provides access to additional data spaces beyond the default\n * addon settings — useful for business data (events, tracks, faces, etc.).\n *\n * Scoping: the implementation prefixes every collection with the calling\n * addon's ID automatically. Addons never see each other's data.\n *\n * - No namespace (default): `\"addon-settings\"` → `\"<addonId>:addon-settings\"`\n * - With namespace: `{ namespace: 'events', collection: 'detections' }` →\n * `\"<addonId>:events:detections\"`\n *\n * Implemented by `@camstack/core/builtins/sqlite-settings` (SQLite WAL backend).\n * Addons access it via `ctx.api.settingsStore.*`.\n */\nexport const settingsStoreCapability = {\n name: 'settings-store',\n scope: 'system',\n mode: 'singleton',\n methods: {\n /** Get a single value by key from a collection. */\n get: method(\n z.object({ namespace: z.string().optional(), collection: z.string(), key: z.string() }),\n z.unknown(),\n ),\n\n /** Set a value by key in a collection (upsert). */\n set: method(\n z.object({ namespace: z.string().optional(), collection: z.string(), key: z.string(), value: z.unknown() }),\n z.void(),\n { kind: 'mutation' },\n ),\n\n /** Get all entries matching an optional filter. */\n query: method(\n z.object({ namespace: z.string().optional(), collection: z.string(), filter: QueryFilterSchema.optional() }),\n z.array(SettingsRecordSchema).readonly(),\n ),\n\n /** Insert a new record. */\n insert: method(\n z.object({ namespace: z.string().optional(), collection: z.string(), record: SettingsRecordSchema }),\n z.void(),\n { kind: 'mutation' },\n ),\n\n /** Update an existing record by ID. */\n update: method(\n z.object({ namespace: z.string().optional(), collection: z.string(), id: z.string(), data: z.record(z.string(), z.unknown()) }),\n z.void(),\n { kind: 'mutation' },\n ),\n\n /** Delete a record by key/ID. */\n delete: method(\n z.object({ namespace: z.string().optional(), collection: z.string(), key: z.string() }),\n z.void(),\n { kind: 'mutation' },\n ),\n\n /** Count entries in a collection, optionally filtered. */\n count: method(\n z.object({ namespace: z.string().optional(), collection: z.string(), filter: QueryFilterSchema.optional() }),\n z.number(),\n ),\n\n /** Grouped counts per ((field-origin)/bucketSize) bucket, filtered. */\n histogram: method(\n z.object({\n namespace: z.string().optional(), collection: z.string(),\n field: z.string(), bucketSize: z.number().int().positive(), origin: z.number().int(),\n filter: QueryFilterSchema.optional(),\n }),\n z.array(z.object({ bucket: z.number().int(), count: z.number().int() })).readonly(),\n ),\n\n /** Check if a collection is empty. */\n isEmpty: method(\n z.object({ namespace: z.string().optional(), collection: z.string() }),\n z.boolean(),\n ),\n\n /**\n * Declare a typed (SQL-backed) collection with explicit columns +\n * indexes. Idempotent: re-declaring an existing collection with the\n * same shape is a no-op; shape changes (new columns, new indexes)\n * are applied additively. Subsequent `insert` / `update` / `delete`\n * / `query` calls on this collection use typed columns instead of\n * JSON-blob storage — `record.data` fields are spread across\n * columns, `query.filter.where` matches real columns (no\n * `json_extract` overhead), `orderBy` uses column indexes.\n *\n * Addons call this in `onInitialize` before their first read/write.\n * Collection names should be namespaced by addon (e.g.\n * `pipeline-analytics:object-events`) to avoid cross-addon\n * clashes — no automatic prefix is added.\n */\n declareCollection: method(\n z.object({\n namespace: z.string().optional(),\n collection: z.string(),\n columns: z.array(CollectionColumnSchema).readonly(),\n indexes: z.array(CollectionIndexSchema).readonly().optional(),\n }),\n z.void(),\n { kind: 'mutation' },\n ),\n },\n} as const satisfies CapabilityDefinition\n\nexport type ISettingsStoreProvider = InferProvider<typeof settingsStoreCapability>\n\n/**\n * tRPC client namespace type for the settings-store capability.\n * Used as the dependency type for services that need settings persistence.\n * Methods are accessed as `client.get.query(input)`, `client.set.mutate(input)`, etc.\n */\nexport type SettingsStoreClient = import('../generated/addon-api.js').AddonApi['settingsStore']\n\nexport { QueryFilterSchema, SettingsRecordSchema, CollectionColumnSchema, CollectionIndexSchema }\n\nexport type CollectionColumn = z.infer<typeof CollectionColumnSchema>\nexport type CollectionIndex = z.infer<typeof CollectionIndexSchema>\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\n\nconst LogLevelSchema = z.enum(['debug', 'info', 'warn', 'error'])\n\nconst LogEntrySchema = z.object({\n timestamp: z.date(),\n level: LogLevelSchema,\n scope: z.array(z.string()),\n message: z.string(),\n meta: z.record(z.string(), z.unknown()).optional(),\n tags: z.record(z.string(), z.string()).optional(),\n})\n\nexport const logDestinationCapability = {\n name: 'log-destination',\n scope: 'system',\n mode: 'collection',\n internal: true,\n methods: {\n write: method(LogEntrySchema, z.void(), { kind: 'mutation' }),\n query: method(\n z.object({\n scope: z.array(z.string()).optional(),\n level: LogLevelSchema.optional(),\n since: z.date().optional(),\n until: z.date().optional(),\n limit: z.number().optional(),\n tags: z.record(z.string(), z.string()).optional(),\n }),\n z.array(LogEntrySchema).readonly(),\n ),\n },\n} as const satisfies CapabilityDefinition\n\nexport type ILogDestinationProvider = InferProvider<typeof logDestinationCapability>\n\nexport { LogEntrySchema, LogLevelSchema }\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\n\nconst StaticDirOutputSchema = z.object({ staticDir: z.string() })\nconst VersionOutputSchema = z.object({ version: z.string() })\n\nexport const adminUiCapability = {\n name: 'admin-ui',\n scope: 'system',\n mode: 'singleton',\n internal: true,\n methods: {\n getStaticDir: method(z.void(), StaticDirOutputSchema),\n getVersion: method(z.void(), VersionOutputSchema),\n },\n} as const satisfies CapabilityDefinition\n\nexport type IAdminUiProvider = InferProvider<typeof adminUiCapability>\n","/**\n * Zod schemas for persisted record types.\n *\n * These schemas serve as the single source of truth for types that are\n * stored in the settings-store backend and retrieved via tRPC. They\n * replace the manual TypeScript interfaces with schema-derived types,\n * enabling runtime validation when reading from the backend.\n *\n * Convention: each schema is named `<Type>Schema`, the inferred TS type\n * keeps the original name for backward compatibility.\n */\nimport { z } from 'zod'\n\n// ── Auth ────────────────────────────────────────────────────────────\n\n/**\n * Auth model (v2 — 2026-05-12 caps-only):\n *\n * Two principals:\n * - `isAdmin: true` — full bypass. Admin scope set is ignored.\n * - `isAdmin: false` — every call gated by `scopes` (see TokenScope).\n *\n * No role enum. There used to be `viewer / agent / scoped` and earlier\n * `super_admin` — collapsed onto the single boolean because every\n * non-admin caller is governed by the same scope-check rules; the\n * distinction was only ever used to route role-specific procedures\n * which we no longer have. Agents are admin sessions issued via\n * `createServiceToken`; CLI / webhook integrations are `cst_*` tokens\n * with `isAdmin: false` + an explicit scope list.\n */\n\n/** Per-method access flavour. Materialised on every cap method via codegen. */\nexport const MethodAccessSchema = z.enum(['view', 'create', 'delete'])\nexport type MethodAccess = z.infer<typeof MethodAccessSchema>\n\n/**\n * A single scope grant. Three forms — checked in matcher with OR\n * semantics; the first match decides whether the call passes:\n *\n * - `category` — broadest. `target: 'device' | 'system'` selects every\n * cap with the matching `scope` declaration. New caps inherit grants\n * automatically — adding a device cap to the codebase makes it\n * reachable to every user with `category:device [...]` without a\n * re-grant. Use this for \"family viewer\" / \"operator\" tiers.\n *\n * - `addon` — every cap that ships inside a given addon id. Niche;\n * useful when an integration needs to interact with one specific\n * addon's surface regardless of how many caps it exports.\n *\n * - `capability` — the most precise form. Single cap name. Use for\n * integration tokens where you want to grant `addons.installPackage`\n * and nothing else.\n *\n * `access` is REQUIRED with min 1 element. `admin` bypass is the\n * \"give me everything\" escape; there is no wildcard scope.\n */\nconst AllowedProviderSchema = z.union([z.literal('*'), z.array(z.string())])\nconst AllowedDevicesSchema = z.record(z.string(), z.union([z.literal('*'), z.array(z.string())]))\n\nexport const CapScopeSchema = z.enum(['device', 'system'])\nexport type CapScope = z.infer<typeof CapScopeSchema>\n\nexport const TokenScopeSchema = z.discriminatedUnion('type', [\n z.object({\n type: z.literal('category'),\n target: CapScopeSchema,\n access: z.array(MethodAccessSchema).min(1),\n }),\n z.object({\n type: z.literal('capability'),\n target: z.string(),\n access: z.array(MethodAccessSchema).min(1),\n }),\n z.object({\n type: z.literal('addon'),\n target: z.string(),\n access: z.array(MethodAccessSchema).min(1),\n }),\n z.object({\n type: z.literal('device'),\n /**\n * One or more deviceIds (serialised as strings for wire-format\n * consistency with the rest of the union). Matcher accepts if\n * `input.deviceId` ∈ `targets`. Array shape avoids the row-explosion\n * of one scope-per-device when granting access to a set of cameras.\n */\n targets: z.array(z.string()).min(1),\n access: z.array(MethodAccessSchema).min(1),\n }),\n])\nexport type TokenScope = z.infer<typeof TokenScopeSchema>\n\nexport const UserRecordSchema = z.object({\n id: z.string(),\n username: z.string(),\n passwordHash: z.string(),\n /**\n * Admin bypass. When true, the middleware skips the scope-access\n * check entirely. There is no other axis of privilege; the legacy\n * role enum collapsed onto this boolean in v2.\n */\n isAdmin: z.boolean().default(false),\n allowedProviders: AllowedProviderSchema,\n allowedDevices: AllowedDevicesSchema,\n /**\n * Scopes granted to this user. Admins bypass; their `scopes` is\n * ignored. Non-admins without scopes are locked out of every\n * protected call.\n */\n scopes: z.array(TokenScopeSchema).default([]),\n createdAt: z.number(),\n updatedAt: z.number(),\n})\nexport type UserRecord = z.infer<typeof UserRecordSchema>\n\nexport const ApiKeyRecordSchema = z.object({\n id: z.string(),\n label: z.string(),\n isAdmin: z.boolean().default(false),\n allowedProviders: AllowedProviderSchema,\n allowedDevices: AllowedDevicesSchema,\n tokenHash: z.string(),\n tokenPrefix: z.string(),\n createdAt: z.number(),\n lastUsedAt: z.number().optional(),\n})\nexport type ApiKeyRecord = z.infer<typeof ApiKeyRecordSchema>\n\n// ── Scoped Tokens ───────────────────────────────────────────────────\n\nexport const ScopedTokenSchema = z.object({\n id: z.string(),\n userId: z.string(),\n name: z.string(),\n tokenHash: z.string(),\n tokenPrefix: z.string(),\n scopes: z.array(TokenScopeSchema),\n // SQLite/JSON storage round-trips undefined → null. Use `nullish` so the\n // schema accepts both `null` (read from disk) and `undefined` (in-memory).\n expiresAt: z.number().nullish(),\n lastUsedAt: z.number().nullish(),\n createdAt: z.number(),\n})\nexport type ScopedToken = z.infer<typeof ScopedTokenSchema>\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { TokenScopeSchema } from '../schemas/auth-records.js'\n\n/**\n * `sso-bridge` — internal hub-only cap that lets SSO-style auth\n * providers (OIDC, SAML, magic-link, …) mint an HMAC-signed token\n * carrying the post-callback claims before redirecting back to\n * `/api/auth/sso/finish`.\n *\n * Without this, any client could craft a `?isAdmin=1` link to\n * `/sso/finish` and become admin. With it, the endpoint accepts ONLY\n * the signed token and rejects everything else.\n *\n * Backed by `AuthManager.{signSsoBridgeToken,verifySsoBridgeToken}` —\n * see `packages/core/src/auth/auth-manager.ts`. The provider is\n * registered at hub boot in `server/backend/src/main.ts`.\n */\nconst SsoBridgeClaimsSchema = z.object({\n userId: z.string(),\n username: z.string(),\n isAdmin: z.boolean(),\n provider: z.string(),\n email: z.string().optional(),\n displayName: z.string().optional(),\n /**\n * Public HTTPS URL of the hub that issued this token. Used by\n * cloud-mode OAuth proxies (Alexa Smart Home Lambda, future Google\n * Home Lambda) to route a request back to the originating hub\n * without holding routing state of their own. The Lambda decodes the\n * JWT WITHOUT verifying the signature — the hub re-verifies on every\n * inbound call so trust still rests with the signing hub.\n */\n hubUrl: z.string().optional(),\n /** Permission scopes baked into the token. Set by the OAuth\n * account-linking grant; absent on ordinary SSO-login tokens. */\n scopes: z.array(TokenScopeSchema).optional(),\n /** OAuth authorization-code binding — set only on `oauth-code` tokens. */\n redirectUri: z.string().optional(),\n integrationId: z.string().optional(),\n /** JWT ID — unique per issued code; consumed-set enforces single-use. */\n jti: z.string().optional(),\n /** OAuth session registry id — set on `oauth-access`/`oauth-refresh`\n * tokens so the verify path can check the session is not revoked. */\n sessionId: z.string().optional(),\n})\n\nexport const ssoBridgeCapability = {\n name: 'sso-bridge',\n scope: 'system',\n mode: 'singleton',\n internal: true,\n methods: {\n signBridgeToken: method(\n z.object({\n claims: SsoBridgeClaimsSchema,\n ttlSec: z.number().int().positive().optional(),\n }),\n z.object({ token: z.string() }),\n ),\n verifyBridgeToken: method(\n z.object({ token: z.string() }),\n SsoBridgeClaimsSchema.nullable(),\n ),\n },\n} as const satisfies CapabilityDefinition\n\nexport type ISsoBridgeProvider = InferProvider<typeof ssoBridgeCapability>\nexport { SsoBridgeClaimsSchema }\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { TokenScopeSchema } from '../schemas/auth-records.js'\n\n/**\n * `oauth-integration` — a collection cap by which an addon declares\n * itself a linkable OAuth client of the hub's core `/oauth2/*` server.\n * Each provider returns a static descriptor; the core enumerates them\n * to validate the `integration=` query param and resolve the consent\n * label + the scopes baked into the issued token.\n */\nconst OauthIntegrationDescriptorSchema = z.object({\n /** Stable id used as the `integration=` query param, e.g. 'export-alexa'. */\n integrationId: z.string(),\n /** Human label rendered on the consent page. */\n displayName: z.string(),\n /** Scopes baked into every token issued for this integration. */\n requestedScopes: z.array(TokenScopeSchema),\n /** Allowed redirect_uri prefixes. /api/oauth2/authorize rejects any\n * redirect_uri that does not start with one of these. Required —\n * an empty list means the integration can never complete linking. */\n allowedRedirectPrefixes: z.array(z.string()).min(1),\n /** Optional public origin (no trailing slash) that this integration's\n * issued codes/tokens should carry as the `hubUrl` claim — typically the\n * operator-selected external-access endpoint resolved by the addon. When\n * present, /api/oauth2/authorize bakes THIS into the code instead of the\n * hub-global `publicHubUrl()`, so a forked exporter addon (which can't set\n * the hub's env) drives the claim that its cloud Lambda routes back on. */\n hubUrl: z.string().optional(),\n})\n\nexport const oauthIntegrationCapability = {\n name: 'oauth-integration',\n scope: 'system',\n mode: 'collection',\n internal: true,\n methods: {\n getDescriptor: method(z.void(), OauthIntegrationDescriptorSchema),\n },\n} as const satisfies CapabilityDefinition\n\nexport type IOauthIntegrationProvider = InferProvider<typeof oauthIntegrationCapability>\nexport type OauthIntegrationDescriptor = z.infer<typeof OauthIntegrationDescriptorSchema>\nexport { OauthIntegrationDescriptorSchema }\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\n\n/**\n * `user-passkeys` — per-user WebAuthn (passkey) enrollment + assertion.\n *\n * Implemented by `@camstack/addon-auth-webauthn` (collection of one\n * for now; the cap is collection-mode for forward compat with\n * provider-specific passkey stores).\n *\n * Lifecycle:\n * 1. Enrollment (admin or self):\n * a. `beginRegistration({userId, username})` → server returns\n * PublicKeyCredentialCreationOptions (challenge, rp, user, …).\n * The browser passes this to `navigator.credentials.create()`.\n * b. `finishRegistration({userId, response, label})` →\n * server verifies attestation, persists the credential\n * (publicKey + counter + transports + label).\n *\n * 2. Authentication (during login):\n * a. `beginAuthentication({userId?})` → server returns\n * PublicKeyCredentialRequestOptions (challenge, allowCredentials).\n * The browser passes this to `navigator.credentials.get()`.\n * b. `finishAuthentication({userId, response})` → server verifies\n * the assertion, bumps the credential counter, returns ok.\n *\n * 3. Management:\n * - `listPasskeys({userId})` — enumerate user's enrolled credentials.\n * - `removePasskey({userId, credentialId})` — revoke one credential.\n *\n * Challenges are short-lived (5 min, in-memory). The cap is internal —\n * the admin-ui composes the begin/finish round-trip and never exposes\n * the cap to non-admins.\n */\n\nconst PasskeySummarySchema = z.object({\n credentialId: z.string(),\n label: z.string(),\n createdAt: z.number(),\n lastUsedAt: z.number().nullable(),\n transports: z.array(z.string()).default([]),\n})\n\nexport type PasskeySummary = z.infer<typeof PasskeySummarySchema>\n\nexport const userPasskeysCapability = {\n name: 'user-passkeys',\n scope: 'system',\n mode: 'collection',\n internal: true,\n methods: {\n beginRegistration: method(\n z.object({ userId: z.string(), username: z.string() }),\n // PublicKeyCredentialCreationOptionsJSON — opaque JSON shape from\n // @simplewebauthn. The browser passes it straight to credentials.create().\n z.object({ optionsJSON: z.record(z.string(), z.unknown()) }),\n { kind: 'mutation', auth: 'admin', access: 'create' },\n ),\n finishRegistration: method(\n z.object({\n userId: z.string(),\n /** RegistrationResponseJSON from the browser. */\n response: z.record(z.string(), z.unknown()),\n /** Operator-visible label (e.g. \"MacBook Touch ID\"). */\n label: z.string(),\n }),\n z.object({ success: z.literal(true), credentialId: z.string() }),\n { kind: 'mutation', auth: 'admin', access: 'create' },\n ),\n beginAuthentication: method(\n // userId optional — when absent, the addon emits a \"passkey discovery\"\n // (`allowCredentials: []`) so the browser shows every available\n // credential. When present, only the user's credentials are allowed.\n z.object({ userId: z.string().optional() }),\n z.object({ optionsJSON: z.record(z.string(), z.unknown()) }),\n { kind: 'mutation', access: 'view' },\n ),\n finishAuthentication: method(\n z.object({\n /** Required — the user the assertion belongs to (verified). */\n userId: z.string(),\n /** AuthenticationResponseJSON from the browser. */\n response: z.record(z.string(), z.unknown()),\n }),\n z.object({ verified: z.boolean() }),\n { kind: 'mutation', access: 'view' },\n ),\n listPasskeys: method(\n z.object({ userId: z.string() }),\n z.array(PasskeySummarySchema),\n { auth: 'admin' },\n ),\n removePasskey: method(\n z.object({ userId: z.string(), credentialId: z.string() }),\n z.object({ success: z.literal(true) }),\n { kind: 'mutation', auth: 'admin', access: 'delete' },\n ),\n },\n} as const satisfies CapabilityDefinition\n\nexport type IUserPasskeysProvider = InferProvider<typeof userPasskeysCapability>\nexport { PasskeySummarySchema }\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\n\n/**\n * `smtp-provider` — pluggable email delivery surface.\n *\n * Collection cap: a deployment may install multiple SMTP relays (e.g.\n * one for transactional / one for notifications). Consumers (magic-link,\n * notifier addons, …) walk the collection and pick the first\n * ready provider OR target a specific addonId.\n *\n * The shape stays small on purpose — `sendEmail` is enough for the\n * 90% case. Attachments / HTML templating / multi-part are room for\n * future fields without breaking the existing call sites.\n */\n\nconst EmailAddressSchema = z.email()\n\nconst SendEmailInputSchema = z.object({\n to: z.union([EmailAddressSchema, z.array(EmailAddressSchema).min(1)]),\n cc: z.array(EmailAddressSchema).optional(),\n bcc: z.array(EmailAddressSchema).optional(),\n /** RFC 5322 `From` field. Most relays will reject if the domain\n * isn't authorised — the addon is responsible for substituting a\n * sane default when omitted. */\n from: z.string().optional(),\n /** Optional `Reply-To` override. */\n replyTo: z.string().optional(),\n subject: z.string(),\n /** Plain-text body. Required even when `html` is present (fallback\n * for clients that strip HTML — including most spam filters). */\n text: z.string(),\n /** Optional HTML body. Renders alongside `text` as multi-part. */\n html: z.string().optional(),\n})\n\nconst SendEmailResultSchema = z.object({\n messageId: z.string(),\n accepted: z.array(EmailAddressSchema).default([]),\n rejected: z.array(EmailAddressSchema).default([]),\n})\n\nconst SmtpStatusSchema = z.object({\n /** True iff the addon has successfully verified the relay. */\n ready: z.boolean(),\n /** Operator-visible host string (no credentials). */\n host: z.string(),\n /** Last error message reported by the relay, when not ready. */\n error: z.string().optional(),\n /** Last successful verify timestamp (unix ms). */\n lastVerifiedAt: z.number().optional(),\n})\n\nexport const smtpProviderCapability = {\n name: 'smtp-provider',\n scope: 'system',\n mode: 'collection',\n internal: true,\n providerKind: 'email',\n methods: {\n sendEmail: method(\n SendEmailInputSchema,\n SendEmailResultSchema,\n { kind: 'mutation', auth: 'admin', access: 'create' },\n ),\n /** Round-trip ping against the SMTP relay (EHLO + AUTH if configured).\n * Used by the operator's \"Test connection\" button. */\n verify: method(\n z.void(),\n SmtpStatusSchema,\n { kind: 'mutation', auth: 'admin', access: 'view' },\n ),\n getStatus: method(\n z.void(),\n SmtpStatusSchema,\n { auth: 'admin' },\n ),\n },\n} as const satisfies CapabilityDefinition\n\nexport type ISmtpProvider = InferProvider<typeof smtpProviderCapability>\nexport { SendEmailInputSchema, SendEmailResultSchema, SmtpStatusSchema }\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { DiscoveredChildDeviceSchema } from './device-discovery.cap.js'\n\n/**\n * `device-adoption` — generic discovery + adoption surface,\n * system-scoped singleton. The de-HA-ified successor to `ha-discovery`:\n * keyed by `integrationId` (the addon resolves integrationId → broker\n * internally) rather than a connection-specific `brokerId`, and it\n * REUSES the shared `DiscoveredChildDevice` candidate type from\n * `device-discovery.cap.ts` so a single shared adoption panel renders\n * any integration's candidate tree.\n *\n * UI flow (Integrations page → integration detail):\n * 1. `listCandidates({integrationId, page, pageSize, filter})` →\n * paginated candidate list, each row collapsed.\n * 2. User expands a row → `getCandidate({integrationId,\n * childNativeId})` returns the single candidate (with its nested\n * `children`) for the accordion render.\n * 3. User clicks \"Adopt\" on one or more candidates →\n * `adopt({integrationId, childNativeIds, perCandidate?})`\n * materialises one parent CamStack device per candidate plus its\n * accessory children. `perCandidate[childNativeId]` carries an\n * optional display-name override + a `hiddenChildIds` pre-hide set\n * (the parent's `accessories.hiddenChildIds` gates UI visibility).\n * 4. User clicks \"Release\" → `release({integrationId, camDeviceId})`\n * removes the parent + every child from the kernel registry.\n */\n\n/**\n * Provider-declared discovery *granularity* filter (the keystone of the\n * single-entity-import design). A provider advertises which discovery\n * granularities it supports via `listCandidateFilters`; the operator picks\n * one and it is passed back as the opaque `filter` string on\n * `listCandidates`/`adopt`.\n *\n * - **`id`** is provider-defined and OPAQUE to the cap + UI layers — only the\n * declaring provider interprets it. The reserved id `'devices'` is the\n * universal default (every provider's current behavior IS the `devices`\n * filter). A provider that declares no filters is treated as a single\n * implicit `{ id:'devices', label:'Devices', isDefault:true }`.\n * - **`label`** is the human label for the UI selector.\n * - **`isDefault`** marks the default filter; exactly one SHOULD be default.\n */\nexport const AdoptionFilterSchema = z.object({\n id: z.string(),\n label: z.string(),\n isDefault: z.boolean().optional(),\n})\nexport type AdoptionFilter = z.infer<typeof AdoptionFilterSchema>\n\n/**\n * Candidate-list TEXT/query filter. Mirrors the prior `ha-discovery` filter,\n * de-HA-ified — `area` / `manufacturer` stay free-form strings so any\n * integration can populate them from its own metadata. Distinct from the\n * granularity `AdoptionFilter` above: this narrows the candidate set within a\n * chosen granularity, whereas the granularity `filter` selects WHAT a\n * candidate is (a device vs an entity).\n */\nexport const CandidateQueryFilterSchema = z.object({\n /** Substring filter on name + manufacturer + model. */\n search: z.string().optional(),\n /** Area-name exact match. */\n area: z.string().optional(),\n /** Manufacturer exact match. */\n manufacturer: z.string().optional(),\n /** When true, only return candidates the operator already adopted. */\n adoptedOnly: z.boolean().optional(),\n /** When true, only return candidates the operator hasn't adopted yet. */\n unadoptedOnly: z.boolean().optional(),\n})\n\nexport const ListCandidatesInputSchema = z.object({\n integrationId: z.string(),\n page: z.number().int().positive().default(1),\n // Pagination is client-side in the adoption UI: the modal fetches the whole\n // candidate set in one page and the shared list paginates locally. The cap\n // stays high enough to return every candidate at once. The large case is the\n // HA `entities` granularity — one HA device maps to many entities, so an\n // install can expose several thousand candidates; the ceiling is sized for it.\n pageSize: z.number().int().positive().max(20000).default(50),\n /**\n * Optional provider-declared discovery GRANULARITY id (opaque; see\n * `AdoptionFilterSchema`). Omitted = the reserved `'devices'` granularity =\n * exactly the pre-existing behavior (fully back-compatible).\n */\n filter: z.string().optional(),\n /** Optional candidate-list text/query narrowing within the granularity. */\n filterText: CandidateQueryFilterSchema.optional(),\n})\nexport const ListCandidatesOutputSchema = z.object({\n candidates: z.array(DiscoveredChildDeviceSchema).readonly(),\n totalCount: z.number().int().nonnegative(),\n page: z.number().int().positive(),\n pageSize: z.number().int().positive(),\n})\n\nexport const GetCandidateInputSchema = z.object({\n integrationId: z.string(),\n childNativeId: z.string(),\n})\n\nexport const AdoptionStatusSchema = z.object({\n /** Last refresh timestamp (ms epoch) — null when never refreshed. */\n lastDiscoveryAt: z.number().int().nonnegative().nullable(),\n /** Count of candidates in the discovery cache. */\n candidateCount: z.number().int().nonnegative(),\n /** Count of candidates the operator has already adopted. */\n adoptedCount: z.number().int().nonnegative(),\n /** Last error message from a refresh attempt. */\n lastError: z.string().nullable(),\n})\n\nconst PerCandidateSchema = z.object({\n /** Override the default display name for this candidate's parent. */\n name: z.string().min(1).optional(),\n /** Pre-hide a subset of entity-children — created (state still flows)\n * but listed in the parent's `accessories.hiddenChildIds`. */\n hiddenChildIds: z.array(z.string()).optional(),\n})\nexport const AdoptInputSchema = z.object({\n integrationId: z.string(),\n /**\n * Candidate native ids to adopt. Their MEANING is filter-relative: under the\n * default `'devices'` granularity these are device-native ids; under a\n * provider-declared granularity (e.g. HA `'entities'`) they are that\n * granularity's native ids (e.g. entity ids). The field name is kept stable\n * to avoid a breaking rename.\n */\n childNativeIds: z.array(z.string()).min(1),\n /**\n * Optional provider-declared discovery GRANULARITY id (opaque; see\n * `AdoptionFilterSchema`). Omitted = the reserved `'devices'` granularity =\n * exactly the pre-existing behavior (fully back-compatible).\n */\n filter: z.string().optional(),\n /** When true, import each adopted device's source-system location (e.g. HA\n * area) into CamStack — fuzzy-match an existing location or create it, then\n * assign. Omitted/false = no location work (back-compat). */\n importLocations: z.boolean().optional(),\n perCandidate: z.record(z.string(), PerCandidateSchema).optional(),\n})\nexport const AdoptResultSchema = z.object({\n adopted: z.array(\n z.object({\n childNativeId: z.string(),\n parentDeviceId: z.number().int().nonnegative(),\n accessoryDeviceIds: z.array(z.number().int().nonnegative()).readonly(),\n }),\n ).readonly(),\n})\n\nexport const ReleaseInputSchema = z.object({\n integrationId: z.string(),\n /** Parent CamStack device id (NOT an accessory child id). Removing\n * the parent cascades into every accessory. */\n camDeviceId: z.number().int().nonnegative(),\n})\n\nexport const ResyncInputSchema = z.object({\n /** Parent CamStack device id of an adopted device. The provider resolves its\n * source (integration/broker + native id) and re-aligns the device's\n * structural spec (type/role/capabilities/units) with the live mapping,\n * rebuilding any child whose class changed while preserving operator edits. */\n camDeviceId: z.number().int().nonnegative(),\n})\nexport const ResyncResultSchema = z.object({\n /** True when the persisted spec actually changed (children may have been rebuilt). */\n changed: z.boolean(),\n /** Number of child devices rebuilt into a new class by this re-sync. */\n rebuiltChildren: z.number().int().nonnegative(),\n})\n\nexport const deviceAdoptionCapability = {\n name: 'device-adoption',\n scope: 'system',\n mode: 'singleton',\n status: { schema: AdoptionStatusSchema, kind: 'poll' },\n methods: {\n listCandidateFilters: method(\n z.object({ integrationId: z.string() }),\n z.object({ filters: z.array(AdoptionFilterSchema) }),\n { auth: 'admin' },\n ),\n listCandidates: method(ListCandidatesInputSchema, ListCandidatesOutputSchema, { auth: 'admin' }),\n getCandidate: method(GetCandidateInputSchema, DiscoveredChildDeviceSchema.nullable(), { auth: 'admin' }),\n refresh: method(z.object({ integrationId: z.string() }), AdoptionStatusSchema, { kind: 'mutation', auth: 'admin' }),\n adopt: method(AdoptInputSchema, AdoptResultSchema, { kind: 'mutation', auth: 'admin' }),\n release: method(ReleaseInputSchema, z.void(), { kind: 'mutation', auth: 'admin' }),\n resync: method(ResyncInputSchema, ResyncResultSchema, { kind: 'mutation', auth: 'admin' }),\n },\n} as const satisfies CapabilityDefinition\n\nexport type IDeviceAdoptionProvider = InferProvider<typeof deviceAdoptionCapability>\nexport type AdoptionStatus = z.infer<typeof AdoptionStatusSchema>\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\n\n/**\n * `broker` — unified pub/sub broker registry, system-scoped collection.\n *\n * The cap models any kind-tagged message broker the user wants to\n * register and that other addons might consume. The first two kinds\n * are MQTT (mosquitto / aedes embedded / cloud bridge) and\n * Home Assistant (HA WebSocket — subscribe_entities + call_service).\n * Future kinds (Zigbee2MQTT bridge, ZHA, KNX, Telegram, …) plug in\n * the same surface.\n *\n * Why one cap, not one cap per kind:\n * - The integrations page wants a single table of \"every broker\"\n * across kinds; a unified cap drives it without join logic.\n * - Generic admin operations (add / remove / test / status) are\n * identical across kinds — duplicating them per cap was busywork.\n * - The `network-access` cap precedent: same interface, many\n * `providerKind: 'ingress'` implementations (Tailscale, ngrok, …).\n *\n * What stays kind-specific:\n * - `getBrokerConfig` payload (kind decides whether it returns\n * mqtt URL+creds, HA baseUrl+token, …) — typed as\n * `Record<string, unknown>` at the wire; consumers narrow.\n * - `publish` / `subscribe` / `getState` arguments (target / filter /\n * key) — also typed as `Record<string, unknown>` so each kind can\n * evolve its surface (MQTT topic+qos vs HA entity_id+domain)\n * without rebreaking the cap signature.\n * - `add` `settings` payload (different fields per kind, validated by\n * the kind-specific provider).\n *\n * Bidirectionality:\n * - `publish` is RPC — synchronous result (provider-defined).\n * - `subscribe` returns a subscription handle; the actual message\n * stream flows over the typed event-bus as `broker.message` events\n * keyed by `(brokerId, subscriptionId)`. Consumers filter in their\n * event handler. Subscriptions persist across reconnects — the\n * provider re-subscribes upstream after a transport drop.\n *\n * Why event-bus push (not a subscription RPC stream):\n * - Matches the rest of CamStack's D8 contract — events for telemetry,\n * RPC for loss-is-a-bug. Broker messages are telemetry (a single\n * drop is recoverable via `getState({key})`).\n * - Frees `broker.subscribe` from holding a long-lived RPC channel.\n * - Cross-process: events already route through `$event-bus`; no\n * per-broker wire-shaping needed.\n */\n\nexport const BrokerStatusEnum = z.enum([\n 'connected',\n 'disconnected',\n 'connecting',\n 'auth-failed',\n 'unreachable',\n 'error',\n])\nexport type BrokerStatus = z.infer<typeof BrokerStatusEnum>\n\nconst BrokerInfoSchema = z.object({\n /** Stable broker id. Persisted; survives addon restarts. */\n id: z.string(),\n /** Addon id of the provider that OWNS this broker.\n *\n * The `broker` cap is a system-scoped collection: several addons\n * register a `broker` provider, each owning a DISJOINT set of\n * brokers (mqtt-broker owns `mqtt_*`, provider-homeassistant owns\n * `ha_*`). A broker therefore belongs to exactly one addon — like a\n * device belongs to one integration. The admin UI threads this id\n * back as the `{ addonId }` system-collection selector on every\n * id-keyed call (`get` / `getSettings` / `setSettings` / `remove` /\n * `testConnection`), so the call routes to the OWNING provider\n * instead of defaulting to the first-registered one. */\n addonId: z.string(),\n /** Human-readable name (operator-chosen at add-time). */\n name: z.string(),\n /** Provider-defined kind tag — `mqtt` / `home-assistant` / future. */\n kind: z.string(),\n status: BrokerStatusEnum,\n /** Free-form provider-specific info (HA version, MQTT broker\n * flavour, latency, mTLS active, …). */\n info: z.record(z.string(), z.unknown()),\n /** Ms epoch of the last connection probe / status update. */\n lastCheckedAt: z.number().nullable(),\n /** Last error message, when `status` indicates failure. */\n error: z.string().nullable(),\n})\n\nexport type BrokerInfo = z.infer<typeof BrokerInfoSchema>\n\nconst RegistryStatusSchema = z.object({\n brokerCount: z.number().int().nonnegative(),\n connectedCount: z.number().int().nonnegative(),\n})\n\n/**\n * One entry per `broker` provider — which addon provides which broker\n * kind(s). The unified create picker reads this to know, for each\n * (addonId, kind) pair the operator can pick, where to route the\n * follow-up `getSettingsSchema` / `testSettings` / `add` calls (via the\n * `{ addonId }` selector). A provider only advertises a kind here when\n * it implements `getSettingsSchema` for that kind (so the picker never\n * offers a kind whose creation form can't be rendered).\n */\nconst BrokerProviderInfoSchema = z.object({\n /** Addon id of the `broker` provider this entry describes. */\n addonId: z.string(),\n /** Broker kinds this provider can create, with a display label. */\n kinds: z.array(z.object({ kind: z.string(), label: z.string() })),\n})\n\nexport type BrokerProviderInfo = z.infer<typeof BrokerProviderInfoSchema>\n\nconst ListInputSchema = z.object({\n /** Optional kind filter — `list({kind:'home-assistant'})` returns\n * only HA brokers. Omit to list every broker. */\n kind: z.string().optional(),\n})\n\nconst GetInputSchema = z.object({ id: z.string() })\n\nconst AddInputSchema = z.object({\n kind: z.string().min(1),\n name: z.string().min(1),\n /** Kind-specific settings (e.g. MQTT `{url,username,password}` or HA\n * `{baseUrl,accessToken}`). Validated by the kind-specific provider\n * branch on receipt — invalid shape rejects the add. */\n settings: z.record(z.string(), z.unknown()),\n})\n\nconst AddResultSchema = z.object({ id: z.string() })\n\nconst RemoveInputSchema = z.object({ id: z.string() })\n\nconst TestConnectionResultSchema = z.discriminatedUnion('ok', [\n z.object({ ok: z.literal(true), latencyMs: z.number().nonnegative() }),\n z.object({ ok: z.literal(false), error: z.string() }),\n])\n\nconst SettingsRecordSchema = z.record(z.string(), z.unknown())\n\nconst SettingsSchemaInputSchema = z.object({ kind: z.string() })\nconst TestSettingsInputSchema = z.object({\n kind: z.string(),\n settings: SettingsRecordSchema,\n})\nconst TestSettingsResultSchema = z.discriminatedUnion('ok', [\n // `.strict()` on the success branch so a stray `error` field is rejected,\n // not silently stripped — a success result must never carry an error.\n z.object({ ok: z.literal(true), latencyMs: z.number().nonnegative().optional() }).strict(),\n z.object({ ok: z.literal(false), error: z.string() }),\n])\n// ConfigSchema is opaque at the cap boundary (rendered by FormBuilder).\nconst SettingsSchemaResultSchema = z.unknown().nullable()\n\nconst PublishInputSchema = z.object({\n brokerId: z.string(),\n /** Kind-specific routing target.\n * MQTT: `{ topic: string, qos?: 0|1|2, retain?: boolean }`.\n * HA: `{ domain: string, service: string, entityId?: string, area?: string }`. */\n target: z.record(z.string(), z.unknown()),\n /** Kind-specific payload.\n * MQTT: raw string / number / object (provider serialises).\n * HA: service-call `data` object (transition, brightness, …). */\n payload: z.unknown().optional(),\n})\n\nconst SubscribeInputSchema = z.object({\n brokerId: z.string(),\n /** Kind-specific filter.\n * MQTT: `{ topic: string, qos?: 0|1|2 }` — topic can include wildcards.\n * HA: `{ entityIds: string[] }` or `{ domain: string }`. */\n filter: z.record(z.string(), z.unknown()),\n})\n\nconst SubscribeResultSchema = z.object({\n /** Stable subscription id. Used to unsubscribe and to filter the\n * matching `broker.message` events on the bus. */\n subscriptionId: z.string(),\n})\n\nconst UnsubscribeInputSchema = z.object({\n brokerId: z.string(),\n subscriptionId: z.string(),\n})\n\nconst GetStateInputSchema = z.object({\n brokerId: z.string(),\n /** Kind-specific lookup key.\n * MQTT: topic string (returns the last retained message).\n * HA: entity_id (returns the cached entity state). */\n key: z.string(),\n})\n\nexport const brokerCapability = {\n name: 'broker',\n scope: 'system',\n mode: 'collection',\n providerKind: 'broker',\n status: { schema: RegistryStatusSchema, kind: 'poll' },\n methods: {\n // ── Registry CRUD ────────────────────────────────────────────────\n list: method(ListInputSchema, z.array(BrokerInfoSchema)),\n get: method(GetInputSchema, BrokerInfoSchema.nullable()),\n /** Enumerate which addon provides which broker kind(s) for the\n * unified create picker. The auto-mount fans this array across\n * every registered `broker` provider (array-output method), so the\n * picker sees every kind from every provider in one call. */\n listProviders: method(z.void(), z.array(BrokerProviderInfoSchema), { auth: 'admin' }),\n add: method(AddInputSchema, AddResultSchema, { kind: 'mutation', auth: 'admin' }),\n remove: method(RemoveInputSchema, z.void(), { kind: 'mutation', auth: 'admin' }),\n testConnection: method(GetInputSchema, TestConnectionResultSchema, { kind: 'mutation', auth: 'admin' }),\n\n // ── Settings ─────────────────────────────────────────────────────\n /** Read the persisted settings record for a broker (kind-specific\n * shape). Admin-only — settings may contain secrets. Returns `null`\n * when the broker id is unknown to the provider (the collection\n * fallback may route a foreign id to the first provider). */\n getSettings: method(GetInputSchema, SettingsRecordSchema.nullable(), { auth: 'admin' }),\n /** Overwrite the persisted settings record. The kind-specific\n * provider validates the shape and applies the change (reconnects\n * if credentials changed). */\n setSettings: method(\n z.object({ id: z.string(), settings: SettingsRecordSchema }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n\n // ── Connection-config (for consumers that open their own client) ─\n /** Returns the kind-specific connection config the consumer needs\n * to open its own client (MQTT pattern: `{url, username, password,\n * clientIdPrefix}`). HA providers MAY return the auth envelope\n * but typical HA consumers use `publish` / `subscribe` instead.\n * Returns `null` when the broker id is unknown to the provider. */\n getBrokerConfig: method(GetInputSchema, SettingsRecordSchema.nullable(), { auth: 'admin' }),\n\n // ── Per-kind creation schema + pre-creation test ─────────────────\n getSettingsSchema: method(SettingsSchemaInputSchema, SettingsSchemaResultSchema, { auth: 'admin' }),\n testSettings: method(TestSettingsInputSchema, TestSettingsResultSchema, { kind: 'mutation', auth: 'admin' }),\n\n // ── Pub/sub primitives ───────────────────────────────────────────\n publish: method(PublishInputSchema, z.unknown(), { kind: 'mutation', auth: 'admin' }),\n subscribe: method(SubscribeInputSchema, SubscribeResultSchema, { kind: 'mutation', auth: 'admin' }),\n unsubscribe: method(UnsubscribeInputSchema, z.void(), { kind: 'mutation', auth: 'admin' }),\n\n /** Read the broker's cached state for a key. Returns `null` when\n * unknown to the broker (never published / unknown entity). */\n getState: method(GetStateInputSchema, z.unknown().nullable()),\n\n /** Status method — explicit registration with a `z.void()` input so\n * the codegen-generated tRPC router types its input as\n * `{addonId?: string, nodeId?: string}` (system-scoped collection\n * shape) instead of the device-scoped `{deviceId}` fallback. */\n getStatus: method(z.void(), RegistryStatusSchema),\n },\n} as const satisfies CapabilityDefinition\n\nexport type IBrokerProvider = InferProvider<typeof brokerCapability>\n\nexport {\n BrokerInfoSchema,\n BrokerProviderInfoSchema,\n RegistryStatusSchema as BrokerRegistryStatusSchema,\n TestConnectionResultSchema as BrokerTestConnectionResultSchema,\n PublishInputSchema as BrokerPublishInputSchema,\n SubscribeInputSchema as BrokerSubscribeInputSchema,\n SubscribeResultSchema as BrokerSubscribeResultSchema,\n UnsubscribeInputSchema as BrokerUnsubscribeInputSchema,\n GetStateInputSchema as BrokerGetStateInputSchema,\n AddInputSchema as BrokerAddInputSchema,\n SettingsSchemaInputSchema as BrokerSettingsSchemaInputSchema,\n TestSettingsInputSchema as BrokerTestSettingsInputSchema,\n TestSettingsResultSchema as BrokerTestSettingsResultSchema,\n}\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\n\n/**\n * `mqtt-broker` — broker-registry cap.\n *\n * NOT a pub/sub proxy. The cap exposes (a) a registry of configured\n * MQTT brokers (external + optionally an embedded `aedes`-backed one)\n * and (b) the connection details a consumer addon needs to spin up\n * its OWN `mqtt.js` client.\n *\n * Why: pub/sub routing over the system event-bus loses fidelity\n * (callback shape, QoS guarantees, will/retain semantics) and adds\n * refcount bookkeeping that addons would rather own themselves. The\n * canonical consumer (`addon-export-ha-mqtt`) needs raw `mqtt.js`\n * features anyway — give it the connection config, get out of the way.\n *\n * Consumer flow:\n * const cfg = await ctx.api.mqttBroker.getBrokerConfig({ id })\n * const client = mqtt.connect(cfg.url, { username: cfg.username, … })\n * client.subscribe('zigbee2mqtt/+')\n *\n * Collection mode: multiple brokers (e.g. one local mosquitto + one\n * cloud bridge). The \"embedded\" entry (when present) is just another\n * broker in the registry — its lifecycle is owned by the addon that\n * spawned it.\n */\n\nconst BrokerKindSchema = z.enum(['external', 'embedded'])\n\n/**\n * Broker live-probe status.\n *\n * - `connected` — last probe completed a clean CONNACK\n * - `disconnected` — no probe has run yet (cold cache)\n * - `auth-failed` — CONNACK refused with auth error (RC 4 / 5)\n * - `unreachable` — TCP connect timed out / refused\n * - `tls-error` — TLS handshake failed (cert / SNI / cipher)\n */\nconst BrokerStatusSchema = z.enum([\n 'connected',\n 'disconnected',\n 'auth-failed',\n 'unreachable',\n 'tls-error',\n])\n\nconst BrokerInfoSchema = z.object({\n id: z.string(),\n name: z.string(),\n url: z.string(),\n kind: BrokerKindSchema,\n status: BrokerStatusSchema,\n latencyMs: z.number().nullable(),\n error: z.string().optional(),\n /** Embedded brokers only: number of MQTT clients currently connected. */\n connectedClients: z.number().int().nonnegative().optional(),\n /** Epoch ms of the last live probe (external) or aedes snapshot (embedded). */\n lastCheckedAt: z.number().optional(),\n})\n\nexport type BrokerInfo = z.infer<typeof BrokerInfoSchema>\nexport type BrokerStatus = z.infer<typeof BrokerStatusSchema>\n\n/**\n * Connection details — what a consumer needs to call\n * `mqtt.connect(url, options)`. We split URL + credentials so the\n * consumer can pass them as `mqtt.connect(url, { username, password })`\n * instead of stuffing creds into the URL (which leaks them into logs).\n */\nconst BrokerConnectionDetailsSchema = z.object({\n url: z.string(),\n username: z.string().optional(),\n password: z.string().optional(),\n /**\n * Suggested prefix for `clientId`. Each consumer should suffix this\n * with its own discriminator (addon id, instance id) so reconnects\n * don't kick each other off (MQTT spec: clientId must be unique per\n * broker).\n */\n clientIdPrefix: z.string().optional(),\n})\n\nexport type BrokerConnectionDetails = z.infer<typeof BrokerConnectionDetailsSchema>\n\nconst AddBrokerInputSchema = z.object({\n name: z.string().min(1),\n url: z.string().regex(/^(mqtt|mqtts|ws|wss):\\/\\//, 'URL must start with mqtt(s):// or ws(s)://'),\n username: z.string().optional(),\n password: z.string().optional(),\n clientIdPrefix: z.string().optional(),\n})\n\nconst AddBrokerResultSchema = z.object({\n id: z.string(),\n})\n\nconst IdInputSchema = z.object({ id: z.string() })\n\nconst TestResultSchema = z.discriminatedUnion('ok', [\n z.object({ ok: z.literal(true), latencyMs: z.number() }),\n z.object({ ok: z.literal(false), error: z.string() }),\n])\n\nconst StartEmbeddedInputSchema = z.object({\n port: z.number().int().min(1).max(65535).default(1883),\n /** Allow anonymous connect (no username/password). Default: false. */\n allowAnonymous: z.boolean().default(false),\n /** Optional shared username/password for clients. */\n username: z.string().optional(),\n password: z.string().optional(),\n})\n\nconst StartEmbeddedResultSchema = z.object({\n id: z.string(),\n url: z.string(),\n})\n\nconst StatusSchema = z.object({\n brokerCount: z.number(),\n embeddedRunning: z.boolean(),\n})\n\nexport const mqttBrokerCapability = {\n name: 'mqtt-broker',\n scope: 'system',\n mode: 'collection',\n providerKind: 'broker',\n status: { schema: StatusSchema, kind: 'poll' },\n methods: {\n listBrokers: method(z.void(), z.array(BrokerInfoSchema)),\n getBrokerConfig: method(IdInputSchema, BrokerConnectionDetailsSchema),\n addBroker: method(AddBrokerInputSchema, AddBrokerResultSchema, { kind: 'mutation' }),\n removeBroker: method(IdInputSchema, z.void(), { kind: 'mutation' }),\n testConnection: method(IdInputSchema, TestResultSchema, { kind: 'mutation' }),\n startEmbeddedBroker: method(StartEmbeddedInputSchema, StartEmbeddedResultSchema, { kind: 'mutation' }),\n stopEmbeddedBroker: method(IdInputSchema, z.void(), { kind: 'mutation' }),\n getStatus: method(z.void(), StatusSchema),\n },\n} as const satisfies CapabilityDefinition\n\nexport type IMqttBrokerProvider = InferProvider<typeof mqttBrokerCapability>\n\nexport {\n BrokerInfoSchema,\n BrokerConnectionDetailsSchema,\n AddBrokerInputSchema,\n StartEmbeddedInputSchema,\n StatusSchema as MqttBrokerStatusSchema,\n}\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\n\n/**\n * `device-export` — collection cap for addons that export camstack\n * devices to external ecosystems (HomeAssistant via MQTT discovery,\n * HomeKit/HAP, Alexa Smart Home, …).\n *\n * No `ecosystem` enum — the addon id identifies the export target.\n * Each addon owns its mapping logic in its own settings UI. The cap\n * exposes only the COMMON surface: link state, supported device\n * kinds (so the UI can filter the device picker), and per-device\n * expose/unexpose.\n */\n\nconst LinkStateSchema = z.enum(['unlinked', 'linked', 'error'])\n\n/**\n * A single label/value row surfaced in the export panel's \"Setup\"\n * section. Rendered with a copy-to-clipboard button. `secret: true`\n * rows are masked by default with a reveal toggle (client ids,\n * secrets, …).\n */\nconst ExportSetupFieldSchema = z.object({\n label: z.string(),\n value: z.string(),\n /** Mask the value by default + render a reveal toggle (client id, secrets). */\n secret: z.boolean().optional(),\n})\n\n/**\n * Generic, addon-agnostic pairing/account block. Any export addon can\n * surface a scannable QR, a set of copyable label/value rows, and a\n * free-form operator note — the `DeviceExportPanel` renders whatever\n * the provider supplies and skips the section entirely when `setup`\n * is unset.\n */\nconst ExportSetupSchema = z.object({\n /** A string to render as a scannable QR — HAP `X-HM://…` URI, a pairing URL, etc. Omitted when there's nothing to scan. */\n qr: z.string().optional(),\n /** Label/value rows shown with a copy button (HAP setup code, OAuth URLs, client id, linked-account count, …). */\n fields: z.array(ExportSetupFieldSchema).readonly().optional(),\n /** Free-form operator instructions rendered above the fields. */\n note: z.string().optional(),\n})\n\nconst DeviceExportStatusSchema = z.object({\n linkState: LinkStateSchema,\n exposedDeviceCount: z.number(),\n error: z.string().optional(),\n /**\n * Optional pairing/account info the panel renders in a generic\n * \"Setup\" section. Addon-agnostic — the addon id identifies the\n * export target, never an `ecosystem` key here.\n */\n setup: ExportSetupSchema.optional(),\n})\n\nconst DeviceKindSchema = z.string() // camstack device kind (e.g. 'camera', 'switch')\n\nconst ExposedDeviceSchema = z.object({\n deviceId: z.string(),\n exposedAs: z.string().optional(),\n capabilities: z.array(z.string()).optional(),\n})\n\nconst ExposeInputSchema = z.object({\n deviceId: z.string(),\n capabilities: z.array(z.string()).optional(),\n})\n\nconst UnexposeInputSchema = z.object({ deviceId: z.string() })\n\nexport const deviceExportCapability = {\n name: 'device-export',\n scope: 'system',\n mode: 'collection',\n providerKind: 'device-export',\n status: { schema: DeviceExportStatusSchema, kind: 'poll' },\n /**\n * Each export provider contributes its own per-device \"Export\" panel\n * (enabled toggle, preferred stream, addon-specific knobs like the\n * HA-MQTT discovery prefix). The three framework methods\n * `getDeviceSettingsContribution` / `getDeviceLiveContribution` /\n * `applyDeviceSettingsPatch` are auto-injected on the provider\n * interface and routed to the device-details aggregator.\n */\n exposesDeviceSettings: true,\n methods: {\n getStatus: method(z.void(), DeviceExportStatusSchema),\n listSupportedDeviceKinds: method(z.void(), z.array(DeviceKindSchema)),\n listExposedDevices: method(z.void(), z.array(ExposedDeviceSchema)),\n exposeDevice: method(ExposeInputSchema, z.void(), { kind: 'mutation' }),\n unexposeDevice: method(UnexposeInputSchema, z.void(), { kind: 'mutation' }),\n },\n} as const satisfies CapabilityDefinition\n\nexport type IDeviceExportProvider = InferProvider<typeof deviceExportCapability>\n\nexport {\n DeviceExportStatusSchema,\n ExportSetupSchema,\n ExportSetupFieldSchema,\n ExposedDeviceSchema,\n ExposeInputSchema,\n UnexposeInputSchema,\n}\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\n\n/**\n * `addon-pages` — system-scoped singleton aggregator cap. Public-facing\n * surface that admin-ui consumes through `useAddonPagesListPages()`.\n *\n * The provider iterates every `addon-pages-source` (collection) provider\n * and emits `AddonPageInfo[]` enriched with versioned `bundleUrl` strings\n * pointing at `/api/addon-pages/<addonId>/<bundle>?v=<mtime>`. The\n * filesystem `mtime` cache-buster lets the browser pick up addon\n * rebuilds without manual reload.\n *\n * The hub-local builtin `addon-pages-aggregator` (see\n * `@camstack/core/builtins/addon-pages-aggregator`) registers the\n * provider. Splitting the public aggregator from the raw collection\n * keeps both ends in codegen — there's no hand-written\n * `addon-pages.router.ts` wrapper anymore.\n */\n\nconst AddonPageDeclarationSchema = z.object({\n id: z.string(),\n label: z.string(),\n icon: z.string(),\n path: z.string(),\n remoteName: z.string(),\n bundle: z.string(),\n})\n\nconst AddonPageInfoSchema = z.object({\n addonId: z.string(),\n page: AddonPageDeclarationSchema,\n bundleUrl: z.string(),\n})\n\nexport const addonPagesCapability = {\n name: 'addon-pages',\n scope: 'system',\n mode: 'singleton',\n methods: {\n listPages: method(z.void(), z.array(AddonPageInfoSchema).readonly()),\n },\n} as const satisfies CapabilityDefinition\n\nexport type IAddonPagesAggregatorProvider = InferProvider<typeof addonPagesCapability>\n\nexport { AddonPageInfoSchema }\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\n\n/**\n * `addon-pages-source` — collection cap exposing per-provider raw page\n * declarations. Every addon that contributes a UI page registers a\n * provider here. The hub-side singleton aggregator (`addon-pages` cap,\n * see `addon-pages.cap.ts`) walks this collection, stamps versioned\n * `bundleUrl` values, and returns the enriched `AddonPageInfo[]` list\n * that admin-ui consumes.\n *\n * The split exists because the public listing has a different output\n * shape than the per-provider raw declarations, and we want both ends\n * to flow through codegen instead of relying on a hand-written wrapper.\n */\nconst AddonPageDeclarationSchema = z.object({\n id: z.string(),\n label: z.string(),\n icon: z.string(),\n path: z.string(),\n /**\n * Module Federation remote name — must match the `name` field on the\n * page addon's `federation()` plugin config. Used by admin-ui's\n * `<AddonPageLoader>` to call `loadRemote('<remoteName>/page')`.\n * Conventionally `addon_<id>_page` (snake_case; MF names cannot\n * contain hyphens).\n */\n remoteName: z.string(),\n /**\n * Bundle filename inside the addon's `dist/` dir served at\n * `/api/addon-pages/<addonId>/<bundle>`. With Module Federation this\n * is always `'remoteEntry.js'`; the value is kept on the metadata so\n * the static-file route can compute an mtime-based cache-buster URL\n * without a separate filesystem stat.\n */\n bundle: z.string(),\n})\n\nexport const addonPagesSourceCapability = {\n name: 'addon-pages-source',\n scope: 'system',\n mode: 'collection',\n internal: true,\n methods: {\n listPages: method(z.void(), z.array(AddonPageDeclarationSchema).readonly()),\n },\n} as const satisfies CapabilityDefinition\n\nexport type IAddonPagesSourceProvider = InferProvider<typeof addonPagesSourceCapability>\n\nexport { AddonPageDeclarationSchema }\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider, type UiContributionRemote } from './capability-definition.js'\n\n/**\n * `addon-widgets-source` — collection cap exposing per-addon raw widget\n * declarations. Mirrors the addon-pages split: every addon shipping\n * widgets registers a provider on this collection cap; the hub-local\n * aggregator (`addon-widgets`, see `addon-widgets.cap.ts`) walks the\n * collection, stamps versioned `bundleUrl`s onto each declaration, and\n * exposes the public listing surface that admin-ui consumes.\n *\n * The split exists because the public listing has a different output\n * shape (flat enriched metadata with `addonId` + `bundleUrl`) than the\n * per-provider raw declarations. Both ends flow through codegen.\n *\n * Unified UI-contribution model (Task 10): a widget descriptor IS a\n * `UiContribution` with `kind:'remote'`. The host renders it through the\n * same `ContributionRenderer` / Module-Federation path as every other\n * contributed UI surface — no bespoke widget-rendering path. The widget-\n * only metadata (sizing hints, `requires`) lives as extra fields on the\n * descriptor; the `UiContribution` core (`tab` / `label` / `order` /\n * `kind` / `remote`) carries identity + placement + the MF remote.\n */\n\n/** Where the widget makes sense to render — maps to a contribution `tab`. */\nconst WidgetHostEnum = z.enum(['device-tab', 'dashboard', 'integration-detail'])\nconst WidgetSizeEnum = z.enum(['xs', 'sm', 'md', 'lg', 'xl'])\n\n/**\n * MF remote descriptor — mirrors `UiContributionRemote` from\n * `capability-definition.ts`. Widget remotes expose a single\n * `'./widgets'` module whose default export is a\n * `Record<componentKey, Component>` map; `componentKey` (the widget\n * `stableId`) picks the entry the host mounts.\n */\nconst WidgetRemoteSchema = z.object({\n remoteName: z.string(),\n exposedModule: z.string(),\n componentKey: z.string().optional(),\n})\n\n/**\n * Compile-time structural assertion that `WidgetRemoteSchema` stays in\n * lockstep with the `UiContributionRemote` TS interface. A field\n * divergence (rename, added required field, dropped field) breaks the\n * build instead of drifting silently. `satisfies z.ZodType<...>` is too\n * strict here because Zod's `.optional()` models `componentKey` as\n * `string | undefined` rather than an exact-optional property, so the\n * lenient assignment form is used instead.\n */\nconst _widgetRemoteSchemaCheck: z.ZodType<UiContributionRemote> = WidgetRemoteSchema\nvoid _widgetRemoteSchemaCheck\n\n/**\n * One widget declaration — a `UiContribution` (`kind:'remote'`) plus\n * widget-only metadata. The `UiContribution` core fields:\n *\n * - `tab` — where the widget hosts. A widget that runs on the\n * dashboard declares `tab:'dashboard'`; a device-tab\n * widget declares the target device-detail tab id.\n * - `subTab` — optional sub-tab within `tab`.\n * - `label` — operator-facing label.\n * - `order` — ordering within `(tab, subTab)`.\n * - `kind` — always `'remote'` for widgets.\n * - `remote` — the MF remote `{ remoteName, exposedModule, componentKey }`.\n *\n * Widget-only fields retained alongside the contribution core:\n *\n * - `stableId` — stable identity within the addon (the MF\n * `componentKey`; kept top-level so consumers have\n * a stable key without reaching into `remote`).\n * - `description` / `icon` — picker metadata.\n * - `bundle` — entry filename inside the addon `dist/` dir; the\n * aggregator stamps a versioned `bundleUrl` from it.\n * - `hosts` — every host the widget supports (a widget can run\n * both on the dashboard and a device tab). `tab`\n * is the PRIMARY host; `hosts` is the full set the\n * picker filters on.\n * - `requires` — host-context requirements validated at mount.\n * - `defaultSize` / `allowedSizes` / `defaultColumns` / `defaultRows`\n * — dashboard placement hints.\n */\nconst WidgetMetadataSchema = z.object({\n // ── UiContribution core (kind:'remote') ──────────────────────────\n /** Primary host tab — `'dashboard'`, `'device-tab'`, or a device-detail tab id. */\n tab: z.string(),\n /** Optional sub-tab within `tab`. */\n subTab: z.string().optional(),\n /** Operator-facing label. */\n label: z.string(),\n /** Ordering within `(tab, subTab)`, ascending. */\n order: z.number().optional(),\n /** Always `'remote'` — a widget is a Module Federation remote. */\n kind: z.literal('remote'),\n /** MF remote descriptor. */\n remote: WidgetRemoteSchema,\n\n // ── Widget-only metadata ─────────────────────────────────────────\n /** Stable id within the addon — kebab-case. Equals `remote.componentKey`. */\n stableId: z.string(),\n description: z.string().optional(),\n icon: z.string().optional(),\n /**\n * Bundle filename inside the addon's `dist/` dir served at\n * `/api/addon-widgets/<addonId>/<bundle>`. With Module Federation\n * this is always `'remoteEntry.js'` — the value is kept on the\n * metadata so the static-file route can compute an mtime-based\n * cache-buster URL without a separate filesystem stat.\n */\n bundle: z.string(),\n /** Every host the widget supports. The picker filters on this set. */\n hosts: z.array(WidgetHostEnum).readonly(),\n /** Required props the host must supply. Validated at `<WidgetSlot>` mount. */\n requires: z.object({\n deviceContext: z.boolean().default(false),\n integrationContext: z.boolean().default(false),\n }),\n /** Dashboard placement HINTS (operator can override per instance). */\n defaultSize: WidgetSizeEnum.default('md'),\n allowedSizes: z.array(WidgetSizeEnum).readonly().default(['sm', 'md', 'lg']),\n defaultColumns: z.number().int().min(1).max(12).default(6),\n defaultRows: z.number().int().min(1).max(12).default(1),\n})\n\nexport const addonWidgetsSourceCapability = {\n name: 'addon-widgets-source',\n scope: 'system',\n mode: 'collection',\n internal: true,\n methods: {\n listWidgets: method(z.void(), z.array(WidgetMetadataSchema).readonly()),\n },\n} as const satisfies CapabilityDefinition\n\nexport type IAddonWidgetsSourceProvider = InferProvider<typeof addonWidgetsSourceCapability>\n\n/** A single widget declaration — a `UiContribution` (`kind:'remote'`) + widget metadata. */\nexport type WidgetMetadata = z.infer<typeof WidgetMetadataSchema>\n\nexport { WidgetMetadataSchema, WidgetRemoteSchema, WidgetHostEnum, WidgetSizeEnum }\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { WidgetMetadataSchema } from './addon-widgets-source.cap.js'\n\n/**\n * `addon-widgets` — system-scoped singleton aggregator cap. Public-facing\n * surface that admin-ui consumes through `useAddonWidgetsListWidgets()`.\n *\n * The provider iterates every `addon-widgets-source` (collection)\n * provider and emits `EnrichedWidgetMetadata[]` enriched with versioned\n * `bundleUrl` strings pointing at\n * `/api/addon-widgets/<addonId>/<bundle>?v=<mtime>`. The filesystem\n * `mtime` cache-buster lets the browser pick up addon rebuilds without\n * manual reload — same scheme used by `addon-pages`.\n *\n * The hub-local builtin `addon-widgets-aggregator` (see\n * `@camstack/core/builtins/addon-widgets-aggregator`) registers the\n * provider. Splitting the public aggregator from the raw collection\n * keeps both ends in codegen — there's no hand-written wrapper.\n */\n\nconst EnrichedWidgetMetadataSchema = WidgetMetadataSchema.extend({\n addonId: z.string(),\n bundleUrl: z.string(),\n})\n\nexport const addonWidgetsCapability = {\n name: 'addon-widgets',\n scope: 'system',\n mode: 'singleton',\n methods: {\n listWidgets: method(z.void(), z.array(EnrichedWidgetMetadataSchema).readonly()),\n },\n} as const satisfies CapabilityDefinition\n\nexport type IAddonWidgetsAggregatorProvider = InferProvider<typeof addonWidgetsCapability>\n\n/** One enriched widget row — `WidgetMetadata` + aggregator-stamped `addonId` + `bundleUrl`. */\nexport type EnrichedWidgetMetadata = z.infer<typeof EnrichedWidgetMetadataSchema>\n\nexport { EnrichedWidgetMetadataSchema }\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\n\nconst AddonHttpRouteSchema = z.object({\n method: z.enum(['GET', 'POST', 'PUT', 'DELETE', 'PATCH']),\n path: z.string(),\n access: z.enum(['public', 'authenticated', 'admin']).optional(),\n description: z.string().optional(),\n})\n\n/**\n * Cross-process route invocation envelope. The hub captures the\n * request as plain data, ships it to the worker via Moleculer, and\n * the worker runs the local handler against a capturing reply. The\n * envelope returned describes what the handler intended (status,\n * headers, body, or a redirect) so the hub can translate it back to\n * the Fastify reply that's actually wired to the socket.\n */\nconst InvokeRequestSchema = z.object({\n method: z.string(),\n path: z.string(),\n params: z.record(z.string(), z.string()),\n query: z.record(z.string(), z.string()),\n body: z.unknown(),\n headers: z.record(z.string(), z.string()),\n user: z.object({\n id: z.string(),\n username: z.string(),\n isAdmin: z.boolean(),\n }).optional(),\n scopedToken: z.unknown().optional(),\n})\n\nconst InvokeReplyEnvelopeSchema = z.object({\n status: z.number().int(),\n headers: z.record(z.string(), z.string()),\n /** When set, the hub MUST `reply.redirect(redirectUrl)` instead of\n * sending `body`. Status defaults to 302 when this is set unless\n * the handler called `reply.code(...)` explicitly. */\n redirectUrl: z.string().nullable(),\n /** JSON-serializable body. `undefined` is treated as \"no body\". */\n body: z.unknown().optional(),\n /** Set when the handler called `reply.type(mime)`. */\n contentType: z.string().optional(),\n})\n\nexport const addonRoutesCapability = {\n name: 'addon-routes',\n scope: 'system',\n mode: 'collection',\n internal: true,\n methods: {\n getRoutes: method(z.void(), z.array(AddonHttpRouteSchema)),\n /**\n * Cross-process dispatch entry point. Forked addons implement this\n * (via `buildAddonRouteProvider`) so the hub's Fastify catch-all\n * can route through Moleculer when the handler lives in a worker.\n *\n * Local addons can implement it for free with the same helper;\n * the hub bypasses the wire on co-located addons.\n */\n invoke: method(InvokeRequestSchema, InvokeReplyEnvelopeSchema, { kind: 'mutation' }),\n },\n} as const satisfies CapabilityDefinition\n\nexport type IAddonRoutesProvider = InferProvider<typeof addonRoutesCapability>\nexport { InvokeRequestSchema, InvokeReplyEnvelopeSchema }\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport type { HwAccelBackend } from '../interfaces/addon.js'\nimport {\n DecoderSessionConfigSchema,\n DecoderStatsSchema,\n} from '../interfaces/stream-broker.js'\nimport {\n EncodedPacketSchema,\n DecodedFrameSchema,\n FrameHandleSchema,\n} from './schemas/streaming-shared.js'\n\n/**\n * Operator-facing hwaccel selection — wins over `probedBestHwaccel`\n * when concrete; `'auto'` defers to the session's local resolver\n * (`ctx.kernel.hwaccel`) which probes the host. Shared across every\n * decoder addon (node-av, ffmpeg, …) so UI + settings + sessions all\n * speak the same vocabulary.\n */\nexport type HwAccelChoice = 'auto' | 'none' | HwAccelBackend\n\n/**\n * Stable UI option list for the `hwaccel` setting. Decoder addons\n * reuse this for `globalSettingsSchema()` so the dropdown is\n * identical everywhere. Order: auto → off → common backends by\n * platform affinity (macOS, NVIDIA, Intel/AMD, Windows, Linux).\n */\nexport const HWACCEL_OPTIONS: ReadonlyArray<{ value: HwAccelChoice; label: string }> = [\n { value: 'auto', label: 'Auto (defer to probed best)' },\n { value: 'none', label: 'Off (software)' },\n { value: 'videotoolbox', label: 'VideoToolbox (macOS)' },\n { value: 'cuda', label: 'CUDA (NVIDIA)' },\n { value: 'nvdec', label: 'NVDEC (NVIDIA legacy)' },\n { value: 'vaapi', label: 'VAAPI (Linux Intel/AMD)' },\n { value: 'qsv', label: 'QuickSync (Intel)' },\n { value: 'd3d11va', label: 'D3D11VA (Windows)' },\n { value: 'dxva2', label: 'DXVA2 (Windows legacy)' },\n { value: 'amf', label: 'AMF (AMD)' },\n { value: 'vdpau', label: 'VDPAU (Linux NVIDIA legacy)' },\n { value: 'drm', label: 'DRM (Linux generic)' },\n]\n\n/**\n * Shared shape of a decoder addon's global settings. Every decoder\n * owns its own instance (node-av, ffmpeg, future backends) — they\n * don't share a store, but they share this config shape.\n */\nexport interface DecoderHwAccelConfig {\n readonly hwaccel: HwAccelChoice\n readonly probedBestHwaccel: string\n}\n\nexport const DEFAULT_DECODER_HWACCEL_CONFIG: DecoderHwAccelConfig = {\n hwaccel: 'auto',\n probedBestHwaccel: '',\n}\n\n/**\n * shm ring usage stats for a `frameSink: 'shm'` decoder session —\n * exposed via `decoder.getShmStats` so downstream consumers can\n * observe ring pressure (slot count, byte budget, hit/miss ratio).\n */\nexport const ShmRingStatsSchema = z.object({\n sessionId: z.string(),\n slotCount: z.number().int(),\n slotByteLength: z.number().int(),\n segmentBytes: z.number().int(),\n budgetMb: z.number().int(),\n framesWritten: z.number().int(),\n getFrameHits: z.number().int(),\n getFrameMisses: z.number().int(),\n})\n\n/** shm ring usage stats payload — see {@link ShmRingStatsSchema}. */\nexport type ShmRingStats = z.infer<typeof ShmRingStatsSchema>\n\nexport const decoderCapability = {\n name: 'decoder',\n scope: 'system',\n // Singleton — one decoder per node. `decoder-nodeav` is the default\n // install; operators can swap to a different provider via the\n // binding system's active-addon selection. The old collection shape\n // existed to let node-av + ffmpeg coexist and priority-sort at\n // stream-start; that fallback was dropped once node-av covered the\n // full codec matrix.\n mode: 'singleton',\n methods: {\n // ── Discovery ─────────────────────────────────────────────────\n supportsCodec: method(z.object({ codec: z.string() }), z.boolean()),\n getInfo: method(z.void(), z.object({\n id: z.string(),\n name: z.string(),\n isPullMode: z.boolean().optional(),\n priority: z.number().optional(),\n })),\n\n // ── Session lifecycle ─────────────────────────────────────────\n // `nodeId` carries the Moleculer nodeID of the decoder provider that\n // owns the session. Brokers store it so they can react to per-agent\n // events (e.g. `pipeline.agent-hwaccel-changed`) and rotate only the\n // sessions that actually live on the affected node.\n createSession: method(DecoderSessionConfigSchema, z.object({ sessionId: z.string(), nodeId: z.string() })),\n destroySession: method(z.object({ sessionId: z.string() }), z.void()),\n\n // ── Data plane ────────────────────────────────────────────────\n pushPacket: method(z.object({\n sessionId: z.string(),\n packet: EncodedPacketSchema,\n }), z.void()),\n openStream: method(z.object({\n sessionId: z.string(),\n url: z.string(),\n }), z.void()),\n\n // ── Output — polling-based frame retrieval ────────────────────\n // `pullFrames` drains the pixel `DecodedFrame[]` of a `frameSink:\n // 'callback'` session. `pullHandles` (Phase 5 / D9) drains the\n // zero-pixel `FrameHandle[]` of a `frameSink: 'shm'` session — the\n // broker hands each handle to a `FrameRingReader` that opens the\n // named segment and reads the pixels back zero-copy. A session is\n // one mode or the other; the unmatched method returns an empty\n // array.\n pullFrames: method(z.object({\n sessionId: z.string(),\n maxCount: z.number().default(1),\n }), z.array(DecodedFrameSchema)),\n pullHandles: method(z.object({\n sessionId: z.string(),\n maxCount: z.number().default(1),\n }), z.array(FrameHandleSchema)),\n\n // ── Frame fetch (Phase 5 / D9 downstream access) ──────────────\n // Read the pixels a FrameHandle refers to from this node's shm ring.\n // Returns null when the slot was already recycled (latest-wins).\n getFrame: method(z.object({ handle: FrameHandleSchema }), DecodedFrameSchema.nullable()),\n // shm ring usage stats for a session.\n getShmStats: method(z.object({ sessionId: z.string() }), ShmRingStatsSchema.nullable()),\n\n // ── Control ───────────────────────────────────────────────────\n updateConfig: method(z.object({\n sessionId: z.string(),\n config: DecoderSessionConfigSchema.partial(),\n }), z.void()),\n getStats: method(z.object({ sessionId: z.string() }), DecoderStatsSchema),\n\n // ── Inventory — session-level state ONLY ─────────────────────\n // Sessions are a decoder concept, so `listActiveSessions` lives\n // here. Process-level measurements (memory/cpu) go through the\n // generic `metrics-provider` cap — decoder stays free of\n // observability concerns that aren't specific to decoding.\n listActiveSessions: method(z.void(), z.array(z.object({\n sessionId: z.string(),\n codec: z.string(),\n outputFormat: z.string(),\n createdAtMs: z.number(),\n })).readonly()),\n\n /**\n * Re-run the host platform-probe for the decoder's hwaccel backend\n * and write the detected value into the addon's own global\n * settings (`probedBestHwaccel`). Replaces the legacy per-agent\n * `pipeline-orchestrator.reprobeAgentHwAccel` — each decoder addon\n * now owns its own probe.\n *\n * Returns the backend the probe picked (`'none'` = software-only\n * host, otherwise one of `HwAccelBackend`). The operator's\n * `hwaccel` setting (auto / none / backend) is not touched; only\n * the `probedBestHwaccel` hint.\n */\n reprobeHwaccel: method(\n z.void(),\n z.object({ backend: z.string() }),\n { kind: 'mutation', auth: 'admin' },\n ),\n },\n} as const satisfies CapabilityDefinition\n\nexport type IDecoderCapProvider = InferProvider<typeof decoderCapability>\n\n/**\n * Pure cap-only view of the decoder provider.\n *\n * For the in-process interface with live `createSession()`, `id`, `name`,\n * `priority`, `isPullMode` fields, consumers should import\n * `IDecoderProvider` from `@camstack/types/interfaces/decoder` — that\n * remains the canonical in-process contract the broker + tests depend\n * on. The live `createSession()` + session object cannot cross process\n * boundaries and will need a session-id based cap API (Phase 4, decoder\n * forkable work) — tracked separately, not in scope for session 5\n * Sprint A.\n *\n * Prior to session 5 this alias used to extend the inferred cap type\n * with the live fields, creating a hybrid interface. No consumer ever\n * referenced `IDecoderProviderV2` — the broker, tests, and addon\n * implementations all imported `IDecoderProvider` directly. The\n * extension was therefore dead code and is removed here.\n */\n\nexport { DecoderSessionConfigSchema }\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\n\nconst RegisteredStreamSchema = z.object({\n streamId: z.string(),\n label: z.string().optional(),\n codec: z.string(),\n type: z.enum(['video', 'audio']),\n sourceUrl: z.string(),\n})\n\nconst ExposedResourceSchema = z.object({\n streamId: z.string(),\n format: z.string(),\n value: z.string(),\n})\n\nexport const restreamerCapability = {\n name: 'restreamer',\n scope: 'system',\n mode: 'collection',\n internal: true,\n methods: {\n registerDevice: method(\n z.object({ deviceId: z.number(), streams: z.array(RegisteredStreamSchema).readonly() }),\n z.void(),\n { kind: 'mutation' },\n ),\n unregisterDevice: method(z.object({ deviceId: z.number() }), z.void(), { kind: 'mutation' }),\n getExposedResources: method(\n z.object({ deviceId: z.number() }),\n z.array(ExposedResourceSchema).readonly(),\n ),\n },\n} as const satisfies CapabilityDefinition\n\nexport type IRestreamerProvider = InferProvider<typeof restreamerCapability>\n\nexport { RegisteredStreamSchema, ExposedResourceSchema }\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\n\n/**\n * Optional client-side hints sent at session creation to help the\n * provider pick the best native source. All fields are optional —\n * a viewer that knows nothing still gets a sane default.\n */\nexport const webrtcClientHintsSchema = z.object({\n viewportWidth: z.number().int().positive().optional(),\n viewportHeight: z.number().int().positive().optional(),\n devicePixelRatio: z.number().positive().optional(),\n /** navigator.connection.downlink — Mbps the browser estimates. */\n downlinkMbps: z.number().nonnegative().optional(),\n /** Hard tier override; takes precedence over scoring when registered. */\n prefersTier: z.string().optional(),\n}).partial()\n\nexport type WebrtcClientHints = z.infer<typeof webrtcClientHintsSchema>\n\nexport const webrtcCapability = {\n name: 'webrtc',\n scope: 'system',\n mode: 'collection',\n internal: true,\n methods: {\n handleOffer: method(\n z.object({ streamId: z.string(), sdpOffer: z.string() }),\n z.string(),\n { kind: 'mutation' },\n ),\n supportsStream: method(z.object({ streamId: z.string() }), z.boolean()),\n registerStream: method(\n z.object({ streamId: z.string(), codec: z.string() }),\n z.void(),\n { kind: 'mutation' },\n ),\n unregisterStream: method(z.object({ streamId: z.string() }), z.void(), { kind: 'mutation' }),\n /**\n * Two-step server-offer signaling. `hints` is optional — providers\n * that don't care about adaptive source selection ignore it.\n */\n createSession: method(\n z.object({\n streamId: z.string(),\n hints: webrtcClientHintsSchema.optional(),\n }),\n z.object({ sessionId: z.string(), sdpOffer: z.string() }),\n { kind: 'mutation' },\n ),\n handleAnswer: method(\n z.object({ sessionId: z.string(), sdpAnswer: z.string() }),\n z.void(),\n { kind: 'mutation' },\n ),\n closeSession: method(z.object({ sessionId: z.string() }), z.void(), { kind: 'mutation' }),\n /**\n * Whether this provider supports adaptive bitrate for the given stream.\n * Currently always false — adaptive selection is one-shot at session\n * start, not in-session encoder switching. Phase 5 plans to layer\n * encoder-driven adaptation on top.\n */\n hasAdaptiveBitrate: method(\n z.object({ streamId: z.string() }),\n z.boolean(),\n ),\n },\n} as const satisfies CapabilityDefinition\n\nexport type IWebrtcProvider = InferProvider<typeof webrtcCapability>\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\nimport { CamProfileSchema } from './schemas/streaming-shared.js'\nimport { webrtcClientHintsSchema } from './webrtc.cap.js'\nimport { BrokerConsumerAttributionSchema } from './stream-broker.cap.js'\n\n/**\n * Discriminated target for a WebRTC session. The client sends this\n * structured object instead of building / parsing brokerId strings;\n * the server resolves it to a brokerId via the assignments map.\n *\n * - `adaptive`: server picks the best broker for the device based on\n * client hints (viewport, downlink).\n * - `profile`: pin the session to a profile slot (`high`/`mid`/`low`).\n * The actual source can change as the operator reassigns the slot.\n * - `cam-stream`: pin the session to a specific source by camStreamId\n * (e.g. `native:main`, `rtsp:sub`). Useful when the operator wants\n * a stable view of a specific source regardless of profile bindings,\n * or to consume a manually-activated stream that isn't profile-bound.\n */\nexport const WebrtcStreamTargetSchema = z.discriminatedUnion('kind', [\n z.object({ kind: z.literal('adaptive') }),\n z.object({ kind: z.literal('profile'), profile: CamProfileSchema }),\n z.object({ kind: z.literal('cam-stream'), camStreamId: z.string().min(1) }),\n])\nexport type WebrtcStreamTarget = z.infer<typeof WebrtcStreamTargetSchema>\n\n/** A stream choice the UI can offer for a device. */\nexport const WebrtcStreamChoiceSchema = z.object({\n /** Stable id for React keys / dropdowns (e.g. `'adaptive'`, `'profile:high'`, `'stream:native:main'`). */\n id: z.string(),\n /** Display label. */\n label: z.string(),\n /** Discriminated target — pass straight to `createSession`. */\n target: WebrtcStreamTargetSchema,\n /** Codec of the underlying broker stream (null for adaptive). */\n codec: z.string().nullable(),\n /** Resolution of the underlying stream (null for adaptive). */\n resolution: z.object({ width: z.number(), height: z.number() }).nullable(),\n /** Broker status (null for adaptive). */\n status: z.enum(['idle', 'connecting', 'streaming', 'error', 'stopped']).nullable(),\n /** Input FPS from the camera (null for adaptive). */\n inputFps: z.number().nullable(),\n /** Decoded FPS (null for adaptive). */\n decodeFps: z.number().nullable(),\n /** Bitrate in kbps (null for adaptive). */\n bitrateKbps: z.number().nullable(),\n})\nexport type WebrtcStreamChoice = z.infer<typeof WebrtcStreamChoiceSchema>\n\n/**\n * WebRTC session — device-scoped facade over the system `webrtc` cap.\n *\n * Exposes per-device signaling (`createSession`, `handleAnswer`,\n * `closeSession`) on the device proxy so UI / integrations can\n * negotiate a session by (deviceId, profile) instead of constructing\n * an opaque `${deviceId}/${profile}` streamId string. The provider is\n * registered by the stream-broker addon for every camera device with\n * at least one active profile slot; internally it resolves\n * `${deviceId}/${profile}` and forwards to the system webrtc provider.\n *\n * The system `webrtc` cap remains available for cross-device / raw\n * streamId callers (debugging, admin tools). Production UI should\n * prefer this device-scoped cap.\n */\nexport const webrtcSessionCapability = {\n name: 'webrtc-session',\n scope: 'device',\n mode: 'singleton',\n kind: 'wrapper',\n defaultActive: true,\n // Deterministic default active provider: the werift stream-broker. Without\n // this, a second registered provider (historically the libwebrtc\n // webrtc-native addon) could win by registration order across reboots.\n preferredProvider: 'stream-broker',\n deviceTypes: [DeviceType.Camera],\n methods: {\n /**\n * List available WebRTC streams for a device.\n * Returns adaptive (if any profile is assigned) + each assigned profile\n * with codec/resolution info. UI renders this directly — no hardcoded\n * profile names needed.\n */\n listStreams: method(\n z.object({ deviceId: z.number().int().nonnegative() }),\n z.array(WebrtcStreamChoiceSchema),\n ),\n /**\n * Open a WebRTC session against a specific target on the device.\n * `target.kind` discriminates between adaptive selection, a profile\n * slot, or a specific cam stream source — see `WebrtcStreamTarget`.\n * The server resolves the target to a live broker; clients never\n * build or parse brokerId strings.\n */\n createSession: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n target: WebrtcStreamTargetSchema,\n hints: webrtcClientHintsSchema.optional(),\n /**\n * SERVER-INJECTED — NOT a client hint. The hub layer that holds\n * the tRPC request context (and therefore the client IP) sets\n * this to `true` when the viewer's source IP is non-LAN\n * (4G/CGNAT/internet). The broker then forces TURN-relay-only\n * ICE for the session so a CGNAT client (which can only offer a\n * relay candidate) gets a clean relay↔relay media path instead\n * of werift nominating a dead host/hairpin-srflx pair. LAN\n * clients leave this absent/false and keep the low-latency\n * direct (host/srflx) path. Clients MUST NOT send this — the\n * server overwrites it from the request context.\n */\n relayOnly: z.boolean().optional(),\n /**\n * Subscriber attribution surfaced in the stream-broker widget's\n * client list. Callers (Alexa addon, browser hooks, WHEP server)\n * populate `kind` and any of `label`/`userId`/`sessionId`/\n * `remoteAddr` they know. The hub layer enriches `remoteAddr`\n * from the tRPC request context.\n */\n consumerAttribution: BrokerConsumerAttributionSchema.optional(),\n }),\n z.object({ sessionId: z.string(), sdpOffer: z.string() }),\n { kind: 'mutation' },\n ),\n /**\n * Accept a CLIENT-generated SDP offer and return the server's\n * SDP answer. Mirrors the WHEP / Alexa\n * `Alexa.RTCSessionController.InitiateSessionWithOffer` direction\n * (client offers, server answers) — the dual of `createSession`,\n * which has the server offer first.\n *\n * `target` defaults to the device's adaptive selection when\n * omitted; an optional `sessionId` lets the client provide its\n * own correlation id (Alexa supplies one in the directive\n * payload). The returned `sessionId` is whatever the server uses\n * to track the session and accepts via `closeSession`.\n */\n handleOffer: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n target: WebrtcStreamTargetSchema.optional(),\n sdpOffer: z.string(),\n sessionId: z.string().optional(),\n /**\n * Force TURN-relay-only ICE for this session. Two kinds of caller\n * set it:\n * - A cloud peer like Alexa's RTCSessionController (reachable\n * only via TURN, never our host/srflx behind NAT) passes\n * `true` from its own trusted addon context.\n * - The hub injects it for browser client-offer viewers from the\n * request's source IP (non-LAN ⇒ true), exactly as it does for\n * `createSession`.\n * A LAN/Tailscale browser doing client-offer passthrough leaves it\n * absent/false so a direct host pair carries full native quality.\n * Untrusted browser clients MUST NOT send it — the hub overwrites\n * it from the request context.\n */\n relayOnly: z.boolean().optional(),\n /**\n * Force a NON-TRICKLE answer: the server awaits ICE gathering to\n * COMPLETE and returns a full-candidate answer SDP (with `a=candidate`\n * lines) instead of the default bare/trickle answer.\n *\n * Set `true` by callers that DON'T support trickle ICE — notably\n * Alexa's RTCSessionController, which never polls `getIceCandidates`\n * nor trickles back via `addIceCandidate`, so without server\n * candidates in the answer SDP its ICE agent stalls (no nominated\n * pair → DTLS never connects → Echo shows black → SessionDisconnected).\n *\n * Browser viewers leave it absent/false: they poll `getIceCandidates`\n * and trickle, so the bare answer lets media start in ~0s instead of\n * blocking on full gathering.\n */\n nonTrickle: z.boolean().optional(),\n /**\n * Suppress TURN servers from the per-session iceConfig: the answer\n * will carry ONLY host + srflx candidates, never a relay one.\n *\n * Set `true` by peers that are themselves directly reachable on the\n * public internet (Alexa's RTCSessionController media gateway is\n * AWS-hosted with public host candidates). Including a TURN relay\n * for such a peer is counterproductive: (a) gathering blocks on the\n * TURN allocation round-trip and slows the answer; (b) werift\n * spends ICE-checking budget on a relay-pair that the peer cannot\n * use, sometimes stalling the host/srflx pair validation enough\n * that Echo's agent times out before nominating one — visible as\n * 'ICE checking → DTLS never connected'. Browser viewers leave it\n * absent/false so the relay candidate remains as a fallback for\n * symmetric-NAT clients.\n *\n * Independent from `relayOnly`. `relayOnly: true` forces ICE to a\n * relay-only pair set; `disableTurn: true` strips the relay\n * candidate entirely. They are mutually exclusive in practice but\n * not policed at the schema level — callers MUST NOT set both.\n */\n disableTurn: z.boolean().optional(),\n /**\n * Suppress IPv6 host candidates from gathering and from\n * `additionalHostAddresses`. The answer SDP will contain only IPv4\n * host/srflx (and TURN, unless `disableTurn` is also set).\n *\n * Set `true` by peers that document IPv4-only ICE — Amazon's\n * `Alexa.RTCSessionController` spec states: \"For ICE candidates,\n * you can use either UDP or TCP but you must use IPv4.\" Echo's\n * media gateway ignores IPv6 candidates and they consume budget\n * against the gateway's documented 6-second SDP processing limit.\n *\n * Browser viewers leave it absent/false so IPv6-only paths\n * (Tailscale, native dual-stack) remain available.\n */\n disableIpv6: z.boolean().optional(),\n /** Subscriber attribution. See `createSession` for the contract. */\n consumerAttribution: BrokerConsumerAttributionSchema.optional(),\n }),\n z.object({ sessionId: z.string(), sdpAnswer: z.string() }),\n { kind: 'mutation' },\n ),\n handleAnswer: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n sessionId: z.string(),\n sdpAnswer: z.string(),\n }),\n z.void(),\n { kind: 'mutation' },\n ),\n /**\n * Trickle ICE — add a remote (client) ICE candidate to a live session.\n * Lets the client send its SDP offer/answer IMMEDIATELY (before ICE\n * gathering finishes) and deliver candidates as they arrive, so the\n * connection establishes in ~0s instead of waiting for full gathering.\n * The dual of `getIceCandidates` in the trickle-ICE signaling exchange.\n */\n addIceCandidate: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n sessionId: z.string(),\n candidate: z.string(),\n sdpMid: z.string().nullable().optional(),\n sdpMLineIndex: z.number().int().nullable().optional(),\n }),\n z.void(),\n { kind: 'mutation' },\n ),\n /**\n * Trickle ICE — poll the server's gathered ICE candidates for a session.\n * The server answers immediately (no gathering wait) and the client polls\n * this to receive host/srflx/relay candidates as werift gathers them,\n * adding each to its PeerConnection. Returns all candidates gathered so\n * far; the client dedupes. `done` flips true once gathering completes.\n */\n getIceCandidates: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n sessionId: z.string(),\n }),\n z.object({\n candidates: z.array(z.object({\n candidate: z.string(),\n sdpMid: z.string().nullable(),\n sdpMLineIndex: z.number().int().nullable(),\n })),\n done: z.boolean(),\n }),\n { kind: 'query' },\n ),\n closeSession: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n sessionId: z.string(),\n }),\n z.void(),\n { kind: 'mutation' },\n ),\n /** Whether the underlying provider supports adaptive bitrate for this profile. */\n hasAdaptiveBitrate: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n profile: CamProfileSchema,\n }),\n z.boolean(),\n ),\n /** Poll the live signaling state of a session. `pendingRenegotiation` is\n * non-null after an adaptive tier switch — the client re-offers on the\n * same sessionId; `epoch` guards against acting on a stale poll twice. */\n getSessionState: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n sessionId: z.string(),\n }),\n z.object({\n pendingRenegotiation: z\n .object({ target: WebrtcStreamTargetSchema, epoch: z.number() })\n .nullable(),\n }),\n ),\n },\n} as const satisfies CapabilityDefinition\n\nexport type IWebrtcSessionProvider = InferProvider<typeof webrtcSessionCapability>\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { RunnerLocalLoadSchema } from './pipeline-runner.cap.js'\nimport { CameraMetricsSchema } from './schemas/orchestrator-metrics.js'\nimport { PipelineEngineChoiceSchema, PipelineStepInputSchema } from './pipeline-executor.cap.js'\n\n// ── Per-camera pipeline config & templates ─────────────────────────\n//\n// Stateless-pipeline model (spec: 2026-04-18-stateless-pipeline-per-camera):\n// the orchestrator owns per-camera pipelines and the global template\n// library. Runners never persist; they receive content via attachCamera.\n\nconst CameraPipelineConfigSchema = z.object({\n engine: PipelineEngineChoiceSchema,\n steps: z.array(PipelineStepInputSchema).readonly(),\n audio: z.object({\n engine: PipelineEngineChoiceSchema,\n modelId: z.string(),\n enabled: z.boolean(),\n settings: z.record(z.string(), z.unknown()).readonly().optional(),\n }).nullable().optional(),\n})\n\nconst PipelineTemplateSchema = z.object({\n id: z.string(),\n name: z.string(),\n description: z.string().optional(),\n config: CameraPipelineConfigSchema,\n createdAt: z.string(),\n updatedAt: z.string(),\n})\n\n// ── 3-level pipeline settings schemas ─────────────────────────────────\n// Agent-level addon config: one entry per addonId in the catalog. The\n// resolver expands this flat map into a tree at dispatch time using\n// catalog compat (inputClasses ↔ outputClasses).\nconst AgentAddonConfigSchema = z.object({\n enabled: z.boolean(),\n modelId: z.string(),\n settings: z.record(z.string(), z.unknown()).readonly(),\n})\n\n// Agent settings (phase 2f): only `addonDefaults` remain on the\n// orchestrator. `userChoice`, `hwaccel`, `audio`, and the authoritative\n// engine triple all moved to per-addon global settings\n// (detection-pipeline / decoder-nodeav / decoder-ffmpeg / audio-analyzer).\nconst AgentPipelineSettingsSchema = z.object({\n addonDefaults: z.record(z.string(), AgentAddonConfigSchema).readonly(),\n})\n\n// Per-agent wholesale pipeline override — a camera can pin a full\n// pipeline for a specific agent, bypassing addonDefaults + stepToggles.\n// The **engine** is NOT carried here: per the 3-level design, the\n// device+agent override still runs under the engine selected on that\n// agent (detection-pipeline global settings there). The operator\n// picks which steps + what audio run — not which engine — so that\n// moving a camera between agents with different engines doesn't\n// require rewriting the override. Same applies to `audio.engine` —\n// inferred from the agent, not stored per-override.\nconst CameraPipelineForAgentSchema = z.object({\n steps: z.array(PipelineStepInputSchema).readonly(),\n audio: z.object({\n modelId: z.string(),\n enabled: z.boolean(),\n }).nullable(),\n})\n\n// Per-(device, agent, addon) shallow patch over agent.addonDefaults[addonId].\n// All fields optional — unset means \"inherit from agent default\".\nconst CameraStepOverridePatchSchema = z.object({\n enabled: z.boolean().optional(),\n modelId: z.string().optional(),\n settings: z.record(z.string(), z.unknown()).readonly().optional(),\n})\n\n// Camera settings — sparse overlay on agent defaults.\nconst CameraPipelineSettingsSchema = z.object({\n pinnedAgentNodeId: z.string().optional(),\n stepToggles: z.record(z.string(), z.boolean()).optional(),\n stepOverridesByAgent: z.record(\n z.string(),\n z.record(z.string(), CameraStepOverridePatchSchema),\n ).optional(),\n pipelineByAgent: z.record(z.string(), CameraPipelineForAgentSchema).optional(),\n})\n\n/**\n * Pipeline placement record persisted by `addon-pipeline-orchestrator` via\n * the multi-level settings store. The orchestrator looks up these records\n * on every `DeviceStreamsRegistered` event to decide whether the camera\n * has a manual pipeline node pin (L1 affinity) or whether the load\n * balancer (L2 capacity / L3 hardware-aware) needs to pick one.\n *\n * Naming convention: `{Pipeline,Decoder}AssignmentSchema` — one schema per\n * placement domain managed by the orchestrator.\n */\nconst PipelineAssignmentSchema = z.object({\n deviceId: z.number(),\n /** Moleculer node id of the runner currently responsible for this camera. */\n agentNodeId: z.string(),\n /** True when the assignment was set manually, false when chosen by the balancer. */\n pinned: z.boolean(),\n /** Why this assignment was made — useful for debugging the load balancer. */\n reason: z.enum(['manual', 'capacity', 'hardware-affinity', 'failover', 'rebalance']),\n /** Unix timestamp (ms) when the assignment was last updated. */\n assignedAt: z.number(),\n})\n\n/**\n * Decoder placement record. Symmetric to `PipelineAssignmentSchema` but for\n * the decoder-node placement domain (`balanceDecoder` decision: manual pin\n * → co-located with pipeline → capacity).\n */\nconst DecoderAssignmentSchema = z.object({\n deviceId: z.number(),\n /** Moleculer node id of the decoder provider currently responsible for this camera. */\n decoderNodeId: z.string(),\n /** True when the assignment was set manually via `assignDecoder`, false when chosen by the balancer. */\n pinned: z.boolean(),\n /** Why this assignment was made — useful for debugging the decoder balancer. */\n reason: z.enum(['manual', 'co-located', 'capacity', 'hardware-affinity']),\n})\n\n/**\n * Per-agent load summary surfaced to the load balancer + dashboards.\n * Aggregated from each runner's `getLocalLoad` cap call.\n */\nconst AgentLoadSummarySchema = z.object({\n nodeId: z.string(),\n online: z.boolean(),\n load: RunnerLocalLoadSchema,\n /** Computed score used by the L2 capacity balancer (lower = less loaded). */\n score: z.number(),\n})\n\n/**\n * Aggregate metrics across the whole detection cluster. Replaces the legacy\n * `IPipelineExecutorProvider.orchestratorStatus()` cap method as the\n * canonical source of truth for global pipeline health.\n */\nconst GlobalMetricsSchema = z.object({\n totalAgents: z.number(),\n onlineAgents: z.number(),\n totalCameras: z.number(),\n attachedCameras: z.number(),\n activeCameras: z.number(),\n /** Average inference time across all agents weighted by their camera count. */\n avgInferenceTimeMs: z.number(),\n /** Total queue depth across all agents. */\n queueDepth: z.number(),\n})\n\n/**\n * Per-node capability binding map: which addon implements each well-known\n * cap on the named node. Persisted hub-side under\n * `addon:pipeline-orchestrator` settings keyed by `nodeBindings.<nodeId>`.\n *\n * The kernel of each process consults its local copy of this map (via the\n * `capability.binding-changed` event subscription) when resolving\n * capability providers.\n */\nconst CapabilityBindingsSchema = z.record(z.string(), z.string())\n\n// NOTE — Phase 6 cleanup (orchestrator settings rework):\n//\n// The `OrchestrationDeviceSettings` and `ResolvedOrchestrationSettings`\n// types used to live here, along with the cap methods\n// `getDeviceOrchestrationSettings` / `getDeviceOrchestrationOverrides`\n// / `getGlobalOrchestrationSettings`. They were a central bottleneck\n// that duplicated the standard addon settings store.\n//\n// Consumers now read per-device settings directly via the kernel\n// helper `resolveAddonSettings(schema, global, device)` from\n// `@camstack/types`, using the standard\n// `AddonRegistryService.getAddonConfigSchema` +\n// `ConfigService.getAddonConfig` / `getAddonDevice` pair. There is no\n// alias cap method on the orchestrator — the 3-level resolver is the\n// one and only read path for every addon, including this one.\n//\n// If a caller needs a typed view of the merged result, it's their\n// responsibility to narrow the returned `Record<string, unknown>`\n// locally (see `DetectionWiringService.resolveDeviceSettings` for the\n// canonical example).\n\n/**\n * Pipeline Orchestrator capability — global load balancer + camera dispatcher.\n *\n * Lives on the hub. Tracks the camera-to-agent assignment map, listens to\n * device lifecycle events, queries each runner's capacity + hardware\n * profile, and dispatches `attachCamera` / `detachCamera` cap calls to the\n * appropriate runner instances. Persists assignments via the multi-level\n * settings store so they survive hub restarts.\n *\n * Strictly the control plane: never sees a frame, never calls inference,\n * never drains queues. The runner does that work locally on each agent.\n */\nexport const pipelineOrchestratorCapability = {\n name: 'pipeline-orchestrator',\n scope: 'system',\n mode: 'singleton',\n exposesDeviceSettings: true,\n methods: {\n // ── Pipeline placement overrides ────────────────────────────────────\n /**\n * Pin a camera's pipeline to a specific agent (L1 affinity).\n * The orchestrator re-evaluates the assignment immediately.\n */\n assignPipeline: method(\n z.object({ deviceId: z.number(), agentNodeId: z.string() }),\n z.object({ success: z.literal(true) }),\n { kind: 'mutation', auth: 'admin' },\n ),\n /**\n * Clear a camera's pipeline pin and let the auto-balancer re-pick\n * the optimal agent. The orchestrator persists `preferredAgent=null`\n * (and `pipelineNodeId='auto'`), then re-runs the balancer with the\n * cached `RunnerCameraConfig` and migrates only when the chosen\n * node differs. The camera stays in `getPipelineAssignments()` —\n * just with `pinned=false`. If no runner is currently available\n * (cluster-wide), the camera is left unassigned but the cached\n * config is kept so the next dispatch event re-attaches it.\n */\n unassignPipeline: method(\n z.object({ deviceId: z.number() }),\n z.object({ success: z.literal(true) }),\n { kind: 'mutation', auth: 'admin' },\n ),\n /**\n * Trigger a full rebalance pass. Iterates over all assigned cameras,\n * recomputes the optimal agent for each one based on current load +\n * hardware affinity, and migrates cameras whose current agent is no\n * longer optimal. Pinned cameras are never migrated.\n */\n rebalance: method(z.void(), z.object({ migrated: z.number() }), { kind: 'mutation', auth: 'admin' }),\n\n // ── Observability ────────────────────────────────────────────────\n /** Get the full camera-to-agent assignment map. */\n getPipelineAssignments: method(z.void(), z.array(PipelineAssignmentSchema).readonly()),\n /** Get one camera's assignment, or null if unassigned. */\n getPipelineAssignment: method(z.object({ deviceId: z.number() }), PipelineAssignmentSchema.nullable()),\n /** Get per-agent load summaries used by the load balancer + dashboards. */\n getAgentLoad: method(z.void(), z.array(AgentLoadSummarySchema).readonly()),\n /** Aggregate global metrics across the whole detection cluster. */\n getGlobalMetrics: method(z.void(), GlobalMetricsSchema),\n /**\n * Per-camera live metrics (phase, fps, inference, queue, drops).\n * The orchestrator owns the device→agent assignment map and is the\n * canonical place to ask \"give me the metrics for this camera\". It\n * resolves the agent that holds the camera and delegates to that\n * runner's `getCameraMetrics`. Returns null if the device is not\n * assigned or the runner has no record for it (e.g. the camera was\n * just dispatched and the runner hasn't received the first frame).\n */\n getCameraMetrics: method(z.object({ deviceId: z.number() }), CameraMetricsSchema.nullable()),\n\n // ── Capability bindings (which addon implements each cap on each node) ──\n /** Read the capability binding map for one node. Empty record = no overrides (first-registered wins). */\n getCapabilityBindings: method(z.object({ nodeId: z.string() }), CapabilityBindingsSchema),\n /** Set the addon that implements `capName` on `nodeId`. Emits `capability.binding-changed`. */\n setCapabilityBinding: method(\n z.object({ nodeId: z.string(), capName: z.string(), addonId: z.string() }),\n z.object({ success: z.literal(true) }),\n { kind: 'mutation', auth: 'admin' },\n ),\n\n // ── Decoder scheduling ─────────────────────────────────────────────\n /** Pin a device's decoder to a specific node. */\n assignDecoder: method(\n z.object({ deviceId: z.number(), nodeId: z.string() }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n /** Clear a device's decoder pin (revert to auto). */\n unassignDecoder: method(\n z.object({ deviceId: z.number() }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n /** Get every camera's decoder placement. */\n getDecoderAssignments: method(z.void(), z.array(DecoderAssignmentSchema).readonly()),\n\n // ── Audio scheduling ───────────────────────────────────────────────\n /** Pin a device's audio analysis to a specific cluster node. */\n assignAudio: method(\n z.object({ deviceId: z.number(), nodeId: z.string() }),\n z.object({ success: z.literal(true) }),\n { kind: 'mutation', auth: 'admin' },\n ),\n /** Clear a device's audio node pin (revert to auto load-balanced). */\n unassignAudio: method(\n z.object({ deviceId: z.number() }),\n z.object({ success: z.literal(true) }),\n { kind: 'mutation', auth: 'admin' },\n ),\n /** Get the current audio assignment for one device, or null if not yet assigned. */\n getAudioAssignment: method(\n z.object({ deviceId: z.number() }),\n z.object({\n nodeId: z.string(),\n pinned: z.boolean(),\n assignedAt: z.number(),\n }).nullable(),\n ),\n /** Get per-node audio load (device counts) for all known audio-analyzer nodes. */\n getAudioNodeLoad: method(\n z.void(),\n z.array(z.object({ nodeId: z.string(), deviceCount: z.number() })),\n ),\n /** Get all current audio assignments across all devices. */\n getAudioAssignments: method(\n z.void(),\n z.array(z.object({\n deviceId: z.number(),\n nodeId: z.string(),\n pinned: z.boolean(),\n assignedAt: z.number(),\n })),\n ),\n\n /**\n * Get one camera's decoder placement (computed if not yet pinned).\n * Consumed by `stream-broker.createBroker` so decoder provider\n * selection is deterministic — fixes the 2026-04-18 race where\n * `capProviders[0]` silently picked ffmpeg-on-agent-0 for a\n * hub-assigned camera.\n *\n * `pipelineNodeId` is the node already chosen to run inference for\n * this camera. When provided, the balancer prefers co-location with\n * it; omitted → falls back to the last known assignment in the\n * `assignments` map and finally to 'hub'.\n */\n getDecoderAssignment: method(\n z.object({\n deviceId: z.number(),\n pipelineNodeId: z.string().optional(),\n }),\n DecoderAssignmentSchema,\n ),\n\n // NOTE: the `getDeviceOrchestrationSettings`,\n // `getDeviceOrchestrationOverrides` and `getGlobalOrchestrationSettings`\n // methods were removed in Phase 6. Consumers now read settings via\n // the standard 3-level resolver (`resolveAddonSettings`) over the\n // addon config store — see the top of this file for details.\n\n // ── 3-level pipeline settings (new model) ──────────────────────────\n //\n // Replaces the per-camera full-config + cluster-default model with:\n // `agent.addonDefaults` (flat per-addon config; auto-seeded from catalog),\n // `camera.stepToggles` (bool overlay; absent = inherit agent),\n // `camera.pipelineByAgent` (wholesale override escape hatch).\n //\n // The orchestrator's `resolvePipeline` collapses these into the\n // `CameraPipelineConfig` the runner consumes at dispatch.\n\n // `agentNodeId` (not `nodeId`) is intentional: the generated cap router\n // auto-routes any input field literally named `nodeId` to that node's\n // provider. `pipeline-orchestrator` is a HUB-SINGLETON cap — the\n // agent-node identifier here is DATA (\"which agent to read/write\"),\n // not routing. Using `agentNodeId` keeps the call on the hub as\n // intended.\n\n /** Read one agent's settings. Null when not yet seeded. */\n getAgentSettings: method(\n z.object({ agentNodeId: z.string() }),\n AgentPipelineSettingsSchema.nullable(),\n ),\n /** Enumerate every agent's settings (hub + remote runners). */\n listAgentSettings: method(\n z.void(),\n z.array(z.object({\n nodeId: z.string(),\n settings: AgentPipelineSettingsSchema,\n })).readonly(),\n ),\n /** Bulk-replace ALL addon configs on one agent. Used by the agent-level PipelineEditor which emits the full map per edit. Merges on top of existing entries — omitted addonIds are left alone. */\n setAgentAddonDefaults: method(\n z.object({\n agentNodeId: z.string(),\n defaults: z.record(z.string(), AgentAddonConfigSchema),\n }),\n z.object({ success: z.literal(true) }),\n { kind: 'mutation', auth: 'admin' },\n ),\n /**\n * Drop a single agent's persisted settings. Used by the cluster\n * \"Offline agents\" panel to evict stale entries left behind when an\n * agent's data dir was rebuilt (new random nodeId) or older code wrote\n * the env name as the nodeId. The orchestrator otherwise never deletes\n * agentSettings — entries accumulate until a hub reset.\n *\n * `success: false` indicates the nodeId wasn't in the store (no-op).\n * Refuses to remove `hub` (the orchestrator always co-resides with it).\n */\n removeAgentSettings: method(\n z.object({ agentNodeId: z.string() }),\n z.object({ success: z.boolean(), removed: z.boolean() }),\n { kind: 'mutation', auth: 'admin' },\n ),\n // Phase 2f: `setAgentEngineChoice`, `setAgentHwAccel`,\n // `reprobeAgentHwAccel` removed. Engine ownership moved to the\n // `detection-pipeline` addon (`engineRuntime/engineBackend/engineDevice`\n // + `pipelineExecutor.reprobeEngine`). Hwaccel ownership moved to\n // each decoder addon (`decoder-nodeav`/`decoder-ffmpeg` global\n // settings + `decoder.reprobeHwaccel`). UI + decoder sessions read\n // via `api.addonSettings.getGlobalSettings({addonId, nodeId})`.\n\n /** Read one camera's settings. Null when never touched (inherits agent defaults fully). */\n getCameraSettings: method(\n z.object({ deviceId: z.number() }),\n CameraPipelineSettingsSchema.nullable(),\n ),\n /** Set or clear the 3-state toggle for one (camera, addonId). Pass `enabled: null` to clear and revert to agent default. */\n setCameraStepToggle: method(\n z.object({\n deviceId: z.number(),\n addonId: z.string(),\n enabled: z.boolean().nullable(),\n }),\n z.object({ success: z.literal(true) }),\n { kind: 'mutation', auth: 'admin' },\n ),\n /** Read every L2.5 override map for a device. Null when device has no overrides. */\n getCameraStepOverrides: method(\n z.object({ deviceId: z.number() }),\n z.record(\n z.string(), // agentNodeId\n z.record(z.string(), CameraStepOverridePatchSchema),\n ).nullable(),\n ),\n /**\n * Write or clear the L2.5 per-agent override for one addonId on a device.\n * `patch: null` clears the entry entirely for that (agent, addon) pair.\n */\n setCameraStepOverride: method(\n z.object({\n deviceId: z.number(),\n agentNodeId: z.string(),\n addonId: z.string(),\n patch: CameraStepOverridePatchSchema.nullable(),\n }),\n z.object({ success: z.literal(true) }),\n { kind: 'mutation', auth: 'admin' },\n ),\n /** Write or clear the wholesale per-agent pipeline override. Pass `pipeline: null` to drop the override. */\n setCameraPipelineForAgent: method(\n z.object({\n deviceId: z.number(),\n agentNodeId: z.string(),\n pipeline: CameraPipelineForAgentSchema.nullable(),\n }),\n z.object({ success: z.literal(true) }),\n { kind: 'mutation', auth: 'admin' },\n ),\n /** Resolve the effective pipeline for `(deviceId, agentNodeId?)` — walks the full precedence chain. Read-only preview used by the UI to show what will run. */\n resolvePipeline: method(\n z.object({ deviceId: z.number(), agentNodeId: z.string().optional() }),\n CameraPipelineConfigSchema,\n ),\n\n // ── Template library (hub-only, read by any device-details UI) ─────\n /** List every template the operator has saved. */\n listTemplates: method(z.void(), z.array(PipelineTemplateSchema).readonly()),\n /** Create a new named preset from a given CameraPipelineConfig. */\n saveTemplate: method(\n z.object({\n name: z.string(),\n description: z.string().optional(),\n config: CameraPipelineConfigSchema,\n }),\n PipelineTemplateSchema,\n { kind: 'mutation', auth: 'admin' },\n ),\n /** Partial update of a template. Any omitted field is preserved. */\n updateTemplate: method(\n z.object({\n id: z.string(),\n name: z.string().optional(),\n description: z.string().optional(),\n config: CameraPipelineConfigSchema.optional(),\n }),\n PipelineTemplateSchema,\n { kind: 'mutation', auth: 'admin' },\n ),\n /** Remove a template. Camera configs that were seeded from it keep a copy. */\n deleteTemplate: method(\n z.object({ id: z.string() }),\n z.object({ success: z.literal(true) }),\n { kind: 'mutation', auth: 'admin' },\n ),\n },\n} as const satisfies CapabilityDefinition\n\nexport type IPipelineOrchestratorProvider = InferProvider<typeof pipelineOrchestratorCapability>\n\nexport {\n PipelineAssignmentSchema,\n DecoderAssignmentSchema,\n AgentLoadSummarySchema,\n GlobalMetricsSchema,\n CapabilityBindingsSchema,\n CameraPipelineConfigSchema,\n CameraStepOverridePatchSchema,\n PipelineTemplateSchema as OrchestratorPipelineTemplateSchema,\n}\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { AudioChunkInputSchema, AudioLevelSchema, AudioClassificationLabelSchema } from './schemas/detection-shared.js'\n\nconst AudioAnalysisResultSchema = z.object({\n level: AudioLevelSchema,\n classification: z.object({\n labels: z.array(AudioClassificationLabelSchema).readonly(),\n inferenceMs: z.number(),\n }).optional(),\n timestamp: z.number(),\n})\n\nconst AudioAnalysisSettingsSchema = z.object({\n minConfidence: z.number().min(0).max(1).default(0.3),\n allowedClasses: z.array(z.string()).default([]),\n})\n\n// Merged from audio-classifier.cap.ts — AudioAnalyzerAddon now owns the\n// pipeline directly (no tRPC roundtrip to a separate classifier addon).\nconst AudioClassificationResultSchema = z.object({\n // Macro-aggregated labels (25-class taxonomy from `AUDIO_MACRO_LABELS`).\n // Primary surface — used by the live audio analyzer and notifications.\n labels: z.array(AudioClassificationLabelSchema).readonly(),\n // Raw backend-native labels (e.g. YAMNet's 521 classes or Apple\n // SoundAnalysis's 303 classes), unaggregated. Optional so existing\n // consumers continue to work; populated by the analyzer provider\n // for callers that want fine-grained output — the benchmark UI uses\n // this in `micro` mode.\n rawLabels: z.array(AudioClassificationLabelSchema).readonly().optional(),\n inferenceMs: z.number(),\n})\n\n/**\n * audio-analyzer — system-scoped compute cap.\n *\n * Owns the engine lifecycle (isReady / dispose), the stateless\n * `analyseChunk` call and the `classify` method. Per-device settings,\n * device-settings contribution and the `onAudioLevel` event live on the\n * paired `audio-analysis` cap (device-scoped, singleton, wrapper\n * defaultActive) so every camera gets its own bindings row and per-device\n * toggle. Pairing mirrors `stream-broker` (system) + `camera-streams`\n * (device) + `webrtc-session` (device) — single addon registers both.\n */\n/**\n * Operator-facing audio-backend choice. 'auto' defers to the addon's\n * platform heuristic (Apple SoundAnalysis on macOS, YAMNet elsewhere).\n */\nexport const AUDIO_BACKEND_CHOICES = [\n { value: 'auto', label: 'Auto (platform default)' },\n { value: 'apple-soundanalysis', label: 'Apple SoundAnalysis (macOS 12+)' },\n { value: 'yamnet-onnx', label: 'YAMNet ONNX (cross-platform)' },\n] as const\n\nexport type AudioBackendChoice = typeof AUDIO_BACKEND_CHOICES[number]['value']\n\n/**\n * Shared shape of the audio-analyzer addon's global settings.\n * `audioBackend` = operator choice (wins); `probedBestAudioBackend`\n * = hint refreshed by `reprobeAudioEngine`. `selectedAudioModel`\n * replaces the orchestrator's legacy\n * `AgentPipelineSettings.audio.modelId`.\n *\n * NOTE — enable/disable is NOT stored here:\n * - per-device: `audio-analysis` wrapper cap + `setWrapperActive`\n * (binding system — the canonical gate).\n * - cluster-wide: `addonDefaults['audio-classifier'].enabled` on\n * the pipeline-orchestrator; drives whether the audio step\n * appears in the resolved tree at all.\n */\nexport interface AudioAnalyzerGlobalConfig {\n readonly audioBackend: AudioBackendChoice\n readonly probedBestAudioBackend: string\n readonly selectedAudioModel: string\n}\n\nexport const DEFAULT_AUDIO_ANALYZER_CONFIG: AudioAnalyzerGlobalConfig = {\n audioBackend: 'auto',\n probedBestAudioBackend: '',\n selectedAudioModel: '',\n}\n\nexport const audioAnalyzerCapability = {\n name: 'audio-analyzer',\n scope: 'system',\n mode: 'singleton',\n methods: {\n analyseChunk: method(\n z.object({ chunk: AudioChunkInputSchema, settings: AudioAnalysisSettingsSchema }),\n AudioAnalysisResultSchema.nullable(),\n { kind: 'mutation' },\n ),\n // ONNX / Apple SoundAnalysis inference can exceed the broker's default\n // 5s requestTimeout on first load or under CPU pressure. 30s covers\n // even the worst-case cold-start without hanging indefinitely.\n classify: method(AudioChunkInputSchema, AudioClassificationResultSchema, { timeoutMs: 30_000 }),\n isReady: method(z.void(), z.boolean()),\n dispose: method(z.void(), z.void(), { kind: 'mutation' }),\n\n /**\n * Re-run the host platform-probe for the audio backend and persist\n * the detected value into `probedBestAudioBackend`. Replaces the\n * orchestrator's legacy `AgentPipelineSettings.audio.engine` —\n * audio-analyzer now owns the choice. Operator `audioBackend` is\n * not touched; only the probed-best hint.\n */\n reprobeAudioEngine: method(\n z.void(),\n z.object({ backend: z.string() }),\n { kind: 'mutation', auth: 'admin' },\n ),\n },\n} as const satisfies CapabilityDefinition\n\nexport type IAudioAnalyzerProvider = InferProvider<typeof audioAnalyzerCapability>\n\nexport { AudioAnalysisResultSchema, AudioAnalysisSettingsSchema, AudioClassificationResultSchema }\n","import { z } from 'zod'\nimport { method, event, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\nimport type { AudioAnalysisSettings } from '../types/io.js'\n\n/**\n * audio-analysis — device-scoped facade over the system `audio-analyzer`.\n *\n * Pairs with `audio-analyzer` (system, singleton) the way `camera-streams`\n * pairs with `stream-broker`: the system cap owns the compute path\n * (`processChunk`, engine lifecycle) while `audio-analysis` exposes the\n * per-device surface — settings resolution, device-settings contribution,\n * audio-level events — and is the binding row every camera sees in the\n * device-manager bindings UI.\n *\n * The cap definition itself declares `kind: 'wrapper'` and `defaultActive: true`,\n * so every camera picks up audio analysis automatically without any runtime flag\n * in the addon's registration. Operators can disable per-device via\n * `device-manager.setWrapperActive` when they don't want a given camera to be\n * analysed (e.g. muted / motion-only cams).\n */\nexport const audioAnalysisCapability = {\n name: 'audio-analysis',\n scope: 'device',\n mode: 'singleton',\n kind: 'wrapper',\n defaultActive: true,\n deviceTypes: [DeviceType.Camera],\n exposesDeviceSettings: true,\n methods: {\n /**\n * Resolve per-device audio analysis settings (minConfidence,\n * allowedClasses) from the addon settings store for a given camera.\n * Orchestrator callers use this before handing chunks to\n * `audio-analyzer.processChunk`.\n */\n resolveDeviceSettings: method(\n z.object({ deviceId: z.number() }),\n z.custom<AudioAnalysisSettings | null>(),\n ),\n },\n events: {\n onAudioLevel: event(z.object({\n deviceId: z.number(),\n rms: z.number(),\n dbfs: z.number(),\n })),\n },\n} as const satisfies CapabilityDefinition\n\nexport type IAudioAnalysisProvider = InferProvider<typeof audioAnalysisCapability>\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\n\n// ── Schema fragments ─────────────────────────────────────────────────────────\n\nconst PcmSampleFormatSchema = z.enum(['f32le', 's16le'])\n\nconst AudioCodecInfoSchema = z.object({\n codec: z.string(),\n canDecode: z.boolean(),\n canEncode: z.boolean(),\n label: z.string().optional(),\n})\n\nconst AudioDecodeSessionConfigSchema = z.object({\n codec: z.string(),\n sourceSampleRate: z.number().int().positive(),\n sourceChannels: z.number().int().positive(),\n extraData: z.instanceof(Uint8Array).optional(),\n targetSampleRate: z.number().int().positive(),\n targetChannels: z.number().int().positive(),\n targetFormat: PcmSampleFormatSchema.optional(),\n idleMs: z.number().int().positive().optional(),\n tag: z.string().optional(),\n})\n\nconst AudioEncodeSessionConfigSchema = z.object({\n codec: z.string(),\n sourceSampleRate: z.number().int().positive(),\n sourceChannels: z.number().int().positive(),\n sourceFormat: PcmSampleFormatSchema.optional(),\n targetSampleRate: z.number().int().positive(),\n targetChannels: z.number().int().positive(),\n bitrateKbps: z.number().int().positive().optional(),\n idleMs: z.number().int().positive().optional(),\n tag: z.string().optional(),\n})\n\nconst AudioPcmChunkSchema = z.object({\n data: z.instanceof(Uint8Array),\n sampleRate: z.number().int().positive(),\n channels: z.number().int().positive(),\n format: PcmSampleFormatSchema,\n pts: z.number(),\n})\n\nconst AudioEncodedChunkSchema = z.object({\n data: z.instanceof(Uint8Array),\n codec: z.string(),\n pts: z.number(),\n frameComplete: z.boolean(),\n})\n\nconst SessionInventoryEntrySchema = z.object({\n sessionId: z.string(),\n kind: z.enum(['decode', 'encode']),\n codec: z.string(),\n sourceSampleRate: z.number(),\n sourceChannels: z.number(),\n targetSampleRate: z.number(),\n targetChannels: z.number(),\n format: PcmSampleFormatSchema,\n tag: z.string().optional(),\n createdAtMs: z.number(),\n lastActivityMs: z.number(),\n framesIn: z.number(),\n framesOut: z.number(),\n})\n\n// ── Capability definition ────────────────────────────────────────────────────\n\n/**\n * audio-codec — bidirectional PCM ↔ encoded audio I/O box.\n *\n * Independent per-consumer sessions. The provider runs decode + resample\n * (or resample + encode) inside the session so a 16kHz mono ASA\n * subscriber and a 48kHz stereo WebRTC subscriber on the same source\n * stream don't share resamplers.\n *\n * Singleton on each node. Decoder and encoder live in the same provider\n * because they share the underlying libav contexts (node-av today,\n * pluggable later) — operators always install one or the other together.\n */\nexport const audioCodecCapability = {\n name: 'audio-codec',\n scope: 'system',\n mode: 'singleton',\n methods: {\n // ── Discovery ─────────────────────────────────────────────────────────\n /** Probe the local runtime and return the supported codec matrix. */\n listSupportedCodecs: method(z.void(), z.array(AudioCodecInfoSchema).readonly()),\n\n /** Cheap predicate — does the runtime support `(codec, kind)`? */\n canHandle: method(\n z.object({ codec: z.string(), kind: z.enum(['decode', 'encode']) }),\n z.boolean(),\n ),\n\n // ── Session lifecycle ─────────────────────────────────────────────────\n createDecodeSession: method(\n AudioDecodeSessionConfigSchema,\n z.object({ sessionId: z.string(), nodeId: z.string() }),\n { kind: 'mutation' },\n ),\n\n createEncodeSession: method(\n AudioEncodeSessionConfigSchema,\n z.object({ sessionId: z.string(), nodeId: z.string() }),\n { kind: 'mutation' },\n ),\n\n closeSession: method(\n z.object({ sessionId: z.string(), nodeId: z.string().optional() }),\n z.void(),\n { kind: 'mutation' },\n ),\n\n // ── Decode data plane ─────────────────────────────────────────────────\n // Session-bound methods include an optional `nodeId` field so the\n // generated cap router auto-routes calls to the same node that owns\n // the session. Audio-codec sessions are process-local — without sticky\n // routing the round-robin across nodes serves \"session not found\" on\n // every other call.\n\n /** Push one encoded audio frame into a decode session. */\n pushEncodedFrame: method(\n z.object({\n sessionId: z.string(),\n nodeId: z.string().optional(),\n data: z.instanceof(Uint8Array),\n /** Source PTS in milliseconds. Synthesised when omitted. */\n pts: z.number().optional(),\n }),\n z.void(),\n { kind: 'mutation' },\n ),\n\n /** Pull up to `maxCount` PCM chunks from a decode session. */\n pullPcm: method(\n z.object({\n sessionId: z.string(),\n nodeId: z.string().optional(),\n maxCount: z.number().int().positive().default(8),\n }),\n z.array(AudioPcmChunkSchema),\n ),\n\n // ── Encode data plane ─────────────────────────────────────────────────\n /** Push one PCM chunk into an encode session. */\n pushPcm: method(\n z.object({\n sessionId: z.string(),\n nodeId: z.string().optional(),\n data: z.instanceof(Uint8Array),\n /** Source PTS in milliseconds. */\n pts: z.number().optional(),\n }),\n z.void(),\n { kind: 'mutation' },\n ),\n\n /** Pull up to `maxCount` encoded chunks from an encode session. */\n pullEncoded: method(\n z.object({\n sessionId: z.string(),\n nodeId: z.string().optional(),\n maxCount: z.number().int().positive().default(8),\n }),\n z.array(AudioEncodedChunkSchema),\n ),\n\n /** Flush any pending encoded output (call before close on graceful tear). */\n flushEncode: method(\n z.object({ sessionId: z.string(), nodeId: z.string().optional() }),\n z.array(AudioEncodedChunkSchema),\n { kind: 'mutation' },\n ),\n\n // ── Inventory ─────────────────────────────────────────────────────────\n listActiveSessions: method(\n z.void(),\n z.array(SessionInventoryEntrySchema).readonly(),\n ),\n },\n} as const satisfies CapabilityDefinition\n\nexport type IAudioCodecCapProvider = InferProvider<typeof audioCodecCapability>\n\nexport {\n AudioCodecInfoSchema,\n AudioDecodeSessionConfigSchema,\n AudioEncodeSessionConfigSchema,\n AudioPcmChunkSchema,\n AudioEncodedChunkSchema,\n PcmSampleFormatSchema,\n}\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\n\n/**\n * Embedding output. `embedding` is wire-encoded as `number[]` so the\n * Zod-validated tRPC surface round-trips cleanly; consumers that need a\n * `Float32Array` can wrap it on the way out (in-process, no marshalling\n * is involved). `inferenceMs` mirrors the runtime field used by the\n * post-analysis enrichment-engine.\n */\nconst EmbeddingResultSchema = z.object({\n embedding: z.array(z.number()),\n inferenceMs: z.number(),\n})\n\nconst EmbeddingInfoSchema = z.object({\n modelId: z.string(),\n embeddingDim: z.number(),\n ready: z.boolean(),\n})\n\nexport const embeddingEncoderCapability = {\n name: 'embedding-encoder',\n scope: 'system',\n mode: 'collection',\n internal: true,\n methods: {\n encode: method(\n z.object({ crop: z.instanceof(Uint8Array), width: z.number(), height: z.number() }),\n EmbeddingResultSchema,\n ),\n encodeText: method(z.object({ text: z.string() }), EmbeddingResultSchema),\n getInfo: method(z.void(), EmbeddingInfoSchema),\n },\n} as const satisfies CapabilityDefinition\n\nexport type IEmbeddingEncoderProvider = InferProvider<typeof embeddingEncoderCapability>\n\nexport { EmbeddingResultSchema, EmbeddingInfoSchema }\n","/**\n * Device Manager capability — hub-side singleton that unifies device persistence,\n * live registry access, and all management operations into a single tRPC surface.\n *\n * Replaces:\n * - `device-persistence` capability (persistence methods absorbed here)\n * - `device-management.router.ts` (deleted in Phase 2)\n * - `device-ops.router.ts` (compat layer — deleted; device-provider ops absorbed here)\n *\n * All device provider addons (rtsp, onvif, frigate, …) are hub-local: they may\n * fork into separate processes but never run on remote cluster agents. Therefore:\n * - No nodeId routing needed — this is a pure hub singleton.\n * - The hub's DeviceRegistry is the single source of truth for all live devices.\n * - No shadow registry or cross-node aggregation required.\n *\n * Forked workers register devices back to the hub via `ctx.devices`\n * (DeviceManagerApi → ctx.api.deviceManager.registerDevice), same as today.\n */\nimport { z } from 'zod'\nimport { method, type CapabilityDefinition } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\nimport { StreamSourceEntrySchema } from './schemas/streaming-shared.js'\nimport { SettingsSchemaWithValuesSchema } from './addon-settings.cap.js'\nimport { SourceInfoSchema } from '../device/source-info.js'\nimport {\n DiscoveryCandidateSchema,\n DeviceSummarySchema,\n FieldProbeResultSchema,\n} from './device-provider.cap.js'\nimport {\n ListCandidatesInputSchema as AdoptionListCandidatesInputSchema,\n ListCandidatesOutputSchema as AdoptionListCandidatesOutputSchema,\n AdoptInputSchema as AdoptionAdoptInputSchema,\n AdoptResultSchema as AdoptionAdoptResultSchema,\n ReleaseInputSchema as AdoptionReleaseInputSchema,\n AdoptionStatusSchema,\n} from './device-adoption.cap.js'\n\n// ── Output schemas ────────────────────────────────────────────────────────────\n\n/** One child-placement directive on a container's `childLayout`. Structurally\n * identical to `ChildLayoutEntry` in `device-management.ts` — the cap wire\n * shape for the same field. The child is identified by its re-sync-stable\n * accessory `stableIdSuffix` (`childKey`); listed children are grouped into\n * named accordion sections (with optional intra-section order). */\nconst ChildLayoutEntrySchema = z.object({\n childKey: z.string(),\n section: z.string(),\n order: z.number().optional(),\n // Section-level default-collapsed hint: when true the accordion section this\n // entry belongs to renders closed by default. The section is treated as\n // collapsed if ANY of its entries sets collapsed:true; consistent values\n // across a section's entries are recommended but not enforced. Absent ⇒ open.\n collapsed: z.boolean().optional(),\n})\n\n/** Cap-wire shape of a DeviceLink — structurally mirrors `DeviceLink` in\n * `device-management.ts`. */\nconst DeviceLinkSchema = z.object({\n id: z.string(),\n source: z.object({ sourceKey: z.string(), cap: z.string(), fieldPath: z.string() }),\n target: z.object({ cap: z.string(), fieldPath: z.string(), itemKey: z.string().optional() }),\n transform: z.discriminatedUnion('kind', [\n z.object({ kind: z.literal('identity') }),\n z.object({ kind: z.literal('enum-map'), mapping: z.record(z.string(), z.union([z.string(), z.number(), z.boolean()])), fallback: z.union([z.string(), z.number(), z.boolean()]).optional() }),\n z.object({ kind: z.literal('linear'), scale: z.number(), offset: z.number(), clamp: z.tuple([z.number(), z.number()]).readonly().optional() }),\n ]).optional(),\n})\n\n/**\n * Serializable projection of a live IDevice.\n * Returned by listAll, getDevice, getChildren.\n * Live methods (getStreamSources, getConfigSchema) are separate calls.\n */\nexport const DeviceInfoSchema = z.object({\n /** Progressive, system-wide unique number. Allocated synchronously by\n * `device-manager.allocateDeviceId` BEFORE the owning `IDevice` is\n * constructed, so every live device exposes an `id` — no transient\n * null window. Distinct from `stableId`, which is unique per\n * integration. Ids are monotonic and never reissued on removal. */\n id: z.number(),\n stableId: z.string(),\n addonId: z.string(),\n type: z.enum(DeviceType),\n name: z.string(),\n /** Operator-organisational location label. `null` when unset. */\n location: z.string().nullable(),\n /** Soft-disabled flag. */\n disabled: z.boolean(),\n parentDeviceId: z.number().nullable(),\n /** Optional semantic role — `DeviceRole` string. null for top-level devices. */\n role: z.string().nullable().optional(),\n online: z.boolean(),\n /** True when the device's initial feature-probe has completed (or it has\n * no probe) — exported shape is stable; exporters gate advertise on this.\n * Optional for deploy-order resilience: a record produced by an older\n * device-manager build omits it, and consumers treat absent as \"not ready\"\n * (export gate carries forward, never advertises a partial shape). */\n probed: z.boolean().optional(),\n features: z.array(z.string()),\n /** true when the device has a getStreamSources() method (ICameraDevice) */\n isCamera: z.boolean(),\n /** Current config values — serializable snapshot */\n config: z.record(z.string(), z.unknown()),\n /** Hardware + identity blob (manufacturer / model / firmware / sn /\n * uid / mac / …). Populated by drivers; editable via setMetadata. */\n metadata: z.record(z.string(), z.unknown()).nullable().optional(),\n /** Optional upstream-system identity + rendering envelope. See\n * `SourceInfo` in `packages/types/src/device/source-info.ts`. */\n sourceInfo: SourceInfoSchema.optional(),\n /** Owning integration id, stamped at create — used by the core to\n * cascade-delete an integration's devices. Optional: only present\n * when the device was created through an integration (e.g. HA). */\n integrationId: z.string().optional(),\n linkDeviceId: z.number().nullable().optional(),\n /** Durable primary-child override for a CONTAINER device, keyed on the\n * chosen child's re-sync/rename-stable `entityId`. Survives a re-sync\n * that reallocates the child's numeric id. `null` clears the override. */\n primaryChildEntityId: z.string().nullable().optional(),\n /** Container-level layout hint: assigns specific child/accessory devices to\n * named accordion sections (with optional intra-section order). See\n * `DeviceMeta.childLayout`. Absent ⇒ no layout declared. */\n childLayout: z.array(ChildLayoutEntrySchema).readonly().optional(),\n /** Operator-authored cross-device field wirings. See `DeviceMeta.deviceLinks`. */\n deviceLinks: z.array(DeviceLinkSchema).readonly().optional(),\n})\n\nexport const ConfigEntrySchema = z.object({\n key: z.string(),\n value: z.unknown(),\n description: z.string().optional(),\n})\n\nexport { StreamSourceEntrySchema }\n\nexport const SavedDeviceRowSchema = z.object({\n /** Numeric id reserved at allocateDeviceId time. */\n id: z.number(),\n /** External-system identifier — required for the worker's `kernel.devices.create()` call. */\n stableId: z.string(),\n type: z.string(),\n name: z.string(),\n /** Operator-organisational location label. `null` when unset. */\n location: z.string().nullable(),\n /** Soft-disabled flag. */\n disabled: z.boolean(),\n parentDeviceId: z.number().nullable(),\n /** Optional semantic role — stringified `DeviceRole` enum value. null for top-level devices. */\n role: z.string().nullable().optional(),\n})\n\n/** Operator-organisational meta surface — populated by the kernel\n * on `DeviceContext.deviceMeta` so `BaseDevice` can resolve\n * `name` / `location` / `disabled` without subclass schema duplication.\n * Mirrors `DeviceMeta` in `device-management.ts` for the cap wire shape. */\nexport const DeviceMetaSchema = z.object({\n id: z.number(),\n stableId: z.string(),\n addonId: z.string(),\n type: z.string(),\n name: z.string(),\n location: z.string().nullable(),\n disabled: z.boolean(),\n parentDeviceId: z.number().nullable(),\n metadata: z.record(z.string(), z.unknown()).nullable().optional(),\n /** Optional upstream-system identity + rendering envelope. See\n * `SourceInfo`. Present when the device has been persisted with a\n * non-synthetic source identifier (HA entities, vendor MAC, …);\n * omitted when the synthetic `{ id: stableId, system: addonId }`\n * fallback is in effect. Persisted under\n * `DeviceMeta.metadata.sourceInfo` — the field on this schema is\n * the typed projection callers consume directly. */\n sourceInfo: SourceInfoSchema.optional(),\n /** Owning integration id, stamped at create — used by the core to\n * cascade-delete an integration's devices. Optional: only present\n * when the device was created through an integration (e.g. HA). */\n integrationId: z.string().optional(),\n linkDeviceId: z.number().nullable().optional(),\n /** Durable primary-child override for a CONTAINER device, keyed on the\n * chosen child's re-sync/rename-stable `entityId`. See `DeviceMeta`. */\n primaryChildEntityId: z.string().nullable().optional(),\n /** Container-level layout hint: assigns child/accessory devices to named\n * accordion sections (with optional intra-section order). See\n * `DeviceMeta.childLayout`. Absent ⇒ no layout declared. */\n childLayout: z.array(ChildLayoutEntrySchema).readonly().optional(),\n /** Operator-authored cross-device field wirings. See `DeviceMeta.deviceLinks`. */\n deviceLinks: z.array(DeviceLinkSchema).readonly().optional(),\n /** Semantic role string (`DeviceRole`) — propagated from the spawn pre-seed.\n * Optional: only present for accessory children that carry a known role. */\n role: z.string().nullable().optional(),\n})\n\n/** ConfigUISchema passed through as unknown — mirrors device-provider's CreationSchemaOutputSchema */\nconst ConfigUISchemaOutput = z.unknown().nullable()\n\nconst StreamProbeResultSchema = z.object({\n streamId: z.string(),\n width: z.number().optional(),\n height: z.number().optional(),\n codec: z.string().optional(),\n fps: z.number().optional(),\n bitrateKbps: z.number().optional(),\n})\n\n// ── Re-export persistence schemas (for DeviceManagerApi / DevicePersistenceAddon consumers) ──\n\nexport const DeviceRegisterPayloadSchema = z.object({\n addonId: z.string(),\n stableId: z.string(),\n /** Pre-allocated numeric id from `allocateDeviceId`. The hub persists\n * it alongside the meta record; callers never invent this value. */\n id: z.number(),\n type: z.string(),\n name: z.string(),\n /** Operator-organisational location label. Optional on register —\n * the hub seeds `null` when omitted. */\n location: z.string().nullable().optional(),\n /** Soft-disabled flag. Optional on register — the hub seeds `false`. */\n disabled: z.boolean().optional(),\n parentDeviceId: z.number().nullable(),\n /** Optional semantic role — see `DeviceRole`. Driver authors pass this\n * at register time when the device is an accessory with a known role. */\n role: z.string().nullable().optional(),\n /** Snapshot of `device.features` at registration time. Persisted in\n * `DeviceMeta` so the hub can answer `getDevice` for forked-worker\n * devices with the right `DeviceFeature[]` even when the live\n * instance lives on a remote node. Re-published on every register\n * call (workers re-register on init), so probe-driven updates\n * (e.g. PTZ flag flipping after the abilities probe) propagate. */\n features: z.array(z.string()).optional(),\n config: z.record(z.string(), z.unknown()),\n})\n\nexport const DeviceRemovePayloadSchema = z.object({\n deviceId: z.number(),\n})\n\nexport const DevicePersistConfigPayloadSchema = z.object({\n deviceId: z.number(),\n data: z.record(z.string(), z.unknown()),\n})\n\n// ── Capability definition ─────────────────────────────────────────────────────\n\nexport const deviceManagerCapability = {\n name: 'device-manager',\n scope: 'system',\n mode: 'singleton',\n methods: {\n // ── Persistence (migrated from device-persistence) ────────────────────────\n\n /** Reserve (or re-resolve) a progressive numeric id for `(addonId, stableId)`.\n * Idempotent: returns the existing id if one is already persisted for the\n * pair. Callers invoke this before `registerDevice` so the live IDevice\n * can bind `id` at construction time through `DeviceContext.id`. */\n allocateDeviceId: method(\n z.object({ addonId: z.string(), stableId: z.string() }),\n z.object({ id: z.number() }),\n { kind: 'mutation' },\n ),\n\n /** Register a device in the DB + in-memory registry. Called by DeviceManagerApi.register(). */\n registerDevice: method(DeviceRegisterPayloadSchema, z.void(), { kind: 'mutation' }),\n\n /** Remove a device from the DB + in-memory registry. Called by DeviceManagerApi.remove(). */\n removeDevice: method(DeviceRemovePayloadSchema, z.void(), { kind: 'mutation' }),\n\n /** Persist device config blob. Called by DeviceConfig.set/setAll(). */\n persistConfig: method(DevicePersistConfigPayloadSchema, z.void(), { kind: 'mutation' }),\n\n /** Load persisted config for a device. Called at restore time. */\n loadConfig: method(\n z.object({ deviceId: z.number() }),\n z.record(z.string(), z.unknown()),\n ),\n\n /** Load persisted runtime state. Called at device adopt time. */\n loadRuntimeState: method(\n z.object({ deviceId: z.number() }),\n z.record(z.string(), z.unknown()),\n ),\n\n /** Load operator-organisational meta surface for a device. Called by\n * the kernel proxy to populate `DeviceContext.deviceMeta` before\n * the device class constructor runs. Returns `null` when the id\n * doesn't resolve to a persisted row. */\n loadMeta: method(\n z.object({ deviceId: z.number() }),\n DeviceMetaSchema.nullable(),\n ),\n\n /** Update the operator-edited display name. Persists to the meta\n * row + emits `EventCategory.DeviceMetaChanged`. */\n setName: method(\n z.object({ deviceId: z.number(), name: z.string() }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n\n /** Update the operator-organisational location label. `null`\n * clears it. */\n setLocation: method(\n z.object({ deviceId: z.number(), location: z.string().nullable() }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n\n /** Update the device type. Writes the meta row, emits a\n * `DeviceMetaChanged` event. Used by the kernel to apply\n * `initialMeta.type` before device construction so the device\n * constructs with its real type instead of the allocateDeviceId\n * placeholder `'generic'`. */\n setType: method(\n z.object({ deviceId: z.number(), type: z.enum(DeviceType) }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n\n /** Stamp (or update) the owning integration id on the device's meta\n * row. Called by the kernel's `create()` pre-seed path when\n * `initialMeta.integrationId` is set (analogous to `setName` /\n * `setType`). Idempotent. */\n setIntegrationId: method(\n z.object({ deviceId: z.number(), integrationId: z.string() }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n\n /** Stamp (or update) the soft-link device id on the device's meta\n * row. Called by the kernel `create()` pre-seed when\n * `initialMeta.linkDeviceId !== undefined`. Idempotent. */\n setLinkDeviceId: method(\n z.object({ deviceId: z.number(), linkDeviceId: z.number().nullable() }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n\n /** Set (or clear) the durable primary-child override on a CONTAINER\n * device's meta row, keyed on the chosen child's re-sync/rename-stable\n * `entityId`. Unlike `setLinkDeviceId` (numeric child id, goes stale on\n * re-sync), this survives a re-sync that reallocates the child's numeric\n * id. `null` clears the override → priority default. Idempotent. */\n setPrimaryChildEntityId: method(\n z.object({ deviceId: z.number(), primaryChildEntityId: z.string().nullable() }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n\n /** Set (or replace) the container-level `childLayout` on a device's meta\n * row — assigns specific child/accessory devices to named accordion\n * sections (with optional intra-section order). Mirrors\n * `setPrimaryChildEntityId`; the layout is parent-only. Persisted,\n * projected, and preserved across re-register/restore. Idempotent. */\n setChildLayout: method(\n z.object({ deviceId: z.number(), childLayout: z.array(ChildLayoutEntrySchema).readonly() }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n\n /** Set (or replace) the cross-device field wirings on a device's meta row.\n * Mirrors `setChildLayout`; persisted, projected, preserved across\n * re-register/restore. Idempotent. */\n setDeviceLinks: method(\n z.object({ deviceId: z.number(), deviceLinks: z.array(DeviceLinkSchema).readonly() }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n\n /** List the wireable status-schema fields per cap bound to a device.\n * Powers the Wiring tab's field pickers. Caps without a status schema are omitted. */\n getWireableFields: method(\n z.object({ deviceId: z.number() }),\n z.object({\n caps: z.array(z.object({\n cap: z.string(),\n fields: z.array(z.object({\n path: z.string(),\n kind: z.enum(['string', 'number', 'boolean', 'enum']),\n enumValues: z.array(z.string()).optional(),\n })).readonly(),\n })).readonly(),\n }),\n { kind: 'query' },\n ),\n\n /** Stamp (or update) the semantic role on the device's meta row.\n * Called by the kernel's `create()` / `spawnAccessoryChild` pre-seed\n * path when `initialMeta.role` is set (analogous to `setIntegrationId`).\n * Idempotent. `null` explicitly clears a previous role. */\n setRole: method(\n z.object({ deviceId: z.number(), role: z.string().nullable() }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n\n /** Batched meta pre-seed — applies every provided field to the device's\n * meta row in ONE settings round-trip (one lock acquisition, one\n * `deviceMeta` write) and emits one `DeviceMetaChanged` event per field\n * that was supplied. Each field carries the SAME semantics as its\n * individual setter (`setName` / `setLocation` / `setType` /\n * `setIntegrationId` / `setLinkDeviceId` / `setRole`) — omitted fields are\n * left untouched; `null` clears `location` / `linkDeviceId` / `role`.\n * Idempotent. Used by the kernel's `spawnAccessoryChild` flow to collapse\n * the per-child meta pre-seed (4-6 individual setter calls) into one,\n * which is the dominant cost when reconciling a many-entity container. */\n applyInitialMeta: method(\n z.object({\n deviceId: z.number(),\n name: z.string().optional(),\n location: z.string().nullable().optional(),\n type: z.enum(DeviceType).optional(),\n integrationId: z.string().optional(),\n linkDeviceId: z.number().nullable().optional(),\n role: z.string().nullable().optional(),\n }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n\n /** Patch the device's hardware-identity metadata blob. Merges\n * `patch` over the current blob (shallow). Value `null` for a\n * given key removes that key. Drivers populate factual fields\n * on first probe (model / firmware / mac / sn / uid); operators\n * can override or augment via the Device Info tab. */\n setMetadata: method(\n z.object({\n deviceId: z.number(),\n patch: z.record(z.string(), z.unknown()),\n }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n\n /** Operator-curated location registry. Returns the union of:\n * (1) labels persisted in the registry via `addLocation`, and\n * (2) labels currently in use on at least one device's\n * `meta.location` field.\n * Sorted case-insensitively + deduped + trimmed of empty strings.\n * Drives the autocomplete in the Device Info location editor. */\n listLocations: method(\n z.void(),\n z.array(z.string()),\n ),\n\n /** Add a label to the curated location registry. No-op when the\n * label (case-insensitive, trimmed) is already present. Empty\n * / whitespace-only inputs throw. */\n addLocation: method(\n z.object({ name: z.string() }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n\n /** Remove a label from the curated registry. Devices that still\n * reference this label keep their `meta.location` value — the\n * registry is purely a suggestion list. To purge from devices,\n * iterate them and call `setLocation(deviceId, null)`\n * separately (or pass `cascade: true` to do it in one shot). */\n removeLocation: method(\n z.object({ name: z.string(), cascade: z.boolean().optional() }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n\n /** Soft-disable / re-enable the device. Drivers consult\n * `BaseDevice.disabled` to gate lifecycle hooks. */\n setDisabled: method(\n z.object({ deviceId: z.number(), disabled: z.boolean() }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n\n /** List persisted devices for an addon (DB, for restore). */\n listPersistedByAddon: method(\n z.object({ addonId: z.string() }),\n z.array(SavedDeviceRowSchema),\n ),\n\n // ── Query — live registry ─────────────────────────────────────────────────\n\n /** List all devices (live registry), optionally filtered by addonId. */\n listAll: method(\n z.object({ addonId: z.string().optional() }),\n z.array(DeviceInfoSchema),\n ),\n\n /** Get a single device by numeric deviceId. */\n getDevice: method(\n z.object({ deviceId: z.number() }),\n DeviceInfoSchema.nullable(),\n ),\n\n /** List children of a parent device (by parent numeric id). */\n getChildren: method(\n z.object({ parentDeviceId: z.number() }),\n z.array(DeviceInfoSchema),\n ),\n\n // ── Runtime — live device operations ─────────────────────────────────────\n\n /** Get stream sources for a camera device. */\n getStreamSources: method(\n z.object({ deviceId: z.number() }),\n z.array(StreamSourceEntrySchema),\n ),\n\n /** Get config entries (key + value + description) for a device. */\n getConfigSchema: method(\n z.object({ deviceId: z.number() }),\n z.array(ConfigEntrySchema),\n ),\n\n /** Get the ConfigUISchema for a device's settings (for admin UI rendering). */\n getSettingsSchema: method(\n z.object({ deviceId: z.number() }),\n ConfigUISchemaOutput,\n ),\n\n // ── Mutations — config changes, enable/disable, remove ────────────────────\n\n /** Update device config values (partial merge). */\n updateConfig: method(\n z.object({\n deviceId: z.number(),\n values: z.record(z.string(), z.unknown()),\n }),\n z.object({ success: z.literal(true) }),\n { kind: 'mutation', auth: 'admin' },\n ),\n\n /** Enable a device (writes enabled=true to device config). */\n enable: method(\n z.object({ deviceId: z.number() }),\n z.object({ success: z.literal(true) }),\n { kind: 'mutation', auth: 'admin' },\n ),\n\n /** Disable a device (writes enabled=false to device config). */\n disable: method(\n z.object({ deviceId: z.number() }),\n z.object({ success: z.literal(true) }),\n { kind: 'mutation', auth: 'admin' },\n ),\n\n /** Remove a device and all children: calls device.removeDevice() then removes from registry + DB. */\n remove: method(\n z.object({ deviceId: z.number() }),\n z.object({ success: z.literal(true) }),\n { kind: 'mutation', auth: 'admin' },\n ),\n\n /** Cascade-delete every top-level device whose `integrationId` matches.\n * Children cascade automatically via the per-parent remove path.\n * Idempotent: a device whose `integrationId` was never set never matches.\n * Returns the count of top-level parents actually removed. */\n removeByIntegration: method(\n z.object({ integrationId: z.string() }),\n z.object({ removed: z.number() }),\n { kind: 'mutation', auth: 'admin' },\n ),\n\n // ── Stream profile map ────────────────────────────────────────────────────\n\n /** Get quality→streamId mapping for a camera. Derived from profileHint if not explicitly set. */\n getStreamProfileMap: method(\n z.object({ deviceId: z.number() }),\n z.record(z.string(), z.string().nullable()),\n ),\n\n /** Persist quality→streamId mapping in device config under reserved key _profileMap. */\n setStreamProfileMap: method(\n z.object({\n deviceId: z.number(),\n profileMap: z.record(z.string(), z.string().nullable()),\n }),\n z.object({ success: z.literal(true) }),\n { kind: 'mutation', auth: 'admin' },\n ),\n\n /** Run ffprobe on each stream source URL and return metadata. No-op if stream probe unavailable. */\n probeStreams: method(\n z.object({ deviceId: z.number() }),\n z.array(StreamProbeResultSchema),\n { kind: 'mutation', auth: 'admin' },\n ),\n\n // ── Bindings — per-device capability provider map ────────────────────────\n\n /**\n * Return the per-capability binding map for a device. Each entry lists the\n * currently-active provider (native or wrapper) + the underlying native\n * addon id, so consumers can decide routing without re-running discovery.\n */\n getBindings: method(\n z.object({ deviceId: z.number() }),\n z.object({\n deviceId: z.number(),\n entries: z.array(z.object({\n capName: z.string(),\n kind: z.enum(['native', 'wrapped']),\n providerAddonId: z.string(),\n providerNodeId: z.string(),\n nativeAddonId: z.string(),\n })),\n }),\n ),\n\n /**\n * Return the binding map for every device known to the hub. Used by\n * `SystemManager` warm-boot: a single round-trip resolves the\n * routing for the entire fleet so subsequent `sm.getDeviceById(id)`\n * calls are sync. Bindings change rarely (only on wrapper toggle or\n * device add/remove) — clients invalidate via the\n * `capability.binding-changed` event.\n */\n getAllBindings: method(\n z.object({}),\n z.array(z.object({\n deviceId: z.number(),\n entries: z.array(z.object({\n capName: z.string(),\n kind: z.enum(['native', 'wrapped']),\n providerAddonId: z.string(),\n providerNodeId: z.string(),\n nativeAddonId: z.string(),\n })),\n })),\n ),\n\n /**\n * Activate (or deactivate) a wrapper addon for a (device, cap) pair.\n * Persists the binding via ctx.settings. active=false clears the wrapper\n * (falls back to native if registered).\n */\n setWrapperActive: method(\n z.object({\n deviceId: z.number(),\n capName: z.string(),\n wrapperAddonId: z.string(),\n active: z.boolean(),\n }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n\n /**\n * Return the addon ids that declared a wrapper provider for `capName`.\n * Backs the device-bindings UI's wrapper-picker dropdown. Entries are\n * sourced from `CapabilityRegistry.wrapperProviders`, populated when\n * the cap definition declares `kind: 'wrapper'`.\n */\n listWrappersForCap: method(\n z.object({ capName: z.string() }),\n z.array(z.string()),\n ),\n\n /**\n * Return every device-scoped capability name that applies to a\n * deviceType (scope:'device' + deviceTypes includes the given type),\n * paired with the wrappers that can provide it. Backs the device\n * bindings UI so it can show rows for bindable caps even when no\n * native is registered yet — the user can still activate a wrapper\n * to light the cap up (e.g. snapshot via ffmpeg fallback for a camera\n * without `snapshotUrl`).\n */\n listBindableCapsForDeviceType: method(\n z.object({ deviceType: z.string() }),\n z.array(z.object({\n capName: z.string(),\n wrappers: z.array(z.string()),\n })),\n ),\n\n // ── Device-details aggregators ───────────────────────────────────────────\n //\n // Single entry point the admin UI calls to render the device-details page.\n // The hub enumerates every provider of `device-settings-contributor` (a\n // `collection` cap) plus its own base section and returns a single\n // `ConfigUISchemaWithValues` with merged tabs/sections.\n //\n // Two endpoints, two cadences:\n // - `getDeviceSettingsAggregate` — editable fields + static readonly.\n // Cached on the UI side, invalidated on successful `updateDeviceField`.\n // - `getDeviceLiveInfoAggregate` — readonly, dynamic. UI polls at a\n // short interval (~2-3 s). Fields carry `source: 'live'` so the\n // renderer knows which query owns the value.\n //\n // Save flow goes through `updateDeviceField` — the aggregator routes the\n // write to `addon-settings.updateDeviceSettings` for the declared\n // `writerAddonId` (or to its own device config store when `writerAddonId`\n // equals the device-manager addon id).\n\n getDeviceSettingsAggregate: method(\n z.object({ deviceId: z.number() }),\n SettingsSchemaWithValuesSchema.nullable(),\n ),\n getDeviceLiveInfoAggregate: method(\n z.object({ deviceId: z.number() }),\n SettingsSchemaWithValuesSchema.nullable(),\n ),\n /**\n * Unified entry point — returns both settings + live in a single call\n * so the admin UI pulls the whole device-details panel with one round-\n * trip instead of firing two parallel queries. The `live` field is the\n * polled portion; the UI re-fetches the whole aggregate at the live\n * cadence and uses the `settings` slice verbatim until the user\n * writes through `updateDeviceFieldsBatch`.\n */\n getDeviceAggregate: method(\n z.object({ deviceId: z.number() }),\n z.object({\n settings: SettingsSchemaWithValuesSchema.nullable(),\n live: SettingsSchemaWithValuesSchema.nullable(),\n }),\n ),\n runDeviceAction: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n action: z.string().min(1),\n input: z.unknown(),\n }),\n z.unknown(),\n { kind: 'mutation' },\n ),\n updateDeviceField: method(\n z.object({\n deviceId: z.number(),\n writerCapName: z.string(),\n writerAddonId: z.string(),\n key: z.string(),\n value: z.unknown(),\n }),\n z.object({ success: z.literal(true) }),\n { kind: 'mutation', auth: 'admin' },\n ),\n /**\n * Batched counterpart of `updateDeviceField` — the admin UI groups\n * per-provider changes so a single round-trip triggers at most one\n * `applyDeviceSettingsPatch` per `(capName, addonId)` tuple. Per-patch\n * failures are reported in `failures[]` without aborting the others;\n * consumers inspect the list and surface targeted errors.\n */\n updateDeviceFieldsBatch: method(\n z.object({\n deviceId: z.number(),\n changes: z.array(z.object({\n writerCapName: z.string(),\n writerAddonId: z.string(),\n key: z.string(),\n value: z.unknown(),\n })),\n }),\n z.object({\n success: z.literal(true),\n failures: z.array(z.object({\n writerCapName: z.string(),\n writerAddonId: z.string(),\n error: z.string(),\n })),\n }),\n { kind: 'mutation', auth: 'admin' },\n ),\n // ── Device-provider operations (routed via CapabilityRegistry) ────────────\n //\n // These methods proxy to the `device-provider` capability collection,\n // routing by addonId. Moving them here from the compat router\n // (`device-ops.router.ts`) allows addon ctx.api callers to reach them\n // through the standard Moleculer-registered cap surface.\n\n /** Trigger device discovery on a device-provider addon. */\n discoverDevices: method(\n z.object({ addonId: z.string() }),\n z.array(DiscoveryCandidateSchema),\n { kind: 'mutation', auth: 'admin' },\n ),\n\n /** Adopt a discovered device via the device-provider capability. */\n adoptDevice: method(\n z.object({\n addonId: z.string(),\n candidate: DiscoveryCandidateSchema,\n /** Owning integration id, stamped onto the new device's meta by the\n * device-manager forwarder so `removeByIntegration` can cascade it.\n * Optional for back-compat (omitted = no stamp = pre-existing behavior). */\n integrationId: z.string().optional(),\n }),\n DeviceSummarySchema,\n { kind: 'mutation', auth: 'admin' },\n ),\n\n /**\n * Get the creation form schema (ConfigUISchema) for a device type from a provider.\n * Returns null when the provider does not support manual creation.\n */\n getCreationSchema: method(\n z.object({\n addonId: z.string(),\n type: z.enum(DeviceType),\n }),\n z.unknown().nullable(),\n ),\n\n /** Create a new device via the device-provider capability. */\n createDevice: method(\n z.object({\n addonId: z.string(),\n type: z.enum(DeviceType),\n config: z.record(z.string(), z.unknown()),\n /** Owning integration id, stamped onto the new device's meta by the\n * device-manager forwarder so `removeByIntegration` can cascade it.\n * Optional for back-compat (omitted = no stamp = pre-existing behavior). */\n integrationId: z.string().optional(),\n }),\n DeviceSummarySchema,\n { kind: 'mutation', auth: 'admin' },\n ),\n\n /**\n * Test a single form field value during device creation (no device\n * exists yet). `formValues` carries the live snapshot of every\n * field in the form so probes that depend on multiple fields (e.g.\n * Reolink autodetect needs host + credentials + UID together) can\n * run without a separate round-trip per field. Optional for\n * backwards compatibility.\n */\n testCreationField: method(\n z.object({\n addonId: z.string(),\n type: z.enum(DeviceType),\n key: z.string(),\n value: z.unknown(),\n formValues: z.record(z.string(), z.unknown()).optional(),\n }),\n FieldProbeResultSchema,\n { kind: 'mutation', auth: 'admin' },\n ),\n\n // ── Device-adoption operations (routed via CapabilityRegistry) ────────────\n //\n // These methods proxy to the `device-adoption` capability for an\n // integration-style addon (Home Assistant, …), routing by addonId —\n // the same hub-side proxy pattern as `discoverDevices`/`adoptDevice`\n // above. The admin UI's generic adopt modal calls them through this\n // singleton so it never needs a direct handle on the addon's\n // `device-adoption` provider.\n\n // getCandidate is not proxied — the adopt modal expands rows from\n // listCandidates' nested `children`, so a single-candidate fetch is\n // never needed at this layer.\n\n /** List adoption candidates for an integration via its device-adoption provider. */\n adoptionListCandidates: method(\n AdoptionListCandidatesInputSchema.extend({ addonId: z.string() }),\n AdoptionListCandidatesOutputSchema,\n { auth: 'admin' },\n ),\n\n /** Trigger a discovery refresh on the integration's device-adoption provider. */\n adoptionRefresh: method(\n z.object({ addonId: z.string(), integrationId: z.string() }),\n AdoptionStatusSchema,\n { kind: 'mutation', auth: 'admin' },\n ),\n\n /** Adopt one or more discovered candidates via the device-adoption provider. */\n adoptionAdopt: method(\n AdoptionAdoptInputSchema.extend({ addonId: z.string() }),\n AdoptionAdoptResultSchema,\n { kind: 'mutation', auth: 'admin' },\n ),\n\n /** Release an adopted parent device via the device-adoption provider. */\n adoptionRelease: method(\n AdoptionReleaseInputSchema.extend({ addonId: z.string() }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n\n /**\n * Test a field value on an existing device (e.g. probe an RTSP URL).\n * Routes through the device-provider for the owning addon.\n */\n testField: method(\n z.object({\n deviceId: z.number(),\n key: z.string(),\n value: z.unknown(),\n }),\n FieldProbeResultSchema,\n { kind: 'mutation', auth: 'admin' },\n ),\n\n /**\n * Aggregate status snapshot across every cap registered for a\n * device. Returns a flat map `{ capName: status | null }` where\n * `status` is whatever `capDef.status.schema` validates to — or\n * `null` when no provider for that cap is registered on the\n * device, or the provider returned null, or the returned value\n * failed validation.\n *\n * `caps` is a positional tuple of cap names. The runtime only\n * returns entries for caps that are KNOWN to the system (validated\n * against `CAP_NAMES_WITH_STATUS` at call time); unknown names are\n * silently skipped. The client-side hook narrows the return type\n * using `CapStatusTypeMap` so the TS-inferred shape matches the\n * runtime shape.\n *\n * When `caps` is omitted, the server returns status for EVERY\n * registered cap on the device. Use this only for debug / overview\n * pages — it's O(N caps) per call.\n */\n getDeviceStatusAggregate: method(\n z.object({\n deviceId: z.number(),\n caps: z.array(z.string()).readonly().optional(),\n }),\n z.record(z.string(), z.unknown().nullable()),\n ),\n },\n} as const satisfies CapabilityDefinition\n\nexport type IDeviceManagerProvider = import('./capability-definition.js').InferProvider<typeof deviceManagerCapability>\nexport type DeviceInfo = z.infer<typeof DeviceInfoSchema>\n/** Input shape for `device-manager.applyInitialMeta` — the batched meta\n * pre-seed the kernel's `spawnAccessoryChild` flow uses to collapse the\n * per-child meta setters into one round-trip. Inferred from the cap method's\n * Zod schema so the kernel caller and the addon impl share one source. */\nexport type DeviceManagerApplyInitialMetaInput =\n z.infer<typeof deviceManagerCapability['methods']['applyInitialMeta']['input']>\n","import { z } from 'zod'\nimport { type CapabilityDefinition, method, event } from './capability-definition.js'\n\n/**\n * `deviceState` — generic, cap-agnostic surface for cross-process\n * access to per-device runtime state. Read pendant for every cap's\n * runtime-state slice + the canonical write entrypoint. Mirrors the\n * in-process `BaseDevice.runtimeState` API:\n *\n * - `getSnapshot({deviceId})` → full `Record<capName, slice>`.\n * - `getCapSlice({deviceId, capName})` → one slice.\n * - `setCapSlice({deviceId, capName, slice})` → unified single-slice\n * write. Hub validates (when a cap schema is registered),\n * persists to disk (debounced), updates the mirror, and emits\n * `onChanged` for that cap.\n * - `onChanged` event → fires on every slice change.\n *\n * Drivers don't implement this cap directly — the kernel auto-mounts\n * a singleton provider against `device-manager`'s in-hub mirror.\n * Every `setCapState` call on a `BaseDevice.runtimeState` ultimately\n * routes through `setCapSlice` (single cross-layer entrypoint) so\n * UIs / addons subscribe to a single event channel for every\n * cap-state change; per-cap events (`battery.onStatusChanged`, …)\n * remain available for typed consumers but no longer have to be\n * defined on every new cap with runtime state.\n */\nexport const deviceStateCapability = {\n name: 'device-state',\n scope: 'system',\n mode: 'singleton',\n methods: {\n /** Full state snapshot for one device. Empty object if no\n * cap-keyed slice has been written yet. */\n getSnapshot: method(\n z.object({ deviceId: z.number() }),\n z.record(z.string(), z.record(z.string(), z.unknown())),\n ),\n /** Single cap slice. Returns null when the slice hasn't been\n * written or the device isn't registered. */\n getCapSlice: method(\n z.object({ deviceId: z.number(), capName: z.string() }),\n z.record(z.string(), z.unknown()).nullable(),\n ),\n /**\n * Whole-system snapshot — every device's full state in one\n * payload. Used by `SystemManager` for warm-boot: a single\n * round-trip populates the client mirror so every subsequent\n * `sm.getDeviceById(id).state.<cap>.value` is sync. Empty inner\n * record for devices that haven't emitted any slice yet.\n */\n getAllSnapshots: method(\n z.object({}),\n z.record(z.string(), z.record(z.string(), z.record(z.string(), z.unknown()))),\n ),\n\n /**\n * Canonical cross-layer WRITE for one cap-keyed slice. Used by\n * everyone who needs to publish runtime state for a device:\n * device providers (via `BaseDevice.runtimeState.setCapState`\n * which delegates here), system-scope addons (e.g. the pipeline\n * runner writing the `motion` slice on phase transitions), and\n * direct cap-router callers in tests.\n *\n * Behavior on the hub:\n * 1. Resolve the device — throws if unknown.\n * 2. Diff the slice against the current mirror (no-op on\n * identical writes — saves disk and event churn).\n * 3. Update the mirror in place.\n * 4. Persist the full per-device blob to disk (debounced).\n * 5. Emit `onChanged` for this cap so subscribers (UI mirror,\n * SystemManager, per-cap typed listeners) refresh.\n *\n * Schema validation is the caller's responsibility — callers\n * going through `BaseDevice.runtimeState.setCapState` get the\n * cap's `runtimeState` schema enforced in-process before the\n * write reaches here. Direct callers should validate against\n * the cap's schema themselves.\n *\n * No `patch` variant — for shallow merges read the slice via\n * `getCapSlice` first, merge, and write. The single-writer\n * conventions on each cap make atomic-merge semantics\n * unnecessary in practice.\n */\n setCapSlice: method(\n z.object({\n deviceId: z.number(),\n capName: z.string(),\n slice: z.record(z.string(), z.unknown()),\n }),\n z.void(),\n { kind: 'mutation' },\n ),\n },\n events: {\n /**\n * Fires whenever a cap-keyed slice changes. Per-event payload\n * carries the slice that changed — subscribers can render off\n * the payload alone without re-querying. Filterable by `deviceId`\n * via the standard `EventFilter` helpers.\n */\n onChanged: event(z.object({\n deviceId: z.number(),\n capName: z.string(),\n slice: z.record(z.string(), z.unknown()),\n })),\n },\n} as const satisfies CapabilityDefinition\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\n\nconst AuthResultSchema = z.object({\n userId: z.string(),\n username: z.string(),\n email: z.string().optional(),\n displayName: z.string().optional(),\n /**\n * Whether the authenticating user is an admin. The auth-provider\n * surface returns this so the server's login flow can mint a JWT\n * with the correct bypass flag. Non-admin users authenticated via\n * an external IdP still need their scopes assigned by an admin via\n * `setUserScopes` — the SSO flow doesn't carry permissions.\n */\n isAdmin: z.boolean().default(false),\n})\n\nexport const authProviderCapability = {\n name: 'auth-provider',\n scope: 'system',\n mode: 'collection',\n internal: true,\n methods: {\n validateCredentials: method(\n z.object({ username: z.string(), password: z.string() }),\n AuthResultSchema.nullable(),\n { kind: 'mutation' },\n ),\n getLoginUrl: method(z.object({ state: z.string() }), z.string()),\n handleCallback: method(z.record(z.string(), z.string()), AuthResultSchema, { kind: 'mutation' }),\n validateToken: method(z.object({ token: z.string() }), AuthResultSchema.nullable()),\n },\n} as const satisfies CapabilityDefinition\n\nexport type IAuthProvider = InferProvider<typeof authProviderCapability>\n\nexport { AuthResultSchema }\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\n\nconst NetworkEndpointSchema = z.object({\n url: z.string(),\n hostname: z.string(),\n port: z.number(),\n protocol: z.enum(['http', 'https']),\n})\n\nconst NetworkAccessStatusSchema = z.object({\n connected: z.boolean(),\n endpoint: NetworkEndpointSchema.nullable(),\n error: z.string().optional(),\n})\n\nexport type NetworkAccessStatus = z.infer<typeof NetworkAccessStatusSchema>\nexport type NetworkEndpoint = z.infer<typeof NetworkEndpointSchema>\n\n/**\n * Optional, richer endpoint shape returned by providers that expose\n * MORE than one ingress concurrently (Tailscale Ingress with mixed\n * serve+funnel rules, future ngrok multi-tunnel, …). Each entry carries\n * the originating provider config (mode + sourcePort) so the\n * orchestrator UI can label rows distinctly. Providers that expose only\n * one endpoint just omit `listEndpoints` from their provider impl.\n */\nconst NetworkEndpointEntrySchema = NetworkEndpointSchema.extend({\n /**\n * Stable id within the provider — typically `<mode>-<sourcePort>` so\n * the orchestrator can dedupe across `listEndpoints` polls.\n */\n id: z.string(),\n /** Operator-facing label (mirrors `MeshEndpoint.label`). */\n label: z.string(),\n /** Optional provider-specific mode tag, used for icon/colour in admin UI. */\n mode: z.string().optional(),\n /** Originating local port the ingress fronts (informational). */\n sourcePort: z.number().optional(),\n})\n\nexport const networkAccessCapability = {\n name: 'network-access',\n scope: 'system',\n mode: 'collection',\n providerKind: 'ingress',\n methods: {\n start: method(z.void(), NetworkEndpointSchema, { kind: 'mutation' }),\n stop: method(z.void(), z.void(), { kind: 'mutation' }),\n getEndpoint: method(z.void(), NetworkEndpointSchema.nullable()),\n getStatus: method(z.void(), NetworkAccessStatusSchema),\n /**\n * Enumerate every active ingress entry. Providers that expose only a\n * single endpoint may omit this method; callers fall back to\n * `getEndpoint()` in that case.\n */\n listEndpoints: method(z.void(), z.array(NetworkEndpointEntrySchema).readonly()),\n },\n} as const satisfies CapabilityDefinition\n\nexport type INetworkAccessProvider = InferProvider<typeof networkAccessCapability>\n\nexport { NetworkEndpointSchema, NetworkAccessStatusSchema, NetworkEndpointEntrySchema }\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\n\n/**\n * A single ICE TURN/STUN server entry, shape compatible with\n * `RTCIceServer` in the WebRTC spec.\n */\nconst TurnServerSchema = z.object({\n /** Single URL or list of URLs (e.g. \"turn:turn.example.com:3478?transport=udp\"). */\n urls: z.union([z.string(), z.array(z.string())]),\n username: z.string().optional(),\n credential: z.string().optional(),\n})\n\n/**\n * turn-provider — system collection of TURN/STUN server providers.\n *\n * Consumed by `webrtc` providers (e.g. addon-go2rtc) when building the\n * ICE server list for an offer. Multiple providers can coexist\n * (Cloudflare, self-hosted coturn, Twilio, etc.) — the webrtc layer\n * concatenates servers from all registered implementations.\n *\n * Exposed over tRPC so that out-of-process addons (forked workers or\n * remote agents) can also enumerate available TURN servers without\n * requiring in-process access to the capability registry.\n */\nexport const turnProviderCapability = {\n name: 'turn-provider',\n scope: 'system',\n mode: 'collection',\n methods: {\n /**\n * Return the current list of TURN/STUN servers with credentials.\n * Implementations may fetch fresh short-lived credentials on each call\n * (e.g. Cloudflare API) — consumers SHOULD call this per-session.\n */\n getTurnServers: method(\n z.void(),\n z.array(TurnServerSchema).readonly(),\n ),\n },\n} as const satisfies CapabilityDefinition\n\nexport type ITurnProvider = InferProvider<typeof turnProviderCapability>\n\nexport { TurnServerSchema }\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\n\n/**\n * A single device snapshot returned as base64 JPEG/PNG.\n *\n * Shared with the `snapshot-provider` collection cap — the orchestrator\n * receives the same shape from each native provider and from the\n * broker-based fallback.\n */\nconst SnapshotImageSchema = z.object({\n base64: z.string(),\n contentType: z.string(),\n})\n\n/**\n * snapshot — device-scoped capability for camera image capture.\n *\n * Two kinds of providers coexist behind this cap name:\n *\n * - **Native** providers (kind:'native'): registered per-device by\n * device-driver addons (RtspCamera, OnvifCamera, …) via\n * `DeviceContext.registerNativeCap`. Each knows how to fetch a frame\n * straight from the camera (HTTP snapshot URL, ONVIF action, etc.).\n *\n * - **Wrapper** providers (kind:'wrapper'): register as a system\n * provider (SnapshotAddon in `@camstack/core/builtins/snapshot`). The\n * wrapper owns the cache and invokes the native via\n * `ctx.getNativeProvider(snapshotCapability, deviceId)` on miss.\n *\n * Device-scoped routing: callers use `ctx.fetchDevice(id).snapshot.*`;\n * the DeviceProxy auto-injects `deviceId` + `nodeId` and dispatches to\n * the provider currently active for that device (wrapper wins when\n * activated via `setWrapperActive`, otherwise the native).\n */\n/**\n * Live readable snapshot state — diagnostic info that a consumer can\n * pull to know when the last image was captured, how stale the cache\n * is, and which stream was used. Distinct from `getSnapshot` which\n * returns the JPEG itself.\n */\nconst SnapshotStatusSchema = z.object({\n /** Ms epoch of the last successful capture. Null if none yet. */\n lastCapturedAt: z.number().nullable(),\n /** Age of the cached image in ms. Null if no cache. */\n cacheAgeMs: z.number().nullable(),\n /** Size in bytes of the last captured image. Null if no capture. */\n lastBytes: z.number().nullable(),\n /** Stream id used for the last capture ('high'|'mid'|'low' or custom). Null if via HTTP endpoint. */\n lastStreamId: z.string().nullable(),\n})\n\nexport const snapshotCapability = {\n name: 'snapshot',\n scope: 'device',\n deviceNative: true,\n mode: 'singleton',\n kind: 'wrapper',\n defaultActive: true,\n deviceTypes: [DeviceType.Camera],\n // Owns per-device snapshot settings (preferred stream, debug logging).\n // The three DeviceSettingsContribution methods are auto-added to the\n // provider interface via `InferProvider` — `SnapshotAddon` implements\n // them and persists per-device state through `ctx.settings.writeDeviceStore`.\n exposesDeviceSettings: true,\n methods: {\n getSnapshot: method(\n z.object({\n deviceId: z.number(),\n streamId: z.string().optional(),\n /**\n * Bypass the cache freshness check and fetch directly from the\n * native (or stream-broker fallback). Triggered by the UI's\n * \"refresh\" button so an operator can force a fresh frame\n * even when the cache is well within `snapshotMaxAgeMs`.\n * On battery cams this WILL wake the camera — accept the\n * cost only when the user explicitly asks for it.\n */\n force: z.boolean().optional(),\n }),\n SnapshotImageSchema.nullable(),\n ),\n invalidateCache: method(\n z.object({ deviceId: z.number() }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n },\n status: {\n schema: SnapshotStatusSchema,\n kind: 'poll',\n },\n} as const satisfies CapabilityDefinition\n\nexport type ISnapshotOrchestrator = InferProvider<typeof snapshotCapability>\n\nexport { SnapshotImageSchema, SnapshotStatusSchema }\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { SnapshotImageSchema } from './snapshot.cap.js'\n\n/**\n * snapshot-provider — collection of native snapshot implementations.\n *\n * Device provider addons (ONVIF, Frigate, etc.) register here\n * when they can capture frames through a protocol-native path (e.g.\n * ONVIF GetSnapshotUri, Frigate /api/<cam>/latest.jpg). The `snapshot`\n * singleton orchestrator iterates over the collection, asking each\n * provider whether it supports the requested device, and calls the\n * first matching one.\n *\n * If no provider in the collection supports a device, the orchestrator\n * falls back to `stream-broker.grabFrame` (universal fallback).\n *\n * Public tRPC router (auto-mounted) so out-of-process addons, agents,\n * and advanced clients can bypass the orchestrator when needed.\n */\nexport const snapshotProviderCapability = {\n name: 'snapshot-provider',\n scope: 'system',\n mode: 'collection',\n methods: {\n supportsDevice: method(\n z.object({ deviceId: z.number() }),\n z.boolean(),\n ),\n getSnapshot: method(\n z.object({\n deviceId: z.number(),\n streamId: z.string().optional(),\n }),\n SnapshotImageSchema.nullable(),\n ),\n },\n} as const satisfies CapabilityDefinition\n\nexport type ISnapshotProvider = InferProvider<typeof snapshotProviderCapability> & {\n readonly id: string\n readonly name: string\n}\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\n\nconst NotificationSchema = z.object({\n title: z.string(),\n body: z.string(),\n imageUrl: z.string().optional(),\n deviceId: z.number().optional(),\n eventId: z.string().optional(),\n priority: z.enum(['low', 'normal', 'high', 'critical']).default('normal'),\n metadata: z.record(z.string(), z.unknown()).optional(),\n})\n\nexport const notificationOutputCapability = {\n name: 'notification-output',\n scope: 'system',\n mode: 'collection',\n methods: {\n send: method(NotificationSchema, z.void(), { kind: 'mutation' }),\n sendTest: method(\n z.void(),\n z.object({ success: z.boolean(), error: z.string().optional() }),\n { kind: 'mutation' },\n ),\n },\n} as const satisfies CapabilityDefinition\n\nexport type INotificationOutputProvider = InferProvider<typeof notificationOutputCapability>\n\nexport { NotificationSchema }\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\n\nconst NotificationRuleConditionsSchema = z.object({\n deviceIds: z.array(z.number()).readonly().optional(),\n classNames: z.array(z.string()).readonly().optional(),\n zoneIds: z.array(z.string()).readonly().optional(),\n minConfidence: z.number().optional(),\n source: z.enum(['pipeline', 'onboard', 'any']).optional(),\n schedule: z.object({\n days: z.array(z.number()).readonly(),\n startHour: z.number(),\n endHour: z.number(),\n }).optional(),\n cooldownSeconds: z.number().optional(),\n minDwellSeconds: z.number().optional(),\n /** Match against `event.data.eventType` token (e.g. `'press_long'`). When non-empty, only events\n * carrying a matching `data.eventType` string pass this condition. Rules without this field are\n * unaffected (back-compat). Distinct from `rule.eventTypes` which holds EventCategory strings. */\n eventTypeTokens: z.array(z.string()).readonly().optional(),\n})\n\nconst NotificationRuleTemplateSchema = z.object({\n title: z.string(),\n body: z.string(),\n imageMode: z.enum(['crop', 'annotated', 'full', 'none']),\n})\n\nconst NotificationRuleSchema = z.object({\n id: z.string(),\n name: z.string(),\n enabled: z.boolean(),\n eventTypes: z.array(z.string()).readonly(),\n conditions: NotificationRuleConditionsSchema,\n outputs: z.array(z.string()).readonly(),\n template: NotificationRuleTemplateSchema.optional(),\n priority: z.enum(['low', 'normal', 'high', 'critical']),\n})\n\nconst NotificationTestResultSchema = z.object({\n ruleId: z.string(),\n eventId: z.string(),\n timestamp: z.number(),\n wouldFire: z.boolean(),\n reason: z.string().optional(),\n})\n\nconst NotificationHistoryEntrySchema = z.object({\n id: z.string(),\n ruleId: z.string(),\n ruleName: z.string(),\n eventId: z.string(),\n timestamp: z.number(),\n outputs: z.array(z.string()).readonly(),\n success: z.boolean(),\n error: z.string().optional(),\n deviceId: z.number().optional(),\n})\n\nconst NotificationHistoryFilterSchema = z.object({\n ruleId: z.string().optional(),\n deviceId: z.number().optional(),\n from: z.number().optional(),\n to: z.number().optional(),\n limit: z.number().optional(),\n})\n\nexport const advancedNotifierCapability = {\n name: 'advanced-notifier',\n scope: 'system',\n mode: 'singleton',\n internal: true,\n methods: {\n getRules: method(\n z.void(),\n z.object({ rules: z.array(NotificationRuleSchema).readonly() }),\n ),\n upsertRule: method(\n z.object({ rule: NotificationRuleSchema }),\n z.object({ success: z.literal(true) }),\n { kind: 'mutation' },\n ),\n deleteRule: method(\n z.object({ ruleId: z.string() }),\n z.object({ success: z.literal(true) }),\n { kind: 'mutation' },\n ),\n testRule: method(\n z.object({ ruleId: z.string(), lookbackMinutes: z.number() }),\n z.object({ results: z.array(NotificationTestResultSchema).readonly() }),\n { kind: 'mutation' },\n ),\n getHistory: method(\n z.object({ filter: NotificationHistoryFilterSchema.optional() }),\n z.object({ entries: z.array(NotificationHistoryEntrySchema).readonly() }),\n ),\n },\n} as const satisfies CapabilityDefinition\n\nexport type IAdvancedNotifierProvider = InferProvider<typeof advancedNotifierCapability>\n\nexport {\n NotificationRuleSchema,\n NotificationRuleConditionsSchema,\n NotificationRuleTemplateSchema,\n NotificationTestResultSchema,\n NotificationHistoryEntrySchema,\n NotificationHistoryFilterSchema,\n}\n","import { type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\n\n/**\n * detection-pipeline — device-scoped facade over the system\n * `pipeline-executor`.\n *\n * Pairs with `pipeline-executor` (system, singleton) the way\n * `audio-analysis` pairs with `audio-analyzer`: the system cap owns the\n * engine lifecycle (engines, templates, models, runPipeline) while\n * `detection-pipeline` is the per-camera binding row in the\n * device-manager UI.\n *\n * The cap definition itself declares `kind: 'wrapper'` and\n * `defaultActive: true`, so every camera opts into detection automatically\n * without any runtime flag in the addon's registration. Operators disable\n * per-device via `device-manager.setWrapperActive` — replaces the legacy\n * `pipelineEnabled` / `disableInference` flags previously stored in the\n * orchestrator's device-settings.\n *\n * `exposesDeviceSettings: true` is intentional — the three\n * DeviceSettingsContribution methods auto-added to the provider\n * interface serve the per-device detection settings panel in the admin\n * UI (model selection, class filters, confidence thresholds).\n */\nexport const detectionPipelineCapability = {\n name: 'detection-pipeline',\n scope: 'device',\n mode: 'singleton',\n kind: 'wrapper',\n defaultActive: true,\n deviceTypes: [DeviceType.Camera],\n exposesDeviceSettings: true,\n methods: {},\n} as const satisfies CapabilityDefinition\n\nexport type IDetectionPipelineProvider = InferProvider<typeof detectionPipelineCapability>\n","import { type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\n\n/**\n * camera-pipeline-config — device-scoped wrapper that carries the\n * pipeline-orchestrator's PER-DEVICE settings contribution into the\n * binding-driven device-detail aggregate (D12).\n *\n * Why this cap exists: the orchestrator's per-camera settings (motion\n * sources / fps / cooldown, detection + audio mode, cluster assignment,\n * the Detection-Zones top-tab widget, onboard-motion + onboard-object-\n * detection toggles) were historically contributed via the\n * `pipeline-orchestrator` cap's `exposesDeviceSettings` methods. But\n * `pipeline-orchestrator` is `scope:'system'` and never appears in\n * `getBindings(deviceId)`, so the D12 binding-driven aggregate\n * (`device-manager.getDeviceAggregate`) silently dropped the entire\n * contribution — the zones tab and the pipeline/motion settings vanished\n * from device-detail.\n *\n * `kind:'wrapper'` + `defaultActive:true` makes this cap auto-bind to every\n * camera (it appears in `getBindings` as `kind:'wrapped'`), so the aggregate\n * invokes the orchestrator's contribution methods through it — restoring the\n * tabs without violating D12 (contributions come only from bound providers).\n *\n * `exposesDeviceSettings:true` (NOT `deviceConfig`) is intentional: the\n * contribution is a dynamic, multi-section, per-device hand-built structure\n * (it probes bindings for onboard-motion / native-object-detection presence,\n * cluster nodes, etc.), which the derived-UI `deviceConfig` archetype cannot\n * express. This mirrors the `detection-pipeline` / `motion-detection`\n * wrapper pattern. The orchestrator class is the provider; it already\n * implements the three DeviceSettingsContribution methods.\n */\nexport const cameraPipelineConfigCapability = {\n name: 'camera-pipeline-config',\n scope: 'device',\n mode: 'singleton',\n kind: 'wrapper',\n defaultActive: true,\n deviceTypes: [DeviceType.Camera],\n exposesDeviceSettings: true,\n methods: {},\n} as const satisfies CapabilityDefinition\n\nexport type ICameraPipelineConfigProvider = InferProvider<typeof cameraPipelineConfigCapability>\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\nimport { BoundingBoxSchema } from './schemas/detection-shared.js'\n\n/**\n * pipeline-analytics — device-scoped wrapper cap. Refines raw\n * per-frame detections emitted by the pipeline runner into tracked\n * objects, per-kind event collections (motion / object / audio), and\n * persisted media. Owns the post-detection domain end-to-end:\n *\n * runner emits PipelineInferenceResult\n * ↓ (event bus)\n * pipeline-analytics subscriber\n * ↓ SORT tracker + zone engine + state analyzer + event emitter\n * → three DB collections (one per kind), one FS media tree, one\n * unified event emitter (FrameTracked + TrackStarted/Ended +\n * DetectionEvent on bus)\n *\n * Pure subscriber model. No `processFrame` cap method — the runner\n * already publishes the raw frame on the bus. The cap surface is\n * only QUERIES + per-device settings, bound on/off via\n * `device-manager.setWrapperActive`. `defaultActive: true` because\n * every camera with a detection pipeline wants its raw detections\n * refined; operators opt out per-device via BindingsTab when needed.\n *\n * Replaces the legacy `analysis-pipeline`, `analysis-data-persistence`\n * (per-device surface) and `track-trail` caps — see P11 cleanup.\n */\n\n// ── Shared sub-schemas ──────────────────────────────────────────────\n\nconst TrackStateSchema = z.enum(['new', 'entered', 'left', 'moving', 'idle'])\nexport type TrackState = z.infer<typeof TrackStateSchema>\n\nconst EventKindSchema = z.enum(['motion', 'object', 'audio'])\nexport type EventKind = z.infer<typeof EventKindSchema>\n\n// ── Track (unified: identity + positions + snapshots) ───────────────\n\nconst TrackPositionSchema = z.object({\n x: z.number(),\n y: z.number(),\n timestamp: z.number(),\n bbox: BoundingBoxSchema,\n})\n\nconst TrackSnapshotSchema = z.object({\n timestamp: z.number(),\n position: TrackPositionSchema,\n /** MediaStore key; resolve via `getTrackMedia({ trackId })`. */\n mediaKey: z.string(),\n})\n\nconst TrackSchema = z.object({\n trackId: z.string(),\n deviceId: z.number(),\n className: z.string(),\n label: z.string().optional(),\n firstSeen: z.number(),\n lastSeen: z.number(),\n /** Frame-rate position history (subject to maxPositionHistory cap). */\n positions: z.array(TrackPositionSchema).readonly(),\n /** Periodic snapshots at snapshotIntervalMs cadence (subject to\n * saveThumbnails policy). */\n snapshots: z.array(TrackSnapshotSchema).readonly(),\n /** Deduplicated zones the track has entered at least once. */\n zonesVisited: z.array(z.string()).readonly(),\n /** Cumulative normalized distance travelled (0..1 units = full frame width). */\n totalDistance: z.number(),\n state: TrackStateSchema,\n active: z.boolean(),\n})\nexport type Track = z.infer<typeof TrackSchema>\n// TrackPosition / TrackSnapshot types stay internal — consumers access\n// them through `track.positions[i]` / `track.snapshots[i]`. Top-level\n// names are reserved for the legacy interfaces/analysis-persistence.ts\n// until P11 cleanup.\n\n// ── Events (per-kind, three separate backing collections) ───────────\n\nconst BaseEventFields = {\n id: z.string(),\n deviceId: z.number(),\n timestamp: z.number(),\n}\n\nconst MotionEventSchema = z.object({\n ...BaseEventFields,\n kind: z.literal('motion'),\n regionCount: z.number(),\n /** Heavy JSON array — omitted in slim projection. */\n regions: z.array(z.object({\n bbox: BoundingBoxSchema,\n pixelCount: z.number(),\n intensity: z.number(),\n })).readonly().optional(),\n /** Omitted in slim projection. */\n frameWidth: z.number().optional(),\n /** Omitted in slim projection. */\n frameHeight: z.number().optional(),\n /** Populated by B5 (recording playback URL for this event). */\n mediaUrl: z.string().optional(),\n})\nexport type MotionEvent = z.infer<typeof MotionEventSchema>\n\nconst ObjectEventSchema = z.object({\n ...BaseEventFields,\n kind: z.literal('object'),\n /** Omitted in slim projection. */\n trackId: z.string().optional(),\n className: z.string(),\n label: z.string().optional(),\n /** Omitted in slim projection. */\n confidence: z.number().optional(),\n /** Heavy JSON — omitted in slim projection. */\n bbox: BoundingBoxSchema.optional(),\n /** Heavy JSON — omitted in slim projection. */\n zones: z.array(z.string()).readonly().optional(),\n /** Omitted in slim projection. */\n state: TrackStateSchema.optional(),\n /** MediaStore key for the crop attached to this event (if any). */\n mediaKey: z.string().optional(),\n /** Populated by B5 (recording playback URL for this event). */\n mediaUrl: z.string().optional(),\n})\nexport type ObjectEvent = z.infer<typeof ObjectEventSchema>\n\nconst AudioEventSchema = z.object({\n ...BaseEventFields,\n kind: z.literal('audio'),\n rms: z.number(),\n dbfs: z.number(),\n classification: z.object({\n className: z.string(),\n originalClass: z.string().optional(),\n score: z.number(),\n }).optional(),\n /** Populated by B5 (recording playback URL for this event). */\n mediaUrl: z.string().optional(),\n})\nexport type AudioEvent = z.infer<typeof AudioEventSchema>\n\n// ── Media files (crops / thumbs / snapshots) ────────────────────────\n\nconst MediaFileSchema = z.object({\n key: z.string(),\n kind: z.enum(['crop', 'thumbnail', 'snapshot']),\n base64: z.string(),\n sizeBytes: z.number(),\n timestamp: z.number(),\n})\nexport type MediaFile = z.infer<typeof MediaFileSchema>\n\n// ── Query input schemas ─────────────────────────────────────────────\n\n// Hard cap on event-list responses. Without it, queries against the\n// 1M+ row analytics tables (audio classifier inserts ~1500 rows/min\n// per active camera) return every row + classification blob, blow\n// past the tRPC 5s default, and OOM the JSON serializer. Callers\n// needing more than MAX in one batch should paginate via since/until.\nconst DEFAULT_EVENT_QUERY_LIMIT = 1000\nconst MAX_EVENT_QUERY_LIMIT = 5000\n\nconst DeviceEventQueryInput = z.object({\n deviceId: z.number(),\n since: z.number().optional(),\n until: z.number().optional(),\n limit: z.number().int().min(1).max(MAX_EVENT_QUERY_LIMIT).default(DEFAULT_EVENT_QUERY_LIMIT),\n /** `slim` drops heavy JSON fields (regions/bbox/zones) and carries an\n * optional `mediaUrl` (populated by B5). `full` (default) keeps today's\n * exact behaviour. Callers may omit this field — the store defaults to\n * `full` when not provided. */\n projection: z.enum(['full', 'slim']).optional(),\n})\n\nconst ObjectEventQueryInput = DeviceEventQueryInput.extend({\n classFilter: z.string().optional(),\n})\n\n// ── Enriched frame emitted on bus after refinement ──────────────────\n//\n// Lightweight: carries only the tracked-detection metadata consumers\n// need to overlay track IDs / zones on a live stream. Full Track state\n// is queryable via getActiveTracks / getTrack.\n\nconst TrackedDetectionSchema = z.object({\n trackId: z.string(),\n className: z.string(),\n confidence: z.number(),\n bbox: BoundingBoxSchema,\n zones: z.array(z.string()).readonly(),\n state: TrackStateSchema,\n})\n\n// ── Capability definition ───────────────────────────────────────────\n\nexport const pipelineAnalyticsCapability = {\n name: 'pipeline-analytics',\n scope: 'device',\n mode: 'singleton',\n kind: 'wrapper',\n defaultActive: true,\n deviceTypes: [DeviceType.Camera],\n exposesDeviceSettings: true,\n methods: {\n // ── Tracks ────────────────────────────────────────────────\n getActiveTracks: method(\n z.object({ deviceId: z.number() }),\n z.array(TrackSchema).readonly(),\n ),\n getTrack: method(\n z.object({ deviceId: z.number(), trackId: z.string() }),\n TrackSchema.nullable(),\n ),\n /** Historical completed tracks for a device. Queried from the\n * persisted `pipeline-analytics:tracks` collection; active tracks\n * still in RAM are not included. */\n listTracks: method(\n z.object({\n deviceId: z.number(),\n since: z.number().optional(),\n until: z.number().optional(),\n limit: z.number().optional(),\n }),\n z.array(TrackSchema).readonly(),\n ),\n clearTracks: method(\n z.object({ deviceId: z.number() }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n\n // ── Events (per-kind, parallel-queryable) ─────────────────\n getMotionEvents: method(\n DeviceEventQueryInput,\n z.array(MotionEventSchema).readonly(),\n ),\n getObjectEvents: method(\n ObjectEventQueryInput,\n z.array(ObjectEventSchema).readonly(),\n ),\n getAudioEvents: method(\n DeviceEventQueryInput,\n z.array(AudioEventSchema).readonly(),\n ),\n\n // ── Density (timeline histogram) ──────────────────────────\n /** Server-side bucketed event counts for the 24-hour timeline.\n * Returns one entry per non-empty bucket; empty buckets are omitted. */\n getEventDensity: method(\n z.object({\n deviceId: z.number(),\n since: z.number(),\n until: z.number(),\n bucketMs: z.number().int().positive(),\n }),\n z.array(z.object({\n bucketStart: z.number(),\n motion: z.number().int(),\n object: z.number().int(),\n audio: z.number().int(),\n })).readonly(),\n ),\n\n // ── Maintenance ───────────────────────────────────────────\n /**\n * Delete all events (motion + object + audio) for the given device\n * that are older than `cutoffMs` (exclusive), and delete their\n * thumbnails in lockstep. Returns per-kind deleted counts.\n *\n * Called by Phase B3 recorder orchestration to keep event history\n * aligned with available footage.\n */\n pruneEventsBefore: method(\n z.object({ deviceId: z.number(), cutoffMs: z.number() }),\n z.object({ motion: z.number().int(), object: z.number().int(), audio: z.number().int() }),\n { kind: 'mutation', auth: 'admin' },\n ),\n\n // ── Media ─────────────────────────────────────────────────\n getEventMedia: method(\n z.object({ eventId: z.string() }),\n z.array(MediaFileSchema).readonly(),\n ),\n getTrackMedia: method(\n z.object({ trackId: z.string() }),\n z.array(MediaFileSchema).readonly(),\n ),\n },\n events: {\n /**\n * Enriched frame emitted after refinement. Carries lightweight\n * tracked-detection metadata (track id, class, zones, state) so\n * downstream consumers (stream overlays, notifications) can\n * annotate without querying full Track state.\n */\n onFrameTracked: {\n data: z.object({\n deviceId: z.number(),\n timestamp: z.number(),\n frameWidth: z.number(),\n frameHeight: z.number(),\n detections: z.array(TrackedDetectionSchema).readonly(),\n }),\n },\n /** Track entered active state (first-seen). */\n onTrackStarted: {\n data: z.object({\n deviceId: z.number(),\n trackId: z.string(),\n className: z.string(),\n }),\n },\n /** Track expired (TTL reached after last detection). */\n onTrackEnded: {\n data: z.object({\n deviceId: z.number(),\n trackId: z.string(),\n className: z.string(),\n durationMs: z.number(),\n }),\n },\n /** Canonical \"something happened at device X\" event, per-kind. */\n onDetectionEvent: {\n data: z.object({\n deviceId: z.number(),\n kind: EventKindSchema,\n eventId: z.string(),\n timestamp: z.number(),\n }),\n },\n },\n} as const satisfies CapabilityDefinition\n\nexport type IPipelineAnalyticsProvider = InferProvider<typeof pipelineAnalyticsCapability>\n\nexport {\n TrackStateSchema,\n EventKindSchema,\n TrackSchema,\n MotionEventSchema,\n ObjectEventSchema,\n AudioEventSchema,\n MediaFileSchema,\n TrackedDetectionSchema,\n}\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\n\n// ── Snapshot schemas ────────────────────────────────────────────────\n\nconst CpuBreakdownSchema = z.object({\n total: z.number(),\n user: z.number(),\n system: z.number(),\n irq: z.number(),\n nice: z.number(),\n loadAvg: z.tuple([z.number(), z.number(), z.number()]),\n cores: z.number(),\n})\n\nconst MemoryInfoSchema = z.object({\n percent: z.number(),\n totalBytes: z.number(),\n usedBytes: z.number(),\n availableBytes: z.number(),\n swapUsedBytes: z.number(),\n swapTotalBytes: z.number(),\n})\n\nconst DiskIoSnapshotSchema = z.object({\n readBytes: z.number(),\n writeBytes: z.number(),\n readOps: z.number(),\n writeOps: z.number(),\n timestampMs: z.number(),\n})\n\nconst NetworkIoSnapshotSchema = z.object({\n rxBytes: z.number(),\n txBytes: z.number(),\n rxPackets: z.number(),\n txPackets: z.number(),\n rxErrors: z.number(),\n txErrors: z.number(),\n timestampMs: z.number(),\n})\n\nconst MetricsGpuInfoSchema = z.object({\n utilization: z.number(),\n model: z.string(),\n memoryUsedBytes: z.number(),\n memoryTotalBytes: z.number(),\n temperature: z.number().nullable(),\n})\n\nconst ProcessResourceInfoSchema = z.object({\n openFds: z.number(),\n threadCount: z.number(),\n activeHandles: z.number(),\n activeRequests: z.number(),\n})\n\nconst PressureAvgsSchema = z.object({\n avg10: z.number(),\n avg60: z.number(),\n avg300: z.number(),\n})\n\nconst PressureInfoSchema = z.object({\n some: PressureAvgsSchema,\n full: PressureAvgsSchema.nullable(),\n})\n\nconst SystemResourceSnapshotSchema = z.object({\n cpu: CpuBreakdownSchema,\n memory: MemoryInfoSchema,\n gpu: MetricsGpuInfoSchema.nullable(),\n network: NetworkIoSnapshotSchema,\n disk: DiskIoSnapshotSchema,\n pressure: z.object({\n cpu: PressureInfoSchema.nullable(),\n memory: PressureInfoSchema.nullable(),\n io: PressureInfoSchema.nullable(),\n }),\n process: ProcessResourceInfoSchema,\n cpuTemperature: z.number().nullable(),\n timestampMs: z.number(),\n})\n\nconst DiskSpaceInfoSchema = z.object({\n path: z.string(),\n totalBytes: z.number(),\n usedBytes: z.number(),\n availableBytes: z.number(),\n percent: z.number(),\n})\n\nconst PidResourceStatsSchema = z.object({\n pid: z.number(),\n cpu: z.number(),\n memory: z.number(),\n})\n\nconst AddonInstanceSchema = z.object({\n addonId: z.string(),\n nodeId: z.string(),\n role: z.enum(['hub', 'worker']),\n pid: z.number(),\n state: z.enum(['starting', 'running', 'stopping', 'stopped', 'crashed']),\n uptimeSec: z.number(),\n})\n\n// ── Process tree snapshot (ghost / zombie surfacing) ────────────────\n//\n// Each entry describes one OS process on the node that looks camstack-\n// related. Classification is ancestry-driven: walk pid→ppid until we\n// hit a known supervisor boundary OR ppid=1.\n//\n// root — the current node's own pid (process.pid)\n// managed — forked addon worker registered in `$process.list`\n// system — ancestry walk crosses a known supervisor boundary\n// (tsx watch launcher, agent CLI, concurrently, vite,\n// npm wrapper). Belongs to the intentional dev tree even\n// when not in $process.list. NEVER killable.\n// ghost — ancestry reaches ppid=1 (or parent invisible in `ps`)\n// without crossing a supervisor boundary. The ONLY\n// classification eligible for kill from the UI.\nconst NodeProcessSchema = z.object({\n pid: z.number(),\n ppid: z.number(),\n pgid: z.number(),\n classification: z.enum(['root', 'managed', 'system', 'ghost']),\n /** `$process` addon binding when `managed`, else null. */\n addonId: z.string().nullable(),\n /** Kernel-reported nodeId when the process is a known agent/worker. */\n nodeId: z.string().nullable(),\n /** Truncated command line. */\n command: z.string(),\n cpuPercent: z.number(),\n memoryRssBytes: z.number(),\n /** Wall-clock uptime (seconds). Parsed from `ps etime`. */\n uptimeSec: z.number(),\n /** True when ancestor walk reaches `ppid=1` (reparented to init/launchd). */\n orphaned: z.boolean(),\n})\n\nconst KillProcessInputSchema = z.object({\n pid: z.number(),\n /** Force = SIGKILL. Default is SIGTERM. */\n force: z.boolean().optional(),\n})\n\nconst KillProcessResultSchema = z.object({\n success: z.boolean(),\n reason: z.string().optional(),\n signal: z.enum(['SIGTERM', 'SIGKILL']).optional(),\n})\n\n// Public SystemMetrics summary — light-weight cached view used by UI widgets.\nconst SystemMetricsSchema = z.object({\n cpuPercent: z.number(),\n memoryPercent: z.number(),\n memoryUsedMB: z.number(),\n memoryTotalMB: z.number(),\n diskPercent: z.number().optional(),\n temperature: z.number().optional(),\n gpuPercent: z.number().optional(),\n gpuMemoryPercent: z.number().optional(),\n})\n\n// ── Capability definition ───────────────────────────────────────────\n\nexport const metricsProviderCapability = {\n name: 'metrics-provider',\n scope: 'system',\n mode: 'singleton',\n methods: {\n /** Fresh, full system snapshot (triggers OS-level collection). */\n collectSnapshot: method(z.void(), SystemResourceSnapshotSchema),\n /** Most recent cached snapshot from the background sampler, or null pre-first-sample. */\n getCached: method(z.void(), SystemResourceSnapshotSchema.nullable()),\n /** Light-weight cached summary for heartbeats and list views. */\n getCurrent: method(z.void(), SystemMetricsSchema),\n /** Disk space for the given mount/path. */\n getDiskSpace: method(z.object({ dirPath: z.string() }), DiskSpaceInfoSchema),\n /** GPU info (null if unavailable). */\n getGpuInfo: method(z.void(), MetricsGpuInfoSchema.nullable()),\n /** CPU temperature in °C (null if unavailable). */\n getCpuTemperature: method(z.void(), z.number().nullable()),\n /** Per-PID resource stats. Missing/dead PIDs are omitted from the result. */\n getProcessStats: method(\n z.object({ pids: z.array(z.number()) }),\n z.array(PidResourceStatsSchema),\n ),\n /**\n * List addon instances known to this node — one entry per forked worker\n * plus a synthetic 'hub' entry representing the local hub process.\n * Used by benchmarks/observability to detect whether a given addon runs\n * in its own process (measurable independently) or inline with the hub.\n */\n listAddonInstances: method(z.void(), z.array(AddonInstanceSchema).readonly()),\n /**\n * Resource stats for the process hosting the given addon.\n * Returns null when the addon runs in-process on the hub (can't measure\n * independently — caller should detect via listAddonInstances). Returns\n * hub process stats for addonId '$hub'.\n */\n getAddonStats: method(z.object({ addonId: z.string() }), PidResourceStatsSchema.nullable()),\n /**\n * Snapshot of every camstack-related process on this node with a\n * ghost/managed/root classification. Powers the Cluster → Agent →\n * Processes tab: cross-references `$process.list` against a `ps` scan\n * so orphaned trees (PPID=1) or unknown children show up as `ghost`\n * and can be killed from the UI.\n */\n listNodeProcesses: method(z.void(), z.array(NodeProcessSchema).readonly()),\n /**\n * Send SIGTERM (or SIGKILL when `force`) to a pid inside this node's\n * process tree. The provider refuses pids that aren't in the live\n * `listNodeProcesses()` snapshot — callers can't use this endpoint\n * to kill arbitrary system processes.\n */\n killProcess: method(\n KillProcessInputSchema,\n KillProcessResultSchema,\n { kind: 'mutation', auth: 'admin' },\n ),\n },\n} as const satisfies CapabilityDefinition\n\nexport type IMetricsProvider = InferProvider<typeof metricsProviderCapability>\n\nexport {\n SystemMetricsSchema,\n SystemResourceSnapshotSchema,\n DiskSpaceInfoSchema,\n MetricsGpuInfoSchema,\n PidResourceStatsSchema,\n AddonInstanceSchema,\n NodeProcessSchema,\n KillProcessInputSchema,\n KillProcessResultSchema,\n CpuBreakdownSchema,\n MemoryInfoSchema,\n DiskIoSnapshotSchema,\n NetworkIoSnapshotSchema,\n ProcessResourceInfoSchema,\n PressureInfoSchema,\n}\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\n\nconst PtzPresetSchema = z.object({ id: z.string(), name: z.string() })\nconst PtzPositionSchema = z.object({ pan: z.number(), tilt: z.number(), zoom: z.number() })\nconst PtzMoveCommandSchema = z.object({\n pan: z.number().optional(),\n tilt: z.number().optional(),\n zoom: z.number().optional(),\n speed: z.number().optional(),\n})\n\n/** PTZ status — current position plus the camera's autofocus state.\n * `getPosition` / `move` still operate on the bare position; the\n * auto-injected `getStatus` returns this richer block. */\nconst PtzStatusSchema = PtzPositionSchema.extend({ autofocus: z.boolean() })\n\n/** Per-camera PTZ availability descriptor — drives the UI. */\nconst PtzOptionsSchema = z.object({\n hasPan: z.boolean(),\n hasTilt: z.boolean(),\n hasZoom: z.boolean(),\n supportsPresets: z.boolean(),\n /** Max number of named presets the camera supports, when known. */\n maxPresets: z.number().optional(),\n /** Whether the camera exposes a controllable autofocus toggle\n * (boolean `hasX` per the getOptions availability convention). */\n hasAutofocus: z.boolean(),\n})\n\nexport const ptzCapability = {\n name: 'ptz',\n scope: 'device',\n deviceNative: true,\n mode: 'singleton',\n deviceTypes: [DeviceType.Camera],\n deviceConfig: {\n ui: { kind: 'widget', widgetId: 'host/ptz-panel', tab: 'ptz', topTab: true, label: 'PTZ', order: 0 },\n },\n methods: {\n move: method(\n PtzMoveCommandSchema.extend({ deviceId: z.number() }),\n z.void(),\n { kind: 'mutation' },\n ),\n continuousMove: method(\n PtzMoveCommandSchema.extend({ deviceId: z.number() }),\n z.void(),\n { kind: 'mutation' },\n ),\n stop: method(\n z.object({ deviceId: z.number() }),\n z.void(),\n { kind: 'mutation' },\n ),\n getPresets: method(\n z.object({ deviceId: z.number() }),\n z.array(PtzPresetSchema),\n ),\n goToPreset: method(\n z.object({ deviceId: z.number(), presetId: z.string() }),\n z.void(),\n { kind: 'mutation' },\n ),\n savePreset: method(\n z.object({ deviceId: z.number(), presetId: z.string(), name: z.string() }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n deletePreset: method(\n z.object({ deviceId: z.number(), presetId: z.string() }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n getOptions: method(\n z.object({ deviceId: z.number() }),\n PtzOptionsSchema,\n ),\n goHome: method(\n z.object({ deviceId: z.number() }),\n z.void(),\n { kind: 'mutation' },\n ),\n /**\n * Pull the current PTZ position. Redundant with the auto-injected\n * `getStatus` method (see `status` below); kept for callers that\n * haven't migrated. Will be folded into `getStatus` in a future\n * cleanup pass once all consumers use the typed status surface.\n */\n getPosition: method(\n z.object({ deviceId: z.number() }),\n PtzPositionSchema,\n ),\n /** Toggle the camera's autofocus. Only meaningful when\n * `getOptions().hasAutofocus` is true. */\n setAutofocus: method(\n z.object({ deviceId: z.number(), enabled: z.boolean() }),\n z.void(),\n { kind: 'mutation' },\n ),\n },\n status: {\n schema: PtzStatusSchema,\n kind: 'command-driven',\n },\n} as const satisfies CapabilityDefinition\n\nexport type IPtzProvider = InferProvider<typeof ptzCapability>\nexport type PtzOptions = z.infer<typeof PtzOptionsSchema>\nexport type PtzStatus = z.infer<typeof PtzStatusSchema>\nexport { PtzPresetSchema, PtzPositionSchema, PtzStatusSchema, PtzMoveCommandSchema, PtzOptionsSchema }\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\n\nconst EventItemSchema = z.object({\n id: z.string(),\n type: z.string(),\n timestamp: z.number(), // unix ms\n label: z.string().optional(),\n thumbnailUrl: z.string().optional(),\n clipUrl: z.string().optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n})\n\nexport const eventsCapability = {\n name: 'events',\n scope: 'device',\n mode: 'singleton',\n deviceTypes: [DeviceType.Camera],\n methods: {\n getEvents: method(\n z.object({\n deviceId: z.number(),\n from: z.number().optional(),\n to: z.number().optional(),\n limit: z.number().optional(),\n }),\n z.array(EventItemSchema),\n ),\n getEventThumbnail: method(\n z.object({ deviceId: z.number(), eventId: z.string() }),\n z.object({ base64: z.string(), contentType: z.string() }).nullable(),\n ),\n getEventClipUrl: method(\n z.object({ deviceId: z.number(), eventId: z.string() }),\n z.string().nullable(),\n ),\n },\n} as const satisfies CapabilityDefinition\n\nexport type IEventsProvider = InferProvider<typeof eventsCapability>\nexport { EventItemSchema }\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { RecordingConfigSchema } from '../interfaces/recording-config.js'\n\nexport const RecordingStatusSchema = z.object({\n deviceId: z.number(),\n enabled: z.boolean(),\n activeMode: z.enum(['off', 'continuous']),\n nodeId: z.string(),\n storageBytes: z.number(),\n})\nexport type RecordingStatus = z.infer<typeof RecordingStatusSchema>\n\nexport const RecordingRangeSchema = z.object({\n profile: z.string(),\n startMs: z.number(),\n endMs: z.number(),\n})\nexport const RecordingAvailabilitySchema = z.object({\n deviceId: z.number(),\n ranges: z.array(RecordingRangeSchema),\n})\nexport type RecordingAvailability = z.infer<typeof RecordingAvailabilitySchema>\n\nexport const RecordingManifestSchema = z.object({\n deviceId: z.number(),\n /** Local filesystem path to the master playlist; null when no recording exists for the requested range. */\n localMasterPath: z.string().nullable(),\n /** HTTP(S) URL to the master playlist on the recording node's playback server\n * (the PRIMARY candidate); null when no recording / server. Carries the\n * scoped playback token in its path. */\n playbackUrl: z.string().nullable(),\n /**\n * Candidate master-playlist URLs the client tries in order (LAN first, then\n * remote — Tailscale/Cloudflare if the operator configured extra hosts), each\n * carrying the same scoped token. `playbackUrl` is the first entry. Empty when\n * there is no recording / server.\n */\n playbackEndpoints: z.array(z.string()),\n})\nexport type RecordingManifest = z.infer<typeof RecordingManifestSchema>\n\n/** Recording storage usage for one camera (bytes on disk across all its\n * profiles/subtrees/locations on this node). */\nexport const RecordingDeviceUsageSchema = z.object({\n deviceId: z.number(),\n usedBytes: z.number(),\n})\nexport type RecordingDeviceUsage = z.infer<typeof RecordingDeviceUsageSchema>\n\n/** Recording storage usage + capacity for one storage location. */\nexport const RecordingLocationUsageSchema = z.object({\n /** StorageLocation id; null for the legacy/degraded single-root fallback. */\n locationId: z.string().nullable(),\n /** Bytes of recordings stored on this location. */\n usedBytes: z.number(),\n /** Free bytes on the location's volume; null when capacity is unknown (remote). */\n availableBytes: z.number().nullable(),\n /** Total bytes of the location's volume; null when unknown. */\n totalBytes: z.number().nullable(),\n})\nexport type RecordingLocationUsage = z.infer<typeof RecordingLocationUsageSchema>\n\n/** Aggregate recordings storage usage for a node: global total + per-camera +\n * per-location used/available. Stat-based (accurate even for detached cameras),\n * computed on demand — not from the name-only playback index. */\nexport const RecordingStorageUsageSchema = z.object({\n nodeId: z.string(),\n totalUsedBytes: z.number(),\n devices: z.array(RecordingDeviceUsageSchema),\n locations: z.array(RecordingLocationUsageSchema),\n})\nexport type RecordingStorageUsage = z.infer<typeof RecordingStorageUsageSchema>\n\nexport const recordingCapability = {\n name: 'recording',\n scope: 'system',\n mode: 'singleton',\n exposesDeviceSettings: true,\n status: {\n schema: RecordingStatusSchema,\n kind: 'command-driven',\n },\n methods: {\n getAvailability: method(\n z.object({ deviceId: z.number(), fromMs: z.number(), toMs: z.number() }),\n RecordingAvailabilitySchema,\n { kind: 'query', auth: 'admin' },\n ),\n getPlaybackManifest: method(\n z.object({ deviceId: z.number(), fromMs: z.number(), toMs: z.number() }),\n RecordingManifestSchema,\n { kind: 'query', auth: 'admin' },\n ),\n getStorageUsage: method(\n z.object({}),\n RecordingStorageUsageSchema,\n { kind: 'query', auth: 'admin' },\n ),\n getDeviceConfig: method(\n z.object({ deviceId: z.number() }),\n RecordingConfigSchema,\n { kind: 'query', auth: 'admin' },\n ),\n setDeviceConfig: method(\n z.object({ deviceId: z.number(), config: RecordingConfigSchema }),\n RecordingConfigSchema,\n { kind: 'mutation', auth: 'admin' },\n ),\n /** Re-scan this device's footage from disk (stat sizes) and reseed the\n * index, then return the fresh status. */\n rescanStorage: method(\n z.object({ deviceId: z.number() }),\n RecordingStatusSchema,\n { kind: 'mutation', auth: 'admin' },\n ),\n /** Apply this device's retention policy to footage now; returns the oldest\n * surviving footage start (the retention floor) or null if no footage. */\n pruneFootage: method(\n z.object({ deviceId: z.number() }),\n z.object({\n floorMs: z.number().nullable(),\n deletedBuckets: z.number().int(),\n reclaimedBytes: z.number().int(),\n }),\n { kind: 'mutation', auth: 'admin' },\n ),\n },\n} as const satisfies CapabilityDefinition\n\nexport type IRecordingProvider = InferProvider<typeof recordingCapability>\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { CamProfileSchema } from './schemas/streaming-shared.js'\n\n/**\n * device-ops — device-scoped cap that unifies the per-IDevice operations\n * previously routed through the `.device-ops` Moleculer bridge service.\n *\n * Each worker that hosts live `IDevice` instances auto-registers a native\n * provider for this cap (per device) backed by its local\n * `DeviceRegistry`. Hub-side callers reach it transparently through\n * `ctx.fetchDevice(id).deviceOps.*` — the DeviceProxy injects\n * `deviceId` + `nodeId` and dispatches through the standard cap-router,\n * so there's no parallel bridge path anymore.\n *\n * The surface is intentionally small — every method corresponds to a\n * single action on the live `IDevice` (or `ICameraDevice` for\n * `getStreamSources`). Richer orchestration (enable/disable with\n * integration plumbing, bulk updates) stays in the `device-manager` cap;\n * `device-ops` is the per-device primitive the device-manager routes to.\n */\nconst StreamSourceEntrySchema = z.object({\n id: z.string(),\n label: z.string(),\n protocol: z.enum(['rtsp', 'rtmp', 'annexb', 'http-mjpeg', 'webrtc', 'custom']),\n url: z.string().optional(),\n resolution: z.object({ width: z.number(), height: z.number() }).optional(),\n fps: z.number().optional(),\n bitrate: z.number().optional(),\n codec: z.string().optional(),\n profileHint: CamProfileSchema.optional(),\n sdp: z.string().optional(),\n})\n\nconst ConfigEntrySchema = z.object({\n key: z.string(),\n value: z.unknown(),\n})\n\nexport const RawStateResultSchema = z.object({\n /** Originating provider id, e.g. 'homeassistant' | 'reolink' | 'hikvision'. */\n source: z.string(),\n /** Opaque, DISPLAY-SAFE upstream blob (no secrets/PII). */\n data: z.record(z.string(), z.unknown()),\n})\nexport type RawStateResult = z.infer<typeof RawStateResultSchema>\n\nexport const deviceOpsCapability = {\n name: 'device-ops',\n scope: 'device',\n // Device-native: a provider is auto-registered PER DEVICE in the worker\n // that hosts the live `IDevice` (see `buildDeviceOpsProvider`). The mount\n // MUST use `requireDeviceScoped` (→ `getNativeProvider(cap, deviceId)`) so\n // calls route to the owning runner; without this flag codegen falls back to\n // `getSingleton('device-ops')`, which returns null for a per-device cap and\n // makes every device-ops method unroutable for forked devices.\n deviceNative: true,\n mode: 'singleton',\n methods: {\n /**\n * Return stream sources for camera-like devices. Non-camera devices\n * return an empty array (the bridge did the same; preserved for compat).\n */\n getStreamSources: method(\n z.object({ deviceId: z.number() }),\n z.array(StreamSourceEntrySchema),\n ),\n\n /**\n * Return the device's config entries (key + current value). Used by\n * the device-manager aggregator when reading the driver's schema+values.\n */\n getConfigEntries: method(\n z.object({ deviceId: z.number() }),\n z.array(ConfigEntrySchema),\n ),\n\n /**\n * Bulk-apply a config patch via `IDevice.config.setAll`. Covers the\n * updateConfig / setStreamProfileMap / enable-as-config paths from\n * the old bridge.\n */\n setConfig: method(\n z.object({\n deviceId: z.number(),\n values: z.record(z.string(), z.unknown()),\n }),\n z.void(),\n { kind: 'mutation' },\n ),\n\n /**\n * Invoke a device custom action on a forked/remote device (the\n * cross-process transport for `IDevice.runDeviceAction`). Mirrors\n * `setConfig` — the device-manager calls this when the device is not\n * hub-local.\n */\n runAction: method(\n z.object({\n deviceId: z.number(),\n action: z.string().min(1),\n input: z.unknown(),\n }),\n z.unknown(),\n { kind: 'mutation' },\n ),\n\n /**\n * Invoke `IDevice.removeDevice()` so the driver can release resources\n * (close sockets, stop background tasks, …). The device-manager still\n * performs its own persistence cleanup before/after this call.\n */\n removeDevice: method(\n z.object({ deviceId: z.number() }),\n z.void(),\n { kind: 'mutation' },\n ),\n\n /**\n * Build the ConfigUISchema (FormBuilder input shape) from the device's\n * Zod config schema. Runs on the worker that owns the IDevice so the\n * Zod types stay local (they're function references, not\n * serializable). Returns a fully JSON-serializable schema with\n * sections/fields the admin UI renders directly.\n *\n * Needed because the hub-side `device-manager.getSettingsSchema`\n * couldn't reach forked-worker devices — it had no registry entry\n * and no cross-process lookup, so the UI silently rendered an empty\n * settings panel for every worker-owned device.\n *\n * Returns `null` when the device isn't found on this worker.\n */\n getSettingsSchema: method(\n z.object({ deviceId: z.number() }),\n z.unknown().nullable(),\n ),\n\n /**\n * Opt-in: return the device's RAW upstream state (the provider's\n * cached values) as a display-safe `{ source, data }` blob. Returns\n * `null` when the device exposes no raw state — the State panel hides\n * its Raw toggle in that case. One-shot (read the provider's existing\n * cache; no upstream round-trip).\n */\n getRawState: method(\n z.object({ deviceId: z.number() }),\n RawStateResultSchema.nullable(),\n { auth: 'protected' },\n ),\n },\n} as const satisfies CapabilityDefinition\n\nexport type IDeviceOpsProvider = InferProvider<typeof deviceOpsCapability>\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\n\n/**\n * camera-credentials — device-scoped cap exposing the camera's network\n * + auth surface in a vendor-neutral shape.\n *\n * Why it exists: cross-vendor wrappers (the planned ONVIF generic addon\n * for PTZ / intercom / events; future homekit / mqtt bridges) need the\n * camera's IP + port + creds without each wrapper re-implementing\n * vendor-specific config-blob extraction. With this cap, every camera\n * provider returns a uniform CameraCredentials and consumers stay\n * vendor-agnostic.\n *\n * Implementations:\n * - Each camera-providing addon registers this cap natively per\n * device (Reolink, Hikvision, RTSP, Frigate, ONVIF self).\n * - Returns a snapshot from the persisted device config blob — no\n * extra round-trip to the camera, no probing.\n * - The cap is admin-only (`auth: 'admin'`) — credentials must not\n * leak through user-scoped paths.\n *\n * Sensitive data handling:\n * - getCredentials returns the full snapshot to admin callers only.\n * - Wrappers are expected to use the value to construct a per-call\n * client and NOT to log / event-bus-emit the password field.\n * - The cap status payload (mirrored to runtime-state) carries\n * non-sensitive metadata only — host + ports + protocol hints. The\n * password / username live on `getCredentials` exclusively.\n *\n * See `docs/onvif-generic-addon-plan.md` for the consuming wrapper\n * design.\n */\n\nexport const CameraCredentialsSchema = z.object({\n /** Camera IP or hostname (no scheme). */\n host: z.string(),\n /** Primary protocol port (varies per vendor: Baichuan 9000, ISAPI 80/443, RTSP 554). */\n port: z.number().int().positive().optional(),\n /** ONVIF service port if known by the provider. */\n onvifPort: z.number().int().positive().optional(),\n /** RTSP service port if known. */\n rtspPort: z.number().int().positive().optional(),\n /** HTTP(S) flag for the primary protocol port. */\n https: z.boolean().optional(),\n /** Login username. */\n username: z.string().optional(),\n /** Login password. CONSUMERS MUST NOT log or event-bus this value. */\n password: z.string().optional(),\n /** ONVIF profile hint advertised by the camera (`T`, `Q`, `G`, `S`). */\n onvifProfile: z.string().optional(),\n})\n\nexport type CameraCredentials = z.infer<typeof CameraCredentialsSchema>\n\n/**\n * Non-sensitive camera-credentials status — host + ports + protocol\n * hints only. Mirrors what shows up in the bindings UI / device\n * aggregate. The full credentials (with password) are exposed only via\n * `getCredentials` to admin callers.\n */\nexport const CameraCredentialsStatusSchema = z.object({\n host: z.string(),\n port: z.number().int().positive().nullable(),\n onvifPort: z.number().int().positive().nullable(),\n rtspPort: z.number().int().positive().nullable(),\n https: z.boolean().nullable(),\n hasUsername: z.boolean(),\n hasPassword: z.boolean(),\n onvifProfile: z.string().nullable(),\n})\n\nexport type CameraCredentialsStatus = z.infer<typeof CameraCredentialsStatusSchema>\n\nexport const cameraCredentialsCapability = {\n name: 'camera-credentials',\n scope: 'device',\n deviceNative: true,\n mode: 'singleton',\n deviceTypes: [DeviceType.Camera],\n methods: {\n /**\n * Return the camera's full credential bundle for admin consumers.\n * Each provider implementation returns a snapshot of its persisted\n * config — no I/O to the camera. Returns null when the device is\n * not owned by this addon (deviceId mismatch).\n */\n getCredentials: method(\n z.object({ deviceId: z.number() }),\n CameraCredentialsSchema.nullable(),\n { kind: 'query', auth: 'admin' },\n ),\n },\n status: {\n schema: CameraCredentialsStatusSchema,\n kind: 'command-driven',\n },\n} as const satisfies CapabilityDefinition\n\nexport type ICameraCredentialsProvider = InferProvider<typeof cameraCredentialsCapability>\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\n\n/**\n * reboot — device-scoped capability for \"soft\" device reboots (firmware\n * reboot via vendor protocol; cameras, NVRs, doorbells). Surfaces a\n * single mutation so the UI can offer a confirm-and-reboot button for\n * any device whose driver advertises `DeviceFeature.Rebootable`.\n *\n * Implementation contract: the driver SHOULD return only after the\n * remote acknowledges the request (camera will go offline shortly\n * after). Wrappers in the addon should NOT block on the device coming\n * back online — operators read the device-online indicator for that.\n *\n * Errors propagate verbatim: a 401 from the camera surfaces as a tRPC\n * error to the UI, which renders it next to the button.\n */\nexport const rebootCapability = {\n name: 'reboot',\n scope: 'device',\n deviceNative: true,\n mode: 'singleton',\n deviceTypes: [DeviceType.Camera, DeviceType.Sensor, DeviceType.Switch],\n methods: {\n reboot: method(\n z.object({ deviceId: z.number().int().nonnegative() }),\n z.object({ success: z.literal(true) }),\n { kind: 'mutation', auth: 'admin' },\n ),\n },\n} as const satisfies CapabilityDefinition\n\nexport type IRebootProvider = InferProvider<typeof rebootCapability>\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\n\n/**\n * button — device-scoped capability for HA `button.*` / `input_button.*`\n * fire-only actuators. A button entity has no readable state — pressing it\n * triggers an action on the HA side. There is no `status` / `runtimeState`:\n * nothing to poll, nothing to subscribe to.\n *\n * Usage: the admin UI renders a single \"Press\" affordance. The provider calls\n * the HA `button.press` (or `input_button.press`) service. The domain is\n * derived from the entity_id prefix at runtime.\n */\nexport const buttonCapability = {\n name: 'button',\n scope: 'device',\n deviceNative: true,\n mode: 'singleton',\n deviceTypes: [DeviceType.Button],\n methods: {\n press: method(\n z.object({ deviceId: z.number().int().nonnegative() }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n },\n} as const satisfies CapabilityDefinition\n\nexport type IButtonProvider = InferProvider<typeof buttonCapability>\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\n\n/**\n * Generic on-screen-display (video overlay) cap. Each camera exposes\n * a firmware-defined list of overlays (channel name, timestamp,\n * watermark, logo, …); the cap models them as a homogeneous array of\n * descriptors so the admin UI can render them with zero per-firmware\n * code.\n */\n\nexport const OsdOverlayKindEnum = z.enum(['text', 'timestamp', 'watermark'])\nexport type OsdOverlayKind = z.infer<typeof OsdOverlayKindEnum>\n\nexport const OsdPositionEnum = z.enum([\n 'top-left', 'top-center', 'top-right',\n 'bottom-left', 'bottom-center', 'bottom-right',\n 'custom',\n])\nexport type OsdPosition = z.infer<typeof OsdPositionEnum>\n\nexport const OsdOverlaySchema = z.object({\n /** Stable driver-assigned id. Reolink uses `'channel'`, `'time'`, `'watermark'`. */\n id: z.string(),\n kind: OsdOverlayKindEnum,\n enabled: z.boolean(),\n /** Active text (text/watermark). Undefined for 'timestamp' (firmware-generated). */\n text: z.string().optional(),\n position: OsdPositionEnum.optional(),\n /**\n * Positions the firmware accepts for this specific overlay. Populated\n * by the driver at register time. Empty array → positioning not\n * configurable; the UI hides the position field.\n */\n availablePositions: z.array(OsdPositionEnum).readonly(),\n /** Firmware does not allow editing the `text` field (e.g. timestamp). */\n readOnly: z.boolean().optional(),\n})\n\nexport type OsdOverlay = z.infer<typeof OsdOverlaySchema>\n\nexport const OsdStatusSchema = z.object({\n overlays: z.array(OsdOverlaySchema).readonly(),\n})\n\nexport type OsdStatus = z.infer<typeof OsdStatusSchema>\n\nconst OsdOverlayPatchSchema = z.object({\n enabled: z.boolean().optional(),\n text: z.string().optional(),\n position: OsdPositionEnum.optional(),\n}).partial()\n\nexport const osdCapability = {\n name: 'osd',\n scope: 'device',\n deviceNative: true,\n mode: 'singleton',\n deviceTypes: [DeviceType.Camera],\n methods: {\n /**\n * Patch a single overlay by id. Provider handles read-modify-write\n * against firmware APIs that require the full object (Reolink\n * `SetOsd`). Omitted patch keys are preserved. Successful\n * completion triggers `onStatusChanged`.\n */\n setOverlay: method(\n z.object({\n deviceId: z.number(),\n overlayId: z.string(),\n patch: OsdOverlayPatchSchema,\n }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n },\n events: {\n onStatusChanged: { data: z.object({\n deviceId: z.number(),\n status: OsdStatusSchema,\n })},\n },\n status: {\n schema: OsdStatusSchema,\n kind: 'command-driven',\n },\n settings: {\n bindings: [{\n kind: 'array',\n statusPath: 'overlays',\n idField: 'id',\n method: 'setOverlay',\n idArg: 'overlayId',\n patchArg: 'patch',\n sectionId: 'osd',\n sectionTitle: 'Video overlays',\n itemFields: {\n enabled: {\n label: (o) => `${String(o.id)} enabled`,\n kind: 'boolean',\n },\n text: {\n label: (o) => `${String(o.id)} text`,\n kind: 'text',\n when: (o) => o.kind !== 'timestamp' && !o.readOnly,\n },\n position: {\n label: (o) => `${String(o.id)} position`,\n kind: 'select',\n options: (o) => (o.availablePositions as readonly string[] | undefined) ?? [],\n when: (o) => Array.isArray(o.availablePositions) && o.availablePositions.length > 0,\n },\n },\n }],\n },\n} as const satisfies CapabilityDefinition\n\nexport type IOsdProvider = InferProvider<typeof osdCapability>\nexport { OsdOverlayPatchSchema }\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\n\n/**\n * List of accessory children linked to a parent device. The cap surfaces\n * the grouping and the per-child UI-visibility flag — the single source\n * of truth for what an accessory IS remains the child device itself\n * (resolved via `device-manager.getDevice` from the listed numeric ids).\n *\n * Two parallel arrays:\n * - `childDeviceIds` — every accessory child the parent recognises\n * - `hiddenChildIds` — subset that the operator chose to hide from\n * the parent's UI surface (panels / detail page / grid). The hidden\n * children remain registered and continue to receive state updates;\n * they're omitted only from the parent's UI accessories view.\n *\n * Use cases:\n * - Camera parents hiding seldom-used accessories (e.g. a chime that\n * was provisioned but isn't connected to anything).\n * - HA-integration parents hiding entity-children the user doesn't\n * care about (an \"Aqara plug\" exposes one switch + 3 sensors —\n * the operator may want only the switch visible).\n *\n * Toggling visibility is the parent provider's responsibility — it\n * implements `setChildHidden` and persists the set so reboots survive.\n */\nexport const AccessoriesStatusSchema = z.object({\n /** All accessory children of the parent. */\n childDeviceIds: z.array(z.number()).readonly(),\n /** Subset of `childDeviceIds` the operator hid from the UI. The order\n * is irrelevant; the array is treated as a set by consumers. */\n hiddenChildIds: z.array(z.number()).readonly(),\n})\n\nexport type AccessoriesStatus = z.infer<typeof AccessoriesStatusSchema>\n\nexport const accessoriesCapability = {\n name: 'accessories',\n scope: 'device',\n deviceNative: true,\n mode: 'singleton',\n // Cameras + Hubs are the historical consumers; the HA integration\n // landed in Phase E adds Switch / Light / Sensor / Thermostat / Cover\n // / Lock / Fan / MediaPlayer / AlarmPanel / Generic as parent types\n // for adopted HA devices whose entity-children sit under accessories.\n deviceTypes: [\n DeviceType.Camera,\n DeviceType.Hub,\n DeviceType.Switch,\n DeviceType.Light,\n DeviceType.Sensor,\n DeviceType.Thermostat,\n DeviceType.Cover,\n DeviceType.Lock,\n DeviceType.Fan,\n DeviceType.MediaPlayer,\n DeviceType.AlarmPanel,\n DeviceType.Generic,\n ],\n methods: {\n /**\n * Toggle the UI-visibility of a single accessory child. Hidden\n * children stay registered and continue to receive state updates;\n * they're omitted only from the parent's UI accessories panel.\n *\n * Idempotent — hiding an already-hidden child or unhiding a\n * non-hidden child is a no-op. Providers that don't support\n * per-child visibility may implement this as a no-op (the UI hide\n * toggle gracefully degrades).\n */\n setChildHidden: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n childDeviceId: z.number().int().nonnegative(),\n hidden: z.boolean(),\n }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n },\n events: {\n /**\n * Emitted when a child device is created, removed, or its parent\n * assignment changes. Payload carries the fresh list and the\n * hidden subset.\n */\n onAccessoriesChanged: { data: z.object({\n deviceId: z.number(),\n childDeviceIds: z.array(z.number()).readonly(),\n hiddenChildIds: z.array(z.number()).readonly(),\n })},\n /**\n * Emitted when the operator toggles a child's UI-visibility.\n * Subscribers (admin UI accessories panel) re-render off this\n * signal without re-fetching the full status block.\n */\n onChildVisibilityChanged: { data: z.object({\n deviceId: z.number(),\n childDeviceId: z.number(),\n hidden: z.boolean(),\n })},\n },\n status: {\n schema: AccessoriesStatusSchema,\n kind: 'command-driven',\n },\n} as const satisfies CapabilityDefinition\n\nexport type IAccessoriesProvider = InferProvider<typeof accessoriesCapability>\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\n\n/**\n * Two-way audio / talk-back cap. Clients open a WebRTC audio-only\n * session (server-initiated offer pattern, identical to the main\n * video WebRTC flow) and the browser captures the mic; the server\n * receives Opus RTP via werift, decodes through ffmpeg, re-encodes\n * to the firmware's expected codec (Reolink: IMA ADPCM), and pipes\n * it onto the camera's dedicated talk channel.\n *\n * All audio transcoding happens server-side — clients don't need to\n * know the camera's wire format. The `ability` cached in `status`\n * exposes the firmware's codec/sampleRate only for display/debug;\n * the client never has to act on those values.\n */\nexport const IntercomAbilitySchema = z.object({\n /** Codecs accepted by firmware, in preference order. Driver-authored strings. */\n codecs: z.array(z.string()),\n /** Sample rate (Hz) the firmware expects. Reolink typical: 16000. */\n sampleRate: z.number(),\n duplex: z.enum(['half', 'full']),\n /** Max in-flight audio backlog before drop (ms). Server uses this to bound latency. */\n maxBacklogMs: z.number(),\n})\n\nexport type IntercomAbility = z.infer<typeof IntercomAbilitySchema>\n\nexport const IntercomStatusSchema = z.object({\n /** True while a talk session is open. */\n talking: z.boolean(),\n /** Ms epoch of the most recent session start. Null if never opened. */\n lastSessionAt: z.number().nullable(),\n /** Firmware ability cached at first session creation. Null until probed. */\n ability: IntercomAbilitySchema.nullable(),\n})\n\nexport type IntercomStatus = z.infer<typeof IntercomStatusSchema>\n\n/**\n * Wire codec of a `pushTalkAudio` payload. The cap is codec-agnostic: the\n * caller declares (or omits) the wire format; the provider decides whether\n * to passthrough to the camera's native channel, transcode via the\n * `audio-codec` cap, or reject the call.\n *\n * - `opus`: encoded Opus access unit (one frame per call). `sampleRate`\n * tags the encoder rate (HAP-style: 48000 for iOS, 16000/24000 for LTE).\n * - `s16le`: raw little-endian signed 16-bit PCM, mono unless `channels`\n * says otherwise. `sampleRate` is REQUIRED.\n * - `g711ulaw` / `g711alaw`: 8 kHz mono G.711 (µ-law / A-law). `sampleRate`\n * is implied 8000 — set explicitly for clarity in logs.\n *\n * When `codec` is omitted the provider falls back to its native default\n * (the format the camera-side encoder consumes natively). That default\n * is \"s16le @ provider-native sampleRate, mono\" — Hikvision: 8000 Hz,\n * Reolink: per-talk-session rate (16000 Hz typical).\n */\nexport const TalkAudioCodecSchema = z.enum([\n 'opus',\n 's16le',\n 'g711ulaw',\n 'g711alaw',\n])\n\nexport type TalkAudioCodec = z.infer<typeof TalkAudioCodecSchema>\n\nexport const intercomCapability = {\n name: 'intercom',\n scope: 'device',\n deviceNative: true,\n mode: 'singleton',\n deviceTypes: [DeviceType.Camera],\n methods: {\n /**\n * Open a server-side WebRTC audio-only session. Returns an SDP\n * offer with a single sendonly audio m-line the client answers\n * (client → server direction). The server wakes battery cams\n * transparently before opening the upstream talk channel.\n */\n startSession: method(\n z.object({ deviceId: z.number() }),\n z.object({ sessionId: z.string(), sdpOffer: z.string() }),\n { kind: 'mutation', auth: 'admin' },\n ),\n handleAnswer: method(\n z.object({\n deviceId: z.number(),\n sessionId: z.string(),\n sdpAnswer: z.string(),\n }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n /** Close explicitly. Server also auto-closes on 30s idle. */\n stopSession: method(\n z.object({ deviceId: z.number(), sessionId: z.string() }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n /**\n * Open a raw-PCM talk session (no WebRTC SDP plumbing). Used by\n * non-WebRTC consumers (HomeKit export, Alexa raw audio, test\n * harnesses) that already have decoded PCM frames and just need a\n * direct path onto the camera's talk channel. Mutually exclusive\n * with `startSession` (an active WebRTC session must be stopped\n * before a raw-PCM session can be opened on the same device, and\n * vice versa).\n */\n startTalkSession: method(\n z.object({ deviceId: z.number() }),\n z.object({ sessionId: z.string() }),\n { kind: 'mutation', auth: 'admin' },\n ),\n /**\n * Push one chunk of talk-back audio onto the active talk session.\n * The cap is codec-agnostic: the caller declares (or omits) the\n * wire format via `codec`; the provider decides between passthrough\n * (when the wire codec matches the camera's native talk channel),\n * transcoding via the `audio-codec` cap, or rejecting the call.\n *\n * Callers do NOT need to know the camera's wire format or sample\n * rate — that information lives entirely inside the provider.\n *\n * Sequence numbers MUST be monotonic per talk session; older frames\n * arriving after newer ones are dropped to avoid smearing the\n * downstream encoder state (G.711 is stateless but IMA ADPCM's\n * predictor would corrupt with re-ordering).\n */\n pushTalkAudio: method(\n z.object({\n deviceId: z.number(),\n /** Audio bytes for ONE frame, base64-encoded so the payload\n * survives tRPC JSON serialization. */\n audioBase64: z.string(),\n /** Wire codec of the payload. Omit to let the provider default\n * to its native expected format (s16le @ provider-native rate,\n * mono). See {@link TalkAudioCodecSchema} for the supported set. */\n codec: TalkAudioCodecSchema.optional(),\n /** Sample rate (Hz). REQUIRED for `s16le`; advisory for\n * `opus` (encoder clock); ignored for `g711*` (implied 8000). */\n sampleRate: z.number().int().positive().optional(),\n /** Channel count. Default 1. */\n channels: z.number().int().positive().optional(),\n /** Sequence number for ordering / dropping out-of-order frames. */\n sequenceNumber: z.number().int(),\n }),\n z.object({ accepted: z.boolean() }),\n { kind: 'mutation', auth: 'admin' },\n ),\n /** Close the raw-PCM talk session. Idempotent. */\n endTalkSession: method(\n z.object({ deviceId: z.number() }),\n z.void(),\n { kind: 'mutation', auth: 'admin' },\n ),\n },\n events: {\n onStatusChanged: { data: z.object({\n deviceId: z.number(),\n status: IntercomStatusSchema,\n })},\n },\n status: {\n schema: IntercomStatusSchema,\n kind: 'command-driven',\n },\n} as const satisfies CapabilityDefinition\n\nexport type IIntercomProvider = InferProvider<typeof intercomCapability>\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferNativeProvider } from './capability-definition.js'\nimport { DeviceType } from '../device/device-type.js'\nimport { CamStreamKindSchema, CamStreamResolutionSchema } from './schemas/streaming-shared.js'\n\n/**\n * One publishable camera stream as its OWNING PROVIDER describes it — the same\n * payload the (legacy) push `streamBroker.publishCameraStream` carried, minus\n * `deviceId`.\n *\n * The stream-broker PULLS this catalog per camera (on start, on a configurable\n * reconcile poll, and on device / stream-params events) to (re)build its\n * cam-stream registry, instead of relying on providers to push. Pull is\n * authoritative (RPC); the poll is the backstop for any missed event. This\n * makes the broker self-heal after a restart — it re-derives the full catalog\n * from the providers rather than waiting to be re-fed.\n *\n * `url` is the dial source where the provider can resolve it synchronously\n * (rtsp / rtmp / http). For lazy sources (Reolink rfc4571) it carries the\n * `lazy:rfc4571:` sentinel; the real URL is still materialised at DIAL time via\n * the broker's `onRequestStreamSourceRefresh` round-trip — unchanged by the\n * pull model. `push-annexb` sources carry no URL (the provider pushes frames).\n */\nexport const CamStreamDescriptorSchema = z.object({\n camStreamId: z.string().min(1),\n kind: CamStreamKindSchema,\n url: z.string().optional(),\n codec: z.string().optional(),\n resolution: CamStreamResolutionSchema.optional(),\n fps: z.number().positive().optional(),\n label: z.string().optional(),\n /** Device-level features (e.g. `battery-operated`) — drives broker policy. */\n deviceFeatures: z.array(z.string()).optional(),\n /** Eligible for automatic profile assignment. Absent = `true`. */\n autoEligible: z.boolean().optional(),\n /** Transport-specific opaque metadata (e.g. rfc4571 SDP). */\n metadata: z.record(z.string(), z.unknown()).optional(),\n})\nexport type CamStreamDescriptor = z.infer<typeof CamStreamDescriptorSchema>\n\n/**\n * `stream-catalog` — device-scoped, provider-implemented. The pull counterpart\n * of the removed `publishCameraStream` push: a camera provider returns the full\n * set of stream descriptors it can offer for the device, synchronously, so the\n * broker can reconcile its registry against the authoritative provider state.\n */\nexport const streamCatalogCapability = {\n name: 'stream-catalog',\n scope: 'device',\n deviceNative: true,\n mode: 'singleton',\n deviceTypes: [DeviceType.Camera],\n methods: {\n getCatalog: method(\n z.object({ deviceId: z.number().int().nonnegative() }),\n z.array(CamStreamDescriptorSchema).readonly(),\n ),\n },\n} as const satisfies CapabilityDefinition\n\nexport type IStreamCatalogProvider = InferNativeProvider<typeof streamCatalogCapability>\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\nimport { MODEL_FORMATS } from '../types/models.js'\n\nconst ModelFormatSchema = z.enum(MODEL_FORMATS)\n\nconst HwAccelBackendInputSchema = z.enum([\n 'videotoolbox', 'cuda', 'nvdec', 'vaapi', 'qsv',\n 'd3d11va', 'dxva2', 'amf', 'vdpau', 'drm',\n 'coreml', 'tensorrt', 'openvino', 'directml', 'webgpu',\n 'none',\n]).nullable().optional()\n\nconst HwAccelResolutionSchema = z.object({\n preferred: z.array(z.string()).readonly(),\n})\n\nconst HardwareEncoderIdSchema = z.enum([\n 'h264_videotoolbox',\n 'hevc_videotoolbox',\n 'h264_vaapi',\n 'hevc_vaapi',\n 'h264_nvenc',\n 'hevc_nvenc',\n 'h264_qsv',\n 'hevc_qsv',\n 'h264_amf',\n 'hevc_amf',\n 'libx264',\n 'libx265',\n])\nexport type HardwareEncoderId = z.infer<typeof HardwareEncoderIdSchema>\n\nconst HardwareEncoderProbeSchema = z.object({\n encoder: HardwareEncoderIdSchema,\n codec: z.enum(['H264', 'H265']),\n family: z.enum(['videotoolbox', 'vaapi', 'nvenc', 'qsv', 'amf', 'software']),\n available: z.boolean(),\n reason: z.string().optional(),\n})\nexport type HardwareEncoderProbe = z.infer<typeof HardwareEncoderProbeSchema>\n\nconst HardwareEncodersSchema = z.object({\n encoders: z.array(HardwareEncoderProbeSchema).readonly(),\n defaultH264: HardwareEncoderIdSchema,\n defaultH265: HardwareEncoderIdSchema,\n probedAt: z.number(),\n})\nexport type HardwareEncoders = z.infer<typeof HardwareEncodersSchema>\n\n/**\n * Decode-side companion to {@link HardwareEncodersSchema}: the `-hwaccel`\n * methods the configured ffmpeg binary actually supports (parsed from\n * `ffmpeg -hwaccels`). Used to gate decode-hwaccel attempts so the transcode\n * egress never spends a spawn on a backend this build cannot offer. Per-stream\n * decode fragility (e.g. VideoToolbox HEVC) is still handled by the egress's\n * software fallback — this only filters out wholly-unsupported backends.\n */\nconst HardwareDecodeAccelsSchema = z.object({\n methods: z.array(z.string()).readonly(),\n probedAt: z.number(),\n})\nexport type HardwareDecodeAccels = z.infer<typeof HardwareDecodeAccelsSchema>\n\nconst HardwarePlatformSchema = z.enum(['darwin', 'linux', 'win32'])\nconst HardwareArchSchema = z.enum(['arm64', 'x64'])\n\nconst GpuInfoSchema = z.object({\n type: z.enum(['nvidia', 'amd', 'intel', 'apple']),\n name: z.string(),\n memoryMB: z.number().optional(),\n})\n\nconst NpuInfoSchema = z.object({\n type: z.enum(['apple-ane', 'intel-npu']),\n})\n\nconst HardwareInfoSchema = z.object({\n platform: HardwarePlatformSchema,\n arch: HardwareArchSchema,\n cpuModel: z.string(),\n cpuCores: z.number(),\n totalRAM_MB: z.number(),\n availableRAM_MB: z.number(),\n gpu: GpuInfoSchema.nullable(),\n npu: NpuInfoSchema.nullable(),\n})\n\nconst PlatformScoreSchema = z.object({\n runtime: z.enum(['node', 'python']),\n backend: z.string(),\n format: z.enum(['onnx', 'coreml', 'openvino']),\n score: z.number(),\n reason: z.string(),\n available: z.boolean(),\n})\n\nconst PlatformCapabilitiesSchema = z.object({\n hardware: HardwareInfoSchema,\n scores: z.array(PlatformScoreSchema).readonly(),\n bestScore: PlatformScoreSchema,\n pythonPath: z.string().nullable(),\n})\n\nconst ModelRequirementSchema = z.object({\n modelId: z.string(),\n name: z.string(),\n minRAM_MB: z.number(),\n accuracyScore: z.number(),\n formats: z.array(z.string()).readonly(),\n})\n\nconst ResolvedInferenceConfigSchema = z.object({\n modelId: z.string(),\n runtime: z.enum(['node', 'python']),\n backend: z.string(),\n format: ModelFormatSchema,\n reason: z.string(),\n})\n\nexport const platformProbeCapability = {\n name: 'platform-probe',\n scope: 'system',\n mode: 'singleton',\n methods: {\n getCapabilities: method(z.void(), PlatformCapabilitiesSchema),\n getHardware: method(z.void(), HardwareInfoSchema),\n resolveInferenceConfig: method(\n z.object({ requirements: z.array(ModelRequirementSchema).readonly() }),\n ResolvedInferenceConfigSchema,\n ),\n resolveHwAccel: method(\n z.object({ prefer: HwAccelBackendInputSchema, nodeId: z.string().optional() }),\n HwAccelResolutionSchema,\n ),\n /**\n * Hardware-encoder probe — see Task #185. Cached after first call.\n */\n getHardwareEncoders: method(z.void(), HardwareEncodersSchema),\n refreshHardwareEncoders: method(\n z.void(),\n HardwareEncodersSchema,\n { kind: 'mutation', auth: 'admin' },\n ),\n /**\n * Decode-side hw-accel probe — the `-hwaccel` methods the configured ffmpeg\n * binary supports (via `ffmpeg -hwaccels`). Cached after first call.\n */\n getHardwareDecodeAccels: method(z.void(), HardwareDecodeAccelsSchema),\n refreshHardwareDecodeAccels: method(\n z.void(),\n HardwareDecodeAccelsSchema,\n { kind: 'mutation', auth: 'admin' },\n ),\n },\n} as const satisfies CapabilityDefinition\n\nexport type IPlatformProbeProvider = InferProvider<typeof platformProbeCapability>\n","/**\n * local-network — hub-only singleton.\n *\n * Enumerates the host's network interfaces and ranks them so that:\n *\n * • Addons that need a \"where do we listen / point a tunnel at\" answer\n * (cloudflare-tunnel, ngrok, RTSP restream, cluster join URL, TLS\n * cert SAN) consume `getPreferred()` instead of hard-coding\n * `localhost`. Critical for docker-sidecar setups where the addon\n * process needs the container's eth0 (not 127.0.0.1).\n *\n * • The SDK (mobile / web client) consumes `getConnectionEndpoints()`\n * to receive an ordered list of candidate base URLs it should race\n * on connect — LAN IPv4 first (lowest latency when on same network),\n * then public hostname (if a tunnel is up), then IPv6. The SDK can\n * race them with short timeouts and stick with the winner for the\n * session.\n *\n * Why hub-only: agents are not directly addressable by the operator's\n * clients — they reverse-connect to the hub. Exposing their interfaces\n * via the same surface would leak internal topology with no upside.\n *\n * Implementation in `@camstack/core/builtins/local-network/`.\n */\nimport { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\n\n/** Coarse classification derived from the interface name + IP range. */\nconst InterfaceKindEnum = z.enum([\n 'lan', // wired ethernet (en0, eth0, ...)\n 'wifi', // wireless (en1, wlan*, ...)\n 'docker', // docker0 / br-* / veth*\n 'vpn', // tun*, utun*, wg*, tap*\n 'loopback', // lo, lo0\n 'other', // anything we can't classify confidently\n])\n\nconst LocalInterfaceSchema = z.object({\n /** Interface name as reported by the OS (e.g. `en0`, `eth0`, `lo0`). */\n name: z.string(),\n family: z.enum(['IPv4', 'IPv6']),\n address: z.string(),\n /** CIDR shorthand (e.g. `192.168.1.10/24`). Empty when OS doesn't expose. */\n cidr: z.string(),\n /** OS netmask. Stable across calls so the SDK can hash on it. */\n netmask: z.string(),\n /** True for `127.0.0.1`/`::1`. Returned for completeness but never preferred. */\n internal: z.boolean(),\n /** Hardware MAC (empty for loopback / virtual interfaces). */\n mac: z.string(),\n /** Derived classification — see `InterfaceKindEnum`. */\n kind: InterfaceKindEnum,\n /**\n * `true` for the auto-selected outbound interface. Exactly zero or\n * one entry has this set per call; the SDK picks this one for the\n * first connection attempt.\n */\n preferred: z.boolean(),\n /**\n * Heuristic flag: `true` when the address looks usable for clients\n * (RFC 1918 / public IPv4, IPv6 ULA / GUA), `false` for link-local\n * / loopback / multicast / docker / vpn / unknown ranges. Same\n * heuristic that drives `autoSeedAllowlist`.\n */\n plausible: z.boolean(),\n /**\n * Human-readable rationale for non-plausible entries (e.g. \"IPv6\n * link-local — only reachable on the same link\"). Empty string for\n * plausible entries. The UI surfaces this verbatim as the tooltip\n * on the \"Unlikely usable\" badge so the backend stays the single\n * source of truth — front-end consumers don't re-derive the reason.\n */\n plausibleReason: z.string(),\n})\n\nconst ListResultSchema = z.object({\n interfaces: z.array(LocalInterfaceSchema).readonly(),\n /** Wall-clock timestamp at which the snapshot was probed. */\n probedAt: z.number(),\n})\n\nconst PreferredSchema = LocalInterfaceSchema.nullable()\n\n/**\n * Candidate base URL for the SDK to race on connect. Order matters —\n * the SDK should attempt these top-to-bottom with a short per-candidate\n * timeout (e.g. 1500ms) and cache the winner for the session.\n */\nconst ConnectionEndpointSchema = z.object({\n /** Operator-facing label (e.g. \"LAN — en0\", \"Public tunnel\"). */\n label: z.string(),\n /** Fully-formed base URL with scheme + host + port. */\n baseUrl: z.string(),\n /** Network-level hint for the SDK — picks a small icon, sorts within\n * a tier. Coarse categorisation (LAN vs public vs loopback). */\n kind: z.enum([\n 'lan-ipv4', // private RFC1918 / link-local IPv4\n 'lan-ipv6', // private IPv6\n 'public', // tunnel / external FQDN\n 'loopback', // 127.0.0.1 — last-resort fallback\n ]),\n /**\n * Originating-interface kind — `lan`/`wifi`/`docker`/`vpn`/`other`/\n * `loopback`/`public`. Lets the UI render an accurate badge (e.g. a\n * VPN address gets a \"VPN\" tag instead of being lumped under\n * \"lan-ipv4\"). `'public'` for the tunnel hostname.\n */\n interfaceKind: z.enum(['lan', 'wifi', 'docker', 'vpn', 'other', 'loopback', 'public']),\n /**\n * Mirrors `LocalInterface.plausible` — false for endpoints derived\n * from non-plausible interfaces (VPN, docker, link-local, …). The\n * UI uses it to mark \"Unlikely usable\" without re-deriving from\n * the address shape.\n */\n plausible: z.boolean(),\n /** Same as `LocalInterface.plausibleReason` — empty when plausible. */\n plausibleReason: z.string(),\n /**\n * Suggested priority for racing — lower = try first. Stable across\n * calls so the client can sort even if the cap returns a new\n * ordering between polls.\n */\n priority: z.number(),\n})\n\nconst GetConnectionEndpointsResultSchema = z.object({\n endpoints: z.array(ConnectionEndpointSchema).readonly(),\n})\n\nconst AllowedAddressesSchema = z.object({\n /**\n * Allowlist of interface addresses operators have explicitly opted\n * into for the connection-endpoint race. Empty array = \"auto\" — every\n * non-loopback / non-link-local interface participates. Set by the\n * Network Addresses admin page and persisted by the addon.\n */\n addresses: z.array(z.string()).readonly(),\n})\n\nexport const localNetworkCapability = {\n name: 'local-network',\n scope: 'system',\n mode: 'singleton',\n methods: {\n /** Return the current interface snapshot. */\n list: method(z.void(), ListResultSchema),\n\n /**\n * Auto-selected outbound interface. Heuristic:\n * 1. Skip internal / link-local / 169.254.*.\n * 2. Prefer LAN/wifi (real Ethernet) over docker/vpn.\n * 3. IPv4 wins over IPv6 (compat with legacy consumers).\n * 4. Tie-break on lowest CIDR mask (most-specific subnet).\n * Returns `null` only when the host has zero non-loopback addresses.\n * Honours `getAllowedAddresses()` — if the operator pinned an\n * allowlist, only those addresses are candidates.\n */\n getPreferred: method(z.void(), PreferredSchema),\n\n /**\n * Ordered candidate base URLs the SDK should try on connect.\n * Includes LAN IPs (one per non-internal interface), the public\n * tunnel hostname (when active), and loopback as a last-resort\n * fallback. Filterable by `includeLoopback` / `ipv4Only`.\n * Honours `getAllowedAddresses()` when set — addresses outside\n * the allowlist are dropped (the public tunnel + loopback are\n * always included as escape hatches).\n */\n getConnectionEndpoints: method(\n z.object({\n /** Local hub HTTP port to use in base URLs. */\n port: z.number().int().min(1).max(65535),\n /** Include `http(s)://127.0.0.1:<port>` as the lowest-priority\n * candidate. Default `true`. */\n includeLoopback: z.boolean().optional(),\n /** Skip IPv6 entries. Some legacy clients can't parse them.\n * Default `false`. */\n ipv4Only: z.boolean().optional(),\n /** Scheme to emit for LAN/loopback URLs. Default `'http'`.\n * Pass `'https'` when the caller is itself loaded over HTTPS\n * to avoid mixed-content blocks in the browser. The public\n * tunnel always emits `https://` regardless. */\n scheme: z.enum(['http', 'https']).optional(),\n }),\n GetConnectionEndpointsResultSchema,\n ),\n\n /**\n * Read the operator's allowlist. Empty = \"auto\" (no filter). Used\n * by the admin UI's address selector to seed its checkbox state.\n */\n getAllowedAddresses: method(z.void(), AllowedAddressesSchema),\n\n /**\n * Replace the allowlist atomically. Persisted via the addon store\n * (kernel-managed) so it survives restarts. Pass `[]` to revert to\n * auto mode.\n */\n setAllowedAddresses: method(\n AllowedAddressesSchema,\n z.object({ success: z.literal(true) }),\n { kind: 'mutation' },\n ),\n\n /**\n * Re-run the boot heuristic over the current interface snapshot\n * and atomically replace the allowlist with the result. Useful\n * after a major network change (new dock, new VPN, IP rebound)\n * when the operator wants to wipe their manual edits and start\n * over from the auto-detected best matches.\n */\n resetAllowlistToBestMatch: method(\n z.void(),\n AllowedAddressesSchema,\n { kind: 'mutation' },\n ),\n },\n} as const satisfies CapabilityDefinition\n\nexport type ILocalNetworkProvider = InferProvider<typeof localNetworkCapability>\nexport type LocalInterface = z.infer<typeof LocalInterfaceSchema>\nexport type ConnectionEndpoint = z.infer<typeof ConnectionEndpointSchema>\n","/**\n * mesh-network — collection cap for mesh-VPN providers.\n *\n * Different shape from `network-access` (public tunnels):\n *\n * • `network-access` exposes ONE public URL the operator hands to\n * external clients. start/stop spawns a single edge process.\n *\n * • `mesh-network` joins the host into a private mesh (Tailscale,\n * Headscale, ZeroTier). The result is one or more *private*\n * endpoints (mesh IP `100.x.x.x`, MagicDNS hostname) reachable\n * only by peers on the same mesh. Optionally, providers that\n * support it (Tailscale Funnel / Serve) also expose a public\n * ingress for select ports.\n *\n * Per-provider access from the admin UI uses this collection cap's\n * generic per-`addonId` routing (every method accepts an optional\n * `addonId`) — there is no singleton facade cap.\n */\nimport { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\n\n/**\n * A reachable endpoint on the mesh. A single provider may expose\n * multiple (mesh IP + MagicDNS hostname + Funnel public URL).\n */\nconst MeshEndpointSchema = z.object({\n /** Stable identifier within the provider (e.g. `mesh-ipv4`, `magicdns`, `funnel`). */\n id: z.string(),\n /** Operator-facing label (e.g. \"Mesh IPv4\", \"MagicDNS\"). */\n label: z.string(),\n /**\n * Where the endpoint is reachable from:\n * - `mesh`: only peers on the same mesh (Tailscale tailnet, …)\n * - `public`: open internet (Funnel, public-tunnel pass-through)\n */\n scope: z.enum(['mesh', 'public']),\n /** Full base URL (e.g. `https://camstack.tail-abc.ts.net`). */\n url: z.string(),\n /** Hostname portion (for SAN cert checks + display). */\n hostname: z.string(),\n /** Port (`443` for Funnel/Serve, anything for raw mesh IP). */\n port: z.number(),\n /** Always `http` or `https`. */\n protocol: z.enum(['http', 'https']),\n})\n\nexport type MeshEndpoint = z.infer<typeof MeshEndpointSchema>\n\nexport const MeshPeerSchema = z.object({\n /** Stable peer id assigned by the mesh control plane. */\n id: z.string(),\n /** Hostname / device name as shown in the mesh dashboard. */\n hostname: z.string(),\n /** MagicDNS / mesh DNS name (e.g. `peer-foo.tail-abc.ts.net`). Empty when the provider doesn't support DNS or peer-side resolution is disabled. */\n magicDns: z.string(),\n /** Mesh IPv4 / IPv6 addresses combined. Multiple when dual-stacked. */\n addresses: z.array(z.string()).readonly(),\n /** Operating system reported by the peer (informational). */\n os: z.string().optional(),\n /** Whether this peer is currently reachable. */\n online: z.boolean(),\n /** Last-seen timestamp (epoch ms). 0 when never seen. */\n lastSeenMs: z.number(),\n /** True for the row representing the current host. */\n isSelf: z.boolean(),\n /**\n * Connection mode to this peer:\n * - `direct`: NAT-traversed P2P (UDP punched)\n * - `relay`: traffic relayed through provider edge (Tailscale DERP)\n * - `idle`: peer reachable but no recent traffic / handshake\n */\n connection: z.enum(['direct', 'relay', 'idle']),\n /** DERP region / relay node identifier when `connection: relay`. Null otherwise. */\n relay: z.string().nullable(),\n /** Last successful handshake timestamp (epoch ms). 0 when never. */\n lastHandshakeMs: z.number(),\n /** Bytes received from this peer since the daemon started. */\n rxBytes: z.number(),\n /** Bytes transmitted to this peer since the daemon started. */\n txBytes: z.number(),\n /** ACL tags this peer carries (e.g. `[\"tag:server\"]`). Empty when human-owned. */\n tags: z.array(z.string()).readonly(),\n /** True when the peer advertises itself as an exit-node candidate. */\n exitNodeOption: z.boolean(),\n /** Subnet routes the peer advertises (e.g. `[\"192.168.1.0/24\"]`). */\n advertisedRoutes: z.array(z.string()).readonly(),\n /** Owner account login (e.g. `foo@example.com`). Null for tagged peers. */\n userLogin: z.string().nullable(),\n /** Pre-auth key / machine-key expiry (epoch ms). Null when keys don't expire. */\n keyExpiry: z.number().nullable(),\n})\n\nexport type MeshPeer = z.infer<typeof MeshPeerSchema>\n\nexport const MeshStatusSchema = z.object({\n /** True when the host is joined and the daemon reports healthy. */\n joined: z.boolean(),\n /** Local mesh IPv4 (e.g. `100.x.x.x` for Tailscale). Empty when not joined. */\n meshIp: z.string(),\n /** MagicDNS / mesh hostname (e.g. `camstack.tail-abc.ts.net`). Empty if not configured. */\n magicDnsHostname: z.string(),\n /** Number of peers visible to this host (excluding self). */\n peerCount: z.number(),\n /** Every endpoint this provider exposes for the current host. */\n endpoints: z.array(MeshEndpointSchema).readonly(),\n /** Last error from the daemon, when not joined. */\n error: z.string().optional(),\n\n // ── Account / tenant identity (generic across providers) ────────\n /**\n * Tenant / tailnet / network display name (Tailscale = tailnet\n * domain, Headscale = namespace, ZeroTier = network name). Empty\n * pre-join. Per-provider semantics, common slot.\n */\n tenantName: z.string(),\n /**\n * Mesh DNS suffix when the provider exposes peer-resolvable DNS\n * (Tailscale MagicDNS, Headscale MagicDNS, …). Empty when the\n * provider doesn't ship DNS (e.g. ZeroTier).\n */\n magicDnsSuffix: z.string(),\n /**\n * Authenticated user / account login bound to this host. Null when\n * the provider authenticates with a long-lived network token rather\n * than a user account (e.g. ZeroTier API token).\n */\n userLogin: z.string().nullable(),\n /**\n * Provider control-plane URL (Tailscale SaaS `https://login.tailscale.com`,\n * self-hosted Headscale, ZeroTier Central, …). Empty when not\n * applicable (rare).\n */\n controlPlaneUrl: z.string(),\n /**\n * Machine-key / node-key expiry (epoch ms). Null when the provider\n * doesn't rotate keys for the bound host. Operator-facing surface\n * for \"your access expires on …\" banners.\n */\n keyExpiry: z.number().nullable(),\n\n // ── Onboard-daemon handoff (Tailscale, generic slot) ────────────\n /**\n * When the provider runs its OWN mesh daemon (e.g. the Tailscale\n * client addon in `onboard` mode spawns a private `tailscaled`),\n * this carries the local control-socket path. Companion addons that\n * must drive the SAME daemon — chiefly `tailscale-ingress` for\n * Serve/Funnel — read it to point their CLI at the right socket\n * instead of the system default. Empty when the provider uses the\n * host's system daemon (or doesn't have the concept).\n */\n daemonSocket: z.string().optional(),\n /**\n * Path to the mesh CLI binary the provider downloaded for onboard\n * mode. Companion addons reuse it so they don't need a system\n * install when the operator chose a fully self-contained mesh.\n * Empty in host mode.\n */\n daemonCliPath: z.string().optional(),\n})\n\nexport type MeshStatus = z.infer<typeof MeshStatusSchema>\n\n// Provider-specific runtime flags (accept-routes, advertise-routes,\n// shields-up, ssh, exit-node, etc.) intentionally NOT in the cap\n// schema — they vary too much between Tailscale / Headscale / ZeroTier /\n// Nebula. Each addon declares those via its own `getSettingsUISchema`\n// (form-builder), which the generic Mesh page renders as a \"Settings\"\n// tab below the addon's status / peers tabs.\n\n/**\n * `mesh-network` — per-provider implementation. Tailscale registers\n * one (and only one) entry. Future Headscale / ZeroTier addons would\n * register their own entries.\n */\nexport const meshNetworkCapability = {\n name: 'mesh-network',\n scope: 'system',\n mode: 'collection',\n providerKind: 'mesh',\n methods: {\n /** Return the current join state + endpoints + peer count. Cheap\n * poll-target — admin UI hits this every few seconds. */\n getStatus: method(z.void(), MeshStatusSchema),\n\n /**\n * Join the host to the provider's mesh using a one-time auth key\n * (generated by the operator in the provider's admin dashboard).\n * Implementations should be idempotent — re-calling with the same\n * key while already joined is a no-op + success.\n */\n join: method(\n z.object({\n /** Provider-specific auth key. For Tailscale this is the\n * `tskey-auth-*` token from admin.tailscale.com. */\n authKey: z.string().min(8),\n /** Optional hostname override the host should advertise. */\n hostname: z.string().optional(),\n }),\n z.object({ joined: z.literal(true) }),\n { kind: 'mutation' },\n ),\n\n /**\n * Start an interactive browser-redirect login flow.\n *\n * The provider spawns its daemon's join command without a pre-auth\n * key, captures the verification URL the daemon prints, and returns\n * it. The admin UI opens the URL in a new tab; the user completes\n * authentication in the provider's web console and the background\n * process self-terminates. The caller then polls `getStatus()` until\n * `joined: true`.\n *\n * Mirrors the `tailscale up` (no `--auth-key`) flow.\n */\n startLogin: method(\n z.object({\n /** Optional hostname override the host should advertise once joined. */\n hostname: z.string().optional(),\n }),\n z.object({\n /** Authentication URL the operator should open in a browser. */\n loginUrl: z.string(),\n }),\n { kind: 'mutation' },\n ),\n\n /** Leave the mesh. After this the meshIp/magicDnsHostname/etc.\n * vanish until the next `join`. The bound account stays — a\n * subsequent `join` reuses it without prompting for a new login. */\n leave: method(\n z.void(),\n z.object({ left: z.literal(true) }),\n { kind: 'mutation' },\n ),\n\n /**\n * Sign out of the mesh account entirely. Distinct from `leave`:\n * `leave` only takes the host off-mesh (`tailscale down`) while the\n * account binding survives, so the next `join` reconnects silently.\n * `logout` (`tailscale logout`) wipes the daemon's stored\n * credentials — the next `startLogin` MUST go through a fresh\n * browser-redirect flow to bind a new account.\n */\n logout: method(\n z.void(),\n z.object({ loggedOut: z.literal(true) }),\n { kind: 'mutation' },\n ),\n\n /** Enumerate every peer the daemon currently knows about. */\n listPeers: method(z.void(), z.object({\n peers: z.array(MeshPeerSchema).readonly(),\n })),\n\n /**\n * Probe the mesh daemon / API for a sanity check WITHOUT joining.\n * Operator-facing \"test connection\" button: validates the auth key\n * + reaches the control plane and reports back what would happen\n * on join.\n *\n * Tailscale: dry-runs `tailscale up --auth-key=… --reset` against\n * an idempotency probe; for an already-joined node it just returns\n * the current status.\n */\n testConnection: method(\n z.object({\n /** Optional auth key — when provided, probes the key validity\n * against the provider's API. Omit when already joined to\n * just ping the daemon. */\n authKey: z.string().optional(),\n }),\n z.object({\n ok: z.boolean(),\n /** Provider-side identifier resolved by the probe (tailnet\n * name for Tailscale, network id for ZeroTier, etc.). */\n tenant: z.string().optional(),\n /** Daemon binary version, when reachable. */\n daemonVersion: z.string().optional(),\n /** Human-readable error when `ok: false`. */\n error: z.string().optional(),\n }),\n { kind: 'mutation' },\n ),\n\n // Provider-specific runtime knobs (accept-routes / advertise-routes /\n // shields-up / ssh / exit-node, …) live on the addon's own\n // `getSettingsUISchema` (form-builder), NOT here. Different mesh\n // providers (Tailscale, Headscale, ZeroTier, Nebula) have very\n // different config surfaces — picking one shape and forcing all\n // implementations to honour it would either lose options or\n // misrepresent them. The Mesh page renders the addon's settings\n // schema as a \"Settings\" tab next to the generic Status / Peers\n // tabs driven by this cap.\n },\n} as const satisfies CapabilityDefinition\n\nexport type IMeshNetworkProvider = InferProvider<typeof meshNetworkCapability>\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\n// Canonical schemas — the local enum/scope duplicates that lived here got the\n// cap-router types out of sync with `auth-records` once already. One source\n// of truth, imported.\nimport { TokenScopeSchema } from '../schemas/auth-records.js'\n\nconst UserSummarySchema = z.object({\n id: z.string(),\n username: z.string(),\n isAdmin: z.boolean().default(false),\n allowedProviders: z.union([z.array(z.string()), z.literal('*')]),\n allowedDevices: z.record(z.string(), z.union([z.array(z.string()), z.literal('*')])),\n scopes: z.array(TokenScopeSchema).default([]),\n /**\n * True iff this user has a CONFIRMED TOTP enrollment. Surfaced on\n * `listUsers` so the admin Users page can render the \"Remove 2FA\"\n * action conditionally without firing one `getTotpStatus` query per\n * row. Self-service enrollment lives on the user's profile page.\n */\n totpEnabled: z.boolean().default(false),\n createdAt: z.number(),\n updatedAt: z.number(),\n})\n\nconst CreateUserInputSchema = z.object({\n username: z.string(),\n password: z.string().min(6),\n isAdmin: z.boolean().default(false),\n allowedProviders: z.union([z.array(z.string()), z.literal('*')]).optional(),\n allowedDevices: z.record(z.string(), z.union([z.array(z.string()), z.literal('*')])).optional(),\n scopes: z.array(TokenScopeSchema).optional(),\n})\n\nconst UpdateUserInputSchema = z.object({\n id: z.string(),\n isAdmin: z.boolean().optional(),\n allowedProviders: z.union([z.array(z.string()), z.literal('*')]).optional(),\n allowedDevices: z.record(z.string(), z.union([z.array(z.string()), z.literal('*')])).optional(),\n scopes: z.array(TokenScopeSchema).optional(),\n})\n\nconst ApiKeySummarySchema = z.object({\n id: z.string(),\n label: z.string(),\n isAdmin: z.boolean().default(false),\n allowedProviders: z.union([z.array(z.string()), z.literal('*')]).optional(),\n allowedDevices: z.record(z.string(), z.union([z.array(z.string()), z.literal('*')])).optional(),\n tokenPrefix: z.string(),\n createdAt: z.number(),\n lastUsedAt: z.number().optional(),\n})\n\nconst CreateApiKeyInputSchema = z.object({\n label: z.string(),\n isAdmin: z.boolean().default(false),\n allowedProviders: z.union([z.array(z.string()), z.literal('*')]).optional(),\n allowedDevices: z.record(z.string(), z.union([z.array(z.string()), z.literal('*')])).optional(),\n})\n\nconst CreateApiKeyResultSchema = z.object({\n token: z.string(),\n record: ApiKeySummarySchema,\n})\n\nconst ScopedTokenSummarySchema = z.object({\n id: z.string(),\n userId: z.string(),\n name: z.string(),\n tokenPrefix: z.string(),\n scopes: z.array(TokenScopeSchema),\n expiresAt: z.number().nullish(),\n lastUsedAt: z.number().nullish(),\n createdAt: z.number(),\n})\n\nconst CreateScopedTokenInputSchema = z.object({\n userId: z.string(),\n name: z.string(),\n scopes: z.array(TokenScopeSchema),\n expiresAt: z.number().optional(),\n})\n\nconst CreateScopedTokenResultSchema = z.object({\n token: z.string(),\n record: ScopedTokenSummarySchema,\n})\n\nconst OauthSessionSummarySchema = z.object({\n id: z.string(),\n userId: z.string(),\n username: z.string(),\n integrationId: z.string(),\n scopes: z.array(TokenScopeSchema),\n createdAt: z.number(),\n lastUsedAt: z.number(),\n revokedAt: z.number().nullable(),\n})\n\n// ── TOTP / 2FA schemas ────────────────────────────────────────────────\n//\n// Setup returns the operator-visible secret (for manual entry) plus an\n// `otpauth://` URL that authenticator apps consume as a QR-code payload.\n// Recovery codes are deferred to a follow-up phase — the user record\n// would need a separate `recovery_codes` collection.\n\nconst TotpSetupResultSchema = z.object({\n secret: z.string(),\n otpauthUrl: z.string(),\n})\n\nconst TotpStatusSchema = z.object({\n /** True iff `confirmedAt != null` — a pending half-enrollment is reported as `enabled: false`. */\n enabled: z.boolean(),\n /** Null when no row exists OR the row is still pending confirmation. */\n confirmedAt: z.number().nullable(),\n})\n\n/**\n * user-management — singleton capability for user accounts, API keys,\n * and scoped tokens.\n *\n * v2 model: every method gated by `auth: 'admin'`. Admin-only delegation\n * — the subset check on `setUserScopes` / `createScopedToken` is moot\n * because non-admins never reach these. If/when we open non-admin\n * delegation, structural caller-scope subset check goes inside the\n * provider.\n */\nexport const userManagementCapability = {\n name: 'user-management',\n scope: 'system',\n mode: 'singleton',\n methods: {\n listUsers: method(z.void(), z.array(UserSummarySchema), { auth: 'admin' }),\n createUser: method(CreateUserInputSchema, UserSummarySchema, { kind: 'mutation', auth: 'admin', access: 'create' }),\n updateUser: method(UpdateUserInputSchema, z.object({ success: z.literal(true) }), { kind: 'mutation', auth: 'admin', access: 'create' }),\n deleteUser: method(z.object({ id: z.string() }), z.object({ success: z.literal(true) }), { kind: 'mutation', auth: 'admin', access: 'delete' }),\n resetPassword: method(\n z.object({ id: z.string(), newPassword: z.string().min(6) }),\n z.object({ success: z.literal(true) }),\n { kind: 'mutation', auth: 'admin', access: 'create' },\n ),\n setUserScopes: method(\n z.object({ userId: z.string(), scopes: z.array(TokenScopeSchema) }),\n z.object({ success: z.literal(true) }),\n { kind: 'mutation', auth: 'admin', access: 'create' },\n ),\n validateCredentials: method(\n z.object({ username: z.string(), password: z.string() }),\n UserSummarySchema.extend({ passwordHash: z.string() }).nullable(),\n { kind: 'mutation', access: 'view' },\n ),\n\n listApiKeys: method(z.void(), z.array(ApiKeySummarySchema), { auth: 'admin' }),\n createApiKey: method(CreateApiKeyInputSchema, CreateApiKeyResultSchema, { kind: 'mutation', auth: 'admin', access: 'create' }),\n revokeApiKey: method(z.object({ id: z.string() }), z.object({ success: z.literal(true) }), { kind: 'mutation', auth: 'admin', access: 'delete' }),\n validateApiKey: method(z.object({ token: z.string() }), ApiKeySummarySchema.nullable(), { kind: 'mutation', access: 'view' }),\n\n createScopedToken: method(CreateScopedTokenInputSchema, CreateScopedTokenResultSchema, { kind: 'mutation', auth: 'admin', access: 'create' }),\n revokeScopedToken: method(z.object({ id: z.string() }), z.object({ success: z.literal(true) }), { kind: 'mutation', auth: 'admin', access: 'delete' }),\n validateScopedToken: method(z.object({ token: z.string() }), ScopedTokenSummarySchema.nullable(), { access: 'view' }),\n listScopedTokens: method(z.object({ userId: z.string() }), z.array(ScopedTokenSummarySchema), { auth: 'admin' }),\n\n // ── TOTP / 2FA ─────────────────────────────────────────────────\n //\n // Setup → Confirm → (Verify on login) → Disable.\n //\n // Admin-only for now: operator enrolls TOTP on a user's behalf by\n // pairing their authenticator with the returned QR. Self-service\n // enrollment is a follow-up (needs the cap framework to expose the\n // caller's identity to the provider so the provider can enforce\n // self-or-admin).\n setupTotp: method(\n z.object({ userId: z.string() }),\n TotpSetupResultSchema,\n { kind: 'mutation', auth: 'admin', access: 'create' },\n ),\n confirmTotp: method(\n z.object({ userId: z.string(), code: z.string() }),\n z.object({ success: z.literal(true) }),\n { kind: 'mutation', auth: 'admin', access: 'create' },\n ),\n disableTotp: method(\n z.object({ userId: z.string() }),\n z.object({ success: z.literal(true) }),\n { kind: 'mutation', auth: 'admin', access: 'delete' },\n ),\n getTotpStatus: method(\n z.object({ userId: z.string() }),\n TotpStatusSchema,\n { auth: 'admin' },\n ),\n // Public (no `auth`) — used by the login flow's second-step\n // challenge endpoint. The userId comes from the password-validation\n // step (signed bridge token), so this method is not a free oracle.\n verifyTotp: method(\n z.object({ userId: z.string(), code: z.string() }),\n z.object({ valid: z.boolean() }),\n { kind: 'mutation', access: 'view' },\n ),\n\n // ── OAuth account-linking grant ────────────────────────────────\n //\n // Core's /oauth2/* endpoints delegate here. Tokens are sso-bridge\n // JWTs (kinds oauth-code / oauth-access / oauth-refresh) and ALWAYS\n // carry isAdmin:false — the operator login proves hub control; the\n // issued token is minimal (device scope only).\n oauthIssueCode: method(\n z.object({\n integrationId: z.string(),\n userId: z.string(),\n username: z.string(),\n scopes: z.array(TokenScopeSchema),\n redirectUri: z.string(),\n hubUrl: z.string(),\n }),\n z.object({ code: z.string() }),\n { kind: 'mutation', access: 'create' },\n ),\n oauthExchangeCode: method(\n z.object({ code: z.string(), redirectUri: z.string() }),\n z.object({\n accessToken: z.string(),\n refreshToken: z.string(),\n expiresIn: z.number(),\n }).nullable(),\n { kind: 'mutation', access: 'view' },\n ),\n oauthRefresh: method(\n z.object({ refreshToken: z.string() }),\n z.object({\n accessToken: z.string(),\n refreshToken: z.string(),\n expiresIn: z.number(),\n }).nullable(),\n { kind: 'mutation', access: 'view' },\n ),\n oauthVerifyAccessToken: method(\n z.object({ token: z.string() }),\n z.object({\n userId: z.string(),\n username: z.string(),\n scopes: z.array(TokenScopeSchema),\n }).nullable(),\n { access: 'view' },\n ),\n\n // ── OAuth linked-session management (Phase D) ──────────────────\n //\n // The admin UI lists active account-linking sessions and revokes\n // them; revocation makes the linked integration's tokens fail\n // verification immediately.\n listOauthSessions: method(\n z.void(),\n z.array(OauthSessionSummarySchema),\n { auth: 'admin' },\n ),\n revokeOauthSession: method(\n z.object({ id: z.string() }),\n z.object({ success: z.boolean() }),\n { kind: 'mutation', auth: 'admin', access: 'delete' },\n ),\n },\n} as const satisfies CapabilityDefinition\n\nexport type IUserManagementProvider = InferProvider<typeof userManagementCapability>\n\nexport {\n UserSummarySchema, CreateUserInputSchema, UpdateUserInputSchema,\n ApiKeySummarySchema, CreateApiKeyInputSchema, CreateApiKeyResultSchema,\n ScopedTokenSummarySchema, CreateScopedTokenInputSchema, CreateScopedTokenResultSchema,\n OauthSessionSummarySchema,\n}\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\n\n/**\n * system — system-scoped singleton capability exposing hub-level\n * health, feature flags, network interface enumeration, and the\n * analytics-suite retention controls.\n *\n * Implementation lives in the server's `FeatureService` plus the\n * `analysis-data-persistence` singleton (provided by\n * `addon-analytics-suite`). The provider is registered from\n * `trpc.router.ts` against the existing services — no addon owns\n * this surface end-to-end.\n *\n * Phase E of the API consolidation: previously a hand-written core\n * router. Cap conversion lets the canonical hooks\n * (`useSystemInfo`, `useSystemHealth`, `useSystemNetworkAddresses`,\n * `useSystemGetRetentionConfig`, `useSystemSetRetentionConfig`,\n * `useSystemForceRetentionCleanup`) flow through the same codegen\n * as every other cap.\n */\n\nconst FeatureManifestSchema = z.object({\n streaming: z.boolean(),\n notifications: z.boolean(),\n objectDetection: z.boolean(),\n remoteAccess: z.boolean(),\n agentCluster: z.boolean(),\n smartHome: z.boolean(),\n recordings: z.boolean(),\n backup: z.boolean(),\n repl: z.boolean(),\n})\n\nconst HealthStatusSchema = z.object({\n status: z.literal('ok'),\n uptime: z.number(),\n})\n\nconst NetworkAddressSchema = z.object({\n name: z.string(),\n address: z.string(),\n family: z.string(),\n internal: z.boolean(),\n})\n\nexport const systemCapability = {\n name: 'system',\n scope: 'system',\n mode: 'singleton',\n methods: {\n info: method(z.void(), FeatureManifestSchema),\n health: method(z.void(), HealthStatusSchema),\n featureFlags: method(z.void(), FeatureManifestSchema),\n networkAddresses: method(z.void(), z.array(NetworkAddressSchema).readonly()),\n // Retention config is opaque on the wire — the analytics-suite owns the\n // schema. `getRetentionConfig` returns null when the analytics addon\n // is not loaded; `setRetentionConfig` accepts a partial patch.\n getRetentionConfig: method(z.void(), z.unknown().nullable(), { auth: 'admin' }),\n setRetentionConfig: method(\n z.record(z.string(), z.unknown()),\n z.null(),\n { kind: 'mutation', auth: 'admin' },\n ),\n forceRetentionCleanup: method(z.void(), z.void(), { kind: 'mutation', auth: 'admin' }),\n },\n} as const satisfies CapabilityDefinition\n\nexport type ISystemProvider = InferProvider<typeof systemCapability>\n\nexport {\n FeatureManifestSchema,\n HealthStatusSchema,\n NetworkAddressSchema,\n}\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\n\n/**\n * network-quality — system-scoped singleton capability tracking RTT,\n * jitter, and observed/peak bandwidth per device + per client.\n *\n * Implementation lives in the server's `NetworkQualityService` (thin\n * wrapper over the shared `NetworkQualityTracker` from `@camstack/core`).\n * The provider is registered from `trpc.router.ts` against the existing\n * service instance — no addon owns this state.\n *\n * Phase E of the API consolidation: previously a hand-written core\n * router. Cap conversion lets the same codegen pipeline produce both\n * the tRPC router and the canonical UI hooks\n * (`useNetworkQualityGetDeviceStats`, …).\n */\n\nconst StreamNetworkStatsSchema = z.object({\n nominalBitrateKbps: z.number(),\n observedBitrateKbps: z.number(),\n peakBitrateKbps: z.number(),\n packetLossPercent: z.number(),\n lastUpdated: z.number(),\n})\n\nconst ClientNetworkStatsSchema = z.object({\n rttMs: z.number(),\n jitterMs: z.number(),\n estimatedBandwidthKbps: z.number(),\n packetLossPercent: z.number().min(0).max(100),\n lastUpdated: z.number(),\n})\n\nconst DeviceNetworkStatsSchema = z.object({\n deviceId: z.number(),\n streams: z.record(z.string(), StreamNetworkStatsSchema),\n client: ClientNetworkStatsSchema.optional(),\n})\n\nexport const networkQualityCapability = {\n name: 'network-quality',\n scope: 'system',\n mode: 'singleton',\n methods: {\n getDeviceStats: method(\n z.object({ deviceId: z.number() }),\n DeviceNetworkStatsSchema.nullable(),\n ),\n getAllStats: method(\n z.void(),\n z.array(DeviceNetworkStatsSchema).readonly(),\n ),\n reportClientStats: method(\n z.object({\n deviceId: z.number(),\n rttMs: z.number().min(0).max(60000),\n jitterMs: z.number().min(0).max(10000),\n estimatedBandwidthKbps: z.number().min(0).max(1000000),\n packetLossPercent: z.number().min(0).max(100),\n }),\n z.void(),\n { kind: 'mutation' },\n ),\n },\n} as const satisfies CapabilityDefinition\n\nexport type INetworkQualityProvider = InferProvider<typeof networkQualityCapability>\n\nexport {\n StreamNetworkStatsSchema,\n ClientNetworkStatsSchema,\n DeviceNetworkStatsSchema,\n}\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\n\n/**\n * toast — system-scoped singleton capability that streams toast\n * notifications from the hub to connected admin-UI clients.\n *\n * Single push subscription (`onToast`). The provider lives in the\n * server's `ToastService` (always available after boot) and is\n * registered from `trpc.router.ts` against that service. No addon\n * owns this state — toasts are server-broadcasted side-effects of\n * other admin actions.\n *\n * Phase E of the API consolidation: previously a hand-written core\n * router (re-introduced after a brief detour as a cap years ago).\n * Cap conversion unifies the codegen pipeline so admin-ui consumers\n * pick up the standard `useToastOnToast` hook through the same\n * generator that emits every other system-cap subscription wrapper.\n */\n\nconst ToastSchema = z.object({\n title: z.string(),\n message: z.string(),\n severity: z.enum(['info', 'warning', 'critical']),\n duration: z.number().optional(),\n action: z\n .object({\n label: z.string(),\n url: z.string(),\n })\n .optional(),\n})\n\nexport const toastCapability = {\n name: 'toast',\n scope: 'system',\n mode: 'singleton',\n methods: {\n onToast: method(z.void(), ToastSchema, { kind: 'subscription' }),\n },\n} as const satisfies CapabilityDefinition\n\nexport type IToastProvider = InferProvider<typeof toastCapability>\n\nexport { ToastSchema }\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\n\n/**\n * nodes — system-scoped singleton capability for cluster topology\n * queries and remote addon lifecycle operations.\n *\n * Implementation lives in the server's `AgentRegistryService`,\n * `MoleculerService`, and `AddonRegistryService`. The provider is\n * registered from `trpc.router.ts` against those services — no addon\n * owns the cluster topology view.\n *\n * Phase E of the API consolidation: previously a hand-written core\n * router. Cap conversion lets `useNodesTopology`, `useNodesRestartNode`,\n * etc. flow through the same codegen pipeline as every other cap.\n */\n\n// ── Topology ─────────────────────────────────────────────────────────\n\nconst TopologyServiceSchema = z.object({\n addonId: z.string(),\n capabilities: z.array(z.string()).readonly(),\n status: z.string(),\n})\n\nconst TopologyProcessSchema = z.object({\n pid: z.number(),\n name: z.string(),\n state: z.string(),\n cpuPercent: z.number(),\n memoryRss: z.number(),\n uptimeSeconds: z.number(),\n services: z.array(TopologyServiceSchema).readonly(),\n groupId: z.string().optional(),\n})\n\n// Diagrams redesign (2026-05-20): topology now carries a per-node\n// roll-up of addons by category, so the admin UI's Cluster page can\n// render compact \"category cards\" without re-walking the whole\n// `addons[]` + `processes[]` arrays on each frame.\nconst TopologyCategoryAddonSchema = z.object({\n id: z.string(),\n status: z.string(),\n cpuPercent: z.number(),\n memoryRss: z.number(),\n})\n\nconst TopologyCategorySchema = z.object({\n category: z.string(),\n total: z.number(),\n healthy: z.number(),\n addons: z.array(TopologyCategoryAddonSchema).readonly(),\n})\n\nconst TopologyNodeSchema = z.object({\n id: z.string(),\n name: z.string(),\n hostname: z.string(),\n platform: z.string(),\n arch: z.string(),\n cpuModel: z.string().nullable(),\n cpuCores: z.number(),\n memoryMB: z.number(),\n engines: z.array(z.string()).readonly(),\n isHub: z.boolean(),\n isOnline: z.boolean(),\n cpuPercent: z.number(),\n memoryPercent: z.number(),\n uptime: z.number(),\n lastSeen: z.string(),\n localIps: z.array(z.string()).readonly(),\n addons: z.array(\n z.object({\n id: z.string(),\n capabilities: z.array(z.string()).readonly(),\n status: z.string(),\n }),\n ).readonly(),\n processes: z.array(TopologyProcessSchema).readonly(),\n categories: z.array(TopologyCategorySchema).readonly(),\n})\n\n// Observed runtime cap-usage edges — drives the Capability Flow tab on\n// the Cluster page. Each edge counts cap calls made in a sliding window.\nconst CapUsageEdgeSchema = z.object({\n callerAddonId: z.string(),\n providerAddonId: z.string(),\n capName: z.string(),\n callsPerMin: z.number(),\n lastCallAtMs: z.number(),\n})\n\n// ── Cluster addon-status ────────────────────────────────────────────\n\nconst ClusterAddonNodeDeploymentSchema = z.object({\n nodeId: z.string(),\n name: z.string(),\n version: z.string(),\n status: z.string(),\n synced: z.boolean(),\n})\n\nconst ClusterAddonStatusEntrySchema = z.object({\n hubVersion: z.string(),\n nodes: z.array(ClusterAddonNodeDeploymentSchema),\n})\n\n// ── Method input/output shapes ──────────────────────────────────────\n\nconst NodeAddonInputSchema = z.object({\n nodeId: z.string(),\n addonId: z.string(),\n})\n\nconst NodeAddonEntrySchema = z.object({\n id: z.string(),\n status: z.string(),\n version: z.string().optional(),\n packageName: z.string().optional(),\n})\n\nconst SuccessSchema = z.object({ success: z.boolean() })\n\nconst RestartProcessResultSchema = z.object({\n success: z.boolean(),\n reason: z.string().optional(),\n})\n\nconst RestartNodeResultSchema = z.object({\n restarted: z.array(z.string()).readonly(),\n failed: z.array(z.string()).readonly(),\n})\n\nconst RenameNodeResultSchema = z.object({\n nodeId: z.string(),\n name: z.string(),\n})\n\n/**\n * `nodes` is a **hub-centric** cluster-management cap: the hub hosts\n * the single provider and every per-node method (`getNodeAddons`,\n * `restartProcess`, `restartNode`, `undeployAddon`, …) takes `nodeId`\n * as DATA — the provider fans out to the target node itself via\n * `broker.call(..., { nodeID })`. Agents host no `nodes` provider.\n *\n * `nodeIdMode: 'data'` therefore forwards `nodeId` to the hub provider\n * intact instead of stripping it for generic cap-router node routing\n * (which would reject any non-hub `nodeId` with \"Node routing not\n * available\", since `nodes` is mounted as a hub singleton).\n */\nexport const nodesCapability = {\n name: 'nodes',\n scope: 'system',\n mode: 'singleton',\n nodeIdMode: 'data',\n methods: {\n topology: method(\n z.void(),\n z.array(TopologyNodeSchema).readonly(),\n { auth: 'admin' },\n ),\n deployAddon: method(NodeAddonInputSchema, SuccessSchema, {\n kind: 'mutation',\n auth: 'admin',\n }),\n undeployAddon: method(NodeAddonInputSchema, SuccessSchema, {\n kind: 'mutation',\n auth: 'admin',\n }),\n restartAddon: method(NodeAddonInputSchema, SuccessSchema, {\n kind: 'mutation',\n auth: 'admin',\n }),\n restartProcess: method(\n z.object({ nodeId: z.string(), processName: z.string() }),\n RestartProcessResultSchema,\n { kind: 'mutation', auth: 'admin' },\n ),\n restartNode: method(\n z.object({ nodeId: z.string() }),\n RestartNodeResultSchema,\n { kind: 'mutation', auth: 'admin' },\n ),\n shutdownNode: method(\n z.object({ nodeId: z.string() }),\n SuccessSchema,\n { kind: 'mutation', auth: 'admin' },\n ),\n renameNode: method(\n z.object({ nodeId: z.string(), name: z.string().min(1).max(64) }),\n RenameNodeResultSchema,\n { kind: 'mutation', auth: 'admin' },\n ),\n clusterAddonStatus: method(\n z.void(),\n z.record(z.string(), ClusterAddonStatusEntrySchema),\n { auth: 'admin' },\n ),\n getCapUsageGraph: method(\n z.object({\n windowSeconds: z.number().int().positive().max(300).default(60),\n }),\n z.array(CapUsageEdgeSchema).readonly(),\n { auth: 'admin' },\n ),\n /**\n * Direct per-node addon listing — calls `$agent.status` on the target\n * node (or returns the hub registry for `nodeId === 'hub'`) and surfaces\n * the full addon roster including `version` + `packageName`. The\n * `topology` cap also includes addons but strips them down to\n * `{id, capabilities, status}` for the cluster diagram; this method\n * is the one the per-node \"Addons\" tab should call.\n */\n getNodeAddons: method(\n z.object({ nodeId: z.string() }),\n z.array(NodeAddonEntrySchema).readonly(),\n { auth: 'admin' },\n ),\n setProcessLogLevel: method(\n z.object({ nodeId: z.string(), level: z.string() }),\n SuccessSchema,\n { kind: 'mutation', auth: 'admin' },\n ),\n executeQuery: method(\n z.object({\n nodeId: z.string(),\n addonId: z.string(),\n queryName: z.string(),\n params: z.record(z.string(), z.unknown()).optional(),\n }),\n z.unknown(),\n { kind: 'mutation', auth: 'admin' },\n ),\n },\n} as const satisfies CapabilityDefinition\n\nexport type INodesProvider = InferProvider<typeof nodesCapability>\n\nexport {\n TopologyNodeSchema,\n TopologyProcessSchema,\n TopologyServiceSchema,\n ClusterAddonStatusEntrySchema,\n ClusterAddonNodeDeploymentSchema,\n NodeAddonEntrySchema,\n}\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\n\n/**\n * integrations — system-scoped singleton capability for integration\n * (provider-instance) lifecycle. Integrations are typically per-addon\n * data records that pin a device-provider addon to a concrete config\n * (Reolink credentials, ONVIF endpoint, etc.).\n *\n * Implementation lives in the server's `AddonRegistryService`\n * (specifically `getIntegrationRegistry()`). The provider is registered\n * from `trpc.router.ts` against that service plus the event bus and\n * logger — no addon owns this end-to-end.\n *\n * Phase E of the API consolidation: previously a hand-written core\n * router. Cap conversion lets `useIntegrationsList`,\n * `useIntegrationsCreate`, `useIntegrationsTestConnection` and\n * friends flow through the same codegen pipeline as every other cap.\n */\n\n// ── Schemas ─────────────────────────────────────────────────────────\n\nconst IntegrationWithStateSchema = z.object({\n id: z.string(),\n addonId: z.string(),\n name: z.string(),\n enabled: z.boolean(),\n info: z.record(z.string(), z.unknown()).readonly(),\n createdAt: z.number(),\n updatedAt: z.number(),\n processState: z.string(),\n})\n\nconst IntegrationLiteSchema = z.object({\n id: z.string(),\n addonId: z.string(),\n name: z.string(),\n enabled: z.boolean(),\n info: z.record(z.string(), z.unknown()).readonly(),\n createdAt: z.number(),\n updatedAt: z.number(),\n})\n\nconst AvailableIntegrationTypeSchema = z.object({\n addonId: z.string(),\n name: z.string(),\n description: z.string(),\n iconUrl: z.string().nullable(),\n color: z.string(),\n instanceMode: z.string(),\n discoveryMode: z.string(),\n /**\n * Which integration-marker cap the addon declared, so the wizard can\n * branch on CAP — never on addon name. `device-adoption` integrations\n * (Home Assistant, …) route through the broker step (Approach A);\n * `device-provider` integrations (Reolink/Frigate/ONVIF) keep the\n * legacy config → discovery flow.\n */\n kind: z.enum(['device-adoption', 'device-provider']),\n /**\n * For `device-adoption` addons: the broker kind to create/link\n * (e.g. `home-assistant`), declared in the addon manifest. `null` for\n * `device-provider` addons, which carry no broker.\n */\n brokerKind: z.string().nullable(),\n /** True when the integration's source system exposes locations the adoption\n * flow can import (e.g. HA areas). Drives the adopt modal's \"import\n * locations\" checkbox. Provider-declared in the addon manifest. */\n supportsLocationImport: z.boolean(),\n existingInstances: z.array(z.object({ id: z.string(), name: z.string() })),\n canAdd: z.boolean(),\n})\n\nconst TestConnectionResultSchema = z.object({\n success: z.boolean(),\n error: z.string().optional(),\n})\n\n// ── Method I/O ──────────────────────────────────────────────────────\n\nconst CreateIntegrationInputSchema = z.object({\n addonId: z.string(),\n name: z.string(),\n enabled: z.boolean().optional(),\n info: z.record(z.string(), z.unknown()).optional(),\n settings: z.record(z.string(), z.unknown()).optional(),\n skipRestart: z.boolean().optional(),\n})\n\nconst UpdateIntegrationInputSchema = z.object({\n id: z.string(),\n name: z.string().optional(),\n enabled: z.boolean().optional(),\n info: z.record(z.string(), z.unknown()).optional(),\n})\n\nconst DeleteIntegrationResultSchema = z.object({\n success: z.boolean(),\n deletedId: z.string(),\n})\n\nexport const integrationsCapability = {\n name: 'integrations',\n scope: 'system',\n mode: 'singleton',\n methods: {\n list: method(z.void(), z.array(IntegrationWithStateSchema)),\n get: method(z.object({ id: z.string() }), IntegrationWithStateSchema),\n getByAddonId: method(\n z.object({ addonId: z.string() }),\n IntegrationLiteSchema.nullable(),\n ),\n create: method(\n CreateIntegrationInputSchema,\n IntegrationLiteSchema,\n { kind: 'mutation', auth: 'admin' },\n ),\n update: method(\n UpdateIntegrationInputSchema,\n IntegrationLiteSchema,\n { kind: 'mutation', auth: 'admin' },\n ),\n delete: method(\n z.object({ id: z.string() }),\n DeleteIntegrationResultSchema,\n { kind: 'mutation', auth: 'admin' },\n ),\n getSettings: method(\n z.object({ id: z.string() }),\n z.record(z.string(), z.unknown()),\n { auth: 'admin' },\n ),\n setSettings: method(\n z.object({\n id: z.string(),\n settings: z.record(z.string(), z.unknown()),\n }),\n z.object({ success: z.boolean() }),\n { kind: 'mutation', auth: 'admin' },\n ),\n getAvailableTypes: method(\n z.void(),\n z.array(AvailableIntegrationTypeSchema),\n { auth: 'admin' },\n ),\n testConnection: method(\n z.object({\n addonId: z.string(),\n settings: z.record(z.string(), z.unknown()),\n }),\n TestConnectionResultSchema,\n { kind: 'mutation', auth: 'admin' },\n ),\n },\n} as const satisfies CapabilityDefinition\n\nexport type IIntegrationsProvider = InferProvider<typeof integrationsCapability>\n\nexport {\n IntegrationWithStateSchema,\n IntegrationLiteSchema,\n AvailableIntegrationTypeSchema,\n TestConnectionResultSchema,\n CreateIntegrationInputSchema,\n UpdateIntegrationInputSchema,\n DeleteIntegrationResultSchema,\n}\n","import { z } from 'zod'\nimport { method, type CapabilityDefinition, type InferProvider } from './capability-definition.js'\n\n/**\n * addons — system-scoped singleton capability for addon package\n * management (install, update, configure, restart) and per-addon log\n * streaming.\n *\n * Implementation lives in the server's `AddonRegistryService`,\n * `AddonPackageService`, and `LoggingService`. The provider is\n * registered from `trpc.router.ts` against those services — no addon\n * owns this surface end-to-end (it manages addons themselves).\n *\n * Phase E of the API consolidation: previously a hand-written core\n * router. Cap conversion lets `useAddonsList`, `useAddonsInstallPackage`,\n * `useAddonsOnAddonLogs`, etc. flow through the same codegen pipeline\n * as every other cap.\n */\n\n// ── Loose-shape Zod helpers ─────────────────────────────────────────\n//\n// The `addons` surface ships rich runtime objects (manifests, addon\n// declarations, package metadata) whose precise shapes already live in\n// `@camstack/types/interfaces`. We deliberately keep the cap schemas\n// loose — `z.record(z.string(), z.unknown())` plus a few well-known\n// fields — so admin-ui consumers can keep using the existing\n// `AddonListItem` interface via cast, and so we don't risk inflating\n// the inferred AppRouter type past the TypeScript inference budget.\n\nconst LogLevelSchema = z.enum(['debug', 'info', 'warn', 'error'])\nconst ChannelSchema = z.enum(['off', 'latest', 'beta'])\nconst ChannelWithInheritSchema = z.enum(['off', 'latest', 'beta', 'inherit'])\n\n// Mirrors `AddonListItem` from interfaces/api-responses.ts. Schema is\n// intentionally loose — `z.unknown()` slots accept any runtime shape so\n// admin-ui can keep using the `AddonListItem` interface via cast.\nconst ManifestShapeSchema = z.object({\n id: z.string(),\n name: z.string().optional(),\n version: z.string().optional(),\n description: z.string().optional(),\n icon: z.string().optional(),\n color: z.string().optional(),\n // Loose schema for `manifest.capabilities` — runtime entries are\n // either kebab-case strings (legacy form) or `CapabilityDeclaration`\n // objects. The cap output schema deliberately keeps it as\n // `readonly unknown[]` so admin-ui consumers cast to the canonical\n // `AddonListItem` (from `@camstack/types`) before reading fields.\n capabilities: z.array(z.unknown()).readonly().optional(),\n packageName: z.string(),\n packageVersion: z.string(),\n packageDisplayName: z.string().optional(),\n /**\n * Bundle metadata when the npm package ships multiple addon entries\n * (mirror of `AddonPackageManifest.bundle` in @camstack/types). When\n * present, the admin UI groups all entries with the same packageName\n * under a collapsible bundle card. Single-entry packages omit this.\n */\n bundle: z.object({\n displayName: z.string(),\n description: z.string().optional(),\n icon: z.string().optional(),\n }).optional(),\n protected: z.boolean().optional(),\n removable: z.boolean().optional(),\n})\n\nconst AddonProcessSchema = z.object({\n pid: z.number().optional(),\n mode: z.string(),\n state: z.string(),\n})\n\n/**\n * Per-addon health snapshot from the kernel's AddonHealthMonitor.\n * Surfaces the retry-loop state to the admin UI so the Addons page\n * can:\n * - Show a red badge + error stack on `phase=failed` rows\n * - Render a \"Retry now\" button (calls `addons.retryLoad`)\n * - Display a \"next retry in Ns\" countdown\n * - Suppress alarming UI during the 5-minute boot grace\n */\nconst AddonHealthSchema = z.object({\n phase: z.enum(['pending', 'healthy', 'failed']),\n retryCount: z.number(),\n firstFailureAt: z.number().nullable(),\n lastAttemptAt: z.number().nullable(),\n lastError: z\n .object({ message: z.string(), stack: z.string().optional() })\n .nullable(),\n nextRetryAt: z.number().nullable(),\n alertEmitted: z.boolean(),\n retrying: z.boolean(),\n inGracePeriod: z.boolean(),\n})\n\nconst AddonListItemSchema = z.object({\n manifest: ManifestShapeSchema,\n declaration: z.unknown().optional(),\n source: z.string(),\n installSource: z.string().optional(),\n process: AddonProcessSchema.optional(),\n /**\n * True when `applyUpdate` last ran for this package and a pre-update\n * backup is still on disk (post-update health-check hasn't cleared\n * it yet, or the user hasn't called `clearBackup`). Drives the\n * Rollback button visibility in admin-ui's AddonCard.\n */\n hasBackup: z.boolean().optional(),\n /** Kernel health snapshot — null when monitor doesn't track this package. */\n health: AddonHealthSchema.nullable().optional(),\n})\n\nconst InstalledPackageSchema = z.object({\n name: z.string(),\n version: z.string(),\n dir: z.string(),\n installSource: z.string().optional(),\n})\n\nconst PackageUpdateSchema = z.object({\n name: z.string(),\n currentVersion: z.string(),\n latestVersion: z.string(),\n category: z.enum(['addon', 'core']),\n requiresRestart: z.boolean(),\n isSystem: z.boolean(),\n})\n\nconst PackageVersionInfoSchema = z.object({\n version: z.string(),\n publishedAt: z.string(),\n deprecated: z.string().optional(),\n distTags: z.array(z.string()).readonly(),\n})\n\nconst SearchResultSchema = z.object({\n name: z.string(),\n version: z.string(),\n description: z.string(),\n keywords: z.array(z.string()).readonly(),\n publishedAt: z.string(),\n author: z.string(),\n installed: z.boolean(),\n installedVersion: z.string().optional(),\n})\n\nconst AutoUpdateSettingsSchema = z.object({\n channel: ChannelSchema,\n intervalSeconds: z.number(),\n})\n\nconst AddonAutoUpdateSchema = ChannelWithInheritSchema\n\nconst RestartAddonResultSchema = z.unknown()\n\nconst InstallPackageResultSchema = z.unknown()\nconst ReloadPackagesResultSchema = z.unknown()\n\n/**\n * Result of `updateFrameworkPackage`. The cap method returns BEFORE the\n * server restarts so the admin UI can react to the `restartingAt`\n * timestamp (shows reconnect overlay). The transition from\n * `fromVersion` to `toVersion` will be confirmed by a subsequent\n * `system.restart-completed` event after the new process boots.\n *\n * Spec: docs/superpowers/specs/2026-05-14-framework-live-update-design.md\n */\nconst UpdateFrameworkPackageResultSchema = z.object({\n packageName: z.string(),\n fromVersion: z.string(),\n toVersion: z.string(),\n /** Ms-epoch the server scheduled its self-restart. */\n restartingAt: z.number(),\n})\n\n// ── Bulk update progress ────────────────────────────────────────────\n\nconst BulkUpdateItemStatusSchema = z.enum([\n 'queued',\n 'updating',\n 'done',\n 'done-pending-restart',\n 'failed',\n])\n\nconst BulkUpdateItemSchema = z.object({\n name: z.string(),\n isSystem: z.boolean(),\n fromVersion: z.string(),\n toVersion: z.string(),\n status: BulkUpdateItemStatusSchema,\n error: z.string().optional(),\n startedAtMs: z.number().optional(),\n completedAtMs: z.number().optional(),\n})\n\nconst BulkUpdatePhaseSchema = z.enum([\n 'regular',\n 'system',\n 'restarting',\n 'finalizing',\n])\n\nconst BulkUpdateStateSchema = z.object({\n id: z.string(),\n nodeId: z.string(),\n startedAtMs: z.number(),\n completedAtMs: z.number().optional(),\n total: z.number(),\n completed: z.number(),\n failed: z.number(),\n current: z.string().nullable(),\n phase: BulkUpdatePhaseSchema,\n cancelled: z.boolean(),\n items: z.array(BulkUpdateItemSchema).readonly(),\n})\n\nexport type BulkUpdateItemStatus = z.infer<typeof BulkUpdateItemStatusSchema>\nexport type BulkUpdateItem = z.infer<typeof BulkUpdateItemSchema>\nexport type BulkUpdatePhase = z.infer<typeof BulkUpdatePhaseSchema>\nexport type BulkUpdateState = z.infer<typeof BulkUpdateStateSchema>\n\n/**\n * One framework package row for the admin-UI \"System packages\" panel.\n * `latestVersion` is null when the npm lookup failed (offline / registry\n * unreachable) — the UI hides the Update button in that case.\n */\nconst FrameworkPackageStatusSchema = z.object({\n packageName: z.string(),\n currentVersion: z.string(),\n latestVersion: z.string().nullable(),\n hasUpdate: z.boolean(),\n /** Optional manifest description for the row tooltip. */\n description: z.string().optional(),\n})\n\n// LogStream entry — mirrors LoggingService output.\nconst LogStreamEntrySchema = z.object({\n timestamp: z.string(),\n level: z.string(),\n message: z.string(),\n scope: z.string().optional(),\n})\n\n// Generic log query result — admin-ui treats it as the same schema.\nconst LogQueryEntrySchema = z.unknown()\n\n// Custom action dispatcher — pass-through. Used by `bindAddonActions`\n// helper which downcasts to `(input: unknown) => Promise<unknown>` and\n// stamps the per-action types on its own.\nconst CustomActionInputSchema = z.object({\n addonId: z.string().min(1),\n action: z.string().min(1),\n input: z.unknown(),\n})\n\n/**\n * `addons` is a **hub-centric** cap: the hub hosts the single provider\n * and orchestrates per-node operations itself. The optional `nodeId`\n * on `listUpdates` / `updatePackage` / `forceRefresh` is DATA for the\n * hub provider's internal dispatcher (it reads/pushes to the target\n * agent via `$agent.*` Moleculer actions), NOT a routing hint for the\n * cap-router — agents host no `addons` provider of their own.\n *\n * `nodeIdMode: 'data'` therefore forwards `nodeId` to the local hub\n * provider intact instead of stripping it for generic node routing.\n * See `CapabilityDefinition.nodeIdMode` and `addon-settings.cap.ts`\n * for the same pattern.\n */\nexport const addonsCapability = {\n name: 'addons',\n scope: 'system',\n mode: 'singleton',\n nodeIdMode: 'data',\n methods: {\n // ── Listing ──────────────────────────────────────────────────────\n list: method(z.void(), z.array(AddonListItemSchema).readonly()),\n\n // ── Logs (query) ────────────────────────────────────────────────\n // Default auth (`protected`): authenticated users — including scoped\n // tokens with the right route-prefix scope. Reading logs isn't an\n // administrative action; install/restart/uninstall stay admin-only.\n getLogs: method(\n z.object({\n addonId: z.string(),\n limit: z.number().min(1).max(500).default(100),\n level: LogLevelSchema.optional(),\n }),\n z.array(LogQueryEntrySchema),\n ),\n\n // ── Packages ────────────────────────────────────────────────────\n listPackages: method(z.void(), z.array(InstalledPackageSchema).readonly()),\n installPackage: method(\n z.object({ packageName: z.string(), version: z.string().optional() }),\n InstallPackageResultSchema,\n { kind: 'mutation', auth: 'admin' },\n ),\n installFromWorkspace: method(\n z.object({ packageName: z.string() }),\n InstallPackageResultSchema,\n { kind: 'mutation', auth: 'admin' },\n ),\n isWorkspaceAvailable: method(z.void(), z.boolean()),\n listWorkspacePackages: method(z.void(), z.array(z.unknown()).readonly()),\n uninstallPackage: method(\n z.object({ packageName: z.string() }),\n z.unknown(),\n { kind: 'mutation', auth: 'admin' },\n ),\n reloadPackages: method(z.void(), ReloadPackagesResultSchema, {\n kind: 'mutation', auth: 'admin',\n }),\n // Note: original router declared `searchAvailable` input as optional\n // outer object. The cap codegen requires a stable input shape — we\n // make `query` optional inside a required object to preserve client\n // call shape (`{ query?: string }`).\n searchAvailable: method(\n z.object({ query: z.string().optional() }),\n z.array(SearchResultSchema),\n ),\n /**\n * Available package updates for a node. `nodeId` omitted (or\n * `'hub'`) checks the hub's own installed packages; an agent\n * `nodeId` checks that agent's installed roster against npm\n * (the hub does the npm lookups + diff — agents stay npm-free).\n */\n listUpdates: method(\n z.object({ nodeId: z.string().optional() }),\n z.array(PackageUpdateSchema).readonly(),\n { auth: 'admin' },\n ),\n /**\n * Update one package on a node. `nodeId` omitted (or `'hub'`)\n * installs on the hub via npm; an agent `nodeId` makes the hub\n * pack the resolved version and push the tarball to that agent\n * (`$agent.deploy` + `$agent.reload`) — agents need no npm runtime.\n */\n updatePackage: method(\n z.object({\n name: z.string().min(1),\n version: z.string().optional(),\n nodeId: z.string().optional(),\n }),\n z.unknown(),\n { kind: 'mutation', auth: 'admin' },\n ),\n /**\n * Roll back an addon to the version it had before the most recent\n * `updatePackage` call. The backup directory pointer is kept in the\n * central addon manifest until the post-update health-check\n * confirms the new install works (then it's cleared automatically),\n * so this only succeeds when the most recent update either failed\n * its restart or the user explicitly wants to revert.\n *\n * Returns `{ rolledBackTo: <version> }` on success, or\n * `{ rolledBackTo: null }` when there's no backup to roll back to\n * (caller can show a \"no backup available\" UI).\n */\n rollbackPackage: method(\n z.object({ name: z.string().min(1) }),\n z.object({ rolledBackTo: z.string().nullable() }),\n { kind: 'mutation', auth: 'admin' },\n ),\n /** Re-check updates for a node, bypassing any cache. `nodeId`\n * omitted (or `'hub'`) refreshes the hub; an agent `nodeId`\n * re-checks that agent's roster. */\n forceRefresh: method(\n z.object({ nodeId: z.string().optional() }),\n z.unknown(),\n { kind: 'mutation', auth: 'admin' },\n ),\n restartServer: method(\n z.object({ confirm: z.literal(true) }),\n z.unknown(),\n { kind: 'mutation', auth: 'admin' },\n ),\n /**\n * Most-recent restart marker (kind / packageName / from→to versions\n * / requestedBy / requestedAt). Returns `null` when this process\n * didn't boot from a tracked restart, or when the\n * post-boot retention window (5 min) has elapsed.\n *\n * Drives the admin-UI reconnect overlay's success toast — the\n * `system.restart-completed` event itself is fired before the\n * client has time to re-subscribe, so the client queries this on\n * first reconnect instead.\n */\n getLastRestart: method(\n z.void(),\n z.object({\n kind: z.enum(['framework-update', 'manual', 'system', 'framework-bulk-update']),\n packageName: z.string().optional(),\n fromVersion: z.string().optional(),\n toVersion: z.string().optional(),\n requestedBy: z.string().optional(),\n requestedAt: z.number(),\n }).nullable(),\n { auth: 'admin' },\n ),\n /**\n * Snapshot of the framework packages installed under the hub's\n * `<appRoot>/node_modules/`. Each row carries the currently\n * installed version and (best-effort) the latest version\n * available on npm. Drives the admin-UI \"System packages\" panel.\n *\n * Spec: docs/superpowers/specs/2026-05-14-framework-live-update-design.md\n */\n listFrameworkPackages: method(\n z.void(),\n z.array(FrameworkPackageStatusSchema).readonly(),\n { auth: 'admin' },\n ),\n /**\n * Cluster-wide capability-provider discovery. Returns the list of\n * `{ addonId, mode, isActive }` tuples for whatever addon(s)\n * currently provide the requested capability across the cluster.\n *\n * Why this lives on `addons` (and not on a `capabilities` cap of\n * its own): the hub's main-process `CapabilityRegistry` already\n * aggregates registrations from every forked group-runner and\n * remote agent via Moleculer event propagation — there's no\n * cross-process registry mirror to build, just an introspection\n * shim.\n *\n * Use this from addon code when you need to know whether another\n * addon has registered a specific cap (e.g. `tailscale-ingress`\n * checking `tailscale-client` is up before calling `tailscale\n * serve`). Don't reach for `ctx.capabilities.getCollectionEntries`\n * — that reads the LOCAL registry of the calling addon's group\n * runner and never sees providers in other processes. See\n * `CLAUDE.md` → Critical rules → ctx.api vs ctx.capabilities.\n */\n listCapabilityProviders: method(\n z.object({ capName: z.string().min(1) }),\n z.array(z.object({\n addonId: z.string(),\n mode: z.enum(['singleton', 'collection']),\n isActive: z.boolean(),\n })).readonly(),\n ),\n /**\n * Toggle a single collection-cap provider on/off. Generic write-side\n * counterpart of `listCapabilityProviders` — drives the per-provider\n * Enable/Disable affordance in admin pages (TURN servers, etc.)\n * without needing a bespoke orchestrator cap.\n *\n * Reaches the hub's `CapabilityRegistry` directly:\n * `enableCollectionProvider` / `disableCollectionProvider` flip the\n * registry-level `disabledProviders` set. `getCollectionEntries`\n * already filters disabled providers out, so a disabled provider\n * drops out of every collection aggregate immediately. Only valid\n * for `mode: 'collection'` caps — the registry no-ops + warns for\n * singletons.\n */\n setCapabilityProviderEnabled: method(\n z.object({\n capName: z.string().min(1),\n addonId: z.string().min(1),\n enabled: z.boolean(),\n }),\n z.object({ success: z.literal(true) }),\n { kind: 'mutation', auth: 'admin' },\n ),\n /**\n * Live-update one of the framework packages marked\n * `camstack.system: true` (`@camstack/types|kernel|core|sdk|ui-library`).\n * Runs `npm install --prefix <appRoot> <name>@<version> --no-save`,\n * writes a `.restart-pending` marker, emits `system.restarting`\n * and schedules a graceful process exit. The supervisor (Docker /\n * Electron / systemd) brings the hub back up; on first boot after\n * the restart the marker fires `system.restart-completed`.\n *\n * `version` defaults to `'latest'`. The allow-list of valid\n * `packageName` values is enforced server-side.\n *\n * Spec: docs/superpowers/specs/2026-05-14-framework-live-update-design.md\n */\n updateFrameworkPackage: method(\n z.object({\n packageName: z.string().min(1),\n version: z.string().optional(),\n deferRestart: z.boolean().optional(),\n }),\n UpdateFrameworkPackageResultSchema,\n { kind: 'mutation', auth: 'admin' },\n ),\n /**\n * Kicks off a server-side bulk update operation and returns the bulk\n * id immediately. The operation runs asynchronously; observe progress\n * via the `AddonsBulkUpdateProgress` event or `getBulkUpdateState`.\n * Items with `isSystem: true` use `deferRestart` — the hub restarts\n * ONCE at the end of the system phase, after all system packages are\n * installed.\n *\n * `items[].version` is REQUIRED — callers must pass the resolved\n * version from `listUpdates`. There is no `'latest'` default here\n * (unlike `updatePackage`) to guarantee deterministic bulk rolls.\n */\n startBulkUpdate: method(\n z.object({\n nodeId: z.string(),\n items: z.array(z.object({\n name: z.string(),\n version: z.string(),\n isSystem: z.boolean(),\n })).readonly(),\n }),\n z.object({ id: z.string() }),\n { kind: 'mutation', auth: 'admin' },\n ),\n /**\n * Returns the current state of a bulk update by id.\n * Returns `null` if the id is unknown or has been auto-cleaned\n * (5 minutes after `completedAt` the record is evicted from memory).\n */\n getBulkUpdateState: method(\n z.object({ id: z.string() }),\n BulkUpdateStateSchema.nullable(),\n { auth: 'admin' },\n ),\n /**\n * Cancels an in-flight bulk update. The update loop exits after the\n * currently-processing item completes — cancellation is not\n * instantaneous. Has no effect once the `restarting` phase has been\n * entered (the hub is already shutting down at that point).\n * Returns `{ cancelled: false }` if the id is unknown, the operation\n * has already completed, or the `restarting` phase is active.\n */\n cancelBulkUpdate: method(\n z.object({ id: z.string() }),\n z.object({ cancelled: z.boolean() }),\n { kind: 'mutation', auth: 'admin' },\n ),\n /**\n * Lists all currently active (non-completed) bulk updates.\n * If `nodeId` is provided, filters to only bulk updates targeting\n * that node. Useful for restoring an in-progress banner on a fresh\n * page load when the UI reconnects mid-operation.\n */\n listActiveBulkUpdates: method(\n z.object({ nodeId: z.string().optional() }),\n z.array(BulkUpdateStateSchema).readonly(),\n { auth: 'admin' },\n ),\n\n getVersions: method(\n z.object({ name: z.string() }),\n z.array(PackageVersionInfoSchema).readonly(),\n ),\n restartAddon: method(\n z.object({ addonId: z.string() }),\n RestartAddonResultSchema,\n { kind: 'mutation', auth: 'admin' },\n ),\n\n /**\n * Force-retry a failed addon NOW. Resets the retry counter so the\n * next failure starts from the 60s interval again. Used by the\n * \"Retry now\" button in the Addons admin page row + AlertCenter\n * alert action. Idempotent on healthy addons (no-op).\n */\n retryLoad: method(\n z.object({ packageName: z.string() }),\n z.object({ success: z.literal(true) }),\n { kind: 'mutation', auth: 'admin' },\n ),\n\n // ── Auto-update ─────────────────────────────────────────────────\n getAutoUpdateSettings: method(\n z.void(),\n AutoUpdateSettingsSchema,\n { auth: 'admin' },\n ),\n setAutoUpdateSettings: method(\n z.object({\n channel: ChannelSchema,\n intervalSeconds: z.number().min(300).max(86400).optional(),\n }),\n z.unknown(),\n { kind: 'mutation', auth: 'admin' },\n ),\n getAddonAutoUpdate: method(\n z.object({ addonId: z.string() }),\n AddonAutoUpdateSchema,\n { auth: 'admin' },\n ),\n setAddonAutoUpdate: method(\n z.object({ addonId: z.string(), channel: ChannelWithInheritSchema }),\n z.unknown(),\n { kind: 'mutation', auth: 'admin' },\n ),\n applyAutoUpdateToAll: method(\n z.object({ channel: ChannelSchema }),\n z.object({ success: z.literal(true) }),\n { kind: 'mutation', auth: 'admin' },\n ),\n\n // ── Custom action dispatcher ────────────────────────────────────\n // Generic dispatcher used by `bindAddonActions`. Per-action auth\n // is enforced inside the provider; the outer cap auth is\n // `protected` (any authenticated user) so individual addons can\n // gate their own actions to public/protected/admin/superAdmin.\n custom: method(CustomActionInputSchema, z.unknown(), { kind: 'mutation' }),\n\n // ── Log streaming ───────────────────────────────────────────────\n onAddonLogs: method(\n z.object({\n addonId: z.string(),\n level: LogLevelSchema.optional(),\n }),\n LogStreamEntrySchema,\n { kind: 'subscription' },\n ),\n },\n} as const satisfies CapabilityDefinition\n\nexport type IAddonsProvider = InferProvider<typeof addonsCapability>\n\nexport {\n AddonListItemSchema,\n InstalledPackageSchema,\n PackageUpdateSchema,\n PackageVersionInfoSchema,\n SearchResultSchema,\n AutoUpdateSettingsSchema,\n AddonAutoUpdateSchema,\n LogStreamEntrySchema,\n CustomActionInputSchema,\n LogLevelSchema,\n ChannelSchema,\n ChannelWithInheritSchema,\n UpdateFrameworkPackageResultSchema,\n FrameworkPackageStatusSchema,\n BulkUpdateItemStatusSchema,\n BulkUpdateItemSchema,\n BulkUpdatePhaseSchema,\n BulkUpdateStateSchema,\n}\n","/**\n * Capability definitions — Zod-schema-first, single source of truth.\n *\n * Each capability has its own .cap.ts file. Shared schemas live in schemas/.\n * TypeScript interfaces are inferred via z.infer<> — zero duplication.\n */\n\n// ── Pipeline capability roster ──────────────────────────────────────\n//\n// Canonical names of the capabilities considered \"pipeline-owning\":\n// anything under this list is an addon whose `getConfigSchema()` is\n// rendered on the Pipeline Defaults / per-device Detection tab, and\n// whose per-device settings changes trigger an `OrchestrationSettingsUpdated`\n// event so the orchestrator can restart detection.\n//\n// Consumers (backend + admin-ui) import this list instead of hardcoding\n// addon ids. Any new addon that declares one of these caps automatically\n// participates in the pipeline surface without code changes.\n\n/** Caps that show up in the canonical flow strip (decode → motion → detect → audio → analyze → notify). */\nexport const PIPELINE_FLOW_CAPABILITY_NAMES: readonly string[] = [\n 'decoder',\n 'motion-detection',\n 'pipeline-executor',\n 'audio-analyzer',\n 'pipeline-analytics',\n 'notification-output',\n]\n\n/**\n * Superset that also includes the control-plane capabilities (orchestrator\n * + runner). Used to enumerate addons whose settings belong to the pipeline\n * page — not just flow providers.\n */\nexport const PIPELINE_OWNER_CAPABILITY_NAMES: readonly string[] = [\n ...PIPELINE_FLOW_CAPABILITY_NAMES,\n 'pipeline-orchestrator',\n 'pipeline-runner',\n]\n\n// Core types\nexport type {\n CapabilityDefinition,\n CapabilityMethodSchema,\n CapabilityMethodKind,\n CapabilityMethodAuth,\n CapabilityMethodOptions,\n CapabilityEventSchema,\n InferProvider,\n InferNativeProvider,\n InferEvents,\n InferName,\n InferDeviceProxyCap,\n InferRuntimeState,\n DeviceSettingsContribution,\n ProviderKind,\n UiContribution,\n UiContributionKind,\n UiContributionRemote,\n DeviceConfigSpec,\n DeviceConfigUiSpec,\n DeviceConfigDerivedFormUi,\n DeviceConfigWidgetUi,\n} from './capability-definition.js'\nexport { method, event, expandCapMethods, DEVICE_SETTINGS_CONTRIBUTION_METHODS, DEVICE_STATUS_METHOD, isDeviceConfigCap } from './capability-definition.js'\n\nexport * from './custom-actions.js'\n\n// ── Shared Schemas ───────────────────────────────────────────────────\nexport {\n FrameInputSchema, BoundingBoxSchema, SpatialDetectionSchema,\n AudioChunkInputSchema, AudioLevelSchema, AudioClassificationLabelSchema,\n} from './schemas/detection-shared.js'\n\nexport {\n StreamSourceEntrySchema, StreamSourceSchema, EncodedPacketSchema, DecodedFrameSchema,\n FrameHandleSchema, FrameHandleFormatSchema,\n SubscribeFramesInputSchema, SubscribeFramesResultSchema,\n DecodedAudioChunkSchema,\n SubscribeAudioChunksInputSchema, SubscribeAudioChunksResultSchema,\n BrokerStatusSchema, BrokerStatsSchema,\n CamProfileSchema, CAM_PROFILE_ORDER,\n CamStreamKindSchema, CamStreamResolutionSchema,\n CameraStreamSchema, ProfileSlotStatusSchema, ProfileSlotSchema,\n ProfileRtspEntrySchema,\n makeProfileBrokerId, parseProfileBrokerId, selectAssignedProfileSlots, makeSourceBrokerId,\n} from './schemas/streaming-shared.js'\nexport type {\n CamProfile, CamStreamKind, CameraStream, ProfileSlotStatus, ProfileSlot,\n ProfileRtspEntry,\n FrameHandleFormat, SubscribeFramesInput, SubscribeFramesResult,\n DecodedAudioChunkWire, SubscribeAudioChunksInput, SubscribeAudioChunksResult,\n} from './schemas/streaming-shared.js'\n\n// ── Addon Settings ──────────────────────────────────────────────────\nexport {\n addonSettingsCapability, type IAddonSettingsProvider,\n SettingsSchemaWithValuesSchema, ConfigSectionWithValuesSchema, ConfigTabDeclarationSchema,\n SettingsPatchSchema, SettingsUpdateResultSchema,\n} from './addon-settings.cap.js'\n\n// ── Alerts ──────────────────────────────────────────────────────────\nexport { alertsCapability, AlertSeveritySchema, AlertStatusSchema, AlertSourceSchema, AlertSchema } from './alerts.cap.js'\nexport type { AlertSeverity, AlertStatus, Alert } from './alerts.cap.js'\n\n// ── Infrastructure ───────────────────────────────────────────────────\nexport { storageCapability, StorageLocationTypeSchema, type IStorageCapProvider } from './storage.cap.js'\nexport {\n storageProviderCapability,\n type IStorageProviderImpl,\n ProviderInfoSchema as StorageProviderInfoSchema,\n TestLocationResultSchema as StorageTestLocationResultSchema,\n BeginUploadInputSchema as StorageBeginUploadInputSchema,\n BeginUploadResultSchema as StorageBeginUploadResultSchema,\n WriteChunkInputSchema as StorageWriteChunkInputSchema,\n FinalizeUploadInputSchema as StorageFinalizeUploadInputSchema,\n AbortUploadInputSchema as StorageAbortUploadInputSchema,\n BeginDownloadInputSchema as StorageBeginDownloadInputSchema,\n BeginDownloadResultSchema as StorageBeginDownloadResultSchema,\n ReadChunkInputSchema as StorageReadChunkInputSchema,\n EndDownloadInputSchema as StorageEndDownloadInputSchema,\n} from './storage-provider.cap.js'\nexport {\n storageEvictableCapability,\n type IStorageEvictableProvider,\n type EvictableUsage,\n type EvictResult,\n} from './storage-evictable.cap.js'\nexport {\n backupCapability,\n type IBackupProvider,\n BackupEntrySchema,\n BackupDestinationInfoSchema,\n ArchiveEntrySchema,\n ArchiveManifestSchema,\n LocationStatSchema,\n} from './backup.cap.js'\nexport {\n settingsStoreCapability, type ISettingsStoreProvider, type SettingsStoreClient,\n QueryFilterSchema, SettingsRecordSchema,\n CollectionColumnSchema, CollectionIndexSchema,\n type CollectionColumn, type CollectionIndex,\n} from './settings-store.cap.js'\nexport { logDestinationCapability, LogEntrySchema, LogLevelSchema } from './log-destination.cap.js'\nexport { adminUiCapability } from './admin-ui.cap.js'\nexport type { IAdminUiProvider } from './admin-ui.cap.js'\nexport { ssoBridgeCapability, SsoBridgeClaimsSchema } from './sso-bridge.cap.js'\nexport type { ISsoBridgeProvider } from './sso-bridge.cap.js'\nexport {\n oauthIntegrationCapability,\n OauthIntegrationDescriptorSchema,\n type IOauthIntegrationProvider,\n type OauthIntegrationDescriptor,\n} from './oauth-integration.cap.js'\nexport { userPasskeysCapability, PasskeySummarySchema } from './user-passkeys.cap.js'\nexport type { IUserPasskeysProvider, PasskeySummary } from './user-passkeys.cap.js'\nexport { smtpProviderCapability, SendEmailInputSchema, SendEmailResultSchema, SmtpStatusSchema } from './smtp-provider.cap.js'\nexport type { ISmtpProvider } from './smtp-provider.cap.js'\n// Generic device-adoption cap.\nexport {\n deviceAdoptionCapability,\n ListCandidatesInputSchema as AdoptionListCandidatesInputSchema,\n ListCandidatesOutputSchema as AdoptionListCandidatesOutputSchema,\n GetCandidateInputSchema as AdoptionGetCandidateInputSchema,\n AdoptionFilterSchema,\n CandidateQueryFilterSchema,\n AdoptInputSchema as AdoptionAdoptInputSchema,\n AdoptResultSchema as AdoptionAdoptResultSchema,\n ReleaseInputSchema as AdoptionReleaseInputSchema,\n AdoptionStatusSchema,\n type IDeviceAdoptionProvider,\n type AdoptionStatus,\n type AdoptionFilter,\n} from './device-adoption.cap.js'\n\n// Unified broker registry cap — Phase E2a foundation. Long-term\n// replaces `mqtt-broker` (kept alongside for now during HA work).\nexport {\n brokerCapability,\n BrokerStatusEnum,\n BrokerInfoSchema as UnifiedBrokerInfoSchema,\n BrokerProviderInfoSchema,\n BrokerRegistryStatusSchema,\n BrokerTestConnectionResultSchema,\n BrokerPublishInputSchema,\n BrokerSubscribeInputSchema,\n BrokerSubscribeResultSchema,\n BrokerUnsubscribeInputSchema,\n BrokerGetStateInputSchema,\n BrokerAddInputSchema,\n type IBrokerProvider,\n type BrokerInfo as UnifiedBrokerInfo,\n type BrokerProviderInfo,\n type BrokerStatus as UnifiedBrokerStatus,\n} from './broker.cap.js'\nexport {\n mqttBrokerCapability,\n BrokerInfoSchema,\n BrokerConnectionDetailsSchema,\n AddBrokerInputSchema,\n StartEmbeddedInputSchema,\n MqttBrokerStatusSchema,\n} from './mqtt-broker.cap.js'\nexport type {\n IMqttBrokerProvider,\n BrokerInfo,\n BrokerConnectionDetails,\n} from './mqtt-broker.cap.js'\nexport type { BrokerStatus as MqttBrokerLiveStatus } from './mqtt-broker.cap.js'\nexport {\n deviceExportCapability,\n DeviceExportStatusSchema,\n ExportSetupSchema,\n ExportSetupFieldSchema,\n ExposedDeviceSchema,\n ExposeInputSchema as DeviceExportExposeInputSchema,\n UnexposeInputSchema as DeviceExportUnexposeInputSchema,\n} from './device-export.cap.js'\nexport type { IDeviceExportProvider } from './device-export.cap.js'\nexport { addonPagesCapability, AddonPageInfoSchema } from './addon-pages.cap.js'\nexport type { IAddonPagesAggregatorProvider } from './addon-pages.cap.js'\nexport { addonPagesSourceCapability, AddonPageDeclarationSchema } from './addon-pages-source.cap.js'\nexport type { IAddonPagesSourceProvider } from './addon-pages-source.cap.js'\nexport { addonWidgetsCapability, EnrichedWidgetMetadataSchema } from './addon-widgets.cap.js'\nexport type { IAddonWidgetsAggregatorProvider, EnrichedWidgetMetadata } from './addon-widgets.cap.js'\nexport {\n addonWidgetsSourceCapability,\n WidgetMetadataSchema,\n WidgetRemoteSchema,\n WidgetHostEnum,\n WidgetSizeEnum,\n} from './addon-widgets-source.cap.js'\nexport type { IAddonWidgetsSourceProvider, WidgetMetadata } from './addon-widgets-source.cap.js'\nexport { addonRoutesCapability } from './addon-routes.cap.js'\n\n// ── Streaming ────────────────────────────────────────────────────────\nexport {\n streamBrokerCapability,\n RtspRestreamEntrySchema,\n BrokerRtspClientSchema,\n BrokerDecodedClientSchema,\n BrokerAudioClientSchema,\n BrokerEncodedClientSchema,\n BrokerConsumerKindSchema,\n BrokerConsumerAttributionSchema,\n BrokerClientsSchema,\n PlaceholderReasonSchema,\n GetStreamWithCodecInputSchema,\n RtpSourceSchema,\n} from './stream-broker.cap.js'\nexport type {\n BrokerRtspClient,\n BrokerDecodedClient,\n BrokerAudioClient,\n BrokerEncodedClient,\n BrokerConsumerKind,\n BrokerConsumerAttribution,\n BrokerClients,\n PlaceholderReason,\n VideoCodecTarget,\n AudioCodecTarget,\n GetStreamWithCodecInput,\n RtpSource,\n} from './stream-broker.cap.js'\nexport {\n decoderCapability,\n DecoderSessionConfigSchema,\n HWACCEL_OPTIONS,\n DEFAULT_DECODER_HWACCEL_CONFIG,\n ShmRingStatsSchema,\n} from './decoder.cap.js'\nexport type {\n IDecoderCapProvider,\n HwAccelChoice,\n DecoderHwAccelConfig,\n ShmRingStats,\n} from './decoder.cap.js'\nexport { restreamerCapability, RegisteredStreamSchema, ExposedResourceSchema } from './restreamer.cap.js'\nexport { webrtcCapability, webrtcClientHintsSchema, type IWebrtcProvider, type WebrtcClientHints } from './webrtc.cap.js'\nexport { webrtcSessionCapability, type IWebrtcSessionProvider, type WebrtcStreamChoice, WebrtcStreamChoiceSchema, type WebrtcStreamTarget, WebrtcStreamTargetSchema } from './webrtc-session.cap.js'\nexport {\n cameraStreamsCapability,\n type ICameraStreamsProvider,\n type PickedCamStream,\n type StreamCodec,\n PickedCamStreamSchema,\n PickStreamRequirementsSchema,\n PickStreamPreferencesSchema,\n StreamCodecSchema,\n} from './camera-streams.cap.js'\nexport { streamingEngineCapability, StreamFormatSchema, StreamInfoSchema } from './streaming-engine.cap.js'\n\n// ── Detection ────────────────────────────────────────────────────────\nexport { motionDetectionCapability, MotionRegionSchema, MotionAnalysisResultSchema } from './motion-detection.cap.js'\nexport type { MotionRegion, MotionAnalysisResult, IMotionDetectionProvider } from './motion-detection.cap.js'\nexport {\n pipelineExecutorCapability,\n PipelineEngineChoiceSchema,\n PipelineDefaultStepSchema,\n DetectorOutputSchema,\n PipelineStepInputSchema,\n PipelineRunResultBridge,\n} from './pipeline-executor.cap.js'\nexport type { PipelineStepInputOutput } from './pipeline-executor.cap.js'\nexport { pipelineRunnerCapability, RunnerCameraConfigSchema, RunnerLocalLoadSchema, RunnerLocalMetricsSchema, MotionSourceEnum, MotionSourcesSchema, ReportMotionInputSchema, RunnerCameraDeviceUIFields } from './pipeline-runner.cap.js'\nexport type { MotionSource, MotionSources, ReportMotionInput } from './pipeline-runner.cap.js'\nexport { pipelineOrchestratorCapability, PipelineAssignmentSchema, DecoderAssignmentSchema, AgentLoadSummarySchema, GlobalMetricsSchema, CapabilityBindingsSchema } from './pipeline-orchestrator.cap.js'\nexport { OrchestratorMetricsSchema, CameraMetricsSchema, CameraMetricsWithDeviceIdSchema } from './schemas/orchestrator-metrics.js'\nexport {\n audioAnalyzerCapability,\n AUDIO_BACKEND_CHOICES,\n DEFAULT_AUDIO_ANALYZER_CONFIG,\n AudioAnalysisResultSchema,\n AudioAnalysisSettingsSchema,\n AudioClassificationResultSchema,\n} from './audio-analyzer.cap.js'\nexport type {\n IAudioAnalyzerProvider,\n AudioBackendChoice,\n AudioAnalyzerGlobalConfig,\n} from './audio-analyzer.cap.js'\nexport { audioAnalysisCapability, type IAudioAnalysisProvider } from './audio-analysis.cap.js'\nexport {\n audioCodecCapability,\n AudioCodecInfoSchema,\n AudioDecodeSessionConfigSchema,\n AudioEncodeSessionConfigSchema,\n AudioPcmChunkSchema,\n AudioEncodedChunkSchema,\n PcmSampleFormatSchema,\n type IAudioCodecCapProvider,\n} from './audio-codec.cap.js'\nexport { embeddingEncoderCapability, EmbeddingResultSchema, EmbeddingInfoSchema } from './embedding-encoder.cap.js'\nexport type { IEmbeddingEncoderProvider } from './embedding-encoder.cap.js'\n\n// ── Providers & Integrations ─────────────────────────────────────────\nexport { deviceProviderCapability, ProviderStatusSchema, DiscoveredDeviceSchema } from './device-provider.cap.js'\nexport {\n deviceManagerCapability,\n type IDeviceManagerProvider,\n DeviceInfoSchema,\n ConfigEntrySchema,\n} from './device-manager.cap.js'\nexport type { DeviceInfo, DeviceManagerApplyInitialMetaInput } from './device-manager.cap.js'\nexport { deviceStateCapability } from './device-state.cap.js'\nexport { authProviderCapability, AuthResultSchema } from './auth-provider.cap.js'\nexport { networkAccessCapability, NetworkEndpointSchema, NetworkAccessStatusSchema } from './network-access.cap.js'\nexport type { NetworkAccessStatus, NetworkEndpoint } from './network-access.cap.js'\nexport { turnProviderCapability, TurnServerSchema } from './turn-provider.cap.js'\nexport type { ITurnProvider } from './turn-provider.cap.js'\nexport { snapshotCapability, type ISnapshotOrchestrator, SnapshotImageSchema } from './snapshot.cap.js'\nexport { snapshotProviderCapability, type ISnapshotProvider } from './snapshot-provider.cap.js'\nexport { notificationOutputCapability, NotificationSchema } from './notification-output.cap.js'\nexport { advancedNotifierCapability, NotificationRuleSchema, NotificationHistoryEntrySchema } from './advanced-notifier.cap.js'\nexport type { IAdvancedNotifierProvider } from './advanced-notifier.cap.js'\nexport { detectionPipelineCapability, type IDetectionPipelineProvider } from './detection-pipeline.cap.js'\nexport { cameraPipelineConfigCapability, type ICameraPipelineConfigProvider } from './camera-pipeline-config.cap.js'\n// analysis-pipeline + analysis-data-persistence caps removed in P12b —\n// addon-pipeline-analytics owns post-detection refinement end-to-end\n// (Track + per-kind events + media) via its own single cap. See\n// pipeline-analytics.cap.ts. track-trail cap removed in P12a — trails\n// are `track.positions[]` on the Track schema.\nexport {\n pipelineAnalyticsCapability,\n type IPipelineAnalyticsProvider,\n type Track, type TrackState,\n type MotionEvent, type ObjectEvent, type AudioEvent,\n type MediaFile, type EventKind,\n TrackSchema, TrackStateSchema,\n MotionEventSchema, ObjectEventSchema, AudioEventSchema,\n MediaFileSchema, EventKindSchema, TrackedDetectionSchema,\n} from './pipeline-analytics.cap.js'\nexport { metricsProviderCapability, SystemMetricsSchema, type IMetricsProvider } from './metrics-provider.cap.js'\n// scene-intelligence cap removed in P12a — no provider was ever registered\n// and no admin UI/addon consumer. If scene queries come back, reintroduce\n// as part of the future embedding addon.\n\n\n// ── Device-Scoped Camera Caps ───────────────────────────────────────\nexport {\n ptzCapability,\n PtzPresetSchema,\n PtzPositionSchema,\n PtzStatusSchema,\n PtzMoveCommandSchema,\n type IPtzProvider,\n type PtzOptions,\n type PtzStatus,\n} from './ptz.cap.js'\nexport {\n ptzAutotrackCapability,\n PtzAutotrackSettingsSchema,\n PtzAutotrackStatusSchema,\n PtzAutotrackTargetOptionSchema,\n PtzAutotrackRuntimeStateSchema,\n type PtzAutotrackSettings,\n type PtzAutotrackStatus,\n type PtzAutotrackTargetOption,\n type PtzAutotrackRuntimeState,\n type IPtzAutotrackProvider,\n} from './ptz-autotrack.cap.js'\nexport { eventsCapability, EventItemSchema, type IEventsProvider } from './events.cap.js'\nexport {\n consumablesCapability,\n ConsumableItemSchema,\n ConsumablesStatusSchema,\n type ConsumableItem,\n type ConsumablesStatus,\n type IConsumablesProvider,\n} from './consumables.cap.js'\nexport {\n zonesCapability,\n ZoneSchema,\n ZoneKindEnum,\n PolygonPointSchema,\n type Zone,\n type ZoneKind,\n type PolygonPoint,\n type IZonesProvider,\n} from './zones.cap.js'\nexport {\n ZoneRuleSchema,\n ZoneRuleModeEnum,\n ZoneRulesArraySchema,\n type ZoneRule,\n type ZoneRuleMode,\n type ZoneRules,\n} from './schemas/zone-rule.js'\nexport {\n zoneRulesCapability,\n ZoneRuleStageEnum,\n type ZoneRuleStage,\n type IZoneRulesProvider,\n} from './zone-rules.cap.js'\nexport {\n zoneAnalyticsCapability,\n HistoryResolutionEnum,\n HistoryPointSchema,\n ZoneScopeBreakdownSchema,\n PerScopeBreakdownSchema,\n type CameraOccupancySnapshot,\n type ZoneScopeBreakdown,\n type PerScopeBreakdown,\n type HistoryPoint,\n type HistoryResolution,\n type IZoneAnalyticsProvider,\n} from './zone-analytics.cap.js'\nexport {\n audioMetricsCapability,\n AudioMetricsSnapshotSchema,\n AudioClassSummarySchema,\n AudioMetricsHistoryPointSchema,\n AudioMetricsHistorySchema,\n type AudioMetricsSnapshot,\n type AudioClassSummary,\n type AudioMetricsHistoryPoint,\n type AudioMetricsHistory,\n type IAudioMetricsProvider,\n} from './audio-metrics.cap.js'\nexport { motionCapability, MotionStatusSchema, MotionOnMotionChangedDataSchema, type MotionStatus, type MotionOnMotionChangedData, type IMotionProvider } from './motion.cap.js'\n// HA-targeted binary sensor cap family (Phase B1)\nexport { contactCapability, ContactStatusSchema, type ContactStatus, type IContactProvider } from './contact.cap.js'\nexport { floodCapability, FloodStatusSchema, type FloodStatus, type IFloodProvider } from './flood.cap.js'\nexport { smokeCapability, SmokeStatusSchema, type SmokeStatus, type ISmokeProvider } from './smoke.cap.js'\nexport { carbonMonoxideCapability, CarbonMonoxideStatusSchema, type CarbonMonoxideStatus, type ICarbonMonoxideProvider } from './carbon-monoxide.cap.js'\nexport { gasCapability, GasStatusSchema, type GasStatus, type IGasProvider } from './gas.cap.js'\nexport { tamperCapability, TamperStatusSchema, type TamperStatus, type ITamperProvider } from './tamper.cap.js'\nexport { vibrationCapability, VibrationStatusSchema, type VibrationStatus, type IVibrationProvider } from './vibration.cap.js'\nexport { connectivityCapability, ConnectivityStatusSchema, type ConnectivityStatus, type IConnectivityProvider } from './connectivity.cap.js'\nexport { binaryCapability, BinaryStatusSchema, type BinaryStatus, type IBinaryProvider } from './binary.cap.js'\n// HA-targeted numeric single-metric sensor caps (Phase B2)\nexport { temperatureSensorCapability, TemperatureSensorStatusSchema, type TemperatureSensorStatus, type ITemperatureSensorProvider } from './temperature-sensor.cap.js'\nexport { humiditySensorCapability, HumiditySensorStatusSchema, type HumiditySensorStatus, type IHumiditySensorProvider } from './humidity-sensor.cap.js'\nexport { ambientLightSensorCapability, AmbientLightSensorStatusSchema, type AmbientLightSensorStatus, type IAmbientLightSensorProvider } from './ambient-light-sensor.cap.js'\nexport { pressureSensorCapability, PressureSensorStatusSchema, type PressureSensorStatus, type IPressureSensorProvider } from './pressure-sensor.cap.js'\n// HA-targeted multi-metric + generic sensor caps (Phase B3)\nexport { powerMeterCapability, PowerMeterStatusSchema, type PowerMeterStatus, type IPowerMeterProvider } from './power-meter.cap.js'\nexport { airQualitySensorCapability, AirQualitySensorStatusSchema, type AirQualitySensorStatus, type IAirQualitySensorProvider } from './air-quality-sensor.cap.js'\nexport { numericSensorCapability, NumericSensorStatusSchema, type NumericSensorStatus, type INumericSensorProvider } from './numeric-sensor.cap.js'\nexport { enumSensorCapability, EnumSensorStatusSchema, EnumSensorDateTimeFormatSchema, type EnumSensorStatus, type EnumSensorDateTimeFormat, type IEnumSensorProvider } from './enum-sensor.cap.js'\nexport {\n recordingCapability,\n RecordingStatusSchema,\n RecordingRangeSchema,\n RecordingAvailabilitySchema,\n RecordingManifestSchema,\n RecordingDeviceUsageSchema,\n RecordingLocationUsageSchema,\n RecordingStorageUsageSchema,\n type RecordingStatus,\n type RecordingAvailability,\n type RecordingManifest,\n type RecordingDeviceUsage,\n type RecordingLocationUsage,\n type RecordingStorageUsage,\n type IRecordingProvider,\n} from './recording.cap.js'\nexport { deviceOpsCapability, RawStateResultSchema, type RawStateResult, type IDeviceOpsProvider } from './device-ops.cap.js'\nexport { batteryCapability, BatteryStatusSchema, type BatteryStatus, type IBatteryProvider } from './battery.cap.js'\nexport { deviceStatusCapability, DeviceStatusSchema, type DeviceStatus, type IDeviceStatusProvider } from './device-status.cap.js'\nexport { featureProbeCapability, FeatureProbeStatusSchema, type FeatureProbeStatus, type IFeatureProbeProvider } from './feature-probe.cap.js'\nexport { cameraCredentialsCapability, CameraCredentialsSchema, CameraCredentialsStatusSchema, type CameraCredentials, type CameraCredentialsStatus, type ICameraCredentialsProvider } from './camera-credentials.cap.js'\nexport { rebootCapability, type IRebootProvider } from './reboot.cap.js'\nexport {\n deviceDiscoveryCapability,\n DeviceDiscoveryStatusSchema,\n DiscoveredChildDeviceSchema,\n DiscoveredChildStatusSchema,\n type DeviceDiscoveryStatus,\n type DiscoveredChildDevice,\n type DiscoveredChildStatus,\n type IDeviceDiscoveryProvider,\n type IDeviceDiscoveryNativeProvider,\n} from './device-discovery.cap.js'\nexport { brightnessCapability, BrightnessStatusSchema, type BrightnessStatus, type IBrightnessProvider } from './brightness.cap.js'\n// HA-targeted actuator caps (Phase C1)\nexport {\n colorCapability, ColorStatusSchema,\n type ColorStatus, type ColorRgbTriplet, type ColorHsvTriplet, type ColorInput, type IColorProvider,\n} from './color.cap.js'\nexport {\n climateControlCapability, ClimateControlStatusSchema, HvacModeSchema,\n type ClimateControlStatus, type HvacMode, type IClimateControlProvider,\n} from './climate-control.cap.js'\n// HA-targeted actuator caps (Phase C2)\nexport {\n coverCapability, CoverStatusSchema, CoverStateSchema,\n type CoverStatus, type CoverState, type ICoverProvider,\n} from './cover.cap.js'\nexport {\n valveCapability, ValveStatusSchema, ValveStateSchema,\n type ValveStatus, type ValveState, type IValveProvider,\n} from './valve.cap.js'\nexport {\n humidifierCapability, HumidifierStatusSchema,\n type HumidifierStatus, type IHumidifierProvider,\n} from './humidifier.cap.js'\nexport {\n waterHeaterCapability, WaterHeaterStatusSchema,\n type WaterHeaterStatus, type IWaterHeaterProvider,\n} from './water-heater.cap.js'\n// Read-only display caps (HA weather / image)\nexport {\n weatherCapability, WeatherStatusSchema,\n type WeatherStatus, type IWeatherProvider,\n} from './weather.cap.js'\nexport {\n imageCapability, ImageStatusSchema,\n type ImageStatus, type IImageProvider,\n} from './image.cap.js'\nexport {\n lockControlCapability, LockControlStatusSchema, LockStateSchema,\n type LockControlStatus, type LockState, type ILockControlProvider,\n} from './lock-control.cap.js'\nexport {\n vacuumControlCapability, VacuumControlStatusSchema, VacuumStateSchema, TankStatusSchema,\n type VacuumControlStatus, type VacuumState, type TankStatus, type IVacuumControlProvider,\n} from './vacuum-control.cap.js'\nexport {\n lawnMowerControlCapability, LawnMowerControlStatusSchema, LawnMowerActivitySchema,\n type LawnMowerControlStatus, type LawnMowerActivity, type ILawnMowerControlProvider,\n} from './lawn-mower-control.cap.js'\nexport {\n fanControlCapability, FanControlStatusSchema, FanDirectionSchema,\n type FanControlStatus, type FanDirection, type IFanControlProvider,\n} from './fan-control.cap.js'\n// HA-targeted actuator caps (Phase C3)\nexport {\n controlCapability, ControlStatusSchema, ControlKindSchema,\n type ControlStatus, type ControlKind, type ControlSetValueInput, type IControlProvider,\n} from './control.cap.js'\nexport {\n notifierCapability, NotifierStatusSchema,\n type NotifierStatus, type NotifierPriority, type NotifierAction, type NotifierSupports,\n type NotifierSendInput, type NotifierSendResult, type INotifierProvider,\n} from './notifier.cap.js'\nexport {\n mediaPlayerCapability, MediaPlayerStatusSchema, MediaPlayerStateSchema, MediaPlayerRepeatSchema,\n type MediaPlayerStatus, type MediaPlayerState, type MediaPlayerRepeat, type MediaInfo,\n type IMediaPlayerProvider,\n} from './media-player.cap.js'\nexport {\n alarmPanelCapability, AlarmPanelStatusSchema, AlarmStateSchema, AlarmArmModeSchema,\n type AlarmPanelStatus, type AlarmState, type AlarmArmMode, type IAlarmPanelProvider,\n} from './alarm-panel.cap.js'\nexport {\n presenceCapability, PresenceStatusSchema,\n type PresenceStatus, type GpsLocation, type IPresenceProvider,\n} from './presence.cap.js'\nexport {\n scriptRunnerCapability, ScriptRunnerStatusSchema,\n type ScriptRunnerStatus, type IScriptRunnerProvider,\n} from './script-runner.cap.js'\nexport {\n automationControlCapability, AutomationControlStatusSchema,\n type AutomationControlStatus, type IAutomationControlProvider,\n} from './automation-control.cap.js'\n// HA-targeted actuator caps (Phase C4 — fire-only button)\nexport { buttonCapability, type IButtonProvider } from './button.cap.js'\nexport {\n motionTriggerCapability,\n MotionTriggerStatusSchema,\n MotionTriggerRuntimeStateSchema,\n type MotionTriggerStatus,\n type MotionTriggerRuntimeState,\n type IMotionTriggerProvider,\n} from './motion-trigger.cap.js'\nexport {\n osdCapability, OsdOverlaySchema, OsdOverlayKindEnum, OsdPositionEnum, OsdStatusSchema, OsdOverlayPatchSchema,\n type OsdOverlay, type OsdOverlayKind, type OsdPosition, type OsdStatus, type IOsdProvider,\n} from './osd.cap.js'\nexport { accessoriesCapability, AccessoriesStatusSchema, type AccessoriesStatus, type IAccessoriesProvider } from './accessories.cap.js'\nexport { switchCapability, SwitchStatusSchema, type SwitchStatus, type ISwitchProvider } from './switch.cap.js'\nexport {\n intercomCapability, IntercomAbilitySchema, IntercomStatusSchema,\n type IntercomAbility, type IntercomStatus, type IIntercomProvider,\n} from './intercom.cap.js'\nexport {\n doorbellCapability, DoorbellStatusSchema, DoorbellPressEventSchema,\n type DoorbellStatus, type DoorbellPressEvent, type IDoorbellProvider,\n} from './doorbell.cap.js'\nexport {\n eventEmitterCapability, EventFireSchema, EventEmitterStatusSchema,\n type EventFire, type EventEmitterStatus, type IEventEmitterProvider,\n} from './event-emitter.cap.js'\nexport {\n updateCapability, UpdateStatusSchema,\n type UpdateStatus, type IUpdateProvider,\n} from './update.cap.js'\nexport {\n nativeObjectDetectionCapability, NativeObjectClassEnum, NativeDetectionSchema, NativeObjectDetectionStatusSchema, NativeObjectDetectionRuntimeStateSchema,\n type NativeObjectClass, type NativeDetection, type NativeObjectDetectionStatus, type NativeObjectDetectionRuntimeState, type INativeObjectDetectionProvider,\n} from './native-object-detection.cap.js'\nexport {\n streamParamsCapability,\n StreamProfileSchema,\n StreamParamsStatusSchema,\n StreamParamsOptionsSchema,\n StreamProfilePatchSchema,\n StreamProfileConfigSchema,\n StreamProfileOptionsSchema,\n type StreamParamsStatus,\n type StreamParamsOptions,\n type StreamProfile,\n type StreamProfilePatch,\n type IStreamParamsProvider,\n} from './stream-params.cap.js'\nexport {\n streamCatalogCapability,\n CamStreamDescriptorSchema,\n type CamStreamDescriptor,\n type IStreamCatalogProvider,\n} from './stream-catalog.cap.js'\nexport {\n buildStreamParamsConfigSchema,\n parseStreamParamsFormPatch,\n STREAM_PROFILE_META,\n type StreamProfileMeta,\n} from './stream-params-config-schema.js'\nexport {\n motionZonesCapability,\n MotionZoneRegionSchema,\n MotionZoneStatusSchema,\n MotionZoneOptionsSchema,\n MotionZonePatchSchema,\n type MotionZoneRegion,\n type MotionZoneStatus,\n type MotionZoneOptions,\n type MotionZonePatch,\n type IMotionZonesProvider,\n} from './motion-zones.cap.js'\nexport {\n privacyMaskCapability,\n PrivacyMaskShapeSchema,\n PrivacyMaskRegionSchema,\n PrivacyMaskStatusSchema,\n PrivacyMaskOptionsSchema,\n PrivacyMaskPatchSchema,\n type PrivacyMaskShape,\n type PrivacyMaskRegion,\n type PrivacyMaskStatus,\n type PrivacyMaskOptions,\n type PrivacyMaskPatch,\n type IPrivacyMaskProvider,\n} from './privacy-mask.cap.js'\nexport {\n MaskPointSchema,\n MaskRectShapeSchema,\n MaskPolygonShapeSchema,\n MaskGridShapeSchema,\n MaskLineShapeSchema,\n MaskShapeSchema,\n MaskShapeKindSchema,\n MaskPolygonVerticesSchema,\n MaskGridDimsSchema,\n type MaskPoint,\n type MaskRectShape,\n type MaskPolygonShape,\n type MaskGridShape,\n type MaskLineShape,\n type MaskShape,\n type MaskShapeKind,\n type MaskPolygonVertices,\n type MaskGridDims,\n} from './mask-shape.js'\n\n\n// ── Platform probe (per-node hardware + inference backend scoring) ─\nexport {\n platformProbeCapability,\n type IPlatformProbeProvider,\n type HardwareEncoderId,\n type HardwareEncoderProbe,\n type HardwareEncoders,\n type HardwareDecodeAccels,\n} from './platform-probe.cap.js'\n\n// ── Local network (hub-only host interface enumeration) ────────────\nexport {\n localNetworkCapability,\n type ILocalNetworkProvider,\n type LocalInterface,\n type ConnectionEndpoint,\n} from './local-network.cap.js'\n\n// ── Mesh networks (Tailscale / Headscale / ZeroTier) ────────────────\n//\n// Per-provider access from the admin UI uses the `mesh-network`\n// collection cap's generic per-`addonId` routing — there is no\n// singleton facade cap.\nexport {\n meshNetworkCapability,\n MeshPeerSchema,\n MeshStatusSchema,\n type IMeshNetworkProvider,\n type MeshEndpoint,\n type MeshPeer,\n type MeshStatus,\n} from './mesh-network.cap.js'\n\n\n// ── User Management ─────────────────────────────────────────────────\nexport { userManagementCapability, type IUserManagementProvider } from './user-management.cap.js'\n\n// ── Core/Server Caps (Phase E — formerly hand-written core routers) ─\nexport {\n systemCapability, type ISystemProvider,\n FeatureManifestSchema, HealthStatusSchema, NetworkAddressSchema,\n} from './system.cap.js'\nexport {\n networkQualityCapability, type INetworkQualityProvider,\n StreamNetworkStatsSchema, ClientNetworkStatsSchema, DeviceNetworkStatsSchema,\n} from './network-quality.cap.js'\nexport { toastCapability, type IToastProvider, ToastSchema } from './toast.cap.js'\nexport {\n nodesCapability, type INodesProvider,\n TopologyNodeSchema, TopologyProcessSchema, TopologyServiceSchema,\n ClusterAddonStatusEntrySchema, ClusterAddonNodeDeploymentSchema,\n} from './nodes.cap.js'\nexport {\n integrationsCapability, type IIntegrationsProvider,\n IntegrationWithStateSchema, IntegrationLiteSchema,\n AvailableIntegrationTypeSchema, TestConnectionResultSchema,\n CreateIntegrationInputSchema, UpdateIntegrationInputSchema,\n DeleteIntegrationResultSchema,\n} from './integrations.cap.js'\nexport {\n addonsCapability, type IAddonsProvider,\n AddonListItemSchema, InstalledPackageSchema, PackageUpdateSchema,\n PackageVersionInfoSchema, SearchResultSchema, AutoUpdateSettingsSchema,\n AddonAutoUpdateSchema, LogStreamEntrySchema, CustomActionInputSchema,\n type BulkUpdateItemStatus,\n type BulkUpdateItem,\n type BulkUpdatePhase,\n type BulkUpdateState,\n} from './addons.cap.js'\nexport {\n UserSummarySchema, CreateUserInputSchema, UpdateUserInputSchema,\n ApiKeySummarySchema, CreateApiKeyInputSchema, CreateApiKeyResultSchema,\n ScopedTokenSummarySchema, CreateScopedTokenInputSchema, CreateScopedTokenResultSchema,\n} from './user-management.cap.js'\n\n// ── Strongly-typed readiness registry ───────────────────────────────\n//\n// `CapabilityName` is the exhaustive union of every registered capability's\n// `.name` literal. Passing it to `IReadinessRegistry<CapabilityName>` means\n// the compiler rejects any unknown string (e.g. a stale 'detection-pipeline'\n// instead of 'pipeline-executor') at call sites.\nimport type { addonSettingsCapability } from './addon-settings.cap.js'\nimport type { alertsCapability } from './alerts.cap.js'\nimport type { storageCapability } from './storage.cap.js'\nimport type { storageProviderCapability } from './storage-provider.cap.js'\nimport type { storageEvictableCapability } from './storage-evictable.cap.js'\nimport type { backupCapability } from './backup.cap.js'\nimport type { settingsStoreCapability } from './settings-store.cap.js'\nimport type { logDestinationCapability } from './log-destination.cap.js'\nimport type { adminUiCapability } from './admin-ui.cap.js'\nimport type { ssoBridgeCapability } from './sso-bridge.cap.js'\nimport type { userPasskeysCapability } from './user-passkeys.cap.js'\nimport type { smtpProviderCapability } from './smtp-provider.cap.js'\nimport type { mqttBrokerCapability } from './mqtt-broker.cap.js'\nimport type { brokerCapability } from './broker.cap.js'\nimport type { deviceAdoptionCapability } from './device-adoption.cap.js'\nimport type { deviceExportCapability } from './device-export.cap.js'\nimport type { addonPagesCapability } from './addon-pages.cap.js'\nimport type { addonPagesSourceCapability } from './addon-pages-source.cap.js'\nimport type { addonWidgetsCapability } from './addon-widgets.cap.js'\nimport type { addonWidgetsSourceCapability } from './addon-widgets-source.cap.js'\nimport type { addonRoutesCapability } from './addon-routes.cap.js'\nimport type { streamBrokerCapability } from './stream-broker.cap.js'\nimport type { decoderCapability } from './decoder.cap.js'\nimport type { restreamerCapability } from './restreamer.cap.js'\nimport type { webrtcCapability } from './webrtc.cap.js'\nimport type { webrtcSessionCapability } from './webrtc-session.cap.js'\nimport type { cameraStreamsCapability } from './camera-streams.cap.js'\nimport type { streamingEngineCapability } from './streaming-engine.cap.js'\nimport type { motionDetectionCapability } from './motion-detection.cap.js'\nimport type { pipelineExecutorCapability } from './pipeline-executor.cap.js'\nimport type { detectionPipelineCapability } from './detection-pipeline.cap.js'\nimport type { cameraPipelineConfigCapability } from './camera-pipeline-config.cap.js'\nimport type { pipelineRunnerCapability } from './pipeline-runner.cap.js'\nimport type { pipelineOrchestratorCapability } from './pipeline-orchestrator.cap.js'\nimport type { audioAnalyzerCapability } from './audio-analyzer.cap.js'\nimport type { audioAnalysisCapability } from './audio-analysis.cap.js'\nimport type { audioCodecCapability } from './audio-codec.cap.js'\nimport type { embeddingEncoderCapability } from './embedding-encoder.cap.js'\nimport type { deviceProviderCapability } from './device-provider.cap.js'\nimport type { deviceManagerCapability } from './device-manager.cap.js'\nimport type { deviceStateCapability } from './device-state.cap.js'\nimport type { authProviderCapability } from './auth-provider.cap.js'\nimport type { networkAccessCapability } from './network-access.cap.js'\nimport type { turnProviderCapability } from './turn-provider.cap.js'\nimport type { snapshotCapability } from './snapshot.cap.js'\nimport type { snapshotProviderCapability } from './snapshot-provider.cap.js'\nimport type { notificationOutputCapability } from './notification-output.cap.js'\nimport type { advancedNotifierCapability } from './advanced-notifier.cap.js'\nimport type { pipelineAnalyticsCapability } from './pipeline-analytics.cap.js'\nimport type { metricsProviderCapability } from './metrics-provider.cap.js'\nimport type { ptzCapability } from './ptz.cap.js'\nimport type { ptzAutotrackCapability } from './ptz-autotrack.cap.js'\nimport type { consumablesCapability } from './consumables.cap.js'\nimport type { rebootCapability } from './reboot.cap.js'\nimport type { deviceDiscoveryCapability } from './device-discovery.cap.js'\nimport type { brightnessCapability } from './brightness.cap.js'\nimport type { colorCapability } from './color.cap.js'\nimport type { climateControlCapability } from './climate-control.cap.js'\nimport type { coverCapability } from './cover.cap.js'\nimport type { valveCapability } from './valve.cap.js'\nimport type { humidifierCapability } from './humidifier.cap.js'\nimport type { waterHeaterCapability } from './water-heater.cap.js'\nimport type { weatherCapability } from './weather.cap.js'\nimport type { imageCapability } from './image.cap.js'\nimport type { lockControlCapability } from './lock-control.cap.js'\nimport type { vacuumControlCapability } from './vacuum-control.cap.js'\nimport type { lawnMowerControlCapability } from './lawn-mower-control.cap.js'\nimport type { fanControlCapability } from './fan-control.cap.js'\nimport type { controlCapability } from './control.cap.js'\nimport type { notifierCapability } from './notifier.cap.js'\nimport type { mediaPlayerCapability } from './media-player.cap.js'\nimport type { alarmPanelCapability } from './alarm-panel.cap.js'\nimport type { presenceCapability } from './presence.cap.js'\nimport type { scriptRunnerCapability } from './script-runner.cap.js'\nimport type { automationControlCapability } from './automation-control.cap.js'\nimport type { motionTriggerCapability } from './motion-trigger.cap.js'\nimport type { eventsCapability } from './events.cap.js'\nimport type { zonesCapability } from './zones.cap.js'\nimport type { zoneRulesCapability } from './zone-rules.cap.js'\nimport type { zoneAnalyticsCapability } from './zone-analytics.cap.js'\nimport type { audioMetricsCapability } from './audio-metrics.cap.js'\nimport type { motionCapability } from './motion.cap.js'\nimport type { contactCapability } from './contact.cap.js'\nimport type { floodCapability } from './flood.cap.js'\nimport type { smokeCapability } from './smoke.cap.js'\nimport type { carbonMonoxideCapability } from './carbon-monoxide.cap.js'\nimport type { gasCapability } from './gas.cap.js'\nimport type { tamperCapability } from './tamper.cap.js'\nimport type { vibrationCapability } from './vibration.cap.js'\nimport type { connectivityCapability } from './connectivity.cap.js'\nimport type { binaryCapability } from './binary.cap.js'\nimport type { temperatureSensorCapability } from './temperature-sensor.cap.js'\nimport type { humiditySensorCapability } from './humidity-sensor.cap.js'\nimport type { ambientLightSensorCapability } from './ambient-light-sensor.cap.js'\nimport type { pressureSensorCapability } from './pressure-sensor.cap.js'\nimport type { powerMeterCapability } from './power-meter.cap.js'\nimport type { airQualitySensorCapability } from './air-quality-sensor.cap.js'\nimport type { numericSensorCapability } from './numeric-sensor.cap.js'\nimport type { enumSensorCapability } from './enum-sensor.cap.js'\nimport type { recordingCapability } from './recording.cap.js'\nimport type { deviceOpsCapability } from './device-ops.cap.js'\nimport type { platformProbeCapability } from './platform-probe.cap.js'\nimport type { localNetworkCapability } from './local-network.cap.js'\nimport type { meshNetworkCapability } from './mesh-network.cap.js'\nimport type { userManagementCapability } from './user-management.cap.js'\nimport type { systemCapability } from './system.cap.js'\nimport type { networkQualityCapability } from './network-quality.cap.js'\nimport type { toastCapability } from './toast.cap.js'\nimport type { nodesCapability } from './nodes.cap.js'\nimport type { integrationsCapability } from './integrations.cap.js'\nimport type { addonsCapability } from './addons.cap.js'\nimport type { oauthIntegrationCapability } from './oauth-integration.cap.js'\nimport type { streamParamsCapability } from './stream-params.cap.js'\nimport type { streamCatalogCapability } from './stream-catalog.cap.js'\nimport type { motionZonesCapability } from './motion-zones.cap.js'\nimport type { privacyMaskCapability } from './privacy-mask.cap.js'\nimport type { IReadinessRegistry } from '../interfaces/readiness.js'\n\ntype AnyCapability =\n | typeof addonSettingsCapability\n | typeof alertsCapability\n | typeof storageCapability\n | typeof storageProviderCapability\n | typeof storageEvictableCapability\n | typeof backupCapability\n | typeof settingsStoreCapability\n | typeof logDestinationCapability\n | typeof adminUiCapability\n | typeof ssoBridgeCapability\n | typeof userPasskeysCapability\n | typeof smtpProviderCapability\n | typeof mqttBrokerCapability\n | typeof brokerCapability\n | typeof deviceAdoptionCapability\n | typeof deviceExportCapability\n | typeof addonPagesCapability\n | typeof addonPagesSourceCapability\n | typeof addonWidgetsCapability\n | typeof addonWidgetsSourceCapability\n | typeof addonRoutesCapability\n | typeof streamBrokerCapability\n | typeof decoderCapability\n | typeof restreamerCapability\n | typeof webrtcCapability\n | typeof webrtcSessionCapability\n | typeof cameraStreamsCapability\n | typeof streamingEngineCapability\n | typeof motionDetectionCapability\n | typeof pipelineExecutorCapability\n | typeof detectionPipelineCapability\n | typeof cameraPipelineConfigCapability\n | typeof pipelineRunnerCapability\n | typeof pipelineOrchestratorCapability\n | typeof audioAnalyzerCapability\n | typeof audioAnalysisCapability\n | typeof audioCodecCapability\n | typeof embeddingEncoderCapability\n | typeof deviceProviderCapability\n | typeof deviceManagerCapability\n | typeof deviceStateCapability\n | typeof authProviderCapability\n | typeof networkAccessCapability\n | typeof turnProviderCapability\n | typeof snapshotCapability\n | typeof snapshotProviderCapability\n | typeof notificationOutputCapability\n | typeof advancedNotifierCapability\n | typeof pipelineAnalyticsCapability\n | typeof metricsProviderCapability\n | typeof ptzCapability\n | typeof ptzAutotrackCapability\n | typeof consumablesCapability\n | typeof rebootCapability\n | typeof deviceDiscoveryCapability\n | typeof brightnessCapability\n | typeof colorCapability\n | typeof climateControlCapability\n | typeof coverCapability\n | typeof valveCapability\n | typeof humidifierCapability\n | typeof waterHeaterCapability\n | typeof weatherCapability\n | typeof imageCapability\n | typeof lockControlCapability\n | typeof vacuumControlCapability\n | typeof lawnMowerControlCapability\n | typeof fanControlCapability\n | typeof controlCapability\n | typeof notifierCapability\n | typeof mediaPlayerCapability\n | typeof alarmPanelCapability\n | typeof presenceCapability\n | typeof scriptRunnerCapability\n | typeof automationControlCapability\n | typeof motionTriggerCapability\n | typeof eventsCapability\n | typeof zonesCapability\n | typeof zoneRulesCapability\n | typeof zoneAnalyticsCapability\n | typeof audioMetricsCapability\n | typeof motionCapability\n | typeof contactCapability\n | typeof floodCapability\n | typeof smokeCapability\n | typeof carbonMonoxideCapability\n | typeof gasCapability\n | typeof tamperCapability\n | typeof vibrationCapability\n | typeof connectivityCapability\n | typeof binaryCapability\n | typeof temperatureSensorCapability\n | typeof humiditySensorCapability\n | typeof ambientLightSensorCapability\n | typeof pressureSensorCapability\n | typeof powerMeterCapability\n | typeof airQualitySensorCapability\n | typeof numericSensorCapability\n | typeof enumSensorCapability\n | typeof recordingCapability\n | typeof deviceOpsCapability\n | typeof platformProbeCapability\n | typeof localNetworkCapability\n | typeof meshNetworkCapability\n | typeof userManagementCapability\n | typeof systemCapability\n | typeof networkQualityCapability\n | typeof toastCapability\n | typeof nodesCapability\n | typeof integrationsCapability\n | typeof addonsCapability\n | typeof oauthIntegrationCapability\n | typeof streamParamsCapability\n | typeof streamCatalogCapability\n | typeof motionZonesCapability\n | typeof privacyMaskCapability\n\nexport type CapabilityName = AnyCapability['name']\n\nexport type ITypedReadinessRegistry = IReadinessRegistry<CapabilityName>\n"],"names":["z","StreamSourceEntrySchema","BrokerStatusSchema","DeviceType","DeviceFeature","ChargingStatus","DeviceRole","Feature","ModelFormatSchema","PipelineTemplateSchema","SettingsRecordSchema","LogLevelSchema","BrokerInfoSchema","TestConnectionResultSchema","AddonPageDeclarationSchema","ConfigEntrySchema","AdoptionListCandidatesInputSchema","AdoptionListCandidatesOutputSchema","AdoptionAdoptInputSchema","AdoptionAdoptResultSchema","AdoptionReleaseInputSchema"],"mappings":";;AAaO,MAAM,wBAAwBA,IAAAA,EAAE,KAAK,CAAC,aAAa,UAAU,QAAQ,CAAC;AAItE,MAAM,0BAA0BA,IAAAA,EAAE,OAAO;AAAA,EAC9C,SAASA,IAAAA,EAAE,OAAA;AAAA,EACX,MAAM;AAAA,EACN,UAAUA,IAAAA,EAAE,OAAA,EAAS,SAAA;AAAA,EACrB,WAAWA,IAAAA,EAAE,QAAA;AAAA,EACb,WAAWA,IAAAA,EAAE,OAAA;AAAA,EACb,OAAOA,IAAAA,EAAE,OAAA,EAAS,SAAA;AACpB,CAAC;AAIM,MAAM,0BAA0BA,IAAAA,EAAE,OAAO;AAAA,EAC9C,SAASA,IAAAA,EAAE,OAAA;AAAA,EACX,MAAMA,IAAAA,EAAE,MAAM,uBAAuB,EAAE,SAAA;AAAA,EACvC,SAASA,IAAAA,EAAE,MAAM,uBAAuB,EAAE,SAAA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