@camstack/addon-admin-ui 0.1.15 → 0.1.16

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.
Files changed (51) hide show
  1. package/dist/assets/{__mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.mjs-CKfGBI-Z.js → __mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.mjs-CeLhKMin.js} +1 -1
  2. package/dist/assets/{__mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.mjs_commonjs-proxy-CykPKLuU.js → __mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.mjs_commonjs-proxy-DXPQtD9p.js} +1 -1
  3. package/dist/assets/{__mfe_internal__admin_ui_host__loadShare___mf_0_trpc_mf_1_react_mf_2_query__loadShare__.mjs-xMlwAAY4.js → __mfe_internal__admin_ui_host__loadShare___mf_0_trpc_mf_1_react_mf_2_query__loadShare__.mjs-OcRSBqRe.js} +1 -1
  4. package/dist/assets/{__mfe_internal__admin_ui_host__loadShare___mf_0_trpc_mf_1_react_mf_2_query__loadShare__.mjs_commonjs-proxy-Clpxla3F.js → __mfe_internal__admin_ui_host__loadShare___mf_0_trpc_mf_1_react_mf_2_query__loadShare__.mjs_commonjs-proxy-GvBGLFI2.js} +1 -1
  5. package/dist/assets/{__mfe_internal__admin_ui_host__loadShare__react__loadShare__.mjs-B_akQFxJ.js → __mfe_internal__admin_ui_host__loadShare__react__loadShare__.mjs-Dl4u0xYE.js} +1 -1
  6. package/dist/assets/{__mfe_internal__admin_ui_host__loadShare__react__loadShare__.mjs_commonjs-proxy-BZBxNMgx.js → __mfe_internal__admin_ui_host__loadShare__react__loadShare__.mjs_commonjs-proxy-CSyOECfO.js} +1 -1
  7. package/dist/assets/{__mfe_internal__admin_ui_host__loadShare__react_mf_2_dom__loadShare__.mjs-CCRqQaXq.js → __mfe_internal__admin_ui_host__loadShare__react_mf_2_dom__loadShare__.mjs-CzO_Esxm.js} +1 -1
  8. package/dist/assets/{__mfe_internal__admin_ui_host__loadShare__react_mf_2_dom__loadShare__.mjs_commonjs-proxy-B5D3mvYP.js → __mfe_internal__admin_ui_host__loadShare__react_mf_2_dom__loadShare__.mjs_commonjs-proxy-xw6c6JeS.js} +1 -1
  9. package/dist/assets/{__mfe_internal__admin_ui_host__loadShare__react_mf_2_dom_mf_1_client__loadShare__.mjs-CRHuTm5p.js → __mfe_internal__admin_ui_host__loadShare__react_mf_2_dom_mf_1_client__loadShare__.mjs-DNpf5SLz.js} +1 -1
  10. package/dist/assets/{__mfe_internal__admin_ui_host__loadShare__react_mf_2_dom_mf_1_client__loadShare__.mjs_commonjs-proxy-XIS4Ck9-.js → __mfe_internal__admin_ui_host__loadShare__react_mf_2_dom_mf_1_client__loadShare__.mjs_commonjs-proxy-BEKtiDI3.js} +1 -1
  11. package/dist/assets/{_virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-D4TBsvIB.js → _virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-DlquBRmD.js} +1 -1
  12. package/dist/assets/auth-records-BEfan3dC.js +1 -0
  13. package/dist/assets/capability-router-map-B3jHfbHt.js +1 -0
  14. package/dist/assets/devices-CVfa8e_5.js +1 -0
  15. package/dist/assets/{hostInit-DpSCsYyA.js → hostInit-Bq0J4U4L.js} +1 -1
  16. package/dist/assets/index-B3BmQjhl.js +1 -0
  17. package/dist/assets/index-BYRl5bfb.js +1 -0
  18. package/dist/assets/index-Bftw8yZ0.js +80 -0
  19. package/dist/assets/index-BqEwAQt-.js +1098 -0
  20. package/dist/assets/index-ByDDdVKJ.css +1 -0
  21. package/dist/assets/index-C5--Sp9A.js +80 -0
  22. package/dist/assets/index-CJH_U_aT.js +1 -0
  23. package/dist/assets/index-CLnkxPD7.js +1 -0
  24. package/dist/assets/index-gZlh9vZc.js +1 -0
  25. package/dist/assets/index-o6URf7uT.js +1 -0
  26. package/dist/assets/index-otlbS_ZJ.js +1 -0
  27. package/dist/assets/{remoteEntry-0zDoMSWf.js → remoteEntry-qFyESaJr.js} +1 -1
  28. package/dist/assets/{schemas-BOzikgNT.js → schemas-XgIEoUz3.js} +1 -1
  29. package/dist/assets/{virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-BnGk9xo_.js → virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-cGbq1Btt.js} +2 -2
  30. package/dist/index.html +7 -8
  31. package/dist/mf-entry-bootstrap-0.js +2 -2
  32. package/dist/server/addon.js +11 -25
  33. package/dist/server/addon.js.map +1 -1
  34. package/dist/sw.js +1 -1
  35. package/package.json +4 -3
  36. package/dist/assets/capability-router-map-Bqwnkkax.js +0 -1
  37. package/dist/assets/devices-CFL4MLSo.js +0 -511
  38. package/dist/assets/index-BP0PcGIN.js +0 -1
  39. package/dist/assets/index-BQVATbZy.js +0 -5
  40. package/dist/assets/index-BZhZ3Jvf.js +0 -1
  41. package/dist/assets/index-BfdtdylV.js +0 -533
  42. package/dist/assets/index-BkJ1uzOh.js +0 -8420
  43. package/dist/assets/index-BuajxCgS.js +0 -1
  44. package/dist/assets/index-CKMQgnc3.js +0 -1
  45. package/dist/assets/index-DAq7g5_U.js +0 -1
  46. package/dist/assets/index-DRebE_bu.js +0 -22
  47. package/dist/assets/index-DUjRaULz.js +0 -1
  48. package/dist/assets/index-OcuNiGT5.js +0 -34
  49. package/dist/assets/index-R6tzT59K.css +0 -1
  50. package/dist/assets/index-pmj5N6Ix.js +0 -5
  51. package/dist/server/addon.d.ts +0 -12
@@ -1 +0,0 @@
1
- import{aH as C,aI as h,aJ as E,aK as T,aL as S,aM as M,aN as _,aO as L,aP as I,aQ as P,aR as y,aS as D,aT as A,aU as R,aV as v,aW as N,aa as k,aX as O,aY as V,aZ as w,a_ as x,a$ as B,b0 as F,b1 as Y,b2 as j,b3 as H,b4 as $,b5 as q,b6 as G,b7 as U,b8 as W,b9 as Z,ba as z,bb as X,bc as J,bd as K,be as Q,bf as ee,bg as ae,bh as te,bi as se,bj as re}from"./devices-CFL4MLSo.js";const c=[{id:"liveStream",label:"Live Stream",sources:{frigate:!0,scrypted:!0,rtsp:!0},adapterMethod:"getLiveStream"},{id:"multiResolution",label:"Multi-Resolution",sources:{frigate:!0,scrypted:!0,rtsp:!1},adapterMethod:"getResolutions"},{id:"motion",label:"Motion Detection",sources:{frigate:!1,scrypted:!0,rtsp:!1},adapterMethod:"getMotion"},{id:"objectDetection",label:"Object Detection",sources:{frigate:!1,scrypted:!0,rtsp:!1},adapterMethod:"getObjectDetections"},{id:"audioVolume",label:"Audio Level",sources:{frigate:!1,scrypted:!0,rtsp:!1},adapterMethod:"getAudioVolume"},{id:"audioVolumes",label:"Audio Volumes (dBFS)",sources:{frigate:!1,scrypted:!0,rtsp:!1},adapterMethod:"getAudioVolumes"},{id:"ptz",label:"PTZ Control",sources:{frigate:!1,scrypted:!0,rtsp:!1},adapterMethod:"getPTZ"},{id:"intercom",label:"Intercom (Mic)",sources:{frigate:!1,scrypted:!0,rtsp:!1},adapterMethod:"getIntercomSupport"},{id:"deviceStatus",label:"Device Status",sources:{frigate:!1,scrypted:!0,rtsp:!1},adapterMethod:"getStatus"},{id:"timeline",label:"Detection Timeline",sources:{frigate:!0,scrypted:!0,rtsp:!1},adapterMethod:"getCameraDayData"},{id:"clusteredTimeline",label:"Clustered Timeline",sources:{frigate:!0,scrypted:!0,rtsp:!1},requiresBackend:!0,adapterMethod:"getClusteredDayData"},{id:"detectionClasses",label:"Detection Classes",sources:{frigate:!0,scrypted:!0,rtsp:!1},adapterMethod:"getDetectionClasses"},{id:"videoClips",label:"Video Clips",sources:{frigate:!0,scrypted:!0,rtsp:!1},adapterMethod:"getVideoClips"},{id:"nvrPlayback",label:"NVR Playback",sources:{frigate:!0,scrypted:!0,rtsp:!1},adapterMethod:"getNvrPlaybackSupported"},{id:"nvrScrub",label:"NVR Scrub/Seek",sources:{frigate:!1,scrypted:!0,rtsp:!1},adapterMethod:"seekRecordingStream"},{id:"recordingThumbnail",label:"Recording Thumbnails",sources:{frigate:!0,scrypted:!0,rtsp:!1},adapterMethod:"getRecordingStreamThumbnail"},{id:"nvrSeekToLive",label:"Seek to Live",sources:{frigate:!1,scrypted:!0,rtsp:!1},adapterMethod:"seekNvrToLive"}];function le(s,e,n){const i=c.find(o=>o.id===s);return!(!i||!i.sources[e]||i.platforms&&i.platforms[n]===!1)}function ie(s){return c.filter(e=>e.sources[s])}function oe(){return c.filter(s=>s.requiresBackend)}function de(s,e,n){if(s.length===0)return null;const i=e.viewportWidth*e.viewportHeight*(e.pixelRatio??1),o=e.bandwidthMbps??100,f=e.packetLoss??0,m=e.rttMs??50;let r="high";e.maxResolution==="low"||e.isCellular||o<1||f>.05?r="low":e.maxResolution==="medium"||o<5||i<5e5||m>200?r="medium":(e.maxResolution==="high"||i>2e6)&&(r="high");const b={main:"high",sub:"medium",ext:"low"},g=n??"native",p=s.map(a=>{let t=0;const d=b[a.profile]??"medium";if(d===r?t+=100:(r==="high"&&d==="medium"||r==="medium"&&d==="high"||r==="medium"&&d==="low"||r==="low"&&d==="medium")&&(t+=50),a.transport===g?t+=30:a.transport==="native"?t+=20:a.transport==="rtsp"?t+=15:a.transport==="rtmp"&&(t+=10),a.metadata?.width&&a.metadata?.height){const u=a.metadata.width*a.metadata.height/Math.max(i,1);u>=.8&&u<=2?t+=25:u>=.5&&u<=3&&(t+=15),u>4&&o<10&&(t-=20)}return a.metadata?.codec&&(o<5&&a.metadata.codec.includes("265")&&(t+=10),o>=10&&a.metadata.codec.includes("264")&&(t+=5)),{...a,score:t,targetTier:r}});p.sort((a,t)=>t.score-a.score);const l=p[0];return{streamName:l.streamName,profile:l.profile,transport:l.transport,label:l.label,metadata:l.metadata,reason:`${l.targetTier} quality → ${l.profile}/${l.transport} (score: ${l.score})`}}function ue(s,e){return e?10:s.isCellular||(s.packetLoss??0)>.02?15:30}const pe=Object.freeze(Object.defineProperty({__proto__:null,DEFAULT_ENABLED_CLASSES:C,DetectionClass:h,ELIGIBLE_HA_DOMAINS:E,ELIGIBLE_HA_DOMAINS_SET:T,ELIGIBLE_SCRYPTED_DEVICE_TYPES:S,ELIGIBLE_SCRYPTED_DEVICE_TYPES_SET:M,FEATURE_MATRIX:c,HA_DOMAIN_TYPE_MAP:_,RAW_TO_CANONICAL:L,SCRYPTED_TYPE_TO_CANONICAL:I,System:P,TIMELINE_PRESET_ALL:y,TIMELINE_PRESET_CRITICAL:D,TIMELINE_PRESET_IMPORTANT:A,animalClasses:R,audioClasses:v,audioLabelClasses:N,createSystem:k,defaultDetectionClasses:O,detectionClassesDefaultMap:V,doorbellClasses:w,faceClasses:x,getBackendRequiredFeatures:oe,getCanonicalDeviceType:B,getClassesForTimelinePreset:F,getNextEvalInterval:ue,getParentClass:Y,getParentDetectionClass:j,getSourceFeatures:ie,isAnimalClassname:H,isAudioClassname:$,isDoorbellClassname:q,isFaceClassname:G,isFeatureAvailable:le,isLabelDetection:U,isMotionClassname:W,isPackageClassname:Z,isPersonClassname:z,isPlateClassname:X,isSensorLabelClassname:J,isVehicleClassname:K,licensePlateClasses:Q,motionClasses:ee,packageClasses:ae,personClasses:te,selectOptimalStream:de,sensorLabelClasses:se,vehicleClasses:re},Symbol.toStringTag,{value:"Module"}));export{pe as s};
@@ -1 +0,0 @@
1
- import{o as i,a as l,_ as p,s as e,r as b,l as I,n as a,b as v,c as T,d as f,u as S,e as Ve,f as M,g as gt,h as R,t as Ma,i as Ri,Z as Ei,j as qi,k as xi,m as Bi,p as Oi,q as Ni,v as Ta,w as _i,x as zi,y as Ra,z as Fi}from"./schemas-BOzikgNT.js";var Li=["onnx","coreml","openvino","tflite","pt"],Ui="main-group",Hi="hub-only";function we(t){return{placement:t.execution?.placement??Hi,group:t.execution?.group??Ui}}function zc(t){const r=we(t).placement;return r==="any-node"||r==="agent-only"}function Fc(t){return we(t).placement==="agent-only"}function Lc(t){return we(t).group}function Uc(t){return we(t).placement}var Wi=(t=>(t.SystemBoot="system.boot",t.SystemAddonsReady="system.addons-ready",t.SystemRestarting="system.restarting",t.SystemReadyState="system.ready-state",t.AddonStarted="addon.started",t.AddonStopped="addon.stopped",t.AddonRestarted="addon.restarted",t.AddonUpdated="addon.updated",t.AddonInstalled="addon.installed",t.AddonUninstalled="addon.uninstalled",t.AddonCrashed="addon.crashed",t.AddonError="addon.error",t.AddonPageReady="addon.page-ready",t.AddonWidgetReady="addon.widget-ready",t.DeviceRegistered="device.registered",t.DeviceUnregistered="device.unregistered",t.DeviceEnabled="device.enabled",t.DeviceDisabled="device.disabled",t.DeviceSettingsUpdated="device.settings-updated",t.DeviceBindingsChanged="device.bindings-changed",t.DeviceMetaChanged="device.meta-changed",t.DeviceStreamsRegistered="device.streams-registered",t.IntegrationEnabled="integration.enabled",t.IntegrationDisabled="integration.disabled",t.IntegrationDeleted="integration.deleted",t.ProviderStarted="provider.started",t.ProviderStopped="provider.stopped",t.ProcessCrashed="process.crashed",t.ProcessRestartScheduled="process.restart_scheduled",t.ProcessRestarted="process.restarted",t.RecordingStarted="recording.started",t.RecordingStopped="recording.stopped",t.RecordingError="recording.error",t.RecordingHealthDegraded="recording.health.degraded",t.RecordingStorageCritical="recording.storage.critical",t.RecordingSegmentWritten="recording.segment.written",t.RecordingPolicyFallback="recording.policy.fallback",t.RecordingRetentionCompleted="recording.retention.completed",t.DetectionEvent="detection.event",t.SessionTrackNew="session.track.new",t.SessionTrackExpired="session.track.expired",t.BenchmarkProgress="benchmark.progress",t.PlatformProbePhase="platform-probe.phase",t.PipelineProgress="pipeline.progress",t.PipelineTrace="pipeline.trace",t.PipelineInferenceResult="pipeline.inference-result",t.PipelineCameraAssigned="pipeline.camera-assigned",t.PipelineCameraUnassigned="pipeline.camera-unassigned",t.PipelineCameraUpdated="pipeline.camera-updated",t.PipelineRunnerLoadSnapshot="pipeline.runner-load-snapshot",t.PipelineCameraMetricsSnapshot="pipeline.camera-metrics-snapshot",t.StreamBrokerMetricsSnapshot="stream-broker.metrics-snapshot",t.StreamBrokerOnCamStreamDemand="stream-broker.onCamStreamDemand",t.StreamBrokerOnCamStreamIdle="stream-broker.onCamStreamIdle",t.StreamBrokerOnRequestStreamSourceRefresh="stream-broker.onRequestStreamSourceRefresh",t.DeviceStateChanged="device.state-changed",t.BatteryOnStatusChanged="battery.onStatusChanged",t.DoorbellOnPressed="doorbell.onPressed",t.PipelineEngineMetricsSnapshot="pipeline.engine-metrics-snapshot",t.ClusterTopologySnapshot="cluster.topology-snapshot",t.MetricsNodeResourcesSnapshot="metrics.node-resources-snapshot",t.MetricsNodeProcessesSnapshot="metrics.node-processes-snapshot",t.CapabilityBindingChanged="capability.binding-changed",t.ModelDownloadProgress="model.download.progress",t.AgentRegistered="agent.registered",t.AgentUnregistered="agent.unregistered",t.AgentOnline="agent.online",t.AgentOffline="agent.offline",t.WorkerOnline="worker.online",t.WorkerOffline="worker.offline",t.AgentTaskDispatched="agent.task.dispatched",t.AgentTaskAssigned="agent.task.assigned",t.AgentTrpcConnected="agent.trpc.connected",t.AgentWsConnected="agent.ws.connected",t.AgentWsDisconnected="agent.ws.disconnected",t.AgentBackupActivated="agent.backup.activated",t.OrchestrationSettingsUpdated="orchestration.settings-updated",t.PipelineAgentHwaccelChanged="pipeline.agent-hwaccel-changed",t.MotionAnalysis="detection.motion-analysis",t.MotionZonesRaw="detection.motion-zones-raw",t.MotionOnMotionChanged="motion.on-motion-changed",t.DetectionResult="detection.result",t.DetectionRaw="detection.raw",t.DetectionCameraNative="detection.camera-native",t.PipelineAudioInferenceResult="pipeline.audio-inference-result",t.DetectionPhaseTransition="detection.phase-transition",t.ProviderMotion="provider.motion",t.ProviderDetection="provider.detection",t.EnrichmentEmbeddingStored="enrichment.embedding.stored",t.EnrichmentSceneStateChanged="enrichment.scene.state-changed",t.EnrichmentActivitySummary="enrichment.activity.summary",t.PipelineAnalyticsTrackStarted="pipeline-analytics.track-started",t.PipelineAnalyticsTrackEnded="pipeline-analytics.track-ended",t.PipelineAnalyticsDetectionEvent="pipeline-analytics.detection-event",t.PipelineAnalyticsFrameTracked="pipeline-analytics.frame-tracked",t.FrigateLiveEvent="frigate.live-event",t.CameraStreamsProfileSlotsChanged="camera-streams.onProfileSlotsChanged",t.StreamOnline="stream.online",t.StreamOffline="stream.offline",t.NetworkTunnelStarted="network.tunnel.started",t.NetworkTunnelStopped="network.tunnel.stopped",t.BackupCompleted="backup.completed",t.BackupRestored="backup.restored",t.NotificationDispatched="notification.dispatched",t.NotificationFailed="notification.failed",t.DeviceUpdated="device.updated",t.DeviceOnline="device.online",t.DeviceOffline="device.offline",t.DeviceAwake="device.awake",t.DeviceSleeping="device.sleeping",t.RetentionCleanup="retention.cleanup",t))(Wi||{}),$i=[{id:"overview",label:"Overview",icon:"layout-dashboard",order:-10},{id:"general",label:"General",icon:"settings",order:0},{id:"image",label:"Image",icon:"image",order:5},{id:"light",label:"Light",icon:"lightbulb",order:7},{id:"motion",label:"Motion",icon:"activity",order:10},{id:"audio",label:"Audio",icon:"mic",order:12},{id:"alarms",label:"Alarms",icon:"bell-ring",order:13},{id:"snapshot",label:"Snapshot",icon:"camera",order:15},{id:"osd",label:"OSD",icon:"type",order:18},{id:"stream-broker",label:"Stream Broker",icon:"radio",order:20},{id:"streaming",label:"Streaming",icon:"video",order:35},{id:"pipeline",label:"Detection Pipeline",icon:"cpu",order:39},{id:"zones",label:"Detection",icon:"shapes",order:38},{id:"live-stats",label:"Live Stats",icon:"activity",order:39},{id:"recording",label:"Recording",icon:"circle-dot",order:40},{id:"engine",label:"Inference Engine",icon:"zap",order:41},{id:"scheduler",label:"Scheduler",icon:"list-checks",order:42},{id:"decoder",label:"Decoder",icon:"film",order:43},{id:"notifications",label:"Notifications",icon:"bell",order:50},{id:"network",label:"Network",icon:"globe",order:60},{id:"storage",label:"Storage",icon:"hard-drive",order:70},{id:"advanced",label:"Advanced",icon:"wrench",order:100}],Hc=Object.fromEntries($i.map(t=>[t.id,t]));function Gi(t){return t.type==="separator"||t.type==="info"||t.type==="button"||t.type==="object-array"||t.type==="widget"}function zt(t,r){return{...t.tabs?{tabs:[...t.tabs]}:{},sections:t.sections.map(n=>({...n,fields:n.fields.map(c=>Ke(c,r))}))}}function Ke(t,r){if(Gi(t))return t;if(t.type==="group"){const g=t.fields.map(k=>Ke(k,r));return{...t,fields:g}}if(t.type==="sub-tabs"){const g=t.tabs.map(k=>({...k,fields:k.fields.map(C=>Ke(C,r))}));return{...t,tabs:g}}const n=t.key,c=Object.prototype.hasOwnProperty.call(r,n)?r[n]:void 0,u=t.default;if(t.multiple){const g=Array.isArray(c)?c:c!=null?[c]:[],A=t.multiple.itemDefault!==void 0?t.multiple.itemDefault:u!==void 0?u:ji(t)==="string"?"":null,k=Math.max(t.multiple.min,g.length),C=[];for(let w=0;w<k;w++)C.push(w<g.length?g[w]:A);return{...t,value:C}}const h=c!==void 0?c:u!==void 0?u:null,y=t.type==="textarea"&&t.isJson&&h!==null&&typeof h=="object"?JSON.stringify(h,null,2):h;return{...t,value:y}}function ji(t){switch(t.type){case"text":case"textarea":case"password":case"color":case"probe":return"string";case"number":case"slider":return"number";case"boolean":return"boolean";default:return"other"}}function Wc(t,r){return t.category===r}function Ea(t,r,n){return{id:typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():Math.random().toString(36).slice(2),timestamp:new Date,source:r,category:t,data:n}}function Vi(t,r){const n=r.ts??Date.now();t.emit(Ea("system.ready-state",{type:"capability",id:r.capName,nodeId:r.sourceNodeId},{capName:r.capName,scope:r.scope,state:r.state,generation:r.generation,sourceNodeId:r.sourceNodeId,ts:n}))}var Ki=class{_ctx=null;_config;_readinessGeneration=typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():Math.random().toString(36).slice(2,14);_registeredCapNames=[];defaults;constructor(t){this.defaults=t,this._config={...t}}get autoEmitReadiness(){return!0}get ctx(){if(!this._ctx)throw new Error(`${this.constructor.name}: ctx accessed before initialize()`);return this._ctx}get ctxIfReady(){return this._ctx}get config(){return this._config}async initialize(t){this._ctx=t,await this.resolveConfig();const r=await this.onInitialize();this.emitLifecycle("addon.started");const n=Zi(r),c=n&&"providers"in n&&n.providers?n.providers:[];return this._registeredCapNames=c.map(u=>u.capability.name),n}postBrokerStart(){this.autoEmitReadiness&&this._registeredCapNames.length>0&&this.emitReadinessForProviders("ready")}async onHubReachable(){}async shutdown(){this.emitLifecycle("addon.stopped"),this.autoEmitReadiness&&this.emitReadinessForProviders("down"),await this.onShutdown();for(const t of this._subscriptions)t();this._subscriptions=[],this._ctx=null}async onShutdown(){}async onConfigChanged(){}field(t){return t}schema(t){return t}globalSettingsSchema(){return null}deviceSettingsSchema(){return null}async getGlobalSettings(t){const r=this.globalSettingsSchema();if(!r)return{sections:[]};const n=await this._ctx?.settings?.readAddonStore()??{};return zt(r,t?{...n,...t}:n)}async updateGlobalSettings(t){await this._ctx?.settings?.writeAddonStore(t),await this.resolveConfig(),await this.onConfigChanged(),this.emitLifecycle("addon.updated",{level:"global"}),this.maybeAutoRestart(t,this.globalSettingsSchema())}maybeAutoRestart(t,r){if(!r)return;const n=new Set;for(const y of r.sections)for(const m of y.fields)m.type==="separator"||m.type==="info"||m.requiresRestart&&n.add(m.key);if(n.size===0||!Object.keys(t).some(y=>n.has(y)))return;const u=this._ctx;if(!u)return;const h=u.id;setImmediate(()=>{u.api.addons?.restartAddon?.mutate({addonId:h}).then(()=>{u.logger.info("addon auto-restart triggered by restart-required setting change",{meta:{changedFields:Object.keys(t).filter(m=>n.has(m))}})}).catch(m=>{u.logger.error("addon auto-restart failed",{meta:{error:m instanceof Error?m.message:String(m)}})})})}async getDeviceSettings(t){const r=this.deviceSettingsSchema();if(!r)return{sections:[]};const n=await this._ctx?.settings?.readDeviceStore(t)??{};return zt(r,n)}async updateDeviceSettings(t,r){await this._ctx?.settings?.writeDeviceStore(t,r)}_subscriptions=[];watchCapability(t,r){const n=Array.isArray(t)?t:[t],c=new Set(n);this.subscribe({category:"system.ready-state"},u=>{const h=u.data;if(typeof h.capName!="string"||!c.has(h.capName)||h.scope?.type!=="node")return;const y=h.scope.nodeId;if(typeof y!="string"||y.length===0)return;const m=h.capName;h.state==="down"?r.onDown?.(y,m):h.state==="ready"&&r.onReady?.(y,m)})}subscribe(t,r){const n=this.ctx.eventBus.subscribe(t,r);this._subscriptions.push(n)}emitLifecycle(t,r){try{this._ctx?.eventBus.emit({id:`${this._ctx.id}-${Date.now()}`,timestamp:new Date,source:{type:"addon",id:this._ctx.id,nodeId:this._ctx.kernel.localNodeId??"hub"},category:t,data:r??{}})}catch{}}emitReadinessForProviders(t){const r=this._ctx;if(!r||this._registeredCapNames.length===0)return;const n=r.kernel?.localNodeId??"hub",c=n.includes("/")?n.split("/")[0]:n;for(const u of this._registeredCapNames)try{Vi(r.eventBus,{capName:u,scope:{type:"node",nodeId:c},state:t,generation:this._readinessGeneration,sourceNodeId:c})}catch{}}async resolveModelsDir(){return this.ctx.api.storage.resolve.query({location:"models",relativePath:""}).catch(()=>"camstack-data/models")}get capabilities(){return this.ctx.capabilities??null}async resolveConfig(){const t=await this._ctx?.settings?.readAddonStore()??{},r={...this.defaults};for(const n of Object.keys(this.defaults)){const c=t[n];if(c!=null){const u=typeof this.defaults[n];typeof c===u&&(r[n]=c)}}this._config=r}};function Zi(t){if(t!=null)return Array.isArray(t)?{providers:t}:t}var Yi=class extends Error{capName;scope;waitedMs;constructor(t,r,n){super(`Timed out waiting for ${t} (${ne(r)}) to become ready after ${n}ms`),this.name="ReadinessTimeoutError",this.capName=t,this.scope=r,this.waitedMs=n}};function Me(t,r){return`${t}|${ne(r)}`}function ne(t){switch(t.type){case"global":return"global";case"node":return`node:${t.nodeId}`;case"device":return`device:${t.deviceId}`}}function Te(t,r){return t.type!==r.type?!1:t.type==="global"||r.type==="global"?!0:t.type==="node"&&r.type==="node"?t.nodeId===r.nodeId:t.type==="device"&&r.type==="device"?t.deviceId===r.deviceId:!1}var $c=class{bus;sourceNodeId;logger;now;generation;snapshot=new Map;subscriptions=new Set;unsubscribeBus;unsubscribeAgentOffline;constructor(t){if(this.bus=t.eventBus,this.sourceNodeId=t.sourceNodeId,this.logger=t.logger,this.now=t.now??(()=>Date.now()),this.generation=t.generation??Qi(),this.unsubscribeBus=this.bus.subscribe({category:"system.ready-state"},r=>this.ingest(r.data)),this.unsubscribeAgentOffline=this.bus.subscribe({category:"agent.offline"},r=>this.synthesizeDownForNode(r.data.agentId)),typeof this.bus.getRecent=="function")try{const r=this.bus.getRecent({category:"system.ready-state"});for(const n of r)this.ingest(n.data)}catch{}}close(){this.unsubscribeBus(),this.unsubscribeAgentOffline(),this.subscriptions.clear()}get(t,r){return this.snapshot.get(Me(t,r))??null}getSnapshotForTransport(){return Array.from(this.snapshot.values())}hydrate(t){const r=this.now();for(const n of t){const c=Me(n.capName,n.scope);if(this.snapshot.has(c))continue;const u={capName:n.capName,scope:n.scope,state:n.state,generation:n.generation,epoch:1,lastChange:r,sourceNodeId:n.sourceNodeId};this.snapshot.set(c,u),this.logger&&this.logger.debug(`readiness: ${n.capName} (${ne(n.scope)}) → ${n.state} (hydrated, gen=${n.generation.slice(0,6)})`);const h={capName:n.capName,scope:n.scope,state:n.state,epoch:1,generation:n.generation,sourceNodeId:"hydrated",ts:r,durationInPrevState:0};for(const y of this.subscriptions)if(y.capName===n.capName&&Te(y.scope,n.scope))try{y.handler(h)}catch(m){this.logger?.warn(`readiness hydrate handler threw for ${n.capName}: ${m.message??String(m)}`)}}}getAll(){return new Map(this.snapshot)}emitReady(t,r){this.emitTransition(t,r,"ready")}emitStarting(t,r){this.emitTransition(t,r,"starting")}emitDown(t,r){this.emitTransition(t,r,"down")}awaitReady(t,r,n={}){const c=n.timeoutMs??Number.POSITIVE_INFINITY,u=this.now();return this.get(t,r)?.state==="ready"?Promise.resolve():n.signal?.aborted?Promise.reject(n.signal.reason??new Error("aborted")):new Promise((y,m)=>{let g=!1;const A=this.onReadyState(t,r,z=>{z.state==="ready"&&(g||(g=!0,x(),y()))}),C=!Number.isFinite(c)?null:setTimeout(()=>{g||(g=!0,x(),m(new Yi(t,r,this.now()-u)))},c),w=()=>{g||(g=!0,x(),m(n.signal?.reason??new Error("aborted")))};n.signal?.addEventListener("abort",w,{once:!0});function x(){A(),C!==null&&clearTimeout(C),n.signal?.removeEventListener("abort",w)}})}onReadyState(t,r,n){const c={capName:t,scope:r,handler:n};this.subscriptions.add(c);const u=this.get(t,r);return u!==null&&queueMicrotask(()=>{this.subscriptions.has(c)&&n({capName:t,scope:r,state:u.state,epoch:u.epoch,generation:u.generation,sourceNodeId:this.sourceNodeId,ts:u.lastChange,durationInPrevState:0})}),()=>{this.subscriptions.delete(c)}}emitTransition(t,r,n){const c=this.now();this.bus.emit(Ea("system.ready-state",{type:"capability",id:t,nodeId:this.sourceNodeId},{capName:t,scope:r,state:n,generation:this.generation,sourceNodeId:this.sourceNodeId,ts:c}))}ingest(t){if(typeof t?.capName!="string"||t.state!=="ready"&&t.state!=="starting"&&t.state!=="down"||typeof t.generation!="string"||t.scope?.type!=="global"&&t.scope?.type!=="node"&&t.scope?.type!=="device")return;const r=Me(t.capName,t.scope),n=this.snapshot.get(r)??null,c=this.now();let u;if(n===null?u=t.state==="ready"?1:0:n.generation!==t.generation&&t.state==="ready"?u=n.epoch+1:u=n.epoch,n!==null&&n.generation===t.generation&&n.state===t.state)return;const h=n===null?0:Math.max(0,c-n.lastChange),y={capName:t.capName,scope:t.scope,state:t.state,generation:t.generation,epoch:u,lastChange:c,sourceNodeId:t.sourceNodeId};this.snapshot.set(r,y);const m={capName:t.capName,scope:t.scope,state:t.state,epoch:u,generation:t.generation,sourceNodeId:t.sourceNodeId,ts:t.ts,durationInPrevState:h};this.logger&&this.logger.debug(`readiness: ${t.capName} (${ne(t.scope)}) → ${t.state} epoch=${u} gen=${t.generation.slice(0,6)} (prev ${h}ms)`);for(const g of this.subscriptions)if(g.capName===t.capName&&Te(g.scope,t.scope))try{g.handler(m)}catch(A){this.logger?.warn(`readiness handler threw for ${t.capName}: ${A.message??String(A)}`)}}synthesizeDownForNode(t){const r=this.now();for(const[n,c]of this.snapshot){if(c.state==="down"||!(c.scope.type==="node"&&c.scope.nodeId===t||c.scope.type==="device"&&c.sourceNodeId===t))continue;const h=Math.max(0,r-c.lastChange),y={...c,state:"down",lastChange:r};this.snapshot.set(n,y);const m={capName:c.capName,scope:c.scope,state:"down",epoch:c.epoch,generation:c.generation,sourceNodeId:this.sourceNodeId,ts:r,durationInPrevState:h};this.logger&&this.logger.debug(`readiness: ${c.capName} (${ne(c.scope)}) → down (synthesized from agent.offline ${t})`);for(const g of this.subscriptions)if(g.capName===c.capName&&Te(g.scope,c.scope))try{g.handler(m)}catch(A){this.logger?.warn(`readiness handler threw during agent.offline demux for ${c.capName}: ${A.message??String(A)}`)}}}};function Qi(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():Math.random().toString(36).slice(2,14)}function Gc(t,r){for(const{capName:n,scope:c}of r)t.emitDown(n,c)}var Ji={high:"High",mid:"Mid",low:"Low"};function jc(t){return Ji[t]??t.charAt(0).toUpperCase()+t.slice(1)}function Xi(t){return(t.width??0)*(t.height??0)}function en(t){if(t.length===0)return[];const r=t.map((c,u)=>({s:c,i:u,px:Xi(c.metadata??{})})).sort((c,u)=>u.px-c.px),n=Array.from({length:t.length});for(let c=0;c<r.length;c++){const{s:u,i:h}=r[c];let y;c===0?y="high":c===r.length-1?y="low":y="mid",n[h]={...u,quality:y}}return n}function Vc(t){const r=t.height??0,n=t.width??0;return r>=1080||n>=1920?"high":r>=480||n>=640?"mid":"low"}function Kc(t){const r=t.protocols.find(u=>u.type==="rtsp"&&u.url)??t.protocols.find(u=>u.url),n=r?.type,c=n==="rtsp"?"rtsp":n==="http"||n==="flv"?"http-mjpeg":"custom";return{id:t.id,label:t.label??t.id,protocol:c,url:r?.url,profileHint:t.quality}}function E(t){return typeof t=="string"}function tn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function an(t){return E(t)&&t.trim()?{url:t}:tn(t)&&E(t.url)&&t.url.trim()?{url:t.url,label:E(t.label)?t.label:void 0}:null}function Zc(t){const r=E(t.snapshot_url)?t.snapshot_url:void 0;if(Array.isArray(t.streams)){const y=[];for(const m of t.streams){const g=an(m);g&&y.push(g)}return{streams:y,snapshot_url:r}}const n=[],c=E(t.main_stream_url)?t.main_stream_url:void 0;c&&n.push({url:c,label:E(t.main_stream_name)?t.main_stream_name:void 0});const u=E(t.sub_stream_url)?t.sub_stream_url:void 0;u&&n.push({url:u,label:E(t.sub_stream_name)?t.sub_stream_name:void 0});const h=E(t.third_stream_url)?t.third_stream_url:void 0;return h&&n.push({url:h,label:E(t.third_stream_name)?t.third_stream_name:void 0}),{streams:n,snapshot_url:r}}function Yc(t){if(t.length===0)return{};const r=en(t),n={},c=r.find(m=>m.quality==="high"),u=r.find(m=>m.quality==="mid"),h=r.find(m=>m.quality==="low");c&&(n.high=c.id),u&&(n.mid=u.id),h&&(n.low=h.id);const y=c??u??h??r[0];return y&&(n.high||(n.high=y.id),n.mid||(n.mid=y.id),n.low||(n.low=y.id)),n}var Qc={streaming:!0,notifications:!0,objectDetection:!1,remoteAccess:!0,agentCluster:!1,smartHome:!0,recordings:!0,backup:!0,repl:!0},Jc=["face","plate"],Xc=["face","plate","clip","custom"],nn=i({inputFps:a(),outputFps:a(),avgDecodeTimeMs:a(),droppedFrames:a()}),Ft=i({codec:e(),maxFps:a().default(0),outputFormat:f(["jpeg","rgb","bgr","yuv420","gray"]).default("jpeg"),scale:a().default(1),width:a().optional(),height:a().optional(),deviceId:a().int().nonnegative().optional(),tag:e().optional()}),el={cleanupIntervalMs:3600*1e3,detectionEventsDays:30,audioLevelsDays:7,snapshotsDays:14},on=(t=>(t.Addon="addon",t.Core="core",t.Device="device",t.Provider="provider",t.System="system",t))(on||{}),rn="camstack/camstack-models",tl=`https://huggingface.co/${rn}/resolve/main`,al={"features.streaming":!0,"features.notifications":!0,"features.objectDetection":!1,"features.remoteAccess":!0,"features.agentCluster":!1,"features.smartHome":!0,"features.recordings":!0,"features.backup":!0,"features.repl":!0,"retention.detectionEventsDays":30,"retention.audioLevelsDays":7,"logging.level":"info","logging.retentionDays":30,"eventBus.ringBufferSize":1e4,"storage.provider":"sqlite-storage","storage.locations":{data:"camstack-data/data",media:"camstack-data/media",recordings:"camstack-data/recordings",cache:"/tmp/camstack-cache",logs:"camstack-data/logs",models:"camstack-data/models"},providers:[],"recording.segmentDurationSeconds":4,"recording.defaultRetentionDays":30,"ffmpeg.binaryPath":"ffmpeg","ffmpeg.hwAccel":"auto","ffmpeg.threadCount":0,"auth.tokenExpiry":"24h"};function qa(t){return JSON.parse(t)}function sn(t){return t===null||typeof t!="object"||Array.isArray(t)?null:{...t}}function il(t){return Array.isArray(t)?t:[]}function nl(t,r=""){return typeof t=="string"?t:r}function ol(t,r=0){return typeof t=="number"?t:r}function rl(t,r=!1){return typeof t=="boolean"?t:r}function sl(t){try{return sn(qa(t))}catch{return null}}function dl(t){try{const r=qa(t);return Array.isArray(r)?r:null}catch{return null}}function cl(t,r){return`https://huggingface.co/${t}/resolve/main/${r}`}function ll(t,r){if(t.length!==r.length)return 0;let n=0,c=0,u=0;for(let y=0;y<t.length;y++)n+=t[y]*r[y],c+=t[y]*t[y],u+=r[y]*r[y];const h=Math.sqrt(c)*Math.sqrt(u);return h===0?0:n/h}var ul=class{constructor(t,r){this.elementId=t,this.getBackend=typeof r=="function"?r:()=>r}elementId;cache={};listeners=new Set;loaded=!1;getBackend;async ensureLoaded(){if(this.loaded)return;const t=this.getBackend();if(!t)throw new Error(`ElementConfigStore(${this.elementId}): settings backend not available`);const r=await t.query({collection:"config",filter:{where:{id:this.elementId},limit:1}});r.length>0&&(this.cache=r[0].data??{}),this.loaded=!0}getAll(){return{...this.cache}}get(t){const r=t.split(".");let n=this.cache;for(const c of r){if(n===null||typeof n!="object"||Array.isArray(n))return;n=Reflect.get(n,c)}return n}async set(t,r){await this.ensureLoaded(),dn(this.cache,t,r),await this.persist(),this.notifyListeners()}async setAll(t){await this.ensureLoaded(),this.cache={...t},await this.persist(),this.notifyListeners()}onChange(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}async load(){await this.ensureLoaded()}async loadDefaults(t){await this.ensureLoaded(),Object.keys(this.cache).length===0&&(this.cache={...t},await this.persist())}async persist(){const t=this.getBackend();if(!t)throw new Error(`ElementConfigStore(${this.elementId}): settings backend not available — cannot persist config`);await t.set({collection:"config",key:this.elementId,value:this.cache})}notifyListeners(){const t=this.getAll();for(const r of this.listeners)try{r(t)}catch{}}};function dn(t,r,n){const c=r.split(".");let u=t;for(let h=0;h<c.length-1;h++){const y=c[h],m=u[y];if(m===null||typeof m!="object"||Array.isArray(m)){const g={};u[y]=g,u=g}else u=m}u[c[c.length-1]]=n}var xa={cpu:"onnx",coreml:"onnx",cuda:"onnx",tensorrt:"onnx","onnx-py":"onnx",pytorch:"pt",openvino:"openvino"},cn={onnx:"onnx",coreml:"coreml",openvino:"openvino",tflite:"tflite",pytorch:"pt"},ln={coreml:"coreml_inference.py",pytorch:"pytorch_inference.py",openvino:"openvino_inference.py"};function un(t,r){return t==="node"?"onnx":{coreml:"coreml",openvino:"openvino",pytorch:"pytorch","onnx-py":"onnx",cpu:"onnx"}[r]??r}function ml(t,r){return t==="node"?xa[r]??"onnx":{coreml:"coreml",openvino:"openvino",pytorch:"pt","onnx-py":"onnx",cpu:"onnx"}[r]??"onnx"}function pl(t,r){return!t||t==="auto"?"auto":un(t,r??"cpu")}function gl(t){return xa[t]??"onnx"}function hl(t){return cn[t]}function vl(t){return ln[t]}function yl(t){return t==="coreml"||t==="pytorch"||t==="openvino"}function mn(t){return t instanceof Error?t.message:typeof t=="string"?t:String(t)}async function fl(t,r){const n=performance.now();try{return{output:r!==void 0?await pn(t(),r):await t(),durationMs:Lt(performance.now()-n),ok:!0}}catch(c){return{output:void 0,durationMs:Lt(performance.now()-n),ok:!1,error:mn(c)}}}function Lt(t){return Math.round(t*100)/100}function pn(t,r){return new Promise((n,c)=>{const u=setTimeout(()=>c(new Error(`Inference timeout after ${r}ms`)),r);t.then(h=>{clearTimeout(u),n(h)}).catch(h=>{clearTimeout(u),c(h)})})}var Sl=[{id:"person",name:"Person"},{id:"bicycle",name:"Bicycle"},{id:"car",name:"Car"},{id:"motorcycle",name:"Motorcycle"},{id:"airplane",name:"Airplane"},{id:"bus",name:"Bus"},{id:"train",name:"Train"},{id:"truck",name:"Truck"},{id:"boat",name:"Boat"},{id:"traffic light",name:"Traffic Light"},{id:"fire hydrant",name:"Fire Hydrant"},{id:"stop sign",name:"Stop Sign"},{id:"parking meter",name:"Parking Meter"},{id:"bench",name:"Bench"},{id:"bird",name:"Bird"},{id:"cat",name:"Cat"},{id:"dog",name:"Dog"},{id:"horse",name:"Horse"},{id:"sheep",name:"Sheep"},{id:"cow",name:"Cow"},{id:"elephant",name:"Elephant"},{id:"bear",name:"Bear"},{id:"zebra",name:"Zebra"},{id:"giraffe",name:"Giraffe"},{id:"backpack",name:"Backpack"},{id:"umbrella",name:"Umbrella"},{id:"handbag",name:"Handbag"},{id:"tie",name:"Tie"},{id:"suitcase",name:"Suitcase"},{id:"frisbee",name:"Frisbee"},{id:"skis",name:"Skis"},{id:"snowboard",name:"Snowboard"},{id:"sports ball",name:"Sports Ball"},{id:"kite",name:"Kite"},{id:"baseball bat",name:"Baseball Bat"},{id:"baseball glove",name:"Baseball Glove"},{id:"skateboard",name:"Skateboard"},{id:"surfboard",name:"Surfboard"},{id:"tennis racket",name:"Tennis Racket"},{id:"bottle",name:"Bottle"},{id:"wine glass",name:"Wine Glass"},{id:"cup",name:"Cup"},{id:"fork",name:"Fork"},{id:"knife",name:"Knife"},{id:"spoon",name:"Spoon"},{id:"bowl",name:"Bowl"},{id:"banana",name:"Banana"},{id:"apple",name:"Apple"},{id:"sandwich",name:"Sandwich"},{id:"orange",name:"Orange"},{id:"broccoli",name:"Broccoli"},{id:"carrot",name:"Carrot"},{id:"hot dog",name:"Hot Dog"},{id:"pizza",name:"Pizza"},{id:"donut",name:"Donut"},{id:"cake",name:"Cake"},{id:"chair",name:"Chair"},{id:"couch",name:"Couch"},{id:"potted plant",name:"Potted Plant"},{id:"bed",name:"Bed"},{id:"dining table",name:"Dining Table"},{id:"toilet",name:"Toilet"},{id:"tv",name:"TV"},{id:"laptop",name:"Laptop"},{id:"mouse",name:"Mouse"},{id:"remote",name:"Remote"},{id:"keyboard",name:"Keyboard"},{id:"cell phone",name:"Cell Phone"},{id:"microwave",name:"Microwave"},{id:"oven",name:"Oven"},{id:"toaster",name:"Toaster"},{id:"sink",name:"Sink"},{id:"refrigerator",name:"Refrigerator"},{id:"book",name:"Book"},{id:"clock",name:"Clock"},{id:"vase",name:"Vase"},{id:"scissors",name:"Scissors"},{id:"teddy bear",name:"Teddy Bear"},{id:"hair drier",name:"Hair Drier"},{id:"toothbrush",name:"Toothbrush"}],bl=[{id:"person",name:"Person"},{id:"vehicle",name:"Vehicle"},{id:"animal",name:"Animal"}],Il={mapping:{person:"person",bicycle:"vehicle",car:"vehicle",motorcycle:"vehicle",airplane:"vehicle",bus:"vehicle",train:"vehicle",truck:"vehicle",boat:"vehicle",bird:"animal",cat:"animal",dog:"animal",horse:"animal",sheep:"animal",cow:"animal",elephant:"animal",bear:"animal",zebra:"animal",giraffe:"animal"},preserveOriginal:!1},gn=[{id:"speech",name:"Speech",icon:"🗣️"},{id:"scream",name:"Scream / Shout",icon:"😱"},{id:"crying",name:"Crying / Baby",icon:"😢"},{id:"laughter",name:"Laughter",icon:"😂"},{id:"music",name:"Music",icon:"🎵"},{id:"dog",name:"Dog",icon:"🐕"},{id:"cat",name:"Cat",icon:"🐈"},{id:"bird",name:"Bird",icon:"🐦"},{id:"animal",name:"Animal (other)",icon:"🐾"},{id:"alarm",name:"Alarm / Siren",icon:"🚨"},{id:"doorbell",name:"Doorbell / Knock",icon:"🔔"},{id:"glass_breaking",name:"Glass Breaking",icon:"💥"},{id:"gunshot",name:"Gunshot / Explosion",icon:"💣"},{id:"vehicle",name:"Vehicle",icon:"🚗"},{id:"siren",name:"Emergency Siren",icon:"🚑"},{id:"fire",name:"Fire / Smoke",icon:"🔥"},{id:"water",name:"Water",icon:"💧"},{id:"wind",name:"Wind / Weather",icon:"🌬️"},{id:"door",name:"Door",icon:"🚪"},{id:"footsteps",name:"Footsteps",icon:"👣"},{id:"crowd",name:"Crowd / Chatter",icon:"👥"},{id:"telephone",name:"Telephone",icon:"📞"},{id:"engine",name:"Engine / Motor",icon:"⚙️"},{id:"tools",name:"Tools / Construction",icon:"🔨"},{id:"silence",name:"Silence",icon:"🤫"}],hn={mapping:{Speech:"speech","Child speech, kid speaking":"speech",Conversation:"speech","Narration, monologue":"speech",Babbling:"speech",Whispering:"speech","Speech synthesizer":"speech",Humming:"speech",Rapping:"speech",Singing:"speech",Choir:"speech","Child singing":"speech",Shout:"scream",Bellow:"scream",Yell:"scream",Screaming:"scream","Children shouting":"scream",Whoop:"scream","Crying, sobbing":"crying","Baby cry, infant cry":"crying",Whimper:"crying","Wail, moan":"crying",Groan:"crying",Laughter:"laughter","Baby laughter":"laughter",Giggle:"laughter",Snicker:"laughter","Belly laugh":"laughter","Chuckle, chortle":"laughter",Music:"music","Musical instrument":"music",Guitar:"music",Piano:"music",Drum:"music","Drum kit":"music","Violin, fiddle":"music",Flute:"music",Saxophone:"music",Trumpet:"music",Synthesizer:"music","Pop music":"music","Rock music":"music","Hip hop music":"music","Classical music":"music",Jazz:"music","Electronic music":"music","Background music":"music",Dog:"dog",Bark:"dog",Yip:"dog",Howl:"dog","Bow-wow":"dog",Growling:"dog","Whimper (dog)":"dog",Cat:"cat",Purr:"cat",Meow:"cat",Hiss:"cat",Caterwaul:"cat",Bird:"bird","Bird vocalization, bird call, bird song":"bird","Chirp, tweet":"bird",Squawk:"bird",Crow:"bird",Owl:"bird","Pigeon, dove":"bird",Animal:"animal","Domestic animals, pets":"animal","Livestock, farm animals, working animals":"animal",Horse:"animal","Cattle, bovinae":"animal",Pig:"animal",Sheep:"animal",Goat:"animal",Frog:"animal",Insect:"animal",Cricket:"animal",Alarm:"alarm","Alarm clock":"alarm","Smoke detector, smoke alarm":"alarm","Fire alarm":"alarm",Buzzer:"alarm","Civil defense siren":"alarm","Car alarm":"alarm",Siren:"siren","Police car (siren)":"siren","Ambulance (siren)":"siren","Fire engine, fire truck (siren)":"siren","Emergency vehicle":"siren",Foghorn:"siren",Doorbell:"doorbell","Ding-dong":"doorbell",Knock:"doorbell",Tap:"doorbell",Glass:"glass_breaking",Shatter:"glass_breaking","Chink, clink":"glass_breaking","Gunshot, gunfire":"gunshot","Machine gun":"gunshot",Explosion:"gunshot",Fireworks:"gunshot",Firecracker:"gunshot","Artillery fire":"gunshot","Cap gun":"gunshot",Boom:"gunshot",Vehicle:"vehicle",Car:"vehicle",Truck:"vehicle",Bus:"vehicle",Motorcycle:"vehicle","Car passing by":"vehicle","Vehicle horn, car horn, honking":"vehicle","Traffic noise, roadway noise":"vehicle",Train:"vehicle",Aircraft:"vehicle",Helicopter:"vehicle",Bicycle:"vehicle",Skateboard:"vehicle",Fire:"fire",Crackle:"fire",Water:"water",Rain:"water",Raindrop:"water","Rain on surface":"water",Stream:"water",Waterfall:"water",Ocean:"water","Waves, surf":"water","Splash, splatter":"water",Wind:"wind",Thunderstorm:"wind",Thunder:"wind","Wind noise (microphone)":"wind","Rustling leaves":"wind",Door:"door","Sliding door":"door",Slam:"door","Cupboard open or close":"door","Walk, footsteps":"footsteps",Run:"footsteps",Shuffle:"footsteps",Crowd:"crowd",Chatter:"crowd",Cheering:"crowd",Applause:"crowd","Children playing":"crowd","Hubbub, speech noise, speech babble":"crowd",Telephone:"telephone","Telephone bell ringing":"telephone",Ringtone:"telephone","Telephone dialing, DTMF":"telephone","Busy signal":"telephone",Engine:"engine","Engine starting":"engine",Idling:"engine","Accelerating, revving, vroom":"engine","Light engine (high frequency)":"engine","Medium engine (mid frequency)":"engine","Heavy engine (low frequency)":"engine","Lawn mower":"engine",Chainsaw:"engine",Hammer:"tools",Jackhammer:"tools",Sawing:"tools","Power tool":"tools",Drill:"tools",Sanding:"tools",Silence:"silence"},preserveOriginal:!1},vn={mapping:{speech:"speech",child_speech:"speech",conversation:"speech",whispering:"speech",singing:"speech",humming:"speech",shout:"scream",yell:"scream",screaming:"scream",crying:"crying",baby_crying:"crying",sobbing:"crying",laughter:"laughter",baby_laughter:"laughter",giggling:"laughter",music:"music",guitar:"music",piano:"music",drums:"music",dog_bark:"dog",dog_bow_wow:"dog",dog_growling:"dog",dog_howl:"dog",cat_meow:"cat",cat_purr:"cat",cat_hiss:"cat",bird:"bird",bird_chirp:"bird",bird_squawk:"bird",animal:"animal",horse:"animal",cow_moo:"animal",insect:"animal",alarm:"alarm",smoke_alarm:"alarm",fire_alarm:"alarm",car_alarm:"alarm",siren:"siren",police_siren:"siren",ambulance_siren:"siren",doorbell:"doorbell",door_knock:"doorbell",knocking:"doorbell",glass_breaking:"glass_breaking",glass_shatter:"glass_breaking",gunshot:"gunshot",explosion:"gunshot",fireworks:"gunshot",car:"vehicle",truck:"vehicle",motorcycle:"vehicle",car_horn:"vehicle",vehicle_horn:"vehicle",traffic:"vehicle",fire:"fire",fire_crackle:"fire",water:"water",rain:"water",ocean:"water",splash:"water",wind:"wind",thunder:"wind",thunderstorm:"wind",door:"door",door_slam:"door",sliding_door:"door",footsteps:"footsteps",walking:"footsteps",running:"footsteps",crowd:"crowd",chatter:"crowd",cheering:"crowd",applause:"crowd",telephone_ring:"telephone",ringtone:"telephone",engine:"engine",engine_starting:"engine",lawn_mower:"engine",chainsaw:"engine",hammer:"tools",jackhammer:"tools",drill:"tools",power_tool:"tools",silence:"silence"},preserveOriginal:!1},ht=new Map;for(const[t,r]of Object.entries(hn.mapping))ht.set(t.toLowerCase(),r);for(const[t,r]of Object.entries(vn.mapping))ht.set(t.toLowerCase(),r);function kl(t){return ht.get(t.toLowerCase())??null}function Al(){return gn.map(t=>t.id)}var Cl={camera:{type:"camera",label:"Camera",icon:"camera"}},q=(t=>(t.Camera="camera",t.Hub="hub",t.Light="light",t.Siren="siren",t.Switch="switch",t.Sensor="sensor",t.Thermostat="thermostat",t.Button="button",t.Generic="generic",t))(q||{}),yn=(t=>(t.BatteryOperated="battery-operated",t.Rebootable="rebootable",t.NativeSnapshot="native-snapshot",t.DoorbellButton="doorbell-button",t.TwoWayAudio="two-way-audio",t.PanTiltZoom="pan-tilt-zoom",t.PtzAutotrack="ptz-autotrack",t.MotionTrigger="motion-trigger",t))(yn||{}),fn=(t=>(t.ChargingDC="charging-dc",t.ChargingSolar="charging-solar",t.NotCharging="not-charging",t))(fn||{}),Sn=(t=>(t.Siren="siren",t.Floodlight="floodlight",t.Spotlight="spotlight",t.PirSensor="pir-sensor",t.Chime="chime",t.Autotrack="autotrack",t.Nightvision="nightvision",t.PrivacyMask="privacy-mask",t.Doorbell="doorbell",t))(Sn||{}),_={Siren:"siren",Floodlight:"floodlight",Spotlight:"spotlight",PirSensor:"pir-sensor",Chime:"chime",Autotrack:"autotrack",Nightvision:"nightvision",PrivacyMask:"privacy-mask"},wl={[_.Siren]:"Siren",[_.Floodlight]:"Floodlight",[_.Spotlight]:"Spotlight",[_.PirSensor]:"PIR",[_.Chime]:"Chime",[_.Autotrack]:"Autotracking",[_.Nightvision]:"Night Vision",[_.PrivacyMask]:"Privacy Mask"};function Pl(t,r,n){const c=`${t}:${r}`;return typeof n=="number"?`${c}:${n}`:c}function bn(t,r){return!t||t.length===0?!1:t.includes(r.when.hasFeature)}var In={id:"battery",label:"Battery-operated camera",when:{hasFeature:"battery-operated"},defaults:{audioMode:"disabled",detectionMode:"on-motion"},settings:{"snapshot.minRefreshIntervalSec":3600,"streamBroker.preBufferEnabled":!1}},kn=[In];function Dl(t){for(const r of kn)if(bn(t,r))return r;return null}var An=class he{schema;data;persistFn;constructor(r,n,c){this.schema=r,this.data=n,this.persistFn=c}static fromSchema(r,n,c={},u){const h=r.safeParse(c);if(h.success)return new he(r,h.data,n);const y=new Set;for(const k of h.error.issues){const C=k.path[0];typeof C=="string"&&y.add(C)}const m={...c};for(const k of y)delete m[k];const g=r.safeParse(m);if(u?.({droppedKeys:[...y],issues:h.error.issues}),g.success)return n(g.data).catch(()=>{}),new he(r,g.data,n);const A=r.parse({});return new he(r,A,n)}get values(){return this.data}get(r){return this.data[r]}async set(r,n){const c=this.schema.parse({...this.data,[r]:n});this.data=c,await this.persistFn(this.data)}async setAll(r){const n=this.schema.parse({...this.data,...r});this.data=n,await this.persistFn(this.data)}async deleteKey(r){const{[r]:n,...c}=this.data,u=this.schema.parse(c);this.data=u,await this.persistFn(this.data)}entries(){const r=this.schema.shape;return Object.entries(r).map(([n,c])=>({key:n,schema:c,value:this.data[n],description:c.description}))}},Cn=class Ba{writer;pendingWrites=new Set;slices;schemas=new Map;listeners=new Set;capListeners=new Map;constructor(r,n){this.writer=n,this.slices=new Map;for(const[c,u]of Object.entries(r))u&&typeof u=="object"&&!Array.isArray(u)&&this.slices.set(c,{...u})}static fromInitial(r,n){return new Ba(r,n)}installCapSchema(r,n){const c=this.schemas.get(r);if(c){if(c!==n)throw new Error(`[DeviceRuntimeState] capability "${r}" registered a different runtime-state schema; each cap must declare ONE shape across every provider`);return}this.schemas.set(r,n);const u=this.slices.get(r);if(u){const h=n.safeParse(u);h.success?this.slices.set(r,h.data):this.slices.delete(r)}}getCapState(r){const n=this.slices.get(r);if(n)return Object.freeze({...n})}getCapField(r,n){return this.slices.get(r)?.[n]}setCapState(r,n){this.applyCapWrite(r,n,!1)}patchCapState(r,n){this.applyCapWrite(r,n,!0)}applyCapWrite(r,n,c){const u=this.schemas.get(r);if(!u)throw new Error(`[DeviceRuntimeState] no schema registered for cap "${r}" — did the device register it via ctx.registerNativeCap before writing?`);const h=this.slices.get(r)??{},y=c?{...h,...n}:{...n},m=u.parse(y);if(wn(h,m))return;this.slices.set(r,m),this.fireListeners([r]);const g=this.writer(r,{...m}).catch(()=>{});this.pendingWrites.add(g),g.finally(()=>{this.pendingWrites.delete(g)})}fireListeners(r){const n=this.snapshot();for(const c of this.listeners)try{c(r,n)}catch{}for(const c of r){const u=this.capListeners.get(c);if(!u)continue;const h=this.getCapState(c);for(const y of u)try{y(h)}catch{}}}subscribe(r){return this.listeners.add(r),()=>{this.listeners.delete(r)}}subscribeCap(r,n){let c=this.capListeners.get(r);c||(c=new Set,this.capListeners.set(r,c));const u=h=>{n(h)};return c.add(u),()=>{const h=this.capListeners.get(r);h&&(h.delete(u),h.size===0&&this.capListeners.delete(r))}}snapshot(){const r={};for(const[n,c]of this.slices)r[n]=Object.freeze({...c});return Object.freeze(r)}async flush(){if(this.pendingWrites.size===0)return;const r=[...this.pendingWrites];await Promise.allSettled(r)}};function wn(t,r){const n=Object.keys(t),c=Object.keys(r);if(n.length!==c.length)return!1;for(const u of n)if(t[u]!==r[u])return!1;return!0}var Re="lastFetchedAt";function Ml(t){const{runtimeState:r,cap:n,ownDeviceId:c,refresh:u,staleMs:h,empty:y}=t,m=async()=>{const k=r.getCapState(n.name),C=typeof k?.[Re]=="number"?k[Re]:0;(!k||Date.now()-C>h)&&await u()},g=()=>{const k=r.getCapState(n.name);if(!k)return y();const{[Re]:C,...w}=k;return w};return{ensureFresh:m,getStatus:async({deviceId:k})=>{if(k!==c)throw new Error(`${n.name}: deviceId mismatch, expected ${c}, got ${k}`);return await m(),g()}}}var Ee=i({online:v(),lastChangedAt:a()}),vt={name:"device-status",scope:"device",mode:"singleton",methods:{},events:{onStatusChanged:{data:i({deviceId:a(),status:Ee})}},status:{schema:Ee,kind:"push"},runtimeState:Ee},qe=i({flags:b(e(),S()),deviceType:e().nullable(),model:e().nullable(),channelCount:a().nullable(),lastProbedAt:a(),lastFetchedAt:a()}),yt={name:"feature-probe",scope:"device",mode:"singleton",methods:{},events:{onProbeChanged:{data:i({deviceId:a(),status:qe})}},status:{schema:qe,kind:"push"},runtimeState:qe},Pn=i({id:e(),title:e(),description:e().optional(),style:f(["card","accordion"]).optional(),defaultCollapsed:v().optional(),columns:M([I(1),I(2),I(3),I(4)]).optional(),tab:e().optional(),location:f(["settings","top-tab"]).optional(),order:a().optional(),fields:l(Ra())}),Dn=i({id:e(),label:e(),icon:e(),order:a().optional()}),Mn=i({tabs:l(Dn).optional(),sections:l(Pn)}),Ut=Mn.nullable(),Tn={getDeviceSettingsContribution:{input:i({deviceId:a()}),output:Ut,kind:"query",auth:"protected"},getDeviceLiveContribution:{input:i({deviceId:a()}),output:Ut,kind:"query",auth:"protected"},applyDeviceSettingsPatch:{input:i({deviceId:a(),patch:b(e(),S())}),output:i({success:I(!0)}),kind:"mutation",auth:"admin"}},Rn={getStatus:{input:i({deviceId:a()}),output:S().nullable(),kind:"query",auth:"protected"}};function Tl(t){let r=t.methods;return t.exposesDeviceSettings&&(r={...Tn,...r}),t.status&&(r={...Rn,...r}),r}function s(t,r,n){return{input:t,output:r,kind:n?.kind??"query",auth:n?.auth??"protected",timeoutMs:n?.timeoutMs}}function $(t){return{data:t}}var En=i({className:e(),hits:a().int().nonnegative(),avgScore:a().min(0).max(1),peakScore:a().min(0).max(1)}),Ht=i({ts:a().int(),windowSec:a().int().positive(),level:i({rms:a(),dbfs:a()}),peakDbfs:a(),avgDbfs:a(),current:i({className:e(),score:a().min(0).max(1),timestamp:a().int()}).nullable(),byClass:l(En).readonly()}),qn=i({ts:a().int(),dbfs:a().nullable(),peakDbfs:a(),avgDbfs:a(),topClass:e().nullable(),topScore:a().min(0).max(1).nullable()}),xn=i({points:l(qn).readonly(),effectiveSampleEveryMs:a().int().positive(),windowMsActual:a().int().nonnegative()}),Oa={name:"audio-metrics",scope:"device",mode:"singleton",deviceTypes:["camera"],methods:{getCurrentSnapshot:s(i({deviceId:a()}),Ht.nullable()),getHistory:s(i({deviceId:a(),windowSec:a().int().positive().optional(),sampleEveryMs:a().int().positive().optional()}),xn)},runtimeState:Ht},xe=i({percentage:a().min(0).max(100),charging:f(["dc","solar","none"]),sleeping:v(),lastUpdated:a()}),Na={name:"battery",scope:"device",mode:"singleton",deviceTypes:["camera","sensor","button","switch"],methods:{},events:{onStatusChanged:{data:i({deviceId:a(),status:xe})}},status:{schema:xe,kind:"push"},runtimeState:xe},Wt=i({percentage:a().min(0).max(100),lastChangedAt:a()}),_a={name:"brightness",scope:"device",mode:"singleton",deviceTypes:["light"],methods:{setBrightness:s(i({deviceId:a().int().nonnegative(),percentage:a().min(0).max(100)}),p(),{kind:"mutation",auth:"admin"})},events:{onBrightnessChanged:{data:i({deviceId:a(),percentage:a().min(0).max(100),lastChangedAt:a()})}},status:{schema:Wt,kind:"command-driven"},runtimeState:Wt},U=f(["high","mid","low"]),Rl=["high","mid","low"],za=f(["pull-rtsp","pull-rtmp","pull-http","pull-rfc4571","push-annexb"]),ft=i({width:a().int().positive(),height:a().int().positive()}),Ze=i({camStreamId:e().min(1),deviceId:a().int().nonnegative(),kind:za,url:e().optional(),codec:e().optional(),resolution:ft.optional(),fps:a().positive().optional(),label:e().optional(),deviceFeatures:l(e()).optional(),autoEligible:v().optional(),metadata:b(e(),S()).optional()}),ve=f(["unassigned","idle","connecting","streaming","error"]),Ye=i({deviceId:a().int().nonnegative(),profile:U,brokerId:e(),sourceCamStreamId:e().nullable(),status:ve,resolution:ft.optional(),codec:e().optional(),preBufferSec:a().nonnegative().optional(),errorMessage:e().optional()}),Bn=i({id:e(),label:e(),protocol:f(["rtsp","rtmp","annexb","http-mjpeg","webrtc","custom"]),url:e().optional(),resolution:i({width:a(),height:a()}).readonly().optional(),fps:a().optional(),bitrate:a().optional(),codec:e().optional(),profileHint:f(["high","mid","low"]).optional()}),El=i({type:e(),url:e(),videoCodec:e().optional(),audioCodec:e().optional(),metadata:b(e(),S()).readonly().optional()}),On=i({type:f(["video","audio"]),data:T(Uint8Array),pts:a(),dts:a(),keyframe:v(),codec:e()}),Nn=i({data:T(Uint8Array),width:a(),height:a(),format:f(["jpeg","rgb","bgr","yuv420","gray"]),timestamp:a()}),_n=f(["idle","connecting","streaming","error","stopped"]),zn=i({status:_n,inputFps:a(),decodeFps:a(),encodedSubscribers:a(),decodedSubscribers:a(),uptimeMs:a(),bitrateKbps:a(),idrIntervalMs:a(),codec:e().optional(),totalBytes:a(),packetCount:a(),rtspClients:a(),pipeClients:a(),preBufferSec:a(),preBufferMs:a(),preBufferPackets:a(),decoderNodeId:e().nullable(),audio:i({codec:e(),sampleRate:a(),channels:a(),supported:v()}).nullable().optional()}),St=f(["webrtc","hls","mjpeg","rtsp"]),Fn=i({streamId:e(),format:St,url:e().nullable(),active:v()}),Ln={name:"streaming-engine",scope:"system",mode:"singleton",internal:!0,methods:{registerStream:s(i({streamId:e(),sourceUrl:e(),codec:e().optional()}),p(),{kind:"mutation"}),unregisterStream:s(i({streamId:e()}),p(),{kind:"mutation"}),getStreamUrl:s(i({streamId:e(),format:St}),e().nullable()),listStreams:s(p(),l(Fn))}},Qe=i({brokerId:e(),url:e(),mutedUrl:e(),enabled:v()}),Un=i({sessionId:e(),remoteAddr:e(),playing:v(),muted:v(),connectedAt:a(),lastRtpAt:a(),bytesSent:a()}),Hn=i({tag:e(),subscribedAt:a(),maxFps:a(),framesDelivered:a(),framesDropped:a()}),Wn=i({tag:e(),subscribedAt:a(),chunksDelivered:a()}),$n=i({rtsp:l(Un).readonly(),decoded:l(Hn).readonly(),audio:l(Wn).readonly(),pipeClients:a(),encodedSubscribers:a()}),ql=f(["reconnecting","sleeping","offline","disabled","waking"]),Gn={name:"stream-broker",scope:"system",mode:"singleton",exposesDeviceSettings:!0,methods:{publishCameraStream:s(i({deviceId:a().int().nonnegative(),camStreamId:e().min(1),kind:za,url:e().optional(),codec:e().optional(),resolution:ft.optional(),fps:a().positive().optional(),label:e().optional(),deviceFeatures:l(e()).optional(),autoEligible:v().optional(),metadata:b(e(),S()).optional()}),i({success:I(!0)}),{kind:"mutation",auth:"admin"}),retractCameraStream:s(i({deviceId:a().int().nonnegative(),camStreamId:e().min(1)}),i({success:I(!0)}),{kind:"mutation",auth:"admin"}),assignProfile:s(i({deviceId:a().int().nonnegative(),profile:U,camStreamId:e().min(1)}),i({success:I(!0)}),{kind:"mutation",auth:"admin"}),unassignProfile:s(i({deviceId:a().int().nonnegative(),profile:U}),i({success:I(!0)}),{kind:"mutation",auth:"admin"}),listAllCameraStreams:s(p(),l(Ze).readonly()),listAllProfileSlots:s(p(),l(Ye).readonly()),getBrokerStats:s(i({brokerId:e()}),zn),listClients:s(i({brokerId:e()}),$n),killClient:s(i({brokerId:e(),channel:f(["rtsp","decoded","audio"]),handle:e()}),i({killed:v()}),{kind:"mutation",auth:"admin"}),restartProfile:s(i({deviceId:a().int().nonnegative(),profile:U}),i({success:v()}),{kind:"mutation",auth:"admin"}),getStreamUrl:s(i({streamId:e(),format:St}),i({url:e()})),getBroker:s(i({brokerId:e()}),R()),setPreBufferDuration:s(i({brokerId:e(),seconds:a().min(0).max(30)}),p(),{kind:"mutation",auth:"admin"}),getPreBufferInfo:s(i({brokerId:e()}),i({configuredSec:a(),bufferedMs:a(),packetCount:a()})),getRtspPort:s(p(),a()),getAllRtspEntries:s(i({hostname:e().optional()}),l(Qe).readonly()),getRtspEntry:s(i({brokerId:e(),hostname:e().optional()}),Qe.nullable()),regenerateRtspToken:s(i({brokerId:e()}),e().nullable(),{kind:"mutation",auth:"admin"}),setRtspEnabled:s(i({brokerId:e(),enabled:v()}),p(),{kind:"mutation",auth:"admin"}),isRtspEnabled:s(i({brokerId:e()}),v())},events:{onCamStreamDemand:$(i({deviceId:a().int().nonnegative(),camStreamId:e(),profile:U})),onCamStreamIdle:$(i({deviceId:a().int().nonnegative(),camStreamId:e()})),onRequestStreamSourceRefresh:$(i({deviceId:a().int().nonnegative(),camStreamId:e(),brokerId:e()}))}},Fa={name:"camera-streams",scope:"device",mode:"singleton",deviceTypes:["camera"],methods:{getCameraStreams:s(i({deviceId:a().int().nonnegative()}),l(Ze).readonly()),getBrokerStreams:s(i({deviceId:a().int().nonnegative()}),l(Ye).readonly()),getRtspEntries:s(i({deviceId:a().int().nonnegative(),hostname:e().optional()}),l(Qe).readonly())},events:{onCamStreamsChanged:$(i({deviceId:a().int().nonnegative(),camStreams:l(Ze).readonly()})),onProfileSlotsChanged:$(i({deviceId:a().int().nonnegative(),profileSlots:l(Ye).readonly()}))},runtimeState:i({online:v(),slotStatuses:i({high:ve.optional(),mid:ve.optional(),low:ve.optional()}),slotErrors:i({high:e().optional(),mid:e().optional(),low:e().optional()}),lastChangedAt:a()})},jn=f(["online","sleeping","offline","unknown"]),Je=i({childNativeId:e(),name:e(),type:f(q),status:jn,metadata:i({model:e().optional(),serialNumber:e().optional(),uid:e().optional(),rtspChannel:a().int().nonnegative().optional(),isBattery:v().optional(),isDoorbell:v().optional(),isMultifocal:v().optional()}).default({}),alreadyAdopted:v(),adoptedDeviceId:a().int().nonnegative().nullable()}),$t=i({discovered:l(Je),lastDiscoveryAt:a().int().nonnegative().nullable(),lastError:e().nullable()}),La={name:"device-discovery",scope:"device",mode:"singleton",deviceTypes:["hub"],status:{schema:$t,kind:"poll"},runtimeState:$t.extend({lastFetchedAt:a().int().nonnegative()}),methods:{listDiscovered:s(i({deviceId:a().int().nonnegative()}),l(Je).readonly()),refreshDiscovery:s(i({deviceId:a().int().nonnegative()}),l(Je).readonly(),{kind:"mutation",auth:"admin"}),adoptDevice:s(i({deviceId:a().int().nonnegative(),childNativeId:e(),name:e().optional()}),i({deviceId:a().int().nonnegative(),stableId:e()}),{kind:"mutation",auth:"admin"}),releaseDevice:s(i({deviceId:a().int().nonnegative(),childDeviceId:a().int().nonnegative()}),p(),{kind:"mutation",auth:"admin"})}},Gt=i({lastPressedAt:a().nullable(),pressCountSinceStart:a()}),Vn=i({deviceId:a(),timestamp:a()}),Ua={name:"doorbell",scope:"device",mode:"singleton",deviceTypes:["button"],methods:{},events:{onPressed:{data:Vn}},status:{schema:Gt,kind:"push"},runtimeState:Gt},Kn=f(["jpeg","rgb","bgr","yuv420","gray"]),ye=i({data:R(),format:Kn,width:a(),height:a(),timestamp:a()}),Z=i({x:a(),y:a(),w:a(),h:a()}),Zn=i({class:e(),originalClass:e(),score:a(),bbox:Z}),jt=i({data:T(Float32Array),sampleRate:a(),channels:a(),timestamp:a(),deviceId:a().optional()}),Yn=i({rms:a(),dbfs:a()}),Xe=i({className:e(),originalClass:e().optional(),score:a()}),Ie=i({bbox:Z,pixelCount:a(),intensity:a()}),Qn=i({detected:v(),regionCount:a(),regions:l(Ie).readonly(),rawRegions:l(Ie).readonly(),frameWidth:a(),frameHeight:a(),analysisMs:a()}),Jn={name:"motion-detection",scope:"device",mode:"singleton",exposesDeviceSettings:!0,methods:{analyze:s(i({deviceId:a(),frame:ye}),Qn,{kind:"mutation"}),removeCamera:s(i({deviceId:a()}),p(),{kind:"mutation"}),reset:s(p(),p(),{kind:"mutation"})},events:{onMotion:{data:i({deviceId:a(),detected:v(),regionCount:a()})}}},xl=i({activeCameras:a(),throttledCameras:a(),avgInferenceTimeMs:a(),queueDepth:a()}),bt=i({detectionMode:f(["disabled","always-on","on-motion"]),configuredFps:a(),actualFps:a(),queueDepth:a(),avgInferenceTimeMs:a(),droppedFrames:a(),phase:f(["idle","watching","active"])}),Xn=bt.extend({deviceId:a()}),et=f(["onnx","coreml","openvino","tflite","pt"]),re=f(["detector","cropper","classifier","refiner","audio-classifier"]),P=i({runtime:f(["node","python"]),backend:e(),format:et,device:e().optional()}),eo=i({id:e(),label:e(),description:e().optional()}),to=i({engine:P,devices:l(eo).readonly(),defaultDevice:e()}),tt=gt(()=>i({addonId:e(),addonName:e(),slot:re,inputClasses:l(e()).readonly(),outputClasses:l(e()).readonly(),enabled:v(),modelId:e(),children:l(tt).readonly(),engine:P.optional(),group:e().optional(),settings:b(e(),S()).optional()})),ke=gt(()=>i({addonId:e(),enabled:v(),modelId:e(),children:l(ke).readonly(),settings:b(e(),S()).optional()})),Be=i({id:e(),name:e(),createdAt:e(),updatedAt:e(),engine:P,steps:l(ke).readonly()}),ao=i({id:e(),name:e(),formats:b(e(),i({downloaded:v(),sizeMB:a()}))}),io=R(),no=i({id:e(),name:e(),slot:re,inputClasses:l(e()).readonly(),outputClasses:l(e()).readonly(),childSlots:l(re).readonly(),models:l(ao).readonly(),defaultModelId:e(),defaultModelIdByFormat:b(e(),e()).optional(),enabledByDefault:v().optional(),defaultConfidence:a(),group:e().optional(),configSchema:l(io).readonly().optional()}),oo=i({id:re,label:e(),priority:a(),parentSlot:re.nullable(),addons:l(no).readonly()}),ro=i({availableEngines:l(to).readonly(),selectedEngine:P,slots:l(oo).readonly()}),so=i({detections:l(Zn).readonly(),inferenceMs:a(),modelId:e()}),K=gt(()=>i({addonId:e(),modelId:e(),enabled:v().default(!0),children:l(K).optional(),settings:b(e(),S()).optional()})),co=i({filename:e(),stepIds:l(e()).readonly().optional()}),lo=i({base64:e(),filename:e()}),uo=i({filename:e(),sizeKb:a()}),mo=i({base64:e()}),po=i({id:e(),name:e(),description:e(),available:v(),rawLabels:l(e()).readonly().optional()}),go=i({activeBackend:e(),availableBackends:l(po).readonly(),sampleRate:a(),chunkDurationMs:a()}),ho=i({filePath:e(),sizeMB:a(),durationMs:a()}),vo=i({success:v(),error:e().optional(),frame:R().optional()}),yo=R(),fo=R(),So=R(),bo=R(),Io=R(),Vt=R(),ko={name:"pipeline-executor",scope:"system",mode:"singleton",methods:{getAvailableEngines:s(p(),l(P)),getSelectedEngine:s(p(),P),getDefaultSteps:s(P,l(tt)),reprobeEngine:s(p(),P,{kind:"mutation",auth:"admin"}),getVideoPipelineSteps:s(p(),b(e(),i({modelId:e(),settings:b(e(),S()).readonly()}))),setVideoPipelineSteps:s(i({steps:b(e(),i({modelId:e(),settings:b(e(),S()).readonly()}))}),i({success:I(!0)}),{kind:"mutation",auth:"admin"}),getSchema:s(p(),ro),getGlobalSteps:s(p(),l(tt).readonly().nullable()),getGlobalPipelineConfig:s(p(),yo),getOrchestratorConfigSchema:s(p(),fo),listTemplates:s(p(),l(Be).readonly()),saveTemplate:s(i({name:e(),steps:l(ke).readonly(),engine:P}),Be,{kind:"mutation"}),updateTemplate:s(i({id:e(),name:e().optional(),steps:l(ke).readonly().optional()}),Be,{kind:"mutation"}),deleteTemplate:s(i({id:e()}),p(),{kind:"mutation"}),getCapabilities:s(p(),bo),getAddonModels:s(i({addonId:e()}),Io),downloadModel:s(i({addonId:e(),modelId:e(),format:et}),ho,{kind:"mutation"}),deleteModel:s(i({addonId:e(),modelId:e(),format:et}),i({success:I(!0)}),{kind:"mutation"}),detect:s(i({addonId:e(),frame:ye,config:b(e(),S()).optional()}),so),runPipeline:s(i({engine:P.optional(),steps:l(K).min(1),frame:ye.optional(),imageBase64:e().optional(),image:T(Uint8Array).optional(),referenceImage:e().optional(),deviceId:a().optional(),sessionId:e().optional()}),Vt,{kind:"mutation"}),runPipelineBatch:s(i({engine:P.optional(),steps:l(K).min(1),frames:l(ye).min(1).max(255),deviceId:a().optional(),sessionId:e().optional()}),i({results:l(Vt).readonly()}),{kind:"mutation"}),cacheFrameInPool:s(i({data:T(Uint8Array),width:a().int().positive(),height:a().int().positive(),format:f(["rgb","bgr","gray"])}),i({frameId:a(),width:a(),height:a()}),{kind:"mutation"}),inferCached:s(i({stepId:e(),frameId:a().int()}),b(e(),S()),{kind:"mutation"}),uncacheFrame:s(i({frameId:a().int()}),p(),{kind:"mutation"}),getEffectiveTuning:s(p(),i({batchMode:e(),windowMs:a(),maxBatchSize:a(),concurrency:a()})),listLoadedEngines:s(p(),l(i({engineKey:e(),engine:P,modelsLoaded:l(e()).readonly(),inUseByCameras:l(a()).readonly(),kind:f(["runtime","warm-override"]),poolPid:a().nullable(),idleMs:a().nullable(),idleTtlMs:a().nullable()})).readonly()),spinEngine:s(i({engine:P}),i({success:I(!0)}),{kind:"mutation",auth:"admin"}),killEngine:s(i({engine:P,force:v().optional()}),i({success:v(),reason:e().optional()}),{kind:"mutation",auth:"admin"}),listReferenceImages:s(p(),l(co).readonly()),getReferenceImage:s(i({filename:e()}),lo.nullable()),getReferenceAudioFiles:s(p(),l(uo).readonly()),getReferenceAudio:s(i({filename:e()}),mo.nullable()),getAudioCapabilities:s(p(),go),runAudioTest:s(i({addonId:e(),modelId:e(),filename:e().optional(),settings:b(e(),S()).optional()}),vo,{kind:"mutation"}),getDetectionConfigSchema:s(p(),So)}},Ao=f(["polygon","tripwire"]),Co=i({x:a(),y:a()}),ae=i({id:e(),name:e(),kind:Ao.default("polygon"),polygon:l(Co).readonly(),color:e().default("#3b82f6")}),Ha={name:"zones",scope:"device",mode:"singleton",deviceTypes:["camera"],methods:{listZones:s(i({deviceId:a()}),l(ae).readonly()),addZone:s(i({deviceId:a(),zone:ae}),p(),{kind:"mutation",auth:"admin"}),removeZone:s(i({deviceId:a(),zoneId:e()}),p(),{kind:"mutation",auth:"admin"}),updateZone:s(i({deviceId:a(),zone:ae}),p(),{kind:"mutation",auth:"admin"})},runtimeState:i({zones:l(ae).readonly()})},j={min:0,max:6e4,default:3e4,step:500},H={min:1,max:30,default:4,step:1},W={min:1,max:30,default:10,step:1},It=f(["onboard","analyzer"]),wo=l(It),Po=i({deviceId:a(),detected:v(),source:It.default("analyzer"),regions:l(Ie).readonly().optional()}),Do=i({deviceId:a(),detectionMode:f(["disabled","always-on","on-motion"]).default("on-motion"),audioMode:f(["disabled","always-on","on-motion"]).default("always-on"),motionCooldownMs:a().min(j.min).default(j.default),motionFps:a().min(H.min).max(H.max).default(H.default),detectionFps:a().min(W.min).max(W.max).default(W.default),motionStreamId:e(),detectionStreamId:e(),motionSources:wo.default(["analyzer"]),pipelineEnabled:v().default(!0),engine:P.optional(),steps:l(K).readonly().optional(),audio:i({engine:P,modelId:e(),enabled:v()}).nullable().optional(),zones:l(ae).readonly().default([])}),Bl=[{key:"motionSources",type:"multiselect",label:"Motion Sources",default:["analyzer"],options:[{value:"analyzer",label:"Frame-diff Analyzer (motion addon)"},{value:"onboard",label:"Camera Onboard Sensor"}]},{key:"motionFps",type:"slider",label:"Motion FPS (analyzer)",min:H.min,max:H.max,step:H.step,default:H.default,showValue:!0,unit:"fps",showWhen:{field:"motionSources",includes:"analyzer"}},{key:"detectionFps",type:"slider",label:"Detection FPS",min:W.min,max:W.max,step:W.step,default:W.default,showValue:!0,unit:"fps"},{key:"motionCooldownMs",type:"slider",label:"Motion Cooldown",description:"Time without a fresh motion event before the active phase ends. Applies to all motion sources — every motion event re-arms the timer.",min:j.min,max:j.max,step:j.step,default:j.default,showValue:!0,unit:"s",displayScale:1e3}],Wa=i({nodeId:e(),attachedCameras:a(),activeCameras:a(),avgInferenceFps:a(),avgInferenceTimeMs:a(),queueDepthTotal:a(),hardware:i({hasGpu:v(),inferenceBackend:e().optional(),cpuCores:a().optional()})}),Mo=i({nodeId:e(),activeCameras:a(),throttledCameras:a(),avgInferenceTimeMs:a(),queueDepth:a()}),To={name:"pipeline-runner",scope:"system",mode:"singleton",methods:{attachCamera:s(Do,i({success:I(!0)}),{kind:"mutation"}),detachCamera:s(i({deviceId:a()}),i({success:I(!0)}),{kind:"mutation"}),reportMotion:s(Po,i({success:I(!0)}),{kind:"mutation"}),getLocalLoad:s(p(),Wa),getLocalMetrics:s(p(),Mo),getCameraMetrics:s(i({deviceId:a()}),bt.nullable()),getAllCameraMetrics:s(p(),l(Xn).readonly()),getLocalCameras:s(p(),l(a()).readonly())}},Kt=i({detected:v(),lastDetectedAt:a().nullable(),autoClearAfterMs:a().nullable()}),Ro=i({deviceId:a(),detected:v(),timestamp:a(),source:It,regions:l(Ie).readonly().optional()}),$a={name:"motion",scope:"device",mode:"singleton",deviceTypes:["camera","sensor"],methods:{isDetected:s(i({deviceId:a()}),v())},events:{onMotionChanged:{data:Ro}},status:{schema:Kt,kind:"push"},runtimeState:Kt},Ga=i({enabled:v(),lastChangedAt:a()}),Eo=Ga.extend({lastFetchedAt:a()}),ja={name:"motion-trigger",scope:"device",mode:"singleton",deviceTypes:["light","siren","switch"],methods:{setMotionTrigger:s(i({deviceId:a().int().nonnegative(),enabled:v()}),p(),{kind:"mutation",auth:"admin"})},events:{onMotionTriggerChanged:{data:i({deviceId:a(),enabled:v(),lastChangedAt:a()})}},status:{schema:Ga,kind:"command-driven"},runtimeState:Eo},qo=e().describe("Vendor target string (people/vehicle/pet); empty = camera default"),at=i({targetType:qo,stopDelaySeconds:a().int().min(0).max(300),disappearDelaySeconds:a().int().min(0).max(300)}),xo=i({value:e(),label:e()}),fe=i({enabled:v(),lastChangedAt:a(),currentSettings:at.nullable(),supportedTargetTypes:l(xo)}),Bo=fe.extend({lastFetchedAt:a()}),Va={name:"ptz-autotrack",scope:"device",mode:"singleton",deviceTypes:["camera"],methods:{getStatus:s(i({deviceId:a()}),fe),setEnabled:s(i({deviceId:a(),enabled:v()}),p(),{kind:"mutation"}),getSettings:s(i({deviceId:a()}),at.nullable()),setSettings:s(i({deviceId:a(),settings:at.partial()}),p(),{kind:"mutation"})},events:{onStatusChanged:{data:i({deviceId:a(),status:fe})}},status:{schema:fe,kind:"command-driven"},runtimeState:Bo},Zt=i({on:v(),lastChangedAt:a()}),Ka={name:"switch",scope:"device",mode:"singleton",deviceTypes:["switch","siren","light"],methods:{setState:s(i({deviceId:a(),on:v()}),p(),{kind:"mutation",auth:"admin"})},events:{onStateChanged:{data:i({deviceId:a(),on:v(),lastChangedAt:a()})}},status:{schema:Zt,kind:"command-driven"},runtimeState:Zt,settings:{bindings:[{kind:"scalar",statusPath:"on",method:"setState",valueArg:"on",field:{label:"On",kind:"boolean"}}]}},it=i({totalObjects:a().int().nonnegative(),byClass:b(e(),a().int().nonnegative())}),Oo=it.extend({zoneId:e(),zoneName:e(),trackIds:l(e()).readonly()}),Yt=i({ts:a().int(),frameWidth:a().int().nonnegative(),frameHeight:a().int().nonnegative(),zones:l(Oo).readonly(),frame:it,unzoned:it}),No=f(["minute","5min","hour"]),Oe=i({from:a().int(),to:a().int(),resolution:No}),Ne=i({ts:a().int(),count:a().int().nonnegative()}),Za={name:"zone-analytics",scope:"device",mode:"singleton",deviceTypes:["camera"],methods:{getCurrentSnapshot:s(i({deviceId:a()}),Yt.nullable()),getZoneHistory:s(i({deviceId:a(),zoneId:e(),className:e().optional()}).extend(Oe.shape),l(Ne).readonly()),getCameraHistory:s(i({deviceId:a(),className:e().optional()}).extend(Oe.shape),l(Ne).readonly()),getUnzonedHistory:s(i({deviceId:a(),className:e().optional()}).extend(Oe.shape),l(Ne).readonly())},runtimeState:Yt},_o=f(["include","exclude"]),ie=i({id:e(),name:e().optional(),zoneIds:l(e()).min(1).readonly(),mode:_o,classFilter:l(e()).readonly().optional(),overlapThreshold:a().min(0).max(1).optional(),bboxInclusionPct:a().min(0).max(100).optional(),preferMask:v().optional(),enabled:v().default(!0)}),Ol=l(ie).readonly(),Qt=f(["motion","detection"]),Ya={name:"zone-rules",scope:"device",mode:"singleton",deviceTypes:["camera"],methods:{listRules:s(i({deviceId:a(),stage:Qt}),l(ie).readonly()),setRules:s(i({deviceId:a(),stage:Qt,rules:l(ie).readonly()}),p(),{kind:"mutation",auth:"admin"})},runtimeState:i({motion:l(ie).readonly(),detection:l(ie).readonly()})},zo={audioMetrics:Oa,battery:Na,brightness:_a,cameraStreams:Fa,deviceDiscovery:La,deviceStatus:vt,doorbell:Ua,featureProbe:yt,motion:$a,motionTrigger:ja,ptzAutotrack:Va,switch:Ka,zoneAnalytics:Za,zoneRules:Ya,zones:Ha},Nl=class{id;stableId;type;name;parentDeviceId;role;get online(){return this.runtimeState.getCapState("device-status")?.online??!1}set online(t){this.markOnline(t)}get state(){if(!this._stateProxyCache){const t={},r={get:(n,c)=>{const u=c;if(u in t)return t[u];const h=zo[u];if(!h)return;const y=this.sliceProxy(h);return t[u]=y,y}};this._stateProxyCache=new Proxy(t,r)}return this._stateProxyCache}_stateProxyCache;config;runtimeState;ctx;location;disabled;constructor(t,r,n){if(this.ctx=t,this.id=t.id,this.stableId=t.stableId,this.type=n.type,!t.deviceMeta)throw new Error(`BaseDevice constructor: ctx.deviceMeta is required (id=${t.id} stableId=${t.stableId})`);this.name=t.deviceMeta.name,this.location=t.deviceMeta.location,this.disabled=t.deviceMeta.disabled,this.role=n.role,this.parentDeviceId=t.parentDeviceId;const c=t.persistedConfig??{};this.config=An.fromSchema(r,A=>t.persistConfig(A),c,({droppedKeys:A,issues:k})=>{t.logger.warn("Device config recovery: dropping invalid persisted fields",{tags:{deviceId:t.id,stableId:t.stableId},meta:{droppedKeys:[...A],firstIssue:k[0]?.message??null}})});let u=null;const h=async(A,k)=>{u||(u=t.fetchDevice(t.id)),await(await u).deviceState.setCapSlice({capName:A,slice:k})},y=t.initialRuntimeState??{};this.runtimeState=Cn.fromInitial(y,h),t.bindRuntimeState?.(this.runtimeState),t.registerNativeCap?.(vt,{});const m={online:!1,lastChangedAt:Date.now()};this.runtimeState.setCapState("device-status",m),t.registerNativeCap?.(yt,{});const g={flags:{},deviceType:null,model:null,channelCount:null,lastProbedAt:0,lastFetchedAt:0};this.runtimeState.setCapState("feature-probe",g)}async removeDevice(){}markOnline(t){if(this.online===t)return;const r={online:t,lastChangedAt:Date.now()};this.runtimeState.setCapState("device-status",r)}async refreshFeatures(){const r=this.ctx.api?.deviceManager?.registerDevice;if(r)try{await r.mutate({addonId:this.ctx.deviceMeta.addonId,stableId:this.stableId,id:this.id,type:this.type,name:this.name,parentDeviceId:this.parentDeviceId,features:[...this.features],config:{}})}catch{}}getCapSlice(t){return this.runtimeState.getCapState(t.name)??null}setCapSlice(t,r){this.runtimeState.setCapState(t.name,r)}sliceProxy(t){const r={},n={get:(c,u)=>this.runtimeState.getCapState(t.name)?.[u],set:(c,u,h)=>(this.runtimeState.patchCapState(t.name,{[u]:h}),!0),has:(c,u)=>{const h=this.runtimeState.getCapState(t.name);return h?u in h:!1},ownKeys:()=>{const c=this.runtimeState.getCapState(t.name);return c?Object.keys(c):[]},getOwnPropertyDescriptor:(c,u)=>{const h=this.runtimeState.getCapState(t.name);if(!(!h||!(u in h)))return{configurable:!0,enumerable:!0,value:h[u]}}};return new Proxy(r,n)}getSettingsUISchema(){return{sections:[]}}async applySettingsPatch(t){await this.config.setAll(t)}async onProbe(){}async onActivate(){}async reprobe(){this._kernelReprobe?await this._kernelReprobe():await this.onProbe()}_kernelReprobe;getAccessoryChildren(){return[]}getProbeFlags(){return this.runtimeState.getCapState("feature-probe")?.flags??{}}hasProbed(){return(this.runtimeState.getCapState("feature-probe")?.lastProbedAt??0)>0}},Fo=i({connected:v(),deviceCount:a(),error:e().optional()}),_l=i({externalId:e(),name:e(),type:e(),metadata:b(e(),S()).optional()}),Ae=i({stableId:e(),type:f(q),suggestedName:e(),prefilledConfig:b(e(),S())}),Ce=i({id:a(),stableId:e(),addonId:e(),type:e(),name:e(),parentDeviceId:a().nullable(),online:v(),features:l(e()),config:b(e(),S())}),nt=i({status:f(["ok","error"]),labels:l(e()).optional(),error:e().optional()}),Lo=S(),Qa={name:"device-provider",scope:"system",mode:"collection",methods:{start:s(p(),p(),{kind:"mutation"}),stop:s(p(),p(),{kind:"mutation"}),getStatus:s(p(),Fo),getDevices:s(p(),l(i({id:e(),name:e(),type:e()}))),supportsDiscovery:s(i({}),v()),discoverDevices:s(i({}),l(Ae),{kind:"mutation",auth:"admin"}),adoptDiscoveredDevice:s(i({candidate:Ae}),Ce,{kind:"mutation",auth:"admin"}),supportsManualCreation:s(i({}),v()),getChildCreationSchema:s(i({type:f(q)}),Lo),createDevice:s(i({type:f(q),config:b(e(),S())}),Ce,{kind:"mutation",auth:"admin"}),testCreationField:s(i({type:f(q),key:e(),value:S(),formValues:b(e(),S()).optional()}),nt,{kind:"mutation",auth:"admin"})}};function Uo(t,r){const n={};for(const c of t.config.entries())n[c.key]=c.value;return{id:t.id,stableId:t.stableId,addonId:r,type:String(t.type),name:t.name,parentDeviceId:t.parentDeviceId,online:t.online,features:[...t.features],config:n}}var zl=class extends Ki{async onInitialize(){return this.ctx.logger.info(`${this.providerName} Provider initialized`),[{capability:Qa,provider:this}]}async onShutdown(){const t=await this.ctx.kernel.devices?.getAll()??[];for(const r of t)try{await this.ctx.kernel.devices?.decommission(r.id)}catch(n){this.ctx.logger.warn(`${this.providerName}: decommission failed`,{tags:{deviceId:r.id,stableId:r.stableId},meta:{error:n instanceof Error?n.message:String(n)}})}this.ctx.logger.info(`${this.providerName} Provider shut down`,{meta:{decommissionedCount:t.length}})}async start(){}async stop(){}async getStatus(){return{connected:!0,deviceCount:(await this.ctx.kernel.devices?.getAll()??[]).length}}async getDevices(){return(await this.ctx.kernel.devices?.getAll()??[]).map(r=>({id:r.stableId,name:r.name,type:String(r.type)}))}async supportsDiscovery(){return!1}async discoverDevices(){return[]}async adoptDiscoveredDevice(t){throw new Error(`${this.providerName} provider does not support discovery-based adoption`)}async supportsManualCreation(){return!0}async getChildCreationSchema(t){return this.onGetCreationSchema(t.type)}async createDevice(t){const r=await this.onCreateDevice(t.type,t.config),n=this.deviceClasses[r.meta.type];if(!n)throw new Error(`${this.providerName} provider: no device class registered for type "${r.meta.type}" — add it to the deviceClasses map`);const c=this.generateStableId(r.meta.type,r.config),u=await this.ctx.kernel.devices.create(c,n,r.config,null,r.meta);if(r.onAfterCreate)try{await r.onAfterCreate(u)}catch(h){this.ctx.logger.warn("createDevice: onAfterCreate hook threw — device is already registered",{tags:{deviceId:u.id,stableId:c},meta:{error:h instanceof Error?h.message:String(h)}})}return this.toSummary(u)}generateStableId(t,r){return`${this.addonId}-${Date.now()}`}async testCreationField(t){return{status:"ok",labels:["probe not implemented"]}}async restoreDevices(t){await this.onRestoreDevices(t),t.length>0&&this.ctx.logger.info(`Restored ${t.length} ${this.providerName} device(s)`)}async onRestoreDevices(t){const r=new Set;for(const c of t){if(c.parentDeviceId!==null)continue;const u=this.deviceClasses[c.type];if(!u){this.ctx.logger.warn("No device class registered for restored type — skipping",{tags:{stableId:c.stableId},meta:{type:c.type}});continue}try{await this.ctx.kernel.devices.create(c.stableId,u,{}),r.add(c.id)}catch(h){this.ctx.logger.warn("Failed to restore device",{tags:{stableId:c.stableId},meta:{type:c.type,error:h instanceof Error?h.message:String(h)}})}}const n=t.filter(c=>c.parentDeviceId!==null);for(const c of n){const u=this.deviceClasses[c.type];if(u&&c.parentDeviceId!==null&&r.has(c.parentDeviceId))try{await this.ctx.kernel.devices.create(c.stableId,u,{},c.parentDeviceId),r.add(c.id)}catch(h){this.ctx.logger.warn("Failed to restore hub-adopted child",{tags:{stableId:c.stableId,parentDeviceId:c.parentDeviceId},meta:{type:c.type,error:h instanceof Error?h.message:String(h)}})}}}toSummary(t){return Uo(t,this.addonId)}};function oe(t){return t.def}function Fl(t,r="Configuration",n="main"){const c=t.map(u=>Ho(u.key,u.schema,u.description));return{sections:[{id:n,title:r,fields:c}]}}function Ho(t,r,n){const c=Se(r),u=Vo(r),h=n??Ja(t),y={key:t,label:h,description:n,default:u};return c instanceof Ei?Wo(t,y):c instanceof qi?$o(c,y):c instanceof xi?{...y,type:"boolean"}:c instanceof Bi?jo(c,y):c instanceof Oi||c instanceof Ni?{...y,type:"textarea",rows:6,isJson:!0}:{...y,type:"text"}}function Wo(t,r){const n=t.toLowerCase();return n.includes("password")||n.includes("secret")||n.includes("token")||n.includes("apikey")||n.includes("api_key")?{...r,type:"password",showToggle:!0}:{...r,type:"text"}}function $o(t,r){const n=t,c=n.minValue,u=n.maxValue,h=c!=null&&isFinite(c)?c:void 0,y=u!=null&&isFinite(u)?u:void 0,m=Go(t);return{...r,type:"number",...h!==void 0?{min:h}:{},...y!==void 0?{max:y}:{},...m!==void 0?{step:m}:{}}}function Go(t){const n=oe(t).checks??[];for(const c of n)if(c._zod?.def?.check==="multiple_of"&&c._zod.def.value!==void 0)return c._zod.def.value}function jo(t,r){const n=t.options.map(u=>String(u));return{...r,type:"select",options:n.map(u=>({label:Ja(u),value:u}))}}function Se(t){return t instanceof Ta||t instanceof _i||t instanceof zi?Se(oe(t).innerType):t}function Vo(t){if(t instanceof Ta)return oe(t).defaultValue}function Ja(t){return t.replace(/([A-Z])/g," $1").replace(/[_-]/g," ").replace(/^\w/,r=>r.toUpperCase()).trim()}var Ko="device.state-changed";function Xa(t){const r=new Map,n=new Map;let c=null;const u=(m,g)=>`${m}:${g}`,h=()=>{c||t.live?.onEvent&&(c=t.live.onEvent.subscribe({category:Ko},{onData:m=>{const g=m.data;if(!g||typeof g.deviceId!="number"||typeof g.capName!="string")return;const A=u(g.deviceId,g.capName);r.set(A,g.slice);const k=n.get(A);if(k)for(const C of k)try{C(g.slice)}catch{}}}))},y=()=>{c&&(n.size>0||(c.unsubscribe(),c=null))};return{read(m,g){return r.get(u(m,g))},async refresh(m,g){const A=await t.deviceState.getCapSlice.query({deviceId:m,capName:g}),k=u(m,g);r.set(k,A??void 0);const C=n.get(k);if(C)for(const w of C)try{w(A??void 0)}catch{}},watch(m,g,A){const k=u(m,g);let C=n.get(k);return C||(C=new Set,n.set(k,C)),C.add(A),h(),()=>{C.delete(A),C.size===0&&n.delete(k),y()}},async write(m,g,A){await t.deviceState.setCapSlice.mutate({deviceId:m,capName:g,slice:A})}}}function Zo(t,r,n){const c=(u,h)=>`${u}:${h}`;return{read(u,h){return t.get(u)?.get(h)},async refresh(){},watch(u,h,y){const m=c(u,h);let g=r.get(m);return g||(g=new Set,r.set(m,g)),g.add(y),()=>{g.delete(y),g.size===0&&r.delete(m)}},async write(u,h,y){if(!n)throw new Error("createMirrorSource: write requires an api reference — pass it as the third argument when constructing the source");await n.deviceState.setCapSlice.mutate({deviceId:u,capName:h,slice:y})}}}function D(t,r,n){const c=Yo(t)?t:Xa(t);return{get value(){return c.read(r,n)},refresh(){return c.refresh(r,n)},subscribe(u){const h=c.watch(r,n,y=>{try{u(y)}catch{}});try{u(c.read(r,n))}catch{}return c.read(r,n)===void 0&&c.refresh(r,n).catch(()=>{}),h},async set(u){await c.write(r,n,u)},async patch(u){const y={...c.read(r,n)??{},...u};await c.write(r,n,y)}}}function Yo(t){return typeof t.read=="function"&&typeof t.watch=="function"}function Qo(t,r,n){const c=t,u=n?.stateSource??Xa(t);function h(d,B){const O=typeof d=="object"&&d!==null?d:{};return B!==void 0?{...O,deviceId:r.deviceId,nodeId:B}:{...O,deviceId:r.deviceId}}function y(d,B,O,F,X){const me=c[d]?.[B];if(!me)throw new Error(`DeviceProxy: api has no '${d}.${B}'`);const ee=me;return O==="mutation"?ee.mutate(F):O==="subscription"?ee.subscribe(F,X):ee.query(F)}function m(d,B,O,F,X,me){const ee=r.entries.find(Ti=>Ti.capName===d);return y(B,O,F,h(X,ee?.providerNodeId),me)}function g(d,B,O,F,X){return y(d,B,O,h(F,void 0),X)}const A={getStatus:d=>m("accessories","accessories","getStatus","query",d)},k={resolveDeviceSettings:d=>m("audio-analysis","audioAnalysis","resolveDeviceSettings","query",d),getDeviceSettingsContribution:d=>m("audio-analysis","audioAnalysis","getDeviceSettingsContribution","query",d),getDeviceLiveContribution:d=>m("audio-analysis","audioAnalysis","getDeviceLiveContribution","query",d),applyDeviceSettingsPatch:d=>m("audio-analysis","audioAnalysis","applyDeviceSettingsPatch","mutation",d)},C={getCurrentSnapshot:d=>m("audio-metrics","audioMetrics","getCurrentSnapshot","query",d),getHistory:d=>m("audio-metrics","audioMetrics","getHistory","query",d)},w={getStatus:d=>m("battery","battery","getStatus","query",d)},x={setBrightness:d=>m("brightness","brightness","setBrightness","mutation",d),getStatus:d=>m("brightness","brightness","getStatus","query",d)},z={getCredentials:d=>m("camera-credentials","cameraCredentials","getCredentials","query",d),getStatus:d=>m("camera-credentials","cameraCredentials","getStatus","query",d)},ce={getCameraStreams:d=>m("camera-streams","cameraStreams","getCameraStreams","query",d),getBrokerStreams:d=>m("camera-streams","cameraStreams","getBrokerStreams","query",d),getRtspEntries:d=>m("camera-streams","cameraStreams","getRtspEntries","query",d)},Y={getDeviceSettingsContribution:d=>m("detection-pipeline","detectionPipeline","getDeviceSettingsContribution","query",d),getDeviceLiveContribution:d=>m("detection-pipeline","detectionPipeline","getDeviceLiveContribution","query",d),applyDeviceSettingsPatch:d=>m("detection-pipeline","detectionPipeline","applyDeviceSettingsPatch","mutation",d)},G={listDiscovered:d=>m("device-discovery","deviceDiscovery","listDiscovered","query",d),refreshDiscovery:d=>m("device-discovery","deviceDiscovery","refreshDiscovery","mutation",d),adoptDevice:d=>m("device-discovery","deviceDiscovery","adoptDevice","mutation",d),releaseDevice:d=>m("device-discovery","deviceDiscovery","releaseDevice","mutation",d),getStatus:d=>m("device-discovery","deviceDiscovery","getStatus","query",d)},Ct={getStreamSources:d=>m("device-ops","deviceOps","getStreamSources","query",d),getConfigEntries:d=>m("device-ops","deviceOps","getConfigEntries","query",d),setConfig:d=>m("device-ops","deviceOps","setConfig","mutation",d),removeDevice:d=>m("device-ops","deviceOps","removeDevice","mutation",d),getSettingsSchema:d=>m("device-ops","deviceOps","getSettingsSchema","query",d)},wt={getStatus:d=>m("device-status","deviceStatus","getStatus","query",d)},Pt={getStatus:d=>m("doorbell","doorbell","getStatus","query",d)},Dt={getEvents:d=>m("events","events","getEvents","query",d),getEventThumbnail:d=>m("events","events","getEventThumbnail","query",d),getEventClipUrl:d=>m("events","events","getEventClipUrl","query",d)},Mt={getStatus:d=>m("feature-probe","featureProbe","getStatus","query",d)},Tt={startSession:d=>m("intercom","intercom","startSession","mutation",d),handleAnswer:d=>m("intercom","intercom","handleAnswer","mutation",d),stopSession:d=>m("intercom","intercom","stopSession","mutation",d),getStatus:d=>m("intercom","intercom","getStatus","query",d)},Rt={isDetected:d=>m("motion","motion","isDetected","query",d),getStatus:d=>m("motion","motion","getStatus","query",d)},Et={analyze:d=>m("motion-detection","motionDetection","analyze","mutation",d),removeCamera:d=>m("motion-detection","motionDetection","removeCamera","mutation",d),reset:d=>m("motion-detection","motionDetection","reset","mutation",d),getDeviceSettingsContribution:d=>m("motion-detection","motionDetection","getDeviceSettingsContribution","query",d),getDeviceLiveContribution:d=>m("motion-detection","motionDetection","getDeviceLiveContribution","query",d),applyDeviceSettingsPatch:d=>m("motion-detection","motionDetection","applyDeviceSettingsPatch","mutation",d)},qt={setMotionTrigger:d=>m("motion-trigger","motionTrigger","setMotionTrigger","mutation",d),getStatus:d=>m("motion-trigger","motionTrigger","getStatus","query",d)},xt={getStatus:d=>m("native-object-detection","nativeObjectDetection","getStatus","query",d)},Bt={setOverlay:d=>m("osd","osd","setOverlay","mutation",d),getStatus:d=>m("osd","osd","getStatus","query",d)},Ot={getActiveTracks:d=>m("pipeline-analytics","pipelineAnalytics","getActiveTracks","query",d),getTrack:d=>m("pipeline-analytics","pipelineAnalytics","getTrack","query",d),listTracks:d=>m("pipeline-analytics","pipelineAnalytics","listTracks","query",d),clearTracks:d=>m("pipeline-analytics","pipelineAnalytics","clearTracks","mutation",d),getMotionEvents:d=>m("pipeline-analytics","pipelineAnalytics","getMotionEvents","query",d),getObjectEvents:d=>m("pipeline-analytics","pipelineAnalytics","getObjectEvents","query",d),getAudioEvents:d=>m("pipeline-analytics","pipelineAnalytics","getAudioEvents","query",d),getEventMedia:d=>m("pipeline-analytics","pipelineAnalytics","getEventMedia","query",d),getTrackMedia:d=>m("pipeline-analytics","pipelineAnalytics","getTrackMedia","query",d),getDeviceSettingsContribution:d=>m("pipeline-analytics","pipelineAnalytics","getDeviceSettingsContribution","query",d),getDeviceLiveContribution:d=>m("pipeline-analytics","pipelineAnalytics","getDeviceLiveContribution","query",d),applyDeviceSettingsPatch:d=>m("pipeline-analytics","pipelineAnalytics","applyDeviceSettingsPatch","mutation",d)},Nt={move:d=>m("ptz","ptz","move","mutation",d),continuousMove:d=>m("ptz","ptz","continuousMove","mutation",d),stop:d=>m("ptz","ptz","stop","mutation",d),getPresets:d=>m("ptz","ptz","getPresets","query",d),goToPreset:d=>m("ptz","ptz","goToPreset","mutation",d),goHome:d=>m("ptz","ptz","goHome","mutation",d),getPosition:d=>m("ptz","ptz","getPosition","query",d),getStatus:d=>m("ptz","ptz","getStatus","query",d)},_t={getStatus:d=>m("ptz-autotrack","ptzAutotrack","getStatus","query",d),setEnabled:d=>m("ptz-autotrack","ptzAutotrack","setEnabled","mutation",d),getSettings:d=>m("ptz-autotrack","ptzAutotrack","getSettings","query",d),setSettings:d=>m("ptz-autotrack","ptzAutotrack","setSettings","mutation",d)},o={reboot:d=>m("reboot","reboot","reboot","mutation",d)},N={getSegments:d=>m("recording","recording","getSegments","query",d),getPlaybackUrl:d=>m("recording","recording","getPlaybackUrl","query",d),getThumbnailAt:d=>m("recording","recording","getThumbnailAt","query",d)},le={getSnapshot:d=>m("snapshot","snapshot","getSnapshot","query",d),invalidateCache:d=>m("snapshot","snapshot","invalidateCache","mutation",d),getStatus:d=>m("snapshot","snapshot","getStatus","query",d),getDeviceSettingsContribution:d=>m("snapshot","snapshot","getDeviceSettingsContribution","query",d),getDeviceLiveContribution:d=>m("snapshot","snapshot","getDeviceLiveContribution","query",d),applyDeviceSettingsPatch:d=>m("snapshot","snapshot","applyDeviceSettingsPatch","mutation",d)},Q={setState:d=>m("switch","switch","setState","mutation",d),getStatus:d=>m("switch","switch","getStatus","query",d)},De={listStreams:d=>m("webrtc-session","webrtcSession","listStreams","query",d),createSession:d=>m("webrtc-session","webrtcSession","createSession","mutation",d),handleAnswer:d=>m("webrtc-session","webrtcSession","handleAnswer","mutation",d),closeSession:d=>m("webrtc-session","webrtcSession","closeSession","mutation",d),hasAdaptiveBitrate:d=>m("webrtc-session","webrtcSession","hasAdaptiveBitrate","query",d)},ue={getCurrentSnapshot:d=>m("zone-analytics","zoneAnalytics","getCurrentSnapshot","query",d),getZoneHistory:d=>m("zone-analytics","zoneAnalytics","getZoneHistory","query",d),getCameraHistory:d=>m("zone-analytics","zoneAnalytics","getCameraHistory","query",d),getUnzonedHistory:d=>m("zone-analytics","zoneAnalytics","getUnzonedHistory","query",d)},J={listRules:d=>m("zone-rules","zoneRules","listRules","query",d),setRules:d=>m("zone-rules","zoneRules","setRules","mutation",d)},fi={listZones:d=>m("zones","zones","listZones","query",d),addZone:d=>m("zones","zones","addZone","mutation",d),removeZone:d=>m("zones","zones","removeZone","mutation",d),updateZone:d=>m("zones","zones","updateZone","mutation",d)},Si={getDeviceSettings:d=>g("addonSettings","getDeviceSettings","query",d),updateDeviceSettings:d=>g("addonSettings","updateDeviceSettings","mutation",d)},bi={loadConfig:d=>g("deviceManager","loadConfig","query",d),loadRuntimeState:d=>g("deviceManager","loadRuntimeState","query",d),loadMeta:d=>g("deviceManager","loadMeta","query",d),setName:d=>g("deviceManager","setName","mutation",d),setLocation:d=>g("deviceManager","setLocation","mutation",d),setMetadata:d=>g("deviceManager","setMetadata","mutation",d),setDisabled:d=>g("deviceManager","setDisabled","mutation",d),getDevice:d=>g("deviceManager","getDevice","query",d),getStreamSources:d=>g("deviceManager","getStreamSources","query",d),getConfigSchema:d=>g("deviceManager","getConfigSchema","query",d),getSettingsSchema:d=>g("deviceManager","getSettingsSchema","query",d),updateConfig:d=>g("deviceManager","updateConfig","mutation",d),enable:d=>g("deviceManager","enable","mutation",d),disable:d=>g("deviceManager","disable","mutation",d),remove:d=>g("deviceManager","remove","mutation",d),getStreamProfileMap:d=>g("deviceManager","getStreamProfileMap","query",d),setStreamProfileMap:d=>g("deviceManager","setStreamProfileMap","mutation",d),probeStreams:d=>g("deviceManager","probeStreams","mutation",d),getBindings:d=>g("deviceManager","getBindings","query",d),getAllBindings:d=>g("deviceManager","getAllBindings","query",d),setWrapperActive:d=>g("deviceManager","setWrapperActive","mutation",d),getDeviceSettingsAggregate:d=>g("deviceManager","getDeviceSettingsAggregate","query",d),getDeviceLiveInfoAggregate:d=>g("deviceManager","getDeviceLiveInfoAggregate","query",d),getDeviceAggregate:d=>g("deviceManager","getDeviceAggregate","query",d),updateDeviceField:d=>g("deviceManager","updateDeviceField","mutation",d),updateDeviceFieldsBatch:d=>g("deviceManager","updateDeviceFieldsBatch","mutation",d),testField:d=>g("deviceManager","testField","mutation",d),getDeviceStatusAggregate:d=>g("deviceManager","getDeviceStatusAggregate","query",d)},Ii={getSnapshot:d=>g("deviceState","getSnapshot","query",d),getCapSlice:d=>g("deviceState","getCapSlice","query",d),setCapSlice:d=>g("deviceState","setCapSlice","mutation",d)},ki={getDeviceStats:d=>g("networkQuality","getDeviceStats","query",d),reportClientStats:d=>g("networkQuality","reportClientStats","mutation",d)},Ai={runPipeline:d=>g("pipelineExecutor","runPipeline","mutation",d),runPipelineBatch:d=>g("pipelineExecutor","runPipelineBatch","mutation",d)},Ci={assignPipeline:d=>g("pipelineOrchestrator","assignPipeline","mutation",d),unassignPipeline:d=>g("pipelineOrchestrator","unassignPipeline","mutation",d),getPipelineAssignment:d=>g("pipelineOrchestrator","getPipelineAssignment","query",d),getCameraMetrics:d=>g("pipelineOrchestrator","getCameraMetrics","query",d),assignDecoder:d=>g("pipelineOrchestrator","assignDecoder","mutation",d),unassignDecoder:d=>g("pipelineOrchestrator","unassignDecoder","mutation",d),assignAudio:d=>g("pipelineOrchestrator","assignAudio","mutation",d),unassignAudio:d=>g("pipelineOrchestrator","unassignAudio","mutation",d),getAudioAssignment:d=>g("pipelineOrchestrator","getAudioAssignment","query",d),getAudioAssignments:d=>g("pipelineOrchestrator","getAudioAssignments","query",d),getDecoderAssignment:d=>g("pipelineOrchestrator","getDecoderAssignment","query",d),getCameraSettings:d=>g("pipelineOrchestrator","getCameraSettings","query",d),setCameraStepToggle:d=>g("pipelineOrchestrator","setCameraStepToggle","mutation",d),getCameraStepOverrides:d=>g("pipelineOrchestrator","getCameraStepOverrides","query",d),setCameraStepOverride:d=>g("pipelineOrchestrator","setCameraStepOverride","mutation",d),setCameraPipelineForAgent:d=>g("pipelineOrchestrator","setCameraPipelineForAgent","mutation",d),resolvePipeline:d=>g("pipelineOrchestrator","resolvePipeline","query",d),getDeviceSettingsContribution:d=>g("pipelineOrchestrator","getDeviceSettingsContribution","query",d),getDeviceLiveContribution:d=>g("pipelineOrchestrator","getDeviceLiveContribution","query",d),applyDeviceSettingsPatch:d=>g("pipelineOrchestrator","applyDeviceSettingsPatch","mutation",d)},wi={detachCamera:d=>g("pipelineRunner","detachCamera","mutation",d),getCameraMetrics:d=>g("pipelineRunner","getCameraMetrics","query",d)},Pi={getPolicyStatus:d=>g("recordingEngine","getPolicyStatus","query",d)},Di={supportsDevice:d=>g("snapshotProvider","supportsDevice","query",d),getSnapshot:d=>g("snapshotProvider","getSnapshot","query",d)},Mi={publishCameraStream:d=>g("streamBroker","publishCameraStream","mutation",d),retractCameraStream:d=>g("streamBroker","retractCameraStream","mutation",d),assignProfile:d=>g("streamBroker","assignProfile","mutation",d),unassignProfile:d=>g("streamBroker","unassignProfile","mutation",d),restartProfile:d=>g("streamBroker","restartProfile","mutation",d),getDeviceSettingsContribution:d=>g("streamBroker","getDeviceSettingsContribution","query",d),getDeviceLiveContribution:d=>g("streamBroker","getDeviceLiveContribution","query",d),applyDeviceSettingsPatch:d=>g("streamBroker","applyDeviceSettingsPatch","mutation",d)};return{deviceId:r.deviceId,binding:r,state:{audioMetrics:D(u,r.deviceId,"audio-metrics"),battery:D(u,r.deviceId,"battery"),brightness:D(u,r.deviceId,"brightness"),cameraStreams:D(u,r.deviceId,"camera-streams"),deviceDiscovery:D(u,r.deviceId,"device-discovery"),deviceStatus:D(u,r.deviceId,"device-status"),doorbell:D(u,r.deviceId,"doorbell"),featureProbe:D(u,r.deviceId,"feature-probe"),motion:D(u,r.deviceId,"motion"),motionTrigger:D(u,r.deviceId,"motion-trigger"),ptzAutotrack:D(u,r.deviceId,"ptz-autotrack"),switch:D(u,r.deviceId,"switch"),zoneAnalytics:D(u,r.deviceId,"zone-analytics"),zoneRules:D(u,r.deviceId,"zone-rules"),zones:D(u,r.deviceId,"zones")},accessories:A,audioAnalysis:k,audioMetrics:C,battery:w,brightness:x,cameraCredentials:z,cameraStreams:ce,detectionPipeline:Y,deviceDiscovery:G,deviceOps:Ct,deviceStatus:wt,doorbell:Pt,events:Dt,featureProbe:Mt,intercom:Tt,motion:Rt,motionDetection:Et,motionTrigger:qt,nativeObjectDetection:xt,osd:Bt,pipelineAnalytics:Ot,ptz:Nt,ptzAutotrack:_t,reboot:o,recording:N,snapshot:le,switch:Q,webrtcSession:De,zoneAnalytics:ue,zoneRules:J,zones:fi,addonSettings:Si,deviceManager:bi,deviceState:Ii,networkQuality:ki,pipelineExecutor:Ai,pipelineOrchestrator:Ci,pipelineRunner:wi,recordingEngine:Pi,snapshotProvider:Di,streamBroker:Mi}}function Ll(t,r,n,c,u){if(n.length===0||r.length===0)return{passed:t,excluded:[]};const h=n.filter(w=>w.enabled!==!1),y=h.filter(w=>w.mode==="include"),m=h.filter(w=>w.mode==="exclude"),g=y.length>0,A=new Map(r.map(w=>[w.id,w])),k=[],C=[];for(const w of t){const x=c(w),z=u?.(w),ce=y.some(G=>Jt(G,x,z,A)),Y=m.some(G=>Jt(G,x,z,A));g?ce&&!Y?k.push(w):C.push(w):Y?C.push(w):k.push(w)}return{passed:k,excluded:C}}function Jt(t,r,n,c){if(t.classFilter&&t.classFilter.length>0&&n!==void 0&&!t.classFilter.includes(n))return!1;for(const u of t.zoneIds){const h=c.get(u);if(h&&Jo(r,h.polygon))return!0}return!1}function Jo(t,r){if(r.length<3)return!1;let n=!1;const{x:c,y:u}=t;for(let h=0,y=r.length-1;h<r.length;y=h++){const m=r[h],g=r[y];m.y>u!=g.y>u&&c<(g.x-m.x)*(u-m.y)/(g.y-m.y||Number.EPSILON)+m.x&&(n=!n)}return n}function Ul(t){const r=t;function n(o,N,le,Q,De){const ue=r[o]?.[N];if(!ue)throw new Error(`SystemProxy: api has no '${o}.${N}'`);const J=ue;return le==="mutation"?J.mutate(Q):le==="subscription"?J.subscribe(Q,De):J.query(Q)}return{addonPages:{listPages:o=>n("addonPages","listPages","query",o)},addons:{list:o=>n("addons","list","query",o),getLogs:o=>n("addons","getLogs","query",o),listPackages:o=>n("addons","listPackages","query",o),installPackage:o=>n("addons","installPackage","mutation",o),installFromWorkspace:o=>n("addons","installFromWorkspace","mutation",o),isWorkspaceAvailable:o=>n("addons","isWorkspaceAvailable","query",o),listWorkspacePackages:o=>n("addons","listWorkspacePackages","query",o),uninstallPackage:o=>n("addons","uninstallPackage","mutation",o),reloadPackages:o=>n("addons","reloadPackages","mutation",o),searchAvailable:o=>n("addons","searchAvailable","query",o),listUpdates:o=>n("addons","listUpdates","query",o),updatePackage:o=>n("addons","updatePackage","mutation",o),forceRefresh:o=>n("addons","forceRefresh","mutation",o),restartServer:o=>n("addons","restartServer","mutation",o),getVersions:o=>n("addons","getVersions","query",o),restartAddon:o=>n("addons","restartAddon","mutation",o),getAutoUpdateSettings:o=>n("addons","getAutoUpdateSettings","query",o),setAutoUpdateSettings:o=>n("addons","setAutoUpdateSettings","mutation",o),getAddonAutoUpdate:o=>n("addons","getAddonAutoUpdate","query",o),setAddonAutoUpdate:o=>n("addons","setAddonAutoUpdate","mutation",o),applyAutoUpdateToAll:o=>n("addons","applyAutoUpdateToAll","mutation",o),custom:o=>n("addons","custom","mutation",o),onAddonLogs:(o,N)=>n("addons","onAddonLogs","subscription",o,N)},addonSettings:{getGlobalSettings:o=>n("addonSettings","getGlobalSettings","query",o),updateGlobalSettings:o=>n("addonSettings","updateGlobalSettings","mutation",o)},addonWidgets:{listWidgets:o=>n("addonWidgets","listWidgets","query",o)},alerts:{emit:o=>n("alerts","emit","mutation",o),update:o=>n("alerts","update","mutation",o),list:o=>n("alerts","list","query",o),getUnreadCount:o=>n("alerts","getUnreadCount","query",o),markRead:o=>n("alerts","markRead","mutation",o),markAllRead:o=>n("alerts","markAllRead","mutation",o),dismiss:o=>n("alerts","dismiss","mutation",o)},audioAnalyzer:{analyseChunk:o=>n("audioAnalyzer","analyseChunk","mutation",o),classify:o=>n("audioAnalyzer","classify","query",o),isReady:o=>n("audioAnalyzer","isReady","query",o),dispose:o=>n("audioAnalyzer","dispose","mutation",o),reprobeAudioEngine:o=>n("audioAnalyzer","reprobeAudioEngine","mutation",o)},audioCodec:{listSupportedCodecs:o=>n("audioCodec","listSupportedCodecs","query",o),canHandle:o=>n("audioCodec","canHandle","query",o),createDecodeSession:o=>n("audioCodec","createDecodeSession","mutation",o),createEncodeSession:o=>n("audioCodec","createEncodeSession","mutation",o),closeSession:o=>n("audioCodec","closeSession","mutation",o),pushEncodedFrame:o=>n("audioCodec","pushEncodedFrame","mutation",o),pullPcm:o=>n("audioCodec","pullPcm","query",o),pushPcm:o=>n("audioCodec","pushPcm","mutation",o),pullEncoded:o=>n("audioCodec","pullEncoded","query",o),flushEncode:o=>n("audioCodec","flushEncode","mutation",o),listActiveSessions:o=>n("audioCodec","listActiveSessions","query",o)},backup:{trigger:o=>n("backup","trigger","mutation",o),list:o=>n("backup","list","query",o),restore:o=>n("backup","restore","mutation",o),delete:o=>n("backup","delete","mutation",o)},decoder:{supportsCodec:o=>n("decoder","supportsCodec","query",o),getInfo:o=>n("decoder","getInfo","query",o),createSession:o=>n("decoder","createSession","query",o),destroySession:o=>n("decoder","destroySession","query",o),pushPacket:o=>n("decoder","pushPacket","query",o),openStream:o=>n("decoder","openStream","query",o),pullFrames:o=>n("decoder","pullFrames","query",o),updateConfig:o=>n("decoder","updateConfig","query",o),getStats:o=>n("decoder","getStats","query",o),listActiveSessions:o=>n("decoder","listActiveSessions","query",o),reprobeHwaccel:o=>n("decoder","reprobeHwaccel","mutation",o)},deviceManager:{allocateDeviceId:o=>n("deviceManager","allocateDeviceId","mutation",o),registerDevice:o=>n("deviceManager","registerDevice","mutation",o),removeDevice:o=>n("deviceManager","removeDevice","mutation",o),persistConfig:o=>n("deviceManager","persistConfig","mutation",o),listLocations:o=>n("deviceManager","listLocations","query",o),addLocation:o=>n("deviceManager","addLocation","mutation",o),removeLocation:o=>n("deviceManager","removeLocation","mutation",o),listPersistedByAddon:o=>n("deviceManager","listPersistedByAddon","query",o),listAll:o=>n("deviceManager","listAll","query",o),getChildren:o=>n("deviceManager","getChildren","query",o),listWrappersForCap:o=>n("deviceManager","listWrappersForCap","query",o),listBindableCapsForDeviceType:o=>n("deviceManager","listBindableCapsForDeviceType","query",o),discoverDevices:o=>n("deviceManager","discoverDevices","mutation",o),adoptDevice:o=>n("deviceManager","adoptDevice","mutation",o),getCreationSchema:o=>n("deviceManager","getCreationSchema","query",o),createDevice:o=>n("deviceManager","createDevice","mutation",o),testCreationField:o=>n("deviceManager","testCreationField","mutation",o)},deviceProvider:{start:o=>n("deviceProvider","start","mutation",o),stop:o=>n("deviceProvider","stop","mutation",o),getStatus:o=>n("deviceProvider","getStatus","query",o),getDevices:o=>n("deviceProvider","getDevices","query",o),supportsDiscovery:o=>n("deviceProvider","supportsDiscovery","query",o),discoverDevices:o=>n("deviceProvider","discoverDevices","mutation",o),adoptDiscoveredDevice:o=>n("deviceProvider","adoptDiscoveredDevice","mutation",o),supportsManualCreation:o=>n("deviceProvider","supportsManualCreation","query",o),getChildCreationSchema:o=>n("deviceProvider","getChildCreationSchema","query",o),createDevice:o=>n("deviceProvider","createDevice","mutation",o),testCreationField:o=>n("deviceProvider","testCreationField","mutation",o)},deviceState:{getAllSnapshots:o=>n("deviceState","getAllSnapshots","query",o)},integrations:{list:o=>n("integrations","list","query",o),get:o=>n("integrations","get","query",o),getByAddonId:o=>n("integrations","getByAddonId","query",o),create:o=>n("integrations","create","mutation",o),update:o=>n("integrations","update","mutation",o),delete:o=>n("integrations","delete","mutation",o),getSettings:o=>n("integrations","getSettings","query",o),setSettings:o=>n("integrations","setSettings","mutation",o),getAvailableTypes:o=>n("integrations","getAvailableTypes","query",o),testConnection:o=>n("integrations","testConnection","mutation",o)},metricsProvider:{collectSnapshot:o=>n("metricsProvider","collectSnapshot","query",o),getCached:o=>n("metricsProvider","getCached","query",o),getCurrent:o=>n("metricsProvider","getCurrent","query",o),getDiskSpace:o=>n("metricsProvider","getDiskSpace","query",o),getGpuInfo:o=>n("metricsProvider","getGpuInfo","query",o),getCpuTemperature:o=>n("metricsProvider","getCpuTemperature","query",o),getProcessStats:o=>n("metricsProvider","getProcessStats","query",o),listAddonInstances:o=>n("metricsProvider","listAddonInstances","query",o),getAddonStats:o=>n("metricsProvider","getAddonStats","query",o),listNodeProcesses:o=>n("metricsProvider","listNodeProcesses","query",o),killProcess:o=>n("metricsProvider","killProcess","mutation",o)},networkQuality:{getAllStats:o=>n("networkQuality","getAllStats","query",o)},nodes:{topology:o=>n("nodes","topology","query",o),deployAddon:o=>n("nodes","deployAddon","mutation",o),undeployAddon:o=>n("nodes","undeployAddon","mutation",o),restartAddon:o=>n("nodes","restartAddon","mutation",o),restartProcess:o=>n("nodes","restartProcess","mutation",o),restartNode:o=>n("nodes","restartNode","mutation",o),shutdownNode:o=>n("nodes","shutdownNode","mutation",o),renameNode:o=>n("nodes","renameNode","mutation",o),clusterAddonStatus:o=>n("nodes","clusterAddonStatus","query",o),setProcessLogLevel:o=>n("nodes","setProcessLogLevel","mutation",o),executeQuery:o=>n("nodes","executeQuery","mutation",o)},notificationOutput:{send:o=>n("notificationOutput","send","mutation",o),sendTest:o=>n("notificationOutput","sendTest","mutation",o)},pipelineExecutor:{getAvailableEngines:o=>n("pipelineExecutor","getAvailableEngines","query",o),getSelectedEngine:o=>n("pipelineExecutor","getSelectedEngine","query",o),getDefaultSteps:o=>n("pipelineExecutor","getDefaultSteps","query",o),reprobeEngine:o=>n("pipelineExecutor","reprobeEngine","mutation",o),getVideoPipelineSteps:o=>n("pipelineExecutor","getVideoPipelineSteps","query",o),setVideoPipelineSteps:o=>n("pipelineExecutor","setVideoPipelineSteps","mutation",o),getSchema:o=>n("pipelineExecutor","getSchema","query",o),getGlobalSteps:o=>n("pipelineExecutor","getGlobalSteps","query",o),getGlobalPipelineConfig:o=>n("pipelineExecutor","getGlobalPipelineConfig","query",o),getOrchestratorConfigSchema:o=>n("pipelineExecutor","getOrchestratorConfigSchema","query",o),listTemplates:o=>n("pipelineExecutor","listTemplates","query",o),saveTemplate:o=>n("pipelineExecutor","saveTemplate","mutation",o),updateTemplate:o=>n("pipelineExecutor","updateTemplate","mutation",o),deleteTemplate:o=>n("pipelineExecutor","deleteTemplate","mutation",o),getCapabilities:o=>n("pipelineExecutor","getCapabilities","query",o),getAddonModels:o=>n("pipelineExecutor","getAddonModels","query",o),downloadModel:o=>n("pipelineExecutor","downloadModel","mutation",o),deleteModel:o=>n("pipelineExecutor","deleteModel","mutation",o),detect:o=>n("pipelineExecutor","detect","query",o),cacheFrameInPool:o=>n("pipelineExecutor","cacheFrameInPool","mutation",o),inferCached:o=>n("pipelineExecutor","inferCached","mutation",o),uncacheFrame:o=>n("pipelineExecutor","uncacheFrame","mutation",o),getEffectiveTuning:o=>n("pipelineExecutor","getEffectiveTuning","query",o),listLoadedEngines:o=>n("pipelineExecutor","listLoadedEngines","query",o),spinEngine:o=>n("pipelineExecutor","spinEngine","mutation",o),killEngine:o=>n("pipelineExecutor","killEngine","mutation",o),listReferenceImages:o=>n("pipelineExecutor","listReferenceImages","query",o),getReferenceImage:o=>n("pipelineExecutor","getReferenceImage","query",o),getReferenceAudioFiles:o=>n("pipelineExecutor","getReferenceAudioFiles","query",o),getReferenceAudio:o=>n("pipelineExecutor","getReferenceAudio","query",o),getAudioCapabilities:o=>n("pipelineExecutor","getAudioCapabilities","query",o),runAudioTest:o=>n("pipelineExecutor","runAudioTest","mutation",o),getDetectionConfigSchema:o=>n("pipelineExecutor","getDetectionConfigSchema","query",o)},pipelineOrchestrator:{rebalance:o=>n("pipelineOrchestrator","rebalance","mutation",o),getPipelineAssignments:o=>n("pipelineOrchestrator","getPipelineAssignments","query",o),getAgentLoad:o=>n("pipelineOrchestrator","getAgentLoad","query",o),getGlobalMetrics:o=>n("pipelineOrchestrator","getGlobalMetrics","query",o),getCapabilityBindings:o=>n("pipelineOrchestrator","getCapabilityBindings","query",o),setCapabilityBinding:o=>n("pipelineOrchestrator","setCapabilityBinding","mutation",o),getDecoderAssignments:o=>n("pipelineOrchestrator","getDecoderAssignments","query",o),getAudioNodeLoad:o=>n("pipelineOrchestrator","getAudioNodeLoad","query",o),getAgentSettings:o=>n("pipelineOrchestrator","getAgentSettings","query",o),listAgentSettings:o=>n("pipelineOrchestrator","listAgentSettings","query",o),setAgentAddonDefaults:o=>n("pipelineOrchestrator","setAgentAddonDefaults","mutation",o),removeAgentSettings:o=>n("pipelineOrchestrator","removeAgentSettings","mutation",o),listTemplates:o=>n("pipelineOrchestrator","listTemplates","query",o),saveTemplate:o=>n("pipelineOrchestrator","saveTemplate","mutation",o),updateTemplate:o=>n("pipelineOrchestrator","updateTemplate","mutation",o),deleteTemplate:o=>n("pipelineOrchestrator","deleteTemplate","mutation",o)},pipelineRunner:{attachCamera:o=>n("pipelineRunner","attachCamera","mutation",o),reportMotion:o=>n("pipelineRunner","reportMotion","mutation",o),getLocalLoad:o=>n("pipelineRunner","getLocalLoad","query",o),getLocalMetrics:o=>n("pipelineRunner","getLocalMetrics","query",o),getAllCameraMetrics:o=>n("pipelineRunner","getAllCameraMetrics","query",o),getLocalCameras:o=>n("pipelineRunner","getLocalCameras","query",o)},platformProbe:{getCapabilities:o=>n("platformProbe","getCapabilities","query",o),getHardware:o=>n("platformProbe","getHardware","query",o),resolveInferenceConfig:o=>n("platformProbe","resolveInferenceConfig","query",o),resolveHwAccel:o=>n("platformProbe","resolveHwAccel","query",o)},recordingEngine:{getStatus:o=>n("recordingEngine","getStatus","query",o),enable:o=>n("recordingEngine","enable","mutation",o),disable:o=>n("recordingEngine","disable","mutation",o),getConfig:o=>n("recordingEngine","getConfig","query",o),updateConfig:o=>n("recordingEngine","updateConfig","mutation",o),getPlaylist:o=>n("recordingEngine","getPlaylist","query",o),getThumbnail:o=>n("recordingEngine","getThumbnail","query",o),getSegments:o=>n("recordingEngine","getSegments","query",o),getAvailability:o=>n("recordingEngine","getAvailability","query",o),estimateStorage:o=>n("recordingEngine","estimateStorage","query",o),estimateGlobalStorage:o=>n("recordingEngine","estimateGlobalStorage","query",o),getStorageUsage:o=>n("recordingEngine","getStorageUsage","query",o),setPolicy:o=>n("recordingEngine","setPolicy","mutation",o),getPolicy:o=>n("recordingEngine","getPolicy","query",o),getRetentionConfig:o=>n("recordingEngine","getRetentionConfig","query",o),updateRetentionConfig:o=>n("recordingEngine","updateRetentionConfig","mutation",o),getMotionStats:o=>n("recordingEngine","getMotionStats","query",o)},settingsStore:{get:o=>n("settingsStore","get","query",o),set:o=>n("settingsStore","set","mutation",o),query:o=>n("settingsStore","query","query",o),insert:o=>n("settingsStore","insert","mutation",o),update:o=>n("settingsStore","update","mutation",o),delete:o=>n("settingsStore","delete","mutation",o),count:o=>n("settingsStore","count","query",o),isEmpty:o=>n("settingsStore","isEmpty","query",o),declareCollection:o=>n("settingsStore","declareCollection","mutation",o)},storage:{resolve:o=>n("storage","resolve","query",o),write:o=>n("storage","write","mutation",o),read:o=>n("storage","read","query",o),exists:o=>n("storage","exists","query",o),list:o=>n("storage","list","query",o),delete:o=>n("storage","delete","mutation",o),getAvailableSpace:o=>n("storage","getAvailableSpace","query",o)},streamBroker:{listAllCameraStreams:o=>n("streamBroker","listAllCameraStreams","query",o),listAllProfileSlots:o=>n("streamBroker","listAllProfileSlots","query",o),getBrokerStats:o=>n("streamBroker","getBrokerStats","query",o),listClients:o=>n("streamBroker","listClients","query",o),killClient:o=>n("streamBroker","killClient","mutation",o),getStreamUrl:o=>n("streamBroker","getStreamUrl","query",o),getBroker:o=>n("streamBroker","getBroker","query",o),setPreBufferDuration:o=>n("streamBroker","setPreBufferDuration","mutation",o),getPreBufferInfo:o=>n("streamBroker","getPreBufferInfo","query",o),getRtspPort:o=>n("streamBroker","getRtspPort","query",o),getAllRtspEntries:o=>n("streamBroker","getAllRtspEntries","query",o),getRtspEntry:o=>n("streamBroker","getRtspEntry","query",o),regenerateRtspToken:o=>n("streamBroker","regenerateRtspToken","mutation",o),setRtspEnabled:o=>n("streamBroker","setRtspEnabled","mutation",o),isRtspEnabled:o=>n("streamBroker","isRtspEnabled","query",o)},system:{info:o=>n("system","info","query",o),health:o=>n("system","health","query",o),featureFlags:o=>n("system","featureFlags","query",o),networkAddresses:o=>n("system","networkAddresses","query",o),getRetentionConfig:o=>n("system","getRetentionConfig","query",o),setRetentionConfig:o=>n("system","setRetentionConfig","mutation",o),forceRetentionCleanup:o=>n("system","forceRetentionCleanup","mutation",o)},toast:{onToast:(o,N)=>n("toast","onToast","subscription",o,N)},turnProvider:{getTurnServers:o=>n("turnProvider","getTurnServers","query",o)},userManagement:{listUsers:o=>n("userManagement","listUsers","query",o),createUser:o=>n("userManagement","createUser","mutation",o),updateUser:o=>n("userManagement","updateUser","mutation",o),deleteUser:o=>n("userManagement","deleteUser","mutation",o),resetPassword:o=>n("userManagement","resetPassword","mutation",o),validateCredentials:o=>n("userManagement","validateCredentials","mutation",o),listApiKeys:o=>n("userManagement","listApiKeys","query",o),createApiKey:o=>n("userManagement","createApiKey","mutation",o),revokeApiKey:o=>n("userManagement","revokeApiKey","mutation",o),validateApiKey:o=>n("userManagement","validateApiKey","mutation",o),createScopedToken:o=>n("userManagement","createScopedToken","mutation",o),revokeScopedToken:o=>n("userManagement","revokeScopedToken","mutation",o),validateScopedToken:o=>n("userManagement","validateScopedToken","query",o),listScopedTokens:o=>n("userManagement","listScopedTokens","query",o)}}}var Xo="device.state-changed",er="capability.binding-changed",tr="device.registered",ar="device.unregistered",ir="device.updated",Hl=class{constructor(t){this.api=t,this.stateSource=Zo(this.stateMirror,this.handleListeners,this.api)}api;stateMirror=new Map;bindings=new Map;devices=new Map;handleListeners=new Map;globalStateListeners=new Set;capListeners=new Map;deviceListeners=new Map;addedListeners=new Set;removedListeners=new Set;pendingWaits=new Set;stateSource;bridges=[];initialized=!1;initPromise=null;async init(t=15e3){if(!this.initialized){if(this.initPromise)return this.initPromise;this.initPromise=(async()=>{const r=(h,y)=>Number.isFinite(t)?new Promise((m,g)=>{const A=setTimeout(()=>g(new Error(`SystemMirror.init: '${y}' timed out after ${t}ms`)),t);h.then(k=>{clearTimeout(A),m(k)},k=>{clearTimeout(A),g(k)})}):h,[n,c,u]=await Promise.all([r(this.api.deviceManager.getAllBindings.query({}),"deviceManager.getAllBindings"),r(this.api.deviceState.getAllSnapshots.query({}),"deviceState.getAllSnapshots"),r(this.api.deviceManager.listAll.query({}),"deviceManager.listAll")]);for(const h of n)this.bindings.set(h.deviceId,h);for(const[h,y]of Object.entries(c)){const m=Number(h);if(!Number.isFinite(m))continue;const g=new Map;for(const[A,k]of Object.entries(y))g.set(A,k);this.stateMirror.set(m,g)}for(const h of u)this.devices.set(h.id,h);try{this.subscribeBus()}catch{}this.initialized=!0})();try{await this.initPromise}finally{this.initPromise=null}}}isReady(){return this.initialized}async awaitReady(){if(!this.initialized)return this.initPromise?this.initPromise:this.init()}dispose(){for(const t of this.bridges)try{t.unsubscribe()}catch{}this.bridges=[],this.handleListeners.clear(),this.globalStateListeners.clear(),this.capListeners.clear(),this.deviceListeners.clear(),this.addedListeners.clear(),this.removedListeners.clear(),this.pendingWaits.clear(),this.initialized=!1}getDeviceById(t){const r=this.bindings.get(t);return r?Qo(this.api,r,{stateSource:this.stateSource}):null}getDeviceByName(t){for(const r of this.devices.values())if(r.name===t)return this.getDeviceById(r.id);return null}getDeviceByStableId(t){for(const r of this.devices.values())if(r.stableId===t)return this.getDeviceById(r.id);return null}getDevicesByAddon(t){return this.query({addonId:t})}getDevicesByType(t){return this.query({type:t})}getDeviceInfo(t){return this.devices.get(t)??null}getAllDevices(){const t=[];for(const r of this.bindings.keys()){const n=this.getDeviceById(r);n&&t.push(n)}return t}filterByCap(t){return this.query({caps:t})}query(t={}){const r=[];for(const[n,c]of this.bindings){const u=this.devices.get(n);if(t.id!==void 0&&!pe(n,t.id)||t.stableId!==void 0&&(!u||!pe(u.stableId,t.stableId))||t.addonId!==void 0&&(!u||!pe(u.addonId,t.addonId))||t.type!==void 0&&(!u||!pe(u.type,t.type)))continue;if(t.caps!==void 0){const y=_e(t.caps),m=new Set(c.entries.map(g=>g.capName));if(!y.every(g=>m.has(g)))continue}if(t.anyCap!==void 0){const y=_e(t.anyCap),m=new Set(c.entries.map(g=>g.capName));if(!y.some(g=>m.has(g)))continue}if(t.name!==void 0&&(!u||!nr(u.name,t.name))||t.online!==void 0&&(!u||u.online!==t.online))continue;if(t.parentDeviceId!==void 0){if(!u)continue;const y=t.parentDeviceId;if((u.parentDeviceId??null)!==y)continue}if(t.feature!==void 0&&(!u||!_e(t.feature).every(m=>u.features.includes(m)))||t.isCamera!==void 0&&(!u||u.isCamera!==t.isCamera))continue;const h=this.getDeviceById(n);if(h){if(t.where&&u){if(!t.where(u,h))continue}else if(t.where&&!u)continue;r.push(h)}}return r}whereState(t,r){const n=[];for(const[c,u]of this.stateMirror){const h=u.get(t);if(!h||!r(h,c))continue;const y=this.getDeviceById(c);y&&n.push(y)}return n}mapState(t,r){const n=[];for(const[c,u]of this.stateMirror){const h=u.get(t);h&&n.push(r(h,c))}return n}findState(t,r){for(const[n,c]of this.stateMirror){const u=c.get(t);if(u&&r(u,n))return this.getDeviceById(n)}return null}countByCap(t){let r=0;for(const n of this.bindings.values())n.entries.some(c=>c.capName===t)&&r++;return r}countByState(t,r){let n=0;for(const[c,u]of this.stateMirror){const h=u.get(t);h&&r(h,c)&&n++}return n}listen(t){return this.globalStateListeners.add(t),()=>{this.globalStateListeners.delete(t)}}listenCap(t,r){let n=this.capListeners.get(t);return n||(n=new Set,this.capListeners.set(t,n)),n.add(r),()=>{n.delete(r),n.size===0&&this.capListeners.delete(t)}}listenDevice(t,r){let n=this.deviceListeners.get(t);return n||(n=new Set,this.deviceListeners.set(t,n)),n.add(r),()=>{n.delete(r),n.size===0&&this.deviceListeners.delete(t)}}onDeviceAdded(t){return this.addedListeners.add(t),()=>{this.addedListeners.delete(t)}}onDeviceRemoved(t){return this.removedListeners.add(t),()=>{this.removedListeners.delete(t)}}waitForState(t,r,n,c=3e4){return new Promise((u,h)=>{const m=(()=>{const k=this.stateMirror.get(t)?.get(r);return k&&n(k)?k:null})();if(m){u(m);return}let g=null;const A=this.listenDevice(t,(k,C,w)=>{C===r&&w&&n(w)&&(g&&clearTimeout(g),A(),u(w))});Number.isFinite(c)&&(g=setTimeout(()=>{A(),h(new Error(`waitForState timed out after ${c}ms (deviceId=${t}, capName=${r})`))},c))})}waitForDevice(t,r=3e4){return new Promise((n,c)=>{const u=this.getDeviceById(t);if(u){n(u);return}let h=null;const y=this.onDeviceAdded(m=>{if(m!==t)return;const g=this.getDeviceById(m);g&&(h&&clearTimeout(h),y(),n(g))});Number.isFinite(r)&&(h=setTimeout(()=>{y(),c(new Error(`waitForDevice timed out after ${r}ms (deviceId=${t})`))},r))})}async forEachCap(t,r){for(const n of this.filterByCap(t))await r(n)}async invokeCap(t,r,n,c={}){const u=this.filterByCap(t),h=Math.max(1,c.parallelism??u.length),y=[];for(let m=0;m<u.length;m+=h){const g=u.slice(m,m+h),A=await Promise.allSettled(g.map(async k=>{const C=k[t];if(!C||typeof C[r]!="function")throw new Error(`device '${k.deviceId}' does not expose '${t}.${r}'`);return await C[r](n)}));for(let k=0;k<A.length;k++){const C=g[k],w=A[k];w.status==="fulfilled"?y.push({deviceId:C.deviceId,ok:!0,result:w.value}):y.push({deviceId:C.deviceId,ok:!1,error:w.reason})}}return y}summary(){const t={},r={},n={};let c=0,u=0;for(const h of this.bindings.values())for(const y of h.entries)t[y.capName]=(t[y.capName]??0)+1;for(const h of this.devices.values())r[h.addonId]=(r[h.addonId]??0)+1,n[h.type]=(n[h.type]??0)+1,h.online?c++:u++;return{totalDevices:this.bindings.size,online:c,offline:u,byCap:t,byAddon:r,byType:n,statedDevices:this.stateMirror.size}}dump(t){const r=c=>{const u=this.devices.get(c)??null,h=this.bindings.get(c)??null,y={},m=this.stateMirror.get(c);if(m)for(const[g,A]of m)y[g]={...A};return{deviceId:c,info:u,binding:h?{...h,entries:h.entries.map(g=>({...g}))}:null,state:y}};if(t!==void 0)return r(t);const n=[];for(const c of this.bindings.keys())n.push(r(c));return n}getRawMirror(){return this.stateMirror}getSystemState(){const t=new Map;for(const[r,n]of this.stateMirror){const c=new Map;for(const[u,h]of n)c.set(u,{...h});t.set(r,c)}return t}subscribeBus(){if(!this.api.live?.onEvent)return;const t=this.api.live.onEvent;this.bridges.push(t.subscribe({category:Xo},{onData:r=>{const n=r.data;!n||typeof n.deviceId!="number"||typeof n.capName!="string"||this.applyStateUpdate(n.deviceId,n.capName,n.slice)}})),this.bridges.push(t.subscribe({category:er},{onData:r=>{const n=r.data,c=typeof n?.deviceId=="number"?n.deviceId:n?.source?.type==="device"&&typeof n.source.id=="number"?n.source.id:null;c!==null&&this.refreshBinding(c)}})),this.bridges.push(t.subscribe({category:tr},{onData:r=>{const n=r.data;typeof n?.deviceId=="number"&&this.refreshDeviceMetadata(n.deviceId,"added")}})),this.bridges.push(t.subscribe({category:ar},{onData:r=>{const n=r.data;typeof n?.deviceId=="number"&&this.applyDeviceRemoval(n.deviceId)}})),this.bridges.push(t.subscribe({category:ir},{onData:r=>{const n=r.data;typeof n?.deviceId=="number"&&this.refreshDeviceMetadata(n.deviceId,"updated")}}))}applyStateUpdate(t,r,n){let c=this.stateMirror.get(t);c||(c=new Map,this.stateMirror.set(t,c)),n===void 0?c.delete(r):c.set(r,n);const u=`${t}:${r}`,h=this.handleListeners.get(u);if(h)for(const g of h)try{g(n)}catch{}for(const g of this.globalStateListeners)try{g(t,r,n)}catch{}const y=this.capListeners.get(r);if(y)for(const g of y)try{g(t,n)}catch{}const m=this.deviceListeners.get(t);if(m)for(const g of m)try{g(t,r,n)}catch{}}applyDeviceRemoval(t){const r=this.devices.get(t)??null;this.bindings.delete(t),this.devices.delete(t),this.stateMirror.delete(t);for(const n of this.removedListeners)try{n(t,r)}catch{}}async refreshBinding(t){try{const n=(await this.api.deviceManager.getAllBindings.query({})).find(c=>c.deviceId===t);n?this.bindings.set(t,n):this.applyDeviceRemoval(t)}catch{}}async refreshDeviceMetadata(t,r){try{const c=(await this.api.deviceManager.listAll.query({})).find(h=>h.id===t);if(!c)return;const u=!this.devices.has(t);if(this.devices.set(t,c),r==="added"&&u){await this.refreshBinding(t);for(const h of this.addedListeners)try{h(t,c)}catch{}}}catch{}}};function pe(t,r){return Array.isArray(r)?r.includes(t):t===r}function _e(t){return Array.isArray(t)?t:[t]}function nr(t,r){return typeof r=="string"?t===r:r instanceof RegExp?r.test(t):"exact"in r?t===r.exact:"contains"in r?t.toLowerCase().includes(r.contains.toLowerCase()):!1}function Wl(t){return t}function $l(t,r,n){return{input:t,output:r,kind:n?.kind??"query",auth:n?.auth??"protected",scope:n?.scope??{kind:"system"}}}var or=i({id:e(),label:e(),icon:e(),order:a().optional()}),rr=i({id:e(),title:e(),description:e().optional(),style:f(["card","accordion"]).optional(),defaultCollapsed:v().optional(),columns:M([I(1),I(2),I(3),I(4)]).optional(),tab:e().optional(),location:f(["settings","top-tab"]).optional(),order:a().optional(),fields:l(Ra())}),V=i({tabs:l(or).optional(),sections:l(rr)}),Xt=b(e(),S()),ea=i({success:I(!0)}),sr={name:"addon-settings",scope:"system",mode:"singleton",nodeIdMode:"data",methods:{getGlobalSettings:s(i({addonId:e(),nodeId:e().optional(),overlay:b(e(),S()).optional()}),V.nullable()),updateGlobalSettings:s(i({addonId:e(),nodeId:e().optional(),patch:Xt}),ea,{kind:"mutation",auth:"admin"}),getDeviceSettings:s(i({addonId:e(),deviceId:a(),nodeId:e().optional()}),V.nullable()),updateDeviceSettings:s(i({addonId:e(),deviceId:a(),nodeId:e().optional(),patch:Xt}),ea,{kind:"mutation",auth:"admin"})}},dr=f(["info","success","warning","error"]),cr=f(["active","in-progress","completed","failed","dismissed"]),lr=i({type:e(),id:e()}),ze=i({id:e(),category:e(),severity:dr,title:e(),message:e(),status:cr,progress:a().optional(),read:v(),createdAt:a(),updatedAt:a(),source:lr.optional(),metadata:b(e(),S()).optional()}),ur={name:"alerts",scope:"system",mode:"singleton",methods:{emit:s(ze,p(),{kind:"mutation"}),update:s(i({alertId:e(),patch:ze.partial()}),p(),{kind:"mutation"}),list:s(i({unreadOnly:v().optional(),limit:a().optional()}).optional(),l(ze).readonly()),getUnreadCount:s(p(),a()),markRead:s(i({alertId:e()}),p(),{kind:"mutation"}),markAllRead:s(p(),p(),{kind:"mutation"}),dismiss:s(i({alertId:e()}),p(),{kind:"mutation"})}},L=f(["data","media","recordings","models","cache","logs","addons-data"]),mr={name:"storage",scope:"system",mode:"collection",methods:{resolve:s(i({location:L,relativePath:e()}),e()),write:s(i({location:L,relativePath:e()}),p(),{kind:"mutation"}),read:s(i({location:L,relativePath:e()}),T(Uint8Array)),exists:s(i({location:L,relativePath:e()}),v()),list:s(i({location:L,prefix:e().optional()}),l(e()).readonly()),delete:s(i({location:L,relativePath:e()}),p(),{kind:"mutation"}),getAvailableSpace:s(i({location:L}),a().nullable())}},ta=i({id:e(),label:e().optional(),createdAt:a(),sizeBytes:a(),locations:l(e()).optional()}),pr={name:"backup",scope:"system",mode:"singleton",methods:{trigger:s(i({locations:l(e()).optional(),label:e().optional()}).optional(),ta,{kind:"mutation",auth:"superAdmin"}),list:s(p(),l(ta).readonly(),{auth:"superAdmin"}),restore:s(i({backupId:e()}),p(),{kind:"mutation",auth:"superAdmin"}),delete:s(i({backupId:e()}),p(),{kind:"mutation",auth:"superAdmin"})}},aa=i({where:b(e(),S()).optional(),whereIn:b(e(),l(S())).optional(),whereBetween:b(e(),Ma([S(),S()])).optional(),orderBy:i({field:e(),direction:f(["asc","desc"])}).optional(),limit:a().optional(),offset:a().optional()}),ia=i({id:e(),data:b(e(),S())}),gr=i({name:e(),type:f(["TEXT","INTEGER","REAL","JSON"]),primaryKey:v().optional(),notNull:v().optional(),unique:v().optional()}),hr=i({name:e(),columns:l(e()).readonly(),unique:v().optional()}),vr={name:"settings-store",scope:"system",mode:"singleton",methods:{get:s(i({namespace:e().optional(),collection:e(),key:e()}),S()),set:s(i({namespace:e().optional(),collection:e(),key:e(),value:S()}),p(),{kind:"mutation"}),query:s(i({namespace:e().optional(),collection:e(),filter:aa.optional()}),l(ia).readonly()),insert:s(i({namespace:e().optional(),collection:e(),record:ia}),p(),{kind:"mutation"}),update:s(i({namespace:e().optional(),collection:e(),id:e(),data:b(e(),S())}),p(),{kind:"mutation"}),delete:s(i({namespace:e().optional(),collection:e(),key:e()}),p(),{kind:"mutation"}),count:s(i({namespace:e().optional(),collection:e(),filter:aa.optional()}),a()),isEmpty:s(i({namespace:e().optional(),collection:e()}),v()),declareCollection:s(i({namespace:e().optional(),collection:e(),columns:l(gr).readonly(),indexes:l(hr).readonly().optional()}),p(),{kind:"mutation"})}},ei=f(["debug","info","warn","error"]),na=i({timestamp:Ve(),level:ei,scope:l(e()),message:e(),meta:b(e(),S()).optional(),tags:b(e(),e()).optional()}),yr={name:"log-destination",scope:"system",mode:"collection",internal:!0,methods:{write:s(na,p(),{kind:"mutation"}),query:s(i({scope:l(e()).optional(),level:ei.optional(),since:Ve().optional(),until:Ve().optional(),limit:a().optional(),tags:b(e(),e()).optional()}),l(na).readonly())}},fr={name:"admin-ui",scope:"system",mode:"singleton",internal:!0,methods:{getStaticDir:s(p(),e()),getVersion:s(p(),e())}},Sr=i({id:e(),label:e(),icon:e(),path:e(),remoteName:e(),bundle:e()}),br=i({addonId:e(),page:Sr,bundleUrl:e()}),Ir={name:"addon-pages",scope:"system",mode:"singleton",methods:{listPages:s(p(),l(br).readonly())}},kr=i({id:e(),label:e(),icon:e(),path:e(),remoteName:e(),bundle:e()}),Ar={name:"addon-pages-source",scope:"system",mode:"collection",internal:!0,methods:{listPages:s(p(),l(kr).readonly())}},Cr=f(["device-tab","dashboard","integration-detail"]),oa=f(["xs","sm","md","lg","xl"]),ti=i({stableId:e(),label:e(),description:e().optional(),icon:e().optional(),remoteName:e(),bundle:e(),hosts:l(Cr).readonly(),requires:i({deviceContext:v().default(!1),integrationContext:v().default(!1)}),defaultSize:oa.default("md"),allowedSizes:l(oa).readonly().default(["sm","md","lg"]),defaultColumns:a().int().min(1).max(12).default(6),defaultRows:a().int().min(1).max(12).default(1)}),wr={name:"addon-widgets-source",scope:"system",mode:"collection",internal:!0,methods:{listWidgets:s(p(),l(ti).readonly())}},Pr=ti.extend({addonId:e(),bundleUrl:e()}),Dr={name:"addon-widgets",scope:"system",mode:"singleton",methods:{listWidgets:s(p(),l(Pr).readonly())}},Mr=i({method:f(["GET","POST","PUT","DELETE","PATCH"]),path:e()}),Tr={name:"addon-routes",scope:"system",mode:"collection",internal:!0,methods:{getRoutes:s(p(),l(Mr))}},Gl=[{value:"auto",label:"Auto (defer to probed best)"},{value:"none",label:"Off (software)"},{value:"videotoolbox",label:"VideoToolbox (macOS)"},{value:"cuda",label:"CUDA (NVIDIA)"},{value:"nvdec",label:"NVDEC (NVIDIA legacy)"},{value:"vaapi",label:"VAAPI (Linux Intel/AMD)"},{value:"qsv",label:"QuickSync (Intel)"},{value:"d3d11va",label:"D3D11VA (Windows)"},{value:"dxva2",label:"DXVA2 (Windows legacy)"},{value:"amf",label:"AMF (AMD)"},{value:"vdpau",label:"VDPAU (Linux NVIDIA legacy)"},{value:"drm",label:"DRM (Linux generic)"}],jl={hwaccel:"auto",probedBestHwaccel:""},Rr={name:"decoder",scope:"system",mode:"singleton",methods:{supportsCodec:s(i({codec:e()}),v()),getInfo:s(p(),i({id:e(),name:e(),isPullMode:v().optional(),priority:a().optional()})),createSession:s(Ft,i({sessionId:e(),nodeId:e()})),destroySession:s(i({sessionId:e()}),p()),pushPacket:s(i({sessionId:e(),packet:On}),p()),openStream:s(i({sessionId:e(),url:e()}),p()),pullFrames:s(i({sessionId:e(),maxCount:a().default(1)}),l(Nn)),updateConfig:s(i({sessionId:e(),config:Ft.partial()}),p()),getStats:s(i({sessionId:e()}),nn),listActiveSessions:s(p(),l(i({sessionId:e(),codec:e(),outputFormat:e(),createdAtMs:a()})).readonly()),reprobeHwaccel:s(p(),i({backend:e()}),{kind:"mutation",auth:"admin"})}},Er=i({streamId:e(),label:e().optional(),codec:e(),type:f(["video","audio"]),sourceUrl:e()}),qr=i({streamId:e(),format:e(),value:e()}),xr={name:"restreamer",scope:"system",mode:"collection",internal:!0,methods:{registerDevice:s(i({deviceId:a(),streams:l(Er).readonly()}),p(),{kind:"mutation"}),unregisterDevice:s(i({deviceId:a()}),p(),{kind:"mutation"}),getExposedResources:s(i({deviceId:a()}),l(qr).readonly())}},ai=i({viewportWidth:a().int().positive().optional(),viewportHeight:a().int().positive().optional(),devicePixelRatio:a().positive().optional(),downlinkMbps:a().nonnegative().optional(),prefersTier:e().optional()}).partial(),Br={name:"webrtc",scope:"system",mode:"collection",internal:!0,methods:{handleOffer:s(i({streamId:e(),sdpOffer:e()}),e(),{kind:"mutation"}),supportsStream:s(i({streamId:e()}),v()),registerStream:s(i({streamId:e(),codec:e()}),p(),{kind:"mutation"}),unregisterStream:s(i({streamId:e()}),p(),{kind:"mutation"}),createSession:s(i({streamId:e(),hints:ai.optional()}),i({sessionId:e(),sdpOffer:e()}),{kind:"mutation"}),handleAnswer:s(i({sessionId:e(),sdpAnswer:e()}),p(),{kind:"mutation"}),closeSession:s(i({sessionId:e()}),p(),{kind:"mutation"}),hasAdaptiveBitrate:s(i({streamId:e()}),v())}},ii=Ri("kind",[i({kind:I("adaptive")}),i({kind:I("profile"),profile:U}),i({kind:I("cam-stream"),camStreamId:e().min(1)})]),Or=i({id:e(),label:e(),target:ii,codec:e().nullable(),resolution:i({width:a(),height:a()}).nullable(),status:f(["idle","connecting","streaming","error","stopped"]).nullable(),inputFps:a().nullable(),decodeFps:a().nullable(),bitrateKbps:a().nullable()}),Nr={name:"webrtc-session",scope:"device",mode:"singleton",deviceTypes:["camera"],methods:{listStreams:s(i({deviceId:a().int().nonnegative()}),l(Or)),createSession:s(i({deviceId:a().int().nonnegative(),target:ii,hints:ai.optional()}),i({sessionId:e(),sdpOffer:e()}),{kind:"mutation"}),handleAnswer:s(i({deviceId:a().int().nonnegative(),sessionId:e(),sdpAnswer:e()}),p(),{kind:"mutation"}),closeSession:s(i({deviceId:a().int().nonnegative(),sessionId:e()}),p(),{kind:"mutation"}),hasAdaptiveBitrate:s(i({deviceId:a().int().nonnegative(),profile:U}),v())}},be=i({engine:P,steps:l(K).readonly(),audio:i({engine:P,modelId:e(),enabled:v(),settings:b(e(),S()).readonly().optional()}).nullable().optional()}),Fe=i({id:e(),name:e(),description:e().optional(),config:be,createdAt:e(),updatedAt:e()}),ni=i({enabled:v(),modelId:e(),settings:b(e(),S()).readonly()}),ra=i({addonDefaults:b(e(),ni).readonly()}),oi=i({steps:l(K).readonly(),audio:i({modelId:e(),enabled:v()}).nullable()}),ot=i({enabled:v().optional(),modelId:e().optional(),settings:b(e(),S()).readonly().optional()}),_r=i({pinnedAgentNodeId:e().optional(),stepToggles:b(e(),v()).optional(),stepOverridesByAgent:b(e(),b(e(),ot)).optional(),pipelineByAgent:b(e(),oi).optional()}),sa=i({deviceId:a(),agentNodeId:e(),pinned:v(),reason:f(["manual","capacity","hardware-affinity","failover","rebalance"]),assignedAt:a()}),da=i({deviceId:a(),decoderNodeId:e(),pinned:v(),reason:f(["manual","co-located","capacity","hardware-affinity"])}),zr=i({nodeId:e(),online:v(),load:Wa,score:a()}),Fr=i({totalAgents:a(),onlineAgents:a(),totalCameras:a(),attachedCameras:a(),activeCameras:a(),avgInferenceTimeMs:a(),queueDepth:a()}),Lr=b(e(),e()),Ur={name:"pipeline-orchestrator",scope:"system",mode:"singleton",exposesDeviceSettings:!0,methods:{assignPipeline:s(i({deviceId:a(),agentNodeId:e()}),i({success:I(!0)}),{kind:"mutation",auth:"admin"}),unassignPipeline:s(i({deviceId:a()}),i({success:I(!0)}),{kind:"mutation",auth:"admin"}),rebalance:s(p(),i({migrated:a()}),{kind:"mutation",auth:"admin"}),getPipelineAssignments:s(p(),l(sa).readonly()),getPipelineAssignment:s(i({deviceId:a()}),sa.nullable()),getAgentLoad:s(p(),l(zr).readonly()),getGlobalMetrics:s(p(),Fr),getCameraMetrics:s(i({deviceId:a()}),bt.nullable()),getCapabilityBindings:s(i({nodeId:e()}),Lr),setCapabilityBinding:s(i({nodeId:e(),capName:e(),addonId:e()}),i({success:I(!0)}),{kind:"mutation",auth:"admin"}),assignDecoder:s(i({deviceId:a(),nodeId:e()}),p(),{kind:"mutation",auth:"admin"}),unassignDecoder:s(i({deviceId:a()}),p(),{kind:"mutation",auth:"admin"}),getDecoderAssignments:s(p(),l(da).readonly()),assignAudio:s(i({deviceId:a(),nodeId:e()}),i({success:I(!0)}),{kind:"mutation",auth:"admin"}),unassignAudio:s(i({deviceId:a()}),i({success:I(!0)}),{kind:"mutation",auth:"admin"}),getAudioAssignment:s(i({deviceId:a()}),i({nodeId:e(),pinned:v(),assignedAt:a()}).nullable()),getAudioNodeLoad:s(p(),l(i({nodeId:e(),deviceCount:a()}))),getAudioAssignments:s(p(),l(i({deviceId:a(),nodeId:e(),pinned:v(),assignedAt:a()}))),getDecoderAssignment:s(i({deviceId:a(),pipelineNodeId:e().optional()}),da),getAgentSettings:s(i({agentNodeId:e()}),ra.nullable()),listAgentSettings:s(p(),l(i({nodeId:e(),settings:ra})).readonly()),setAgentAddonDefaults:s(i({agentNodeId:e(),defaults:b(e(),ni)}),i({success:I(!0)}),{kind:"mutation",auth:"admin"}),removeAgentSettings:s(i({agentNodeId:e()}),i({success:v(),removed:v()}),{kind:"mutation",auth:"admin"}),getCameraSettings:s(i({deviceId:a()}),_r.nullable()),setCameraStepToggle:s(i({deviceId:a(),addonId:e(),enabled:v().nullable()}),i({success:I(!0)}),{kind:"mutation",auth:"admin"}),getCameraStepOverrides:s(i({deviceId:a()}),b(e(),b(e(),ot)).nullable()),setCameraStepOverride:s(i({deviceId:a(),agentNodeId:e(),addonId:e(),patch:ot.nullable()}),i({success:I(!0)}),{kind:"mutation",auth:"admin"}),setCameraPipelineForAgent:s(i({deviceId:a(),agentNodeId:e(),pipeline:oi.nullable()}),i({success:I(!0)}),{kind:"mutation",auth:"admin"}),resolvePipeline:s(i({deviceId:a(),agentNodeId:e().optional()}),be),listTemplates:s(p(),l(Fe).readonly()),saveTemplate:s(i({name:e(),description:e().optional(),config:be}),Fe,{kind:"mutation",auth:"admin"}),updateTemplate:s(i({id:e(),name:e().optional(),description:e().optional(),config:be.optional()}),Fe,{kind:"mutation",auth:"admin"}),deleteTemplate:s(i({id:e()}),i({success:I(!0)}),{kind:"mutation",auth:"admin"})}},Hr=i({level:Yn,classification:i({labels:l(Xe).readonly(),inferenceMs:a()}).optional(),timestamp:a()}),Wr=i({minConfidence:a().min(0).max(1).default(.3),allowedClasses:l(e()).default([])}),$r=i({labels:l(Xe).readonly(),rawLabels:l(Xe).readonly().optional(),inferenceMs:a()}),Vl=[{value:"auto",label:"Auto (platform default)"},{value:"apple-soundanalysis",label:"Apple SoundAnalysis (macOS 12+)"},{value:"yamnet-onnx",label:"YAMNet ONNX (cross-platform)"}],Kl={audioBackend:"auto",probedBestAudioBackend:"",selectedAudioModel:""},Gr={name:"audio-analyzer",scope:"system",mode:"singleton",methods:{analyseChunk:s(i({chunk:jt,settings:Wr}),Hr.nullable(),{kind:"mutation"}),classify:s(jt,$r,{timeoutMs:3e4}),isReady:s(p(),v()),dispose:s(p(),p(),{kind:"mutation"}),reprobeAudioEngine:s(p(),i({backend:e()}),{kind:"mutation",auth:"admin"})}},jr={name:"audio-analysis",scope:"device",mode:"singleton",deviceTypes:["camera"],exposesDeviceSettings:!0,methods:{resolveDeviceSettings:s(i({deviceId:a()}),R())},events:{onAudioLevel:$(i({deviceId:a(),rms:a(),dbfs:a()}))}},Pe=f(["f32le","s16le"]),Vr=i({codec:e(),canDecode:v(),canEncode:v(),label:e().optional()}),Kr=i({codec:e(),sourceSampleRate:a().int().positive(),sourceChannels:a().int().positive(),extraData:T(Uint8Array).optional(),targetSampleRate:a().int().positive(),targetChannels:a().int().positive(),targetFormat:Pe.optional(),idleMs:a().int().positive().optional(),tag:e().optional()}),Zr=i({codec:e(),sourceSampleRate:a().int().positive(),sourceChannels:a().int().positive(),sourceFormat:Pe.optional(),targetSampleRate:a().int().positive(),targetChannels:a().int().positive(),bitrateKbps:a().int().positive().optional(),idleMs:a().int().positive().optional(),tag:e().optional()}),Yr=i({data:T(Uint8Array),sampleRate:a().int().positive(),channels:a().int().positive(),format:Pe,pts:a()}),ca=i({data:T(Uint8Array),codec:e(),pts:a(),frameComplete:v()}),Qr=i({sessionId:e(),kind:f(["decode","encode"]),codec:e(),sourceSampleRate:a(),sourceChannels:a(),targetSampleRate:a(),targetChannels:a(),format:Pe,tag:e().optional(),createdAtMs:a(),lastActivityMs:a(),framesIn:a(),framesOut:a()}),Jr={name:"audio-codec",scope:"system",mode:"singleton",methods:{listSupportedCodecs:s(p(),l(Vr).readonly()),canHandle:s(i({codec:e(),kind:f(["decode","encode"])}),v()),createDecodeSession:s(Kr,i({sessionId:e(),nodeId:e()}),{kind:"mutation"}),createEncodeSession:s(Zr,i({sessionId:e(),nodeId:e()}),{kind:"mutation"}),closeSession:s(i({sessionId:e(),nodeId:e().optional()}),p(),{kind:"mutation"}),pushEncodedFrame:s(i({sessionId:e(),nodeId:e().optional(),data:T(Uint8Array),pts:a().optional()}),p(),{kind:"mutation"}),pullPcm:s(i({sessionId:e(),nodeId:e().optional(),maxCount:a().int().positive().default(8)}),l(Yr)),pushPcm:s(i({sessionId:e(),nodeId:e().optional(),data:T(Uint8Array),pts:a().optional()}),p(),{kind:"mutation"}),pullEncoded:s(i({sessionId:e(),nodeId:e().optional(),maxCount:a().int().positive().default(8)}),l(ca)),flushEncode:s(i({sessionId:e(),nodeId:e().optional()}),l(ca),{kind:"mutation"}),listActiveSessions:s(p(),l(Qr).readonly())}},la=i({embedding:l(a()),dimensions:a()}),Xr=i({modelId:e(),dimensions:a(),inputSize:a()}),es={name:"embedding-encoder",scope:"system",mode:"collection",internal:!0,methods:{encode:s(i({crop:T(Uint8Array),width:a(),height:a()}),la),encodeText:s(i({text:e()}),la),getInfo:s(p(),Xr)}},Le=i({id:a(),stableId:e(),addonId:e(),type:f(q),name:e(),location:e().nullable(),disabled:v(),parentDeviceId:a().nullable(),role:e().nullable().optional(),online:v(),features:l(e()),isCamera:v(),config:b(e(),S()),metadata:b(e(),S()).nullable().optional()}),ts=i({key:e(),value:S(),description:e().optional()}),as=i({id:a(),stableId:e(),type:e(),name:e(),location:e().nullable(),disabled:v(),parentDeviceId:a().nullable(),role:e().nullable().optional()}),is=i({id:a(),stableId:e(),addonId:e(),type:e(),name:e(),location:e().nullable(),disabled:v(),parentDeviceId:a().nullable(),metadata:b(e(),S()).nullable().optional()}),ns=S().nullable(),os=i({streamId:e(),width:a().optional(),height:a().optional(),codec:e().optional(),fps:a().optional(),bitrateKbps:a().optional()}),rs=i({addonId:e(),stableId:e(),id:a(),type:e(),name:e(),location:e().nullable().optional(),disabled:v().optional(),parentDeviceId:a().nullable(),role:e().nullable().optional(),features:l(e()).optional(),config:b(e(),S())}),ss=i({deviceId:a()}),ds=i({deviceId:a(),data:b(e(),S())}),cs={name:"device-manager",scope:"system",mode:"singleton",methods:{allocateDeviceId:s(i({addonId:e(),stableId:e()}),i({id:a()}),{kind:"mutation"}),registerDevice:s(rs,p(),{kind:"mutation"}),removeDevice:s(ss,p(),{kind:"mutation"}),persistConfig:s(ds,p(),{kind:"mutation"}),loadConfig:s(i({deviceId:a()}),b(e(),S())),loadRuntimeState:s(i({deviceId:a()}),b(e(),S())),loadMeta:s(i({deviceId:a()}),is.nullable()),setName:s(i({deviceId:a(),name:e()}),p(),{kind:"mutation",auth:"admin"}),setLocation:s(i({deviceId:a(),location:e().nullable()}),p(),{kind:"mutation",auth:"admin"}),setMetadata:s(i({deviceId:a(),patch:b(e(),S())}),p(),{kind:"mutation",auth:"admin"}),listLocations:s(p(),l(e())),addLocation:s(i({name:e()}),p(),{kind:"mutation",auth:"admin"}),removeLocation:s(i({name:e(),cascade:v().optional()}),p(),{kind:"mutation",auth:"admin"}),setDisabled:s(i({deviceId:a(),disabled:v()}),p(),{kind:"mutation",auth:"admin"}),listPersistedByAddon:s(i({addonId:e()}),l(as)),listAll:s(i({addonId:e().optional()}),l(Le)),getDevice:s(i({deviceId:a()}),Le.nullable()),getChildren:s(i({parentDeviceId:a()}),l(Le)),getStreamSources:s(i({deviceId:a()}),l(Bn)),getConfigSchema:s(i({deviceId:a()}),l(ts)),getSettingsSchema:s(i({deviceId:a()}),ns),updateConfig:s(i({deviceId:a(),values:b(e(),S())}),i({success:I(!0)}),{kind:"mutation",auth:"admin"}),enable:s(i({deviceId:a()}),i({success:I(!0)}),{kind:"mutation",auth:"admin"}),disable:s(i({deviceId:a()}),i({success:I(!0)}),{kind:"mutation",auth:"admin"}),remove:s(i({deviceId:a()}),i({success:I(!0)}),{kind:"mutation",auth:"admin"}),getStreamProfileMap:s(i({deviceId:a()}),b(e(),e().nullable())),setStreamProfileMap:s(i({deviceId:a(),profileMap:b(e(),e().nullable())}),i({success:I(!0)}),{kind:"mutation",auth:"admin"}),probeStreams:s(i({deviceId:a()}),l(os),{kind:"mutation",auth:"admin"}),getBindings:s(i({deviceId:a()}),i({deviceId:a(),entries:l(i({capName:e(),kind:f(["native","wrapped"]),providerAddonId:e(),providerNodeId:e(),nativeAddonId:e()}))})),getAllBindings:s(i({}),l(i({deviceId:a(),entries:l(i({capName:e(),kind:f(["native","wrapped"]),providerAddonId:e(),providerNodeId:e(),nativeAddonId:e()}))}))),setWrapperActive:s(i({deviceId:a(),capName:e(),wrapperAddonId:e(),active:v()}),p(),{kind:"mutation",auth:"admin"}),listWrappersForCap:s(i({capName:e()}),l(e())),listBindableCapsForDeviceType:s(i({deviceType:e()}),l(i({capName:e(),wrappers:l(e())}))),getDeviceSettingsAggregate:s(i({deviceId:a()}),V.nullable()),getDeviceLiveInfoAggregate:s(i({deviceId:a()}),V.nullable()),getDeviceAggregate:s(i({deviceId:a()}),i({settings:V.nullable(),live:V.nullable()})),updateDeviceField:s(i({deviceId:a(),writerCapName:e(),writerAddonId:e(),key:e(),value:S()}),i({success:I(!0)}),{kind:"mutation",auth:"admin"}),updateDeviceFieldsBatch:s(i({deviceId:a(),changes:l(i({writerCapName:e(),writerAddonId:e(),key:e(),value:S()}))}),i({success:I(!0),failures:l(i({writerCapName:e(),writerAddonId:e(),error:e()}))}),{kind:"mutation",auth:"admin"}),discoverDevices:s(i({addonId:e()}),l(Ae),{kind:"mutation",auth:"admin"}),adoptDevice:s(i({addonId:e(),candidate:Ae}),Ce,{kind:"mutation",auth:"admin"}),getCreationSchema:s(i({addonId:e(),type:f(q)}),S().nullable()),createDevice:s(i({addonId:e(),type:f(q),config:b(e(),S())}),Ce,{kind:"mutation",auth:"admin"}),testCreationField:s(i({addonId:e(),type:f(q),key:e(),value:S(),formValues:b(e(),S()).optional()}),nt,{kind:"mutation",auth:"admin"}),testField:s(i({deviceId:a(),key:e(),value:S()}),nt,{kind:"mutation",auth:"admin"}),getDeviceStatusAggregate:s(i({deviceId:a(),caps:l(e()).readonly().optional()}),b(e(),S().nullable()))}},ls={name:"device-state",scope:"system",mode:"singleton",methods:{getSnapshot:s(i({deviceId:a()}),b(e(),b(e(),S()))),getCapSlice:s(i({deviceId:a(),capName:e()}),b(e(),S()).nullable()),getAllSnapshots:s(i({}),b(e(),b(e(),b(e(),S())))),setCapSlice:s(i({deviceId:a(),capName:e(),slice:b(e(),S())}),p(),{kind:"mutation"})},events:{onChanged:$(i({deviceId:a(),capName:e(),slice:b(e(),S())}))}},Ue=i({userId:e(),username:e(),email:e().optional(),displayName:e().optional(),roles:l(e()).optional()}),us={name:"auth-provider",scope:"system",mode:"collection",internal:!0,methods:{validateCredentials:s(i({username:e(),password:e()}),Ue.nullable(),{kind:"mutation"}),getLoginUrl:s(i({state:e()}),e()),handleCallback:s(b(e(),e()),Ue,{kind:"mutation"}),validateToken:s(i({token:e()}),Ue.nullable())}},rt=i({url:e(),hostname:e(),port:a(),protocol:f(["http","https"])}),ms=i({connected:v(),endpoint:rt.nullable(),error:e().optional()}),ps={name:"network-access",scope:"system",mode:"collection",internal:!0,methods:{start:s(p(),rt,{kind:"mutation"}),stop:s(p(),p(),{kind:"mutation"}),getEndpoint:s(p(),rt.nullable()),getStatus:s(p(),ms)}},gs=i({urls:M([e(),l(e())]),username:e().optional(),credential:e().optional()}),hs={name:"turn-provider",scope:"system",mode:"collection",methods:{getTurnServers:s(p(),l(gs).readonly())}},ri=i({base64:e(),contentType:e()}),vs=i({lastCapturedAt:a().nullable(),cacheAgeMs:a().nullable(),lastBytes:a().nullable(),lastStreamId:e().nullable()}),ys={name:"snapshot",scope:"device",mode:"singleton",deviceTypes:["camera"],exposesDeviceSettings:!0,methods:{getSnapshot:s(i({deviceId:a(),streamId:e().optional(),force:v().optional()}),ri.nullable()),invalidateCache:s(i({deviceId:a()}),p(),{kind:"mutation",auth:"admin"})},status:{schema:vs,kind:"poll"}},fs={name:"snapshot-provider",scope:"system",mode:"collection",methods:{supportsDevice:s(i({deviceId:a()}),v()),getSnapshot:s(i({deviceId:a(),streamId:e().optional()}),ri.nullable())}},Ss=i({title:e(),body:e(),imageUrl:e().optional(),deviceId:a().optional(),eventId:e().optional(),priority:f(["low","normal","high","critical"]).default("normal"),metadata:b(e(),S()).optional()}),bs={name:"notification-output",scope:"system",mode:"collection",methods:{send:s(Ss,p(),{kind:"mutation"}),sendTest:s(p(),i({success:v(),error:e().optional()}),{kind:"mutation"})}},ua=i({id:e(),name:e(),enabled:v(),conditions:b(e(),S()),actions:l(b(e(),S()))}),Is=i({id:e(),ruleId:e(),timestamp:a(),deviceId:a().optional(),success:v(),error:e().optional()}),ks={name:"advanced-notifier",scope:"system",mode:"singleton",internal:!0,methods:{getRules:s(p(),l(ua).readonly()),upsertRule:s(ua,p(),{kind:"mutation"}),deleteRule:s(i({ruleId:e()}),p(),{kind:"mutation"}),testRule:s(i({ruleId:e(),lookbackMinutes:a()}),l(b(e(),S())),{kind:"mutation"}),getHistory:s(i({ruleId:e().optional(),limit:a().optional()}),l(Is))}},si=f(["continuous","motion","scheduled","composite"]),As=i({streamId:e(),mode:f(["always","inherit"])}),Cs=i({days:l(a()).readonly(),startTime:e(),endTime:e(),mode:f(["continuous","motion"])}),se=i({deviceId:a(),mode:si,streams:l(As).readonly(),enabled:v(),preBufferSec:a(),postBufferSec:a(),scheduleRules:l(Cs).readonly().optional()}),di=f(["recording:main","recording:mid","recording:sub","thumbnail:scrub","thumbnail:event"]),st=i({deviceId:a(),dataCategory:di,storageName:e(),subDirectory:e(),retentionDays:a().nullable(),retentionGb:a().nullable()}),ws=i({id:e(),deviceId:a(),streamId:e(),startTime:a(),endTime:a(),duration:a(),path:e(),storageName:e(),subDirectory:e(),sizeBytes:a(),codec:f(["h264","h265"]),hasAudio:v()}),Ps=i({deviceId:a(),timestamp:a(),path:e(),storageName:e(),subDirectory:e(),sizeBytes:a(),category:f(["scrub","event"])}),Ds=i({startTime:a(),endTime:a(),streams:l(e()).readonly()}),Ms=i({totalBytes:a(),segmentCount:a()}),Ts=i({bitrateKbps:a(),retentionDays:a().nullable(),retentionGb:a().nullable(),estimatedGb:a(),estimatedDaysAtCapacity:a().nullable()}),ma=i({perStream:b(e(),Ts),thumbnails:i({estimatedGb:a()}),totalEstimatedGb:a(),motionEstimate:i({avgEventsPerDay:a(),avgDurationSec:a(),dutyCyclePercent:a()}).optional()}),Rs=i({totalEvents:a(),avgDurationSec:a(),avgEventsPerDay:a(),dutyCyclePercent:a()}),ge=i({deviceId:a()}),Es=i({deviceId:a(),policy:se.omit({deviceId:!0}),storageOverrides:l(st.omit({deviceId:!0})).readonly().optional(),ffmpegOverrides:b(e(),S()).optional()}),pa=i({deviceId:a(),startTime:a(),endTime:a()}),qs=i({deviceId:a(),streamId:e(),startTime:a(),endTime:a()}),xs=i({deviceId:a(),streamId:e(),startTime:a(),endTime:a(),live:v().optional()}),Bs=i({deviceId:a(),timestamp:a(),category:e().optional()}),Os=i({deviceId:a(),streamId:e()}),Ns=i({deviceId:a(),motionInput:i({avgEventsPerDay:a(),avgDurationSec:a()}).optional()}),_s=i({deviceId:a(),dataCategory:di}),zs=i({deviceId:a(),policy:se.omit({deviceId:!0})}),Fs=i({deviceId:a(),policy:se.omit({deviceId:!0}),ffmpegOverrides:b(e(),S()).optional()}),Ls={name:"recording-engine",scope:"system",mode:"singleton",methods:{getStatus:s(p(),i({activeRecordings:a(),totalSegments:a(),totalSizeMB:a()})),enable:s(Es,p(),{kind:"mutation",auth:"admin"}),disable:s(ge,p(),{kind:"mutation",auth:"admin"}),getConfig:s(ge,se.nullable()),updateConfig:s(Fs,p(),{kind:"mutation",auth:"admin"}),getPlaylist:s(xs,e()),getThumbnail:s(Bs,Ps.nullable()),getSegments:s(qs,l(ws).readonly()),getAvailability:s(pa,l(Ds).readonly()),estimateStorage:s(Ns,ma),estimateGlobalStorage:s(p(),ma),getStorageUsage:s(Os,Ms),setPolicy:s(zs,p(),{kind:"mutation",auth:"admin"}),getPolicy:s(ge,se.nullable()),getPolicyStatus:s(ge,i({deviceId:a(),enabled:v(),mode:si,activeStreams:a()}).nullable()),getRetentionConfig:s(_s,st.nullable()),updateRetentionConfig:s(st,p(),{kind:"mutation",auth:"admin"}),getMotionStats:s(pa,Rs)}},Us={name:"detection-pipeline",scope:"device",mode:"singleton",deviceTypes:["camera"],exposesDeviceSettings:!0,methods:{}},kt=f(["new","entered","left","moving","idle"]),Hs=f(["motion","object","audio"]),ci=i({x:a(),y:a(),timestamp:a(),bbox:Z}),Ws=i({timestamp:a(),position:ci,mediaKey:e()}),He=i({trackId:e(),deviceId:a(),className:e(),label:e().optional(),firstSeen:a(),lastSeen:a(),positions:l(ci).readonly(),snapshots:l(Ws).readonly(),zonesVisited:l(e()).readonly(),totalDistance:a(),state:kt,active:v()}),At={id:e(),deviceId:a(),timestamp:a()},$s=i({...At,kind:I("motion"),regionCount:a(),regions:l(i({bbox:Z,pixelCount:a(),intensity:a()})).readonly(),frameWidth:a(),frameHeight:a()}),Gs=i({...At,kind:I("object"),trackId:e(),className:e(),label:e().optional(),confidence:a(),bbox:Z,zones:l(e()).readonly(),state:kt,mediaKey:e().optional()}),js=i({...At,kind:I("audio"),rms:a(),dbfs:a(),classification:i({className:e(),originalClass:e().optional(),score:a()}).optional()}),ga=i({key:e(),kind:f(["crop","thumbnail","snapshot"]),base64:e(),sizeBytes:a(),timestamp:a()}),Vs=1e3,Ks=5e3,dt=i({deviceId:a(),since:a().optional(),until:a().optional(),limit:a().int().min(1).max(Ks).default(Vs)}),Zs=dt.extend({classFilter:e().optional()}),Ys=i({trackId:e(),className:e(),confidence:a(),bbox:Z,zones:l(e()).readonly(),state:kt}),Qs={name:"pipeline-analytics",scope:"device",mode:"singleton",deviceTypes:["camera"],exposesDeviceSettings:!0,methods:{getActiveTracks:s(i({deviceId:a()}),l(He).readonly()),getTrack:s(i({deviceId:a(),trackId:e()}),He.nullable()),listTracks:s(i({deviceId:a(),since:a().optional(),until:a().optional(),limit:a().optional()}),l(He).readonly()),clearTracks:s(i({deviceId:a()}),p(),{kind:"mutation",auth:"admin"}),getMotionEvents:s(dt,l($s).readonly()),getObjectEvents:s(Zs,l(Gs).readonly()),getAudioEvents:s(dt,l(js).readonly()),getEventMedia:s(i({eventId:e()}),l(ga).readonly()),getTrackMedia:s(i({trackId:e()}),l(ga).readonly())},events:{onFrameTracked:{data:i({deviceId:a(),timestamp:a(),frameWidth:a(),frameHeight:a(),detections:l(Ys).readonly()})},onTrackStarted:{data:i({deviceId:a(),trackId:e(),className:e()})},onTrackEnded:{data:i({deviceId:a(),trackId:e(),className:e(),durationMs:a()})},onDetectionEvent:{data:i({deviceId:a(),kind:Hs,eventId:e(),timestamp:a()})}}},Js=i({total:a(),user:a(),system:a(),irq:a(),nice:a(),loadAvg:Ma([a(),a(),a()]),cores:a()}),Xs=i({percent:a(),totalBytes:a(),usedBytes:a(),availableBytes:a(),swapUsedBytes:a(),swapTotalBytes:a()}),ed=i({readBytes:a(),writeBytes:a(),readOps:a(),writeOps:a(),timestampMs:a()}),td=i({rxBytes:a(),txBytes:a(),rxPackets:a(),txPackets:a(),rxErrors:a(),txErrors:a(),timestampMs:a()}),li=i({utilization:a(),model:e(),memoryUsedBytes:a(),memoryTotalBytes:a(),temperature:a().nullable()}),ad=i({openFds:a(),threadCount:a(),activeHandles:a(),activeRequests:a()}),ha=i({avg10:a(),avg60:a(),avg300:a()}),We=i({some:ha,full:ha.nullable()}),va=i({cpu:Js,memory:Xs,gpu:li.nullable(),network:td,disk:ed,pressure:i({cpu:We.nullable(),memory:We.nullable(),io:We.nullable()}),process:ad,cpuTemperature:a().nullable(),timestampMs:a()}),id=i({path:e(),totalBytes:a(),usedBytes:a(),availableBytes:a(),percent:a()}),ya=i({pid:a(),cpu:a(),memory:a()}),nd=i({addonId:e(),nodeId:e(),role:f(["hub","worker"]),pid:a(),state:f(["starting","running","stopping","stopped","crashed"]),uptimeSec:a()}),od=i({pid:a(),ppid:a(),pgid:a(),classification:f(["root","managed","system","ghost"]),addonId:e().nullable(),nodeId:e().nullable(),command:e(),cpuPercent:a(),memoryRssBytes:a(),uptimeSec:a(),orphaned:v()}),rd=i({pid:a(),force:v().optional()}),sd=i({success:v(),reason:e().optional(),signal:f(["SIGTERM","SIGKILL"]).optional()}),dd=i({cpuPercent:a(),memoryPercent:a(),memoryUsedMB:a(),memoryTotalMB:a(),diskPercent:a().optional(),temperature:a().optional(),gpuPercent:a().optional(),gpuMemoryPercent:a().optional()}),cd={name:"metrics-provider",scope:"system",mode:"singleton",methods:{collectSnapshot:s(p(),va),getCached:s(p(),va.nullable()),getCurrent:s(p(),dd),getDiskSpace:s(i({dirPath:e()}),id),getGpuInfo:s(p(),li.nullable()),getCpuTemperature:s(p(),a().nullable()),getProcessStats:s(i({pids:l(a())}),l(ya)),listAddonInstances:s(p(),l(nd).readonly()),getAddonStats:s(i({addonId:e()}),ya.nullable()),listNodeProcesses:s(p(),l(od).readonly()),killProcess:s(rd,sd,{kind:"mutation",auth:"admin"})}},ld=i({id:e(),name:e()}),fa=i({pan:a(),tilt:a(),zoom:a()}),Sa=i({pan:a().optional(),tilt:a().optional(),zoom:a().optional(),speed:a().optional()}),ud={name:"ptz",scope:"device",mode:"singleton",deviceTypes:["camera"],methods:{move:s(Sa.extend({deviceId:a()}),p(),{kind:"mutation"}),continuousMove:s(Sa.extend({deviceId:a()}),p(),{kind:"mutation"}),stop:s(i({deviceId:a()}),p(),{kind:"mutation"}),getPresets:s(i({deviceId:a()}),l(ld)),goToPreset:s(i({deviceId:a(),presetId:e()}),p(),{kind:"mutation"}),goHome:s(i({deviceId:a()}),p(),{kind:"mutation"}),getPosition:s(i({deviceId:a()}),fa)},status:{schema:fa,kind:"command-driven"}},md=i({id:e(),type:e(),timestamp:a(),label:e().optional(),thumbnailUrl:e().optional(),clipUrl:e().optional(),metadata:b(e(),S()).optional()}),pd={name:"events",scope:"device",mode:"singleton",deviceTypes:["camera"],methods:{getEvents:s(i({deviceId:a(),from:a().optional(),to:a().optional(),limit:a().optional()}),l(md)),getEventThumbnail:s(i({deviceId:a(),eventId:e()}),i({base64:e(),contentType:e()}).nullable()),getEventClipUrl:s(i({deviceId:a(),eventId:e()}),e().nullable())}},gd=i({id:e(),startTs:a(),endTs:a(),durationSec:a(),sizeBytes:a().optional()}),hd={name:"recording",scope:"device",mode:"singleton",deviceTypes:["camera"],methods:{getSegments:s(i({deviceId:a(),from:a().optional(),to:a().optional()}),l(gd)),getPlaybackUrl:s(i({deviceId:a(),segmentId:e()}),e().nullable()),getThumbnailAt:s(i({deviceId:a(),timestamp:a()}),i({base64:e(),contentType:e()}).nullable())}},vd=i({id:e(),label:e(),protocol:f(["rtsp","rtmp","annexb","http-mjpeg","webrtc","custom"]),url:e().optional(),resolution:i({width:a(),height:a()}).optional(),fps:a().optional(),bitrate:a().optional(),codec:e().optional(),profileHint:f(["high","mid","low"]).optional(),sdp:e().optional()}),yd=i({key:e(),value:S()}),fd={name:"device-ops",scope:"device",mode:"singleton",methods:{getStreamSources:s(i({deviceId:a()}),l(vd)),getConfigEntries:s(i({deviceId:a()}),l(yd)),setConfig:s(i({deviceId:a(),values:b(e(),S())}),p(),{kind:"mutation"}),removeDevice:s(i({deviceId:a()}),p(),{kind:"mutation"}),getSettingsSchema:s(i({deviceId:a()}),S().nullable())}},Sd=i({host:e(),port:a().int().positive().optional(),onvifPort:a().int().positive().optional(),rtspPort:a().int().positive().optional(),https:v().optional(),username:e().optional(),password:e().optional(),onvifProfile:e().optional()}),bd=i({host:e(),port:a().int().positive().nullable(),onvifPort:a().int().positive().nullable(),rtspPort:a().int().positive().nullable(),https:v().nullable(),hasUsername:v(),hasPassword:v(),onvifProfile:e().nullable()}),Id={name:"camera-credentials",scope:"device",mode:"singleton",deviceTypes:["camera"],methods:{getCredentials:s(i({deviceId:a()}),Sd.nullable(),{kind:"query",auth:"admin"})},status:{schema:bd,kind:"command-driven"}},kd={name:"reboot",scope:"device",mode:"singleton",deviceTypes:["camera","sensor","switch"],methods:{reboot:s(i({deviceId:a().int().nonnegative()}),i({success:I(!0)}),{kind:"mutation",auth:"admin"})}},Ad=f(["text","timestamp","watermark"]),ct=f(["top-left","top-center","top-right","bottom-left","bottom-center","bottom-right","custom"]),Cd=i({id:e(),kind:Ad,enabled:v(),text:e().optional(),position:ct.optional(),availablePositions:l(ct).readonly(),readOnly:v().optional()}),ba=i({overlays:l(Cd).readonly()}),wd=i({enabled:v().optional(),text:e().optional(),position:ct.optional()}).partial(),Pd={name:"osd",scope:"device",mode:"singleton",deviceTypes:["camera"],methods:{setOverlay:s(i({deviceId:a(),overlayId:e(),patch:wd}),p(),{kind:"mutation",auth:"admin"})},events:{onStatusChanged:{data:i({deviceId:a(),status:ba})}},status:{schema:ba,kind:"command-driven"},settings:{bindings:[{kind:"array",statusPath:"overlays",idField:"id",method:"setOverlay",idArg:"overlayId",patchArg:"patch",sectionId:"osd",sectionTitle:"Video overlays",itemFields:{enabled:{label:t=>`${String(t.id)} enabled`,kind:"boolean"},text:{label:t=>`${String(t.id)} text`,kind:"text",when:t=>t.kind!=="timestamp"&&!t.readOnly},position:{label:t=>`${String(t.id)} position`,kind:"select",options:t=>t.availablePositions??[],when:t=>Array.isArray(t.availablePositions)&&t.availablePositions.length>0}}}]}},Dd=i({childDeviceIds:l(a()).readonly()}),Md={name:"accessories",scope:"device",mode:"singleton",deviceTypes:["camera","hub"],methods:{},events:{onAccessoriesChanged:{data:i({deviceId:a(),childDeviceIds:l(a()).readonly()})}},status:{schema:Dd,kind:"command-driven"}},Td=i({codecs:l(e()),sampleRate:a(),duplex:f(["half","full"]),maxBacklogMs:a()}),Ia=i({talking:v(),lastSessionAt:a().nullable(),ability:Td.nullable()}),Rd={name:"intercom",scope:"device",mode:"singleton",deviceTypes:["camera"],methods:{startSession:s(i({deviceId:a()}),i({sessionId:e(),sdpOffer:e()}),{kind:"mutation",auth:"admin"}),handleAnswer:s(i({deviceId:a(),sessionId:e(),sdpAnswer:e()}),p(),{kind:"mutation",auth:"admin"}),stopSession:s(i({deviceId:a(),sessionId:e()}),p(),{kind:"mutation",auth:"admin"})},events:{onStatusChanged:{data:i({deviceId:a(),status:Ia})}},status:{schema:Ia,kind:"command-driven"}},lt=f(["person","vehicle","animal","face","package","other"]),ui=i({class:lt,timestamp:a(),confidence:a().min(0).max(1).optional()}),Ed=i({lastByClass:b(lt,ui.nullable()),supportedClasses:l(lt).readonly()}),qd={name:"native-object-detection",scope:"device",mode:"singleton",deviceTypes:["camera"],methods:{},events:{onDetected:{data:i({deviceId:a(),detection:ui})}},status:{schema:Ed,kind:"push"}},xd=f(Li),Bd=f(["videotoolbox","cuda","nvdec","vaapi","qsv","d3d11va","dxva2","amf","vdpau","drm","coreml","tensorrt","openvino","directml","webgpu","none"]).nullable().optional(),Od=i({preferred:l(e()).readonly()}),Nd=f(["darwin","linux","win32"]),_d=f(["arm64","x64"]),zd=i({type:f(["nvidia","amd","intel","apple"]),name:e(),memoryMB:a().optional()}),Fd=i({type:f(["apple-ane","intel-npu"])}),mi=i({platform:Nd,arch:_d,cpuModel:e(),cpuCores:a(),totalRAM_MB:a(),availableRAM_MB:a(),gpu:zd.nullable(),npu:Fd.nullable()}),ka=i({runtime:f(["node","python"]),backend:e(),format:f(["onnx","coreml","openvino"]),score:a(),reason:e(),available:v()}),Ld=i({hardware:mi,scores:l(ka).readonly(),bestScore:ka,pythonPath:e().nullable()}),Ud=i({modelId:e(),name:e(),minRAM_MB:a(),accuracyScore:a(),formats:l(e()).readonly()}),Hd=i({modelId:e(),runtime:f(["node","python"]),backend:e(),format:xd,reason:e()}),Wd={name:"platform-probe",scope:"system",mode:"singleton",methods:{getCapabilities:s(p(),Ld),getHardware:s(p(),mi),resolveInferenceConfig:s(i({requirements:l(Ud).readonly()}),Hd),resolveHwAccel:s(i({prefer:Bd,nodeId:e().optional()}),Od)}},de=f(["super_admin","admin","viewer","agent"]),$e=i({id:e(),username:e(),role:de,allowedProviders:M([l(e()),I("*")]),allowedDevices:b(e(),M([l(e()),I("*")])),createdAt:a(),updatedAt:a()}),$d=i({username:e(),password:e().min(6),role:de,allowedProviders:M([l(e()),I("*")]).optional(),allowedDevices:b(e(),M([l(e()),I("*")])).optional()}),Gd=i({id:e(),role:de.optional(),allowedProviders:M([l(e()),I("*")]).optional(),allowedDevices:b(e(),M([l(e()),I("*")])).optional()}),ut=i({id:e(),label:e(),role:de,allowedProviders:M([l(e()),I("*")]).optional(),allowedDevices:b(e(),M([l(e()),I("*")])).optional(),tokenPrefix:e(),createdAt:a(),lastUsedAt:a().optional()}),jd=i({label:e(),role:de,allowedProviders:M([l(e()),I("*")]).optional(),allowedDevices:b(e(),M([l(e()),I("*")])).optional()}),Vd=i({token:e(),record:ut}),pi=i({type:f(["addon","route-prefix","capability"]),target:e()}),mt=i({id:e(),userId:e(),name:e(),tokenPrefix:e(),scopes:l(pi),expiresAt:a().optional(),lastUsedAt:a().optional(),createdAt:a()}),Kd=i({name:e(),scopes:l(pi),expiresAt:a().optional()}),Zd=i({token:e(),record:mt}),Yd={name:"user-management",scope:"system",mode:"singleton",methods:{listUsers:s(p(),l($e),{auth:"admin"}),createUser:s($d,$e,{kind:"mutation",auth:"superAdmin"}),updateUser:s(Gd,i({success:I(!0)}),{kind:"mutation",auth:"superAdmin"}),deleteUser:s(i({id:e()}),i({success:I(!0)}),{kind:"mutation",auth:"superAdmin"}),resetPassword:s(i({id:e(),newPassword:e().min(6)}),i({success:I(!0)}),{kind:"mutation",auth:"superAdmin"}),validateCredentials:s(i({username:e(),password:e()}),$e.extend({passwordHash:e()}).nullable(),{kind:"mutation"}),listApiKeys:s(p(),l(ut),{auth:"admin"}),createApiKey:s(jd,Vd,{kind:"mutation",auth:"admin"}),revokeApiKey:s(i({id:e()}),i({success:I(!0)}),{kind:"mutation",auth:"admin"}),validateApiKey:s(i({token:e()}),ut.nullable(),{kind:"mutation"}),createScopedToken:s(Kd,Zd,{kind:"mutation",auth:"admin"}),revokeScopedToken:s(i({id:e()}),i({success:I(!0)}),{kind:"mutation",auth:"admin"}),validateScopedToken:s(i({token:e()}),mt.nullable()),listScopedTokens:s(i({userId:e()}),l(mt),{auth:"admin"})}},Aa=i({streaming:v(),notifications:v(),objectDetection:v(),remoteAccess:v(),agentCluster:v(),smartHome:v(),recordings:v(),backup:v(),repl:v()}),Qd=i({status:I("ok"),uptime:a()}),Jd=i({name:e(),address:e(),family:e(),internal:v()}),Xd={name:"system",scope:"system",mode:"singleton",methods:{info:s(p(),Aa),health:s(p(),Qd),featureFlags:s(p(),Aa),networkAddresses:s(p(),l(Jd).readonly()),getRetentionConfig:s(p(),S().nullable(),{auth:"admin"}),setRetentionConfig:s(b(e(),S()),Fi(),{kind:"mutation",auth:"superAdmin"}),forceRetentionCleanup:s(p(),p(),{kind:"mutation",auth:"superAdmin"})}},ec=i({nominalBitrateKbps:a(),observedBitrateKbps:a(),peakBitrateKbps:a(),packetLossPercent:a(),lastUpdated:a()}),tc=i({rttMs:a(),jitterMs:a(),estimatedBandwidthKbps:a(),lastUpdated:a()}),Ca=i({deviceId:a(),streams:b(e(),ec),client:tc.optional()}),ac={name:"network-quality",scope:"system",mode:"singleton",methods:{getDeviceStats:s(i({deviceId:a()}),Ca.nullable()),getAllStats:s(p(),l(Ca).readonly()),reportClientStats:s(i({deviceId:a(),rttMs:a().min(0).max(6e4),jitterMs:a().min(0).max(1e4),estimatedBandwidthKbps:a().min(0).max(1e6)}),p(),{kind:"mutation"})}},ic=i({title:e(),message:e(),severity:f(["info","warning","critical"]),duration:a().optional(),action:i({label:e(),url:e()}).optional()}),nc={name:"toast",scope:"system",mode:"singleton",methods:{onToast:s(p(),ic,{kind:"subscription"})}},oc=i({addonId:e(),capabilities:l(e()).readonly(),status:e()}),rc=i({pid:a(),name:e(),state:e(),cpuPercent:a(),memoryRss:a(),uptimeSeconds:a(),services:l(oc).readonly(),groupId:e().optional()}),sc=i({id:e(),name:e(),hostname:e(),platform:e(),arch:e(),cpuModel:e().nullable(),cpuCores:a(),memoryMB:a(),engines:l(e()).readonly(),isHub:v(),isOnline:v(),cpuPercent:a(),memoryPercent:a(),uptime:a(),lastSeen:e(),localIps:l(e()).readonly(),addons:l(i({id:e(),capabilities:l(e()).readonly(),status:e()})).readonly(),processes:l(rc).readonly()}),dc=i({nodeId:e(),name:e(),version:e(),status:e(),synced:v()}),cc=i({hubVersion:e(),nodes:l(dc)}),Ge=i({nodeId:e(),addonId:e()}),te=i({success:v()}),lc=i({success:v(),reason:e().optional()}),uc=i({restarted:l(e()).readonly(),failed:l(e()).readonly()}),mc=i({nodeId:e(),name:e()}),pc={name:"nodes",scope:"system",mode:"singleton",methods:{topology:s(p(),l(sc).readonly(),{auth:"admin"}),deployAddon:s(Ge,te,{kind:"mutation",auth:"superAdmin"}),undeployAddon:s(Ge,te,{kind:"mutation",auth:"superAdmin"}),restartAddon:s(Ge,te,{kind:"mutation",auth:"superAdmin"}),restartProcess:s(i({nodeId:e(),processName:e()}),lc,{kind:"mutation",auth:"superAdmin"}),restartNode:s(i({nodeId:e()}),uc,{kind:"mutation",auth:"superAdmin"}),shutdownNode:s(i({nodeId:e()}),te,{kind:"mutation",auth:"superAdmin"}),renameNode:s(i({nodeId:e(),name:e().min(1).max(64)}),mc,{kind:"mutation",auth:"superAdmin"}),clusterAddonStatus:s(p(),b(e(),cc),{auth:"superAdmin"}),setProcessLogLevel:s(i({nodeId:e(),level:e()}),te,{kind:"mutation",auth:"superAdmin"}),executeQuery:s(i({nodeId:e(),addonId:e(),queryName:e(),params:b(e(),S()).optional()}),S(),{kind:"mutation",auth:"superAdmin"})}},wa=i({id:e(),addonId:e(),name:e(),enabled:v(),info:b(e(),S()).readonly(),createdAt:a(),updatedAt:a(),processState:e()}),je=i({id:e(),addonId:e(),name:e(),enabled:v(),info:b(e(),S()).readonly(),createdAt:a(),updatedAt:a()}),gc=i({addonId:e(),name:e(),description:e(),iconUrl:e().nullable(),color:e(),instanceMode:e(),discoveryMode:e(),existingInstances:l(i({id:e(),name:e()})),canAdd:v()}),hc=i({success:v(),error:e().optional()}),vc=i({addonId:e(),name:e(),enabled:v().optional(),info:b(e(),S()).optional(),settings:b(e(),S()).optional(),skipRestart:v().optional()}),yc=i({id:e(),name:e().optional(),enabled:v().optional(),info:b(e(),S()).optional()}),fc=i({success:v(),deletedId:e()}),Sc={name:"integrations",scope:"system",mode:"singleton",methods:{list:s(p(),l(wa)),get:s(i({id:e()}),wa),getByAddonId:s(i({addonId:e()}),je.nullable()),create:s(vc,je,{kind:"mutation",auth:"admin"}),update:s(yc,je,{kind:"mutation",auth:"superAdmin"}),delete:s(i({id:e()}),fc,{kind:"mutation",auth:"superAdmin"}),getSettings:s(i({id:e()}),b(e(),S()),{auth:"admin"}),setSettings:s(i({id:e(),settings:b(e(),S())}),i({success:v()}),{kind:"mutation",auth:"superAdmin"}),getAvailableTypes:s(p(),l(gc),{auth:"admin"}),testConnection:s(i({addonId:e(),settings:b(e(),S())}),hc,{kind:"mutation",auth:"admin"})}},Pa=f(["debug","info","warn","error"]),pt=f(["off","latest","beta"]),gi=f(["off","latest","beta","inherit"]),bc=i({id:e(),name:e().optional(),version:e().optional(),description:e().optional(),icon:e().optional(),color:e().optional(),capabilities:l(S()).readonly().optional(),packageName:e(),packageVersion:e(),packageDisplayName:e().optional(),protected:v().optional(),removable:v().optional()}),Ic=i({pid:a().optional(),mode:e(),state:e()}),kc=i({manifest:bc,declaration:S().optional(),source:e(),installSource:e().optional(),process:Ic.optional()}),Ac=i({name:e(),version:e(),dir:e(),installSource:e().optional()}),Cc=i({name:e(),currentVersion:e(),latestVersion:e(),category:f(["addon","core"]),requiresRestart:v()}),wc=i({version:e(),publishedAt:e(),deprecated:e().optional(),distTags:l(e()).readonly()}),Pc=i({name:e(),version:e(),description:e(),keywords:l(e()).readonly(),publishedAt:e(),author:e(),installed:v(),installedVersion:e().optional()}),Dc=i({channel:pt,intervalSeconds:a()}),Mc=gi,Tc=S(),Da=S(),Rc=S(),Ec=i({timestamp:e(),level:e(),message:e(),scope:e().optional()}),qc=S(),xc=i({addonId:e().min(1),action:e().min(1),input:S()}),Bc={name:"addons",scope:"system",mode:"singleton",methods:{list:s(p(),l(kc).readonly()),getLogs:s(i({addonId:e(),limit:a().min(1).max(500).default(100),level:Pa.optional()}),l(qc),{auth:"admin"}),listPackages:s(p(),l(Ac).readonly()),installPackage:s(i({packageName:e(),version:e().optional()}),Da,{kind:"mutation",auth:"superAdmin"}),installFromWorkspace:s(i({packageName:e()}),Da,{kind:"mutation",auth:"admin"}),isWorkspaceAvailable:s(p(),v()),listWorkspacePackages:s(p(),l(S()).readonly()),uninstallPackage:s(i({packageName:e()}),S(),{kind:"mutation",auth:"superAdmin"}),reloadPackages:s(p(),Rc,{kind:"mutation",auth:"admin"}),searchAvailable:s(i({query:e().optional()}),l(Pc)),listUpdates:s(p(),l(Cc).readonly(),{auth:"admin"}),updatePackage:s(i({name:e().min(1),version:e().optional()}),S(),{kind:"mutation",auth:"superAdmin"}),forceRefresh:s(p(),S(),{kind:"mutation",auth:"admin"}),restartServer:s(i({confirm:I(!0)}),S(),{kind:"mutation",auth:"superAdmin"}),getVersions:s(i({name:e()}),l(wc).readonly()),restartAddon:s(i({addonId:e()}),Tc,{kind:"mutation",auth:"superAdmin"}),getAutoUpdateSettings:s(p(),Dc,{auth:"admin"}),setAutoUpdateSettings:s(i({channel:pt,intervalSeconds:a().min(300).max(86400).optional()}),S(),{kind:"mutation",auth:"superAdmin"}),getAddonAutoUpdate:s(i({addonId:e()}),Mc,{auth:"admin"}),setAddonAutoUpdate:s(i({addonId:e(),channel:gi}),S(),{kind:"mutation",auth:"admin"}),applyAutoUpdateToAll:s(i({channel:pt}),i({success:I(!0)}),{kind:"mutation",auth:"superAdmin"}),custom:s(xc,S(),{kind:"mutation"}),onAddonLogs:s(i({addonId:e(),level:Pa.optional()}),Ec,{kind:"subscription"})}},Oc=["decoder","motion-detection","pipeline-executor","audio-analyzer","pipeline-analytics","notification-output"],Zl=[...Oc,"pipeline-orchestrator","pipeline-runner"],Yl={accessories:"accessories",addonPages:"addon-pages",addonPagesSource:"addon-pages-source",addonRoutes:"addon-routes",addonSettings:"addon-settings",addonWidgets:"addon-widgets",addonWidgetsSource:"addon-widgets-source",addons:"addons",adminUi:"admin-ui",advancedNotifier:"advanced-notifier",alerts:"alerts",audioAnalysis:"audio-analysis",audioAnalyzer:"audio-analyzer",audioCodec:"audio-codec",audioMetrics:"audio-metrics",authProvider:"auth-provider",backup:"backup",battery:"battery",brightness:"brightness",cameraCredentials:"camera-credentials",cameraStreams:"camera-streams",decoder:"decoder",detectionPipeline:"detection-pipeline",deviceDiscovery:"device-discovery",deviceManager:"device-manager",deviceOps:"device-ops",deviceProvider:"device-provider",deviceState:"device-state",deviceStatus:"device-status",doorbell:"doorbell",embeddingEncoder:"embedding-encoder",events:"events",featureProbe:"feature-probe",integrations:"integrations",intercom:"intercom",logDestination:"log-destination",metricsProvider:"metrics-provider",motion:"motion",motionDetection:"motion-detection",motionTrigger:"motion-trigger",nativeObjectDetection:"native-object-detection",networkAccess:"network-access",networkQuality:"network-quality",nodes:"nodes",notificationOutput:"notification-output",osd:"osd",pipelineAnalytics:"pipeline-analytics",pipelineExecutor:"pipeline-executor",pipelineOrchestrator:"pipeline-orchestrator",pipelineRunner:"pipeline-runner",platformProbe:"platform-probe",ptz:"ptz",ptzAutotrack:"ptz-autotrack",reboot:"reboot",recording:"recording",recordingEngine:"recording-engine",restreamer:"restreamer",settingsStore:"settings-store",snapshot:"snapshot",snapshotProvider:"snapshot-provider",storage:"storage",streamBroker:"stream-broker",streamingEngine:"streaming-engine",switch:"switch",system:"system",toast:"toast",turnProvider:"turn-provider",userManagement:"user-management",webrtc:"webrtc",webrtcSession:"webrtc-session",zoneAnalytics:"zone-analytics",zoneRules:"zone-rules",zones:"zones"},Ql=[{key:"accessories",name:"accessories"},{key:"addonPages",name:"addon-pages"},{key:"addonPagesSource",name:"addon-pages-source"},{key:"addonRoutes",name:"addon-routes"},{key:"addonSettings",name:"addon-settings"},{key:"addonWidgets",name:"addon-widgets"},{key:"addonWidgetsSource",name:"addon-widgets-source"},{key:"addons",name:"addons"},{key:"adminUi",name:"admin-ui"},{key:"advancedNotifier",name:"advanced-notifier"},{key:"alerts",name:"alerts"},{key:"audioAnalysis",name:"audio-analysis"},{key:"audioAnalyzer",name:"audio-analyzer"},{key:"audioCodec",name:"audio-codec"},{key:"audioMetrics",name:"audio-metrics"},{key:"authProvider",name:"auth-provider"},{key:"backup",name:"backup"},{key:"battery",name:"battery"},{key:"brightness",name:"brightness"},{key:"cameraCredentials",name:"camera-credentials"},{key:"cameraStreams",name:"camera-streams"},{key:"decoder",name:"decoder"},{key:"detectionPipeline",name:"detection-pipeline"},{key:"deviceDiscovery",name:"device-discovery"},{key:"deviceManager",name:"device-manager"},{key:"deviceOps",name:"device-ops"},{key:"deviceProvider",name:"device-provider"},{key:"deviceState",name:"device-state"},{key:"deviceStatus",name:"device-status"},{key:"doorbell",name:"doorbell"},{key:"embeddingEncoder",name:"embedding-encoder"},{key:"events",name:"events"},{key:"featureProbe",name:"feature-probe"},{key:"integrations",name:"integrations"},{key:"intercom",name:"intercom"},{key:"logDestination",name:"log-destination"},{key:"metricsProvider",name:"metrics-provider"},{key:"motion",name:"motion"},{key:"motionDetection",name:"motion-detection"},{key:"motionTrigger",name:"motion-trigger"},{key:"nativeObjectDetection",name:"native-object-detection"},{key:"networkAccess",name:"network-access"},{key:"networkQuality",name:"network-quality"},{key:"nodes",name:"nodes"},{key:"notificationOutput",name:"notification-output"},{key:"osd",name:"osd"},{key:"pipelineAnalytics",name:"pipeline-analytics"},{key:"pipelineExecutor",name:"pipeline-executor"},{key:"pipelineOrchestrator",name:"pipeline-orchestrator"},{key:"pipelineRunner",name:"pipeline-runner"},{key:"platformProbe",name:"platform-probe"},{key:"ptz",name:"ptz"},{key:"ptzAutotrack",name:"ptz-autotrack"},{key:"reboot",name:"reboot"},{key:"recording",name:"recording"},{key:"recordingEngine",name:"recording-engine"},{key:"restreamer",name:"restreamer"},{key:"settingsStore",name:"settings-store"},{key:"snapshot",name:"snapshot"},{key:"snapshotProvider",name:"snapshot-provider"},{key:"storage",name:"storage"},{key:"streamBroker",name:"stream-broker"},{key:"streamingEngine",name:"streaming-engine"},{key:"switch",name:"switch"},{key:"system",name:"system"},{key:"toast",name:"toast"},{key:"turnProvider",name:"turn-provider"},{key:"userManagement",name:"user-management"},{key:"webrtc",name:"webrtc"},{key:"webrtcSession",name:"webrtc-session"},{key:"zoneAnalytics",name:"zone-analytics"},{key:"zoneRules",name:"zone-rules"},{key:"zones",name:"zones"}],Jl=[Md,Ir,Ar,Tr,sr,Dr,wr,Bc,fr,ks,ur,jr,Gr,Jr,Oa,us,pr,Na,_a,Id,Fa,Rr,Us,La,cs,fd,Qa,ls,vt,Ua,es,pd,yt,Sc,Rd,yr,cd,$a,Jn,ja,qd,ps,ac,pc,bs,Pd,Qs,ko,Ur,To,Wd,ud,Va,kd,hd,Ls,xr,vr,ys,fs,mr,Gn,Ln,Ka,Xd,nc,hs,Yd,Br,Nr,Za,Ya,Ha],Xl=["accessories","battery","brightness","camera-credentials","device-discovery","device-status","doorbell","feature-probe","intercom","motion","motion-trigger","native-object-detection","osd","ptz","ptz-autotrack","snapshot","switch"],hi=f(["super_admin","admin","viewer","agent"]),vi=M([I("*"),l(e())]),yi=b(e(),M([I("*"),l(e())])),eu=i({id:e(),username:e(),passwordHash:e(),role:hi,allowedProviders:vi,allowedDevices:yi,createdAt:a(),updatedAt:a()}),tu=i({id:e(),label:e(),role:hi,allowedProviders:vi,allowedDevices:yi,tokenHash:e(),tokenPrefix:e(),createdAt:a(),lastUsedAt:a().optional()}),Nc=i({type:f(["addon","route-prefix","capability"]),target:e()}),au=i({id:e(),userId:e(),name:e(),tokenHash:e(),tokenPrefix:e(),scopes:l(Nc),expiresAt:a().optional(),lastUsedAt:a().optional(),createdAt:a()});function iu(t){try{const r=new URL(t);return!r.username&&!r.password?t:(r.username="",r.password="",r.toString())}catch{return t}}var nu=class{constructor(t){this.capacity=t,this.items=Array.from({length:t})}capacity;items;head=0;tail=0;count=0;get size(){return this.count}push(t){this.items[this.tail]=t,this.tail=(this.tail+1)%this.capacity,this.count<this.capacity?this.count++:this.head=(this.head+1)%this.capacity}drain(t){const r=[],n=Math.min(t,this.count);for(let c=0;c<n;c++)r.push(this.items[this.head]),this.items[this.head]=void 0,this.head=(this.head+1)%this.capacity;return this.count-=n,r}};function ou(t,r,n){const c={};for(const u of Object.keys(n))c[u]=h=>t.addons.custom.mutate({addonId:r,action:u,input:h});return c}export{wl as ACCESSORY_LABEL,Jl as ALL_CAPABILITY_DEFINITIONS,vn as APPLE_SA_TO_MACRO,Vl as AUDIO_BACKEND_CHOICES,gn as AUDIO_MACRO_LABELS,Dd as AccessoriesStatusSchema,_ as AccessoryKind,Mc as AddonAutoUpdateSchema,kc as AddonListItemSchema,kr as AddonPageDeclarationSchema,br as AddonPageInfoSchema,zr as AgentLoadSummarySchema,ze as AlertSchema,dr as AlertSeveritySchema,lr as AlertSourceSchema,cr as AlertStatusSchema,tu as ApiKeyRecordSchema,ut as ApiKeySummarySchema,Hr as AudioAnalysisResultSchema,Wr as AudioAnalysisSettingsSchema,jt as AudioChunkInputSchema,En as AudioClassSummarySchema,Xe as AudioClassificationLabelSchema,$r as AudioClassificationResultSchema,Vr as AudioCodecInfoSchema,Kr as AudioDecodeSessionConfigSchema,Zr as AudioEncodeSessionConfigSchema,ca as AudioEncodedChunkSchema,js as AudioEventSchema,Yn as AudioLevelSchema,qn as AudioMetricsHistoryPointSchema,xn as AudioMetricsHistorySchema,Ht as AudioMetricsSnapshotSchema,Yr as AudioPcmChunkSchema,Ue as AuthResultSchema,Dc as AutoUpdateSettingsSchema,gc as AvailableIntegrationTypeSchema,xa as BACKEND_TO_FORMAT,In as BATTERY_DEVICE_PROFILE,Ki as BaseAddon,Nl as BaseDevice,zl as BaseDeviceProvider,xe as BatteryStatusSchema,Z as BoundingBoxSchema,Wt as BrightnessStatusSchema,Wn as BrokerAudioClientSchema,$n as BrokerClientsSchema,Hn as BrokerDecodedClientSchema,Un as BrokerRtspClientSchema,zn as BrokerStatsSchema,_n as BrokerStatusSchema,Rl as CAM_PROFILE_ORDER,Yl as CAPABILITY_NAMES,Ql as CAPABILITY_ROUTER_KEYS,Xl as CAP_NAMES_WITH_STATUS,Sl as COCO_80_LABELS,Il as COCO_TO_MACRO,U as CamProfileSchema,za as CamStreamKindSchema,ft as CamStreamResolutionSchema,Sd as CameraCredentialsSchema,bd as CameraCredentialsStatusSchema,bt as CameraMetricsSchema,Xn as CameraMetricsWithDeviceIdSchema,Ze as CameraStreamSchema,Lr as CapabilityBindingsSchema,fn as ChargingStatus,tc as ClientNetworkStatsSchema,dc as ClusterAddonNodeDeploymentSchema,cc as ClusterAddonStatusEntrySchema,gr as CollectionColumnSchema,hr as CollectionIndexSchema,ts as ConfigEntrySchema,rr as ConfigSectionWithValuesSchema,or as ConfigTabDeclarationSchema,jd as CreateApiKeyInputSchema,Vd as CreateApiKeyResultSchema,vc as CreateIntegrationInputSchema,Kd as CreateScopedTokenInputSchema,Zd as CreateScopedTokenResultSchema,$d as CreateUserInputSchema,xc as CustomActionInputSchema,Ui as DEFAULT_ADDON_GROUP,Hi as DEFAULT_ADDON_PLACEMENT,Kl as DEFAULT_AUDIO_ANALYZER_CONFIG,jl as DEFAULT_DECODER_HWACCEL_CONFIG,Qc as DEFAULT_FEATURES,el as DEFAULT_RETENTION,kn as DEVICE_PROFILES,Tn as DEVICE_SETTINGS_CONTRIBUTION_METHODS,Rn as DEVICE_STATUS_METHOD,Cl as DEVICE_TYPE_INFO,Nn as DecodedFrameSchema,da as DecoderAssignmentSchema,Ft as DecoderSessionConfigSchema,nn as DecoderStatsSchema,fc as DeleteIntegrationResultSchema,so as DetectorOutputSchema,An as DeviceConfig,$t as DeviceDiscoveryStatusSchema,yn as DeviceFeature,Le as DeviceInfoSchema,Ca as DeviceNetworkStatsSchema,Sn as DeviceRole,Cn as DeviceRuntimeState,Ee as DeviceStatusSchema,q as DeviceType,Je as DiscoveredChildDeviceSchema,jn as DiscoveredChildStatusSchema,_l as DiscoveredDeviceSchema,Vn as DoorbellPressEventSchema,Gt as DoorbellStatusSchema,ul as ElementConfigStore,Xr as EmbeddingInfoSchema,la as EmbeddingResultSchema,On as EncodedPacketSchema,Pr as EnrichedWidgetMetadataSchema,Wi as EventCategory,md as EventItemSchema,Hs as EventKindSchema,on as EventSourceType,qr as ExposedResourceSchema,Aa as FeatureManifestSchema,qe as FeatureProbeStatusSchema,ye as FrameInputSchema,Fr as GlobalMetricsSchema,tl as HF_BASE_URL,rn as HF_REPO,Gl as HWACCEL_OPTIONS,Qd as HealthStatusSchema,Ne as HistoryPointSchema,No as HistoryResolutionEnum,Ac as InstalledPackageSchema,je as IntegrationLiteSchema,wa as IntegrationWithStateSchema,Td as IntercomAbilitySchema,Ia as IntercomStatusSchema,na as LogEntrySchema,ei as LogLevelSchema,Ec as LogStreamEntrySchema,bl as MACRO_LABELS,Li as MODEL_FORMATS,ga as MediaFileSchema,Qn as MotionAnalysisResultSchema,$s as MotionEventSchema,Ro as MotionOnMotionChangedDataSchema,Ie as MotionRegionSchema,It as MotionSourceEnum,wo as MotionSourcesSchema,Kt as MotionStatusSchema,Eo as MotionTriggerRuntimeStateSchema,Ga as MotionTriggerStatusSchema,ui as NativeDetectionSchema,lt as NativeObjectClassEnum,Ed as NativeObjectDetectionStatusSchema,ms as NetworkAccessStatusSchema,Jd as NetworkAddressSchema,rt as NetworkEndpointSchema,Is as NotificationHistoryEntrySchema,ua as NotificationRuleSchema,Ss as NotificationSchema,Gs as ObjectEventSchema,xl as OrchestratorMetricsSchema,Ad as OsdOverlayKindEnum,wd as OsdOverlayPatchSchema,Cd as OsdOverlaySchema,ct as OsdPositionEnum,ba as OsdStatusSchema,Oc as PIPELINE_FLOW_CAPABILITY_NAMES,Zl as PIPELINE_OWNER_CAPABILITY_NAMES,ln as PYTHON_SCRIPT,Cc as PackageUpdateSchema,wc as PackageVersionInfoSchema,Pe as PcmSampleFormatSchema,it as PerScopeBreakdownSchema,sa as PipelineAssignmentSchema,tt as PipelineDefaultStepSchema,P as PipelineEngineChoiceSchema,Vt as PipelineRunResultBridge,K as PipelineStepInputSchema,ql as PlaceholderReasonSchema,Co as PolygonPointSchema,Ye as ProfileSlotSchema,ve as ProfileSlotStatusSchema,Fo as ProviderStatusSchema,Bo as PtzAutotrackRuntimeStateSchema,at as PtzAutotrackSettingsSchema,fe as PtzAutotrackStatusSchema,xo as PtzAutotrackTargetOptionSchema,Sa as PtzMoveCommandSchema,fa as PtzPositionSchema,ld as PtzPresetSchema,aa as QueryFilterSchema,Xc as RECOGNITION_TYPES,al as RUNTIME_DEFAULTS,cn as RUNTIME_TO_FORMAT,$c as ReadinessRegistry,Yi as ReadinessTimeoutError,Er as RegisteredStreamSchema,Po as ReportMotionInputSchema,nu as RingBuffer,Qe as RtspRestreamEntrySchema,Do as RunnerCameraConfigSchema,Bl as RunnerCameraDeviceUIFields,Wa as RunnerLocalLoadSchema,Mo as RunnerLocalMetricsSchema,Ji as STREAM_QUALITY_LABELS,Jc as SUB_DETECTION_TYPES,au as ScopedTokenSchema,mt as ScopedTokenSummarySchema,Pc as SearchResultSchema,gd as SegmentSchema,Xt as SettingsPatchSchema,ia as SettingsRecordSchema,V as SettingsSchemaWithValuesSchema,ea as SettingsUpdateResultSchema,ri as SnapshotImageSchema,Zn as SpatialDetectionSchema,L as StorageLocationTypeSchema,St as StreamFormatSchema,Fn as StreamInfoSchema,ec as StreamNetworkStatsSchema,Bn as StreamSourceEntrySchema,El as StreamSourceSchema,Zt as SwitchStatusSchema,dd as SystemMetricsSchema,Hl as SystemMirror,hc as TestConnectionResultSchema,ic as ToastSchema,Nc as TokenScopeSchema,sc as TopologyNodeSchema,rc as TopologyProcessSchema,oc as TopologyServiceSchema,He as TrackSchema,kt as TrackStateSchema,Ys as TrackedDetectionSchema,gs as TurnServerSchema,yc as UpdateIntegrationInputSchema,Gd as UpdateUserInputSchema,eu as UserRecordSchema,hi as UserRoleSchema,$e as UserSummarySchema,$i as WELL_KNOWN_TABS,Hc as WELL_KNOWN_TAB_MAP,Or as WebrtcStreamChoiceSchema,ii as WebrtcStreamTargetSchema,Cr as WidgetHostEnum,ti as WidgetMetadataSchema,oa as WidgetSizeEnum,hn as YAMNET_TO_MACRO,Ao as ZoneKindEnum,_o as ZoneRuleModeEnum,ie as ZoneRuleSchema,Qt as ZoneRuleStageEnum,Ol as ZoneRulesArraySchema,ae as ZoneSchema,Oo as ZoneScopeBreakdownSchema,Md as accessoriesCapability,Pl as accessoryStableId,Ir as addonPagesCapability,Ar as addonPagesSourceCapability,Tr as addonRoutesCapability,sr as addonSettingsCapability,Dr as addonWidgetsCapability,wr as addonWidgetsSourceCapability,Bc as addonsCapability,fr as adminUiCapability,ks as advancedNotifierCapability,ur as alertsCapability,rl as asBoolean,il as asJsonArray,sn as asJsonObject,ol as asNumber,nl as asString,jr as audioAnalysisCapability,Gr as audioAnalyzerCapability,Jr as audioCodecCapability,Oa as audioMetricsCapability,us as authProviderCapability,Yc as autoAssignProfiles,pr as backupCapability,Na as batteryCapability,ou as bindAddonActions,_a as brightnessCapability,Id as cameraCredentialsCapability,Fa as cameraStreamsCapability,Vc as classifyStream,en as classifyStreams,ll as cosineSimilarity,Qo as createDeviceProxy,Ea as createEvent,Xa as createLazyTrpcSource,Zo as createMirrorSource,Ml as createRuntimeStateBridge,D as createSliceHandle,Ul as createSystemProxy,$l as customAction,Rr as decoderCapability,Wl as defineCustomActions,Us as detectionPipelineCapability,La as deviceDiscoveryCapability,cs as deviceManagerCapability,bn as deviceMatchesProfile,fd as deviceOpsCapability,Qa as deviceProviderCapability,ls as deviceStateCapability,vt as deviceStatusCapability,Ua as doorbellCapability,es as embeddingEncoderCapability,Gc as emitDownForOwnedCaps,Vi as emitReadiness,mn as errMsg,Ll as evaluateZoneRules,$ as event,pd as eventsCapability,Tl as expandCapMethods,yt as featureProbeCapability,gl as formatForBackend,hl as formatForRuntime,Al as getAudioMacroClassIds,cl as hfModelUrl,zt as hydrateSchema,Sc as integrationsCapability,Rd as intercomCapability,Fc as isAgentOnlyPlacement,zc as isDeployableToAgent,Wc as isEvent,yr as logDestinationCapability,kl as mapAudioLabelToMacro,iu as maskUrlCredentials,s as method,cd as metricsProviderCapability,$a as motionCapability,Jn as motionDetectionCapability,ja as motionTriggerCapability,qd as nativeObjectDetectionCapability,ps as networkAccessCapability,ac as networkQualityCapability,pc as nodesCapability,Zi as normalizeAddonInitResult,bs as notificationOutputCapability,Pd as osdCapability,Zc as parseCameraStreamConfig,dl as parseJsonArray,sl as parseJsonObject,qa as parseJsonUnknown,Qs as pipelineAnalyticsCapability,ko as pipelineExecutorCapability,Ur as pipelineOrchestratorCapability,To as pipelineRunnerCapability,Wd as platformProbeCapability,Va as ptzAutotrackCapability,ud as ptzCapability,vl as pythonScriptForBackend,Me as readinessKey,kd as rebootCapability,hd as recordingCapability,Ls as recordingEngineCapability,yl as requiresPython,we as resolveAddonExecution,Lc as resolveAddonGroup,Uc as resolveAddonPlacement,pl as resolveAddonRuntime,un as resolveDetectionRuntime,Dl as resolveDeviceProfile,ml as resolveModelFormat,xr as restreamerCapability,fl as runInferenceStep,ne as scopeKey,vr as settingsStoreCapability,ys as snapshotCapability,fs as snapshotProviderCapability,mr as storageCapability,Gn as streamBrokerCapability,Xi as streamPixels,jc as streamQualityLabel,Ln as streamingEngineCapability,Ka as switchCapability,Xd as systemCapability,Uo as toDeviceSummary,Kc as toStreamSourceEntry,nc as toastCapability,hs as turnProviderCapability,Yd as userManagementCapability,Br as webrtcCapability,ai as webrtcClientHintsSchema,Nr as webrtcSessionCapability,Fl as zodEntriesToConfigUI,Za as zoneAnalyticsCapability,Ya as zoneRulesCapability,Ha as zonesCapability};