@camstack/addon-provider-homeassistant 1.2.73 → 1.2.75

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-BiCYEtvX.js");
2
+ const require_dist = require("./dist-gv0Gmrm1.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-BQ3x3HG3.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-CQzCvoCx.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
@@ -13114,7 +13114,26 @@ var DiscoveryCandidateSchema = object({
13114
13114
  * identity ahead of adoption. Rendering metadata (unit, precision)
13115
13115
  * flows live through the cap STATUS SLICE after adoption.
13116
13116
  */
13117
- sourceInfo: SourceInfoSchema.optional()
13117
+ sourceInfo: SourceInfoSchema.optional(),
13118
+ /**
13119
+ * Set when this candidate is a device the provider ALREADY owns.
13120
+ *
13121
+ * A scan cannot generally produce the identity a device was onboarded under
13122
+ * (Reolink keys on `mac-<mac>`, learned at adopt time), so a stableId
13123
+ * comparison never matches and an owned device looks addable. Re-adopting one
13124
+ * overwrites its config with scan-derived values — that is how a Home Hub's
13125
+ * Baichuan port was overwritten with its ONVIF port, taking the hub and its
13126
+ * three child cameras offline for four hours.
13127
+ *
13128
+ * A provider that can recognise its own devices says so here. Absent means
13129
+ * "not recognised", which is not the same as "known to be new" — a provider
13130
+ * that cannot tell simply never sets it.
13131
+ */
13132
+ alreadyOnboarded: boolean().optional(),
13133
+ /** Numeric id of the device this candidate was matched to. Set with `alreadyOnboarded`. */
13134
+ onboardedDeviceId: number().optional(),
13135
+ /** Operator-facing name of the matched device, so the UI can say WHICH one it is. */
13136
+ onboardedName: string().optional()
13118
13137
  });
13119
13138
  /**
13120
13139
  * Flat device summary returned by `createDevice` / `adoptDiscoveredDevice`.
@@ -13170,6 +13189,35 @@ var deviceProviderCapability = {
13170
13189
  name: string(),
13171
13190
  type: string()
13172
13191
  }))),
13192
+ /**
13193
+ * Tear down and reconstruct ONE device in place from its persisted rows —
13194
+ * touching no other device this provider owns.
13195
+ *
13196
+ * The primitive `deviceManager.migrateDevice` uses to flush the two
13197
+ * migrated numbers: after `swapIds` the runner's live instance still
13198
+ * carries the PRE-swap numeric id (baked into the object, its native-cap
13199
+ * registrations and its log tags), and a live object cannot be renumbered.
13200
+ * Before this method the only flush was restarting the whole owning addon
13201
+ * — which took every camera the provider owns down with it (28 devices
13202
+ * for one migrated camera, measured 2026-09-04, and the morning of the
13203
+ * same day ~27 devices' native caps did not come back on their own).
13204
+ *
13205
+ * Keyed by `stableId`, deliberately: the numeric id is exactly the thing
13206
+ * that changes. The reply carries the id the device answers on NOW.
13207
+ * Implemented once in `BaseDeviceProvider` — decommission the live
13208
+ * instance (if any), then re-create from the persisted row: the same
13209
+ * teardown/rehydrate pair every graceful shutdown + boot already uses.
13210
+ * An RPC, never an event: a dropped event would leave the runner writing
13211
+ * against the wrong camera (D8).
13212
+ *
13213
+ * Construction can dial hardware, and the migrated source is
13214
+ * characteristically dead — the timeout covers a full activate window
13215
+ * rather than the 60 s default.
13216
+ */
13217
+ reloadDevice: method(object({ stableId: string() }), object({ deviceId: number() }), {
13218
+ kind: "mutation",
13219
+ timeoutMs: 3 * 6e4
13220
+ }),
13173
13221
  supportsDiscovery: method(object({}), boolean()),
13174
13222
  /**
13175
13223
  * Run a network scan. `params` carries optional provider-specific scan
@@ -13497,7 +13545,8 @@ method(object({
13497
13545
  targetId: number()
13498
13546
  }), MigrateDeviceResultSchema, {
13499
13547
  kind: "mutation",
13500
- auth: "admin"
13548
+ auth: "admin",
13549
+ timeoutMs: 12 * 6e4
13501
13550
  }), 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({
13502
13551
  deviceId: number(),
13503
13552
  name: string()
@@ -32972,6 +33021,147 @@ var BaseDevice = class {
32972
33021
  }
32973
33022
  };
32974
33023
  /**
33024
+ * Delays before retry rounds 1..N — the round count IS the bound.
33025
+ * 10 s catches "the hub was busy for a moment"; the full schedule
33026
+ * (10 + 30 + 90 s of waiting, plus up to one 60 s transport timeout
33027
+ * per attempt) covers a device-manager lock held for minutes — the
33028
+ * 2026-09-04 outage's migration hold was ~3.5 min.
33029
+ */
33030
+ var DEVICE_RESTORE_RETRY_DELAYS_MS = [
33031
+ 1e4,
33032
+ 3e4,
33033
+ 9e4
33034
+ ];
33035
+ /** Abortable sleep — resolves early (never rejects) on abort. */
33036
+ function sleep$1(ms, signal) {
33037
+ return new Promise((resolve) => {
33038
+ if (signal.aborted) {
33039
+ resolve();
33040
+ return;
33041
+ }
33042
+ const onAbort = () => {
33043
+ clearTimeout(timer);
33044
+ resolve();
33045
+ };
33046
+ const timer = setTimeout(() => {
33047
+ signal.removeEventListener("abort", onAbort);
33048
+ resolve();
33049
+ }, ms);
33050
+ timer.unref?.();
33051
+ signal.addEventListener("abort", onAbort, { once: true });
33052
+ });
33053
+ }
33054
+ /** Drain `items` through at most `width` concurrent lanes. `fn` must
33055
+ * not reject (callers wrap their own try/catch). */
33056
+ async function runWithConcurrency(items, width, fn) {
33057
+ const queue = [...items];
33058
+ const laneCount = Math.max(1, Math.min(width, queue.length));
33059
+ const lane = async () => {
33060
+ for (;;) {
33061
+ const item = queue.shift();
33062
+ if (item === void 0) return;
33063
+ await fn(item);
33064
+ }
33065
+ };
33066
+ await Promise.all(Array.from({ length: laneCount }, lane));
33067
+ }
33068
+ var DeviceRestoreRetryScheduler = class {
33069
+ #logger;
33070
+ #attempt;
33071
+ #onPermanentFailure;
33072
+ #delaysMs;
33073
+ #concurrency;
33074
+ #now;
33075
+ #abort = new AbortController();
33076
+ constructor(options) {
33077
+ this.#logger = options.logger;
33078
+ this.#attempt = options.attempt;
33079
+ this.#onPermanentFailure = options.onPermanentFailure;
33080
+ this.#delaysMs = options.delaysMs ?? DEVICE_RESTORE_RETRY_DELAYS_MS;
33081
+ this.#concurrency = options.concurrency ?? 4;
33082
+ this.#now = options.now ?? Date.now;
33083
+ }
33084
+ /** Stop retrying (shutdown). Pending entries are NOT marked
33085
+ * permanently failed — the next boot restores them from disk. */
33086
+ cancel() {
33087
+ this.#abort.abort();
33088
+ }
33089
+ /**
33090
+ * Run the bounded retry rounds. Resolves when every entry has either
33091
+ * restored, been marked permanently failed, or the scheduler was
33092
+ * cancelled. Never rejects.
33093
+ */
33094
+ async run(initialFailures) {
33095
+ let pending = initialFailures.map((failure) => ({
33096
+ saved: failure.saved,
33097
+ lastError: failure.error,
33098
+ attempts: 1
33099
+ }));
33100
+ for (let round = 0; round < this.#delaysMs.length; round += 1) {
33101
+ if (pending.length === 0 || this.#abort.signal.aborted) break;
33102
+ await sleep$1(this.#delaysMs[round] ?? 0, this.#abort.signal);
33103
+ if (this.#abort.signal.aborted) break;
33104
+ pending = await this.#runRound(pending, round);
33105
+ }
33106
+ if (this.#abort.signal.aborted) return [];
33107
+ const terminal = pending.map((entry) => ({
33108
+ deviceId: entry.saved.id,
33109
+ stableId: entry.saved.stableId,
33110
+ type: String(entry.saved.type),
33111
+ attempts: entry.attempts,
33112
+ lastError: entry.lastError,
33113
+ failedAt: this.#now()
33114
+ }));
33115
+ for (const failure of terminal) this.#onPermanentFailure(failure);
33116
+ return terminal;
33117
+ }
33118
+ /** One retry round: parents first (phase 0), then hub-adopted
33119
+ * children (phase 1) — a child's attempt depends on its parent
33120
+ * having landed, exactly like the initial two-pass restore. */
33121
+ async #runRound(pending, round) {
33122
+ const next = [];
33123
+ const parents = pending.filter((entry) => entry.saved.parentDeviceId === null);
33124
+ const children = pending.filter((entry) => entry.saved.parentDeviceId !== null);
33125
+ for (const phase of [parents, children]) await runWithConcurrency(phase, this.#concurrency, async (entry) => {
33126
+ if (this.#abort.signal.aborted) {
33127
+ next.push(entry);
33128
+ return;
33129
+ }
33130
+ const attemptNo = entry.attempts + 1;
33131
+ try {
33132
+ await this.#attempt(entry.saved);
33133
+ this.#logger.info("Device restored on retry", {
33134
+ tags: {
33135
+ deviceId: entry.saved.id,
33136
+ stableId: entry.saved.stableId
33137
+ },
33138
+ meta: { attempt: attemptNo }
33139
+ });
33140
+ } catch (err) {
33141
+ const lastError = err instanceof Error ? err.message : String(err);
33142
+ const remainingRetries = this.#delaysMs.length - (round + 1);
33143
+ this.#logger.warn("Device restore retry failed", {
33144
+ tags: {
33145
+ deviceId: entry.saved.id,
33146
+ stableId: entry.saved.stableId
33147
+ },
33148
+ meta: {
33149
+ attempt: attemptNo,
33150
+ remainingRetries,
33151
+ error: lastError
33152
+ }
33153
+ });
33154
+ next.push({
33155
+ saved: entry.saved,
33156
+ lastError,
33157
+ attempts: attemptNo
33158
+ });
33159
+ }
33160
+ });
33161
+ return next;
33162
+ }
33163
+ };
33164
+ /**
32975
33165
  * Convert an IDevice to the flat DeviceSummary shape expected by the
32976
33166
  * device-provider cap router. Shared across all providers.
32977
33167
  */
@@ -33020,6 +33210,7 @@ var BaseDeviceProvider = class extends BaseAddon {
33020
33210
  }];
33021
33211
  }
33022
33212
  async onShutdown() {
33213
+ this.cancelRestoreRetries();
33023
33214
  const devices = await this.ctx.kernel.devices?.getAll() ?? [];
33024
33215
  for (const device of devices) try {
33025
33216
  await this.ctx.kernel.devices?.decommission(device.id);
@@ -33037,9 +33228,16 @@ var BaseDeviceProvider = class extends BaseAddon {
33037
33228
  async start() {}
33038
33229
  async stop() {}
33039
33230
  async getStatus() {
33231
+ const all = await this.ctx.kernel.devices?.getAll() ?? [];
33232
+ const summary = this.restoreFailureSummary();
33233
+ if (summary === null) return {
33234
+ connected: true,
33235
+ deviceCount: all.length
33236
+ };
33040
33237
  return {
33041
33238
  connected: true,
33042
- deviceCount: (await this.ctx.kernel.devices?.getAll() ?? []).length
33239
+ deviceCount: all.length,
33240
+ error: summary
33043
33241
  };
33044
33242
  }
33045
33243
  async getDevices() {
@@ -33129,8 +33327,137 @@ var BaseDeviceProvider = class extends BaseAddon {
33129
33327
  };
33130
33328
  }
33131
33329
  async restoreDevices(savedDevices) {
33132
- await this.onRestoreDevices(savedDevices);
33133
- if (savedDevices.length > 0) this.ctx.logger.info(`Restored ${savedDevices.length} ${this.providerName} device(s)`);
33330
+ const report = await this.onRestoreDevices(savedDevices);
33331
+ if (savedDevices.length === 0) return;
33332
+ if (report && report.failedCount > 0) {
33333
+ this.ctx.logger.warn(`Restored ${report.restoredCount}/${savedDevices.length} ${this.providerName} device(s) — ${report.failedCount} failed, bounded retry scheduled`);
33334
+ return;
33335
+ }
33336
+ const restoredCount = report ? report.restoredCount : savedDevices.length;
33337
+ this.ctx.logger.info(`Restored ${restoredCount} ${this.providerName} device(s)`);
33338
+ }
33339
+ /** Retry schedule. Overridable (tests use millisecond delays). */
33340
+ restoreRetryDelaysMs = DEVICE_RESTORE_RETRY_DELAYS_MS;
33341
+ /** Retry lane width. See `device-restore-retry.ts` for why retries
33342
+ * never re-stampede full-width while the initial pass does (D167). */
33343
+ restoreRetryConcurrency = 4;
33344
+ _restoreRetryScheduler = null;
33345
+ _restoreRetryCompletion = null;
33346
+ _permanentRestoreFailures = /* @__PURE__ */ new Map();
33347
+ /** Settles when the background retry rounds finish (or `null` when
33348
+ * nothing failed). Exposed for tests and subclass diagnostics —
33349
+ * boot NEVER awaits this: the runner's post-init handshake goes out
33350
+ * with the devices that restored, and a late success is announced
33351
+ * through the `native-cap-change` → `updateCaps` path. */
33352
+ get restoreRetryCompletion() {
33353
+ return this._restoreRetryCompletion;
33354
+ }
33355
+ /** Devices that exhausted the retry bound this process lifetime. */
33356
+ get permanentRestoreFailures() {
33357
+ return [...this._permanentRestoreFailures.values()];
33358
+ }
33359
+ /** One-line operator-facing summary for `getStatus().error`, or
33360
+ * `null` when every device restored. */
33361
+ restoreFailureSummary() {
33362
+ if (this._permanentRestoreFailures.size === 0) return null;
33363
+ const ids = [...this._permanentRestoreFailures.keys()].join(", ");
33364
+ return `${this._permanentRestoreFailures.size} device(s) permanently failed restore (deviceIds: ${ids}) — restart the ${this.providerName} provider to retry`;
33365
+ }
33366
+ cancelRestoreRetries() {
33367
+ this._restoreRetryScheduler?.cancel();
33368
+ this._restoreRetryScheduler = null;
33369
+ }
33370
+ recordPermanentRestoreFailure(failure) {
33371
+ this._permanentRestoreFailures.set(failure.deviceId, failure);
33372
+ this.ctx.logger.error("Device restore permanently failed — its capabilities will not register until the provider restarts", {
33373
+ tags: {
33374
+ deviceId: failure.deviceId,
33375
+ stableId: failure.stableId
33376
+ },
33377
+ meta: {
33378
+ type: failure.type,
33379
+ attempts: failure.attempts,
33380
+ error: failure.lastError
33381
+ }
33382
+ });
33383
+ }
33384
+ scheduleRestoreRetries(failures, attempt) {
33385
+ const scheduler = new DeviceRestoreRetryScheduler({
33386
+ logger: this.ctx.logger,
33387
+ delaysMs: this.restoreRetryDelaysMs,
33388
+ concurrency: this.restoreRetryConcurrency,
33389
+ attempt,
33390
+ onPermanentFailure: (failure) => this.recordPermanentRestoreFailure(failure)
33391
+ });
33392
+ this._restoreRetryScheduler = scheduler;
33393
+ this._restoreRetryCompletion = scheduler.run(failures).then(() => void 0).catch((err) => {
33394
+ this.ctx.logger.error("Restore retry scheduler crashed", { meta: { error: err instanceof Error ? err.message : String(err) } });
33395
+ });
33396
+ }
33397
+ /**
33398
+ * Tear down and reconstruct ONE device from its persisted rows — the
33399
+ * `deviceProvider.reloadDevice` cap method. Persistence is never touched,
33400
+ * and no other device this provider owns is disturbed.
33401
+ *
33402
+ * Keyed by `stableId` because the caller's whole reason to be here is that
33403
+ * the NUMERIC id changed (`deviceManager.migrateDevice` swapped it): the
33404
+ * fresh instance resolves its id through `allocateDeviceId`, which returns
33405
+ * whatever number the row carries NOW. The teardown is `decommission` —
33406
+ * exactly what a graceful shutdown runs per device (fires `removeDevice()`,
33407
+ * unregisters native caps, drops the registry entry) — and the rebuild is
33408
+ * the boot restore's own `create()` path, including its pass 2: first-class
33409
+ * children (hub-adopted cameras under an NVR) are decommissioned with the
33410
+ * parent by the cascade and must be re-created explicitly, because only
33411
+ * accessory children come back through `getAccessoryChildren()`.
33412
+ *
33413
+ * Reloading an accessory child directly is refused (no device class) —
33414
+ * reload its parent instead.
33415
+ */
33416
+ async reloadDevice(input) {
33417
+ const { stableId } = input;
33418
+ const devices = this.ctx.kernel.devices;
33419
+ if (!devices) throw new Error(`${this.providerName}: kernel.devices unavailable — cannot reload`);
33420
+ const live = (await devices.getAll()).find((d) => d.stableId === stableId);
33421
+ if (live) await devices.decommission(live.id);
33422
+ const { id } = await this.ctx.api.deviceManager.allocateDeviceId.mutate({
33423
+ addonId: this.addonId,
33424
+ stableId
33425
+ });
33426
+ const meta = await this.ctx.api.deviceManager.loadMeta.query({ deviceId: id });
33427
+ if (meta === null) throw new Error(`${this.providerName}: no persisted meta for "${stableId}" (id ${id}) — cannot reload`);
33428
+ const deviceType = Object.values(DeviceType).find((t) => t === meta.type);
33429
+ const Class = deviceType !== void 0 ? this.deviceClasses[deviceType] : void 0;
33430
+ if (!Class) throw new Error(`${this.providerName}: no device class for type "${meta.type}" — "${stableId}" is an accessory child; reload its parent instead`);
33431
+ await devices.create(stableId, Class, {}, meta.parentDeviceId ?? null);
33432
+ const rows = await this.ctx.api.deviceManager.listPersistedByAddon.query({ addonId: this.addonId });
33433
+ for (const row of rows) {
33434
+ if (row.parentDeviceId !== id) continue;
33435
+ const childType = Object.values(DeviceType).find((t) => t === row.type);
33436
+ const ChildClass = childType !== void 0 ? this.deviceClasses[childType] : void 0;
33437
+ if (!ChildClass) continue;
33438
+ try {
33439
+ await devices.create(row.stableId, ChildClass, {}, id);
33440
+ } catch (err) {
33441
+ this.ctx.logger.warn("reloadDevice: failed to re-create first-class child", {
33442
+ tags: {
33443
+ deviceId: row.id,
33444
+ stableId: row.stableId
33445
+ },
33446
+ meta: {
33447
+ parentDeviceId: id,
33448
+ error: err instanceof Error ? err.message : String(err)
33449
+ }
33450
+ });
33451
+ }
33452
+ }
33453
+ this.ctx.logger.info("device reloaded in place from persisted rows", {
33454
+ tags: { deviceId: id },
33455
+ meta: {
33456
+ stableId,
33457
+ type: meta.type
33458
+ }
33459
+ });
33460
+ return { deviceId: id };
33134
33461
  }
33135
33462
  /**
33136
33463
  * Restore devices from persisted state. Two-pass:
@@ -33156,55 +33483,125 @@ var BaseDeviceProvider = class extends BaseAddon {
33156
33483
  * accessory-spawn flow handles via the parent's
33157
33484
  * `getAccessoryChildren()`. Override only when the default doesn't
33158
33485
  * fit.
33486
+ *
33487
+ * A row that fails either pass is NOT terminal (D347): it is handed
33488
+ * to a bounded background retry (`DeviceRestoreRetryScheduler`).
33489
+ * Only after the bound is exhausted is the device marked permanently
33490
+ * failed — logged at ERROR with `tags.deviceId` and surfaced via
33491
+ * `getStatus().error`.
33159
33492
  */
33493
+ /**
33494
+ * Repair a row's PERSISTED config blob immediately before it is restored.
33495
+ * Default: no-op — most providers have nothing to heal.
33496
+ *
33497
+ * This exists because a restored device self-hydrates from the DB: `create()`
33498
+ * passes `{}` and `BaseDevice` parses the stored blob against the device
33499
+ * schema. A blob that lost a REQUIRED field therefore fails restore forever,
33500
+ * and no later pass revisits it — a hub-adopted Reolink camera whose blob had
33501
+ * been emptied failed all four bounded attempts against fields
33502
+ * (`host`, `password`) it inherits from its parent and never dials itself.
33503
+ *
33504
+ * Implementations get every saved row, so a child can read its parent's blob.
33505
+ * A heal that throws is treated like any other restore failure: retried under
33506
+ * the bound, then reported — never swallowed.
33507
+ */
33508
+ async healSavedConfig(_saved, _allSaved) {}
33160
33509
  async onRestoreDevices(savedDevices) {
33161
33510
  const restored = /* @__PURE__ */ new Set();
33511
+ const failures = [];
33512
+ const attemptRestore = async (saved) => {
33513
+ if (restored.has(saved.id)) return;
33514
+ const Class = this.deviceClasses[saved.type];
33515
+ if (!Class) throw new Error(`no device class registered for type "${saved.type}"`);
33516
+ if (saved.parentDeviceId !== null && !restored.has(saved.parentDeviceId)) throw new Error(`parent device ${saved.parentDeviceId} not restored`);
33517
+ await this.healSavedConfig(saved, savedDevices);
33518
+ await this.ctx.kernel.devices.create(saved.stableId, Class, {}, saved.parentDeviceId);
33519
+ restored.add(saved.id);
33520
+ };
33162
33521
  const topLevel = savedDevices.filter((saved) => saved.parentDeviceId === null);
33163
33522
  const restoreOne = async (saved) => {
33164
- const Class = this.deviceClasses[saved.type];
33165
- if (!Class) {
33523
+ if (!this.deviceClasses[saved.type]) {
33166
33524
  this.ctx.logger.warn("No device class registered for restored type — skipping", {
33167
- tags: { stableId: saved.stableId },
33525
+ tags: {
33526
+ deviceId: saved.id,
33527
+ stableId: saved.stableId
33528
+ },
33168
33529
  meta: { type: saved.type }
33169
33530
  });
33170
33531
  return;
33171
33532
  }
33172
33533
  try {
33173
- await this.ctx.kernel.devices.create(saved.stableId, Class, {});
33174
- restored.add(saved.id);
33534
+ await attemptRestore(saved);
33175
33535
  } catch (err) {
33176
- this.ctx.logger.warn("Failed to restore device", {
33177
- tags: { stableId: saved.stableId },
33536
+ const error = err instanceof Error ? err.message : String(err);
33537
+ this.ctx.logger.warn("Failed to restore device — bounded retry scheduled", {
33538
+ tags: {
33539
+ deviceId: saved.id,
33540
+ stableId: saved.stableId
33541
+ },
33178
33542
  meta: {
33179
33543
  type: saved.type,
33180
- error: err instanceof Error ? err.message : String(err)
33544
+ attempt: 1,
33545
+ error
33181
33546
  }
33182
33547
  });
33548
+ failures.push({
33549
+ saved,
33550
+ error
33551
+ });
33183
33552
  }
33184
33553
  };
33185
33554
  await Promise.all(topLevel.map((saved) => restoreOne(saved)));
33555
+ const failedTopLevelIds = new Set(failures.map((failure) => failure.saved.id));
33186
33556
  const childRows = savedDevices.filter((s) => s.parentDeviceId !== null);
33187
33557
  for (const saved of childRows) {
33188
- const Class = this.deviceClasses[saved.type];
33189
- if (!Class) continue;
33558
+ if (!this.deviceClasses[saved.type]) continue;
33190
33559
  if (saved.parentDeviceId === null) continue;
33191
- if (!restored.has(saved.parentDeviceId)) continue;
33192
- try {
33193
- await this.ctx.kernel.devices.create(saved.stableId, Class, {}, saved.parentDeviceId);
33194
- restored.add(saved.id);
33195
- } catch (err) {
33196
- this.ctx.logger.warn("Failed to restore hub-adopted child", {
33560
+ if (restored.has(saved.parentDeviceId)) {
33561
+ try {
33562
+ await attemptRestore(saved);
33563
+ } catch (err) {
33564
+ const error = err instanceof Error ? err.message : String(err);
33565
+ this.ctx.logger.warn("Failed to restore hub-adopted child — bounded retry scheduled", {
33566
+ tags: {
33567
+ deviceId: saved.id,
33568
+ stableId: saved.stableId,
33569
+ parentDeviceId: saved.parentDeviceId
33570
+ },
33571
+ meta: {
33572
+ type: saved.type,
33573
+ attempt: 1,
33574
+ error
33575
+ }
33576
+ });
33577
+ failures.push({
33578
+ saved,
33579
+ error
33580
+ });
33581
+ }
33582
+ continue;
33583
+ }
33584
+ if (failedTopLevelIds.has(saved.parentDeviceId)) {
33585
+ this.ctx.logger.warn("Hub-adopted child deferred — parent failed initial restore", {
33197
33586
  tags: {
33587
+ deviceId: saved.id,
33198
33588
  stableId: saved.stableId,
33199
33589
  parentDeviceId: saved.parentDeviceId
33200
33590
  },
33201
- meta: {
33202
- type: saved.type,
33203
- error: err instanceof Error ? err.message : String(err)
33204
- }
33591
+ meta: { type: saved.type }
33592
+ });
33593
+ failures.push({
33594
+ saved,
33595
+ error: `parent device ${saved.parentDeviceId} not restored`
33205
33596
  });
33597
+ continue;
33206
33598
  }
33207
33599
  }
33600
+ if (failures.length > 0) this.scheduleRestoreRetries(failures, attemptRestore);
33601
+ return {
33602
+ restoredCount: restored.size,
33603
+ failedCount: failures.length
33604
+ };
33208
33605
  }
33209
33606
  /** Convert an IDevice to the flat DeviceSummary for the cap router. */
33210
33607
  toSummary(device) {
@@ -34967,6 +35364,12 @@ Object.freeze({
34967
35364
  addonId: null,
34968
35365
  access: "view"
34969
35366
  },
35367
+ "deviceProvider.reloadDevice": {
35368
+ capName: "device-provider",
35369
+ capScope: "system",
35370
+ addonId: null,
35371
+ access: "create"
35372
+ },
34970
35373
  "deviceProvider.start": {
34971
35374
  capName: "device-provider",
34972
35375
  capScope: "system",
@@ -13114,7 +13114,26 @@ var DiscoveryCandidateSchema = object({
13114
13114
  * identity ahead of adoption. Rendering metadata (unit, precision)
13115
13115
  * flows live through the cap STATUS SLICE after adoption.
13116
13116
  */
13117
- sourceInfo: SourceInfoSchema.optional()
13117
+ sourceInfo: SourceInfoSchema.optional(),
13118
+ /**
13119
+ * Set when this candidate is a device the provider ALREADY owns.
13120
+ *
13121
+ * A scan cannot generally produce the identity a device was onboarded under
13122
+ * (Reolink keys on `mac-<mac>`, learned at adopt time), so a stableId
13123
+ * comparison never matches and an owned device looks addable. Re-adopting one
13124
+ * overwrites its config with scan-derived values — that is how a Home Hub's
13125
+ * Baichuan port was overwritten with its ONVIF port, taking the hub and its
13126
+ * three child cameras offline for four hours.
13127
+ *
13128
+ * A provider that can recognise its own devices says so here. Absent means
13129
+ * "not recognised", which is not the same as "known to be new" — a provider
13130
+ * that cannot tell simply never sets it.
13131
+ */
13132
+ alreadyOnboarded: boolean().optional(),
13133
+ /** Numeric id of the device this candidate was matched to. Set with `alreadyOnboarded`. */
13134
+ onboardedDeviceId: number().optional(),
13135
+ /** Operator-facing name of the matched device, so the UI can say WHICH one it is. */
13136
+ onboardedName: string().optional()
13118
13137
  });
13119
13138
  /**
13120
13139
  * Flat device summary returned by `createDevice` / `adoptDiscoveredDevice`.
@@ -13170,6 +13189,35 @@ var deviceProviderCapability = {
13170
13189
  name: string(),
13171
13190
  type: string()
13172
13191
  }))),
13192
+ /**
13193
+ * Tear down and reconstruct ONE device in place from its persisted rows —
13194
+ * touching no other device this provider owns.
13195
+ *
13196
+ * The primitive `deviceManager.migrateDevice` uses to flush the two
13197
+ * migrated numbers: after `swapIds` the runner's live instance still
13198
+ * carries the PRE-swap numeric id (baked into the object, its native-cap
13199
+ * registrations and its log tags), and a live object cannot be renumbered.
13200
+ * Before this method the only flush was restarting the whole owning addon
13201
+ * — which took every camera the provider owns down with it (28 devices
13202
+ * for one migrated camera, measured 2026-09-04, and the morning of the
13203
+ * same day ~27 devices' native caps did not come back on their own).
13204
+ *
13205
+ * Keyed by `stableId`, deliberately: the numeric id is exactly the thing
13206
+ * that changes. The reply carries the id the device answers on NOW.
13207
+ * Implemented once in `BaseDeviceProvider` — decommission the live
13208
+ * instance (if any), then re-create from the persisted row: the same
13209
+ * teardown/rehydrate pair every graceful shutdown + boot already uses.
13210
+ * An RPC, never an event: a dropped event would leave the runner writing
13211
+ * against the wrong camera (D8).
13212
+ *
13213
+ * Construction can dial hardware, and the migrated source is
13214
+ * characteristically dead — the timeout covers a full activate window
13215
+ * rather than the 60 s default.
13216
+ */
13217
+ reloadDevice: method(object({ stableId: string() }), object({ deviceId: number() }), {
13218
+ kind: "mutation",
13219
+ timeoutMs: 3 * 6e4
13220
+ }),
13173
13221
  supportsDiscovery: method(object({}), boolean()),
13174
13222
  /**
13175
13223
  * Run a network scan. `params` carries optional provider-specific scan
@@ -13497,7 +13545,8 @@ method(object({
13497
13545
  targetId: number()
13498
13546
  }), MigrateDeviceResultSchema, {
13499
13547
  kind: "mutation",
13500
- auth: "admin"
13548
+ auth: "admin",
13549
+ timeoutMs: 12 * 6e4
13501
13550
  }), 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({
13502
13551
  deviceId: number(),
13503
13552
  name: string()
@@ -32972,6 +33021,147 @@ var BaseDevice = class {
32972
33021
  }
32973
33022
  };
32974
33023
  /**
33024
+ * Delays before retry rounds 1..N — the round count IS the bound.
33025
+ * 10 s catches "the hub was busy for a moment"; the full schedule
33026
+ * (10 + 30 + 90 s of waiting, plus up to one 60 s transport timeout
33027
+ * per attempt) covers a device-manager lock held for minutes — the
33028
+ * 2026-09-04 outage's migration hold was ~3.5 min.
33029
+ */
33030
+ var DEVICE_RESTORE_RETRY_DELAYS_MS = [
33031
+ 1e4,
33032
+ 3e4,
33033
+ 9e4
33034
+ ];
33035
+ /** Abortable sleep — resolves early (never rejects) on abort. */
33036
+ function sleep$1(ms, signal) {
33037
+ return new Promise((resolve) => {
33038
+ if (signal.aborted) {
33039
+ resolve();
33040
+ return;
33041
+ }
33042
+ const onAbort = () => {
33043
+ clearTimeout(timer);
33044
+ resolve();
33045
+ };
33046
+ const timer = setTimeout(() => {
33047
+ signal.removeEventListener("abort", onAbort);
33048
+ resolve();
33049
+ }, ms);
33050
+ timer.unref?.();
33051
+ signal.addEventListener("abort", onAbort, { once: true });
33052
+ });
33053
+ }
33054
+ /** Drain `items` through at most `width` concurrent lanes. `fn` must
33055
+ * not reject (callers wrap their own try/catch). */
33056
+ async function runWithConcurrency(items, width, fn) {
33057
+ const queue = [...items];
33058
+ const laneCount = Math.max(1, Math.min(width, queue.length));
33059
+ const lane = async () => {
33060
+ for (;;) {
33061
+ const item = queue.shift();
33062
+ if (item === void 0) return;
33063
+ await fn(item);
33064
+ }
33065
+ };
33066
+ await Promise.all(Array.from({ length: laneCount }, lane));
33067
+ }
33068
+ var DeviceRestoreRetryScheduler = class {
33069
+ #logger;
33070
+ #attempt;
33071
+ #onPermanentFailure;
33072
+ #delaysMs;
33073
+ #concurrency;
33074
+ #now;
33075
+ #abort = new AbortController();
33076
+ constructor(options) {
33077
+ this.#logger = options.logger;
33078
+ this.#attempt = options.attempt;
33079
+ this.#onPermanentFailure = options.onPermanentFailure;
33080
+ this.#delaysMs = options.delaysMs ?? DEVICE_RESTORE_RETRY_DELAYS_MS;
33081
+ this.#concurrency = options.concurrency ?? 4;
33082
+ this.#now = options.now ?? Date.now;
33083
+ }
33084
+ /** Stop retrying (shutdown). Pending entries are NOT marked
33085
+ * permanently failed — the next boot restores them from disk. */
33086
+ cancel() {
33087
+ this.#abort.abort();
33088
+ }
33089
+ /**
33090
+ * Run the bounded retry rounds. Resolves when every entry has either
33091
+ * restored, been marked permanently failed, or the scheduler was
33092
+ * cancelled. Never rejects.
33093
+ */
33094
+ async run(initialFailures) {
33095
+ let pending = initialFailures.map((failure) => ({
33096
+ saved: failure.saved,
33097
+ lastError: failure.error,
33098
+ attempts: 1
33099
+ }));
33100
+ for (let round = 0; round < this.#delaysMs.length; round += 1) {
33101
+ if (pending.length === 0 || this.#abort.signal.aborted) break;
33102
+ await sleep$1(this.#delaysMs[round] ?? 0, this.#abort.signal);
33103
+ if (this.#abort.signal.aborted) break;
33104
+ pending = await this.#runRound(pending, round);
33105
+ }
33106
+ if (this.#abort.signal.aborted) return [];
33107
+ const terminal = pending.map((entry) => ({
33108
+ deviceId: entry.saved.id,
33109
+ stableId: entry.saved.stableId,
33110
+ type: String(entry.saved.type),
33111
+ attempts: entry.attempts,
33112
+ lastError: entry.lastError,
33113
+ failedAt: this.#now()
33114
+ }));
33115
+ for (const failure of terminal) this.#onPermanentFailure(failure);
33116
+ return terminal;
33117
+ }
33118
+ /** One retry round: parents first (phase 0), then hub-adopted
33119
+ * children (phase 1) — a child's attempt depends on its parent
33120
+ * having landed, exactly like the initial two-pass restore. */
33121
+ async #runRound(pending, round) {
33122
+ const next = [];
33123
+ const parents = pending.filter((entry) => entry.saved.parentDeviceId === null);
33124
+ const children = pending.filter((entry) => entry.saved.parentDeviceId !== null);
33125
+ for (const phase of [parents, children]) await runWithConcurrency(phase, this.#concurrency, async (entry) => {
33126
+ if (this.#abort.signal.aborted) {
33127
+ next.push(entry);
33128
+ return;
33129
+ }
33130
+ const attemptNo = entry.attempts + 1;
33131
+ try {
33132
+ await this.#attempt(entry.saved);
33133
+ this.#logger.info("Device restored on retry", {
33134
+ tags: {
33135
+ deviceId: entry.saved.id,
33136
+ stableId: entry.saved.stableId
33137
+ },
33138
+ meta: { attempt: attemptNo }
33139
+ });
33140
+ } catch (err) {
33141
+ const lastError = err instanceof Error ? err.message : String(err);
33142
+ const remainingRetries = this.#delaysMs.length - (round + 1);
33143
+ this.#logger.warn("Device restore retry failed", {
33144
+ tags: {
33145
+ deviceId: entry.saved.id,
33146
+ stableId: entry.saved.stableId
33147
+ },
33148
+ meta: {
33149
+ attempt: attemptNo,
33150
+ remainingRetries,
33151
+ error: lastError
33152
+ }
33153
+ });
33154
+ next.push({
33155
+ saved: entry.saved,
33156
+ lastError,
33157
+ attempts: attemptNo
33158
+ });
33159
+ }
33160
+ });
33161
+ return next;
33162
+ }
33163
+ };
33164
+ /**
32975
33165
  * Convert an IDevice to the flat DeviceSummary shape expected by the
32976
33166
  * device-provider cap router. Shared across all providers.
32977
33167
  */
@@ -33020,6 +33210,7 @@ var BaseDeviceProvider = class extends BaseAddon {
33020
33210
  }];
33021
33211
  }
33022
33212
  async onShutdown() {
33213
+ this.cancelRestoreRetries();
33023
33214
  const devices = await this.ctx.kernel.devices?.getAll() ?? [];
33024
33215
  for (const device of devices) try {
33025
33216
  await this.ctx.kernel.devices?.decommission(device.id);
@@ -33037,9 +33228,16 @@ var BaseDeviceProvider = class extends BaseAddon {
33037
33228
  async start() {}
33038
33229
  async stop() {}
33039
33230
  async getStatus() {
33231
+ const all = await this.ctx.kernel.devices?.getAll() ?? [];
33232
+ const summary = this.restoreFailureSummary();
33233
+ if (summary === null) return {
33234
+ connected: true,
33235
+ deviceCount: all.length
33236
+ };
33040
33237
  return {
33041
33238
  connected: true,
33042
- deviceCount: (await this.ctx.kernel.devices?.getAll() ?? []).length
33239
+ deviceCount: all.length,
33240
+ error: summary
33043
33241
  };
33044
33242
  }
33045
33243
  async getDevices() {
@@ -33129,8 +33327,137 @@ var BaseDeviceProvider = class extends BaseAddon {
33129
33327
  };
33130
33328
  }
33131
33329
  async restoreDevices(savedDevices) {
33132
- await this.onRestoreDevices(savedDevices);
33133
- if (savedDevices.length > 0) this.ctx.logger.info(`Restored ${savedDevices.length} ${this.providerName} device(s)`);
33330
+ const report = await this.onRestoreDevices(savedDevices);
33331
+ if (savedDevices.length === 0) return;
33332
+ if (report && report.failedCount > 0) {
33333
+ this.ctx.logger.warn(`Restored ${report.restoredCount}/${savedDevices.length} ${this.providerName} device(s) — ${report.failedCount} failed, bounded retry scheduled`);
33334
+ return;
33335
+ }
33336
+ const restoredCount = report ? report.restoredCount : savedDevices.length;
33337
+ this.ctx.logger.info(`Restored ${restoredCount} ${this.providerName} device(s)`);
33338
+ }
33339
+ /** Retry schedule. Overridable (tests use millisecond delays). */
33340
+ restoreRetryDelaysMs = DEVICE_RESTORE_RETRY_DELAYS_MS;
33341
+ /** Retry lane width. See `device-restore-retry.ts` for why retries
33342
+ * never re-stampede full-width while the initial pass does (D167). */
33343
+ restoreRetryConcurrency = 4;
33344
+ _restoreRetryScheduler = null;
33345
+ _restoreRetryCompletion = null;
33346
+ _permanentRestoreFailures = /* @__PURE__ */ new Map();
33347
+ /** Settles when the background retry rounds finish (or `null` when
33348
+ * nothing failed). Exposed for tests and subclass diagnostics —
33349
+ * boot NEVER awaits this: the runner's post-init handshake goes out
33350
+ * with the devices that restored, and a late success is announced
33351
+ * through the `native-cap-change` → `updateCaps` path. */
33352
+ get restoreRetryCompletion() {
33353
+ return this._restoreRetryCompletion;
33354
+ }
33355
+ /** Devices that exhausted the retry bound this process lifetime. */
33356
+ get permanentRestoreFailures() {
33357
+ return [...this._permanentRestoreFailures.values()];
33358
+ }
33359
+ /** One-line operator-facing summary for `getStatus().error`, or
33360
+ * `null` when every device restored. */
33361
+ restoreFailureSummary() {
33362
+ if (this._permanentRestoreFailures.size === 0) return null;
33363
+ const ids = [...this._permanentRestoreFailures.keys()].join(", ");
33364
+ return `${this._permanentRestoreFailures.size} device(s) permanently failed restore (deviceIds: ${ids}) — restart the ${this.providerName} provider to retry`;
33365
+ }
33366
+ cancelRestoreRetries() {
33367
+ this._restoreRetryScheduler?.cancel();
33368
+ this._restoreRetryScheduler = null;
33369
+ }
33370
+ recordPermanentRestoreFailure(failure) {
33371
+ this._permanentRestoreFailures.set(failure.deviceId, failure);
33372
+ this.ctx.logger.error("Device restore permanently failed — its capabilities will not register until the provider restarts", {
33373
+ tags: {
33374
+ deviceId: failure.deviceId,
33375
+ stableId: failure.stableId
33376
+ },
33377
+ meta: {
33378
+ type: failure.type,
33379
+ attempts: failure.attempts,
33380
+ error: failure.lastError
33381
+ }
33382
+ });
33383
+ }
33384
+ scheduleRestoreRetries(failures, attempt) {
33385
+ const scheduler = new DeviceRestoreRetryScheduler({
33386
+ logger: this.ctx.logger,
33387
+ delaysMs: this.restoreRetryDelaysMs,
33388
+ concurrency: this.restoreRetryConcurrency,
33389
+ attempt,
33390
+ onPermanentFailure: (failure) => this.recordPermanentRestoreFailure(failure)
33391
+ });
33392
+ this._restoreRetryScheduler = scheduler;
33393
+ this._restoreRetryCompletion = scheduler.run(failures).then(() => void 0).catch((err) => {
33394
+ this.ctx.logger.error("Restore retry scheduler crashed", { meta: { error: err instanceof Error ? err.message : String(err) } });
33395
+ });
33396
+ }
33397
+ /**
33398
+ * Tear down and reconstruct ONE device from its persisted rows — the
33399
+ * `deviceProvider.reloadDevice` cap method. Persistence is never touched,
33400
+ * and no other device this provider owns is disturbed.
33401
+ *
33402
+ * Keyed by `stableId` because the caller's whole reason to be here is that
33403
+ * the NUMERIC id changed (`deviceManager.migrateDevice` swapped it): the
33404
+ * fresh instance resolves its id through `allocateDeviceId`, which returns
33405
+ * whatever number the row carries NOW. The teardown is `decommission` —
33406
+ * exactly what a graceful shutdown runs per device (fires `removeDevice()`,
33407
+ * unregisters native caps, drops the registry entry) — and the rebuild is
33408
+ * the boot restore's own `create()` path, including its pass 2: first-class
33409
+ * children (hub-adopted cameras under an NVR) are decommissioned with the
33410
+ * parent by the cascade and must be re-created explicitly, because only
33411
+ * accessory children come back through `getAccessoryChildren()`.
33412
+ *
33413
+ * Reloading an accessory child directly is refused (no device class) —
33414
+ * reload its parent instead.
33415
+ */
33416
+ async reloadDevice(input) {
33417
+ const { stableId } = input;
33418
+ const devices = this.ctx.kernel.devices;
33419
+ if (!devices) throw new Error(`${this.providerName}: kernel.devices unavailable — cannot reload`);
33420
+ const live = (await devices.getAll()).find((d) => d.stableId === stableId);
33421
+ if (live) await devices.decommission(live.id);
33422
+ const { id } = await this.ctx.api.deviceManager.allocateDeviceId.mutate({
33423
+ addonId: this.addonId,
33424
+ stableId
33425
+ });
33426
+ const meta = await this.ctx.api.deviceManager.loadMeta.query({ deviceId: id });
33427
+ if (meta === null) throw new Error(`${this.providerName}: no persisted meta for "${stableId}" (id ${id}) — cannot reload`);
33428
+ const deviceType = Object.values(DeviceType).find((t) => t === meta.type);
33429
+ const Class = deviceType !== void 0 ? this.deviceClasses[deviceType] : void 0;
33430
+ if (!Class) throw new Error(`${this.providerName}: no device class for type "${meta.type}" — "${stableId}" is an accessory child; reload its parent instead`);
33431
+ await devices.create(stableId, Class, {}, meta.parentDeviceId ?? null);
33432
+ const rows = await this.ctx.api.deviceManager.listPersistedByAddon.query({ addonId: this.addonId });
33433
+ for (const row of rows) {
33434
+ if (row.parentDeviceId !== id) continue;
33435
+ const childType = Object.values(DeviceType).find((t) => t === row.type);
33436
+ const ChildClass = childType !== void 0 ? this.deviceClasses[childType] : void 0;
33437
+ if (!ChildClass) continue;
33438
+ try {
33439
+ await devices.create(row.stableId, ChildClass, {}, id);
33440
+ } catch (err) {
33441
+ this.ctx.logger.warn("reloadDevice: failed to re-create first-class child", {
33442
+ tags: {
33443
+ deviceId: row.id,
33444
+ stableId: row.stableId
33445
+ },
33446
+ meta: {
33447
+ parentDeviceId: id,
33448
+ error: err instanceof Error ? err.message : String(err)
33449
+ }
33450
+ });
33451
+ }
33452
+ }
33453
+ this.ctx.logger.info("device reloaded in place from persisted rows", {
33454
+ tags: { deviceId: id },
33455
+ meta: {
33456
+ stableId,
33457
+ type: meta.type
33458
+ }
33459
+ });
33460
+ return { deviceId: id };
33134
33461
  }
33135
33462
  /**
33136
33463
  * Restore devices from persisted state. Two-pass:
@@ -33156,55 +33483,125 @@ var BaseDeviceProvider = class extends BaseAddon {
33156
33483
  * accessory-spawn flow handles via the parent's
33157
33484
  * `getAccessoryChildren()`. Override only when the default doesn't
33158
33485
  * fit.
33486
+ *
33487
+ * A row that fails either pass is NOT terminal (D347): it is handed
33488
+ * to a bounded background retry (`DeviceRestoreRetryScheduler`).
33489
+ * Only after the bound is exhausted is the device marked permanently
33490
+ * failed — logged at ERROR with `tags.deviceId` and surfaced via
33491
+ * `getStatus().error`.
33159
33492
  */
33493
+ /**
33494
+ * Repair a row's PERSISTED config blob immediately before it is restored.
33495
+ * Default: no-op — most providers have nothing to heal.
33496
+ *
33497
+ * This exists because a restored device self-hydrates from the DB: `create()`
33498
+ * passes `{}` and `BaseDevice` parses the stored blob against the device
33499
+ * schema. A blob that lost a REQUIRED field therefore fails restore forever,
33500
+ * and no later pass revisits it — a hub-adopted Reolink camera whose blob had
33501
+ * been emptied failed all four bounded attempts against fields
33502
+ * (`host`, `password`) it inherits from its parent and never dials itself.
33503
+ *
33504
+ * Implementations get every saved row, so a child can read its parent's blob.
33505
+ * A heal that throws is treated like any other restore failure: retried under
33506
+ * the bound, then reported — never swallowed.
33507
+ */
33508
+ async healSavedConfig(_saved, _allSaved) {}
33160
33509
  async onRestoreDevices(savedDevices) {
33161
33510
  const restored = /* @__PURE__ */ new Set();
33511
+ const failures = [];
33512
+ const attemptRestore = async (saved) => {
33513
+ if (restored.has(saved.id)) return;
33514
+ const Class = this.deviceClasses[saved.type];
33515
+ if (!Class) throw new Error(`no device class registered for type "${saved.type}"`);
33516
+ if (saved.parentDeviceId !== null && !restored.has(saved.parentDeviceId)) throw new Error(`parent device ${saved.parentDeviceId} not restored`);
33517
+ await this.healSavedConfig(saved, savedDevices);
33518
+ await this.ctx.kernel.devices.create(saved.stableId, Class, {}, saved.parentDeviceId);
33519
+ restored.add(saved.id);
33520
+ };
33162
33521
  const topLevel = savedDevices.filter((saved) => saved.parentDeviceId === null);
33163
33522
  const restoreOne = async (saved) => {
33164
- const Class = this.deviceClasses[saved.type];
33165
- if (!Class) {
33523
+ if (!this.deviceClasses[saved.type]) {
33166
33524
  this.ctx.logger.warn("No device class registered for restored type — skipping", {
33167
- tags: { stableId: saved.stableId },
33525
+ tags: {
33526
+ deviceId: saved.id,
33527
+ stableId: saved.stableId
33528
+ },
33168
33529
  meta: { type: saved.type }
33169
33530
  });
33170
33531
  return;
33171
33532
  }
33172
33533
  try {
33173
- await this.ctx.kernel.devices.create(saved.stableId, Class, {});
33174
- restored.add(saved.id);
33534
+ await attemptRestore(saved);
33175
33535
  } catch (err) {
33176
- this.ctx.logger.warn("Failed to restore device", {
33177
- tags: { stableId: saved.stableId },
33536
+ const error = err instanceof Error ? err.message : String(err);
33537
+ this.ctx.logger.warn("Failed to restore device — bounded retry scheduled", {
33538
+ tags: {
33539
+ deviceId: saved.id,
33540
+ stableId: saved.stableId
33541
+ },
33178
33542
  meta: {
33179
33543
  type: saved.type,
33180
- error: err instanceof Error ? err.message : String(err)
33544
+ attempt: 1,
33545
+ error
33181
33546
  }
33182
33547
  });
33548
+ failures.push({
33549
+ saved,
33550
+ error
33551
+ });
33183
33552
  }
33184
33553
  };
33185
33554
  await Promise.all(topLevel.map((saved) => restoreOne(saved)));
33555
+ const failedTopLevelIds = new Set(failures.map((failure) => failure.saved.id));
33186
33556
  const childRows = savedDevices.filter((s) => s.parentDeviceId !== null);
33187
33557
  for (const saved of childRows) {
33188
- const Class = this.deviceClasses[saved.type];
33189
- if (!Class) continue;
33558
+ if (!this.deviceClasses[saved.type]) continue;
33190
33559
  if (saved.parentDeviceId === null) continue;
33191
- if (!restored.has(saved.parentDeviceId)) continue;
33192
- try {
33193
- await this.ctx.kernel.devices.create(saved.stableId, Class, {}, saved.parentDeviceId);
33194
- restored.add(saved.id);
33195
- } catch (err) {
33196
- this.ctx.logger.warn("Failed to restore hub-adopted child", {
33560
+ if (restored.has(saved.parentDeviceId)) {
33561
+ try {
33562
+ await attemptRestore(saved);
33563
+ } catch (err) {
33564
+ const error = err instanceof Error ? err.message : String(err);
33565
+ this.ctx.logger.warn("Failed to restore hub-adopted child — bounded retry scheduled", {
33566
+ tags: {
33567
+ deviceId: saved.id,
33568
+ stableId: saved.stableId,
33569
+ parentDeviceId: saved.parentDeviceId
33570
+ },
33571
+ meta: {
33572
+ type: saved.type,
33573
+ attempt: 1,
33574
+ error
33575
+ }
33576
+ });
33577
+ failures.push({
33578
+ saved,
33579
+ error
33580
+ });
33581
+ }
33582
+ continue;
33583
+ }
33584
+ if (failedTopLevelIds.has(saved.parentDeviceId)) {
33585
+ this.ctx.logger.warn("Hub-adopted child deferred — parent failed initial restore", {
33197
33586
  tags: {
33587
+ deviceId: saved.id,
33198
33588
  stableId: saved.stableId,
33199
33589
  parentDeviceId: saved.parentDeviceId
33200
33590
  },
33201
- meta: {
33202
- type: saved.type,
33203
- error: err instanceof Error ? err.message : String(err)
33204
- }
33591
+ meta: { type: saved.type }
33205
33592
  });
33593
+ failures.push({
33594
+ saved,
33595
+ error: `parent device ${saved.parentDeviceId} not restored`
33596
+ });
33597
+ continue;
33206
33598
  }
33207
33599
  }
33600
+ if (failures.length > 0) this.scheduleRestoreRetries(failures, attemptRestore);
33601
+ return {
33602
+ restoredCount: restored.size,
33603
+ failedCount: failures.length
33604
+ };
33208
33605
  }
33209
33606
  /** Convert an IDevice to the flat DeviceSummary for the cap router. */
33210
33607
  toSummary(device) {
@@ -34967,6 +35364,12 @@ Object.freeze({
34967
35364
  addonId: null,
34968
35365
  access: "view"
34969
35366
  },
35367
+ "deviceProvider.reloadDevice": {
35368
+ capName: "device-provider",
35369
+ capScope: "system",
35370
+ addonId: null,
35371
+ access: "create"
35372
+ },
34970
35373
  "deviceProvider.start": {
34971
35374
  capName: "device-provider",
34972
35375
  capScope: "system",
@@ -3,7 +3,7 @@ Object.defineProperties(exports, {
3
3
  [Symbol.toStringTag]: { value: "Module" }
4
4
  });
5
5
  //#endregion
6
- const require_dist = require("../dist-BiCYEtvX.js");
6
+ const require_dist = require("../dist-gv0Gmrm1.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-BQ3x3HG3.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-CQzCvoCx.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.73",
3
+ "version": "1.2.75",
4
4
  "description": "Home Assistant device provider addon for CamStack",
5
5
  "keywords": [
6
6
  "camstack",