@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.js CHANGED
@@ -100698,7 +100698,7 @@ function parseBaichuanWebhookObject(mess) {
100698
100698
  return parsed;
100699
100699
  }
100700
100700
  //#endregion
100701
- //#region ../types/dist/event-category-7P4A3bYA.mjs
100701
+ //#region ../types/dist/event-category-BEsBTS72.mjs
100702
100702
  var EventCategory = /* @__PURE__ */ function(EventCategory) {
100703
100703
  EventCategory["SystemBoot"] = "system.boot";
100704
100704
  EventCategory["SystemAddonsReady"] = "system.addons-ready";
@@ -101145,6 +101145,14 @@ var EventCategory = /* @__PURE__ */ function(EventCategory) {
101145
101145
  */
101146
101146
  EventCategory["StreamBrokerOnRequestStreamSourceRefresh"] = "stream-broker.onRequestStreamSourceRefresh";
101147
101147
  /**
101148
+ * A broker RE-DIALED its source (every dial after the first). A consumer that
101149
+ * reads the broker over a transport that does not announce the cut — the
101150
+ * recorder's ffmpeg writer — learns here instead of through its idle clock.
101151
+ * Telemetry: a dropped event only means the idle clock recovers it later.
101152
+ * Payload: `{ deviceId, camStreamId, brokerId, reason }`.
101153
+ */
101154
+ EventCategory["StreamBrokerOnSourceRestart"] = "stream-broker.onSourceRestart";
101155
+ /**
101148
101156
  * A camera provider changed a device's stream parameters (codec /
101149
101157
  * resolution / bitrate / a stream added or removed). A LOW-LATENCY NUDGE
101150
101158
  * for the stream-broker's catalog reconcile: it carries NO authoritative
@@ -106821,7 +106829,7 @@ var ZodIssueCode = {
106821
106829
  var ZodFirstPartyTypeKind;
106822
106830
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
106823
106831
  //#endregion
106824
- //#region ../types/dist/runtime-capabilities-CK6y0W5U.mjs
106832
+ //#region ../types/dist/runtime-capabilities-CG61dYnO.mjs
106825
106833
  /**
106826
106834
  * The audio chunk plane's byte format, and the ONE expansion from a coded
106827
106835
  * window to float samples (D455).
@@ -111687,6 +111695,15 @@ var CameraStreamSchema = object({
111687
111695
  */
111688
111696
  autoEligible: boolean().optional(),
111689
111697
  /**
111698
+ * The longest continuous session the SOURCE will keep open, in ms, declared by
111699
+ * the provider that knows it (a hub that cuts every child's session on a
111700
+ * timer). Absent = no limit. The broker re-dials a live source a little
111701
+ * BEFORE this elapses, on its own terms and announced to consumers, so the
111702
+ * source's cut never lands mid-recording. Declare slightly under what was
111703
+ * observed.
111704
+ */
111705
+ maxSessionMs: number$1().int().positive().optional(),
111706
+ /**
111690
111707
  * The profile slot the PUBLISHER says this stream is: `low` for a stream
111691
111708
  * whose only sensible role is the low-bandwidth one, `high` for a main
111692
111709
  * stream. Consulted by the broker's automatic ranking
@@ -127382,7 +127399,7 @@ function e(group, en, it, flags = {}) {
127382
127399
  };
127383
127400
  }
127384
127401
  var N = { noise: true };
127385
- 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", {
127402
+ 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", {
127386
127403
  noise: true,
127387
127404
  deprecated: true
127388
127405
  }), EventCategory.PipelineAnalyticsTrackEnded, e("detection", "Track ended", "Traccia terminata", {
@@ -154130,8 +154147,15 @@ function convertLegacyWhen(half) {
154130
154147
  /** The longest one `wait` step lasts. It is cut by a restart of the run and does not survive a hub restart. */
154131
154148
  var WAIT_MAX_SECONDS = 3600;
154132
154149
  var WAIT_TOO_LONG = `a wait is at most one hour (${WAIT_MAX_SECONDS} s)`;
154150
+ /**
154151
+ * Every step kind may be switched off without deleting it: `enabled: false`
154152
+ * skips the step (and, for a block step, its whole subtree), traced `disabled`.
154153
+ * Absent means enabled.
154154
+ */
154155
+ var stepEnabledShape = { enabled: boolean().optional() };
154133
154156
  var AutomationWaitStepSchema = object({
154134
154157
  kind: literal("wait"),
154158
+ ...stepEnabledShape,
154135
154159
  seconds: number$1().min(0).max(WAIT_MAX_SECONDS, WAIT_TOO_LONG)
154136
154160
  });
154137
154161
  /**
@@ -154140,6 +154164,7 @@ var AutomationWaitStepSchema = object({
154140
154164
  */
154141
154165
  var AutomationCommandStepBaseSchema = object({
154142
154166
  kind: literal("command"),
154167
+ ...stepEnabledShape,
154143
154168
  /** WHO the step acts on. */
154144
154169
  target: ActionTargetSchema,
154145
154170
  /** The vocabulary action this step performs (`cover.open`). */
@@ -154215,6 +154240,7 @@ var AutomationGuardedCommandStepSchema = AutomationCommandStepBaseSchema.extend(
154215
154240
  /** End the run here, on purpose. `reason` may carry `{{vars.x}}` slots. */
154216
154241
  var AutomationStopStepSchema = object({
154217
154242
  kind: literal("stop"),
154243
+ ...stepEnabledShape,
154218
154244
  reason: string().min(1, "a stop needs a reason: it is what the run trace shows").max(200),
154219
154245
  /** `ok`: the run ends as a success. `failed`: it ends as a failure, with the reason. */
154220
154246
  outcome: _enum(["ok", "failed"]),
@@ -154234,6 +154260,7 @@ var RESERVED_RUN_VARS = [
154234
154260
  */
154235
154261
  var AutomationSetStepSchema = object({
154236
154262
  kind: literal("set"),
154263
+ ...stepEnabledShape,
154237
154264
  vars: record(string(), union([
154238
154265
  string().max(500),
154239
154266
  number$1(),
@@ -154242,8 +154269,25 @@ var AutomationSetStepSchema = object({
154242
154269
  /** Set only when this reads true; false or unknown leaves the bag as it is. */
154243
154270
  if: AutomationWhenSchema.optional()
154244
154271
  });
154272
+ var NOTIFY_BODY_MAX = 2e3;
154273
+ /**
154274
+ * Send a notification through one notification target (the same targets the
154275
+ * notification centre addresses). Title and body may carry `{{vars.x}}` slots.
154276
+ * Not a device command: a notification target is an instance of the
154277
+ * `notification-output` cap, not a device.
154278
+ */
154279
+ var AutomationNotifyStepSchema = object({
154280
+ kind: literal("notify"),
154281
+ ...stepEnabledShape,
154282
+ /** The notification target (an instance id of `notification-output`). */
154283
+ targetId: string().min(1, "pick the notification target"),
154284
+ title: string().max(200).optional(),
154285
+ body: string().min(1, "a notification needs a message").max(NOTIFY_BODY_MAX),
154286
+ ...continueOnErrorShape
154287
+ });
154245
154288
  var AutomationRunActionStepSchema = object({
154246
154289
  kind: literal("action"),
154290
+ ...stepEnabledShape,
154247
154291
  /** An entry of the `actions` surface (`internal:<uuid>` or `<addonId>:<localId>`). */
154248
154292
  actionId: string().min(1),
154249
154293
  /** Values for the action's declared variables; the others take their default. */
@@ -154269,6 +154313,7 @@ var WAIT_UNTIL_TIMEOUT_MAX_S = 21600;
154269
154313
  */
154270
154314
  var AutomationWaitUntilStepSchema = object({
154271
154315
  kind: literal("wait-until"),
154316
+ ...stepEnabledShape,
154272
154317
  when: AutomationWhenSchema,
154273
154318
  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)`),
154274
154319
  onTimeout: _enum(["continue", "stop"])
@@ -154294,7 +154339,8 @@ var plainStepSchemas = [
154294
154339
  AutomationCommandStepBaseSchema.extend(continueOnErrorShape).strict().superRefine(refineKnownAction),
154295
154340
  AutomationStopStepSchema.omit({ if: true }).strict(),
154296
154341
  AutomationSetStepSchema.omit({ if: true }).strict(),
154297
- AutomationRunActionStepSchema.strict()
154342
+ AutomationRunActionStepSchema.strict(),
154343
+ AutomationNotifyStepSchema.strict()
154298
154344
  ];
154299
154345
  /**
154300
154346
  * A plain step: a flow step with no condition of its own and no step inside
@@ -154302,7 +154348,7 @@ var plainStepSchemas = [
154302
154348
  */
154303
154349
  var AutomationBranchStepSchema = discriminatedUnion("kind", plainStepSchemas, { error: nestTooDeep });
154304
154350
  /** A step that can run beside others: it writes no variable and does not end the run. */
154305
- 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");
154351
+ 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");
154306
154352
  /**
154307
154353
  * Several steps at once (#500): all are started together and all are awaited.
154308
154354
  * A failure fails the run once the others finished, as in a sequence; a member
@@ -154310,6 +154356,7 @@ var AutomationParallelMemberSchema = AutomationBranchStepSchema.refine((step) =>
154310
154356
  */
154311
154357
  var AutomationParallelStepSchema = object({
154312
154358
  kind: literal("parallel"),
154359
+ ...stepEnabledShape,
154313
154360
  steps: array(AutomationParallelMemberSchema).min(2, "a parallel needs at least two steps").max(5, `a parallel takes at most 5 steps`)
154314
154361
  }).strict();
154315
154362
  var REPEAT_NEEDS_MAX = "a repeat on a condition needs a maximum number of iterations";
@@ -154350,6 +154397,7 @@ var AutomationRepeatLoopSchema = discriminatedUnion("by", [
154350
154397
  function repeatSchemaOf(step) {
154351
154398
  return object({
154352
154399
  kind: literal("repeat"),
154400
+ ...stepEnabledShape,
154353
154401
  loop: AutomationRepeatLoopSchema,
154354
154402
  steps: array(step).min(1, "a repeat needs at least one step").max(10, `a repeat takes at most 10 steps`)
154355
154403
  }).strict();
@@ -154365,6 +154413,7 @@ function chooseSchemaOf(step) {
154365
154413
  const steps = array(step).max(10);
154366
154414
  return object({
154367
154415
  kind: literal("choose"),
154416
+ ...stepEnabledShape,
154368
154417
  branches: array(object({
154369
154418
  if: AutomationWhenSchema,
154370
154419
  steps: steps.min(1, "a branch needs at least one step")
@@ -154390,8 +154439,10 @@ var AutomationActionSchema = discriminatedUnion("kind", [
154390
154439
  AutomationParallelStepSchema,
154391
154440
  AutomationRepeatStepSchema,
154392
154441
  AutomationRunActionStepSchema,
154442
+ AutomationNotifyStepSchema,
154393
154443
  object({
154394
154444
  kind: literal("code"),
154445
+ ...stepEnabledShape,
154395
154446
  /** Compiled into the automation's OWN block by esbuild — not a third
154396
154447
  * runtime, not a `vm`, and not dynamically evaluated. */
154397
154448
  code: string().min(1).max(2e4)
@@ -159391,6 +159442,8 @@ method(object({
159391
159442
  /** The slot the publisher says this stream IS — see `CameraStreamSchema.profileHint`. */
159392
159443
  profileHint: CamProfileSchema.optional(),
159393
159444
  metadata: record(string(), unknown()).optional(),
159445
+ /** The longest session the source keeps open (ms) — see `CameraStreamSchema.maxSessionMs`. */
159446
+ maxSessionMs: number$1().int().positive().optional(),
159394
159447
  /** Required when kind === 'derived' — the source camStreamId the
159395
159448
  * derived broker reads its encoded plane from.
159396
159449
  * The runtime guard (broker manager, Task 10) enforces presence for
@@ -159609,6 +159662,11 @@ method(object({
159609
159662
  deviceId: number$1().int().nonnegative(),
159610
159663
  camStreamId: string(),
159611
159664
  brokerId: string()
159665
+ })), event(object({
159666
+ deviceId: number$1().int().nonnegative(),
159667
+ camStreamId: string(),
159668
+ brokerId: string(),
159669
+ reason: string()
159612
159670
  })), NOT_A_DEVICE.PIPELINE;
159613
159671
  var StreamCodecSchema = _enum([
159614
159672
  "h264",
@@ -162713,7 +162771,7 @@ var mediaPlayerCapability = {
162713
162771
  ]
162714
162772
  }
162715
162773
  };
162716
- 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;
162774
+ 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;
162717
162775
  var NUMBER = {
162718
162776
  kind: "fixed",
162719
162777
  result: ["number"]
@@ -169151,6 +169209,15 @@ var DeviceFaultSchema = object({
169151
169209
  label: string(),
169152
169210
  severity: DeviceErrorSeveritySchema
169153
169211
  });
169212
+ /** One kind of fault a device CAN raise: the integration's own declared catalog entry. */
169213
+ var DeviceFaultTypeSchema = DeviceFaultSchema;
169214
+ /**
169215
+ * The fault catalog of a device, declared by its integration at runtime (never a
169216
+ * code enum). A fault outside the catalog is still published and still matches
169217
+ * a rule that names no code.
169218
+ */
169219
+ var ListFaultTypesInputSchema = object({ deviceId: number$1().int().nonnegative() });
169220
+ var FaultTypesSchema = object({ types: array(DeviceFaultTypeSchema) });
169154
169221
  /**
169155
169222
  * The fault a device reports right now. One slice per device.
169156
169223
  *
@@ -169188,7 +169255,12 @@ var errorCapability = {
169188
169255
  scope: "device",
169189
169256
  deviceNative: true,
169190
169257
  mode: "singleton",
169191
- methods: {},
169258
+ methods: {
169259
+ /** The fault codes this device's integration can raise; `[]` when it declares none. */
169260
+ listFaultTypes: method(ListFaultTypesInputSchema, FaultTypesSchema, {
169261
+ kind: "query",
169262
+ auth: "protected"
169263
+ }) },
169192
169264
  status: {
169193
169265
  schema: ErrorStatusSchema,
169194
169266
  kind: "push",
@@ -171136,6 +171208,43 @@ function heatPumpInstantCop(power) {
171136
171208
  if (thermalW === null || electricalW === null || electricalW <= 0) return null;
171137
171209
  return thermalW / electricalW;
171138
171210
  }
171211
+ var HEAT_PUMP_CUSTOMIZE_DEVICE_TYPES = [DeviceType.HeatPump];
171212
+ /** One electrical reading the operator may take from a device they pick, unit checked. */
171213
+ function electricalTarget(id, path, unit) {
171214
+ return {
171215
+ id,
171216
+ cardinality: "scalar",
171217
+ vocabulary: { cap: "heat-pump-status" },
171218
+ deviceTypes: HEAT_PUMP_CUSTOMIZE_DEVICE_TYPES,
171219
+ apply: "replace",
171220
+ path,
171221
+ sources: [{
171222
+ kind: "numeric",
171223
+ requiredUnit: unit,
171224
+ transforms: [{ kind: "identity" }]
171225
+ }],
171226
+ sourceReport: { status: "assignment-status" }
171227
+ };
171228
+ }
171229
+ var HEAT_PUMP_TARGETS = [electricalTarget("electrical-power", "power.electricalW", "W"), electricalTarget("electrical-energy", "energy.electricalKwh", "kWh")];
171230
+ /**
171231
+ * Customize (D984, #476): a gateway that reports no instantaneous electrical
171232
+ * power (the cloud ones) or whose energy meter the operator trusts less than a
171233
+ * dedicated one lets the OPERATOR pick a device for `power.electricalW` and
171234
+ * `energy.electricalKwh` — a `replace` over a field listed in `overridable`,
171235
+ * nothing else. The replaced value IS the cap field, so the instant COP, the
171236
+ * hero pills and the history use it; nothing is linked by itself (D356), the
171237
+ * unit is checked, and a source that does not answer releases the field back to
171238
+ * the native reading (never a 0, D393).
171239
+ */
171240
+ var heatPumpStatusCustomize = {
171241
+ version: 1,
171242
+ overridable: HEAT_PUMP_TARGETS.map((target) => ({
171243
+ path: target.path,
171244
+ by: target.id
171245
+ })),
171246
+ targets: HEAT_PUMP_TARGETS
171247
+ };
171139
171248
  var heatPumpStatusCapability = {
171140
171249
  name: "heat-pump-status",
171141
171250
  scope: "device",
@@ -171154,6 +171263,7 @@ var heatPumpStatusCapability = {
171154
171263
  * (the series are recorded). See `RuntimeStateDurability`.
171155
171264
  */
171156
171265
  durability: "session",
171266
+ customize: heatPumpStatusCustomize,
171157
171267
  /**
171158
171268
  * History (D850, D917): `circuits[]` is a keyed array — one series per circuit and
171159
171269
  * field, named by the circuit's label. The mode is a state (D896); the energy
@@ -172945,6 +173055,8 @@ var IntegrationInstanceKindSchema = object({
172945
173055
  role: IntegrationInstanceRoleSchema.optional(),
172946
173056
  /** `testInstance` really probes the remote for this kind; absent takes the provider's `canTest`. */
172947
173057
  canTest: boolean().optional(),
173058
+ /** `false`: Add never offers this kind (the system creates its one instance, e.g. a default integration). Absent = creatable. */
173059
+ creatable: boolean().optional(),
172948
173060
  /** The kind signs in through a server-held interactive session. */
172949
173061
  signIn: object({
172950
173062
  basePath: string().min(1),
@@ -184117,6 +184229,13 @@ var NcSystemEventConditionSchema = object({
184117
184229
  * pick from. The hub refuses an id the action index does not know.
184118
184230
  */
184119
184231
  commandActions: array(string().min(1)).min(1).optional(),
184232
+ /**
184233
+ * `device-attention-*` only: the fault CODES this rule speaks about (the
184234
+ * integration declares them through `error.listFaultTypes`; free text is
184235
+ * accepted too). Absent or empty = any fault. The rule matches when any
184236
+ * fault of the episode is in the list.
184237
+ */
184238
+ faultCodes: array(string().min(1)).optional(),
184120
184239
  /** `device-command` only: how the command settled. A device's own change is not a command. */
184121
184240
  commandOutcomes: array(_enum([
184122
184241
  "confirmed",
@@ -196042,7 +196161,16 @@ var CamStreamDescriptorSchema = object({
196042
196161
  /** The slot the publisher says this stream IS — see `CameraStreamSchema.profileHint`. */
196043
196162
  profileHint: CamProfileSchema.optional(),
196044
196163
  /** Transport-specific opaque metadata (e.g. rfc4571 SDP). */
196045
- metadata: record(string(), unknown()).optional()
196164
+ metadata: record(string(), unknown()).optional(),
196165
+ /**
196166
+ * The longest continuous session the SOURCE will keep open, in ms, declared by
196167
+ * the provider that knows it (a hub that cuts every child's session on a
196168
+ * timer). Absent = no limit. The broker re-dials a live source a little
196169
+ * BEFORE this elapses, on its own terms and announced to consumers, so the
196170
+ * source's cut never lands mid-recording. Declare slightly under what was
196171
+ * observed.
196172
+ */
196173
+ maxSessionMs: number$1().int().positive().optional()
196046
196174
  });
196047
196175
  /**
196048
196176
  * `stream-catalog` — device-scoped, provider-implemented. The pull counterpart
@@ -202950,6 +203078,20 @@ function deviceErrorEdge(previous, next) {
202950
203078
  function deviceErrorAlertId(deviceId) {
202951
203079
  return `device-error:${String(deviceId)}`;
202952
203080
  }
203081
+ /** Every active fault, the principal first; a status that lists none still names its principal. */
203082
+ function activeFaults(status) {
203083
+ if (status.faults !== void 0 && status.faults.length > 0) return status.faults.map(({ code, label, severity }) => ({
203084
+ code,
203085
+ label,
203086
+ severity
203087
+ }));
203088
+ if (status.code === null) return [];
203089
+ return [{
203090
+ code: status.code,
203091
+ label: status.label ?? status.code,
203092
+ severity: status.severity
203093
+ }];
203094
+ }
202953
203095
  /** The alert that opens an episode. `since` is the fault's own start, else `now`. */
202954
203096
  function buildDeviceErrorAlert(deviceId, deviceName, status, now) {
202955
203097
  const label = status.label ?? status.code ?? "Fault";
@@ -202977,7 +203119,9 @@ function buildDeviceErrorAlert(deviceId, deviceName, status, now) {
202977
203119
  metadata: {
202978
203120
  episodeId: `${alertId}@${String(startedAt)}`,
202979
203121
  code: status.code,
202980
- deviceSeverity: status.severity
203122
+ deviceSeverity: status.severity,
203123
+ label: status.label,
203124
+ faults: activeFaults(status)
202981
203125
  }
202982
203126
  };
202983
203127
  }
@@ -202987,6 +203131,8 @@ var BaseDevice = class {
202987
203131
  type;
202988
203132
  /** True when another process owns the base slices (`options.deviceStatus: 'external'`). */
202989
203133
  statusIsExternal;
203134
+ /** The fault catalog the integration declared; `[]` until it does. */
203135
+ faultTypes = [];
202990
203136
  name;
202991
203137
  parentDeviceId;
202992
203138
  role;
@@ -203324,10 +203470,19 @@ var BaseDevice = class {
203324
203470
  * a restart is compared, not announced again.
203325
203471
  */
203326
203472
  registerErrorCap() {
203327
- this.ctx.registerNativeCap?.(errorCapability, {});
203473
+ this.ctx.registerNativeCap?.(errorCapability, { listFaultTypes: async () => ({ types: [...this.faultTypes] }) });
203328
203474
  if (this.runtimeState.getCapState(errorCapability.name) === void 0) this.setCapSlice(errorCapability, ERROR_STATUS_COLD);
203329
203475
  }
203330
203476
  /**
203477
+ * Declare the fault kinds this device's integration can raise (code, label,
203478
+ * severity), served by `error.listFaultTypes` so a rule's code picker is
203479
+ * offered the integration's own words. The default is `[]`; a fault outside
203480
+ * the catalog is still published. Call it before or after `registerErrorCap`.
203481
+ */
203482
+ declareFaultTypes(types) {
203483
+ this.faultTypes = types.map((type) => ({ ...type }));
203484
+ }
203485
+ /**
203331
203486
  * Publish the device's fault. The slice is written; on an EDGE (a fault
203332
203487
  * starts, or one resolves) an attention episode opens or closes through the
203333
203488
  * alerts cap, which the notification center announces as
@@ -210304,6 +210459,13 @@ Object.freeze({
210304
210459
  access: "view",
210305
210460
  role: "viewer"
210306
210461
  },
210462
+ "error.listFaultTypes": {
210463
+ capName: "error",
210464
+ capScope: "device",
210465
+ addonId: null,
210466
+ access: "view",
210467
+ role: "viewer"
210468
+ },
210307
210469
  "eventEmitter.getStatus": {
210308
210470
  capName: "event-emitter",
210309
210471
  capScope: "device",
@@ -218927,6 +219089,11 @@ Object.freeze({
218927
219089
  form: "single",
218928
219090
  optional: false
218929
219091
  }],
219092
+ "error.listFaultTypes": [{
219093
+ name: "deviceId",
219094
+ form: "single",
219095
+ optional: false
219096
+ }],
218930
219097
  "eventEmitter.getStatus": [{
218931
219098
  name: "deviceId",
218932
219099
  form: "single",
@@ -221259,7 +221426,8 @@ var NC_SYSTEM_EVENT_FILTER_KEYS = [
221259
221426
  "consumableLowPercent",
221260
221427
  "commandActions",
221261
221428
  "commandOutcomes",
221262
- "commandActorKinds"
221429
+ "commandActorKinds",
221430
+ "faultCodes"
221263
221431
  ];
221264
221432
  new Map(Object.entries({
221265
221433
  "device-online": "device-events",
@@ -221630,6 +221798,8 @@ object({
221630
221798
  nodeId: string().optional(),
221631
221799
  /** The alert's own action link (where the operator acts on it), when it has one. */
221632
221800
  actionUrl: string().optional(),
221801
+ /** A device fault episode: every active fault (`metadata.faults`), principal first. */
221802
+ faults: array(DeviceFaultSchema).optional(),
221633
221803
  at: number$1()
221634
221804
  });
221635
221805
  var RULE_BODY_ONLY = ["body"];
@@ -221914,6 +222084,9 @@ var STATE_SUMMARY_VARS = [
221914
222084
  ([...RULE_TEXT], [...DEVICE_ATTENTION, ...ALERT_EPISODE]),
221915
222085
  ([...RULE_TEXT], [...ALERT_EPISODE]),
221916
222086
  ([...RULE_TEXT], [...DEVICE_ATTENTION, ...ALERT_EPISODE]),
222087
+ ([...RULE_TEXT], [...DEVICE_ATTENTION]),
222088
+ ([...RULE_TEXT], [...DEVICE_ATTENTION]),
222089
+ ([...RULE_TEXT], [...DEVICE_ATTENTION]),
221917
222090
  [...RULE_TEXT],
221918
222091
  [...RULE_TEXT],
221919
222092
  [...RULE_TEXT],
@@ -222678,6 +222851,19 @@ object({
222678
222851
  delay: number$1().nonnegative().optional(),
222679
222852
  commands: record(string(), unknown())
222680
222853
  });
222854
+ /** The `instance-select` field of a link, keyed like the body field it fills. */
222855
+ function linkFieldDescriptor(key, target, labels) {
222856
+ return {
222857
+ type: "instance-select",
222858
+ key,
222859
+ label: labels.label,
222860
+ ...labels.description !== void 0 ? { description: labels.description } : {},
222861
+ required: labels.required ?? true,
222862
+ ...labels.noneLabel !== void 0 ? { noneLabel: labels.noneLabel } : {},
222863
+ functionCap: target.cap,
222864
+ ...target.kind !== void 0 ? { kind: target.kind } : {}
222865
+ };
222866
+ }
222681
222867
  //#endregion
222682
222868
  //#region src/clips/clip-prefetch.ts
222683
222869
  /** The longest a device may stay quiet after refusals, whatever its interval. */
@@ -223177,6 +223363,11 @@ var reolinkCameraSchema = object({
223177
223363
  /** Empty for a camera adopted from an NVR / Home Hub: it borrows its integration's session. */
223178
223364
  password: string().default("").describe("Password").meta({ secret: true }),
223179
223365
  /**
223366
+ * The SMTP password last written to the camera on the Email tab (or by Auto-configure email
223367
+ * push). A keychain secret: the form shows set / not set, never the value.
223368
+ */
223369
+ emailPassword: string().default("").describe("Camera SMTP password").meta({ secret: true }),
223370
+ /**
223180
223371
  * Transport mode resolved at creation time by autodetect (Slice 15).
223181
223372
  * - `tcp` : standard TCP-based Baichuan (regular cameras, NVR/Hub)
223182
223373
  * - `udp` : BCUDP-based Baichuan (battery cams, UDP-only models like
@@ -223504,6 +223695,17 @@ var reolinkCameraSchema = object({
223504
223695
  supported: boolean().optional()
223505
223696
  }).optional(),
223506
223697
  /**
223698
+ * The power source of a battery camera (`getPowerSource`): `adapter`,
223699
+ * `battery`, or `unknown` when the read failed or the firmware is
223700
+ * silent. Drives the Advanced tab's "Power source" setting; `unknown`
223701
+ * hides it.
223702
+ */
223703
+ powerSourceSnapshot: object({ source: _enum([
223704
+ "adapter",
223705
+ "battery",
223706
+ "unknown"
223707
+ ]) }).optional(),
223708
+ /**
223507
223709
  * Snapshot of the camera's auto-reboot schedule from
223508
223710
  * `getAutoReboot` (cmd_id 101). Drives the "Auto reboot" section
223509
223711
  * defaults on the Advanced tab. `weekDay` is the lib's `DayOfWeek`
@@ -223575,6 +223777,16 @@ var reolinkCameraSchema = object({
223575
223777
  */
223576
223778
  webhookUrlGeneration: number$1().int().optional(),
223577
223779
  /**
223780
+ * "Auto-configure event push on add": right after the camera is added, arm its local event push
223781
+ * (HaCfg webhook for a standalone battery camera, else the camera mailbox). Default on.
223782
+ */
223783
+ autoConfigureEventPush: boolean().optional(),
223784
+ /**
223785
+ * What the one-time add-time run did (`configured:<mechanism>` | `skipped` | `failed`). Present
223786
+ * means the run happened: a restart never writes the camera again.
223787
+ */
223788
+ eventPushAutoConfigured: string().optional(),
223789
+ /**
223578
223790
  * On-camera motion detection master switch + sensitivity.
223579
223791
  * Pushed via `setMotionAlarm` (cmdId=47). The Reolink mobile
223580
223792
  * app + camera web UI use 1..50 (1 = least sensitive,
@@ -229785,6 +229997,17 @@ function deriveReolinkCameraFeatures(inputs) {
229785
229997
  return out;
229786
229998
  }
229787
229999
  //#endregion
230000
+ //#region src/email-smtp-password.ts
230001
+ /**
230002
+ * The camera SMTP password an operator wrote on the Email tab, when it is a real value to push
230003
+ * to the camera and keep: a non-empty string that is not a keychain marker. Blank means "keep
230004
+ * the stored one" and a marker is the form echoing back what it was shown; neither is a write.
230005
+ */
230006
+ function smtpPasswordToWrite(value) {
230007
+ if (typeof value !== "string" || value.length === 0) return null;
230008
+ return isSecretMarker(value) ? null : value;
230009
+ }
230010
+ //#endregion
229788
230011
  //#region src/hub-child-settings.ts
229789
230012
  /**
229790
230013
  * A camera adopted under an NVR / Home Hub dials through the integration's session: the address
@@ -231709,6 +231932,22 @@ var SLEEP_HYSTERESIS_MS = 5e3;
231709
231932
  * exactly its recovery role.
231710
231933
  */
231711
231934
  var HUB_SUMMARY_SLEEP_GRACE_MS = 18e4;
231935
+ /**
231936
+ * How recent the last video packet must be for the stream to count as
231937
+ * flowing. A camera that is delivering video is awake, whatever a second-hand
231938
+ * claim says: a Home Hub child on DC power was marked sleeping every 28 min
231939
+ * (and by the lagging hub summary) while its RTP was running, which froze the
231940
+ * snapshot tile on "sleeping".
231941
+ */
231942
+ var VIDEO_FLOW_FRESH_MS = 5e3;
231943
+ /**
231944
+ * A source that is not the camera's own reading of itself: the parent's
231945
+ * summaries, and a pushed `simple-event` (the Home Hub's session cut arrives
231946
+ * as one).
231947
+ */
231948
+ function isSecondHand(source) {
231949
+ return source === "hub-summary" || source === "hub-reconcile" || source === "simple-event";
231950
+ }
231712
231951
  /** A source whose verdict comes from the parent NVR's channel summary. */
231713
231952
  function isSummarySourced(source) {
231714
231953
  return source === "hub-summary" || source === "hub-reconcile";
@@ -231729,8 +231968,23 @@ function isSummarySourced(source) {
231729
231968
  * observation inside the grace says otherwise.
231730
231969
  */
231731
231970
  function decideSleepCommit(input) {
231732
- const { current, next, source, lastFirstHandCommitAt, nowMs } = input;
231971
+ const { current, next, source, lastFirstHandCommitAt, nowMs, videoFlowing, wired } = input;
231733
231972
  if (current === next) return { kind: "unchanged" };
231973
+ if (next === true && isSecondHand(source)) {
231974
+ const sinceMs = nowMs - lastFirstHandCommitAt;
231975
+ if (wired) return {
231976
+ kind: "refused",
231977
+ reason: "wired",
231978
+ windowMs: 0,
231979
+ sinceLastChangeMs: sinceMs
231980
+ };
231981
+ if (videoFlowing) return {
231982
+ kind: "refused",
231983
+ reason: "video-flowing",
231984
+ windowMs: VIDEO_FLOW_FRESH_MS,
231985
+ sinceLastChangeMs: sinceMs
231986
+ };
231987
+ }
231734
231988
  const summarySourced = isSummarySourced(source);
231735
231989
  const firstHandWake = source === "confirmed-wake" && next === false;
231736
231990
  const sinceLastChangeMs = nowMs - lastFirstHandCommitAt;
@@ -231755,6 +232009,58 @@ function decideSleepCommit(input) {
231755
232009
  };
231756
232010
  }
231757
232011
  //#endregion
232012
+ //#region src/session-limit.ts
232013
+ /**
232014
+ * How long the broker lets a Home Hub child's session run before it re-dials on
232015
+ * its own terms.
232016
+ *
232017
+ * Observed 2026-11-20 on two DC-powered children of one Home Hub: the hub cut
232018
+ * BOTH sessions at the same second, every 28 min 07 s (16:16:36, then 16:44:43),
232019
+ * which is a hub session limit, not the camera. Declared a minute under that so
232020
+ * the planned re-dial always wins the race against the hub's cut and the
232021
+ * recording rolls over at a time of our choosing.
232022
+ */
232023
+ var HOME_HUB_SESSION_LIMIT_MS = 27 * 6e4;
232024
+ /**
232025
+ * Stamp the descriptors with the session limit the broker acts on. Only a
232026
+ * battery child of a hub gets one: a standalone camera has no such cut, and
232027
+ * declaring one there would re-dial a healthy stream for nothing.
232028
+ */
232029
+ function withSessionLimit(descriptors, input) {
232030
+ if (!input.isHubChild || !input.isBattery) return [...descriptors];
232031
+ return descriptors.map((d) => ({
232032
+ ...d,
232033
+ maxSessionMs: HOME_HUB_SESSION_LIMIT_MS
232034
+ }));
232035
+ }
232036
+ //#endregion
232037
+ //#region src/video-flow.ts
232038
+ /**
232039
+ * Report every video packet a stream server produces. The three stream kinds
232040
+ * the server can sit on name the same event differently (`videoFrame` for the
232041
+ * native and composite streams, `videoAccessUnit` for the always-on one), so
232042
+ * the kind is narrowed by class, not asserted.
232043
+ *
232044
+ * Returns the unsubscribe. A stream kind this does not know is reported
232045
+ * through `onUnknown` and never watched — silence would read as "no video".
232046
+ */
232047
+ function watchVideoFlow(stream, onFlow, onUnknown) {
232048
+ if (stream instanceof require_chunk_LXENEW4N.BaichuanVideoStream || stream instanceof CompositeStream) {
232049
+ stream.on("videoFrame", onFlow);
232050
+ return () => {
232051
+ stream.off("videoFrame", onFlow);
232052
+ };
232053
+ }
232054
+ if (stream instanceof ContinuousVideoStream) {
232055
+ stream.on("videoAccessUnit", onFlow);
232056
+ return () => {
232057
+ stream.off("videoAccessUnit", onFlow);
232058
+ };
232059
+ }
232060
+ onUnknown();
232061
+ return () => {};
232062
+ }
232063
+ //#endregion
231758
232064
  //#region src/snapshot-wake-gate.ts
231759
232065
  /**
231760
232066
  * Decide whether a snapshot read may reach the camera's socket.
@@ -231778,6 +232084,74 @@ function decideSnapshotCameraAccess(input) {
231778
232084
  };
231779
232085
  }
231780
232086
  //#endregion
232087
+ //#region src/event-push-on-add.ts
232088
+ function reasonOf(err) {
232089
+ return err instanceof Error ? err.message : String(err);
232090
+ }
232091
+ async function decide(ports) {
232092
+ if (!ports.enabled()) return {
232093
+ status: "skipped",
232094
+ reason: "auto-configure event push on add is switched off"
232095
+ };
232096
+ if (!ports.isEligible()) return {
232097
+ status: "skipped",
232098
+ reason: "hub-attached camera: the hub owns its event push, no email or webhook is written"
232099
+ };
232100
+ const method = ports.method();
232101
+ const webhookPossible = ports.isBattery() && method !== "email";
232102
+ const failures = [];
232103
+ if (webhookPossible) try {
232104
+ await ports.configureWebhook();
232105
+ return {
232106
+ status: "configured",
232107
+ mechanism: "webhook"
232108
+ };
232109
+ } catch (err) {
232110
+ failures.push(`webhook: ${reasonOf(err)}`);
232111
+ if (method === "webhook") return {
232112
+ status: "failed",
232113
+ reason: failures.join("; ")
232114
+ };
232115
+ }
232116
+ else if (method === "webhook") return {
232117
+ status: "skipped",
232118
+ reason: "the webhook needs a standalone battery camera and this one is not"
232119
+ };
232120
+ try {
232121
+ await ports.configureEmail();
232122
+ return {
232123
+ status: "configured",
232124
+ mechanism: "email"
232125
+ };
232126
+ } catch (err) {
232127
+ failures.push(`email: ${reasonOf(err)}`);
232128
+ return {
232129
+ status: "failed",
232130
+ reason: failures.join("; ")
232131
+ };
232132
+ }
232133
+ }
232134
+ /**
232135
+ * Arm a camera's local event push ONCE, right after it is added. A failure is an outcome, never
232136
+ * a throw: it must not block the add. The outcome is logged and recorded, and a recorded camera
232137
+ * is never written again. Battery cameras prefer the webhook (it works while asleep) and fall back
232138
+ * to the camera mailbox; only one path is armed, so events are not delivered twice.
232139
+ */
232140
+ async function autoConfigureEventPushOnce(ports) {
232141
+ if (ports.recordedOutcome() !== void 0) return "already-ran";
232142
+ const outcome = await decide(ports);
232143
+ ports.log(outcome);
232144
+ try {
232145
+ await ports.record(outcome);
232146
+ } catch (err) {
232147
+ ports.log({
232148
+ status: "failed",
232149
+ reason: `could not record the run: ${reasonOf(err)}`
232150
+ });
232151
+ }
232152
+ return outcome;
232153
+ }
232154
+ //#endregion
231781
232155
  //#region src/webhook-generation.ts
231782
232156
  /**
231783
232157
  * Point a battery camera's webhook at the data-plane URL ONCE per URL generation.
@@ -232418,6 +232792,13 @@ var PirAccessory = class extends BaseDevice {
232418
232792
  * inverse `101 - userValue` (lower raw = more sensitive).
232419
232793
  * Mirrors `refreshSwitchFromExternal`'s reverse transform. */
232420
232794
  async pushConfigToFirmware(enable) {
232795
+ if (this.parent.wakeForWrite && !await this.parent.wakeForWrite()) {
232796
+ this.ctx.logger.warn("pir write not sent — the battery camera could not be woken", {
232797
+ tags: { deviceId: this.id },
232798
+ meta: { channel: this.channel }
232799
+ });
232800
+ throw new Error("The camera is asleep and could not be woken; try again in a moment.");
232801
+ }
232421
232802
  const api = await this.api;
232422
232803
  const sensitive = this.config.get("pirSensitive");
232423
232804
  const reduceAlarm = this.config.get("pirReduceAlarm");
@@ -234313,10 +234694,9 @@ var PowerSourceReadingSchema = _enum([
234313
234694
  "battery",
234314
234695
  "unknown"
234315
234696
  ]);
234316
- var ReadPowerSourceResultSchema = object({ source: PowerSourceReadingSchema });
234317
234697
  /** The device (or this code) declined before any real write was sent. */
234318
234698
  var PowerSourceRefusalReasonSchema = _enum(["dry-run-refused", "dry-run-failed"]);
234319
- var SwitchPowerSourceResultSchema = discriminatedUnion("outcome", [
234699
+ discriminatedUnion("outcome", [
234320
234700
  object({
234321
234701
  outcome: literal("refused"),
234322
234702
  mode: PowerSourceModeSchema,
@@ -234460,6 +234840,107 @@ async function switchPowerSourceTo(target, mode) {
234460
234840
  applied
234461
234841
  };
234462
234842
  }
234843
+ /** The settings key of the power source: an ordinary select, owned by the camera (never stored). */
234844
+ var POWER_SOURCE_SETTING_KEY = "powerSource";
234845
+ /**
234846
+ * The power source as a setting, in its own section of the Advanced tab.
234847
+ * Only a battery camera whose read ANSWERED with a mode has one: a camera that
234848
+ * was never asked, or that did not answer, shows nothing rather than a guess.
234849
+ */
234850
+ function buildPowerSourceSettingsSection(input) {
234851
+ const { isBattery, source } = input;
234852
+ if (!isBattery || source === void 0 || source === "unknown") return [];
234853
+ return [{
234854
+ id: "power-source",
234855
+ tab: "advanced",
234856
+ title: "Power source",
234857
+ titleKey: "provider-reolink:schema.s_power-source.title",
234858
+ description: "Only switch to wired power when the adapter meets the camera's spec.",
234859
+ descriptionKey: "provider-reolink:schema.s_power-source.description",
234860
+ columns: 1,
234861
+ fields: [{
234862
+ type: "select",
234863
+ key: POWER_SOURCE_SETTING_KEY,
234864
+ label: "Power source",
234865
+ labelKey: "provider-reolink:schema.s_power-source.powerSource.label",
234866
+ default: source,
234867
+ required: true,
234868
+ options: [{
234869
+ value: "adapter",
234870
+ label: "Wired power",
234871
+ labelKey: "provider-reolink:schema.s_power-source.powerSource.o_adapter.label"
234872
+ }, {
234873
+ value: "battery",
234874
+ label: "Battery power",
234875
+ labelKey: "provider-reolink:schema.s_power-source.powerSource.o_battery.label"
234876
+ }]
234877
+ }]
234878
+ }];
234879
+ }
234880
+ /**
234881
+ * Apply the setting: switch the camera and REFUSE to call a switch that did not
234882
+ * land a success — the settings form keeps the operator's edit, marked unsaved.
234883
+ */
234884
+ async function applyPowerSourceSetting(target, value) {
234885
+ const mode = PowerSourceModeSchema.safeParse(value);
234886
+ if (!mode.success) throw new Error(`Not a power source: ${String(value)}`);
234887
+ const outcome = await switchPowerSourceTo(target, mode.data);
234888
+ if (outcome.outcome === "refused") throw new Error(`The camera refused the power source switch (${outcome.reason})`);
234889
+ if (outcome.outcome === "failed") throw new Error(`The power source switch failed: ${outcome.error}`);
234890
+ if (!outcome.applied) throw new Error(`The camera did not take the power source switch (it reports ${outcome.after})`);
234891
+ }
234892
+ //#endregion
234893
+ //#region src/keep-awake-loop.ts
234894
+ /**
234895
+ * Stream-scoped keep-awake for a battery camera. While at least one stream
234896
+ * consumer is attached, a periodic wake keeps the firmware from entering
234897
+ * standby (which would stop the video). One timer per camera; started when the
234898
+ * first consumer attaches, stopped when the last one leaves.
234899
+ *
234900
+ * Pure: the timer and the wake call are injected so the loop is testable.
234901
+ */
234902
+ var KEEP_AWAKE_INTERVAL_MS = 2e4;
234903
+ function createKeepAwakeLoop(deps) {
234904
+ let handle = null;
234905
+ let failing = false;
234906
+ const tick = () => {
234907
+ deps.wake().then(() => {
234908
+ failing = false;
234909
+ }).catch((err) => {
234910
+ const first = !failing;
234911
+ failing = true;
234912
+ try {
234913
+ deps.onFailure(err, first);
234914
+ } catch {}
234915
+ });
234916
+ };
234917
+ const arm = () => {
234918
+ handle = deps.setTimer(() => {
234919
+ if (handle === null) return;
234920
+ tick();
234921
+ arm();
234922
+ }, deps.intervalMs);
234923
+ };
234924
+ const halt = (activeStreams) => {
234925
+ if (handle === null) return;
234926
+ deps.clearTimer(handle);
234927
+ handle = null;
234928
+ failing = false;
234929
+ deps.onStop(activeStreams);
234930
+ };
234931
+ return {
234932
+ sync: (activeStreams) => {
234933
+ if (!deps.isBattery()) return;
234934
+ if (activeStreams > 0) {
234935
+ if (handle !== null) return;
234936
+ arm();
234937
+ deps.onStart(activeStreams);
234938
+ } else halt(activeStreams);
234939
+ },
234940
+ stop: () => halt(0),
234941
+ running: () => handle !== null
234942
+ };
234943
+ }
234463
234944
  //#endregion
234464
234945
  //#region src/ptz-zoom.ts
234465
234946
  /**
@@ -235433,6 +235914,7 @@ function slicesForPatch(patch) {
235433
235914
  if (has("pirReduceFalseAlarm")) out.add("pir");
235434
235915
  if (has("autoRebootEnabled", "autoRebootWeekDay", "autoRebootHour", "autoRebootMinute")) out.add("autoReboot");
235435
235916
  if (has("timeZoneId")) out.add("systemGeneral");
235917
+ if (has("powerSource")) out.add("powerSource");
235436
235918
  return out;
235437
235919
  }
235438
235920
  /**
@@ -235449,8 +235931,6 @@ var RefreshSettingsResultSchema = object({
235449
235931
  capsWarmed: number$1(),
235450
235932
  capsTotal: number$1()
235451
235933
  });
235452
- /** The two switch actions, one implementation each way. */
235453
- var POWER_SWITCH_ACTIONS = [["switch-to-wired-power", "adapter"], ["switch-to-battery-power", "battery"]];
235454
235934
  /** The uid out of a device's metadata bag, or nothing. Never a cast. */
235455
235935
  function metaUid(metadata) {
235456
235936
  if (metadata === null) return void 0;
@@ -235573,8 +236053,44 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
235573
236053
  nextEventHealthCheckAt = 0;
235574
236054
  /** Active video streams keyed by camStreamId. */
235575
236055
  active = /* @__PURE__ */ new Map();
236056
+ /**
236057
+ * Stream-scoped keep-awake (battery only): while a consumer holds a stream,
236058
+ * a periodic wake stops the firmware from entering standby. Reconciled with
236059
+ * `this.active` through `syncKeepAwake()` after every mutation of the map.
236060
+ */
236061
+ keepAwake = createKeepAwakeLoop({
236062
+ intervalMs: KEEP_AWAKE_INTERVAL_MS,
236063
+ isBattery: () => this.isBattery,
236064
+ wake: async () => {
236065
+ await (await this.ensureApi()).wakeUp(this.getChannel(), {
236066
+ attempts: 1,
236067
+ waitAfterWakeMs: 0
236068
+ });
236069
+ },
236070
+ setTimer: (fn, ms) => setTimeout(fn, ms),
236071
+ clearTimer: (h) => clearTimeout(h),
236072
+ onStart: (activeStreams) => this.ctx.logger.info("keep-awake: started", {
236073
+ tags: { deviceId: this.id },
236074
+ meta: { activeStreams }
236075
+ }),
236076
+ onStop: (activeStreams) => this.ctx.logger.info("keep-awake: stopped", {
236077
+ tags: { deviceId: this.id },
236078
+ meta: { activeStreams }
236079
+ }),
236080
+ onFailure: (err, first) => {
236081
+ (first ? this.ctx.logger.info.bind(this.ctx.logger) : this.ctx.logger.debug.bind(this.ctx.logger))("keep-awake: wake failed", {
236082
+ tags: { deviceId: this.id },
236083
+ meta: { error: err instanceof Error ? err.message : String(err) }
236084
+ });
236085
+ }
236086
+ });
236087
+ syncKeepAwake() {
236088
+ this.keepAwake.sync(this.active.size);
236089
+ }
235576
236090
  /** Login lock — concurrent demand events must not race the login flow. */
235577
236091
  loginPromise = null;
236092
+ /** Wall-clock ms of the last video packet the stream server produced; 0 = none yet. */
236093
+ lastVideoFlowAt = 0;
235578
236094
  /** True once we've discovered (via getBatteryInfo) that this is a battery cam. */
235579
236095
  isBattery = false;
235580
236096
  /**
@@ -236258,6 +236774,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
236258
236774
  } catch (err) {
236259
236775
  this.ctx.logger.debug("reolink getPirInfo probe failed", { meta: { error: err instanceof Error ? err.message : String(err) } });
236260
236776
  }
236777
+ if (want("powerSource") && this.isBattery) cacheUpdate.powerSourceSnapshot = { source: await readPowerSource(await this.powerSourceTarget()) };
236261
236778
  if (want("autoReboot")) try {
236262
236779
  const reboot = await api.getAutoReboot();
236263
236780
  cacheUpdate.autoRebootSnapshot = {
@@ -236610,6 +237127,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
236610
237127
  runTest: false
236611
237128
  }, this.getChannel());
236612
237129
  this.ctx.logger.info("email-push: camera auto-configure applied", { tags: { deviceId: this.id } });
237130
+ if (params.authPassword !== void 0) await this.config.setAll({ emailPassword: params.authPassword });
236613
237131
  await this.refreshCameraEmailConfig().catch(() => {});
236614
237132
  }
236615
237133
  /**
@@ -236656,6 +237174,39 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
236656
237174
  });
236657
237175
  }
236658
237176
  /**
237177
+ * Arm this camera's local event push ONCE, right after it is added (the provider's
237178
+ * `onAfterCreate`). Reuses `autoConfigureBaichuanWebhook` / `autoConfigureEmailPush` as they
237179
+ * are; the outcome is logged and recorded, and never throws: it must not block the add.
237180
+ */
237181
+ async autoConfigureEventPushOnAdd() {
237182
+ return await autoConfigureEventPushOnce({
237183
+ enabled: () => this.config.get("autoConfigureEventPush") !== false,
237184
+ recordedOutcome: () => this.config.get("eventPushAutoConfigured"),
237185
+ isEligible: () => this.isEmailPushEligible,
237186
+ isBattery: () => this.isBattery,
237187
+ method: () => this.config.get("batterySleepPushMethod") ?? "auto",
237188
+ configureWebhook: async () => await this.autoConfigureBaichuanWebhook(),
237189
+ configureEmail: async () => await this.autoConfigureEmailPush(),
237190
+ record: async (outcome) => {
237191
+ await this.config.setAll({ eventPushAutoConfigured: outcome.status === "configured" ? `configured:${outcome.mechanism}` : outcome.status });
237192
+ },
237193
+ log: (outcome) => {
237194
+ if (outcome.status === "configured") this.ctx.logger.info("event-push: auto-configured on add", {
237195
+ tags: { deviceId: this.id },
237196
+ meta: { mechanism: outcome.mechanism }
237197
+ });
237198
+ else if (outcome.status === "skipped") this.ctx.logger.info("event-push: auto-configure on add skipped", {
237199
+ tags: { deviceId: this.id },
237200
+ meta: { reason: outcome.reason }
237201
+ });
237202
+ else this.ctx.logger.warn("event-push: auto-configure on add failed", {
237203
+ tags: { deviceId: this.id },
237204
+ meta: { reason: outcome.reason }
237205
+ });
237206
+ }
237207
+ });
237208
+ }
237209
+ /**
236659
237210
  * Move this battery camera's HaCfg webhook to the addon's data-plane URL, once, on the first
236660
237211
  * Baichuan contact after the upgrade (the camera is awake: this costs no wake). Only a camera
236661
237212
  * that is armed is touched; a failure is logged and retried at the next contact.
@@ -236836,16 +237387,6 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
236836
237387
  capsTotal
236837
237388
  };
236838
237389
  });
236839
- if (this.isBattery) {
236840
- this.registerDeviceAction("read-power-source", deviceCustomAction(unknown(), ReadPowerSourceResultSchema, { kind: "mutation" }), async () => {
236841
- await this.wakeIfSleeping();
236842
- return { source: await readPowerSource(await this.powerSourceTarget()) };
236843
- });
236844
- for (const [action, mode] of POWER_SWITCH_ACTIONS) this.registerDeviceAction(action, deviceCustomAction(unknown(), SwitchPowerSourceResultSchema, { kind: "mutation" }), async () => {
236845
- await this.wakeIfSleeping();
236846
- return switchPowerSourceTo(await this.powerSourceTarget(), mode);
236847
- });
236848
- }
236849
237390
  this.registerDeviceAction("refresh-sessions", deviceCustomAction(unknown(), _void(), { kind: "mutation" }), async () => {
236850
237391
  await this.refreshSessionsSnapshot();
236851
237392
  });
@@ -237151,17 +237692,20 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
237151
237692
  next,
237152
237693
  source,
237153
237694
  lastFirstHandCommitAt: this.sleepStateChangedAt,
237154
- nowMs: Date.now()
237695
+ nowMs: Date.now(),
237696
+ videoFlowing: Date.now() - this.lastVideoFlowAt < VIDEO_FLOW_FRESH_MS,
237697
+ wired: this.config.get("deviceCache")?.powerSourceSnapshot?.source === "adapter"
237155
237698
  });
237156
237699
  if (decision.kind === "unchanged") return false;
237157
237700
  if (decision.kind === "refused") {
237158
- 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", {
237701
+ (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", {
237159
237702
  tags: { deviceId: this.id },
237160
237703
  meta: {
237161
237704
  next,
237162
237705
  source,
237163
237706
  windowMs: decision.windowMs,
237164
- sinceLastChangeMs: decision.sinceLastChangeMs
237707
+ sinceLastChangeMs: decision.sinceLastChangeMs,
237708
+ reason: decision.reason
237165
237709
  }
237166
237710
  });
237167
237711
  return false;
@@ -237395,56 +237939,6 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
237395
237939
  };
237396
237940
  }
237397
237941
  /**
237398
- * Battery-cam power-source section (General tab): read the source, switch to
237399
- * wired or back to battery. Returns `[]` for a wired-only camera. The buttons
237400
- * dispatch the `read-power-source` / `switch-to-*-power` device actions.
237401
- */
237402
- buildPowerSourceSection() {
237403
- if (!this.isBattery) return [];
237404
- const switchMessage = "Switch {outcome} · before: {before} · after: {after} · applied: {applied}";
237405
- return [{
237406
- id: "power-source",
237407
- tab: "general",
237408
- title: "Power source",
237409
- titleKey: "provider-reolink:schema.s_power-source.title",
237410
- description: "Only switch to wired power when the adapter meets the camera's spec.",
237411
- descriptionKey: "provider-reolink:schema.s_power-source.description",
237412
- columns: 1,
237413
- fields: [
237414
- {
237415
- type: "device-action-button",
237416
- key: "_readPowerSource",
237417
- label: "Power source",
237418
- labelKey: "provider-reolink:schema.s_power-source._readPowerSource.label",
237419
- buttonLabel: "Read power source",
237420
- action: "read-power-source",
237421
- variant: "default",
237422
- successMessage: "Power source: {source}"
237423
- },
237424
- {
237425
- type: "device-action-button",
237426
- key: "_switchToWiredPower",
237427
- label: "Wired power",
237428
- labelKey: "provider-reolink:schema.s_power-source._switchToWiredPower.label",
237429
- buttonLabel: "Switch to wired power",
237430
- action: "switch-to-wired-power",
237431
- variant: "default",
237432
- successMessage: switchMessage
237433
- },
237434
- {
237435
- type: "device-action-button",
237436
- key: "_switchToBatteryPower",
237437
- label: "Battery power",
237438
- labelKey: "provider-reolink:schema.s_power-source._switchToBatteryPower.label",
237439
- buttonLabel: "Switch to battery power",
237440
- action: "switch-to-battery-power",
237441
- variant: "default",
237442
- successMessage: switchMessage
237443
- }
237444
- ]
237445
- }];
237446
- }
237447
- /**
237448
237942
  * Battery-cam Email Push auto-configure section. Returns `[]` for any
237449
237943
  * camera that wouldn't benefit (wired cams keep a live socket for
237450
237944
  * native push; hub children have no independent email path). The
@@ -237635,7 +238129,8 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
237635
238129
  if (typeof fields.emailSmtpServer === "string") patch.smtpServer = fields.emailSmtpServer;
237636
238130
  if (typeof fields.emailSmtpPort === "number") patch.smtpPort = fields.emailSmtpPort;
237637
238131
  if (typeof fields.emailUserName === "string") patch.userName = fields.emailUserName;
237638
- if (typeof fields.emailPassword === "string" && fields.emailPassword.length > 0) patch.password = fields.emailPassword;
238132
+ const smtpPassword = smtpPasswordToWrite(fields.emailPassword);
238133
+ if (smtpPassword !== null) patch.password = smtpPassword;
237639
238134
  if (typeof fields.emailSsl === "boolean") patch.ssl = fields.emailSsl ? 1 : 0;
237640
238135
  if (typeof fields.emailRecipient1 === "string") patch.address1 = fields.emailRecipient1;
237641
238136
  if (typeof fields.emailRecipient2 === "string") patch.address2 = fields.emailRecipient2;
@@ -240198,7 +240693,10 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
240198
240693
  * See `native-sdp-overlay.ts`.
240199
240694
  */
240200
240695
  withLiveNativeSdp(descriptors) {
240201
- return overlayLiveNativeRfc4571Sdp(descriptors, (camStreamId) => {
240696
+ return overlayLiveNativeRfc4571Sdp(withSessionLimit(descriptors, {
240697
+ isHubChild: this.isHubChild(),
240698
+ isBattery: this.isBattery
240699
+ }), (camStreamId) => {
240202
240700
  const server = this.active.get(camStreamId)?.server;
240203
240701
  if (!server?.server?.listening) return null;
240204
240702
  return {
@@ -240500,6 +240998,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
240500
240998
  ...entry.fps !== void 0 ? { fps: entry.fps } : {},
240501
240999
  ...entry.codec !== void 0 ? { codec: entry.codec } : {},
240502
241000
  ...entry.metadata ? { metadata: entry.metadata } : {},
241001
+ ...entry.maxSessionMs !== void 0 ? { maxSessionMs: entry.maxSessionMs } : {},
240503
241002
  deviceFeatures: entry.deviceFeatures ?? [...this.features],
240504
241003
  autoEligible: entry.autoEligible ?? true
240505
241004
  });
@@ -240579,6 +241078,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
240579
241078
  this.stopBatteryUpdatePolling();
240580
241079
  this.stopAlignAuxPolling();
240581
241080
  this.stopWatchdogs();
241081
+ this.keepAwake.stop();
240582
241082
  this.detachFromHubSession();
240583
241083
  if (this.reconnectTimer) {
240584
241084
  clearTimeout(this.reconnectTimer);
@@ -240624,6 +241124,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
240624
241124
  await existing.server.close("recreate");
240625
241125
  } catch {}
240626
241126
  this.active.delete(camStreamId);
241127
+ this.syncKeepAwake();
240627
241128
  }
240628
241129
  let api;
240629
241130
  try {
@@ -240671,9 +241172,18 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
240671
241172
  server
240672
241173
  };
240673
241174
  this.active.set(camStreamId, entry);
241175
+ this.syncKeepAwake();
241176
+ const stopVideoWatch = watchVideoFlow(server.videoStream, () => {
241177
+ this.lastVideoFlowAt = Date.now();
241178
+ }, () => this.ctx.logger.warn("rfc4571: unknown video stream kind — video flow not observed", { tags: {
241179
+ deviceId: this.id,
241180
+ camStreamId
241181
+ } }));
240674
241182
  server.server.once("close", () => {
241183
+ stopVideoWatch();
240675
241184
  if (this.active.get(camStreamId)?.server === server) {
240676
241185
  this.active.delete(camStreamId);
241186
+ this.syncKeepAwake();
240677
241187
  this.ctx.logger.debug("rfc4571: server closed — evicting cache entry", { tags: {
240678
241188
  deviceId: this.id,
240679
241189
  camStreamId
@@ -240728,6 +241238,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
240728
241238
  async closeActiveStreams(reason) {
240729
241239
  const entries = [...this.active.values()];
240730
241240
  this.active.clear();
241241
+ this.keepAwake.stop();
240731
241242
  if (entries.length === 0) return;
240732
241243
  this.ctx.logger.debug("Closing active RFC 4571 servers", {
240733
241244
  tags: { deviceId: this.id },
@@ -241411,6 +241922,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
241411
241922
  this.stopWatchdogs();
241412
241923
  const entries = [...this.active.values()];
241413
241924
  this.active.clear();
241925
+ this.keepAwake.stop();
241414
241926
  for (const entry of entries) try {
241415
241927
  await entry.server.close("disconnect-all");
241416
241928
  } catch {}
@@ -242356,7 +242868,10 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
242356
242868
  }),
242357
242869
  ...this.buildSessionsTabSections(),
242358
242870
  ...this.buildEmailPushSection(),
242359
- ...this.buildPowerSourceSection(),
242871
+ ...buildPowerSourceSettingsSection({
242872
+ isBattery: this.isBattery,
242873
+ source: cache?.powerSourceSnapshot?.source
242874
+ }),
242360
242875
  ...this.buildEmailTabSections(),
242361
242876
  ...buildClipRefreshDeviceSection({
242362
242877
  isHubChild: this.isHubChild(),
@@ -242385,7 +242900,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
242385
242900
  emailSmtpServer: emailSnap?.smtpServer ?? "",
242386
242901
  emailSmtpPort: emailSnap?.smtpPort ?? 587,
242387
242902
  emailUserName: emailSnap?.userName ?? "",
242388
- emailPassword: "",
242903
+ emailPassword: this.config.get("emailPassword"),
242389
242904
  emailSsl: emailSnap?.ssl ?? false,
242390
242905
  emailRecipient1: emailSnap?.recipients?.[0] ?? "",
242391
242906
  emailRecipient2: emailSnap?.recipients?.[1] ?? "",
@@ -242452,6 +242967,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
242452
242967
  audioNoiseLevel: this.config.get("audioNoiseLevel") ?? (cache?.audioNoiseSnapshot?.enabled ? cache.audioNoiseSnapshot?.level ?? 1 : 0),
242453
242968
  autoFocusEnabled: this.config.get("autoFocusEnabled") ?? cache?.autoFocusSnapshot?.enabled ?? true,
242454
242969
  pirReduceFalseAlarm: this.config.get("pirReduceFalseAlarm") ?? cache?.pirSnapshot?.reduceFalseAlarm ?? false,
242970
+ ...cache?.powerSourceSnapshot !== void 0 ? { [POWER_SOURCE_SETTING_KEY]: cache.powerSourceSnapshot.source } : {},
242455
242971
  gop: this.config.get("gop") ?? cache?.encSnapshot?.mainStream?.gop ?? 4,
242456
242972
  autoRebootEnabled: this.config.get("autoRebootEnabled") ?? cache?.autoRebootSnapshot?.enabled ?? false,
242457
242973
  autoRebootWeekDay: this.config.get("autoRebootWeekDay") ?? cache?.autoRebootSnapshot?.weekDay ?? "everyday",
@@ -242481,8 +242997,8 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
242481
242997
  }
242482
242998
  async applySettingsPatch(patch) {
242483
242999
  if (this.isHubChild()) this.refuseHubChildPatch(patch);
242484
- const { emailSmtpServer, emailSmtpPort, emailUserName, emailPassword, emailSsl, emailRecipient1, emailRecipient2, emailRecipient3, emailSendNickname, emailScheduleEnabled, osdChannelEnabled, osdChannelName, osdChannelPosition, osdTimeEnabled, osdTimePosition, osdWatermark, hubName: _hubName, ...rest } = patch;
242485
- 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 } });
243000
+ 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;
243001
+ 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 } });
242486
243002
  const emailFields = {
242487
243003
  emailSmtpServer,
242488
243004
  emailSmtpPort,
@@ -242495,12 +243011,18 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
242495
243011
  emailSendNickname,
242496
243012
  emailScheduleEnabled
242497
243013
  };
242498
- if (Object.values(emailFields).some((v) => v !== void 0)) await this.applyEmailConfigPatch(emailFields).catch((err) => {
242499
- this.ctx.logger.warn("email config write failed", {
242500
- tags: { deviceId: this.id },
242501
- meta: { error: err instanceof Error ? err.message : String(err) }
243014
+ if (Object.values(emailFields).some((v) => v !== void 0)) {
243015
+ let written = true;
243016
+ await this.applyEmailConfigPatch(emailFields).catch((err) => {
243017
+ written = false;
243018
+ this.ctx.logger.warn("email config write failed", {
243019
+ tags: { deviceId: this.id },
243020
+ meta: { error: err instanceof Error ? err.message : String(err) }
243021
+ });
242502
243022
  });
242503
- });
243023
+ const stored = smtpPasswordToWrite(emailPassword);
243024
+ if (written && stored !== null) await this.config.setAll({ emailPassword: stored });
243025
+ }
242504
243026
  const osdPatch = buildOsdPatch({
242505
243027
  osdChannelEnabled,
242506
243028
  osdChannelName,
@@ -242517,6 +243039,10 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
242517
243039
  osdTimePosition,
242518
243040
  osdWatermark
242519
243041
  ].some((v) => v !== void 0);
243042
+ if (powerSource !== void 0) {
243043
+ await applyPowerSourceSetting(await this.powerSourceTarget(), powerSource);
243044
+ await this.refreshParentSettingsSnapshot(new Set(["powerSource"]), "post-write");
243045
+ }
242520
243046
  if (Object.keys(rest).length === 0 && !hasOsdPatch) return;
242521
243047
  if (Object.keys(rest).length > 0) await this.config.setAll(rest);
242522
243048
  const typedPatch = patch;
@@ -242951,6 +243477,11 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
242951
243477
  isSleeping() {
242952
243478
  return this.sleeping;
242953
243479
  }
243480
+ /** Implements `ReolinkAccessoryHost.wakeForWrite`: an accessory's operator
243481
+ * write (PIR, ...) wakes a sleeping battery camera first. */
243482
+ wakeForWrite() {
243483
+ return this.wakeIfSleeping();
243484
+ }
242954
243485
  async ensureApi() {
242955
243486
  if (this.isHubChild()) {
242956
243487
  const session = this.hubSession();
@@ -243826,6 +244357,21 @@ function buildCreationFormSchema() {
243826
244357
  }
243827
244358
  }
243828
244359
  ]
244360
+ },
244361
+ {
244362
+ id: "events",
244363
+ title: "Events",
244364
+ titleKey: "provider-reolink:creation.s_events.title",
244365
+ columns: 1,
244366
+ fields: [{
244367
+ type: "boolean",
244368
+ key: "autoConfigureEventPush",
244369
+ label: "Auto-configure event push on add",
244370
+ labelKey: "provider-reolink:creation.s_events.autoConfigureEventPush.label",
244371
+ description: "Once, right after the camera is added, set up its local push (webhook or camera mailbox) so motion and AI events reach CamStack.",
244372
+ descriptionKey: "provider-reolink:creation.s_events.autoConfigureEventPush.description",
244373
+ default: true
244374
+ }]
243829
244375
  }
243830
244376
  ] };
243831
244377
  }
@@ -243975,6 +244521,8 @@ var EmailPushBridge = class {
243975
244521
  /** The last failure that was reported, so a mailbox provider that stays away is said once. */
243976
244522
  lastFailure = null;
243977
244523
  chain = Promise.resolve();
244524
+ /** The integrations whose empty link this process filled (only those are released). */
244525
+ filled = /* @__PURE__ */ new Set();
243978
244526
  constructor(deps) {
243979
244527
  this.deps = deps;
243980
244528
  }
@@ -244045,43 +244593,104 @@ var EmailPushBridge = class {
244045
244593
  const recipients = this.recipients();
244046
244594
  if (recipients.length === 0) {
244047
244595
  if (this.brokerId !== null && this.subscriptionId !== null) await this.deps.port.unsubscribe(this.brokerId, this.subscriptionId);
244048
- if (this.brokerId !== null) await this.syncLinks(this.brokerId, /* @__PURE__ */ new Set());
244596
+ if (this.brokerId !== null) await this.syncLinks(this.brokerId, await this.tryDefaultId(), false);
244049
244597
  this.subscriptionId = null;
244050
244598
  this.declared = null;
244051
244599
  return;
244052
244600
  }
244053
- const owners = this.linkOwners();
244054
- const key = `${recipients.join(",")}|${[...owners].sort().join(",")}`;
244601
+ const { defaultId, complete } = await this.resolveDefault();
244602
+ const picked = await this.pickedMailbox(defaultId);
244603
+ const key = `${recipients.join(",")}|${defaultId ?? ""}|${picked ?? this.brokerId ?? ""}`;
244055
244604
  if (!force && this.declared === key && this.subscriptionId !== null) return;
244056
- const brokerId = await this.ensureMailbox();
244605
+ const brokerId = picked ?? await this.ensureMailbox();
244606
+ if (this.brokerId !== null && this.brokerId !== brokerId && this.subscriptionId !== null) {
244607
+ await this.deps.port.unsubscribe(this.brokerId, this.subscriptionId);
244608
+ this.subscriptionId = null;
244609
+ }
244057
244610
  await this.seedBaseline(brokerId);
244058
244611
  const { subscriptionId } = await this.deps.port.subscribe(brokerId, recipients);
244059
244612
  this.brokerId = brokerId;
244060
244613
  this.subscriptionId = subscriptionId;
244061
- this.declared = await this.syncLinks(brokerId, owners) ? key : null;
244614
+ const linked = await this.syncLinks(brokerId, defaultId, true);
244615
+ this.declared = linked && complete ? `${recipients.join(",")}|${defaultId ?? ""}|${brokerId}` : null;
244062
244616
  await this.reconcile();
244063
244617
  }
244064
- /** The integrations whose standalone cameras mail the mailbox: they link to it. */
244065
- linkOwners() {
244066
- const owners = /* @__PURE__ */ new Set();
244067
- for (const cam of this.deps.listCameras()) if (cam.isEmailPushEligible && cam.integrationId !== null) owners.add(cam.integrationId);
244068
- return owners;
244618
+ /**
244619
+ * The default integration holds the mailbox link for every email-push camera (a hub child's
244620
+ * integration carries none). `complete` is false when it could not be resolved: the caller
244621
+ * retries at the next sync.
244622
+ */
244623
+ async resolveDefault() {
244624
+ const cam = this.deps.listCameras().find((c) => c.isEmailPushEligible);
244625
+ const tags = cam === void 0 ? {} : { tags: { deviceId: cam.id } };
244626
+ let defaultId = null;
244627
+ try {
244628
+ defaultId = await this.deps.defaultIntegrationId();
244629
+ } catch (err) {
244630
+ this.deps.logger.warn("email-push: the default integration could not be read", {
244631
+ ...tags,
244632
+ meta: { error: errMsg(err) }
244633
+ });
244634
+ return {
244635
+ defaultId: null,
244636
+ complete: false
244637
+ };
244638
+ }
244639
+ if (defaultId === null) {
244640
+ 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);
244641
+ return {
244642
+ defaultId: null,
244643
+ complete: false
244644
+ };
244645
+ }
244646
+ return {
244647
+ defaultId,
244648
+ complete: true
244649
+ };
244650
+ }
244651
+ async tryDefaultId() {
244652
+ try {
244653
+ return await this.deps.defaultIntegrationId();
244654
+ } catch {
244655
+ return null;
244656
+ }
244069
244657
  }
244070
244658
  /**
244071
- * Make the `mailboxId` links say who uses the mailbox: `owners` link to it, no other
244072
- * integration does. Idempotent, so an install whose mailbox already exists is filled from it
244073
- * (the mailbox is re-adopted by `ensureMailbox`) with nothing stored beforehand. False when the
244074
- * links could not be written: the caller retries at the next sync.
244659
+ * The mailbox the operator picked on the default integration, or null while none is picked.
244660
+ * A pick that no mailbox answers to throws: the bridge never swaps it for another one.
244075
244661
  */
244076
- async syncLinks(brokerId, owners) {
244662
+ async pickedMailbox(defaultId) {
244663
+ if (defaultId === null) return null;
244664
+ const row = (await this.deps.links.list()).find((r) => r.id === defaultId);
244665
+ if (row === void 0 || row.mailboxId === "") return null;
244666
+ 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`);
244667
+ return row.mailboxId;
244668
+ }
244669
+ /** The mailbox a camera is pointed at: the operator's pick, else the one this addon adopts or creates. */
244670
+ async resolveMailbox() {
244671
+ return await this.pickedMailbox(await this.tryDefaultId()) ?? await this.ensureMailbox();
244672
+ }
244673
+ /**
244674
+ * Make the `mailboxId` link of the DEFAULT integration say it uses the mailbox. It is filled only
244675
+ * while empty (a pick of the operator is never overwritten) and released only if this process
244676
+ * filled it. A hub integration carries no link: a stale one is cleared. With no default
244677
+ * resolved nothing is touched. False when the links could not be written.
244678
+ */
244679
+ async syncLinks(brokerId, defaultId, inUse) {
244680
+ if (defaultId === null) return true;
244077
244681
  try {
244078
244682
  const rows = await this.deps.links.list();
244079
- for (const row of rows) {
244080
- const wanted = owners.has(row.id) ? brokerId : "";
244081
- if (row.mailboxId !== wanted) await this.deps.links.set(row.id, wanted);
244082
- }
244083
- 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: {
244084
- integrationId: owner,
244683
+ for (const row of rows) if (row.id !== defaultId) {
244684
+ if (row.mailboxId !== "") await this.deps.links.set(row.id, "");
244685
+ } else if (inUse && row.mailboxId === "") {
244686
+ await this.deps.links.set(row.id, brokerId);
244687
+ this.filled.add(row.id);
244688
+ } else if (!inUse && this.filled.has(row.id) && row.mailboxId === brokerId) {
244689
+ await this.deps.links.set(row.id, "");
244690
+ this.filled.delete(row.id);
244691
+ }
244692
+ 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: {
244693
+ integrationId: defaultId,
244085
244694
  brokerId
244086
244695
  } });
244087
244696
  return true;
@@ -244220,7 +244829,7 @@ var EmailPushBridge = class {
244220
244829
  */
244221
244830
  async buildCameraSetupParams(cam) {
244222
244831
  if (!cam.isEmailPushEligible) return null;
244223
- const brokerId = await this.ensureMailbox();
244832
+ const brokerId = await this.resolveMailbox();
244224
244833
  const parsed = SmtpInboundConfigSchema.safeParse(await this.deps.port.getBrokerConfig(brokerId));
244225
244834
  if (!parsed.success) throw new Error("The camera mailbox answered a configuration this build cannot read");
244226
244835
  const config = parsed.data;
@@ -244242,6 +244851,60 @@ function pickMailbox(list) {
244242
244851
  return list.find((b) => b.id === "smtp-inbound-default")?.id ?? list[0]?.id ?? null;
244243
244852
  }
244244
244853
  //#endregion
244854
+ //#region src/email-push-removal-hook.ts
244855
+ /**
244856
+ * A removed camera leaves its `cam-<stableId>` recipient in the mailbox (D865). The addon holds
244857
+ * no per-device DATA for the intake (the mailbox is owned by the mail addon), so removal only
244858
+ * redeclares the recipient set without the camera. Driven by the tombstone, never by absence.
244859
+ */
244860
+ function createEmailPushRemovalHook(deps) {
244861
+ return {
244862
+ onDeviceRemoved: async () => {
244863
+ await deps.resync();
244864
+ return { counts: { "mailbox-recipients": 0 } };
244865
+ },
244866
+ listDeviceData: async () => []
244867
+ };
244868
+ }
244869
+ var LEGACY_PREFIX = "/webhook/";
244870
+ async function startLegacyWebhookIntake(deps) {
244871
+ const warned = /* @__PURE__ */ new Set();
244872
+ const server = (0, node_http.createServer)((req, res) => {
244873
+ const url = req.url ?? "";
244874
+ if (!url.startsWith(LEGACY_PREFIX)) {
244875
+ res.writeHead(404).end();
244876
+ return;
244877
+ }
244878
+ const rest = url.slice(8);
244879
+ req.url = rest;
244880
+ const id = decodeURIComponent(rest.replace(/^\//, "").split("?")[0] ?? "");
244881
+ const camera = deps.listCameras().find((c) => c.stableId === id);
244882
+ if (camera !== void 0 && !warned.has(id)) {
244883
+ warned.add(id);
244884
+ deps.logger.warn("legacy webhook port used — camera will be re-pointed", {
244885
+ tags: { deviceId: camera.id },
244886
+ meta: { port: deps.port ?? 9081 }
244887
+ });
244888
+ }
244889
+ Promise.resolve(deps.handler(req, res)).catch((err) => {
244890
+ deps.logger.error("legacy webhook intake failed", { meta: { error: err instanceof Error ? err.message : String(err) } });
244891
+ if (!res.headersSent) res.writeHead(500);
244892
+ res.end();
244893
+ });
244894
+ });
244895
+ await new Promise((resolve, reject) => {
244896
+ server.once("error", reject);
244897
+ server.listen(deps.port ?? 9081, "0.0.0.0", () => {
244898
+ server.off("error", reject);
244899
+ resolve();
244900
+ });
244901
+ });
244902
+ return {
244903
+ server,
244904
+ close: () => new Promise((resolve) => server.close(() => resolve()))
244905
+ };
244906
+ }
244907
+ //#endregion
244245
244908
  //#region src/reolink-connection-test.ts
244246
244909
  /**
244247
244910
  * The Reolink NVR / Home Hub connection test (planning#581): log in over Baichuan with the
@@ -244349,6 +245012,28 @@ var reolinkConnectionsEntryKind = defineEntryKind("connections", {
244349
245012
  }),
244350
245013
  writeTrigger: "an operator adds, edits or removes a Reolink integration"
244351
245014
  });
245015
+ /** The kind of the default integration (standalone cameras): a name and the mailbox link, no Test. */
245016
+ var REOLINK_DEFAULT_KIND = "default";
245017
+ /** The kind of an NVR / Home Hub integration: its connection, with a Test. */
245018
+ var REOLINK_HUB_KIND = "connection";
245019
+ /** The form of the default integration: which camera mailbox its standalone cameras use. */
245020
+ function buildDefaultInstanceSchema() {
245021
+ return { sections: [{
245022
+ id: "mailbox",
245023
+ title: "Camera mailbox",
245024
+ titleKey: "provider-reolink:connection.s_mailbox.title",
245025
+ description: "The mailbox the standalone cameras send their email push to.",
245026
+ descriptionKey: "provider-reolink:connection.s_mailbox.description",
245027
+ columns: 1,
245028
+ fields: [{
245029
+ ...linkFieldDescriptor(MAILBOX_LINK_FIELD, SMTP_MAILBOX_LINK, {
245030
+ label: "Camera mailbox",
245031
+ required: false
245032
+ }),
245033
+ labelKey: "provider-reolink:connection.s_mailbox.mailboxId.label"
245034
+ }]
245035
+ }] };
245036
+ }
244352
245037
  /** Every kind this addon declares, keyed by its name. */
244353
245038
  var reolinkRecordKinds = { connections: reolinkConnectionsEntryKind };
244354
245039
  /**
@@ -244455,12 +245140,26 @@ function buildReolinkInstances(records, deps) {
244455
245140
  kind: "connection",
244456
245141
  canTest: true,
244457
245142
  kinds: [{
244458
- id: "connection",
244459
- label: "Reolink",
245143
+ id: REOLINK_DEFAULT_KIND,
245144
+ label: "Reolink standalone cameras",
244460
245145
  functionCap: "device-provider",
244461
- role: "devices"
245146
+ role: "devices",
245147
+ canTest: false,
245148
+ creatable: false
245149
+ }, {
245150
+ id: REOLINK_HUB_KIND,
245151
+ label: "Reolink NVR / Home Hub",
245152
+ functionCap: "device-provider",
245153
+ role: "devices",
245154
+ canTest: true
245155
+ }],
245156
+ links: [{
245157
+ kind: REOLINK_DEFAULT_KIND,
245158
+ field: MAILBOX_LINK_FIELD,
245159
+ to: SMTP_MAILBOX_LINK
244462
245160
  }]
244463
245161
  },
245162
+ kindOf: () => REOLINK_HUB_KIND,
244464
245163
  formSchema: () => buildHubInstanceSchema(),
244465
245164
  initialBody: (name) => ({ name }),
244466
245165
  configured: (body) => (body.host ?? "").length === 0 || (body.password ?? "").length > 0,
@@ -244474,10 +245173,15 @@ function buildReolinkInstances(records, deps) {
244474
245173
  */
244475
245174
  function reolinkInstancesProvider(instances, deps) {
244476
245175
  const base = instances.toProvider();
244477
- const withAddDevice = async (instance) => ({
244478
- ...instance,
244479
- addDevice: await integrationIsHubCached(instances, deps.evidenceCache, instance.id) ? "children" : "scan"
244480
- });
245176
+ const withAddDevice = async (instance) => {
245177
+ const isHub = await integrationIsHubCached(instances, deps.evidenceCache, instance.id);
245178
+ const known = deps.evidenceCache.get(instance.id) !== null;
245179
+ return {
245180
+ ...instance,
245181
+ kind: known && !isHub ? REOLINK_DEFAULT_KIND : REOLINK_HUB_KIND,
245182
+ addDevice: isHub ? "children" : "scan"
245183
+ };
245184
+ };
244481
245185
  return {
244482
245186
  ...base,
244483
245187
  listInstances: async (input) => Promise.all((await base.listInstances(input)).map(withAddDevice)),
@@ -244493,7 +245197,7 @@ function reolinkInstancesProvider(instances, deps) {
244493
245197
  originStableId: evidence.originStableId,
244494
245198
  info: evidence.info,
244495
245199
  settings: body === null ? {} : hubSettingsOf(body)
244496
- }) || body === null ? buildHubInstanceSchema() : { sections: [] };
245200
+ }) || body === null ? buildHubInstanceSchema() : buildDefaultInstanceSchema();
244497
245201
  }
244498
245202
  };
244499
245203
  }
@@ -244545,60 +245249,6 @@ function mailboxLinkStoreOver(records) {
244545
245249
  };
244546
245250
  }
244547
245251
  //#endregion
244548
- //#region src/email-push-removal-hook.ts
244549
- /**
244550
- * A removed camera leaves its `cam-<stableId>` recipient in the mailbox (D865). The addon holds
244551
- * no per-device DATA for the intake (the mailbox is owned by the mail addon), so removal only
244552
- * redeclares the recipient set without the camera. Driven by the tombstone, never by absence.
244553
- */
244554
- function createEmailPushRemovalHook(deps) {
244555
- return {
244556
- onDeviceRemoved: async () => {
244557
- await deps.resync();
244558
- return { counts: { "mailbox-recipients": 0 } };
244559
- },
244560
- listDeviceData: async () => []
244561
- };
244562
- }
244563
- var LEGACY_PREFIX = "/webhook/";
244564
- async function startLegacyWebhookIntake(deps) {
244565
- const warned = /* @__PURE__ */ new Set();
244566
- const server = (0, node_http.createServer)((req, res) => {
244567
- const url = req.url ?? "";
244568
- if (!url.startsWith(LEGACY_PREFIX)) {
244569
- res.writeHead(404).end();
244570
- return;
244571
- }
244572
- const rest = url.slice(8);
244573
- req.url = rest;
244574
- const id = decodeURIComponent(rest.replace(/^\//, "").split("?")[0] ?? "");
244575
- const camera = deps.listCameras().find((c) => c.stableId === id);
244576
- if (camera !== void 0 && !warned.has(id)) {
244577
- warned.add(id);
244578
- deps.logger.warn("legacy webhook port used — camera will be re-pointed", {
244579
- tags: { deviceId: camera.id },
244580
- meta: { port: deps.port ?? 9081 }
244581
- });
244582
- }
244583
- Promise.resolve(deps.handler(req, res)).catch((err) => {
244584
- deps.logger.error("legacy webhook intake failed", { meta: { error: err instanceof Error ? err.message : String(err) } });
244585
- if (!res.headersSent) res.writeHead(500);
244586
- res.end();
244587
- });
244588
- });
244589
- await new Promise((resolve, reject) => {
244590
- server.once("error", reject);
244591
- server.listen(deps.port ?? 9081, "0.0.0.0", () => {
244592
- server.off("error", reject);
244593
- resolve();
244594
- });
244595
- });
244596
- return {
244597
- server,
244598
- close: () => new Promise((resolve) => server.close(() => resolve()))
244599
- };
244600
- }
244601
- //#endregion
244602
245252
  //#region src/migrations/drop-webhook-intake-settings.ts
244603
245253
  /**
244604
245254
  * The camera webhook is a plane of the addon's HTTP data plane, not a private listener
@@ -244819,6 +245469,14 @@ var REOLINK_MIGRATIONS = [{
244819
245469
  },
244820
245470
  plan: planDropWebhookIntakeSettings
244821
245471
  }];
245472
+ /** The date of the device claim (D1007). */
245473
+ var CLAIM_DEVICES_DATE = "2026-11-04";
245474
+ /**
245475
+ * Every persisted camera that names no integration is claimed to the addon's default one. The
245476
+ * integration a hub migration created is never the default, so it is not eligible. The integration
245477
+ * settings themselves stay where they are until this addon's own wave moves them.
245478
+ */
245479
+ var REOLINK_CLAIM_ELIGIBLE = (integration) => integration.info[MIGRATED_FROM_HUB_KEY] === void 0;
244822
245480
  /**
244823
245481
  * The integration wave (D1007) in declaration order, which must follow `seq`: the device claim
244824
245482
  * shipped first (seq 3) and the rows move follows it (seq 4). The engine refuses the whole
@@ -244826,10 +245484,10 @@ var REOLINK_MIGRATIONS = [{
244826
245484
  */
244827
245485
  var REOLINK_INTEGRATION_MIGRATIONS = [claimDevicesMigration({
244828
245486
  addonId: "provider-reolink",
244829
- date: "2026-11-04",
245487
+ date: CLAIM_DEVICES_DATE,
244830
245488
  seq: 3,
244831
245489
  dependsOn: [],
244832
- eligible: (integration) => integration.info[MIGRATED_FROM_HUB_KEY] === void 0
245490
+ eligible: REOLINK_CLAIM_ELIGIBLE
244833
245491
  }), REOLINK_ROWS_TO_RECORD_MIGRATION];
244834
245492
  //#endregion
244835
245493
  //#region src/reolink-adoption-provider.ts
@@ -245681,12 +246339,24 @@ var ReolinkProviderAddon = class extends BaseDeviceProvider {
245681
246339
  if (records === void 0) throw new Error("provider-reolink: ctx.records is required (hub-only addon)");
245682
246340
  return records;
245683
246341
  }
246342
+ /**
246343
+ * The registry id of the default integration (standalone cameras): the lowest-numbered one this
246344
+ * addon owns that no hub migration created, the same rule as the device claim (D1007).
246345
+ */
246346
+ async resolveDefaultIntegrationId() {
246347
+ return defaultIntegrationOf((await this.ctx.api.integrations.list.query()).filter((i) => i.addonId === this.ctx.id).map((i) => ({
246348
+ id: i.id,
246349
+ name: i.name,
246350
+ info: { ...i.info }
246351
+ })), REOLINK_CLAIM_ELIGIBLE)?.id ?? null;
246352
+ }
245684
246353
  /** The camera mailbox bridge, built once. */
245685
246354
  ensureEmailBridge() {
245686
246355
  this.emailBridge ??= new EmailPushBridge({
245687
246356
  port: createBrokerPort(this.ctx.api),
245688
246357
  links: mailboxLinkStoreOver(this.requireRecords()),
245689
246358
  listCameras: () => this.listReolinkCameras(),
246359
+ defaultIntegrationId: () => this.resolveDefaultIntegrationId(),
245690
246360
  logger: this.ctx.logger.child("email-push"),
245691
246361
  pending: {
245692
246362
  read: () => this.readPendingMailbox(),
@@ -246507,6 +247177,12 @@ var ReolinkProviderAddon = class extends BaseDeviceProvider {
246507
247177
  const emailBridge = this.ensureEmailBridge();
246508
247178
  device.setEmailPushParamsResolver(() => emailBridge.buildCameraSetupParams(device));
246509
247179
  device.setBaichuanWebhookParamsResolver(() => this.buildWebhookParams(device));
247180
+ device.autoConfigureEventPushOnAdd().catch((err) => {
247181
+ ctx.logger.warn("event-push: auto-configure on add threw", {
247182
+ tags: { deviceId: device.id },
247183
+ meta: { error: err instanceof Error ? err.message : String(err) }
247184
+ });
247185
+ });
246510
247186
  }
246511
247187
  ctx.api?.pipelineOrchestrator?.applyDeviceSettingsPatch?.mutate({
246512
247188
  deviceId: device.id,