@camstack/addon-provider-homeassistant 1.2.72 → 1.2.74

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
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_dist = require("./dist-DkMiMzBV.js");
2
+ const require_dist = require("./dist-Ccw8gsKE.js");
3
3
  let node_crypto = require("node:crypto");
4
4
  let node_zlib = require("node:zlib");
5
5
  //#region src/ha-device-source.ts
package/dist/addon.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { $ as presenceCapability, A as controlCapability, At as EventCategory, B as humiditySensorCapability, C as buildAddonRouteProvider, Ct as number, D as colorCapability, Dt as union, E as climateControlCapability, Et as string, F as eventEmitterCapability, G as motionCapability, H as lawnMowerControlCapability, I as fanControlCapability, J as notifierCapability, K as normalizeUnit, L as floodCapability, M as deviceAdoptionCapability, O as connectivityCapability, Ot as unknown, P as enumSensorCapability, Q as prepareNotification, R as gasCapability, S as brokerCapability, St as literal, T as carbonMonoxideCapability, Tt as record, U as lockControlCapability, V as imageCapability, W as mediaPlayerCapability, Y as numericSensorCapability, Z as powerMeterCapability, _ as automationControlCapability, _t as createEvent, at as temperatureSensorCapability, b as binaryCapability, bt as array, ct as valveCapability, d as TargetSchema, dt as weatherCapability, et as pressureSensorCapability, f as accessoriesCapability, ft as errMsg, g as ambientLightSensorCapability, gt as DeviceType, h as alarmPanelCapability, ht as DeviceRole, it as tamperCapability, j as coverCapability, k as contactCapability, kt as url, lt as vibrationCapability, m as airQualitySensorCapability, mt as DeviceFeature, n as BaseDevice, nt as smokeCapability, ot as updateCapability, p as addonRoutesCapability, q as notificationOutputCapability, r as BaseDeviceProvider, rt as switchCapability, s as EnumSensorDateTimeFormatSchema, st as vacuumControlCapability, tt as scriptRunnerCapability, ut as waterHeaterCapability, v as batteryCapability, w as buttonCapability, wt as object, x as brightnessCapability, xt as discriminatedUnion, y as bestLocationMatch, yt as _enum, z as humidifierCapability } from "./dist-CwsG7FxA.mjs";
1
+ import { $ as presenceCapability, A as controlCapability, At as EventCategory, B as humiditySensorCapability, C as buildAddonRouteProvider, Ct as number, D as colorCapability, Dt as union, E as climateControlCapability, Et as string, F as eventEmitterCapability, G as motionCapability, H as lawnMowerControlCapability, I as fanControlCapability, J as notifierCapability, K as normalizeUnit, L as floodCapability, M as deviceAdoptionCapability, O as connectivityCapability, Ot as unknown, P as enumSensorCapability, Q as prepareNotification, R as gasCapability, S as brokerCapability, St as literal, T as carbonMonoxideCapability, Tt as record, U as lockControlCapability, V as imageCapability, W as mediaPlayerCapability, Y as numericSensorCapability, Z as powerMeterCapability, _ as automationControlCapability, _t as createEvent, at as temperatureSensorCapability, b as binaryCapability, bt as array, ct as valveCapability, d as TargetSchema, dt as weatherCapability, et as pressureSensorCapability, f as accessoriesCapability, ft as errMsg, g as ambientLightSensorCapability, gt as DeviceType, h as alarmPanelCapability, ht as DeviceRole, it as tamperCapability, j as coverCapability, k as contactCapability, kt as url, lt as vibrationCapability, m as airQualitySensorCapability, mt as DeviceFeature, n as BaseDevice, nt as smokeCapability, ot as updateCapability, p as addonRoutesCapability, q as notificationOutputCapability, r as BaseDeviceProvider, rt as switchCapability, s as EnumSensorDateTimeFormatSchema, st as vacuumControlCapability, tt as scriptRunnerCapability, ut as waterHeaterCapability, v as batteryCapability, w as buttonCapability, wt as object, x as brightnessCapability, xt as discriminatedUnion, y as bestLocationMatch, yt as _enum, z as humidifierCapability } from "./dist-CrzCO0F_.mjs";
2
2
  import { randomUUID } from "node:crypto";
3
3
  import { brotliCompressSync, deflateSync, gzipSync } from "node:zlib";
4
4
  //#region src/ha-device-source.ts
@@ -10749,6 +10749,89 @@ var LocationStatSchema = object({
10749
10749
  fileCount: number(),
10750
10750
  present: boolean()
10751
10751
  });
10752
+ /** Lifecycle of a backup run. Terminal states: succeeded / failed / cancelled. */
10753
+ var BackupRunStateSchema = _enum([
10754
+ "queued",
10755
+ "running",
10756
+ "succeeded",
10757
+ "failed",
10758
+ "cancelled"
10759
+ ]);
10760
+ /**
10761
+ * Where a running backup currently is. `queued` before it starts,
10762
+ * `building` while the tar.gz is being staged, `uploading` during the
10763
+ * per-destination fan-out, `done` once terminal.
10764
+ */
10765
+ var BackupRunPhaseSchema = _enum([
10766
+ "queued",
10767
+ "building",
10768
+ "uploading",
10769
+ "done"
10770
+ ]);
10771
+ /**
10772
+ * Observable state of one backup run — readable WHILE it runs via
10773
+ * `backup.listRuns`. This is what makes the execution queue and
10774
+ * `backup.cancel` usable: the 2026-09-04 incident (two concurrent
10775
+ * multi-GB builds, staging 5.1 GB → 18 GB, load 62) was only
10776
+ * diagnosable with `du` because nothing reported that runs existed or
10777
+ * how large the staged archive had grown.
10778
+ */
10779
+ var BackupRunSchema = object({
10780
+ /** Stable run id — the handle `backup.cancel` takes. */
10781
+ id: string(),
10782
+ state: BackupRunStateSchema,
10783
+ phase: BackupRunPhaseSchema,
10784
+ /**
10785
+ * Resolved destination location ids. Empty while queued (targets are
10786
+ * resolved when the run starts, against the then-current policies).
10787
+ */
10788
+ destinationIds: array(string()).readonly(),
10789
+ label: string().optional(),
10790
+ /** ms-epoch when the run was submitted (trigger call / schedule fire). */
10791
+ requestedAt: number(),
10792
+ /** ms-epoch when the run left the queue and started building. */
10793
+ startedAt: number().optional(),
10794
+ /** ms-epoch when the run reached a terminal state. */
10795
+ finishedAt: number().optional(),
10796
+ /** Compressed bytes of the staging archive written so far. */
10797
+ stagedBytes: number(),
10798
+ /** Final staged archive size, once the build phase completes. */
10799
+ archiveSizeBytes: number().optional(),
10800
+ /** Bytes pushed to the destination currently uploading. */
10801
+ uploadedBytes: number(),
10802
+ /** Destinations where the archive fully landed (uploaded + indexed). */
10803
+ completedDestinationIds: array(string()).readonly(),
10804
+ /** Destinations that failed during the fan-out. */
10805
+ failedDestinationIds: array(string()).readonly(),
10806
+ /** Failure message when `state === 'failed'`. */
10807
+ error: string().optional(),
10808
+ /**
10809
+ * 1-based place in the execution queue — 1 = runs next. Present only
10810
+ * while `state === 'queued'`. Stamped by the orchestrator from the
10811
+ * queue's OWN pending order, never derived from timestamps, so the
10812
+ * UI cannot show an order the executor will not honour.
10813
+ */
10814
+ queuePosition: number().int().min(1).optional()
10815
+ });
10816
+ /**
10817
+ * Result of `backup.trigger`. The call still resolves when the run
10818
+ * terminates (compat with schedule-driven runs and the admin UI), but
10819
+ * it now names the run and says whether it had to WAIT: a trigger that
10820
+ * arrives while another run is in flight is enqueued (or joined onto
10821
+ * an identical already-queued run), never started concurrently.
10822
+ */
10823
+ var BackupTriggerResultSchema = object({
10824
+ /** The run this trigger mapped to — poll it via `listRuns`, stop it via `cancel`. */
10825
+ runId: string(),
10826
+ /** True when the run waited behind an in-flight run instead of starting immediately. */
10827
+ queued: boolean(),
10828
+ /** True when this trigger was coalesced onto an identical already-queued run. */
10829
+ joined: boolean(),
10830
+ /** True when the run was cancelled before completing every destination. */
10831
+ cancelled: boolean(),
10832
+ /** One entry per destination the archive landed at (partial on cancel). */
10833
+ entries: array(BackupEntrySchema).readonly()
10834
+ });
10752
10835
  /**
10753
10836
  * A backup schedule — the N:M "entry" that binds one cron cadence to a
10754
10837
  * SET of destination locations. Supersedes the per-location cron on
@@ -10796,7 +10879,10 @@ method(_void(), array(BackupDestinationInfoSchema).readonly(), { auth: "admin" }
10796
10879
  * retention (manual runs).
10797
10880
  */
10798
10881
  retentionCount: number().int().min(1).max(1e3).optional()
10799
- }).optional(), array(BackupEntrySchema).readonly(), {
10882
+ }).optional(), BackupTriggerResultSchema, {
10883
+ kind: "mutation",
10884
+ auth: "admin"
10885
+ }), method(_void(), array(BackupRunSchema).readonly(), { auth: "admin" }), method(object({ runId: string() }), object({ cancelled: boolean() }), {
10800
10886
  kind: "mutation",
10801
10887
  auth: "admin"
10802
10888
  }), method(_void(), array(BackupEntrySchema).readonly(), { auth: "admin" }), method(_void(), array(LocationStatSchema).readonly(), { auth: "admin" }), method(object({
@@ -11562,6 +11648,14 @@ method(object({
11562
11648
  }), object({ success: literal(true) }), {
11563
11649
  kind: "mutation",
11564
11650
  auth: "admin"
11651
+ }), method(object({ deviceId: number().int().nonnegative() }), object({
11652
+ derivedStreamsDeleted: array(string()).readonly(),
11653
+ assignmentsPurged: boolean(),
11654
+ probeSnapshotsDropped: number().int().nonnegative(),
11655
+ rtspTokenRowsDeleted: number().int().nonnegative()
11656
+ }), {
11657
+ kind: "mutation",
11658
+ auth: "admin"
11565
11659
  }), method(object({
11566
11660
  deviceId: number(),
11567
11661
  /** Absent = the LOWEST assigned profile — a notification attachment is
@@ -13076,6 +13170,35 @@ var deviceProviderCapability = {
13076
13170
  name: string(),
13077
13171
  type: string()
13078
13172
  }))),
13173
+ /**
13174
+ * Tear down and reconstruct ONE device in place from its persisted rows —
13175
+ * touching no other device this provider owns.
13176
+ *
13177
+ * The primitive `deviceManager.migrateDevice` uses to flush the two
13178
+ * migrated numbers: after `swapIds` the runner's live instance still
13179
+ * carries the PRE-swap numeric id (baked into the object, its native-cap
13180
+ * registrations and its log tags), and a live object cannot be renumbered.
13181
+ * Before this method the only flush was restarting the whole owning addon
13182
+ * — which took every camera the provider owns down with it (28 devices
13183
+ * for one migrated camera, measured 2026-09-04, and the morning of the
13184
+ * same day ~27 devices' native caps did not come back on their own).
13185
+ *
13186
+ * Keyed by `stableId`, deliberately: the numeric id is exactly the thing
13187
+ * that changes. The reply carries the id the device answers on NOW.
13188
+ * Implemented once in `BaseDeviceProvider` — decommission the live
13189
+ * instance (if any), then re-create from the persisted row: the same
13190
+ * teardown/rehydrate pair every graceful shutdown + boot already uses.
13191
+ * An RPC, never an event: a dropped event would leave the runner writing
13192
+ * against the wrong camera (D8).
13193
+ *
13194
+ * Construction can dial hardware, and the migrated source is
13195
+ * characteristically dead — the timeout covers a full activate window
13196
+ * rather than the 60 s default.
13197
+ */
13198
+ reloadDevice: method(object({ stableId: string() }), object({ deviceId: number() }), {
13199
+ kind: "mutation",
13200
+ timeoutMs: 3 * 6e4
13201
+ }),
13079
13202
  supportsDiscovery: method(object({}), boolean()),
13080
13203
  /**
13081
13204
  * Run a network scan. `params` carries optional provider-specific scan
@@ -13403,7 +13526,8 @@ method(object({
13403
13526
  targetId: number()
13404
13527
  }), MigrateDeviceResultSchema, {
13405
13528
  kind: "mutation",
13406
- auth: "admin"
13529
+ auth: "admin",
13530
+ timeoutMs: 12 * 6e4
13407
13531
  }), method(DeviceRegisterPayloadSchema, _void(), { kind: "mutation" }), method(DeviceRemovePayloadSchema, _void(), { kind: "mutation" }), method(DevicePersistConfigPayloadSchema, _void(), { kind: "mutation" }), method(object({ deviceId: number() }), record(string(), unknown())), method(object({ deviceId: number() }), record(string(), unknown())), method(object({ deviceId: number() }), DeviceMetaSchema.nullable()), method(object({
13408
13532
  deviceId: number(),
13409
13533
  name: string()
@@ -32878,6 +33002,147 @@ var BaseDevice = class {
32878
33002
  }
32879
33003
  };
32880
33004
  /**
33005
+ * Delays before retry rounds 1..N — the round count IS the bound.
33006
+ * 10 s catches "the hub was busy for a moment"; the full schedule
33007
+ * (10 + 30 + 90 s of waiting, plus up to one 60 s transport timeout
33008
+ * per attempt) covers a device-manager lock held for minutes — the
33009
+ * 2026-09-04 outage's migration hold was ~3.5 min.
33010
+ */
33011
+ var DEVICE_RESTORE_RETRY_DELAYS_MS = [
33012
+ 1e4,
33013
+ 3e4,
33014
+ 9e4
33015
+ ];
33016
+ /** Abortable sleep — resolves early (never rejects) on abort. */
33017
+ function sleep$1(ms, signal) {
33018
+ return new Promise((resolve) => {
33019
+ if (signal.aborted) {
33020
+ resolve();
33021
+ return;
33022
+ }
33023
+ const onAbort = () => {
33024
+ clearTimeout(timer);
33025
+ resolve();
33026
+ };
33027
+ const timer = setTimeout(() => {
33028
+ signal.removeEventListener("abort", onAbort);
33029
+ resolve();
33030
+ }, ms);
33031
+ timer.unref?.();
33032
+ signal.addEventListener("abort", onAbort, { once: true });
33033
+ });
33034
+ }
33035
+ /** Drain `items` through at most `width` concurrent lanes. `fn` must
33036
+ * not reject (callers wrap their own try/catch). */
33037
+ async function runWithConcurrency(items, width, fn) {
33038
+ const queue = [...items];
33039
+ const laneCount = Math.max(1, Math.min(width, queue.length));
33040
+ const lane = async () => {
33041
+ for (;;) {
33042
+ const item = queue.shift();
33043
+ if (item === void 0) return;
33044
+ await fn(item);
33045
+ }
33046
+ };
33047
+ await Promise.all(Array.from({ length: laneCount }, lane));
33048
+ }
33049
+ var DeviceRestoreRetryScheduler = class {
33050
+ #logger;
33051
+ #attempt;
33052
+ #onPermanentFailure;
33053
+ #delaysMs;
33054
+ #concurrency;
33055
+ #now;
33056
+ #abort = new AbortController();
33057
+ constructor(options) {
33058
+ this.#logger = options.logger;
33059
+ this.#attempt = options.attempt;
33060
+ this.#onPermanentFailure = options.onPermanentFailure;
33061
+ this.#delaysMs = options.delaysMs ?? DEVICE_RESTORE_RETRY_DELAYS_MS;
33062
+ this.#concurrency = options.concurrency ?? 4;
33063
+ this.#now = options.now ?? Date.now;
33064
+ }
33065
+ /** Stop retrying (shutdown). Pending entries are NOT marked
33066
+ * permanently failed — the next boot restores them from disk. */
33067
+ cancel() {
33068
+ this.#abort.abort();
33069
+ }
33070
+ /**
33071
+ * Run the bounded retry rounds. Resolves when every entry has either
33072
+ * restored, been marked permanently failed, or the scheduler was
33073
+ * cancelled. Never rejects.
33074
+ */
33075
+ async run(initialFailures) {
33076
+ let pending = initialFailures.map((failure) => ({
33077
+ saved: failure.saved,
33078
+ lastError: failure.error,
33079
+ attempts: 1
33080
+ }));
33081
+ for (let round = 0; round < this.#delaysMs.length; round += 1) {
33082
+ if (pending.length === 0 || this.#abort.signal.aborted) break;
33083
+ await sleep$1(this.#delaysMs[round] ?? 0, this.#abort.signal);
33084
+ if (this.#abort.signal.aborted) break;
33085
+ pending = await this.#runRound(pending, round);
33086
+ }
33087
+ if (this.#abort.signal.aborted) return [];
33088
+ const terminal = pending.map((entry) => ({
33089
+ deviceId: entry.saved.id,
33090
+ stableId: entry.saved.stableId,
33091
+ type: String(entry.saved.type),
33092
+ attempts: entry.attempts,
33093
+ lastError: entry.lastError,
33094
+ failedAt: this.#now()
33095
+ }));
33096
+ for (const failure of terminal) this.#onPermanentFailure(failure);
33097
+ return terminal;
33098
+ }
33099
+ /** One retry round: parents first (phase 0), then hub-adopted
33100
+ * children (phase 1) — a child's attempt depends on its parent
33101
+ * having landed, exactly like the initial two-pass restore. */
33102
+ async #runRound(pending, round) {
33103
+ const next = [];
33104
+ const parents = pending.filter((entry) => entry.saved.parentDeviceId === null);
33105
+ const children = pending.filter((entry) => entry.saved.parentDeviceId !== null);
33106
+ for (const phase of [parents, children]) await runWithConcurrency(phase, this.#concurrency, async (entry) => {
33107
+ if (this.#abort.signal.aborted) {
33108
+ next.push(entry);
33109
+ return;
33110
+ }
33111
+ const attemptNo = entry.attempts + 1;
33112
+ try {
33113
+ await this.#attempt(entry.saved);
33114
+ this.#logger.info("Device restored on retry", {
33115
+ tags: {
33116
+ deviceId: entry.saved.id,
33117
+ stableId: entry.saved.stableId
33118
+ },
33119
+ meta: { attempt: attemptNo }
33120
+ });
33121
+ } catch (err) {
33122
+ const lastError = err instanceof Error ? err.message : String(err);
33123
+ const remainingRetries = this.#delaysMs.length - (round + 1);
33124
+ this.#logger.warn("Device restore retry failed", {
33125
+ tags: {
33126
+ deviceId: entry.saved.id,
33127
+ stableId: entry.saved.stableId
33128
+ },
33129
+ meta: {
33130
+ attempt: attemptNo,
33131
+ remainingRetries,
33132
+ error: lastError
33133
+ }
33134
+ });
33135
+ next.push({
33136
+ saved: entry.saved,
33137
+ lastError,
33138
+ attempts: attemptNo
33139
+ });
33140
+ }
33141
+ });
33142
+ return next;
33143
+ }
33144
+ };
33145
+ /**
32881
33146
  * Convert an IDevice to the flat DeviceSummary shape expected by the
32882
33147
  * device-provider cap router. Shared across all providers.
32883
33148
  */
@@ -32926,6 +33191,7 @@ var BaseDeviceProvider = class extends BaseAddon {
32926
33191
  }];
32927
33192
  }
32928
33193
  async onShutdown() {
33194
+ this.cancelRestoreRetries();
32929
33195
  const devices = await this.ctx.kernel.devices?.getAll() ?? [];
32930
33196
  for (const device of devices) try {
32931
33197
  await this.ctx.kernel.devices?.decommission(device.id);
@@ -32943,9 +33209,16 @@ var BaseDeviceProvider = class extends BaseAddon {
32943
33209
  async start() {}
32944
33210
  async stop() {}
32945
33211
  async getStatus() {
33212
+ const all = await this.ctx.kernel.devices?.getAll() ?? [];
33213
+ const summary = this.restoreFailureSummary();
33214
+ if (summary === null) return {
33215
+ connected: true,
33216
+ deviceCount: all.length
33217
+ };
32946
33218
  return {
32947
33219
  connected: true,
32948
- deviceCount: (await this.ctx.kernel.devices?.getAll() ?? []).length
33220
+ deviceCount: all.length,
33221
+ error: summary
32949
33222
  };
32950
33223
  }
32951
33224
  async getDevices() {
@@ -33035,8 +33308,137 @@ var BaseDeviceProvider = class extends BaseAddon {
33035
33308
  };
33036
33309
  }
33037
33310
  async restoreDevices(savedDevices) {
33038
- await this.onRestoreDevices(savedDevices);
33039
- if (savedDevices.length > 0) this.ctx.logger.info(`Restored ${savedDevices.length} ${this.providerName} device(s)`);
33311
+ const report = await this.onRestoreDevices(savedDevices);
33312
+ if (savedDevices.length === 0) return;
33313
+ if (report && report.failedCount > 0) {
33314
+ this.ctx.logger.warn(`Restored ${report.restoredCount}/${savedDevices.length} ${this.providerName} device(s) — ${report.failedCount} failed, bounded retry scheduled`);
33315
+ return;
33316
+ }
33317
+ const restoredCount = report ? report.restoredCount : savedDevices.length;
33318
+ this.ctx.logger.info(`Restored ${restoredCount} ${this.providerName} device(s)`);
33319
+ }
33320
+ /** Retry schedule. Overridable (tests use millisecond delays). */
33321
+ restoreRetryDelaysMs = DEVICE_RESTORE_RETRY_DELAYS_MS;
33322
+ /** Retry lane width. See `device-restore-retry.ts` for why retries
33323
+ * never re-stampede full-width while the initial pass does (D167). */
33324
+ restoreRetryConcurrency = 4;
33325
+ _restoreRetryScheduler = null;
33326
+ _restoreRetryCompletion = null;
33327
+ _permanentRestoreFailures = /* @__PURE__ */ new Map();
33328
+ /** Settles when the background retry rounds finish (or `null` when
33329
+ * nothing failed). Exposed for tests and subclass diagnostics —
33330
+ * boot NEVER awaits this: the runner's post-init handshake goes out
33331
+ * with the devices that restored, and a late success is announced
33332
+ * through the `native-cap-change` → `updateCaps` path. */
33333
+ get restoreRetryCompletion() {
33334
+ return this._restoreRetryCompletion;
33335
+ }
33336
+ /** Devices that exhausted the retry bound this process lifetime. */
33337
+ get permanentRestoreFailures() {
33338
+ return [...this._permanentRestoreFailures.values()];
33339
+ }
33340
+ /** One-line operator-facing summary for `getStatus().error`, or
33341
+ * `null` when every device restored. */
33342
+ restoreFailureSummary() {
33343
+ if (this._permanentRestoreFailures.size === 0) return null;
33344
+ const ids = [...this._permanentRestoreFailures.keys()].join(", ");
33345
+ return `${this._permanentRestoreFailures.size} device(s) permanently failed restore (deviceIds: ${ids}) — restart the ${this.providerName} provider to retry`;
33346
+ }
33347
+ cancelRestoreRetries() {
33348
+ this._restoreRetryScheduler?.cancel();
33349
+ this._restoreRetryScheduler = null;
33350
+ }
33351
+ recordPermanentRestoreFailure(failure) {
33352
+ this._permanentRestoreFailures.set(failure.deviceId, failure);
33353
+ this.ctx.logger.error("Device restore permanently failed — its capabilities will not register until the provider restarts", {
33354
+ tags: {
33355
+ deviceId: failure.deviceId,
33356
+ stableId: failure.stableId
33357
+ },
33358
+ meta: {
33359
+ type: failure.type,
33360
+ attempts: failure.attempts,
33361
+ error: failure.lastError
33362
+ }
33363
+ });
33364
+ }
33365
+ scheduleRestoreRetries(failures, attempt) {
33366
+ const scheduler = new DeviceRestoreRetryScheduler({
33367
+ logger: this.ctx.logger,
33368
+ delaysMs: this.restoreRetryDelaysMs,
33369
+ concurrency: this.restoreRetryConcurrency,
33370
+ attempt,
33371
+ onPermanentFailure: (failure) => this.recordPermanentRestoreFailure(failure)
33372
+ });
33373
+ this._restoreRetryScheduler = scheduler;
33374
+ this._restoreRetryCompletion = scheduler.run(failures).then(() => void 0).catch((err) => {
33375
+ this.ctx.logger.error("Restore retry scheduler crashed", { meta: { error: err instanceof Error ? err.message : String(err) } });
33376
+ });
33377
+ }
33378
+ /**
33379
+ * Tear down and reconstruct ONE device from its persisted rows — the
33380
+ * `deviceProvider.reloadDevice` cap method. Persistence is never touched,
33381
+ * and no other device this provider owns is disturbed.
33382
+ *
33383
+ * Keyed by `stableId` because the caller's whole reason to be here is that
33384
+ * the NUMERIC id changed (`deviceManager.migrateDevice` swapped it): the
33385
+ * fresh instance resolves its id through `allocateDeviceId`, which returns
33386
+ * whatever number the row carries NOW. The teardown is `decommission` —
33387
+ * exactly what a graceful shutdown runs per device (fires `removeDevice()`,
33388
+ * unregisters native caps, drops the registry entry) — and the rebuild is
33389
+ * the boot restore's own `create()` path, including its pass 2: first-class
33390
+ * children (hub-adopted cameras under an NVR) are decommissioned with the
33391
+ * parent by the cascade and must be re-created explicitly, because only
33392
+ * accessory children come back through `getAccessoryChildren()`.
33393
+ *
33394
+ * Reloading an accessory child directly is refused (no device class) —
33395
+ * reload its parent instead.
33396
+ */
33397
+ async reloadDevice(input) {
33398
+ const { stableId } = input;
33399
+ const devices = this.ctx.kernel.devices;
33400
+ if (!devices) throw new Error(`${this.providerName}: kernel.devices unavailable — cannot reload`);
33401
+ const live = (await devices.getAll()).find((d) => d.stableId === stableId);
33402
+ if (live) await devices.decommission(live.id);
33403
+ const { id } = await this.ctx.api.deviceManager.allocateDeviceId.mutate({
33404
+ addonId: this.addonId,
33405
+ stableId
33406
+ });
33407
+ const meta = await this.ctx.api.deviceManager.loadMeta.query({ deviceId: id });
33408
+ if (meta === null) throw new Error(`${this.providerName}: no persisted meta for "${stableId}" (id ${id}) — cannot reload`);
33409
+ const deviceType = Object.values(DeviceType).find((t) => t === meta.type);
33410
+ const Class = deviceType !== void 0 ? this.deviceClasses[deviceType] : void 0;
33411
+ if (!Class) throw new Error(`${this.providerName}: no device class for type "${meta.type}" — "${stableId}" is an accessory child; reload its parent instead`);
33412
+ await devices.create(stableId, Class, {}, meta.parentDeviceId ?? null);
33413
+ const rows = await this.ctx.api.deviceManager.listPersistedByAddon.query({ addonId: this.addonId });
33414
+ for (const row of rows) {
33415
+ if (row.parentDeviceId !== id) continue;
33416
+ const childType = Object.values(DeviceType).find((t) => t === row.type);
33417
+ const ChildClass = childType !== void 0 ? this.deviceClasses[childType] : void 0;
33418
+ if (!ChildClass) continue;
33419
+ try {
33420
+ await devices.create(row.stableId, ChildClass, {}, id);
33421
+ } catch (err) {
33422
+ this.ctx.logger.warn("reloadDevice: failed to re-create first-class child", {
33423
+ tags: {
33424
+ deviceId: row.id,
33425
+ stableId: row.stableId
33426
+ },
33427
+ meta: {
33428
+ parentDeviceId: id,
33429
+ error: err instanceof Error ? err.message : String(err)
33430
+ }
33431
+ });
33432
+ }
33433
+ }
33434
+ this.ctx.logger.info("device reloaded in place from persisted rows", {
33435
+ tags: { deviceId: id },
33436
+ meta: {
33437
+ stableId,
33438
+ type: meta.type
33439
+ }
33440
+ });
33441
+ return { deviceId: id };
33040
33442
  }
33041
33443
  /**
33042
33444
  * Restore devices from persisted state. Two-pass:
@@ -33062,55 +33464,108 @@ var BaseDeviceProvider = class extends BaseAddon {
33062
33464
  * accessory-spawn flow handles via the parent's
33063
33465
  * `getAccessoryChildren()`. Override only when the default doesn't
33064
33466
  * fit.
33467
+ *
33468
+ * A row that fails either pass is NOT terminal (D347): it is handed
33469
+ * to a bounded background retry (`DeviceRestoreRetryScheduler`).
33470
+ * Only after the bound is exhausted is the device marked permanently
33471
+ * failed — logged at ERROR with `tags.deviceId` and surfaced via
33472
+ * `getStatus().error`.
33065
33473
  */
33066
33474
  async onRestoreDevices(savedDevices) {
33067
33475
  const restored = /* @__PURE__ */ new Set();
33476
+ const failures = [];
33477
+ const attemptRestore = async (saved) => {
33478
+ if (restored.has(saved.id)) return;
33479
+ const Class = this.deviceClasses[saved.type];
33480
+ if (!Class) throw new Error(`no device class registered for type "${saved.type}"`);
33481
+ if (saved.parentDeviceId !== null && !restored.has(saved.parentDeviceId)) throw new Error(`parent device ${saved.parentDeviceId} not restored`);
33482
+ await this.ctx.kernel.devices.create(saved.stableId, Class, {}, saved.parentDeviceId);
33483
+ restored.add(saved.id);
33484
+ };
33068
33485
  const topLevel = savedDevices.filter((saved) => saved.parentDeviceId === null);
33069
33486
  const restoreOne = async (saved) => {
33070
- const Class = this.deviceClasses[saved.type];
33071
- if (!Class) {
33487
+ if (!this.deviceClasses[saved.type]) {
33072
33488
  this.ctx.logger.warn("No device class registered for restored type — skipping", {
33073
- tags: { stableId: saved.stableId },
33489
+ tags: {
33490
+ deviceId: saved.id,
33491
+ stableId: saved.stableId
33492
+ },
33074
33493
  meta: { type: saved.type }
33075
33494
  });
33076
33495
  return;
33077
33496
  }
33078
33497
  try {
33079
- await this.ctx.kernel.devices.create(saved.stableId, Class, {});
33080
- restored.add(saved.id);
33498
+ await attemptRestore(saved);
33081
33499
  } catch (err) {
33082
- this.ctx.logger.warn("Failed to restore device", {
33083
- tags: { stableId: saved.stableId },
33500
+ const error = err instanceof Error ? err.message : String(err);
33501
+ this.ctx.logger.warn("Failed to restore device — bounded retry scheduled", {
33502
+ tags: {
33503
+ deviceId: saved.id,
33504
+ stableId: saved.stableId
33505
+ },
33084
33506
  meta: {
33085
33507
  type: saved.type,
33086
- error: err instanceof Error ? err.message : String(err)
33508
+ attempt: 1,
33509
+ error
33087
33510
  }
33088
33511
  });
33512
+ failures.push({
33513
+ saved,
33514
+ error
33515
+ });
33089
33516
  }
33090
33517
  };
33091
33518
  await Promise.all(topLevel.map((saved) => restoreOne(saved)));
33519
+ const failedTopLevelIds = new Set(failures.map((failure) => failure.saved.id));
33092
33520
  const childRows = savedDevices.filter((s) => s.parentDeviceId !== null);
33093
33521
  for (const saved of childRows) {
33094
- const Class = this.deviceClasses[saved.type];
33095
- if (!Class) continue;
33522
+ if (!this.deviceClasses[saved.type]) continue;
33096
33523
  if (saved.parentDeviceId === null) continue;
33097
- if (!restored.has(saved.parentDeviceId)) continue;
33098
- try {
33099
- await this.ctx.kernel.devices.create(saved.stableId, Class, {}, saved.parentDeviceId);
33100
- restored.add(saved.id);
33101
- } catch (err) {
33102
- this.ctx.logger.warn("Failed to restore hub-adopted child", {
33524
+ if (restored.has(saved.parentDeviceId)) {
33525
+ try {
33526
+ await attemptRestore(saved);
33527
+ } catch (err) {
33528
+ const error = err instanceof Error ? err.message : String(err);
33529
+ this.ctx.logger.warn("Failed to restore hub-adopted child — bounded retry scheduled", {
33530
+ tags: {
33531
+ deviceId: saved.id,
33532
+ stableId: saved.stableId,
33533
+ parentDeviceId: saved.parentDeviceId
33534
+ },
33535
+ meta: {
33536
+ type: saved.type,
33537
+ attempt: 1,
33538
+ error
33539
+ }
33540
+ });
33541
+ failures.push({
33542
+ saved,
33543
+ error
33544
+ });
33545
+ }
33546
+ continue;
33547
+ }
33548
+ if (failedTopLevelIds.has(saved.parentDeviceId)) {
33549
+ this.ctx.logger.warn("Hub-adopted child deferred — parent failed initial restore", {
33103
33550
  tags: {
33551
+ deviceId: saved.id,
33104
33552
  stableId: saved.stableId,
33105
33553
  parentDeviceId: saved.parentDeviceId
33106
33554
  },
33107
- meta: {
33108
- type: saved.type,
33109
- error: err instanceof Error ? err.message : String(err)
33110
- }
33555
+ meta: { type: saved.type }
33556
+ });
33557
+ failures.push({
33558
+ saved,
33559
+ error: `parent device ${saved.parentDeviceId} not restored`
33111
33560
  });
33561
+ continue;
33112
33562
  }
33113
33563
  }
33564
+ if (failures.length > 0) this.scheduleRestoreRetries(failures, attemptRestore);
33565
+ return {
33566
+ restoredCount: restored.size,
33567
+ failedCount: failures.length
33568
+ };
33114
33569
  }
33115
33570
  /** Convert an IDevice to the flat DeviceSummary for the cap router. */
33116
33571
  toSummary(device) {
@@ -33619,6 +34074,12 @@ Object.freeze({
33619
34074
  addonId: null,
33620
34075
  access: "create"
33621
34076
  },
34077
+ "backup.cancel": {
34078
+ capName: "backup",
34079
+ capScope: "system",
34080
+ addonId: null,
34081
+ access: "create"
34082
+ },
33622
34083
  "backup.delete": {
33623
34084
  capName: "backup",
33624
34085
  capScope: "system",
@@ -33661,6 +34122,12 @@ Object.freeze({
33661
34122
  addonId: null,
33662
34123
  access: "view"
33663
34124
  },
34125
+ "backup.listRuns": {
34126
+ capName: "backup",
34127
+ capScope: "system",
34128
+ addonId: null,
34129
+ access: "view"
34130
+ },
33664
34131
  "backup.listSchedules": {
33665
34132
  capName: "backup",
33666
34133
  capScope: "system",
@@ -34861,6 +35328,12 @@ Object.freeze({
34861
35328
  addonId: null,
34862
35329
  access: "view"
34863
35330
  },
35331
+ "deviceProvider.reloadDevice": {
35332
+ capName: "device-provider",
35333
+ capScope: "system",
35334
+ addonId: null,
35335
+ access: "create"
35336
+ },
34864
35337
  "deviceProvider.start": {
34865
35338
  capName: "device-provider",
34866
35339
  capScope: "system",
@@ -38227,6 +38700,12 @@ Object.freeze({
38227
38700
  addonId: null,
38228
38701
  access: "create"
38229
38702
  },
38703
+ "streamBroker.forgetDeviceHardware": {
38704
+ capName: "stream-broker",
38705
+ capScope: "system",
38706
+ addonId: null,
38707
+ access: "delete"
38708
+ },
38230
38709
  "streamBroker.getAllRtspEntries": {
38231
38710
  capName: "stream-broker",
38232
38711
  capScope: "system",
@@ -40685,6 +41164,11 @@ Object.freeze({
40685
41164
  form: "single",
40686
41165
  optional: false
40687
41166
  }],
41167
+ "streamBroker.forgetDeviceHardware": [{
41168
+ name: "deviceId",
41169
+ form: "single",
41170
+ optional: false
41171
+ }],
40688
41172
  "streamBroker.getDeviceAudioMute": [{
40689
41173
  name: "deviceId",
40690
41174
  form: "single",
@@ -10749,6 +10749,89 @@ var LocationStatSchema = object({
10749
10749
  fileCount: number(),
10750
10750
  present: boolean()
10751
10751
  });
10752
+ /** Lifecycle of a backup run. Terminal states: succeeded / failed / cancelled. */
10753
+ var BackupRunStateSchema = _enum([
10754
+ "queued",
10755
+ "running",
10756
+ "succeeded",
10757
+ "failed",
10758
+ "cancelled"
10759
+ ]);
10760
+ /**
10761
+ * Where a running backup currently is. `queued` before it starts,
10762
+ * `building` while the tar.gz is being staged, `uploading` during the
10763
+ * per-destination fan-out, `done` once terminal.
10764
+ */
10765
+ var BackupRunPhaseSchema = _enum([
10766
+ "queued",
10767
+ "building",
10768
+ "uploading",
10769
+ "done"
10770
+ ]);
10771
+ /**
10772
+ * Observable state of one backup run — readable WHILE it runs via
10773
+ * `backup.listRuns`. This is what makes the execution queue and
10774
+ * `backup.cancel` usable: the 2026-09-04 incident (two concurrent
10775
+ * multi-GB builds, staging 5.1 GB → 18 GB, load 62) was only
10776
+ * diagnosable with `du` because nothing reported that runs existed or
10777
+ * how large the staged archive had grown.
10778
+ */
10779
+ var BackupRunSchema = object({
10780
+ /** Stable run id — the handle `backup.cancel` takes. */
10781
+ id: string(),
10782
+ state: BackupRunStateSchema,
10783
+ phase: BackupRunPhaseSchema,
10784
+ /**
10785
+ * Resolved destination location ids. Empty while queued (targets are
10786
+ * resolved when the run starts, against the then-current policies).
10787
+ */
10788
+ destinationIds: array(string()).readonly(),
10789
+ label: string().optional(),
10790
+ /** ms-epoch when the run was submitted (trigger call / schedule fire). */
10791
+ requestedAt: number(),
10792
+ /** ms-epoch when the run left the queue and started building. */
10793
+ startedAt: number().optional(),
10794
+ /** ms-epoch when the run reached a terminal state. */
10795
+ finishedAt: number().optional(),
10796
+ /** Compressed bytes of the staging archive written so far. */
10797
+ stagedBytes: number(),
10798
+ /** Final staged archive size, once the build phase completes. */
10799
+ archiveSizeBytes: number().optional(),
10800
+ /** Bytes pushed to the destination currently uploading. */
10801
+ uploadedBytes: number(),
10802
+ /** Destinations where the archive fully landed (uploaded + indexed). */
10803
+ completedDestinationIds: array(string()).readonly(),
10804
+ /** Destinations that failed during the fan-out. */
10805
+ failedDestinationIds: array(string()).readonly(),
10806
+ /** Failure message when `state === 'failed'`. */
10807
+ error: string().optional(),
10808
+ /**
10809
+ * 1-based place in the execution queue — 1 = runs next. Present only
10810
+ * while `state === 'queued'`. Stamped by the orchestrator from the
10811
+ * queue's OWN pending order, never derived from timestamps, so the
10812
+ * UI cannot show an order the executor will not honour.
10813
+ */
10814
+ queuePosition: number().int().min(1).optional()
10815
+ });
10816
+ /**
10817
+ * Result of `backup.trigger`. The call still resolves when the run
10818
+ * terminates (compat with schedule-driven runs and the admin UI), but
10819
+ * it now names the run and says whether it had to WAIT: a trigger that
10820
+ * arrives while another run is in flight is enqueued (or joined onto
10821
+ * an identical already-queued run), never started concurrently.
10822
+ */
10823
+ var BackupTriggerResultSchema = object({
10824
+ /** The run this trigger mapped to — poll it via `listRuns`, stop it via `cancel`. */
10825
+ runId: string(),
10826
+ /** True when the run waited behind an in-flight run instead of starting immediately. */
10827
+ queued: boolean(),
10828
+ /** True when this trigger was coalesced onto an identical already-queued run. */
10829
+ joined: boolean(),
10830
+ /** True when the run was cancelled before completing every destination. */
10831
+ cancelled: boolean(),
10832
+ /** One entry per destination the archive landed at (partial on cancel). */
10833
+ entries: array(BackupEntrySchema).readonly()
10834
+ });
10752
10835
  /**
10753
10836
  * A backup schedule — the N:M "entry" that binds one cron cadence to a
10754
10837
  * SET of destination locations. Supersedes the per-location cron on
@@ -10796,7 +10879,10 @@ method(_void(), array(BackupDestinationInfoSchema).readonly(), { auth: "admin" }
10796
10879
  * retention (manual runs).
10797
10880
  */
10798
10881
  retentionCount: number().int().min(1).max(1e3).optional()
10799
- }).optional(), array(BackupEntrySchema).readonly(), {
10882
+ }).optional(), BackupTriggerResultSchema, {
10883
+ kind: "mutation",
10884
+ auth: "admin"
10885
+ }), method(_void(), array(BackupRunSchema).readonly(), { auth: "admin" }), method(object({ runId: string() }), object({ cancelled: boolean() }), {
10800
10886
  kind: "mutation",
10801
10887
  auth: "admin"
10802
10888
  }), method(_void(), array(BackupEntrySchema).readonly(), { auth: "admin" }), method(_void(), array(LocationStatSchema).readonly(), { auth: "admin" }), method(object({
@@ -11562,6 +11648,14 @@ method(object({
11562
11648
  }), object({ success: literal(true) }), {
11563
11649
  kind: "mutation",
11564
11650
  auth: "admin"
11651
+ }), method(object({ deviceId: number().int().nonnegative() }), object({
11652
+ derivedStreamsDeleted: array(string()).readonly(),
11653
+ assignmentsPurged: boolean(),
11654
+ probeSnapshotsDropped: number().int().nonnegative(),
11655
+ rtspTokenRowsDeleted: number().int().nonnegative()
11656
+ }), {
11657
+ kind: "mutation",
11658
+ auth: "admin"
11565
11659
  }), method(object({
11566
11660
  deviceId: number(),
11567
11661
  /** Absent = the LOWEST assigned profile — a notification attachment is
@@ -13076,6 +13170,35 @@ var deviceProviderCapability = {
13076
13170
  name: string(),
13077
13171
  type: string()
13078
13172
  }))),
13173
+ /**
13174
+ * Tear down and reconstruct ONE device in place from its persisted rows —
13175
+ * touching no other device this provider owns.
13176
+ *
13177
+ * The primitive `deviceManager.migrateDevice` uses to flush the two
13178
+ * migrated numbers: after `swapIds` the runner's live instance still
13179
+ * carries the PRE-swap numeric id (baked into the object, its native-cap
13180
+ * registrations and its log tags), and a live object cannot be renumbered.
13181
+ * Before this method the only flush was restarting the whole owning addon
13182
+ * — which took every camera the provider owns down with it (28 devices
13183
+ * for one migrated camera, measured 2026-09-04, and the morning of the
13184
+ * same day ~27 devices' native caps did not come back on their own).
13185
+ *
13186
+ * Keyed by `stableId`, deliberately: the numeric id is exactly the thing
13187
+ * that changes. The reply carries the id the device answers on NOW.
13188
+ * Implemented once in `BaseDeviceProvider` — decommission the live
13189
+ * instance (if any), then re-create from the persisted row: the same
13190
+ * teardown/rehydrate pair every graceful shutdown + boot already uses.
13191
+ * An RPC, never an event: a dropped event would leave the runner writing
13192
+ * against the wrong camera (D8).
13193
+ *
13194
+ * Construction can dial hardware, and the migrated source is
13195
+ * characteristically dead — the timeout covers a full activate window
13196
+ * rather than the 60 s default.
13197
+ */
13198
+ reloadDevice: method(object({ stableId: string() }), object({ deviceId: number() }), {
13199
+ kind: "mutation",
13200
+ timeoutMs: 3 * 6e4
13201
+ }),
13079
13202
  supportsDiscovery: method(object({}), boolean()),
13080
13203
  /**
13081
13204
  * Run a network scan. `params` carries optional provider-specific scan
@@ -13403,7 +13526,8 @@ method(object({
13403
13526
  targetId: number()
13404
13527
  }), MigrateDeviceResultSchema, {
13405
13528
  kind: "mutation",
13406
- auth: "admin"
13529
+ auth: "admin",
13530
+ timeoutMs: 12 * 6e4
13407
13531
  }), method(DeviceRegisterPayloadSchema, _void(), { kind: "mutation" }), method(DeviceRemovePayloadSchema, _void(), { kind: "mutation" }), method(DevicePersistConfigPayloadSchema, _void(), { kind: "mutation" }), method(object({ deviceId: number() }), record(string(), unknown())), method(object({ deviceId: number() }), record(string(), unknown())), method(object({ deviceId: number() }), DeviceMetaSchema.nullable()), method(object({
13408
13532
  deviceId: number(),
13409
13533
  name: string()
@@ -32878,6 +33002,147 @@ var BaseDevice = class {
32878
33002
  }
32879
33003
  };
32880
33004
  /**
33005
+ * Delays before retry rounds 1..N — the round count IS the bound.
33006
+ * 10 s catches "the hub was busy for a moment"; the full schedule
33007
+ * (10 + 30 + 90 s of waiting, plus up to one 60 s transport timeout
33008
+ * per attempt) covers a device-manager lock held for minutes — the
33009
+ * 2026-09-04 outage's migration hold was ~3.5 min.
33010
+ */
33011
+ var DEVICE_RESTORE_RETRY_DELAYS_MS = [
33012
+ 1e4,
33013
+ 3e4,
33014
+ 9e4
33015
+ ];
33016
+ /** Abortable sleep — resolves early (never rejects) on abort. */
33017
+ function sleep$1(ms, signal) {
33018
+ return new Promise((resolve) => {
33019
+ if (signal.aborted) {
33020
+ resolve();
33021
+ return;
33022
+ }
33023
+ const onAbort = () => {
33024
+ clearTimeout(timer);
33025
+ resolve();
33026
+ };
33027
+ const timer = setTimeout(() => {
33028
+ signal.removeEventListener("abort", onAbort);
33029
+ resolve();
33030
+ }, ms);
33031
+ timer.unref?.();
33032
+ signal.addEventListener("abort", onAbort, { once: true });
33033
+ });
33034
+ }
33035
+ /** Drain `items` through at most `width` concurrent lanes. `fn` must
33036
+ * not reject (callers wrap their own try/catch). */
33037
+ async function runWithConcurrency(items, width, fn) {
33038
+ const queue = [...items];
33039
+ const laneCount = Math.max(1, Math.min(width, queue.length));
33040
+ const lane = async () => {
33041
+ for (;;) {
33042
+ const item = queue.shift();
33043
+ if (item === void 0) return;
33044
+ await fn(item);
33045
+ }
33046
+ };
33047
+ await Promise.all(Array.from({ length: laneCount }, lane));
33048
+ }
33049
+ var DeviceRestoreRetryScheduler = class {
33050
+ #logger;
33051
+ #attempt;
33052
+ #onPermanentFailure;
33053
+ #delaysMs;
33054
+ #concurrency;
33055
+ #now;
33056
+ #abort = new AbortController();
33057
+ constructor(options) {
33058
+ this.#logger = options.logger;
33059
+ this.#attempt = options.attempt;
33060
+ this.#onPermanentFailure = options.onPermanentFailure;
33061
+ this.#delaysMs = options.delaysMs ?? DEVICE_RESTORE_RETRY_DELAYS_MS;
33062
+ this.#concurrency = options.concurrency ?? 4;
33063
+ this.#now = options.now ?? Date.now;
33064
+ }
33065
+ /** Stop retrying (shutdown). Pending entries are NOT marked
33066
+ * permanently failed — the next boot restores them from disk. */
33067
+ cancel() {
33068
+ this.#abort.abort();
33069
+ }
33070
+ /**
33071
+ * Run the bounded retry rounds. Resolves when every entry has either
33072
+ * restored, been marked permanently failed, or the scheduler was
33073
+ * cancelled. Never rejects.
33074
+ */
33075
+ async run(initialFailures) {
33076
+ let pending = initialFailures.map((failure) => ({
33077
+ saved: failure.saved,
33078
+ lastError: failure.error,
33079
+ attempts: 1
33080
+ }));
33081
+ for (let round = 0; round < this.#delaysMs.length; round += 1) {
33082
+ if (pending.length === 0 || this.#abort.signal.aborted) break;
33083
+ await sleep$1(this.#delaysMs[round] ?? 0, this.#abort.signal);
33084
+ if (this.#abort.signal.aborted) break;
33085
+ pending = await this.#runRound(pending, round);
33086
+ }
33087
+ if (this.#abort.signal.aborted) return [];
33088
+ const terminal = pending.map((entry) => ({
33089
+ deviceId: entry.saved.id,
33090
+ stableId: entry.saved.stableId,
33091
+ type: String(entry.saved.type),
33092
+ attempts: entry.attempts,
33093
+ lastError: entry.lastError,
33094
+ failedAt: this.#now()
33095
+ }));
33096
+ for (const failure of terminal) this.#onPermanentFailure(failure);
33097
+ return terminal;
33098
+ }
33099
+ /** One retry round: parents first (phase 0), then hub-adopted
33100
+ * children (phase 1) — a child's attempt depends on its parent
33101
+ * having landed, exactly like the initial two-pass restore. */
33102
+ async #runRound(pending, round) {
33103
+ const next = [];
33104
+ const parents = pending.filter((entry) => entry.saved.parentDeviceId === null);
33105
+ const children = pending.filter((entry) => entry.saved.parentDeviceId !== null);
33106
+ for (const phase of [parents, children]) await runWithConcurrency(phase, this.#concurrency, async (entry) => {
33107
+ if (this.#abort.signal.aborted) {
33108
+ next.push(entry);
33109
+ return;
33110
+ }
33111
+ const attemptNo = entry.attempts + 1;
33112
+ try {
33113
+ await this.#attempt(entry.saved);
33114
+ this.#logger.info("Device restored on retry", {
33115
+ tags: {
33116
+ deviceId: entry.saved.id,
33117
+ stableId: entry.saved.stableId
33118
+ },
33119
+ meta: { attempt: attemptNo }
33120
+ });
33121
+ } catch (err) {
33122
+ const lastError = err instanceof Error ? err.message : String(err);
33123
+ const remainingRetries = this.#delaysMs.length - (round + 1);
33124
+ this.#logger.warn("Device restore retry failed", {
33125
+ tags: {
33126
+ deviceId: entry.saved.id,
33127
+ stableId: entry.saved.stableId
33128
+ },
33129
+ meta: {
33130
+ attempt: attemptNo,
33131
+ remainingRetries,
33132
+ error: lastError
33133
+ }
33134
+ });
33135
+ next.push({
33136
+ saved: entry.saved,
33137
+ lastError,
33138
+ attempts: attemptNo
33139
+ });
33140
+ }
33141
+ });
33142
+ return next;
33143
+ }
33144
+ };
33145
+ /**
32881
33146
  * Convert an IDevice to the flat DeviceSummary shape expected by the
32882
33147
  * device-provider cap router. Shared across all providers.
32883
33148
  */
@@ -32926,6 +33191,7 @@ var BaseDeviceProvider = class extends BaseAddon {
32926
33191
  }];
32927
33192
  }
32928
33193
  async onShutdown() {
33194
+ this.cancelRestoreRetries();
32929
33195
  const devices = await this.ctx.kernel.devices?.getAll() ?? [];
32930
33196
  for (const device of devices) try {
32931
33197
  await this.ctx.kernel.devices?.decommission(device.id);
@@ -32943,9 +33209,16 @@ var BaseDeviceProvider = class extends BaseAddon {
32943
33209
  async start() {}
32944
33210
  async stop() {}
32945
33211
  async getStatus() {
33212
+ const all = await this.ctx.kernel.devices?.getAll() ?? [];
33213
+ const summary = this.restoreFailureSummary();
33214
+ if (summary === null) return {
33215
+ connected: true,
33216
+ deviceCount: all.length
33217
+ };
32946
33218
  return {
32947
33219
  connected: true,
32948
- deviceCount: (await this.ctx.kernel.devices?.getAll() ?? []).length
33220
+ deviceCount: all.length,
33221
+ error: summary
32949
33222
  };
32950
33223
  }
32951
33224
  async getDevices() {
@@ -33035,8 +33308,137 @@ var BaseDeviceProvider = class extends BaseAddon {
33035
33308
  };
33036
33309
  }
33037
33310
  async restoreDevices(savedDevices) {
33038
- await this.onRestoreDevices(savedDevices);
33039
- if (savedDevices.length > 0) this.ctx.logger.info(`Restored ${savedDevices.length} ${this.providerName} device(s)`);
33311
+ const report = await this.onRestoreDevices(savedDevices);
33312
+ if (savedDevices.length === 0) return;
33313
+ if (report && report.failedCount > 0) {
33314
+ this.ctx.logger.warn(`Restored ${report.restoredCount}/${savedDevices.length} ${this.providerName} device(s) — ${report.failedCount} failed, bounded retry scheduled`);
33315
+ return;
33316
+ }
33317
+ const restoredCount = report ? report.restoredCount : savedDevices.length;
33318
+ this.ctx.logger.info(`Restored ${restoredCount} ${this.providerName} device(s)`);
33319
+ }
33320
+ /** Retry schedule. Overridable (tests use millisecond delays). */
33321
+ restoreRetryDelaysMs = DEVICE_RESTORE_RETRY_DELAYS_MS;
33322
+ /** Retry lane width. See `device-restore-retry.ts` for why retries
33323
+ * never re-stampede full-width while the initial pass does (D167). */
33324
+ restoreRetryConcurrency = 4;
33325
+ _restoreRetryScheduler = null;
33326
+ _restoreRetryCompletion = null;
33327
+ _permanentRestoreFailures = /* @__PURE__ */ new Map();
33328
+ /** Settles when the background retry rounds finish (or `null` when
33329
+ * nothing failed). Exposed for tests and subclass diagnostics —
33330
+ * boot NEVER awaits this: the runner's post-init handshake goes out
33331
+ * with the devices that restored, and a late success is announced
33332
+ * through the `native-cap-change` → `updateCaps` path. */
33333
+ get restoreRetryCompletion() {
33334
+ return this._restoreRetryCompletion;
33335
+ }
33336
+ /** Devices that exhausted the retry bound this process lifetime. */
33337
+ get permanentRestoreFailures() {
33338
+ return [...this._permanentRestoreFailures.values()];
33339
+ }
33340
+ /** One-line operator-facing summary for `getStatus().error`, or
33341
+ * `null` when every device restored. */
33342
+ restoreFailureSummary() {
33343
+ if (this._permanentRestoreFailures.size === 0) return null;
33344
+ const ids = [...this._permanentRestoreFailures.keys()].join(", ");
33345
+ return `${this._permanentRestoreFailures.size} device(s) permanently failed restore (deviceIds: ${ids}) — restart the ${this.providerName} provider to retry`;
33346
+ }
33347
+ cancelRestoreRetries() {
33348
+ this._restoreRetryScheduler?.cancel();
33349
+ this._restoreRetryScheduler = null;
33350
+ }
33351
+ recordPermanentRestoreFailure(failure) {
33352
+ this._permanentRestoreFailures.set(failure.deviceId, failure);
33353
+ this.ctx.logger.error("Device restore permanently failed — its capabilities will not register until the provider restarts", {
33354
+ tags: {
33355
+ deviceId: failure.deviceId,
33356
+ stableId: failure.stableId
33357
+ },
33358
+ meta: {
33359
+ type: failure.type,
33360
+ attempts: failure.attempts,
33361
+ error: failure.lastError
33362
+ }
33363
+ });
33364
+ }
33365
+ scheduleRestoreRetries(failures, attempt) {
33366
+ const scheduler = new DeviceRestoreRetryScheduler({
33367
+ logger: this.ctx.logger,
33368
+ delaysMs: this.restoreRetryDelaysMs,
33369
+ concurrency: this.restoreRetryConcurrency,
33370
+ attempt,
33371
+ onPermanentFailure: (failure) => this.recordPermanentRestoreFailure(failure)
33372
+ });
33373
+ this._restoreRetryScheduler = scheduler;
33374
+ this._restoreRetryCompletion = scheduler.run(failures).then(() => void 0).catch((err) => {
33375
+ this.ctx.logger.error("Restore retry scheduler crashed", { meta: { error: err instanceof Error ? err.message : String(err) } });
33376
+ });
33377
+ }
33378
+ /**
33379
+ * Tear down and reconstruct ONE device from its persisted rows — the
33380
+ * `deviceProvider.reloadDevice` cap method. Persistence is never touched,
33381
+ * and no other device this provider owns is disturbed.
33382
+ *
33383
+ * Keyed by `stableId` because the caller's whole reason to be here is that
33384
+ * the NUMERIC id changed (`deviceManager.migrateDevice` swapped it): the
33385
+ * fresh instance resolves its id through `allocateDeviceId`, which returns
33386
+ * whatever number the row carries NOW. The teardown is `decommission` —
33387
+ * exactly what a graceful shutdown runs per device (fires `removeDevice()`,
33388
+ * unregisters native caps, drops the registry entry) — and the rebuild is
33389
+ * the boot restore's own `create()` path, including its pass 2: first-class
33390
+ * children (hub-adopted cameras under an NVR) are decommissioned with the
33391
+ * parent by the cascade and must be re-created explicitly, because only
33392
+ * accessory children come back through `getAccessoryChildren()`.
33393
+ *
33394
+ * Reloading an accessory child directly is refused (no device class) —
33395
+ * reload its parent instead.
33396
+ */
33397
+ async reloadDevice(input) {
33398
+ const { stableId } = input;
33399
+ const devices = this.ctx.kernel.devices;
33400
+ if (!devices) throw new Error(`${this.providerName}: kernel.devices unavailable — cannot reload`);
33401
+ const live = (await devices.getAll()).find((d) => d.stableId === stableId);
33402
+ if (live) await devices.decommission(live.id);
33403
+ const { id } = await this.ctx.api.deviceManager.allocateDeviceId.mutate({
33404
+ addonId: this.addonId,
33405
+ stableId
33406
+ });
33407
+ const meta = await this.ctx.api.deviceManager.loadMeta.query({ deviceId: id });
33408
+ if (meta === null) throw new Error(`${this.providerName}: no persisted meta for "${stableId}" (id ${id}) — cannot reload`);
33409
+ const deviceType = Object.values(DeviceType).find((t) => t === meta.type);
33410
+ const Class = deviceType !== void 0 ? this.deviceClasses[deviceType] : void 0;
33411
+ if (!Class) throw new Error(`${this.providerName}: no device class for type "${meta.type}" — "${stableId}" is an accessory child; reload its parent instead`);
33412
+ await devices.create(stableId, Class, {}, meta.parentDeviceId ?? null);
33413
+ const rows = await this.ctx.api.deviceManager.listPersistedByAddon.query({ addonId: this.addonId });
33414
+ for (const row of rows) {
33415
+ if (row.parentDeviceId !== id) continue;
33416
+ const childType = Object.values(DeviceType).find((t) => t === row.type);
33417
+ const ChildClass = childType !== void 0 ? this.deviceClasses[childType] : void 0;
33418
+ if (!ChildClass) continue;
33419
+ try {
33420
+ await devices.create(row.stableId, ChildClass, {}, id);
33421
+ } catch (err) {
33422
+ this.ctx.logger.warn("reloadDevice: failed to re-create first-class child", {
33423
+ tags: {
33424
+ deviceId: row.id,
33425
+ stableId: row.stableId
33426
+ },
33427
+ meta: {
33428
+ parentDeviceId: id,
33429
+ error: err instanceof Error ? err.message : String(err)
33430
+ }
33431
+ });
33432
+ }
33433
+ }
33434
+ this.ctx.logger.info("device reloaded in place from persisted rows", {
33435
+ tags: { deviceId: id },
33436
+ meta: {
33437
+ stableId,
33438
+ type: meta.type
33439
+ }
33440
+ });
33441
+ return { deviceId: id };
33040
33442
  }
33041
33443
  /**
33042
33444
  * Restore devices from persisted state. Two-pass:
@@ -33062,55 +33464,108 @@ var BaseDeviceProvider = class extends BaseAddon {
33062
33464
  * accessory-spawn flow handles via the parent's
33063
33465
  * `getAccessoryChildren()`. Override only when the default doesn't
33064
33466
  * fit.
33467
+ *
33468
+ * A row that fails either pass is NOT terminal (D347): it is handed
33469
+ * to a bounded background retry (`DeviceRestoreRetryScheduler`).
33470
+ * Only after the bound is exhausted is the device marked permanently
33471
+ * failed — logged at ERROR with `tags.deviceId` and surfaced via
33472
+ * `getStatus().error`.
33065
33473
  */
33066
33474
  async onRestoreDevices(savedDevices) {
33067
33475
  const restored = /* @__PURE__ */ new Set();
33476
+ const failures = [];
33477
+ const attemptRestore = async (saved) => {
33478
+ if (restored.has(saved.id)) return;
33479
+ const Class = this.deviceClasses[saved.type];
33480
+ if (!Class) throw new Error(`no device class registered for type "${saved.type}"`);
33481
+ if (saved.parentDeviceId !== null && !restored.has(saved.parentDeviceId)) throw new Error(`parent device ${saved.parentDeviceId} not restored`);
33482
+ await this.ctx.kernel.devices.create(saved.stableId, Class, {}, saved.parentDeviceId);
33483
+ restored.add(saved.id);
33484
+ };
33068
33485
  const topLevel = savedDevices.filter((saved) => saved.parentDeviceId === null);
33069
33486
  const restoreOne = async (saved) => {
33070
- const Class = this.deviceClasses[saved.type];
33071
- if (!Class) {
33487
+ if (!this.deviceClasses[saved.type]) {
33072
33488
  this.ctx.logger.warn("No device class registered for restored type — skipping", {
33073
- tags: { stableId: saved.stableId },
33489
+ tags: {
33490
+ deviceId: saved.id,
33491
+ stableId: saved.stableId
33492
+ },
33074
33493
  meta: { type: saved.type }
33075
33494
  });
33076
33495
  return;
33077
33496
  }
33078
33497
  try {
33079
- await this.ctx.kernel.devices.create(saved.stableId, Class, {});
33080
- restored.add(saved.id);
33498
+ await attemptRestore(saved);
33081
33499
  } catch (err) {
33082
- this.ctx.logger.warn("Failed to restore device", {
33083
- tags: { stableId: saved.stableId },
33500
+ const error = err instanceof Error ? err.message : String(err);
33501
+ this.ctx.logger.warn("Failed to restore device — bounded retry scheduled", {
33502
+ tags: {
33503
+ deviceId: saved.id,
33504
+ stableId: saved.stableId
33505
+ },
33084
33506
  meta: {
33085
33507
  type: saved.type,
33086
- error: err instanceof Error ? err.message : String(err)
33508
+ attempt: 1,
33509
+ error
33087
33510
  }
33088
33511
  });
33512
+ failures.push({
33513
+ saved,
33514
+ error
33515
+ });
33089
33516
  }
33090
33517
  };
33091
33518
  await Promise.all(topLevel.map((saved) => restoreOne(saved)));
33519
+ const failedTopLevelIds = new Set(failures.map((failure) => failure.saved.id));
33092
33520
  const childRows = savedDevices.filter((s) => s.parentDeviceId !== null);
33093
33521
  for (const saved of childRows) {
33094
- const Class = this.deviceClasses[saved.type];
33095
- if (!Class) continue;
33522
+ if (!this.deviceClasses[saved.type]) continue;
33096
33523
  if (saved.parentDeviceId === null) continue;
33097
- if (!restored.has(saved.parentDeviceId)) continue;
33098
- try {
33099
- await this.ctx.kernel.devices.create(saved.stableId, Class, {}, saved.parentDeviceId);
33100
- restored.add(saved.id);
33101
- } catch (err) {
33102
- this.ctx.logger.warn("Failed to restore hub-adopted child", {
33524
+ if (restored.has(saved.parentDeviceId)) {
33525
+ try {
33526
+ await attemptRestore(saved);
33527
+ } catch (err) {
33528
+ const error = err instanceof Error ? err.message : String(err);
33529
+ this.ctx.logger.warn("Failed to restore hub-adopted child — bounded retry scheduled", {
33530
+ tags: {
33531
+ deviceId: saved.id,
33532
+ stableId: saved.stableId,
33533
+ parentDeviceId: saved.parentDeviceId
33534
+ },
33535
+ meta: {
33536
+ type: saved.type,
33537
+ attempt: 1,
33538
+ error
33539
+ }
33540
+ });
33541
+ failures.push({
33542
+ saved,
33543
+ error
33544
+ });
33545
+ }
33546
+ continue;
33547
+ }
33548
+ if (failedTopLevelIds.has(saved.parentDeviceId)) {
33549
+ this.ctx.logger.warn("Hub-adopted child deferred — parent failed initial restore", {
33103
33550
  tags: {
33551
+ deviceId: saved.id,
33104
33552
  stableId: saved.stableId,
33105
33553
  parentDeviceId: saved.parentDeviceId
33106
33554
  },
33107
- meta: {
33108
- type: saved.type,
33109
- error: err instanceof Error ? err.message : String(err)
33110
- }
33555
+ meta: { type: saved.type }
33556
+ });
33557
+ failures.push({
33558
+ saved,
33559
+ error: `parent device ${saved.parentDeviceId} not restored`
33111
33560
  });
33561
+ continue;
33112
33562
  }
33113
33563
  }
33564
+ if (failures.length > 0) this.scheduleRestoreRetries(failures, attemptRestore);
33565
+ return {
33566
+ restoredCount: restored.size,
33567
+ failedCount: failures.length
33568
+ };
33114
33569
  }
33115
33570
  /** Convert an IDevice to the flat DeviceSummary for the cap router. */
33116
33571
  toSummary(device) {
@@ -33619,6 +34074,12 @@ Object.freeze({
33619
34074
  addonId: null,
33620
34075
  access: "create"
33621
34076
  },
34077
+ "backup.cancel": {
34078
+ capName: "backup",
34079
+ capScope: "system",
34080
+ addonId: null,
34081
+ access: "create"
34082
+ },
33622
34083
  "backup.delete": {
33623
34084
  capName: "backup",
33624
34085
  capScope: "system",
@@ -33661,6 +34122,12 @@ Object.freeze({
33661
34122
  addonId: null,
33662
34123
  access: "view"
33663
34124
  },
34125
+ "backup.listRuns": {
34126
+ capName: "backup",
34127
+ capScope: "system",
34128
+ addonId: null,
34129
+ access: "view"
34130
+ },
33664
34131
  "backup.listSchedules": {
33665
34132
  capName: "backup",
33666
34133
  capScope: "system",
@@ -34861,6 +35328,12 @@ Object.freeze({
34861
35328
  addonId: null,
34862
35329
  access: "view"
34863
35330
  },
35331
+ "deviceProvider.reloadDevice": {
35332
+ capName: "device-provider",
35333
+ capScope: "system",
35334
+ addonId: null,
35335
+ access: "create"
35336
+ },
34864
35337
  "deviceProvider.start": {
34865
35338
  capName: "device-provider",
34866
35339
  capScope: "system",
@@ -38227,6 +38700,12 @@ Object.freeze({
38227
38700
  addonId: null,
38228
38701
  access: "create"
38229
38702
  },
38703
+ "streamBroker.forgetDeviceHardware": {
38704
+ capName: "stream-broker",
38705
+ capScope: "system",
38706
+ addonId: null,
38707
+ access: "delete"
38708
+ },
38230
38709
  "streamBroker.getAllRtspEntries": {
38231
38710
  capName: "stream-broker",
38232
38711
  capScope: "system",
@@ -40685,6 +41164,11 @@ Object.freeze({
40685
41164
  form: "single",
40686
41165
  optional: false
40687
41166
  }],
41167
+ "streamBroker.forgetDeviceHardware": [{
41168
+ name: "deviceId",
41169
+ form: "single",
41170
+ optional: false
41171
+ }],
40688
41172
  "streamBroker.getDeviceAudioMute": [{
40689
41173
  name: "deviceId",
40690
41174
  form: "single",
@@ -3,7 +3,7 @@ Object.defineProperties(exports, {
3
3
  [Symbol.toStringTag]: { value: "Module" }
4
4
  });
5
5
  //#endregion
6
- const require_dist = require("../dist-DkMiMzBV.js");
6
+ const require_dist = require("../dist-Ccw8gsKE.js");
7
7
  let node_crypto = require("node:crypto");
8
8
  //#region src/ha-export/topics.ts
9
9
  /**
@@ -1,4 +1,4 @@
1
- import { At as EventCategory, C as buildAddonRouteProvider, Et as string, N as deviceExportCapability, X as oauthIntegrationCapability, a as COCO_TO_MACRO, c as FanDirectionSchema, i as CAMERA_SWITCH_ORDER, l as HvacModeSchema, o as CameraSwitchIdSchema, p as addonRoutesCapability, pt as BaseAddon, t as AlarmArmModeSchema, u as MediaPlayerRepeatSchema, vt as nodePin } from "../dist-CwsG7FxA.mjs";
1
+ import { At as EventCategory, C as buildAddonRouteProvider, Et as string, N as deviceExportCapability, X as oauthIntegrationCapability, a as COCO_TO_MACRO, c as FanDirectionSchema, i as CAMERA_SWITCH_ORDER, l as HvacModeSchema, o as CameraSwitchIdSchema, p as addonRoutesCapability, pt as BaseAddon, t as AlarmArmModeSchema, u as MediaPlayerRepeatSchema, vt as nodePin } from "../dist-CrzCO0F_.mjs";
2
2
  import { createHmac, timingSafeEqual } from "node:crypto";
3
3
  //#region src/ha-export/topics.ts
4
4
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@camstack/addon-provider-homeassistant",
3
- "version": "1.2.72",
3
+ "version": "1.2.74",
4
4
  "description": "Home Assistant device provider addon for CamStack",
5
5
  "keywords": [
6
6
  "camstack",