@camstack/addon-provider-homematic 1.2.181 → 1.2.183

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.
package/dist/addon.js CHANGED
@@ -794,7 +794,7 @@ var EventCategory = /* @__PURE__ */ function(EventCategory) {
794
794
  return EventCategory;
795
795
  }({});
796
796
  //#endregion
797
- //#region ../types/dist/device-type-CfHw_quR.mjs
797
+ //#region ../types/dist/device-type-D1fH5kaC.mjs
798
798
  /**
799
799
  import { errMsg } from '@camstack/types'
800
800
  * Extract a human-readable message from an unknown error value.
@@ -1025,6 +1025,12 @@ var DeviceFeature = /* @__PURE__ */ function(DeviceFeature) {
1025
1025
  DeviceFeature["MediaPlayerPrevious"] = "media-player-previous";
1026
1026
  /** Media player exposes stop distinct from pause. */
1027
1027
  DeviceFeature["MediaPlayerStop"] = "media-player-stop";
1028
+ /** Media player exposes volume up / down in steps (an infrared TV has no level). */
1029
+ DeviceFeature["MediaPlayerVolumeStep"] = "media-player-volume-step";
1030
+ /** Media player exposes channel up / down in steps. */
1031
+ DeviceFeature["MediaPlayerChannelStep"] = "media-player-channel-step";
1032
+ /** Media player exposes power on / off. */
1033
+ DeviceFeature["MediaPlayerPower"] = "media-player-power";
1028
1034
  /** Alarm panel requires a PIN code on arm/disarm. */
1029
1035
  DeviceFeature["AlarmPinRequired"] = "alarm-pin-required";
1030
1036
  /** Presence device carries GPS coordinates (lat/lng/accuracy) in
@@ -4561,6 +4567,12 @@ var numberProcessor = (schema, ctx, _json, _params) => {
4561
4567
  var booleanProcessor = (_schema, _ctx, json, _params) => {
4562
4568
  json.type = "boolean";
4563
4569
  };
4570
+ var bigintProcessor = (_schema, ctx, _json, _params) => {
4571
+ if (ctx.unrepresentable === "throw") throw new Error("BigInt cannot be represented in JSON Schema");
4572
+ };
4573
+ var symbolProcessor = (_schema, ctx, _json, _params) => {
4574
+ if (ctx.unrepresentable === "throw") throw new Error("Symbols cannot be represented in JSON Schema");
4575
+ };
4564
4576
  var nullProcessor = (_schema, ctx, json, _params) => {
4565
4577
  if (ctx.target === "openapi-3.0") {
4566
4578
  json.type = "string";
@@ -4568,12 +4580,17 @@ var nullProcessor = (_schema, ctx, json, _params) => {
4568
4580
  json.enum = [null];
4569
4581
  } else json.type = "null";
4570
4582
  };
4583
+ var undefinedProcessor = (_schema, ctx, _json, _params) => {
4584
+ if (ctx.unrepresentable === "throw") throw new Error("Undefined cannot be represented in JSON Schema");
4585
+ };
4571
4586
  var voidProcessor = (_schema, ctx, _json, _params) => {
4572
4587
  if (ctx.unrepresentable === "throw") throw new Error("Void cannot be represented in JSON Schema");
4573
4588
  };
4574
4589
  var neverProcessor = (_schema, _ctx, json, _params) => {
4575
4590
  json.not = {};
4576
4591
  };
4592
+ var anyProcessor = (_schema, _ctx, _json, _params) => {};
4593
+ var unknownProcessor = (_schema, _ctx, _json, _params) => {};
4577
4594
  var dateProcessor = (_schema, ctx, _json, _params) => {
4578
4595
  if (ctx.unrepresentable === "throw") throw new Error("Date cannot be represented in JSON Schema");
4579
4596
  };
@@ -4605,12 +4622,53 @@ var literalProcessor = (schema, ctx, json, _params) => {
4605
4622
  json.enum = vals;
4606
4623
  }
4607
4624
  };
4625
+ var nanProcessor = (_schema, ctx, _json, _params) => {
4626
+ if (ctx.unrepresentable === "throw") throw new Error("NaN cannot be represented in JSON Schema");
4627
+ };
4628
+ var templateLiteralProcessor = (schema, _ctx, json, _params) => {
4629
+ const _json = json;
4630
+ const pattern = schema._zod.pattern;
4631
+ if (!pattern) throw new Error("Pattern not found in template literal");
4632
+ _json.type = "string";
4633
+ _json.pattern = pattern.source;
4634
+ };
4635
+ var fileProcessor = (schema, _ctx, json, _params) => {
4636
+ const _json = json;
4637
+ const file = {
4638
+ type: "string",
4639
+ format: "binary",
4640
+ contentEncoding: "binary"
4641
+ };
4642
+ const { minimum, maximum, mime } = schema._zod.bag;
4643
+ if (minimum !== void 0) file.minLength = minimum;
4644
+ if (maximum !== void 0) file.maxLength = maximum;
4645
+ if (mime) if (mime.length === 1) {
4646
+ file.contentMediaType = mime[0];
4647
+ Object.assign(_json, file);
4648
+ } else {
4649
+ Object.assign(_json, file);
4650
+ _json.anyOf = mime.map((m) => ({ contentMediaType: m }));
4651
+ }
4652
+ else Object.assign(_json, file);
4653
+ };
4654
+ var successProcessor = (_schema, _ctx, json, _params) => {
4655
+ json.type = "boolean";
4656
+ };
4608
4657
  var customProcessor = (_schema, ctx, _json, _params) => {
4609
4658
  if (ctx.unrepresentable === "throw") throw new Error("Custom types cannot be represented in JSON Schema");
4610
4659
  };
4660
+ var functionProcessor = (_schema, ctx, _json, _params) => {
4661
+ if (ctx.unrepresentable === "throw") throw new Error("Function types cannot be represented in JSON Schema");
4662
+ };
4611
4663
  var transformProcessor = (_schema, ctx, _json, _params) => {
4612
4664
  if (ctx.unrepresentable === "throw") throw new Error("Transforms cannot be represented in JSON Schema");
4613
4665
  };
4666
+ var mapProcessor = (_schema, ctx, _json, _params) => {
4667
+ if (ctx.unrepresentable === "throw") throw new Error("Map cannot be represented in JSON Schema");
4668
+ };
4669
+ var setProcessor = (_schema, ctx, _json, _params) => {
4670
+ if (ctx.unrepresentable === "throw") throw new Error("Set cannot be represented in JSON Schema");
4671
+ };
4614
4672
  var arrayProcessor = (schema, ctx, _json, params) => {
4615
4673
  const json = _json;
4616
4674
  const def = schema._zod.def;
@@ -4815,6 +4873,12 @@ var readonlyProcessor = (schema, ctx, json, params) => {
4815
4873
  seen.ref = def.innerType;
4816
4874
  json.readOnly = true;
4817
4875
  };
4876
+ var promiseProcessor = (schema, ctx, _json, params) => {
4877
+ const def = schema._zod.def;
4878
+ process$1(def.innerType, ctx, params);
4879
+ const seen = ctx.seen.get(schema);
4880
+ seen.ref = def.innerType;
4881
+ };
4818
4882
  var optionalProcessor = (schema, ctx, _json, params) => {
4819
4883
  const def = schema._zod.def;
4820
4884
  process$1(def.innerType, ctx, params);
@@ -4827,6 +4891,81 @@ var lazyProcessor = (schema, ctx, _json, params) => {
4827
4891
  const seen = ctx.seen.get(schema);
4828
4892
  seen.ref = innerType;
4829
4893
  };
4894
+ var allProcessors = {
4895
+ string: stringProcessor,
4896
+ number: numberProcessor,
4897
+ boolean: booleanProcessor,
4898
+ bigint: bigintProcessor,
4899
+ symbol: symbolProcessor,
4900
+ null: nullProcessor,
4901
+ undefined: undefinedProcessor,
4902
+ void: voidProcessor,
4903
+ never: neverProcessor,
4904
+ any: anyProcessor,
4905
+ unknown: unknownProcessor,
4906
+ date: dateProcessor,
4907
+ enum: enumProcessor,
4908
+ literal: literalProcessor,
4909
+ nan: nanProcessor,
4910
+ template_literal: templateLiteralProcessor,
4911
+ file: fileProcessor,
4912
+ success: successProcessor,
4913
+ custom: customProcessor,
4914
+ function: functionProcessor,
4915
+ transform: transformProcessor,
4916
+ map: mapProcessor,
4917
+ set: setProcessor,
4918
+ array: arrayProcessor,
4919
+ object: objectProcessor,
4920
+ union: unionProcessor,
4921
+ intersection: intersectionProcessor,
4922
+ tuple: tupleProcessor,
4923
+ record: recordProcessor,
4924
+ nullable: nullableProcessor,
4925
+ nonoptional: nonoptionalProcessor,
4926
+ default: defaultProcessor,
4927
+ prefault: prefaultProcessor,
4928
+ catch: catchProcessor,
4929
+ pipe: pipeProcessor,
4930
+ readonly: readonlyProcessor,
4931
+ promise: promiseProcessor,
4932
+ optional: optionalProcessor,
4933
+ lazy: lazyProcessor
4934
+ };
4935
+ function toJSONSchema(input, params) {
4936
+ if ("_idmap" in input) {
4937
+ const registry = input;
4938
+ const ctx = initializeContext({
4939
+ ...params,
4940
+ processors: allProcessors
4941
+ });
4942
+ const defs = {};
4943
+ for (const entry of registry._idmap.entries()) {
4944
+ const [_, schema] = entry;
4945
+ process$1(schema, ctx);
4946
+ }
4947
+ const schemas = {};
4948
+ ctx.external = {
4949
+ registry,
4950
+ uri: params?.uri,
4951
+ defs
4952
+ };
4953
+ for (const entry of registry._idmap.entries()) {
4954
+ const [key, schema] = entry;
4955
+ extractDefs(ctx, schema);
4956
+ schemas[key] = finalize(ctx, schema);
4957
+ }
4958
+ if (Object.keys(defs).length > 0) schemas.__shared = { [ctx.target === "draft-2020-12" ? "$defs" : "definitions"]: defs };
4959
+ return { schemas };
4960
+ }
4961
+ const ctx = initializeContext({
4962
+ ...params,
4963
+ processors: allProcessors
4964
+ });
4965
+ process$1(input, ctx);
4966
+ extractDefs(ctx, input);
4967
+ return finalize(ctx, input);
4968
+ }
4830
4969
  //#endregion
4831
4970
  //#region ../../node_modules/zod/v4/classic/iso.js
4832
4971
  var ZodISODateTime = /*@__PURE__*/ $constructor("ZodISODateTime", (inst, def) => {
@@ -5851,7 +5990,7 @@ var ZodIssueCode = {
5851
5990
  var ZodFirstPartyTypeKind;
5852
5991
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
5853
5992
  //#endregion
5854
- //#region ../types/dist/sleep-QsoHs66J.mjs
5993
+ //#region ../types/dist/sleep-9TIHFj1w.mjs
5855
5994
  /**
5856
5995
  * The audio chunk plane's byte format, and the ONE expansion from a coded
5857
5996
  * window to float samples (D455).
@@ -5930,6 +6069,22 @@ function buildAlawTable() {
5930
6069
  }
5931
6070
  buildUlawTable();
5932
6071
  buildAlawTable();
6072
+ /**
6073
+ * An addon whose own migrations did not apply refuses to initialise (D987). The error is typed
6074
+ * so a runner hosting several addons can tell "this addon is blocked" from a crash and keep its
6075
+ * co-located siblings running. Recognised by NAME and shape, never `instanceof`: a forked addon
6076
+ * bundles its own copy of this module, so the class the runner sees is not the one that threw.
6077
+ */
6078
+ var MIGRATIONS_BLOCKED_ERROR_NAME = "AddonMigrationsBlockedError";
6079
+ var AddonMigrationsBlockedError = class extends Error {
6080
+ /** The ledger ids that did not apply and block the owner. */
6081
+ migrationIds;
6082
+ constructor(migrationIds) {
6083
+ super(`migration(s) ${migrationIds.join(", ")} did not apply and block this addon — fix or retry them (migrations.retry), then restart it`);
6084
+ this.name = MIGRATIONS_BLOCKED_ERROR_NAME;
6085
+ this.migrationIds = migrationIds;
6086
+ }
6087
+ };
5933
6088
  /** Is this field's stored value a credential? */
5934
6089
  function isSecretConfigField(field) {
5935
6090
  if (field.type === "password") return true;
@@ -5983,9 +6138,16 @@ function isSecretMarker(value) {
5983
6138
  const ref = value["$secret"];
5984
6139
  return typeof ref === "string" && ref.length > 0;
5985
6140
  }
6141
+ /** Anything carrying a `$secret` key — a stored marker or a UI view of one. */
6142
+ function isSecretMarkerLike(value) {
6143
+ return isRecord$7(value) && Object.prototype.hasOwnProperty.call(value, "$secret");
6144
+ }
5986
6145
  function isSecretClear(value) {
5987
6146
  return isRecord$7(value) && value["$secretClear"] === true;
5988
6147
  }
6148
+ function isSecretFieldView(value) {
6149
+ return isRecord$7(value) && value["set"] === true && isSecretMarkerLike(value);
6150
+ }
5989
6151
  /**
5990
6152
  * The UI view of a stored secret field value: a marker becomes "set", inline
5991
6153
  * plaintext becomes "set (inline)", nothing becomes `null`. A value never
@@ -6367,6 +6529,53 @@ function emitReadiness(bus, params) {
6367
6529
  ts
6368
6530
  }));
6369
6531
  }
6532
+ /** Why a catalogue entry is not a runnable body of its declared kind. */
6533
+ var AddonMigrationDefinitionError = class extends Error {
6534
+ id;
6535
+ constructor(id, message) {
6536
+ super(`${id}: ${message}`);
6537
+ this.id = id;
6538
+ this.name = "AddonMigrationDefinitionError";
6539
+ }
6540
+ };
6541
+ /**
6542
+ * Bind a catalogue to the addon's ports. Throws {@link AddonMigrationDefinitionError} when
6543
+ * an entry's `bodyKind` does not match the body it carries, or is `sql` (a hub-only
6544
+ * body). A throwing body never escapes `execute`: it is reported as a failed result.
6545
+ */
6546
+ function defineAddonMigrations(catalogue, ports) {
6547
+ return catalogue.map((entry) => {
6548
+ const { meta } = entry;
6549
+ if ("plan" in entry) {
6550
+ if (meta.bodyKind !== "plan") throw new AddonMigrationDefinitionError(meta.id, `carries a plan body but declares "${meta.bodyKind}"`);
6551
+ return {
6552
+ meta,
6553
+ execute: () => guarded(async () => ({
6554
+ kind: "plan",
6555
+ plan: await entry.plan(ports)
6556
+ }))
6557
+ };
6558
+ }
6559
+ if (meta.bodyKind !== "procedure") throw new AddonMigrationDefinitionError(meta.id, `carries a procedure body but declares "${meta.bodyKind}"`);
6560
+ return {
6561
+ meta,
6562
+ execute: () => guarded(async () => ({
6563
+ kind: "procedure",
6564
+ result: await entry.procedure(ports)
6565
+ }))
6566
+ };
6567
+ });
6568
+ }
6569
+ async function guarded(work) {
6570
+ try {
6571
+ return await work();
6572
+ } catch (err) {
6573
+ return {
6574
+ kind: "failed",
6575
+ error: errMsg(err)
6576
+ };
6577
+ }
6578
+ }
6370
6579
  var NOT_RUN = {
6371
6580
  declared: false,
6372
6581
  snapshot: null,
@@ -6381,7 +6590,7 @@ var NOT_RUN = {
6381
6590
  * throws: an unreachable or refusing engine is logged and reported `declared: false`,
6382
6591
  * because the hub (and this addon's boot) must not hang on a migration.
6383
6592
  */
6384
- async function runAddonMigrations(host, migrations, logger) {
6593
+ async function runAddonMigrations(host, migrations, logger, options = {}) {
6385
6594
  const first = migrations[0];
6386
6595
  if (first === void 0) return NOT_RUN;
6387
6596
  const owner = first.meta.owner;
@@ -6410,7 +6619,9 @@ async function runAddonMigrations(host, migrations, logger) {
6410
6619
  else if (status === "blocked") blocked.push(id);
6411
6620
  else skipped.push(id);
6412
6621
  };
6622
+ const selected = options.only === void 0 ? null : new Set(options.only);
6413
6623
  for (const step of declaration.steps) {
6624
+ if (selected !== null && !selected.has(step.id)) continue;
6414
6625
  const bound = byId.get(step.id);
6415
6626
  if (bound === void 0 || step.action === "skip") {
6416
6627
  skipped.push(step.id);
@@ -6588,11 +6799,36 @@ function projectStore(store, perNodeKeys, nodeId) {
6588
6799
  }
6589
6800
  return out;
6590
6801
  }
6802
+ /**
6803
+ * The address of one keychain value: `secret://<owner>/<scope>/<fieldPath>`.
6804
+ *
6805
+ * A ref is DETERMINISTIC from where the value lives — the owner addon, the
6806
+ * scope (global, one node, one device, one integration, one row of a business
6807
+ * collection) and the field path inside that scope — so saving the same field
6808
+ * twice updates the same ref, and the ref itself says which settings blob
6809
+ * points at it. It is also the AAD of the value's ciphertext: a ciphertext
6810
+ * copied onto another ref does not decrypt.
6811
+ *
6812
+ * Array items are addressed by ITEM ID, never by index
6813
+ * (`providers[authentik].clientSecret`), so reordering a list keeps every ref.
6814
+ *
6815
+ * Pure and browser-safe: no node builtins, no I/O.
6816
+ */
6817
+ /** The URI scheme of every keychain ref. */
6818
+ var SECRET_REF_SCHEME = "secret://";
6591
6819
  var GLOBAL_SCOPE = { kind: "global" };
6592
6820
  /** The scope every addon-wide (not per-node, not per-device) setting lives in. */
6593
6821
  function globalSecretScope() {
6594
6822
  return GLOBAL_SCOPE;
6595
6823
  }
6824
+ /**
6825
+ * An addon id as a ref owner. A hub in-process builtin's context id is
6826
+ * `addon:<id>`; the owner of its secrets is `<id>`, exactly as for the same
6827
+ * addon running forked.
6828
+ */
6829
+ function normalizeSecretOwner(addonId) {
6830
+ return addonId.startsWith("addon:") ? addonId.slice(6) : addonId;
6831
+ }
6596
6832
  function encodeSegment(value) {
6597
6833
  return encodeURIComponent(value);
6598
6834
  }
@@ -6603,6 +6839,16 @@ function decodeSegment(value) {
6603
6839
  return null;
6604
6840
  }
6605
6841
  }
6842
+ /** The scope as it appears inside a ref (`global`, `node/<id>`, …). */
6843
+ function formatSecretScope(scope) {
6844
+ switch (scope.kind) {
6845
+ case "global": return "global";
6846
+ case "node": return `node/${encodeSegment(scope.nodeId)}`;
6847
+ case "device": return `device/${scope.deviceId}`;
6848
+ case "integration": return `integration/${encodeSegment(scope.integrationId)}`;
6849
+ case "row": return `row/${encodeSegment(scope.collection)}/${encodeSegment(scope.rowId)}`;
6850
+ }
6851
+ }
6606
6852
  /**
6607
6853
  * The field path of a value inside an array item, addressed by the item's id:
6608
6854
  * `arrayItemFieldPath('providers', 'authentik', 'clientSecret')` →
@@ -6611,6 +6857,13 @@ function decodeSegment(value) {
6611
6857
  function arrayItemFieldPath(arrayKey, itemId, fieldKey) {
6612
6858
  return `${arrayKey}[${encodeSegment(itemId)}].${fieldKey}`;
6613
6859
  }
6860
+ /** Build a ref. Throws on an empty owner or field path — both are bugs. */
6861
+ function buildSecretRef(parts) {
6862
+ const owner = normalizeSecretOwner(parts.owner);
6863
+ if (owner.length === 0) throw new Error("buildSecretRef: owner is empty");
6864
+ if (parts.fieldPath.length === 0) throw new Error("buildSecretRef: fieldPath is empty");
6865
+ return `${SECRET_REF_SCHEME}${encodeSegment(owner)}/${formatSecretScope(parts.scope)}/${parts.fieldPath}`;
6866
+ }
6614
6867
  function parseScope(segments) {
6615
6868
  switch (segments[0]) {
6616
6869
  case "global": return {
@@ -7528,15 +7781,19 @@ var BaseAddon = class {
7528
7781
  * nothing; the boot continues. A migration that FAILED (or was blocked by one)
7529
7782
  * and declares `onFailure: 'block-owner'` makes this throw, so the addon does not
7530
7783
  * serve data whose shape it cannot trust; `tolerate` migrations never do.
7784
+ *
7785
+ * ALWAYS pass the whole catalogue; a phase that must run only some of it passes
7786
+ * `{ only: [ids] }` — never a filtered catalogue (the engine would judge the
7787
+ * omitted applied ids "newer").
7531
7788
  */
7532
- async runMigrations(migrations) {
7789
+ async runMigrations(migrations, options) {
7533
7790
  const api = this.ctx.api.migrations;
7534
7791
  const report = await runAddonMigrations({
7535
7792
  declareOwner: (input) => api.declareOwner.mutate(input),
7536
7793
  startMigration: (input) => api.startMigration.mutate(input),
7537
7794
  finishMigration: (input) => api.finishMigration.mutate(input)
7538
- }, migrations, this.ctx.logger);
7539
- if (report.blockOwner.length > 0) throw new Error(`migration(s) ${report.blockOwner.join(", ")} did not apply and block this addon — fix or retry them (migrations.retry), then restart it`);
7795
+ }, migrations, this.ctx.logger, options);
7796
+ if (report.blockOwner.length > 0) throw new AddonMigrationsBlockedError(report.blockOwner);
7540
7797
  return report;
7541
7798
  }
7542
7799
  /**
@@ -7677,10 +7934,9 @@ var BaseAddon = class {
7677
7934
  *
7678
7935
  * Override it only when an `instanceMode: multiple` addon's instances differ: an NVR integration
7679
7936
  * needs its connection fields, the default integration the addon's own sections. It is the
7680
- * SHAPE of the form only — the values live in `integrations.getSettings`, and the write path is
7681
- * unchanged (`integrations.setSettings` for an account integration).
7937
+ * SHAPE of the form only — the values live on the instance record.
7682
7938
  */
7683
- async integrationSettingsSchema(_instance) {
7939
+ async integrationFormSchema(_instance) {
7684
7940
  return null;
7685
7941
  }
7686
7942
  /**
@@ -7726,7 +7982,7 @@ var BaseAddon = class {
7726
7982
  * per-instance schema when it declares one, else its global schema (what they always showed).
7727
7983
  */
7728
7984
  async getIntegrationFormSchema(instance, nodeId) {
7729
- const scoped = await this.integrationSettingsSchema(instance);
7985
+ const scoped = await this.integrationFormSchema(instance);
7730
7986
  if (scoped === null) return this.getGlobalSettings(void 0, void 0, nodeId);
7731
7987
  return hydrateSchema(scoped, {}, { inlineSecretsAsViews: true });
7732
7988
  }
@@ -7876,6 +8132,10 @@ var BaseAddon = class {
7876
8132
  const stored = keychain ? await this.readAddonStoreWithRetry() : {};
7877
8133
  const patch = {};
7878
8134
  for (const key of keys) {
8135
+ if (tree.get(key)?.kind === "array") {
8136
+ patch[key] = [];
8137
+ continue;
8138
+ }
7879
8139
  const keychainStored = tree.has(key) || collectSecretMarkerRefs(stored[key]).length > 0;
7880
8140
  patch[key] = keychain && keychainStored ? SECRET_CLEAR : "";
7881
8141
  }
@@ -8515,6 +8775,45 @@ function normalizeAddonInitResult(result) {
8515
8775
  if (Array.isArray(result)) return { providers: result };
8516
8776
  return result;
8517
8777
  }
8778
+ var PREFIX = "records/";
8779
+ /** The base of every records failure. `detail` is the human part of the message. */
8780
+ var RecordsError = class extends Error {
8781
+ code;
8782
+ detail;
8783
+ constructor(code, detail) {
8784
+ super(`${PREFIX}${code}: ${detail}`);
8785
+ this.name = "RecordsError";
8786
+ this.code = code;
8787
+ this.detail = detail;
8788
+ }
8789
+ };
8790
+ /** A write guarded by `ifRev` found another revision (or an existing row for `ifRev: 0`). */
8791
+ var RevConflictError = class extends RecordsError {
8792
+ constructor(detail) {
8793
+ super("rev-conflict", detail);
8794
+ this.name = "RevConflictError";
8795
+ }
8796
+ };
8797
+ /** The keychain could not store or serve a value: explicit, never an empty string. */
8798
+ var RecordSecretUnavailableError = class extends RecordsError {
8799
+ constructor(detail) {
8800
+ super("secret-unavailable", detail);
8801
+ this.name = "RecordSecretUnavailableError";
8802
+ }
8803
+ };
8804
+ var InvalidRecordError = class extends RecordsError {
8805
+ constructor(detail) {
8806
+ super("invalid-record", detail);
8807
+ this.name = "InvalidRecordError";
8808
+ }
8809
+ };
8810
+ /** A kind declaration the engine refuses (non-additive change, bad shape, wrong file). */
8811
+ var DeclarationRefusedError = class extends RecordsError {
8812
+ constructor(detail) {
8813
+ super("declaration-refused", detail);
8814
+ this.name = "DeclarationRefusedError";
8815
+ }
8816
+ };
8518
8817
  /** Limits and names of `ctx.records` (D881). One authority; the engine and the facade read it. */
8519
8818
  /** The files a kind may live in. `history` is device-history's (D850), never records. */
8520
8819
  var RECORD_DATABASES = ["settings", "events"];
@@ -8530,6 +8829,183 @@ var RECORD_DEFAULT_MAX_DATA_BYTES = 64 * 1024;
8530
8829
  var RECORD_MAX_DATA_BYTES = 1024 * 1024;
8531
8830
  var RECORD_BATCH_MAX = 1e3;
8532
8831
  var RECORD_QUERY_MAX = 1e3;
8832
+ /** A kind in the `settings` file may not bound itself above this (D447: high volume is `events`). */
8833
+ var RECORD_SETTINGS_MAX_ROWS = 5e4;
8834
+ /** The `Column`-free proof prefix: a ref collection for a kind's secret fields. */
8835
+ var RECORD_SECRET_COLLECTION_PREFIX = "records:";
8836
+ /**
8837
+ * Secret fields of a record, addressed the way a Zod schema declares them
8838
+ * (`collectZodSecretPaths`): dotted keys, `[]` for "each element of this array"
8839
+ * (`auth.accessToken`, `headers[].value`).
8840
+ *
8841
+ * `{}` after a key means "each value of this map" (`applianceSecrets{}`): the map's own key
8842
+ * names the value (`applianceSecrets{fridge}`), so no id key is declared and a body that drops a
8843
+ * key releases exactly that key's secret.
8844
+ *
8845
+ * Array elements are matched by a DECLARED id key (`secretArrayKeys`:
8846
+ * `{ headers: 'name' }`), never by index, so reordering a list keeps every
8847
+ * keychain ref (the same rule as `arrayItemFieldPath`). The concrete path of a
8848
+ * leaf names its element: `headers[X-Api].value`.
8849
+ *
8850
+ * Pure and browser-safe. Nothing here mutates: every transform returns a new value.
8851
+ */
8852
+ /** The array prefixes (declared form, e.g. `headers` or `a.headers`) of a path. */
8853
+ function parseSecretPath(path) {
8854
+ if (path.length === 0) throw new InvalidRecordError("an empty secret path");
8855
+ return path.split(".").map((raw) => {
8856
+ const each = raw.endsWith("[]");
8857
+ const map = raw.endsWith("{}");
8858
+ const key = each || map ? raw.slice(0, -2) : raw;
8859
+ if (key.length === 0) throw new InvalidRecordError(`secret path "${path}" has an empty segment`);
8860
+ return {
8861
+ key,
8862
+ each,
8863
+ map
8864
+ };
8865
+ });
8866
+ }
8867
+ /** The declared array prefixes of `path` that need an id key (`headers`, `a.rows`). */
8868
+ function secretArrayPrefixes(path) {
8869
+ const segments = parseSecretPath(path);
8870
+ const prefixes = [];
8871
+ const walked = [];
8872
+ for (const segment of segments) {
8873
+ walked.push(segment.key);
8874
+ if (segment.each) prefixes.push(walked.join("."));
8875
+ }
8876
+ return prefixes;
8877
+ }
8878
+ function isRecord$4(value) {
8879
+ return typeof value === "object" && value !== null && !Array.isArray(value);
8880
+ }
8881
+ function elementId(element, idKey, declared, prefix) {
8882
+ const id = isRecord$4(element) ? element[idKey] : void 0;
8883
+ if (typeof id !== "string" || id.length === 0) throw new InvalidRecordError(`"${declared}": every element of "${prefix}" needs a non-empty string "${idKey}" to carry a secret`);
8884
+ return id;
8885
+ }
8886
+ /**
8887
+ * Visit every secret leaf PRESENT in `data` (an absent branch has nothing to
8888
+ * visit). `replace` returns the new leaf value, or {@link REMOVE_LEAF}; the
8889
+ * result is a new body, `data` is untouched.
8890
+ */
8891
+ var REMOVE_LEAF = Symbol("remove-leaf");
8892
+ function mapAt(node, segments, index, walkedKeys, concretePrefix, declared, arrayKeys, visit) {
8893
+ if (!isRecord$4(node)) return node;
8894
+ const segment = segments[index];
8895
+ if (segment === void 0) return node;
8896
+ if (!Object.prototype.hasOwnProperty.call(node, segment.key)) return node;
8897
+ const child = node[segment.key];
8898
+ const keys = [...walkedKeys, segment.key];
8899
+ const last = index === segments.length - 1;
8900
+ if (segment.each) {
8901
+ if (!Array.isArray(child)) return node;
8902
+ const prefix = keys.join(".");
8903
+ const idKey = arrayKeys[prefix];
8904
+ if (idKey === void 0) throw new InvalidRecordError(`"${declared}": no id key declared for the array "${prefix}"`);
8905
+ const mapped = child.map((element) => {
8906
+ const id = elementId(element, idKey, declared, prefix);
8907
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}[${encodeURIComponent(id)}]`;
8908
+ return last ? element : mapAt(element, segments, index + 1, keys, concrete, declared, arrayKeys, visit);
8909
+ });
8910
+ return {
8911
+ ...node,
8912
+ [segment.key]: mapped
8913
+ };
8914
+ }
8915
+ if (segment.map) {
8916
+ if (!isRecord$4(child)) return node;
8917
+ const kept = Object.entries(child).map(([mapKey, value]) => {
8918
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}{${encodeURIComponent(mapKey)}}`;
8919
+ if (!last) return [mapKey, mapAt(value, segments, index + 1, keys, concrete, declared, arrayKeys, visit)];
8920
+ return [mapKey, visit({
8921
+ declared,
8922
+ concrete,
8923
+ value
8924
+ })];
8925
+ }).filter(([, value]) => value !== REMOVE_LEAF);
8926
+ return {
8927
+ ...node,
8928
+ [segment.key]: Object.fromEntries(kept)
8929
+ };
8930
+ }
8931
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}`;
8932
+ if (last) {
8933
+ const replacement = visit({
8934
+ declared,
8935
+ concrete,
8936
+ value: child
8937
+ });
8938
+ if (replacement === REMOVE_LEAF) return Object.fromEntries(Object.entries(node).filter(([key]) => key !== segment.key));
8939
+ return {
8940
+ ...node,
8941
+ [segment.key]: replacement
8942
+ };
8943
+ }
8944
+ return {
8945
+ ...node,
8946
+ [segment.key]: mapAt(child, segments, index + 1, keys, concrete, declared, arrayKeys, visit)
8947
+ };
8948
+ }
8949
+ /** Replace/remove every present secret leaf; returns a NEW body. */
8950
+ function mapSecretLeaves(data, paths, arrayKeys, visit) {
8951
+ let current = data;
8952
+ for (const declared of paths) current = mapAt(current, parseSecretPath(declared), 0, [], "", declared, arrayKeys, visit);
8953
+ return current;
8954
+ }
8955
+ /** Every present secret leaf, read-only. */
8956
+ function collectSecretLeaves(data, paths, arrayKeys) {
8957
+ const found = [];
8958
+ mapSecretLeaves(data, paths, arrayKeys, (leaf) => {
8959
+ found.push(leaf);
8960
+ return leaf.value;
8961
+ });
8962
+ return found;
8963
+ }
8964
+ /**
8965
+ * The keychain collection name a kind's secrets live under. Prefixed so a
8966
+ * record's refs never collide with the refs a legacy collection of the same name
8967
+ * already holds during an adoption.
8968
+ */
8969
+ function recordSecretCollection(kind) {
8970
+ return `${RECORD_SECRET_COLLECTION_PREFIX}${kind}`;
8971
+ }
8972
+ /** The ONE ref a row's secret field may carry: the engine and the facade both build it here. */
8973
+ function recordSecretRef(owner, kind, rowId, concretePath) {
8974
+ return buildSecretRef({
8975
+ owner,
8976
+ scope: {
8977
+ kind: "row",
8978
+ collection: recordSecretCollection(kind),
8979
+ rowId
8980
+ },
8981
+ fieldPath: concretePath
8982
+ });
8983
+ }
8984
+ /**
8985
+ * A stored secret, as an admin read shows it: a VIEW naming the row's own
8986
+ * keychain ref (`set: true`), never the value and no longer the bare redaction
8987
+ * token. The form hands it to the secret field, which reveals the value by ref
8988
+ * through the audited `keychain-admin.reveal`; sent back untouched it keeps the
8989
+ * stored secret (the records door reads a view as KEEP).
8990
+ *
8991
+ * ONE implementation for the entries service and for every addon that serves
8992
+ * its own instances (`RecordIntegrationInstances`).
8993
+ */
8994
+ function isRecord$3(value) {
8995
+ return typeof value === "object" && value !== null && !Array.isArray(value);
8996
+ }
8997
+ function secretViewsOf(owner, kind, id, decl, data) {
8998
+ if (decl.secretPaths.length === 0) return data;
8999
+ const shown = mapSecretLeaves(data, decl.secretPaths, decl.secretArrayKeys, (leaf) => {
9000
+ if (leaf.value !== "__camstack_redacted__") return leaf.value;
9001
+ return {
9002
+ $secret: recordSecretRef(owner, kind, id, leaf.concrete),
9003
+ v: 1,
9004
+ set: true
9005
+ };
9006
+ });
9007
+ return isRecord$3(shown) ? shown : data;
9008
+ }
8533
9009
  /**
8534
9010
  * The share-view scope kinds a share-link token can carry. The hub mints
8535
9011
  * and validates them (`ShareViewGrantSchema` builds its
@@ -8602,7 +9078,8 @@ function isZodSecret(schema) {
8602
9078
  }
8603
9079
  /**
8604
9080
  * Every declared secret path in a config schema: dotted keys, `[]` for "each
8605
- * element of this array" (`connection.password`, `rows[].token`). A declared
9081
+ * element of this array" (`connection.password`, `rows[].token`), `{}` for "each value of this
9082
+ * map" (`applianceSecrets{}`). A declared
8606
9083
  * object or array is reported as one path and not descended into — everything
8607
9084
  * under it is secret.
8608
9085
  */
@@ -8613,6 +9090,7 @@ function collectZodSecretPaths(schema, prefix = "") {
8613
9090
  const def = defOf(layer);
8614
9091
  if (def.type === "object" && def.shape) for (const [key, child] of Object.entries(def.shape)) paths.push(...collectZodSecretPaths(child, prefix ? `${prefix}.${key}` : key));
8615
9092
  else if (def.type === "array" && def.element) paths.push(...collectZodSecretPaths(def.element, `${prefix}[]`));
9093
+ else if (def.type === "record" && def.valueType) paths.push(...collectZodSecretPaths(def.valueType, `${prefix}{}`));
8616
9094
  else if (def.type === "union" && def.options) for (const option of def.options) paths.push(...collectZodSecretPaths(option, prefix));
8617
9095
  else if (def.type === "intersection") {
8618
9096
  if (def.left) paths.push(...collectZodSecretPaths(def.left, prefix));
@@ -8687,6 +9165,126 @@ var RecordKindDeclarationSchema = object({
8687
9165
  }).strict();
8688
9166
  /** The kind names: lower-case, dash separated, short enough for an index name. */
8689
9167
  var RecordKindNameSchema = string().regex(/^[a-z][a-z0-9-]{0,47}$/);
9168
+ /** Cross-field rules a declaration must satisfy. Throws {@link DeclarationRefusedError}. */
9169
+ function assertValidDeclaration(name, decl) {
9170
+ const refuse = (why) => {
9171
+ throw new DeclarationRefusedError(`kind "${name}": ${why}`);
9172
+ };
9173
+ if (!RecordKindNameSchema.safeParse(name).success) refuse("the name must be lower-case-dashed");
9174
+ const seen = /* @__PURE__ */ new Set();
9175
+ for (const index of decl.indexes) {
9176
+ if (seen.has(index.name)) refuse(`index name "${index.name}" is declared twice`);
9177
+ seen.add(index.name);
9178
+ }
9179
+ const { retention } = decl;
9180
+ const hasSecrets = decl.secretPaths.length > 0;
9181
+ if ("ttlMs" in retention) {
9182
+ if (retention.from === "at" && decl.at !== "required") refuse("a ttl from \"at\" needs at: \"required\"");
9183
+ if (hasSecrets) refuse("a kind with secret fields cannot use engine TTL (its keychain values would be orphaned)");
9184
+ }
9185
+ if ("maxRows" in retention || "maxRowsPerDevice" in retention) {
9186
+ if (retention.maxRowsPerDevice !== void 0 && decl.device !== "required") refuse("maxRowsPerDevice needs device: \"required\"");
9187
+ if (decl.at !== "required") refuse("a row bound trims the oldest \"at\": it needs at: \"required\"");
9188
+ if (hasSecrets) refuse("a kind with secret fields cannot use an engine row bound");
9189
+ const bound = Math.max(retention.maxRows ?? 0, retention.maxRowsPerDevice ?? 0);
9190
+ if (decl.database === "settings" && bound > 5e4) refuse(`a row bound above ${RECORD_SETTINGS_MAX_ROWS} belongs in database: "events" (a big delete on the settings thread stalls every configuration read)`);
9191
+ }
9192
+ if (decl.deviceRemoval === "delete" && decl.device === "none") refuse("deviceRemoval: \"delete\" needs a device: \"required\" or \"optional\"");
9193
+ for (const path of decl.secretPaths) for (const prefix of secretArrayPrefixes(path)) if (decl.secretArrayKeys[prefix] === void 0) refuse(`secret path "${path}" crosses the array "${prefix}": declare its id key in secretArrayKeys`);
9194
+ }
9195
+ function bodyFieldsOf(schema) {
9196
+ return { ...toJSONSchema(schema, {
9197
+ unrepresentable: "any",
9198
+ io: "input"
9199
+ }) };
9200
+ }
9201
+ function isRecordLike(value) {
9202
+ return typeof value === "object" && value !== null && !Array.isArray(value);
9203
+ }
9204
+ /** Does every branch of the body schema carry `field`? (A discriminated union has several.) */
9205
+ function hasNameField(json, field) {
9206
+ const branches = json["oneOf"] ?? json["anyOf"];
9207
+ if (Array.isArray(branches)) return branches.length > 0 && branches.every((b) => isRecordLike(b) && hasNameField(b, field));
9208
+ const properties = json["properties"];
9209
+ return isRecordLike(properties) && Object.prototype.hasOwnProperty.call(properties, field);
9210
+ }
9211
+ /**
9212
+ * Declare the kinds of a package. The keys are the kind names. The result is
9213
+ * what `ctx.records.declare` sends to the engine and what `ctx.records.kind`
9214
+ * types its handle from.
9215
+ */
9216
+ function defineRecordKinds(specs) {
9217
+ const out = {};
9218
+ for (const [name, spec] of Object.entries(specs)) {
9219
+ const secretPaths = collectZodSecretPaths(spec.schema);
9220
+ const nameField = spec.entry?.nameField ?? "name";
9221
+ const fields = bodyFieldsOf(spec.schema);
9222
+ if (spec.entry !== void 0 && !hasNameField(fields, nameField)) throw new DeclarationRefusedError(`kind "${name}": an entry kind's schema needs a "${nameField}" field`);
9223
+ const parsed = RecordKindDeclarationSchema.parse({
9224
+ database: spec.database,
9225
+ class: spec.class,
9226
+ writeTrigger: spec.writeTrigger,
9227
+ device: spec.device,
9228
+ at: spec.at,
9229
+ indexes: spec.indexes === void 0 ? void 0 : [...spec.indexes],
9230
+ retention: spec.retention,
9231
+ deviceRemoval: spec.deviceRemoval,
9232
+ maxDataBytes: spec.maxDataBytes,
9233
+ secretPaths: [...new Set([...secretPaths, ...spec.retiredSecretPaths ?? []])],
9234
+ secretArrayKeys: spec.secretArrayKeys === void 0 ? void 0 : { ...spec.secretArrayKeys },
9235
+ transactFamily: spec.transactFamily,
9236
+ entry: spec.entry === void 0 ? void 0 : {
9237
+ title: spec.entry.title,
9238
+ nameField,
9239
+ fields
9240
+ }
9241
+ });
9242
+ assertValidDeclaration(name, parsed);
9243
+ out[name] = {
9244
+ name,
9245
+ schema: spec.schema,
9246
+ declaration: parsed
9247
+ };
9248
+ }
9249
+ return out;
9250
+ }
9251
+ /**
9252
+ * Entry kinds (D881): every list of user-created entries (notification
9253
+ * targets, brokers, LLM profiles) is ONE record kind with an id, a name and a
9254
+ * kind-specific body, and the admin UI lists/adds/edits/deletes all of them
9255
+ * through the `record-entries` capability with password fields derived from
9256
+ * the schema (`.meta({ secret: true })`).
9257
+ */
9258
+ /** The body of a plain entry: a name and the fields the kind adds. */
9259
+ function entryBody(shape) {
9260
+ return object({
9261
+ name: string().min(1),
9262
+ ...shape
9263
+ });
9264
+ }
9265
+ /**
9266
+ * Declare one entry kind. An entry is configuration: never trimmed by the
9267
+ * engine, never aged, belonging to no device.
9268
+ */
9269
+ function defineEntryKind(name, spec) {
9270
+ const defined = defineRecordKinds({ [name]: {
9271
+ schema: spec.schema,
9272
+ class: "config",
9273
+ writeTrigger: spec.writeTrigger ?? "an operator adds or edits an entry in the entries UI",
9274
+ retention: { none: "an entry goes only when the operator deletes it" },
9275
+ ...spec.maxDataBytes === void 0 ? {} : { maxDataBytes: spec.maxDataBytes },
9276
+ ...spec.database === void 0 ? {} : { database: spec.database },
9277
+ ...spec.indexes === void 0 ? {} : { indexes: spec.indexes },
9278
+ ...spec.secretArrayKeys === void 0 ? {} : { secretArrayKeys: spec.secretArrayKeys },
9279
+ ...spec.retiredSecretPaths === void 0 ? {} : { retiredSecretPaths: spec.retiredSecretPaths },
9280
+ entry: {
9281
+ title: spec.title,
9282
+ ...spec.nameField === void 0 ? {} : { nameField: spec.nameField }
9283
+ }
9284
+ } })[name];
9285
+ if (defined === void 0) throw new DeclarationRefusedError(`entry kind "${name}" was not built`);
9286
+ return defined;
9287
+ }
8690
9288
  object({
8691
9289
  field: string().min(1),
8692
9290
  on: literal("advance")
@@ -9382,6 +9980,7 @@ var CAP_NAMES = Object.freeze([
9382
9980
  "backup",
9383
9981
  "battery",
9384
9982
  "binary",
9983
+ "board-key-source",
9385
9984
  "brightness",
9386
9985
  "broker",
9387
9986
  "button",
@@ -9503,6 +10102,7 @@ var CAP_NAMES = Object.freeze([
9503
10102
  "privacy-mask",
9504
10103
  "ptz",
9505
10104
  "ptz-autotrack",
10105
+ "pump-cycle",
9506
10106
  "reboot",
9507
10107
  "record-entries",
9508
10108
  "recording",
@@ -10795,18 +11395,6 @@ Object.freeze({
10795
11395
  "path": "pumpRunning",
10796
11396
  "valueType": "boolean"
10797
11397
  },
10798
- {
10799
- "path": "pumpIntervalEnabled",
10800
- "valueType": "boolean"
10801
- },
10802
- {
10803
- "path": "pumpOnTime",
10804
- "valueType": "number"
10805
- },
10806
- {
10807
- "path": "pumpOffTime",
10808
- "valueType": "number"
10809
- },
10810
11398
  {
10811
11399
  "path": "lastDrink",
10812
11400
  "valueType": "number"
@@ -10930,6 +11518,20 @@ Object.freeze({
10930
11518
  "valueType": "number"
10931
11519
  }
10932
11520
  ],
11521
+ "pump-cycle": [
11522
+ {
11523
+ "path": "enabled",
11524
+ "valueType": "boolean"
11525
+ },
11526
+ {
11527
+ "path": "onTime",
11528
+ "valueType": "number"
11529
+ },
11530
+ {
11531
+ "path": "offTime",
11532
+ "valueType": "number"
11533
+ }
11534
+ ],
10933
11535
  "recording-archive": [
10934
11536
  {
10935
11537
  "path": "deviceId",
@@ -11379,7 +11981,7 @@ object({
11379
11981
  params: record(string(), union([string(), number()])).optional()
11380
11982
  });
11381
11983
  //#endregion
11382
- //#region ../types/dist/composition-Dh3RfMx5.mjs
11984
+ //#region ../types/dist/composition-pOHbTzRB.mjs
11383
11985
  /**
11384
11986
  * The ffmpeg build every CamStack node downloads, per platform and arch.
11385
11987
  *
@@ -12142,38 +12744,6 @@ function validateExpressionSource(src) {
12142
12744
  return null;
12143
12745
  }
12144
12746
  /**
12145
- * One power reading becomes a washer, dryer or dishwasher (D944 helper).
12146
- *
12147
- * Standby of the control board is under 5 W; a motor or a heater is far
12148
- * above that, so 5 W is the line. A door lock or a short pump spike is not
12149
- * a cycle, so running starts only after 30 s above the line.
12150
- *
12151
- * A wash, dry or dishwasher pause (soak, heat-wait, heater off between
12152
- * bursts) lasts several minutes. Ending the cycle on the first dip would
12153
- * report "finished" in the middle of the program, so the stop dwell is
12154
- * 10 minutes on every type. The number is stored per type so one machine
12155
- * can move later without moving the others.
12156
- */
12157
- var APPLIANCE_TEMPLATE_ID = "appliance";
12158
- var APPLIANCE_KINDS = [
12159
- "washer",
12160
- "dryer",
12161
- "dishwasher"
12162
- ];
12163
- DeviceType.Washer, DeviceType.Dryer, DeviceType.Dishwasher;
12164
- /**
12165
- * A dumb plug-in stove or heater, built from a smart plug (a `Heater`).
12166
- *
12167
- * The plug is the actuator: `switch.setState` is a FORWARD to the plug's own
12168
- * (D967), so the heater switches exactly as the plug does. Running is the
12169
- * plug being on; when a power reading is also named, running is the draw
12170
- * staying above the line instead (a plug left on with the stove's own
12171
- * thermostat open is not heating). 50 W is far above any standby and below
12172
- * the smallest radiator.
12173
- */
12174
- var HEATER_TEMPLATE_ID = "heater";
12175
- DeviceType.Heater;
12176
- /**
12177
12747
  * Statistics and integrals over a history read (D944).
12178
12748
  *
12179
12749
  * Pure: the same points always give the same answer, so a restart recomputes
@@ -12317,34 +12887,6 @@ var HelperSpecSchema = discriminatedUnion("kind", [
12317
12887
  /** Actuator groups only. Readings leave this unset. */
12318
12888
  active: ActiveCriterionSchema.optional()
12319
12889
  }),
12320
- object({
12321
- kind: literal("appliance"),
12322
- templateId: literal(APPLIANCE_TEMPLATE_ID),
12323
- appliance: _enum(APPLIANCE_KINDS),
12324
- thresholdWatts: number().positive(),
12325
- startDwellMs: number().int().nonnegative(),
12326
- stopDwellMs: number().int().nonnegative(),
12327
- member: HelperMemberSchema,
12328
- /**
12329
- * The plug that powers the appliance (`switch.on`). Optional: when set, the
12330
- * composition carries a `power-source` feature, so the hub can cut and restore
12331
- * that plug (power-source link of a NEW-target composition).
12332
- */
12333
- powerSwitch: HelperMemberSchema.optional(),
12334
- /** How long a forced restart keeps the plug off; the cap's default when unset. */
12335
- offSeconds: number().optional()
12336
- }),
12337
- object({
12338
- kind: literal("heater"),
12339
- templateId: literal(HEATER_TEMPLATE_ID),
12340
- /** The plug, read and commanded at `switch.on`. */
12341
- plug: HelperMemberSchema,
12342
- /** The plug's power reading, when it has one: running is then the draw, not the switch. */
12343
- meter: HelperMemberSchema.optional(),
12344
- thresholdWatts: number().positive(),
12345
- startDwellMs: number().int().nonnegative(),
12346
- stopDwellMs: number().int().nonnegative()
12347
- }),
12348
12890
  object({
12349
12891
  kind: literal("statistic"),
12350
12892
  stat: _enum(STATISTIC_STATS),
@@ -12516,7 +13058,14 @@ var CompositionForwardCommandSchema = object({
12516
13058
  method: string().min(1),
12517
13059
  args: record(string().min(1), CompositionForwardArgSchema).optional()
12518
13060
  });
12519
- var CompositionCommandTargetSchema = discriminatedUnion("kind", [CompositionForwardCommandSchema, CompositionCodeSourceSchema]);
13061
+ var CompositionCommandTargetSchema = discriminatedUnion("kind", [
13062
+ CompositionForwardCommandSchema,
13063
+ CompositionCodeSourceSchema,
13064
+ object({
13065
+ kind: literal("extension"),
13066
+ target: literal("remote")
13067
+ })
13068
+ ]);
12520
13069
  /** An item key inside an item-array cap (`consumables.items[<key>]`). */
12521
13070
  var COMPOSITION_ITEM_KEY_RE = /^[a-z0-9][a-z0-9-]{0,47}$/;
12522
13071
  /**
@@ -12561,7 +13110,7 @@ var CompositionSchema = object({
12561
13110
  kind: literal("existing"),
12562
13111
  device: CompositionSourceRefSchema
12563
13112
  })]),
12564
- features: array(CompositionFeatureSchema).min(1).max(16),
13113
+ features: array(CompositionFeatureSchema).min(0).max(16),
12565
13114
  /**
12566
13115
  * Present when the block is a helper template. Absent on a free
12567
13116
  * composition (the room example, device 4603). The editor reads this,
@@ -12593,6 +13142,73 @@ var NodeColorIdSchema = _enum([
12593
13142
  "node-g",
12594
13143
  "node-h"
12595
13144
  ]);
13145
+ //#endregion
13146
+ //#region ../types/dist/index.mjs
13147
+ var SMTP_INBOUND_DEFAULT_PORT = 2525;
13148
+ var SMTP_INBOUND_DEFAULT_DOMAIN = "camstack.local";
13149
+ var SMTP_INBOUND_DEFAULT_MAX_MESSAGE_BYTES = 25 * 1024 * 1024;
13150
+ /** The text excerpt a message carries on the bus. */
13151
+ var SMTP_INBOUND_TEXT_MAX_CHARS = 4096;
13152
+ var PortSchema = number().int().min(1).max(65535);
13153
+ /** A recipient local-part: what stands before the `@`. */
13154
+ var SmtpRecipientSchema = string().min(1).max(64).regex(/^[A-Za-z0-9._+-]+$/);
13155
+ object({
13156
+ port: PortSchema.default(SMTP_INBOUND_DEFAULT_PORT),
13157
+ bindHost: string().min(1).default("0.0.0.0"),
13158
+ domain: string().min(1).default(SMTP_INBOUND_DEFAULT_DOMAIN),
13159
+ requireAuth: boolean().default(true),
13160
+ username: string().default(""),
13161
+ password: string().default("").meta({ secret: true }),
13162
+ starttls: boolean().default(false),
13163
+ maxMessageBytes: number().int().positive().default(SMTP_INBOUND_DEFAULT_MAX_MESSAGE_BYTES)
13164
+ });
13165
+ object({
13166
+ host: string().min(1).nullable(),
13167
+ hostReason: string().nullable(),
13168
+ port: PortSchema,
13169
+ domain: string().min(1),
13170
+ requireAuth: boolean(),
13171
+ username: string(),
13172
+ password: string(),
13173
+ starttls: boolean()
13174
+ });
13175
+ object({
13176
+ recipients: array(SmtpRecipientSchema).min(1),
13177
+ /**
13178
+ * Who is subscribing. A second `subscribe` with the same id REPLACES that subscriber's
13179
+ * recipients (the way a consumer that restarted, or lost a device, declares its set again);
13180
+ * a recipient held by another subscriber is refused with `smtp-inbound/recipient-claimed`.
13181
+ * Absent, the subscriber is anonymous and unique.
13182
+ */
13183
+ subscriberId: string().min(1).max(64).optional()
13184
+ });
13185
+ var SmtpInboundAttachmentSchema = object({
13186
+ filename: string(),
13187
+ contentType: string(),
13188
+ bytes: number().int().nonnegative()
13189
+ });
13190
+ /** The payload of one `broker.message` (the key is the recipient local-part). */
13191
+ var SmtpInboundMessageSchema = object({
13192
+ /** Monotonic per mailbox; a gap tells a consumer it missed an event. */
13193
+ seq: number().int().positive(),
13194
+ messageId: string(),
13195
+ receivedAt: number().int().nonnegative(),
13196
+ from: string(),
13197
+ to: string(),
13198
+ subject: string(),
13199
+ text: string().max(SMTP_INBOUND_TEXT_MAX_CHARS),
13200
+ attachments: array(SmtpInboundAttachmentSchema)
13201
+ });
13202
+ object({
13203
+ /** The newest seq issued so far (0 before any mail). */
13204
+ lastSeq: number().int().nonnegative(),
13205
+ /** The oldest seq still retained; messages below it are gone. */
13206
+ oldestSeq: number().int().nonnegative(),
13207
+ messages: array(object({
13208
+ key: string(),
13209
+ message: SmtpInboundMessageSchema
13210
+ }))
13211
+ });
12596
13212
  new Set([
12597
13213
  "track",
12598
13214
  "face",
@@ -12712,6 +13328,205 @@ var IntegrationInstanceRefSchema = object({
12712
13328
  ]),
12713
13329
  candidateStableId: string().optional()
12714
13330
  });
13331
+ /**
13332
+ * `RecordIntegrationInstances` - the `integration-instances` provider over ONE
13333
+ * entry kind, so an addon that holds a connection serves it in ~30 lines.
13334
+ *
13335
+ * Every instance is one record of the addon's own kind, keyed by the
13336
+ * `integrations` registry id. The records door does the secret work: a field the
13337
+ * kind marks `.meta({ secret: true })` is a keychain marker bound to the row, so
13338
+ * deleting the row deletes the secret, and one row's value is never another's.
13339
+ *
13340
+ * Patch rules for a secret (`updateInstance`): omitted, `''`, the redaction
13341
+ * token or the view the form was given KEEP the stored secret;
13342
+ * `{ $secretClear: true }` clears it; any other string replaces it.
13343
+ */
13344
+ /** The most instances one addon lists (an integrations page, not a table). */
13345
+ var INSTANCES_LIST_MAX = 1e3;
13346
+ /** The keys of the kind's secret fields that sit at the top level of the body. */
13347
+ function topLevelSecretKeys(paths) {
13348
+ return new Set(paths.filter((p) => !p.includes(".") && !p.includes("[") && !p.includes("{")));
13349
+ }
13350
+ /** The keys of the kind's top-level MAPS whose values are secrets (`applianceSecrets{}`). */
13351
+ function secretMapKeys(paths) {
13352
+ return new Set(paths.filter((p) => p.endsWith("{}") && !p.slice(0, -2).match(/[.[{]/)).map((p) => p.slice(0, -2)));
13353
+ }
13354
+ /**
13355
+ * A patch value for a map of secrets: an entry that is omitted, `''`, the redaction token or the
13356
+ * view the form was given KEEPS its stored secret (it is left out of the merge); `{ $secretClear }`
13357
+ * or `null` removes the entry; any other string replaces it. Null when nothing is left to merge.
13358
+ */
13359
+ function secretMapPatch(value) {
13360
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
13361
+ const out = {};
13362
+ for (const [key, entry] of Object.entries(value)) if (entry === null || isSecretClear(entry)) out[key] = null;
13363
+ else if (typeof entry === "string" && entry !== "" && entry !== "__camstack_redacted__" && !isSecretFieldView(entry)) out[key] = entry;
13364
+ return Object.keys(out).length > 0 ? out : null;
13365
+ }
13366
+ /** Does the kind's body schema carry an `enabled` field? */
13367
+ function declaresEnabled(kind) {
13368
+ const json = toJSONSchema(kind.schema, {
13369
+ unrepresentable: "any",
13370
+ io: "input"
13371
+ });
13372
+ const properties = Reflect.get(json, "properties");
13373
+ return typeof properties === "object" && properties !== null && "enabled" in properties;
13374
+ }
13375
+ var RecordIntegrationInstances = class {
13376
+ records;
13377
+ kind;
13378
+ hooks;
13379
+ handle;
13380
+ secretKeys;
13381
+ secretMaps;
13382
+ nameField;
13383
+ /** The `integrations` registry owns the on/off switch (`role: devices`); the body has none. */
13384
+ registryOwnsEnabled;
13385
+ constructor(records, kind, hooks) {
13386
+ this.records = records;
13387
+ this.kind = kind;
13388
+ this.hooks = hooks;
13389
+ this.handle = records.kind(kind);
13390
+ this.secretKeys = topLevelSecretKeys(kind.declaration.secretPaths);
13391
+ this.secretMaps = secretMapKeys(kind.declaration.secretPaths);
13392
+ this.nameField = kind.declaration.entry?.nameField ?? "name";
13393
+ this.registryOwnsEnabled = hooks.description.role === "devices";
13394
+ if (this.registryOwnsEnabled && declaresEnabled(kind)) throw new Error(`kind "${kind.name}": the integrations registry owns the on/off switch of a role "devices" addon, so the body must not declare "enabled"`);
13395
+ }
13396
+ /**
13397
+ * One instance read for the addon's own runtime; null when absent. When the keychain is
13398
+ * locked the row is served WITHOUT its secrets and says so (`secrets: 'unavailable'`), so the
13399
+ * caller can keep what it had instead of reconfiguring with an empty secret (D49).
13400
+ */
13401
+ async readResolved(id) {
13402
+ try {
13403
+ const record = await this.handle.getResolved(id);
13404
+ return record === null ? null : {
13405
+ id,
13406
+ body: record.data,
13407
+ enabled: record.data.enabled !== false,
13408
+ secrets: "resolved"
13409
+ };
13410
+ } catch (err) {
13411
+ if (!(err instanceof RecordSecretUnavailableError)) throw err;
13412
+ const stored = await this.handle.get(id);
13413
+ if (stored === null) return null;
13414
+ return {
13415
+ id,
13416
+ body: Object.fromEntries(Object.entries(stored.data).filter(([key]) => !this.secretKeys.has(key))),
13417
+ enabled: stored.data.enabled !== false,
13418
+ secrets: "unavailable"
13419
+ };
13420
+ }
13421
+ }
13422
+ /** The body of {@link readResolved} alone; a locked keychain yields the row without secrets. */
13423
+ async getResolved(id) {
13424
+ return (await this.readResolved(id))?.body ?? null;
13425
+ }
13426
+ /** Every instance, secrets resolved where the keychain allows; an absent one is skipped. */
13427
+ async listResolved() {
13428
+ const page = await this.handle.query({ limit: INSTANCES_LIST_MAX });
13429
+ const out = [];
13430
+ for (const record of page.records) {
13431
+ const read = await this.readResolved(record.id);
13432
+ if (read !== null) out.push(read);
13433
+ }
13434
+ return out;
13435
+ }
13436
+ viewOf(record) {
13437
+ const shown = secretViewsOf(this.records.owner, this.kind.name, record.id, this.kind.declaration, record.data);
13438
+ const rawName = record.data[this.nameField];
13439
+ const kind = this.hooks.kindOf?.(record.data);
13440
+ const health = this.hooks.health?.(record.data, record.id);
13441
+ return {
13442
+ id: record.id,
13443
+ name: typeof rawName === "string" ? rawName : record.id,
13444
+ configured: this.hooks.configured(record.data),
13445
+ ...this.registryOwnsEnabled ? {} : { enabled: record.data.enabled !== false },
13446
+ formValues: shown,
13447
+ ...kind !== void 0 ? { kind } : {},
13448
+ ...health?.status !== void 0 ? { status: health.status } : {},
13449
+ ...health?.lastCheckedAt !== void 0 ? { lastCheckedAt: health.lastCheckedAt } : {}
13450
+ };
13451
+ }
13452
+ describe = async () => this.hooks.mintId === void 0 ? this.hooks.description : {
13453
+ ...this.hooks.description,
13454
+ mintsId: true
13455
+ };
13456
+ instanceFormSchema = async ({ id }) => this.hooks.formSchema(id);
13457
+ listInstances = async () => {
13458
+ return (await this.handle.query({ limit: INSTANCES_LIST_MAX })).records.map((record) => this.viewOf(record));
13459
+ };
13460
+ getInstance = async ({ id }) => {
13461
+ const record = await this.handle.get(id);
13462
+ return record === null ? null : this.viewOf(record);
13463
+ };
13464
+ /** Insert ONE row (`ifRev: 0`: an existing id is refused, never overwritten). */
13465
+ createInstance = async ({ id, name, kind }) => {
13466
+ const minted = id ?? this.hooks.mintId?.({
13467
+ name,
13468
+ ...kind !== void 0 ? { kind } : {}
13469
+ });
13470
+ if (minted === void 0) throw new Error("createInstance needs an id: this provider does not mint one");
13471
+ await this.handle.put({
13472
+ id: minted,
13473
+ data: this.hooks.initialBody(name, kind)
13474
+ }, { ifRev: 0 });
13475
+ await this.hooks.onChanged?.(minted, "created");
13476
+ return { id: minted };
13477
+ };
13478
+ updateInstance = async ({ id, name, values }) => {
13479
+ const patch = {};
13480
+ for (const [key, value] of Object.entries(values)) {
13481
+ if (value === void 0) continue;
13482
+ if (this.secretMaps.has(key)) {
13483
+ const entries = secretMapPatch(value);
13484
+ if (entries !== null) patch[key] = entries;
13485
+ } else if (!this.secretKeys.has(key)) patch[key] = value;
13486
+ else if (isSecretClear(value)) patch[key] = null;
13487
+ else if (typeof value === "string" && value !== "" && value !== "__camstack_redacted__" && !isSecretFieldView(value)) patch[key] = value;
13488
+ }
13489
+ if (name !== void 0) patch[this.nameField] = name;
13490
+ await this.handle.patch(id, patch);
13491
+ await this.hooks.onChanged?.(id, "updated");
13492
+ return { ok: true };
13493
+ };
13494
+ /** The switch lives in the record body; the addon is told so it applies it (D996). */
13495
+ setInstanceEnabled = async ({ id, enabled }) => {
13496
+ if (this.registryOwnsEnabled) throw new Error(`instance "${id}": the integrations registry owns the on/off switch of this addon; set it with integrations.update`);
13497
+ await this.handle.patch(id, { enabled });
13498
+ await this.hooks.onChanged?.(id, "enabled");
13499
+ return { ok: true };
13500
+ };
13501
+ /** The row and its keychain refs go together (the records door). */
13502
+ deleteInstance = async ({ id }) => {
13503
+ await this.handle.delete(id);
13504
+ await this.hooks.onChanged?.(id, "deleted");
13505
+ return { ok: true };
13506
+ };
13507
+ testInstance = async (input) => {
13508
+ if (this.hooks.test === void 0) return {
13509
+ success: false,
13510
+ status: "unsupported",
13511
+ error: "This integration declares no connection test"
13512
+ };
13513
+ return this.hooks.test(input);
13514
+ };
13515
+ /** The flat provider object to hand to `registerProvider`. */
13516
+ toProvider() {
13517
+ return {
13518
+ describe: this.describe,
13519
+ instanceFormSchema: this.instanceFormSchema,
13520
+ listInstances: this.listInstances,
13521
+ getInstance: this.getInstance,
13522
+ createInstance: this.createInstance,
13523
+ updateInstance: this.updateInstance,
13524
+ setInstanceEnabled: this.setInstanceEnabled,
13525
+ deleteInstance: this.deleteInstance,
13526
+ testInstance: this.testInstance
13527
+ };
13528
+ }
13529
+ };
12715
13530
  var EncodeProfileSchema = object({
12716
13531
  video: object({
12717
13532
  codec: _enum([
@@ -13747,7 +14562,13 @@ var MigrationLedgerEntrySchema = object({
13747
14562
  * joined by the engine from the catalogues it knows this boot. Absent when no
13748
14563
  * catalogue lists the id (a newer database).
13749
14564
  */
13750
- meta: MigrationMetaSchema.optional()
14565
+ meta: MigrationMetaSchema.optional(),
14566
+ /**
14567
+ * Set when this is an applied row of an addon owner whose catalogue the answering
14568
+ * process has not loaded (the owner has not declared yet): the row is applied, the
14569
+ * process just cannot judge it. Never `skipped-newer` — that needs the owner loaded.
14570
+ */
14571
+ ownerNotLoaded: boolean().optional()
13751
14572
  });
13752
14573
  /** A catalogued migration that is not applied, with where it stands. */
13753
14574
  var MigrationPendingEntrySchema = object({
@@ -13781,6 +14602,159 @@ var MigrationOwnerStepSchema = object({
13781
14602
  state: union([literal("pending"), MigrationStatusSchema])
13782
14603
  });
13783
14604
  /**
14605
+ * Move an integration's legacy `integration_settings` rows into a typed record of the addon's own
14606
+ * kind (planning#416, the one store). The record is keyed by the `integrations` registry id, so
14607
+ * the integration id, the devices stamped with it and the automations that name it do not change.
14608
+ *
14609
+ * Order, so a crash or a locked keychain is safe at every point:
14610
+ *
14611
+ * 1. Phase A, read only: every row of every integration of the addon is read with its secrets
14612
+ * resolved. One that cannot be read (a locked keychain) throws, naming the integration, before
14613
+ * anything is written; `block-owner` then holds the addon.
14614
+ * 2. Phase B, per integration: the addon's `bodyFrom` builds the body; the record is put with
14615
+ * `ifRev: 0` (an existing record is never overwritten). A record this pass CREATED is read back
14616
+ * and every secret leaf must equal what the rows held, else the record is deleted and the pass
14617
+ * throws; an EXISTING record must hold every secret the rows carry, else the rows are kept and
14618
+ * a warning names the path. Only then are the rows (and their keychain values) cleared.
14619
+ *
14620
+ * Idempotent: an integration whose rows are gone and whose record exists is skipped, so a rerun is
14621
+ * a no-op. A default integration with no rows still gets its record (an empty body, D985).
14622
+ * Never logs or throws a secret value; messages name integration ids and secret PATHS only.
14623
+ */
14624
+ function secretLeavesOf(body, spec) {
14625
+ const out = /* @__PURE__ */ new Map();
14626
+ for (const leaf of collectSecretLeaves(body, spec.secretPaths, spec.secretArrayKeys ?? {})) if (typeof leaf.value === "string" && leaf.value.length > 0) out.set(leaf.concrete, leaf.value);
14627
+ return out;
14628
+ }
14629
+ function why(err) {
14630
+ return err instanceof Error ? err.message : String(err);
14631
+ }
14632
+ async function moveIntegrationRowsToRecords(ports, spec) {
14633
+ const integrations = await ports.listIntegrations(spec.addonId);
14634
+ if (integrations.length === 0) return {
14635
+ outcome: "already-done",
14636
+ summary: { integrations: 0 }
14637
+ };
14638
+ const rowsOf = /* @__PURE__ */ new Map();
14639
+ for (const integration of integrations) try {
14640
+ rowsOf.set(integration.id, await ports.readRows(integration.id));
14641
+ } catch (err) {
14642
+ throw new Error(`integration '${integration.id}': the legacy settings cannot be read with their secrets (${why(err)}) - nothing moved`, { cause: err });
14643
+ }
14644
+ let created = 0;
14645
+ let cleared = 0;
14646
+ let kept = 0;
14647
+ for (const integration of integrations) {
14648
+ const values = rowsOf.get(integration.id) ?? {};
14649
+ const hasRows = Object.keys(values).length > 0;
14650
+ const body = spec.bodyFrom(values, ports, integration);
14651
+ const put = await ports.putRecord(integration.id, body);
14652
+ if (put === "created") created += 1;
14653
+ if (!hasRows) continue;
14654
+ const wanted = secretLeavesOf(body, spec);
14655
+ const back = await ports.readRecord(integration.id);
14656
+ if (back === null) throw new Error(`integration '${integration.id}': the record is gone after it was put`);
14657
+ const held = secretLeavesOf(back, spec);
14658
+ if (put === "created") {
14659
+ const wrong = [...wanted].filter(([path, value]) => held.get(path) !== value).map(([p]) => p);
14660
+ if (wrong.length > 0) {
14661
+ await ports.deleteRecord(integration.id);
14662
+ throw new Error(`integration '${integration.id}': ${wrong.join(", ")} did not read back from the record - the record was removed and the legacy settings are kept`);
14663
+ }
14664
+ } else {
14665
+ const missing = [...wanted].filter(([path]) => !held.has(path)).map(([p]) => p);
14666
+ if (missing.length > 0) {
14667
+ ports.warn(`integration '${integration.id}': the existing record holds no ${missing.join(", ")}; the legacy settings are kept, not cleared`);
14668
+ kept += 1;
14669
+ continue;
14670
+ }
14671
+ }
14672
+ await ports.clearRows(integration.id);
14673
+ cleared += 1;
14674
+ }
14675
+ return created === 0 && cleared === 0 ? {
14676
+ outcome: "already-done",
14677
+ summary: {
14678
+ integrations: integrations.length,
14679
+ kept
14680
+ }
14681
+ } : {
14682
+ outcome: "done",
14683
+ summary: {
14684
+ integrations: integrations.length,
14685
+ created,
14686
+ cleared,
14687
+ kept
14688
+ }
14689
+ };
14690
+ }
14691
+ /**
14692
+ * The addon-side ports of `moveIntegrationRowsToRecords` (planning#416). An addon runs the move
14693
+ * from its own process, so the leftover rows are reached through the migration-only door
14694
+ * (`migrations.readLegacyIntegrationRows` / `clearLegacyIntegrationRows`) on the hub's connection.
14695
+ * The door returns markers. This process is the owner, so it resolves and releases them with
14696
+ * `resolveSecretMarkers` — the same call the old settings door used — and only then asks the
14697
+ * door to delete the rows. The addon's own record kind is its records handle.
14698
+ */
14699
+ async function resolvedRows(stored, secrets) {
14700
+ if (secrets === null) return stored;
14701
+ const { value, unresolved } = await resolveSecretMarkers(stored, secrets);
14702
+ if (unresolved.length > 0) throw new Error(`${unresolved.length} secret(s) cannot be read from the keychain`);
14703
+ return value;
14704
+ }
14705
+ function integrationRowsPortsOverApi(deps) {
14706
+ const secrets = deps.secrets ?? null;
14707
+ return {
14708
+ warn: (message) => deps.log.warn(message),
14709
+ listIntegrations: async (addonId) => (await deps.api.list()).filter((i) => i.addonId === addonId).map((i) => ({
14710
+ id: i.id,
14711
+ name: i.name
14712
+ })),
14713
+ readRows: async (integrationId) => resolvedRows(await deps.api.readLegacyIntegrationRows({ integrationId }), secrets),
14714
+ putRecord: async (id, body) => {
14715
+ if (await deps.records.get(id) !== null) return "exists";
14716
+ try {
14717
+ await deps.records.put({
14718
+ id,
14719
+ data: body
14720
+ }, { ifRev: 0 });
14721
+ } catch (err) {
14722
+ if (err instanceof RevConflictError) return "exists";
14723
+ throw err;
14724
+ }
14725
+ return "created";
14726
+ },
14727
+ readRecord: async (id) => (await deps.records.getResolved(id))?.data ?? null,
14728
+ deleteRecord: async (id) => {
14729
+ await deps.records.delete(id);
14730
+ },
14731
+ clearRows: async (integrationId) => {
14732
+ const refs = collectSecretMarkerRefs(await deps.api.readLegacyIntegrationRows({ integrationId }));
14733
+ if (refs.length > 0 && secrets !== null) await secrets.delete(refs);
14734
+ await deps.api.clearLegacyIntegrationRows({ integrationId });
14735
+ }
14736
+ };
14737
+ }
14738
+ function defaultIntegrationApiOver(api) {
14739
+ return {
14740
+ list: () => api.integrations.list.query(),
14741
+ readLegacyIntegrationRows: (input) => api.migrations.readLegacyIntegrationRows.query(input),
14742
+ clearLegacyIntegrationRows: (input) => api.migrations.clearLegacyIntegrationRows.mutate(input),
14743
+ listDevices: (addonId) => api.deviceManager.listAll.query({
14744
+ addonId,
14745
+ projection: "slim"
14746
+ }),
14747
+ setDeviceIntegrationId: async (deviceId, integrationId) => {
14748
+ await api.deviceManager.setIntegrationId.mutate({
14749
+ deviceId,
14750
+ integrationId
14751
+ });
14752
+ },
14753
+ readDeviceHasConfig: async (deviceId) => Object.keys((await api.deviceManager.getDevice.query({ deviceId }))?.config ?? {}).length > 0,
14754
+ readDeviceIntegrationId: async (deviceId) => (await api.deviceManager.getDevice.query({ deviceId }))?.integrationId ?? null
14755
+ };
14756
+ }
14757
+ /**
13784
14758
  * The trainer contract — what the hub hands the cloud trainer and what it
13785
14759
  * gets back (cloud training, D805+).
13786
14760
  *
@@ -18865,24 +19839,52 @@ var APPLIANCE_CAP_VOCABULARY = {
18865
19839
  args: { on: false }
18866
19840
  },
18867
19841
  {
18868
- id: "petFountain.intervalOn",
18869
- method: "setPumpInterval",
19842
+ id: "petFountain.resetDailyConsumption",
19843
+ method: "resetDailyConsumption",
19844
+ label: t("Clear daily consumption", "Azzera il consumo giornaliero"),
19845
+ phrase: t("Clear the daily water consumption of {device}", "Azzera il consumo giornaliero di acqua di {device}"),
19846
+ icon: "rotate-ccw"
19847
+ }
19848
+ ],
19849
+ state: [{
19850
+ kind: "boolean",
19851
+ field: "empty",
19852
+ label: t("Tank empty", "Serbatoio vuoto"),
19853
+ whenTrue: t("When the tank of {device} is empty", "Quando il serbatoio di {device} è vuoto"),
19854
+ whenFalse: t("When the tank of {device} is refilled", "Quando il serbatoio di {device} viene riempito"),
19855
+ icon: "droplet"
19856
+ }, {
19857
+ kind: "numeric",
19858
+ field: "waterLevel",
19859
+ quantity: t("the water level", "il livello dell’acqua"),
19860
+ label: t("Water level", "Livello dell’acqua"),
19861
+ unit: "%",
19862
+ icon: "droplets"
19863
+ }]
19864
+ },
19865
+ "pump-cycle": {
19866
+ scope: "device",
19867
+ noun: t("Pump cycle", "Ciclo della pompa"),
19868
+ actions: [
19869
+ {
19870
+ id: "pumpCycle.on",
19871
+ method: "setEnabled",
18870
19872
  label: t("Pump cycle on", "Ciclo pompa attivo"),
18871
19873
  phrase: t("Run the pump of {device} on its on/off cycle", "Fai lavorare la pompa di {device} a ciclo acceso/spento"),
18872
19874
  icon: "timer",
18873
19875
  args: { on: true }
18874
19876
  },
18875
19877
  {
18876
- id: "petFountain.intervalOff",
18877
- method: "setPumpInterval",
19878
+ id: "pumpCycle.off",
19879
+ method: "setEnabled",
18878
19880
  label: t("Pump cycle off", "Ciclo pompa spento"),
18879
19881
  phrase: t("Run the pump of {device} continuously", "Fai lavorare la pompa di {device} in continuo"),
18880
19882
  icon: "timer-off",
18881
19883
  args: { on: false }
18882
19884
  },
18883
19885
  {
18884
- id: "petFountain.pumpOnMinutes",
18885
- method: "setPumpOnMinutes",
19886
+ id: "pumpCycle.onMinutes",
19887
+ method: "setOnMinutes",
18886
19888
  label: t("Set pump run time", "Imposta il tempo di lavoro della pompa"),
18887
19889
  phrase: t("Set the pump of {device} to run {minutes} minutes per cycle", "Imposta la pompa di {device} a lavorare {minutes} minuti per ciclo"),
18888
19890
  icon: "timer",
@@ -18898,8 +19900,8 @@ var APPLIANCE_CAP_VOCABULARY = {
18898
19900
  }]
18899
19901
  },
18900
19902
  {
18901
- id: "petFountain.pumpOffMinutes",
18902
- method: "setPumpOffMinutes",
19903
+ id: "pumpCycle.offMinutes",
19904
+ method: "setOffMinutes",
18903
19905
  label: t("Set pump rest time", "Imposta il tempo di riposo della pompa"),
18904
19906
  phrase: t("Set the pump of {device} to rest {minutes} minutes per cycle", "Imposta la pompa di {device} a riposare {minutes} minuti per ciclo"),
18905
19907
  icon: "timer-off",
@@ -18913,35 +19915,63 @@ var APPLIANCE_CAP_VOCABULARY = {
18913
19915
  unit: "min"
18914
19916
  }
18915
19917
  }]
18916
- },
18917
- {
18918
- id: "petFountain.resetDailyConsumption",
18919
- method: "resetDailyConsumption",
18920
- label: t("Clear daily consumption", "Azzera il consumo giornaliero"),
18921
- phrase: t("Clear the daily water consumption of {device}", "Azzera il consumo giornaliero di acqua di {device}"),
18922
- icon: "rotate-ccw"
18923
19918
  }
18924
19919
  ],
18925
19920
  state: [{
18926
19921
  kind: "boolean",
18927
- field: "empty",
18928
- label: t("Tank empty", "Serbatoio vuoto"),
18929
- whenTrue: t("When the tank of {device} is empty", "Quando il serbatoio di {device} è vuoto"),
18930
- whenFalse: t("When the tank of {device} is refilled", "Quando il serbatoio di {device} viene riempito"),
18931
- icon: "droplet"
18932
- }, {
18933
- kind: "numeric",
18934
- field: "waterLevel",
18935
- quantity: t("the water level", "il livello dell’acqua"),
18936
- label: t("Water level", "Livello dell’acqua"),
18937
- unit: "%",
18938
- icon: "droplets"
19922
+ field: "enabled",
19923
+ label: t("Pump cycle", "Ciclo pompa"),
19924
+ whenTrue: t("When {device} starts running its pump on a cycle", "Quando {device} inizia a far lavorare la pompa a ciclo"),
19925
+ whenFalse: t("When {device} runs its pump continuously", "Quando {device} fa lavorare la pompa in continuo"),
19926
+ icon: "timer"
18939
19927
  }]
18940
19928
  },
18941
19929
  "media-player": {
18942
19930
  scope: "device",
18943
19931
  noun: t("Media player", "Lettore multimediale"),
18944
19932
  actions: [
19933
+ {
19934
+ id: "media.turnOn",
19935
+ method: "turnOn",
19936
+ label: t("Turn on", "Accendi"),
19937
+ phrase: t("Turn on {device}", "Accendi {device}"),
19938
+ icon: "power"
19939
+ },
19940
+ {
19941
+ id: "media.turnOff",
19942
+ method: "turnOff",
19943
+ label: t("Turn off", "Spegni"),
19944
+ phrase: t("Turn off {device}", "Spegni {device}"),
19945
+ icon: "power"
19946
+ },
19947
+ {
19948
+ id: "media.volumeUp",
19949
+ method: "volumeUp",
19950
+ label: t("Volume up", "Alza il volume"),
19951
+ phrase: t("Raise the volume of {device}", "Alza il volume di {device}"),
19952
+ icon: "volume-2"
19953
+ },
19954
+ {
19955
+ id: "media.volumeDown",
19956
+ method: "volumeDown",
19957
+ label: t("Volume down", "Abbassa il volume"),
19958
+ phrase: t("Lower the volume of {device}", "Abbassa il volume di {device}"),
19959
+ icon: "volume-2"
19960
+ },
19961
+ {
19962
+ id: "media.channelUp",
19963
+ method: "channelUp",
19964
+ label: t("Channel up", "Canale successivo"),
19965
+ phrase: t("Go to the next channel on {device}", "Passa al canale successivo su {device}"),
19966
+ icon: "skip-forward"
19967
+ },
19968
+ {
19969
+ id: "media.channelDown",
19970
+ method: "channelDown",
19971
+ label: t("Channel down", "Canale precedente"),
19972
+ phrase: t("Go to the previous channel on {device}", "Torna al canale precedente su {device}"),
19973
+ icon: "skip-back"
19974
+ },
18945
19975
  {
18946
19976
  id: "media.play",
18947
19977
  method: "play",
@@ -20828,6 +21858,7 @@ var SYSTEM_CAP_VOCABULARY = {
20828
21858
  "audio-analyzer": system(PIPELINE),
20829
21859
  "audio-codec": system(INTERNAL),
20830
21860
  "auth-provider": system(IDENTITY),
21861
+ "board-key-source": system(INTERNAL),
20831
21862
  backup: system("system backups — run and restored from the Backups page"),
20832
21863
  broker: system("message-broker connections — configured, not actuated"),
20833
21864
  "calendar-source": system(INTERNAL),
@@ -45816,6 +46847,49 @@ var binaryCapability = {
45816
46847
  volatileStateFields: ["lastChangedAt"]
45817
46848
  };
45818
46849
  /**
46850
+ * Why a board key could not be read. Typed so a caller reports the cause and
46851
+ * never treats "could not read" as "has no key" (D49).
46852
+ */
46853
+ var BoardKeyFailureReasonSchema = _enum([
46854
+ "unknown-source",
46855
+ "not-admin",
46856
+ "no-builder",
46857
+ "no-ingress-url",
46858
+ "unreachable",
46859
+ "unknown-board",
46860
+ "no-encryption-key",
46861
+ "unreadable-config"
46862
+ ]);
46863
+ var BoardKeySourceSchema = object({
46864
+ sourceId: string(),
46865
+ name: string()
46866
+ });
46867
+ var BoardKeyBoardSchema = object({
46868
+ /** The builder's file name, e.g. `kitchen.yaml`: the handle `getBoardKey` takes. */
46869
+ configuration: string(),
46870
+ /** The node name the builder gives the board. */
46871
+ name: string(),
46872
+ /** The address the builder knows the board by, when it has one. */
46873
+ address: string().nullable()
46874
+ });
46875
+ var BoardKeyFailureSchema = object({
46876
+ ok: literal(false),
46877
+ reason: BoardKeyFailureReasonSchema,
46878
+ detail: string().optional()
46879
+ });
46880
+ var ListBoardsResultSchema = discriminatedUnion("ok", [object({
46881
+ ok: literal(true),
46882
+ boards: array(BoardKeyBoardSchema).readonly()
46883
+ }), BoardKeyFailureSchema]);
46884
+ var GetBoardKeyResultSchema = discriminatedUnion("ok", [object({
46885
+ ok: literal(true),
46886
+ key: string()
46887
+ }), BoardKeyFailureSchema]);
46888
+ method(_void(), array(BoardKeySourceSchema).readonly(), { auth: "admin" }), method(object({ sourceId: string().min(1) }), ListBoardsResultSchema, { auth: "admin" }), method(object({
46889
+ sourceId: string().min(1),
46890
+ configuration: string().min(1)
46891
+ }), GetBoardKeyResultSchema, { auth: "admin" });
46892
+ /**
45819
46893
  * Dimmable-light brightness control. Co-exists with `switch` on the
45820
46894
  * same device — the switch toggles on/off, this cap sets the level
45821
46895
  * applied when the light is on. Drivers map their per-vendor dim
@@ -48505,6 +49579,244 @@ var controlCapability = {
48505
49579
  */
48506
49580
  history: "none"
48507
49581
  };
49582
+ /**
49583
+ * Media-player cap. Models HA `media_player.*` (Sonos, Chromecast,
49584
+ * Apple TV, Spotify, Roku, generic OTT receivers, …) on
49585
+ * `DeviceType.MediaPlayer`. Disjoint from the camera streaming
49586
+ * surface — those use `DeviceType.Camera` + the broker pipeline.
49587
+ *
49588
+ * The cap declares a wide method surface; not every backend supports
49589
+ * every method. Drivers signal sub-capability via the
49590
+ * `DeviceFeature.MediaPlayerXxx` flags (paired one-to-one with the
49591
+ * corresponding method) so the UI gates buttons without a slice
49592
+ * fetch — same pattern as `PanTiltZoom` for cameras.
49593
+ */
49594
+ var MediaPlayerStateSchema = _enum([
49595
+ "off",
49596
+ "on",
49597
+ "idle",
49598
+ "playing",
49599
+ "paused",
49600
+ "buffering",
49601
+ "standby"
49602
+ ]);
49603
+ var MediaPlayerRepeatSchema = _enum([
49604
+ "off",
49605
+ "all",
49606
+ "one"
49607
+ ]);
49608
+ var MediaInfoSchema = object({
49609
+ /** Free-form media kind (`music`, `tvshow`, `movie`, `app`, `channel`,
49610
+ * `podcast`, …). */
49611
+ type: string(),
49612
+ /** Human-readable title. */
49613
+ title: string(),
49614
+ /** Optional artist / channel / station label. */
49615
+ artist: string().optional(),
49616
+ /** Optional album / season / show name. */
49617
+ album: string().optional(),
49618
+ /** Optional cover-art / thumbnail URL. */
49619
+ imageUrl: string().optional()
49620
+ });
49621
+ /**
49622
+ * Where `state`, `volumeLevel`, `isMuted` and `source` come from. `reported`:
49623
+ * the device said so. `assumed`: the driver has no feedback (infrared) and
49624
+ * tracks what it last SENT; it moves only after a send was accepted, and a
49625
+ * human at the real remote makes it wrong. A UI shows an assumed value as a
49626
+ * guess, never as a reading.
49627
+ */
49628
+ var MediaPlayerStateSourceSchema = _enum(["reported", "assumed"]);
49629
+ /** The fields of a media-player status a driver can only guess. */
49630
+ var MediaPlayerAssumedFieldSchema = _enum([
49631
+ "state",
49632
+ "volumeLevel",
49633
+ "isMuted",
49634
+ "source"
49635
+ ]);
49636
+ var MediaPlayerStatusSchema = object({
49637
+ /** Playback lifecycle state. */
49638
+ state: MediaPlayerStateSchema,
49639
+ /**
49640
+ * Whether the state fields are readings or the driver's own bookkeeping.
49641
+ * A slice written before this field existed parses as `reported`.
49642
+ */
49643
+ stateSource: MediaPlayerStateSourceSchema.default("reported"),
49644
+ /**
49645
+ * Which fields are the driver's own guess. `stateSource` is `assumed` when
49646
+ * this is not empty; a field not listed here is a reading even then (power
49647
+ * from a running-state source, mute guessed from the last send).
49648
+ */
49649
+ assumedFields: array(MediaPlayerAssumedFieldSchema).default([]),
49650
+ /** Volume as 0..100 inclusive. Null when the device has no volume
49651
+ * surface. Pair with `DeviceFeature.MediaPlayerVolume`. */
49652
+ volumeLevel: number().min(0).max(100).nullable().meta(readingMeta("percentage")),
49653
+ /** Mute toggle distinct from volume=0. Null when no mute surface.
49654
+ * Pair with `DeviceFeature.MediaPlayerMute`. */
49655
+ isMuted: boolean().nullable(),
49656
+ /** Active source / input. Empty when no source surface. */
49657
+ source: string(),
49658
+ /** Selectable sources. Empty when no source surface.
49659
+ * Pair with `DeviceFeature.MediaPlayerSelectSource`. */
49660
+ availableSources: array(string()),
49661
+ /** Currently-playing media info. Null when nothing is playing. */
49662
+ currentMedia: MediaInfoSchema.nullable(),
49663
+ /** Current playback position in ms. Null when not seekable or
49664
+ * nothing is playing. Pair with `DeviceFeature.MediaPlayerSeek`. */
49665
+ position: number().int().nonnegative().nullable().meta(readingMeta("duration-ms")),
49666
+ /** Total duration of the current media in ms. Null when unknown
49667
+ * (live stream) or nothing is playing. */
49668
+ duration: number().int().nonnegative().nullable().meta(readingMeta("duration-ms")),
49669
+ /** Shuffle toggle. Null when no shuffle surface.
49670
+ * Pair with `DeviceFeature.MediaPlayerShuffle`. */
49671
+ shuffle: boolean().nullable(),
49672
+ /** Repeat mode. Null when no repeat surface.
49673
+ * Pair with `DeviceFeature.MediaPlayerRepeat`. */
49674
+ repeat: MediaPlayerRepeatSchema.nullable(),
49675
+ /** Ms epoch when the slice was last updated. */
49676
+ lastChangedAt: number()
49677
+ });
49678
+ var stepInput = object({
49679
+ deviceId: number().int().nonnegative(),
49680
+ /** How many presses: the caller's count (Alexa `volumeSteps`, `channelCount`). */
49681
+ steps: number().int().min(1).max(50).default(1)
49682
+ });
49683
+ var deviceOnly = object({ deviceId: number().int().nonnegative() });
49684
+ var mediaPlayerCapability = {
49685
+ name: "media-player",
49686
+ scope: "device",
49687
+ deviceNative: true,
49688
+ mode: "singleton",
49689
+ deviceTypes: [DeviceType.MediaPlayer],
49690
+ methods: {
49691
+ turnOn: method(deviceOnly, _void(), {
49692
+ kind: "mutation",
49693
+ auth: "protected"
49694
+ }),
49695
+ turnOff: method(deviceOnly, _void(), {
49696
+ kind: "mutation",
49697
+ auth: "protected"
49698
+ }),
49699
+ volumeUp: method(stepInput, _void(), {
49700
+ kind: "mutation",
49701
+ auth: "protected"
49702
+ }),
49703
+ volumeDown: method(stepInput, _void(), {
49704
+ kind: "mutation",
49705
+ auth: "protected"
49706
+ }),
49707
+ channelUp: method(stepInput, _void(), {
49708
+ kind: "mutation",
49709
+ auth: "protected"
49710
+ }),
49711
+ channelDown: method(stepInput, _void(), {
49712
+ kind: "mutation",
49713
+ auth: "protected"
49714
+ }),
49715
+ play: method(object({ deviceId: number().int().nonnegative() }), _void(), {
49716
+ kind: "mutation",
49717
+ auth: "protected"
49718
+ }),
49719
+ pause: method(object({ deviceId: number().int().nonnegative() }), _void(), {
49720
+ kind: "mutation",
49721
+ auth: "protected"
49722
+ }),
49723
+ stop: method(object({ deviceId: number().int().nonnegative() }), _void(), {
49724
+ kind: "mutation",
49725
+ auth: "protected"
49726
+ }),
49727
+ next: method(object({ deviceId: number().int().nonnegative() }), _void(), {
49728
+ kind: "mutation",
49729
+ auth: "protected"
49730
+ }),
49731
+ previous: method(object({ deviceId: number().int().nonnegative() }), _void(), {
49732
+ kind: "mutation",
49733
+ auth: "protected"
49734
+ }),
49735
+ seek: method(object({
49736
+ deviceId: number().int().nonnegative(),
49737
+ position: number().int().nonnegative()
49738
+ }), _void(), {
49739
+ kind: "mutation",
49740
+ auth: "protected"
49741
+ }),
49742
+ setVolume: method(object({
49743
+ deviceId: number().int().nonnegative(),
49744
+ volumeLevel: number().min(0).max(100)
49745
+ }), _void(), {
49746
+ kind: "mutation",
49747
+ auth: "protected"
49748
+ }),
49749
+ setMute: method(object({
49750
+ deviceId: number().int().nonnegative(),
49751
+ muted: boolean()
49752
+ }), _void(), {
49753
+ kind: "mutation",
49754
+ auth: "protected"
49755
+ }),
49756
+ setShuffle: method(object({
49757
+ deviceId: number().int().nonnegative(),
49758
+ shuffle: boolean()
49759
+ }), _void(), {
49760
+ kind: "mutation",
49761
+ auth: "protected"
49762
+ }),
49763
+ setRepeat: method(object({
49764
+ deviceId: number().int().nonnegative(),
49765
+ repeat: MediaPlayerRepeatSchema
49766
+ }), _void(), {
49767
+ kind: "mutation",
49768
+ auth: "protected"
49769
+ }),
49770
+ selectSource: method(object({
49771
+ deviceId: number().int().nonnegative(),
49772
+ source: string().min(1)
49773
+ }), _void(), {
49774
+ kind: "mutation",
49775
+ auth: "protected"
49776
+ }),
49777
+ playMedia: method(object({
49778
+ deviceId: number().int().nonnegative(),
49779
+ /** Media identifier / URL. */
49780
+ mediaId: string().min(1),
49781
+ /** Media kind (`music`, `tvshow`, `movie`, `app`, …) — provider
49782
+ * passes it through to the upstream service. */
49783
+ mediaType: string().min(1)
49784
+ }), _void(), {
49785
+ kind: "mutation",
49786
+ auth: "protected"
49787
+ })
49788
+ },
49789
+ status: {
49790
+ schema: MediaPlayerStatusSchema,
49791
+ kind: "push"
49792
+ },
49793
+ /**
49794
+ * Runtime-state slice — mirrored by the kernel. UI players read the
49795
+ * full slice for live now-playing, volume, and progress updates
49796
+ * without polling.
49797
+ */
49798
+ runtimeState: MediaPlayerStatusSchema,
49799
+ /**
49800
+ * Runtime-state durability: **session** — a restored transport position describes a playback that stopped when the hub did.
49801
+ *
49802
+ * See `RuntimeStateDurability`. Enforced by
49803
+ * `scripts/check-runtime-state-durability.ts`.
49804
+ */
49805
+ durability: "session",
49806
+ /**
49807
+ * History (D850): volume (a level an operator or an automation sets; the
49808
+ * default 10 s floor folds a slider drag into its end value) and mute.
49809
+ * `position` is not recorded: it moves continuously while playing.
49810
+ */
49811
+ history: { fields: {
49812
+ volumeLevel: {
49813
+ kind: "gauge",
49814
+ unit: "%",
49815
+ deadband: 1
49816
+ },
49817
+ isMuted: { kind: "boolean" }
49818
+ } }
49819
+ };
48508
49820
  DeviceType.Camera, DeviceType.Sensor, DeviceType.Button, DeviceType.Switch, DeviceType.PetFeeder, DeviceType.Container, DeviceType.Thermostat, DeviceType.EventEmitter, DeviceType.Camera, DeviceType.Hub, DeviceType.Light, DeviceType.Siren, DeviceType.Switch, DeviceType.Sensor, DeviceType.Thermostat, DeviceType.Climate, DeviceType.Button, DeviceType.EventEmitter, DeviceType.Update, DeviceType.Generic, DeviceType.Notifier, DeviceType.Script, DeviceType.Automation, DeviceType.Lock, DeviceType.Cover, DeviceType.Valve, DeviceType.Humidifier, DeviceType.WaterHeater, DeviceType.Fan, DeviceType.MediaPlayer, DeviceType.AlarmPanel, DeviceType.Control, DeviceType.Presence, DeviceType.Weather, DeviceType.Vacuum, DeviceType.LawnMower, DeviceType.Container, DeviceType.Image, DeviceType.PetFeeder, DeviceType.PetFountain, DeviceType.Dishwasher, DeviceType.Washer, DeviceType.Heater, DeviceType.Dryer, DeviceType.Gateway, DeviceType.Camera, DeviceType.Fan, DeviceType.Lock, DeviceType.Camera, DeviceType.Switch, DeviceType.Light, DeviceType.Fan, DeviceType.Climate, DeviceType.Thermostat, DeviceType.Humidifier, DeviceType.WaterHeater, DeviceType.MediaPlayer, DeviceType.Washer, DeviceType.Dryer, DeviceType.Dishwasher, DeviceType.Vacuum, DeviceType.LawnMower, DeviceType.PetFeeder, DeviceType.Heater, DeviceType.Switch, DeviceType.Light, DeviceType.Fan, DeviceType.Climate, DeviceType.Thermostat, DeviceType.Humidifier, DeviceType.WaterHeater, DeviceType.MediaPlayer, DeviceType.Washer, DeviceType.Dryer, DeviceType.Dishwasher, DeviceType.Vacuum, DeviceType.LawnMower, DeviceType.PetFeeder, DeviceType.Heater, DeviceType.Switch, DeviceType.Light, DeviceType.Fan, DeviceType.Climate, DeviceType.Thermostat, DeviceType.Humidifier, DeviceType.WaterHeater, DeviceType.MediaPlayer, DeviceType.Washer, DeviceType.Dryer, DeviceType.Dishwasher, DeviceType.Vacuum, DeviceType.LawnMower, DeviceType.PetFeeder, DeviceType.Heater, DeviceType.Switch, DeviceType.Light, DeviceType.Fan, DeviceType.Climate, DeviceType.Thermostat, DeviceType.Humidifier, DeviceType.WaterHeater, DeviceType.MediaPlayer, DeviceType.Washer, DeviceType.Dryer, DeviceType.Dishwasher, DeviceType.Vacuum, DeviceType.LawnMower, DeviceType.PetFeeder, DeviceType.Heater, DeviceType.Gateway, DeviceType.Hub, DeviceType.Camera, DeviceType.Sensor, DeviceType.MediaPlayer, DeviceType.Vacuum, DeviceType.Generic, DeviceType.Washer, DeviceType.Dryer, DeviceType.Dishwasher, DeviceType.PetFountain, DeviceType.Fan, DeviceType.Humidifier, DeviceType.Climate, DeviceType.WaterHeater, DeviceType.MediaPlayer, DeviceType.Washer, DeviceType.Dryer, DeviceType.Dishwasher, DeviceType.Vacuum, DeviceType.LawnMower, DeviceType.MediaPlayer, DeviceType.WaterHeater, DeviceType.Humidifier, DeviceType.Fan, DeviceType.Climate, DeviceType.Thermostat, DeviceType.PetFeeder, DeviceType.Heater;
48509
49821
  var NUMBER = {
48510
49822
  kind: "fixed",
@@ -48952,117 +50264,6 @@ function actuator(input) {
48952
50264
  };
48953
50265
  }
48954
50266
  new Map(GROUP_TEMPLATES.map((template) => [template.id, template]));
48955
- var PowerSourceRefusalReasonSchema = _enum([
48956
- "no-power-source",
48957
- "switch-missing",
48958
- "switch-offline",
48959
- "switch-unknown",
48960
- "restart-in-progress",
48961
- "switch-call-failed"
48962
- ]);
48963
- var PowerSourceActionResultSchema = discriminatedUnion("accepted", [object({ accepted: literal(true) }), object({
48964
- accepted: literal(false),
48965
- reason: PowerSourceRefusalReasonSchema,
48966
- /** One line for the operator, naming the switch. */
48967
- message: string()
48968
- })]);
48969
- var PowerSourceInfoSchema = object({
48970
- /** False when the device has no power source linked; the rest is then empty. */
48971
- linked: boolean(),
48972
- switchDeviceId: number().nullable(),
48973
- switchName: string().nullable(),
48974
- /** The switch's on/off state, or null when it is unknown. Never false for unknown (D393). */
48975
- switchOn: boolean().nullable(),
48976
- switchOnline: boolean().nullable(),
48977
- restartInProgress: boolean(),
48978
- offSeconds: number().int()
48979
- });
48980
- /** The composed slice: the switch state the link mirrors, plus the stored off time. */
48981
- var PowerSourceStateSchema = object({
48982
- /** Null while the switch has not reported: unknown is never `false` (D393). */
48983
- switchOn: boolean().nullable(),
48984
- offSeconds: number().int(),
48985
- lastFetchedAt: number()
48986
- });
48987
- var POWER_SOURCE_DEVICE_TYPES = [
48988
- DeviceType.Gateway,
48989
- DeviceType.Hub,
48990
- DeviceType.Camera,
48991
- DeviceType.Sensor,
48992
- DeviceType.MediaPlayer,
48993
- DeviceType.Vacuum,
48994
- DeviceType.Generic,
48995
- DeviceType.Washer,
48996
- DeviceType.Dryer,
48997
- DeviceType.Dishwasher,
48998
- DeviceType.PetFountain,
48999
- DeviceType.Fan,
49000
- DeviceType.Humidifier,
49001
- DeviceType.Climate,
49002
- DeviceType.WaterHeater
49003
- ];
49004
- var powerSourceCustomize = {
49005
- version: 1,
49006
- targets: [{
49007
- id: "switch",
49008
- cardinality: "scalar",
49009
- vocabulary: {
49010
- cap: "power-source",
49011
- stateField: "switchOn"
49012
- },
49013
- deviceTypes: POWER_SOURCE_DEVICE_TYPES,
49014
- apply: "add",
49015
- path: "switchOn",
49016
- sources: [{
49017
- kind: "switch",
49018
- transforms: [{ kind: "identity" }]
49019
- }],
49020
- companions: [{
49021
- kind: "constant",
49022
- path: "offSeconds",
49023
- value: 10,
49024
- when: "add"
49025
- }, {
49026
- kind: "clock",
49027
- path: "lastFetchedAt",
49028
- when: "always"
49029
- }],
49030
- sourceReport: { status: "assignment-status" }
49031
- }]
49032
- };
49033
- var deviceInput$2 = object({ deviceId: number().int().nonnegative() });
49034
- var powerSourceCapability = {
49035
- name: "power-source",
49036
- scope: "device",
49037
- mode: "singleton",
49038
- deviceTypes: POWER_SOURCE_DEVICE_TYPES,
49039
- methods: {
49040
- getStatus: systemMethod(deviceInput$2, PowerSourceInfoSchema, { auth: "admin" }),
49041
- powerOn: systemMethod(deviceInput$2, PowerSourceActionResultSchema, {
49042
- kind: "mutation",
49043
- auth: "admin"
49044
- }),
49045
- powerOff: systemMethod(deviceInput$2, PowerSourceActionResultSchema, {
49046
- kind: "mutation",
49047
- auth: "admin"
49048
- }),
49049
- forceRestart: systemMethod(deviceInput$2, PowerSourceActionResultSchema, {
49050
- kind: "mutation",
49051
- auth: "admin"
49052
- })
49053
- },
49054
- runtimeState: PowerSourceStateSchema,
49055
- customize: powerSourceCustomize,
49056
- /**
49057
- * Runtime-state durability: **session** — mirrored from the linked switch on
49058
- * its next report; a restored value would outlive the reading it names.
49059
- *
49060
- * See `RuntimeStateDurability`. Enforced by
49061
- * `scripts/check-runtime-state-durability.ts`.
49062
- */
49063
- durability: "session",
49064
- history: "none"
49065
- };
49066
50267
  DeviceFeature.LightColorRgb, DeviceFeature.LightColorHsv, DeviceFeature.LightColorMired;
49067
50268
  DeviceType.Camera;
49068
50269
  `${COMPOSED_DEVICE_STABLE_ID_PREFIX}`;
@@ -49090,6 +50291,168 @@ var ComposableCapabilitiesSchema = object({ caps: array(object({
49090
50291
  }).optional()
49091
50292
  })) });
49092
50293
  /**
50294
+ * A saved Customize assignment (D936). The schema is the type: callers use
50295
+ * `z.infer`, they do not restate the shape.
50296
+ */
50297
+ var OverrideSourceSchema = object({
50298
+ addonId: string().min(1),
50299
+ stableId: string().min(1),
50300
+ cap: string().min(1),
50301
+ fieldPath: string().min(1)
50302
+ });
50303
+ var IdentityTransformDraftSchema = object({ kind: literal("identity") });
50304
+ var InvertTransformDraftSchema = object({ kind: literal("invert") });
50305
+ var ThresholdTransformDraftSchema = object({
50306
+ kind: literal("threshold"),
50307
+ comparison: _enum(["gte", "lte"]),
50308
+ threshold: number(),
50309
+ startDwellMs: number().nonnegative(),
50310
+ stopDwellMs: number().nonnegative()
50311
+ });
50312
+ var CustomizeTransformDraftSchema = discriminatedUnion("kind", [
50313
+ IdentityTransformDraftSchema,
50314
+ InvertTransformDraftSchema,
50315
+ ThresholdTransformDraftSchema,
50316
+ object({
50317
+ kind: literal("linear"),
50318
+ scale: number(),
50319
+ offset: number(),
50320
+ clampMin: number().optional(),
50321
+ clampMax: number().optional()
50322
+ }),
50323
+ object({
50324
+ kind: literal("enum-map"),
50325
+ mapping: record(string(), string().nullable())
50326
+ }),
50327
+ object({ kind: literal("number") })
50328
+ ]);
50329
+ var ScalarOverrideDraftSchema = object({
50330
+ kind: literal("scalar"),
50331
+ cap: string().min(1),
50332
+ targetId: string().min(1),
50333
+ source: OverrideSourceSchema,
50334
+ transform: CustomizeTransformDraftSchema
50335
+ });
50336
+ var KeyedArrayOverrideDraftSchema = object({
50337
+ kind: literal("keyedArray"),
50338
+ cap: string().min(1),
50339
+ targetId: string().min(1),
50340
+ key: string().min(1),
50341
+ label: string().min(1),
50342
+ fieldPath: string().min(1),
50343
+ source: OverrideSourceSchema,
50344
+ transform: CustomizeTransformDraftSchema
50345
+ });
50346
+ var PulseOverrideDraftSchema = object({
50347
+ kind: literal("pulse"),
50348
+ cap: string().min(1),
50349
+ targetId: string().min(1),
50350
+ enabled: boolean(),
50351
+ debounceMs: number().nonnegative(),
50352
+ edges: array(_enum([
50353
+ "rising",
50354
+ "button",
50355
+ "native-event"
50356
+ ])).min(1).optional(),
50357
+ sources: array(OverrideSourceSchema).min(1)
50358
+ });
50359
+ var SpanSourceDraftSchema = OverrideSourceSchema.extend({ mode: _enum([
50360
+ "in-addition",
50361
+ "confirm",
50362
+ "replace"
50363
+ ]).optional() });
50364
+ discriminatedUnion("kind", [
50365
+ ScalarOverrideDraftSchema,
50366
+ KeyedArrayOverrideDraftSchema,
50367
+ PulseOverrideDraftSchema,
50368
+ object({
50369
+ kind: literal("span"),
50370
+ cap: string().min(1),
50371
+ targetId: string().min(1),
50372
+ timeoutMs: number().nonnegative(),
50373
+ cooldownMs: number().nonnegative().optional(),
50374
+ sources: array(SpanSourceDraftSchema)
50375
+ })
50376
+ ]);
50377
+ object({
50378
+ targetId: string().min(1),
50379
+ configured: boolean(),
50380
+ source: _enum(["native", "assigned"]),
50381
+ state: _enum([
50382
+ "active",
50383
+ "stale",
50384
+ "released",
50385
+ "unavailable"
50386
+ ]),
50387
+ reason: string().nullable()
50388
+ });
50389
+ /**
50390
+ * What a running-threshold proposal says (planning#405). The schema is the
50391
+ * type: the algorithm, the capability method and the UI all read `z.infer`.
50392
+ *
50393
+ * A proposal is read-only advice: it carries the numbers it was derived from
50394
+ * (`evidence`) so the operator can judge it, and an `insufficient` answer names
50395
+ * WHY with a typed reason and the catalog defaults, never an invented number.
50396
+ */
50397
+ var RunningProposalTierSchema = _enum(["raw", "5m"]);
50398
+ var RunningProposalConfidenceSchema = _enum([
50399
+ "high",
50400
+ "medium",
50401
+ "low"
50402
+ ]);
50403
+ var RunningProposalInsufficientReasonSchema = _enum([
50404
+ "no-history",
50405
+ "span-too-short",
50406
+ "truncated",
50407
+ "no-idle-floor",
50408
+ "no-runs",
50409
+ "no-separation"
50410
+ ]);
50411
+ var RunningProposalReplaySchema = object({
50412
+ /** Intervals the real dwell expression held true over the window. */
50413
+ intervals: number().int().nonnegative(),
50414
+ /** Intervals outside every run, or a second interval inside one. */
50415
+ extra: number().int().nonnegative(),
50416
+ /** Runs without an interval of their own (none, or merged into a neighbour). */
50417
+ missed: number().int().nonnegative()
50418
+ });
50419
+ var RunningProposalEvidenceSchema = object({
50420
+ tier: RunningProposalTierSchema,
50421
+ spanMs: number().nonnegative(),
50422
+ from: number(),
50423
+ to: number(),
50424
+ points: number().int().nonnegative(),
50425
+ runsFound: number().int().nonnegative(),
50426
+ pausesFound: number().int().nonnegative(),
50427
+ longestPauseMs: number().nonnegative(),
50428
+ /** Episodes shorter than ~90 s (an anti-crease pulse, a display waking): never a run, never a pause. */
50429
+ pulsesFound: number().int().nonnegative(),
50430
+ longestPulseMs: number().nonnegative(),
50431
+ idleFloorW: number(),
50432
+ noiseCeilingW: number(),
50433
+ plateauW: number(),
50434
+ replay: RunningProposalReplaySchema
50435
+ });
50436
+ var RunningProposalInsufficientEvidenceSchema = object({
50437
+ spanMs: number().nonnegative(),
50438
+ points: number().int().nonnegative(),
50439
+ runsFound: number().int().nonnegative()
50440
+ });
50441
+ var RunningThresholdProposalSchema = discriminatedUnion("state", [object({
50442
+ state: literal("proposal"),
50443
+ transform: ThresholdTransformDraftSchema,
50444
+ evidence: RunningProposalEvidenceSchema,
50445
+ confidence: RunningProposalConfidenceSchema,
50446
+ /** Why the confidence is not higher; empty when nothing held it back. */
50447
+ notes: array(string())
50448
+ }), object({
50449
+ state: literal("insufficient"),
50450
+ reason: RunningProposalInsufficientReasonSchema,
50451
+ evidence: RunningProposalInsufficientEvidenceSchema,
50452
+ /** The catalog defaults, offered as what stands when nothing better is known. */
50453
+ fallback: ThresholdTransformDraftSchema
50454
+ })]);
50455
+ /**
49093
50456
  * The report of a one-shot "move this owner's plaintext secrets into the
49094
50457
  * keychain" run (D878). COUNTS only - never a value, never a ref.
49095
50458
  *
@@ -49379,6 +50742,14 @@ method(object({}), object({ blocks: array(CoreBlockSchema) }), { auth: "admin" }
49379
50742
  kind: "mutation",
49380
50743
  auth: "admin",
49381
50744
  access: "view"
50745
+ }), method(object({
50746
+ deviceId: number().int(),
50747
+ cap: string().min(1),
50748
+ fieldPath: string().min(1),
50749
+ deviceType: _enum(DeviceType).optional()
50750
+ }), RunningThresholdProposalSchema, {
50751
+ auth: "admin",
50752
+ access: "view"
49382
50753
  }), method(object({
49383
50754
  blockId: string().min(1),
49384
50755
  trace: AutomationRunTraceSchema.optional(),
@@ -50355,7 +51726,27 @@ method(object({
50355
51726
  * exposes only the COMMON surface: link state, supported device
50356
51727
  * kinds (so the UI can filter the device picker), and per-device
50357
51728
  * expose/unexpose.
50358
- */
51729
+ *
51730
+ * INSTANCES. One export addon can serve several independent targets (a
51731
+ * HomeKit bridge, a Home Assistant broker). `listInstances` names them.
51732
+ * `instanceId` on a READ is optional: absent = the whole addon (linked if any
51733
+ * enabled instance is, `exposedDeviceCount` = distinct devices, `setup` = the
51734
+ * default instance's); present = that instance; an id the provider does not
51735
+ * serve is refused with `ExportInstanceUnknownError` (`export-instance-unknown`),
51736
+ * never answered empty. `instanceId` on a WRITE is REQUIRED: a membership
51737
+ * change always names the target it changes. A single-instance provider
51738
+ * accepts an absent id on a read or its own id, and refuses any other.
51739
+ */
51740
+ /** Which instance of an export addon a call addresses. Absent on a read = the whole addon. */
51741
+ var InstanceIdSchema$1 = string().min(1);
51742
+ var InstancePinSchema = object({ instanceId: InstanceIdSchema$1.optional() });
51743
+ /** One independent export target of an addon. */
51744
+ var ExportInstanceSchema = object({
51745
+ instanceId: InstanceIdSchema$1,
51746
+ name: string(),
51747
+ enabled: boolean(),
51748
+ kind: string().optional()
51749
+ });
50359
51750
  var LinkStateSchema = _enum([
50360
51751
  "unlinked",
50361
51752
  "linked",
@@ -50406,10 +51797,14 @@ var ExposedDeviceSchema = object({
50406
51797
  capabilities: array(string()).optional()
50407
51798
  });
50408
51799
  var ExposeInputSchema = object({
51800
+ instanceId: InstanceIdSchema$1,
50409
51801
  deviceId: string(),
50410
51802
  capabilities: array(string()).optional()
50411
51803
  });
50412
- var UnexposeInputSchema = object({ deviceId: string() });
51804
+ var UnexposeInputSchema = object({
51805
+ instanceId: InstanceIdSchema$1,
51806
+ deviceId: string()
51807
+ });
50413
51808
  /**
50414
51809
  * What an exporter may expose besides devices (D968). An action and a
50415
51810
  * notification target are LIST ENTRIES, never devices (D954): they enter an
@@ -50438,15 +51833,21 @@ var ExposedEntitySchema = object({
50438
51833
  entity: ExportEntityRefSchema,
50439
51834
  exposedAs: string().optional()
50440
51835
  });
50441
- var ExposeEntityInputSchema = object({ entity: ExportEntityRefSchema });
50442
- var UnexposeEntityInputSchema = object({ entity: ExportEntityRefSchema });
50443
- method(_void(), DeviceExportStatusSchema), method(_void(), array(DeviceKindSchema)), method(_void(), array(ExposedDeviceSchema)), method(ExposeInputSchema, _void(), {
51836
+ var ExposeEntityInputSchema = object({
51837
+ instanceId: InstanceIdSchema$1,
51838
+ entity: ExportEntityRefSchema
51839
+ });
51840
+ var UnexposeEntityInputSchema = object({
51841
+ instanceId: InstanceIdSchema$1,
51842
+ entity: ExportEntityRefSchema
51843
+ });
51844
+ method(InstancePinSchema, DeviceExportStatusSchema), method(_void(), array(ExportInstanceSchema)), method(InstancePinSchema, array(DeviceKindSchema)), method(InstancePinSchema, array(ExposedDeviceSchema)), method(ExposeInputSchema, _void(), {
50444
51845
  kind: "mutation",
50445
51846
  auth: "admin"
50446
51847
  }), method(UnexposeInputSchema, _void(), {
50447
51848
  kind: "mutation",
50448
51849
  auth: "admin"
50449
- }), optionalMethod(_void(), array(ExportEntityKindSchema)), optionalMethod(_void(), array(ExposedEntitySchema)), optionalMethod(ExposeEntityInputSchema, _void(), {
51850
+ }), optionalMethod(_void(), array(ExportEntityKindSchema)), optionalMethod(InstancePinSchema, array(ExposedEntitySchema)), optionalMethod(ExposeEntityInputSchema, _void(), {
50450
51851
  kind: "mutation",
50451
51852
  auth: "admin"
50452
51853
  }), optionalMethod(UnexposeEntityInputSchema, _void(), {
@@ -52448,7 +53849,7 @@ var DishwasherStatusSchema = object({
52448
53849
  /** Ms epoch of the last value received from the appliance; 0 = never. */
52449
53850
  lastFetchedAt: number()
52450
53851
  });
52451
- var DeviceIdSchema$1 = number().int().nonnegative();
53852
+ var DeviceIdSchema$2 = number().int().nonnegative();
52452
53853
  /** A value a program option or setting can take. */
52453
53854
  var DishwasherValueSchema = union([
52454
53855
  boolean(),
@@ -52523,77 +53924,77 @@ var dishwasherCapability = {
52523
53924
  * option feature keys; each is checked against the program's constraints.
52524
53925
  */
52525
53926
  start: method(object({
52526
- deviceId: DeviceIdSchema$1,
53927
+ deviceId: DeviceIdSchema$2,
52527
53928
  program: string().min(1).optional(),
52528
53929
  options: record(string(), DishwasherValueSchema).optional()
52529
53930
  }), _void(), {
52530
53931
  kind: "mutation",
52531
53932
  auth: "protected"
52532
53933
  }),
52533
- pause: method(object({ deviceId: DeviceIdSchema$1 }), _void(), {
53934
+ pause: method(object({ deviceId: DeviceIdSchema$2 }), _void(), {
52534
53935
  kind: "mutation",
52535
53936
  auth: "protected"
52536
53937
  }),
52537
- resume: method(object({ deviceId: DeviceIdSchema$1 }), _void(), {
53938
+ resume: method(object({ deviceId: DeviceIdSchema$2 }), _void(), {
52538
53939
  kind: "mutation",
52539
53940
  auth: "protected"
52540
53941
  }),
52541
- stop: method(object({ deviceId: DeviceIdSchema$1 }), _void(), {
53942
+ stop: method(object({ deviceId: DeviceIdSchema$2 }), _void(), {
52542
53943
  kind: "mutation",
52543
53944
  auth: "protected"
52544
53945
  }),
52545
53946
  /** Select (not start) a program; refused when the appliance does not offer it. */
52546
53947
  setProgram: method(object({
52547
- deviceId: DeviceIdSchema$1,
53948
+ deviceId: DeviceIdSchema$2,
52548
53949
  program: string().min(1)
52549
53950
  }), _void(), {
52550
53951
  kind: "mutation",
52551
53952
  auth: "protected"
52552
53953
  }),
52553
53954
  setPower: method(object({
52554
- deviceId: DeviceIdSchema$1,
53955
+ deviceId: DeviceIdSchema$2,
52555
53956
  on: boolean()
52556
53957
  }), _void(), {
52557
53958
  kind: "mutation",
52558
53959
  auth: "protected"
52559
53960
  }),
52560
53961
  setHalfLoad: method(object({
52561
- deviceId: DeviceIdSchema$1,
53962
+ deviceId: DeviceIdSchema$2,
52562
53963
  on: boolean()
52563
53964
  }), _void(), {
52564
53965
  kind: "mutation",
52565
53966
  auth: "protected"
52566
53967
  }),
52567
53968
  setHygienePlus: method(object({
52568
- deviceId: DeviceIdSchema$1,
53969
+ deviceId: DeviceIdSchema$2,
52569
53970
  on: boolean()
52570
53971
  }), _void(), {
52571
53972
  kind: "mutation",
52572
53973
  auth: "protected"
52573
53974
  }),
52574
53975
  setExtraDry: method(object({
52575
- deviceId: DeviceIdSchema$1,
53976
+ deviceId: DeviceIdSchema$2,
52576
53977
  on: boolean()
52577
53978
  }), _void(), {
52578
53979
  kind: "mutation",
52579
53980
  auth: "protected"
52580
53981
  }),
52581
53982
  setIntensiveZone: method(object({
52582
- deviceId: DeviceIdSchema$1,
53983
+ deviceId: DeviceIdSchema$2,
52583
53984
  on: boolean()
52584
53985
  }), _void(), {
52585
53986
  kind: "mutation",
52586
53987
  auth: "protected"
52587
53988
  }),
52588
53989
  setVarioSpeedPlus: method(object({
52589
- deviceId: DeviceIdSchema$1,
53990
+ deviceId: DeviceIdSchema$2,
52590
53991
  on: boolean()
52591
53992
  }), _void(), {
52592
53993
  kind: "mutation",
52593
53994
  auth: "protected"
52594
53995
  }),
52595
53996
  setChildLock: method(object({
52596
- deviceId: DeviceIdSchema$1,
53997
+ deviceId: DeviceIdSchema$2,
52597
53998
  on: boolean()
52598
53999
  }), _void(), {
52599
54000
  kind: "mutation",
@@ -52605,7 +54006,7 @@ var dishwasherCapability = {
52605
54006
  * its declared range / members.
52606
54007
  */
52607
54008
  setOption: method(object({
52608
- deviceId: DeviceIdSchema$1,
54009
+ deviceId: DeviceIdSchema$2,
52609
54010
  key: string().min(1),
52610
54011
  value: DishwasherValueSchema
52611
54012
  }), _void(), {
@@ -52613,7 +54014,7 @@ var dishwasherCapability = {
52613
54014
  auth: "protected"
52614
54015
  }),
52615
54016
  /** What this appliance can do, from its own description — the UI is derived from it. */
52616
- getOptions: method(object({ deviceId: DeviceIdSchema$1 }), DishwasherOptionsSchema, { auth: "protected" })
54017
+ getOptions: method(object({ deviceId: DeviceIdSchema$2 }), DishwasherOptionsSchema, { auth: "protected" })
52617
54018
  },
52618
54019
  status: {
52619
54020
  schema: DishwasherStatusSchema,
@@ -54037,15 +55438,15 @@ var FanPresetCaptureResultSchema = object({
54037
55438
  items: array(FanCaptureItemSchema),
54038
55439
  omitted: array(FanCaptureOmissionSchema)
54039
55440
  });
54040
- var deviceInput$1 = object({ deviceId: number().int().nonnegative() });
55441
+ var deviceInput$2 = object({ deviceId: number().int().nonnegative() });
54041
55442
  DeviceType.Fan;
54042
- method(deviceInput$1, array(FanPresetSchema), { auth: "protected" }), method(deviceInput$1.extend({ presets: array(FanPresetSchema).max(12) }), FanPresetsSetResultSchema, {
55443
+ method(deviceInput$2, array(FanPresetSchema), { auth: "protected" }), method(deviceInput$2.extend({ presets: array(FanPresetSchema).max(12) }), FanPresetsSetResultSchema, {
54043
55444
  kind: "mutation",
54044
55445
  auth: "admin"
54045
- }), method(deviceInput$1.extend({ presetId: string().min(1) }), FanPresetApplyResultSchema, {
55446
+ }), method(deviceInput$2.extend({ presetId: string().min(1) }), FanPresetApplyResultSchema, {
54046
55447
  kind: "mutation",
54047
55448
  auth: "protected"
54048
- }), method(deviceInput$1.extend({
55449
+ }), method(deviceInput$2.extend({
54049
55450
  fields: array(FanCaptureFieldSchema).optional(),
54050
55451
  steps: array(ActionStepSchema).max(20).default([])
54051
55452
  }), FanPresetCaptureResultSchema, { auth: "protected" });
@@ -54893,11 +56294,7 @@ var CreateIntegrationInputSchema = object({
54893
56294
  info: record(string(), unknown()).optional(),
54894
56295
  /** `stableId` of the discovery candidate the form was seeded from (D984). */
54895
56296
  originStableId: string().optional(),
54896
- settings: record(string(), unknown()).optional(),
54897
- /** Keys of `settings` the form's schema declares secret (by type) — kept in
54898
- * the keychain, not the table (D787). */
54899
- secretKeys: array(string()).optional(),
54900
- skipRestart: boolean().optional()
56297
+ settings: record(string(), unknown()).optional()
54901
56298
  });
54902
56299
  var UpdateIntegrationInputSchema = object({
54903
56300
  id: string(),
@@ -54918,16 +56315,6 @@ method(_void(), array(IntegrationWithStateSchema)), method(object({ id: string()
54918
56315
  }), method(object({ id: string() }), DeleteIntegrationResultSchema, {
54919
56316
  kind: "mutation",
54920
56317
  auth: "admin"
54921
- }), method(object({ id: string() }), record(string(), unknown()), { auth: "admin" }), method(object({
54922
- id: string(),
54923
- settings: record(string(), unknown()),
54924
- /** Keys the form's schema declares secret (by type) — keychain-stored (D787). */
54925
- secretKeys: array(string()).optional(),
54926
- /** The integration's own addon applies the change in-process and asks the hub not to respawn it. */
54927
- skipRestart: boolean().optional()
54928
- }), object({ success: boolean() }), {
54929
- kind: "mutation",
54930
- auth: "admin"
54931
56318
  }), method(_void(), array(AvailableIntegrationTypeSchema), { auth: "admin" }), method(object({
54932
56319
  addonId: string(),
54933
56320
  settings: record(string(), unknown())
@@ -54956,13 +56343,65 @@ method(_void(), array(IntegrationWithStateSchema)), method(object({ id: string()
54956
56343
  */
54957
56344
  var ConfigSchemaPassthrough$3 = custom();
54958
56345
  var IntegrationInstanceIdSchema = string().min(1);
56346
+ var IntegrationInstanceModeSchema = _enum(["single", "multiple"]);
56347
+ /**
56348
+ * One kind of instance a provider can create (an adapter, an account type). The sign-in and
56349
+ * connect fields follow the `broker` contract (`broker.cap.ts`): `signIn.basePath` is a
56350
+ * hub-relative route set speaking the sign-in contract, `connectPath` / `disconnectPath` open an
56351
+ * interactive account link (popup) and may carry `{{brokerId}}`, which the UI replaces with the
56352
+ * instance id.
56353
+ */
56354
+ var IntegrationInstanceKindSchema = object({
56355
+ /** Stable id of the kind, sent back as `createInstance.kind`. */
56356
+ id: string().min(1),
56357
+ label: string().min(1),
56358
+ /** The kind signs in through a server-held interactive session. */
56359
+ signIn: object({
56360
+ basePath: string().min(1),
56361
+ methods: array(_enum(["device-code", "proxy"])).optional()
56362
+ }).optional(),
56363
+ /** Relative hub path to start an interactive account link of an instance of this kind. */
56364
+ connectPath: string().min(1).optional(),
56365
+ /** Relative hub path to disconnect that account. */
56366
+ disconnectPath: string().min(1).optional()
56367
+ });
54959
56368
  var IntegrationInstanceDescriptionSchema = object({
56369
+ /** What the instances are for the Integrations page; see {@link IntegrationInstanceRoleSchema}. */
56370
+ role: _enum([
56371
+ "devices",
56372
+ "services",
56373
+ "both"
56374
+ ]),
56375
+ /** How the devices of an instance are found; absent means `{ mode: 'none' }`. */
56376
+ discovery: object({
56377
+ mode: _enum([
56378
+ "none",
56379
+ "lan",
56380
+ "account"
56381
+ ]),
56382
+ scopedToInstance: boolean()
56383
+ }).optional(),
54960
56384
  /** `single`: at most one instance can exist (Loki). `multiple`: an account each. */
54961
- instanceMode: _enum(["single", "multiple"]),
56385
+ instanceMode: IntegrationInstanceModeSchema,
54962
56386
  /** What the instance is, for the UI (`destination`, `relay`, `account`). */
54963
56387
  kind: string(),
54964
56388
  /** True when `testInstance` really probes the remote. */
54965
- canTest: boolean()
56389
+ canTest: boolean(),
56390
+ /**
56391
+ * The kinds an instance can be of. Absent or one entry: nothing to choose; more than one: the
56392
+ * Add flow asks which first and sends it as `createInstance.kind`.
56393
+ */
56394
+ kinds: array(IntegrationInstanceKindSchema).optional(),
56395
+ /**
56396
+ * The provider accepts `createInstance.id` for an id that once existed (an adopted id, because
56397
+ * devices carry it). The UI then offers "restore under its old id" on Add. Absent means no.
56398
+ */
56399
+ allowRestoreId: boolean().optional(),
56400
+ /**
56401
+ * `createInstance` without an `id` works: the provider mints it. Absent means the caller must
56402
+ * send an id (the UI then mints an opaque one).
56403
+ */
56404
+ mintsId: boolean().optional()
54966
56405
  });
54967
56406
  var IntegrationInstanceStatusSchema = object({
54968
56407
  state: _enum([
@@ -54971,16 +56410,28 @@ var IntegrationInstanceStatusSchema = object({
54971
56410
  "error",
54972
56411
  "unknown"
54973
56412
  ]),
54974
- detail: string().optional()
56413
+ detail: string().optional(),
56414
+ /** A short human word for the state ("Signed in", "Token expired"); shown instead of `state`. */
56415
+ label: string().optional()
54975
56416
  });
54976
56417
  var IntegrationInstanceSchema = object({
54977
56418
  id: IntegrationInstanceIdSchema,
54978
56419
  name: string(),
54979
56420
  /** The addon's own rule (an URL is present, a client id is present...). */
54980
56421
  configured: boolean(),
56422
+ /**
56423
+ * The instance's own on/off switch (D996), derived from the record body (`enabled !== false`,
56424
+ * so a row written before the field existed is on). Absent when the `integrations` registry
56425
+ * owns the switch (`describe().role` is `devices`): read it from the registry row.
56426
+ */
56427
+ enabled: boolean().optional(),
56428
+ /** The kind of this instance (one of `describe().kinds[].id`), when the provider has kinds. */
56429
+ kind: string().optional(),
54981
56430
  /** Values for the instance form; a secret is a `SecretFieldView`, never text. */
54982
56431
  formValues: record(string(), unknown()),
54983
- status: IntegrationInstanceStatusSchema.optional()
56432
+ status: IntegrationInstanceStatusSchema.optional(),
56433
+ /** Epoch ms of the last probe of the remote that produced `status`; absent when never checked. */
56434
+ lastCheckedAt: number().optional()
54984
56435
  });
54985
56436
  var IntegrationInstancePatchSchema = object({
54986
56437
  id: IntegrationInstanceIdSchema,
@@ -54988,25 +56439,57 @@ var IntegrationInstancePatchSchema = object({
54988
56439
  /** Omitted / '' / redaction token keeps a secret; `{ $secretClear: true }` clears it. */
54989
56440
  values: record(string(), unknown())
54990
56441
  });
54991
- method(_void(), IntegrationInstanceDescriptionSchema, { auth: "admin" }), method(object({ id: IntegrationInstanceIdSchema.nullable() }), ConfigSchemaPassthrough$3, { auth: "admin" }), method(_void(), array(IntegrationInstanceSchema).readonly(), { auth: "admin" }), method(object({ id: IntegrationInstanceIdSchema }), IntegrationInstanceSchema.nullable(), { auth: "admin" }), method(object({
54992
- id: IntegrationInstanceIdSchema,
54993
- name: string().min(1)
54994
- }), object({ id: string() }), {
54995
- kind: "mutation",
54996
- auth: "admin"
54997
- }), method(IntegrationInstancePatchSchema, object({ ok: literal(true) }), {
54998
- kind: "mutation",
54999
- auth: "admin"
55000
- }), method(object({ id: IntegrationInstanceIdSchema }), object({ ok: literal(true) }), {
55001
- kind: "mutation",
55002
- auth: "admin"
55003
- }), optionalMethod(object({
55004
- id: IntegrationInstanceIdSchema.nullable(),
55005
- values: record(string(), unknown())
55006
- }), TestConnectionResultSchema$1, {
55007
- kind: "mutation",
55008
- auth: "admin"
55009
- });
56442
+ var integrationInstancesCapability = {
56443
+ name: "integration-instances",
56444
+ scope: "system",
56445
+ mode: "collection",
56446
+ methods: {
56447
+ describe: method(_void(), IntegrationInstanceDescriptionSchema, { auth: "admin" }),
56448
+ /** The form; `id: null` is the create form. */
56449
+ instanceFormSchema: method(object({ id: IntegrationInstanceIdSchema.nullable() }), ConfigSchemaPassthrough$3, { auth: "admin" }),
56450
+ listInstances: method(_void(), array(IntegrationInstanceSchema).readonly(), { auth: "admin" }),
56451
+ getInstance: method(object({ id: IntegrationInstanceIdSchema }), IntegrationInstanceSchema.nullable(), { auth: "admin" }),
56452
+ /**
56453
+ * Insert the typed record. With `id` it is stored under that id (a duplicate id is refused);
56454
+ * without one the PROVIDER mints it and answers it. `kind` picks one of `describe().kinds`.
56455
+ */
56456
+ createInstance: method(object({
56457
+ id: IntegrationInstanceIdSchema.optional(),
56458
+ name: string().min(1),
56459
+ kind: string().min(1).optional()
56460
+ }), object({ id: string() }), {
56461
+ kind: "mutation",
56462
+ auth: "admin"
56463
+ }),
56464
+ updateInstance: method(IntegrationInstancePatchSchema, object({ ok: literal(true) }), {
56465
+ kind: "mutation",
56466
+ auth: "admin"
56467
+ }),
56468
+ /**
56469
+ * Switch ONE instance on or off. A row control, not a form field: `updateInstance.values` is the
56470
+ * form patch (D62, D996). An off instance keeps its record and secrets and does no work.
56471
+ */
56472
+ setInstanceEnabled: method(object({
56473
+ id: IntegrationInstanceIdSchema,
56474
+ enabled: boolean()
56475
+ }), object({ ok: literal(true) }), {
56476
+ kind: "mutation",
56477
+ auth: "admin"
56478
+ }),
56479
+ /** Delete the record and its keychain refs together. */
56480
+ deleteInstance: method(object({ id: IntegrationInstanceIdSchema }), object({ ok: literal(true) }), {
56481
+ kind: "mutation",
56482
+ auth: "admin"
56483
+ }),
56484
+ testInstance: optionalMethod(object({
56485
+ id: IntegrationInstanceIdSchema.nullable(),
56486
+ values: record(string(), unknown())
56487
+ }), TestConnectionResultSchema$1, {
56488
+ kind: "mutation",
56489
+ auth: "admin"
56490
+ })
56491
+ }
56492
+ };
55010
56493
  /**
55011
56494
  * Two-way audio / talk-back cap. Clients open a WebRTC audio-only
55012
56495
  * session (server-initiated offer pattern, identical to the main
@@ -57024,6 +58507,11 @@ var LogEntrySchema = object({
57024
58507
  * flight, and not asking for the next slice ends the scan.
57025
58508
  */
57026
58509
  var LogReadQuerySchema = object({
58510
+ /**
58511
+ * Which destination INSTANCE answers (a destination addon may hold several records). Absent ⇒
58512
+ * the provider's first readable one, so a caller written before instances existed is unchanged.
58513
+ */
58514
+ instanceId: string().min(1).max(200).optional(),
57027
58515
  /** Correlates `cancelRead`. Caller-chosen, unique per in-flight read. */
57028
58516
  requestId: string().min(1).max(64).optional(),
57029
58517
  /** The device the line is about (`tags.deviceId`, numeric). */
@@ -57086,6 +58574,8 @@ var LogReadResultSchema = object({
57086
58574
  /** True when `cancelRead` ended this slice early. */
57087
58575
  cancelled: boolean().optional()
57088
58576
  });
58577
+ /** Names one destination instance; absent ⇒ the provider's first readable one. */
58578
+ var LogInstanceSelectorSchema = object({ instanceId: string().min(1).max(200).optional() });
57089
58579
  var LogReadCapabilitiesSchema = object({
57090
58580
  /** False ⇒ this destination only ships lines (console, forwarder, an unconfigured Loki). */
57091
58581
  readable: boolean(),
@@ -57104,7 +58594,7 @@ var LogReadCapabilitiesSchema = object({
57104
58594
  /** How far back the store reaches, when the provider knows (days). */
57105
58595
  retentionDays: number().nullable()
57106
58596
  });
57107
- method(LogEntrySchema, _void(), { kind: "mutation" }), optionalMethod(_void(), LogReadCapabilitiesSchema, { auth: "admin" }), optionalMethod(LogReadQuerySchema, LogReadResultSchema, { auth: "admin" }), optionalMethod(object({ requestId: string().min(1).max(64) }), object({ cancelled: boolean() }), {
58597
+ method(LogEntrySchema, _void(), { kind: "mutation" }), optionalMethod(LogInstanceSelectorSchema, LogReadCapabilitiesSchema, { auth: "admin" }), optionalMethod(LogReadQuerySchema, LogReadResultSchema, { auth: "admin" }), optionalMethod(object({ requestId: string().min(1).max(64) }), object({ cancelled: boolean() }), {
57108
58598
  kind: "mutation",
57109
58599
  auth: "admin"
57110
58600
  });
@@ -57208,214 +58698,6 @@ var LoginMethodContributionSchema = discriminatedUnion("kind", [
57208
58698
  ]);
57209
58699
  method(_void(), array(LoginMethodContributionSchema).readonly());
57210
58700
  /**
57211
- * Media-player cap. Models HA `media_player.*` (Sonos, Chromecast,
57212
- * Apple TV, Spotify, Roku, generic OTT receivers, …) on
57213
- * `DeviceType.MediaPlayer`. Disjoint from the camera streaming
57214
- * surface — those use `DeviceType.Camera` + the broker pipeline.
57215
- *
57216
- * The cap declares a wide method surface; not every backend supports
57217
- * every method. Drivers signal sub-capability via the
57218
- * `DeviceFeature.MediaPlayerXxx` flags (paired one-to-one with the
57219
- * corresponding method) so the UI gates buttons without a slice
57220
- * fetch — same pattern as `PanTiltZoom` for cameras.
57221
- */
57222
- var MediaPlayerStateSchema = _enum([
57223
- "off",
57224
- "on",
57225
- "idle",
57226
- "playing",
57227
- "paused",
57228
- "buffering",
57229
- "standby"
57230
- ]);
57231
- var MediaPlayerRepeatSchema = _enum([
57232
- "off",
57233
- "all",
57234
- "one"
57235
- ]);
57236
- var MediaInfoSchema = object({
57237
- /** Free-form media kind (`music`, `tvshow`, `movie`, `app`, `channel`,
57238
- * `podcast`, …). */
57239
- type: string(),
57240
- /** Human-readable title. */
57241
- title: string(),
57242
- /** Optional artist / channel / station label. */
57243
- artist: string().optional(),
57244
- /** Optional album / season / show name. */
57245
- album: string().optional(),
57246
- /** Optional cover-art / thumbnail URL. */
57247
- imageUrl: string().optional()
57248
- });
57249
- /**
57250
- * Where `state`, `volumeLevel`, `isMuted` and `source` come from. `reported`:
57251
- * the device said so. `assumed`: the driver has no feedback (infrared) and
57252
- * tracks what it last SENT; it moves only after a send was accepted, and a
57253
- * human at the real remote makes it wrong. A UI shows an assumed value as a
57254
- * guess, never as a reading.
57255
- */
57256
- var MediaPlayerStateSourceSchema = _enum(["reported", "assumed"]);
57257
- /** The fields of a media-player status a driver can only guess. */
57258
- var MediaPlayerAssumedFieldSchema = _enum([
57259
- "state",
57260
- "volumeLevel",
57261
- "isMuted",
57262
- "source"
57263
- ]);
57264
- var MediaPlayerStatusSchema = object({
57265
- /** Playback lifecycle state. */
57266
- state: MediaPlayerStateSchema,
57267
- /**
57268
- * Whether the state fields are readings or the driver's own bookkeeping.
57269
- * A slice written before this field existed parses as `reported`.
57270
- */
57271
- stateSource: MediaPlayerStateSourceSchema.default("reported"),
57272
- /**
57273
- * Which fields are the driver's own guess. `stateSource` is `assumed` when
57274
- * this is not empty; a field not listed here is a reading even then (power
57275
- * from a running-state source, mute guessed from the last send).
57276
- */
57277
- assumedFields: array(MediaPlayerAssumedFieldSchema).default([]),
57278
- /** Volume as 0..100 inclusive. Null when the device has no volume
57279
- * surface. Pair with `DeviceFeature.MediaPlayerVolume`. */
57280
- volumeLevel: number().min(0).max(100).nullable().meta(readingMeta("percentage")),
57281
- /** Mute toggle distinct from volume=0. Null when no mute surface.
57282
- * Pair with `DeviceFeature.MediaPlayerMute`. */
57283
- isMuted: boolean().nullable(),
57284
- /** Active source / input. Empty when no source surface. */
57285
- source: string(),
57286
- /** Selectable sources. Empty when no source surface.
57287
- * Pair with `DeviceFeature.MediaPlayerSelectSource`. */
57288
- availableSources: array(string()),
57289
- /** Currently-playing media info. Null when nothing is playing. */
57290
- currentMedia: MediaInfoSchema.nullable(),
57291
- /** Current playback position in ms. Null when not seekable or
57292
- * nothing is playing. Pair with `DeviceFeature.MediaPlayerSeek`. */
57293
- position: number().int().nonnegative().nullable().meta(readingMeta("duration-ms")),
57294
- /** Total duration of the current media in ms. Null when unknown
57295
- * (live stream) or nothing is playing. */
57296
- duration: number().int().nonnegative().nullable().meta(readingMeta("duration-ms")),
57297
- /** Shuffle toggle. Null when no shuffle surface.
57298
- * Pair with `DeviceFeature.MediaPlayerShuffle`. */
57299
- shuffle: boolean().nullable(),
57300
- /** Repeat mode. Null when no repeat surface.
57301
- * Pair with `DeviceFeature.MediaPlayerRepeat`. */
57302
- repeat: MediaPlayerRepeatSchema.nullable(),
57303
- /** Ms epoch when the slice was last updated. */
57304
- lastChangedAt: number()
57305
- });
57306
- var mediaPlayerCapability = {
57307
- name: "media-player",
57308
- scope: "device",
57309
- deviceNative: true,
57310
- mode: "singleton",
57311
- deviceTypes: [DeviceType.MediaPlayer],
57312
- methods: {
57313
- play: method(object({ deviceId: number().int().nonnegative() }), _void(), {
57314
- kind: "mutation",
57315
- auth: "protected"
57316
- }),
57317
- pause: method(object({ deviceId: number().int().nonnegative() }), _void(), {
57318
- kind: "mutation",
57319
- auth: "protected"
57320
- }),
57321
- stop: method(object({ deviceId: number().int().nonnegative() }), _void(), {
57322
- kind: "mutation",
57323
- auth: "protected"
57324
- }),
57325
- next: method(object({ deviceId: number().int().nonnegative() }), _void(), {
57326
- kind: "mutation",
57327
- auth: "protected"
57328
- }),
57329
- previous: method(object({ deviceId: number().int().nonnegative() }), _void(), {
57330
- kind: "mutation",
57331
- auth: "protected"
57332
- }),
57333
- seek: method(object({
57334
- deviceId: number().int().nonnegative(),
57335
- position: number().int().nonnegative()
57336
- }), _void(), {
57337
- kind: "mutation",
57338
- auth: "protected"
57339
- }),
57340
- setVolume: method(object({
57341
- deviceId: number().int().nonnegative(),
57342
- volumeLevel: number().min(0).max(100)
57343
- }), _void(), {
57344
- kind: "mutation",
57345
- auth: "protected"
57346
- }),
57347
- setMute: method(object({
57348
- deviceId: number().int().nonnegative(),
57349
- muted: boolean()
57350
- }), _void(), {
57351
- kind: "mutation",
57352
- auth: "protected"
57353
- }),
57354
- setShuffle: method(object({
57355
- deviceId: number().int().nonnegative(),
57356
- shuffle: boolean()
57357
- }), _void(), {
57358
- kind: "mutation",
57359
- auth: "protected"
57360
- }),
57361
- setRepeat: method(object({
57362
- deviceId: number().int().nonnegative(),
57363
- repeat: MediaPlayerRepeatSchema
57364
- }), _void(), {
57365
- kind: "mutation",
57366
- auth: "protected"
57367
- }),
57368
- selectSource: method(object({
57369
- deviceId: number().int().nonnegative(),
57370
- source: string().min(1)
57371
- }), _void(), {
57372
- kind: "mutation",
57373
- auth: "protected"
57374
- }),
57375
- playMedia: method(object({
57376
- deviceId: number().int().nonnegative(),
57377
- /** Media identifier / URL. */
57378
- mediaId: string().min(1),
57379
- /** Media kind (`music`, `tvshow`, `movie`, `app`, …) — provider
57380
- * passes it through to the upstream service. */
57381
- mediaType: string().min(1)
57382
- }), _void(), {
57383
- kind: "mutation",
57384
- auth: "protected"
57385
- })
57386
- },
57387
- status: {
57388
- schema: MediaPlayerStatusSchema,
57389
- kind: "push"
57390
- },
57391
- /**
57392
- * Runtime-state slice — mirrored by the kernel. UI players read the
57393
- * full slice for live now-playing, volume, and progress updates
57394
- * without polling.
57395
- */
57396
- runtimeState: MediaPlayerStatusSchema,
57397
- /**
57398
- * Runtime-state durability: **session** — a restored transport position describes a playback that stopped when the hub did.
57399
- *
57400
- * See `RuntimeStateDurability`. Enforced by
57401
- * `scripts/check-runtime-state-durability.ts`.
57402
- */
57403
- durability: "session",
57404
- /**
57405
- * History (D850): volume (a level an operator or an automation sets; the
57406
- * default 10 s floor folds a slider drag into its end value) and mute.
57407
- * `position` is not recorded: it moves continuously while playing.
57408
- */
57409
- history: { fields: {
57410
- volumeLevel: {
57411
- kind: "gauge",
57412
- unit: "%",
57413
- deadband: 1
57414
- },
57415
- isMuted: { kind: "boolean" }
57416
- } }
57417
- };
57418
- /**
57419
58701
  * mesh-network — collection cap for mesh-VPN providers.
57420
58702
  *
57421
58703
  * Different shape from `network-access` (public tunnels):
@@ -58009,6 +59291,27 @@ method(object({}), object({ entries: array(MigrationLedgerEntrySchema) }), { aut
58009
59291
  }), {
58010
59292
  kind: "mutation",
58011
59293
  auth: "admin"
59294
+ }), method(object({ integrationId: string().min(1) }), record(string(), unknown()), { auth: "admin" }), method(object({ integrationId: string().min(1) }), object({
59295
+ rows: number().int().nonnegative(),
59296
+ secrets: number().int().nonnegative()
59297
+ }), {
59298
+ kind: "mutation",
59299
+ auth: "admin"
59300
+ }), method(object({
59301
+ integrationId: string().min(1),
59302
+ patch: record(string(), unknown())
59303
+ }), object({ written: boolean() }), {
59304
+ kind: "mutation",
59305
+ auth: "admin"
59306
+ }), method(object({
59307
+ integrationId: string().min(1),
59308
+ keys: array(string().min(1))
59309
+ }), object({
59310
+ present: boolean(),
59311
+ removed: record(string(), unknown())
59312
+ }), {
59313
+ kind: "mutation",
59314
+ auth: "admin"
58012
59315
  });
58013
59316
  method(object({
58014
59317
  sourceUrl: string(),
@@ -66174,6 +67477,21 @@ var NcTemplateVarKindSchema = _enum([
66174
67477
  "sound",
66175
67478
  "system"
66176
67479
  ]);
67480
+ /**
67481
+ * The default title/body a rule of one SITUATION is delivered with when the
67482
+ * operator wrote no template — served so an editor can pre-fill it (and the
67483
+ * operator can rebuild it from placeholders) instead of starting from a blank
67484
+ * box that, once saved, silently replaces it. `id` names the situation inside
67485
+ * a rule `kind`: `appliance-cycle` is a `sensor` rule whose device is an
67486
+ * appliance finishing a cycle. Texts are raw templates (`{{var}}` intact), in
67487
+ * the hub's current language and with its overrides applied.
67488
+ */
67489
+ var NcTemplateDefaultSchema = object({
67490
+ id: _enum(["appliance-cycle"]),
67491
+ kind: NcRuleKindSchema,
67492
+ title: string(),
67493
+ body: string()
67494
+ });
66177
67495
  /** Which producer renders a template: an ordinary rule, a timelapse, a digest. */
66178
67496
  var NcTemplateFamilySchema = _enum([
66179
67497
  "rule",
@@ -67029,7 +68347,11 @@ method(object({}), object({ rules: array(NcRuleSchema) }), { auth: "admin" }), m
67029
68347
  }), method(object({}), object({
67030
68348
  catalog: array(NcConditionDescriptorSchema),
67031
68349
  taxonomy: NcTaxonomySchema.optional()
67032
- })), method(object({}), object({ vars: array(NcTemplateVarDescriptorSchema) })), method(NcTemplatePreviewInputSchema, NcTemplatePreviewSchema, {
68350
+ })), method(object({}), object({
68351
+ vars: array(NcTemplateVarDescriptorSchema),
68352
+ /** Per-situation default texts; absent on a hub that predates them. */
68353
+ defaults: array(NcTemplateDefaultSchema)
68354
+ })), method(NcTemplatePreviewInputSchema, NcTemplatePreviewSchema, {
67033
68355
  kind: "mutation",
67034
68356
  access: "view"
67035
68357
  }), method(object({ filter: NcHistoryFilterSchema.default({ limit: 100 }) }), object({ entries: array(NcHistoryEntrySchema) }), { auth: "admin" }), method(object({}), NcRuleLastRunsSchema, { auth: "admin" }), method(object({ artifactId: string().min(1) }), object({ url: string().nullable() }), { auth: "admin" }), method(object({}), object({ snoozes: array(NcSnoozeSchema) }), { caller: "required" }), method(object({ snooze: NcSnoozeInputSchema }), object({ snooze: NcSnoozeSchema }), {
@@ -67925,7 +69247,7 @@ var petFeederCapability = {
67925
69247
  /**
67926
69248
  * Pet water-fountain cap. Models the telemetry and the control surface of a
67927
69249
  * circulating drinking fountain: how much water is in the tank, how much the
67928
- * pet drank, whether the pump runs and on what duty cycle.
69250
+ * pet drank, whether the pump runs.
67929
69251
  *
67930
69252
  * It has no native vendor provider of its own: a fountain reaches CamStack as
67931
69253
  * a container of loose entities (a pump switch, two number boxes, a "filter
@@ -67941,8 +69263,10 @@ var petFeederCapability = {
67941
69263
  * never here. Every reading may be `null`: a source that is offline or does
67942
69264
  * not report is unknown, never zero.
67943
69265
  *
67944
- * The filter is not a field of this cap: it is an item of the `consumables`
67945
- * cap on the same device (kind `wear`), reset by the same forward mechanism.
69266
+ * The pump's on/off duty cycle is model-specific and lives in the optional
69267
+ * `pump-cycle` cap. The filter, the cleaning and the water change are not
69268
+ * fields of this cap: they are items of the `consumables` cap on the same
69269
+ * device (kind `wear`), reset by the same forward mechanism.
67946
69270
  */
67947
69271
  var PetFountainStatusSchema = object({
67948
69272
  /** Water in the tank, 0..100 (%). Null while the source has not reported. */
@@ -67953,27 +69277,20 @@ var PetFountainStatusSchema = object({
67953
69277
  empty: boolean().nullable(),
67954
69278
  /** True while the pump is running. Null while unknown. */
67955
69279
  pumpRunning: boolean().nullable(),
67956
- /** True when the pump works on an on/off duty cycle rather than continuously. */
67957
- pumpIntervalEnabled: boolean().nullable(),
67958
- /** How long the pump runs per cycle, in seconds. */
67959
- pumpOnTime: number().min(0).nullable().meta(readingMeta("duration")),
67960
- /** How long the pump rests per cycle, in seconds. */
67961
- pumpOffTime: number().min(0).nullable().meta(readingMeta("duration")),
67962
69280
  /** Water drunk in the last drink, in litres. */
67963
69281
  lastDrink: number().min(0).nullable().meta(readingMeta("volume")),
67964
69282
  /** Water drunk in the current hour, in litres. */
67965
69283
  currentHourDrink: number().min(0).nullable().meta(readingMeta("volume")),
67966
69284
  /** Water drunk over the last 24 hours (rolling), in litres. */
67967
69285
  last24hDrink: number().min(0).nullable().meta(readingMeta("volume")),
67968
- /** Water drunk since local midnight, in litres. */
69286
+ /** Water drunk since local midnight, in litres. Null when the fountain has no such sensor. */
67969
69287
  todayDrink: number().min(0).nullable().meta(readingMeta("volume")),
67970
69288
  /** Decoded fault message. Null means healthy; a non-null string is an active fault. */
67971
69289
  error: string().nullable(),
67972
69290
  /** Ms epoch when the slice was last refreshed. */
67973
69291
  lastFetchedAt: number()
67974
69292
  });
67975
- var DeviceIdSchema = number().int().nonnegative();
67976
- var MinutesSchema = number().int().min(0);
69293
+ var DeviceIdSchema$1 = number().int().nonnegative();
67977
69294
  var petFountainCapability = {
67978
69295
  name: "pet-fountain",
67979
69296
  scope: "device",
@@ -67983,38 +69300,14 @@ var petFountainCapability = {
67983
69300
  methods: {
67984
69301
  /** Start or stop the pump. */
67985
69302
  setPump: method(object({
67986
- deviceId: DeviceIdSchema,
67987
- on: boolean()
67988
- }), _void(), {
67989
- kind: "mutation",
67990
- auth: "protected"
67991
- }),
67992
- /** Switch the on/off duty cycle on or off (off = the pump runs continuously). */
67993
- setPumpInterval: method(object({
67994
- deviceId: DeviceIdSchema,
69303
+ deviceId: DeviceIdSchema$1,
67995
69304
  on: boolean()
67996
69305
  }), _void(), {
67997
69306
  kind: "mutation",
67998
69307
  auth: "protected"
67999
69308
  }),
68000
- /** Set how many minutes the pump runs per cycle. */
68001
- setPumpOnMinutes: method(object({
68002
- deviceId: DeviceIdSchema,
68003
- minutes: MinutesSchema
68004
- }), _void(), {
68005
- kind: "mutation",
68006
- auth: "protected"
68007
- }),
68008
- /** Set how many minutes the pump rests per cycle. */
68009
- setPumpOffMinutes: method(object({
68010
- deviceId: DeviceIdSchema,
68011
- minutes: MinutesSchema
68012
- }), _void(), {
68013
- kind: "mutation",
68014
- auth: "protected"
68015
- }),
68016
69309
  /** Clear the rolling daily consumption counters on the device. */
68017
- resetDailyConsumption: method(object({ deviceId: DeviceIdSchema }), _void(), {
69310
+ resetDailyConsumption: method(object({ deviceId: DeviceIdSchema$1 }), _void(), {
68018
69311
  kind: "mutation",
68019
69312
  auth: "protected"
68020
69313
  })
@@ -69649,6 +70942,14 @@ var powerMeterCapability = {
69649
70942
  deviceNative: true,
69650
70943
  mode: "singleton",
69651
70944
  deviceTypes: POWER_METER_DEVICE_TYPES,
70945
+ deviceConfig: { ui: {
70946
+ kind: "widget",
70947
+ widgetId: "host/power-meter-line",
70948
+ tab: "power",
70949
+ placement: "hero",
70950
+ label: "Power",
70951
+ order: 4
70952
+ } },
69652
70953
  methods: {},
69653
70954
  status: {
69654
70955
  schema: PowerMeterStatusSchema,
@@ -69708,6 +71009,117 @@ var powerMeterCapability = {
69708
71009
  volatileStateFields: ["lastFetchedAt"],
69709
71010
  customize: powerMeterCustomize
69710
71011
  };
71012
+ var PowerSourceRefusalReasonSchema = _enum([
71013
+ "no-power-source",
71014
+ "switch-missing",
71015
+ "switch-offline",
71016
+ "switch-unknown",
71017
+ "restart-in-progress",
71018
+ "switch-call-failed"
71019
+ ]);
71020
+ var PowerSourceActionResultSchema = discriminatedUnion("accepted", [object({ accepted: literal(true) }), object({
71021
+ accepted: literal(false),
71022
+ reason: PowerSourceRefusalReasonSchema,
71023
+ /** One line for the operator, naming the switch. */
71024
+ message: string()
71025
+ })]);
71026
+ var PowerSourceInfoSchema = object({
71027
+ /** False when the device has no power source linked; the rest is then empty. */
71028
+ linked: boolean(),
71029
+ switchDeviceId: number().nullable(),
71030
+ switchName: string().nullable(),
71031
+ /** The switch's on/off state, or null when it is unknown. Never false for unknown (D393). */
71032
+ switchOn: boolean().nullable(),
71033
+ switchOnline: boolean().nullable(),
71034
+ restartInProgress: boolean(),
71035
+ offSeconds: number().int()
71036
+ });
71037
+ /** The composed slice: the switch state the link mirrors, plus the stored off time. */
71038
+ var PowerSourceStateSchema = object({
71039
+ /** Null while the switch has not reported: unknown is never `false` (D393). */
71040
+ switchOn: boolean().nullable(),
71041
+ offSeconds: number().int(),
71042
+ lastFetchedAt: number()
71043
+ });
71044
+ var POWER_SOURCE_DEVICE_TYPES = [
71045
+ DeviceType.Gateway,
71046
+ DeviceType.Hub,
71047
+ DeviceType.Camera,
71048
+ DeviceType.Sensor,
71049
+ DeviceType.MediaPlayer,
71050
+ DeviceType.Vacuum,
71051
+ DeviceType.Generic,
71052
+ DeviceType.Washer,
71053
+ DeviceType.Dryer,
71054
+ DeviceType.Dishwasher,
71055
+ DeviceType.PetFountain,
71056
+ DeviceType.Fan,
71057
+ DeviceType.Humidifier,
71058
+ DeviceType.Climate,
71059
+ DeviceType.WaterHeater
71060
+ ];
71061
+ var powerSourceCustomize = {
71062
+ version: 1,
71063
+ targets: [{
71064
+ id: "switch",
71065
+ cardinality: "scalar",
71066
+ vocabulary: {
71067
+ cap: "power-source",
71068
+ stateField: "switchOn"
71069
+ },
71070
+ deviceTypes: POWER_SOURCE_DEVICE_TYPES,
71071
+ apply: "add",
71072
+ path: "switchOn",
71073
+ sources: [{
71074
+ kind: "switch",
71075
+ transforms: [{ kind: "identity" }]
71076
+ }],
71077
+ companions: [{
71078
+ kind: "constant",
71079
+ path: "offSeconds",
71080
+ value: 10,
71081
+ when: "add"
71082
+ }, {
71083
+ kind: "clock",
71084
+ path: "lastFetchedAt",
71085
+ when: "always"
71086
+ }],
71087
+ sourceReport: { status: "assignment-status" }
71088
+ }]
71089
+ };
71090
+ var deviceInput$1 = object({ deviceId: number().int().nonnegative() });
71091
+ var powerSourceCapability = {
71092
+ name: "power-source",
71093
+ scope: "device",
71094
+ mode: "singleton",
71095
+ deviceTypes: POWER_SOURCE_DEVICE_TYPES,
71096
+ methods: {
71097
+ getStatus: systemMethod(deviceInput$1, PowerSourceInfoSchema, { auth: "admin" }),
71098
+ powerOn: systemMethod(deviceInput$1, PowerSourceActionResultSchema, {
71099
+ kind: "mutation",
71100
+ auth: "admin"
71101
+ }),
71102
+ powerOff: systemMethod(deviceInput$1, PowerSourceActionResultSchema, {
71103
+ kind: "mutation",
71104
+ auth: "admin"
71105
+ }),
71106
+ forceRestart: systemMethod(deviceInput$1, PowerSourceActionResultSchema, {
71107
+ kind: "mutation",
71108
+ auth: "admin"
71109
+ })
71110
+ },
71111
+ runtimeState: PowerSourceStateSchema,
71112
+ customize: powerSourceCustomize,
71113
+ /**
71114
+ * Runtime-state durability: **session** — mirrored from the linked switch on
71115
+ * its next report; a restored value would outlive the reading it names.
71116
+ *
71117
+ * See `RuntimeStateDurability`. Enforced by
71118
+ * `scripts/check-runtime-state-durability.ts`.
71119
+ */
71120
+ durability: "session",
71121
+ history: "none"
71122
+ };
69711
71123
  /**
69712
71124
  * Presence cap. Models HA `person.*` and `device_tracker.*` entities
69713
71125
  * on `DeviceType.Presence`. Read-only — no setters: presence is
@@ -70347,6 +71759,79 @@ var ptzAutotrackCapability = {
70347
71759
  */
70348
71760
  history: "none"
70349
71761
  };
71762
+ /**
71763
+ * The on/off duty cycle of a pet fountain's pump. Some models run the pump
71764
+ * continuously and have nothing to configure; others can alternate a run time
71765
+ * and a rest time. That is model-specific, so it is its own optional cap on the
71766
+ * fountain device: a fountain without cycle entities simply never composes it
71767
+ * (planning#366), and the `pet-fountain` cap stays the model-independent core.
71768
+ *
71769
+ * Like `pet-fountain` it has no native vendor provider: an operator BUILDS the
71770
+ * cycle from loose entities (a cycle switch and two number boxes) and every
71771
+ * method is a forward to one source entity (D659, D967). Durations are stored
71772
+ * in SECONDS (D944); a number box that cannot be read back leaves them `null`
71773
+ * — unknown, never zero (D393).
71774
+ */
71775
+ var PumpCycleStatusSchema = object({
71776
+ /** True when the pump works on the on/off cycle, false when it runs continuously. Null while unknown. */
71777
+ enabled: boolean().nullable(),
71778
+ /** How long the pump runs per cycle, in seconds. Null while unknown. */
71779
+ onTime: number().min(0).nullable().meta(readingMeta("duration")),
71780
+ /** How long the pump rests per cycle, in seconds. Null while unknown. */
71781
+ offTime: number().min(0).nullable().meta(readingMeta("duration")),
71782
+ /** Ms epoch when the slice was last refreshed. */
71783
+ lastFetchedAt: number()
71784
+ });
71785
+ var DeviceIdSchema = number().int().nonnegative();
71786
+ var MinutesSchema = number().int().min(0);
71787
+ var pumpCycleCapability = {
71788
+ name: "pump-cycle",
71789
+ scope: "device",
71790
+ deviceNative: true,
71791
+ mode: "singleton",
71792
+ deviceTypes: [DeviceType.PetFountain],
71793
+ methods: {
71794
+ /** Switch the on/off duty cycle on or off (off = the pump runs continuously). */
71795
+ setEnabled: method(object({
71796
+ deviceId: DeviceIdSchema,
71797
+ on: boolean()
71798
+ }), _void(), {
71799
+ kind: "mutation",
71800
+ auth: "protected"
71801
+ }),
71802
+ /** Set how many minutes the pump runs per cycle. */
71803
+ setOnMinutes: method(object({
71804
+ deviceId: DeviceIdSchema,
71805
+ minutes: MinutesSchema
71806
+ }), _void(), {
71807
+ kind: "mutation",
71808
+ auth: "protected"
71809
+ }),
71810
+ /** Set how many minutes the pump rests per cycle. */
71811
+ setOffMinutes: method(object({
71812
+ deviceId: DeviceIdSchema,
71813
+ minutes: MinutesSchema
71814
+ }), _void(), {
71815
+ kind: "mutation",
71816
+ auth: "protected"
71817
+ })
71818
+ },
71819
+ status: {
71820
+ schema: PumpCycleStatusSchema,
71821
+ kind: "push"
71822
+ },
71823
+ /** Runtime-state slice — mirrored by the kernel; the hero card reads it whole. */
71824
+ runtimeState: PumpCycleStatusSchema,
71825
+ /**
71826
+ * Runtime-state durability: **session** — live appliance state re-published on connect.
71827
+ *
71828
+ * See `RuntimeStateDurability`. Enforced by
71829
+ * `scripts/check-runtime-state-durability.ts`.
71830
+ */
71831
+ durability: "session",
71832
+ /** History (D850): a duty-cycle setting is not a series worth recording. */
71833
+ history: "none"
71834
+ };
70350
71835
  DeviceType.Camera, DeviceType.Sensor, DeviceType.Switch, DeviceType.Gateway, method(object({ deviceId: number().int().nonnegative() }), object({ success: literal(true) }), {
70351
71836
  kind: "mutation",
70352
71837
  auth: "admin"
@@ -73137,7 +74622,13 @@ var RemoteMediaCommandSchema = _enum([
73137
74622
  "next",
73138
74623
  "previous",
73139
74624
  "setMute",
73140
- "selectSource"
74625
+ "selectSource",
74626
+ "turnOn",
74627
+ "turnOff",
74628
+ "volumeUp",
74629
+ "volumeDown",
74630
+ "channelUp",
74631
+ "channelDown"
73141
74632
  ]);
73142
74633
  /** A send result, or `not-routed`: the role is not bound, so the native cap answers. */
73143
74634
  var RemoteMediaCommandResultSchema = discriminatedUnion("status", [...RemoteSendResultSchema.options, object({ status: literal("not-routed") })]);
@@ -73158,7 +74649,7 @@ method(deviceInput, RemoteConfigSchema, { auth: "admin" }), method(deviceInput.e
73158
74649
  }), RemoteSendResultSchema, {
73159
74650
  kind: "mutation",
73160
74651
  auth: "protected"
73161
- }), method(deviceInput.extend({
74652
+ }), method(deviceInput, MediaPlayerStatusSchema.nullable(), { auth: "protected" }), method(deviceInput.extend({
73162
74653
  command: RemoteMediaCommandSchema,
73163
74654
  muted: boolean().optional(),
73164
74655
  source: string().optional(),
@@ -75404,7 +76895,11 @@ listSignals: method(_void(), array(StreamSignalSchema).readonly()) }
75404
76895
  * `getSettingsUISchema()` surface.
75405
76896
  */
75406
76897
  var SwitchStatusSchema = object({
75407
- on: boolean().meta({ label: "On" }),
76898
+ /**
76899
+ * `null` = the device has never reported its state (a measurement that
76900
+ * has not happened is unknown, never `false`).
76901
+ */
76902
+ on: boolean().nullable().meta({ label: "On" }),
75408
76903
  /** Ms epoch of the last state change. Useful for UI "X minutes ago". */
75409
76904
  lastChangedAt: number()
75410
76905
  });
@@ -75429,7 +76924,7 @@ var switchCapability = {
75429
76924
  }) },
75430
76925
  events: { onStateChanged: { data: object({
75431
76926
  deviceId: number(),
75432
- on: boolean(),
76927
+ on: boolean().nullable(),
75433
76928
  lastChangedAt: number()
75434
76929
  }) } },
75435
76930
  status: {
@@ -79078,6 +80573,26 @@ function buildDescriptor(capName, kind) {
79078
80573
  * contributes one entry per bound cap present in this map.
79079
80574
  */
79080
80575
  var EVENT_KIND_BY_CAP = Object.freeze(Object.fromEntries(Object.entries(CAP_TO_KIND).map(([capName, kind]) => [capName, buildDescriptor(capName, kind)])));
80576
+ /**
80577
+ * What a remote key is CALLED and what it LOOKS like, for every role (D963),
80578
+ * shared by the admin UI and the viewer. A role is data on the wire; each
80579
+ * client resolves its name from `label` (English and Italian side by side) and
80580
+ * its glyph from `icon`, a lucide id from the shared icon catalogue — the
80581
+ * server sends an id, a client maps it to its own icon set.
80582
+ *
80583
+ * `legend` is text printed on the key INSTEAD of a glyph (a digit has no
80584
+ * pictogram): a client that can draw text shows it, one that cannot falls back
80585
+ * to `icon`.
80586
+ */
80587
+ function digit(n) {
80588
+ return {
80589
+ label: t(n, n),
80590
+ icon: "hash",
80591
+ legend: n
80592
+ };
80593
+ }
80594
+ digit("0"), digit("1"), digit("2"), digit("3"), digit("4"), digit("5"), digit("6"), digit("7"), digit("8"), digit("9");
80595
+ DeviceFeature.MediaPlayerPower, DeviceFeature.MediaPlayerVolumeStep, DeviceFeature.MediaPlayerChannelStep, DeviceFeature.MediaPlayerMute, DeviceFeature.MediaPlayerStop, DeviceFeature.MediaPlayerNext, DeviceFeature.MediaPlayerPrevious;
79081
80596
  var btn = (idSuffix, row, col, init) => ({
79082
80597
  idSuffix,
79083
80598
  row,
@@ -79204,6 +80719,42 @@ discriminatedUnion("kind", [object({
79204
80719
  kind: literal("pronto"),
79205
80720
  code: string()
79206
80721
  })]);
80722
+ /**
80723
+ * Propose a running threshold from a device's own power history (planning#405).
80724
+ *
80725
+ * Pure and deterministic: the same series gives the same answer. The series is
80726
+ * a HELD-VALUE step series — a point's value stands until the next point — which
80727
+ * is how device-history stores a gauge, so "time at a level" is exact, not a
80728
+ * count of samples.
80729
+ *
80730
+ * 1. idle floor F = time-weighted median; noise ceiling N = highest value seen
80731
+ * near F. A device that is not near one level most of the time has no floor.
80732
+ * 2. coarse activity = above max(2N, N + 5 W); consecutive stretches are episodes.
80733
+ * 3. an episode shorter than `PULSE_MAX_MS` is a PULSE (an anti-crease tumble, a
80734
+ * display waking): it is neither a run nor a pause. Among the remaining
80735
+ * episodes, gaps over `PAUSE_MAX_MS` always separate runs; the rest split in
80736
+ * two by the largest log-scale jump (>= 3x): the short ones are pauses INSIDE
80737
+ * a run (a soak), the long ones separate runs. A stretch under `MIN_RUN_MS`
80738
+ * is no run.
80739
+ * 4. T = geometric mean of N and the plateau's 10th percentile, snapped to a
80740
+ * grid a person would type; stop dwell covers the longest pause and the
80741
+ * kind's floor; start dwell covers the longest pulse and standby blip above T.
80742
+ * 5. the numbers are proved by REPLAY through the real `dwell` evaluation: each
80743
+ * run must hold exactly one true interval and nothing may flap outside.
80744
+ */
80745
+ var SECOND_MS = 1e3;
80746
+ var MINUTE_MS$1 = 60 * SECOND_MS;
80747
+ 24 * (60 * MINUTE_MS$1);
80748
+ 10 * MINUTE_MS$1;
80749
+ 30 * SECOND_MS;
80750
+ 60 * SECOND_MS;
80751
+ 20 * MINUTE_MS$1;
80752
+ 90 * SECOND_MS;
80753
+ 30 * MINUTE_MS$1;
80754
+ 10 * MINUTE_MS$1;
80755
+ DeviceType.Dryer, 3 * MINUTE_MS$1, DeviceType.Dishwasher, 3 * MINUTE_MS$1, DeviceType.Washer, 10 * MINUTE_MS$1;
80756
+ 10 * SECOND_MS;
80757
+ 10 * SECOND_MS;
79207
80758
  DeviceFeature.FanSpeed, DeviceFeature.FanPreset, DeviceFeature.FanDirection, DeviceFeature.FanOscillating, DeviceFeature.CoverStoppable, DeviceFeature.CoverPositionable, DeviceFeature.CoverTilt, DeviceFeature.ValvePositionable, DeviceFeature.MediaPlayerVolume, DeviceFeature.ClimateFanMode;
79208
80759
  SOURCE_CAPS.filter((cap) => cap !== "switch" && cap !== "motion");
79209
80760
  String.raw`rose\(active(\d+), changed(\d+), (\d+(?:\.\d+)?)\)`;
@@ -79564,6 +81115,7 @@ var DEVICE_LOCAL_STATE_CAPS = {
79564
81115
  pressureSensor: pressureSensorCapability,
79565
81116
  privacyMask: privacyMaskCapability,
79566
81117
  ptzAutotrack: ptzAutotrackCapability,
81118
+ pumpCycle: pumpCycleCapability,
79567
81119
  recordingOnboard: recordingOnboardCapability,
79568
81120
  recordingSignal: recordingSignalCapability,
79569
81121
  runningState: runningStateCapability,
@@ -81748,6 +83300,27 @@ Object.freeze({
81748
83300
  access: "view",
81749
83301
  role: "viewer"
81750
83302
  },
83303
+ "boardKeySource.getBoardKey": {
83304
+ capName: "board-key-source",
83305
+ capScope: "system",
83306
+ addonId: null,
83307
+ access: "view",
83308
+ role: "admin"
83309
+ },
83310
+ "boardKeySource.listBoards": {
83311
+ capName: "board-key-source",
83312
+ capScope: "system",
83313
+ addonId: null,
83314
+ access: "view",
83315
+ role: "admin"
83316
+ },
83317
+ "boardKeySource.listSources": {
83318
+ capName: "board-key-source",
83319
+ capScope: "system",
83320
+ addonId: null,
83321
+ access: "view",
83322
+ role: "admin"
83323
+ },
81751
83324
  "brightness.getStatus": {
81752
83325
  capName: "brightness",
81753
83326
  capScope: "device",
@@ -82287,6 +83860,13 @@ Object.freeze({
82287
83860
  access: "create",
82288
83861
  role: "admin"
82289
83862
  },
83863
+ "coreBlocks.proposeRunningThreshold": {
83864
+ capName: "core-blocks",
83865
+ capScope: "system",
83866
+ addonId: null,
83867
+ access: "view",
83868
+ role: "admin"
83869
+ },
82290
83870
  "coreBlocks.reportAutomationRun": {
82291
83871
  capName: "core-blocks",
82292
83872
  capScope: "system",
@@ -82798,6 +84378,13 @@ Object.freeze({
82798
84378
  access: "view",
82799
84379
  role: "admin"
82800
84380
  },
84381
+ "deviceExport.listInstances": {
84382
+ capName: "device-export",
84383
+ capScope: "system",
84384
+ addonId: null,
84385
+ access: "view",
84386
+ role: "admin"
84387
+ },
82801
84388
  "deviceExport.listSupportedDeviceKinds": {
82802
84389
  capName: "device-export",
82803
84390
  capScope: "system",
@@ -84429,6 +86016,13 @@ Object.freeze({
84429
86016
  access: "view",
84430
86017
  role: "admin"
84431
86018
  },
86019
+ "integrationInstances.setInstanceEnabled": {
86020
+ capName: "integration-instances",
86021
+ capScope: "system",
86022
+ addonId: null,
86023
+ access: "create",
86024
+ role: "admin"
86025
+ },
84432
86026
  "integrationInstances.testInstance": {
84433
86027
  capName: "integration-instances",
84434
86028
  capScope: "system",
@@ -84478,13 +86072,6 @@ Object.freeze({
84478
86072
  access: "view",
84479
86073
  role: "admin"
84480
86074
  },
84481
- "integrations.getSettings": {
84482
- capName: "integrations",
84483
- capScope: "system",
84484
- addonId: null,
84485
- access: "view",
84486
- role: "admin"
84487
- },
84488
86075
  "integrations.list": {
84489
86076
  capName: "integrations",
84490
86077
  capScope: "system",
@@ -84492,13 +86079,6 @@ Object.freeze({
84492
86079
  access: "view",
84493
86080
  role: "admin"
84494
86081
  },
84495
- "integrations.setSettings": {
84496
- capName: "integrations",
84497
- capScope: "system",
84498
- addonId: null,
84499
- access: "create",
84500
- role: "admin"
84501
- },
84502
86082
  "integrations.testConnection": {
84503
86083
  capName: "integrations",
84504
86084
  capScope: "system",
@@ -85227,6 +86807,20 @@ Object.freeze({
85227
86807
  access: "view",
85228
86808
  role: "admin"
85229
86809
  },
86810
+ "mediaPlayer.channelDown": {
86811
+ capName: "media-player",
86812
+ capScope: "device",
86813
+ addonId: null,
86814
+ access: "create",
86815
+ role: "viewer"
86816
+ },
86817
+ "mediaPlayer.channelUp": {
86818
+ capName: "media-player",
86819
+ capScope: "device",
86820
+ addonId: null,
86821
+ access: "create",
86822
+ role: "viewer"
86823
+ },
85230
86824
  "mediaPlayer.getStatus": {
85231
86825
  capName: "media-player",
85232
86826
  capScope: "device",
@@ -85318,6 +86912,34 @@ Object.freeze({
85318
86912
  access: "create",
85319
86913
  role: "viewer"
85320
86914
  },
86915
+ "mediaPlayer.turnOff": {
86916
+ capName: "media-player",
86917
+ capScope: "device",
86918
+ addonId: null,
86919
+ access: "create",
86920
+ role: "viewer"
86921
+ },
86922
+ "mediaPlayer.turnOn": {
86923
+ capName: "media-player",
86924
+ capScope: "device",
86925
+ addonId: null,
86926
+ access: "create",
86927
+ role: "viewer"
86928
+ },
86929
+ "mediaPlayer.volumeDown": {
86930
+ capName: "media-player",
86931
+ capScope: "device",
86932
+ addonId: null,
86933
+ access: "create",
86934
+ role: "viewer"
86935
+ },
86936
+ "mediaPlayer.volumeUp": {
86937
+ capName: "media-player",
86938
+ capScope: "device",
86939
+ addonId: null,
86940
+ access: "create",
86941
+ role: "viewer"
86942
+ },
85321
86943
  "meshNetwork.getStatus": {
85322
86944
  capName: "mesh-network",
85323
86945
  capScope: "system",
@@ -85451,6 +87073,13 @@ Object.freeze({
85451
87073
  access: "view",
85452
87074
  role: "admin"
85453
87075
  },
87076
+ "migrations.clearLegacyIntegrationRows": {
87077
+ capName: "migrations",
87078
+ capScope: "system",
87079
+ addonId: null,
87080
+ access: "delete",
87081
+ role: "admin"
87082
+ },
85454
87083
  "migrations.declareOwner": {
85455
87084
  capName: "migrations",
85456
87085
  capScope: "system",
@@ -85458,6 +87087,13 @@ Object.freeze({
85458
87087
  access: "create",
85459
87088
  role: "admin"
85460
87089
  },
87090
+ "migrations.deleteLegacyIntegrationRowKeys": {
87091
+ capName: "migrations",
87092
+ capScope: "system",
87093
+ addonId: null,
87094
+ access: "delete",
87095
+ role: "admin"
87096
+ },
85461
87097
  "migrations.dryRun": {
85462
87098
  capName: "migrations",
85463
87099
  capScope: "system",
@@ -85493,6 +87129,20 @@ Object.freeze({
85493
87129
  access: "create",
85494
87130
  role: "admin"
85495
87131
  },
87132
+ "migrations.patchLegacyIntegrationRows": {
87133
+ capName: "migrations",
87134
+ capScope: "system",
87135
+ addonId: null,
87136
+ access: "create",
87137
+ role: "admin"
87138
+ },
87139
+ "migrations.readLegacyIntegrationRows": {
87140
+ capName: "migrations",
87141
+ capScope: "system",
87142
+ addonId: null,
87143
+ access: "view",
87144
+ role: "admin"
87145
+ },
85496
87146
  "migrations.restorePreMigration": {
85497
87147
  capName: "migrations",
85498
87148
  capScope: "system",
@@ -86564,27 +88214,6 @@ Object.freeze({
86564
88214
  access: "create",
86565
88215
  role: "viewer"
86566
88216
  },
86567
- "petFountain.setPumpInterval": {
86568
- capName: "pet-fountain",
86569
- capScope: "device",
86570
- addonId: null,
86571
- access: "create",
86572
- role: "viewer"
86573
- },
86574
- "petFountain.setPumpOffMinutes": {
86575
- capName: "pet-fountain",
86576
- capScope: "device",
86577
- addonId: null,
86578
- access: "create",
86579
- role: "viewer"
86580
- },
86581
- "petFountain.setPumpOnMinutes": {
86582
- capName: "pet-fountain",
86583
- capScope: "device",
86584
- addonId: null,
86585
- access: "create",
86586
- role: "viewer"
86587
- },
86588
88217
  "pipelineAnalytics.addRetrainFrameFromRecording": {
86589
88218
  capName: "pipeline-analytics",
86590
88219
  capScope: "device",
@@ -88363,6 +89992,34 @@ Object.freeze({
88363
89992
  access: "create",
88364
89993
  role: "admin"
88365
89994
  },
89995
+ "pumpCycle.getStatus": {
89996
+ capName: "pump-cycle",
89997
+ capScope: "device",
89998
+ addonId: null,
89999
+ access: "view",
90000
+ role: "viewer"
90001
+ },
90002
+ "pumpCycle.setEnabled": {
90003
+ capName: "pump-cycle",
90004
+ capScope: "device",
90005
+ addonId: null,
90006
+ access: "create",
90007
+ role: "viewer"
90008
+ },
90009
+ "pumpCycle.setOffMinutes": {
90010
+ capName: "pump-cycle",
90011
+ capScope: "device",
90012
+ addonId: null,
90013
+ access: "create",
90014
+ role: "viewer"
90015
+ },
90016
+ "pumpCycle.setOnMinutes": {
90017
+ capName: "pump-cycle",
90018
+ capScope: "device",
90019
+ addonId: null,
90020
+ access: "create",
90021
+ role: "viewer"
90022
+ },
88366
90023
  "reboot.reboot": {
88367
90024
  capName: "reboot",
88368
90025
  capScope: "device",
@@ -88867,6 +90524,13 @@ Object.freeze({
88867
90524
  access: "create",
88868
90525
  role: "admin"
88869
90526
  },
90527
+ "remote.getAssumedStatus": {
90528
+ capName: "remote",
90529
+ capScope: "system",
90530
+ addonId: null,
90531
+ access: "view",
90532
+ role: "admin"
90533
+ },
88870
90534
  "remote.getConfig": {
88871
90535
  capName: "remote",
88872
90536
  capScope: "system",
@@ -91682,6 +93346,11 @@ Object.freeze({
91682
93346
  form: "single",
91683
93347
  optional: false
91684
93348
  }],
93349
+ "coreBlocks.proposeRunningThreshold": [{
93350
+ name: "deviceId",
93351
+ form: "single",
93352
+ optional: false
93353
+ }],
91685
93354
  "cover.close": [{
91686
93355
  name: "deviceId",
91687
93356
  form: "single",
@@ -92533,6 +94202,16 @@ Object.freeze({
92533
94202
  form: "single",
92534
94203
  optional: true
92535
94204
  }],
94205
+ "mediaPlayer.channelDown": [{
94206
+ name: "deviceId",
94207
+ form: "single",
94208
+ optional: false
94209
+ }],
94210
+ "mediaPlayer.channelUp": [{
94211
+ name: "deviceId",
94212
+ form: "single",
94213
+ optional: false
94214
+ }],
92536
94215
  "mediaPlayer.getStatus": [{
92537
94216
  name: "deviceId",
92538
94217
  form: "single",
@@ -92598,6 +94277,26 @@ Object.freeze({
92598
94277
  form: "single",
92599
94278
  optional: false
92600
94279
  }],
94280
+ "mediaPlayer.turnOff": [{
94281
+ name: "deviceId",
94282
+ form: "single",
94283
+ optional: false
94284
+ }],
94285
+ "mediaPlayer.turnOn": [{
94286
+ name: "deviceId",
94287
+ form: "single",
94288
+ optional: false
94289
+ }],
94290
+ "mediaPlayer.volumeDown": [{
94291
+ name: "deviceId",
94292
+ form: "single",
94293
+ optional: false
94294
+ }],
94295
+ "mediaPlayer.volumeUp": [{
94296
+ name: "deviceId",
94297
+ form: "single",
94298
+ optional: false
94299
+ }],
92601
94300
  "meter.getStatus": [{
92602
94301
  name: "deviceId",
92603
94302
  form: "single",
@@ -92907,21 +94606,6 @@ Object.freeze({
92907
94606
  form: "single",
92908
94607
  optional: false
92909
94608
  }],
92910
- "petFountain.setPumpInterval": [{
92911
- name: "deviceId",
92912
- form: "single",
92913
- optional: false
92914
- }],
92915
- "petFountain.setPumpOffMinutes": [{
92916
- name: "deviceId",
92917
- form: "single",
92918
- optional: false
92919
- }],
92920
- "petFountain.setPumpOnMinutes": [{
92921
- name: "deviceId",
92922
- form: "single",
92923
- optional: false
92924
- }],
92925
94609
  "pipelineAnalytics.addRetrainFrameFromRecording": [{
92926
94610
  name: "deviceId",
92927
94611
  form: "single",
@@ -93557,6 +95241,26 @@ Object.freeze({
93557
95241
  form: "single",
93558
95242
  optional: false
93559
95243
  }],
95244
+ "pumpCycle.getStatus": [{
95245
+ name: "deviceId",
95246
+ form: "single",
95247
+ optional: false
95248
+ }],
95249
+ "pumpCycle.setEnabled": [{
95250
+ name: "deviceId",
95251
+ form: "single",
95252
+ optional: false
95253
+ }],
95254
+ "pumpCycle.setOffMinutes": [{
95255
+ name: "deviceId",
95256
+ form: "single",
95257
+ optional: false
95258
+ }],
95259
+ "pumpCycle.setOnMinutes": [{
95260
+ name: "deviceId",
95261
+ form: "single",
95262
+ optional: false
95263
+ }],
93560
95264
  "reboot.reboot": [{
93561
95265
  name: "deviceId",
93562
95266
  form: "single",
@@ -93758,6 +95462,11 @@ Object.freeze({
93758
95462
  form: "single",
93759
95463
  optional: true
93760
95464
  }],
95465
+ "remote.getAssumedStatus": [{
95466
+ name: "deviceId",
95467
+ form: "single",
95468
+ optional: false
95469
+ }],
93761
95470
  "remote.getConfig": [{
93762
95471
  name: "deviceId",
93763
95472
  form: "single",
@@ -94305,99 +96014,6 @@ Object.freeze({
94305
96014
  "network-access": "ingress",
94306
96015
  "smtp-provider": "email"
94307
96016
  });
94308
- /**
94309
- * A saved Customize assignment (D936). The schema is the type: callers use
94310
- * `z.infer`, they do not restate the shape.
94311
- */
94312
- var OverrideSourceSchema = object({
94313
- addonId: string().min(1),
94314
- stableId: string().min(1),
94315
- cap: string().min(1),
94316
- fieldPath: string().min(1)
94317
- });
94318
- var CustomizeTransformDraftSchema = discriminatedUnion("kind", [
94319
- object({ kind: literal("identity") }),
94320
- object({ kind: literal("invert") }),
94321
- object({
94322
- kind: literal("threshold"),
94323
- comparison: _enum(["gte", "lte"]),
94324
- threshold: number(),
94325
- startDwellMs: number().nonnegative(),
94326
- stopDwellMs: number().nonnegative()
94327
- }),
94328
- object({
94329
- kind: literal("linear"),
94330
- scale: number(),
94331
- offset: number(),
94332
- clampMin: number().optional(),
94333
- clampMax: number().optional()
94334
- }),
94335
- object({
94336
- kind: literal("enum-map"),
94337
- mapping: record(string(), string().nullable())
94338
- }),
94339
- object({ kind: literal("number") })
94340
- ]);
94341
- var ScalarOverrideDraftSchema = object({
94342
- kind: literal("scalar"),
94343
- cap: string().min(1),
94344
- targetId: string().min(1),
94345
- source: OverrideSourceSchema,
94346
- transform: CustomizeTransformDraftSchema
94347
- });
94348
- var KeyedArrayOverrideDraftSchema = object({
94349
- kind: literal("keyedArray"),
94350
- cap: string().min(1),
94351
- targetId: string().min(1),
94352
- key: string().min(1),
94353
- label: string().min(1),
94354
- fieldPath: string().min(1),
94355
- source: OverrideSourceSchema,
94356
- transform: CustomizeTransformDraftSchema
94357
- });
94358
- var PulseOverrideDraftSchema = object({
94359
- kind: literal("pulse"),
94360
- cap: string().min(1),
94361
- targetId: string().min(1),
94362
- enabled: boolean(),
94363
- debounceMs: number().nonnegative(),
94364
- edges: array(_enum([
94365
- "rising",
94366
- "button",
94367
- "native-event"
94368
- ])).min(1).optional(),
94369
- sources: array(OverrideSourceSchema).min(1)
94370
- });
94371
- var SpanSourceDraftSchema = OverrideSourceSchema.extend({ mode: _enum([
94372
- "in-addition",
94373
- "confirm",
94374
- "replace"
94375
- ]).optional() });
94376
- discriminatedUnion("kind", [
94377
- ScalarOverrideDraftSchema,
94378
- KeyedArrayOverrideDraftSchema,
94379
- PulseOverrideDraftSchema,
94380
- object({
94381
- kind: literal("span"),
94382
- cap: string().min(1),
94383
- targetId: string().min(1),
94384
- timeoutMs: number().nonnegative(),
94385
- cooldownMs: number().nonnegative().optional(),
94386
- sources: array(SpanSourceDraftSchema)
94387
- })
94388
- ]);
94389
- object({
94390
- targetId: string().min(1),
94391
- configured: boolean(),
94392
- source: _enum(["native", "assigned"]),
94393
- state: _enum([
94394
- "active",
94395
- "stale",
94396
- "released",
94397
- "unavailable"
94398
- ]),
94399
- reason: string().nullable()
94400
- });
94401
96017
  var G711_SCALE_CORRECTION_DB = {
94402
96018
  PCMU: 20 * Math.log10(4),
94403
96019
  PCMA: 20 * Math.log10(8)
@@ -95013,6 +96629,7 @@ var STATE_SUMMARY_VARS = [
95013
96629
  [...RULE_TEXT],
95014
96630
  ([...RULE_TEXT], [...DEVICE_EVENTS]),
95015
96631
  ([...RULE_TEXT], [...COMBINED_ALARM]),
96632
+ ([...RULE_TEXT], [...COMBINED_ALARM]),
95016
96633
  ([...RULE_TEXT], [...DEVICE_EVENTS]),
95017
96634
  ([...RULE_TEXT], [...BATTERY, ...CONSUMABLE]),
95018
96635
  ([...RULE_TEXT], [...CONSUMABLE]),
@@ -119909,6 +121526,83 @@ function buildCcuOverviewHandlers(deps) {
119909
121526
  };
119910
121527
  }
119911
121528
  //#endregion
121529
+ //#region src/custom-actions.ts
121530
+ /**
121531
+ * Custom actions of the Homematic addon: the LAN scan behind the integration
121532
+ * form's CCU picker, and the CCU management page (`provider-homematic` admin
121533
+ * page). Reads are `query`; every CCU write is a `mutation` whose input carries
121534
+ * the operator's `confirmed` flag.
121535
+ */
121536
+ var homematicActions = defineCustomActions({
121537
+ discoverCcu: customAction(object({}), object({
121538
+ hosts: array(object({
121539
+ host: string(),
121540
+ name: string(),
121541
+ id: string()
121542
+ })),
121543
+ summary: string()
121544
+ }), {
121545
+ kind: "mutation",
121546
+ auth: "admin"
121547
+ }),
121548
+ listCcus: customAction(object({}), array(CcuListItemSchema), {
121549
+ kind: "query",
121550
+ auth: "admin"
121551
+ }),
121552
+ ccuOverview: customAction(IntegrationRefSchema, CcuOverviewSchema, {
121553
+ kind: "query",
121554
+ auth: "admin"
121555
+ }),
121556
+ listServiceMessages: customAction(IntegrationRefSchema, ServiceMessagesResultSchema, {
121557
+ kind: "query",
121558
+ auth: "admin"
121559
+ }),
121560
+ listCcuDevices: customAction(IntegrationRefSchema, CcuDevicesResultSchema, {
121561
+ kind: "query",
121562
+ auth: "admin"
121563
+ }),
121564
+ listHeatingGroups: customAction(IntegrationRefSchema, HeatingOverviewSchema, {
121565
+ kind: "query",
121566
+ auth: "admin"
121567
+ }),
121568
+ createHeatingGroup: customAction(CreateGroupInputSchema, HeatingGroupSchema, {
121569
+ kind: "mutation",
121570
+ auth: "admin"
121571
+ }),
121572
+ updateHeatingGroup: customAction(UpdateGroupInputSchema, HeatingGroupSchema, {
121573
+ kind: "mutation",
121574
+ auth: "admin"
121575
+ }),
121576
+ deleteHeatingGroup: customAction(DeleteGroupInputSchema, OkResultSchema, {
121577
+ kind: "mutation",
121578
+ auth: "admin"
121579
+ }),
121580
+ ccuPairingStatus: customAction(IntegrationRefSchema, PairingStatusSchema, {
121581
+ kind: "query",
121582
+ auth: "admin"
121583
+ }),
121584
+ setCcuInstallMode: customAction(SetInstallModeInputSchema, OkResultSchema, {
121585
+ kind: "mutation",
121586
+ auth: "admin"
121587
+ }),
121588
+ deleteCcuDevice: customAction(DeleteCcuDeviceInputSchema, OkResultSchema, {
121589
+ kind: "mutation",
121590
+ auth: "admin"
121591
+ }),
121592
+ getCcuDeviceConfig: customAction(DeviceRefSchema, DeviceConfigSchema, {
121593
+ kind: "query",
121594
+ auth: "admin"
121595
+ }),
121596
+ setCcuChannelConfig: customAction(SetChannelConfigInputSchema, OkResultSchema, {
121597
+ kind: "mutation",
121598
+ auth: "admin"
121599
+ }),
121600
+ acknowledgeServiceMessage: customAction(AcknowledgeInputSchema, OkResultSchema, {
121601
+ kind: "mutation",
121602
+ auth: "admin"
121603
+ })
121604
+ });
121605
+ //#endregion
119912
121606
  //#region src/callback-host.ts
119913
121607
  /**
119914
121608
  * Pick the hub LAN IPv4 a CCU at `ccuHost` can call back to. Prefers an
@@ -120175,83 +121869,170 @@ function buildConnectionFormSchema() {
120175
121869
  }
120176
121870
  ] };
120177
121871
  }
121872
+ var homematicConnectionsEntryKind = defineEntryKind("connections", {
121873
+ title: "Homematic CCUs",
121874
+ schema: entryBody({
121875
+ host: string().nullish(),
121876
+ enableHmipRf: boolean().nullish(),
121877
+ enableBidcosRf: boolean().nullish(),
121878
+ enableGroups: boolean().nullish(),
121879
+ enableBidcosWired: boolean().nullish(),
121880
+ username: string().nullish(),
121881
+ password: string().optional().meta({ secret: true }),
121882
+ callbackHost: string().nullish(),
121883
+ callbackPort: number().int().min(1).max(65535).nullish(),
121884
+ tls: boolean().nullish()
121885
+ }),
121886
+ writeTrigger: "an operator adds, edits or removes a Homematic CCU"
121887
+ });
121888
+ /** Every kind this addon declares, keyed by its name. */
121889
+ var homematicRecordKinds = { connections: homematicConnectionsEntryKind };
121890
+ /** The record body as the flat settings the connection schema parses: no name, no unset keys. */
121891
+ function connectionSettingsOf(body) {
121892
+ const out = {};
121893
+ for (const [key, value] of Object.entries(body)) {
121894
+ if (key === "name" || value === null || value === void 0) continue;
121895
+ out[key] = value;
121896
+ }
121897
+ return out;
121898
+ }
121899
+ function settingsReadOf(resolved) {
121900
+ return resolved === null ? {
121901
+ values: {},
121902
+ secretsLocked: false
121903
+ } : {
121904
+ values: connectionSettingsOf(resolved.body),
121905
+ secretsLocked: resolved.secrets === "unavailable"
121906
+ };
121907
+ }
121908
+ function buildHomematicInstances(records, deps) {
121909
+ return new RecordIntegrationInstances(records, homematicConnectionsEntryKind, {
121910
+ description: {
121911
+ role: "devices",
121912
+ discovery: {
121913
+ mode: "lan",
121914
+ scopedToInstance: false
121915
+ },
121916
+ instanceMode: "multiple",
121917
+ kind: "connection",
121918
+ canTest: false
121919
+ },
121920
+ formSchema: () => buildConnectionFormSchema(),
121921
+ initialBody: (name) => ({ name }),
121922
+ configured: (body) => (body.host ?? "").trim().length > 0,
121923
+ onChanged: () => deps.onChanged()
121924
+ });
121925
+ }
121926
+ /** The ONE reader of a CCU's connection: the integration's record, never the legacy rows. */
121927
+ async function readCcuConnection(instances, integrationId) {
121928
+ const read = settingsReadOf(await instances.readResolved(integrationId));
121929
+ return {
121930
+ connection: connectionFromSettings(read.values),
121931
+ secretsLocked: read.secretsLocked
121932
+ };
121933
+ }
121934
+ /** The hosts of the CCUs already set up, for discovery to leave out; an unreadable one is skipped. */
121935
+ async function knownCcuHostsOf(deps) {
121936
+ const hosts = [];
121937
+ for (const id of deps.integrationIds) try {
121938
+ const { connection } = await readCcuConnection(deps.instances, id);
121939
+ if (connection !== null) hosts.push(connection.host);
121940
+ } catch (err) {
121941
+ deps.onUnreadable(id, err);
121942
+ }
121943
+ return hosts;
121944
+ }
120178
121945
  //#endregion
120179
- //#region src/custom-actions.ts
121946
+ //#region src/migrations/integration-rows-to-record.ts
120180
121947
  /**
120181
- * Custom actions of the Homematic addon: the LAN scan behind the integration
120182
- * form's CCU picker, and the CCU management page (`provider-homematic` admin
120183
- * page). Reads are `query`; every CCU write is a `mutation` whose input carries
120184
- * the operator's `confirmed` flag.
121948
+ * Every Homematic integration moves from legacy `integration_settings` rows into its own
121949
+ * `connections` record under the registry id (planning#416, D1007): the CCU connection the live
121950
+ * session dials, the WebUI password a keychain secret declared by the kind. Each integration's
121951
+ * record is built from ITS OWN rows, never from another's. Only the integration configuration
121952
+ * moves: adopted devices, their stable ids and their history are not touched.
121953
+ *
121954
+ * Keys nothing reads any more are named in a warning, by key, and dropped with the rows once the
121955
+ * record has been read back; a value of the wrong type is left out and named by key as well.
120185
121956
  */
120186
- var homematicActions = defineCustomActions({
120187
- discoverCcu: customAction(object({}), object({
120188
- hosts: array(object({
120189
- host: string(),
120190
- name: string(),
120191
- id: string()
120192
- })),
120193
- summary: string()
120194
- }), {
120195
- kind: "mutation",
120196
- auth: "admin"
120197
- }),
120198
- listCcus: customAction(object({}), array(CcuListItemSchema), {
120199
- kind: "query",
120200
- auth: "admin"
120201
- }),
120202
- ccuOverview: customAction(IntegrationRefSchema, CcuOverviewSchema, {
120203
- kind: "query",
120204
- auth: "admin"
120205
- }),
120206
- listServiceMessages: customAction(IntegrationRefSchema, ServiceMessagesResultSchema, {
120207
- kind: "query",
120208
- auth: "admin"
120209
- }),
120210
- listCcuDevices: customAction(IntegrationRefSchema, CcuDevicesResultSchema, {
120211
- kind: "query",
120212
- auth: "admin"
120213
- }),
120214
- listHeatingGroups: customAction(IntegrationRefSchema, HeatingOverviewSchema, {
120215
- kind: "query",
120216
- auth: "admin"
120217
- }),
120218
- createHeatingGroup: customAction(CreateGroupInputSchema, HeatingGroupSchema, {
120219
- kind: "mutation",
120220
- auth: "admin"
120221
- }),
120222
- updateHeatingGroup: customAction(UpdateGroupInputSchema, HeatingGroupSchema, {
120223
- kind: "mutation",
120224
- auth: "admin"
120225
- }),
120226
- deleteHeatingGroup: customAction(DeleteGroupInputSchema, OkResultSchema, {
120227
- kind: "mutation",
120228
- auth: "admin"
120229
- }),
120230
- ccuPairingStatus: customAction(IntegrationRefSchema, PairingStatusSchema, {
120231
- kind: "query",
120232
- auth: "admin"
120233
- }),
120234
- setCcuInstallMode: customAction(SetInstallModeInputSchema, OkResultSchema, {
120235
- kind: "mutation",
120236
- auth: "admin"
120237
- }),
120238
- deleteCcuDevice: customAction(DeleteCcuDeviceInputSchema, OkResultSchema, {
120239
- kind: "mutation",
120240
- auth: "admin"
120241
- }),
120242
- getCcuDeviceConfig: customAction(DeviceRefSchema, DeviceConfigSchema, {
120243
- kind: "query",
120244
- auth: "admin"
120245
- }),
120246
- setCcuChannelConfig: customAction(SetChannelConfigInputSchema, OkResultSchema, {
120247
- kind: "mutation",
120248
- auth: "admin"
120249
- }),
120250
- acknowledgeServiceMessage: customAction(AcknowledgeInputSchema, OkResultSchema, {
120251
- kind: "mutation",
120252
- auth: "admin"
121957
+ var HOMEMATIC_ROWS_TO_RECORD_ID = "provider-homematic/2026-11-05-integration-rows-to-record";
121958
+ var TEXT_KEYS = [
121959
+ "host",
121960
+ "username",
121961
+ "callbackHost"
121962
+ ];
121963
+ var FLAG_KEYS = [
121964
+ "enableHmipRf",
121965
+ "enableBidcosRf",
121966
+ "enableGroups",
121967
+ "enableBidcosWired",
121968
+ "tls"
121969
+ ];
121970
+ function portOf(value) {
121971
+ const n = typeof value === "string" && value.trim() !== "" ? Number(value) : value;
121972
+ return typeof n === "number" && Number.isInteger(n) && n >= 1 && n <= 65535 ? n : null;
121973
+ }
121974
+ /** The record body of one integration, from its resolved legacy rows. Never logs a value. */
121975
+ function homematicBodyFromRows(values, log, integration) {
121976
+ const body = { name: integration.name };
121977
+ const unusable = [];
121978
+ const known = new Set([
121979
+ "password",
121980
+ "callbackPort",
121981
+ ...TEXT_KEYS,
121982
+ ...FLAG_KEYS
121983
+ ]);
121984
+ for (const key of TEXT_KEYS) {
121985
+ if (!(key in values)) continue;
121986
+ const raw = values[key];
121987
+ if (typeof raw === "string") {
121988
+ if (raw.trim() !== "") body[key] = raw.trim();
121989
+ } else unusable.push(key);
121990
+ }
121991
+ for (const key of FLAG_KEYS) {
121992
+ if (!(key in values)) continue;
121993
+ const raw = values[key];
121994
+ if (typeof raw === "boolean") body[key] = raw;
121995
+ else unusable.push(key);
121996
+ }
121997
+ if ("callbackPort" in values) {
121998
+ const raw = values["callbackPort"];
121999
+ if (raw !== "" && raw !== null) {
122000
+ const port = portOf(raw);
122001
+ if (port === null) unusable.push("callbackPort");
122002
+ else body["callbackPort"] = port;
122003
+ }
122004
+ }
122005
+ if ("password" in values) {
122006
+ const password = values["password"];
122007
+ if (typeof password === "string") {
122008
+ if (password.length > 0) body["password"] = password;
122009
+ } else unusable.push("password");
122010
+ }
122011
+ const unknown = Object.keys(values).filter((key) => !known.has(key));
122012
+ if (unknown.length > 0) log.warn(`integration '${integration.id}': legacy settings nothing reads any more are dropped: ${unknown.join(", ")}`);
122013
+ if (unusable.length > 0) log.warn(`integration '${integration.id}': legacy settings with an unusable value are left out: ${unusable.join(", ")}`);
122014
+ return homematicConnectionsEntryKind.schema.parse(body);
122015
+ }
122016
+ var HOMEMATIC_ROWS_TO_RECORD_MIGRATION = {
122017
+ meta: {
122018
+ id: HOMEMATIC_ROWS_TO_RECORD_ID,
122019
+ owner: "provider-homematic",
122020
+ level: "addon-state",
122021
+ seq: 1,
122022
+ dependsOn: [],
122023
+ store: "settings",
122024
+ scope: "cluster",
122025
+ onFailure: "block-owner",
122026
+ bodyKind: "procedure",
122027
+ description: "Move every Homematic CCU integration into its own connection record keyed by its registry id, the WebUI password as a keychain secret, then clear its legacy integration settings rows; adopted devices are not touched",
122028
+ fixtureMark: "a legacy setting key the migration does not know"
122029
+ },
122030
+ procedure: (ports) => moveIntegrationRowsToRecords(ports, {
122031
+ addonId: "provider-homematic",
122032
+ secretPaths: homematicConnectionsEntryKind.declaration.secretPaths,
122033
+ bodyFrom: homematicBodyFromRows
120253
122034
  })
120254
- });
122035
+ };
120255
122036
  //#endregion
120256
122037
  //#region src/homematic-facade-resolver.ts
120257
122038
  /**
@@ -123782,11 +125563,27 @@ var HomematicProviderAddon = class extends BaseDeviceProvider {
123782
125563
  /** Live per-integration CCU sessions, or null before init / after shutdown. */
123783
125564
  integrationReconciler = null;
123784
125565
  clients = null;
125566
+ instances = null;
123785
125567
  constructor() {
123786
125568
  super({});
123787
125569
  }
123788
125570
  async onInitialize() {
123789
125571
  const regs = this.providerRegistrationsFromSuper(await super.onInitialize());
125572
+ const records = this.ctx.records;
125573
+ if (records === void 0) throw new Error("provider-homematic: ctx.records is required (hub-only addon)");
125574
+ await records.declare(homematicRecordKinds);
125575
+ const instances = buildHomematicInstances(records, { onChanged: () => this.reconcileIntegrations() });
125576
+ this.instances = instances;
125577
+ await this.runMigrations(defineAddonMigrations([HOMEMATIC_ROWS_TO_RECORD_MIGRATION], integrationRowsPortsOverApi({
125578
+ api: defaultIntegrationApiOver(this.ctx.api),
125579
+ secrets: this.ctx.secrets ?? null,
125580
+ records: records.kind({
125581
+ name: homematicConnectionsEntryKind.name,
125582
+ declaration: homematicConnectionsEntryKind.declaration,
125583
+ schema: record(string(), unknown())
125584
+ }),
125585
+ log: { warn: (message) => this.ctx.logger.warn(message) }
125586
+ })));
123790
125587
  this.clients = new HmClientRegistry(this.ctx.logger);
123791
125588
  this.clients.setOnConnected((integrationId) => {
123792
125589
  this.ctx.logger.info("Homematic: CCU connected", { meta: { integrationId } });
@@ -123802,6 +125599,10 @@ var HomematicProviderAddon = class extends BaseDeviceProvider {
123802
125599
  return {
123803
125600
  providers: [
123804
125601
  ...regs,
125602
+ {
125603
+ capability: integrationInstancesCapability,
125604
+ provider: instances.toProvider()
125605
+ },
123805
125606
  {
123806
125607
  capability: deviceAdoptionCapability,
123807
125608
  provider: this.buildAdoptionProvider()
@@ -123875,8 +125676,9 @@ var HomematicProviderAddon = class extends BaseDeviceProvider {
123875
125676
  homematicFacades.clear();
123876
125677
  await super.onShutdown();
123877
125678
  }
123878
- globalSettingsSchema() {
123879
- return buildConnectionFormSchema();
125679
+ requireInstances() {
125680
+ if (!this.instances) throw new Error("Homematic provider not initialised");
125681
+ return this.instances;
123880
125682
  }
123881
125683
  /**
123882
125684
  * Stable id, integration-scoped so two CCUs exposing the same device address
@@ -123923,20 +125725,14 @@ var HomematicProviderAddon = class extends BaseDeviceProvider {
123923
125725
  async knownCcuHosts() {
123924
125726
  try {
123925
125727
  const all = await this.ctx.api.integrations.list.query();
123926
- const hosts = [];
123927
- for (const integration of all) {
123928
- if (integration.addonId !== this.ctx.id) continue;
123929
- try {
123930
- const connection = connectionFromSettings(await this.ctx.api.integrations.getSettings.query({ id: integration.id }));
123931
- if (connection) hosts.push(connection.host);
123932
- } catch (err) {
123933
- this.ctx.logger.warn("Homematic discovery: settings read failed", {
123934
- tags: { integrationId: integration.id },
123935
- meta: { error: errMsg(err) }
123936
- });
123937
- }
123938
- }
123939
- return hosts;
125728
+ return await knownCcuHostsOf({
125729
+ instances: this.requireInstances(),
125730
+ integrationIds: all.filter((i) => i.addonId === this.ctx.id).map((i) => i.id),
125731
+ onUnreadable: (integrationId, err) => this.ctx.logger.warn("Homematic discovery: settings read failed", {
125732
+ tags: { integrationId },
125733
+ meta: { error: errMsg(err) }
125734
+ })
125735
+ });
123940
125736
  } catch (err) {
123941
125737
  this.ctx.logger.warn("Homematic discovery: integration list failed", { meta: { error: errMsg(err) } });
123942
125738
  return [];
@@ -123991,8 +125787,8 @@ var HomematicProviderAddon = class extends BaseDeviceProvider {
123991
125787
  },
123992
125788
  listIntegrations: () => this.ctx.api.integrations.list.query(),
123993
125789
  applySettings: async (integration) => {
123994
- const connection = connectionFromSettings(await this.ctx.api.integrations.getSettings.query({ id: integration.id }));
123995
- if (!connection) return false;
125790
+ const { connection, secretsLocked } = await readCcuConnection(this.requireInstances(), integration.id);
125791
+ if (secretsLocked || !connection) return false;
123996
125792
  await this.requireClients().upsert(integration.id, integration.name, connection);
123997
125793
  return true;
123998
125794
  },