@camstack/server 1.2.728 → 1.2.729

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 (107) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/dist/agent/main.js +2 -14
  3. package/dist/api/core/cap-providers.js +0 -7
  4. package/dist/api/trpc/generated-cap-mounts.js +2 -1
  5. package/dist/api/trpc/generated-cap-routers.js +1848 -1839
  6. package/dist/boot/boot-config.js +1 -1
  7. package/dist/core/addon/addon-package.service.js +3 -105
  8. package/dist/core/addon-bridge/addon-bridge.service.js +1 -5
  9. package/dist/launcher.js +12 -124
  10. package/package.json +21 -17
  11. package/system/dist/addon-runner.js +1 -2
  12. package/system/dist/addon-runner.mjs +1 -2
  13. package/system/dist/{agent-https-B1XLr4nm.js → agent-https-BMmfwElS.js} +1 -1
  14. package/system/dist/{agent-https-BsedJhrb.mjs → agent-https-BXB7X23w.mjs} +1 -1
  15. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.js +1 -1
  16. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.mjs +1 -1
  17. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.js +1 -1
  18. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.mjs +1 -1
  19. package/system/dist/builtins/alerts/alerts.addon.js +1 -1
  20. package/system/dist/builtins/alerts/alerts.addon.mjs +1 -1
  21. package/system/dist/builtins/autotrack/index.js +1 -1
  22. package/system/dist/builtins/autotrack/index.mjs +1 -1
  23. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.js +2 -2
  24. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.mjs +2 -2
  25. package/system/dist/builtins/calendars/calendars.addon.js +1 -1
  26. package/system/dist/builtins/calendars/calendars.addon.mjs +1 -1
  27. package/system/dist/builtins/camera-grid/index.js +1 -1
  28. package/system/dist/builtins/camera-grid/index.mjs +1 -1
  29. package/system/dist/builtins/composer/composer.addon.js +3 -3
  30. package/system/dist/builtins/composer/composer.addon.mjs +3 -3
  31. package/system/dist/builtins/console-logging/index.js +1 -1
  32. package/system/dist/builtins/console-logging/index.mjs +1 -1
  33. package/system/dist/builtins/core-blocks/core-blocks.addon.js +2 -2
  34. package/system/dist/builtins/core-blocks/core-blocks.addon.mjs +2 -2
  35. package/system/dist/builtins/device-history/device-history.addon.d.ts +4 -0
  36. package/system/dist/builtins/device-history/device-history.addon.js +769 -17
  37. package/system/dist/builtins/device-history/device-history.addon.mjs +769 -17
  38. package/system/dist/builtins/device-history/runs/device-runs-provider.d.ts +7 -0
  39. package/system/dist/builtins/device-history/runs/device-runs-record-kinds.d.ts +15 -0
  40. package/system/dist/builtins/device-history/runs/device-runs-service.d.ts +42 -0
  41. package/system/dist/builtins/device-history/runs/energy-from-history.d.ts +22 -0
  42. package/system/dist/builtins/device-history/runs/run-recorder.d.ts +111 -0
  43. package/system/dist/builtins/device-history/runs/slice-readers.d.ts +9 -0
  44. package/system/dist/builtins/device-manager/device-manager.addon.js +1 -1
  45. package/system/dist/builtins/device-manager/device-manager.addon.mjs +1 -1
  46. package/system/dist/builtins/hub-forwarder/index.js +1 -1
  47. package/system/dist/builtins/hub-forwarder/index.mjs +1 -1
  48. package/system/dist/builtins/keychain/index.js +47 -38
  49. package/system/dist/builtins/keychain/index.mjs +47 -38
  50. package/system/dist/builtins/keychain/key-sources.d.ts +12 -7
  51. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.js +1 -1
  52. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.mjs +1 -1
  53. package/system/dist/builtins/local-auth/local-auth.addon.js +3 -3
  54. package/system/dist/builtins/local-auth/local-auth.addon.mjs +3 -3
  55. package/system/dist/builtins/local-network/local-network.addon.js +2 -2
  56. package/system/dist/builtins/local-network/local-network.addon.mjs +2 -2
  57. package/system/dist/builtins/loki-logging/index.js +1 -1
  58. package/system/dist/builtins/loki-logging/index.mjs +1 -1
  59. package/system/dist/builtins/native-metrics/native-metrics.addon.js +1 -1
  60. package/system/dist/builtins/native-metrics/native-metrics.addon.mjs +1 -1
  61. package/system/dist/builtins/platform-probe/index.js +1 -1
  62. package/system/dist/builtins/platform-probe/index.mjs +1 -1
  63. package/system/dist/builtins/record-entries/index.js +1 -1
  64. package/system/dist/builtins/record-entries/index.mjs +1 -1
  65. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.js +1 -1
  66. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.mjs +1 -1
  67. package/system/dist/builtins/snapshot/index.js +1 -1
  68. package/system/dist/builtins/snapshot/index.mjs +1 -1
  69. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.js +1 -1
  70. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.mjs +1 -1
  71. package/system/dist/builtins/sqlite-storage/index.js +1 -1
  72. package/system/dist/builtins/sqlite-storage/index.mjs +1 -1
  73. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.js +2 -2
  74. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.mjs +2 -2
  75. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.js +1 -1
  76. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.mjs +1 -1
  77. package/system/dist/builtins/system-config/system-config.addon.js +3 -3
  78. package/system/dist/builtins/system-config/system-config.addon.mjs +284 -284
  79. package/system/dist/builtins/winston-logging/index.js +1 -1
  80. package/system/dist/builtins/winston-logging/index.mjs +1 -1
  81. package/system/dist/{composition-sources-BjuQ3xot.mjs → composition-sources-BCfgVe9V.mjs} +1 -1
  82. package/system/dist/{composition-sources-C5r8i46e.js → composition-sources-D6b0p8Hl.js} +1 -1
  83. package/system/dist/{constants-GnxjCxT3.mjs → constants-BQLyzulL.mjs} +1 -1
  84. package/system/dist/{constants-Bh5wQoTg.js → constants-ePrW9DMj.js} +1 -1
  85. package/system/dist/{device-ca-OWEYAYaG.mjs → device-ca-C8X1AGHU.mjs} +2 -2
  86. package/system/dist/{device-ca-oM-nuINR.js → device-ca-Dh9wjg_e.js} +2 -2
  87. package/system/dist/{dist-B9xpybTG.js → dist-D-7p7cJp.js} +198 -35
  88. package/system/dist/{dist-Cw8KtuQY.mjs → dist-XvOCXwnA.mjs} +187 -36
  89. package/system/dist/file-host-worker.js +1 -1
  90. package/system/dist/file-host-worker.mjs +1 -1
  91. package/system/dist/{hub-mdns-ciao-BPENkOKX.js → hub-mdns-ciao-BFZZAJIx.js} +2 -2
  92. package/system/dist/{hub-mdns-ciao-C3qMZFP0.mjs → hub-mdns-ciao-CGwz5__T.mjs} +2 -2
  93. package/system/dist/index.js +40 -186
  94. package/system/dist/index.mjs +41 -185
  95. package/system/dist/kernel/addon-installer.d.ts +9 -60
  96. package/system/dist/kernel/bootstrap-config.d.ts +3 -1
  97. package/system/dist/kernel/config-schema.d.ts +2 -11
  98. package/system/dist/kernel/fs-utils.d.ts +0 -6
  99. package/system/dist/kernel/index.d.ts +2 -3
  100. package/system/dist/{restore-archive-BiN1yKZV.js → restore-archive-3e5X8g6h.js} +1 -1
  101. package/system/dist/{restore-archive-DJv5ATV8.mjs → restore-archive-B3M3ZwAl.mjs} +82 -82
  102. package/system/dist/{retention-DQje-V4I.mjs → retention-BPxZj_Qf.mjs} +1 -1
  103. package/system/dist/{retention-BT7TgsUn.js → retention-DacNjIXz.js} +1 -1
  104. package/system/dist/{wal-maintenance-DM08Htuy.mjs → wal-maintenance-C4K7pX1x.mjs} +0 -0
  105. package/system/dist/{wal-maintenance-BLwgOIXb.js → wal-maintenance-Dguwwx4N.js} +0 -0
  106. package/system/package.json +5 -2
  107. package/system/dist/kernel/workspace-detect.d.ts +0 -9
@@ -1,5 +1,6 @@
1
- import { Jn as deviceRemovalHookCapability, Kn as deviceHistoryCapability, Ms as EventCategory, Qa as BaseAddon, R as DEVICE_HISTORY_ENERGY_KEY, Za as wattMillisecondsToKwh, Zo as historyUnitFor, ns as isReadingQuantity, nt as HISTORY_CATALOG, qo as emitReadiness, rn as armRemovalReconcile, rt as HISTORY_ITEM_CATALOG } from "../../dist-Cw8KtuQY.mjs";
2
- import { S as subjectIdOf, _ as readUnit, a as FIVE_MINUTES_MS, b as SeriesRegistry, c as bucketEndOf, d as CAP_KEY_PREFIX, f as CaptureEngine, g as readPath, h as catalogMetrics, i as DAY_MS, l as bucketStartOf, m as capSeriesKey, n as RetentionJob, o as HOUR_MS, p as capItemSeriesKey, r as DepartureTracker, s as ROLLUP_GRACE_MS, t as DEFAULT_RETENTION, u as floorTo, v as DeviceDirectory, x as identityOf, y as isRealDeviceType } from "../../retention-DQje-V4I.mjs";
1
+ import { $a as wattMillisecondsToKwh, $o as historyUnitFor, K as DeviceRunSchema, Ms as DeviceType, Ps as EventCategory, R as DEVICE_HISTORY_ENERGY_KEY, Xn as deviceRunsCapability, Yn as deviceRemovalHookCapability, Yo as emitReadiness, eo as BaseAddon, in as armRemovalReconcile, is as isReadingQuantity, it as HISTORY_ITEM_CATALOG, qn as deviceHistoryCapability, qo as defineRecordKinds, rt as HISTORY_CATALOG } from "../../dist-XvOCXwnA.mjs";
2
+ import { S as subjectIdOf, _ as readUnit, a as FIVE_MINUTES_MS, b as SeriesRegistry, c as bucketEndOf, d as CAP_KEY_PREFIX, f as CaptureEngine, g as readPath, h as catalogMetrics, i as DAY_MS, l as bucketStartOf, m as capSeriesKey, n as RetentionJob, o as HOUR_MS, p as capItemSeriesKey, r as DepartureTracker, s as ROLLUP_GRACE_MS, t as DEFAULT_RETENTION, u as floorTo, v as DeviceDirectory, x as identityOf, y as isRealDeviceType } from "../../retention-BPxZj_Qf.mjs";
3
+ import { randomUUID } from "node:crypto";
3
4
  //#region src/builtins/device-history/capture/point-writer.ts
4
5
  var FLUSH_INTERVAL_MS = 1e4;
5
6
  var MAX_BUFFER_AGE_MS = 6e4;
@@ -479,7 +480,7 @@ function bounded(newestFirst, maxPoints) {
479
480
  overflow
480
481
  };
481
482
  }
482
- function errorText(err) {
483
+ function errorText$1(err) {
483
484
  return err instanceof Error ? err.message : String(err);
484
485
  }
485
486
  var HistoryQuery = class {
@@ -544,7 +545,7 @@ var HistoryQuery = class {
544
545
  } catch (err) {
545
546
  out.push({
546
547
  ok: false,
547
- error: errorText(err)
548
+ error: errorText$1(err)
548
549
  });
549
550
  }
550
551
  }
@@ -2594,6 +2595,688 @@ var HistoryRuntime = class {
2594
2595
  }
2595
2596
  };
2596
2597
  //#endregion
2598
+ //#region src/builtins/device-history/runs/device-runs-provider.ts
2599
+ /** `device_outcome` index: deviceId, outcome (equality), then the start as the range. */
2600
+ function outcomeWhere(deviceId, outcome, window) {
2601
+ const range = {
2602
+ ...window.atFrom !== void 0 ? { gte: window.atFrom } : {},
2603
+ ...window.atTo !== void 0 ? { lt: window.atTo } : {}
2604
+ };
2605
+ return {
2606
+ deviceId,
2607
+ outcome,
2608
+ ...Object.keys(range).length > 0 ? { startedAt: range } : {}
2609
+ };
2610
+ }
2611
+ function createDeviceRunsProvider(runs) {
2612
+ return {
2613
+ listRuns: async (input) => {
2614
+ const paging = {
2615
+ desc: true,
2616
+ limit: input.limit,
2617
+ ...input.cursor !== void 0 ? { cursor: input.cursor } : {}
2618
+ };
2619
+ const page = input.outcome === void 0 ? await runs.query({
2620
+ deviceId: input.deviceId,
2621
+ ...input.atFrom !== void 0 ? { atFrom: input.atFrom } : {},
2622
+ ...input.atTo !== void 0 ? { atTo: input.atTo } : {},
2623
+ ...paging
2624
+ }) : await runs.query({
2625
+ where: outcomeWhere(input.deviceId, input.outcome, input),
2626
+ ...paging
2627
+ });
2628
+ return {
2629
+ runs: page.records.map((row) => row.data),
2630
+ nextCursor: page.nextCursor
2631
+ };
2632
+ },
2633
+ getRun: async ({ deviceId, runId }) => {
2634
+ const row = await runs.get(runId);
2635
+ return row !== null && row.data.deviceId === deviceId ? row.data : null;
2636
+ },
2637
+ getCurrentRun: async ({ deviceId }) => {
2638
+ return (await runs.query({
2639
+ where: {
2640
+ state: "open",
2641
+ deviceId
2642
+ },
2643
+ desc: true,
2644
+ limit: 1
2645
+ })).records[0]?.data ?? null;
2646
+ }
2647
+ };
2648
+ }
2649
+ var deviceRunsRecordKinds = defineRecordKinds({ "device-runs": {
2650
+ schema: DeviceRunSchema,
2651
+ class: "ledger",
2652
+ database: "events",
2653
+ writeTrigger: "a running-state flip opens (write-through) or closes a run; the boot reconcile closes or opens one the flips missed",
2654
+ device: "required",
2655
+ at: "required",
2656
+ indexes: [{
2657
+ name: "open",
2658
+ fields: ["state", "deviceId"]
2659
+ }, {
2660
+ name: "device_outcome",
2661
+ fields: [
2662
+ "deviceId",
2663
+ "outcome",
2664
+ "startedAt"
2665
+ ]
2666
+ }],
2667
+ retention: { maxRowsPerDevice: 500 },
2668
+ deviceRemoval: "delete"
2669
+ } });
2670
+ //#endregion
2671
+ //#region src/builtins/device-history/runs/slice-readers.ts
2672
+ function numberField(slice, key) {
2673
+ const value = slice?.[key];
2674
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
2675
+ }
2676
+ function stringField(slice, key) {
2677
+ const value = slice?.[key];
2678
+ return typeof value === "string" && value.length > 0 ? value : null;
2679
+ }
2680
+ function booleanField(slice, key) {
2681
+ const value = slice?.[key];
2682
+ return typeof value === "boolean" ? value : null;
2683
+ }
2684
+ function isSlice(value) {
2685
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2686
+ }
2687
+ var MAX_POINTS = 5e3;
2688
+ /** kWh over `[from, to]`, or `null` when the series cannot say (no meter, no points, too short). */
2689
+ async function energyKwhFromHistory(query, deviceId, from, to) {
2690
+ if (to - from < 6e5) return null;
2691
+ const result = await query({
2692
+ key: DEVICE_HISTORY_ENERGY_KEY,
2693
+ subject: {
2694
+ kind: "device",
2695
+ deviceId
2696
+ },
2697
+ from,
2698
+ to,
2699
+ resolution: "5m",
2700
+ maxPoints: MAX_POINTS
2701
+ });
2702
+ if (result.truncated) return null;
2703
+ let total = 0;
2704
+ let seen = false;
2705
+ for (const series of result.series) for (const point of series.points) {
2706
+ if (point.delta === null || point.t < from - 5 * 6e4 || point.t > to) continue;
2707
+ total += point.delta;
2708
+ seen = true;
2709
+ }
2710
+ return seen ? total : null;
2711
+ }
2712
+ //#endregion
2713
+ //#region src/builtins/device-history/runs/run-recorder.ts
2714
+ /**
2715
+ * The run recorder (D992): turns the `running-state` flips of a device into one
2716
+ * durable `device-runs` row per run.
2717
+ *
2718
+ * - open: `running` false -> true writes the OPEN row through, so a run that
2719
+ * outlives this process is on disk from its first instant;
2720
+ * - close: true -> false closes it, with the energy of the run and its outcome;
2721
+ * - boot reconcile: the open rows are compared with the live snapshots - a
2722
+ * device still running keeps its row, one that stopped while nobody watched
2723
+ * closes `unknown`, one running with no row opens late. A run is never
2724
+ * duplicated: a device has at most one open run, in the mirror and on disk.
2725
+ *
2726
+ * Nothing one-shot gates on a fallible read (D49): a failed load or snapshot
2727
+ * read changes nothing and the next pass tries again; events that arrive before
2728
+ * the first answered load wait in a bounded buffer and replay after it.
2729
+ *
2730
+ * Energy comes from device-history's own data: the meter counter at open minus
2731
+ * the counter at close, else the stored history of the window. Both unknown is
2732
+ * `null` - never `0`.
2733
+ */
2734
+ var RUNNING_STATE_CAP = "running-state";
2735
+ var POWER_METER_CAP = "power-meter";
2736
+ /** Events held before the first answered load; beyond it the oldest are dropped, counted and logged. */
2737
+ var MAX_BUFFERED_EVENTS = 2e3;
2738
+ var RECORDER_TICK_MS = 6e4;
2739
+ var APPLIANCE_TYPES = new Set([
2740
+ DeviceType.Washer,
2741
+ DeviceType.Dryer,
2742
+ DeviceType.Dishwasher
2743
+ ]);
2744
+ function runIdOf(deviceId, startedAt) {
2745
+ return `${deviceId}:${startedAt}`;
2746
+ }
2747
+ function errorText(err) {
2748
+ return err instanceof Error ? err.message : String(err);
2749
+ }
2750
+ function applianceDetailOf(run) {
2751
+ return run.detail;
2752
+ }
2753
+ var RunRecorder = class {
2754
+ deps;
2755
+ open = /* @__PURE__ */ new Map();
2756
+ lastEnergy = /* @__PURE__ */ new Map();
2757
+ lastPower = /* @__PURE__ */ new Map();
2758
+ lastDishwasher = /* @__PURE__ */ new Map();
2759
+ chains = /* @__PURE__ */ new Map();
2760
+ buffered = [];
2761
+ loaded = false;
2762
+ droppedWhileBuffering = 0;
2763
+ ticks = 0;
2764
+ constructor(deps) {
2765
+ this.deps = deps;
2766
+ }
2767
+ /**
2768
+ * One minute of the owner's clock: retry the load until it answers, then
2769
+ * compare against the snapshots every {@link RECONCILE_EVERY_TICKS} and save
2770
+ * the open totals every {@link FLUSH_EVERY_TICKS}.
2771
+ */
2772
+ async tick() {
2773
+ this.ticks += 1;
2774
+ if (!this.loaded || this.ticks % 5 === 0) await this.reconcile();
2775
+ if (this.ticks % 5 === 0) await this.flushOpen();
2776
+ }
2777
+ /** Has a load of the open rows ANSWERED? Until then flips are buffered. */
2778
+ isLoaded() {
2779
+ return this.loaded;
2780
+ }
2781
+ /** Resolves when every queued flip has been handled (specs, shutdown). */
2782
+ async idle() {
2783
+ await Promise.all([...this.chains.values()]);
2784
+ }
2785
+ /** The open run of a device, from the mirror. */
2786
+ openRunOf(deviceId) {
2787
+ return this.open.get(deviceId)?.run ?? null;
2788
+ }
2789
+ /** Feed one `DeviceStateChanged` slice. Never throws; a failure is logged with the device. */
2790
+ handleState(deviceId, capName, slice, at) {
2791
+ if (capName !== "running-state" && capName !== "power-meter" && capName !== "dishwasher") return;
2792
+ if (!this.loaded) {
2793
+ this.buffer({
2794
+ deviceId,
2795
+ capName,
2796
+ slice,
2797
+ at
2798
+ });
2799
+ return;
2800
+ }
2801
+ this.enqueue(deviceId, () => this.apply(deviceId, capName, slice, at));
2802
+ }
2803
+ buffer(entry) {
2804
+ this.buffered.push(entry);
2805
+ if (this.buffered.length > 2e3) {
2806
+ this.buffered = this.buffered.slice(this.buffered.length - MAX_BUFFERED_EVENTS);
2807
+ this.droppedWhileBuffering += 1;
2808
+ }
2809
+ }
2810
+ enqueue(deviceId, work) {
2811
+ const next = (this.chains.get(deviceId) ?? Promise.resolve()).then(work).catch((err) => {
2812
+ this.deps.logger.warn("device-runs: a flip could not be recorded", {
2813
+ tags: { deviceId },
2814
+ meta: { error: errorText(err) }
2815
+ });
2816
+ }).finally(() => {
2817
+ if (this.chains.get(deviceId) === next) this.chains.delete(deviceId);
2818
+ });
2819
+ this.chains.set(deviceId, next);
2820
+ return next;
2821
+ }
2822
+ async apply(deviceId, capName, slice, at) {
2823
+ if (capName === "power-meter") {
2824
+ this.notePower(deviceId, slice, at);
2825
+ return;
2826
+ }
2827
+ if (capName === "dishwasher") {
2828
+ this.lastDishwasher.set(deviceId, slice);
2829
+ return;
2830
+ }
2831
+ const type = await this.deps.deviceTypeOf(deviceId);
2832
+ if (type === void 0 || !APPLIANCE_TYPES.has(type)) return;
2833
+ const running = booleanField(slice, "running");
2834
+ if (running === null) return;
2835
+ const held = this.open.get(deviceId);
2836
+ const since = numberField(slice, "since") ?? at;
2837
+ if (running && held === void 0) await this.openRun(deviceId, since, "running-state", slice, at);
2838
+ else if (!running && held !== void 0) await this.closeRun(deviceId, held, since, "running-state", slice);
2839
+ else if (running && held !== void 0) this.notePhase(held, slice, at);
2840
+ }
2841
+ notePower(deviceId, slice, at) {
2842
+ const energy = numberField(slice, "energy");
2843
+ if (energy !== null) this.lastEnergy.set(deviceId, energy);
2844
+ const power = numberField(slice, "power");
2845
+ if (power !== null) this.lastPower.set(deviceId, power);
2846
+ const held = this.open.get(deviceId);
2847
+ if (held === void 0 || power === null) return;
2848
+ this.accrue(held.power, at);
2849
+ held.power.lastW = power;
2850
+ held.power.peakW = held.power.peakW === null ? power : Math.max(held.power.peakW, power);
2851
+ held.dirty = true;
2852
+ }
2853
+ /** Close the interval since the previous reading at the watts it held. */
2854
+ accrue(acc, to) {
2855
+ if (acc.lastW !== null && to > acc.lastAt) {
2856
+ const ms = to - acc.lastAt;
2857
+ acc.weightedWms += acc.lastW * ms;
2858
+ acc.observedMs += ms;
2859
+ }
2860
+ acc.lastAt = Math.max(acc.lastAt, to);
2861
+ }
2862
+ powerOf(open) {
2863
+ const { power } = open;
2864
+ return {
2865
+ peakW: power.peakW,
2866
+ avgW: power.observedMs > 0 ? power.weightedWms / power.observedMs : null,
2867
+ observedMs: power.observedMs
2868
+ };
2869
+ }
2870
+ async energyNow(deviceId) {
2871
+ const seen = this.lastEnergy.get(deviceId);
2872
+ if (seen !== void 0) return seen;
2873
+ try {
2874
+ return numberField(await this.deps.readCapSlice(deviceId, POWER_METER_CAP), "energy");
2875
+ } catch (err) {
2876
+ this.deps.logger.warn("device-runs: the meter could not be read", {
2877
+ tags: { deviceId },
2878
+ meta: { error: errorText(err) }
2879
+ });
2880
+ return null;
2881
+ }
2882
+ }
2883
+ async measureEnergy(deviceId, detail, startedAt, endedAt) {
2884
+ const end = await this.energyNow(deviceId);
2885
+ if (detail.energyStartKwh !== null && end !== null && end >= detail.energyStartKwh) return {
2886
+ kwh: end - detail.energyStartKwh,
2887
+ method: "counter-delta"
2888
+ };
2889
+ if (endedAt - startedAt >= 6e5) try {
2890
+ const kwh = await this.deps.energyFromHistory(deviceId, startedAt, endedAt);
2891
+ if (kwh !== null) return {
2892
+ kwh,
2893
+ method: "history-integral"
2894
+ };
2895
+ } catch (err) {
2896
+ this.deps.logger.warn("device-runs: the stored energy could not be read", {
2897
+ tags: { deviceId },
2898
+ meta: { error: errorText(err) }
2899
+ });
2900
+ }
2901
+ return {
2902
+ kwh: null,
2903
+ method: null
2904
+ };
2905
+ }
2906
+ notePhase(open, slice, at) {
2907
+ const phase = stringField(slice, "phase");
2908
+ if (phase === null) return;
2909
+ if (open.run.phases[open.run.phases.length - 1]?.phase === phase) return;
2910
+ open.run = {
2911
+ ...open.run,
2912
+ phases: [...open.run.phases, {
2913
+ phase,
2914
+ at
2915
+ }]
2916
+ };
2917
+ open.dirty = true;
2918
+ }
2919
+ async openRun(deviceId, startedAt, source, slice, now, energyStartKwh) {
2920
+ const dishwasher = this.lastDishwasher.get(deviceId) ?? null;
2921
+ const phase = stringField(slice, "phase");
2922
+ const sliceSource = stringField(slice, "source");
2923
+ const power = this.lastPower.get(deviceId);
2924
+ const detail = {
2925
+ kind: "appliance",
2926
+ energyKwh: null,
2927
+ energyMethod: null,
2928
+ peakW: power ?? null,
2929
+ avgW: null,
2930
+ program: stringField(dishwasher, "program"),
2931
+ remainingAtStartSec: numberField(dishwasher, "remaining"),
2932
+ finalPhase: null,
2933
+ energyStartKwh: energyStartKwh !== void 0 ? energyStartKwh : await this.energyNow(deviceId),
2934
+ powerObservedMs: 0
2935
+ };
2936
+ const run = {
2937
+ runId: runIdOf(deviceId, startedAt),
2938
+ deviceId,
2939
+ kind: "appliance",
2940
+ state: "open",
2941
+ startedAt,
2942
+ endedAt: null,
2943
+ durationMs: null,
2944
+ outcome: null,
2945
+ startSource: source,
2946
+ endSource: null,
2947
+ runningSource: sliceSource === "native" || sliceSource === "assigned" ? sliceSource : null,
2948
+ phases: phase === null ? [] : [{
2949
+ phase,
2950
+ at: startedAt
2951
+ }],
2952
+ detail
2953
+ };
2954
+ await this.deps.runs.put({
2955
+ id: run.runId,
2956
+ deviceId,
2957
+ at: startedAt,
2958
+ data: run
2959
+ });
2960
+ this.open.set(deviceId, {
2961
+ run,
2962
+ dirty: false,
2963
+ power: {
2964
+ lastAt: Math.max(startedAt, now),
2965
+ lastW: power ?? null,
2966
+ weightedWms: 0,
2967
+ observedMs: 0,
2968
+ peakW: power ?? null
2969
+ }
2970
+ });
2971
+ this.deps.logger.info("device-runs: a run opened", {
2972
+ tags: { deviceId },
2973
+ meta: {
2974
+ runId: run.runId,
2975
+ source
2976
+ }
2977
+ });
2978
+ this.announce(EventCategory.DeviceRunOpened, run);
2979
+ }
2980
+ async closeRun(deviceId, held, rawEndedAt, source, slice) {
2981
+ const { run } = held;
2982
+ const endedAt = Math.max(rawEndedAt, run.startedAt);
2983
+ this.accrue(held.power, endedAt);
2984
+ const measured = this.powerOf(held);
2985
+ const detail = applianceDetailOf(run);
2986
+ const energy = await this.measureEnergy(deviceId, detail, run.startedAt, endedAt);
2987
+ const phase = stringField(slice, "phase");
2988
+ const phases = phase !== null && run.phases[run.phases.length - 1]?.phase !== phase ? [...run.phases, {
2989
+ phase,
2990
+ at: endedAt
2991
+ }] : run.phases;
2992
+ const durationMs = endedAt - run.startedAt;
2993
+ const closed = {
2994
+ ...run,
2995
+ state: "closed",
2996
+ endedAt,
2997
+ durationMs,
2998
+ outcome: this.outcomeOf(deviceId, source, durationMs, phases.map((p) => p.phase)),
2999
+ endSource: source,
3000
+ phases,
3001
+ detail: {
3002
+ ...detail,
3003
+ energyKwh: energy.kwh,
3004
+ energyMethod: energy.method,
3005
+ peakW: measured.peakW,
3006
+ avgW: measured.avgW,
3007
+ powerObservedMs: measured.observedMs,
3008
+ finalPhase: phases[phases.length - 1]?.phase ?? null
3009
+ }
3010
+ };
3011
+ await this.deps.runs.put({
3012
+ id: closed.runId,
3013
+ deviceId,
3014
+ at: closed.startedAt,
3015
+ data: closed
3016
+ });
3017
+ this.open.delete(deviceId);
3018
+ this.deps.logger.info("device-runs: a run closed", {
3019
+ tags: { deviceId },
3020
+ meta: {
3021
+ runId: closed.runId,
3022
+ outcome: closed.outcome,
3023
+ durationMs,
3024
+ energyKwh: energy.kwh,
3025
+ energyMethod: energy.method,
3026
+ source
3027
+ }
3028
+ });
3029
+ this.announce(EventCategory.DeviceRunClosed, closed);
3030
+ }
3031
+ outcomeOf(deviceId, source, durationMs, phases) {
3032
+ if (source === "reconcile") return "unknown";
3033
+ if (stringField(this.lastDishwasher.get(deviceId) ?? null, "state") === "error") return "error";
3034
+ const finished = phases.some((p) => /finish/i.test(p));
3035
+ return durationMs < 12e4 && !finished ? "aborted" : "completed";
3036
+ }
3037
+ announce(category, run) {
3038
+ try {
3039
+ this.deps.emit(category, run);
3040
+ } catch (err) {
3041
+ this.deps.logger.warn("device-runs: the run event was not emitted", {
3042
+ tags: { deviceId: run.deviceId },
3043
+ meta: {
3044
+ category,
3045
+ error: errorText(err)
3046
+ }
3047
+ });
3048
+ }
3049
+ }
3050
+ /**
3051
+ * Write the power totals of every open run (a crash then loses at most one
3052
+ * interval of peak/mean, never the run). Timer-driven; a failed write leaves
3053
+ * the run dirty for the next pass.
3054
+ */
3055
+ async flushOpen() {
3056
+ const now = this.deps.clock();
3057
+ for (const [deviceId, held] of this.open) {
3058
+ if (!held.dirty) continue;
3059
+ this.accrue(held.power, now);
3060
+ const measured = this.powerOf(held);
3061
+ try {
3062
+ await this.deps.runs.patch(held.run.runId, {
3063
+ phases: held.run.phases,
3064
+ detail: {
3065
+ peakW: measured.peakW,
3066
+ avgW: measured.avgW,
3067
+ powerObservedMs: measured.observedMs
3068
+ }
3069
+ });
3070
+ held.dirty = false;
3071
+ } catch (err) {
3072
+ this.deps.logger.warn("device-runs: the open run totals were not saved", {
3073
+ tags: { deviceId },
3074
+ meta: {
3075
+ runId: held.run.runId,
3076
+ error: errorText(err)
3077
+ }
3078
+ });
3079
+ }
3080
+ }
3081
+ }
3082
+ /**
3083
+ * Compare the open rows on disk with the live snapshots. Returns `false` when
3084
+ * either read failed - nothing changed and the caller tries again (D49).
3085
+ * Only the FIRST answered pass reads the rows (the mirror is the truth after
3086
+ * it) and replays the flips buffered while it was pending; later passes
3087
+ * compare the mirror with the snapshots, so a row read a moment before a
3088
+ * close can never bring a closed run back.
3089
+ */
3090
+ async reconcile() {
3091
+ let rows = [];
3092
+ let snapshots;
3093
+ try {
3094
+ if (!this.loaded) rows = await this.loadOpenRows();
3095
+ snapshots = await this.deps.readSnapshots();
3096
+ } catch (err) {
3097
+ this.deps.logger.warn("device-runs: reconcile read failed - nothing changed", { meta: { error: errorText(err) } });
3098
+ return false;
3099
+ }
3100
+ await this.settleAgainst(rows, snapshots);
3101
+ if (!this.loaded) {
3102
+ this.loaded = true;
3103
+ const replay = this.buffered;
3104
+ this.buffered = [];
3105
+ if (this.droppedWhileBuffering > 0) {
3106
+ this.deps.logger.warn("device-runs: flips were dropped while the load was pending", { meta: { dropped: this.droppedWhileBuffering } });
3107
+ this.droppedWhileBuffering = 0;
3108
+ }
3109
+ for (const entry of replay) this.handleState(entry.deviceId, entry.capName, entry.slice, entry.at);
3110
+ }
3111
+ return true;
3112
+ }
3113
+ async loadOpenRows() {
3114
+ const out = [];
3115
+ let cursor;
3116
+ do {
3117
+ const page = await this.deps.runs.query({
3118
+ where: { state: "open" },
3119
+ limit: 500,
3120
+ ...cursor !== void 0 ? { cursor } : {}
3121
+ });
3122
+ for (const row of page.records) out.push(row.data);
3123
+ cursor = page.nextCursor ?? void 0;
3124
+ } while (cursor !== void 0);
3125
+ return out;
3126
+ }
3127
+ async settleAgainst(rows, snapshots) {
3128
+ const now = this.deps.clock();
3129
+ const newest = /* @__PURE__ */ new Map();
3130
+ for (const row of rows.toSorted((a, b) => a.startedAt - b.startedAt)) {
3131
+ const earlier = newest.get(row.deviceId);
3132
+ if (earlier !== void 0) await this.exclusive(earlier.deviceId, async () => {
3133
+ await this.closeRun(earlier.deviceId, this.adopt(earlier), now, "reconcile", {});
3134
+ });
3135
+ newest.set(row.deviceId, row);
3136
+ }
3137
+ for (const row of newest.values()) await this.exclusive(row.deviceId, async () => {
3138
+ this.seedPower(row.deviceId, snapshots[String(row.deviceId)]?.[POWER_METER_CAP]);
3139
+ const held = this.adopt(row);
3140
+ const slice = runningSliceOf(snapshots, row.deviceId);
3141
+ if (booleanField(slice, "running") !== false) return;
3142
+ const since = numberField(slice, "since");
3143
+ await this.closeRun(row.deviceId, held, since !== null && since > row.startedAt ? since : now, "reconcile", slice ?? {});
3144
+ });
3145
+ await this.settleMirror(snapshots, now);
3146
+ await this.openLate(snapshots, now);
3147
+ }
3148
+ /** A mirrored run whose device now says it stopped closes `unknown` (a later pass, flips missed). */
3149
+ async settleMirror(snapshots, now) {
3150
+ for (const [deviceId, held] of [...this.open]) {
3151
+ const slice = runningSliceOf(snapshots, deviceId);
3152
+ if (booleanField(slice, "running") !== false) continue;
3153
+ const since = numberField(slice, "since");
3154
+ await this.exclusive(deviceId, async () => {
3155
+ const current = this.open.get(deviceId);
3156
+ if (current === void 0 || current.run.runId !== held.run.runId) return;
3157
+ await this.closeRun(deviceId, current, since !== null && since > held.run.startedAt ? since : now, "reconcile", slice ?? {});
3158
+ });
3159
+ }
3160
+ }
3161
+ /** A device running with no open run: open it late, from its own `since`. */
3162
+ async openLate(snapshots, now) {
3163
+ for (const [key, caps] of Object.entries(snapshots)) {
3164
+ const deviceId = Number(key);
3165
+ if (!Number.isInteger(deviceId)) continue;
3166
+ const slice = caps[RUNNING_STATE_CAP];
3167
+ if (!isSlice(slice) || booleanField(slice, "running") !== true) continue;
3168
+ await this.exclusive(deviceId, async () => {
3169
+ if (this.open.has(deviceId)) return;
3170
+ const type = await this.deps.deviceTypeOf(deviceId);
3171
+ if (type === void 0 || !APPLIANCE_TYPES.has(type)) return;
3172
+ this.seedPower(deviceId, caps[POWER_METER_CAP]);
3173
+ await this.openRun(deviceId, numberField(slice, "since") ?? now, "reconcile", slice, now, null);
3174
+ });
3175
+ }
3176
+ }
3177
+ /** One device at a time; a failure is logged with the device and never aborts the pass. */
3178
+ exclusive(deviceId, work) {
3179
+ return this.enqueue(deviceId, work);
3180
+ }
3181
+ seedPower(deviceId, slice) {
3182
+ if (!isSlice(slice)) return;
3183
+ const energy = numberField(slice, "energy");
3184
+ if (energy !== null && !this.lastEnergy.has(deviceId)) this.lastEnergy.set(deviceId, energy);
3185
+ const power = numberField(slice, "power");
3186
+ if (power !== null && !this.lastPower.has(deviceId)) this.lastPower.set(deviceId, power);
3187
+ }
3188
+ /** Put a stored open row back in the mirror, its power totals resumed from the row. */
3189
+ adopt(row) {
3190
+ const existing = this.open.get(row.deviceId);
3191
+ if (existing !== void 0) return existing;
3192
+ const detail = applianceDetailOf(row);
3193
+ const held = {
3194
+ run: row,
3195
+ dirty: false,
3196
+ power: {
3197
+ lastAt: this.deps.clock(),
3198
+ lastW: this.lastPower.get(row.deviceId) ?? null,
3199
+ weightedWms: (detail.avgW ?? 0) * detail.powerObservedMs,
3200
+ observedMs: detail.powerObservedMs,
3201
+ peakW: detail.peakW
3202
+ }
3203
+ };
3204
+ this.open.set(row.deviceId, held);
3205
+ return held;
3206
+ }
3207
+ };
3208
+ function runningSliceOf(snapshots, deviceId) {
3209
+ const slice = snapshots[String(deviceId)]?.[RUNNING_STATE_CAP];
3210
+ return isSlice(slice) ? slice : null;
3211
+ }
3212
+ //#endregion
3213
+ //#region src/builtins/device-history/runs/device-runs-service.ts
3214
+ var DeviceRunsService = class {
3215
+ deps;
3216
+ recorder = null;
3217
+ handle = null;
3218
+ timer = null;
3219
+ provider = null;
3220
+ constructor(deps) {
3221
+ this.deps = deps;
3222
+ }
3223
+ /** Declare the kind, then the first reconcile; an unanswered one is retried by the timer. */
3224
+ async open() {
3225
+ await this.deps.records.declare(deviceRunsRecordKinds);
3226
+ const handle = this.deps.records.kind(deviceRunsRecordKinds["device-runs"]);
3227
+ this.handle = handle;
3228
+ const recorder = new RunRecorder({
3229
+ ...this.deps,
3230
+ runs: handle
3231
+ });
3232
+ this.recorder = recorder;
3233
+ this.provider = createDeviceRunsProvider(handle);
3234
+ await recorder.reconcile();
3235
+ return { provider: this.provider };
3236
+ }
3237
+ startTimer() {
3238
+ const recorder = this.recorder;
3239
+ if (recorder === null || this.timer !== null) return;
3240
+ const timer = setInterval(() => {
3241
+ recorder.tick().catch((err) => {
3242
+ this.deps.logger.warn("device-runs: scheduled pass threw", { meta: { error: err instanceof Error ? err.message : String(err) } });
3243
+ });
3244
+ }, RECORDER_TICK_MS);
3245
+ timer.unref();
3246
+ this.timer = timer;
3247
+ }
3248
+ handleState(deviceId, capName, slice, at) {
3249
+ this.recorder?.handleState(deviceId, capName, slice, at);
3250
+ }
3251
+ async stop() {
3252
+ if (this.timer !== null) clearInterval(this.timer);
3253
+ this.timer = null;
3254
+ const recorder = this.recorder;
3255
+ if (recorder === null) return;
3256
+ await recorder.idle();
3257
+ await recorder.flushOpen();
3258
+ }
3259
+ /** The D865 hook body: how many run rows the removal deleted. */
3260
+ async removeDevice(deviceId) {
3261
+ return (await this.deps.records.deleteDevice(deviceId, { kinds: ["device-runs"] }))["device-runs"] ?? 0;
3262
+ }
3263
+ /** Run rows per device, for the admin clean-up listing. */
3264
+ async countByDevice() {
3265
+ const handle = this.handle;
3266
+ if (handle === null) return [];
3267
+ const rows = await handle.aggregate({
3268
+ op: "count",
3269
+ groupBy: "deviceId"
3270
+ });
3271
+ const out = [];
3272
+ for (const row of rows) if (typeof row.group === "number" && row.value !== null) out.push({
3273
+ deviceId: row.group,
3274
+ count: row.value
3275
+ });
3276
+ return out;
3277
+ }
3278
+ };
3279
+ //#endregion
2597
3280
  //#region src/builtins/device-history/device-history.addon.ts
2598
3281
  /**
2599
3282
  * device-history — the ONE mechanism for numeric history (D850). Hub-only, its
@@ -2638,6 +3321,8 @@ var DeviceHistoryAddon = class extends BaseAddon {
2638
3321
  runtime = null;
2639
3322
  unsubscribe = null;
2640
3323
  removalHook = null;
3324
+ runsProvider = null;
3325
+ runs = null;
2641
3326
  /** This instance's readiness generation (the base class keeps its own private). */
2642
3327
  readinessGeneration = `device-history-${Date.now().toString(36)}`;
2643
3328
  constructor() {
@@ -2653,7 +3338,11 @@ var DeviceHistoryAddon = class extends BaseAddon {
2653
3338
  if (ctx === null) return;
2654
3339
  const raw = ctx.kernel?.localNodeId ?? "hub";
2655
3340
  const nodeId = raw.includes("/") ? raw.split("/")[0] ?? raw : raw;
2656
- for (const capName of [deviceHistoryCapability.name, deviceRemovalHookCapability.name]) try {
3341
+ for (const capName of [
3342
+ deviceHistoryCapability.name,
3343
+ deviceRunsCapability.name,
3344
+ deviceRemovalHookCapability.name
3345
+ ]) try {
2657
3346
  emitReadiness(ctx.eventBus, {
2658
3347
  capName,
2659
3348
  scope: {
@@ -2698,6 +3387,10 @@ var DeviceHistoryAddon = class extends BaseAddon {
2698
3387
  if (this.runtime === null) throw new Error("device-history is starting — the history store is not open yet");
2699
3388
  return this.runtime;
2700
3389
  }
3390
+ requireRuns() {
3391
+ if (this.runsProvider === null) throw new Error("device-runs is starting — the run ledger is not open yet");
3392
+ return this.runsProvider;
3393
+ }
2701
3394
  async onInitialize() {
2702
3395
  const provider = {
2703
3396
  listSeries: async (input) => this.requireRuntime().query.listSeries({
@@ -2732,34 +3425,57 @@ var DeviceHistoryAddon = class extends BaseAddon {
2732
3425
  listOrphanSeries: async () => this.requireRuntime().listOrphans(),
2733
3426
  deleteOrphanSeries: async (input) => ({ results: await this.requireRuntime().deleteOrphans(input.seriesIds) })
2734
3427
  };
3428
+ const runsFacade = {
3429
+ listRuns: async (input) => this.requireRuns().listRuns(input),
3430
+ getRun: async (input) => this.requireRuns().getRun(input),
3431
+ getCurrentRun: async (input) => this.requireRuns().getCurrentRun(input)
3432
+ };
2735
3433
  this.emitStoreReadiness("starting");
2736
3434
  this.ctx.logger.info("Initialized — device-history provider registered (store opens on hub link)");
2737
3435
  const removalHook = {
2738
3436
  onDeviceRemoved: async (input) => {
2739
3437
  const { series } = await this.requireRuntime().removeDevice(input.deviceId);
2740
- if (series > 0) this.ctx.logger.info("device-history: removed the history of a deleted device", {
3438
+ const deviceRuns = await this.runs?.removeDevice(input.deviceId) ?? 0;
3439
+ if (series > 0 || deviceRuns > 0) this.ctx.logger.info("device-history: removed the history of a deleted device", {
2741
3440
  tags: { deviceId: input.deviceId },
2742
3441
  meta: {
2743
- counts: { series },
3442
+ counts: {
3443
+ series,
3444
+ deviceRuns
3445
+ },
2744
3446
  deletedAt: input.deletedAt
2745
3447
  }
2746
3448
  });
2747
- return { counts: { series } };
3449
+ return { counts: {
3450
+ series,
3451
+ deviceRuns
3452
+ } };
2748
3453
  },
2749
- listDeviceData: async () => [...this.requireRuntime().seriesByDevice()].map(([deviceId, count]) => ({
3454
+ listDeviceData: async () => [...[...this.requireRuntime().seriesByDevice()].map(([deviceId, count]) => ({
2750
3455
  store: "series",
2751
3456
  deviceId,
2752
3457
  count
2753
- }))
3458
+ })), ...(await this.runs?.countByDevice() ?? []).map(({ deviceId, count }) => ({
3459
+ store: "runs",
3460
+ deviceId,
3461
+ count
3462
+ }))]
2754
3463
  };
2755
3464
  this.removalHook = removalHook;
2756
- return [{
2757
- capability: deviceHistoryCapability,
2758
- provider
2759
- }, {
2760
- capability: deviceRemovalHookCapability,
2761
- provider: removalHook
2762
- }];
3465
+ return [
3466
+ {
3467
+ capability: deviceHistoryCapability,
3468
+ provider
3469
+ },
3470
+ {
3471
+ capability: deviceRunsCapability,
3472
+ provider: runsFacade
3473
+ },
3474
+ {
3475
+ capability: deviceRemovalHookCapability,
3476
+ provider: removalHook
3477
+ }
3478
+ ];
2763
3479
  }
2764
3480
  async onHubReachable() {
2765
3481
  const api = this.ctx.api;
@@ -2797,6 +3513,10 @@ var DeviceHistoryAddon = class extends BaseAddon {
2797
3513
  clock: () => Date.now()
2798
3514
  });
2799
3515
  await runtime.prepare();
3516
+ const runs = this.openRuns(runtime);
3517
+ const runsOpened = await runs.open();
3518
+ this.runsProvider = runsOpened.provider;
3519
+ this.runs = runs;
2800
3520
  this.unsubscribe = this.ctx.eventBus.subscribe({ category: EventCategory.DeviceStateChanged }, (event) => {
2801
3521
  const data = event.data;
2802
3522
  if (!isRecord(data)) return;
@@ -2804,11 +3524,13 @@ var DeviceHistoryAddon = class extends BaseAddon {
2804
3524
  if (typeof deviceId !== "number" || typeof capName !== "string" || !isRecord(slice)) return;
2805
3525
  const at = event.timestamp instanceof Date ? event.timestamp.getTime() : Date.now();
2806
3526
  runtime.capture.handleState(deviceId, capName, slice, at);
3527
+ runs.handleState(deviceId, capName, slice, at);
2807
3528
  });
2808
3529
  this.ctx.addDisposer(async () => this.stopRuntime());
2809
3530
  this.runtime = runtime;
2810
3531
  await runtime.finishBoot();
2811
3532
  runtime.startTimers();
3533
+ runs.startTimer();
2812
3534
  const removalHook = this.removalHook;
2813
3535
  if (removalHook !== null) this.ctx.addDisposer(armRemovalReconcile({
2814
3536
  api: this.ctx.api,
@@ -2821,15 +3543,45 @@ var DeviceHistoryAddon = class extends BaseAddon {
2821
3543
  metrics: runtime.status().metrics
2822
3544
  } });
2823
3545
  }
3546
+ openRuns(runtime) {
3547
+ const { ctx } = this;
3548
+ const records = ctx.records;
3549
+ if (records === void 0) throw new Error("device-history needs ctx.records on the hub for the run ledger");
3550
+ return new DeviceRunsService({
3551
+ records,
3552
+ readSnapshots: async () => ctx.api.deviceState.getAllSnapshots.query({}),
3553
+ readCapSlice: (deviceId, capName) => ctx.api.deviceState.getCapSlice.query({
3554
+ deviceId,
3555
+ capName
3556
+ }),
3557
+ deviceTypeOf: (deviceId) => runtime.directory.ensure(deviceId),
3558
+ energyFromHistory: (deviceId, from, to) => energyKwhFromHistory((query) => runtime.query.query(query), deviceId, from, to),
3559
+ emit: (category, run) => ctx.eventBus.emit({
3560
+ id: randomUUID(),
3561
+ timestamp: /* @__PURE__ */ new Date(),
3562
+ source: {
3563
+ type: "device",
3564
+ id: run.deviceId
3565
+ },
3566
+ category,
3567
+ data: run
3568
+ }),
3569
+ logger: ctx.logger,
3570
+ clock: () => Date.now()
3571
+ });
3572
+ }
2824
3573
  async stopRuntime() {
2825
3574
  this.unsubscribe?.();
2826
3575
  this.unsubscribe = null;
3576
+ await this.runs?.stop();
2827
3577
  await this.runtime?.stop();
2828
3578
  }
2829
3579
  async onShutdown() {
2830
3580
  this.emitStoreReadiness("down");
2831
3581
  await this.stopRuntime();
2832
3582
  this.runtime = null;
3583
+ this.runs = null;
3584
+ this.runsProvider = null;
2833
3585
  }
2834
3586
  globalSettingsSchema() {
2835
3587
  return this.schema({ sections: [{