@camstack/system 1.2.180 → 1.2.181

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 (60) hide show
  1. package/dist/addon-runner.js +2 -2
  2. package/dist/addon-runner.mjs +2 -2
  3. package/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.js +1 -1
  4. package/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.mjs +1 -1
  5. package/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.js +1 -1
  6. package/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.mjs +1 -1
  7. package/dist/builtins/alerts/alerts.addon.js +1 -1
  8. package/dist/builtins/alerts/alerts.addon.mjs +1 -1
  9. package/dist/builtins/backup-orchestrator/backup-orchestrator.addon.js +1 -1
  10. package/dist/builtins/backup-orchestrator/backup-orchestrator.addon.mjs +1 -1
  11. package/dist/builtins/console-logging/index.js +1 -1
  12. package/dist/builtins/console-logging/index.mjs +1 -1
  13. package/dist/builtins/core-blocks/core-blocks.addon.js +1 -1
  14. package/dist/builtins/core-blocks/core-blocks.addon.mjs +1 -1
  15. package/dist/builtins/device-manager/device-manager.addon.js +231 -88
  16. package/dist/builtins/device-manager/device-manager.addon.mjs +231 -88
  17. package/dist/builtins/device-manager/device-meta-actions.d.ts +7 -18
  18. package/dist/builtins/device-manager/device-provider-context.d.ts +4 -0
  19. package/dist/builtins/device-manager/migrate-device.d.ts +14 -3
  20. package/dist/builtins/device-manager/migrate-guard.d.ts +39 -0
  21. package/dist/builtins/device-manager/migrate-reload.d.ts +8 -0
  22. package/dist/builtins/doorbell/virtual-doorbell.addon.js +1 -1
  23. package/dist/builtins/doorbell/virtual-doorbell.addon.mjs +1 -1
  24. package/dist/builtins/hub-forwarder/index.js +1 -1
  25. package/dist/builtins/hub-forwarder/index.mjs +1 -1
  26. package/dist/builtins/liveness-monitor/liveness-monitor.addon.js +1 -1
  27. package/dist/builtins/liveness-monitor/liveness-monitor.addon.mjs +1 -1
  28. package/dist/builtins/local-auth/local-auth.addon.js +1 -1
  29. package/dist/builtins/local-auth/local-auth.addon.mjs +1 -1
  30. package/dist/builtins/local-network/local-network.addon.js +1 -1
  31. package/dist/builtins/local-network/local-network.addon.mjs +1 -1
  32. package/dist/builtins/loki-logging/index.js +1 -1
  33. package/dist/builtins/loki-logging/index.mjs +1 -1
  34. package/dist/builtins/native-metrics/native-metrics.addon.js +1 -1
  35. package/dist/builtins/native-metrics/native-metrics.addon.mjs +1 -1
  36. package/dist/builtins/platform-probe/index.js +1 -1
  37. package/dist/builtins/platform-probe/index.mjs +1 -1
  38. package/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.js +1 -1
  39. package/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.mjs +1 -1
  40. package/dist/builtins/snapshot/index.js +1 -1
  41. package/dist/builtins/snapshot/index.mjs +1 -1
  42. package/dist/builtins/sqlite-storage/filesystem-storage.addon.js +1 -1
  43. package/dist/builtins/sqlite-storage/filesystem-storage.addon.mjs +1 -1
  44. package/dist/builtins/sqlite-storage/sqlite-settings.addon.js +0 -0
  45. package/dist/builtins/sqlite-storage/sqlite-settings.addon.mjs +0 -0
  46. package/dist/builtins/storage-orchestrator/storage-orchestrator.addon.js +1 -1
  47. package/dist/builtins/storage-orchestrator/storage-orchestrator.addon.mjs +1 -1
  48. package/dist/builtins/system-config/system-config.addon.js +1 -1
  49. package/dist/builtins/system-config/system-config.addon.mjs +1 -1
  50. package/dist/builtins/winston-logging/index.js +1 -1
  51. package/dist/builtins/winston-logging/index.mjs +1 -1
  52. package/dist/{dist-DqNTelT4.mjs → dist-DbnNk4Lw.mjs} +44 -1
  53. package/dist/{dist-TEwQZL3g.js → dist-whe0b4_3.js} +44 -1
  54. package/dist/index.js +2 -2
  55. package/dist/index.mjs +2 -2
  56. package/dist/{manifest-system-deps-Ci-jhrxY.mjs → manifest-system-deps-DOcMuUWK.mjs} +1 -1
  57. package/dist/{manifest-system-deps-BVIr3MYJ.js → manifest-system-deps-y5vZBO6q.js} +1 -1
  58. package/dist/{retired-settings-keys-DauPtbFR.js → retired-settings-keys-BdvmiaK7.js} +1 -1
  59. package/dist/{retired-settings-keys-CeSITpIX.mjs → retired-settings-keys-CyQG8b-A.mjs} +1 -1
  60. package/package.json +1 -1
@@ -1,5 +1,5 @@
1
- import { $t as isDeviceConfigCap, Bt as DeviceRole, Ft as BaseAddon, H as deviceManagerCapability, J as enumerateSchemaFields, P as buildStreamParamsConfigSchema, Pt as errMsg, U as deviceStateCapability, Vt as DeviceType, W as deviceStatusCapability, Wt as WELL_KNOWN_TAB_MAP, a as CAMERA_SWITCH_ORDER, b as STREAM_PROFILE_META, f as DeviceStatusSchema, ft as normalizeUnit, mt as parseStreamParamsFormPatch, o as CAP_NAMES_WITH_STATUS, on as sleep, q as enumerateItemArrayFields, sn as EventCategory, t as ALL_CAPABILITY_DEFINITIONS, xt as runtimeStatePolicyFor, yt as resolveContainerPrimaryChild, zt as DeviceFeature } from "../../dist-DqNTelT4.mjs";
2
- import { n as purgeRetiredSettingsRows } from "../../retired-settings-keys-CeSITpIX.mjs";
1
+ import { $t as isDeviceConfigCap, Bt as DeviceRole, Ft as BaseAddon, H as deviceManagerCapability, J as enumerateSchemaFields, P as buildStreamParamsConfigSchema, Pt as errMsg, U as deviceStateCapability, Vt as DeviceType, W as deviceStatusCapability, Wt as WELL_KNOWN_TAB_MAP, a as CAMERA_SWITCH_ORDER, b as STREAM_PROFILE_META, f as DeviceStatusSchema, ft as normalizeUnit, mt as parseStreamParamsFormPatch, o as CAP_NAMES_WITH_STATUS, on as sleep, q as enumerateItemArrayFields, sn as EventCategory, t as ALL_CAPABILITY_DEFINITIONS, xt as runtimeStatePolicyFor, yt as resolveContainerPrimaryChild, zt as DeviceFeature } from "../../dist-DbnNk4Lw.mjs";
2
+ import { n as purgeRetiredSettingsRows } from "../../retired-settings-keys-CyQG8b-A.mjs";
3
3
  import { randomUUID } from "node:crypto";
4
4
  import { canonicalDeviceFingerprint } from "@camstack/types/node";
5
5
  //#region src/builtins/device-manager/adoption-job-engine.ts
@@ -3275,8 +3275,6 @@ var DeviceEventPropagator = class {
3275
3275
  return chain;
3276
3276
  }
3277
3277
  };
3278
- //#endregion
3279
- //#region src/builtins/device-manager/migrate-device.ts
3280
3278
  /** A refusal that names a switch the camera does not offer, rather than one it
3281
3279
  * could not be asked about. The cap documents rejecting the former; anything
3282
3280
  * else is treated as the camera being out of reach, which is the safe reading:
@@ -3288,10 +3286,31 @@ function classify(err) {
3288
3286
  detail
3289
3287
  };
3290
3288
  }
3289
+ /**
3290
+ * One switch write under the bound. The race, not the write, is what fails on
3291
+ * timeout — the underlying promise is marked handled so a late rejection from
3292
+ * a camera that eventually answers "no" cannot surface as an unhandled
3293
+ * rejection after the migration already reported `unreachable`.
3294
+ */
3295
+ async function setSwitchBounded(deps, deviceId, switchId, enabled) {
3296
+ const budget = deps.switchTimeoutMs ?? 15e3;
3297
+ const write = deps.setSwitch(deviceId, switchId, enabled);
3298
+ write.catch(() => {});
3299
+ let timer;
3300
+ try {
3301
+ await Promise.race([write, new Promise((_resolve, reject) => {
3302
+ timer = setTimeout(() => {
3303
+ reject(/* @__PURE__ */ new Error(`switch write did not answer within ${budget}ms — reported unreachable; if it lands late, a duplicate write of the same value is a no-op`));
3304
+ }, budget);
3305
+ })]);
3306
+ } finally {
3307
+ if (timer !== void 0) clearTimeout(timer);
3308
+ }
3309
+ }
3291
3310
  async function applyAll(deps, deviceId, enabled) {
3292
3311
  const out = [];
3293
3312
  for (const switchId of CAMERA_SWITCH_ORDER) try {
3294
- await deps.setSwitch(deviceId, switchId, enabled);
3313
+ await setSwitchBounded(deps, deviceId, switchId, enabled);
3295
3314
  out.push({
3296
3315
  deviceId,
3297
3316
  switchId,
@@ -3339,7 +3358,6 @@ async function migrateDevice$1(deps, input) {
3339
3358
  });
3340
3359
  }
3341
3360
  const up = await applyAll(deps, sourceId, true);
3342
- await deps.respawnRunners([sourceId, targetId]);
3343
3361
  deps.log("camera migrated", {
3344
3362
  sourceId,
3345
3363
  targetId,
@@ -3355,6 +3373,52 @@ async function migrateDevice$1(deps, input) {
3355
3373
  };
3356
3374
  }
3357
3375
  //#endregion
3376
+ //#region src/builtins/device-manager/migrate-reload.ts
3377
+ async function reloadMigratedDevices(pctx, targets) {
3378
+ const ctx = pctx.host.ctx;
3379
+ for (const target of targets) {
3380
+ pctx.metaStore.idToAddonId.set(target.deviceId, target.addonId);
3381
+ pctx.host.remoteNativeCaps.delete(target.deviceId);
3382
+ pctx.host.capabilityRegistry?.unregisterAllNativeForDevice(target.deviceId);
3383
+ }
3384
+ const fallbackAddons = /* @__PURE__ */ new Map();
3385
+ await Promise.all(targets.map(async (target) => {
3386
+ try {
3387
+ const reloaded = await (await pctx.host.requireDeviceProvider(target.addonId)).reloadDevice({ stableId: target.stableId });
3388
+ ctx.logger.info("migration: device reloaded in place — no other device disturbed", {
3389
+ tags: { deviceId: target.deviceId },
3390
+ meta: {
3391
+ addonId: target.addonId,
3392
+ stableId: target.stableId,
3393
+ reloadedAs: reloaded.deviceId
3394
+ }
3395
+ });
3396
+ } catch (err) {
3397
+ ctx.logger.error("migration: in-place reload FAILED — falling back to a provider restart", {
3398
+ tags: { deviceId: target.deviceId },
3399
+ meta: {
3400
+ addonId: target.addonId,
3401
+ stableId: target.stableId,
3402
+ error: err instanceof Error ? err.message : String(err)
3403
+ }
3404
+ });
3405
+ fallbackAddons.set(target.addonId, target.deviceId);
3406
+ }
3407
+ }));
3408
+ if (fallbackAddons.size === 0) return;
3409
+ await Promise.all([...fallbackAddons.entries()].map(async ([addonId, migratedDeviceId]) => {
3410
+ const owned = [...pctx.metaStore.idToAddonId.entries()].filter(([, a]) => a === addonId).length;
3411
+ ctx.logger.info("migration: restarting a whole provider to flush the id maps", {
3412
+ tags: { deviceId: migratedDeviceId },
3413
+ meta: {
3414
+ addonId,
3415
+ devicesTakenDown: owned
3416
+ }
3417
+ });
3418
+ await ctx.api.addons.restartAddon.mutate({ addonId });
3419
+ }));
3420
+ }
3421
+ //#endregion
3358
3422
  //#region src/builtins/device-manager/migrate-hardware-state.ts
3359
3423
  /**
3360
3424
  * The per-device state half of a migration (`deviceManager.migrateDevice`).
@@ -3535,72 +3599,121 @@ async function allocateDeviceId(pctx, input) {
3535
3599
  * The temp id comes from `allocateNextDeviceId`, the monotonic counter, so the
3536
3600
  * value a crash could park a row on was never used and will never be reused.
3537
3601
  * `swapIds` therefore runs INSIDE the same lock the id was allocated under.
3602
+ *
3603
+ * Retry-safe since 2026-09-04 (`migrate-guard.ts`): a concurrent call touching
3604
+ * either device is REFUSED before it can queue on the lock, and a repeat of a
3605
+ * completed swap — matched against the `addonId`/`stableId` fingerprint the
3606
+ * swap left on the rows — is a no-op returning the original report. A client
3607
+ * retry ran a second full cycle on 2026-09-01 and swapped two cameras back;
3608
+ * neither path can re-run a swap any more.
3538
3609
  */
3539
3610
  async function migrateDevice(pctx, input) {
3540
3611
  const { sourceId, targetId } = input;
3541
3612
  const ctx = pctx.host.ctx;
3542
- return await pctx.metaStore.withMetaWriteLock(async () => {
3543
- for (const id of [sourceId, targetId]) if (await pctx.metaStore.rows.get(id) === null) throw new Error(`[device-manager] migrateDevice: device ${id} does not exist`);
3544
- const tempId = await pctx.metaStore.allocateNextDeviceId();
3545
- return await migrateDevice$1({
3546
- setSwitch: async (deviceId, switchId, enabled) => {
3547
- await ctx.api.pipelineOrchestrator.setCameraSwitch.mutate({
3548
- deviceId,
3549
- switchId,
3550
- enabled
3551
- });
3552
- },
3553
- swapIds: async (a, b) => {
3554
- await pctx.metaStore.rows.swapIds(a, b, tempId);
3555
- },
3556
- swapHardwareState: async (a, b) => {
3557
- const swapped = await swapHardwareState(pctx.settings, a, b);
3558
- pctx.host.seedMirror(a, pctx.host.withResetSessionProbe(swapped.runtimeStateNowAtSource));
3559
- pctx.host.seedMirror(b, pctx.host.withResetSessionProbe(swapped.runtimeStateNowAtTarget));
3560
- ctx.logger.info("migration: hardware-scoped device state swapped", {
3561
- tags: { deviceId: a },
3613
+ pctx.migrationGuard.begin(sourceId, targetId);
3614
+ try {
3615
+ const outcome = await pctx.metaStore.withMetaWriteLock(async () => {
3616
+ const sourceRow = await pctx.metaStore.rows.get(sourceId);
3617
+ if (sourceRow === null) throw new Error(`[device-manager] migrateDevice: device ${sourceId} does not exist`);
3618
+ const targetRow = await pctx.metaStore.rows.get(targetId);
3619
+ if (targetRow === null) throw new Error(`[device-manager] migrateDevice: device ${targetId} does not exist`);
3620
+ const replay = pctx.migrationGuard.matchReplay(sourceId, targetId, {
3621
+ addonId: sourceRow.meta.addonId,
3622
+ stableId: sourceRow.meta.stableId
3623
+ }, {
3624
+ addonId: targetRow.meta.addonId,
3625
+ stableId: targetRow.meta.stableId
3626
+ });
3627
+ if (replay !== null) {
3628
+ ctx.logger.info("migrateDevice: this swap already completed — replaying the original report, NOTHING re-run", {
3629
+ tags: { deviceId: sourceId },
3562
3630
  meta: {
3563
- sourceId: a,
3564
- targetId: b,
3565
- hardwareKeysToSource: swapped.hardwareKeysToSource,
3566
- hardwareKeysToTarget: swapped.hardwareKeysToTarget,
3567
- roleKeysKeptAtSource: swapped.roleKeysKeptAtSource,
3568
- roleKeysKeptAtTarget: swapped.roleKeysKeptAtTarget
3631
+ sourceId,
3632
+ targetId
3569
3633
  }
3570
3634
  });
3571
- },
3572
- forgetStreamState: async (deviceId) => {
3573
- await ctx.api.streamBroker.forgetDeviceHardware.mutate({ deviceId });
3574
- },
3575
- respawnRunners: async (deviceIds) => {
3576
- const owners = /* @__PURE__ */ new Set();
3577
- for (const deviceId of deviceIds) {
3578
- const addonId = pctx.metaStore.idToAddonId.get(deviceId);
3579
- if (addonId !== void 0) owners.add(addonId);
3580
- }
3581
- for (const addonId of owners) {
3582
- const owned = [...pctx.metaStore.idToAddonId.entries()].filter(([, a]) => a === addonId).length;
3583
- ctx.logger.info("migration: restarting a whole provider to flush the id maps", {
3584
- tags: { deviceId: sourceId },
3635
+ return {
3636
+ result: replay,
3637
+ reloadTargets: null
3638
+ };
3639
+ }
3640
+ const tempId = await pctx.metaStore.allocateNextDeviceId();
3641
+ const result = await migrateDevice$1({
3642
+ setSwitch: async (deviceId, switchId, enabled) => {
3643
+ if (switchId === "stream-broker") {
3644
+ const moved = await writeDisabledFlagUnderLock(pctx, deviceId, !enabled);
3645
+ emitDisabledEvents(pctx, deviceId, !enabled, moved);
3646
+ return;
3647
+ }
3648
+ await ctx.api.pipelineOrchestrator.setCameraSwitch.mutate({
3649
+ deviceId,
3650
+ switchId,
3651
+ enabled
3652
+ });
3653
+ },
3654
+ swapIds: async (a, b) => {
3655
+ await pctx.metaStore.rows.swapIds(a, b, tempId);
3656
+ },
3657
+ swapHardwareState: async (a, b) => {
3658
+ const swapped = await swapHardwareState(pctx.settings, a, b);
3659
+ pctx.host.seedMirror(a, pctx.host.withResetSessionProbe(swapped.runtimeStateNowAtSource));
3660
+ pctx.host.seedMirror(b, pctx.host.withResetSessionProbe(swapped.runtimeStateNowAtTarget));
3661
+ ctx.logger.info("migration: hardware-scoped device state swapped", {
3662
+ tags: { deviceId: a },
3585
3663
  meta: {
3586
- addonId,
3587
- devicesTakenDown: owned
3664
+ sourceId: a,
3665
+ targetId: b,
3666
+ hardwareKeysToSource: swapped.hardwareKeysToSource,
3667
+ hardwareKeysToTarget: swapped.hardwareKeysToTarget,
3668
+ roleKeysKeptAtSource: swapped.roleKeysKeptAtSource,
3669
+ roleKeysKeptAtTarget: swapped.roleKeysKeptAtTarget
3588
3670
  }
3589
3671
  });
3590
- await ctx.api.addons.restartAddon.mutate({ addonId });
3672
+ },
3673
+ forgetStreamState: async (deviceId) => {
3674
+ await ctx.api.streamBroker.forgetDeviceHardware.mutate({ deviceId });
3675
+ },
3676
+ log: (message, meta) => {
3677
+ ctx.logger.info(message, {
3678
+ tags: { deviceId: sourceId },
3679
+ meta
3680
+ });
3591
3681
  }
3592
- },
3593
- log: (message, meta) => {
3594
- ctx.logger.info(message, {
3595
- tags: { deviceId: sourceId },
3596
- meta
3597
- });
3598
- }
3599
- }, {
3600
- sourceId,
3601
- targetId
3682
+ }, {
3683
+ sourceId,
3684
+ targetId
3685
+ });
3686
+ pctx.migrationGuard.recordCompleted({
3687
+ sourceId,
3688
+ targetId,
3689
+ identityAtSource: {
3690
+ addonId: targetRow.meta.addonId,
3691
+ stableId: targetRow.meta.stableId
3692
+ },
3693
+ identityAtTarget: {
3694
+ addonId: sourceRow.meta.addonId,
3695
+ stableId: sourceRow.meta.stableId
3696
+ },
3697
+ result
3698
+ });
3699
+ return {
3700
+ result,
3701
+ reloadTargets: [{
3702
+ deviceId: sourceId,
3703
+ addonId: targetRow.meta.addonId,
3704
+ stableId: targetRow.meta.stableId
3705
+ }, {
3706
+ deviceId: targetId,
3707
+ addonId: sourceRow.meta.addonId,
3708
+ stableId: sourceRow.meta.stableId
3709
+ }]
3710
+ };
3602
3711
  });
3603
- });
3712
+ if (outcome.reloadTargets !== null) await reloadMigratedDevices(pctx, outcome.reloadTargets);
3713
+ return outcome.result;
3714
+ } finally {
3715
+ pctx.migrationGuard.end(sourceId, targetId);
3716
+ }
3604
3717
  }
3605
3718
  async function registerDevice(pctx, input) {
3606
3719
  const { addonId, stableId, id, type, name, parentDeviceId, features, config } = input;
@@ -4287,35 +4400,23 @@ async function setMetadata(pctx, input) {
4287
4400
  });
4288
4401
  }
4289
4402
  /**
4290
- * Soft-disable the device. Persisted on the meta row;
4291
- * lifecycle gating is the driver's responsibility (BaseDevice
4292
- * exposes `this.disabled` for the driver to consult at the top
4293
- * of its lifecycle methods).
4294
- *
4295
- * TWO events leave here, and they are not the same message:
4296
- *
4297
- * - `device.meta-changed` fires on EVERY call. It is the meta-surface echo
4298
- * every UI redraws on, and idempotence is not interesting to it.
4299
- * - `device.disabled` / `device.enabled` fire ONLY when the flag actually
4300
- * MOVES. They are the lifecycle announcement — the operator asked to be
4301
- * told when a camera is switched off, and a write that re-states a flag the
4302
- * device already had is not that. Telemetry semantics (D8) are fine here: a
4303
- * dropped announcement costs a notification, never durable state, and the
4304
- * meta row is the authority either way (D62 — this switch stores nothing of
4305
- * its own).
4403
+ * Read + patch the `disabled` flag. The caller HOLDS the meta write lock —
4404
+ * this is split out of {@link setDisabled} so `migrateDevice`, which holds the
4405
+ * lock for its whole run, can write the same authority without re-acquiring
4406
+ * it (the self-deadlock documented at its `setSwitch`).
4306
4407
  */
4307
- async function setDisabled(pctx, input) {
4308
- const { deviceId, disabled } = input;
4309
- const moved = await pctx.metaStore.withMetaWriteLock(async () => {
4310
- const persisted = await pctx.metaStore.resolvePersistedById(deviceId);
4311
- if (!persisted) throw new Error(`[device-manager] setDisabled: unknown device id=${deviceId}`);
4312
- const { meta: m } = persisted;
4313
- await pctx.metaStore.rows.patch(deviceId, { disabled });
4314
- return {
4315
- changed: (m.disabled ?? false) !== disabled,
4316
- integrationId: m.integrationId ?? ""
4317
- };
4318
- });
4408
+ async function writeDisabledFlagUnderLock(pctx, deviceId, disabled) {
4409
+ const persisted = await pctx.metaStore.resolvePersistedById(deviceId);
4410
+ if (!persisted) throw new Error(`[device-manager] setDisabled: unknown device id=${deviceId}`);
4411
+ const { meta: m } = persisted;
4412
+ await pctx.metaStore.rows.patch(deviceId, { disabled });
4413
+ return {
4414
+ changed: (m.disabled ?? false) !== disabled,
4415
+ integrationId: m.integrationId ?? ""
4416
+ };
4417
+ }
4418
+ /** The two announcements — meta echo always, lifecycle only on a transition. */
4419
+ function emitDisabledEvents(pctx, deviceId, disabled, moved) {
4319
4420
  pctx.host.ctx.eventBus.emit({
4320
4421
  id: randomUUID(),
4321
4422
  timestamp: /* @__PURE__ */ new Date(),
@@ -4345,6 +4446,10 @@ async function setDisabled(pctx, input) {
4345
4446
  }
4346
4447
  });
4347
4448
  }
4449
+ async function setDisabled(pctx, input) {
4450
+ const { deviceId, disabled } = input;
4451
+ emitDisabledEvents(pctx, deviceId, disabled, await pctx.metaStore.withMetaWriteLock(() => writeDisabledFlagUnderLock(pctx, deviceId, disabled)));
4452
+ }
4348
4453
  async function loadRuntimeState(pctx, input) {
4349
4454
  const { deviceId } = input;
4350
4455
  if (!await pctx.metaStore.resolvePersistedById(deviceId)) return {};
@@ -5959,6 +6064,43 @@ function resolveNativeCapOwnerSync(pctx, capName, deviceId) {
5959
6064
  };
5960
6065
  return resolveRemoteNativeCapFromRegistry(pctx.bindingsDeps, capName, deviceId);
5961
6066
  }
6067
+ function sameIdentity(a, b) {
6068
+ return a.addonId === b.addonId && a.stableId === b.stableId;
6069
+ }
6070
+ /** One guard per device-manager instance. `now` is injectable for the specs. */
6071
+ function createMigrationGuard(now = Date.now) {
6072
+ const inFlight = /* @__PURE__ */ new Set();
6073
+ const completed = /* @__PURE__ */ new Map();
6074
+ const pairKey = (sourceId, targetId) => `${sourceId}->${targetId}`;
6075
+ return {
6076
+ begin(sourceId, targetId) {
6077
+ for (const id of [sourceId, targetId]) if (inFlight.has(id)) throw new Error(`[device-manager] migrateDevice: a migration involving device ${id} is already in flight — this call was refused, not queued. The running migration's report stands; re-read the device rows before retrying.`);
6078
+ inFlight.add(sourceId);
6079
+ inFlight.add(targetId);
6080
+ },
6081
+ end(sourceId, targetId) {
6082
+ inFlight.delete(sourceId);
6083
+ inFlight.delete(targetId);
6084
+ },
6085
+ recordCompleted(record) {
6086
+ completed.set(pairKey(record.sourceId, record.targetId), {
6087
+ ...record,
6088
+ completedAt: now()
6089
+ });
6090
+ },
6091
+ matchReplay(sourceId, targetId, atSource, atTarget) {
6092
+ const key = pairKey(sourceId, targetId);
6093
+ const record = completed.get(key);
6094
+ if (record === void 0) return null;
6095
+ if (now() - record.completedAt > 9e5) {
6096
+ completed.delete(key);
6097
+ return null;
6098
+ }
6099
+ if (!sameIdentity(record.identityAtSource, atSource) || !sameIdentity(record.identityAtTarget, atTarget)) return null;
6100
+ return record.result;
6101
+ }
6102
+ };
6103
+ }
5962
6104
  //#endregion
5963
6105
  //#region src/builtins/device-manager/device-manager.addon.ts
5964
6106
  var DeviceManagerAddon = class extends BaseAddon {
@@ -6199,6 +6341,7 @@ var DeviceManagerAddon = class extends BaseAddon {
6199
6341
  settings,
6200
6342
  registry,
6201
6343
  bindingsDeps: this.bindingsDeps,
6344
+ migrationGuard: createMigrationGuard(),
6202
6345
  requireDeviceOps,
6203
6346
  stampIntegrationId: stampIntegrationId$1,
6204
6347
  get provider() {
@@ -24,6 +24,13 @@ export declare function allocateDeviceId(pctx: ProviderContext, input: Parameter
24
24
  * The temp id comes from `allocateNextDeviceId`, the monotonic counter, so the
25
25
  * value a crash could park a row on was never used and will never be reused.
26
26
  * `swapIds` therefore runs INSIDE the same lock the id was allocated under.
27
+ *
28
+ * Retry-safe since 2026-09-04 (`migrate-guard.ts`): a concurrent call touching
29
+ * either device is REFUSED before it can queue on the lock, and a repeat of a
30
+ * completed swap — matched against the `addonId`/`stableId` fingerprint the
31
+ * swap left on the rows — is a no-op returning the original report. A client
32
+ * retry ran a second full cycle on 2026-09-01 and swapped two cameras back;
33
+ * neither path can re-run a swap any more.
27
34
  */
28
35
  export declare function migrateDevice(pctx: ProviderContext, input: Parameters<IDeviceManagerProvider['migrateDevice']>[0]): ReturnType<IDeviceManagerProvider['migrateDevice']>;
29
36
  export declare function registerDevice(pctx: ProviderContext, input: Parameters<IDeviceManagerProvider['registerDevice']>[0]): ReturnType<IDeviceManagerProvider['registerDevice']>;
@@ -188,24 +195,6 @@ export declare function applyInitialMeta(pctx: ProviderContext, input: Parameter
188
195
  * the meta-changed event.
189
196
  */
190
197
  export declare function setMetadata(pctx: ProviderContext, input: Parameters<IDeviceManagerProvider['setMetadata']>[0]): ReturnType<IDeviceManagerProvider['setMetadata']>;
191
- /**
192
- * Soft-disable the device. Persisted on the meta row;
193
- * lifecycle gating is the driver's responsibility (BaseDevice
194
- * exposes `this.disabled` for the driver to consult at the top
195
- * of its lifecycle methods).
196
- *
197
- * TWO events leave here, and they are not the same message:
198
- *
199
- * - `device.meta-changed` fires on EVERY call. It is the meta-surface echo
200
- * every UI redraws on, and idempotence is not interesting to it.
201
- * - `device.disabled` / `device.enabled` fire ONLY when the flag actually
202
- * MOVES. They are the lifecycle announcement — the operator asked to be
203
- * told when a camera is switched off, and a write that re-states a flag the
204
- * device already had is not that. Telemetry semantics (D8) are fine here: a
205
- * dropped announcement costs a notification, never durable state, and the
206
- * meta row is the authority either way (D62 — this switch stores nothing of
207
- * its own).
208
- */
209
198
  export declare function setDisabled(pctx: ProviderContext, input: Parameters<IDeviceManagerProvider['setDisabled']>[0]): ReturnType<IDeviceManagerProvider['setDisabled']>;
210
199
  export declare function loadRuntimeState(pctx: ProviderContext, input: Parameters<IDeviceManagerProvider['loadRuntimeState']>[0]): ReturnType<IDeviceManagerProvider['loadRuntimeState']>;
211
200
  /**
@@ -2,6 +2,7 @@ import { AddonContext, ICapabilityRegistry, IDeviceAdoptionProvider, IDeviceMana
2
2
  import { AdoptionJobEngine } from './adoption-job-engine.js';
3
3
  import { BindingsDeps } from './device-bindings-store.js';
4
4
  import { DeviceManagerSettings, DeviceMetaStore } from './device-meta-store.js';
5
+ import { MigrationGuard } from './migrate-guard.js';
5
6
  type IDeviceProviderCap = InferProvider<typeof deviceProviderCapability>;
6
7
  /**
7
8
  * The addon-instance surface the extracted provider functions need. Exposed by
@@ -47,6 +48,9 @@ export interface ProviderContext {
47
48
  /** Hub-process device registry (null when this node owns no registry). */
48
49
  readonly registry: IDeviceRegistry | null;
49
50
  readonly bindingsDeps: BindingsDeps;
51
+ /** In-flight refusal + completed-swap replay for `migrateDevice` — the
52
+ * reason a retried migration can no longer undo the one that ran. */
53
+ readonly migrationGuard: MigrationGuard;
50
54
  /** Resolve the per-device `device-ops` native provider (throws when absent). */
51
55
  requireDeviceOps(deviceId: number): IDeviceOpsProvider;
52
56
  /** Stamp an integration id onto a device's meta row + emit DeviceMetaChanged. */
@@ -1,4 +1,11 @@
1
1
  import { CameraSwitchId } from '@camstack/types';
2
+ /**
3
+ * Upper bound for ONE switch write. Generous against a live camera (a real
4
+ * write is sub-second; the camera-plane pair is a few seconds of HTTP) and
5
+ * small against the alternative: the 60 s transport default that let three
6
+ * phases burn three minutes on 2026-09-01.
7
+ */
8
+ export declare const SWITCH_WRITE_TIMEOUT_MS = 15000;
2
9
  /** What actually happened to one switch on one device. */
3
10
  export type SwitchOutcome = 'off' | 'on' | 'not-offered' | 'unreachable';
4
11
  export interface SwitchReport {
@@ -59,10 +66,14 @@ export interface MigrateDeviceDeps {
59
66
  * dropped event (D8) would leave the feeder respawning forever.
60
67
  */
61
68
  readonly forgetStreamState: (deviceId: number) => Promise<void>;
62
- /** Respawn the runners that hold either number in memory. Disabling stops
63
- * data PRODUCTION; it does not flush a cache that maps id → addon. */
64
- readonly respawnRunners: (deviceIds: readonly number[]) => Promise<void>;
65
69
  readonly log: (message: string, meta: Record<string, unknown>) => void;
70
+ /**
71
+ * Override for {@link SWITCH_WRITE_TIMEOUT_MS}, for the specs. A write that
72
+ * outlives the bound is reported `unreachable` — never `off`/`on` — and may
73
+ * still land later, which every switch authority tolerates (a duplicate
74
+ * write of the same value is a no-op at all eight of them).
75
+ */
76
+ readonly switchTimeoutMs?: number;
66
77
  }
67
78
  /**
68
79
  * Put both cameras to sleep, exchange their identities, wake the target.
@@ -0,0 +1,39 @@
1
+ import { MigrateDeviceResult } from './migrate-device.js';
2
+ /** The addon-facing identity a device row carries — what `swapIds` moves. */
3
+ export interface DeviceIdentity {
4
+ readonly addonId: string;
5
+ readonly stableId: string;
6
+ }
7
+ /** What a finished migration left behind, for replay matching. */
8
+ export interface CompletedMigration {
9
+ readonly sourceId: number;
10
+ readonly targetId: number;
11
+ /** Identity the completed swap left at `sourceId` (the pre-swap target's). */
12
+ readonly identityAtSource: DeviceIdentity;
13
+ /** Identity the completed swap left at `targetId` (the pre-swap source's). */
14
+ readonly identityAtTarget: DeviceIdentity;
15
+ readonly result: MigrateDeviceResult;
16
+ }
17
+ /**
18
+ * How long a completed migration absorbs an identical repeat call. Sized to
19
+ * comfortably cover the cap's own `timeoutMs` (10 min): a retry fired by a
20
+ * client that gave up arrives inside that envelope; a call arriving later is
21
+ * an operator's deliberate new operation and runs.
22
+ */
23
+ export declare const MIGRATION_REPLAY_WINDOW_MS: number;
24
+ export interface MigrationGuard {
25
+ /** Claim both ids for a run. Throws when either is already in flight. */
26
+ begin(sourceId: number, targetId: number): void;
27
+ /** Release both ids. Always paired with {@link begin} via try/finally. */
28
+ end(sourceId: number, targetId: number): void;
29
+ /** Record a completed swap's fingerprint for replay matching. */
30
+ recordCompleted(record: CompletedMigration): void;
31
+ /**
32
+ * The original report, when the call is a repeat of a completed swap: same
33
+ * ordered pair, current row identities equal to the recorded post-swap
34
+ * identities, within the window. `null` means "this is a new operation".
35
+ */
36
+ matchReplay(sourceId: number, targetId: number, atSource: DeviceIdentity, atTarget: DeviceIdentity): MigrateDeviceResult | null;
37
+ }
38
+ /** One guard per device-manager instance. `now` is injectable for the specs. */
39
+ export declare function createMigrationGuard(now?: () => number): MigrationGuard;
@@ -0,0 +1,8 @@
1
+ import { ProviderContext } from './device-provider-context.js';
2
+ /** One migrated number and the identity that lives at it AFTER the swap. */
3
+ export interface MigratedDeviceTarget {
4
+ readonly deviceId: number;
5
+ readonly addonId: string;
6
+ readonly stableId: string;
7
+ }
8
+ export declare function reloadMigratedDevices(pctx: ProviderContext, targets: readonly MigratedDeviceTarget[]): Promise<void>;
@@ -3,7 +3,7 @@ Object.defineProperties(exports, {
3
3
  [Symbol.toStringTag]: { value: "Module" }
4
4
  });
5
5
  require("../../chunk-Cek0wNdY.js");
6
- const require_dist = require("../../dist-TEwQZL3g.js");
6
+ const require_dist = require("../../dist-whe0b4_3.js");
7
7
  //#region src/builtins/doorbell/trigger-engine.ts
8
8
  /**
9
9
  * Pure trigger logic for the virtual-doorbell builtin — edge detection over
@@ -1,4 +1,4 @@
1
- import { Ft as BaseAddon, G as doorbellCapability, Jt as createEvent, M as bareAddonId, Pt as errMsg, Vt as DeviceType, Y as evaluateSensorEdge, _ as SOURCE_CAPS, nt as isSameAddonId, rt as isSourceCap, sn as EventCategory, v as SOURCE_DEVICE_TYPES } from "../../dist-DqNTelT4.mjs";
1
+ import { Ft as BaseAddon, G as doorbellCapability, Jt as createEvent, M as bareAddonId, Pt as errMsg, Vt as DeviceType, Y as evaluateSensorEdge, _ as SOURCE_CAPS, nt as isSameAddonId, rt as isSourceCap, sn as EventCategory, v as SOURCE_DEVICE_TYPES } from "../../dist-DbnNk4Lw.mjs";
2
2
  //#region src/builtins/doorbell/trigger-engine.ts
3
3
  /**
4
4
  * Pure trigger logic for the virtual-doorbell builtin — edge detection over
@@ -3,7 +3,7 @@ Object.defineProperties(exports, {
3
3
  [Symbol.toStringTag]: { value: "Module" }
4
4
  });
5
5
  require("../../chunk-Cek0wNdY.js");
6
- const require_dist = require("../../dist-TEwQZL3g.js");
6
+ const require_dist = require("../../dist-whe0b4_3.js");
7
7
  const require_formatter = require("../../formatter-DqAKDlvN.js");
8
8
  //#region src/builtins/hub-forwarder/hub-forwarder-destination.ts
9
9
  var DEFAULT_OUTBOUND_BUFFER_SIZE = 500;
@@ -1,4 +1,4 @@
1
- import { Ft as BaseAddon, ct as logDestinationCapability } from "../../dist-DqNTelT4.mjs";
1
+ import { Ft as BaseAddon, ct as logDestinationCapability } from "../../dist-DbnNk4Lw.mjs";
2
2
  import { t as formatLogLine } from "../../formatter-B7qW8bPJ.mjs";
3
3
  //#region src/builtins/hub-forwarder/hub-forwarder-destination.ts
4
4
  var DEFAULT_OUTBOUND_BUFFER_SIZE = 500;
@@ -1,6 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  require("../../chunk-Cek0wNdY.js");
3
- const require_dist = require("../../dist-TEwQZL3g.js");
3
+ const require_dist = require("../../dist-whe0b4_3.js");
4
4
  //#region src/builtins/liveness-monitor/liveness-checks.ts
5
5
  var NO_DEVICES = "liveness:no-devices";
6
6
  var ALL_OFFLINE = "liveness:all-devices-offline";
@@ -1,4 +1,4 @@
1
- import { Ft as BaseAddon, Jt as createEvent, Pt as errMsg, sn as EventCategory } from "../../dist-DqNTelT4.mjs";
1
+ import { Ft as BaseAddon, Jt as createEvent, Pt as errMsg, sn as EventCategory } from "../../dist-DbnNk4Lw.mjs";
2
2
  //#region src/builtins/liveness-monitor/liveness-checks.ts
3
3
  var NO_DEVICES = "liveness:no-devices";
4
4
  var ALL_OFFLINE = "liveness:all-devices-offline";
@@ -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-TEwQZL3g.js");
6
+ const require_dist = require("../../dist-whe0b4_3.js");
7
7
  let node_crypto = require("node:crypto");
8
8
  node_crypto = require_chunk.__toESM(node_crypto);
9
9
  let crypto$1 = require("crypto");
@@ -1,5 +1,5 @@
1
1
  import { i as __require, o as __toESM, t as __commonJSMin } from "../../chunk-CNf5ZN-e.mjs";
2
- import { A as authProviderCapability, Ft as BaseAddon, T as UserRecordSchema, jt as userManagementCapability, r as ApiKeyRecordSchema, x as ScopedTokenSchema } from "../../dist-DqNTelT4.mjs";
2
+ import { A as authProviderCapability, Ft as BaseAddon, T as UserRecordSchema, jt as userManagementCapability, r as ApiKeyRecordSchema, x as ScopedTokenSchema } from "../../dist-DbnNk4Lw.mjs";
3
3
  import * as crypto$2 from "node:crypto";
4
4
  import { createHash, randomUUID, timingSafeEqual } from "node:crypto";
5
5
  import nodeCrypto from "crypto";
@@ -1,6 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_chunk = require("../../chunk-Cek0wNdY.js");
3
- const require_dist = require("../../dist-TEwQZL3g.js");
3
+ const require_dist = require("../../dist-whe0b4_3.js");
4
4
  const require_tls = require("../../tls-BxQlomxd.js");
5
5
  let node_fs_promises = require("node:fs/promises");
6
6
  let node_path = require("node:path");
@@ -1,4 +1,4 @@
1
- import { Ft as BaseAddon, sn as EventCategory, st as localNetworkCapability } from "../../dist-DqNTelT4.mjs";
1
+ import { Ft as BaseAddon, sn as EventCategory, st as localNetworkCapability } from "../../dist-DbnNk4Lw.mjs";
2
2
  import { S as readLanHttpState, _ as DEFAULT_LAN_HTTP_PORT, a as writeTlsMode, i as writeExtraSans, l as reissueTlsLeaf, n as readTlsAccessStatus, o as validateUploadedTls, r as readTlsMode, s as ensureTlsCert, t as readExtraSans, y as applyLanHttp } from "../../tls-DOTmtLCW.mjs";
3
3
  import { mkdir, writeFile } from "node:fs/promises";
4
4
  import { join } from "node:path";
@@ -3,7 +3,7 @@ Object.defineProperties(exports, {
3
3
  [Symbol.toStringTag]: { value: "Module" }
4
4
  });
5
5
  require("../../chunk-Cek0wNdY.js");
6
- const require_dist = require("../../dist-TEwQZL3g.js");
6
+ const require_dist = require("../../dist-whe0b4_3.js");
7
7
  //#region src/builtins/loki-logging/loki-payload.ts
8
8
  /**
9
9
  * Loki rejects a label name that is not a valid Prometheus label
@@ -1,4 +1,4 @@
1
- import { Ft as BaseAddon, ct as logDestinationCapability } from "../../dist-DqNTelT4.mjs";
1
+ import { Ft as BaseAddon, ct as logDestinationCapability } from "../../dist-DbnNk4Lw.mjs";
2
2
  //#region src/builtins/loki-logging/loki-payload.ts
3
3
  /**
4
4
  * Loki rejects a label name that is not a valid Prometheus label