@camstack/addon-provider-reolink 1.2.253 → 1.2.255

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/addon.mjs CHANGED
@@ -100690,7 +100690,7 @@ function parseBaichuanWebhookObject(mess) {
100690
100690
  return parsed;
100691
100691
  }
100692
100692
  //#endregion
100693
- //#region ../types/dist/event-category-7P4A3bYA.mjs
100693
+ //#region ../types/dist/event-category-BEsBTS72.mjs
100694
100694
  var EventCategory = /* @__PURE__ */ function(EventCategory) {
100695
100695
  EventCategory["SystemBoot"] = "system.boot";
100696
100696
  EventCategory["SystemAddonsReady"] = "system.addons-ready";
@@ -101137,6 +101137,14 @@ var EventCategory = /* @__PURE__ */ function(EventCategory) {
101137
101137
  */
101138
101138
  EventCategory["StreamBrokerOnRequestStreamSourceRefresh"] = "stream-broker.onRequestStreamSourceRefresh";
101139
101139
  /**
101140
+ * A broker RE-DIALED its source (every dial after the first). A consumer that
101141
+ * reads the broker over a transport that does not announce the cut — the
101142
+ * recorder's ffmpeg writer — learns here instead of through its idle clock.
101143
+ * Telemetry: a dropped event only means the idle clock recovers it later.
101144
+ * Payload: `{ deviceId, camStreamId, brokerId, reason }`.
101145
+ */
101146
+ EventCategory["StreamBrokerOnSourceRestart"] = "stream-broker.onSourceRestart";
101147
+ /**
101140
101148
  * A camera provider changed a device's stream parameters (codec /
101141
101149
  * resolution / bitrate / a stream added or removed). A LOW-LATENCY NUDGE
101142
101150
  * for the stream-broker's catalog reconcile: it carries NO authoritative
@@ -106813,7 +106821,7 @@ var ZodIssueCode = {
106813
106821
  var ZodFirstPartyTypeKind;
106814
106822
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
106815
106823
  //#endregion
106816
- //#region ../types/dist/runtime-capabilities-CK6y0W5U.mjs
106824
+ //#region ../types/dist/runtime-capabilities-CG61dYnO.mjs
106817
106825
  /**
106818
106826
  * The audio chunk plane's byte format, and the ONE expansion from a coded
106819
106827
  * window to float samples (D455).
@@ -111679,6 +111687,15 @@ var CameraStreamSchema = object({
111679
111687
  */
111680
111688
  autoEligible: boolean().optional(),
111681
111689
  /**
111690
+ * The longest continuous session the SOURCE will keep open, in ms, declared by
111691
+ * the provider that knows it (a hub that cuts every child's session on a
111692
+ * timer). Absent = no limit. The broker re-dials a live source a little
111693
+ * BEFORE this elapses, on its own terms and announced to consumers, so the
111694
+ * source's cut never lands mid-recording. Declare slightly under what was
111695
+ * observed.
111696
+ */
111697
+ maxSessionMs: number$1().int().positive().optional(),
111698
+ /**
111682
111699
  * The profile slot the PUBLISHER says this stream is: `low` for a stream
111683
111700
  * whose only sensible role is the low-bandwidth one, `high` for a main
111684
111701
  * stream. Consulted by the broker's automatic ranking
@@ -127374,7 +127391,7 @@ function e(group, en, it, flags = {}) {
127374
127391
  };
127375
127392
  }
127376
127393
  var N = { noise: true };
127377
- EventCategory.SystemBoot, e("system", "System booted", "Sistema avviato"), EventCategory.SystemAddonsReady, e("system", "Addons ready", "Addon pronti"), EventCategory.SystemRestarting, e("system", "System restarting", "Sistema in riavvio"), EventCategory.SystemRestartCompleted, e("system", "Restart completed", "Riavvio completato"), EventCategory.SystemTlsCertChanged, e("system", "TLS certificate changed", "Certificato TLS cambiato"), EventCategory.UpdateAvailable, e("system", "Update available", "Aggiornamento disponibile"), EventCategory.SystemReadyState, e("system", "Readiness changed", "Stato di prontezza cambiato"), EventCategory.AddonStarted, e("addons", "Addon started", "Addon avviato"), EventCategory.AddonStopped, e("addons", "Addon stopped", "Addon fermato"), EventCategory.AddonRestarted, e("addons", "Addon restarted", "Addon riavviato"), EventCategory.AddonUpdated, e("addons", "Addon updated", "Addon aggiornato"), EventCategory.AddonInstalled, e("addons", "Addon installed", "Addon installato"), EventCategory.AddonUninstalled, e("addons", "Addon uninstalled", "Addon disinstallato"), EventCategory.AddonCrashed, e("addons", "Addon crashed", "Addon in errore fatale"), EventCategory.AddonRunnerFailed, e("addons", "Runner failed for good", "Runner fallito definitivamente"), EventCategory.AddonRunnerRefused, e("addons", "Runner refused", "Runner rifiutato"), EventCategory.ProcessStateChanged, e("addons", "Process state changed", "Stato del processo cambiato"), EventCategory.SystemRunnerCheck, e("system", "Runner check", "Verifica dei runner"), EventCategory.AlertEpisode, e("system", "Alert episode", "Episodio di allarme"), EventCategory.AddonError, e("addons", "Addon error", "Errore di un addon"), EventCategory.AddonPageReady, e("addons", "Addon page ready", "Pagina addon pronta"), EventCategory.AddonWidgetReady, e("addons", "Addon widget ready", "Widget addon pronto"), EventCategory.AddonLoadFailed, e("addons", "Addon failed to load", "Caricamento addon fallito"), EventCategory.KeychainChanged, e("system", "Keychain changed", "Portachiavi modificato"), EventCategory.AddonLoadRecovered, e("addons", "Addon load recovered", "Caricamento addon ripristinato"), EventCategory.AddonUnsupportedVersion, e("addons", "Addon version unsupported", "Versione addon non supportata"), EventCategory.AddonUnsupportedResolved, e("addons", "Unsupported addon resolved", "Addon non supportato risolto"), EventCategory.AddonRetryScheduled, e("addons", "Addon retry scheduled", "Nuovo tentativo addon pianificato"), EventCategory.SystemLivenessFailed, e("system", "Liveness check failed", "Controllo di attività fallito"), EventCategory.SystemLivenessRecovered, e("system", "Liveness recovered", "Controllo di attività ripristinato"), EventCategory.AddonRetryAttempting, e("addons", "Addon retry running", "Nuovo tentativo addon in corso"), EventCategory.DeviceRegistered, e("devices", "Device registered", "Dispositivo registrato"), EventCategory.DeviceUnregistered, e("devices", "Device removed", "Dispositivo rimosso"), EventCategory.DeviceEnabled, e("devices", "Device enabled", "Dispositivo abilitato"), EventCategory.DeviceDisabled, e("devices", "Device disabled", "Dispositivo disabilitato"), EventCategory.DeviceSettingsUpdated, e("devices", "Device settings updated", "Impostazioni dispositivo aggiornate"), EventCategory.DeviceBindingsChanged, e("devices", "Device bindings changed", "Collegamenti dispositivo cambiati"), EventCategory.DeviceMetaChanged, e("devices", "Device details changed", "Dettagli dispositivo cambiati"), EventCategory.DeviceSourceInfoChanged, e("devices", "Device source info changed", "Info sorgente dispositivo cambiate"), EventCategory.DeviceStreamsRegistered, e("streams", "Device streams registered", "Stream del dispositivo registrati"), EventCategory.DeviceProvisioned, e("devices", "Device provisioned", "Dispositivo configurato"), EventCategory.DeviceReady, e("devices", "Device ready", "Dispositivo pronto"), EventCategory.IdentityLinkCreated, e("integrations", "Identity linked", "Identità collegata"), EventCategory.IdentityLinkLost, e("integrations", "Identity link lost", "Collegamento identità perso"), EventCategory.IntegrationEnabled, e("integrations", "Integration enabled", "Integrazione abilitata"), EventCategory.IntegrationDisabled, e("integrations", "Integration disabled", "Integrazione disabilitata"), EventCategory.IntegrationDeleted, e("integrations", "Integration deleted", "Integrazione eliminata"), EventCategory.BrokerStatusChanged, e("integrations", "Broker status changed", "Stato del broker cambiato"), EventCategory.BrokerMessage, e("integrations", "Broker message", "Messaggio del broker", N), EventCategory.ProviderStarted, e("integrations", "Provider started", "Provider avviato"), EventCategory.ProviderStopped, e("integrations", "Provider stopped", "Provider fermato"), EventCategory.ProcessCrashed, e("addons", "Process crashed", "Processo andato in crash"), EventCategory.ProcessRestartScheduled, e("addons", "Process restart scheduled", "Riavvio del processo pianificato"), EventCategory.ProcessRestarted, e("addons", "Process restarted", "Processo riavviato"), EventCategory.StorageLocationsChanged, e("storage", "Storage locations changed", "Posizioni di archiviazione cambiate"), EventCategory.RecordingStarted, e("recording", "Recording started", "Registrazione avviata"), EventCategory.RecordingStopped, e("recording", "Recording stopped", "Registrazione fermata"), EventCategory.RecordingError, e("recording", "Recording error", "Errore di registrazione"), EventCategory.RecordingHealthDegraded, e("recording", "Recording degraded", "Registrazione degradata"), EventCategory.RecordingHealthStalled, e("recording", "Recording stalled", "Registrazione bloccata"), EventCategory.RecordingHealthOk, e("recording", "Recording healthy", "Registrazione regolare"), EventCategory.RecordingStorageCritical, e("recording", "Recording storage critical", "Spazio di registrazione critico"), EventCategory.StorageLocationLow, e("storage", "Storage location low", "Spazio in esaurimento"), EventCategory.StorageLocationCritical, e("storage", "Storage location critical", "Spazio critico"), EventCategory.StorageLocationOk, e("storage", "Storage location recovered", "Spazio tornato regolare"), EventCategory.StorageDrainProgress, e("storage", "Drain progress", "Avanzamento dello svuotamento"), EventCategory.StorageDrainComplete, e("storage", "Drain complete", "Svuotamento completato"), EventCategory.RecordingSegmentWritten, e("recording", "Segment written", "Segmento scritto"), EventCategory.RecordingPolicyFallback, e("recording", "Recording policy fallback", "Politica di registrazione di ripiego"), EventCategory.RecordingRetentionCompleted, e("recording", "Retention completed", "Pulizia completata"), EventCategory.RecordingExportProgress, e("recording", "Export progress", "Avanzamento esportazione"), EventCategory.RecordingExportCompleted, e("recording", "Export completed", "Esportazione completata"), EventCategory.RecordingExportFailed, e("recording", "Export failed", "Esportazione fallita"), EventCategory.DetectionEvent, e("detection", "Detection", "Rilevamento"), EventCategory.SessionTrackNew, e("detection", "Session track started", "Nuova traccia di sessione"), EventCategory.SessionTrackExpired, e("detection", "Session track expired", "Traccia di sessione scaduta"), EventCategory.BenchmarkProgress, e("metrics", "Benchmark progress", "Avanzamento benchmark", N), EventCategory.PlatformProbePhase, e("metrics", "Platform probe phase", "Fase di analisi piattaforma", N), EventCategory.PipelineProgress, e("pipeline", "Pipeline progress", "Avanzamento pipeline", N), EventCategory.PipelineTrace, e("pipeline", "Pipeline trace", "Traccia pipeline", N), EventCategory.PipelineInferenceResult, e("pipeline", "Inference result", "Risultato di inferenza", N), EventCategory.PipelineCameraAssigned, e("pipeline", "Camera assigned to pipeline", "Camera assegnata alla pipeline"), EventCategory.PipelineCameraUnassigned, e("pipeline", "Camera unassigned from pipeline", "Camera rimossa dalla pipeline"), EventCategory.PipelineNodeInferenceUnavailable, e("pipeline", "Node inference unavailable", "Inferenza del nodo non disponibile"), EventCategory.PipelineDetectionBlind, e("pipeline", "Detection blind", "Rilevamento cieco"), EventCategory.PipelineMotionNoisy, e("pipeline", "Motion too noisy", "Movimento troppo disturbato"), EventCategory.PipelineMotionCalm, e("pipeline", "Motion calm again", "Movimento di nuovo calmo"), EventCategory.PipelinePackageLlmSilent, e("pipeline", "Package check silent", "Verifica pacchi senza risposta"), EventCategory.PipelinePackageLlmAnswered, e("pipeline", "Package check answered", "Verifica pacchi con risposta"), EventCategory.PipelineCameraUpdated, e("pipeline", "Pipeline camera updated", "Camera della pipeline aggiornata"), EventCategory.PipelineIngestOwnerChanged, e("pipeline", "Ingest owner changed", "Responsabile dell’acquisizione cambiato"), EventCategory.PipelineRunnerLoadSnapshot, e("metrics", "Runner load snapshot", "Carico dei runner", N), EventCategory.PipelineCameraMetricsSnapshot, e("metrics", "Camera metrics snapshot", "Metriche delle camere", N), EventCategory.StreamBrokerMetricsSnapshot, e("metrics", "Stream broker metrics", "Metriche dello stream broker", N), EventCategory.StreamBrokerOnCamStreamDemand, e("streams", "Stream requested", "Stream richiesto"), EventCategory.StreamBrokerOnCamStreamIdle, e("streams", "Stream idle", "Stream inattivo"), EventCategory.StreamBrokerOnRequestStreamSourceRefresh, e("streams", "Stream source refresh requested", "Aggiornamento sorgente stream richiesto"), EventCategory.StreamParamsChanged, e("streams", "Stream parameters changed", "Parametri dello stream cambiati"), EventCategory.DeviceStateChanged, e("devices", "Device state changed", "Stato dispositivo cambiato"), EventCategory.DeviceCommandSettled, e("devices", "Device command settled", "Comando al dispositivo concluso"), EventCategory.DeviceNativeShadowChanged, e("devices", "Device native state changed", "Stato nativo del dispositivo cambiato"), EventCategory.ZoneAnalyticsOccupancyChanged, e("detection", "Zone occupancy changed", "Occupazione zona cambiata"), EventCategory.BatteryOnStatusChanged, e("devices", "Battery status changed", "Stato batteria cambiato"), EventCategory.NetworkLinkOnStatusChanged, e("devices", "Network link status changed", "Stato del collegamento di rete cambiato"), EventCategory.BatteryOnWakeStarted, e("devices", "Battery device woke up", "Dispositivo a batteria attivato"), EventCategory.DoorbellOnPressed, e("devices", "Doorbell pressed", "Campanello premuto"), EventCategory.RunningStarted, e("devices", "Run started", "Esecuzione avviata"), EventCategory.RunningFinished, e("devices", "Run finished", "Esecuzione terminata"), EventCategory.WorkloadStarted, e("devices", "Workload started", "Carico di lavoro avviato"), EventCategory.WorkloadStopped, e("devices", "Workload stopped", "Carico di lavoro fermato"), EventCategory.WorkloadCrashed, e("devices", "Workload crashed", "Carico di lavoro in crash"), EventCategory.WorkloadRecovered, e("devices", "Workload recovered", "Carico di lavoro ripristinato"), EventCategory.DeviceRunOpened, e("devices", "Device run opened", "Ciclo del dispositivo aperto"), EventCategory.DeviceRunClosed, e("devices", "Device run closed", "Ciclo del dispositivo chiuso"), EventCategory.EventEmitted, e("devices", "Device event", "Evento del dispositivo"), EventCategory.PipelineEngineMetricsSnapshot, e("metrics", "Engine metrics snapshot", "Metriche dei motori", N), EventCategory.PipelineEngineProvisioning, e("pipeline", "Engine provisioning", "Preparazione del motore"), EventCategory.ClusterTopologySnapshot, e("metrics", "Cluster topology snapshot", "Topologia del cluster", N), EventCategory.MetricsNodeResourcesSnapshot, e("metrics", "Node resources snapshot", "Risorse dei nodi", N), EventCategory.MetricsNodeProcessesSnapshot, e("metrics", "Node processes snapshot", "Processi dei nodi", N), EventCategory.CapabilityBindingChanged, e("system", "Capability binding changed", "Collegamento di capability cambiato", N), EventCategory.ModelDownloadProgress, e("pipeline", "Model download progress", "Avanzamento download modello", N), EventCategory.AgentRegistered, e("agents", "Agent registered", "Agent registrato"), EventCategory.AgentUnregistered, e("agents", "Agent removed", "Agent rimosso"), EventCategory.AgentOnline, e("agents", "Agent online", "Agent online"), EventCategory.AgentOffline, e("agents", "Agent offline", "Agent offline"), EventCategory.WorkerOnline, e("agents", "Worker online", "Worker online"), EventCategory.WorkerOffline, e("agents", "Worker offline", "Worker offline"), EventCategory.AgentTaskDispatched, e("agents", "Agent task dispatched", "Attività inviata a un agent"), EventCategory.AgentTaskAssigned, e("agents", "Agent task assigned", "Attività assegnata a un agent"), EventCategory.AgentTrpcConnected, e("agents", "Agent API connected", "API dell’agent connessa"), EventCategory.AgentWsConnected, e("agents", "Agent socket connected", "Socket dell’agent connesso"), EventCategory.AgentWsDisconnected, e("agents", "Agent socket disconnected", "Socket dell’agent disconnesso"), EventCategory.AgentBackupActivated, e("agents", "Agent backup activated", "Backup dell’agent attivato"), EventCategory.OrchestrationSettingsUpdated, e("pipeline", "Orchestration settings updated", "Impostazioni di orchestrazione aggiornate"), EventCategory.MotionAnalysis, e("detection", "Motion analysis", "Analisi del movimento", N), EventCategory.MotionZonesRaw, e("detection", "Raw motion zones", "Zone di movimento grezze", N), EventCategory.MotionOnMotionChanged, e("detection", "Motion changed", "Movimento cambiato", N), EventCategory.DetectionResult, e("detection", "Detection result", "Risultato del rilevamento", N), EventCategory.DetectionRaw, e("detection", "Raw detection", "Rilevamento grezzo"), EventCategory.DetectionCameraNative, e("detection", "Camera native detection", "Rilevamento nativo della camera"), EventCategory.PipelineAudioInferenceResult, e("pipeline", "Audio inference result", "Risultato di inferenza audio", N), EventCategory.DetectionPhaseTransition, e("detection", "Detection phase changed", "Fase di rilevamento cambiata"), EventCategory.ProviderMotion, e("detection", "Camera raw motion", "Movimento grezzo della camera", N), EventCategory.ProviderDetection, e("detection", "Camera onboard detection", "Rilevamento a bordo camera"), EventCategory.EnrichmentEmbeddingStored, e("enrichment", "Embedding stored", "Embedding salvato"), EventCategory.EnrichmentSceneStateChanged, e("enrichment", "Scene state changed", "Stato della scena cambiato"), EventCategory.EnrichmentActivitySummary, e("enrichment", "Activity summary", "Riepilogo dell’attività"), EventCategory.PipelineAnalyticsTrackLifecycle, e("detection", "Track lifecycle", "Ciclo di vita della traccia"), EventCategory.PipelineAnalyticsTrackStarted, e("detection", "Track started", "Traccia iniziata", {
127394
+ EventCategory.SystemBoot, e("system", "System booted", "Sistema avviato"), EventCategory.SystemAddonsReady, e("system", "Addons ready", "Addon pronti"), EventCategory.SystemRestarting, e("system", "System restarting", "Sistema in riavvio"), EventCategory.SystemRestartCompleted, e("system", "Restart completed", "Riavvio completato"), EventCategory.SystemTlsCertChanged, e("system", "TLS certificate changed", "Certificato TLS cambiato"), EventCategory.UpdateAvailable, e("system", "Update available", "Aggiornamento disponibile"), EventCategory.SystemReadyState, e("system", "Readiness changed", "Stato di prontezza cambiato"), EventCategory.AddonStarted, e("addons", "Addon started", "Addon avviato"), EventCategory.AddonStopped, e("addons", "Addon stopped", "Addon fermato"), EventCategory.AddonRestarted, e("addons", "Addon restarted", "Addon riavviato"), EventCategory.AddonUpdated, e("addons", "Addon updated", "Addon aggiornato"), EventCategory.AddonInstalled, e("addons", "Addon installed", "Addon installato"), EventCategory.AddonUninstalled, e("addons", "Addon uninstalled", "Addon disinstallato"), EventCategory.AddonCrashed, e("addons", "Addon crashed", "Addon in errore fatale"), EventCategory.AddonRunnerFailed, e("addons", "Runner failed for good", "Runner fallito definitivamente"), EventCategory.AddonRunnerRefused, e("addons", "Runner refused", "Runner rifiutato"), EventCategory.ProcessStateChanged, e("addons", "Process state changed", "Stato del processo cambiato"), EventCategory.SystemRunnerCheck, e("system", "Runner check", "Verifica dei runner"), EventCategory.AlertEpisode, e("system", "Alert episode", "Episodio di allarme"), EventCategory.AddonError, e("addons", "Addon error", "Errore di un addon"), EventCategory.AddonPageReady, e("addons", "Addon page ready", "Pagina addon pronta"), EventCategory.AddonWidgetReady, e("addons", "Addon widget ready", "Widget addon pronto"), EventCategory.AddonLoadFailed, e("addons", "Addon failed to load", "Caricamento addon fallito"), EventCategory.KeychainChanged, e("system", "Keychain changed", "Portachiavi modificato"), EventCategory.AddonLoadRecovered, e("addons", "Addon load recovered", "Caricamento addon ripristinato"), EventCategory.AddonUnsupportedVersion, e("addons", "Addon version unsupported", "Versione addon non supportata"), EventCategory.AddonUnsupportedResolved, e("addons", "Unsupported addon resolved", "Addon non supportato risolto"), EventCategory.AddonRetryScheduled, e("addons", "Addon retry scheduled", "Nuovo tentativo addon pianificato"), EventCategory.SystemLivenessFailed, e("system", "Liveness check failed", "Controllo di attività fallito"), EventCategory.SystemLivenessRecovered, e("system", "Liveness recovered", "Controllo di attività ripristinato"), EventCategory.AddonRetryAttempting, e("addons", "Addon retry running", "Nuovo tentativo addon in corso"), EventCategory.DeviceRegistered, e("devices", "Device registered", "Dispositivo registrato"), EventCategory.DeviceUnregistered, e("devices", "Device removed", "Dispositivo rimosso"), EventCategory.DeviceEnabled, e("devices", "Device enabled", "Dispositivo abilitato"), EventCategory.DeviceDisabled, e("devices", "Device disabled", "Dispositivo disabilitato"), EventCategory.DeviceSettingsUpdated, e("devices", "Device settings updated", "Impostazioni dispositivo aggiornate"), EventCategory.DeviceBindingsChanged, e("devices", "Device bindings changed", "Collegamenti dispositivo cambiati"), EventCategory.DeviceMetaChanged, e("devices", "Device details changed", "Dettagli dispositivo cambiati"), EventCategory.DeviceSourceInfoChanged, e("devices", "Device source info changed", "Info sorgente dispositivo cambiate"), EventCategory.DeviceStreamsRegistered, e("streams", "Device streams registered", "Stream del dispositivo registrati"), EventCategory.DeviceProvisioned, e("devices", "Device provisioned", "Dispositivo configurato"), EventCategory.DeviceReady, e("devices", "Device ready", "Dispositivo pronto"), EventCategory.IdentityLinkCreated, e("integrations", "Identity linked", "Identità collegata"), EventCategory.IdentityLinkLost, e("integrations", "Identity link lost", "Collegamento identità perso"), EventCategory.IntegrationEnabled, e("integrations", "Integration enabled", "Integrazione abilitata"), EventCategory.IntegrationDisabled, e("integrations", "Integration disabled", "Integrazione disabilitata"), EventCategory.IntegrationDeleted, e("integrations", "Integration deleted", "Integrazione eliminata"), EventCategory.BrokerStatusChanged, e("integrations", "Broker status changed", "Stato del broker cambiato"), EventCategory.BrokerMessage, e("integrations", "Broker message", "Messaggio del broker", N), EventCategory.ProviderStarted, e("integrations", "Provider started", "Provider avviato"), EventCategory.ProviderStopped, e("integrations", "Provider stopped", "Provider fermato"), EventCategory.ProcessCrashed, e("addons", "Process crashed", "Processo andato in crash"), EventCategory.ProcessRestartScheduled, e("addons", "Process restart scheduled", "Riavvio del processo pianificato"), EventCategory.ProcessRestarted, e("addons", "Process restarted", "Processo riavviato"), EventCategory.StorageLocationsChanged, e("storage", "Storage locations changed", "Posizioni di archiviazione cambiate"), EventCategory.RecordingStarted, e("recording", "Recording started", "Registrazione avviata"), EventCategory.RecordingStopped, e("recording", "Recording stopped", "Registrazione fermata"), EventCategory.RecordingError, e("recording", "Recording error", "Errore di registrazione"), EventCategory.RecordingHealthDegraded, e("recording", "Recording degraded", "Registrazione degradata"), EventCategory.RecordingHealthStalled, e("recording", "Recording stalled", "Registrazione bloccata"), EventCategory.RecordingHealthOk, e("recording", "Recording healthy", "Registrazione regolare"), EventCategory.RecordingStorageCritical, e("recording", "Recording storage critical", "Spazio di registrazione critico"), EventCategory.StorageLocationLow, e("storage", "Storage location low", "Spazio in esaurimento"), EventCategory.StorageLocationCritical, e("storage", "Storage location critical", "Spazio critico"), EventCategory.StorageLocationOk, e("storage", "Storage location recovered", "Spazio tornato regolare"), EventCategory.StorageDrainProgress, e("storage", "Drain progress", "Avanzamento dello svuotamento"), EventCategory.StorageDrainComplete, e("storage", "Drain complete", "Svuotamento completato"), EventCategory.RecordingSegmentWritten, e("recording", "Segment written", "Segmento scritto"), EventCategory.RecordingPolicyFallback, e("recording", "Recording policy fallback", "Politica di registrazione di ripiego"), EventCategory.RecordingRetentionCompleted, e("recording", "Retention completed", "Pulizia completata"), EventCategory.RecordingExportProgress, e("recording", "Export progress", "Avanzamento esportazione"), EventCategory.RecordingExportCompleted, e("recording", "Export completed", "Esportazione completata"), EventCategory.RecordingExportFailed, e("recording", "Export failed", "Esportazione fallita"), EventCategory.DetectionEvent, e("detection", "Detection", "Rilevamento"), EventCategory.SessionTrackNew, e("detection", "Session track started", "Nuova traccia di sessione"), EventCategory.SessionTrackExpired, e("detection", "Session track expired", "Traccia di sessione scaduta"), EventCategory.BenchmarkProgress, e("metrics", "Benchmark progress", "Avanzamento benchmark", N), EventCategory.PlatformProbePhase, e("metrics", "Platform probe phase", "Fase di analisi piattaforma", N), EventCategory.PipelineProgress, e("pipeline", "Pipeline progress", "Avanzamento pipeline", N), EventCategory.PipelineTrace, e("pipeline", "Pipeline trace", "Traccia pipeline", N), EventCategory.PipelineInferenceResult, e("pipeline", "Inference result", "Risultato di inferenza", N), EventCategory.PipelineCameraAssigned, e("pipeline", "Camera assigned to pipeline", "Camera assegnata alla pipeline"), EventCategory.PipelineCameraUnassigned, e("pipeline", "Camera unassigned from pipeline", "Camera rimossa dalla pipeline"), EventCategory.PipelineNodeInferenceUnavailable, e("pipeline", "Node inference unavailable", "Inferenza del nodo non disponibile"), EventCategory.PipelineDetectionBlind, e("pipeline", "Detection blind", "Rilevamento cieco"), EventCategory.PipelineMotionNoisy, e("pipeline", "Motion too noisy", "Movimento troppo disturbato"), EventCategory.PipelineMotionCalm, e("pipeline", "Motion calm again", "Movimento di nuovo calmo"), EventCategory.PipelinePackageLlmSilent, e("pipeline", "Package check silent", "Verifica pacchi senza risposta"), EventCategory.PipelinePackageLlmAnswered, e("pipeline", "Package check answered", "Verifica pacchi con risposta"), EventCategory.PipelineCameraUpdated, e("pipeline", "Pipeline camera updated", "Camera della pipeline aggiornata"), EventCategory.PipelineIngestOwnerChanged, e("pipeline", "Ingest owner changed", "Responsabile dell’acquisizione cambiato"), EventCategory.PipelineRunnerLoadSnapshot, e("metrics", "Runner load snapshot", "Carico dei runner", N), EventCategory.PipelineCameraMetricsSnapshot, e("metrics", "Camera metrics snapshot", "Metriche delle camere", N), EventCategory.StreamBrokerMetricsSnapshot, e("metrics", "Stream broker metrics", "Metriche dello stream broker", N), EventCategory.StreamBrokerOnCamStreamDemand, e("streams", "Stream requested", "Stream richiesto"), EventCategory.StreamBrokerOnCamStreamIdle, e("streams", "Stream idle", "Stream inattivo"), EventCategory.StreamBrokerOnRequestStreamSourceRefresh, e("streams", "Stream source refresh requested", "Aggiornamento sorgente stream richiesto"), EventCategory.StreamBrokerOnSourceRestart, e("streams", "Stream source restarted", "Sorgente stream riavviata"), EventCategory.StreamParamsChanged, e("streams", "Stream parameters changed", "Parametri dello stream cambiati"), EventCategory.DeviceStateChanged, e("devices", "Device state changed", "Stato dispositivo cambiato"), EventCategory.DeviceCommandSettled, e("devices", "Device command settled", "Comando al dispositivo concluso"), EventCategory.DeviceNativeShadowChanged, e("devices", "Device native state changed", "Stato nativo del dispositivo cambiato"), EventCategory.ZoneAnalyticsOccupancyChanged, e("detection", "Zone occupancy changed", "Occupazione zona cambiata"), EventCategory.BatteryOnStatusChanged, e("devices", "Battery status changed", "Stato batteria cambiato"), EventCategory.NetworkLinkOnStatusChanged, e("devices", "Network link status changed", "Stato del collegamento di rete cambiato"), EventCategory.BatteryOnWakeStarted, e("devices", "Battery device woke up", "Dispositivo a batteria attivato"), EventCategory.DoorbellOnPressed, e("devices", "Doorbell pressed", "Campanello premuto"), EventCategory.RunningStarted, e("devices", "Run started", "Esecuzione avviata"), EventCategory.RunningFinished, e("devices", "Run finished", "Esecuzione terminata"), EventCategory.WorkloadStarted, e("devices", "Workload started", "Carico di lavoro avviato"), EventCategory.WorkloadStopped, e("devices", "Workload stopped", "Carico di lavoro fermato"), EventCategory.WorkloadCrashed, e("devices", "Workload crashed", "Carico di lavoro in crash"), EventCategory.WorkloadRecovered, e("devices", "Workload recovered", "Carico di lavoro ripristinato"), EventCategory.DeviceRunOpened, e("devices", "Device run opened", "Ciclo del dispositivo aperto"), EventCategory.DeviceRunClosed, e("devices", "Device run closed", "Ciclo del dispositivo chiuso"), EventCategory.EventEmitted, e("devices", "Device event", "Evento del dispositivo"), EventCategory.PipelineEngineMetricsSnapshot, e("metrics", "Engine metrics snapshot", "Metriche dei motori", N), EventCategory.PipelineEngineProvisioning, e("pipeline", "Engine provisioning", "Preparazione del motore"), EventCategory.ClusterTopologySnapshot, e("metrics", "Cluster topology snapshot", "Topologia del cluster", N), EventCategory.MetricsNodeResourcesSnapshot, e("metrics", "Node resources snapshot", "Risorse dei nodi", N), EventCategory.MetricsNodeProcessesSnapshot, e("metrics", "Node processes snapshot", "Processi dei nodi", N), EventCategory.CapabilityBindingChanged, e("system", "Capability binding changed", "Collegamento di capability cambiato", N), EventCategory.ModelDownloadProgress, e("pipeline", "Model download progress", "Avanzamento download modello", N), EventCategory.AgentRegistered, e("agents", "Agent registered", "Agent registrato"), EventCategory.AgentUnregistered, e("agents", "Agent removed", "Agent rimosso"), EventCategory.AgentOnline, e("agents", "Agent online", "Agent online"), EventCategory.AgentOffline, e("agents", "Agent offline", "Agent offline"), EventCategory.WorkerOnline, e("agents", "Worker online", "Worker online"), EventCategory.WorkerOffline, e("agents", "Worker offline", "Worker offline"), EventCategory.AgentTaskDispatched, e("agents", "Agent task dispatched", "Attività inviata a un agent"), EventCategory.AgentTaskAssigned, e("agents", "Agent task assigned", "Attività assegnata a un agent"), EventCategory.AgentTrpcConnected, e("agents", "Agent API connected", "API dell’agent connessa"), EventCategory.AgentWsConnected, e("agents", "Agent socket connected", "Socket dell’agent connesso"), EventCategory.AgentWsDisconnected, e("agents", "Agent socket disconnected", "Socket dell’agent disconnesso"), EventCategory.AgentBackupActivated, e("agents", "Agent backup activated", "Backup dell’agent attivato"), EventCategory.OrchestrationSettingsUpdated, e("pipeline", "Orchestration settings updated", "Impostazioni di orchestrazione aggiornate"), EventCategory.MotionAnalysis, e("detection", "Motion analysis", "Analisi del movimento", N), EventCategory.MotionZonesRaw, e("detection", "Raw motion zones", "Zone di movimento grezze", N), EventCategory.MotionOnMotionChanged, e("detection", "Motion changed", "Movimento cambiato", N), EventCategory.DetectionResult, e("detection", "Detection result", "Risultato del rilevamento", N), EventCategory.DetectionRaw, e("detection", "Raw detection", "Rilevamento grezzo"), EventCategory.DetectionCameraNative, e("detection", "Camera native detection", "Rilevamento nativo della camera"), EventCategory.PipelineAudioInferenceResult, e("pipeline", "Audio inference result", "Risultato di inferenza audio", N), EventCategory.DetectionPhaseTransition, e("detection", "Detection phase changed", "Fase di rilevamento cambiata"), EventCategory.ProviderMotion, e("detection", "Camera raw motion", "Movimento grezzo della camera", N), EventCategory.ProviderDetection, e("detection", "Camera onboard detection", "Rilevamento a bordo camera"), EventCategory.EnrichmentEmbeddingStored, e("enrichment", "Embedding stored", "Embedding salvato"), EventCategory.EnrichmentSceneStateChanged, e("enrichment", "Scene state changed", "Stato della scena cambiato"), EventCategory.EnrichmentActivitySummary, e("enrichment", "Activity summary", "Riepilogo dell’attività"), EventCategory.PipelineAnalyticsTrackLifecycle, e("detection", "Track lifecycle", "Ciclo di vita della traccia"), EventCategory.PipelineAnalyticsTrackStarted, e("detection", "Track started", "Traccia iniziata", {
127378
127395
  noise: true,
127379
127396
  deprecated: true
127380
127397
  }), EventCategory.PipelineAnalyticsTrackEnded, e("detection", "Track ended", "Traccia terminata", {
@@ -154122,8 +154139,15 @@ function convertLegacyWhen(half) {
154122
154139
  /** The longest one `wait` step lasts. It is cut by a restart of the run and does not survive a hub restart. */
154123
154140
  var WAIT_MAX_SECONDS = 3600;
154124
154141
  var WAIT_TOO_LONG = `a wait is at most one hour (${WAIT_MAX_SECONDS} s)`;
154142
+ /**
154143
+ * Every step kind may be switched off without deleting it: `enabled: false`
154144
+ * skips the step (and, for a block step, its whole subtree), traced `disabled`.
154145
+ * Absent means enabled.
154146
+ */
154147
+ var stepEnabledShape = { enabled: boolean().optional() };
154125
154148
  var AutomationWaitStepSchema = object({
154126
154149
  kind: literal("wait"),
154150
+ ...stepEnabledShape,
154127
154151
  seconds: number$1().min(0).max(WAIT_MAX_SECONDS, WAIT_TOO_LONG)
154128
154152
  });
154129
154153
  /**
@@ -154132,6 +154156,7 @@ var AutomationWaitStepSchema = object({
154132
154156
  */
154133
154157
  var AutomationCommandStepBaseSchema = object({
154134
154158
  kind: literal("command"),
154159
+ ...stepEnabledShape,
154135
154160
  /** WHO the step acts on. */
154136
154161
  target: ActionTargetSchema,
154137
154162
  /** The vocabulary action this step performs (`cover.open`). */
@@ -154207,6 +154232,7 @@ var AutomationGuardedCommandStepSchema = AutomationCommandStepBaseSchema.extend(
154207
154232
  /** End the run here, on purpose. `reason` may carry `{{vars.x}}` slots. */
154208
154233
  var AutomationStopStepSchema = object({
154209
154234
  kind: literal("stop"),
154235
+ ...stepEnabledShape,
154210
154236
  reason: string().min(1, "a stop needs a reason: it is what the run trace shows").max(200),
154211
154237
  /** `ok`: the run ends as a success. `failed`: it ends as a failure, with the reason. */
154212
154238
  outcome: _enum(["ok", "failed"]),
@@ -154226,6 +154252,7 @@ var RESERVED_RUN_VARS = [
154226
154252
  */
154227
154253
  var AutomationSetStepSchema = object({
154228
154254
  kind: literal("set"),
154255
+ ...stepEnabledShape,
154229
154256
  vars: record(string(), union([
154230
154257
  string().max(500),
154231
154258
  number$1(),
@@ -154234,8 +154261,25 @@ var AutomationSetStepSchema = object({
154234
154261
  /** Set only when this reads true; false or unknown leaves the bag as it is. */
154235
154262
  if: AutomationWhenSchema.optional()
154236
154263
  });
154264
+ var NOTIFY_BODY_MAX = 2e3;
154265
+ /**
154266
+ * Send a notification through one notification target (the same targets the
154267
+ * notification centre addresses). Title and body may carry `{{vars.x}}` slots.
154268
+ * Not a device command: a notification target is an instance of the
154269
+ * `notification-output` cap, not a device.
154270
+ */
154271
+ var AutomationNotifyStepSchema = object({
154272
+ kind: literal("notify"),
154273
+ ...stepEnabledShape,
154274
+ /** The notification target (an instance id of `notification-output`). */
154275
+ targetId: string().min(1, "pick the notification target"),
154276
+ title: string().max(200).optional(),
154277
+ body: string().min(1, "a notification needs a message").max(NOTIFY_BODY_MAX),
154278
+ ...continueOnErrorShape
154279
+ });
154237
154280
  var AutomationRunActionStepSchema = object({
154238
154281
  kind: literal("action"),
154282
+ ...stepEnabledShape,
154239
154283
  /** An entry of the `actions` surface (`internal:<uuid>` or `<addonId>:<localId>`). */
154240
154284
  actionId: string().min(1),
154241
154285
  /** Values for the action's declared variables; the others take their default. */
@@ -154261,6 +154305,7 @@ var WAIT_UNTIL_TIMEOUT_MAX_S = 21600;
154261
154305
  */
154262
154306
  var AutomationWaitUntilStepSchema = object({
154263
154307
  kind: literal("wait-until"),
154308
+ ...stepEnabledShape,
154264
154309
  when: AutomationWhenSchema,
154265
154310
  timeoutS: number$1().int().min(1, "a wait needs a timeout of at least one second").max(WAIT_UNTIL_TIMEOUT_MAX_S, `a wait for a condition is at most six hours (${WAIT_UNTIL_TIMEOUT_MAX_S} s)`),
154266
154311
  onTimeout: _enum(["continue", "stop"])
@@ -154286,7 +154331,8 @@ var plainStepSchemas = [
154286
154331
  AutomationCommandStepBaseSchema.extend(continueOnErrorShape).strict().superRefine(refineKnownAction),
154287
154332
  AutomationStopStepSchema.omit({ if: true }).strict(),
154288
154333
  AutomationSetStepSchema.omit({ if: true }).strict(),
154289
- AutomationRunActionStepSchema.strict()
154334
+ AutomationRunActionStepSchema.strict(),
154335
+ AutomationNotifyStepSchema.strict()
154290
154336
  ];
154291
154337
  /**
154292
154338
  * A plain step: a flow step with no condition of its own and no step inside
@@ -154294,7 +154340,7 @@ var plainStepSchemas = [
154294
154340
  */
154295
154341
  var AutomationBranchStepSchema = discriminatedUnion("kind", plainStepSchemas, { error: nestTooDeep });
154296
154342
  /** A step that can run beside others: it writes no variable and does not end the run. */
154297
- var AutomationParallelMemberSchema = AutomationBranchStepSchema.refine((step) => step.kind === "command" || step.kind === "action" || step.kind === "wait", "a parallel holds device commands, actions and waits only: a set or a stop beside other steps has no order");
154343
+ var AutomationParallelMemberSchema = AutomationBranchStepSchema.refine((step) => step.kind === "command" || step.kind === "action" || step.kind === "notify" || step.kind === "wait", "a parallel holds device commands, actions and waits only: a set or a stop beside other steps has no order");
154298
154344
  /**
154299
154345
  * Several steps at once (#500): all are started together and all are awaited.
154300
154346
  * A failure fails the run once the others finished, as in a sequence; a member
@@ -154302,6 +154348,7 @@ var AutomationParallelMemberSchema = AutomationBranchStepSchema.refine((step) =>
154302
154348
  */
154303
154349
  var AutomationParallelStepSchema = object({
154304
154350
  kind: literal("parallel"),
154351
+ ...stepEnabledShape,
154305
154352
  steps: array(AutomationParallelMemberSchema).min(2, "a parallel needs at least two steps").max(5, `a parallel takes at most 5 steps`)
154306
154353
  }).strict();
154307
154354
  var REPEAT_NEEDS_MAX = "a repeat on a condition needs a maximum number of iterations";
@@ -154342,6 +154389,7 @@ var AutomationRepeatLoopSchema = discriminatedUnion("by", [
154342
154389
  function repeatSchemaOf(step) {
154343
154390
  return object({
154344
154391
  kind: literal("repeat"),
154392
+ ...stepEnabledShape,
154345
154393
  loop: AutomationRepeatLoopSchema,
154346
154394
  steps: array(step).min(1, "a repeat needs at least one step").max(10, `a repeat takes at most 10 steps`)
154347
154395
  }).strict();
@@ -154357,6 +154405,7 @@ function chooseSchemaOf(step) {
154357
154405
  const steps = array(step).max(10);
154358
154406
  return object({
154359
154407
  kind: literal("choose"),
154408
+ ...stepEnabledShape,
154360
154409
  branches: array(object({
154361
154410
  if: AutomationWhenSchema,
154362
154411
  steps: steps.min(1, "a branch needs at least one step")
@@ -154382,8 +154431,10 @@ var AutomationActionSchema = discriminatedUnion("kind", [
154382
154431
  AutomationParallelStepSchema,
154383
154432
  AutomationRepeatStepSchema,
154384
154433
  AutomationRunActionStepSchema,
154434
+ AutomationNotifyStepSchema,
154385
154435
  object({
154386
154436
  kind: literal("code"),
154437
+ ...stepEnabledShape,
154387
154438
  /** Compiled into the automation's OWN block by esbuild — not a third
154388
154439
  * runtime, not a `vm`, and not dynamically evaluated. */
154389
154440
  code: string().min(1).max(2e4)
@@ -159383,6 +159434,8 @@ method(object({
159383
159434
  /** The slot the publisher says this stream IS — see `CameraStreamSchema.profileHint`. */
159384
159435
  profileHint: CamProfileSchema.optional(),
159385
159436
  metadata: record(string(), unknown()).optional(),
159437
+ /** The longest session the source keeps open (ms) — see `CameraStreamSchema.maxSessionMs`. */
159438
+ maxSessionMs: number$1().int().positive().optional(),
159386
159439
  /** Required when kind === 'derived' — the source camStreamId the
159387
159440
  * derived broker reads its encoded plane from.
159388
159441
  * The runtime guard (broker manager, Task 10) enforces presence for
@@ -159601,6 +159654,11 @@ method(object({
159601
159654
  deviceId: number$1().int().nonnegative(),
159602
159655
  camStreamId: string(),
159603
159656
  brokerId: string()
159657
+ })), event(object({
159658
+ deviceId: number$1().int().nonnegative(),
159659
+ camStreamId: string(),
159660
+ brokerId: string(),
159661
+ reason: string()
159604
159662
  })), NOT_A_DEVICE.PIPELINE;
159605
159663
  var StreamCodecSchema = _enum([
159606
159664
  "h264",
@@ -162705,7 +162763,7 @@ var mediaPlayerCapability = {
162705
162763
  ]
162706
162764
  }
162707
162765
  };
162708
- DeviceType.Camera, DeviceType.Sensor, DeviceType.Button, DeviceType.Switch, DeviceType.PetFeeder, DeviceType.Container, DeviceType.Climate, DeviceType.EventEmitter, DeviceType.Climate, DeviceType.Climate, DeviceType.Camera, DeviceType.Light, DeviceType.Siren, DeviceType.Switch, DeviceType.Sensor, DeviceType.Climate, DeviceType.Button, DeviceType.EventEmitter, DeviceType.Update, DeviceType.Generic, DeviceType.Notifier, DeviceType.Script, DeviceType.Automation, DeviceType.Lock, DeviceType.Cover, DeviceType.Valve, DeviceType.Humidifier, DeviceType.WaterHeater, DeviceType.Fan, DeviceType.MediaPlayer, DeviceType.AlarmPanel, DeviceType.Control, DeviceType.Presence, DeviceType.Weather, DeviceType.WeatherStation, DeviceType.Vacuum, DeviceType.LawnMower, DeviceType.Container, DeviceType.Image, DeviceType.PetFeeder, DeviceType.PetFountain, DeviceType.Dishwasher, DeviceType.Washer, DeviceType.Dryer, DeviceType.Gateway, DeviceType.HeatPump, DeviceType.EnergySystem, DeviceType.Workload, DeviceType.Camera, DeviceType.Fan, DeviceType.Fan, DeviceType.Fan, DeviceType.Fan, DeviceType.Fan, DeviceType.Fan, DeviceType.Fan, DeviceType.Fan, DeviceType.Fan, DeviceType.Fan, DeviceType.Lock, DeviceType.Camera, DeviceType.Switch, DeviceType.Light, DeviceType.Fan, DeviceType.Climate, DeviceType.Humidifier, DeviceType.WaterHeater, DeviceType.MediaPlayer, DeviceType.Washer, DeviceType.Dryer, DeviceType.Dishwasher, DeviceType.Vacuum, DeviceType.LawnMower, DeviceType.PetFeeder, DeviceType.Workload, DeviceType.Switch, DeviceType.Light, DeviceType.Fan, DeviceType.Climate, DeviceType.Humidifier, DeviceType.WaterHeater, DeviceType.MediaPlayer, DeviceType.Washer, DeviceType.Dryer, DeviceType.Dishwasher, DeviceType.Vacuum, DeviceType.LawnMower, DeviceType.PetFeeder, DeviceType.Workload, DeviceType.Switch, DeviceType.Light, DeviceType.Fan, DeviceType.Climate, DeviceType.Humidifier, DeviceType.WaterHeater, DeviceType.MediaPlayer, DeviceType.Washer, DeviceType.Dryer, DeviceType.Dishwasher, DeviceType.Vacuum, DeviceType.LawnMower, DeviceType.PetFeeder, DeviceType.Workload, DeviceType.Switch, DeviceType.Light, DeviceType.Fan, DeviceType.Climate, DeviceType.Humidifier, DeviceType.WaterHeater, DeviceType.MediaPlayer, DeviceType.Washer, DeviceType.Dryer, DeviceType.Dishwasher, DeviceType.Vacuum, DeviceType.LawnMower, DeviceType.PetFeeder, DeviceType.Workload, DeviceType.Gateway, DeviceType.Camera, DeviceType.Sensor, DeviceType.MediaPlayer, DeviceType.Vacuum, DeviceType.Generic, DeviceType.Washer, DeviceType.Dryer, DeviceType.Dishwasher, DeviceType.PetFountain, DeviceType.Fan, DeviceType.Humidifier, DeviceType.Climate, DeviceType.WaterHeater, DeviceType.MediaPlayer, DeviceType.Washer, DeviceType.Dryer, DeviceType.Dishwasher, DeviceType.Vacuum, DeviceType.LawnMower, DeviceType.MediaPlayer, DeviceType.WaterHeater, DeviceType.Humidifier, DeviceType.Fan, DeviceType.Climate, DeviceType.PetFeeder, DeviceType.MediaPlayer, DeviceType.WeatherStation, DeviceType.WeatherStation, DeviceType.WeatherStation, DeviceType.WeatherStation, DeviceType.WeatherStation, DeviceType.WeatherStation, DeviceType.WeatherStation, DeviceType.WeatherStation, DeviceType.WeatherStation, DeviceType.WeatherStation, DeviceType.WeatherStation, DeviceType.WeatherStation, DeviceType.WeatherStation, DeviceType.WeatherStation, DeviceType.WeatherStation, DeviceType.WeatherStation, DeviceType.WeatherStation, DeviceType.WeatherStation, DeviceType.WeatherStation, DeviceType.WeatherStation;
162766
+ DeviceType.Camera, DeviceType.Sensor, DeviceType.Button, DeviceType.Switch, DeviceType.PetFeeder, DeviceType.Container, DeviceType.Climate, DeviceType.EventEmitter, DeviceType.Climate, DeviceType.Climate, DeviceType.Camera, DeviceType.Light, DeviceType.Siren, DeviceType.Switch, DeviceType.Sensor, DeviceType.Climate, DeviceType.Button, DeviceType.EventEmitter, DeviceType.Update, DeviceType.Generic, DeviceType.Notifier, DeviceType.Script, DeviceType.Automation, DeviceType.Lock, DeviceType.Cover, DeviceType.Valve, DeviceType.Humidifier, DeviceType.WaterHeater, DeviceType.Fan, DeviceType.MediaPlayer, DeviceType.AlarmPanel, DeviceType.Control, DeviceType.Presence, DeviceType.Weather, DeviceType.WeatherStation, DeviceType.Vacuum, DeviceType.LawnMower, DeviceType.Container, DeviceType.Image, DeviceType.PetFeeder, DeviceType.PetFountain, DeviceType.Dishwasher, DeviceType.Washer, DeviceType.Dryer, DeviceType.Gateway, DeviceType.HeatPump, DeviceType.EnergySystem, DeviceType.Workload, DeviceType.Camera, DeviceType.Fan, DeviceType.Fan, DeviceType.Fan, DeviceType.Fan, DeviceType.Fan, DeviceType.Fan, DeviceType.Fan, DeviceType.Fan, DeviceType.Fan, DeviceType.Fan, DeviceType.HeatPump, DeviceType.HeatPump, DeviceType.Lock, DeviceType.Camera, DeviceType.Switch, DeviceType.Light, DeviceType.Fan, DeviceType.Climate, DeviceType.Humidifier, DeviceType.WaterHeater, DeviceType.MediaPlayer, DeviceType.Washer, DeviceType.Dryer, DeviceType.Dishwasher, DeviceType.Vacuum, DeviceType.LawnMower, DeviceType.PetFeeder, DeviceType.Workload, DeviceType.Switch, DeviceType.Light, DeviceType.Fan, DeviceType.Climate, DeviceType.Humidifier, DeviceType.WaterHeater, DeviceType.MediaPlayer, DeviceType.Washer, DeviceType.Dryer, DeviceType.Dishwasher, DeviceType.Vacuum, DeviceType.LawnMower, DeviceType.PetFeeder, DeviceType.Workload, DeviceType.Switch, DeviceType.Light, DeviceType.Fan, DeviceType.Climate, DeviceType.Humidifier, DeviceType.WaterHeater, DeviceType.MediaPlayer, DeviceType.Washer, DeviceType.Dryer, DeviceType.Dishwasher, DeviceType.Vacuum, DeviceType.LawnMower, DeviceType.PetFeeder, DeviceType.Workload, DeviceType.Switch, DeviceType.Light, DeviceType.Fan, DeviceType.Climate, DeviceType.Humidifier, DeviceType.WaterHeater, DeviceType.MediaPlayer, DeviceType.Washer, DeviceType.Dryer, DeviceType.Dishwasher, DeviceType.Vacuum, DeviceType.LawnMower, DeviceType.PetFeeder, DeviceType.Workload, DeviceType.Gateway, DeviceType.Camera, DeviceType.Sensor, DeviceType.MediaPlayer, DeviceType.Vacuum, DeviceType.Generic, DeviceType.Washer, DeviceType.Dryer, DeviceType.Dishwasher, DeviceType.PetFountain, DeviceType.Fan, DeviceType.Humidifier, DeviceType.Climate, DeviceType.WaterHeater, DeviceType.MediaPlayer, DeviceType.Washer, DeviceType.Dryer, DeviceType.Dishwasher, DeviceType.Vacuum, DeviceType.LawnMower, DeviceType.MediaPlayer, DeviceType.WaterHeater, DeviceType.Humidifier, DeviceType.Fan, DeviceType.Climate, DeviceType.PetFeeder, DeviceType.MediaPlayer, DeviceType.WeatherStation, DeviceType.WeatherStation, DeviceType.WeatherStation, DeviceType.WeatherStation, DeviceType.WeatherStation, DeviceType.WeatherStation, DeviceType.WeatherStation, DeviceType.WeatherStation, DeviceType.WeatherStation, DeviceType.WeatherStation, DeviceType.WeatherStation, DeviceType.WeatherStation, DeviceType.WeatherStation, DeviceType.WeatherStation, DeviceType.WeatherStation, DeviceType.WeatherStation, DeviceType.WeatherStation, DeviceType.WeatherStation, DeviceType.WeatherStation, DeviceType.WeatherStation;
162709
162767
  var NUMBER = {
162710
162768
  kind: "fixed",
162711
162769
  result: ["number"]
@@ -169143,6 +169201,15 @@ var DeviceFaultSchema = object({
169143
169201
  label: string(),
169144
169202
  severity: DeviceErrorSeveritySchema
169145
169203
  });
169204
+ /** One kind of fault a device CAN raise: the integration's own declared catalog entry. */
169205
+ var DeviceFaultTypeSchema = DeviceFaultSchema;
169206
+ /**
169207
+ * The fault catalog of a device, declared by its integration at runtime (never a
169208
+ * code enum). A fault outside the catalog is still published and still matches
169209
+ * a rule that names no code.
169210
+ */
169211
+ var ListFaultTypesInputSchema = object({ deviceId: number$1().int().nonnegative() });
169212
+ var FaultTypesSchema = object({ types: array(DeviceFaultTypeSchema) });
169146
169213
  /**
169147
169214
  * The fault a device reports right now. One slice per device.
169148
169215
  *
@@ -169180,7 +169247,12 @@ var errorCapability = {
169180
169247
  scope: "device",
169181
169248
  deviceNative: true,
169182
169249
  mode: "singleton",
169183
- methods: {},
169250
+ methods: {
169251
+ /** The fault codes this device's integration can raise; `[]` when it declares none. */
169252
+ listFaultTypes: method(ListFaultTypesInputSchema, FaultTypesSchema, {
169253
+ kind: "query",
169254
+ auth: "protected"
169255
+ }) },
169184
169256
  status: {
169185
169257
  schema: ErrorStatusSchema,
169186
169258
  kind: "push",
@@ -171128,6 +171200,43 @@ function heatPumpInstantCop(power) {
171128
171200
  if (thermalW === null || electricalW === null || electricalW <= 0) return null;
171129
171201
  return thermalW / electricalW;
171130
171202
  }
171203
+ var HEAT_PUMP_CUSTOMIZE_DEVICE_TYPES = [DeviceType.HeatPump];
171204
+ /** One electrical reading the operator may take from a device they pick, unit checked. */
171205
+ function electricalTarget(id, path, unit) {
171206
+ return {
171207
+ id,
171208
+ cardinality: "scalar",
171209
+ vocabulary: { cap: "heat-pump-status" },
171210
+ deviceTypes: HEAT_PUMP_CUSTOMIZE_DEVICE_TYPES,
171211
+ apply: "replace",
171212
+ path,
171213
+ sources: [{
171214
+ kind: "numeric",
171215
+ requiredUnit: unit,
171216
+ transforms: [{ kind: "identity" }]
171217
+ }],
171218
+ sourceReport: { status: "assignment-status" }
171219
+ };
171220
+ }
171221
+ var HEAT_PUMP_TARGETS = [electricalTarget("electrical-power", "power.electricalW", "W"), electricalTarget("electrical-energy", "energy.electricalKwh", "kWh")];
171222
+ /**
171223
+ * Customize (D984, #476): a gateway that reports no instantaneous electrical
171224
+ * power (the cloud ones) or whose energy meter the operator trusts less than a
171225
+ * dedicated one lets the OPERATOR pick a device for `power.electricalW` and
171226
+ * `energy.electricalKwh` — a `replace` over a field listed in `overridable`,
171227
+ * nothing else. The replaced value IS the cap field, so the instant COP, the
171228
+ * hero pills and the history use it; nothing is linked by itself (D356), the
171229
+ * unit is checked, and a source that does not answer releases the field back to
171230
+ * the native reading (never a 0, D393).
171231
+ */
171232
+ var heatPumpStatusCustomize = {
171233
+ version: 1,
171234
+ overridable: HEAT_PUMP_TARGETS.map((target) => ({
171235
+ path: target.path,
171236
+ by: target.id
171237
+ })),
171238
+ targets: HEAT_PUMP_TARGETS
171239
+ };
171131
171240
  var heatPumpStatusCapability = {
171132
171241
  name: "heat-pump-status",
171133
171242
  scope: "device",
@@ -171146,6 +171255,7 @@ var heatPumpStatusCapability = {
171146
171255
  * (the series are recorded). See `RuntimeStateDurability`.
171147
171256
  */
171148
171257
  durability: "session",
171258
+ customize: heatPumpStatusCustomize,
171149
171259
  /**
171150
171260
  * History (D850, D917): `circuits[]` is a keyed array — one series per circuit and
171151
171261
  * field, named by the circuit's label. The mode is a state (D896); the energy
@@ -172937,6 +173047,8 @@ var IntegrationInstanceKindSchema = object({
172937
173047
  role: IntegrationInstanceRoleSchema.optional(),
172938
173048
  /** `testInstance` really probes the remote for this kind; absent takes the provider's `canTest`. */
172939
173049
  canTest: boolean().optional(),
173050
+ /** `false`: Add never offers this kind (the system creates its one instance, e.g. a default integration). Absent = creatable. */
173051
+ creatable: boolean().optional(),
172940
173052
  /** The kind signs in through a server-held interactive session. */
172941
173053
  signIn: object({
172942
173054
  basePath: string().min(1),
@@ -184109,6 +184221,13 @@ var NcSystemEventConditionSchema = object({
184109
184221
  * pick from. The hub refuses an id the action index does not know.
184110
184222
  */
184111
184223
  commandActions: array(string().min(1)).min(1).optional(),
184224
+ /**
184225
+ * `device-attention-*` only: the fault CODES this rule speaks about (the
184226
+ * integration declares them through `error.listFaultTypes`; free text is
184227
+ * accepted too). Absent or empty = any fault. The rule matches when any
184228
+ * fault of the episode is in the list.
184229
+ */
184230
+ faultCodes: array(string().min(1)).optional(),
184112
184231
  /** `device-command` only: how the command settled. A device's own change is not a command. */
184113
184232
  commandOutcomes: array(_enum([
184114
184233
  "confirmed",
@@ -196034,7 +196153,16 @@ var CamStreamDescriptorSchema = object({
196034
196153
  /** The slot the publisher says this stream IS — see `CameraStreamSchema.profileHint`. */
196035
196154
  profileHint: CamProfileSchema.optional(),
196036
196155
  /** Transport-specific opaque metadata (e.g. rfc4571 SDP). */
196037
- metadata: record(string(), unknown()).optional()
196156
+ metadata: record(string(), unknown()).optional(),
196157
+ /**
196158
+ * The longest continuous session the SOURCE will keep open, in ms, declared by
196159
+ * the provider that knows it (a hub that cuts every child's session on a
196160
+ * timer). Absent = no limit. The broker re-dials a live source a little
196161
+ * BEFORE this elapses, on its own terms and announced to consumers, so the
196162
+ * source's cut never lands mid-recording. Declare slightly under what was
196163
+ * observed.
196164
+ */
196165
+ maxSessionMs: number$1().int().positive().optional()
196038
196166
  });
196039
196167
  /**
196040
196168
  * `stream-catalog` — device-scoped, provider-implemented. The pull counterpart
@@ -202942,6 +203070,20 @@ function deviceErrorEdge(previous, next) {
202942
203070
  function deviceErrorAlertId(deviceId) {
202943
203071
  return `device-error:${String(deviceId)}`;
202944
203072
  }
203073
+ /** Every active fault, the principal first; a status that lists none still names its principal. */
203074
+ function activeFaults(status) {
203075
+ if (status.faults !== void 0 && status.faults.length > 0) return status.faults.map(({ code, label, severity }) => ({
203076
+ code,
203077
+ label,
203078
+ severity
203079
+ }));
203080
+ if (status.code === null) return [];
203081
+ return [{
203082
+ code: status.code,
203083
+ label: status.label ?? status.code,
203084
+ severity: status.severity
203085
+ }];
203086
+ }
202945
203087
  /** The alert that opens an episode. `since` is the fault's own start, else `now`. */
202946
203088
  function buildDeviceErrorAlert(deviceId, deviceName, status, now) {
202947
203089
  const label = status.label ?? status.code ?? "Fault";
@@ -202969,7 +203111,9 @@ function buildDeviceErrorAlert(deviceId, deviceName, status, now) {
202969
203111
  metadata: {
202970
203112
  episodeId: `${alertId}@${String(startedAt)}`,
202971
203113
  code: status.code,
202972
- deviceSeverity: status.severity
203114
+ deviceSeverity: status.severity,
203115
+ label: status.label,
203116
+ faults: activeFaults(status)
202973
203117
  }
202974
203118
  };
202975
203119
  }
@@ -202979,6 +203123,8 @@ var BaseDevice = class {
202979
203123
  type;
202980
203124
  /** True when another process owns the base slices (`options.deviceStatus: 'external'`). */
202981
203125
  statusIsExternal;
203126
+ /** The fault catalog the integration declared; `[]` until it does. */
203127
+ faultTypes = [];
202982
203128
  name;
202983
203129
  parentDeviceId;
202984
203130
  role;
@@ -203316,10 +203462,19 @@ var BaseDevice = class {
203316
203462
  * a restart is compared, not announced again.
203317
203463
  */
203318
203464
  registerErrorCap() {
203319
- this.ctx.registerNativeCap?.(errorCapability, {});
203465
+ this.ctx.registerNativeCap?.(errorCapability, { listFaultTypes: async () => ({ types: [...this.faultTypes] }) });
203320
203466
  if (this.runtimeState.getCapState(errorCapability.name) === void 0) this.setCapSlice(errorCapability, ERROR_STATUS_COLD);
203321
203467
  }
203322
203468
  /**
203469
+ * Declare the fault kinds this device's integration can raise (code, label,
203470
+ * severity), served by `error.listFaultTypes` so a rule's code picker is
203471
+ * offered the integration's own words. The default is `[]`; a fault outside
203472
+ * the catalog is still published. Call it before or after `registerErrorCap`.
203473
+ */
203474
+ declareFaultTypes(types) {
203475
+ this.faultTypes = types.map((type) => ({ ...type }));
203476
+ }
203477
+ /**
203323
203478
  * Publish the device's fault. The slice is written; on an EDGE (a fault
203324
203479
  * starts, or one resolves) an attention episode opens or closes through the
203325
203480
  * alerts cap, which the notification center announces as
@@ -210296,6 +210451,13 @@ Object.freeze({
210296
210451
  access: "view",
210297
210452
  role: "viewer"
210298
210453
  },
210454
+ "error.listFaultTypes": {
210455
+ capName: "error",
210456
+ capScope: "device",
210457
+ addonId: null,
210458
+ access: "view",
210459
+ role: "viewer"
210460
+ },
210299
210461
  "eventEmitter.getStatus": {
210300
210462
  capName: "event-emitter",
210301
210463
  capScope: "device",
@@ -218919,6 +219081,11 @@ Object.freeze({
218919
219081
  form: "single",
218920
219082
  optional: false
218921
219083
  }],
219084
+ "error.listFaultTypes": [{
219085
+ name: "deviceId",
219086
+ form: "single",
219087
+ optional: false
219088
+ }],
218922
219089
  "eventEmitter.getStatus": [{
218923
219090
  name: "deviceId",
218924
219091
  form: "single",
@@ -221251,7 +221418,8 @@ var NC_SYSTEM_EVENT_FILTER_KEYS = [
221251
221418
  "consumableLowPercent",
221252
221419
  "commandActions",
221253
221420
  "commandOutcomes",
221254
- "commandActorKinds"
221421
+ "commandActorKinds",
221422
+ "faultCodes"
221255
221423
  ];
221256
221424
  new Map(Object.entries({
221257
221425
  "device-online": "device-events",
@@ -221622,6 +221790,8 @@ object({
221622
221790
  nodeId: string().optional(),
221623
221791
  /** The alert's own action link (where the operator acts on it), when it has one. */
221624
221792
  actionUrl: string().optional(),
221793
+ /** A device fault episode: every active fault (`metadata.faults`), principal first. */
221794
+ faults: array(DeviceFaultSchema).optional(),
221625
221795
  at: number$1()
221626
221796
  });
221627
221797
  var RULE_BODY_ONLY = ["body"];
@@ -221906,6 +222076,9 @@ var STATE_SUMMARY_VARS = [
221906
222076
  ([...RULE_TEXT], [...DEVICE_ATTENTION, ...ALERT_EPISODE]),
221907
222077
  ([...RULE_TEXT], [...ALERT_EPISODE]),
221908
222078
  ([...RULE_TEXT], [...DEVICE_ATTENTION, ...ALERT_EPISODE]),
222079
+ ([...RULE_TEXT], [...DEVICE_ATTENTION]),
222080
+ ([...RULE_TEXT], [...DEVICE_ATTENTION]),
222081
+ ([...RULE_TEXT], [...DEVICE_ATTENTION]),
221909
222082
  [...RULE_TEXT],
221910
222083
  [...RULE_TEXT],
221911
222084
  [...RULE_TEXT],
@@ -222670,6 +222843,19 @@ object({
222670
222843
  delay: number$1().nonnegative().optional(),
222671
222844
  commands: record(string(), unknown())
222672
222845
  });
222846
+ /** The `instance-select` field of a link, keyed like the body field it fills. */
222847
+ function linkFieldDescriptor(key, target, labels) {
222848
+ return {
222849
+ type: "instance-select",
222850
+ key,
222851
+ label: labels.label,
222852
+ ...labels.description !== void 0 ? { description: labels.description } : {},
222853
+ required: labels.required ?? true,
222854
+ ...labels.noneLabel !== void 0 ? { noneLabel: labels.noneLabel } : {},
222855
+ functionCap: target.cap,
222856
+ ...target.kind !== void 0 ? { kind: target.kind } : {}
222857
+ };
222858
+ }
222673
222859
  //#endregion
222674
222860
  //#region src/clips/clip-prefetch.ts
222675
222861
  /** The longest a device may stay quiet after refusals, whatever its interval. */
@@ -223169,6 +223355,11 @@ var reolinkCameraSchema = object({
223169
223355
  /** Empty for a camera adopted from an NVR / Home Hub: it borrows its integration's session. */
223170
223356
  password: string().default("").describe("Password").meta({ secret: true }),
223171
223357
  /**
223358
+ * The SMTP password last written to the camera on the Email tab (or by Auto-configure email
223359
+ * push). A keychain secret: the form shows set / not set, never the value.
223360
+ */
223361
+ emailPassword: string().default("").describe("Camera SMTP password").meta({ secret: true }),
223362
+ /**
223172
223363
  * Transport mode resolved at creation time by autodetect (Slice 15).
223173
223364
  * - `tcp` : standard TCP-based Baichuan (regular cameras, NVR/Hub)
223174
223365
  * - `udp` : BCUDP-based Baichuan (battery cams, UDP-only models like
@@ -223496,6 +223687,17 @@ var reolinkCameraSchema = object({
223496
223687
  supported: boolean().optional()
223497
223688
  }).optional(),
223498
223689
  /**
223690
+ * The power source of a battery camera (`getPowerSource`): `adapter`,
223691
+ * `battery`, or `unknown` when the read failed or the firmware is
223692
+ * silent. Drives the Advanced tab's "Power source" setting; `unknown`
223693
+ * hides it.
223694
+ */
223695
+ powerSourceSnapshot: object({ source: _enum([
223696
+ "adapter",
223697
+ "battery",
223698
+ "unknown"
223699
+ ]) }).optional(),
223700
+ /**
223499
223701
  * Snapshot of the camera's auto-reboot schedule from
223500
223702
  * `getAutoReboot` (cmd_id 101). Drives the "Auto reboot" section
223501
223703
  * defaults on the Advanced tab. `weekDay` is the lib's `DayOfWeek`
@@ -223567,6 +223769,16 @@ var reolinkCameraSchema = object({
223567
223769
  */
223568
223770
  webhookUrlGeneration: number$1().int().optional(),
223569
223771
  /**
223772
+ * "Auto-configure event push on add": right after the camera is added, arm its local event push
223773
+ * (HaCfg webhook for a standalone battery camera, else the camera mailbox). Default on.
223774
+ */
223775
+ autoConfigureEventPush: boolean().optional(),
223776
+ /**
223777
+ * What the one-time add-time run did (`configured:<mechanism>` | `skipped` | `failed`). Present
223778
+ * means the run happened: a restart never writes the camera again.
223779
+ */
223780
+ eventPushAutoConfigured: string().optional(),
223781
+ /**
223570
223782
  * On-camera motion detection master switch + sensitivity.
223571
223783
  * Pushed via `setMotionAlarm` (cmdId=47). The Reolink mobile
223572
223784
  * app + camera web UI use 1..50 (1 = least sensitive,
@@ -229777,6 +229989,17 @@ function deriveReolinkCameraFeatures(inputs) {
229777
229989
  return out;
229778
229990
  }
229779
229991
  //#endregion
229992
+ //#region src/email-smtp-password.ts
229993
+ /**
229994
+ * The camera SMTP password an operator wrote on the Email tab, when it is a real value to push
229995
+ * to the camera and keep: a non-empty string that is not a keychain marker. Blank means "keep
229996
+ * the stored one" and a marker is the form echoing back what it was shown; neither is a write.
229997
+ */
229998
+ function smtpPasswordToWrite(value) {
229999
+ if (typeof value !== "string" || value.length === 0) return null;
230000
+ return isSecretMarker(value) ? null : value;
230001
+ }
230002
+ //#endregion
229780
230003
  //#region src/hub-child-settings.ts
229781
230004
  /**
229782
230005
  * A camera adopted under an NVR / Home Hub dials through the integration's session: the address
@@ -231701,6 +231924,22 @@ var SLEEP_HYSTERESIS_MS = 5e3;
231701
231924
  * exactly its recovery role.
231702
231925
  */
231703
231926
  var HUB_SUMMARY_SLEEP_GRACE_MS = 18e4;
231927
+ /**
231928
+ * How recent the last video packet must be for the stream to count as
231929
+ * flowing. A camera that is delivering video is awake, whatever a second-hand
231930
+ * claim says: a Home Hub child on DC power was marked sleeping every 28 min
231931
+ * (and by the lagging hub summary) while its RTP was running, which froze the
231932
+ * snapshot tile on "sleeping".
231933
+ */
231934
+ var VIDEO_FLOW_FRESH_MS = 5e3;
231935
+ /**
231936
+ * A source that is not the camera's own reading of itself: the parent's
231937
+ * summaries, and a pushed `simple-event` (the Home Hub's session cut arrives
231938
+ * as one).
231939
+ */
231940
+ function isSecondHand(source) {
231941
+ return source === "hub-summary" || source === "hub-reconcile" || source === "simple-event";
231942
+ }
231704
231943
  /** A source whose verdict comes from the parent NVR's channel summary. */
231705
231944
  function isSummarySourced(source) {
231706
231945
  return source === "hub-summary" || source === "hub-reconcile";
@@ -231721,8 +231960,23 @@ function isSummarySourced(source) {
231721
231960
  * observation inside the grace says otherwise.
231722
231961
  */
231723
231962
  function decideSleepCommit(input) {
231724
- const { current, next, source, lastFirstHandCommitAt, nowMs } = input;
231963
+ const { current, next, source, lastFirstHandCommitAt, nowMs, videoFlowing, wired } = input;
231725
231964
  if (current === next) return { kind: "unchanged" };
231965
+ if (next === true && isSecondHand(source)) {
231966
+ const sinceMs = nowMs - lastFirstHandCommitAt;
231967
+ if (wired) return {
231968
+ kind: "refused",
231969
+ reason: "wired",
231970
+ windowMs: 0,
231971
+ sinceLastChangeMs: sinceMs
231972
+ };
231973
+ if (videoFlowing) return {
231974
+ kind: "refused",
231975
+ reason: "video-flowing",
231976
+ windowMs: VIDEO_FLOW_FRESH_MS,
231977
+ sinceLastChangeMs: sinceMs
231978
+ };
231979
+ }
231726
231980
  const summarySourced = isSummarySourced(source);
231727
231981
  const firstHandWake = source === "confirmed-wake" && next === false;
231728
231982
  const sinceLastChangeMs = nowMs - lastFirstHandCommitAt;
@@ -231747,6 +232001,58 @@ function decideSleepCommit(input) {
231747
232001
  };
231748
232002
  }
231749
232003
  //#endregion
232004
+ //#region src/session-limit.ts
232005
+ /**
232006
+ * How long the broker lets a Home Hub child's session run before it re-dials on
232007
+ * its own terms.
232008
+ *
232009
+ * Observed 2026-11-20 on two DC-powered children of one Home Hub: the hub cut
232010
+ * BOTH sessions at the same second, every 28 min 07 s (16:16:36, then 16:44:43),
232011
+ * which is a hub session limit, not the camera. Declared a minute under that so
232012
+ * the planned re-dial always wins the race against the hub's cut and the
232013
+ * recording rolls over at a time of our choosing.
232014
+ */
232015
+ var HOME_HUB_SESSION_LIMIT_MS = 27 * 6e4;
232016
+ /**
232017
+ * Stamp the descriptors with the session limit the broker acts on. Only a
232018
+ * battery child of a hub gets one: a standalone camera has no such cut, and
232019
+ * declaring one there would re-dial a healthy stream for nothing.
232020
+ */
232021
+ function withSessionLimit(descriptors, input) {
232022
+ if (!input.isHubChild || !input.isBattery) return [...descriptors];
232023
+ return descriptors.map((d) => ({
232024
+ ...d,
232025
+ maxSessionMs: HOME_HUB_SESSION_LIMIT_MS
232026
+ }));
232027
+ }
232028
+ //#endregion
232029
+ //#region src/video-flow.ts
232030
+ /**
232031
+ * Report every video packet a stream server produces. The three stream kinds
232032
+ * the server can sit on name the same event differently (`videoFrame` for the
232033
+ * native and composite streams, `videoAccessUnit` for the always-on one), so
232034
+ * the kind is narrowed by class, not asserted.
232035
+ *
232036
+ * Returns the unsubscribe. A stream kind this does not know is reported
232037
+ * through `onUnknown` and never watched — silence would read as "no video".
232038
+ */
232039
+ function watchVideoFlow(stream, onFlow, onUnknown) {
232040
+ if (stream instanceof BaichuanVideoStream || stream instanceof CompositeStream) {
232041
+ stream.on("videoFrame", onFlow);
232042
+ return () => {
232043
+ stream.off("videoFrame", onFlow);
232044
+ };
232045
+ }
232046
+ if (stream instanceof ContinuousVideoStream) {
232047
+ stream.on("videoAccessUnit", onFlow);
232048
+ return () => {
232049
+ stream.off("videoAccessUnit", onFlow);
232050
+ };
232051
+ }
232052
+ onUnknown();
232053
+ return () => {};
232054
+ }
232055
+ //#endregion
231750
232056
  //#region src/snapshot-wake-gate.ts
231751
232057
  /**
231752
232058
  * Decide whether a snapshot read may reach the camera's socket.
@@ -231770,6 +232076,74 @@ function decideSnapshotCameraAccess(input) {
231770
232076
  };
231771
232077
  }
231772
232078
  //#endregion
232079
+ //#region src/event-push-on-add.ts
232080
+ function reasonOf(err) {
232081
+ return err instanceof Error ? err.message : String(err);
232082
+ }
232083
+ async function decide(ports) {
232084
+ if (!ports.enabled()) return {
232085
+ status: "skipped",
232086
+ reason: "auto-configure event push on add is switched off"
232087
+ };
232088
+ if (!ports.isEligible()) return {
232089
+ status: "skipped",
232090
+ reason: "hub-attached camera: the hub owns its event push, no email or webhook is written"
232091
+ };
232092
+ const method = ports.method();
232093
+ const webhookPossible = ports.isBattery() && method !== "email";
232094
+ const failures = [];
232095
+ if (webhookPossible) try {
232096
+ await ports.configureWebhook();
232097
+ return {
232098
+ status: "configured",
232099
+ mechanism: "webhook"
232100
+ };
232101
+ } catch (err) {
232102
+ failures.push(`webhook: ${reasonOf(err)}`);
232103
+ if (method === "webhook") return {
232104
+ status: "failed",
232105
+ reason: failures.join("; ")
232106
+ };
232107
+ }
232108
+ else if (method === "webhook") return {
232109
+ status: "skipped",
232110
+ reason: "the webhook needs a standalone battery camera and this one is not"
232111
+ };
232112
+ try {
232113
+ await ports.configureEmail();
232114
+ return {
232115
+ status: "configured",
232116
+ mechanism: "email"
232117
+ };
232118
+ } catch (err) {
232119
+ failures.push(`email: ${reasonOf(err)}`);
232120
+ return {
232121
+ status: "failed",
232122
+ reason: failures.join("; ")
232123
+ };
232124
+ }
232125
+ }
232126
+ /**
232127
+ * Arm a camera's local event push ONCE, right after it is added. A failure is an outcome, never
232128
+ * a throw: it must not block the add. The outcome is logged and recorded, and a recorded camera
232129
+ * is never written again. Battery cameras prefer the webhook (it works while asleep) and fall back
232130
+ * to the camera mailbox; only one path is armed, so events are not delivered twice.
232131
+ */
232132
+ async function autoConfigureEventPushOnce(ports) {
232133
+ if (ports.recordedOutcome() !== void 0) return "already-ran";
232134
+ const outcome = await decide(ports);
232135
+ ports.log(outcome);
232136
+ try {
232137
+ await ports.record(outcome);
232138
+ } catch (err) {
232139
+ ports.log({
232140
+ status: "failed",
232141
+ reason: `could not record the run: ${reasonOf(err)}`
232142
+ });
232143
+ }
232144
+ return outcome;
232145
+ }
232146
+ //#endregion
231773
232147
  //#region src/webhook-generation.ts
231774
232148
  /**
231775
232149
  * Point a battery camera's webhook at the data-plane URL ONCE per URL generation.
@@ -232410,6 +232784,13 @@ var PirAccessory = class extends BaseDevice {
232410
232784
  * inverse `101 - userValue` (lower raw = more sensitive).
232411
232785
  * Mirrors `refreshSwitchFromExternal`'s reverse transform. */
232412
232786
  async pushConfigToFirmware(enable) {
232787
+ if (this.parent.wakeForWrite && !await this.parent.wakeForWrite()) {
232788
+ this.ctx.logger.warn("pir write not sent — the battery camera could not be woken", {
232789
+ tags: { deviceId: this.id },
232790
+ meta: { channel: this.channel }
232791
+ });
232792
+ throw new Error("The camera is asleep and could not be woken; try again in a moment.");
232793
+ }
232413
232794
  const api = await this.api;
232414
232795
  const sensitive = this.config.get("pirSensitive");
232415
232796
  const reduceAlarm = this.config.get("pirReduceAlarm");
@@ -234305,10 +234686,9 @@ var PowerSourceReadingSchema = _enum([
234305
234686
  "battery",
234306
234687
  "unknown"
234307
234688
  ]);
234308
- var ReadPowerSourceResultSchema = object({ source: PowerSourceReadingSchema });
234309
234689
  /** The device (or this code) declined before any real write was sent. */
234310
234690
  var PowerSourceRefusalReasonSchema = _enum(["dry-run-refused", "dry-run-failed"]);
234311
- var SwitchPowerSourceResultSchema = discriminatedUnion("outcome", [
234691
+ discriminatedUnion("outcome", [
234312
234692
  object({
234313
234693
  outcome: literal("refused"),
234314
234694
  mode: PowerSourceModeSchema,
@@ -234452,6 +234832,107 @@ async function switchPowerSourceTo(target, mode) {
234452
234832
  applied
234453
234833
  };
234454
234834
  }
234835
+ /** The settings key of the power source: an ordinary select, owned by the camera (never stored). */
234836
+ var POWER_SOURCE_SETTING_KEY = "powerSource";
234837
+ /**
234838
+ * The power source as a setting, in its own section of the Advanced tab.
234839
+ * Only a battery camera whose read ANSWERED with a mode has one: a camera that
234840
+ * was never asked, or that did not answer, shows nothing rather than a guess.
234841
+ */
234842
+ function buildPowerSourceSettingsSection(input) {
234843
+ const { isBattery, source } = input;
234844
+ if (!isBattery || source === void 0 || source === "unknown") return [];
234845
+ return [{
234846
+ id: "power-source",
234847
+ tab: "advanced",
234848
+ title: "Power source",
234849
+ titleKey: "provider-reolink:schema.s_power-source.title",
234850
+ description: "Only switch to wired power when the adapter meets the camera's spec.",
234851
+ descriptionKey: "provider-reolink:schema.s_power-source.description",
234852
+ columns: 1,
234853
+ fields: [{
234854
+ type: "select",
234855
+ key: POWER_SOURCE_SETTING_KEY,
234856
+ label: "Power source",
234857
+ labelKey: "provider-reolink:schema.s_power-source.powerSource.label",
234858
+ default: source,
234859
+ required: true,
234860
+ options: [{
234861
+ value: "adapter",
234862
+ label: "Wired power",
234863
+ labelKey: "provider-reolink:schema.s_power-source.powerSource.o_adapter.label"
234864
+ }, {
234865
+ value: "battery",
234866
+ label: "Battery power",
234867
+ labelKey: "provider-reolink:schema.s_power-source.powerSource.o_battery.label"
234868
+ }]
234869
+ }]
234870
+ }];
234871
+ }
234872
+ /**
234873
+ * Apply the setting: switch the camera and REFUSE to call a switch that did not
234874
+ * land a success — the settings form keeps the operator's edit, marked unsaved.
234875
+ */
234876
+ async function applyPowerSourceSetting(target, value) {
234877
+ const mode = PowerSourceModeSchema.safeParse(value);
234878
+ if (!mode.success) throw new Error(`Not a power source: ${String(value)}`);
234879
+ const outcome = await switchPowerSourceTo(target, mode.data);
234880
+ if (outcome.outcome === "refused") throw new Error(`The camera refused the power source switch (${outcome.reason})`);
234881
+ if (outcome.outcome === "failed") throw new Error(`The power source switch failed: ${outcome.error}`);
234882
+ if (!outcome.applied) throw new Error(`The camera did not take the power source switch (it reports ${outcome.after})`);
234883
+ }
234884
+ //#endregion
234885
+ //#region src/keep-awake-loop.ts
234886
+ /**
234887
+ * Stream-scoped keep-awake for a battery camera. While at least one stream
234888
+ * consumer is attached, a periodic wake keeps the firmware from entering
234889
+ * standby (which would stop the video). One timer per camera; started when the
234890
+ * first consumer attaches, stopped when the last one leaves.
234891
+ *
234892
+ * Pure: the timer and the wake call are injected so the loop is testable.
234893
+ */
234894
+ var KEEP_AWAKE_INTERVAL_MS = 2e4;
234895
+ function createKeepAwakeLoop(deps) {
234896
+ let handle = null;
234897
+ let failing = false;
234898
+ const tick = () => {
234899
+ deps.wake().then(() => {
234900
+ failing = false;
234901
+ }).catch((err) => {
234902
+ const first = !failing;
234903
+ failing = true;
234904
+ try {
234905
+ deps.onFailure(err, first);
234906
+ } catch {}
234907
+ });
234908
+ };
234909
+ const arm = () => {
234910
+ handle = deps.setTimer(() => {
234911
+ if (handle === null) return;
234912
+ tick();
234913
+ arm();
234914
+ }, deps.intervalMs);
234915
+ };
234916
+ const halt = (activeStreams) => {
234917
+ if (handle === null) return;
234918
+ deps.clearTimer(handle);
234919
+ handle = null;
234920
+ failing = false;
234921
+ deps.onStop(activeStreams);
234922
+ };
234923
+ return {
234924
+ sync: (activeStreams) => {
234925
+ if (!deps.isBattery()) return;
234926
+ if (activeStreams > 0) {
234927
+ if (handle !== null) return;
234928
+ arm();
234929
+ deps.onStart(activeStreams);
234930
+ } else halt(activeStreams);
234931
+ },
234932
+ stop: () => halt(0),
234933
+ running: () => handle !== null
234934
+ };
234935
+ }
234455
234936
  //#endregion
234456
234937
  //#region src/ptz-zoom.ts
234457
234938
  /**
@@ -235425,6 +235906,7 @@ function slicesForPatch(patch) {
235425
235906
  if (has("pirReduceFalseAlarm")) out.add("pir");
235426
235907
  if (has("autoRebootEnabled", "autoRebootWeekDay", "autoRebootHour", "autoRebootMinute")) out.add("autoReboot");
235427
235908
  if (has("timeZoneId")) out.add("systemGeneral");
235909
+ if (has("powerSource")) out.add("powerSource");
235428
235910
  return out;
235429
235911
  }
235430
235912
  /**
@@ -235441,8 +235923,6 @@ var RefreshSettingsResultSchema = object({
235441
235923
  capsWarmed: number$1(),
235442
235924
  capsTotal: number$1()
235443
235925
  });
235444
- /** The two switch actions, one implementation each way. */
235445
- var POWER_SWITCH_ACTIONS = [["switch-to-wired-power", "adapter"], ["switch-to-battery-power", "battery"]];
235446
235926
  /** The uid out of a device's metadata bag, or nothing. Never a cast. */
235447
235927
  function metaUid(metadata) {
235448
235928
  if (metadata === null) return void 0;
@@ -235565,8 +236045,44 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
235565
236045
  nextEventHealthCheckAt = 0;
235566
236046
  /** Active video streams keyed by camStreamId. */
235567
236047
  active = /* @__PURE__ */ new Map();
236048
+ /**
236049
+ * Stream-scoped keep-awake (battery only): while a consumer holds a stream,
236050
+ * a periodic wake stops the firmware from entering standby. Reconciled with
236051
+ * `this.active` through `syncKeepAwake()` after every mutation of the map.
236052
+ */
236053
+ keepAwake = createKeepAwakeLoop({
236054
+ intervalMs: KEEP_AWAKE_INTERVAL_MS,
236055
+ isBattery: () => this.isBattery,
236056
+ wake: async () => {
236057
+ await (await this.ensureApi()).wakeUp(this.getChannel(), {
236058
+ attempts: 1,
236059
+ waitAfterWakeMs: 0
236060
+ });
236061
+ },
236062
+ setTimer: (fn, ms) => setTimeout(fn, ms),
236063
+ clearTimer: (h) => clearTimeout(h),
236064
+ onStart: (activeStreams) => this.ctx.logger.info("keep-awake: started", {
236065
+ tags: { deviceId: this.id },
236066
+ meta: { activeStreams }
236067
+ }),
236068
+ onStop: (activeStreams) => this.ctx.logger.info("keep-awake: stopped", {
236069
+ tags: { deviceId: this.id },
236070
+ meta: { activeStreams }
236071
+ }),
236072
+ onFailure: (err, first) => {
236073
+ (first ? this.ctx.logger.info.bind(this.ctx.logger) : this.ctx.logger.debug.bind(this.ctx.logger))("keep-awake: wake failed", {
236074
+ tags: { deviceId: this.id },
236075
+ meta: { error: err instanceof Error ? err.message : String(err) }
236076
+ });
236077
+ }
236078
+ });
236079
+ syncKeepAwake() {
236080
+ this.keepAwake.sync(this.active.size);
236081
+ }
235568
236082
  /** Login lock — concurrent demand events must not race the login flow. */
235569
236083
  loginPromise = null;
236084
+ /** Wall-clock ms of the last video packet the stream server produced; 0 = none yet. */
236085
+ lastVideoFlowAt = 0;
235570
236086
  /** True once we've discovered (via getBatteryInfo) that this is a battery cam. */
235571
236087
  isBattery = false;
235572
236088
  /**
@@ -236250,6 +236766,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
236250
236766
  } catch (err) {
236251
236767
  this.ctx.logger.debug("reolink getPirInfo probe failed", { meta: { error: err instanceof Error ? err.message : String(err) } });
236252
236768
  }
236769
+ if (want("powerSource") && this.isBattery) cacheUpdate.powerSourceSnapshot = { source: await readPowerSource(await this.powerSourceTarget()) };
236253
236770
  if (want("autoReboot")) try {
236254
236771
  const reboot = await api.getAutoReboot();
236255
236772
  cacheUpdate.autoRebootSnapshot = {
@@ -236602,6 +237119,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
236602
237119
  runTest: false
236603
237120
  }, this.getChannel());
236604
237121
  this.ctx.logger.info("email-push: camera auto-configure applied", { tags: { deviceId: this.id } });
237122
+ if (params.authPassword !== void 0) await this.config.setAll({ emailPassword: params.authPassword });
236605
237123
  await this.refreshCameraEmailConfig().catch(() => {});
236606
237124
  }
236607
237125
  /**
@@ -236648,6 +237166,39 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
236648
237166
  });
236649
237167
  }
236650
237168
  /**
237169
+ * Arm this camera's local event push ONCE, right after it is added (the provider's
237170
+ * `onAfterCreate`). Reuses `autoConfigureBaichuanWebhook` / `autoConfigureEmailPush` as they
237171
+ * are; the outcome is logged and recorded, and never throws: it must not block the add.
237172
+ */
237173
+ async autoConfigureEventPushOnAdd() {
237174
+ return await autoConfigureEventPushOnce({
237175
+ enabled: () => this.config.get("autoConfigureEventPush") !== false,
237176
+ recordedOutcome: () => this.config.get("eventPushAutoConfigured"),
237177
+ isEligible: () => this.isEmailPushEligible,
237178
+ isBattery: () => this.isBattery,
237179
+ method: () => this.config.get("batterySleepPushMethod") ?? "auto",
237180
+ configureWebhook: async () => await this.autoConfigureBaichuanWebhook(),
237181
+ configureEmail: async () => await this.autoConfigureEmailPush(),
237182
+ record: async (outcome) => {
237183
+ await this.config.setAll({ eventPushAutoConfigured: outcome.status === "configured" ? `configured:${outcome.mechanism}` : outcome.status });
237184
+ },
237185
+ log: (outcome) => {
237186
+ if (outcome.status === "configured") this.ctx.logger.info("event-push: auto-configured on add", {
237187
+ tags: { deviceId: this.id },
237188
+ meta: { mechanism: outcome.mechanism }
237189
+ });
237190
+ else if (outcome.status === "skipped") this.ctx.logger.info("event-push: auto-configure on add skipped", {
237191
+ tags: { deviceId: this.id },
237192
+ meta: { reason: outcome.reason }
237193
+ });
237194
+ else this.ctx.logger.warn("event-push: auto-configure on add failed", {
237195
+ tags: { deviceId: this.id },
237196
+ meta: { reason: outcome.reason }
237197
+ });
237198
+ }
237199
+ });
237200
+ }
237201
+ /**
236651
237202
  * Move this battery camera's HaCfg webhook to the addon's data-plane URL, once, on the first
236652
237203
  * Baichuan contact after the upgrade (the camera is awake: this costs no wake). Only a camera
236653
237204
  * that is armed is touched; a failure is logged and retried at the next contact.
@@ -236828,16 +237379,6 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
236828
237379
  capsTotal
236829
237380
  };
236830
237381
  });
236831
- if (this.isBattery) {
236832
- this.registerDeviceAction("read-power-source", deviceCustomAction(unknown(), ReadPowerSourceResultSchema, { kind: "mutation" }), async () => {
236833
- await this.wakeIfSleeping();
236834
- return { source: await readPowerSource(await this.powerSourceTarget()) };
236835
- });
236836
- for (const [action, mode] of POWER_SWITCH_ACTIONS) this.registerDeviceAction(action, deviceCustomAction(unknown(), SwitchPowerSourceResultSchema, { kind: "mutation" }), async () => {
236837
- await this.wakeIfSleeping();
236838
- return switchPowerSourceTo(await this.powerSourceTarget(), mode);
236839
- });
236840
- }
236841
237382
  this.registerDeviceAction("refresh-sessions", deviceCustomAction(unknown(), _void(), { kind: "mutation" }), async () => {
236842
237383
  await this.refreshSessionsSnapshot();
236843
237384
  });
@@ -237143,17 +237684,20 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
237143
237684
  next,
237144
237685
  source,
237145
237686
  lastFirstHandCommitAt: this.sleepStateChangedAt,
237146
- nowMs: Date.now()
237687
+ nowMs: Date.now(),
237688
+ videoFlowing: Date.now() - this.lastVideoFlowAt < VIDEO_FLOW_FRESH_MS,
237689
+ wired: this.config.get("deviceCache")?.powerSourceSnapshot?.source === "adapter"
237147
237690
  });
237148
237691
  if (decision.kind === "unchanged") return false;
237149
237692
  if (decision.kind === "refused") {
237150
- this.ctx.logger.debug(decision.reason === "hysteresis" ? "ignoring sleep inference flap within hysteresis window" : "hub-summary sleep flip refused — fresher first-hand state inside grace", {
237693
+ (decision.reason === "video-flowing" || decision.reason === "wired" ? this.ctx.logger.info.bind(this.ctx.logger) : this.ctx.logger.debug.bind(this.ctx.logger))(decision.reason === "hysteresis" ? "ignoring sleep inference flap within hysteresis window" : decision.reason === "video-flowing" ? "sleep claim refused — video is flowing" : decision.reason === "wired" ? "sleep claim refused — camera is on a wired power source" : "hub-summary sleep flip refused — fresher first-hand state inside grace", {
237151
237694
  tags: { deviceId: this.id },
237152
237695
  meta: {
237153
237696
  next,
237154
237697
  source,
237155
237698
  windowMs: decision.windowMs,
237156
- sinceLastChangeMs: decision.sinceLastChangeMs
237699
+ sinceLastChangeMs: decision.sinceLastChangeMs,
237700
+ reason: decision.reason
237157
237701
  }
237158
237702
  });
237159
237703
  return false;
@@ -237387,56 +237931,6 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
237387
237931
  };
237388
237932
  }
237389
237933
  /**
237390
- * Battery-cam power-source section (General tab): read the source, switch to
237391
- * wired or back to battery. Returns `[]` for a wired-only camera. The buttons
237392
- * dispatch the `read-power-source` / `switch-to-*-power` device actions.
237393
- */
237394
- buildPowerSourceSection() {
237395
- if (!this.isBattery) return [];
237396
- const switchMessage = "Switch {outcome} · before: {before} · after: {after} · applied: {applied}";
237397
- return [{
237398
- id: "power-source",
237399
- tab: "general",
237400
- title: "Power source",
237401
- titleKey: "provider-reolink:schema.s_power-source.title",
237402
- description: "Only switch to wired power when the adapter meets the camera's spec.",
237403
- descriptionKey: "provider-reolink:schema.s_power-source.description",
237404
- columns: 1,
237405
- fields: [
237406
- {
237407
- type: "device-action-button",
237408
- key: "_readPowerSource",
237409
- label: "Power source",
237410
- labelKey: "provider-reolink:schema.s_power-source._readPowerSource.label",
237411
- buttonLabel: "Read power source",
237412
- action: "read-power-source",
237413
- variant: "default",
237414
- successMessage: "Power source: {source}"
237415
- },
237416
- {
237417
- type: "device-action-button",
237418
- key: "_switchToWiredPower",
237419
- label: "Wired power",
237420
- labelKey: "provider-reolink:schema.s_power-source._switchToWiredPower.label",
237421
- buttonLabel: "Switch to wired power",
237422
- action: "switch-to-wired-power",
237423
- variant: "default",
237424
- successMessage: switchMessage
237425
- },
237426
- {
237427
- type: "device-action-button",
237428
- key: "_switchToBatteryPower",
237429
- label: "Battery power",
237430
- labelKey: "provider-reolink:schema.s_power-source._switchToBatteryPower.label",
237431
- buttonLabel: "Switch to battery power",
237432
- action: "switch-to-battery-power",
237433
- variant: "default",
237434
- successMessage: switchMessage
237435
- }
237436
- ]
237437
- }];
237438
- }
237439
- /**
237440
237934
  * Battery-cam Email Push auto-configure section. Returns `[]` for any
237441
237935
  * camera that wouldn't benefit (wired cams keep a live socket for
237442
237936
  * native push; hub children have no independent email path). The
@@ -237627,7 +238121,8 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
237627
238121
  if (typeof fields.emailSmtpServer === "string") patch.smtpServer = fields.emailSmtpServer;
237628
238122
  if (typeof fields.emailSmtpPort === "number") patch.smtpPort = fields.emailSmtpPort;
237629
238123
  if (typeof fields.emailUserName === "string") patch.userName = fields.emailUserName;
237630
- if (typeof fields.emailPassword === "string" && fields.emailPassword.length > 0) patch.password = fields.emailPassword;
238124
+ const smtpPassword = smtpPasswordToWrite(fields.emailPassword);
238125
+ if (smtpPassword !== null) patch.password = smtpPassword;
237631
238126
  if (typeof fields.emailSsl === "boolean") patch.ssl = fields.emailSsl ? 1 : 0;
237632
238127
  if (typeof fields.emailRecipient1 === "string") patch.address1 = fields.emailRecipient1;
237633
238128
  if (typeof fields.emailRecipient2 === "string") patch.address2 = fields.emailRecipient2;
@@ -240190,7 +240685,10 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
240190
240685
  * See `native-sdp-overlay.ts`.
240191
240686
  */
240192
240687
  withLiveNativeSdp(descriptors) {
240193
- return overlayLiveNativeRfc4571Sdp(descriptors, (camStreamId) => {
240688
+ return overlayLiveNativeRfc4571Sdp(withSessionLimit(descriptors, {
240689
+ isHubChild: this.isHubChild(),
240690
+ isBattery: this.isBattery
240691
+ }), (camStreamId) => {
240194
240692
  const server = this.active.get(camStreamId)?.server;
240195
240693
  if (!server?.server?.listening) return null;
240196
240694
  return {
@@ -240492,6 +240990,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
240492
240990
  ...entry.fps !== void 0 ? { fps: entry.fps } : {},
240493
240991
  ...entry.codec !== void 0 ? { codec: entry.codec } : {},
240494
240992
  ...entry.metadata ? { metadata: entry.metadata } : {},
240993
+ ...entry.maxSessionMs !== void 0 ? { maxSessionMs: entry.maxSessionMs } : {},
240495
240994
  deviceFeatures: entry.deviceFeatures ?? [...this.features],
240496
240995
  autoEligible: entry.autoEligible ?? true
240497
240996
  });
@@ -240571,6 +241070,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
240571
241070
  this.stopBatteryUpdatePolling();
240572
241071
  this.stopAlignAuxPolling();
240573
241072
  this.stopWatchdogs();
241073
+ this.keepAwake.stop();
240574
241074
  this.detachFromHubSession();
240575
241075
  if (this.reconnectTimer) {
240576
241076
  clearTimeout(this.reconnectTimer);
@@ -240616,6 +241116,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
240616
241116
  await existing.server.close("recreate");
240617
241117
  } catch {}
240618
241118
  this.active.delete(camStreamId);
241119
+ this.syncKeepAwake();
240619
241120
  }
240620
241121
  let api;
240621
241122
  try {
@@ -240663,9 +241164,18 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
240663
241164
  server
240664
241165
  };
240665
241166
  this.active.set(camStreamId, entry);
241167
+ this.syncKeepAwake();
241168
+ const stopVideoWatch = watchVideoFlow(server.videoStream, () => {
241169
+ this.lastVideoFlowAt = Date.now();
241170
+ }, () => this.ctx.logger.warn("rfc4571: unknown video stream kind — video flow not observed", { tags: {
241171
+ deviceId: this.id,
241172
+ camStreamId
241173
+ } }));
240666
241174
  server.server.once("close", () => {
241175
+ stopVideoWatch();
240667
241176
  if (this.active.get(camStreamId)?.server === server) {
240668
241177
  this.active.delete(camStreamId);
241178
+ this.syncKeepAwake();
240669
241179
  this.ctx.logger.debug("rfc4571: server closed — evicting cache entry", { tags: {
240670
241180
  deviceId: this.id,
240671
241181
  camStreamId
@@ -240720,6 +241230,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
240720
241230
  async closeActiveStreams(reason) {
240721
241231
  const entries = [...this.active.values()];
240722
241232
  this.active.clear();
241233
+ this.keepAwake.stop();
240723
241234
  if (entries.length === 0) return;
240724
241235
  this.ctx.logger.debug("Closing active RFC 4571 servers", {
240725
241236
  tags: { deviceId: this.id },
@@ -241403,6 +241914,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
241403
241914
  this.stopWatchdogs();
241404
241915
  const entries = [...this.active.values()];
241405
241916
  this.active.clear();
241917
+ this.keepAwake.stop();
241406
241918
  for (const entry of entries) try {
241407
241919
  await entry.server.close("disconnect-all");
241408
241920
  } catch {}
@@ -242348,7 +242860,10 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
242348
242860
  }),
242349
242861
  ...this.buildSessionsTabSections(),
242350
242862
  ...this.buildEmailPushSection(),
242351
- ...this.buildPowerSourceSection(),
242863
+ ...buildPowerSourceSettingsSection({
242864
+ isBattery: this.isBattery,
242865
+ source: cache?.powerSourceSnapshot?.source
242866
+ }),
242352
242867
  ...this.buildEmailTabSections(),
242353
242868
  ...buildClipRefreshDeviceSection({
242354
242869
  isHubChild: this.isHubChild(),
@@ -242377,7 +242892,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
242377
242892
  emailSmtpServer: emailSnap?.smtpServer ?? "",
242378
242893
  emailSmtpPort: emailSnap?.smtpPort ?? 587,
242379
242894
  emailUserName: emailSnap?.userName ?? "",
242380
- emailPassword: "",
242895
+ emailPassword: this.config.get("emailPassword"),
242381
242896
  emailSsl: emailSnap?.ssl ?? false,
242382
242897
  emailRecipient1: emailSnap?.recipients?.[0] ?? "",
242383
242898
  emailRecipient2: emailSnap?.recipients?.[1] ?? "",
@@ -242444,6 +242959,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
242444
242959
  audioNoiseLevel: this.config.get("audioNoiseLevel") ?? (cache?.audioNoiseSnapshot?.enabled ? cache.audioNoiseSnapshot?.level ?? 1 : 0),
242445
242960
  autoFocusEnabled: this.config.get("autoFocusEnabled") ?? cache?.autoFocusSnapshot?.enabled ?? true,
242446
242961
  pirReduceFalseAlarm: this.config.get("pirReduceFalseAlarm") ?? cache?.pirSnapshot?.reduceFalseAlarm ?? false,
242962
+ ...cache?.powerSourceSnapshot !== void 0 ? { [POWER_SOURCE_SETTING_KEY]: cache.powerSourceSnapshot.source } : {},
242447
242963
  gop: this.config.get("gop") ?? cache?.encSnapshot?.mainStream?.gop ?? 4,
242448
242964
  autoRebootEnabled: this.config.get("autoRebootEnabled") ?? cache?.autoRebootSnapshot?.enabled ?? false,
242449
242965
  autoRebootWeekDay: this.config.get("autoRebootWeekDay") ?? cache?.autoRebootSnapshot?.weekDay ?? "everyday",
@@ -242473,8 +242989,8 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
242473
242989
  }
242474
242990
  async applySettingsPatch(patch) {
242475
242991
  if (this.isHubChild()) this.refuseHubChildPatch(patch);
242476
- const { emailSmtpServer, emailSmtpPort, emailUserName, emailPassword, emailSsl, emailRecipient1, emailRecipient2, emailRecipient3, emailSendNickname, emailScheduleEnabled, osdChannelEnabled, osdChannelName, osdChannelPosition, osdTimeEnabled, osdTimePosition, osdWatermark, hubName: _hubName, ...rest } = patch;
242477
- if ((osdChannelEnabled !== void 0 || osdChannelName !== void 0 || osdChannelPosition !== void 0 || osdTimeEnabled !== void 0 || osdTimePosition !== void 0 || osdWatermark !== void 0 || emailSmtpServer !== void 0 || emailRecipient1 !== void 0) && !await this.wakeIfSleeping()) this.ctx.logger.warn("settings write: battery cam did not wake — writing anyway", { tags: { deviceId: this.id } });
242992
+ const { emailSmtpServer, emailSmtpPort, emailUserName, emailPassword, emailSsl, emailRecipient1, emailRecipient2, emailRecipient3, emailSendNickname, emailScheduleEnabled, osdChannelEnabled, osdChannelName, osdChannelPosition, osdTimeEnabled, osdTimePosition, osdWatermark, hubName: _hubName, [POWER_SOURCE_SETTING_KEY]: powerSource, ...rest } = patch;
242993
+ if ((osdChannelEnabled !== void 0 || osdChannelName !== void 0 || osdChannelPosition !== void 0 || osdTimeEnabled !== void 0 || osdTimePosition !== void 0 || osdWatermark !== void 0 || emailSmtpServer !== void 0 || emailRecipient1 !== void 0 || powerSource !== void 0) && !await this.wakeIfSleeping()) this.ctx.logger.warn("settings write: battery cam did not wake — writing anyway", { tags: { deviceId: this.id } });
242478
242994
  const emailFields = {
242479
242995
  emailSmtpServer,
242480
242996
  emailSmtpPort,
@@ -242487,12 +243003,18 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
242487
243003
  emailSendNickname,
242488
243004
  emailScheduleEnabled
242489
243005
  };
242490
- if (Object.values(emailFields).some((v) => v !== void 0)) await this.applyEmailConfigPatch(emailFields).catch((err) => {
242491
- this.ctx.logger.warn("email config write failed", {
242492
- tags: { deviceId: this.id },
242493
- meta: { error: err instanceof Error ? err.message : String(err) }
243006
+ if (Object.values(emailFields).some((v) => v !== void 0)) {
243007
+ let written = true;
243008
+ await this.applyEmailConfigPatch(emailFields).catch((err) => {
243009
+ written = false;
243010
+ this.ctx.logger.warn("email config write failed", {
243011
+ tags: { deviceId: this.id },
243012
+ meta: { error: err instanceof Error ? err.message : String(err) }
243013
+ });
242494
243014
  });
242495
- });
243015
+ const stored = smtpPasswordToWrite(emailPassword);
243016
+ if (written && stored !== null) await this.config.setAll({ emailPassword: stored });
243017
+ }
242496
243018
  const osdPatch = buildOsdPatch({
242497
243019
  osdChannelEnabled,
242498
243020
  osdChannelName,
@@ -242509,6 +243031,10 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
242509
243031
  osdTimePosition,
242510
243032
  osdWatermark
242511
243033
  ].some((v) => v !== void 0);
243034
+ if (powerSource !== void 0) {
243035
+ await applyPowerSourceSetting(await this.powerSourceTarget(), powerSource);
243036
+ await this.refreshParentSettingsSnapshot(new Set(["powerSource"]), "post-write");
243037
+ }
242512
243038
  if (Object.keys(rest).length === 0 && !hasOsdPatch) return;
242513
243039
  if (Object.keys(rest).length > 0) await this.config.setAll(rest);
242514
243040
  const typedPatch = patch;
@@ -242943,6 +243469,11 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
242943
243469
  isSleeping() {
242944
243470
  return this.sleeping;
242945
243471
  }
243472
+ /** Implements `ReolinkAccessoryHost.wakeForWrite`: an accessory's operator
243473
+ * write (PIR, ...) wakes a sleeping battery camera first. */
243474
+ wakeForWrite() {
243475
+ return this.wakeIfSleeping();
243476
+ }
242946
243477
  async ensureApi() {
242947
243478
  if (this.isHubChild()) {
242948
243479
  const session = this.hubSession();
@@ -243818,6 +244349,21 @@ function buildCreationFormSchema() {
243818
244349
  }
243819
244350
  }
243820
244351
  ]
244352
+ },
244353
+ {
244354
+ id: "events",
244355
+ title: "Events",
244356
+ titleKey: "provider-reolink:creation.s_events.title",
244357
+ columns: 1,
244358
+ fields: [{
244359
+ type: "boolean",
244360
+ key: "autoConfigureEventPush",
244361
+ label: "Auto-configure event push on add",
244362
+ labelKey: "provider-reolink:creation.s_events.autoConfigureEventPush.label",
244363
+ description: "Once, right after the camera is added, set up its local push (webhook or camera mailbox) so motion and AI events reach CamStack.",
244364
+ descriptionKey: "provider-reolink:creation.s_events.autoConfigureEventPush.description",
244365
+ default: true
244366
+ }]
243821
244367
  }
243822
244368
  ] };
243823
244369
  }
@@ -243967,6 +244513,8 @@ var EmailPushBridge = class {
243967
244513
  /** The last failure that was reported, so a mailbox provider that stays away is said once. */
243968
244514
  lastFailure = null;
243969
244515
  chain = Promise.resolve();
244516
+ /** The integrations whose empty link this process filled (only those are released). */
244517
+ filled = /* @__PURE__ */ new Set();
243970
244518
  constructor(deps) {
243971
244519
  this.deps = deps;
243972
244520
  }
@@ -244037,43 +244585,104 @@ var EmailPushBridge = class {
244037
244585
  const recipients = this.recipients();
244038
244586
  if (recipients.length === 0) {
244039
244587
  if (this.brokerId !== null && this.subscriptionId !== null) await this.deps.port.unsubscribe(this.brokerId, this.subscriptionId);
244040
- if (this.brokerId !== null) await this.syncLinks(this.brokerId, /* @__PURE__ */ new Set());
244588
+ if (this.brokerId !== null) await this.syncLinks(this.brokerId, await this.tryDefaultId(), false);
244041
244589
  this.subscriptionId = null;
244042
244590
  this.declared = null;
244043
244591
  return;
244044
244592
  }
244045
- const owners = this.linkOwners();
244046
- const key = `${recipients.join(",")}|${[...owners].sort().join(",")}`;
244593
+ const { defaultId, complete } = await this.resolveDefault();
244594
+ const picked = await this.pickedMailbox(defaultId);
244595
+ const key = `${recipients.join(",")}|${defaultId ?? ""}|${picked ?? this.brokerId ?? ""}`;
244047
244596
  if (!force && this.declared === key && this.subscriptionId !== null) return;
244048
- const brokerId = await this.ensureMailbox();
244597
+ const brokerId = picked ?? await this.ensureMailbox();
244598
+ if (this.brokerId !== null && this.brokerId !== brokerId && this.subscriptionId !== null) {
244599
+ await this.deps.port.unsubscribe(this.brokerId, this.subscriptionId);
244600
+ this.subscriptionId = null;
244601
+ }
244049
244602
  await this.seedBaseline(brokerId);
244050
244603
  const { subscriptionId } = await this.deps.port.subscribe(brokerId, recipients);
244051
244604
  this.brokerId = brokerId;
244052
244605
  this.subscriptionId = subscriptionId;
244053
- this.declared = await this.syncLinks(brokerId, owners) ? key : null;
244606
+ const linked = await this.syncLinks(brokerId, defaultId, true);
244607
+ this.declared = linked && complete ? `${recipients.join(",")}|${defaultId ?? ""}|${brokerId}` : null;
244054
244608
  await this.reconcile();
244055
244609
  }
244056
- /** The integrations whose standalone cameras mail the mailbox: they link to it. */
244057
- linkOwners() {
244058
- const owners = /* @__PURE__ */ new Set();
244059
- for (const cam of this.deps.listCameras()) if (cam.isEmailPushEligible && cam.integrationId !== null) owners.add(cam.integrationId);
244060
- return owners;
244610
+ /**
244611
+ * The default integration holds the mailbox link for every email-push camera (a hub child's
244612
+ * integration carries none). `complete` is false when it could not be resolved: the caller
244613
+ * retries at the next sync.
244614
+ */
244615
+ async resolveDefault() {
244616
+ const cam = this.deps.listCameras().find((c) => c.isEmailPushEligible);
244617
+ const tags = cam === void 0 ? {} : { tags: { deviceId: cam.id } };
244618
+ let defaultId = null;
244619
+ try {
244620
+ defaultId = await this.deps.defaultIntegrationId();
244621
+ } catch (err) {
244622
+ this.deps.logger.warn("email-push: the default integration could not be read", {
244623
+ ...tags,
244624
+ meta: { error: errMsg(err) }
244625
+ });
244626
+ return {
244627
+ defaultId: null,
244628
+ complete: false
244629
+ };
244630
+ }
244631
+ if (defaultId === null) {
244632
+ this.deps.logger.warn("email-push: a camera uses the mailbox but the default integration is not resolved yet; retrying at the next sync", tags);
244633
+ return {
244634
+ defaultId: null,
244635
+ complete: false
244636
+ };
244637
+ }
244638
+ return {
244639
+ defaultId,
244640
+ complete: true
244641
+ };
244642
+ }
244643
+ async tryDefaultId() {
244644
+ try {
244645
+ return await this.deps.defaultIntegrationId();
244646
+ } catch {
244647
+ return null;
244648
+ }
244061
244649
  }
244062
244650
  /**
244063
- * Make the `mailboxId` links say who uses the mailbox: `owners` link to it, no other
244064
- * integration does. Idempotent, so an install whose mailbox already exists is filled from it
244065
- * (the mailbox is re-adopted by `ensureMailbox`) with nothing stored beforehand. False when the
244066
- * links could not be written: the caller retries at the next sync.
244651
+ * The mailbox the operator picked on the default integration, or null while none is picked.
244652
+ * A pick that no mailbox answers to throws: the bridge never swaps it for another one.
244067
244653
  */
244068
- async syncLinks(brokerId, owners) {
244654
+ async pickedMailbox(defaultId) {
244655
+ if (defaultId === null) return null;
244656
+ const row = (await this.deps.links.list()).find((r) => r.id === defaultId);
244657
+ if (row === void 0 || row.mailboxId === "") return null;
244658
+ if (!(await this.deps.port.list()).some((m) => m.id === row.mailboxId)) throw new Error(`the camera mailbox picked on the default integration (${row.mailboxId}) does not exist`);
244659
+ return row.mailboxId;
244660
+ }
244661
+ /** The mailbox a camera is pointed at: the operator's pick, else the one this addon adopts or creates. */
244662
+ async resolveMailbox() {
244663
+ return await this.pickedMailbox(await this.tryDefaultId()) ?? await this.ensureMailbox();
244664
+ }
244665
+ /**
244666
+ * Make the `mailboxId` link of the DEFAULT integration say it uses the mailbox. It is filled only
244667
+ * while empty (a pick of the operator is never overwritten) and released only if this process
244668
+ * filled it. A hub integration carries no link: a stale one is cleared. With no default
244669
+ * resolved nothing is touched. False when the links could not be written.
244670
+ */
244671
+ async syncLinks(brokerId, defaultId, inUse) {
244672
+ if (defaultId === null) return true;
244069
244673
  try {
244070
244674
  const rows = await this.deps.links.list();
244071
- for (const row of rows) {
244072
- const wanted = owners.has(row.id) ? brokerId : "";
244073
- if (row.mailboxId !== wanted) await this.deps.links.set(row.id, wanted);
244074
- }
244075
- for (const owner of owners) if (!rows.some((row) => row.id === owner)) this.deps.logger.warn("email-push: an integration with email-push cameras has no record to link the mailbox from", { meta: {
244076
- integrationId: owner,
244675
+ for (const row of rows) if (row.id !== defaultId) {
244676
+ if (row.mailboxId !== "") await this.deps.links.set(row.id, "");
244677
+ } else if (inUse && row.mailboxId === "") {
244678
+ await this.deps.links.set(row.id, brokerId);
244679
+ this.filled.add(row.id);
244680
+ } else if (!inUse && this.filled.has(row.id) && row.mailboxId === brokerId) {
244681
+ await this.deps.links.set(row.id, "");
244682
+ this.filled.delete(row.id);
244683
+ }
244684
+ if (inUse && !rows.some((row) => row.id === defaultId)) this.deps.logger.warn("email-push: the default integration has no record to link the mailbox from", { meta: {
244685
+ integrationId: defaultId,
244077
244686
  brokerId
244078
244687
  } });
244079
244688
  return true;
@@ -244212,7 +244821,7 @@ var EmailPushBridge = class {
244212
244821
  */
244213
244822
  async buildCameraSetupParams(cam) {
244214
244823
  if (!cam.isEmailPushEligible) return null;
244215
- const brokerId = await this.ensureMailbox();
244824
+ const brokerId = await this.resolveMailbox();
244216
244825
  const parsed = SmtpInboundConfigSchema.safeParse(await this.deps.port.getBrokerConfig(brokerId));
244217
244826
  if (!parsed.success) throw new Error("The camera mailbox answered a configuration this build cannot read");
244218
244827
  const config = parsed.data;
@@ -244234,6 +244843,60 @@ function pickMailbox(list) {
244234
244843
  return list.find((b) => b.id === "smtp-inbound-default")?.id ?? list[0]?.id ?? null;
244235
244844
  }
244236
244845
  //#endregion
244846
+ //#region src/email-push-removal-hook.ts
244847
+ /**
244848
+ * A removed camera leaves its `cam-<stableId>` recipient in the mailbox (D865). The addon holds
244849
+ * no per-device DATA for the intake (the mailbox is owned by the mail addon), so removal only
244850
+ * redeclares the recipient set without the camera. Driven by the tombstone, never by absence.
244851
+ */
244852
+ function createEmailPushRemovalHook(deps) {
244853
+ return {
244854
+ onDeviceRemoved: async () => {
244855
+ await deps.resync();
244856
+ return { counts: { "mailbox-recipients": 0 } };
244857
+ },
244858
+ listDeviceData: async () => []
244859
+ };
244860
+ }
244861
+ var LEGACY_PREFIX = "/webhook/";
244862
+ async function startLegacyWebhookIntake(deps) {
244863
+ const warned = /* @__PURE__ */ new Set();
244864
+ const server = createServer((req, res) => {
244865
+ const url = req.url ?? "";
244866
+ if (!url.startsWith(LEGACY_PREFIX)) {
244867
+ res.writeHead(404).end();
244868
+ return;
244869
+ }
244870
+ const rest = url.slice(8);
244871
+ req.url = rest;
244872
+ const id = decodeURIComponent(rest.replace(/^\//, "").split("?")[0] ?? "");
244873
+ const camera = deps.listCameras().find((c) => c.stableId === id);
244874
+ if (camera !== void 0 && !warned.has(id)) {
244875
+ warned.add(id);
244876
+ deps.logger.warn("legacy webhook port used — camera will be re-pointed", {
244877
+ tags: { deviceId: camera.id },
244878
+ meta: { port: deps.port ?? 9081 }
244879
+ });
244880
+ }
244881
+ Promise.resolve(deps.handler(req, res)).catch((err) => {
244882
+ deps.logger.error("legacy webhook intake failed", { meta: { error: err instanceof Error ? err.message : String(err) } });
244883
+ if (!res.headersSent) res.writeHead(500);
244884
+ res.end();
244885
+ });
244886
+ });
244887
+ await new Promise((resolve, reject) => {
244888
+ server.once("error", reject);
244889
+ server.listen(deps.port ?? 9081, "0.0.0.0", () => {
244890
+ server.off("error", reject);
244891
+ resolve();
244892
+ });
244893
+ });
244894
+ return {
244895
+ server,
244896
+ close: () => new Promise((resolve) => server.close(() => resolve()))
244897
+ };
244898
+ }
244899
+ //#endregion
244237
244900
  //#region src/reolink-connection-test.ts
244238
244901
  /**
244239
244902
  * The Reolink NVR / Home Hub connection test (planning#581): log in over Baichuan with the
@@ -244341,6 +245004,28 @@ var reolinkConnectionsEntryKind = defineEntryKind("connections", {
244341
245004
  }),
244342
245005
  writeTrigger: "an operator adds, edits or removes a Reolink integration"
244343
245006
  });
245007
+ /** The kind of the default integration (standalone cameras): a name and the mailbox link, no Test. */
245008
+ var REOLINK_DEFAULT_KIND = "default";
245009
+ /** The kind of an NVR / Home Hub integration: its connection, with a Test. */
245010
+ var REOLINK_HUB_KIND = "connection";
245011
+ /** The form of the default integration: which camera mailbox its standalone cameras use. */
245012
+ function buildDefaultInstanceSchema() {
245013
+ return { sections: [{
245014
+ id: "mailbox",
245015
+ title: "Camera mailbox",
245016
+ titleKey: "provider-reolink:connection.s_mailbox.title",
245017
+ description: "The mailbox the standalone cameras send their email push to.",
245018
+ descriptionKey: "provider-reolink:connection.s_mailbox.description",
245019
+ columns: 1,
245020
+ fields: [{
245021
+ ...linkFieldDescriptor(MAILBOX_LINK_FIELD, SMTP_MAILBOX_LINK, {
245022
+ label: "Camera mailbox",
245023
+ required: false
245024
+ }),
245025
+ labelKey: "provider-reolink:connection.s_mailbox.mailboxId.label"
245026
+ }]
245027
+ }] };
245028
+ }
244344
245029
  /** Every kind this addon declares, keyed by its name. */
244345
245030
  var reolinkRecordKinds = { connections: reolinkConnectionsEntryKind };
244346
245031
  /**
@@ -244447,12 +245132,26 @@ function buildReolinkInstances(records, deps) {
244447
245132
  kind: "connection",
244448
245133
  canTest: true,
244449
245134
  kinds: [{
244450
- id: "connection",
244451
- label: "Reolink",
245135
+ id: REOLINK_DEFAULT_KIND,
245136
+ label: "Reolink standalone cameras",
244452
245137
  functionCap: "device-provider",
244453
- role: "devices"
245138
+ role: "devices",
245139
+ canTest: false,
245140
+ creatable: false
245141
+ }, {
245142
+ id: REOLINK_HUB_KIND,
245143
+ label: "Reolink NVR / Home Hub",
245144
+ functionCap: "device-provider",
245145
+ role: "devices",
245146
+ canTest: true
245147
+ }],
245148
+ links: [{
245149
+ kind: REOLINK_DEFAULT_KIND,
245150
+ field: MAILBOX_LINK_FIELD,
245151
+ to: SMTP_MAILBOX_LINK
244454
245152
  }]
244455
245153
  },
245154
+ kindOf: () => REOLINK_HUB_KIND,
244456
245155
  formSchema: () => buildHubInstanceSchema(),
244457
245156
  initialBody: (name) => ({ name }),
244458
245157
  configured: (body) => (body.host ?? "").length === 0 || (body.password ?? "").length > 0,
@@ -244466,10 +245165,15 @@ function buildReolinkInstances(records, deps) {
244466
245165
  */
244467
245166
  function reolinkInstancesProvider(instances, deps) {
244468
245167
  const base = instances.toProvider();
244469
- const withAddDevice = async (instance) => ({
244470
- ...instance,
244471
- addDevice: await integrationIsHubCached(instances, deps.evidenceCache, instance.id) ? "children" : "scan"
244472
- });
245168
+ const withAddDevice = async (instance) => {
245169
+ const isHub = await integrationIsHubCached(instances, deps.evidenceCache, instance.id);
245170
+ const known = deps.evidenceCache.get(instance.id) !== null;
245171
+ return {
245172
+ ...instance,
245173
+ kind: known && !isHub ? REOLINK_DEFAULT_KIND : REOLINK_HUB_KIND,
245174
+ addDevice: isHub ? "children" : "scan"
245175
+ };
245176
+ };
244473
245177
  return {
244474
245178
  ...base,
244475
245179
  listInstances: async (input) => Promise.all((await base.listInstances(input)).map(withAddDevice)),
@@ -244485,7 +245189,7 @@ function reolinkInstancesProvider(instances, deps) {
244485
245189
  originStableId: evidence.originStableId,
244486
245190
  info: evidence.info,
244487
245191
  settings: body === null ? {} : hubSettingsOf(body)
244488
- }) || body === null ? buildHubInstanceSchema() : { sections: [] };
245192
+ }) || body === null ? buildHubInstanceSchema() : buildDefaultInstanceSchema();
244489
245193
  }
244490
245194
  };
244491
245195
  }
@@ -244537,60 +245241,6 @@ function mailboxLinkStoreOver(records) {
244537
245241
  };
244538
245242
  }
244539
245243
  //#endregion
244540
- //#region src/email-push-removal-hook.ts
244541
- /**
244542
- * A removed camera leaves its `cam-<stableId>` recipient in the mailbox (D865). The addon holds
244543
- * no per-device DATA for the intake (the mailbox is owned by the mail addon), so removal only
244544
- * redeclares the recipient set without the camera. Driven by the tombstone, never by absence.
244545
- */
244546
- function createEmailPushRemovalHook(deps) {
244547
- return {
244548
- onDeviceRemoved: async () => {
244549
- await deps.resync();
244550
- return { counts: { "mailbox-recipients": 0 } };
244551
- },
244552
- listDeviceData: async () => []
244553
- };
244554
- }
244555
- var LEGACY_PREFIX = "/webhook/";
244556
- async function startLegacyWebhookIntake(deps) {
244557
- const warned = /* @__PURE__ */ new Set();
244558
- const server = createServer((req, res) => {
244559
- const url = req.url ?? "";
244560
- if (!url.startsWith(LEGACY_PREFIX)) {
244561
- res.writeHead(404).end();
244562
- return;
244563
- }
244564
- const rest = url.slice(8);
244565
- req.url = rest;
244566
- const id = decodeURIComponent(rest.replace(/^\//, "").split("?")[0] ?? "");
244567
- const camera = deps.listCameras().find((c) => c.stableId === id);
244568
- if (camera !== void 0 && !warned.has(id)) {
244569
- warned.add(id);
244570
- deps.logger.warn("legacy webhook port used — camera will be re-pointed", {
244571
- tags: { deviceId: camera.id },
244572
- meta: { port: deps.port ?? 9081 }
244573
- });
244574
- }
244575
- Promise.resolve(deps.handler(req, res)).catch((err) => {
244576
- deps.logger.error("legacy webhook intake failed", { meta: { error: err instanceof Error ? err.message : String(err) } });
244577
- if (!res.headersSent) res.writeHead(500);
244578
- res.end();
244579
- });
244580
- });
244581
- await new Promise((resolve, reject) => {
244582
- server.once("error", reject);
244583
- server.listen(deps.port ?? 9081, "0.0.0.0", () => {
244584
- server.off("error", reject);
244585
- resolve();
244586
- });
244587
- });
244588
- return {
244589
- server,
244590
- close: () => new Promise((resolve) => server.close(() => resolve()))
244591
- };
244592
- }
244593
- //#endregion
244594
245244
  //#region src/migrations/drop-webhook-intake-settings.ts
244595
245245
  /**
244596
245246
  * The camera webhook is a plane of the addon's HTTP data plane, not a private listener
@@ -244811,6 +245461,14 @@ var REOLINK_MIGRATIONS = [{
244811
245461
  },
244812
245462
  plan: planDropWebhookIntakeSettings
244813
245463
  }];
245464
+ /** The date of the device claim (D1007). */
245465
+ var CLAIM_DEVICES_DATE = "2026-11-04";
245466
+ /**
245467
+ * Every persisted camera that names no integration is claimed to the addon's default one. The
245468
+ * integration a hub migration created is never the default, so it is not eligible. The integration
245469
+ * settings themselves stay where they are until this addon's own wave moves them.
245470
+ */
245471
+ var REOLINK_CLAIM_ELIGIBLE = (integration) => integration.info[MIGRATED_FROM_HUB_KEY] === void 0;
244814
245472
  /**
244815
245473
  * The integration wave (D1007) in declaration order, which must follow `seq`: the device claim
244816
245474
  * shipped first (seq 3) and the rows move follows it (seq 4). The engine refuses the whole
@@ -244818,10 +245476,10 @@ var REOLINK_MIGRATIONS = [{
244818
245476
  */
244819
245477
  var REOLINK_INTEGRATION_MIGRATIONS = [claimDevicesMigration({
244820
245478
  addonId: "provider-reolink",
244821
- date: "2026-11-04",
245479
+ date: CLAIM_DEVICES_DATE,
244822
245480
  seq: 3,
244823
245481
  dependsOn: [],
244824
- eligible: (integration) => integration.info[MIGRATED_FROM_HUB_KEY] === void 0
245482
+ eligible: REOLINK_CLAIM_ELIGIBLE
244825
245483
  }), REOLINK_ROWS_TO_RECORD_MIGRATION];
244826
245484
  //#endregion
244827
245485
  //#region src/reolink-adoption-provider.ts
@@ -245673,12 +246331,24 @@ var ReolinkProviderAddon = class extends BaseDeviceProvider {
245673
246331
  if (records === void 0) throw new Error("provider-reolink: ctx.records is required (hub-only addon)");
245674
246332
  return records;
245675
246333
  }
246334
+ /**
246335
+ * The registry id of the default integration (standalone cameras): the lowest-numbered one this
246336
+ * addon owns that no hub migration created, the same rule as the device claim (D1007).
246337
+ */
246338
+ async resolveDefaultIntegrationId() {
246339
+ return defaultIntegrationOf((await this.ctx.api.integrations.list.query()).filter((i) => i.addonId === this.ctx.id).map((i) => ({
246340
+ id: i.id,
246341
+ name: i.name,
246342
+ info: { ...i.info }
246343
+ })), REOLINK_CLAIM_ELIGIBLE)?.id ?? null;
246344
+ }
245676
246345
  /** The camera mailbox bridge, built once. */
245677
246346
  ensureEmailBridge() {
245678
246347
  this.emailBridge ??= new EmailPushBridge({
245679
246348
  port: createBrokerPort(this.ctx.api),
245680
246349
  links: mailboxLinkStoreOver(this.requireRecords()),
245681
246350
  listCameras: () => this.listReolinkCameras(),
246351
+ defaultIntegrationId: () => this.resolveDefaultIntegrationId(),
245682
246352
  logger: this.ctx.logger.child("email-push"),
245683
246353
  pending: {
245684
246354
  read: () => this.readPendingMailbox(),
@@ -246499,6 +247169,12 @@ var ReolinkProviderAddon = class extends BaseDeviceProvider {
246499
247169
  const emailBridge = this.ensureEmailBridge();
246500
247170
  device.setEmailPushParamsResolver(() => emailBridge.buildCameraSetupParams(device));
246501
247171
  device.setBaichuanWebhookParamsResolver(() => this.buildWebhookParams(device));
247172
+ device.autoConfigureEventPushOnAdd().catch((err) => {
247173
+ ctx.logger.warn("event-push: auto-configure on add threw", {
247174
+ tags: { deviceId: device.id },
247175
+ meta: { error: err instanceof Error ? err.message : String(err) }
247176
+ });
247177
+ });
246502
247178
  }
246503
247179
  ctx.api?.pipelineOrchestrator?.applyDeviceSettingsPatch?.mutate({
246504
247180
  deviceId: device.id,