@camstack/server 1.2.752 → 1.2.753

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 (90) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/dist/api/trpc/generated-cap-routers.js +10 -0
  3. package/dist/core/moleculer/moleculer.service.js +13 -1
  4. package/package.json +11 -8
  5. package/system/dist/{agent-https-Oc0Go3Gs.js → agent-https-B0bjQVfy.js} +1 -1
  6. package/system/dist/{agent-https-DoGV9jKg.mjs → agent-https-cxghRfum.mjs} +1 -1
  7. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.js +1 -1
  8. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.mjs +1 -1
  9. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.js +1 -1
  10. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.mjs +1 -1
  11. package/system/dist/builtins/alerts/alerts.addon.js +1 -1
  12. package/system/dist/builtins/alerts/alerts.addon.mjs +1 -1
  13. package/system/dist/builtins/autotrack/index.js +1 -1
  14. package/system/dist/builtins/autotrack/index.mjs +1 -1
  15. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.js +2 -2
  16. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.mjs +2 -2
  17. package/system/dist/builtins/calendars/calendars.addon.js +1 -1
  18. package/system/dist/builtins/calendars/calendars.addon.mjs +1 -1
  19. package/system/dist/builtins/camera-grid/index.js +1 -1
  20. package/system/dist/builtins/camera-grid/index.mjs +1 -1
  21. package/system/dist/builtins/composer/composer.addon.js +18 -22
  22. package/system/dist/builtins/composer/composer.addon.mjs +17 -21
  23. package/system/dist/builtins/console-logging/index.js +1 -1
  24. package/system/dist/builtins/console-logging/index.mjs +1 -1
  25. package/system/dist/builtins/core-blocks/composition-api.d.ts +4 -1
  26. package/system/dist/builtins/core-blocks/core-blocks.addon.js +232 -15
  27. package/system/dist/builtins/core-blocks/core-blocks.addon.mjs +232 -15
  28. package/system/dist/builtins/core-blocks/running-proposal.d.ts +32 -0
  29. package/system/dist/builtins/device-history/device-history.addon.js +24 -23
  30. package/system/dist/builtins/device-history/device-history.addon.mjs +3 -2
  31. package/system/dist/builtins/device-manager/device-manager.addon.js +1 -1
  32. package/system/dist/builtins/device-manager/device-manager.addon.mjs +1 -1
  33. package/system/dist/builtins/hub-forwarder/index.js +1 -1
  34. package/system/dist/builtins/hub-forwarder/index.mjs +1 -1
  35. package/system/dist/builtins/keychain/index.js +3 -3
  36. package/system/dist/builtins/keychain/index.mjs +3 -3
  37. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.js +1 -1
  38. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.mjs +1 -1
  39. package/system/dist/builtins/local-auth/local-auth.addon.js +2 -2
  40. package/system/dist/builtins/local-auth/local-auth.addon.mjs +2 -2
  41. package/system/dist/builtins/local-network/local-network.addon.js +2 -2
  42. package/system/dist/builtins/local-network/local-network.addon.mjs +2 -2
  43. package/system/dist/builtins/loki-logging/index.js +1 -1
  44. package/system/dist/builtins/loki-logging/index.mjs +1 -1
  45. package/system/dist/builtins/native-metrics/native-metrics.addon.js +1 -1
  46. package/system/dist/builtins/native-metrics/native-metrics.addon.mjs +1 -1
  47. package/system/dist/builtins/platform-probe/index.js +1 -1
  48. package/system/dist/builtins/platform-probe/index.mjs +1 -1
  49. package/system/dist/builtins/record-entries/index.js +1 -1
  50. package/system/dist/builtins/record-entries/index.mjs +1 -1
  51. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.js +1 -1
  52. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.mjs +1 -1
  53. package/system/dist/builtins/snapshot/index.js +5 -1
  54. package/system/dist/builtins/snapshot/index.mjs +5 -1
  55. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.js +1 -1
  56. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.mjs +1 -1
  57. package/system/dist/builtins/sqlite-storage/index.js +1 -1
  58. package/system/dist/builtins/sqlite-storage/index.mjs +1 -1
  59. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.js +2 -2
  60. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.mjs +2 -2
  61. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.js +1 -1
  62. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.mjs +1 -1
  63. package/system/dist/builtins/system-config/system-config.addon.js +3 -3
  64. package/system/dist/builtins/system-config/system-config.addon.mjs +284 -284
  65. package/system/dist/builtins/winston-logging/index.js +1 -1
  66. package/system/dist/builtins/winston-logging/index.mjs +1 -1
  67. package/system/dist/{retention-C-lijsmN.mjs → capture-engine-CfJdhMTH.mjs} +2 -246
  68. package/system/dist/{retention-WjI-Op7G.js → capture-engine-eRAebXP1.js} +1 -305
  69. package/system/dist/{composition-sources-Bxahhz4f.js → composition-sources-BvDYLpw_.js} +1 -1
  70. package/system/dist/{composition-sources-CzRiSzCV.mjs → composition-sources-ChtkMq1Q.mjs} +1 -1
  71. package/system/dist/{constants-uI6uXyjP.mjs → constants-CYNsr0lM.mjs} +1 -1
  72. package/system/dist/{constants-0rC5QY6i.js → constants-DkC9-VOa.js} +1 -1
  73. package/system/dist/{device-ca-CL_Arugd.js → device-ca-BxInMpK2.js} +1 -1
  74. package/system/dist/{device-ca-D7TyMlsS.mjs → device-ca-CQg3PTnE.mjs} +1 -1
  75. package/system/dist/{dist-Iq3vrBOE.mjs → dist-C5eIFTMo.mjs} +752 -554
  76. package/system/dist/{dist-CYnRCUzN.js → dist-DFWnAzAY.js} +775 -553
  77. package/system/dist/file-host-worker.js +1 -1
  78. package/system/dist/file-host-worker.mjs +1 -1
  79. package/system/dist/{hub-mdns-ciao-CNLYSVyJ.js → hub-mdns-ciao-BQDdPkPO.js} +2 -2
  80. package/system/dist/{hub-mdns-ciao-CvMKderb.mjs → hub-mdns-ciao-DW_g42El.mjs} +2 -2
  81. package/system/dist/index.js +9 -8
  82. package/system/dist/index.mjs +9 -8
  83. package/system/dist/kernel/transport/parent-unowned-call.d.ts +10 -0
  84. package/system/dist/{restore-archive-vzWYLf6p.mjs → restore-archive-CFGGJCfV.mjs} +82 -82
  85. package/system/dist/{restore-archive-Dw04PiG5.js → restore-archive-DRjYgh6D.js} +1 -1
  86. package/system/dist/retention-B9l9TnGE.mjs +245 -0
  87. package/system/dist/retention-BNONb5X_.js +304 -0
  88. package/system/dist/{wal-maintenance-DQXiTaph.js → wal-maintenance-D0zSmIwJ.js} +0 -0
  89. package/system/dist/{wal-maintenance-BzTHorT2.mjs → wal-maintenance-xYk-FpJW.mjs} +0 -0
  90. package/system/package.json +1 -1
@@ -1,8 +1,9 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_chunk = require("../../chunk-Cek0wNdY.js");
3
- const require_dist = require("../../dist-CYnRCUzN.js");
3
+ const require_dist = require("../../dist-DFWnAzAY.js");
4
4
  const require_read_all_rows$1 = require("../../read-all-rows-CVoO1ONM.js");
5
- const require_composition_sources = require("../../composition-sources-Bxahhz4f.js");
5
+ const require_composition_sources = require("../../composition-sources-BvDYLpw_.js");
6
+ const require_capture_engine = require("../../capture-engine-eRAebXP1.js");
6
7
  const require_prefix_range = require("../../prefix-range-D_KueXbQ.js");
7
8
  const require_prefix_walk = require("../../prefix-walk-Dv6MLZlM.js");
8
9
  let zod = require("zod");
@@ -1899,6 +1900,34 @@ var CoreBlockStore = class CoreBlockStore {
1899
1900
  * refuses rather than guess, and the owner does not start.
1900
1901
  */
1901
1902
  var HELPER_TO_CUSTOMIZE_ID = "core-blocks/2026-11-03-helper-to-customize";
1903
+ /**
1904
+ * The documented read-only boundary (D1004 phase 5): the appliance and heater
1905
+ * helper templates are deleted from `@camstack/types`, but a stored block can
1906
+ * still carry their `helper` spec until this migration has run. These two
1907
+ * schemas READ that old shape and nothing else; no live code builds it.
1908
+ */
1909
+ var LegacyApplianceSchema = zod.z.object({
1910
+ kind: zod.z.literal("appliance"),
1911
+ thresholdWatts: zod.z.number(),
1912
+ startDwellMs: zod.z.number(),
1913
+ stopDwellMs: zod.z.number(),
1914
+ member: require_dist.HelperMemberSchema,
1915
+ powerSwitch: require_dist.HelperMemberSchema.optional()
1916
+ });
1917
+ var LegacyHeaterSchema = zod.z.object({
1918
+ kind: zod.z.literal("heater"),
1919
+ plug: require_dist.HelperMemberSchema,
1920
+ meter: require_dist.HelperMemberSchema.optional(),
1921
+ thresholdWatts: zod.z.number(),
1922
+ startDwellMs: zod.z.number(),
1923
+ stopDwellMs: zod.z.number()
1924
+ });
1925
+ var LegacyHelperSchema = zod.z.discriminatedUnion("kind", [LegacyApplianceSchema, LegacyHeaterSchema]);
1926
+ /** A stored block whose composition carries an appliance or heater `helper`, read raw. */
1927
+ var LegacyHelperBlockSchema = zod.z.looseObject({ source: zod.z.looseObject({
1928
+ kind: zod.z.literal("composition"),
1929
+ composition: zod.z.looseObject({ helper: LegacyHelperSchema })
1930
+ }) });
1902
1931
  /** The raw shape of a helper block, enough to refuse one the schema cannot read. */
1903
1932
  var RawHelperBlockSchema = zod.z.object({ source: zod.z.object({ composition: zod.z.object({ helper: zod.z.object({ kind: zod.z.enum(["appliance", "heater"]) }) }) }) });
1904
1933
  function refuse$1(blockId, why) {
@@ -2040,9 +2069,7 @@ function replacementsOf(blockId, composition, helper) {
2040
2069
  })
2041
2070
  };
2042
2071
  }
2043
- function rewriteComposition(blockId, composition) {
2044
- const helper = composition.helper;
2045
- if (helper === void 0 || helper.kind !== "appliance" && helper.kind !== "heater") return null;
2072
+ function rewriteComposition(blockId, composition, helper) {
2046
2073
  if (composition.target.kind !== "new") return refuse$1(blockId, "a helper that targets an existing device");
2047
2074
  const replacements = replacementsOf(blockId, composition, helper);
2048
2075
  const seen = /* @__PURE__ */ new Set();
@@ -2054,24 +2081,38 @@ function rewriteComposition(blockId, composition) {
2054
2081
  });
2055
2082
  const missing = Object.keys(replacements).filter((cap) => !seen.has(cap));
2056
2083
  if (missing.length > 0) return refuse$1(blockId, `no stored ${missing.join(", ")} feature to rewrite`);
2057
- const { helper: _helper, ...rest } = composition;
2058
2084
  const parsed = require_dist.CompositionSchema.safeParse({
2059
- ...rest,
2085
+ ...composition,
2060
2086
  features
2061
2087
  });
2062
2088
  if (!parsed.success) return refuse$1(blockId, `the rewritten composition is invalid: ${parsed.error.message}`);
2063
2089
  return parsed.data;
2064
2090
  }
2091
+ /** `null` when the row holds no appliance or heater helper; throws when it holds one it cannot read. */
2092
+ function legacyHelperOf(row) {
2093
+ if (!RawHelperBlockSchema.safeParse(row.data.block).success) return null;
2094
+ const envelope = LegacyHelperBlockSchema.safeParse(row.data.block);
2095
+ if (!envelope.success) return refuse$1(row.id, `the stored helper spec does not parse: ${envelope.error.message}`);
2096
+ const { helper, ...composition } = envelope.data.source.composition;
2097
+ return {
2098
+ helper,
2099
+ withoutHelper: {
2100
+ ...envelope.data,
2101
+ source: {
2102
+ ...envelope.data.source,
2103
+ composition
2104
+ }
2105
+ }
2106
+ };
2107
+ }
2065
2108
  function rewriteOf$1(row, ports) {
2066
- const parsed = require_dist.CoreBlockSchema.safeParse(row.data.block);
2067
- if (!parsed.success) {
2068
- if (RawHelperBlockSchema.safeParse(row.data.block).success) return refuse$1(row.id, `the stored block does not parse: ${parsed.error.message}`);
2069
- return null;
2070
- }
2109
+ const legacy = legacyHelperOf(row);
2110
+ if (legacy === null) return null;
2111
+ const parsed = require_dist.CoreBlockSchema.safeParse(legacy.withoutHelper);
2112
+ if (!parsed.success) return refuse$1(row.id, `the stored block does not parse: ${parsed.error.message}`);
2071
2113
  const block = parsed.data;
2072
- if (block.source === void 0 || block.source.kind !== "composition") return null;
2073
- const composition = rewriteComposition(row.id, block.source.composition);
2074
- if (composition === null) return null;
2114
+ if (block.source === void 0 || block.source.kind !== "composition") return refuse$1(row.id, "the helper block has no composition source");
2115
+ const composition = rewriteComposition(row.id, block.source.composition, legacy.helper);
2075
2116
  const updatedAt = Math.max(block.updatedAt + 1, ports.now());
2076
2117
  const next = require_dist.CoreBlockSchema.safeParse({
2077
2118
  ...block,
@@ -6736,6 +6777,167 @@ function storedPeers(blocks, targets, lookupCap, candidateBlockId) {
6736
6777
  };
6737
6778
  }
6738
6779
  //#endregion
6780
+ //#region src/builtins/core-blocks/running-proposal.ts
6781
+ /**
6782
+ * `proposeRunningThreshold` — read a SOURCE device's power history and hand it
6783
+ * to the pure algorithm in `@camstack/types` (planning#405).
6784
+ *
6785
+ * The slices are read newest first, one day of RAW at a time so a day never
6786
+ * exceeds the point cap; a truncated slice is dropped, not trusted. When the
6787
+ * raw tier keeps less than the minimum span, the 5-minute rollup answers instead
6788
+ * (its `max` stands for the bucket), and the algorithm caps the confidence.
6789
+ */
6790
+ /** The newest slices the proposal reads: a fortnight shows a weekly habit twice. */
6791
+ var LOOKBACK_MS = 14 * require_dist.DAY_MS;
6792
+ var QUERY_MAX_POINTS = 5e3;
6793
+ async function proposeForDevice(ports, request) {
6794
+ const key = require_capture_engine.capSeriesKey(request.cap, request.fieldPath);
6795
+ const now = ports.now();
6796
+ const info = (await ports.listSeries(request.deviceId)).find((s) => s.key === key);
6797
+ if (info === void 0) {
6798
+ ports.logger.info("running proposal: the device has no history for this field", {
6799
+ tags: { deviceId: request.deviceId },
6800
+ meta: { key }
6801
+ });
6802
+ return require_dist.proposeRunningThreshold(emptySeries(now));
6803
+ }
6804
+ if (info.kind !== "gauge") throw new Error(`core-blocks: ${key} is a ${info.kind} series — a running threshold needs a numeric gauge`);
6805
+ const retention = await ports.retention();
6806
+ const tier = retention.rawMs >= 864e5 ? "raw" : "5m";
6807
+ const keptMs = tier === "raw" ? retention.rawMs : retention.fiveMinuteMs;
6808
+ const from = Math.max(now - Math.min(LOOKBACK_MS, keptMs), info.firstTs);
6809
+ const read = tier === "raw" ? await readRawSlices(ports, request.deviceId, key, from, now) : await readFiveMinute(ports, request.deviceId, key, from, now);
6810
+ const answer = require_dist.proposeRunningThreshold(read);
6811
+ ports.logger.info(`running proposal: ${answer.state}`, {
6812
+ tags: { deviceId: request.deviceId },
6813
+ meta: {
6814
+ key,
6815
+ tier,
6816
+ points: read.points.length,
6817
+ truncated: read.truncated,
6818
+ ...request.deviceType === void 0 ? {} : { deviceType: request.deviceType },
6819
+ ...answer.state === "proposal" ? {
6820
+ confidence: answer.confidence,
6821
+ threshold: answer.transform.threshold
6822
+ } : { reason: answer.reason }
6823
+ }
6824
+ });
6825
+ return answer;
6826
+ }
6827
+ function emptySeries(now) {
6828
+ return {
6829
+ tier: "raw",
6830
+ from: now,
6831
+ to: now,
6832
+ truncated: false,
6833
+ before: null,
6834
+ points: []
6835
+ };
6836
+ }
6837
+ /** Day slices ending at `to`, newest first, none reaching before `from`. */
6838
+ function daySlices(from, to) {
6839
+ const out = [];
6840
+ for (let end = to; end > from; end -= require_dist.DAY_MS) out.push({
6841
+ from: Math.max(from, end - require_dist.DAY_MS),
6842
+ to: end
6843
+ });
6844
+ return out;
6845
+ }
6846
+ async function readRawSlices(ports, deviceId, key, from, to) {
6847
+ const points = [];
6848
+ let before = null;
6849
+ let reached = to;
6850
+ let truncated = false;
6851
+ for (const slice of daySlices(from, to)) {
6852
+ const result = await queryOrNull(ports, deviceId, {
6853
+ deviceId,
6854
+ key,
6855
+ from: slice.from,
6856
+ to: slice.to,
6857
+ resolution: "raw",
6858
+ maxPoints: QUERY_MAX_POINTS
6859
+ });
6860
+ if (result === null || result.truncated || result.resolution !== "raw") {
6861
+ truncated = reached === to;
6862
+ break;
6863
+ }
6864
+ const series = result.series[0];
6865
+ if (series === void 0) break;
6866
+ points.push(...series.points.map(rawStep));
6867
+ before = series.before === null ? null : {
6868
+ t: series.before.t,
6869
+ value: series.before.value
6870
+ };
6871
+ reached = slice.from;
6872
+ }
6873
+ return {
6874
+ tier: "raw",
6875
+ from: reached,
6876
+ to,
6877
+ truncated,
6878
+ before,
6879
+ points: points.sort((a, b) => a.t - b.t)
6880
+ };
6881
+ }
6882
+ async function readFiveMinute(ports, deviceId, key, from, to) {
6883
+ const result = await queryOrNull(ports, deviceId, {
6884
+ deviceId,
6885
+ key,
6886
+ from,
6887
+ to,
6888
+ resolution: "5m",
6889
+ maxPoints: QUERY_MAX_POINTS
6890
+ });
6891
+ const series = result?.series[0];
6892
+ if (result === null || series === void 0) return {
6893
+ tier: "5m",
6894
+ from,
6895
+ to,
6896
+ truncated: true,
6897
+ before: null,
6898
+ points: []
6899
+ };
6900
+ return {
6901
+ tier: "5m",
6902
+ from,
6903
+ to,
6904
+ truncated: result.truncated || result.resolution !== "5m",
6905
+ before: series.before === null ? null : {
6906
+ t: series.before.t,
6907
+ value: series.before.value
6908
+ },
6909
+ points: series.points.map(bucketStep)
6910
+ };
6911
+ }
6912
+ async function queryOrNull(ports, deviceId, input) {
6913
+ try {
6914
+ return await ports.query(input);
6915
+ } catch (err) {
6916
+ ports.logger.warn("running proposal: a history slice could not be read", {
6917
+ tags: { deviceId },
6918
+ meta: {
6919
+ from: input.from,
6920
+ to: input.to,
6921
+ error: require_dist.errMsg(err)
6922
+ }
6923
+ });
6924
+ return null;
6925
+ }
6926
+ }
6927
+ function rawStep(point) {
6928
+ return {
6929
+ t: point.t,
6930
+ value: point.last
6931
+ };
6932
+ }
6933
+ /** A rollup bucket stands for its peak: the highest reading is what says "running". */
6934
+ function bucketStep(point) {
6935
+ return {
6936
+ t: point.t,
6937
+ value: point.samples > 0 ? point.max : null
6938
+ };
6939
+ }
6940
+ //#endregion
6739
6941
  //#region src/builtins/core-blocks/composition-api.ts
6740
6942
  /**
6741
6943
  * The composition half of the `core-blocks` provider (D659). Flat methods,
@@ -6972,6 +7174,7 @@ function customizationOf(blocks, device) {
6972
7174
  function buildCompositionApi(deps) {
6973
7175
  const serialized = writeQueue();
6974
7176
  return {
7177
+ proposeRunningThreshold: (input) => proposeForDevice(deps.runningProposal, input),
6975
7178
  createComposition: ({ block, caller }) => serialized(async () => {
6976
7179
  const name = await nameOnCreate(deps, block);
6977
7180
  const judged = await validateAgainstStore(deps, block.composition, null);
@@ -7795,6 +7998,20 @@ var CoreBlocksAddon = class extends require_dist.BaseAddon {
7795
7998
  if (this.supervisor === null) return Promise.reject(/* @__PURE__ */ new Error("core-blocks: no block supervisor runs on this node — claims cannot be released"));
7796
7999
  return this.supervisor.convergeForClaims();
7797
8000
  },
8001
+ runningProposal: {
8002
+ listSeries: (deviceId) => requireApi().deviceHistory.listSeries.query({ deviceId }),
8003
+ query: (input) => requireApi().deviceHistory.query.query({
8004
+ deviceId: input.deviceId,
8005
+ key: input.key,
8006
+ from: input.from,
8007
+ to: input.to,
8008
+ resolution: input.resolution,
8009
+ maxPoints: input.maxPoints
8010
+ }),
8011
+ retention: async () => require_dist.historyRetentionFromSettings(await requireApi().addonSettingsRaw.getGlobal.query({ addonId: "device-history" })),
8012
+ now: () => Date.now(),
8013
+ logger: this.ctx.logger.child("running-proposal")
8014
+ },
7798
8015
  logger: this.ctx.logger.child("compositions"),
7799
8016
  capabilityDefinitions: require_dist.ALL_CAPABILITY_DEFINITIONS
7800
8017
  });
@@ -1,6 +1,7 @@
1
- import { $ as EMPTY_REMOTE_CONFIG, $t as TemplateKindSchema, Bi as remoteCapability, Bn as coreBlockComposition, Br as isInternalActionId, Bt as RunningStateStatusSchema, C as CORE_BLOCK_ADDON_PREFIX, Ci as occurrenceOn, Cs as hydrateSchema, Ct as MediaPlayerStatusSchema, D as ConditionMirror, Da as timedRunCapability, Ea as templateCapability, Fn as compileScalarOverride, Gr as kebabToCamel, Hi as replacedFieldKeys, Hn as coreBlockSourceKind, I as DEFAULT_HOLD_OVERRIDE, K as DeclaredDevices, Ki as resolveCoreBlockEntry, Kn as customKeyOfRole, Ks as resolveSecretMarkers, Mi as powerSourceLinkOfComposition, Mt as QuantityUnitError, Na as validateSchedulerInput, Nn as collectWhenMirrorSources, Ns as isSecretRefOwnedBy, O as ControlStatusSchema, Oa as timedRunLimitOf, On as capUnitResolver, Ot as PowerSourceInfoSchema, Pi as problemsBlockSave, Pt as REMOTE_MEDIA_COMMANDS, Q as EMPTY_REMOTE_ASSUMED_STATE, Qa as composedDeviceRef, Qt as SwitchStatusSchema, Ra as vocabActionIdFor, Rn as compositionSourceRefs, Rt as RemoteAssumedStateSchema, S as CORE_BLOCKS_ADDON_ID, Ua as CompositionSchema, Ui as resolveActionVariables, Un as coreBlocksCapability, Ut as SchedulerError, Va as zoneOnlySite, Vi as remoteLayoutComponentsCapability, Vn as coreBlockIdFromAddonId, Wt as SchedulerSchema, Ys as secretTreeFromSchema, Z as EMPTY_AUTOMATION_STATE, Zr as localDateOf, _i as normalizeCapStep, ac as DeviceType$1, an as actionsCapability, bn as buildActionSteps, bo as BaseAddon, c as ActionStepSchema, co as helperMembers, cs as collectSecretMarkerRefs, ea as resolveStepArgs, ec as transformSecretWrite, et as FAN_CAPTURE_FIELDS, f as AutomationStateDocSchema, fs as defineAddonMigrations, gi as normalizeActionUnits, hi as nextOccurrence, hs as defineRecordKinds, ia as schedulersCapability, in as actionSourceCapability, it as FanPresetSchema, ja as validateComposition, ji as powerSourceCapability, jn as checkTemplatePayload, jr as internalActionId, js as isSecretMarker, k as CoreBlockSchema, ka as timedRunSeconds, ki as planComposition, l as ActionTargetResolver, mr as evaluateWhenTree, mt as INTERNAL_ACTION_PREFIX, na as runSteps, nt as FanControlStatusSchema, o as ALL_CAPABILITY_DEFINITIONS, oc as errMsg$1, on as addonIdOfActionId, p as BUILTIN_REMOTE_COMPONENTS, pa as siteFor, pn as appendTrace, pt as IDLE_ACTION_STATUS, qi as resolveCoreBlockFiles, qn as customRole, rn as actionEffect, ro as compositionSourceKey, s as ActionError, sc as EventCategory$1, t as ACTION_TARGET_INVALIDATION_EVENTS, ti as lockDoorLinkOfComposition, tr as describeComposableCaps, u as ActionVariableSchema, vi as normalizeCoreBlockWrite, x as COMPOSER_RUNNER_ID, xn as buildCapabilityLookup, xr as fanPresetsCapability, yi as normalizeStepTargets, za as weekdayOfLocalDate, zn as coreBlockAddonId, zt as RemoteConfigSchema } from "../../dist-Iq3vrBOE.mjs";
1
+ import { $ as EMPTY_REMOTE_CONFIG, $s as secretTreeFromSchema, $t as SwitchStatusSchema, Aa as timedRunLimitOf, Ai as planComposition, Ba as vocabActionIdFor, Bn as coreBlockAddonId, Bt as RemoteConfigSchema, C as CORE_BLOCK_ADDON_PREFIX, Ct as MediaPlayerStatusSchema, D as ConditionMirror, Ds as hydrateSchema, Fa as validateSchedulerInput, Fi as problemsBlockSave, Fs as isSecretMarker, Ft as REMOTE_MEDIA_COMMANDS, Ga as CompositionSchema, Gi as resolveActionVariables, Gt as SchedulerSchema, Hi as remoteCapability, Hn as coreBlockIdFromAddonId, I as DEFAULT_HOLD_OVERRIDE, In as compileScalarOverride, Ji as resolveCoreBlockEntry, Jn as customRole, K as DeclaredDevices, Ka as DAY_MS, Kr as kebabToCamel, Li as proposeRunningThreshold, Ls as isSecretRefOwnedBy, Mi as powerSourceCapability, Mn as checkTemplatePayload, Mr as internalActionId, Na as validateComposition, Ni as powerSourceLinkOfComposition, Nt as QuantityUnitError, O as ControlStatusSchema, Oa as templateCapability, Pn as collectWhenMirrorSources, Q as EMPTY_REMOTE_ASSUMED_STATE, Qr as localDateOf, S as CORE_BLOCKS_ADDON_ID, Sn as buildCapabilityLookup, Sr as fanPresetsCapability, Ua as zoneOnlySite, Ui as remoteLayoutComponentsCapability, Un as coreBlockSourceKind, Va as weekdayOfLocalDate, Vn as coreBlockComposition, Vr as isInternalActionId, Vt as RunningStateStatusSchema, Wi as replacedFieldKeys, Wn as coreBlocksCapability, Wt as SchedulerError, Xs as resolveSecretMarkers, Yi as resolveCoreBlockFiles, Z as EMPTY_AUTOMATION_STATE, Za as HelperMemberSchema, _i as normalizeActionUnits, an as actionSourceCapability, bi as normalizeStepTargets, c as ActionStepSchema, dc as EventCategory$1, do as helperMembers, en as TemplateKindSchema, et as FAN_CAPTURE_FIELDS, f as AutomationStateDocSchema, fo as historyRetentionFromSettings, fs as collectSecretMarkerRefs, gi as nextOccurrence, gs as defineAddonMigrations, ha as siteFor, hr as evaluateWhenTree, ia as runSteps, ic as transformSecretWrite, in as actionEffect, it as FanPresetSchema, ja as timedRunSeconds, k as CoreBlockSchema, ka as timedRunCapability, kn as capUnitResolver, kt as PowerSourceInfoSchema, l as ActionTargetResolver, lc as DeviceType$1, mn as appendTrace, mt as INTERNAL_ACTION_PREFIX, na as resolveStepArgs, ni as lockDoorLinkOfComposition, nr as describeComposableCaps, nt as FanControlStatusSchema, o as ALL_CAPABILITY_DEFINITIONS, oa as schedulersCapability, on as actionsCapability, oo as compositionSourceKey, p as BUILTIN_REMOTE_COMPONENTS, pt as IDLE_ACTION_STATUS, qn as customKeyOfRole, s as ActionError, sn as addonIdOfActionId, t as ACTION_TARGET_INVALIDATION_EVENTS, to as composedDeviceRef, u as ActionVariableSchema, uc as errMsg$1, vi as normalizeCapStep, wi as occurrenceOn, wo as BaseAddon, x as COMPOSER_RUNNER_ID, xn as buildActionSteps, yi as normalizeCoreBlockWrite, ys as defineRecordKinds, zn as compositionSourceRefs, zt as RemoteAssumedStateSchema } from "../../dist-C5eIFTMo.mjs";
2
2
  import { t as require_read_all_rows } from "../../read-all-rows-TaPqdWNF.mjs";
3
- import { i as parseDeviceStateChanged, t as describeCompositionSources } from "../../composition-sources-CzRiSzCV.mjs";
3
+ import { i as parseDeviceStateChanged, t as describeCompositionSources } from "../../composition-sources-ChtkMq1Q.mjs";
4
+ import { i as capSeriesKey } from "../../capture-engine-CfJdhMTH.mjs";
4
5
  import { t as prefixRange } from "../../prefix-range-Dl0znowN.mjs";
5
6
  import { n as unwrapStoredValue, t as loadPrefixed } from "../../prefix-walk-DAOBSyH1.mjs";
6
7
  import { createRequire } from "node:module";
@@ -1893,6 +1894,34 @@ var CoreBlockStore = class CoreBlockStore {
1893
1894
  * refuses rather than guess, and the owner does not start.
1894
1895
  */
1895
1896
  var HELPER_TO_CUSTOMIZE_ID = "core-blocks/2026-11-03-helper-to-customize";
1897
+ /**
1898
+ * The documented read-only boundary (D1004 phase 5): the appliance and heater
1899
+ * helper templates are deleted from `@camstack/types`, but a stored block can
1900
+ * still carry their `helper` spec until this migration has run. These two
1901
+ * schemas READ that old shape and nothing else; no live code builds it.
1902
+ */
1903
+ var LegacyApplianceSchema = z.object({
1904
+ kind: z.literal("appliance"),
1905
+ thresholdWatts: z.number(),
1906
+ startDwellMs: z.number(),
1907
+ stopDwellMs: z.number(),
1908
+ member: HelperMemberSchema,
1909
+ powerSwitch: HelperMemberSchema.optional()
1910
+ });
1911
+ var LegacyHeaterSchema = z.object({
1912
+ kind: z.literal("heater"),
1913
+ plug: HelperMemberSchema,
1914
+ meter: HelperMemberSchema.optional(),
1915
+ thresholdWatts: z.number(),
1916
+ startDwellMs: z.number(),
1917
+ stopDwellMs: z.number()
1918
+ });
1919
+ var LegacyHelperSchema = z.discriminatedUnion("kind", [LegacyApplianceSchema, LegacyHeaterSchema]);
1920
+ /** A stored block whose composition carries an appliance or heater `helper`, read raw. */
1921
+ var LegacyHelperBlockSchema = z.looseObject({ source: z.looseObject({
1922
+ kind: z.literal("composition"),
1923
+ composition: z.looseObject({ helper: LegacyHelperSchema })
1924
+ }) });
1896
1925
  /** The raw shape of a helper block, enough to refuse one the schema cannot read. */
1897
1926
  var RawHelperBlockSchema = z.object({ source: z.object({ composition: z.object({ helper: z.object({ kind: z.enum(["appliance", "heater"]) }) }) }) });
1898
1927
  function refuse$1(blockId, why) {
@@ -2034,9 +2063,7 @@ function replacementsOf(blockId, composition, helper) {
2034
2063
  })
2035
2064
  };
2036
2065
  }
2037
- function rewriteComposition(blockId, composition) {
2038
- const helper = composition.helper;
2039
- if (helper === void 0 || helper.kind !== "appliance" && helper.kind !== "heater") return null;
2066
+ function rewriteComposition(blockId, composition, helper) {
2040
2067
  if (composition.target.kind !== "new") return refuse$1(blockId, "a helper that targets an existing device");
2041
2068
  const replacements = replacementsOf(blockId, composition, helper);
2042
2069
  const seen = /* @__PURE__ */ new Set();
@@ -2048,24 +2075,38 @@ function rewriteComposition(blockId, composition) {
2048
2075
  });
2049
2076
  const missing = Object.keys(replacements).filter((cap) => !seen.has(cap));
2050
2077
  if (missing.length > 0) return refuse$1(blockId, `no stored ${missing.join(", ")} feature to rewrite`);
2051
- const { helper: _helper, ...rest } = composition;
2052
2078
  const parsed = CompositionSchema.safeParse({
2053
- ...rest,
2079
+ ...composition,
2054
2080
  features
2055
2081
  });
2056
2082
  if (!parsed.success) return refuse$1(blockId, `the rewritten composition is invalid: ${parsed.error.message}`);
2057
2083
  return parsed.data;
2058
2084
  }
2085
+ /** `null` when the row holds no appliance or heater helper; throws when it holds one it cannot read. */
2086
+ function legacyHelperOf(row) {
2087
+ if (!RawHelperBlockSchema.safeParse(row.data.block).success) return null;
2088
+ const envelope = LegacyHelperBlockSchema.safeParse(row.data.block);
2089
+ if (!envelope.success) return refuse$1(row.id, `the stored helper spec does not parse: ${envelope.error.message}`);
2090
+ const { helper, ...composition } = envelope.data.source.composition;
2091
+ return {
2092
+ helper,
2093
+ withoutHelper: {
2094
+ ...envelope.data,
2095
+ source: {
2096
+ ...envelope.data.source,
2097
+ composition
2098
+ }
2099
+ }
2100
+ };
2101
+ }
2059
2102
  function rewriteOf$1(row, ports) {
2060
- const parsed = CoreBlockSchema.safeParse(row.data.block);
2061
- if (!parsed.success) {
2062
- if (RawHelperBlockSchema.safeParse(row.data.block).success) return refuse$1(row.id, `the stored block does not parse: ${parsed.error.message}`);
2063
- return null;
2064
- }
2103
+ const legacy = legacyHelperOf(row);
2104
+ if (legacy === null) return null;
2105
+ const parsed = CoreBlockSchema.safeParse(legacy.withoutHelper);
2106
+ if (!parsed.success) return refuse$1(row.id, `the stored block does not parse: ${parsed.error.message}`);
2065
2107
  const block = parsed.data;
2066
- if (block.source === void 0 || block.source.kind !== "composition") return null;
2067
- const composition = rewriteComposition(row.id, block.source.composition);
2068
- if (composition === null) return null;
2108
+ if (block.source === void 0 || block.source.kind !== "composition") return refuse$1(row.id, "the helper block has no composition source");
2109
+ const composition = rewriteComposition(row.id, block.source.composition, legacy.helper);
2069
2110
  const updatedAt = Math.max(block.updatedAt + 1, ports.now());
2070
2111
  const next = CoreBlockSchema.safeParse({
2071
2112
  ...block,
@@ -6730,6 +6771,167 @@ function storedPeers(blocks, targets, lookupCap, candidateBlockId) {
6730
6771
  };
6731
6772
  }
6732
6773
  //#endregion
6774
+ //#region src/builtins/core-blocks/running-proposal.ts
6775
+ /**
6776
+ * `proposeRunningThreshold` — read a SOURCE device's power history and hand it
6777
+ * to the pure algorithm in `@camstack/types` (planning#405).
6778
+ *
6779
+ * The slices are read newest first, one day of RAW at a time so a day never
6780
+ * exceeds the point cap; a truncated slice is dropped, not trusted. When the
6781
+ * raw tier keeps less than the minimum span, the 5-minute rollup answers instead
6782
+ * (its `max` stands for the bucket), and the algorithm caps the confidence.
6783
+ */
6784
+ /** The newest slices the proposal reads: a fortnight shows a weekly habit twice. */
6785
+ var LOOKBACK_MS = 14 * DAY_MS;
6786
+ var QUERY_MAX_POINTS = 5e3;
6787
+ async function proposeForDevice(ports, request) {
6788
+ const key = capSeriesKey(request.cap, request.fieldPath);
6789
+ const now = ports.now();
6790
+ const info = (await ports.listSeries(request.deviceId)).find((s) => s.key === key);
6791
+ if (info === void 0) {
6792
+ ports.logger.info("running proposal: the device has no history for this field", {
6793
+ tags: { deviceId: request.deviceId },
6794
+ meta: { key }
6795
+ });
6796
+ return proposeRunningThreshold(emptySeries(now));
6797
+ }
6798
+ if (info.kind !== "gauge") throw new Error(`core-blocks: ${key} is a ${info.kind} series — a running threshold needs a numeric gauge`);
6799
+ const retention = await ports.retention();
6800
+ const tier = retention.rawMs >= 864e5 ? "raw" : "5m";
6801
+ const keptMs = tier === "raw" ? retention.rawMs : retention.fiveMinuteMs;
6802
+ const from = Math.max(now - Math.min(LOOKBACK_MS, keptMs), info.firstTs);
6803
+ const read = tier === "raw" ? await readRawSlices(ports, request.deviceId, key, from, now) : await readFiveMinute(ports, request.deviceId, key, from, now);
6804
+ const answer = proposeRunningThreshold(read);
6805
+ ports.logger.info(`running proposal: ${answer.state}`, {
6806
+ tags: { deviceId: request.deviceId },
6807
+ meta: {
6808
+ key,
6809
+ tier,
6810
+ points: read.points.length,
6811
+ truncated: read.truncated,
6812
+ ...request.deviceType === void 0 ? {} : { deviceType: request.deviceType },
6813
+ ...answer.state === "proposal" ? {
6814
+ confidence: answer.confidence,
6815
+ threshold: answer.transform.threshold
6816
+ } : { reason: answer.reason }
6817
+ }
6818
+ });
6819
+ return answer;
6820
+ }
6821
+ function emptySeries(now) {
6822
+ return {
6823
+ tier: "raw",
6824
+ from: now,
6825
+ to: now,
6826
+ truncated: false,
6827
+ before: null,
6828
+ points: []
6829
+ };
6830
+ }
6831
+ /** Day slices ending at `to`, newest first, none reaching before `from`. */
6832
+ function daySlices(from, to) {
6833
+ const out = [];
6834
+ for (let end = to; end > from; end -= DAY_MS) out.push({
6835
+ from: Math.max(from, end - DAY_MS),
6836
+ to: end
6837
+ });
6838
+ return out;
6839
+ }
6840
+ async function readRawSlices(ports, deviceId, key, from, to) {
6841
+ const points = [];
6842
+ let before = null;
6843
+ let reached = to;
6844
+ let truncated = false;
6845
+ for (const slice of daySlices(from, to)) {
6846
+ const result = await queryOrNull(ports, deviceId, {
6847
+ deviceId,
6848
+ key,
6849
+ from: slice.from,
6850
+ to: slice.to,
6851
+ resolution: "raw",
6852
+ maxPoints: QUERY_MAX_POINTS
6853
+ });
6854
+ if (result === null || result.truncated || result.resolution !== "raw") {
6855
+ truncated = reached === to;
6856
+ break;
6857
+ }
6858
+ const series = result.series[0];
6859
+ if (series === void 0) break;
6860
+ points.push(...series.points.map(rawStep));
6861
+ before = series.before === null ? null : {
6862
+ t: series.before.t,
6863
+ value: series.before.value
6864
+ };
6865
+ reached = slice.from;
6866
+ }
6867
+ return {
6868
+ tier: "raw",
6869
+ from: reached,
6870
+ to,
6871
+ truncated,
6872
+ before,
6873
+ points: points.sort((a, b) => a.t - b.t)
6874
+ };
6875
+ }
6876
+ async function readFiveMinute(ports, deviceId, key, from, to) {
6877
+ const result = await queryOrNull(ports, deviceId, {
6878
+ deviceId,
6879
+ key,
6880
+ from,
6881
+ to,
6882
+ resolution: "5m",
6883
+ maxPoints: QUERY_MAX_POINTS
6884
+ });
6885
+ const series = result?.series[0];
6886
+ if (result === null || series === void 0) return {
6887
+ tier: "5m",
6888
+ from,
6889
+ to,
6890
+ truncated: true,
6891
+ before: null,
6892
+ points: []
6893
+ };
6894
+ return {
6895
+ tier: "5m",
6896
+ from,
6897
+ to,
6898
+ truncated: result.truncated || result.resolution !== "5m",
6899
+ before: series.before === null ? null : {
6900
+ t: series.before.t,
6901
+ value: series.before.value
6902
+ },
6903
+ points: series.points.map(bucketStep)
6904
+ };
6905
+ }
6906
+ async function queryOrNull(ports, deviceId, input) {
6907
+ try {
6908
+ return await ports.query(input);
6909
+ } catch (err) {
6910
+ ports.logger.warn("running proposal: a history slice could not be read", {
6911
+ tags: { deviceId },
6912
+ meta: {
6913
+ from: input.from,
6914
+ to: input.to,
6915
+ error: errMsg$1(err)
6916
+ }
6917
+ });
6918
+ return null;
6919
+ }
6920
+ }
6921
+ function rawStep(point) {
6922
+ return {
6923
+ t: point.t,
6924
+ value: point.last
6925
+ };
6926
+ }
6927
+ /** A rollup bucket stands for its peak: the highest reading is what says "running". */
6928
+ function bucketStep(point) {
6929
+ return {
6930
+ t: point.t,
6931
+ value: point.samples > 0 ? point.max : null
6932
+ };
6933
+ }
6934
+ //#endregion
6733
6935
  //#region src/builtins/core-blocks/composition-api.ts
6734
6936
  /**
6735
6937
  * The composition half of the `core-blocks` provider (D659). Flat methods,
@@ -6966,6 +7168,7 @@ function customizationOf(blocks, device) {
6966
7168
  function buildCompositionApi(deps) {
6967
7169
  const serialized = writeQueue();
6968
7170
  return {
7171
+ proposeRunningThreshold: (input) => proposeForDevice(deps.runningProposal, input),
6969
7172
  createComposition: ({ block, caller }) => serialized(async () => {
6970
7173
  const name = await nameOnCreate(deps, block);
6971
7174
  const judged = await validateAgainstStore(deps, block.composition, null);
@@ -7789,6 +7992,20 @@ var CoreBlocksAddon = class extends BaseAddon {
7789
7992
  if (this.supervisor === null) return Promise.reject(/* @__PURE__ */ new Error("core-blocks: no block supervisor runs on this node — claims cannot be released"));
7790
7993
  return this.supervisor.convergeForClaims();
7791
7994
  },
7995
+ runningProposal: {
7996
+ listSeries: (deviceId) => requireApi().deviceHistory.listSeries.query({ deviceId }),
7997
+ query: (input) => requireApi().deviceHistory.query.query({
7998
+ deviceId: input.deviceId,
7999
+ key: input.key,
8000
+ from: input.from,
8001
+ to: input.to,
8002
+ resolution: input.resolution,
8003
+ maxPoints: input.maxPoints
8004
+ }),
8005
+ retention: async () => historyRetentionFromSettings(await requireApi().addonSettingsRaw.getGlobal.query({ addonId: "device-history" })),
8006
+ now: () => Date.now(),
8007
+ logger: this.ctx.logger.child("running-proposal")
8008
+ },
7792
8009
  logger: this.ctx.logger.child("compositions"),
7793
8010
  capabilityDefinitions: ALL_CAPABILITY_DEFINITIONS
7794
8011
  });
@@ -0,0 +1,32 @@
1
+ /**
2
+ * `proposeRunningThreshold` — read a SOURCE device's power history and hand it
3
+ * to the pure algorithm in `@camstack/types` (planning#405).
4
+ *
5
+ * The slices are read newest first, one day of RAW at a time so a day never
6
+ * exceeds the point cap; a truncated slice is dropped, not trusted. When the
7
+ * raw tier keeps less than the minimum span, the 5-minute rollup answers instead
8
+ * (its `max` stands for the bucket), and the algorithm caps the confidence.
9
+ */
10
+ import { type DeviceHistoryQueryResult, type DeviceHistorySeriesInfo, type DeviceType, type HistoryRetention, type HistoryTier, type IScopedLogger, type RunningThresholdProposal } from "@camstack/types";
11
+ export interface ProposalHistoryQuery {
12
+ readonly deviceId: number;
13
+ readonly key: string;
14
+ readonly from: number;
15
+ readonly to: number;
16
+ readonly resolution: HistoryTier;
17
+ readonly maxPoints: number;
18
+ }
19
+ export interface RunningProposalPorts {
20
+ readonly listSeries: (deviceId: number) => Promise<readonly DeviceHistorySeriesInfo[]>;
21
+ readonly query: (input: ProposalHistoryQuery) => Promise<DeviceHistoryQueryResult>;
22
+ readonly retention: () => Promise<HistoryRetention>;
23
+ readonly now: () => number;
24
+ readonly logger: IScopedLogger;
25
+ }
26
+ export interface RunningProposalRequest {
27
+ readonly deviceId: number;
28
+ readonly cap: string;
29
+ readonly fieldPath: string;
30
+ readonly deviceType?: DeviceType;
31
+ }
32
+ export declare function proposeForDevice(ports: RunningProposalPorts, request: RunningProposalRequest): Promise<RunningThresholdProposal>;