@camstack/addon-provider-reolink 1.2.247 → 1.2.248

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/addon.js CHANGED
@@ -106821,7 +106821,7 @@ var ZodIssueCode = {
106821
106821
  var ZodFirstPartyTypeKind;
106822
106822
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
106823
106823
  //#endregion
106824
- //#region ../types/dist/runtime-capabilities-B36VcCR6.mjs
106824
+ //#region ../types/dist/runtime-capabilities-ql3VRzQu.mjs
106825
106825
  /**
106826
106826
  * The audio chunk plane's byte format, and the ONE expansion from a coded
106827
106827
  * window to float samples (D455).
@@ -106916,6 +106916,97 @@ var AddonMigrationsBlockedError = class extends Error {
106916
106916
  this.migrationIds = migrationIds;
106917
106917
  }
106918
106918
  };
106919
+ var SWITCHES = /* @__PURE__ */ new Map();
106920
+ /** The ids the registry is known to hold a row for (hydrated, or told by the hub). */
106921
+ var ROWS = /* @__PURE__ */ new Set();
106922
+ /** The owner addon of an id, learned from its rows and from the helper that serves it. */
106923
+ var OWNER_OF = /* @__PURE__ */ new Map();
106924
+ /** The addons whose registry read answered at least once. */
106925
+ var ANSWERED = /* @__PURE__ */ new Set();
106926
+ /** The addons whose boot has begun reading the registry: only they can be held back. */
106927
+ var HYDRATING = /* @__PURE__ */ new Set();
106928
+ /**
106929
+ * The addons that serve an instance kind and have not been answered by the registry yet. Scoped
106930
+ * per owner: one addon's failed read never turns off another addon's instances, and an addon that
106931
+ * serves no instance kind never enters it.
106932
+ */
106933
+ var PENDING = /* @__PURE__ */ new Set();
106934
+ /**
106935
+ * An addon's boot is about to read the registry for its rows. From now on, until the registry
106936
+ * answers, its served instance kinds (already built or built later in its boot) fail closed. A
106937
+ * helper used with no addon boot around it (a spec, a tool) is never held back.
106938
+ */
106939
+ function beginHydration(ownerId) {
106940
+ if (ANSWERED.has(ownerId)) return;
106941
+ HYDRATING.add(ownerId);
106942
+ if (KINDS.has(ownerId)) PENDING.add(ownerId);
106943
+ }
106944
+ /** The helper of `ownerId` serves `id`: its fail-closed window is that owner's, not the process's. */
106945
+ function claimInstance(ownerId, id) {
106946
+ OWNER_OF.set(id, ownerId);
106947
+ }
106948
+ /** Whether `ownerId` still waits for the registry to answer (it serves a kind and has no rows yet). */
106949
+ function isHydrationPending(ownerId) {
106950
+ return PENDING.has(ownerId);
106951
+ }
106952
+ /**
106953
+ * The switch of `id` as this process knows it. An id nobody stated reads off while ITS owner waits
106954
+ * for the registry, on afterwards (a fresh instance). An id with no known owner reads off while any
106955
+ * owner waits.
106956
+ */
106957
+ function isInstanceOn(id) {
106958
+ const stated = SWITCHES.get(id);
106959
+ if (stated !== void 0) return stated;
106960
+ const owner = OWNER_OF.get(id);
106961
+ return owner === void 0 ? PENDING.size === 0 : !PENDING.has(owner);
106962
+ }
106963
+ /** Record what the hub told: the registry holds a row of `id` in this state. */
106964
+ function recordRegistrySwitch(id, enabled) {
106965
+ SWITCHES.set(id, enabled);
106966
+ ROWS.add(id);
106967
+ }
106968
+ /** Whether the registry is known to hold a row for `id`. */
106969
+ function hasRegistryRow(id) {
106970
+ return ROWS.has(id);
106971
+ }
106972
+ /** The state this process holds for `id`, or undefined when it holds none. */
106973
+ function statedInstanceSwitch(id) {
106974
+ return SWITCHES.get(id);
106975
+ }
106976
+ /** Forget `id` (the instance was deleted). */
106977
+ function forgetInstanceSwitch(id) {
106978
+ SWITCHES.delete(id);
106979
+ ROWS.delete(id);
106980
+ OWNER_OF.delete(id);
106981
+ }
106982
+ /** Seed the store from the registry rows of `ownerId`; the registry answered, so the owner is known. */
106983
+ function hydrateInstanceSwitches(ownerId, rows) {
106984
+ ANSWERED.add(ownerId);
106985
+ for (const row of rows) {
106986
+ recordRegistrySwitch(row.id, row.enabled);
106987
+ OWNER_OF.set(row.id, ownerId);
106988
+ }
106989
+ }
106990
+ /** The addon's boot has built every instance kind and read the registry: unknown ids now read on. */
106991
+ function settleHydration(ownerId) {
106992
+ PENDING.delete(ownerId);
106993
+ }
106994
+ var KINDS = /* @__PURE__ */ new Map();
106995
+ /**
106996
+ * A helper announces the kind it serves, by owner addon. The one-time body-to-registry move
106997
+ * (D1066) walks exactly these kinds, so an addon needs no list of its own: a record kind IS an
106998
+ * instance kind precisely when a helper wraps it.
106999
+ */
107000
+ function registerServedInstanceKind(ownerId, served) {
107001
+ const owned = KINDS.get(ownerId) ?? /* @__PURE__ */ new Map();
107002
+ owned.set(served.kind.name, served);
107003
+ KINDS.set(ownerId, owned);
107004
+ if (HYDRATING.has(ownerId) && !ANSWERED.has(ownerId)) PENDING.add(ownerId);
107005
+ }
107006
+ /** The instance kinds announced for `ownerId` so far. */
107007
+ function servedInstanceKindsOf(ownerId) {
107008
+ return [...KINDS.get(ownerId)?.values() ?? []];
107009
+ }
106919
107010
  /** Is this field's stored value a credential? */
106920
107011
  function isSecretConfigField(field) {
106921
107012
  if (field.type === "password") return true;
@@ -107596,6 +107687,32 @@ function switchRecordsOverMigrationApi(api) {
107596
107687
  };
107597
107688
  } };
107598
107689
  }
107690
+ /** The record calls the body-to-registry switch migration makes, over the migration API. */
107691
+ function bodySwitchRecordsOverMigrationApi(api) {
107692
+ return { kind: (definition) => {
107693
+ const handle = api.records.kind(definition);
107694
+ return {
107695
+ query: async () => {
107696
+ const rows = [];
107697
+ let cursor;
107698
+ do {
107699
+ const page = await handle.query({
107700
+ limit: 500,
107701
+ ...cursor === void 0 ? {} : { cursor }
107702
+ });
107703
+ rows.push(...page.records);
107704
+ cursor = page.nextCursor ?? void 0;
107705
+ } while (cursor !== void 0);
107706
+ return { records: rows };
107707
+ },
107708
+ get: (id) => handle.get({ id }),
107709
+ put: (input, opts) => handle.put({
107710
+ ...input,
107711
+ ...opts?.ifRev === void 0 ? {} : { ifRev: opts.ifRev }
107712
+ })
107713
+ };
107714
+ } };
107715
+ }
107599
107716
  function integrationRowsApiOver(api) {
107600
107717
  return {
107601
107718
  list: async () => (await api.integrations.list({})).integrations,
@@ -108029,13 +108146,9 @@ function secretViewsOf(owner, kind, id, decl, data) {
108029
108146
  /** The most instances one addon lists (an integrations page, not a table). */
108030
108147
  var INSTANCES_LIST_MAX = 1e3;
108031
108148
  /**
108032
- * The ONE reader of an instance's switch (D996): an absent field means on, so a row written
108033
- * before the field existed needs no migration. Every consumer of an instance body asks this.
108149
+ * The body key the switch USED to live under (D1007, D1015). Nothing writes or reads it any more;
108150
+ * the migrations that move it between the body and the registry name it.
108034
108151
  */
108035
- function isInstanceEnabled(body) {
108036
- return body.enabled !== false;
108037
- }
108038
- /** The body key of the switch; only {@link RecordIntegrationInstances.setInstanceEnabled} writes it. */
108039
108152
  var SWITCH_KEY = "enabled";
108040
108153
  /**
108041
108154
  * The "Add device" mode an instance gets when its provider states none, from how the provider's
@@ -108077,6 +108190,20 @@ var RecordIntegrationInstances = class {
108077
108190
  secretKeys;
108078
108191
  secretMaps;
108079
108192
  nameField;
108193
+ /** The state each instance had when the addon last read it or was told it: {@link reapply} announces only a change. */
108194
+ knownSwitches = /* @__PURE__ */ new Map();
108195
+ /** What the addon reads for `id`: the switch as this process holds it, remembered as known. */
108196
+ knownSwitchOf(id) {
108197
+ claimInstance(this.records.owner, id);
108198
+ const enabled = isInstanceOn(id);
108199
+ this.knownSwitches.set(id, enabled);
108200
+ return enabled;
108201
+ }
108202
+ /** What a view of `id` shows; the addon did not read it, so nothing is remembered as known. */
108203
+ viewSwitchOf(id) {
108204
+ claimInstance(this.records.owner, id);
108205
+ return isInstanceOn(id);
108206
+ }
108080
108207
  switchListeners = /* @__PURE__ */ new Set();
108081
108208
  constructor(records, kind, hooks) {
108082
108209
  this.records = records;
@@ -108086,6 +108213,11 @@ var RecordIntegrationInstances = class {
108086
108213
  this.secretKeys = topLevelSecretKeys(kind.declaration.secretPaths);
108087
108214
  this.secretMaps = secretMapKeys(kind.declaration.secretPaths);
108088
108215
  this.nameField = kind.declaration.entry?.nameField ?? "name";
108216
+ registerServedInstanceKind(records.owner, {
108217
+ kind,
108218
+ reapply: () => this.reapply(),
108219
+ unrowed: () => this.unrowed()
108220
+ });
108089
108221
  if (hooks.kindOf === void 0 && hooks.description.kinds.length !== 1) throw new Error(`record kind '${kind.name}': describe().kinds has ${hooks.description.kinds.length} entries, so kindOf is required to say which one an instance is`);
108090
108222
  }
108091
108223
  /**
@@ -108099,7 +108231,7 @@ var RecordIntegrationInstances = class {
108099
108231
  return record === null ? null : {
108100
108232
  id,
108101
108233
  body: record.data,
108102
- enabled: isInstanceEnabled(record.data),
108234
+ enabled: this.knownSwitchOf(id),
108103
108235
  secrets: "resolved"
108104
108236
  };
108105
108237
  } catch (err) {
@@ -108109,7 +108241,7 @@ var RecordIntegrationInstances = class {
108109
108241
  return {
108110
108242
  id,
108111
108243
  body: Object.fromEntries(Object.entries(stored.data).filter(([key]) => !this.secretKeys.has(key))),
108112
- enabled: isInstanceEnabled(stored.data),
108244
+ enabled: this.knownSwitchOf(id),
108113
108245
  secrets: "unavailable"
108114
108246
  };
108115
108247
  }
@@ -108148,7 +108280,7 @@ var RecordIntegrationInstances = class {
108148
108280
  id: record.id,
108149
108281
  name: typeof rawName === "string" ? rawName : record.id,
108150
108282
  configured: this.hooks.configured(record.data),
108151
- enabled: isInstanceEnabled(record.data),
108283
+ enabled: this.viewSwitchOf(record.id),
108152
108284
  formValues: shown,
108153
108285
  kind,
108154
108286
  addDevice: this.hooks.addDevice?.(record.data) ?? defaultAddDeviceMode(this.hooks.description),
@@ -108204,6 +108336,8 @@ var RecordIntegrationInstances = class {
108204
108336
  id: minted,
108205
108337
  data: initial
108206
108338
  }, { ifRev: 0 });
108339
+ claimInstance(this.records.owner, minted);
108340
+ recordRegistrySwitch(minted, true);
108207
108341
  if (Object.keys(patch).length > 0) await this.handle.patch(minted, patch);
108208
108342
  await this.hooks.onChanged?.(minted, "created");
108209
108343
  return { id: minted };
@@ -108249,23 +108383,53 @@ var RecordIntegrationInstances = class {
108249
108383
  this.switchListeners.add(listener);
108250
108384
  }
108251
108385
  /**
108252
- * The ONE writer of the switch (D996, D1014): the record body's `enabled`, for every role. A
108253
- * configured thing is an instance, so an id with no record yet (a default integration that was
108254
- * never configured) gets its record from `initialBody` before the switch is written.
108386
+ * The hub's notification that the registry row of `id` moved (D1066). The registry holds the
108387
+ * switch; this keeps NO copy of it in the record. It remembers the state for this process's
108388
+ * readers ({@link isInstanceOn}), lets the addon re-apply, and fires the listeners.
108255
108389
  */
108256
108390
  setInstanceEnabled = async ({ id, enabled }) => {
108257
- if (await this.handle.get(id) === null) await this.handle.put({
108258
- id,
108259
- data: this.hooks.initialBody(id)
108260
- }, { ifRev: 0 });
108261
- await this.handle.patch(id, { [SWITCH_KEY]: enabled });
108391
+ claimInstance(this.records.owner, id);
108392
+ recordRegistrySwitch(id, enabled);
108393
+ this.knownSwitches.set(id, enabled);
108262
108394
  await this.hooks.onChanged?.(id, "enabled");
108263
108395
  for (const listener of this.switchListeners) await listener(id, enabled);
108264
108396
  return { ok: true };
108265
108397
  };
108398
+ /**
108399
+ * After the registry answered for a kind built before it could: announce the state of every
108400
+ * instance of this kind, on and off, so an addon that started on the fail-closed default (off)
108401
+ * starts what is on and stops what is off.
108402
+ */
108403
+ async reapply() {
108404
+ const page = await this.handle.query({ limit: INSTANCES_LIST_MAX });
108405
+ for (const record of page.records) {
108406
+ claimInstance(this.records.owner, record.id);
108407
+ const enabled = isInstanceOn(record.id);
108408
+ if (this.knownSwitches.get(record.id) === enabled) continue;
108409
+ this.knownSwitches.set(record.id, enabled);
108410
+ await this.hooks.onChanged?.(record.id, "enabled");
108411
+ for (const listener of this.switchListeners) await listener(record.id, enabled);
108412
+ }
108413
+ }
108414
+ /**
108415
+ * The records of this kind the registry holds no row for: created outside the hub door (a
108416
+ * seed, a migration, a store write). Each carries the state this process holds for it, on when
108417
+ * it holds none, because on was its effective state before the registry owned the switch.
108418
+ */
108419
+ async unrowed() {
108420
+ return (await this.handle.query({ limit: INSTANCES_LIST_MAX })).records.filter((record) => !hasRegistryRow(record.id)).map((record) => {
108421
+ const name = record.data[this.nameField];
108422
+ return {
108423
+ id: record.id,
108424
+ name: typeof name === "string" ? name : record.id,
108425
+ enabled: statedInstanceSwitch(record.id) ?? true
108426
+ };
108427
+ });
108428
+ }
108266
108429
  /** The row and its keychain refs go together (the records door). */
108267
108430
  deleteInstance = async ({ id }) => {
108268
108431
  await this.handle.delete(id);
108432
+ forgetInstanceSwitch(id);
108269
108433
  await this.hooks.onChanged?.(id, "deleted");
108270
108434
  return { ok: true };
108271
108435
  };
@@ -108400,6 +108564,107 @@ function registrySwitchPortsOver(deps) {
108400
108564
  };
108401
108565
  }
108402
108566
  /**
108567
+ * The switch comes back to the registry (D1066), the reverse of {@link registrySwitchToBodyMigration}.
108568
+ * An instance's on/off state lived in its record body (`enabled`, D1007 superseded by D1015); the hub
108569
+ * registry row, keyed by (addon, integration id) like a device, is now the only stored switch.
108570
+ *
108571
+ * For every record of the addon's kind:
108572
+ * - the state is the body's `enabled` (absent means on). When the registry row of that id disagrees,
108573
+ * the BODY wins: it was the only live copy while the body held the switch, and the registry
108574
+ * column of a migrated row was never read;
108575
+ * - a record with no registry row gets one (a services instance, under its addon-minted id);
108576
+ * - the key is then removed from the body, so no second copy remains.
108577
+ * A rerun finds no body that states `enabled` and writes nothing. The registry write goes first, so
108578
+ * a crash between the two steps repeats the pair (idempotent) and never loses a switched-off state.
108579
+ *
108580
+ * It runs in the addon process, after {@link registrySwitchToBodyMigration}, BEFORE the addon
108581
+ * registers its provider.
108582
+ */
108583
+ function bodySwitchToRegistryId(addonId, date, kindName) {
108584
+ return `${addonId}/${date}-body-switch-to-registry-${kindName}`;
108585
+ }
108586
+ async function moveBodySwitchToRegistry(ports, spec) {
108587
+ const records = await ports.listRecords();
108588
+ const adopted = records.length === 0 ? {
108589
+ created: 0,
108590
+ updated: 0,
108591
+ conflicts: []
108592
+ } : await ports.adoptRows(spec.addonId, records.map((r) => ({
108593
+ id: r.id,
108594
+ name: r.name,
108595
+ enabled: r.enabled,
108596
+ stated: r.stated
108597
+ })));
108598
+ const foreign = new Map(adopted.conflicts.map((c) => [c.id, c.ownerAddonId]));
108599
+ for (const [id, owner] of foreign) await ports.warn(`body switch kept: the registry row "${id}" belongs to addon "${owner}", not "${spec.addonId}"`);
108600
+ const stated = records.filter((r) => r.stated && !foreign.has(r.id));
108601
+ for (const row of stated) await ports.stripSwitch(row.id);
108602
+ const summary = {
108603
+ records: records.length,
108604
+ stripped: stated.length,
108605
+ rowsCreated: adopted.created,
108606
+ rowsCorrected: adopted.updated,
108607
+ conflicts: adopted.conflicts.length
108608
+ };
108609
+ return stated.length === 0 && adopted.created === 0 && adopted.updated === 0 ? {
108610
+ outcome: "already-done",
108611
+ summary
108612
+ } : {
108613
+ outcome: "done",
108614
+ summary
108615
+ };
108616
+ }
108617
+ /** A migration entry: an addon states its kind, nothing else. */
108618
+ function bodySwitchToRegistryMigration(spec) {
108619
+ return {
108620
+ meta: {
108621
+ id: bodySwitchToRegistryId(spec.addonId, spec.date, spec.kindName),
108622
+ owner: spec.addonId,
108623
+ level: "addon-state",
108624
+ seq: spec.seq,
108625
+ dependsOn: spec.followsDate === void 0 ? [] : [registrySwitchToBodyId(spec.addonId, spec.followsDate)],
108626
+ store: "settings",
108627
+ scope: "cluster",
108628
+ onFailure: "block-owner",
108629
+ bodyKind: "procedure",
108630
+ description: "Move the switch of every instance record back to its registry row (creating the row of a services instance) and remove it from the body",
108631
+ fixtureMark: "enabled"
108632
+ },
108633
+ procedure: (ports) => moveBodySwitchToRegistry(ports, { addonId: spec.addonId })
108634
+ };
108635
+ }
108636
+ function bodySwitchPortsOver(deps) {
108637
+ const handle = deps.records.kind({
108638
+ name: deps.kind.name,
108639
+ declaration: deps.kind.declaration,
108640
+ schema: record(string(), unknown())
108641
+ });
108642
+ return {
108643
+ listRecords: async () => {
108644
+ return (await handle.query({ limit: 1e3 })).records.map((r) => {
108645
+ const name = r.data[deps.nameField];
108646
+ return {
108647
+ id: r.id,
108648
+ name: typeof name === "string" ? name : r.id,
108649
+ enabled: r.data[SWITCH_KEY] !== false,
108650
+ stated: SWITCH_KEY in r.data
108651
+ };
108652
+ });
108653
+ },
108654
+ adoptRows: deps.adopt,
108655
+ warn: deps.warn,
108656
+ stripSwitch: async (id) => {
108657
+ const row = await handle.get(id);
108658
+ if (row === null || !("enabled" in row.data)) return;
108659
+ const { [SWITCH_KEY]: _dropped, ...rest } = row.data;
108660
+ await handle.put({
108661
+ id,
108662
+ data: rest
108663
+ }, { ifRev: row.rev });
108664
+ }
108665
+ };
108666
+ }
108667
+ /**
108403
108668
  * Build a {@link DurableState} over a single store key. Transport-agnostic:
108404
108669
  * `read`/`write` are the addon-store or device-store accessors. The whole
108405
108670
  * validated value round-trips on every read/write — the schema is the
@@ -108431,6 +108696,20 @@ function createDurableState(deps) {
108431
108696
  };
108432
108697
  }
108433
108698
  /**
108699
+ * The registry could not be read for the switches of an addon that serves instance kinds, so its
108700
+ * instances read off (D1066). A forked runner treats it as a failed boot: the supervisor respawns
108701
+ * it, bounded and marked terminally failed (D6), rather than leave instances off silently.
108702
+ */
108703
+ var INSTANCE_SWITCHES_UNREAD_ERROR_NAME = "InstanceSwitchesUnreadError";
108704
+ var InstanceSwitchesUnreadError = class extends Error {
108705
+ ownerId;
108706
+ constructor(ownerId) {
108707
+ super(`'${ownerId}': the registry did not answer for the instance switches; its instances stay off`);
108708
+ this.ownerId = ownerId;
108709
+ this.name = INSTANCE_SWITCHES_UNREAD_ERROR_NAME;
108710
+ }
108711
+ };
108712
+ /**
108434
108713
  * Per-node scoping for the shared addon-settings blob.
108435
108714
  *
108436
108715
  * An addon's settings store is hub-central (the `addon-settings` cap is
@@ -109414,7 +109693,14 @@ var BaseAddon = class {
109414
109693
  if (secrets !== void 0) this._secretChangeUnsub = secrets.onChange((ref) => {
109415
109694
  if (this._configSecretRefs.has(ref)) this.scheduleSecretReresolve(SECRET_CHANGE_DEBOUNCE_MS);
109416
109695
  });
109696
+ await this.hydrateSwitches();
109417
109697
  const result = await this.onInitialize();
109698
+ await this.moveLateInstanceKinds();
109699
+ await this.adoptUnrowed();
109700
+ if (this.switchesHydrated) {
109701
+ settleHydration(this.ctx.id);
109702
+ for (const served of servedInstanceKindsOf(this.ctx.id)) await served.reapply();
109703
+ }
109418
109704
  this.emitLifecycle(EventCategory.AddonStarted);
109419
109705
  const normalized = normalizeAddonInitResult(result);
109420
109706
  const providers = normalized && "providers" in normalized && normalized.providers ? normalized.providers : [];
@@ -109454,17 +109740,22 @@ var BaseAddon = class {
109454
109740
  this.retiredMigrationIds = ids;
109455
109741
  }
109456
109742
  registrySwitchSpec = null;
109743
+ /** The instance kinds whose switch move this process already ran (or tried), by record kind name. */
109744
+ switchMoved = /* @__PURE__ */ new Set();
109745
+ lastDeclared = [];
109457
109746
  registrySwitchBound() {
109458
- const spec = this.registrySwitchSpec;
109459
- if (spec === null) return [];
109460
109747
  const api = this.ctx.migrationApi;
109748
+ const spec = this.registrySwitchSpec;
109749
+ const kinds = servedInstanceKindsOf(this.ctx.id).filter((k) => !this.switchMoved.has(k.kind.name));
109750
+ if (spec === null && kinds.length === 0) return [];
109461
109751
  if (api === void 0) {
109462
109752
  this.ctx.logger.warn("the registry switch migration is skipped: the migration API is not available on this context");
109463
109753
  return [];
109464
109754
  }
109465
- return migrationSet([registrySwitchToBodyMigration({
109755
+ const date = "2026-11-06";
109756
+ const moveIn = spec === null ? [] : migrationSet([registrySwitchToBodyMigration({
109466
109757
  addonId: this.ctx.id,
109467
- date: "2026-11-06",
109758
+ date,
109468
109759
  seq: 1e3,
109469
109760
  initialBody: spec.initialBody
109470
109761
  })], (a) => registrySwitchPortsOver({
@@ -109472,13 +109763,53 @@ var BaseAddon = class {
109472
109763
  records: switchRecordsOverMigrationApi(a),
109473
109764
  kind: spec.kind
109474
109765
  })).bind(api);
109766
+ const moveBack = kinds.flatMap(({ kind }, index) => {
109767
+ this.switchMoved.add(kind.name);
109768
+ return migrationSet([bodySwitchToRegistryMigration({
109769
+ addonId: this.ctx.id,
109770
+ date: "2026-11-19",
109771
+ seq: 1001 + index,
109772
+ kindName: kind.name,
109773
+ ...spec === null ? {} : { followsDate: date }
109774
+ })], (a) => bodySwitchPortsOver({
109775
+ records: bodySwitchRecordsOverMigrationApi(a),
109776
+ kind,
109777
+ nameField: kind.declaration.entry?.nameField ?? "name",
109778
+ adopt: (addonId, rows) => this.ctx.api.integrations.adoptInstanceRows.mutate({
109779
+ addonId,
109780
+ rows: [...rows]
109781
+ }),
109782
+ warn: async (message) => {
109783
+ await a.log.warn({ message });
109784
+ }
109785
+ })).bind(api);
109786
+ });
109787
+ return [...moveIn, ...moveBack];
109788
+ }
109789
+ /**
109790
+ * A helper built AFTER the addon's migrations ran has a kind that moved nothing yet. Run its
109791
+ * switch move now (the engine replaces an owner's catalogue on every declare, so the whole
109792
+ * declared set goes with it, phased to the late ids), read the registry again, and tell the
109793
+ * addon about every instance that is off so it stops what it started on the default.
109794
+ */
109795
+ async moveLateInstanceKinds() {
109796
+ const late = servedInstanceKindsOf(this.ctx.id).filter((k) => !this.switchMoved.has(k.kind.name));
109797
+ if (late.length === 0) return;
109798
+ try {
109799
+ const only = late.map((k) => bodySwitchToRegistryId(this.ctx.id, "2026-11-19", k.kind.name));
109800
+ await this.runBound(this.lastDeclared, { only });
109801
+ } catch (err) {
109802
+ if (err instanceof AddonMigrationsBlockedError) throw err;
109803
+ this.ctx.logger.error("the late instance switch move failed", { meta: { error: errMsg$3(err) } });
109804
+ }
109475
109805
  }
109476
109806
  async runBound(declared, options) {
109807
+ this.lastDeclared = declared;
109477
109808
  const added = this.registrySwitchBound();
109478
109809
  const migrations = [...declared, ...added];
109479
109810
  const widened = options?.only === void 0 || added.length === 0 ? options : {
109480
109811
  ...options,
109481
- only: [...options.only, ...added.map((m) => m.meta.id)]
109812
+ only: [...new Set([...options.only, ...added.map((m) => m.meta.id)])]
109482
109813
  };
109483
109814
  const phased = this.retiredMigrationIds.length === 0 ? widened ?? {} : {
109484
109815
  ...widened,
@@ -109491,9 +109822,87 @@ var BaseAddon = class {
109491
109822
  finishMigration: (input) => api.finishMigration.mutate(input)
109492
109823
  }, migrations, this.ctx.logger, phased);
109493
109824
  if (report.blockOwner.length > 0) throw new AddonMigrationsBlockedError(report.blockOwner);
109825
+ await this.hydrateSwitches();
109826
+ await this.adoptUnrowed();
109494
109827
  return report;
109495
109828
  }
109496
109829
  /**
109830
+ * Learn the on/off state of this addon's instances from the registry rows (D1066), at boot, after
109831
+ * a migration run, and again through {@link rehydrateSwitches}. It runs on the addon's own boot
109832
+ * path, never inside a method the hub calls into. A registry that cannot answer leaves the
109833
+ * instances of THIS addon reading off (fail closed, per owner) until a read answers.
109834
+ */
109835
+ switchesHydrated = false;
109836
+ async hydrateSwitches() {
109837
+ beginHydration(this.ctx.id);
109838
+ try {
109839
+ const rows = await this.ctx.api.integrations.listByAddon.query({ addonId: this.ctx.id });
109840
+ hydrateInstanceSwitches(this.ctx.id, rows);
109841
+ this.switchesHydrated = true;
109842
+ return true;
109843
+ } catch (err) {
109844
+ this.ctx.logger.warn("instance switches not read from the registry: instances stay off", { meta: { error: errMsg$3(err) } });
109845
+ return false;
109846
+ }
109847
+ }
109848
+ /**
109849
+ * Every record of a served kind the registry holds no row for (created outside the hub door:
109850
+ * a seed, a store write) is adopted with the state it effectively had, on unless this process
109851
+ * stated it off, so the hub can switch it. A failure is logged; the next hydration retries.
109852
+ */
109853
+ async adoptUnrowed() {
109854
+ if (!this.switchesHydrated) return;
109855
+ try {
109856
+ for (const served of servedInstanceKindsOf(this.ctx.id)) {
109857
+ const rows = await served.unrowed();
109858
+ if (rows.length === 0) continue;
109859
+ await this.ctx.api.integrations.adoptInstanceRows.mutate({
109860
+ addonId: this.ctx.id,
109861
+ rows: rows.map((r) => ({
109862
+ id: r.id,
109863
+ name: r.name,
109864
+ enabled: r.enabled,
109865
+ stated: false
109866
+ }))
109867
+ });
109868
+ for (const r of rows) recordRegistrySwitch(r.id, r.enabled);
109869
+ }
109870
+ } catch (err) {
109871
+ this.ctx.logger.warn("records without a registry row were not adopted", { meta: { error: errMsg$3(err) } });
109872
+ }
109873
+ }
109874
+ /**
109875
+ * Read the switches from the registry again and announce the states now known, so an addon that
109876
+ * started on the fail-closed default (off) starts what is on. Throws
109877
+ * {@link InstanceSwitchesUnreadError} when the registry still does not answer while this addon
109878
+ * serves instance kinds: a forked runner turns that into a failed boot (the supervisor respawns
109879
+ * it, bounded, D6), an agent or the hub reads again on the next hub connect (event-driven, D3).
109880
+ * An addon with no instance kind has nothing waiting and never throws.
109881
+ */
109882
+ async rehydrateSwitches() {
109883
+ if (this._ctx === null) return;
109884
+ if (await this.hydrateSwitches()) {
109885
+ await this.adoptUnrowed();
109886
+ settleHydration(this.ctx.id);
109887
+ for (const served of servedInstanceKindsOf(this.ctx.id)) await served.reapply();
109888
+ return;
109889
+ }
109890
+ if (isHydrationPending(this.ctx.id)) throw new InstanceSwitchesUnreadError(this.ctx.id);
109891
+ }
109892
+ /**
109893
+ * Called on the hub-reachable event (instead of `onHubReachable` directly): the switches are
109894
+ * read again, then `onHubReachable` runs. A registry that still does not answer is logged and
109895
+ * left for the next connect.
109896
+ */
109897
+ async hubReachable() {
109898
+ try {
109899
+ await this.rehydrateSwitches();
109900
+ } catch (err) {
109901
+ this.ctx.logger.warn("instance switches still unread at the hub connect", { meta: { error: errMsg$3(err) } });
109902
+ }
109903
+ await this.onHubReachable();
109904
+ }
109905
+ /**
109497
109906
  * Called by the isolated-process runner AFTER `broker.start()`.
109498
109907
  * In-process addons never need this because the hub broker is already
109499
109908
  * running when `initialize()` fires. For forked children the broker
@@ -124078,6 +124487,147 @@ Object.freeze({
124078
124487
  }
124079
124488
  });
124080
124489
  /**
124490
+ * Delays before retry rounds 1..N — the round count IS the bound.
124491
+ * 10 s catches "the hub was busy for a moment"; the full schedule
124492
+ * (10 + 30 + 90 s of waiting, plus up to one 60 s transport timeout
124493
+ * per attempt) covers a device-manager lock held for minutes — the
124494
+ * 2026-09-04 outage's migration hold was ~3.5 min.
124495
+ */
124496
+ var DEVICE_RESTORE_RETRY_DELAYS_MS = [
124497
+ 1e4,
124498
+ 3e4,
124499
+ 9e4
124500
+ ];
124501
+ /** Abortable sleep — resolves early (never rejects) on abort. */
124502
+ function sleep$1(ms, signal) {
124503
+ return new Promise((resolve) => {
124504
+ if (signal.aborted) {
124505
+ resolve();
124506
+ return;
124507
+ }
124508
+ const onAbort = () => {
124509
+ clearTimeout(timer);
124510
+ resolve();
124511
+ };
124512
+ const timer = setTimeout(() => {
124513
+ signal.removeEventListener("abort", onAbort);
124514
+ resolve();
124515
+ }, ms);
124516
+ timer.unref?.();
124517
+ signal.addEventListener("abort", onAbort, { once: true });
124518
+ });
124519
+ }
124520
+ /** Drain `items` through at most `width` concurrent lanes. `fn` must
124521
+ * not reject (callers wrap their own try/catch). */
124522
+ async function runWithConcurrency(items, width, fn) {
124523
+ const queue = [...items];
124524
+ const laneCount = Math.max(1, Math.min(width, queue.length));
124525
+ const lane = async () => {
124526
+ for (;;) {
124527
+ const item = queue.shift();
124528
+ if (item === void 0) return;
124529
+ await fn(item);
124530
+ }
124531
+ };
124532
+ await Promise.all(Array.from({ length: laneCount }, lane));
124533
+ }
124534
+ var DeviceRestoreRetryScheduler = class {
124535
+ #logger;
124536
+ #attempt;
124537
+ #onPermanentFailure;
124538
+ #delaysMs;
124539
+ #concurrency;
124540
+ #now;
124541
+ #abort = new AbortController();
124542
+ constructor(options) {
124543
+ this.#logger = options.logger;
124544
+ this.#attempt = options.attempt;
124545
+ this.#onPermanentFailure = options.onPermanentFailure;
124546
+ this.#delaysMs = options.delaysMs ?? DEVICE_RESTORE_RETRY_DELAYS_MS;
124547
+ this.#concurrency = options.concurrency ?? 4;
124548
+ this.#now = options.now ?? Date.now;
124549
+ }
124550
+ /** Stop retrying (shutdown). Pending entries are NOT marked
124551
+ * permanently failed — the next boot restores them from disk. */
124552
+ cancel() {
124553
+ this.#abort.abort();
124554
+ }
124555
+ /**
124556
+ * Run the bounded retry rounds. Resolves when every entry has either
124557
+ * restored, been marked permanently failed, or the scheduler was
124558
+ * cancelled. Never rejects.
124559
+ */
124560
+ async run(initialFailures) {
124561
+ let pending = initialFailures.map((failure) => ({
124562
+ saved: failure.saved,
124563
+ lastError: failure.error,
124564
+ attempts: 1
124565
+ }));
124566
+ for (let round = 0; round < this.#delaysMs.length; round += 1) {
124567
+ if (pending.length === 0 || this.#abort.signal.aborted) break;
124568
+ await sleep$1(this.#delaysMs[round] ?? 0, this.#abort.signal);
124569
+ if (this.#abort.signal.aborted) break;
124570
+ pending = await this.#runRound(pending, round);
124571
+ }
124572
+ if (this.#abort.signal.aborted) return [];
124573
+ const terminal = pending.map((entry) => ({
124574
+ deviceId: entry.saved.id,
124575
+ stableId: entry.saved.stableId,
124576
+ type: String(entry.saved.type),
124577
+ attempts: entry.attempts,
124578
+ lastError: entry.lastError,
124579
+ failedAt: this.#now()
124580
+ }));
124581
+ for (const failure of terminal) this.#onPermanentFailure(failure);
124582
+ return terminal;
124583
+ }
124584
+ /** One retry round: parents first (phase 0), then hub-adopted
124585
+ * children (phase 1) — a child's attempt depends on its parent
124586
+ * having landed, exactly like the initial two-pass restore. */
124587
+ async #runRound(pending, round) {
124588
+ const next = [];
124589
+ const parents = pending.filter((entry) => entry.saved.parentDeviceId === null);
124590
+ const children = pending.filter((entry) => entry.saved.parentDeviceId !== null);
124591
+ for (const phase of [parents, children]) await runWithConcurrency(phase, this.#concurrency, async (entry) => {
124592
+ if (this.#abort.signal.aborted) {
124593
+ next.push(entry);
124594
+ return;
124595
+ }
124596
+ const attemptNo = entry.attempts + 1;
124597
+ try {
124598
+ await this.#attempt(entry.saved);
124599
+ this.#logger.info("Device restored on retry", {
124600
+ tags: {
124601
+ deviceId: entry.saved.id,
124602
+ stableId: entry.saved.stableId
124603
+ },
124604
+ meta: { attempt: attemptNo }
124605
+ });
124606
+ } catch (err) {
124607
+ const lastError = err instanceof Error ? err.message : String(err);
124608
+ const remainingRetries = this.#delaysMs.length - (round + 1);
124609
+ this.#logger.warn("Device restore retry failed", {
124610
+ tags: {
124611
+ deviceId: entry.saved.id,
124612
+ stableId: entry.saved.stableId
124613
+ },
124614
+ meta: {
124615
+ attempt: attemptNo,
124616
+ remainingRetries,
124617
+ error: lastError
124618
+ }
124619
+ });
124620
+ next.push({
124621
+ saved: entry.saved,
124622
+ lastError,
124623
+ attempts: attemptNo
124624
+ });
124625
+ }
124626
+ });
124627
+ return next;
124628
+ }
124629
+ };
124630
+ /**
124081
124631
  * Promise-based timer helpers — used everywhere the codebase needs to
124082
124632
  * wait, back off, or schedule a retry. Before these helpers landed, each
124083
124633
  * call site re-implemented `new Promise(r => setTimeout(r, ms))` inline,
@@ -126105,6 +126655,27 @@ function deviceTemplateFilterNames() {
126105
126655
  return DEVICE_TEMPLATE_CATALOGUE.filter((item) => item.kind === "filter").map((item) => item.name);
126106
126656
  }
126107
126657
  //#endregion
126658
+ //#region ../types/dist/enums.mjs
126659
+ function e(group, en, it, flags = {}) {
126660
+ return {
126661
+ group,
126662
+ label: {
126663
+ en,
126664
+ it
126665
+ },
126666
+ noise: flags.noise === true,
126667
+ deprecated: flags.deprecated === true
126668
+ };
126669
+ }
126670
+ var N = { noise: true };
126671
+ EventCategory.SystemBoot, e("system", "System booted", "Sistema avviato"), EventCategory.SystemAddonsReady, e("system", "Addons ready", "Addon pronti"), EventCategory.SystemRestarting, e("system", "System restarting", "Sistema in riavvio"), EventCategory.SystemRestartCompleted, e("system", "Restart completed", "Riavvio completato"), EventCategory.SystemTlsCertChanged, e("system", "TLS certificate changed", "Certificato TLS cambiato"), EventCategory.UpdateAvailable, e("system", "Update available", "Aggiornamento disponibile"), EventCategory.SystemReadyState, e("system", "Readiness changed", "Stato di prontezza cambiato"), EventCategory.AddonStarted, e("addons", "Addon started", "Addon avviato"), EventCategory.AddonStopped, e("addons", "Addon stopped", "Addon fermato"), EventCategory.AddonRestarted, e("addons", "Addon restarted", "Addon riavviato"), EventCategory.AddonUpdated, e("addons", "Addon updated", "Addon aggiornato"), EventCategory.AddonInstalled, e("addons", "Addon installed", "Addon installato"), EventCategory.AddonUninstalled, e("addons", "Addon uninstalled", "Addon disinstallato"), EventCategory.AddonCrashed, e("addons", "Addon crashed", "Addon in errore fatale"), EventCategory.AddonRunnerFailed, e("addons", "Runner failed for good", "Runner fallito definitivamente"), EventCategory.AddonRunnerRefused, e("addons", "Runner refused", "Runner rifiutato"), EventCategory.ProcessStateChanged, e("addons", "Process state changed", "Stato del processo cambiato"), EventCategory.SystemRunnerCheck, e("system", "Runner check", "Verifica dei runner"), EventCategory.AlertEpisode, e("system", "Alert episode", "Episodio di allarme"), EventCategory.AddonError, e("addons", "Addon error", "Errore di un addon"), EventCategory.AddonPageReady, e("addons", "Addon page ready", "Pagina addon pronta"), EventCategory.AddonWidgetReady, e("addons", "Addon widget ready", "Widget addon pronto"), EventCategory.AddonLoadFailed, e("addons", "Addon failed to load", "Caricamento addon fallito"), EventCategory.KeychainChanged, e("system", "Keychain changed", "Portachiavi modificato"), EventCategory.AddonLoadRecovered, e("addons", "Addon load recovered", "Caricamento addon ripristinato"), EventCategory.AddonUnsupportedVersion, e("addons", "Addon version unsupported", "Versione addon non supportata"), EventCategory.AddonUnsupportedResolved, e("addons", "Unsupported addon resolved", "Addon non supportato risolto"), EventCategory.AddonRetryScheduled, e("addons", "Addon retry scheduled", "Nuovo tentativo addon pianificato"), EventCategory.SystemLivenessFailed, e("system", "Liveness check failed", "Controllo di attività fallito"), EventCategory.SystemLivenessRecovered, e("system", "Liveness recovered", "Controllo di attività ripristinato"), EventCategory.AddonRetryAttempting, e("addons", "Addon retry running", "Nuovo tentativo addon in corso"), EventCategory.DeviceRegistered, e("devices", "Device registered", "Dispositivo registrato"), EventCategory.DeviceUnregistered, e("devices", "Device removed", "Dispositivo rimosso"), EventCategory.DeviceEnabled, e("devices", "Device enabled", "Dispositivo abilitato"), EventCategory.DeviceDisabled, e("devices", "Device disabled", "Dispositivo disabilitato"), EventCategory.DeviceSettingsUpdated, e("devices", "Device settings updated", "Impostazioni dispositivo aggiornate"), EventCategory.DeviceBindingsChanged, e("devices", "Device bindings changed", "Collegamenti dispositivo cambiati"), EventCategory.DeviceMetaChanged, e("devices", "Device details changed", "Dettagli dispositivo cambiati"), EventCategory.DeviceSourceInfoChanged, e("devices", "Device source info changed", "Info sorgente dispositivo cambiate"), EventCategory.DeviceStreamsRegistered, e("streams", "Device streams registered", "Stream del dispositivo registrati"), EventCategory.DeviceProvisioned, e("devices", "Device provisioned", "Dispositivo configurato"), EventCategory.DeviceReady, e("devices", "Device ready", "Dispositivo pronto"), EventCategory.IdentityLinkCreated, e("integrations", "Identity linked", "Identità collegata"), EventCategory.IdentityLinkLost, e("integrations", "Identity link lost", "Collegamento identità perso"), EventCategory.IntegrationEnabled, e("integrations", "Integration enabled", "Integrazione abilitata"), EventCategory.IntegrationDisabled, e("integrations", "Integration disabled", "Integrazione disabilitata"), EventCategory.IntegrationDeleted, e("integrations", "Integration deleted", "Integrazione eliminata"), EventCategory.BrokerStatusChanged, e("integrations", "Broker status changed", "Stato del broker cambiato"), EventCategory.BrokerMessage, e("integrations", "Broker message", "Messaggio del broker", N), EventCategory.ProviderStarted, e("integrations", "Provider started", "Provider avviato"), EventCategory.ProviderStopped, e("integrations", "Provider stopped", "Provider fermato"), EventCategory.ProcessCrashed, e("addons", "Process crashed", "Processo andato in crash"), EventCategory.ProcessRestartScheduled, e("addons", "Process restart scheduled", "Riavvio del processo pianificato"), EventCategory.ProcessRestarted, e("addons", "Process restarted", "Processo riavviato"), EventCategory.StorageLocationsChanged, e("storage", "Storage locations changed", "Posizioni di archiviazione cambiate"), EventCategory.RecordingStarted, e("recording", "Recording started", "Registrazione avviata"), EventCategory.RecordingStopped, e("recording", "Recording stopped", "Registrazione fermata"), EventCategory.RecordingError, e("recording", "Recording error", "Errore di registrazione"), EventCategory.RecordingHealthDegraded, e("recording", "Recording degraded", "Registrazione degradata"), EventCategory.RecordingHealthStalled, e("recording", "Recording stalled", "Registrazione bloccata"), EventCategory.RecordingHealthOk, e("recording", "Recording healthy", "Registrazione regolare"), EventCategory.RecordingStorageCritical, e("recording", "Recording storage critical", "Spazio di registrazione critico"), EventCategory.StorageLocationLow, e("storage", "Storage location low", "Spazio in esaurimento"), EventCategory.StorageLocationCritical, e("storage", "Storage location critical", "Spazio critico"), EventCategory.StorageLocationOk, e("storage", "Storage location recovered", "Spazio tornato regolare"), EventCategory.StorageDrainProgress, e("storage", "Drain progress", "Avanzamento dello svuotamento"), EventCategory.StorageDrainComplete, e("storage", "Drain complete", "Svuotamento completato"), EventCategory.RecordingSegmentWritten, e("recording", "Segment written", "Segmento scritto"), EventCategory.RecordingPolicyFallback, e("recording", "Recording policy fallback", "Politica di registrazione di ripiego"), EventCategory.RecordingRetentionCompleted, e("recording", "Retention completed", "Pulizia completata"), EventCategory.RecordingExportProgress, e("recording", "Export progress", "Avanzamento esportazione"), EventCategory.RecordingExportCompleted, e("recording", "Export completed", "Esportazione completata"), EventCategory.RecordingExportFailed, e("recording", "Export failed", "Esportazione fallita"), EventCategory.DetectionEvent, e("detection", "Detection", "Rilevamento"), EventCategory.SessionTrackNew, e("detection", "Session track started", "Nuova traccia di sessione"), EventCategory.SessionTrackExpired, e("detection", "Session track expired", "Traccia di sessione scaduta"), EventCategory.BenchmarkProgress, e("metrics", "Benchmark progress", "Avanzamento benchmark", N), EventCategory.PlatformProbePhase, e("metrics", "Platform probe phase", "Fase di analisi piattaforma", N), EventCategory.PipelineProgress, e("pipeline", "Pipeline progress", "Avanzamento pipeline", N), EventCategory.PipelineTrace, e("pipeline", "Pipeline trace", "Traccia pipeline", N), EventCategory.PipelineInferenceResult, e("pipeline", "Inference result", "Risultato di inferenza", N), EventCategory.PipelineCameraAssigned, e("pipeline", "Camera assigned to pipeline", "Camera assegnata alla pipeline"), EventCategory.PipelineCameraUnassigned, e("pipeline", "Camera unassigned from pipeline", "Camera rimossa dalla pipeline"), EventCategory.PipelineNodeInferenceUnavailable, e("pipeline", "Node inference unavailable", "Inferenza del nodo non disponibile"), EventCategory.PipelineDetectionBlind, e("pipeline", "Detection blind", "Rilevamento cieco"), EventCategory.PipelineMotionNoisy, e("pipeline", "Motion too noisy", "Movimento troppo disturbato"), EventCategory.PipelineMotionCalm, e("pipeline", "Motion calm again", "Movimento di nuovo calmo"), EventCategory.PipelinePackageLlmSilent, e("pipeline", "Package check silent", "Verifica pacchi senza risposta"), EventCategory.PipelinePackageLlmAnswered, e("pipeline", "Package check answered", "Verifica pacchi con risposta"), EventCategory.PipelineCameraUpdated, e("pipeline", "Pipeline camera updated", "Camera della pipeline aggiornata"), EventCategory.PipelineIngestOwnerChanged, e("pipeline", "Ingest owner changed", "Responsabile dell’acquisizione cambiato"), EventCategory.PipelineRunnerLoadSnapshot, e("metrics", "Runner load snapshot", "Carico dei runner", N), EventCategory.PipelineCameraMetricsSnapshot, e("metrics", "Camera metrics snapshot", "Metriche delle camere", N), EventCategory.StreamBrokerMetricsSnapshot, e("metrics", "Stream broker metrics", "Metriche dello stream broker", N), EventCategory.StreamBrokerOnCamStreamDemand, e("streams", "Stream requested", "Stream richiesto"), EventCategory.StreamBrokerOnCamStreamIdle, e("streams", "Stream idle", "Stream inattivo"), EventCategory.StreamBrokerOnRequestStreamSourceRefresh, e("streams", "Stream source refresh requested", "Aggiornamento sorgente stream richiesto"), EventCategory.StreamParamsChanged, e("streams", "Stream parameters changed", "Parametri dello stream cambiati"), EventCategory.DeviceStateChanged, e("devices", "Device state changed", "Stato dispositivo cambiato"), EventCategory.DeviceCommandSettled, e("devices", "Device command settled", "Comando al dispositivo concluso"), EventCategory.DeviceNativeShadowChanged, e("devices", "Device native state changed", "Stato nativo del dispositivo cambiato"), EventCategory.ZoneAnalyticsOccupancyChanged, e("detection", "Zone occupancy changed", "Occupazione zona cambiata"), EventCategory.BatteryOnStatusChanged, e("devices", "Battery status changed", "Stato batteria cambiato"), EventCategory.NetworkLinkOnStatusChanged, e("devices", "Network link status changed", "Stato del collegamento di rete cambiato"), EventCategory.BatteryOnWakeStarted, e("devices", "Battery device woke up", "Dispositivo a batteria attivato"), EventCategory.DoorbellOnPressed, e("devices", "Doorbell pressed", "Campanello premuto"), EventCategory.RunningStarted, e("devices", "Run started", "Esecuzione avviata"), EventCategory.RunningFinished, e("devices", "Run finished", "Esecuzione terminata"), EventCategory.WorkloadStarted, e("devices", "Workload started", "Carico di lavoro avviato"), EventCategory.WorkloadStopped, e("devices", "Workload stopped", "Carico di lavoro fermato"), EventCategory.WorkloadCrashed, e("devices", "Workload crashed", "Carico di lavoro in crash"), EventCategory.WorkloadRecovered, e("devices", "Workload recovered", "Carico di lavoro ripristinato"), EventCategory.DeviceRunOpened, e("devices", "Device run opened", "Ciclo del dispositivo aperto"), EventCategory.DeviceRunClosed, e("devices", "Device run closed", "Ciclo del dispositivo chiuso"), EventCategory.EventEmitted, e("devices", "Device event", "Evento del dispositivo"), EventCategory.PipelineEngineMetricsSnapshot, e("metrics", "Engine metrics snapshot", "Metriche dei motori", N), EventCategory.PipelineEngineProvisioning, e("pipeline", "Engine provisioning", "Preparazione del motore"), EventCategory.ClusterTopologySnapshot, e("metrics", "Cluster topology snapshot", "Topologia del cluster", N), EventCategory.MetricsNodeResourcesSnapshot, e("metrics", "Node resources snapshot", "Risorse dei nodi", N), EventCategory.MetricsNodeProcessesSnapshot, e("metrics", "Node processes snapshot", "Processi dei nodi", N), EventCategory.CapabilityBindingChanged, e("system", "Capability binding changed", "Collegamento di capability cambiato", N), EventCategory.ModelDownloadProgress, e("pipeline", "Model download progress", "Avanzamento download modello", N), EventCategory.AgentRegistered, e("agents", "Agent registered", "Agent registrato"), EventCategory.AgentUnregistered, e("agents", "Agent removed", "Agent rimosso"), EventCategory.AgentOnline, e("agents", "Agent online", "Agent online"), EventCategory.AgentOffline, e("agents", "Agent offline", "Agent offline"), EventCategory.WorkerOnline, e("agents", "Worker online", "Worker online"), EventCategory.WorkerOffline, e("agents", "Worker offline", "Worker offline"), EventCategory.AgentTaskDispatched, e("agents", "Agent task dispatched", "Attività inviata a un agent"), EventCategory.AgentTaskAssigned, e("agents", "Agent task assigned", "Attività assegnata a un agent"), EventCategory.AgentTrpcConnected, e("agents", "Agent API connected", "API dell’agent connessa"), EventCategory.AgentWsConnected, e("agents", "Agent socket connected", "Socket dell’agent connesso"), EventCategory.AgentWsDisconnected, e("agents", "Agent socket disconnected", "Socket dell’agent disconnesso"), EventCategory.AgentBackupActivated, e("agents", "Agent backup activated", "Backup dell’agent attivato"), EventCategory.OrchestrationSettingsUpdated, e("pipeline", "Orchestration settings updated", "Impostazioni di orchestrazione aggiornate"), EventCategory.MotionAnalysis, e("detection", "Motion analysis", "Analisi del movimento", N), EventCategory.MotionZonesRaw, e("detection", "Raw motion zones", "Zone di movimento grezze", N), EventCategory.MotionOnMotionChanged, e("detection", "Motion changed", "Movimento cambiato", N), EventCategory.DetectionResult, e("detection", "Detection result", "Risultato del rilevamento", N), EventCategory.DetectionRaw, e("detection", "Raw detection", "Rilevamento grezzo"), EventCategory.DetectionCameraNative, e("detection", "Camera native detection", "Rilevamento nativo della camera"), EventCategory.PipelineAudioInferenceResult, e("pipeline", "Audio inference result", "Risultato di inferenza audio", N), EventCategory.DetectionPhaseTransition, e("detection", "Detection phase changed", "Fase di rilevamento cambiata"), EventCategory.ProviderMotion, e("detection", "Camera raw motion", "Movimento grezzo della camera", N), EventCategory.ProviderDetection, e("detection", "Camera onboard detection", "Rilevamento a bordo camera"), EventCategory.EnrichmentEmbeddingStored, e("enrichment", "Embedding stored", "Embedding salvato"), EventCategory.EnrichmentSceneStateChanged, e("enrichment", "Scene state changed", "Stato della scena cambiato"), EventCategory.EnrichmentActivitySummary, e("enrichment", "Activity summary", "Riepilogo dell’attività"), EventCategory.PipelineAnalyticsTrackLifecycle, e("detection", "Track lifecycle", "Ciclo di vita della traccia"), EventCategory.PipelineAnalyticsTrackStarted, e("detection", "Track started", "Traccia iniziata", {
126672
+ noise: true,
126673
+ deprecated: true
126674
+ }), EventCategory.PipelineAnalyticsTrackEnded, e("detection", "Track ended", "Traccia terminata", {
126675
+ noise: true,
126676
+ deprecated: true
126677
+ }), EventCategory.PipelineAnalyticsDetectionEvent, e("detection", "Analytics detection", "Rilevamento analitico", N), EventCategory.PipelineAnalyticsFrameTracked, e("detection", "Frame tracked", "Fotogramma tracciato", N), EventCategory.PipelineAnalyticsStationaryChanged, e("detection", "Stationary object changed", "Oggetto fermo cambiato"), EventCategory.PipelineAnalyticsPackageDelivered, e("detection", "Package delivered", "Pacco consegnato"), EventCategory.PipelineAnalyticsPackagePickedUp, e("detection", "Package picked up", "Pacco ritirato"), EventCategory.PipelineAnalyticsFaceGalleryChanged, e("enrichment", "Face gallery changed", "Galleria volti cambiata"), EventCategory.PipelineAnalyticsPlateGalleryChanged, e("enrichment", "Plate gallery changed", "Galleria targhe cambiata"), EventCategory.CameraStreamsProfileSlotsChanged, e("streams", "Stream profile slots changed", "Slot dei profili stream cambiati"), EventCategory.StreamOnline, e("streams", "Stream online", "Stream online"), EventCategory.StreamOffline, e("streams", "Stream offline", "Stream offline"), EventCategory.NetworkTunnelStarted, e("network", "Tunnel started", "Tunnel avviato"), EventCategory.NetworkTunnelStopped, e("network", "Tunnel stopped", "Tunnel fermato"), EventCategory.LocalNetworkChanged, e("network", "Local network changed", "Rete locale cambiata"), EventCategory.MeshNetworkChanged, e("network", "Mesh network changed", "Rete mesh cambiata"), EventCategory.BackupCompleted, e("backup", "Backup completed", "Backup completato"), EventCategory.BackupRunCompleted, e("backup", "Backup run completed", "Esecuzione backup completata"), EventCategory.BackupRestored, e("backup", "Backup restored", "Backup ripristinato"), EventCategory.NotificationDispatched, e("notifications", "Notification sent", "Notifica inviata"), EventCategory.NotificationFailed, e("notifications", "Notification failed", "Notifica non riuscita"), EventCategory.NotificationRuleBroken, e("notifications", "Notification rule broken", "Regola di notifica non valida"), EventCategory.NotificationRuleRepaired, e("notifications", "Notification rule repaired", "Regola di notifica riparata"), EventCategory.MigrationFailed, e("system", "Migration failed", "Migrazione fallita"), EventCategory.MigrationApplied, e("system", "Migration applied", "Migrazione applicata"), EventCategory.DeviceUpdated, e("devices", "Device updated", "Dispositivo aggiornato"), EventCategory.DeviceOnline, e("devices", "Device online", "Dispositivo online"), EventCategory.DeviceOffline, e("devices", "Device offline", "Dispositivo offline"), EventCategory.DeviceAwake, e("devices", "Device awake", "Dispositivo attivo"), EventCategory.DeviceSleeping, e("devices", "Device sleeping", "Dispositivo in standby"), EventCategory.RetentionCleanup, e("storage", "Retention cleanup", "Pulizia della conservazione"), EventCategory.AddonsBulkUpdateProgress, e("addons", "Bulk update progress", "Avanzamento aggiornamento multiplo"), EventCategory.AddonsJobProgress, e("addons", "Addon job progress", "Avanzamento attività addon"), EventCategory.AddonsJobLog, e("addons", "Addon job log", "Log attività addon"), EventCategory.AccessoriesChildVisibilityChanged, e("devices", "Child visibility changed", "Visibilità del dispositivo figlio cambiata"), EventCategory.AccessoriesChanged, e("devices", "Accessories changed", "Accessori cambiati"), EventCategory.ActionsRunChanged, e("system", "Action run changed", "Esecuzione dell’azione cambiata"), EventCategory.ModelConvertProgress, e("pipeline", "Model conversion progress", "Avanzamento conversione modello");
126678
+ //#endregion
126108
126679
  //#region ../types/dist/index.mjs
126109
126680
  /**
126110
126681
  * The `smtp-inbound` broker kind (D999): a mailbox a device can send mail to.
@@ -153536,7 +154107,12 @@ var AutomationRunTraceSchema = object({
153536
154107
  * automation outcome so a reader that does not know schedulers still reads
153537
154108
  * the trace; this field says exactly what happened.
153538
154109
  */
153539
- scheduler: SchedulerOutcomeSchema.optional()
154110
+ scheduler: SchedulerOutcomeSchema.optional(),
154111
+ /**
154112
+ * Why the run failed when no step carries it: the run crashed outside the
154113
+ * steps (conditions, gate). Absent when the failure is on a step.
154114
+ */
154115
+ error: string().optional()
153540
154116
  });
153541
154117
  /**
153542
154118
  * What the hub's `runs` ledger holds for one owner (`automation:<blockId>` or
@@ -171336,14 +171912,8 @@ var IntegrationWithStateSchema = object({
171336
171912
  id: string(),
171337
171913
  addonId: string(),
171338
171914
  name: string(),
171339
- /** A projection of the instance body's switch (`setInstanceEnabled` is the only writer). */
171915
+ /** THE switch of the instance: the hub registry row is its only stored copy (D1066). */
171340
171916
  enabled: boolean(),
171341
- /**
171342
- * True when the addon that holds the switch did not answer (down, failed, or keeps no record for
171343
- * this row): `enabled` is then the stored registry flag, a stale value, not the state. A reader
171344
- * must not draw it as on or off (D315).
171345
- */
171346
- switchUnknown: literal(true).optional(),
171347
171917
  info: record(string(), unknown()).readonly(),
171348
171918
  /** The discovery candidate this integration was set up from (D984). */
171349
171919
  originStableId: string().optional(),
@@ -171355,14 +171925,8 @@ var IntegrationLiteSchema = object({
171355
171925
  id: string(),
171356
171926
  addonId: string(),
171357
171927
  name: string(),
171358
- /** A projection of the instance body's switch (`setInstanceEnabled` is the only writer). */
171928
+ /** THE switch of the instance: the hub registry row is its only stored copy (D1066). */
171359
171929
  enabled: boolean(),
171360
- /**
171361
- * True when the addon that holds the switch did not answer (down, failed, or keeps no record for
171362
- * this row): `enabled` is then the stored registry flag, a stale value, not the state. A reader
171363
- * must not draw it as on or off (D315).
171364
- */
171365
- switchUnknown: literal(true).optional(),
171366
171930
  info: record(string(), unknown()).readonly(),
171367
171931
  /** The discovery candidate this integration was set up from (D984). */
171368
171932
  originStableId: string().optional(),
@@ -171478,7 +172042,27 @@ var DeleteIntegrationResultSchema = object({
171478
172042
  success: boolean(),
171479
172043
  deletedId: string()
171480
172044
  });
171481
- method(_void(), array(IntegrationWithStateSchema)), method(object({ id: string() }), IntegrationWithStateSchema), method(object({ addonId: string() }), IntegrationLiteSchema.nullable()), method(UpdateIntegrationInputSchema, IntegrationLiteSchema, {
172045
+ method(_void(), array(IntegrationWithStateSchema)), method(object({ id: string() }), IntegrationWithStateSchema), method(object({ addonId: string() }), IntegrationLiteSchema.nullable()), method(object({ addonId: string() }), array(IntegrationLiteSchema)), method(object({
172046
+ addonId: string(),
172047
+ rows: array(object({
172048
+ id: string().min(1),
172049
+ name: string(),
172050
+ enabled: boolean(),
172051
+ /** True when the record body STATED the switch: only then does it override an existing row. */
172052
+ stated: boolean()
172053
+ }))
172054
+ }), object({
172055
+ created: number$1().int(),
172056
+ updated: number$1().int(),
172057
+ /** Rows whose id belongs to ANOTHER addon: left untouched, so the caller keeps its own copy. */
172058
+ conflicts: array(object({
172059
+ id: string(),
172060
+ ownerAddonId: string()
172061
+ }))
172062
+ }), {
172063
+ kind: "mutation",
172064
+ auth: "admin"
172065
+ }), method(UpdateIntegrationInputSchema, IntegrationLiteSchema, {
171482
172066
  kind: "mutation",
171483
172067
  auth: "admin"
171484
172068
  }), method(object({ id: string() }), DeleteIntegrationResultSchema, {
@@ -202200,147 +202784,6 @@ var BaseDevice = class {
202200
202784
  }
202201
202785
  };
202202
202786
  /**
202203
- * Delays before retry rounds 1..N — the round count IS the bound.
202204
- * 10 s catches "the hub was busy for a moment"; the full schedule
202205
- * (10 + 30 + 90 s of waiting, plus up to one 60 s transport timeout
202206
- * per attempt) covers a device-manager lock held for minutes — the
202207
- * 2026-09-04 outage's migration hold was ~3.5 min.
202208
- */
202209
- var DEVICE_RESTORE_RETRY_DELAYS_MS = [
202210
- 1e4,
202211
- 3e4,
202212
- 9e4
202213
- ];
202214
- /** Abortable sleep — resolves early (never rejects) on abort. */
202215
- function sleep$1(ms, signal) {
202216
- return new Promise((resolve) => {
202217
- if (signal.aborted) {
202218
- resolve();
202219
- return;
202220
- }
202221
- const onAbort = () => {
202222
- clearTimeout(timer);
202223
- resolve();
202224
- };
202225
- const timer = setTimeout(() => {
202226
- signal.removeEventListener("abort", onAbort);
202227
- resolve();
202228
- }, ms);
202229
- timer.unref?.();
202230
- signal.addEventListener("abort", onAbort, { once: true });
202231
- });
202232
- }
202233
- /** Drain `items` through at most `width` concurrent lanes. `fn` must
202234
- * not reject (callers wrap their own try/catch). */
202235
- async function runWithConcurrency(items, width, fn) {
202236
- const queue = [...items];
202237
- const laneCount = Math.max(1, Math.min(width, queue.length));
202238
- const lane = async () => {
202239
- for (;;) {
202240
- const item = queue.shift();
202241
- if (item === void 0) return;
202242
- await fn(item);
202243
- }
202244
- };
202245
- await Promise.all(Array.from({ length: laneCount }, lane));
202246
- }
202247
- var DeviceRestoreRetryScheduler = class {
202248
- #logger;
202249
- #attempt;
202250
- #onPermanentFailure;
202251
- #delaysMs;
202252
- #concurrency;
202253
- #now;
202254
- #abort = new AbortController();
202255
- constructor(options) {
202256
- this.#logger = options.logger;
202257
- this.#attempt = options.attempt;
202258
- this.#onPermanentFailure = options.onPermanentFailure;
202259
- this.#delaysMs = options.delaysMs ?? DEVICE_RESTORE_RETRY_DELAYS_MS;
202260
- this.#concurrency = options.concurrency ?? 4;
202261
- this.#now = options.now ?? Date.now;
202262
- }
202263
- /** Stop retrying (shutdown). Pending entries are NOT marked
202264
- * permanently failed — the next boot restores them from disk. */
202265
- cancel() {
202266
- this.#abort.abort();
202267
- }
202268
- /**
202269
- * Run the bounded retry rounds. Resolves when every entry has either
202270
- * restored, been marked permanently failed, or the scheduler was
202271
- * cancelled. Never rejects.
202272
- */
202273
- async run(initialFailures) {
202274
- let pending = initialFailures.map((failure) => ({
202275
- saved: failure.saved,
202276
- lastError: failure.error,
202277
- attempts: 1
202278
- }));
202279
- for (let round = 0; round < this.#delaysMs.length; round += 1) {
202280
- if (pending.length === 0 || this.#abort.signal.aborted) break;
202281
- await sleep$1(this.#delaysMs[round] ?? 0, this.#abort.signal);
202282
- if (this.#abort.signal.aborted) break;
202283
- pending = await this.#runRound(pending, round);
202284
- }
202285
- if (this.#abort.signal.aborted) return [];
202286
- const terminal = pending.map((entry) => ({
202287
- deviceId: entry.saved.id,
202288
- stableId: entry.saved.stableId,
202289
- type: String(entry.saved.type),
202290
- attempts: entry.attempts,
202291
- lastError: entry.lastError,
202292
- failedAt: this.#now()
202293
- }));
202294
- for (const failure of terminal) this.#onPermanentFailure(failure);
202295
- return terminal;
202296
- }
202297
- /** One retry round: parents first (phase 0), then hub-adopted
202298
- * children (phase 1) — a child's attempt depends on its parent
202299
- * having landed, exactly like the initial two-pass restore. */
202300
- async #runRound(pending, round) {
202301
- const next = [];
202302
- const parents = pending.filter((entry) => entry.saved.parentDeviceId === null);
202303
- const children = pending.filter((entry) => entry.saved.parentDeviceId !== null);
202304
- for (const phase of [parents, children]) await runWithConcurrency(phase, this.#concurrency, async (entry) => {
202305
- if (this.#abort.signal.aborted) {
202306
- next.push(entry);
202307
- return;
202308
- }
202309
- const attemptNo = entry.attempts + 1;
202310
- try {
202311
- await this.#attempt(entry.saved);
202312
- this.#logger.info("Device restored on retry", {
202313
- tags: {
202314
- deviceId: entry.saved.id,
202315
- stableId: entry.saved.stableId
202316
- },
202317
- meta: { attempt: attemptNo }
202318
- });
202319
- } catch (err) {
202320
- const lastError = err instanceof Error ? err.message : String(err);
202321
- const remainingRetries = this.#delaysMs.length - (round + 1);
202322
- this.#logger.warn("Device restore retry failed", {
202323
- tags: {
202324
- deviceId: entry.saved.id,
202325
- stableId: entry.saved.stableId
202326
- },
202327
- meta: {
202328
- attempt: attemptNo,
202329
- remainingRetries,
202330
- error: lastError
202331
- }
202332
- });
202333
- next.push({
202334
- saved: entry.saved,
202335
- lastError,
202336
- attempts: attemptNo
202337
- });
202338
- }
202339
- });
202340
- return next;
202341
- }
202342
- };
202343
- /**
202344
202787
  * Convert an IDevice to the flat DeviceSummary shape expected by the
202345
202788
  * device-provider cap router. Shared across all providers.
202346
202789
  */
@@ -209584,6 +210027,13 @@ Object.freeze({
209584
210027
  access: "create",
209585
210028
  role: "admin"
209586
210029
  },
210030
+ "integrations.adoptInstanceRows": {
210031
+ capName: "integrations",
210032
+ capScope: "system",
210033
+ addonId: null,
210034
+ access: "create",
210035
+ role: "admin"
210036
+ },
209587
210037
  "integrations.delete": {
209588
210038
  capName: "integrations",
209589
210039
  capScope: "system",
@@ -209619,6 +210069,13 @@ Object.freeze({
209619
210069
  access: "view",
209620
210070
  role: "admin"
209621
210071
  },
210072
+ "integrations.listByAddon": {
210073
+ capName: "integrations",
210074
+ capScope: "system",
210075
+ addonId: null,
210076
+ access: "view",
210077
+ role: "admin"
210078
+ },
209622
210079
  "integrations.update": {
209623
210080
  capName: "integrations",
209624
210081
  capScope: "system",
@@ -230601,7 +231058,8 @@ var STALE_MS$1 = 3e4;
230601
231058
  var COOLDOWN_MS$2 = 15e3;
230602
231059
  var FloodlightAccessory = class extends BaseDevice {
230603
231060
  parent;
230604
- features = [DeviceFeature.MotionTrigger];
231061
+ /** Nothing reported: the kernel derives this device's features from its bound caps (#459). */
231062
+ features = [];
230605
231063
  /** Wall-clock ms of the last operator-driven setState/setBrightness
230606
231064
  * /setMotionTrigger. Read by the parent's align loop via the
230607
231065
  * `ReolinkAccessoryRef.isInCooldown` impl below. */
@@ -230966,6 +231424,7 @@ var pirAccessorySchema = reolinkAccessoryBaseSchema.extend({
230966
231424
  var COOLDOWN_MS$1 = 15e3;
230967
231425
  var PirAccessory = class extends BaseDevice {
230968
231426
  parent;
231427
+ /** Nothing reported: the kernel derives this device's features from its bound caps (#459). */
230969
231428
  features = [];
230970
231429
  lastSetAtMs = 0;
230971
231430
  /** Becomes `true` after the first successful `refreshFromFirmware`
@@ -231203,21 +231662,6 @@ var PirAccessory = class extends BaseDevice {
231203
231662
  }
231204
231663
  }
231205
231664
  };
231206
- //#endregion
231207
- //#region src/accessories/siren-play-duration.ts
231208
- /**
231209
- * The duration argument for `setSiren(channel, on, duration)`.
231210
- *
231211
- * The library's Baichuan path picks the "times" mode for ANY defined duration
231212
- * (`duration !== undefined`), so a 0 sent as "until switched off" asked the
231213
- * camera to play the alarm zero times: it acknowledged and stayed silent. Only
231214
- * a positive count is a duration; everything else is the manual mode, where
231215
- * `on` alone starts and stops the siren.
231216
- */
231217
- function sirenPlayDuration(on, configuredTimes) {
231218
- if (!on) return void 0;
231219
- return configuredTimes !== void 0 && configuredTimes > 0 ? configuredTimes : void 0;
231220
- }
231221
231665
  function secondsForPlays(plays, secondsPerPlay) {
231222
231666
  return plays * secondsPerPlay;
231223
231667
  }
@@ -231251,6 +231695,21 @@ function buildReolinkSirenOptions(input) {
231251
231695
  };
231252
231696
  }
231253
231697
  //#endregion
231698
+ //#region src/accessories/siren-play-duration.ts
231699
+ /**
231700
+ * The duration argument for `setSiren(channel, on, duration)`.
231701
+ *
231702
+ * The library's Baichuan path picks the "times" mode for ANY defined duration
231703
+ * (`duration !== undefined`), so a 0 sent as "until switched off" asked the
231704
+ * camera to play the alarm zero times: it acknowledged and stayed silent. Only
231705
+ * a positive count is a duration; everything else is the manual mode, where
231706
+ * `on` alone starts and stops the siren.
231707
+ */
231708
+ function sirenPlayDuration(on, configuredTimes) {
231709
+ if (!on) return void 0;
231710
+ return configuredTimes !== void 0 && configuredTimes > 0 ? configuredTimes : void 0;
231711
+ }
231712
+ //#endregion
231254
231713
  //#region src/accessories/siren.ts
231255
231714
  /** Detection-class combinations the Reolink firmware accepts for the
231256
231715
  * siren-on-motion `typeScheduleList`. Mirrors `motion-floodlight`
@@ -231304,7 +231763,8 @@ var STALE_MS = 3e4;
231304
231763
  var COOLDOWN_MS = 15e3;
231305
231764
  var SirenAccessory = class extends BaseDevice {
231306
231765
  parent;
231307
- features = [DeviceFeature.MotionTrigger];
231766
+ /** Nothing reported: the kernel derives this device's features from its bound caps (#459). */
231767
+ features = [];
231308
231768
  lastSetAtMs = 0;
231309
231769
  /** Clears the `siren` slice when a timed activation runs out. */
231310
231770
  sirenTimer = null;