@camstack/server 1.2.910 → 1.2.912

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 (100) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/dist/agent/main.js +21 -8
  3. package/dist/api/core/cap-providers.js +81 -78
  4. package/dist/api/trpc/generated-cap-routers.js +20 -0
  5. package/dist/core/addon/addon-registry.service.js +25 -1
  6. package/dist/core/addon/instance-lifecycle.js +106 -33
  7. package/package.json +12 -12
  8. package/system/dist/addon-runner.js +229 -21
  9. package/system/dist/addon-runner.mjs +230 -22
  10. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.js +1 -1
  11. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.mjs +1 -1
  12. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.js +1 -1
  13. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.mjs +1 -1
  14. package/system/dist/builtins/alerts/alerts.addon.js +1 -1
  15. package/system/dist/builtins/alerts/alerts.addon.mjs +1 -1
  16. package/system/dist/builtins/autotrack/index.js +1 -1
  17. package/system/dist/builtins/autotrack/index.mjs +1 -1
  18. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.js +2 -2
  19. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.mjs +2 -2
  20. package/system/dist/builtins/calendars/calendars.addon.js +1 -1
  21. package/system/dist/builtins/calendars/calendars.addon.mjs +1 -1
  22. package/system/dist/builtins/camera-grid/index.js +1 -1
  23. package/system/dist/builtins/camera-grid/index.mjs +1 -1
  24. package/system/dist/builtins/composer/composer.addon.js +4 -4
  25. package/system/dist/builtins/composer/composer.addon.mjs +4 -4
  26. package/system/dist/builtins/console-logging/index.js +1 -1
  27. package/system/dist/builtins/console-logging/index.mjs +1 -1
  28. package/system/dist/builtins/core-blocks/core-blocks.addon.js +4 -4
  29. package/system/dist/builtins/core-blocks/core-blocks.addon.mjs +4 -4
  30. package/system/dist/builtins/device-history/device-history.addon.js +2 -2
  31. package/system/dist/builtins/device-history/device-history.addon.mjs +2 -2
  32. package/system/dist/builtins/device-manager/device-manager.addon.js +2 -2
  33. package/system/dist/builtins/device-manager/device-manager.addon.mjs +2 -2
  34. package/system/dist/builtins/hub-forwarder/index.js +1 -1
  35. package/system/dist/builtins/hub-forwarder/index.mjs +1 -1
  36. package/system/dist/builtins/keychain/index.js +4 -4
  37. package/system/dist/builtins/keychain/index.mjs +4 -4
  38. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.js +1 -1
  39. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.mjs +1 -1
  40. package/system/dist/builtins/local-auth/local-auth.addon.js +2 -2
  41. package/system/dist/builtins/local-auth/local-auth.addon.mjs +2 -2
  42. package/system/dist/builtins/local-network/local-network.addon.js +3 -3
  43. package/system/dist/builtins/local-network/local-network.addon.mjs +3 -3
  44. package/system/dist/builtins/loki-logging/index.js +15 -9
  45. package/system/dist/builtins/loki-logging/index.mjs +15 -9
  46. package/system/dist/builtins/loki-logging/loki-logging.addon.d.ts +6 -0
  47. package/system/dist/builtins/native-metrics/native-metrics.addon.js +1 -1
  48. package/system/dist/builtins/native-metrics/native-metrics.addon.mjs +1 -1
  49. package/system/dist/builtins/platform-probe/index.js +1 -1
  50. package/system/dist/builtins/platform-probe/index.mjs +1 -1
  51. package/system/dist/builtins/record-entries/index.js +1 -1
  52. package/system/dist/builtins/record-entries/index.mjs +1 -1
  53. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.js +1 -1
  54. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.mjs +1 -1
  55. package/system/dist/builtins/snapshot/index.js +1 -1
  56. package/system/dist/builtins/snapshot/index.mjs +1 -1
  57. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.js +1 -1
  58. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.mjs +1 -1
  59. package/system/dist/builtins/sqlite-storage/index.js +1 -1
  60. package/system/dist/builtins/sqlite-storage/index.mjs +1 -1
  61. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.js +3 -3
  62. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.mjs +3 -3
  63. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.js +1 -1
  64. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.mjs +1 -1
  65. package/system/dist/builtins/system-config/system-config.addon.js +3 -3
  66. package/system/dist/builtins/system-config/system-config.addon.mjs +284 -284
  67. package/system/dist/builtins/winston-logging/index.js +1 -1
  68. package/system/dist/builtins/winston-logging/index.mjs +1 -1
  69. package/system/dist/{capture-engine-B7DJgM95.js → capture-engine-CRXUcNzg.js} +1 -1
  70. package/system/dist/{capture-engine-DTx0c7kf.mjs → capture-engine-erwNulcY.mjs} +1 -1
  71. package/system/dist/{composition-sources-DRZuLQaM.js → composition-sources-CmJRQLAB.js} +1 -1
  72. package/system/dist/{composition-sources-CY6MmRpR.mjs → composition-sources-DrQFzsQU.mjs} +1 -1
  73. package/system/dist/{constants-BIYn2uH-.js → constants-BuRweEmb.js} +1 -1
  74. package/system/dist/{constants-DKNphWBk.mjs → constants-D9ZICjoN.mjs} +1 -1
  75. package/system/dist/{device-ca-N9oMCP1h.js → device-ca-DGwzbKB7.js} +1 -1
  76. package/system/dist/{device-ca-CoeuG8vp.mjs → device-ca-XXMVM6Lu.mjs} +1 -1
  77. package/system/dist/{dist-xH7EdlAg.js → dist-CZx3IYRz.js} +487 -39
  78. package/system/dist/{dist-CUt0SVMu.mjs → dist-DUYpvNfO.mjs} +486 -38
  79. package/system/dist/file-host-worker.js +1 -1
  80. package/system/dist/file-host-worker.mjs +1 -1
  81. package/system/dist/{hub-identity-BPRu1Pr9.mjs → hub-identity-Dc-SOwBk.mjs} +1 -1
  82. package/system/dist/{hub-identity-As9K7AG1.js → hub-identity-vVRXZi0z.js} +1 -1
  83. package/system/dist/{hub-mdns-ciao-D4CeSt_C.mjs → hub-mdns-ciao-DpRGDUEE.mjs} +2 -2
  84. package/system/dist/{hub-mdns-ciao-jaGozuwj.js → hub-mdns-ciao-uCdDDwE4.js} +2 -2
  85. package/system/dist/index.d.ts +1 -0
  86. package/system/dist/index.js +228 -28
  87. package/system/dist/index.mjs +229 -30
  88. package/system/dist/kernel/moleculer/accessory-spawn-retry.d.ts +67 -0
  89. package/system/dist/kernel/moleculer/device-cap-proxy.d.ts +2 -0
  90. package/system/dist/kernel/moleculer/hub-connect-switches.d.ts +23 -0
  91. package/system/dist/kernel/transport/acting-addon.d.ts +5 -1
  92. package/system/dist/{legacy-integration-rows-door-Gk42wKsu.js → legacy-integration-rows-door-CtObsXaU.js} +1 -1
  93. package/system/dist/{legacy-integration-rows-door-DAAF9Orf.mjs → legacy-integration-rows-door-DvbF3IY8.mjs} +1 -1
  94. package/system/dist/{rename-composition-block-CWJ_zyT_.mjs → rename-composition-block-CowZDV1m.mjs} +1 -1
  95. package/system/dist/{rename-composition-block-PFCvxuaj.js → rename-composition-block-rKmnICiK.js} +1 -1
  96. package/system/dist/{restore-archive-r_vUDU7Z.js → restore-archive-BvvAR6Ww.js} +1 -1
  97. package/system/dist/{restore-archive-BABm0OtJ.mjs → restore-archive-gLbz6iuS.mjs} +82 -82
  98. package/system/dist/{wal-maintenance-DugOl9LZ.mjs → wal-maintenance-B0uiPZUs.mjs} +0 -0
  99. package/system/dist/{wal-maintenance-hrjEiyFX.js → wal-maintenance-CB9zUxb-.js} +0 -0
  100. package/system/package.json +1 -1
@@ -1315,7 +1315,7 @@ var DeviceRole = /* @__PURE__ */ function(DeviceRole) {
1315
1315
  */
1316
1316
  var COMPOSED_DEVICE_STABLE_ID_PREFIX = "composed-";
1317
1317
  //#endregion
1318
- //#region ../types/dist/runtime-capabilities-B36VcCR6.mjs
1318
+ //#region ../types/dist/runtime-capabilities-ql3VRzQu.mjs
1319
1319
  /**
1320
1320
  * The audio chunk plane's byte format, and the ONE expansion from a coded
1321
1321
  * window to float samples (D455).
@@ -1410,6 +1410,97 @@ var AddonMigrationsBlockedError = class extends Error {
1410
1410
  this.migrationIds = migrationIds;
1411
1411
  }
1412
1412
  };
1413
+ var SWITCHES = /* @__PURE__ */ new Map();
1414
+ /** The ids the registry is known to hold a row for (hydrated, or told by the hub). */
1415
+ var ROWS = /* @__PURE__ */ new Set();
1416
+ /** The owner addon of an id, learned from its rows and from the helper that serves it. */
1417
+ var OWNER_OF = /* @__PURE__ */ new Map();
1418
+ /** The addons whose registry read answered at least once. */
1419
+ var ANSWERED = /* @__PURE__ */ new Set();
1420
+ /** The addons whose boot has begun reading the registry: only they can be held back. */
1421
+ var HYDRATING = /* @__PURE__ */ new Set();
1422
+ /**
1423
+ * The addons that serve an instance kind and have not been answered by the registry yet. Scoped
1424
+ * per owner: one addon's failed read never turns off another addon's instances, and an addon that
1425
+ * serves no instance kind never enters it.
1426
+ */
1427
+ var PENDING = /* @__PURE__ */ new Set();
1428
+ /**
1429
+ * An addon's boot is about to read the registry for its rows. From now on, until the registry
1430
+ * answers, its served instance kinds (already built or built later in its boot) fail closed. A
1431
+ * helper used with no addon boot around it (a spec, a tool) is never held back.
1432
+ */
1433
+ function beginHydration(ownerId) {
1434
+ if (ANSWERED.has(ownerId)) return;
1435
+ HYDRATING.add(ownerId);
1436
+ if (KINDS.has(ownerId)) PENDING.add(ownerId);
1437
+ }
1438
+ /** The helper of `ownerId` serves `id`: its fail-closed window is that owner's, not the process's. */
1439
+ function claimInstance(ownerId, id) {
1440
+ OWNER_OF.set(id, ownerId);
1441
+ }
1442
+ /** Whether `ownerId` still waits for the registry to answer (it serves a kind and has no rows yet). */
1443
+ function isHydrationPending(ownerId) {
1444
+ return PENDING.has(ownerId);
1445
+ }
1446
+ /**
1447
+ * The switch of `id` as this process knows it. An id nobody stated reads off while ITS owner waits
1448
+ * for the registry, on afterwards (a fresh instance). An id with no known owner reads off while any
1449
+ * owner waits.
1450
+ */
1451
+ function isInstanceOn(id) {
1452
+ const stated = SWITCHES.get(id);
1453
+ if (stated !== void 0) return stated;
1454
+ const owner = OWNER_OF.get(id);
1455
+ return owner === void 0 ? PENDING.size === 0 : !PENDING.has(owner);
1456
+ }
1457
+ /** Record what the hub told: the registry holds a row of `id` in this state. */
1458
+ function recordRegistrySwitch(id, enabled) {
1459
+ SWITCHES.set(id, enabled);
1460
+ ROWS.add(id);
1461
+ }
1462
+ /** Whether the registry is known to hold a row for `id`. */
1463
+ function hasRegistryRow(id) {
1464
+ return ROWS.has(id);
1465
+ }
1466
+ /** The state this process holds for `id`, or undefined when it holds none. */
1467
+ function statedInstanceSwitch(id) {
1468
+ return SWITCHES.get(id);
1469
+ }
1470
+ /** Forget `id` (the instance was deleted). */
1471
+ function forgetInstanceSwitch(id) {
1472
+ SWITCHES.delete(id);
1473
+ ROWS.delete(id);
1474
+ OWNER_OF.delete(id);
1475
+ }
1476
+ /** Seed the store from the registry rows of `ownerId`; the registry answered, so the owner is known. */
1477
+ function hydrateInstanceSwitches(ownerId, rows) {
1478
+ ANSWERED.add(ownerId);
1479
+ for (const row of rows) {
1480
+ recordRegistrySwitch(row.id, row.enabled);
1481
+ OWNER_OF.set(row.id, ownerId);
1482
+ }
1483
+ }
1484
+ /** The addon's boot has built every instance kind and read the registry: unknown ids now read on. */
1485
+ function settleHydration(ownerId) {
1486
+ PENDING.delete(ownerId);
1487
+ }
1488
+ var KINDS = /* @__PURE__ */ new Map();
1489
+ /**
1490
+ * A helper announces the kind it serves, by owner addon. The one-time body-to-registry move
1491
+ * (D1066) walks exactly these kinds, so an addon needs no list of its own: a record kind IS an
1492
+ * instance kind precisely when a helper wraps it.
1493
+ */
1494
+ function registerServedInstanceKind(ownerId, served) {
1495
+ const owned = KINDS.get(ownerId) ?? /* @__PURE__ */ new Map();
1496
+ owned.set(served.kind.name, served);
1497
+ KINDS.set(ownerId, owned);
1498
+ if (HYDRATING.has(ownerId) && !ANSWERED.has(ownerId)) PENDING.add(ownerId);
1499
+ }
1500
+ /** The instance kinds announced for `ownerId` so far. */
1501
+ function servedInstanceKindsOf(ownerId) {
1502
+ return [...KINDS.get(ownerId)?.values() ?? []];
1503
+ }
1413
1504
  /**
1414
1505
  * The value a redacted secret is replaced with on every read surface.
1415
1506
  *
@@ -2154,6 +2245,32 @@ function switchRecordsOverMigrationApi(api) {
2154
2245
  };
2155
2246
  } };
2156
2247
  }
2248
+ /** The record calls the body-to-registry switch migration makes, over the migration API. */
2249
+ function bodySwitchRecordsOverMigrationApi(api) {
2250
+ return { kind: (definition) => {
2251
+ const handle = api.records.kind(definition);
2252
+ return {
2253
+ query: async () => {
2254
+ const rows = [];
2255
+ let cursor;
2256
+ do {
2257
+ const page = await handle.query({
2258
+ limit: 500,
2259
+ ...cursor === void 0 ? {} : { cursor }
2260
+ });
2261
+ rows.push(...page.records);
2262
+ cursor = page.nextCursor ?? void 0;
2263
+ } while (cursor !== void 0);
2264
+ return { records: rows };
2265
+ },
2266
+ get: (id) => handle.get({ id }),
2267
+ put: (input, opts) => handle.put({
2268
+ ...input,
2269
+ ...opts?.ifRev === void 0 ? {} : { ifRev: opts.ifRev }
2270
+ })
2271
+ };
2272
+ } };
2273
+ }
2157
2274
  function integrationRowsApiOver(api) {
2158
2275
  return {
2159
2276
  list: async () => (await api.integrations.list({})).integrations,
@@ -2674,13 +2791,9 @@ function secretViewsOf(owner, kind, id, decl, data) {
2674
2791
  /** The most instances one addon lists (an integrations page, not a table). */
2675
2792
  var INSTANCES_LIST_MAX = 1e3;
2676
2793
  /**
2677
- * The ONE reader of an instance's switch (D996): an absent field means on, so a row written
2678
- * before the field existed needs no migration. Every consumer of an instance body asks this.
2794
+ * The body key the switch USED to live under (D1007, D1015). Nothing writes or reads it any more;
2795
+ * the migrations that move it between the body and the registry name it.
2679
2796
  */
2680
- function isInstanceEnabled(body) {
2681
- return body.enabled !== false;
2682
- }
2683
- /** The body key of the switch; only {@link RecordIntegrationInstances.setInstanceEnabled} writes it. */
2684
2797
  var SWITCH_KEY = "enabled";
2685
2798
  /**
2686
2799
  * The "Add device" mode an instance gets when its provider states none, from how the provider's
@@ -2722,6 +2835,20 @@ var RecordIntegrationInstances = class {
2722
2835
  secretKeys;
2723
2836
  secretMaps;
2724
2837
  nameField;
2838
+ /** The state each instance had when the addon last read it or was told it: {@link reapply} announces only a change. */
2839
+ knownSwitches = /* @__PURE__ */ new Map();
2840
+ /** What the addon reads for `id`: the switch as this process holds it, remembered as known. */
2841
+ knownSwitchOf(id) {
2842
+ claimInstance(this.records.owner, id);
2843
+ const enabled = isInstanceOn(id);
2844
+ this.knownSwitches.set(id, enabled);
2845
+ return enabled;
2846
+ }
2847
+ /** What a view of `id` shows; the addon did not read it, so nothing is remembered as known. */
2848
+ viewSwitchOf(id) {
2849
+ claimInstance(this.records.owner, id);
2850
+ return isInstanceOn(id);
2851
+ }
2725
2852
  switchListeners = /* @__PURE__ */ new Set();
2726
2853
  constructor(records, kind, hooks) {
2727
2854
  this.records = records;
@@ -2731,6 +2858,11 @@ var RecordIntegrationInstances = class {
2731
2858
  this.secretKeys = topLevelSecretKeys(kind.declaration.secretPaths);
2732
2859
  this.secretMaps = secretMapKeys(kind.declaration.secretPaths);
2733
2860
  this.nameField = kind.declaration.entry?.nameField ?? "name";
2861
+ registerServedInstanceKind(records.owner, {
2862
+ kind,
2863
+ reapply: () => this.reapply(),
2864
+ unrowed: () => this.unrowed()
2865
+ });
2734
2866
  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`);
2735
2867
  }
2736
2868
  /**
@@ -2744,7 +2876,7 @@ var RecordIntegrationInstances = class {
2744
2876
  return record === null ? null : {
2745
2877
  id,
2746
2878
  body: record.data,
2747
- enabled: isInstanceEnabled(record.data),
2879
+ enabled: this.knownSwitchOf(id),
2748
2880
  secrets: "resolved"
2749
2881
  };
2750
2882
  } catch (err) {
@@ -2754,7 +2886,7 @@ var RecordIntegrationInstances = class {
2754
2886
  return {
2755
2887
  id,
2756
2888
  body: Object.fromEntries(Object.entries(stored.data).filter(([key]) => !this.secretKeys.has(key))),
2757
- enabled: isInstanceEnabled(stored.data),
2889
+ enabled: this.knownSwitchOf(id),
2758
2890
  secrets: "unavailable"
2759
2891
  };
2760
2892
  }
@@ -2793,7 +2925,7 @@ var RecordIntegrationInstances = class {
2793
2925
  id: record.id,
2794
2926
  name: typeof rawName === "string" ? rawName : record.id,
2795
2927
  configured: this.hooks.configured(record.data),
2796
- enabled: isInstanceEnabled(record.data),
2928
+ enabled: this.viewSwitchOf(record.id),
2797
2929
  formValues: shown,
2798
2930
  kind,
2799
2931
  addDevice: this.hooks.addDevice?.(record.data) ?? defaultAddDeviceMode(this.hooks.description),
@@ -2849,6 +2981,8 @@ var RecordIntegrationInstances = class {
2849
2981
  id: minted,
2850
2982
  data: initial
2851
2983
  }, { ifRev: 0 });
2984
+ claimInstance(this.records.owner, minted);
2985
+ recordRegistrySwitch(minted, true);
2852
2986
  if (Object.keys(patch).length > 0) await this.handle.patch(minted, patch);
2853
2987
  await this.hooks.onChanged?.(minted, "created");
2854
2988
  return { id: minted };
@@ -2894,23 +3028,53 @@ var RecordIntegrationInstances = class {
2894
3028
  this.switchListeners.add(listener);
2895
3029
  }
2896
3030
  /**
2897
- * The ONE writer of the switch (D996, D1014): the record body's `enabled`, for every role. A
2898
- * configured thing is an instance, so an id with no record yet (a default integration that was
2899
- * never configured) gets its record from `initialBody` before the switch is written.
3031
+ * The hub's notification that the registry row of `id` moved (D1066). The registry holds the
3032
+ * switch; this keeps NO copy of it in the record. It remembers the state for this process's
3033
+ * readers ({@link isInstanceOn}), lets the addon re-apply, and fires the listeners.
2900
3034
  */
2901
3035
  setInstanceEnabled = async ({ id, enabled }) => {
2902
- if (await this.handle.get(id) === null) await this.handle.put({
2903
- id,
2904
- data: this.hooks.initialBody(id)
2905
- }, { ifRev: 0 });
2906
- await this.handle.patch(id, { [SWITCH_KEY]: enabled });
3036
+ claimInstance(this.records.owner, id);
3037
+ recordRegistrySwitch(id, enabled);
3038
+ this.knownSwitches.set(id, enabled);
2907
3039
  await this.hooks.onChanged?.(id, "enabled");
2908
3040
  for (const listener of this.switchListeners) await listener(id, enabled);
2909
3041
  return { ok: true };
2910
3042
  };
3043
+ /**
3044
+ * After the registry answered for a kind built before it could: announce the state of every
3045
+ * instance of this kind, on and off, so an addon that started on the fail-closed default (off)
3046
+ * starts what is on and stops what is off.
3047
+ */
3048
+ async reapply() {
3049
+ const page = await this.handle.query({ limit: INSTANCES_LIST_MAX });
3050
+ for (const record of page.records) {
3051
+ claimInstance(this.records.owner, record.id);
3052
+ const enabled = isInstanceOn(record.id);
3053
+ if (this.knownSwitches.get(record.id) === enabled) continue;
3054
+ this.knownSwitches.set(record.id, enabled);
3055
+ await this.hooks.onChanged?.(record.id, "enabled");
3056
+ for (const listener of this.switchListeners) await listener(record.id, enabled);
3057
+ }
3058
+ }
3059
+ /**
3060
+ * The records of this kind the registry holds no row for: created outside the hub door (a
3061
+ * seed, a migration, a store write). Each carries the state this process holds for it, on when
3062
+ * it holds none, because on was its effective state before the registry owned the switch.
3063
+ */
3064
+ async unrowed() {
3065
+ return (await this.handle.query({ limit: INSTANCES_LIST_MAX })).records.filter((record) => !hasRegistryRow(record.id)).map((record) => {
3066
+ const name = record.data[this.nameField];
3067
+ return {
3068
+ id: record.id,
3069
+ name: typeof name === "string" ? name : record.id,
3070
+ enabled: statedInstanceSwitch(record.id) ?? true
3071
+ };
3072
+ });
3073
+ }
2911
3074
  /** The row and its keychain refs go together (the records door). */
2912
3075
  deleteInstance = async ({ id }) => {
2913
3076
  await this.handle.delete(id);
3077
+ forgetInstanceSwitch(id);
2914
3078
  await this.hooks.onChanged?.(id, "deleted");
2915
3079
  return { ok: true };
2916
3080
  };
@@ -3045,6 +3209,107 @@ function registrySwitchPortsOver(deps) {
3045
3209
  };
3046
3210
  }
3047
3211
  /**
3212
+ * The switch comes back to the registry (D1066), the reverse of {@link registrySwitchToBodyMigration}.
3213
+ * An instance's on/off state lived in its record body (`enabled`, D1007 superseded by D1015); the hub
3214
+ * registry row, keyed by (addon, integration id) like a device, is now the only stored switch.
3215
+ *
3216
+ * For every record of the addon's kind:
3217
+ * - the state is the body's `enabled` (absent means on). When the registry row of that id disagrees,
3218
+ * the BODY wins: it was the only live copy while the body held the switch, and the registry
3219
+ * column of a migrated row was never read;
3220
+ * - a record with no registry row gets one (a services instance, under its addon-minted id);
3221
+ * - the key is then removed from the body, so no second copy remains.
3222
+ * A rerun finds no body that states `enabled` and writes nothing. The registry write goes first, so
3223
+ * a crash between the two steps repeats the pair (idempotent) and never loses a switched-off state.
3224
+ *
3225
+ * It runs in the addon process, after {@link registrySwitchToBodyMigration}, BEFORE the addon
3226
+ * registers its provider.
3227
+ */
3228
+ function bodySwitchToRegistryId(addonId, date, kindName) {
3229
+ return `${addonId}/${date}-body-switch-to-registry-${kindName}`;
3230
+ }
3231
+ async function moveBodySwitchToRegistry(ports, spec) {
3232
+ const records = await ports.listRecords();
3233
+ const adopted = records.length === 0 ? {
3234
+ created: 0,
3235
+ updated: 0,
3236
+ conflicts: []
3237
+ } : await ports.adoptRows(spec.addonId, records.map((r) => ({
3238
+ id: r.id,
3239
+ name: r.name,
3240
+ enabled: r.enabled,
3241
+ stated: r.stated
3242
+ })));
3243
+ const foreign = new Map(adopted.conflicts.map((c) => [c.id, c.ownerAddonId]));
3244
+ for (const [id, owner] of foreign) await ports.warn(`body switch kept: the registry row "${id}" belongs to addon "${owner}", not "${spec.addonId}"`);
3245
+ const stated = records.filter((r) => r.stated && !foreign.has(r.id));
3246
+ for (const row of stated) await ports.stripSwitch(row.id);
3247
+ const summary = {
3248
+ records: records.length,
3249
+ stripped: stated.length,
3250
+ rowsCreated: adopted.created,
3251
+ rowsCorrected: adopted.updated,
3252
+ conflicts: adopted.conflicts.length
3253
+ };
3254
+ return stated.length === 0 && adopted.created === 0 && adopted.updated === 0 ? {
3255
+ outcome: "already-done",
3256
+ summary
3257
+ } : {
3258
+ outcome: "done",
3259
+ summary
3260
+ };
3261
+ }
3262
+ /** A migration entry: an addon states its kind, nothing else. */
3263
+ function bodySwitchToRegistryMigration(spec) {
3264
+ return {
3265
+ meta: {
3266
+ id: bodySwitchToRegistryId(spec.addonId, spec.date, spec.kindName),
3267
+ owner: spec.addonId,
3268
+ level: "addon-state",
3269
+ seq: spec.seq,
3270
+ dependsOn: spec.followsDate === void 0 ? [] : [registrySwitchToBodyId(spec.addonId, spec.followsDate)],
3271
+ store: "settings",
3272
+ scope: "cluster",
3273
+ onFailure: "block-owner",
3274
+ bodyKind: "procedure",
3275
+ 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",
3276
+ fixtureMark: "enabled"
3277
+ },
3278
+ procedure: (ports) => moveBodySwitchToRegistry(ports, { addonId: spec.addonId })
3279
+ };
3280
+ }
3281
+ function bodySwitchPortsOver(deps) {
3282
+ const handle = deps.records.kind({
3283
+ name: deps.kind.name,
3284
+ declaration: deps.kind.declaration,
3285
+ schema: zod.z.record(zod.z.string(), zod.z.unknown())
3286
+ });
3287
+ return {
3288
+ listRecords: async () => {
3289
+ return (await handle.query({ limit: 1e3 })).records.map((r) => {
3290
+ const name = r.data[deps.nameField];
3291
+ return {
3292
+ id: r.id,
3293
+ name: typeof name === "string" ? name : r.id,
3294
+ enabled: r.data[SWITCH_KEY] !== false,
3295
+ stated: SWITCH_KEY in r.data
3296
+ };
3297
+ });
3298
+ },
3299
+ adoptRows: deps.adopt,
3300
+ warn: deps.warn,
3301
+ stripSwitch: async (id) => {
3302
+ const row = await handle.get(id);
3303
+ if (row === null || !("enabled" in row.data)) return;
3304
+ const { [SWITCH_KEY]: _dropped, ...rest } = row.data;
3305
+ await handle.put({
3306
+ id,
3307
+ data: rest
3308
+ }, { ifRev: row.rev });
3309
+ }
3310
+ };
3311
+ }
3312
+ /**
3048
3313
  * Build a {@link DurableState} over a single store key. Transport-agnostic:
3049
3314
  * `read`/`write` are the addon-store or device-store accessors. The whole
3050
3315
  * validated value round-trips on every read/write — the schema is the
@@ -3076,6 +3341,20 @@ function createDurableState(deps) {
3076
3341
  };
3077
3342
  }
3078
3343
  /**
3344
+ * The registry could not be read for the switches of an addon that serves instance kinds, so its
3345
+ * instances read off (D1066). A forked runner treats it as a failed boot: the supervisor respawns
3346
+ * it, bounded and marked terminally failed (D6), rather than leave instances off silently.
3347
+ */
3348
+ var INSTANCE_SWITCHES_UNREAD_ERROR_NAME = "InstanceSwitchesUnreadError";
3349
+ var InstanceSwitchesUnreadError = class extends Error {
3350
+ ownerId;
3351
+ constructor(ownerId) {
3352
+ super(`'${ownerId}': the registry did not answer for the instance switches; its instances stay off`);
3353
+ this.ownerId = ownerId;
3354
+ this.name = INSTANCE_SWITCHES_UNREAD_ERROR_NAME;
3355
+ }
3356
+ };
3357
+ /**
3079
3358
  * Per-node scoping for the shared addon-settings blob.
3080
3359
  *
3081
3360
  * An addon's settings store is hub-central (the `addon-settings` cap is
@@ -4083,7 +4362,14 @@ var BaseAddon = class {
4083
4362
  if (secrets !== void 0) this._secretChangeUnsub = secrets.onChange((ref) => {
4084
4363
  if (this._configSecretRefs.has(ref)) this.scheduleSecretReresolve(SECRET_CHANGE_DEBOUNCE_MS);
4085
4364
  });
4365
+ await this.hydrateSwitches();
4086
4366
  const result = await this.onInitialize();
4367
+ await this.moveLateInstanceKinds();
4368
+ await this.adoptUnrowed();
4369
+ if (this.switchesHydrated) {
4370
+ settleHydration(this.ctx.id);
4371
+ for (const served of servedInstanceKindsOf(this.ctx.id)) await served.reapply();
4372
+ }
4087
4373
  this.emitLifecycle(EventCategory.AddonStarted);
4088
4374
  const normalized = normalizeAddonInitResult(result);
4089
4375
  const providers = normalized && "providers" in normalized && normalized.providers ? normalized.providers : [];
@@ -4123,17 +4409,22 @@ var BaseAddon = class {
4123
4409
  this.retiredMigrationIds = ids;
4124
4410
  }
4125
4411
  registrySwitchSpec = null;
4412
+ /** The instance kinds whose switch move this process already ran (or tried), by record kind name. */
4413
+ switchMoved = /* @__PURE__ */ new Set();
4414
+ lastDeclared = [];
4126
4415
  registrySwitchBound() {
4127
- const spec = this.registrySwitchSpec;
4128
- if (spec === null) return [];
4129
4416
  const api = this.ctx.migrationApi;
4417
+ const spec = this.registrySwitchSpec;
4418
+ const kinds = servedInstanceKindsOf(this.ctx.id).filter((k) => !this.switchMoved.has(k.kind.name));
4419
+ if (spec === null && kinds.length === 0) return [];
4130
4420
  if (api === void 0) {
4131
4421
  this.ctx.logger.warn("the registry switch migration is skipped: the migration API is not available on this context");
4132
4422
  return [];
4133
4423
  }
4134
- return migrationSet([registrySwitchToBodyMigration({
4424
+ const date = "2026-11-06";
4425
+ const moveIn = spec === null ? [] : migrationSet([registrySwitchToBodyMigration({
4135
4426
  addonId: this.ctx.id,
4136
- date: "2026-11-06",
4427
+ date,
4137
4428
  seq: 1e3,
4138
4429
  initialBody: spec.initialBody
4139
4430
  })], (a) => registrySwitchPortsOver({
@@ -4141,13 +4432,53 @@ var BaseAddon = class {
4141
4432
  records: switchRecordsOverMigrationApi(a),
4142
4433
  kind: spec.kind
4143
4434
  })).bind(api);
4435
+ const moveBack = kinds.flatMap(({ kind }, index) => {
4436
+ this.switchMoved.add(kind.name);
4437
+ return migrationSet([bodySwitchToRegistryMigration({
4438
+ addonId: this.ctx.id,
4439
+ date: "2026-11-19",
4440
+ seq: 1001 + index,
4441
+ kindName: kind.name,
4442
+ ...spec === null ? {} : { followsDate: date }
4443
+ })], (a) => bodySwitchPortsOver({
4444
+ records: bodySwitchRecordsOverMigrationApi(a),
4445
+ kind,
4446
+ nameField: kind.declaration.entry?.nameField ?? "name",
4447
+ adopt: (addonId, rows) => this.ctx.api.integrations.adoptInstanceRows.mutate({
4448
+ addonId,
4449
+ rows: [...rows]
4450
+ }),
4451
+ warn: async (message) => {
4452
+ await a.log.warn({ message });
4453
+ }
4454
+ })).bind(api);
4455
+ });
4456
+ return [...moveIn, ...moveBack];
4457
+ }
4458
+ /**
4459
+ * A helper built AFTER the addon's migrations ran has a kind that moved nothing yet. Run its
4460
+ * switch move now (the engine replaces an owner's catalogue on every declare, so the whole
4461
+ * declared set goes with it, phased to the late ids), read the registry again, and tell the
4462
+ * addon about every instance that is off so it stops what it started on the default.
4463
+ */
4464
+ async moveLateInstanceKinds() {
4465
+ const late = servedInstanceKindsOf(this.ctx.id).filter((k) => !this.switchMoved.has(k.kind.name));
4466
+ if (late.length === 0) return;
4467
+ try {
4468
+ const only = late.map((k) => bodySwitchToRegistryId(this.ctx.id, "2026-11-19", k.kind.name));
4469
+ await this.runBound(this.lastDeclared, { only });
4470
+ } catch (err) {
4471
+ if (err instanceof AddonMigrationsBlockedError) throw err;
4472
+ this.ctx.logger.error("the late instance switch move failed", { meta: { error: errMsg(err) } });
4473
+ }
4144
4474
  }
4145
4475
  async runBound(declared, options) {
4476
+ this.lastDeclared = declared;
4146
4477
  const added = this.registrySwitchBound();
4147
4478
  const migrations = [...declared, ...added];
4148
4479
  const widened = options?.only === void 0 || added.length === 0 ? options : {
4149
4480
  ...options,
4150
- only: [...options.only, ...added.map((m) => m.meta.id)]
4481
+ only: [...new Set([...options.only, ...added.map((m) => m.meta.id)])]
4151
4482
  };
4152
4483
  const phased = this.retiredMigrationIds.length === 0 ? widened ?? {} : {
4153
4484
  ...widened,
@@ -4160,9 +4491,87 @@ var BaseAddon = class {
4160
4491
  finishMigration: (input) => api.finishMigration.mutate(input)
4161
4492
  }, migrations, this.ctx.logger, phased);
4162
4493
  if (report.blockOwner.length > 0) throw new AddonMigrationsBlockedError(report.blockOwner);
4494
+ await this.hydrateSwitches();
4495
+ await this.adoptUnrowed();
4163
4496
  return report;
4164
4497
  }
4165
4498
  /**
4499
+ * Learn the on/off state of this addon's instances from the registry rows (D1066), at boot, after
4500
+ * a migration run, and again through {@link rehydrateSwitches}. It runs on the addon's own boot
4501
+ * path, never inside a method the hub calls into. A registry that cannot answer leaves the
4502
+ * instances of THIS addon reading off (fail closed, per owner) until a read answers.
4503
+ */
4504
+ switchesHydrated = false;
4505
+ async hydrateSwitches() {
4506
+ beginHydration(this.ctx.id);
4507
+ try {
4508
+ const rows = await this.ctx.api.integrations.listByAddon.query({ addonId: this.ctx.id });
4509
+ hydrateInstanceSwitches(this.ctx.id, rows);
4510
+ this.switchesHydrated = true;
4511
+ return true;
4512
+ } catch (err) {
4513
+ this.ctx.logger.warn("instance switches not read from the registry: instances stay off", { meta: { error: errMsg(err) } });
4514
+ return false;
4515
+ }
4516
+ }
4517
+ /**
4518
+ * Every record of a served kind the registry holds no row for (created outside the hub door:
4519
+ * a seed, a store write) is adopted with the state it effectively had, on unless this process
4520
+ * stated it off, so the hub can switch it. A failure is logged; the next hydration retries.
4521
+ */
4522
+ async adoptUnrowed() {
4523
+ if (!this.switchesHydrated) return;
4524
+ try {
4525
+ for (const served of servedInstanceKindsOf(this.ctx.id)) {
4526
+ const rows = await served.unrowed();
4527
+ if (rows.length === 0) continue;
4528
+ await this.ctx.api.integrations.adoptInstanceRows.mutate({
4529
+ addonId: this.ctx.id,
4530
+ rows: rows.map((r) => ({
4531
+ id: r.id,
4532
+ name: r.name,
4533
+ enabled: r.enabled,
4534
+ stated: false
4535
+ }))
4536
+ });
4537
+ for (const r of rows) recordRegistrySwitch(r.id, r.enabled);
4538
+ }
4539
+ } catch (err) {
4540
+ this.ctx.logger.warn("records without a registry row were not adopted", { meta: { error: errMsg(err) } });
4541
+ }
4542
+ }
4543
+ /**
4544
+ * Read the switches from the registry again and announce the states now known, so an addon that
4545
+ * started on the fail-closed default (off) starts what is on. Throws
4546
+ * {@link InstanceSwitchesUnreadError} when the registry still does not answer while this addon
4547
+ * serves instance kinds: a forked runner turns that into a failed boot (the supervisor respawns
4548
+ * it, bounded, D6), an agent or the hub reads again on the next hub connect (event-driven, D3).
4549
+ * An addon with no instance kind has nothing waiting and never throws.
4550
+ */
4551
+ async rehydrateSwitches() {
4552
+ if (this._ctx === null) return;
4553
+ if (await this.hydrateSwitches()) {
4554
+ await this.adoptUnrowed();
4555
+ settleHydration(this.ctx.id);
4556
+ for (const served of servedInstanceKindsOf(this.ctx.id)) await served.reapply();
4557
+ return;
4558
+ }
4559
+ if (isHydrationPending(this.ctx.id)) throw new InstanceSwitchesUnreadError(this.ctx.id);
4560
+ }
4561
+ /**
4562
+ * Called on the hub-reachable event (instead of `onHubReachable` directly): the switches are
4563
+ * read again, then `onHubReachable` runs. A registry that still does not answer is logged and
4564
+ * left for the next connect.
4565
+ */
4566
+ async hubReachable() {
4567
+ try {
4568
+ await this.rehydrateSwitches();
4569
+ } catch (err) {
4570
+ this.ctx.logger.warn("instance switches still unread at the hub connect", { meta: { error: errMsg(err) } });
4571
+ }
4572
+ await this.onHubReachable();
4573
+ }
4574
+ /**
4166
4575
  * Called by the isolated-process runner AFTER `broker.start()`.
4167
4576
  * In-process addons never need this because the hub broker is already
4168
4577
  * running when `initialize()` fires. For forked children the broker
@@ -81539,14 +81948,8 @@ var IntegrationWithStateSchema = zod.z.object({
81539
81948
  id: zod.z.string(),
81540
81949
  addonId: zod.z.string(),
81541
81950
  name: zod.z.string(),
81542
- /** A projection of the instance body's switch (`setInstanceEnabled` is the only writer). */
81951
+ /** THE switch of the instance: the hub registry row is its only stored copy (D1066). */
81543
81952
  enabled: zod.z.boolean(),
81544
- /**
81545
- * True when the addon that holds the switch did not answer (down, failed, or keeps no record for
81546
- * this row): `enabled` is then the stored registry flag, a stale value, not the state. A reader
81547
- * must not draw it as on or off (D315).
81548
- */
81549
- switchUnknown: zod.z.literal(true).optional(),
81550
81953
  info: zod.z.record(zod.z.string(), zod.z.unknown()).readonly(),
81551
81954
  /** The discovery candidate this integration was set up from (D984). */
81552
81955
  originStableId: zod.z.string().optional(),
@@ -81558,14 +81961,8 @@ var IntegrationLiteSchema = zod.z.object({
81558
81961
  id: zod.z.string(),
81559
81962
  addonId: zod.z.string(),
81560
81963
  name: zod.z.string(),
81561
- /** A projection of the instance body's switch (`setInstanceEnabled` is the only writer). */
81964
+ /** THE switch of the instance: the hub registry row is its only stored copy (D1066). */
81562
81965
  enabled: zod.z.boolean(),
81563
- /**
81564
- * True when the addon that holds the switch did not answer (down, failed, or keeps no record for
81565
- * this row): `enabled` is then the stored registry flag, a stale value, not the state. A reader
81566
- * must not draw it as on or off (D315).
81567
- */
81568
- switchUnknown: zod.z.literal(true).optional(),
81569
81966
  info: zod.z.record(zod.z.string(), zod.z.unknown()).readonly(),
81570
81967
  /** The discovery candidate this integration was set up from (D984). */
81571
81968
  originStableId: zod.z.string().optional(),
@@ -81688,7 +82085,44 @@ var integrationsCapability = {
81688
82085
  methods: {
81689
82086
  list: method(zod.z.void(), zod.z.array(IntegrationWithStateSchema)),
81690
82087
  get: method(zod.z.object({ id: zod.z.string() }), IntegrationWithStateSchema),
82088
+ /** The devices-role row of an addon; a services instance row never answers for its addon. */
81691
82089
  getByAddonId: method(zod.z.object({ addonId: zod.z.string() }), IntegrationLiteSchema.nullable()),
82090
+ /**
82091
+ * Every registry row of one addon, services instances included: the addon reads its own switches
82092
+ * with it at boot (D1066). A pure registry read; the Integrations list (`list`) hides the rows of
82093
+ * a services instance, this does not.
82094
+ */
82095
+ listByAddon: method(zod.z.object({ addonId: zod.z.string() }), zod.z.array(IntegrationLiteSchema)),
82096
+ /**
82097
+ * The one-time move of an addon's switches into the registry (D1066): for each instance record
82098
+ * the addon holds, an absent row is created as a services row under the addon-minted id, and a
82099
+ * row that disagrees with a STATED body switch is corrected (a body that states nothing never
82100
+ * moves an existing row). A row
82101
+ * that belongs to another addon is left alone and returned in `conflicts` (the caller keeps its
82102
+ * own copy of that state), and an addon naming another addon's id is refused FORBIDDEN.
82103
+ * Idempotent: a rerun changes nothing. It never notifies the addon.
82104
+ */
82105
+ adoptInstanceRows: method(zod.z.object({
82106
+ addonId: zod.z.string(),
82107
+ rows: zod.z.array(zod.z.object({
82108
+ id: zod.z.string().min(1),
82109
+ name: zod.z.string(),
82110
+ enabled: zod.z.boolean(),
82111
+ /** True when the record body STATED the switch: only then does it override an existing row. */
82112
+ stated: zod.z.boolean()
82113
+ }))
82114
+ }), zod.z.object({
82115
+ created: zod.z.number().int(),
82116
+ updated: zod.z.number().int(),
82117
+ /** Rows whose id belongs to ANOTHER addon: left untouched, so the caller keeps its own copy. */
82118
+ conflicts: zod.z.array(zod.z.object({
82119
+ id: zod.z.string(),
82120
+ ownerAddonId: zod.z.string()
82121
+ }))
82122
+ }), {
82123
+ kind: "mutation",
82124
+ auth: "admin"
82125
+ }),
81692
82126
  update: method(UpdateIntegrationInputSchema, IntegrationLiteSchema, {
81693
82127
  kind: "mutation",
81694
82128
  auth: "admin"
@@ -128125,6 +128559,13 @@ var METHOD_ACCESS_MAP = Object.freeze({
128125
128559
  access: "create",
128126
128560
  role: "admin"
128127
128561
  },
128562
+ "integrations.adoptInstanceRows": {
128563
+ capName: "integrations",
128564
+ capScope: "system",
128565
+ addonId: null,
128566
+ access: "create",
128567
+ role: "admin"
128568
+ },
128128
128569
  "integrations.delete": {
128129
128570
  capName: "integrations",
128130
128571
  capScope: "system",
@@ -128160,6 +128601,13 @@ var METHOD_ACCESS_MAP = Object.freeze({
128160
128601
  access: "view",
128161
128602
  role: "admin"
128162
128603
  },
128604
+ "integrations.listByAddon": {
128605
+ capName: "integrations",
128606
+ capScope: "system",
128607
+ addonId: null,
128608
+ access: "view",
128609
+ role: "admin"
128610
+ },
128163
128611
  "integrations.update": {
128164
128612
  capName: "integrations",
128165
128613
  capScope: "system",
@@ -143074,10 +143522,10 @@ Object.defineProperty(exports, "isHistoryHelper", {
143074
143522
  return isHistoryHelper;
143075
143523
  }
143076
143524
  });
143077
- Object.defineProperty(exports, "isInstanceEnabled", {
143525
+ Object.defineProperty(exports, "isInstanceOn", {
143078
143526
  enumerable: true,
143079
143527
  get: function() {
143080
- return isInstanceEnabled;
143528
+ return isInstanceOn;
143081
143529
  }
143082
143530
  });
143083
143531
  Object.defineProperty(exports, "isInternalActionId", {