@camstack/addon-import-alexa 0.2.58 → 0.2.60

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/addon.js +428 -25
  2. package/dist/addon.mjs +428 -25
  3. package/package.json +1 -1
package/dist/addon.js CHANGED
@@ -12999,7 +12999,26 @@ var DiscoveryCandidateSchema = object({
12999
12999
  * identity ahead of adoption. Rendering metadata (unit, precision)
13000
13000
  * flows live through the cap STATUS SLICE after adoption.
13001
13001
  */
13002
- sourceInfo: SourceInfoSchema.optional()
13002
+ sourceInfo: SourceInfoSchema.optional(),
13003
+ /**
13004
+ * Set when this candidate is a device the provider ALREADY owns.
13005
+ *
13006
+ * A scan cannot generally produce the identity a device was onboarded under
13007
+ * (Reolink keys on `mac-<mac>`, learned at adopt time), so a stableId
13008
+ * comparison never matches and an owned device looks addable. Re-adopting one
13009
+ * overwrites its config with scan-derived values — that is how a Home Hub's
13010
+ * Baichuan port was overwritten with its ONVIF port, taking the hub and its
13011
+ * three child cameras offline for four hours.
13012
+ *
13013
+ * A provider that can recognise its own devices says so here. Absent means
13014
+ * "not recognised", which is not the same as "known to be new" — a provider
13015
+ * that cannot tell simply never sets it.
13016
+ */
13017
+ alreadyOnboarded: boolean().optional(),
13018
+ /** Numeric id of the device this candidate was matched to. Set with `alreadyOnboarded`. */
13019
+ onboardedDeviceId: number().optional(),
13020
+ /** Operator-facing name of the matched device, so the UI can say WHICH one it is. */
13021
+ onboardedName: string().optional()
13003
13022
  });
13004
13023
  /**
13005
13024
  * Flat device summary returned by `createDevice` / `adoptDiscoveredDevice`.
@@ -13055,6 +13074,35 @@ var deviceProviderCapability = {
13055
13074
  name: string(),
13056
13075
  type: string()
13057
13076
  }))),
13077
+ /**
13078
+ * Tear down and reconstruct ONE device in place from its persisted rows —
13079
+ * touching no other device this provider owns.
13080
+ *
13081
+ * The primitive `deviceManager.migrateDevice` uses to flush the two
13082
+ * migrated numbers: after `swapIds` the runner's live instance still
13083
+ * carries the PRE-swap numeric id (baked into the object, its native-cap
13084
+ * registrations and its log tags), and a live object cannot be renumbered.
13085
+ * Before this method the only flush was restarting the whole owning addon
13086
+ * — which took every camera the provider owns down with it (28 devices
13087
+ * for one migrated camera, measured 2026-09-04, and the morning of the
13088
+ * same day ~27 devices' native caps did not come back on their own).
13089
+ *
13090
+ * Keyed by `stableId`, deliberately: the numeric id is exactly the thing
13091
+ * that changes. The reply carries the id the device answers on NOW.
13092
+ * Implemented once in `BaseDeviceProvider` — decommission the live
13093
+ * instance (if any), then re-create from the persisted row: the same
13094
+ * teardown/rehydrate pair every graceful shutdown + boot already uses.
13095
+ * An RPC, never an event: a dropped event would leave the runner writing
13096
+ * against the wrong camera (D8).
13097
+ *
13098
+ * Construction can dial hardware, and the migrated source is
13099
+ * characteristically dead — the timeout covers a full activate window
13100
+ * rather than the 60 s default.
13101
+ */
13102
+ reloadDevice: method(object({ stableId: string() }), object({ deviceId: number() }), {
13103
+ kind: "mutation",
13104
+ timeoutMs: 3 * 6e4
13105
+ }),
13058
13106
  supportsDiscovery: method(object({}), boolean()),
13059
13107
  /**
13060
13108
  * Run a network scan. `params` carries optional provider-specific scan
@@ -13382,7 +13430,8 @@ method(object({
13382
13430
  targetId: number()
13383
13431
  }), MigrateDeviceResultSchema, {
13384
13432
  kind: "mutation",
13385
- auth: "admin"
13433
+ auth: "admin",
13434
+ timeoutMs: 12 * 6e4
13386
13435
  }), 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({
13387
13436
  deviceId: number(),
13388
13437
  name: string()
@@ -32755,6 +32804,147 @@ var BaseDevice = class {
32755
32804
  }
32756
32805
  };
32757
32806
  /**
32807
+ * Delays before retry rounds 1..N — the round count IS the bound.
32808
+ * 10 s catches "the hub was busy for a moment"; the full schedule
32809
+ * (10 + 30 + 90 s of waiting, plus up to one 60 s transport timeout
32810
+ * per attempt) covers a device-manager lock held for minutes — the
32811
+ * 2026-09-04 outage's migration hold was ~3.5 min.
32812
+ */
32813
+ var DEVICE_RESTORE_RETRY_DELAYS_MS = [
32814
+ 1e4,
32815
+ 3e4,
32816
+ 9e4
32817
+ ];
32818
+ /** Abortable sleep — resolves early (never rejects) on abort. */
32819
+ function sleep$1(ms, signal) {
32820
+ return new Promise((resolve) => {
32821
+ if (signal.aborted) {
32822
+ resolve();
32823
+ return;
32824
+ }
32825
+ const onAbort = () => {
32826
+ clearTimeout(timer);
32827
+ resolve();
32828
+ };
32829
+ const timer = setTimeout(() => {
32830
+ signal.removeEventListener("abort", onAbort);
32831
+ resolve();
32832
+ }, ms);
32833
+ timer.unref?.();
32834
+ signal.addEventListener("abort", onAbort, { once: true });
32835
+ });
32836
+ }
32837
+ /** Drain `items` through at most `width` concurrent lanes. `fn` must
32838
+ * not reject (callers wrap their own try/catch). */
32839
+ async function runWithConcurrency(items, width, fn) {
32840
+ const queue = [...items];
32841
+ const laneCount = Math.max(1, Math.min(width, queue.length));
32842
+ const lane = async () => {
32843
+ for (;;) {
32844
+ const item = queue.shift();
32845
+ if (item === void 0) return;
32846
+ await fn(item);
32847
+ }
32848
+ };
32849
+ await Promise.all(Array.from({ length: laneCount }, lane));
32850
+ }
32851
+ var DeviceRestoreRetryScheduler = class {
32852
+ #logger;
32853
+ #attempt;
32854
+ #onPermanentFailure;
32855
+ #delaysMs;
32856
+ #concurrency;
32857
+ #now;
32858
+ #abort = new AbortController();
32859
+ constructor(options) {
32860
+ this.#logger = options.logger;
32861
+ this.#attempt = options.attempt;
32862
+ this.#onPermanentFailure = options.onPermanentFailure;
32863
+ this.#delaysMs = options.delaysMs ?? DEVICE_RESTORE_RETRY_DELAYS_MS;
32864
+ this.#concurrency = options.concurrency ?? 4;
32865
+ this.#now = options.now ?? Date.now;
32866
+ }
32867
+ /** Stop retrying (shutdown). Pending entries are NOT marked
32868
+ * permanently failed — the next boot restores them from disk. */
32869
+ cancel() {
32870
+ this.#abort.abort();
32871
+ }
32872
+ /**
32873
+ * Run the bounded retry rounds. Resolves when every entry has either
32874
+ * restored, been marked permanently failed, or the scheduler was
32875
+ * cancelled. Never rejects.
32876
+ */
32877
+ async run(initialFailures) {
32878
+ let pending = initialFailures.map((failure) => ({
32879
+ saved: failure.saved,
32880
+ lastError: failure.error,
32881
+ attempts: 1
32882
+ }));
32883
+ for (let round = 0; round < this.#delaysMs.length; round += 1) {
32884
+ if (pending.length === 0 || this.#abort.signal.aborted) break;
32885
+ await sleep$1(this.#delaysMs[round] ?? 0, this.#abort.signal);
32886
+ if (this.#abort.signal.aborted) break;
32887
+ pending = await this.#runRound(pending, round);
32888
+ }
32889
+ if (this.#abort.signal.aborted) return [];
32890
+ const terminal = pending.map((entry) => ({
32891
+ deviceId: entry.saved.id,
32892
+ stableId: entry.saved.stableId,
32893
+ type: String(entry.saved.type),
32894
+ attempts: entry.attempts,
32895
+ lastError: entry.lastError,
32896
+ failedAt: this.#now()
32897
+ }));
32898
+ for (const failure of terminal) this.#onPermanentFailure(failure);
32899
+ return terminal;
32900
+ }
32901
+ /** One retry round: parents first (phase 0), then hub-adopted
32902
+ * children (phase 1) — a child's attempt depends on its parent
32903
+ * having landed, exactly like the initial two-pass restore. */
32904
+ async #runRound(pending, round) {
32905
+ const next = [];
32906
+ const parents = pending.filter((entry) => entry.saved.parentDeviceId === null);
32907
+ const children = pending.filter((entry) => entry.saved.parentDeviceId !== null);
32908
+ for (const phase of [parents, children]) await runWithConcurrency(phase, this.#concurrency, async (entry) => {
32909
+ if (this.#abort.signal.aborted) {
32910
+ next.push(entry);
32911
+ return;
32912
+ }
32913
+ const attemptNo = entry.attempts + 1;
32914
+ try {
32915
+ await this.#attempt(entry.saved);
32916
+ this.#logger.info("Device restored on retry", {
32917
+ tags: {
32918
+ deviceId: entry.saved.id,
32919
+ stableId: entry.saved.stableId
32920
+ },
32921
+ meta: { attempt: attemptNo }
32922
+ });
32923
+ } catch (err) {
32924
+ const lastError = err instanceof Error ? err.message : String(err);
32925
+ const remainingRetries = this.#delaysMs.length - (round + 1);
32926
+ this.#logger.warn("Device restore retry failed", {
32927
+ tags: {
32928
+ deviceId: entry.saved.id,
32929
+ stableId: entry.saved.stableId
32930
+ },
32931
+ meta: {
32932
+ attempt: attemptNo,
32933
+ remainingRetries,
32934
+ error: lastError
32935
+ }
32936
+ });
32937
+ next.push({
32938
+ saved: entry.saved,
32939
+ lastError,
32940
+ attempts: attemptNo
32941
+ });
32942
+ }
32943
+ });
32944
+ return next;
32945
+ }
32946
+ };
32947
+ /**
32758
32948
  * Convert an IDevice to the flat DeviceSummary shape expected by the
32759
32949
  * device-provider cap router. Shared across all providers.
32760
32950
  */
@@ -32803,6 +32993,7 @@ var BaseDeviceProvider = class extends BaseAddon {
32803
32993
  }];
32804
32994
  }
32805
32995
  async onShutdown() {
32996
+ this.cancelRestoreRetries();
32806
32997
  const devices = await this.ctx.kernel.devices?.getAll() ?? [];
32807
32998
  for (const device of devices) try {
32808
32999
  await this.ctx.kernel.devices?.decommission(device.id);
@@ -32820,9 +33011,16 @@ var BaseDeviceProvider = class extends BaseAddon {
32820
33011
  async start() {}
32821
33012
  async stop() {}
32822
33013
  async getStatus() {
33014
+ const all = await this.ctx.kernel.devices?.getAll() ?? [];
33015
+ const summary = this.restoreFailureSummary();
33016
+ if (summary === null) return {
33017
+ connected: true,
33018
+ deviceCount: all.length
33019
+ };
32823
33020
  return {
32824
33021
  connected: true,
32825
- deviceCount: (await this.ctx.kernel.devices?.getAll() ?? []).length
33022
+ deviceCount: all.length,
33023
+ error: summary
32826
33024
  };
32827
33025
  }
32828
33026
  async getDevices() {
@@ -32912,8 +33110,137 @@ var BaseDeviceProvider = class extends BaseAddon {
32912
33110
  };
32913
33111
  }
32914
33112
  async restoreDevices(savedDevices) {
32915
- await this.onRestoreDevices(savedDevices);
32916
- if (savedDevices.length > 0) this.ctx.logger.info(`Restored ${savedDevices.length} ${this.providerName} device(s)`);
33113
+ const report = await this.onRestoreDevices(savedDevices);
33114
+ if (savedDevices.length === 0) return;
33115
+ if (report && report.failedCount > 0) {
33116
+ this.ctx.logger.warn(`Restored ${report.restoredCount}/${savedDevices.length} ${this.providerName} device(s) — ${report.failedCount} failed, bounded retry scheduled`);
33117
+ return;
33118
+ }
33119
+ const restoredCount = report ? report.restoredCount : savedDevices.length;
33120
+ this.ctx.logger.info(`Restored ${restoredCount} ${this.providerName} device(s)`);
33121
+ }
33122
+ /** Retry schedule. Overridable (tests use millisecond delays). */
33123
+ restoreRetryDelaysMs = DEVICE_RESTORE_RETRY_DELAYS_MS;
33124
+ /** Retry lane width. See `device-restore-retry.ts` for why retries
33125
+ * never re-stampede full-width while the initial pass does (D167). */
33126
+ restoreRetryConcurrency = 4;
33127
+ _restoreRetryScheduler = null;
33128
+ _restoreRetryCompletion = null;
33129
+ _permanentRestoreFailures = /* @__PURE__ */ new Map();
33130
+ /** Settles when the background retry rounds finish (or `null` when
33131
+ * nothing failed). Exposed for tests and subclass diagnostics —
33132
+ * boot NEVER awaits this: the runner's post-init handshake goes out
33133
+ * with the devices that restored, and a late success is announced
33134
+ * through the `native-cap-change` → `updateCaps` path. */
33135
+ get restoreRetryCompletion() {
33136
+ return this._restoreRetryCompletion;
33137
+ }
33138
+ /** Devices that exhausted the retry bound this process lifetime. */
33139
+ get permanentRestoreFailures() {
33140
+ return [...this._permanentRestoreFailures.values()];
33141
+ }
33142
+ /** One-line operator-facing summary for `getStatus().error`, or
33143
+ * `null` when every device restored. */
33144
+ restoreFailureSummary() {
33145
+ if (this._permanentRestoreFailures.size === 0) return null;
33146
+ const ids = [...this._permanentRestoreFailures.keys()].join(", ");
33147
+ return `${this._permanentRestoreFailures.size} device(s) permanently failed restore (deviceIds: ${ids}) — restart the ${this.providerName} provider to retry`;
33148
+ }
33149
+ cancelRestoreRetries() {
33150
+ this._restoreRetryScheduler?.cancel();
33151
+ this._restoreRetryScheduler = null;
33152
+ }
33153
+ recordPermanentRestoreFailure(failure) {
33154
+ this._permanentRestoreFailures.set(failure.deviceId, failure);
33155
+ this.ctx.logger.error("Device restore permanently failed — its capabilities will not register until the provider restarts", {
33156
+ tags: {
33157
+ deviceId: failure.deviceId,
33158
+ stableId: failure.stableId
33159
+ },
33160
+ meta: {
33161
+ type: failure.type,
33162
+ attempts: failure.attempts,
33163
+ error: failure.lastError
33164
+ }
33165
+ });
33166
+ }
33167
+ scheduleRestoreRetries(failures, attempt) {
33168
+ const scheduler = new DeviceRestoreRetryScheduler({
33169
+ logger: this.ctx.logger,
33170
+ delaysMs: this.restoreRetryDelaysMs,
33171
+ concurrency: this.restoreRetryConcurrency,
33172
+ attempt,
33173
+ onPermanentFailure: (failure) => this.recordPermanentRestoreFailure(failure)
33174
+ });
33175
+ this._restoreRetryScheduler = scheduler;
33176
+ this._restoreRetryCompletion = scheduler.run(failures).then(() => void 0).catch((err) => {
33177
+ this.ctx.logger.error("Restore retry scheduler crashed", { meta: { error: err instanceof Error ? err.message : String(err) } });
33178
+ });
33179
+ }
33180
+ /**
33181
+ * Tear down and reconstruct ONE device from its persisted rows — the
33182
+ * `deviceProvider.reloadDevice` cap method. Persistence is never touched,
33183
+ * and no other device this provider owns is disturbed.
33184
+ *
33185
+ * Keyed by `stableId` because the caller's whole reason to be here is that
33186
+ * the NUMERIC id changed (`deviceManager.migrateDevice` swapped it): the
33187
+ * fresh instance resolves its id through `allocateDeviceId`, which returns
33188
+ * whatever number the row carries NOW. The teardown is `decommission` —
33189
+ * exactly what a graceful shutdown runs per device (fires `removeDevice()`,
33190
+ * unregisters native caps, drops the registry entry) — and the rebuild is
33191
+ * the boot restore's own `create()` path, including its pass 2: first-class
33192
+ * children (hub-adopted cameras under an NVR) are decommissioned with the
33193
+ * parent by the cascade and must be re-created explicitly, because only
33194
+ * accessory children come back through `getAccessoryChildren()`.
33195
+ *
33196
+ * Reloading an accessory child directly is refused (no device class) —
33197
+ * reload its parent instead.
33198
+ */
33199
+ async reloadDevice(input) {
33200
+ const { stableId } = input;
33201
+ const devices = this.ctx.kernel.devices;
33202
+ if (!devices) throw new Error(`${this.providerName}: kernel.devices unavailable — cannot reload`);
33203
+ const live = (await devices.getAll()).find((d) => d.stableId === stableId);
33204
+ if (live) await devices.decommission(live.id);
33205
+ const { id } = await this.ctx.api.deviceManager.allocateDeviceId.mutate({
33206
+ addonId: this.addonId,
33207
+ stableId
33208
+ });
33209
+ const meta = await this.ctx.api.deviceManager.loadMeta.query({ deviceId: id });
33210
+ if (meta === null) throw new Error(`${this.providerName}: no persisted meta for "${stableId}" (id ${id}) — cannot reload`);
33211
+ const deviceType = Object.values(DeviceType).find((t) => t === meta.type);
33212
+ const Class = deviceType !== void 0 ? this.deviceClasses[deviceType] : void 0;
33213
+ if (!Class) throw new Error(`${this.providerName}: no device class for type "${meta.type}" — "${stableId}" is an accessory child; reload its parent instead`);
33214
+ await devices.create(stableId, Class, {}, meta.parentDeviceId ?? null);
33215
+ const rows = await this.ctx.api.deviceManager.listPersistedByAddon.query({ addonId: this.addonId });
33216
+ for (const row of rows) {
33217
+ if (row.parentDeviceId !== id) continue;
33218
+ const childType = Object.values(DeviceType).find((t) => t === row.type);
33219
+ const ChildClass = childType !== void 0 ? this.deviceClasses[childType] : void 0;
33220
+ if (!ChildClass) continue;
33221
+ try {
33222
+ await devices.create(row.stableId, ChildClass, {}, id);
33223
+ } catch (err) {
33224
+ this.ctx.logger.warn("reloadDevice: failed to re-create first-class child", {
33225
+ tags: {
33226
+ deviceId: row.id,
33227
+ stableId: row.stableId
33228
+ },
33229
+ meta: {
33230
+ parentDeviceId: id,
33231
+ error: err instanceof Error ? err.message : String(err)
33232
+ }
33233
+ });
33234
+ }
33235
+ }
33236
+ this.ctx.logger.info("device reloaded in place from persisted rows", {
33237
+ tags: { deviceId: id },
33238
+ meta: {
33239
+ stableId,
33240
+ type: meta.type
33241
+ }
33242
+ });
33243
+ return { deviceId: id };
32917
33244
  }
32918
33245
  /**
32919
33246
  * Restore devices from persisted state. Two-pass:
@@ -32939,55 +33266,125 @@ var BaseDeviceProvider = class extends BaseAddon {
32939
33266
  * accessory-spawn flow handles via the parent's
32940
33267
  * `getAccessoryChildren()`. Override only when the default doesn't
32941
33268
  * fit.
33269
+ *
33270
+ * A row that fails either pass is NOT terminal (D347): it is handed
33271
+ * to a bounded background retry (`DeviceRestoreRetryScheduler`).
33272
+ * Only after the bound is exhausted is the device marked permanently
33273
+ * failed — logged at ERROR with `tags.deviceId` and surfaced via
33274
+ * `getStatus().error`.
32942
33275
  */
33276
+ /**
33277
+ * Repair a row's PERSISTED config blob immediately before it is restored.
33278
+ * Default: no-op — most providers have nothing to heal.
33279
+ *
33280
+ * This exists because a restored device self-hydrates from the DB: `create()`
33281
+ * passes `{}` and `BaseDevice` parses the stored blob against the device
33282
+ * schema. A blob that lost a REQUIRED field therefore fails restore forever,
33283
+ * and no later pass revisits it — a hub-adopted Reolink camera whose blob had
33284
+ * been emptied failed all four bounded attempts against fields
33285
+ * (`host`, `password`) it inherits from its parent and never dials itself.
33286
+ *
33287
+ * Implementations get every saved row, so a child can read its parent's blob.
33288
+ * A heal that throws is treated like any other restore failure: retried under
33289
+ * the bound, then reported — never swallowed.
33290
+ */
33291
+ async healSavedConfig(_saved, _allSaved) {}
32943
33292
  async onRestoreDevices(savedDevices) {
32944
33293
  const restored = /* @__PURE__ */ new Set();
33294
+ const failures = [];
33295
+ const attemptRestore = async (saved) => {
33296
+ if (restored.has(saved.id)) return;
33297
+ const Class = this.deviceClasses[saved.type];
33298
+ if (!Class) throw new Error(`no device class registered for type "${saved.type}"`);
33299
+ if (saved.parentDeviceId !== null && !restored.has(saved.parentDeviceId)) throw new Error(`parent device ${saved.parentDeviceId} not restored`);
33300
+ await this.healSavedConfig(saved, savedDevices);
33301
+ await this.ctx.kernel.devices.create(saved.stableId, Class, {}, saved.parentDeviceId);
33302
+ restored.add(saved.id);
33303
+ };
32945
33304
  const topLevel = savedDevices.filter((saved) => saved.parentDeviceId === null);
32946
33305
  const restoreOne = async (saved) => {
32947
- const Class = this.deviceClasses[saved.type];
32948
- if (!Class) {
33306
+ if (!this.deviceClasses[saved.type]) {
32949
33307
  this.ctx.logger.warn("No device class registered for restored type — skipping", {
32950
- tags: { stableId: saved.stableId },
33308
+ tags: {
33309
+ deviceId: saved.id,
33310
+ stableId: saved.stableId
33311
+ },
32951
33312
  meta: { type: saved.type }
32952
33313
  });
32953
33314
  return;
32954
33315
  }
32955
33316
  try {
32956
- await this.ctx.kernel.devices.create(saved.stableId, Class, {});
32957
- restored.add(saved.id);
33317
+ await attemptRestore(saved);
32958
33318
  } catch (err) {
32959
- this.ctx.logger.warn("Failed to restore device", {
32960
- tags: { stableId: saved.stableId },
33319
+ const error = err instanceof Error ? err.message : String(err);
33320
+ this.ctx.logger.warn("Failed to restore device — bounded retry scheduled", {
33321
+ tags: {
33322
+ deviceId: saved.id,
33323
+ stableId: saved.stableId
33324
+ },
32961
33325
  meta: {
32962
33326
  type: saved.type,
32963
- error: err instanceof Error ? err.message : String(err)
33327
+ attempt: 1,
33328
+ error
32964
33329
  }
32965
33330
  });
33331
+ failures.push({
33332
+ saved,
33333
+ error
33334
+ });
32966
33335
  }
32967
33336
  };
32968
33337
  await Promise.all(topLevel.map((saved) => restoreOne(saved)));
33338
+ const failedTopLevelIds = new Set(failures.map((failure) => failure.saved.id));
32969
33339
  const childRows = savedDevices.filter((s) => s.parentDeviceId !== null);
32970
33340
  for (const saved of childRows) {
32971
- const Class = this.deviceClasses[saved.type];
32972
- if (!Class) continue;
33341
+ if (!this.deviceClasses[saved.type]) continue;
32973
33342
  if (saved.parentDeviceId === null) continue;
32974
- if (!restored.has(saved.parentDeviceId)) continue;
32975
- try {
32976
- await this.ctx.kernel.devices.create(saved.stableId, Class, {}, saved.parentDeviceId);
32977
- restored.add(saved.id);
32978
- } catch (err) {
32979
- this.ctx.logger.warn("Failed to restore hub-adopted child", {
33343
+ if (restored.has(saved.parentDeviceId)) {
33344
+ try {
33345
+ await attemptRestore(saved);
33346
+ } catch (err) {
33347
+ const error = err instanceof Error ? err.message : String(err);
33348
+ this.ctx.logger.warn("Failed to restore hub-adopted child — bounded retry scheduled", {
33349
+ tags: {
33350
+ deviceId: saved.id,
33351
+ stableId: saved.stableId,
33352
+ parentDeviceId: saved.parentDeviceId
33353
+ },
33354
+ meta: {
33355
+ type: saved.type,
33356
+ attempt: 1,
33357
+ error
33358
+ }
33359
+ });
33360
+ failures.push({
33361
+ saved,
33362
+ error
33363
+ });
33364
+ }
33365
+ continue;
33366
+ }
33367
+ if (failedTopLevelIds.has(saved.parentDeviceId)) {
33368
+ this.ctx.logger.warn("Hub-adopted child deferred — parent failed initial restore", {
32980
33369
  tags: {
33370
+ deviceId: saved.id,
32981
33371
  stableId: saved.stableId,
32982
33372
  parentDeviceId: saved.parentDeviceId
32983
33373
  },
32984
- meta: {
32985
- type: saved.type,
32986
- error: err instanceof Error ? err.message : String(err)
32987
- }
33374
+ meta: { type: saved.type }
32988
33375
  });
33376
+ failures.push({
33377
+ saved,
33378
+ error: `parent device ${saved.parentDeviceId} not restored`
33379
+ });
33380
+ continue;
32989
33381
  }
32990
33382
  }
33383
+ if (failures.length > 0) this.scheduleRestoreRetries(failures, attemptRestore);
33384
+ return {
33385
+ restoredCount: restored.size,
33386
+ failedCount: failures.length
33387
+ };
32991
33388
  }
32992
33389
  /** Convert an IDevice to the flat DeviceSummary for the cap router. */
32993
33390
  toSummary(device) {
@@ -34750,6 +35147,12 @@ Object.freeze({
34750
35147
  addonId: null,
34751
35148
  access: "view"
34752
35149
  },
35150
+ "deviceProvider.reloadDevice": {
35151
+ capName: "device-provider",
35152
+ capScope: "system",
35153
+ addonId: null,
35154
+ access: "create"
35155
+ },
34753
35156
  "deviceProvider.start": {
34754
35157
  capName: "device-provider",
34755
35158
  capScope: "system",
package/dist/addon.mjs CHANGED
@@ -12999,7 +12999,26 @@ var DiscoveryCandidateSchema = object({
12999
12999
  * identity ahead of adoption. Rendering metadata (unit, precision)
13000
13000
  * flows live through the cap STATUS SLICE after adoption.
13001
13001
  */
13002
- sourceInfo: SourceInfoSchema.optional()
13002
+ sourceInfo: SourceInfoSchema.optional(),
13003
+ /**
13004
+ * Set when this candidate is a device the provider ALREADY owns.
13005
+ *
13006
+ * A scan cannot generally produce the identity a device was onboarded under
13007
+ * (Reolink keys on `mac-<mac>`, learned at adopt time), so a stableId
13008
+ * comparison never matches and an owned device looks addable. Re-adopting one
13009
+ * overwrites its config with scan-derived values — that is how a Home Hub's
13010
+ * Baichuan port was overwritten with its ONVIF port, taking the hub and its
13011
+ * three child cameras offline for four hours.
13012
+ *
13013
+ * A provider that can recognise its own devices says so here. Absent means
13014
+ * "not recognised", which is not the same as "known to be new" — a provider
13015
+ * that cannot tell simply never sets it.
13016
+ */
13017
+ alreadyOnboarded: boolean().optional(),
13018
+ /** Numeric id of the device this candidate was matched to. Set with `alreadyOnboarded`. */
13019
+ onboardedDeviceId: number().optional(),
13020
+ /** Operator-facing name of the matched device, so the UI can say WHICH one it is. */
13021
+ onboardedName: string().optional()
13003
13022
  });
13004
13023
  /**
13005
13024
  * Flat device summary returned by `createDevice` / `adoptDiscoveredDevice`.
@@ -13055,6 +13074,35 @@ var deviceProviderCapability = {
13055
13074
  name: string(),
13056
13075
  type: string()
13057
13076
  }))),
13077
+ /**
13078
+ * Tear down and reconstruct ONE device in place from its persisted rows —
13079
+ * touching no other device this provider owns.
13080
+ *
13081
+ * The primitive `deviceManager.migrateDevice` uses to flush the two
13082
+ * migrated numbers: after `swapIds` the runner's live instance still
13083
+ * carries the PRE-swap numeric id (baked into the object, its native-cap
13084
+ * registrations and its log tags), and a live object cannot be renumbered.
13085
+ * Before this method the only flush was restarting the whole owning addon
13086
+ * — which took every camera the provider owns down with it (28 devices
13087
+ * for one migrated camera, measured 2026-09-04, and the morning of the
13088
+ * same day ~27 devices' native caps did not come back on their own).
13089
+ *
13090
+ * Keyed by `stableId`, deliberately: the numeric id is exactly the thing
13091
+ * that changes. The reply carries the id the device answers on NOW.
13092
+ * Implemented once in `BaseDeviceProvider` — decommission the live
13093
+ * instance (if any), then re-create from the persisted row: the same
13094
+ * teardown/rehydrate pair every graceful shutdown + boot already uses.
13095
+ * An RPC, never an event: a dropped event would leave the runner writing
13096
+ * against the wrong camera (D8).
13097
+ *
13098
+ * Construction can dial hardware, and the migrated source is
13099
+ * characteristically dead — the timeout covers a full activate window
13100
+ * rather than the 60 s default.
13101
+ */
13102
+ reloadDevice: method(object({ stableId: string() }), object({ deviceId: number() }), {
13103
+ kind: "mutation",
13104
+ timeoutMs: 3 * 6e4
13105
+ }),
13058
13106
  supportsDiscovery: method(object({}), boolean()),
13059
13107
  /**
13060
13108
  * Run a network scan. `params` carries optional provider-specific scan
@@ -13382,7 +13430,8 @@ method(object({
13382
13430
  targetId: number()
13383
13431
  }), MigrateDeviceResultSchema, {
13384
13432
  kind: "mutation",
13385
- auth: "admin"
13433
+ auth: "admin",
13434
+ timeoutMs: 12 * 6e4
13386
13435
  }), 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({
13387
13436
  deviceId: number(),
13388
13437
  name: string()
@@ -32755,6 +32804,147 @@ var BaseDevice = class {
32755
32804
  }
32756
32805
  };
32757
32806
  /**
32807
+ * Delays before retry rounds 1..N — the round count IS the bound.
32808
+ * 10 s catches "the hub was busy for a moment"; the full schedule
32809
+ * (10 + 30 + 90 s of waiting, plus up to one 60 s transport timeout
32810
+ * per attempt) covers a device-manager lock held for minutes — the
32811
+ * 2026-09-04 outage's migration hold was ~3.5 min.
32812
+ */
32813
+ var DEVICE_RESTORE_RETRY_DELAYS_MS = [
32814
+ 1e4,
32815
+ 3e4,
32816
+ 9e4
32817
+ ];
32818
+ /** Abortable sleep — resolves early (never rejects) on abort. */
32819
+ function sleep$1(ms, signal) {
32820
+ return new Promise((resolve) => {
32821
+ if (signal.aborted) {
32822
+ resolve();
32823
+ return;
32824
+ }
32825
+ const onAbort = () => {
32826
+ clearTimeout(timer);
32827
+ resolve();
32828
+ };
32829
+ const timer = setTimeout(() => {
32830
+ signal.removeEventListener("abort", onAbort);
32831
+ resolve();
32832
+ }, ms);
32833
+ timer.unref?.();
32834
+ signal.addEventListener("abort", onAbort, { once: true });
32835
+ });
32836
+ }
32837
+ /** Drain `items` through at most `width` concurrent lanes. `fn` must
32838
+ * not reject (callers wrap their own try/catch). */
32839
+ async function runWithConcurrency(items, width, fn) {
32840
+ const queue = [...items];
32841
+ const laneCount = Math.max(1, Math.min(width, queue.length));
32842
+ const lane = async () => {
32843
+ for (;;) {
32844
+ const item = queue.shift();
32845
+ if (item === void 0) return;
32846
+ await fn(item);
32847
+ }
32848
+ };
32849
+ await Promise.all(Array.from({ length: laneCount }, lane));
32850
+ }
32851
+ var DeviceRestoreRetryScheduler = class {
32852
+ #logger;
32853
+ #attempt;
32854
+ #onPermanentFailure;
32855
+ #delaysMs;
32856
+ #concurrency;
32857
+ #now;
32858
+ #abort = new AbortController();
32859
+ constructor(options) {
32860
+ this.#logger = options.logger;
32861
+ this.#attempt = options.attempt;
32862
+ this.#onPermanentFailure = options.onPermanentFailure;
32863
+ this.#delaysMs = options.delaysMs ?? DEVICE_RESTORE_RETRY_DELAYS_MS;
32864
+ this.#concurrency = options.concurrency ?? 4;
32865
+ this.#now = options.now ?? Date.now;
32866
+ }
32867
+ /** Stop retrying (shutdown). Pending entries are NOT marked
32868
+ * permanently failed — the next boot restores them from disk. */
32869
+ cancel() {
32870
+ this.#abort.abort();
32871
+ }
32872
+ /**
32873
+ * Run the bounded retry rounds. Resolves when every entry has either
32874
+ * restored, been marked permanently failed, or the scheduler was
32875
+ * cancelled. Never rejects.
32876
+ */
32877
+ async run(initialFailures) {
32878
+ let pending = initialFailures.map((failure) => ({
32879
+ saved: failure.saved,
32880
+ lastError: failure.error,
32881
+ attempts: 1
32882
+ }));
32883
+ for (let round = 0; round < this.#delaysMs.length; round += 1) {
32884
+ if (pending.length === 0 || this.#abort.signal.aborted) break;
32885
+ await sleep$1(this.#delaysMs[round] ?? 0, this.#abort.signal);
32886
+ if (this.#abort.signal.aborted) break;
32887
+ pending = await this.#runRound(pending, round);
32888
+ }
32889
+ if (this.#abort.signal.aborted) return [];
32890
+ const terminal = pending.map((entry) => ({
32891
+ deviceId: entry.saved.id,
32892
+ stableId: entry.saved.stableId,
32893
+ type: String(entry.saved.type),
32894
+ attempts: entry.attempts,
32895
+ lastError: entry.lastError,
32896
+ failedAt: this.#now()
32897
+ }));
32898
+ for (const failure of terminal) this.#onPermanentFailure(failure);
32899
+ return terminal;
32900
+ }
32901
+ /** One retry round: parents first (phase 0), then hub-adopted
32902
+ * children (phase 1) — a child's attempt depends on its parent
32903
+ * having landed, exactly like the initial two-pass restore. */
32904
+ async #runRound(pending, round) {
32905
+ const next = [];
32906
+ const parents = pending.filter((entry) => entry.saved.parentDeviceId === null);
32907
+ const children = pending.filter((entry) => entry.saved.parentDeviceId !== null);
32908
+ for (const phase of [parents, children]) await runWithConcurrency(phase, this.#concurrency, async (entry) => {
32909
+ if (this.#abort.signal.aborted) {
32910
+ next.push(entry);
32911
+ return;
32912
+ }
32913
+ const attemptNo = entry.attempts + 1;
32914
+ try {
32915
+ await this.#attempt(entry.saved);
32916
+ this.#logger.info("Device restored on retry", {
32917
+ tags: {
32918
+ deviceId: entry.saved.id,
32919
+ stableId: entry.saved.stableId
32920
+ },
32921
+ meta: { attempt: attemptNo }
32922
+ });
32923
+ } catch (err) {
32924
+ const lastError = err instanceof Error ? err.message : String(err);
32925
+ const remainingRetries = this.#delaysMs.length - (round + 1);
32926
+ this.#logger.warn("Device restore retry failed", {
32927
+ tags: {
32928
+ deviceId: entry.saved.id,
32929
+ stableId: entry.saved.stableId
32930
+ },
32931
+ meta: {
32932
+ attempt: attemptNo,
32933
+ remainingRetries,
32934
+ error: lastError
32935
+ }
32936
+ });
32937
+ next.push({
32938
+ saved: entry.saved,
32939
+ lastError,
32940
+ attempts: attemptNo
32941
+ });
32942
+ }
32943
+ });
32944
+ return next;
32945
+ }
32946
+ };
32947
+ /**
32758
32948
  * Convert an IDevice to the flat DeviceSummary shape expected by the
32759
32949
  * device-provider cap router. Shared across all providers.
32760
32950
  */
@@ -32803,6 +32993,7 @@ var BaseDeviceProvider = class extends BaseAddon {
32803
32993
  }];
32804
32994
  }
32805
32995
  async onShutdown() {
32996
+ this.cancelRestoreRetries();
32806
32997
  const devices = await this.ctx.kernel.devices?.getAll() ?? [];
32807
32998
  for (const device of devices) try {
32808
32999
  await this.ctx.kernel.devices?.decommission(device.id);
@@ -32820,9 +33011,16 @@ var BaseDeviceProvider = class extends BaseAddon {
32820
33011
  async start() {}
32821
33012
  async stop() {}
32822
33013
  async getStatus() {
33014
+ const all = await this.ctx.kernel.devices?.getAll() ?? [];
33015
+ const summary = this.restoreFailureSummary();
33016
+ if (summary === null) return {
33017
+ connected: true,
33018
+ deviceCount: all.length
33019
+ };
32823
33020
  return {
32824
33021
  connected: true,
32825
- deviceCount: (await this.ctx.kernel.devices?.getAll() ?? []).length
33022
+ deviceCount: all.length,
33023
+ error: summary
32826
33024
  };
32827
33025
  }
32828
33026
  async getDevices() {
@@ -32912,8 +33110,137 @@ var BaseDeviceProvider = class extends BaseAddon {
32912
33110
  };
32913
33111
  }
32914
33112
  async restoreDevices(savedDevices) {
32915
- await this.onRestoreDevices(savedDevices);
32916
- if (savedDevices.length > 0) this.ctx.logger.info(`Restored ${savedDevices.length} ${this.providerName} device(s)`);
33113
+ const report = await this.onRestoreDevices(savedDevices);
33114
+ if (savedDevices.length === 0) return;
33115
+ if (report && report.failedCount > 0) {
33116
+ this.ctx.logger.warn(`Restored ${report.restoredCount}/${savedDevices.length} ${this.providerName} device(s) — ${report.failedCount} failed, bounded retry scheduled`);
33117
+ return;
33118
+ }
33119
+ const restoredCount = report ? report.restoredCount : savedDevices.length;
33120
+ this.ctx.logger.info(`Restored ${restoredCount} ${this.providerName} device(s)`);
33121
+ }
33122
+ /** Retry schedule. Overridable (tests use millisecond delays). */
33123
+ restoreRetryDelaysMs = DEVICE_RESTORE_RETRY_DELAYS_MS;
33124
+ /** Retry lane width. See `device-restore-retry.ts` for why retries
33125
+ * never re-stampede full-width while the initial pass does (D167). */
33126
+ restoreRetryConcurrency = 4;
33127
+ _restoreRetryScheduler = null;
33128
+ _restoreRetryCompletion = null;
33129
+ _permanentRestoreFailures = /* @__PURE__ */ new Map();
33130
+ /** Settles when the background retry rounds finish (or `null` when
33131
+ * nothing failed). Exposed for tests and subclass diagnostics —
33132
+ * boot NEVER awaits this: the runner's post-init handshake goes out
33133
+ * with the devices that restored, and a late success is announced
33134
+ * through the `native-cap-change` → `updateCaps` path. */
33135
+ get restoreRetryCompletion() {
33136
+ return this._restoreRetryCompletion;
33137
+ }
33138
+ /** Devices that exhausted the retry bound this process lifetime. */
33139
+ get permanentRestoreFailures() {
33140
+ return [...this._permanentRestoreFailures.values()];
33141
+ }
33142
+ /** One-line operator-facing summary for `getStatus().error`, or
33143
+ * `null` when every device restored. */
33144
+ restoreFailureSummary() {
33145
+ if (this._permanentRestoreFailures.size === 0) return null;
33146
+ const ids = [...this._permanentRestoreFailures.keys()].join(", ");
33147
+ return `${this._permanentRestoreFailures.size} device(s) permanently failed restore (deviceIds: ${ids}) — restart the ${this.providerName} provider to retry`;
33148
+ }
33149
+ cancelRestoreRetries() {
33150
+ this._restoreRetryScheduler?.cancel();
33151
+ this._restoreRetryScheduler = null;
33152
+ }
33153
+ recordPermanentRestoreFailure(failure) {
33154
+ this._permanentRestoreFailures.set(failure.deviceId, failure);
33155
+ this.ctx.logger.error("Device restore permanently failed — its capabilities will not register until the provider restarts", {
33156
+ tags: {
33157
+ deviceId: failure.deviceId,
33158
+ stableId: failure.stableId
33159
+ },
33160
+ meta: {
33161
+ type: failure.type,
33162
+ attempts: failure.attempts,
33163
+ error: failure.lastError
33164
+ }
33165
+ });
33166
+ }
33167
+ scheduleRestoreRetries(failures, attempt) {
33168
+ const scheduler = new DeviceRestoreRetryScheduler({
33169
+ logger: this.ctx.logger,
33170
+ delaysMs: this.restoreRetryDelaysMs,
33171
+ concurrency: this.restoreRetryConcurrency,
33172
+ attempt,
33173
+ onPermanentFailure: (failure) => this.recordPermanentRestoreFailure(failure)
33174
+ });
33175
+ this._restoreRetryScheduler = scheduler;
33176
+ this._restoreRetryCompletion = scheduler.run(failures).then(() => void 0).catch((err) => {
33177
+ this.ctx.logger.error("Restore retry scheduler crashed", { meta: { error: err instanceof Error ? err.message : String(err) } });
33178
+ });
33179
+ }
33180
+ /**
33181
+ * Tear down and reconstruct ONE device from its persisted rows — the
33182
+ * `deviceProvider.reloadDevice` cap method. Persistence is never touched,
33183
+ * and no other device this provider owns is disturbed.
33184
+ *
33185
+ * Keyed by `stableId` because the caller's whole reason to be here is that
33186
+ * the NUMERIC id changed (`deviceManager.migrateDevice` swapped it): the
33187
+ * fresh instance resolves its id through `allocateDeviceId`, which returns
33188
+ * whatever number the row carries NOW. The teardown is `decommission` —
33189
+ * exactly what a graceful shutdown runs per device (fires `removeDevice()`,
33190
+ * unregisters native caps, drops the registry entry) — and the rebuild is
33191
+ * the boot restore's own `create()` path, including its pass 2: first-class
33192
+ * children (hub-adopted cameras under an NVR) are decommissioned with the
33193
+ * parent by the cascade and must be re-created explicitly, because only
33194
+ * accessory children come back through `getAccessoryChildren()`.
33195
+ *
33196
+ * Reloading an accessory child directly is refused (no device class) —
33197
+ * reload its parent instead.
33198
+ */
33199
+ async reloadDevice(input) {
33200
+ const { stableId } = input;
33201
+ const devices = this.ctx.kernel.devices;
33202
+ if (!devices) throw new Error(`${this.providerName}: kernel.devices unavailable — cannot reload`);
33203
+ const live = (await devices.getAll()).find((d) => d.stableId === stableId);
33204
+ if (live) await devices.decommission(live.id);
33205
+ const { id } = await this.ctx.api.deviceManager.allocateDeviceId.mutate({
33206
+ addonId: this.addonId,
33207
+ stableId
33208
+ });
33209
+ const meta = await this.ctx.api.deviceManager.loadMeta.query({ deviceId: id });
33210
+ if (meta === null) throw new Error(`${this.providerName}: no persisted meta for "${stableId}" (id ${id}) — cannot reload`);
33211
+ const deviceType = Object.values(DeviceType).find((t) => t === meta.type);
33212
+ const Class = deviceType !== void 0 ? this.deviceClasses[deviceType] : void 0;
33213
+ if (!Class) throw new Error(`${this.providerName}: no device class for type "${meta.type}" — "${stableId}" is an accessory child; reload its parent instead`);
33214
+ await devices.create(stableId, Class, {}, meta.parentDeviceId ?? null);
33215
+ const rows = await this.ctx.api.deviceManager.listPersistedByAddon.query({ addonId: this.addonId });
33216
+ for (const row of rows) {
33217
+ if (row.parentDeviceId !== id) continue;
33218
+ const childType = Object.values(DeviceType).find((t) => t === row.type);
33219
+ const ChildClass = childType !== void 0 ? this.deviceClasses[childType] : void 0;
33220
+ if (!ChildClass) continue;
33221
+ try {
33222
+ await devices.create(row.stableId, ChildClass, {}, id);
33223
+ } catch (err) {
33224
+ this.ctx.logger.warn("reloadDevice: failed to re-create first-class child", {
33225
+ tags: {
33226
+ deviceId: row.id,
33227
+ stableId: row.stableId
33228
+ },
33229
+ meta: {
33230
+ parentDeviceId: id,
33231
+ error: err instanceof Error ? err.message : String(err)
33232
+ }
33233
+ });
33234
+ }
33235
+ }
33236
+ this.ctx.logger.info("device reloaded in place from persisted rows", {
33237
+ tags: { deviceId: id },
33238
+ meta: {
33239
+ stableId,
33240
+ type: meta.type
33241
+ }
33242
+ });
33243
+ return { deviceId: id };
32917
33244
  }
32918
33245
  /**
32919
33246
  * Restore devices from persisted state. Two-pass:
@@ -32939,55 +33266,125 @@ var BaseDeviceProvider = class extends BaseAddon {
32939
33266
  * accessory-spawn flow handles via the parent's
32940
33267
  * `getAccessoryChildren()`. Override only when the default doesn't
32941
33268
  * fit.
33269
+ *
33270
+ * A row that fails either pass is NOT terminal (D347): it is handed
33271
+ * to a bounded background retry (`DeviceRestoreRetryScheduler`).
33272
+ * Only after the bound is exhausted is the device marked permanently
33273
+ * failed — logged at ERROR with `tags.deviceId` and surfaced via
33274
+ * `getStatus().error`.
32942
33275
  */
33276
+ /**
33277
+ * Repair a row's PERSISTED config blob immediately before it is restored.
33278
+ * Default: no-op — most providers have nothing to heal.
33279
+ *
33280
+ * This exists because a restored device self-hydrates from the DB: `create()`
33281
+ * passes `{}` and `BaseDevice` parses the stored blob against the device
33282
+ * schema. A blob that lost a REQUIRED field therefore fails restore forever,
33283
+ * and no later pass revisits it — a hub-adopted Reolink camera whose blob had
33284
+ * been emptied failed all four bounded attempts against fields
33285
+ * (`host`, `password`) it inherits from its parent and never dials itself.
33286
+ *
33287
+ * Implementations get every saved row, so a child can read its parent's blob.
33288
+ * A heal that throws is treated like any other restore failure: retried under
33289
+ * the bound, then reported — never swallowed.
33290
+ */
33291
+ async healSavedConfig(_saved, _allSaved) {}
32943
33292
  async onRestoreDevices(savedDevices) {
32944
33293
  const restored = /* @__PURE__ */ new Set();
33294
+ const failures = [];
33295
+ const attemptRestore = async (saved) => {
33296
+ if (restored.has(saved.id)) return;
33297
+ const Class = this.deviceClasses[saved.type];
33298
+ if (!Class) throw new Error(`no device class registered for type "${saved.type}"`);
33299
+ if (saved.parentDeviceId !== null && !restored.has(saved.parentDeviceId)) throw new Error(`parent device ${saved.parentDeviceId} not restored`);
33300
+ await this.healSavedConfig(saved, savedDevices);
33301
+ await this.ctx.kernel.devices.create(saved.stableId, Class, {}, saved.parentDeviceId);
33302
+ restored.add(saved.id);
33303
+ };
32945
33304
  const topLevel = savedDevices.filter((saved) => saved.parentDeviceId === null);
32946
33305
  const restoreOne = async (saved) => {
32947
- const Class = this.deviceClasses[saved.type];
32948
- if (!Class) {
33306
+ if (!this.deviceClasses[saved.type]) {
32949
33307
  this.ctx.logger.warn("No device class registered for restored type — skipping", {
32950
- tags: { stableId: saved.stableId },
33308
+ tags: {
33309
+ deviceId: saved.id,
33310
+ stableId: saved.stableId
33311
+ },
32951
33312
  meta: { type: saved.type }
32952
33313
  });
32953
33314
  return;
32954
33315
  }
32955
33316
  try {
32956
- await this.ctx.kernel.devices.create(saved.stableId, Class, {});
32957
- restored.add(saved.id);
33317
+ await attemptRestore(saved);
32958
33318
  } catch (err) {
32959
- this.ctx.logger.warn("Failed to restore device", {
32960
- tags: { stableId: saved.stableId },
33319
+ const error = err instanceof Error ? err.message : String(err);
33320
+ this.ctx.logger.warn("Failed to restore device — bounded retry scheduled", {
33321
+ tags: {
33322
+ deviceId: saved.id,
33323
+ stableId: saved.stableId
33324
+ },
32961
33325
  meta: {
32962
33326
  type: saved.type,
32963
- error: err instanceof Error ? err.message : String(err)
33327
+ attempt: 1,
33328
+ error
32964
33329
  }
32965
33330
  });
33331
+ failures.push({
33332
+ saved,
33333
+ error
33334
+ });
32966
33335
  }
32967
33336
  };
32968
33337
  await Promise.all(topLevel.map((saved) => restoreOne(saved)));
33338
+ const failedTopLevelIds = new Set(failures.map((failure) => failure.saved.id));
32969
33339
  const childRows = savedDevices.filter((s) => s.parentDeviceId !== null);
32970
33340
  for (const saved of childRows) {
32971
- const Class = this.deviceClasses[saved.type];
32972
- if (!Class) continue;
33341
+ if (!this.deviceClasses[saved.type]) continue;
32973
33342
  if (saved.parentDeviceId === null) continue;
32974
- if (!restored.has(saved.parentDeviceId)) continue;
32975
- try {
32976
- await this.ctx.kernel.devices.create(saved.stableId, Class, {}, saved.parentDeviceId);
32977
- restored.add(saved.id);
32978
- } catch (err) {
32979
- this.ctx.logger.warn("Failed to restore hub-adopted child", {
33343
+ if (restored.has(saved.parentDeviceId)) {
33344
+ try {
33345
+ await attemptRestore(saved);
33346
+ } catch (err) {
33347
+ const error = err instanceof Error ? err.message : String(err);
33348
+ this.ctx.logger.warn("Failed to restore hub-adopted child — bounded retry scheduled", {
33349
+ tags: {
33350
+ deviceId: saved.id,
33351
+ stableId: saved.stableId,
33352
+ parentDeviceId: saved.parentDeviceId
33353
+ },
33354
+ meta: {
33355
+ type: saved.type,
33356
+ attempt: 1,
33357
+ error
33358
+ }
33359
+ });
33360
+ failures.push({
33361
+ saved,
33362
+ error
33363
+ });
33364
+ }
33365
+ continue;
33366
+ }
33367
+ if (failedTopLevelIds.has(saved.parentDeviceId)) {
33368
+ this.ctx.logger.warn("Hub-adopted child deferred — parent failed initial restore", {
32980
33369
  tags: {
33370
+ deviceId: saved.id,
32981
33371
  stableId: saved.stableId,
32982
33372
  parentDeviceId: saved.parentDeviceId
32983
33373
  },
32984
- meta: {
32985
- type: saved.type,
32986
- error: err instanceof Error ? err.message : String(err)
32987
- }
33374
+ meta: { type: saved.type }
32988
33375
  });
33376
+ failures.push({
33377
+ saved,
33378
+ error: `parent device ${saved.parentDeviceId} not restored`
33379
+ });
33380
+ continue;
32989
33381
  }
32990
33382
  }
33383
+ if (failures.length > 0) this.scheduleRestoreRetries(failures, attemptRestore);
33384
+ return {
33385
+ restoredCount: restored.size,
33386
+ failedCount: failures.length
33387
+ };
32991
33388
  }
32992
33389
  /** Convert an IDevice to the flat DeviceSummary for the cap router. */
32993
33390
  toSummary(device) {
@@ -34750,6 +35147,12 @@ Object.freeze({
34750
35147
  addonId: null,
34751
35148
  access: "view"
34752
35149
  },
35150
+ "deviceProvider.reloadDevice": {
35151
+ capName: "device-provider",
35152
+ capScope: "system",
35153
+ addonId: null,
35154
+ access: "create"
35155
+ },
34753
35156
  "deviceProvider.start": {
34754
35157
  capName: "device-provider",
34755
35158
  capScope: "system",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@camstack/addon-import-alexa",
3
- "version": "0.2.58",
3
+ "version": "0.2.60",
4
4
  "description": "Alexa device-import provider for CamStack — imports the smart-home devices in a user's Alexa account via the unofficial alexa-remote2 cookie/token client (the inverse of the Alexa exporter)",
5
5
  "keywords": [
6
6
  "camstack",