@camstack/addon-import-alexa 0.2.58 → 0.2.59

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 +391 -24
  2. package/dist/addon.mjs +391 -24
  3. package/package.json +1 -1
package/dist/addon.js CHANGED
@@ -13055,6 +13055,35 @@ var deviceProviderCapability = {
13055
13055
  name: string(),
13056
13056
  type: string()
13057
13057
  }))),
13058
+ /**
13059
+ * Tear down and reconstruct ONE device in place from its persisted rows —
13060
+ * touching no other device this provider owns.
13061
+ *
13062
+ * The primitive `deviceManager.migrateDevice` uses to flush the two
13063
+ * migrated numbers: after `swapIds` the runner's live instance still
13064
+ * carries the PRE-swap numeric id (baked into the object, its native-cap
13065
+ * registrations and its log tags), and a live object cannot be renumbered.
13066
+ * Before this method the only flush was restarting the whole owning addon
13067
+ * — which took every camera the provider owns down with it (28 devices
13068
+ * for one migrated camera, measured 2026-09-04, and the morning of the
13069
+ * same day ~27 devices' native caps did not come back on their own).
13070
+ *
13071
+ * Keyed by `stableId`, deliberately: the numeric id is exactly the thing
13072
+ * that changes. The reply carries the id the device answers on NOW.
13073
+ * Implemented once in `BaseDeviceProvider` — decommission the live
13074
+ * instance (if any), then re-create from the persisted row: the same
13075
+ * teardown/rehydrate pair every graceful shutdown + boot already uses.
13076
+ * An RPC, never an event: a dropped event would leave the runner writing
13077
+ * against the wrong camera (D8).
13078
+ *
13079
+ * Construction can dial hardware, and the migrated source is
13080
+ * characteristically dead — the timeout covers a full activate window
13081
+ * rather than the 60 s default.
13082
+ */
13083
+ reloadDevice: method(object({ stableId: string() }), object({ deviceId: number() }), {
13084
+ kind: "mutation",
13085
+ timeoutMs: 3 * 6e4
13086
+ }),
13058
13087
  supportsDiscovery: method(object({}), boolean()),
13059
13088
  /**
13060
13089
  * Run a network scan. `params` carries optional provider-specific scan
@@ -13382,7 +13411,8 @@ method(object({
13382
13411
  targetId: number()
13383
13412
  }), MigrateDeviceResultSchema, {
13384
13413
  kind: "mutation",
13385
- auth: "admin"
13414
+ auth: "admin",
13415
+ timeoutMs: 12 * 6e4
13386
13416
  }), 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
13417
  deviceId: number(),
13388
13418
  name: string()
@@ -32755,6 +32785,147 @@ var BaseDevice = class {
32755
32785
  }
32756
32786
  };
32757
32787
  /**
32788
+ * Delays before retry rounds 1..N — the round count IS the bound.
32789
+ * 10 s catches "the hub was busy for a moment"; the full schedule
32790
+ * (10 + 30 + 90 s of waiting, plus up to one 60 s transport timeout
32791
+ * per attempt) covers a device-manager lock held for minutes — the
32792
+ * 2026-09-04 outage's migration hold was ~3.5 min.
32793
+ */
32794
+ var DEVICE_RESTORE_RETRY_DELAYS_MS = [
32795
+ 1e4,
32796
+ 3e4,
32797
+ 9e4
32798
+ ];
32799
+ /** Abortable sleep — resolves early (never rejects) on abort. */
32800
+ function sleep$1(ms, signal) {
32801
+ return new Promise((resolve) => {
32802
+ if (signal.aborted) {
32803
+ resolve();
32804
+ return;
32805
+ }
32806
+ const onAbort = () => {
32807
+ clearTimeout(timer);
32808
+ resolve();
32809
+ };
32810
+ const timer = setTimeout(() => {
32811
+ signal.removeEventListener("abort", onAbort);
32812
+ resolve();
32813
+ }, ms);
32814
+ timer.unref?.();
32815
+ signal.addEventListener("abort", onAbort, { once: true });
32816
+ });
32817
+ }
32818
+ /** Drain `items` through at most `width` concurrent lanes. `fn` must
32819
+ * not reject (callers wrap their own try/catch). */
32820
+ async function runWithConcurrency(items, width, fn) {
32821
+ const queue = [...items];
32822
+ const laneCount = Math.max(1, Math.min(width, queue.length));
32823
+ const lane = async () => {
32824
+ for (;;) {
32825
+ const item = queue.shift();
32826
+ if (item === void 0) return;
32827
+ await fn(item);
32828
+ }
32829
+ };
32830
+ await Promise.all(Array.from({ length: laneCount }, lane));
32831
+ }
32832
+ var DeviceRestoreRetryScheduler = class {
32833
+ #logger;
32834
+ #attempt;
32835
+ #onPermanentFailure;
32836
+ #delaysMs;
32837
+ #concurrency;
32838
+ #now;
32839
+ #abort = new AbortController();
32840
+ constructor(options) {
32841
+ this.#logger = options.logger;
32842
+ this.#attempt = options.attempt;
32843
+ this.#onPermanentFailure = options.onPermanentFailure;
32844
+ this.#delaysMs = options.delaysMs ?? DEVICE_RESTORE_RETRY_DELAYS_MS;
32845
+ this.#concurrency = options.concurrency ?? 4;
32846
+ this.#now = options.now ?? Date.now;
32847
+ }
32848
+ /** Stop retrying (shutdown). Pending entries are NOT marked
32849
+ * permanently failed — the next boot restores them from disk. */
32850
+ cancel() {
32851
+ this.#abort.abort();
32852
+ }
32853
+ /**
32854
+ * Run the bounded retry rounds. Resolves when every entry has either
32855
+ * restored, been marked permanently failed, or the scheduler was
32856
+ * cancelled. Never rejects.
32857
+ */
32858
+ async run(initialFailures) {
32859
+ let pending = initialFailures.map((failure) => ({
32860
+ saved: failure.saved,
32861
+ lastError: failure.error,
32862
+ attempts: 1
32863
+ }));
32864
+ for (let round = 0; round < this.#delaysMs.length; round += 1) {
32865
+ if (pending.length === 0 || this.#abort.signal.aborted) break;
32866
+ await sleep$1(this.#delaysMs[round] ?? 0, this.#abort.signal);
32867
+ if (this.#abort.signal.aborted) break;
32868
+ pending = await this.#runRound(pending, round);
32869
+ }
32870
+ if (this.#abort.signal.aborted) return [];
32871
+ const terminal = pending.map((entry) => ({
32872
+ deviceId: entry.saved.id,
32873
+ stableId: entry.saved.stableId,
32874
+ type: String(entry.saved.type),
32875
+ attempts: entry.attempts,
32876
+ lastError: entry.lastError,
32877
+ failedAt: this.#now()
32878
+ }));
32879
+ for (const failure of terminal) this.#onPermanentFailure(failure);
32880
+ return terminal;
32881
+ }
32882
+ /** One retry round: parents first (phase 0), then hub-adopted
32883
+ * children (phase 1) — a child's attempt depends on its parent
32884
+ * having landed, exactly like the initial two-pass restore. */
32885
+ async #runRound(pending, round) {
32886
+ const next = [];
32887
+ const parents = pending.filter((entry) => entry.saved.parentDeviceId === null);
32888
+ const children = pending.filter((entry) => entry.saved.parentDeviceId !== null);
32889
+ for (const phase of [parents, children]) await runWithConcurrency(phase, this.#concurrency, async (entry) => {
32890
+ if (this.#abort.signal.aborted) {
32891
+ next.push(entry);
32892
+ return;
32893
+ }
32894
+ const attemptNo = entry.attempts + 1;
32895
+ try {
32896
+ await this.#attempt(entry.saved);
32897
+ this.#logger.info("Device restored on retry", {
32898
+ tags: {
32899
+ deviceId: entry.saved.id,
32900
+ stableId: entry.saved.stableId
32901
+ },
32902
+ meta: { attempt: attemptNo }
32903
+ });
32904
+ } catch (err) {
32905
+ const lastError = err instanceof Error ? err.message : String(err);
32906
+ const remainingRetries = this.#delaysMs.length - (round + 1);
32907
+ this.#logger.warn("Device restore retry failed", {
32908
+ tags: {
32909
+ deviceId: entry.saved.id,
32910
+ stableId: entry.saved.stableId
32911
+ },
32912
+ meta: {
32913
+ attempt: attemptNo,
32914
+ remainingRetries,
32915
+ error: lastError
32916
+ }
32917
+ });
32918
+ next.push({
32919
+ saved: entry.saved,
32920
+ lastError,
32921
+ attempts: attemptNo
32922
+ });
32923
+ }
32924
+ });
32925
+ return next;
32926
+ }
32927
+ };
32928
+ /**
32758
32929
  * Convert an IDevice to the flat DeviceSummary shape expected by the
32759
32930
  * device-provider cap router. Shared across all providers.
32760
32931
  */
@@ -32803,6 +32974,7 @@ var BaseDeviceProvider = class extends BaseAddon {
32803
32974
  }];
32804
32975
  }
32805
32976
  async onShutdown() {
32977
+ this.cancelRestoreRetries();
32806
32978
  const devices = await this.ctx.kernel.devices?.getAll() ?? [];
32807
32979
  for (const device of devices) try {
32808
32980
  await this.ctx.kernel.devices?.decommission(device.id);
@@ -32820,9 +32992,16 @@ var BaseDeviceProvider = class extends BaseAddon {
32820
32992
  async start() {}
32821
32993
  async stop() {}
32822
32994
  async getStatus() {
32995
+ const all = await this.ctx.kernel.devices?.getAll() ?? [];
32996
+ const summary = this.restoreFailureSummary();
32997
+ if (summary === null) return {
32998
+ connected: true,
32999
+ deviceCount: all.length
33000
+ };
32823
33001
  return {
32824
33002
  connected: true,
32825
- deviceCount: (await this.ctx.kernel.devices?.getAll() ?? []).length
33003
+ deviceCount: all.length,
33004
+ error: summary
32826
33005
  };
32827
33006
  }
32828
33007
  async getDevices() {
@@ -32912,8 +33091,137 @@ var BaseDeviceProvider = class extends BaseAddon {
32912
33091
  };
32913
33092
  }
32914
33093
  async restoreDevices(savedDevices) {
32915
- await this.onRestoreDevices(savedDevices);
32916
- if (savedDevices.length > 0) this.ctx.logger.info(`Restored ${savedDevices.length} ${this.providerName} device(s)`);
33094
+ const report = await this.onRestoreDevices(savedDevices);
33095
+ if (savedDevices.length === 0) return;
33096
+ if (report && report.failedCount > 0) {
33097
+ this.ctx.logger.warn(`Restored ${report.restoredCount}/${savedDevices.length} ${this.providerName} device(s) — ${report.failedCount} failed, bounded retry scheduled`);
33098
+ return;
33099
+ }
33100
+ const restoredCount = report ? report.restoredCount : savedDevices.length;
33101
+ this.ctx.logger.info(`Restored ${restoredCount} ${this.providerName} device(s)`);
33102
+ }
33103
+ /** Retry schedule. Overridable (tests use millisecond delays). */
33104
+ restoreRetryDelaysMs = DEVICE_RESTORE_RETRY_DELAYS_MS;
33105
+ /** Retry lane width. See `device-restore-retry.ts` for why retries
33106
+ * never re-stampede full-width while the initial pass does (D167). */
33107
+ restoreRetryConcurrency = 4;
33108
+ _restoreRetryScheduler = null;
33109
+ _restoreRetryCompletion = null;
33110
+ _permanentRestoreFailures = /* @__PURE__ */ new Map();
33111
+ /** Settles when the background retry rounds finish (or `null` when
33112
+ * nothing failed). Exposed for tests and subclass diagnostics —
33113
+ * boot NEVER awaits this: the runner's post-init handshake goes out
33114
+ * with the devices that restored, and a late success is announced
33115
+ * through the `native-cap-change` → `updateCaps` path. */
33116
+ get restoreRetryCompletion() {
33117
+ return this._restoreRetryCompletion;
33118
+ }
33119
+ /** Devices that exhausted the retry bound this process lifetime. */
33120
+ get permanentRestoreFailures() {
33121
+ return [...this._permanentRestoreFailures.values()];
33122
+ }
33123
+ /** One-line operator-facing summary for `getStatus().error`, or
33124
+ * `null` when every device restored. */
33125
+ restoreFailureSummary() {
33126
+ if (this._permanentRestoreFailures.size === 0) return null;
33127
+ const ids = [...this._permanentRestoreFailures.keys()].join(", ");
33128
+ return `${this._permanentRestoreFailures.size} device(s) permanently failed restore (deviceIds: ${ids}) — restart the ${this.providerName} provider to retry`;
33129
+ }
33130
+ cancelRestoreRetries() {
33131
+ this._restoreRetryScheduler?.cancel();
33132
+ this._restoreRetryScheduler = null;
33133
+ }
33134
+ recordPermanentRestoreFailure(failure) {
33135
+ this._permanentRestoreFailures.set(failure.deviceId, failure);
33136
+ this.ctx.logger.error("Device restore permanently failed — its capabilities will not register until the provider restarts", {
33137
+ tags: {
33138
+ deviceId: failure.deviceId,
33139
+ stableId: failure.stableId
33140
+ },
33141
+ meta: {
33142
+ type: failure.type,
33143
+ attempts: failure.attempts,
33144
+ error: failure.lastError
33145
+ }
33146
+ });
33147
+ }
33148
+ scheduleRestoreRetries(failures, attempt) {
33149
+ const scheduler = new DeviceRestoreRetryScheduler({
33150
+ logger: this.ctx.logger,
33151
+ delaysMs: this.restoreRetryDelaysMs,
33152
+ concurrency: this.restoreRetryConcurrency,
33153
+ attempt,
33154
+ onPermanentFailure: (failure) => this.recordPermanentRestoreFailure(failure)
33155
+ });
33156
+ this._restoreRetryScheduler = scheduler;
33157
+ this._restoreRetryCompletion = scheduler.run(failures).then(() => void 0).catch((err) => {
33158
+ this.ctx.logger.error("Restore retry scheduler crashed", { meta: { error: err instanceof Error ? err.message : String(err) } });
33159
+ });
33160
+ }
33161
+ /**
33162
+ * Tear down and reconstruct ONE device from its persisted rows — the
33163
+ * `deviceProvider.reloadDevice` cap method. Persistence is never touched,
33164
+ * and no other device this provider owns is disturbed.
33165
+ *
33166
+ * Keyed by `stableId` because the caller's whole reason to be here is that
33167
+ * the NUMERIC id changed (`deviceManager.migrateDevice` swapped it): the
33168
+ * fresh instance resolves its id through `allocateDeviceId`, which returns
33169
+ * whatever number the row carries NOW. The teardown is `decommission` —
33170
+ * exactly what a graceful shutdown runs per device (fires `removeDevice()`,
33171
+ * unregisters native caps, drops the registry entry) — and the rebuild is
33172
+ * the boot restore's own `create()` path, including its pass 2: first-class
33173
+ * children (hub-adopted cameras under an NVR) are decommissioned with the
33174
+ * parent by the cascade and must be re-created explicitly, because only
33175
+ * accessory children come back through `getAccessoryChildren()`.
33176
+ *
33177
+ * Reloading an accessory child directly is refused (no device class) —
33178
+ * reload its parent instead.
33179
+ */
33180
+ async reloadDevice(input) {
33181
+ const { stableId } = input;
33182
+ const devices = this.ctx.kernel.devices;
33183
+ if (!devices) throw new Error(`${this.providerName}: kernel.devices unavailable — cannot reload`);
33184
+ const live = (await devices.getAll()).find((d) => d.stableId === stableId);
33185
+ if (live) await devices.decommission(live.id);
33186
+ const { id } = await this.ctx.api.deviceManager.allocateDeviceId.mutate({
33187
+ addonId: this.addonId,
33188
+ stableId
33189
+ });
33190
+ const meta = await this.ctx.api.deviceManager.loadMeta.query({ deviceId: id });
33191
+ if (meta === null) throw new Error(`${this.providerName}: no persisted meta for "${stableId}" (id ${id}) — cannot reload`);
33192
+ const deviceType = Object.values(DeviceType).find((t) => t === meta.type);
33193
+ const Class = deviceType !== void 0 ? this.deviceClasses[deviceType] : void 0;
33194
+ if (!Class) throw new Error(`${this.providerName}: no device class for type "${meta.type}" — "${stableId}" is an accessory child; reload its parent instead`);
33195
+ await devices.create(stableId, Class, {}, meta.parentDeviceId ?? null);
33196
+ const rows = await this.ctx.api.deviceManager.listPersistedByAddon.query({ addonId: this.addonId });
33197
+ for (const row of rows) {
33198
+ if (row.parentDeviceId !== id) continue;
33199
+ const childType = Object.values(DeviceType).find((t) => t === row.type);
33200
+ const ChildClass = childType !== void 0 ? this.deviceClasses[childType] : void 0;
33201
+ if (!ChildClass) continue;
33202
+ try {
33203
+ await devices.create(row.stableId, ChildClass, {}, id);
33204
+ } catch (err) {
33205
+ this.ctx.logger.warn("reloadDevice: failed to re-create first-class child", {
33206
+ tags: {
33207
+ deviceId: row.id,
33208
+ stableId: row.stableId
33209
+ },
33210
+ meta: {
33211
+ parentDeviceId: id,
33212
+ error: err instanceof Error ? err.message : String(err)
33213
+ }
33214
+ });
33215
+ }
33216
+ }
33217
+ this.ctx.logger.info("device reloaded in place from persisted rows", {
33218
+ tags: { deviceId: id },
33219
+ meta: {
33220
+ stableId,
33221
+ type: meta.type
33222
+ }
33223
+ });
33224
+ return { deviceId: id };
32917
33225
  }
32918
33226
  /**
32919
33227
  * Restore devices from persisted state. Two-pass:
@@ -32939,55 +33247,108 @@ var BaseDeviceProvider = class extends BaseAddon {
32939
33247
  * accessory-spawn flow handles via the parent's
32940
33248
  * `getAccessoryChildren()`. Override only when the default doesn't
32941
33249
  * fit.
33250
+ *
33251
+ * A row that fails either pass is NOT terminal (D347): it is handed
33252
+ * to a bounded background retry (`DeviceRestoreRetryScheduler`).
33253
+ * Only after the bound is exhausted is the device marked permanently
33254
+ * failed — logged at ERROR with `tags.deviceId` and surfaced via
33255
+ * `getStatus().error`.
32942
33256
  */
32943
33257
  async onRestoreDevices(savedDevices) {
32944
33258
  const restored = /* @__PURE__ */ new Set();
33259
+ const failures = [];
33260
+ const attemptRestore = async (saved) => {
33261
+ if (restored.has(saved.id)) return;
33262
+ const Class = this.deviceClasses[saved.type];
33263
+ if (!Class) throw new Error(`no device class registered for type "${saved.type}"`);
33264
+ if (saved.parentDeviceId !== null && !restored.has(saved.parentDeviceId)) throw new Error(`parent device ${saved.parentDeviceId} not restored`);
33265
+ await this.ctx.kernel.devices.create(saved.stableId, Class, {}, saved.parentDeviceId);
33266
+ restored.add(saved.id);
33267
+ };
32945
33268
  const topLevel = savedDevices.filter((saved) => saved.parentDeviceId === null);
32946
33269
  const restoreOne = async (saved) => {
32947
- const Class = this.deviceClasses[saved.type];
32948
- if (!Class) {
33270
+ if (!this.deviceClasses[saved.type]) {
32949
33271
  this.ctx.logger.warn("No device class registered for restored type — skipping", {
32950
- tags: { stableId: saved.stableId },
33272
+ tags: {
33273
+ deviceId: saved.id,
33274
+ stableId: saved.stableId
33275
+ },
32951
33276
  meta: { type: saved.type }
32952
33277
  });
32953
33278
  return;
32954
33279
  }
32955
33280
  try {
32956
- await this.ctx.kernel.devices.create(saved.stableId, Class, {});
32957
- restored.add(saved.id);
33281
+ await attemptRestore(saved);
32958
33282
  } catch (err) {
32959
- this.ctx.logger.warn("Failed to restore device", {
32960
- tags: { stableId: saved.stableId },
33283
+ const error = err instanceof Error ? err.message : String(err);
33284
+ this.ctx.logger.warn("Failed to restore device — bounded retry scheduled", {
33285
+ tags: {
33286
+ deviceId: saved.id,
33287
+ stableId: saved.stableId
33288
+ },
32961
33289
  meta: {
32962
33290
  type: saved.type,
32963
- error: err instanceof Error ? err.message : String(err)
33291
+ attempt: 1,
33292
+ error
32964
33293
  }
32965
33294
  });
33295
+ failures.push({
33296
+ saved,
33297
+ error
33298
+ });
32966
33299
  }
32967
33300
  };
32968
33301
  await Promise.all(topLevel.map((saved) => restoreOne(saved)));
33302
+ const failedTopLevelIds = new Set(failures.map((failure) => failure.saved.id));
32969
33303
  const childRows = savedDevices.filter((s) => s.parentDeviceId !== null);
32970
33304
  for (const saved of childRows) {
32971
- const Class = this.deviceClasses[saved.type];
32972
- if (!Class) continue;
33305
+ if (!this.deviceClasses[saved.type]) continue;
32973
33306
  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", {
33307
+ if (restored.has(saved.parentDeviceId)) {
33308
+ try {
33309
+ await attemptRestore(saved);
33310
+ } catch (err) {
33311
+ const error = err instanceof Error ? err.message : String(err);
33312
+ this.ctx.logger.warn("Failed to restore hub-adopted child — bounded retry scheduled", {
33313
+ tags: {
33314
+ deviceId: saved.id,
33315
+ stableId: saved.stableId,
33316
+ parentDeviceId: saved.parentDeviceId
33317
+ },
33318
+ meta: {
33319
+ type: saved.type,
33320
+ attempt: 1,
33321
+ error
33322
+ }
33323
+ });
33324
+ failures.push({
33325
+ saved,
33326
+ error
33327
+ });
33328
+ }
33329
+ continue;
33330
+ }
33331
+ if (failedTopLevelIds.has(saved.parentDeviceId)) {
33332
+ this.ctx.logger.warn("Hub-adopted child deferred — parent failed initial restore", {
32980
33333
  tags: {
33334
+ deviceId: saved.id,
32981
33335
  stableId: saved.stableId,
32982
33336
  parentDeviceId: saved.parentDeviceId
32983
33337
  },
32984
- meta: {
32985
- type: saved.type,
32986
- error: err instanceof Error ? err.message : String(err)
32987
- }
33338
+ meta: { type: saved.type }
32988
33339
  });
33340
+ failures.push({
33341
+ saved,
33342
+ error: `parent device ${saved.parentDeviceId} not restored`
33343
+ });
33344
+ continue;
32989
33345
  }
32990
33346
  }
33347
+ if (failures.length > 0) this.scheduleRestoreRetries(failures, attemptRestore);
33348
+ return {
33349
+ restoredCount: restored.size,
33350
+ failedCount: failures.length
33351
+ };
32991
33352
  }
32992
33353
  /** Convert an IDevice to the flat DeviceSummary for the cap router. */
32993
33354
  toSummary(device) {
@@ -34750,6 +35111,12 @@ Object.freeze({
34750
35111
  addonId: null,
34751
35112
  access: "view"
34752
35113
  },
35114
+ "deviceProvider.reloadDevice": {
35115
+ capName: "device-provider",
35116
+ capScope: "system",
35117
+ addonId: null,
35118
+ access: "create"
35119
+ },
34753
35120
  "deviceProvider.start": {
34754
35121
  capName: "device-provider",
34755
35122
  capScope: "system",
package/dist/addon.mjs CHANGED
@@ -13055,6 +13055,35 @@ var deviceProviderCapability = {
13055
13055
  name: string(),
13056
13056
  type: string()
13057
13057
  }))),
13058
+ /**
13059
+ * Tear down and reconstruct ONE device in place from its persisted rows —
13060
+ * touching no other device this provider owns.
13061
+ *
13062
+ * The primitive `deviceManager.migrateDevice` uses to flush the two
13063
+ * migrated numbers: after `swapIds` the runner's live instance still
13064
+ * carries the PRE-swap numeric id (baked into the object, its native-cap
13065
+ * registrations and its log tags), and a live object cannot be renumbered.
13066
+ * Before this method the only flush was restarting the whole owning addon
13067
+ * — which took every camera the provider owns down with it (28 devices
13068
+ * for one migrated camera, measured 2026-09-04, and the morning of the
13069
+ * same day ~27 devices' native caps did not come back on their own).
13070
+ *
13071
+ * Keyed by `stableId`, deliberately: the numeric id is exactly the thing
13072
+ * that changes. The reply carries the id the device answers on NOW.
13073
+ * Implemented once in `BaseDeviceProvider` — decommission the live
13074
+ * instance (if any), then re-create from the persisted row: the same
13075
+ * teardown/rehydrate pair every graceful shutdown + boot already uses.
13076
+ * An RPC, never an event: a dropped event would leave the runner writing
13077
+ * against the wrong camera (D8).
13078
+ *
13079
+ * Construction can dial hardware, and the migrated source is
13080
+ * characteristically dead — the timeout covers a full activate window
13081
+ * rather than the 60 s default.
13082
+ */
13083
+ reloadDevice: method(object({ stableId: string() }), object({ deviceId: number() }), {
13084
+ kind: "mutation",
13085
+ timeoutMs: 3 * 6e4
13086
+ }),
13058
13087
  supportsDiscovery: method(object({}), boolean()),
13059
13088
  /**
13060
13089
  * Run a network scan. `params` carries optional provider-specific scan
@@ -13382,7 +13411,8 @@ method(object({
13382
13411
  targetId: number()
13383
13412
  }), MigrateDeviceResultSchema, {
13384
13413
  kind: "mutation",
13385
- auth: "admin"
13414
+ auth: "admin",
13415
+ timeoutMs: 12 * 6e4
13386
13416
  }), 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
13417
  deviceId: number(),
13388
13418
  name: string()
@@ -32755,6 +32785,147 @@ var BaseDevice = class {
32755
32785
  }
32756
32786
  };
32757
32787
  /**
32788
+ * Delays before retry rounds 1..N — the round count IS the bound.
32789
+ * 10 s catches "the hub was busy for a moment"; the full schedule
32790
+ * (10 + 30 + 90 s of waiting, plus up to one 60 s transport timeout
32791
+ * per attempt) covers a device-manager lock held for minutes — the
32792
+ * 2026-09-04 outage's migration hold was ~3.5 min.
32793
+ */
32794
+ var DEVICE_RESTORE_RETRY_DELAYS_MS = [
32795
+ 1e4,
32796
+ 3e4,
32797
+ 9e4
32798
+ ];
32799
+ /** Abortable sleep — resolves early (never rejects) on abort. */
32800
+ function sleep$1(ms, signal) {
32801
+ return new Promise((resolve) => {
32802
+ if (signal.aborted) {
32803
+ resolve();
32804
+ return;
32805
+ }
32806
+ const onAbort = () => {
32807
+ clearTimeout(timer);
32808
+ resolve();
32809
+ };
32810
+ const timer = setTimeout(() => {
32811
+ signal.removeEventListener("abort", onAbort);
32812
+ resolve();
32813
+ }, ms);
32814
+ timer.unref?.();
32815
+ signal.addEventListener("abort", onAbort, { once: true });
32816
+ });
32817
+ }
32818
+ /** Drain `items` through at most `width` concurrent lanes. `fn` must
32819
+ * not reject (callers wrap their own try/catch). */
32820
+ async function runWithConcurrency(items, width, fn) {
32821
+ const queue = [...items];
32822
+ const laneCount = Math.max(1, Math.min(width, queue.length));
32823
+ const lane = async () => {
32824
+ for (;;) {
32825
+ const item = queue.shift();
32826
+ if (item === void 0) return;
32827
+ await fn(item);
32828
+ }
32829
+ };
32830
+ await Promise.all(Array.from({ length: laneCount }, lane));
32831
+ }
32832
+ var DeviceRestoreRetryScheduler = class {
32833
+ #logger;
32834
+ #attempt;
32835
+ #onPermanentFailure;
32836
+ #delaysMs;
32837
+ #concurrency;
32838
+ #now;
32839
+ #abort = new AbortController();
32840
+ constructor(options) {
32841
+ this.#logger = options.logger;
32842
+ this.#attempt = options.attempt;
32843
+ this.#onPermanentFailure = options.onPermanentFailure;
32844
+ this.#delaysMs = options.delaysMs ?? DEVICE_RESTORE_RETRY_DELAYS_MS;
32845
+ this.#concurrency = options.concurrency ?? 4;
32846
+ this.#now = options.now ?? Date.now;
32847
+ }
32848
+ /** Stop retrying (shutdown). Pending entries are NOT marked
32849
+ * permanently failed — the next boot restores them from disk. */
32850
+ cancel() {
32851
+ this.#abort.abort();
32852
+ }
32853
+ /**
32854
+ * Run the bounded retry rounds. Resolves when every entry has either
32855
+ * restored, been marked permanently failed, or the scheduler was
32856
+ * cancelled. Never rejects.
32857
+ */
32858
+ async run(initialFailures) {
32859
+ let pending = initialFailures.map((failure) => ({
32860
+ saved: failure.saved,
32861
+ lastError: failure.error,
32862
+ attempts: 1
32863
+ }));
32864
+ for (let round = 0; round < this.#delaysMs.length; round += 1) {
32865
+ if (pending.length === 0 || this.#abort.signal.aborted) break;
32866
+ await sleep$1(this.#delaysMs[round] ?? 0, this.#abort.signal);
32867
+ if (this.#abort.signal.aborted) break;
32868
+ pending = await this.#runRound(pending, round);
32869
+ }
32870
+ if (this.#abort.signal.aborted) return [];
32871
+ const terminal = pending.map((entry) => ({
32872
+ deviceId: entry.saved.id,
32873
+ stableId: entry.saved.stableId,
32874
+ type: String(entry.saved.type),
32875
+ attempts: entry.attempts,
32876
+ lastError: entry.lastError,
32877
+ failedAt: this.#now()
32878
+ }));
32879
+ for (const failure of terminal) this.#onPermanentFailure(failure);
32880
+ return terminal;
32881
+ }
32882
+ /** One retry round: parents first (phase 0), then hub-adopted
32883
+ * children (phase 1) — a child's attempt depends on its parent
32884
+ * having landed, exactly like the initial two-pass restore. */
32885
+ async #runRound(pending, round) {
32886
+ const next = [];
32887
+ const parents = pending.filter((entry) => entry.saved.parentDeviceId === null);
32888
+ const children = pending.filter((entry) => entry.saved.parentDeviceId !== null);
32889
+ for (const phase of [parents, children]) await runWithConcurrency(phase, this.#concurrency, async (entry) => {
32890
+ if (this.#abort.signal.aborted) {
32891
+ next.push(entry);
32892
+ return;
32893
+ }
32894
+ const attemptNo = entry.attempts + 1;
32895
+ try {
32896
+ await this.#attempt(entry.saved);
32897
+ this.#logger.info("Device restored on retry", {
32898
+ tags: {
32899
+ deviceId: entry.saved.id,
32900
+ stableId: entry.saved.stableId
32901
+ },
32902
+ meta: { attempt: attemptNo }
32903
+ });
32904
+ } catch (err) {
32905
+ const lastError = err instanceof Error ? err.message : String(err);
32906
+ const remainingRetries = this.#delaysMs.length - (round + 1);
32907
+ this.#logger.warn("Device restore retry failed", {
32908
+ tags: {
32909
+ deviceId: entry.saved.id,
32910
+ stableId: entry.saved.stableId
32911
+ },
32912
+ meta: {
32913
+ attempt: attemptNo,
32914
+ remainingRetries,
32915
+ error: lastError
32916
+ }
32917
+ });
32918
+ next.push({
32919
+ saved: entry.saved,
32920
+ lastError,
32921
+ attempts: attemptNo
32922
+ });
32923
+ }
32924
+ });
32925
+ return next;
32926
+ }
32927
+ };
32928
+ /**
32758
32929
  * Convert an IDevice to the flat DeviceSummary shape expected by the
32759
32930
  * device-provider cap router. Shared across all providers.
32760
32931
  */
@@ -32803,6 +32974,7 @@ var BaseDeviceProvider = class extends BaseAddon {
32803
32974
  }];
32804
32975
  }
32805
32976
  async onShutdown() {
32977
+ this.cancelRestoreRetries();
32806
32978
  const devices = await this.ctx.kernel.devices?.getAll() ?? [];
32807
32979
  for (const device of devices) try {
32808
32980
  await this.ctx.kernel.devices?.decommission(device.id);
@@ -32820,9 +32992,16 @@ var BaseDeviceProvider = class extends BaseAddon {
32820
32992
  async start() {}
32821
32993
  async stop() {}
32822
32994
  async getStatus() {
32995
+ const all = await this.ctx.kernel.devices?.getAll() ?? [];
32996
+ const summary = this.restoreFailureSummary();
32997
+ if (summary === null) return {
32998
+ connected: true,
32999
+ deviceCount: all.length
33000
+ };
32823
33001
  return {
32824
33002
  connected: true,
32825
- deviceCount: (await this.ctx.kernel.devices?.getAll() ?? []).length
33003
+ deviceCount: all.length,
33004
+ error: summary
32826
33005
  };
32827
33006
  }
32828
33007
  async getDevices() {
@@ -32912,8 +33091,137 @@ var BaseDeviceProvider = class extends BaseAddon {
32912
33091
  };
32913
33092
  }
32914
33093
  async restoreDevices(savedDevices) {
32915
- await this.onRestoreDevices(savedDevices);
32916
- if (savedDevices.length > 0) this.ctx.logger.info(`Restored ${savedDevices.length} ${this.providerName} device(s)`);
33094
+ const report = await this.onRestoreDevices(savedDevices);
33095
+ if (savedDevices.length === 0) return;
33096
+ if (report && report.failedCount > 0) {
33097
+ this.ctx.logger.warn(`Restored ${report.restoredCount}/${savedDevices.length} ${this.providerName} device(s) — ${report.failedCount} failed, bounded retry scheduled`);
33098
+ return;
33099
+ }
33100
+ const restoredCount = report ? report.restoredCount : savedDevices.length;
33101
+ this.ctx.logger.info(`Restored ${restoredCount} ${this.providerName} device(s)`);
33102
+ }
33103
+ /** Retry schedule. Overridable (tests use millisecond delays). */
33104
+ restoreRetryDelaysMs = DEVICE_RESTORE_RETRY_DELAYS_MS;
33105
+ /** Retry lane width. See `device-restore-retry.ts` for why retries
33106
+ * never re-stampede full-width while the initial pass does (D167). */
33107
+ restoreRetryConcurrency = 4;
33108
+ _restoreRetryScheduler = null;
33109
+ _restoreRetryCompletion = null;
33110
+ _permanentRestoreFailures = /* @__PURE__ */ new Map();
33111
+ /** Settles when the background retry rounds finish (or `null` when
33112
+ * nothing failed). Exposed for tests and subclass diagnostics —
33113
+ * boot NEVER awaits this: the runner's post-init handshake goes out
33114
+ * with the devices that restored, and a late success is announced
33115
+ * through the `native-cap-change` → `updateCaps` path. */
33116
+ get restoreRetryCompletion() {
33117
+ return this._restoreRetryCompletion;
33118
+ }
33119
+ /** Devices that exhausted the retry bound this process lifetime. */
33120
+ get permanentRestoreFailures() {
33121
+ return [...this._permanentRestoreFailures.values()];
33122
+ }
33123
+ /** One-line operator-facing summary for `getStatus().error`, or
33124
+ * `null` when every device restored. */
33125
+ restoreFailureSummary() {
33126
+ if (this._permanentRestoreFailures.size === 0) return null;
33127
+ const ids = [...this._permanentRestoreFailures.keys()].join(", ");
33128
+ return `${this._permanentRestoreFailures.size} device(s) permanently failed restore (deviceIds: ${ids}) — restart the ${this.providerName} provider to retry`;
33129
+ }
33130
+ cancelRestoreRetries() {
33131
+ this._restoreRetryScheduler?.cancel();
33132
+ this._restoreRetryScheduler = null;
33133
+ }
33134
+ recordPermanentRestoreFailure(failure) {
33135
+ this._permanentRestoreFailures.set(failure.deviceId, failure);
33136
+ this.ctx.logger.error("Device restore permanently failed — its capabilities will not register until the provider restarts", {
33137
+ tags: {
33138
+ deviceId: failure.deviceId,
33139
+ stableId: failure.stableId
33140
+ },
33141
+ meta: {
33142
+ type: failure.type,
33143
+ attempts: failure.attempts,
33144
+ error: failure.lastError
33145
+ }
33146
+ });
33147
+ }
33148
+ scheduleRestoreRetries(failures, attempt) {
33149
+ const scheduler = new DeviceRestoreRetryScheduler({
33150
+ logger: this.ctx.logger,
33151
+ delaysMs: this.restoreRetryDelaysMs,
33152
+ concurrency: this.restoreRetryConcurrency,
33153
+ attempt,
33154
+ onPermanentFailure: (failure) => this.recordPermanentRestoreFailure(failure)
33155
+ });
33156
+ this._restoreRetryScheduler = scheduler;
33157
+ this._restoreRetryCompletion = scheduler.run(failures).then(() => void 0).catch((err) => {
33158
+ this.ctx.logger.error("Restore retry scheduler crashed", { meta: { error: err instanceof Error ? err.message : String(err) } });
33159
+ });
33160
+ }
33161
+ /**
33162
+ * Tear down and reconstruct ONE device from its persisted rows — the
33163
+ * `deviceProvider.reloadDevice` cap method. Persistence is never touched,
33164
+ * and no other device this provider owns is disturbed.
33165
+ *
33166
+ * Keyed by `stableId` because the caller's whole reason to be here is that
33167
+ * the NUMERIC id changed (`deviceManager.migrateDevice` swapped it): the
33168
+ * fresh instance resolves its id through `allocateDeviceId`, which returns
33169
+ * whatever number the row carries NOW. The teardown is `decommission` —
33170
+ * exactly what a graceful shutdown runs per device (fires `removeDevice()`,
33171
+ * unregisters native caps, drops the registry entry) — and the rebuild is
33172
+ * the boot restore's own `create()` path, including its pass 2: first-class
33173
+ * children (hub-adopted cameras under an NVR) are decommissioned with the
33174
+ * parent by the cascade and must be re-created explicitly, because only
33175
+ * accessory children come back through `getAccessoryChildren()`.
33176
+ *
33177
+ * Reloading an accessory child directly is refused (no device class) —
33178
+ * reload its parent instead.
33179
+ */
33180
+ async reloadDevice(input) {
33181
+ const { stableId } = input;
33182
+ const devices = this.ctx.kernel.devices;
33183
+ if (!devices) throw new Error(`${this.providerName}: kernel.devices unavailable — cannot reload`);
33184
+ const live = (await devices.getAll()).find((d) => d.stableId === stableId);
33185
+ if (live) await devices.decommission(live.id);
33186
+ const { id } = await this.ctx.api.deviceManager.allocateDeviceId.mutate({
33187
+ addonId: this.addonId,
33188
+ stableId
33189
+ });
33190
+ const meta = await this.ctx.api.deviceManager.loadMeta.query({ deviceId: id });
33191
+ if (meta === null) throw new Error(`${this.providerName}: no persisted meta for "${stableId}" (id ${id}) — cannot reload`);
33192
+ const deviceType = Object.values(DeviceType).find((t) => t === meta.type);
33193
+ const Class = deviceType !== void 0 ? this.deviceClasses[deviceType] : void 0;
33194
+ if (!Class) throw new Error(`${this.providerName}: no device class for type "${meta.type}" — "${stableId}" is an accessory child; reload its parent instead`);
33195
+ await devices.create(stableId, Class, {}, meta.parentDeviceId ?? null);
33196
+ const rows = await this.ctx.api.deviceManager.listPersistedByAddon.query({ addonId: this.addonId });
33197
+ for (const row of rows) {
33198
+ if (row.parentDeviceId !== id) continue;
33199
+ const childType = Object.values(DeviceType).find((t) => t === row.type);
33200
+ const ChildClass = childType !== void 0 ? this.deviceClasses[childType] : void 0;
33201
+ if (!ChildClass) continue;
33202
+ try {
33203
+ await devices.create(row.stableId, ChildClass, {}, id);
33204
+ } catch (err) {
33205
+ this.ctx.logger.warn("reloadDevice: failed to re-create first-class child", {
33206
+ tags: {
33207
+ deviceId: row.id,
33208
+ stableId: row.stableId
33209
+ },
33210
+ meta: {
33211
+ parentDeviceId: id,
33212
+ error: err instanceof Error ? err.message : String(err)
33213
+ }
33214
+ });
33215
+ }
33216
+ }
33217
+ this.ctx.logger.info("device reloaded in place from persisted rows", {
33218
+ tags: { deviceId: id },
33219
+ meta: {
33220
+ stableId,
33221
+ type: meta.type
33222
+ }
33223
+ });
33224
+ return { deviceId: id };
32917
33225
  }
32918
33226
  /**
32919
33227
  * Restore devices from persisted state. Two-pass:
@@ -32939,55 +33247,108 @@ var BaseDeviceProvider = class extends BaseAddon {
32939
33247
  * accessory-spawn flow handles via the parent's
32940
33248
  * `getAccessoryChildren()`. Override only when the default doesn't
32941
33249
  * fit.
33250
+ *
33251
+ * A row that fails either pass is NOT terminal (D347): it is handed
33252
+ * to a bounded background retry (`DeviceRestoreRetryScheduler`).
33253
+ * Only after the bound is exhausted is the device marked permanently
33254
+ * failed — logged at ERROR with `tags.deviceId` and surfaced via
33255
+ * `getStatus().error`.
32942
33256
  */
32943
33257
  async onRestoreDevices(savedDevices) {
32944
33258
  const restored = /* @__PURE__ */ new Set();
33259
+ const failures = [];
33260
+ const attemptRestore = async (saved) => {
33261
+ if (restored.has(saved.id)) return;
33262
+ const Class = this.deviceClasses[saved.type];
33263
+ if (!Class) throw new Error(`no device class registered for type "${saved.type}"`);
33264
+ if (saved.parentDeviceId !== null && !restored.has(saved.parentDeviceId)) throw new Error(`parent device ${saved.parentDeviceId} not restored`);
33265
+ await this.ctx.kernel.devices.create(saved.stableId, Class, {}, saved.parentDeviceId);
33266
+ restored.add(saved.id);
33267
+ };
32945
33268
  const topLevel = savedDevices.filter((saved) => saved.parentDeviceId === null);
32946
33269
  const restoreOne = async (saved) => {
32947
- const Class = this.deviceClasses[saved.type];
32948
- if (!Class) {
33270
+ if (!this.deviceClasses[saved.type]) {
32949
33271
  this.ctx.logger.warn("No device class registered for restored type — skipping", {
32950
- tags: { stableId: saved.stableId },
33272
+ tags: {
33273
+ deviceId: saved.id,
33274
+ stableId: saved.stableId
33275
+ },
32951
33276
  meta: { type: saved.type }
32952
33277
  });
32953
33278
  return;
32954
33279
  }
32955
33280
  try {
32956
- await this.ctx.kernel.devices.create(saved.stableId, Class, {});
32957
- restored.add(saved.id);
33281
+ await attemptRestore(saved);
32958
33282
  } catch (err) {
32959
- this.ctx.logger.warn("Failed to restore device", {
32960
- tags: { stableId: saved.stableId },
33283
+ const error = err instanceof Error ? err.message : String(err);
33284
+ this.ctx.logger.warn("Failed to restore device — bounded retry scheduled", {
33285
+ tags: {
33286
+ deviceId: saved.id,
33287
+ stableId: saved.stableId
33288
+ },
32961
33289
  meta: {
32962
33290
  type: saved.type,
32963
- error: err instanceof Error ? err.message : String(err)
33291
+ attempt: 1,
33292
+ error
32964
33293
  }
32965
33294
  });
33295
+ failures.push({
33296
+ saved,
33297
+ error
33298
+ });
32966
33299
  }
32967
33300
  };
32968
33301
  await Promise.all(topLevel.map((saved) => restoreOne(saved)));
33302
+ const failedTopLevelIds = new Set(failures.map((failure) => failure.saved.id));
32969
33303
  const childRows = savedDevices.filter((s) => s.parentDeviceId !== null);
32970
33304
  for (const saved of childRows) {
32971
- const Class = this.deviceClasses[saved.type];
32972
- if (!Class) continue;
33305
+ if (!this.deviceClasses[saved.type]) continue;
32973
33306
  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", {
33307
+ if (restored.has(saved.parentDeviceId)) {
33308
+ try {
33309
+ await attemptRestore(saved);
33310
+ } catch (err) {
33311
+ const error = err instanceof Error ? err.message : String(err);
33312
+ this.ctx.logger.warn("Failed to restore hub-adopted child — bounded retry scheduled", {
33313
+ tags: {
33314
+ deviceId: saved.id,
33315
+ stableId: saved.stableId,
33316
+ parentDeviceId: saved.parentDeviceId
33317
+ },
33318
+ meta: {
33319
+ type: saved.type,
33320
+ attempt: 1,
33321
+ error
33322
+ }
33323
+ });
33324
+ failures.push({
33325
+ saved,
33326
+ error
33327
+ });
33328
+ }
33329
+ continue;
33330
+ }
33331
+ if (failedTopLevelIds.has(saved.parentDeviceId)) {
33332
+ this.ctx.logger.warn("Hub-adopted child deferred — parent failed initial restore", {
32980
33333
  tags: {
33334
+ deviceId: saved.id,
32981
33335
  stableId: saved.stableId,
32982
33336
  parentDeviceId: saved.parentDeviceId
32983
33337
  },
32984
- meta: {
32985
- type: saved.type,
32986
- error: err instanceof Error ? err.message : String(err)
32987
- }
33338
+ meta: { type: saved.type }
32988
33339
  });
33340
+ failures.push({
33341
+ saved,
33342
+ error: `parent device ${saved.parentDeviceId} not restored`
33343
+ });
33344
+ continue;
32989
33345
  }
32990
33346
  }
33347
+ if (failures.length > 0) this.scheduleRestoreRetries(failures, attemptRestore);
33348
+ return {
33349
+ restoredCount: restored.size,
33350
+ failedCount: failures.length
33351
+ };
32991
33352
  }
32992
33353
  /** Convert an IDevice to the flat DeviceSummary for the cap router. */
32993
33354
  toSummary(device) {
@@ -34750,6 +35111,12 @@ Object.freeze({
34750
35111
  addonId: null,
34751
35112
  access: "view"
34752
35113
  },
35114
+ "deviceProvider.reloadDevice": {
35115
+ capName: "device-provider",
35116
+ capScope: "system",
35117
+ addonId: null,
35118
+ access: "create"
35119
+ },
34753
35120
  "deviceProvider.start": {
34754
35121
  capName: "device-provider",
34755
35122
  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.59",
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",