@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
@@ -149,6 +149,25 @@ function refusalReportOf(addonId, err) {
149
149
  };
150
150
  }
151
151
  //#endregion
152
+ //#region src/kernel/moleculer/hub-connect-switches.ts
153
+ /**
154
+ * On a hub connect, every addon with instance kinds reads its switches from the registry again
155
+ * (D1066). Event-driven, no timer (D3): the next connect retries. A forked runner's FIRST connect
156
+ * is its boot, so a registry that still does not answer ends the process and the supervisor
157
+ * respawns it, bounded and marked terminally failed (D6), instead of leaving instances off.
158
+ */
159
+ async function rehydrateSwitchesOnHubConnect(entries, deps) {
160
+ for (const entry of entries) {
161
+ if (entry.addon.rehydrateSwitches === void 0) continue;
162
+ try {
163
+ await entry.addon.rehydrateSwitches();
164
+ } catch (err) {
165
+ if (deps.fatalOnUnread && (0, _camstack_types_addon.isInstanceSwitchesUnreadError)(err)) deps.exit(entry.addonId, err);
166
+ else deps.onUnread(entry.addonId, err);
167
+ }
168
+ }
169
+ }
170
+ //#endregion
152
171
  //#region src/kernel/addon-class-resolver.ts
153
172
  function isRecord$4(value) {
154
173
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -6109,6 +6128,156 @@ var AccessoryShrinkGate = class {
6109
6128
  }
6110
6129
  };
6111
6130
  //#endregion
6131
+ //#region src/kernel/moleculer/accessory-spawn-retry.ts
6132
+ /** A spawn failure that knows which step threw. */
6133
+ var AccessorySpawnStepError = class extends Error {
6134
+ step;
6135
+ /** The child's numeric id once allocated; null when allocation itself failed. */
6136
+ deviceId;
6137
+ constructor(step, deviceId, cause) {
6138
+ const reason = cause instanceof Error ? cause.message : String(cause);
6139
+ super(`${step}: ${reason}`, { cause });
6140
+ this.name = "AccessorySpawnStepError";
6141
+ this.step = step;
6142
+ this.deviceId = deviceId;
6143
+ }
6144
+ };
6145
+ function describeError(error) {
6146
+ if (error instanceof AccessorySpawnStepError) return {
6147
+ step: error.step,
6148
+ reason: error.message.slice(error.step.length + 2)
6149
+ };
6150
+ return {
6151
+ step: "unknown",
6152
+ reason: error instanceof Error ? error.message : String(error)
6153
+ };
6154
+ }
6155
+ var AccessorySpawnRetry = class AccessorySpawnRetry {
6156
+ #logger;
6157
+ #delaysMs;
6158
+ /** Pending spawns, by `<parent>:<child stableId>`. */
6159
+ #pending = /* @__PURE__ */ new Map();
6160
+ /** Gave up — sticks until the parent is registered again. */
6161
+ #gaveUp = /* @__PURE__ */ new Set();
6162
+ constructor(options) {
6163
+ this.#logger = options.logger;
6164
+ this.#delaysMs = options.delaysMs ?? _camstack_types_addon.DEVICE_RESTORE_RETRY_DELAYS_MS;
6165
+ }
6166
+ static #key(parentDeviceId, stableId) {
6167
+ return `${parentDeviceId}:${stableId}`;
6168
+ }
6169
+ /** The parent went away (teardown / shutdown): drop its pending rounds and its give-ups. */
6170
+ cancelParent(parentDeviceId) {
6171
+ for (const [key, entry] of this.#pending) {
6172
+ if (entry.parentDeviceId !== parentDeviceId) continue;
6173
+ entry.cancelled = true;
6174
+ if (entry.timer !== null) clearTimeout(entry.timer);
6175
+ this.#pending.delete(key);
6176
+ }
6177
+ this.#forgetGiveUps(parentDeviceId);
6178
+ }
6179
+ /** The parent registered again: a fresh chance for children that gave up. */
6180
+ resetParent(parentDeviceId) {
6181
+ this.#forgetGiveUps(parentDeviceId);
6182
+ }
6183
+ #forgetGiveUps(parentDeviceId) {
6184
+ const prefix = `${parentDeviceId}:`;
6185
+ for (const key of this.#gaveUp) if (key.startsWith(prefix)) this.#gaveUp.delete(key);
6186
+ }
6187
+ /** Record the initial failure and run the bounded rounds in the background. */
6188
+ schedule(request) {
6189
+ const key = AccessorySpawnRetry.#key(request.parentDeviceId, request.stableId);
6190
+ if (this.#pending.has(key)) return;
6191
+ if (this.#gaveUp.has(key)) {
6192
+ this.#logger.debug("Accessory child spawn skipped — gave up earlier, parent not re-registered", {
6193
+ tags: { parentDeviceId: request.parentDeviceId },
6194
+ meta: { stableId: request.stableId }
6195
+ });
6196
+ return;
6197
+ }
6198
+ const entry = {
6199
+ parentDeviceId: request.parentDeviceId,
6200
+ cancelled: false,
6201
+ timer: null
6202
+ };
6203
+ this.#pending.set(key, entry);
6204
+ this.#record(request, request.deviceId, request.error, 0, false);
6205
+ this.#run(key, entry, request);
6206
+ }
6207
+ #record(request, deviceId, error, retry, terminal) {
6208
+ const { step, reason } = describeError(error);
6209
+ this.#logger.error(terminal ? "Accessory child spawn gave up after the bounded retries" : "Accessory child spawn failed", {
6210
+ tags: {
6211
+ ...deviceId === null ? {} : { deviceId },
6212
+ parentDeviceId: request.parentDeviceId
6213
+ },
6214
+ meta: {
6215
+ stableId: request.stableId,
6216
+ step,
6217
+ error: reason,
6218
+ retry,
6219
+ max: this.#delaysMs.length
6220
+ }
6221
+ });
6222
+ }
6223
+ async #run(key, entry, request) {
6224
+ let lastError = request.error;
6225
+ let deviceId = request.deviceId;
6226
+ for (let round = 1; round <= this.#delaysMs.length; round += 1) {
6227
+ await this.#sleep(entry, this.#delaysMs[round - 1] ?? 0);
6228
+ if (entry.cancelled) return;
6229
+ if (!request.isParentRegistered()) {
6230
+ this.#pending.delete(key);
6231
+ this.#logger.info("Accessory child spawn retry skipped — parent no longer registered", {
6232
+ tags: {
6233
+ ...deviceId === null ? {} : { deviceId },
6234
+ parentDeviceId: request.parentDeviceId
6235
+ },
6236
+ meta: {
6237
+ stableId: request.stableId,
6238
+ retry: round
6239
+ }
6240
+ });
6241
+ return;
6242
+ }
6243
+ try {
6244
+ await request.attempt({ final: round === this.#delaysMs.length });
6245
+ if (entry.cancelled) return;
6246
+ this.#pending.delete(key);
6247
+ this.#logger.info("Accessory child spawned on retry", {
6248
+ tags: {
6249
+ ...deviceId === null ? {} : { deviceId },
6250
+ parentDeviceId: request.parentDeviceId
6251
+ },
6252
+ meta: {
6253
+ stableId: request.stableId,
6254
+ retry: round
6255
+ }
6256
+ });
6257
+ return;
6258
+ } catch (err) {
6259
+ if (entry.cancelled) return;
6260
+ lastError = err;
6261
+ if (err instanceof AccessorySpawnStepError && err.deviceId !== null) deviceId = err.deviceId;
6262
+ if (round < this.#delaysMs.length) this.#record(request, deviceId, err, round, false);
6263
+ }
6264
+ }
6265
+ this.#record(request, deviceId, lastError, this.#delaysMs.length, true);
6266
+ this.#pending.delete(key);
6267
+ this.#gaveUp.add(key);
6268
+ }
6269
+ #sleep(entry, ms) {
6270
+ return new Promise((resolve) => {
6271
+ const timer = setTimeout(() => {
6272
+ entry.timer = null;
6273
+ resolve();
6274
+ }, ms);
6275
+ timer.unref?.();
6276
+ entry.timer = timer;
6277
+ });
6278
+ }
6279
+ };
6280
+ //#endregion
6112
6281
  //#region src/kernel/moleculer/runtime-state-load.ts
6113
6282
  /** A device build refused because its runtime state could not be loaded. */
6114
6283
  var RuntimeStateLoadError = class extends Error {
@@ -6689,6 +6858,10 @@ function createBrokerDeviceManagerApi(opts) {
6689
6858
  const resolveParentIntegrationId = async (parentId) => {
6690
6859
  return (await callDeviceManager(api, "loadMeta", { deviceId: parentId }).catch(() => null))?.integrationId ?? void 0;
6691
6860
  };
6861
+ const accessorySpawnRetry = new AccessorySpawnRetry({
6862
+ logger: opts.logger,
6863
+ ...opts.accessorySpawnRetryDelaysMs !== void 0 ? { delaysMs: opts.accessorySpawnRetryDelaysMs } : {}
6864
+ });
6692
6865
  /**
6693
6866
  * Spawn one accessory child device declared by a parent's
6694
6867
  * `getAccessoryChildren()`. Mirrors the standard `create()` flow
@@ -6698,9 +6871,20 @@ function createBrokerDeviceManagerApi(opts) {
6698
6871
  * row already exists, `persistInitialConfig` is skipped (config
6699
6872
  * arg empty) and the child self-hydrates from `loadConfig`.
6700
6873
  */
6701
- const spawnAccessoryChild = async (parent, spec) => {
6874
+ const spawnAccessoryChild = async (parent, spec, spawnOptions = { final: false }) => {
6702
6875
  const childStableId = `${parent.stableId}-${spec.stableIdSuffix}`;
6703
- const id = await deviceApi.allocateDeviceId(childStableId);
6876
+ let allocatedId = null;
6877
+ try {
6878
+ return await spawnAccessoryChildSteps(parent, spec, childStableId, (id) => {
6879
+ allocatedId = id;
6880
+ }, spawnOptions);
6881
+ } catch (err) {
6882
+ throw err instanceof AccessorySpawnStepError ? err : new AccessorySpawnStepError("register", allocatedId, err);
6883
+ }
6884
+ };
6885
+ const spawnAccessoryChildSteps = async (parent, spec, childStableId, onAllocated, spawnOptions) => {
6886
+ const id = await deviceApi.allocateDeviceId(childStableId).catch((err) => Promise.reject(new AccessorySpawnStepError("allocateDeviceId", null, err)));
6887
+ onAllocated(id);
6704
6888
  const existing = registry.getById(id);
6705
6889
  if (existing && existing.stableId === childStableId) return existing;
6706
6890
  const empty = {};
@@ -6717,12 +6901,17 @@ function createBrokerDeviceManagerApi(opts) {
6717
6901
  ...spec.meta.type !== void 0 ? { type: spec.meta.type } : {},
6718
6902
  ...integrationId !== void 0 ? { integrationId } : {}
6719
6903
  }).catch((err) => {
6720
- opts.logger.warn("spawnAccessoryChild: applyInitialMeta pre-seed failed", {
6904
+ if (!spawnOptions.final) return Promise.reject(new AccessorySpawnStepError("applyInitialMeta", id, err));
6905
+ opts.logger.error("Accessory child spawned WITHOUT its meta pre-seed after the last retry", {
6721
6906
  tags: {
6722
- stableId: childStableId,
6723
- deviceId: id
6907
+ deviceId: id,
6908
+ parentDeviceId: parent.id
6724
6909
  },
6725
- meta: { error: err instanceof Error ? err.message : String(err) }
6910
+ meta: {
6911
+ step: "applyInitialMeta",
6912
+ stableId: childStableId,
6913
+ error: err instanceof Error ? err.message : String(err)
6914
+ }
6726
6915
  });
6727
6916
  });
6728
6917
  if (isFirstSpawn && Object.keys(spec.config).length > 0) await callDeviceManager(api, "persistConfig", {
@@ -6730,7 +6919,7 @@ function createBrokerDeviceManagerApi(opts) {
6730
6919
  data: spec.config
6731
6920
  }).catch(() => {});
6732
6921
  const [initialRuntimeState, loadedConfig, deviceMeta] = await Promise.all([
6733
- loadRuntimeStateFor(id, childStableId, "accessory-child"),
6922
+ loadRuntimeStateFor(id, childStableId, "accessory-child").catch((err) => Promise.reject(new AccessorySpawnStepError("loadRuntimeState", id, err))),
6734
6923
  callDeviceManager(api, "loadConfig", { deviceId: id }).catch(() => empty),
6735
6924
  callDeviceManager(api, "loadMeta", { deviceId: id }).catch(() => null)
6736
6925
  ]);
@@ -6769,6 +6958,7 @@ function createBrokerDeviceManagerApi(opts) {
6769
6958
  */
6770
6959
  const teardownLocal = async (deviceId, runLifecycle) => {
6771
6960
  const device = registry.getById(deviceId);
6961
+ accessorySpawnRetry.cancelParent(deviceId);
6772
6962
  cancelProbeRetry(deviceId);
6773
6963
  if (!device) return;
6774
6964
  const children = registry.getChildren(deviceId);
@@ -7013,6 +7203,7 @@ function createBrokerDeviceManagerApi(opts) {
7013
7203
  if (!opts.capabilityRegistry) workerNativeCaps.get("device-ops")?.delete(device.id);
7014
7204
  throw err;
7015
7205
  }
7206
+ accessorySpawnRetry.resetParent(device.id);
7016
7207
  const lifecycleHost = device;
7017
7208
  const shrinkGate = new AccessoryShrinkGate();
7018
7209
  const runReconcileNow = async () => {
@@ -7050,14 +7241,14 @@ function createBrokerDeviceManagerApi(opts) {
7050
7241
  try {
7051
7242
  await spawnAccessoryChild(device, spec);
7052
7243
  } catch (err) {
7053
- opts.logger.warn("Failed to spawn accessory child", {
7054
- tags: {
7055
- parentDeviceId: device.id,
7056
- parentStableId: device.stableId
7057
- },
7058
- meta: {
7059
- stableIdSuffix: spec.stableIdSuffix,
7060
- error: err instanceof Error ? err.message : String(err)
7244
+ accessorySpawnRetry.schedule({
7245
+ deviceId: err instanceof AccessorySpawnStepError ? err.deviceId : null,
7246
+ stableId: `${device.stableId}-${spec.stableIdSuffix}`,
7247
+ parentDeviceId: device.id,
7248
+ error: err,
7249
+ isParentRegistered: () => registry.getById(device.id) !== null,
7250
+ attempt: async (attemptOptions) => {
7251
+ await spawnAccessoryChild(device, spec, attemptOptions);
7061
7252
  }
7062
7253
  });
7063
7254
  }
@@ -12559,18 +12750,35 @@ async function main() {
12559
12750
  if (deviceRestorePromises.length > 0 && !shuttingDown) await Promise.allSettled(deviceRestorePromises);
12560
12751
  refreshChildCaps("post-init", customActionRegistry.describeAll(specs.map((spec) => spec.addonId)));
12561
12752
  let hubReachableFired = false;
12562
- const fireHubReachableOnce = () => {
12753
+ const rehydrateSwitches = (first) => rehydrateSwitchesOnHubConnect(loaded, {
12754
+ fatalOnUnread: first,
12755
+ onUnread: (addonId, err) => {
12756
+ runnerLog.error(`"${addonId}" instance switches not read from the registry`, { meta: { error: (0, _camstack_types_addon.errMsg)(err) } });
12757
+ },
12758
+ exit: (addonId, err) => {
12759
+ console.error(`[addon-runner] "${addonId}" cannot read its instance switches: ${(0, _camstack_types_addon.errMsg)(err)}`);
12760
+ process.exit(1);
12761
+ }
12762
+ });
12763
+ const fireHubReachableOnce = async () => {
12563
12764
  if (hubReachableFired) return;
12564
12765
  hubReachableFired = true;
12565
- for (const entry of loaded) if (typeof entry.addon.onHubReachable === "function") Promise.resolve(entry.addon.onHubReachable()).catch((err) => {
12566
- runnerLog.error(`"${entry.addonId}" onHubReachable() threw`, { meta: { error: (0, _camstack_types_addon.errMsg)(err) } });
12567
- });
12766
+ await rehydrateSwitches(true);
12767
+ for (const entry of loaded) {
12768
+ if (typeof entry.addon.onHubReachable !== "function") continue;
12769
+ Promise.resolve(entry.addon.onHubReachable()).catch((err) => {
12770
+ runnerLog.error(`"${entry.addonId}" onHubReachable() threw`, { meta: { error: (0, _camstack_types_addon.errMsg)(err) } });
12771
+ });
12772
+ }
12568
12773
  };
12569
12774
  udsChildClient.onConnected(() => {
12570
- if (hubReachableFired) refreshChildCaps("on reconnect");
12775
+ if (hubReachableFired) {
12776
+ refreshChildCaps("on reconnect");
12777
+ rehydrateSwitches(false);
12778
+ }
12571
12779
  fireHubReachableOnce();
12572
12780
  });
12573
- fireHubReachableOnce();
12781
+ await fireHubReachableOnce();
12574
12782
  runnerLog.info(`"${nodeId}" started — ${loaded.length} addon(s) ready (UDS connected)`);
12575
12783
  process.stdout.write(`READY:${nodeId}\n`);
12576
12784
  const stopHeapWatch = startRunnerHeapWatch({
@@ -1,5 +1,5 @@
1
1
  import { register } from "node:module";
2
- import { BOOT_RECOVERY_BACKOFF_MS, CALLER_STAMPED_CAPABILITIES, CAP_METHOD_NOT_IMPLEMENTED, CAP_METHOD_TIMEOUTS_MS, COLLECTION_ARRAY_METHODS, COMPOSED_DEVICE_STABLE_ID_PREFIX, DATAPLANE_SECRET_HEADER, DEVICE_CHILDREN_BATCH_MAX, DeviceType, DisposerChain, ErrorI18nPayloadSchema, EventCategory, MIGRATION_API_VERSION, PEER_BYTES_CHUNK_BYTES, PEER_BYTES_MAX_OUTSTANDING, PEER_BYTES_STALL_MS, PEER_BYTES_TICKET_TTL_MS, ReadinessRegistry, ReadinessTimeoutError, addonSliceHandleApi, asJsonObject, asString, collectZodSecretPaths, commandOrigin, createDebugEmitter, createDeviceProxy, createEventBusSliceSource, createRecordsAccess, createSecretsAccess, describeCustomActions, describeNvidia, deviceOpsCapability, emitReadiness, errMsg, expandCapMethods, findMigrationsBlocked, isCollectionArrayMethodName, isProviderOptionalMethodName, maskUrlCredentials, nodeIdOfScopedKey, normalizeAddonInitResult, readCommandOrigin, readErrorI18n, readNodePin, resolveDeviceSettings, resolveSecretViewsIn, scopeKey, scrubKnownSecrets, switchRefusesSetState, withCapInputDefaults } from "@camstack/types/addon";
2
+ import { BOOT_RECOVERY_BACKOFF_MS, CALLER_STAMPED_CAPABILITIES, CAP_METHOD_NOT_IMPLEMENTED, CAP_METHOD_TIMEOUTS_MS, COLLECTION_ARRAY_METHODS, COMPOSED_DEVICE_STABLE_ID_PREFIX, DATAPLANE_SECRET_HEADER, DEVICE_CHILDREN_BATCH_MAX, DEVICE_RESTORE_RETRY_DELAYS_MS, DeviceType, DisposerChain, ErrorI18nPayloadSchema, EventCategory, MIGRATION_API_VERSION, PEER_BYTES_CHUNK_BYTES, PEER_BYTES_MAX_OUTSTANDING, PEER_BYTES_STALL_MS, PEER_BYTES_TICKET_TTL_MS, ReadinessRegistry, ReadinessTimeoutError, addonSliceHandleApi, asJsonObject, asString, collectZodSecretPaths, commandOrigin, createDebugEmitter, createDeviceProxy, createEventBusSliceSource, createRecordsAccess, createSecretsAccess, describeCustomActions, describeNvidia, deviceOpsCapability, emitReadiness, errMsg, expandCapMethods, findMigrationsBlocked, isCollectionArrayMethodName, isInstanceSwitchesUnreadError, isProviderOptionalMethodName, maskUrlCredentials, nodeIdOfScopedKey, normalizeAddonInitResult, readCommandOrigin, readErrorI18n, readNodePin, resolveDeviceSettings, resolveSecretViewsIn, scopeKey, scrubKnownSecrets, switchRefusesSetState, withCapInputDefaults } from "@camstack/types/addon";
3
3
  import * as fs$1 from "node:fs";
4
4
  import fs, { createReadStream, createWriteStream, existsSync, readFileSync, readdirSync } from "node:fs";
5
5
  import * as path from "node:path";
@@ -125,6 +125,25 @@ function refusalReportOf(addonId, err) {
125
125
  };
126
126
  }
127
127
  //#endregion
128
+ //#region src/kernel/moleculer/hub-connect-switches.ts
129
+ /**
130
+ * On a hub connect, every addon with instance kinds reads its switches from the registry again
131
+ * (D1066). Event-driven, no timer (D3): the next connect retries. A forked runner's FIRST connect
132
+ * is its boot, so a registry that still does not answer ends the process and the supervisor
133
+ * respawns it, bounded and marked terminally failed (D6), instead of leaving instances off.
134
+ */
135
+ async function rehydrateSwitchesOnHubConnect(entries, deps) {
136
+ for (const entry of entries) {
137
+ if (entry.addon.rehydrateSwitches === void 0) continue;
138
+ try {
139
+ await entry.addon.rehydrateSwitches();
140
+ } catch (err) {
141
+ if (deps.fatalOnUnread && isInstanceSwitchesUnreadError(err)) deps.exit(entry.addonId, err);
142
+ else deps.onUnread(entry.addonId, err);
143
+ }
144
+ }
145
+ }
146
+ //#endregion
128
147
  //#region src/kernel/addon-class-resolver.ts
129
148
  function isRecord$4(value) {
130
149
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -6054,6 +6073,156 @@ var AccessoryShrinkGate = class {
6054
6073
  }
6055
6074
  };
6056
6075
  //#endregion
6076
+ //#region src/kernel/moleculer/accessory-spawn-retry.ts
6077
+ /** A spawn failure that knows which step threw. */
6078
+ var AccessorySpawnStepError = class extends Error {
6079
+ step;
6080
+ /** The child's numeric id once allocated; null when allocation itself failed. */
6081
+ deviceId;
6082
+ constructor(step, deviceId, cause) {
6083
+ const reason = cause instanceof Error ? cause.message : String(cause);
6084
+ super(`${step}: ${reason}`, { cause });
6085
+ this.name = "AccessorySpawnStepError";
6086
+ this.step = step;
6087
+ this.deviceId = deviceId;
6088
+ }
6089
+ };
6090
+ function describeError(error) {
6091
+ if (error instanceof AccessorySpawnStepError) return {
6092
+ step: error.step,
6093
+ reason: error.message.slice(error.step.length + 2)
6094
+ };
6095
+ return {
6096
+ step: "unknown",
6097
+ reason: error instanceof Error ? error.message : String(error)
6098
+ };
6099
+ }
6100
+ var AccessorySpawnRetry = class AccessorySpawnRetry {
6101
+ #logger;
6102
+ #delaysMs;
6103
+ /** Pending spawns, by `<parent>:<child stableId>`. */
6104
+ #pending = /* @__PURE__ */ new Map();
6105
+ /** Gave up — sticks until the parent is registered again. */
6106
+ #gaveUp = /* @__PURE__ */ new Set();
6107
+ constructor(options) {
6108
+ this.#logger = options.logger;
6109
+ this.#delaysMs = options.delaysMs ?? DEVICE_RESTORE_RETRY_DELAYS_MS;
6110
+ }
6111
+ static #key(parentDeviceId, stableId) {
6112
+ return `${parentDeviceId}:${stableId}`;
6113
+ }
6114
+ /** The parent went away (teardown / shutdown): drop its pending rounds and its give-ups. */
6115
+ cancelParent(parentDeviceId) {
6116
+ for (const [key, entry] of this.#pending) {
6117
+ if (entry.parentDeviceId !== parentDeviceId) continue;
6118
+ entry.cancelled = true;
6119
+ if (entry.timer !== null) clearTimeout(entry.timer);
6120
+ this.#pending.delete(key);
6121
+ }
6122
+ this.#forgetGiveUps(parentDeviceId);
6123
+ }
6124
+ /** The parent registered again: a fresh chance for children that gave up. */
6125
+ resetParent(parentDeviceId) {
6126
+ this.#forgetGiveUps(parentDeviceId);
6127
+ }
6128
+ #forgetGiveUps(parentDeviceId) {
6129
+ const prefix = `${parentDeviceId}:`;
6130
+ for (const key of this.#gaveUp) if (key.startsWith(prefix)) this.#gaveUp.delete(key);
6131
+ }
6132
+ /** Record the initial failure and run the bounded rounds in the background. */
6133
+ schedule(request) {
6134
+ const key = AccessorySpawnRetry.#key(request.parentDeviceId, request.stableId);
6135
+ if (this.#pending.has(key)) return;
6136
+ if (this.#gaveUp.has(key)) {
6137
+ this.#logger.debug("Accessory child spawn skipped — gave up earlier, parent not re-registered", {
6138
+ tags: { parentDeviceId: request.parentDeviceId },
6139
+ meta: { stableId: request.stableId }
6140
+ });
6141
+ return;
6142
+ }
6143
+ const entry = {
6144
+ parentDeviceId: request.parentDeviceId,
6145
+ cancelled: false,
6146
+ timer: null
6147
+ };
6148
+ this.#pending.set(key, entry);
6149
+ this.#record(request, request.deviceId, request.error, 0, false);
6150
+ this.#run(key, entry, request);
6151
+ }
6152
+ #record(request, deviceId, error, retry, terminal) {
6153
+ const { step, reason } = describeError(error);
6154
+ this.#logger.error(terminal ? "Accessory child spawn gave up after the bounded retries" : "Accessory child spawn failed", {
6155
+ tags: {
6156
+ ...deviceId === null ? {} : { deviceId },
6157
+ parentDeviceId: request.parentDeviceId
6158
+ },
6159
+ meta: {
6160
+ stableId: request.stableId,
6161
+ step,
6162
+ error: reason,
6163
+ retry,
6164
+ max: this.#delaysMs.length
6165
+ }
6166
+ });
6167
+ }
6168
+ async #run(key, entry, request) {
6169
+ let lastError = request.error;
6170
+ let deviceId = request.deviceId;
6171
+ for (let round = 1; round <= this.#delaysMs.length; round += 1) {
6172
+ await this.#sleep(entry, this.#delaysMs[round - 1] ?? 0);
6173
+ if (entry.cancelled) return;
6174
+ if (!request.isParentRegistered()) {
6175
+ this.#pending.delete(key);
6176
+ this.#logger.info("Accessory child spawn retry skipped — parent no longer registered", {
6177
+ tags: {
6178
+ ...deviceId === null ? {} : { deviceId },
6179
+ parentDeviceId: request.parentDeviceId
6180
+ },
6181
+ meta: {
6182
+ stableId: request.stableId,
6183
+ retry: round
6184
+ }
6185
+ });
6186
+ return;
6187
+ }
6188
+ try {
6189
+ await request.attempt({ final: round === this.#delaysMs.length });
6190
+ if (entry.cancelled) return;
6191
+ this.#pending.delete(key);
6192
+ this.#logger.info("Accessory child spawned on retry", {
6193
+ tags: {
6194
+ ...deviceId === null ? {} : { deviceId },
6195
+ parentDeviceId: request.parentDeviceId
6196
+ },
6197
+ meta: {
6198
+ stableId: request.stableId,
6199
+ retry: round
6200
+ }
6201
+ });
6202
+ return;
6203
+ } catch (err) {
6204
+ if (entry.cancelled) return;
6205
+ lastError = err;
6206
+ if (err instanceof AccessorySpawnStepError && err.deviceId !== null) deviceId = err.deviceId;
6207
+ if (round < this.#delaysMs.length) this.#record(request, deviceId, err, round, false);
6208
+ }
6209
+ }
6210
+ this.#record(request, deviceId, lastError, this.#delaysMs.length, true);
6211
+ this.#pending.delete(key);
6212
+ this.#gaveUp.add(key);
6213
+ }
6214
+ #sleep(entry, ms) {
6215
+ return new Promise((resolve) => {
6216
+ const timer = setTimeout(() => {
6217
+ entry.timer = null;
6218
+ resolve();
6219
+ }, ms);
6220
+ timer.unref?.();
6221
+ entry.timer = timer;
6222
+ });
6223
+ }
6224
+ };
6225
+ //#endregion
6057
6226
  //#region src/kernel/moleculer/runtime-state-load.ts
6058
6227
  /** A device build refused because its runtime state could not be loaded. */
6059
6228
  var RuntimeStateLoadError = class extends Error {
@@ -6634,6 +6803,10 @@ function createBrokerDeviceManagerApi(opts) {
6634
6803
  const resolveParentIntegrationId = async (parentId) => {
6635
6804
  return (await callDeviceManager(api, "loadMeta", { deviceId: parentId }).catch(() => null))?.integrationId ?? void 0;
6636
6805
  };
6806
+ const accessorySpawnRetry = new AccessorySpawnRetry({
6807
+ logger: opts.logger,
6808
+ ...opts.accessorySpawnRetryDelaysMs !== void 0 ? { delaysMs: opts.accessorySpawnRetryDelaysMs } : {}
6809
+ });
6637
6810
  /**
6638
6811
  * Spawn one accessory child device declared by a parent's
6639
6812
  * `getAccessoryChildren()`. Mirrors the standard `create()` flow
@@ -6643,9 +6816,20 @@ function createBrokerDeviceManagerApi(opts) {
6643
6816
  * row already exists, `persistInitialConfig` is skipped (config
6644
6817
  * arg empty) and the child self-hydrates from `loadConfig`.
6645
6818
  */
6646
- const spawnAccessoryChild = async (parent, spec) => {
6819
+ const spawnAccessoryChild = async (parent, spec, spawnOptions = { final: false }) => {
6647
6820
  const childStableId = `${parent.stableId}-${spec.stableIdSuffix}`;
6648
- const id = await deviceApi.allocateDeviceId(childStableId);
6821
+ let allocatedId = null;
6822
+ try {
6823
+ return await spawnAccessoryChildSteps(parent, spec, childStableId, (id) => {
6824
+ allocatedId = id;
6825
+ }, spawnOptions);
6826
+ } catch (err) {
6827
+ throw err instanceof AccessorySpawnStepError ? err : new AccessorySpawnStepError("register", allocatedId, err);
6828
+ }
6829
+ };
6830
+ const spawnAccessoryChildSteps = async (parent, spec, childStableId, onAllocated, spawnOptions) => {
6831
+ const id = await deviceApi.allocateDeviceId(childStableId).catch((err) => Promise.reject(new AccessorySpawnStepError("allocateDeviceId", null, err)));
6832
+ onAllocated(id);
6649
6833
  const existing = registry.getById(id);
6650
6834
  if (existing && existing.stableId === childStableId) return existing;
6651
6835
  const empty = {};
@@ -6662,12 +6846,17 @@ function createBrokerDeviceManagerApi(opts) {
6662
6846
  ...spec.meta.type !== void 0 ? { type: spec.meta.type } : {},
6663
6847
  ...integrationId !== void 0 ? { integrationId } : {}
6664
6848
  }).catch((err) => {
6665
- opts.logger.warn("spawnAccessoryChild: applyInitialMeta pre-seed failed", {
6849
+ if (!spawnOptions.final) return Promise.reject(new AccessorySpawnStepError("applyInitialMeta", id, err));
6850
+ opts.logger.error("Accessory child spawned WITHOUT its meta pre-seed after the last retry", {
6666
6851
  tags: {
6667
- stableId: childStableId,
6668
- deviceId: id
6852
+ deviceId: id,
6853
+ parentDeviceId: parent.id
6669
6854
  },
6670
- meta: { error: err instanceof Error ? err.message : String(err) }
6855
+ meta: {
6856
+ step: "applyInitialMeta",
6857
+ stableId: childStableId,
6858
+ error: err instanceof Error ? err.message : String(err)
6859
+ }
6671
6860
  });
6672
6861
  });
6673
6862
  if (isFirstSpawn && Object.keys(spec.config).length > 0) await callDeviceManager(api, "persistConfig", {
@@ -6675,7 +6864,7 @@ function createBrokerDeviceManagerApi(opts) {
6675
6864
  data: spec.config
6676
6865
  }).catch(() => {});
6677
6866
  const [initialRuntimeState, loadedConfig, deviceMeta] = await Promise.all([
6678
- loadRuntimeStateFor(id, childStableId, "accessory-child"),
6867
+ loadRuntimeStateFor(id, childStableId, "accessory-child").catch((err) => Promise.reject(new AccessorySpawnStepError("loadRuntimeState", id, err))),
6679
6868
  callDeviceManager(api, "loadConfig", { deviceId: id }).catch(() => empty),
6680
6869
  callDeviceManager(api, "loadMeta", { deviceId: id }).catch(() => null)
6681
6870
  ]);
@@ -6714,6 +6903,7 @@ function createBrokerDeviceManagerApi(opts) {
6714
6903
  */
6715
6904
  const teardownLocal = async (deviceId, runLifecycle) => {
6716
6905
  const device = registry.getById(deviceId);
6906
+ accessorySpawnRetry.cancelParent(deviceId);
6717
6907
  cancelProbeRetry(deviceId);
6718
6908
  if (!device) return;
6719
6909
  const children = registry.getChildren(deviceId);
@@ -6958,6 +7148,7 @@ function createBrokerDeviceManagerApi(opts) {
6958
7148
  if (!opts.capabilityRegistry) workerNativeCaps.get("device-ops")?.delete(device.id);
6959
7149
  throw err;
6960
7150
  }
7151
+ accessorySpawnRetry.resetParent(device.id);
6961
7152
  const lifecycleHost = device;
6962
7153
  const shrinkGate = new AccessoryShrinkGate();
6963
7154
  const runReconcileNow = async () => {
@@ -6995,14 +7186,14 @@ function createBrokerDeviceManagerApi(opts) {
6995
7186
  try {
6996
7187
  await spawnAccessoryChild(device, spec);
6997
7188
  } catch (err) {
6998
- opts.logger.warn("Failed to spawn accessory child", {
6999
- tags: {
7000
- parentDeviceId: device.id,
7001
- parentStableId: device.stableId
7002
- },
7003
- meta: {
7004
- stableIdSuffix: spec.stableIdSuffix,
7005
- error: err instanceof Error ? err.message : String(err)
7189
+ accessorySpawnRetry.schedule({
7190
+ deviceId: err instanceof AccessorySpawnStepError ? err.deviceId : null,
7191
+ stableId: `${device.stableId}-${spec.stableIdSuffix}`,
7192
+ parentDeviceId: device.id,
7193
+ error: err,
7194
+ isParentRegistered: () => registry.getById(device.id) !== null,
7195
+ attempt: async (attemptOptions) => {
7196
+ await spawnAccessoryChild(device, spec, attemptOptions);
7006
7197
  }
7007
7198
  });
7008
7199
  }
@@ -12504,18 +12695,35 @@ async function main() {
12504
12695
  if (deviceRestorePromises.length > 0 && !shuttingDown) await Promise.allSettled(deviceRestorePromises);
12505
12696
  refreshChildCaps("post-init", customActionRegistry.describeAll(specs.map((spec) => spec.addonId)));
12506
12697
  let hubReachableFired = false;
12507
- const fireHubReachableOnce = () => {
12698
+ const rehydrateSwitches = (first) => rehydrateSwitchesOnHubConnect(loaded, {
12699
+ fatalOnUnread: first,
12700
+ onUnread: (addonId, err) => {
12701
+ runnerLog.error(`"${addonId}" instance switches not read from the registry`, { meta: { error: errMsg(err) } });
12702
+ },
12703
+ exit: (addonId, err) => {
12704
+ console.error(`[addon-runner] "${addonId}" cannot read its instance switches: ${errMsg(err)}`);
12705
+ process.exit(1);
12706
+ }
12707
+ });
12708
+ const fireHubReachableOnce = async () => {
12508
12709
  if (hubReachableFired) return;
12509
12710
  hubReachableFired = true;
12510
- for (const entry of loaded) if (typeof entry.addon.onHubReachable === "function") Promise.resolve(entry.addon.onHubReachable()).catch((err) => {
12511
- runnerLog.error(`"${entry.addonId}" onHubReachable() threw`, { meta: { error: errMsg(err) } });
12512
- });
12711
+ await rehydrateSwitches(true);
12712
+ for (const entry of loaded) {
12713
+ if (typeof entry.addon.onHubReachable !== "function") continue;
12714
+ Promise.resolve(entry.addon.onHubReachable()).catch((err) => {
12715
+ runnerLog.error(`"${entry.addonId}" onHubReachable() threw`, { meta: { error: errMsg(err) } });
12716
+ });
12717
+ }
12513
12718
  };
12514
12719
  udsChildClient.onConnected(() => {
12515
- if (hubReachableFired) refreshChildCaps("on reconnect");
12720
+ if (hubReachableFired) {
12721
+ refreshChildCaps("on reconnect");
12722
+ rehydrateSwitches(false);
12723
+ }
12516
12724
  fireHubReachableOnce();
12517
12725
  });
12518
- fireHubReachableOnce();
12726
+ await fireHubReachableOnce();
12519
12727
  runnerLog.info(`"${nodeId}" started — ${loaded.length} addon(s) ready (UDS connected)`);
12520
12728
  process.stdout.write(`READY:${nodeId}\n`);
12521
12729
  const stopHeapWatch = startRunnerHeapWatch({
@@ -3,7 +3,7 @@ Object.defineProperties(exports, {
3
3
  [Symbol.toStringTag]: { value: "Module" }
4
4
  });
5
5
  const require_chunk = require("../../chunk-Cek0wNdY.js");
6
- const require_dist = require("../../dist-xH7EdlAg.js");
6
+ const require_dist = require("../../dist-CZx3IYRz.js");
7
7
  const require_settle_sources = require("../../settle-sources-Bhsy57y-.js");
8
8
  let node_crypto = require("node:crypto");
9
9
  let node_fs = require("node:fs");
@@ -1,4 +1,4 @@
1
- import { Cc as BaseAddon, Du as errMsg, Rn as addonPagesCapability, ku as EventCategory } from "../../dist-CUt0SVMu.mjs";
1
+ import { Cc as BaseAddon, Du as errMsg, Rn as addonPagesCapability, ku as EventCategory } from "../../dist-DUYpvNfO.mjs";
2
2
  import { t as settleSourcesWithTimeout } from "../../settle-sources-CDtNC8ub.mjs";
3
3
  import { createHash, randomUUID } from "node:crypto";
4
4
  import * as fs$1 from "node:fs";