@camstack/addon-provider-homematic 1.2.182 → 1.2.184

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
@@ -5990,7 +5990,7 @@ var ZodIssueCode = {
5990
5990
  var ZodFirstPartyTypeKind;
5991
5991
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
5992
5992
  //#endregion
5993
- //#region ../types/dist/sleep-D1jjWAr8.mjs
5993
+ //#region ../types/dist/sleep-CmjWurK5.mjs
5994
5994
  /**
5995
5995
  * The audio chunk plane's byte format, and the ONE expansion from a coded
5996
5996
  * window to float samples (D455).
@@ -6674,130 +6674,92 @@ async function runAddonMigrations(host, migrations, logger, options = {}) {
6674
6674
  blockOwner
6675
6675
  };
6676
6676
  }
6677
- /**
6678
- * Build a {@link DurableState} over a single store key. Transport-agnostic:
6679
- * `read`/`write` are the addon-store or device-store accessors. The whole
6680
- * validated value round-trips on every read/write — the schema is the
6681
- * single source of truth for what is persisted, so no hand-listed field
6682
- * set can drop a key on save.
6683
- */
6684
- function createDurableState(deps) {
6685
- const get = async () => {
6686
- const raw = (await deps.read())[deps.key];
6687
- if (raw === void 0) return deps.fallback;
6688
- const parsed = deps.schema.safeParse(raw);
6689
- if (!parsed.success) {
6690
- deps.onParseError?.(deps.key, parsed.error);
6691
- return deps.fallback;
6692
- }
6693
- return parsed.data;
6694
- };
6695
- const set = async (next) => {
6696
- const validated = deps.schema.parse(next);
6697
- await deps.write({ [deps.key]: validated });
6698
- };
6699
- const update = async (fn) => {
6700
- await set(fn(await get()));
6701
- };
6677
+ /** The record calls the one-switch migration makes, over the migration API. */
6678
+ function switchRecordsOverMigrationApi(api) {
6679
+ return { kind: (definition) => {
6680
+ const handle = api.records.kind(definition);
6681
+ return {
6682
+ get: (id) => handle.get({ id }),
6683
+ put: (input, opts) => handle.put({
6684
+ ...input,
6685
+ ...opts?.ifRev === void 0 ? {} : { ifRev: opts.ifRev }
6686
+ }),
6687
+ patch: (id, partial) => handle.patch({
6688
+ id,
6689
+ partial
6690
+ })
6691
+ };
6692
+ } };
6693
+ }
6694
+ function integrationRowsApiOver(api) {
6702
6695
  return {
6703
- get,
6704
- set,
6705
- update
6696
+ list: async () => (await api.integrations.list({})).integrations,
6697
+ readLegacyIntegrationRows: (input) => api.legacyRows.read(input),
6698
+ clearLegacyIntegrationRows: (input) => api.legacyRows.clear(input)
6706
6699
  };
6707
6700
  }
6708
- /**
6709
- * Per-node scoping for the shared addon-settings blob.
6710
- *
6711
- * An addon's settings store is hub-central (the `addon-settings` cap is
6712
- * hub-routed — the hub instance answers for every node), so fields whose
6713
- * value is a NODE fact (decoder backend, engine pick, probed hardware
6714
- * capabilities) persist under the node-scoped key `<key>@<nodeId>` inside
6715
- * the single shared blob. The SCHEMA field key stays bare: the write path
6716
- * ({@link scopePatch}) maps the bare field onto the target node's scoped
6717
- * key; the read/hydrate path ({@link projectStore}) maps THIS node's value
6718
- * back, so UI forms and `resolveConfig` only ever see the bare key.
6719
- *
6720
- * Fields opt in via the `perNode: true` schema marker on `ConfigFieldBase`
6721
- * (`interfaces/config-ui.ts`); `BaseAddon` derives the key set from the
6722
- * schema and routes reads/writes through these helpers.
6723
- *
6724
- * ## No bare-key fallback — deliberate
6725
- *
6726
- * {@link readNodeValue} reads the node-scoped key ONLY. A node with no
6727
- * scoped key resolves to `undefined` so the field's schema `default` wins —
6728
- * NEVER `store[base]` and never another node's value. A bare legacy key in
6729
- * the store is invisible to every node, hub included, so one node's
6730
- * selection can never leak onto another. (This generalizes the
6731
- * `decoder-backend-keys.ts` semantics — the no-fallback variant — over an
6732
- * arbitrary set of per-node field keys.)
6733
- *
6734
- * Pure functions only — no I/O, no imports beyond the language. This is a
6735
- * LEAF module: import it via its deep path, never from the root barrel.
6736
- */
6737
- /**
6738
- * Normalize a raw kernel node id to the bare node id used for scoping.
6739
- * `localNodeId` can carry a `<node>/<addon>` suffix on forked child
6740
- * processes; per-node settings are per-NODE, so strip the addon segment.
6741
- * `undefined` / `null` / empty falls back to `'hub'`.
6742
- */
6743
- function normalizeNodeId(raw) {
6744
- if (raw === void 0 || raw === null || raw === "") return "hub";
6745
- const slashIdx = raw.indexOf("/");
6746
- if (slashIdx < 0) return raw;
6747
- const bare = raw.slice(0, slashIdx);
6748
- return bare === "" ? "hub" : bare;
6749
- }
6750
- /** The node-scoped store key for a per-node field: `<base>@<nodeId>`. */
6751
- function nodeScopedKey(base, nodeId) {
6752
- return `${base}@${normalizeNodeId(nodeId)}`;
6753
- }
6754
- /**
6755
- * Read a node's value for a per-node field from the raw shared store:
6756
- * the node-scoped key when present, otherwise `undefined`.
6757
- * Deliberately NO bare-key fallback (see module doc) — the caller lets the
6758
- * schema `default` win on `undefined`.
6759
- */
6760
- function readNodeValue(store, base, nodeId) {
6761
- return store[nodeScopedKey(base, nodeId)];
6762
- }
6763
- /**
6764
- * Re-map a UI/settings patch so every bare perNode field persists under the
6765
- * TARGET node's scoped key; all other keys pass through unchanged. Used on
6766
- * the write path so a save for one node never clobbers another node's value
6767
- * (and the bare key is never written). Returns a new object — the input
6768
- * patch is not mutated.
6769
- */
6770
- function scopePatch(patch, perNodeKeys, nodeId) {
6771
- const out = {};
6772
- for (const [key, value] of Object.entries(patch)) out[perNodeKeys.has(key) ? nodeScopedKey(key, nodeId) : key] = value;
6773
- return out;
6774
- }
6775
- /**
6776
- * Project the raw shared store onto the bare schema keys for ONE node so a
6777
- * UI schema (whose field keys are bare) hydrates from that node's own
6778
- * values:
6779
- *
6780
- * - EVERY `@`-scoped key (any node's) is dropped from the pass-through.
6781
- * - Every bare perNode key is dropped from the pass-through (a stray bare
6782
- * legacy key must never hydrate any node — no bare fallback).
6783
- * - THIS node's effective value ({@link readNodeValue}) is then laid onto
6784
- * each bare perNode key; when the node has no scoped key the bare key is
6785
- * left ABSENT so the field's schema `default` wins.
6786
- *
6787
- * Returns a new object — the input store is not mutated.
6788
- */
6789
- function projectStore(store, perNodeKeys, nodeId) {
6790
- const out = {};
6791
- for (const [key, value] of Object.entries(store)) {
6792
- if (key.includes("@")) continue;
6793
- if (perNodeKeys.has(key)) continue;
6794
- out[key] = value;
6701
+ var PREFIX = "records/";
6702
+ /** The base of every records failure. `detail` is the human part of the message. */
6703
+ var RecordsError = class extends Error {
6704
+ code;
6705
+ detail;
6706
+ constructor(code, detail) {
6707
+ super(`${PREFIX}${code}: ${detail}`);
6708
+ this.name = "RecordsError";
6709
+ this.code = code;
6710
+ this.detail = detail;
6795
6711
  }
6796
- for (const base of perNodeKeys) {
6797
- const value = readNodeValue(store, base, nodeId);
6798
- if (value !== void 0) out[base] = value;
6712
+ };
6713
+ /** A write guarded by `ifRev` found another revision (or an existing row for `ifRev: 0`). */
6714
+ var RevConflictError = class extends RecordsError {
6715
+ constructor(detail) {
6716
+ super("rev-conflict", detail);
6717
+ this.name = "RevConflictError";
6799
6718
  }
6800
- return out;
6719
+ };
6720
+ /** The keychain could not store or serve a value: explicit, never an empty string. */
6721
+ var RecordSecretUnavailableError = class extends RecordsError {
6722
+ constructor(detail) {
6723
+ super("secret-unavailable", detail);
6724
+ this.name = "RecordSecretUnavailableError";
6725
+ }
6726
+ };
6727
+ var InvalidRecordError = class extends RecordsError {
6728
+ constructor(detail) {
6729
+ super("invalid-record", detail);
6730
+ this.name = "InvalidRecordError";
6731
+ }
6732
+ };
6733
+ /** A kind declaration the engine refuses (non-additive change, bad shape, wrong file). */
6734
+ var DeclarationRefusedError = class extends RecordsError {
6735
+ constructor(detail) {
6736
+ super("declaration-refused", detail);
6737
+ this.name = "DeclarationRefusedError";
6738
+ }
6739
+ };
6740
+ function linkTargetOf(meta) {
6741
+ if (typeof meta !== "object" || meta === null) return void 0;
6742
+ const link = Reflect.get(meta, "link");
6743
+ const parsed = LinkTargetSchema.safeParse(link);
6744
+ return parsed.success ? parsed.data : void 0;
6745
+ }
6746
+ var LinkTargetSchema = object({
6747
+ cap: string().min(1),
6748
+ kind: string().min(1).optional()
6749
+ });
6750
+ /** The links a kind declares, read from the meta of its body fields. */
6751
+ function linksOfKind(kind) {
6752
+ const schema = kind.schema;
6753
+ if (!(schema instanceof ZodObject)) return [];
6754
+ const links = [];
6755
+ for (const [field, fieldSchema] of Object.entries(schema.shape)) {
6756
+ const to = linkTargetOf(globalRegistry.get(fieldSchema));
6757
+ if (to !== void 0) links.push({
6758
+ field,
6759
+ to
6760
+ });
6761
+ }
6762
+ return links;
6801
6763
  }
6802
6764
  /**
6803
6765
  * The address of one keychain value: `secret://<owner>/<scope>/<fieldPath>`.
@@ -6933,6 +6895,652 @@ function parseSecretRef(ref) {
6933
6895
  fieldPath
6934
6896
  };
6935
6897
  }
6898
+ /** Limits and names of `ctx.records` (D881). One authority; the engine and the facade read it. */
6899
+ /** The files a kind may live in. `history` is device-history's (D850), never records. */
6900
+ var RECORD_DATABASES = ["settings", "events"];
6901
+ /** The classes of a kind: the `@durable` vocabulary, one authority (replaces the annotation). */
6902
+ var RECORD_CLASSES = [
6903
+ "config",
6904
+ "ledger",
6905
+ "audit",
6906
+ "mirror",
6907
+ "ephemeral"
6908
+ ];
6909
+ var RECORD_DEFAULT_MAX_DATA_BYTES = 64 * 1024;
6910
+ var RECORD_MAX_DATA_BYTES = 1024 * 1024;
6911
+ var RECORD_BATCH_MAX = 1e3;
6912
+ var RECORD_QUERY_MAX = 1e3;
6913
+ /** A kind in the `settings` file may not bound itself above this (D447: high volume is `events`). */
6914
+ var RECORD_SETTINGS_MAX_ROWS = 5e4;
6915
+ /** The `Column`-free proof prefix: a ref collection for a kind's secret fields. */
6916
+ var RECORD_SECRET_COLLECTION_PREFIX = "records:";
6917
+ /**
6918
+ * Secret fields of a record, addressed the way a Zod schema declares them
6919
+ * (`collectZodSecretPaths`): dotted keys, `[]` for "each element of this array"
6920
+ * (`auth.accessToken`, `headers[].value`).
6921
+ *
6922
+ * `{}` after a key means "each value of this map" (`applianceSecrets{}`): the map's own key
6923
+ * names the value (`applianceSecrets{fridge}`), so no id key is declared and a body that drops a
6924
+ * key releases exactly that key's secret.
6925
+ *
6926
+ * Array elements are matched by a DECLARED id key (`secretArrayKeys`:
6927
+ * `{ headers: 'name' }`), never by index, so reordering a list keeps every
6928
+ * keychain ref (the same rule as `arrayItemFieldPath`). The concrete path of a
6929
+ * leaf names its element: `headers[X-Api].value`.
6930
+ *
6931
+ * Pure and browser-safe. Nothing here mutates: every transform returns a new value.
6932
+ */
6933
+ /** The array prefixes (declared form, e.g. `headers` or `a.headers`) of a path. */
6934
+ function parseSecretPath(path) {
6935
+ if (path.length === 0) throw new InvalidRecordError("an empty secret path");
6936
+ return path.split(".").map((raw) => {
6937
+ const each = raw.endsWith("[]");
6938
+ const map = raw.endsWith("{}");
6939
+ const key = each || map ? raw.slice(0, -2) : raw;
6940
+ if (key.length === 0) throw new InvalidRecordError(`secret path "${path}" has an empty segment`);
6941
+ return {
6942
+ key,
6943
+ each,
6944
+ map
6945
+ };
6946
+ });
6947
+ }
6948
+ /** The declared array prefixes of `path` that need an id key (`headers`, `a.rows`). */
6949
+ function secretArrayPrefixes(path) {
6950
+ const segments = parseSecretPath(path);
6951
+ const prefixes = [];
6952
+ const walked = [];
6953
+ for (const segment of segments) {
6954
+ walked.push(segment.key);
6955
+ if (segment.each) prefixes.push(walked.join("."));
6956
+ }
6957
+ return prefixes;
6958
+ }
6959
+ function isRecord$6(value) {
6960
+ return typeof value === "object" && value !== null && !Array.isArray(value);
6961
+ }
6962
+ function elementId(element, idKey, declared, prefix) {
6963
+ const id = isRecord$6(element) ? element[idKey] : void 0;
6964
+ 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`);
6965
+ return id;
6966
+ }
6967
+ /**
6968
+ * Visit every secret leaf PRESENT in `data` (an absent branch has nothing to
6969
+ * visit). `replace` returns the new leaf value, or {@link REMOVE_LEAF}; the
6970
+ * result is a new body, `data` is untouched.
6971
+ */
6972
+ var REMOVE_LEAF = Symbol("remove-leaf");
6973
+ function mapAt(node, segments, index, walkedKeys, concretePrefix, declared, arrayKeys, visit) {
6974
+ if (!isRecord$6(node)) return node;
6975
+ const segment = segments[index];
6976
+ if (segment === void 0) return node;
6977
+ if (!Object.prototype.hasOwnProperty.call(node, segment.key)) return node;
6978
+ const child = node[segment.key];
6979
+ const keys = [...walkedKeys, segment.key];
6980
+ const last = index === segments.length - 1;
6981
+ if (segment.each) {
6982
+ if (!Array.isArray(child)) return node;
6983
+ const prefix = keys.join(".");
6984
+ const idKey = arrayKeys[prefix];
6985
+ if (idKey === void 0) throw new InvalidRecordError(`"${declared}": no id key declared for the array "${prefix}"`);
6986
+ const mapped = child.map((element) => {
6987
+ const id = elementId(element, idKey, declared, prefix);
6988
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}[${encodeURIComponent(id)}]`;
6989
+ return last ? element : mapAt(element, segments, index + 1, keys, concrete, declared, arrayKeys, visit);
6990
+ });
6991
+ return {
6992
+ ...node,
6993
+ [segment.key]: mapped
6994
+ };
6995
+ }
6996
+ if (segment.map) {
6997
+ if (!isRecord$6(child)) return node;
6998
+ const kept = Object.entries(child).map(([mapKey, value]) => {
6999
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}{${encodeURIComponent(mapKey)}}`;
7000
+ if (!last) return [mapKey, mapAt(value, segments, index + 1, keys, concrete, declared, arrayKeys, visit)];
7001
+ return [mapKey, visit({
7002
+ declared,
7003
+ concrete,
7004
+ value
7005
+ })];
7006
+ }).filter(([, value]) => value !== REMOVE_LEAF);
7007
+ return {
7008
+ ...node,
7009
+ [segment.key]: Object.fromEntries(kept)
7010
+ };
7011
+ }
7012
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}`;
7013
+ if (last) {
7014
+ const replacement = visit({
7015
+ declared,
7016
+ concrete,
7017
+ value: child
7018
+ });
7019
+ if (replacement === REMOVE_LEAF) return Object.fromEntries(Object.entries(node).filter(([key]) => key !== segment.key));
7020
+ return {
7021
+ ...node,
7022
+ [segment.key]: replacement
7023
+ };
7024
+ }
7025
+ return {
7026
+ ...node,
7027
+ [segment.key]: mapAt(child, segments, index + 1, keys, concrete, declared, arrayKeys, visit)
7028
+ };
7029
+ }
7030
+ /** Replace/remove every present secret leaf; returns a NEW body. */
7031
+ function mapSecretLeaves(data, paths, arrayKeys, visit) {
7032
+ let current = data;
7033
+ for (const declared of paths) current = mapAt(current, parseSecretPath(declared), 0, [], "", declared, arrayKeys, visit);
7034
+ return current;
7035
+ }
7036
+ /** Every present secret leaf, read-only. */
7037
+ function collectSecretLeaves(data, paths, arrayKeys) {
7038
+ const found = [];
7039
+ mapSecretLeaves(data, paths, arrayKeys, (leaf) => {
7040
+ found.push(leaf);
7041
+ return leaf.value;
7042
+ });
7043
+ return found;
7044
+ }
7045
+ /**
7046
+ * The keychain collection name a kind's secrets live under. Prefixed so a
7047
+ * record's refs never collide with the refs a legacy collection of the same name
7048
+ * already holds during an adoption.
7049
+ */
7050
+ function recordSecretCollection(kind) {
7051
+ return `${RECORD_SECRET_COLLECTION_PREFIX}${kind}`;
7052
+ }
7053
+ /** The ONE ref a row's secret field may carry: the engine and the facade both build it here. */
7054
+ function recordSecretRef(owner, kind, rowId, concretePath) {
7055
+ return buildSecretRef({
7056
+ owner,
7057
+ scope: {
7058
+ kind: "row",
7059
+ collection: recordSecretCollection(kind),
7060
+ rowId
7061
+ },
7062
+ fieldPath: concretePath
7063
+ });
7064
+ }
7065
+ /**
7066
+ * A stored secret, as an admin read shows it: a VIEW naming the row's own
7067
+ * keychain ref (`set: true`), never the value and no longer the bare redaction
7068
+ * token. The form hands it to the secret field, which reveals the value by ref
7069
+ * through the audited `keychain-admin.reveal`; sent back untouched it keeps the
7070
+ * stored secret (the records door reads a view as KEEP).
7071
+ *
7072
+ * ONE implementation for the entries service and for every addon that serves
7073
+ * its own instances (`RecordIntegrationInstances`).
7074
+ */
7075
+ function isRecord$5(value) {
7076
+ return typeof value === "object" && value !== null && !Array.isArray(value);
7077
+ }
7078
+ function secretViewsOf(owner, kind, id, decl, data) {
7079
+ if (decl.secretPaths.length === 0) return data;
7080
+ const shown = mapSecretLeaves(data, decl.secretPaths, decl.secretArrayKeys, (leaf) => {
7081
+ if (leaf.value !== "__camstack_redacted__") return leaf.value;
7082
+ return {
7083
+ $secret: recordSecretRef(owner, kind, id, leaf.concrete),
7084
+ v: 1,
7085
+ set: true
7086
+ };
7087
+ });
7088
+ return isRecord$5(shown) ? shown : data;
7089
+ }
7090
+ /** The most instances one addon lists (an integrations page, not a table). */
7091
+ var INSTANCES_LIST_MAX = 1e3;
7092
+ /**
7093
+ * The ONE reader of an instance's switch (D996): an absent field means on, so a row written
7094
+ * before the field existed needs no migration. Every consumer of an instance body asks this.
7095
+ */
7096
+ function isInstanceEnabled(body) {
7097
+ return body.enabled !== false;
7098
+ }
7099
+ /** The body key of the switch; only {@link RecordIntegrationInstances.setInstanceEnabled} writes it. */
7100
+ var SWITCH_KEY = "enabled";
7101
+ /** The keys of the kind's secret fields that sit at the top level of the body. */
7102
+ function topLevelSecretKeys(paths) {
7103
+ return new Set(paths.filter((p) => !p.includes(".") && !p.includes("[") && !p.includes("{")));
7104
+ }
7105
+ /** The keys of the kind's top-level MAPS whose values are secrets (`applianceSecrets{}`). */
7106
+ function secretMapKeys(paths) {
7107
+ return new Set(paths.filter((p) => p.endsWith("{}") && !p.slice(0, -2).match(/[.[{]/)).map((p) => p.slice(0, -2)));
7108
+ }
7109
+ /**
7110
+ * A patch value for a map of secrets: an entry that is omitted, `''`, the redaction token or the
7111
+ * view the form was given KEEPS its stored secret (it is left out of the merge); `{ $secretClear }`
7112
+ * or `null` removes the entry; any other string replaces it. Null when nothing is left to merge.
7113
+ */
7114
+ function secretMapPatch(value) {
7115
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
7116
+ const out = {};
7117
+ for (const [key, entry] of Object.entries(value)) if (entry === null || isSecretClear(entry)) out[key] = null;
7118
+ else if (typeof entry === "string" && entry !== "" && entry !== "__camstack_redacted__" && !isSecretFieldView(entry)) out[key] = entry;
7119
+ return Object.keys(out).length > 0 ? out : null;
7120
+ }
7121
+ var RecordIntegrationInstances = class {
7122
+ records;
7123
+ kind;
7124
+ hooks;
7125
+ handle;
7126
+ secretKeys;
7127
+ secretMaps;
7128
+ nameField;
7129
+ switchListeners = /* @__PURE__ */ new Set();
7130
+ constructor(records, kind, hooks) {
7131
+ this.records = records;
7132
+ this.kind = kind;
7133
+ this.hooks = hooks;
7134
+ this.handle = records.kind(kind);
7135
+ this.secretKeys = topLevelSecretKeys(kind.declaration.secretPaths);
7136
+ this.secretMaps = secretMapKeys(kind.declaration.secretPaths);
7137
+ this.nameField = kind.declaration.entry?.nameField ?? "name";
7138
+ }
7139
+ /**
7140
+ * One instance read for the addon's own runtime; null when absent. When the keychain is
7141
+ * locked the row is served WITHOUT its secrets and says so (`secrets: 'unavailable'`), so the
7142
+ * caller can keep what it had instead of reconfiguring with an empty secret (D49).
7143
+ */
7144
+ async readResolved(id) {
7145
+ try {
7146
+ const record = await this.handle.getResolved(id);
7147
+ return record === null ? null : {
7148
+ id,
7149
+ body: record.data,
7150
+ enabled: isInstanceEnabled(record.data),
7151
+ secrets: "resolved"
7152
+ };
7153
+ } catch (err) {
7154
+ if (!(err instanceof RecordSecretUnavailableError)) throw err;
7155
+ const stored = await this.handle.get(id);
7156
+ if (stored === null) return null;
7157
+ return {
7158
+ id,
7159
+ body: Object.fromEntries(Object.entries(stored.data).filter(([key]) => !this.secretKeys.has(key))),
7160
+ enabled: isInstanceEnabled(stored.data),
7161
+ secrets: "unavailable"
7162
+ };
7163
+ }
7164
+ }
7165
+ /** The body of {@link readResolved} alone; a locked keychain yields the row without secrets. */
7166
+ async getResolved(id) {
7167
+ return (await this.readResolved(id))?.body ?? null;
7168
+ }
7169
+ /** Every instance, secrets resolved where the keychain allows; an absent one is skipped. */
7170
+ async listResolved() {
7171
+ const page = await this.handle.query({ limit: INSTANCES_LIST_MAX });
7172
+ const out = [];
7173
+ for (const record of page.records) {
7174
+ const read = await this.readResolved(record.id);
7175
+ if (read !== null) out.push(read);
7176
+ }
7177
+ return out;
7178
+ }
7179
+ viewOf(record) {
7180
+ const shown = secretViewsOf(this.records.owner, this.kind.name, record.id, this.kind.declaration, record.data);
7181
+ const rawName = record.data[this.nameField];
7182
+ const kind = this.hooks.kindOf?.(record.data);
7183
+ const health = this.hooks.health?.(record.data, record.id);
7184
+ return {
7185
+ id: record.id,
7186
+ name: typeof rawName === "string" ? rawName : record.id,
7187
+ configured: this.hooks.configured(record.data),
7188
+ enabled: isInstanceEnabled(record.data),
7189
+ formValues: shown,
7190
+ ...kind !== void 0 ? { kind } : {},
7191
+ ...health?.status !== void 0 ? { status: health.status } : {},
7192
+ ...health?.lastCheckedAt !== void 0 ? { lastCheckedAt: health.lastCheckedAt } : {}
7193
+ };
7194
+ }
7195
+ describe = async () => {
7196
+ const declared = linksOfKind(this.kind);
7197
+ const links = this.hooks.description.links !== void 0 || declared.length === 0 ? {} : { links: declared.map((link) => ({
7198
+ kind: this.kind.name,
7199
+ field: link.field,
7200
+ to: link.to
7201
+ })) };
7202
+ return {
7203
+ ...this.hooks.description,
7204
+ ...links,
7205
+ ...this.hooks.mintId === void 0 ? {} : { mintsId: true }
7206
+ };
7207
+ };
7208
+ instanceFormSchema = async ({ id }) => this.hooks.formSchema(id);
7209
+ listInstances = async () => {
7210
+ return (await this.handle.query({ limit: INSTANCES_LIST_MAX })).records.map((record) => this.viewOf(record));
7211
+ };
7212
+ getInstance = async ({ id }) => {
7213
+ const record = await this.handle.get(id);
7214
+ return record === null ? null : this.viewOf(record);
7215
+ };
7216
+ /** Insert ONE row (`ifRev: 0`: an existing id is refused, never overwritten). */
7217
+ createInstance = async ({ id, name, kind, values }) => {
7218
+ const minted = id ?? this.hooks.mintId?.({
7219
+ name,
7220
+ ...kind !== void 0 ? { kind } : {}
7221
+ });
7222
+ if (minted === void 0) throw new Error("createInstance needs an id: this provider does not mint one");
7223
+ await this.handle.put({
7224
+ id: minted,
7225
+ data: this.hooks.initialBody(name, kind)
7226
+ }, { ifRev: 0 });
7227
+ const patch = this.patchOf(values ?? {});
7228
+ if (Object.keys(patch).length > 0) await this.handle.patch(minted, patch);
7229
+ await this.hooks.onChanged?.(minted, "created");
7230
+ return { id: minted };
7231
+ };
7232
+ updateInstance = async ({ id, name, values }) => {
7233
+ const patch = this.patchOf(values);
7234
+ if (name !== void 0) patch[this.nameField] = name;
7235
+ await this.handle.patch(id, patch);
7236
+ await this.hooks.onChanged?.(id, "updated");
7237
+ return { ok: true };
7238
+ };
7239
+ /** The record patch a form `values` object means: secrets kept, cleared or replaced. */
7240
+ patchOf(values) {
7241
+ const patch = {};
7242
+ for (const [key, value] of Object.entries(values)) {
7243
+ if (value === void 0) continue;
7244
+ if (key === "enabled") continue;
7245
+ if (this.secretMaps.has(key)) {
7246
+ const entries = secretMapPatch(value);
7247
+ if (entries !== null) patch[key] = entries;
7248
+ } else if (!this.secretKeys.has(key)) patch[key] = value;
7249
+ else if (isSecretClear(value)) patch[key] = null;
7250
+ else if (typeof value === "string" && value !== "" && value !== "__camstack_redacted__" && !isSecretFieldView(value)) patch[key] = value;
7251
+ }
7252
+ return patch;
7253
+ }
7254
+ /**
7255
+ * Listen to the switch of ANY instance of this helper (in the process that serves it). The
7256
+ * durable replacement of the `integration.enabled` / `integration.disabled` events (D8): the
7257
+ * addon reconciles from the record, whichever way it flipped.
7258
+ */
7259
+ onSwitched(listener) {
7260
+ this.switchListeners.add(listener);
7261
+ }
7262
+ /**
7263
+ * The ONE writer of the switch (D996, D1014): the record body's `enabled`, for every role. A
7264
+ * configured thing is an instance, so an id with no record yet (a default integration that was
7265
+ * never configured) gets its record from `initialBody` before the switch is written.
7266
+ */
7267
+ setInstanceEnabled = async ({ id, enabled }) => {
7268
+ if (await this.handle.get(id) === null) await this.handle.put({
7269
+ id,
7270
+ data: this.hooks.initialBody(id)
7271
+ }, { ifRev: 0 });
7272
+ await this.handle.patch(id, { [SWITCH_KEY]: enabled });
7273
+ await this.hooks.onChanged?.(id, "enabled");
7274
+ for (const listener of this.switchListeners) await listener(id, enabled);
7275
+ return { ok: true };
7276
+ };
7277
+ /** The row and its keychain refs go together (the records door). */
7278
+ deleteInstance = async ({ id }) => {
7279
+ await this.handle.delete(id);
7280
+ await this.hooks.onChanged?.(id, "deleted");
7281
+ return { ok: true };
7282
+ };
7283
+ testInstance = async (input) => {
7284
+ if (this.hooks.test === void 0) return {
7285
+ success: false,
7286
+ status: "unsupported",
7287
+ error: "This integration declares no connection test"
7288
+ };
7289
+ return this.hooks.test(input);
7290
+ };
7291
+ /** The flat provider object to hand to `registerProvider`. */
7292
+ toProvider() {
7293
+ return {
7294
+ describe: this.describe,
7295
+ instanceFormSchema: this.instanceFormSchema,
7296
+ listInstances: this.listInstances,
7297
+ getInstance: this.getInstance,
7298
+ createInstance: this.createInstance,
7299
+ updateInstance: this.updateInstance,
7300
+ setInstanceEnabled: this.setInstanceEnabled,
7301
+ deleteInstance: this.deleteInstance,
7302
+ testInstance: this.testInstance
7303
+ };
7304
+ }
7305
+ };
7306
+ /**
7307
+ * The one-switch migration (epic #440, step 3). An integration's on/off state used to live in the
7308
+ * registry's `enabled` column for a device addon; it now lives only in the instance record's
7309
+ * body (`enabled`, D1007 superseded). This moves a registry `enabled = false` into the body, once.
7310
+ *
7311
+ * For every registry row of the addon that is OFF:
7312
+ * - no record under its id: the record is created from `initialBody(name)` with `enabled: false`
7313
+ * (a default integration that never had settings, Reolink's among them);
7314
+ * - a record whose body states no `enabled`: `enabled: false` is written into it;
7315
+ * - a record that already states `enabled` (either way) is the newer truth and is left alone.
7316
+ * A row that is ON writes nothing: an absent field reads as on. A rerun finds every off row with
7317
+ * a stated switch and does nothing, so nothing switched off comes back on and nothing switched on
7318
+ * goes off. The registry column itself is neither read afterwards nor written; its drop is step 5.
7319
+ *
7320
+ * It runs in the addon process, BEFORE the addon registers its `integration-instances` provider,
7321
+ * which is also why `integrations.list` still answers the stored column at that point.
7322
+ */
7323
+ function registrySwitchToBodyId(addonId, date) {
7324
+ return `${addonId}/${date}-registry-switch-to-body`;
7325
+ }
7326
+ async function moveRegistrySwitchToBody(ports, spec) {
7327
+ const rows = await ports.listIntegrations(spec.addonId);
7328
+ let created = 0;
7329
+ let switched = 0;
7330
+ let kept = 0;
7331
+ for (const row of rows) {
7332
+ if (row.enabled) continue;
7333
+ const body = await ports.readBody(row.id);
7334
+ if (body === null) {
7335
+ if (await ports.createRecord(row.id, {
7336
+ ...spec.initialBody(row.name),
7337
+ ["enabled"]: false
7338
+ }) === "created") created += 1;
7339
+ else kept += 1;
7340
+ continue;
7341
+ }
7342
+ if ("enabled" in body) {
7343
+ kept += 1;
7344
+ continue;
7345
+ }
7346
+ await ports.switchOff(row.id);
7347
+ switched += 1;
7348
+ }
7349
+ const summary = {
7350
+ integrations: rows.length,
7351
+ off: rows.filter((r) => !r.enabled).length,
7352
+ created,
7353
+ switched,
7354
+ kept
7355
+ };
7356
+ return created === 0 && switched === 0 ? {
7357
+ outcome: "already-done",
7358
+ summary
7359
+ } : {
7360
+ outcome: "done",
7361
+ summary
7362
+ };
7363
+ }
7364
+ /** A migration entry: an addon states its kind and how a new body starts, nothing else. */
7365
+ function registrySwitchToBodyMigration(spec) {
7366
+ return {
7367
+ meta: {
7368
+ id: registrySwitchToBodyId(spec.addonId, spec.date),
7369
+ owner: spec.addonId,
7370
+ level: "addon-state",
7371
+ seq: spec.seq,
7372
+ dependsOn: [],
7373
+ store: "settings",
7374
+ scope: "cluster",
7375
+ onFailure: "block-owner",
7376
+ bodyKind: "procedure",
7377
+ description: "Move the registry enabled flag of every switched-off integration into its instance record body, creating the record when there is none",
7378
+ fixtureMark: "enabled"
7379
+ },
7380
+ procedure: (ports) => moveRegistrySwitchToBody(ports, {
7381
+ addonId: spec.addonId,
7382
+ initialBody: spec.initialBody
7383
+ })
7384
+ };
7385
+ }
7386
+ /** The hub and records sides of {@link registrySwitchToBodyMigration}. */
7387
+ function registrySwitchPortsOver(deps) {
7388
+ const handle = deps.records.kind({
7389
+ name: deps.kind.name,
7390
+ declaration: deps.kind.declaration,
7391
+ schema: record(string(), unknown())
7392
+ });
7393
+ return {
7394
+ listIntegrations: async (addonId) => (await deps.api.list()).filter((i) => i.addonId === addonId).map((i) => ({
7395
+ id: i.id,
7396
+ name: i.name,
7397
+ enabled: i.enabled !== false
7398
+ })),
7399
+ readBody: async (id) => (await handle.get(id))?.data ?? null,
7400
+ createRecord: async (id, body) => {
7401
+ if (await handle.get(id) !== null) return "exists";
7402
+ await handle.put({
7403
+ id,
7404
+ data: body
7405
+ }, { ifRev: 0 });
7406
+ return "created";
7407
+ },
7408
+ switchOff: async (id) => {
7409
+ await handle.patch(id, { [SWITCH_KEY]: false });
7410
+ }
7411
+ };
7412
+ }
7413
+ /**
7414
+ * Build a {@link DurableState} over a single store key. Transport-agnostic:
7415
+ * `read`/`write` are the addon-store or device-store accessors. The whole
7416
+ * validated value round-trips on every read/write — the schema is the
7417
+ * single source of truth for what is persisted, so no hand-listed field
7418
+ * set can drop a key on save.
7419
+ */
7420
+ function createDurableState(deps) {
7421
+ const get = async () => {
7422
+ const raw = (await deps.read())[deps.key];
7423
+ if (raw === void 0) return deps.fallback;
7424
+ const parsed = deps.schema.safeParse(raw);
7425
+ if (!parsed.success) {
7426
+ deps.onParseError?.(deps.key, parsed.error);
7427
+ return deps.fallback;
7428
+ }
7429
+ return parsed.data;
7430
+ };
7431
+ const set = async (next) => {
7432
+ const validated = deps.schema.parse(next);
7433
+ await deps.write({ [deps.key]: validated });
7434
+ };
7435
+ const update = async (fn) => {
7436
+ await set(fn(await get()));
7437
+ };
7438
+ return {
7439
+ get,
7440
+ set,
7441
+ update
7442
+ };
7443
+ }
7444
+ /**
7445
+ * Per-node scoping for the shared addon-settings blob.
7446
+ *
7447
+ * An addon's settings store is hub-central (the `addon-settings` cap is
7448
+ * hub-routed — the hub instance answers for every node), so fields whose
7449
+ * value is a NODE fact (decoder backend, engine pick, probed hardware
7450
+ * capabilities) persist under the node-scoped key `<key>@<nodeId>` inside
7451
+ * the single shared blob. The SCHEMA field key stays bare: the write path
7452
+ * ({@link scopePatch}) maps the bare field onto the target node's scoped
7453
+ * key; the read/hydrate path ({@link projectStore}) maps THIS node's value
7454
+ * back, so UI forms and `resolveConfig` only ever see the bare key.
7455
+ *
7456
+ * Fields opt in via the `perNode: true` schema marker on `ConfigFieldBase`
7457
+ * (`interfaces/config-ui.ts`); `BaseAddon` derives the key set from the
7458
+ * schema and routes reads/writes through these helpers.
7459
+ *
7460
+ * ## No bare-key fallback — deliberate
7461
+ *
7462
+ * {@link readNodeValue} reads the node-scoped key ONLY. A node with no
7463
+ * scoped key resolves to `undefined` so the field's schema `default` wins —
7464
+ * NEVER `store[base]` and never another node's value. A bare legacy key in
7465
+ * the store is invisible to every node, hub included, so one node's
7466
+ * selection can never leak onto another. (This generalizes the
7467
+ * `decoder-backend-keys.ts` semantics — the no-fallback variant — over an
7468
+ * arbitrary set of per-node field keys.)
7469
+ *
7470
+ * Pure functions only — no I/O, no imports beyond the language. This is a
7471
+ * LEAF module: import it via its deep path, never from the root barrel.
7472
+ */
7473
+ /**
7474
+ * Normalize a raw kernel node id to the bare node id used for scoping.
7475
+ * `localNodeId` can carry a `<node>/<addon>` suffix on forked child
7476
+ * processes; per-node settings are per-NODE, so strip the addon segment.
7477
+ * `undefined` / `null` / empty falls back to `'hub'`.
7478
+ */
7479
+ function normalizeNodeId(raw) {
7480
+ if (raw === void 0 || raw === null || raw === "") return "hub";
7481
+ const slashIdx = raw.indexOf("/");
7482
+ if (slashIdx < 0) return raw;
7483
+ const bare = raw.slice(0, slashIdx);
7484
+ return bare === "" ? "hub" : bare;
7485
+ }
7486
+ /** The node-scoped store key for a per-node field: `<base>@<nodeId>`. */
7487
+ function nodeScopedKey(base, nodeId) {
7488
+ return `${base}@${normalizeNodeId(nodeId)}`;
7489
+ }
7490
+ /**
7491
+ * Read a node's value for a per-node field from the raw shared store:
7492
+ * the node-scoped key when present, otherwise `undefined`.
7493
+ * Deliberately NO bare-key fallback (see module doc) — the caller lets the
7494
+ * schema `default` win on `undefined`.
7495
+ */
7496
+ function readNodeValue(store, base, nodeId) {
7497
+ return store[nodeScopedKey(base, nodeId)];
7498
+ }
7499
+ /**
7500
+ * Re-map a UI/settings patch so every bare perNode field persists under the
7501
+ * TARGET node's scoped key; all other keys pass through unchanged. Used on
7502
+ * the write path so a save for one node never clobbers another node's value
7503
+ * (and the bare key is never written). Returns a new object — the input
7504
+ * patch is not mutated.
7505
+ */
7506
+ function scopePatch(patch, perNodeKeys, nodeId) {
7507
+ const out = {};
7508
+ for (const [key, value] of Object.entries(patch)) out[perNodeKeys.has(key) ? nodeScopedKey(key, nodeId) : key] = value;
7509
+ return out;
7510
+ }
7511
+ /**
7512
+ * Project the raw shared store onto the bare schema keys for ONE node so a
7513
+ * UI schema (whose field keys are bare) hydrates from that node's own
7514
+ * values:
7515
+ *
7516
+ * - EVERY `@`-scoped key (any node's) is dropped from the pass-through.
7517
+ * - Every bare perNode key is dropped from the pass-through (a stray bare
7518
+ * legacy key must never hydrate any node — no bare fallback).
7519
+ * - THIS node's effective value ({@link readNodeValue}) is then laid onto
7520
+ * each bare perNode key; when the node has no scoped key the bare key is
7521
+ * left ABSENT so the field's schema `default` wins.
7522
+ *
7523
+ * Returns a new object — the input store is not mutated.
7524
+ */
7525
+ function projectStore(store, perNodeKeys, nodeId) {
7526
+ const out = {};
7527
+ for (const [key, value] of Object.entries(store)) {
7528
+ if (key.includes("@")) continue;
7529
+ if (perNodeKeys.has(key)) continue;
7530
+ out[key] = value;
7531
+ }
7532
+ for (const base of perNodeKeys) {
7533
+ const value = readNodeValue(store, base, nodeId);
7534
+ if (value !== void 0) out[base] = value;
7535
+ }
7536
+ return out;
7537
+ }
7538
+ /** Every scope, in the order the guard and the docs list them. */
7539
+ var SCOPED_SETTINGS_SCOPES = [
7540
+ "cluster",
7541
+ "device-defaults",
7542
+ "node"
7543
+ ];
6936
7544
  /** A write to a secret path could not be stored in the keychain, so it was refused. */
6937
7545
  var KeychainWriteRefusedError = class extends Error {
6938
7546
  fieldPath;
@@ -6943,7 +7551,7 @@ var KeychainWriteRefusedError = class extends Error {
6943
7551
  }
6944
7552
  };
6945
7553
  var KEEP = { kind: "keep" };
6946
- function isRecord$6(value) {
7554
+ function isRecord$4(value) {
6947
7555
  return typeof value === "object" && value !== null && !Array.isArray(value);
6948
7556
  }
6949
7557
  function defaultMintId() {
@@ -6956,7 +7564,7 @@ function collectSecretMarkerRefs(value, out = []) {
6956
7564
  return out;
6957
7565
  }
6958
7566
  if (Array.isArray(value)) for (const item of value) collectSecretMarkerRefs(item, out);
6959
- else if (isRecord$6(value)) for (const child of Object.values(value)) collectSecretMarkerRefs(child, out);
7567
+ else if (isRecord$4(value)) for (const child of Object.values(value)) collectSecretMarkerRefs(child, out);
6960
7568
  return out;
6961
7569
  }
6962
7570
  async function storedValueEquals(secrets, marker, candidate) {
@@ -7011,7 +7619,7 @@ function rowId(row, idKey) {
7011
7619
  return null;
7012
7620
  }
7013
7621
  async function writeArray(ctx, node, incoming, stored, fieldPath) {
7014
- const storedRows = Array.isArray(stored) ? stored.filter(isRecord$6) : [];
7622
+ const storedRows = Array.isArray(stored) ? stored.filter(isRecord$4) : [];
7015
7623
  if (!Array.isArray(incoming)) {
7016
7624
  ctx.deletes.push(...collectSecretMarkerRefs(storedRows));
7017
7625
  return {
@@ -7027,7 +7635,7 @@ async function writeArray(ctx, node, incoming, stored, fieldPath) {
7027
7635
  const kept = /* @__PURE__ */ new Set();
7028
7636
  const rows = [];
7029
7637
  for (const row of incoming) {
7030
- if (!isRecord$6(row)) {
7638
+ if (!isRecord$4(row)) {
7031
7639
  rows.push(row);
7032
7640
  continue;
7033
7641
  }
@@ -7052,7 +7660,7 @@ async function writeNode(ctx, node, incoming, stored, fieldPath) {
7052
7660
  case "leaf": return writeLeaf(ctx, incoming, stored, fieldPath);
7053
7661
  case "array": return writeArray(ctx, node, incoming, stored, fieldPath);
7054
7662
  case "object": {
7055
- if (!isRecord$6(incoming)) {
7663
+ if (!isRecord$4(incoming)) {
7056
7664
  if (incoming === void 0) return KEEP;
7057
7665
  ctx.deletes.push(...collectSecretMarkerRefs(stored));
7058
7666
  return {
@@ -7060,7 +7668,7 @@ async function writeNode(ctx, node, incoming, stored, fieldPath) {
7060
7668
  value: incoming
7061
7669
  };
7062
7670
  }
7063
- const storedObj = isRecord$6(stored) ? stored : {};
7671
+ const storedObj = isRecord$4(stored) ? stored : {};
7064
7672
  return {
7065
7673
  kind: "value",
7066
7674
  value: await writeMembers(ctx, node.children, incoming, storedObj, (m) => `${fieldPath}.${m}`)
@@ -7183,7 +7791,7 @@ async function resolveSecretMarkers(value, secrets, options = {}) {
7183
7791
  value: items
7184
7792
  };
7185
7793
  }
7186
- if (isRecord$6(v)) {
7794
+ if (isRecord$4(v)) {
7187
7795
  const out = {};
7188
7796
  for (const [k, child] of Object.entries(v)) {
7189
7797
  const s = substitute(child);
@@ -7215,7 +7823,7 @@ var SecretOverwriteRefusedError = class extends Error {
7215
7823
  this.name = "SecretOverwriteRefusedError";
7216
7824
  }
7217
7825
  };
7218
- function isRecord$5(value) {
7826
+ function isRecord$3(value) {
7219
7827
  return typeof value === "object" && value !== null && !Array.isArray(value);
7220
7828
  }
7221
7829
  function resolvedValue(pass, marker) {
@@ -7244,7 +7852,7 @@ function inArray(pass, incoming, stored) {
7244
7852
  return incoming.map((item, index) => {
7245
7853
  const twin = stored[index];
7246
7854
  if (isSecretMarker(twin)) return typeof item === "string" && item === resolvedValue(pass, twin) ? twin : item;
7247
- if (isRecord$5(item) && isRecord$5(twin)) return inArrayRow(pass, item, twin);
7855
+ if (isRecord$3(item) && isRecord$3(twin)) return inArrayRow(pass, item, twin);
7248
7856
  if (Array.isArray(item) && Array.isArray(twin)) return inArray(pass, item, twin);
7249
7857
  return item;
7250
7858
  });
@@ -7255,7 +7863,7 @@ function inArrayRow(pass, incoming, stored) {
7255
7863
  const twin = stored[key];
7256
7864
  if (isSecretMarker(twin)) {
7257
7865
  if (typeof value === "string" && value === resolvedValue(pass, twin)) out[key] = twin;
7258
- } else if (isRecord$5(value) && isRecord$5(twin)) out[key] = inArrayRow(pass, value, twin);
7866
+ } else if (isRecord$3(value) && isRecord$3(twin)) out[key] = inArrayRow(pass, value, twin);
7259
7867
  else if (Array.isArray(value) && Array.isArray(twin)) out[key] = inArray(pass, value, twin);
7260
7868
  }
7261
7869
  return out;
@@ -7263,7 +7871,7 @@ function inArrayRow(pass, incoming, stored) {
7263
7871
  async function walk(pass, incoming, stored) {
7264
7872
  if (isSecretMarker(stored)) return atMarker(pass, incoming, stored);
7265
7873
  if (Array.isArray(incoming) && Array.isArray(stored)) return inArray(pass, incoming, stored);
7266
- if (!isRecord$5(incoming) || !isRecord$5(stored)) return incoming;
7874
+ if (!isRecord$3(incoming) || !isRecord$3(stored)) return incoming;
7267
7875
  const out = { ...incoming };
7268
7876
  for (const [key, value] of Object.entries(incoming)) out[key] = await walk(pass, value, stored[key]);
7269
7877
  return out;
@@ -7294,7 +7902,7 @@ async function restoreUnchangedSecrets(input) {
7294
7902
  function isJsonEqual(a, b) {
7295
7903
  if (Object.is(a, b)) return true;
7296
7904
  if (Array.isArray(a)) return Array.isArray(b) && a.length === b.length && a.every((v, i) => isJsonEqual(v, b[i]));
7297
- if (isRecord$5(a) && isRecord$5(b)) {
7905
+ if (isRecord$3(a) && isRecord$3(b)) {
7298
7906
  const keys = Object.keys(a);
7299
7907
  if (keys.length !== Object.keys(b).length) return false;
7300
7908
  return keys.every((k) => Object.prototype.hasOwnProperty.call(b, k) && isJsonEqual(a[k], b[k]));
@@ -7318,7 +7926,7 @@ function markerKeysOf(blob, owner) {
7318
7926
  }
7319
7927
  function nodeFromStored(value, owner) {
7320
7928
  if (isSecretMarker(value)) return isSecretRefOwnedBy(value.$secret, owner) ? { kind: "leaf" } : null;
7321
- if (!isRecord$5(value)) return null;
7929
+ if (!isRecord$3(value)) return null;
7322
7930
  const children = /* @__PURE__ */ new Map();
7323
7931
  for (const [key, child] of Object.entries(value)) {
7324
7932
  const node = nodeFromStored(child, owner);
@@ -7613,6 +8221,28 @@ var SECRET_RETRY_MAX_MS = 5 * 6e4;
7613
8221
  /** Coalesces a burst of `keychain.changed` events into one re-resolve. */
7614
8222
  var SECRET_CHANGE_DEBOUNCE_MS = 250;
7615
8223
  /**
8224
+ * Pair a catalogue with the function that builds its ports FROM THE MIGRATION API. The one
8225
+ * place a catalogue is bound: a migration reaches nothing a ports binder cannot reach
8226
+ * through `api` (guard `check-migration-ports-surface`).
8227
+ */
8228
+ function migrationSet(catalogue, bindPorts) {
8229
+ return { bind: (api) => defineAddonMigrations(catalogue, bindPorts(api)) };
8230
+ }
8231
+ /** A mixed array is a mistake: the other kind would be dropped without a word. */
8232
+ function refuseMixed(form, kept, dropped) {
8233
+ if (dropped > 0) throw new Error(`runMigrations(${form}): ${dropped} of ${kept + dropped} entries are of the other kind and would be dropped; pass one kind per call`);
8234
+ }
8235
+ function catalogueOf(list) {
8236
+ const kept = list.filter((entry) => !("execute" in entry));
8237
+ refuseMixed("catalogue, (api) => ports", kept.length, list.length - kept.length);
8238
+ return kept;
8239
+ }
8240
+ function boundOf(list) {
8241
+ const kept = list.filter((entry) => "execute" in entry);
8242
+ refuseMixed("bound migrations", kept.length, list.length - kept.length);
8243
+ return kept;
8244
+ }
8245
+ /**
7616
8246
  * Base class for CamStack addons. Eliminates settings boilerplate:
7617
8247
  *
7618
8248
  * - Typed `config` property with automatic resolution from store + defaults
@@ -7690,6 +8320,13 @@ var BaseAddon = class {
7690
8320
  */
7691
8321
  secretStatePaths = [];
7692
8322
  _addonSecretTree = null;
8323
+ /**
8324
+ * D986 M4: the scoped schemas this addon declared, resolved once per capability
8325
+ * (`loadScopedSchemas`) so the sync readers (`perNodeKeys`, the secret tree, the restart check)
8326
+ * see them. Empty until loaded: the readers then fall back to {@link globalSettingsSchema}.
8327
+ */
8328
+ _scopedByCap = /* @__PURE__ */ new Map();
8329
+ _nodeKeysByCap = /* @__PURE__ */ new Map();
7693
8330
  _deviceSecretTree = null;
7694
8331
  /** Refs the last resolved config pointed at — a change to one re-resolves. */
7695
8332
  _configSecretRefs = /* @__PURE__ */ new Set();
@@ -7759,6 +8396,7 @@ var BaseAddon = class {
7759
8396
  this._ctx = context;
7760
8397
  this._secretSettings = null;
7761
8398
  }
8399
+ await this.loadScopedSchemas();
7762
8400
  await this.resolveConfig();
7763
8401
  if (secrets !== void 0) this._secretChangeUnsub = secrets.onChange((ref) => {
7764
8402
  if (this._configSecretRefs.has(ref)) this.scheduleSecretReresolve(SECRET_CHANGE_DEBOUNCE_MS);
@@ -7768,31 +8406,65 @@ var BaseAddon = class {
7768
8406
  const normalized = normalizeAddonInitResult(result);
7769
8407
  const providers = normalized && "providers" in normalized && normalized.providers ? normalized.providers : [];
7770
8408
  this._registeredCapNames = providers.map((p) => p.capability.name);
8409
+ await this.loadScopedSchemas();
7771
8410
  return normalized;
7772
8411
  }
8412
+ async runMigrations(first, second, third) {
8413
+ if (typeof second === "function") return this.runMigrationSets([migrationSet(catalogueOf(first), second)], third);
8414
+ return this.runBound(boundOf(first), second);
8415
+ }
7773
8416
  /**
7774
- * Run this addon's migration catalogue (D987 M3) through the hub's `migrations`
7775
- * engine. Call it at the point of the boot where the data must already have the new
7776
- * shape — `onInitialize`, or `onRestoreDevices` for a migration that needs the
7777
- * restored devices — with the catalogue bound to the addon's ports
7778
- * (`defineAddonMigrations(ADDON_MIGRATIONS, ports)`).
7779
- *
7780
- * An engine that cannot be reached or refuses the catalogue is logged and runs
7781
- * nothing; the boot continues. A migration that FAILED (or was blocked by one)
7782
- * and declares `onFailure: 'block-owner'` makes this throw, so the addon does not
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").
8417
+ * Several catalogues of ONE owner in one declaration (the engine replaces an owner's
8418
+ * catalogue on every declare, so two calls would each judge the other's ids "newer").
8419
+ * Build each entry with `migrationSet(catalogue, (api) => ports)`.
7788
8420
  */
7789
- async runMigrations(migrations, options) {
8421
+ async runMigrationSets(sets, options) {
8422
+ const api = this.ctx.migrationApi;
8423
+ if (api === void 0) throw new Error(`${this.ctx.id}: the migration API is not available on this context`);
8424
+ return this.runBound(sets.flatMap((set) => set.bind(api)), options);
8425
+ }
8426
+ /**
8427
+ * A device addon states its instance kind once, before its migrations run, and the one-switch
8428
+ * migration (registry `enabled` to the instance body, epic #440 step 3) joins whatever
8429
+ * catalogue the addon runs, in the SAME declaration (the engine replaces an owner's catalogue
8430
+ * on every declare).
8431
+ */
8432
+ declareRegistrySwitch(spec) {
8433
+ this.registrySwitchSpec = spec;
8434
+ }
8435
+ registrySwitchSpec = null;
8436
+ registrySwitchBound() {
8437
+ const spec = this.registrySwitchSpec;
8438
+ if (spec === null) return [];
8439
+ const api = this.ctx.migrationApi;
8440
+ if (api === void 0) {
8441
+ this.ctx.logger.warn("the registry switch migration is skipped: the migration API is not available on this context");
8442
+ return [];
8443
+ }
8444
+ return migrationSet([registrySwitchToBodyMigration({
8445
+ addonId: this.ctx.id,
8446
+ date: "2026-11-06",
8447
+ seq: 1e3,
8448
+ initialBody: spec.initialBody
8449
+ })], (a) => registrySwitchPortsOver({
8450
+ api: integrationRowsApiOver(a),
8451
+ records: switchRecordsOverMigrationApi(a),
8452
+ kind: spec.kind
8453
+ })).bind(api);
8454
+ }
8455
+ async runBound(declared, options) {
8456
+ const added = this.registrySwitchBound();
8457
+ const migrations = [...declared, ...added];
8458
+ const phased = options?.only === void 0 || added.length === 0 ? options : {
8459
+ ...options,
8460
+ only: [...options.only, ...added.map((m) => m.meta.id)]
8461
+ };
7790
8462
  const api = this.ctx.api.migrations;
7791
8463
  const report = await runAddonMigrations({
7792
8464
  declareOwner: (input) => api.declareOwner.mutate(input),
7793
8465
  startMigration: (input) => api.startMigration.mutate(input),
7794
8466
  finishMigration: (input) => api.finishMigration.mutate(input)
7795
- }, migrations, this.ctx.logger, options);
8467
+ }, migrations, this.ctx.logger, phased);
7796
8468
  if (report.blockOwner.length > 0) throw new AddonMigrationsBlockedError(report.blockOwner);
7797
8469
  return report;
7798
8470
  }
@@ -7856,6 +8528,16 @@ var BaseAddon = class {
7856
8528
  schema(schema) {
7857
8529
  return schema;
7858
8530
  }
8531
+ /**
8532
+ * The capability names whose scoped settings schemas ({@link clusterSettingsSchema},
8533
+ * {@link nodeSettingsSchema}, {@link deviceDefaultsSchema}) this addon declares. Read BEFORE
8534
+ * `onInitialize`, when the providers it registers are not known yet: the first config resolve
8535
+ * must already know which keys are per node. Names the providers register at init are added
8536
+ * once known.
8537
+ */
8538
+ scopedSettingsCapabilities() {
8539
+ return [];
8540
+ }
7859
8541
  /** Override to provide global-level settings UI schema. */
7860
8542
  globalSettingsSchema(_cap) {
7861
8543
  return null;
@@ -7899,7 +8581,8 @@ var BaseAddon = class {
7899
8581
  return [];
7900
8582
  }
7901
8583
  async getGlobalSettings(overlay, cap, nodeId) {
7902
- const schema = this.globalSettingsSchema(cap);
8584
+ await this.loadScopedSchemas(cap);
8585
+ const schema = this.globalSettingsSchema(cap) ?? this.scopedFormSchema(cap);
7903
8586
  if (!schema) return { sections: [] };
7904
8587
  const projected = await this.readRawProjectedStore(nodeId, cap);
7905
8588
  return hydrateSchema(schema, overlay ? await this.overlayKeepingMarkers(projected, overlay) : projected, { inlineSecretsAsViews: true });
@@ -7934,10 +8617,9 @@ var BaseAddon = class {
7934
8617
  *
7935
8618
  * Override it only when an `instanceMode: multiple` addon's instances differ: an NVR integration
7936
8619
  * needs its connection fields, the default integration the addon's own sections. It is the
7937
- * SHAPE of the form only — the values live in `integrations.getSettings`, and the write path is
7938
- * unchanged (`integrations.setSettings` for an account integration).
8620
+ * SHAPE of the form only — the values live on the instance record.
7939
8621
  */
7940
- async integrationSettingsSchema(_instance) {
8622
+ async integrationFormSchema(_instance) {
7941
8623
  return null;
7942
8624
  }
7943
8625
  /**
@@ -7983,7 +8665,7 @@ var BaseAddon = class {
7983
8665
  * per-instance schema when it declares one, else its global schema (what they always showed).
7984
8666
  */
7985
8667
  async getIntegrationFormSchema(instance, nodeId) {
7986
- const scoped = await this.integrationSettingsSchema(instance);
8668
+ const scoped = await this.integrationFormSchema(instance);
7987
8669
  if (scoped === null) return this.getGlobalSettings(void 0, void 0, nodeId);
7988
8670
  return hydrateSchema(scoped, {}, { inlineSecretsAsViews: true });
7989
8671
  }
@@ -8031,6 +8713,7 @@ var BaseAddon = class {
8031
8713
  * resolved blob back is a no-op for every unchanged secret.
8032
8714
  */
8033
8715
  async resolveGlobalStore(nodeId, cap) {
8716
+ await this.loadScopedSchemas(cap);
8034
8717
  const raw = await this._ctx?.settings?.readAddonStore() ?? {};
8035
8718
  return this.projectForNode(raw, nodeId, cap);
8036
8719
  }
@@ -8041,6 +8724,7 @@ var BaseAddon = class {
8041
8724
  }
8042
8725
  /** The PROJECTED store with its markers — the form hydrate only (D798). */
8043
8726
  async readRawProjectedStore(nodeId, cap) {
8727
+ await this.loadScopedSchemas(cap);
8044
8728
  const raw = await this.rawSettings()?.readAddonStore() ?? {};
8045
8729
  return this.projectForNode(raw, nodeId, cap);
8046
8730
  }
@@ -8143,6 +8827,7 @@ var BaseAddon = class {
8143
8827
  await this.applyGlobalPatch(patch, nodeId);
8144
8828
  }
8145
8829
  async applyGlobalPatch(barePatch, nodeId) {
8830
+ await this.loadScopedSchemas();
8146
8831
  const keys = this.perNodeKeys();
8147
8832
  const localNode = normalizeNodeId(this._ctx?.kernel?.localNodeId);
8148
8833
  const target = normalizeNodeId(nodeId ?? this._ctx?.kernel?.localNodeId);
@@ -8156,7 +8841,8 @@ var BaseAddon = class {
8156
8841
  await this.resolveConfig();
8157
8842
  await this.onConfigChanged();
8158
8843
  this.emitLifecycle(EventCategory.AddonUpdated, { level: "global" });
8159
- this.maybeAutoRestart(Object.keys(barePatch), this.globalSettingsSchema());
8844
+ const legacy = this.globalSettingsSchema();
8845
+ this.maybeAutoRestart(Object.keys(barePatch), [...legacy === null ? [] : [legacy], ...this.loadedScopedSchemas().map((entry) => entry.schema)]);
8160
8846
  }
8161
8847
  /**
8162
8848
  * The set of field keys the global settings schema declares `perNode: true`
@@ -8164,14 +8850,67 @@ var BaseAddon = class {
8164
8850
  * declarations). Empty set ⇒ every per-node code path is bypassed and the
8165
8851
  * settings API behaves exactly like the legacy node-agnostic one.
8166
8852
  */
8167
- _perNodeKeysCache = /* @__PURE__ */ new Map();
8853
+ /**
8854
+ * Load the scoped schemas of every capability this addon declares (the override and the
8855
+ * providers registered at init, plus `extraCap`) that is not loaded yet, then drop what was
8856
+ * derived from the previous set. Idempotent.
8857
+ */
8858
+ async loadScopedSchemas(extraCap) {
8859
+ const caps = new Set([
8860
+ ...this.scopedSettingsCapabilities(),
8861
+ ...this._registeredCapNames,
8862
+ ...extraCap === void 0 ? [] : [extraCap]
8863
+ ]);
8864
+ let added = false;
8865
+ for (const cap of caps) {
8866
+ if (this._scopedByCap.has(cap)) continue;
8867
+ const loaded = [];
8868
+ for (const scope of SCOPED_SETTINGS_SCOPES) {
8869
+ const schema = await this.getScopedSettingsSchema(scope, cap);
8870
+ if (schema !== null) loaded.push({
8871
+ scope,
8872
+ schema
8873
+ });
8874
+ }
8875
+ this._scopedByCap.set(cap, loaded);
8876
+ added = true;
8877
+ }
8878
+ if (!added) return;
8879
+ this._nodeKeysByCap = /* @__PURE__ */ new Map();
8880
+ this._addonSecretTree = null;
8881
+ }
8882
+ /**
8883
+ * The form the settings API serves while an addon declares no {@link globalSettingsSchema}: the
8884
+ * sections of its scoped schemas, so dropping the old hook does not blank the form.
8885
+ */
8886
+ scopedFormSchema(cap) {
8887
+ const byId = /* @__PURE__ */ new Map();
8888
+ for (const entry of this.loadedScopedSchemas(cap)) for (const section of entry.schema.sections) if (!byId.has(section.id)) byId.set(section.id, section);
8889
+ return byId.size === 0 ? null : { sections: [...byId.values()] };
8890
+ }
8891
+ /** Every loaded scoped schema of `cap`, or of every loaded capability. */
8892
+ loadedScopedSchemas(cap) {
8893
+ if (cap !== void 0) return this._scopedByCap.get(cap) ?? [];
8894
+ return [...this._scopedByCap.values()].flat();
8895
+ }
8896
+ /**
8897
+ * The field keys that are stored per node: every field of a {@link nodeSettingsSchema}, plus
8898
+ * the fields the legacy {@link globalSettingsSchema} still marks `perNode: true`. Derived once
8899
+ * per `cap` argument and memoized (schemas are static declarations). Empty set ⇒ every
8900
+ * per-node code path is bypassed and the settings API behaves like the node-agnostic one.
8901
+ * Call {@link loadScopedSchemas} first (the async seams do).
8902
+ */
8168
8903
  perNodeKeys(cap) {
8169
8904
  const cacheKey = cap ?? "";
8170
- const cached = this._perNodeKeysCache.get(cacheKey);
8905
+ const cached = this._nodeKeysByCap.get(cacheKey);
8171
8906
  if (cached) return cached;
8172
- const schema = this.globalSettingsSchema(cap);
8173
- const keys = new Set(schema ? schema.sections.flatMap((section) => collectPerNodeFieldKeys(section.fields)) : []);
8174
- this._perNodeKeysCache.set(cacheKey, keys);
8907
+ const legacy = this.globalSettingsSchema(cap);
8908
+ const keys = new Set(legacy ? legacy.sections.flatMap((section) => collectPerNodeFieldKeys(section.fields)) : []);
8909
+ for (const { scope, schema } of this.loadedScopedSchemas(cap)) {
8910
+ if (scope !== "node") continue;
8911
+ for (const section of schema.sections) for (const key of collectValueFieldKeys(section.fields)) keys.add(key);
8912
+ }
8913
+ this._nodeKeysByCap.set(cacheKey, keys);
8175
8914
  return keys;
8176
8915
  }
8177
8916
  /**
@@ -8181,10 +8920,9 @@ var BaseAddon = class {
8181
8920
  * time to return its response before the addon is torn down and
8182
8921
  * re-initialised by `AddonRegistryService.restartAddon`.
8183
8922
  */
8184
- maybeAutoRestart(patchKeys, schema) {
8185
- if (!schema) return;
8923
+ maybeAutoRestart(patchKeys, schemas) {
8186
8924
  const restartKeys = /* @__PURE__ */ new Set();
8187
- for (const section of schema.sections) for (const field of section.fields) {
8925
+ for (const schema of schemas) for (const section of schema.sections) for (const field of section.fields) {
8188
8926
  if (field.type === "separator" || field.type === "info") continue;
8189
8927
  if (field.requiresRestart) restartKeys.add(field.key);
8190
8928
  }
@@ -8380,12 +9118,14 @@ var BaseAddon = class {
8380
9118
  * here, in the addon's own process, so the hub keeps no copy of it.
8381
9119
  */
8382
9120
  async getDeclaredSettingsKeys() {
9121
+ await this.loadScopedSchemas();
8383
9122
  return { keys: [...this.declaredKeySet()].toSorted() };
8384
9123
  }
8385
9124
  declaredKeySet() {
8386
9125
  const keys = new Set(Object.keys(this.defaults));
8387
9126
  const schema = this.globalSettingsSchema();
8388
9127
  if (schema) for (const section of schema.sections) for (const key of collectFieldKeys(section.fields)) keys.add(key);
9128
+ for (const { schema: scoped } of this.loadedScopedSchemas()) for (const section of scoped.sections) for (const key of collectFieldKeys(section.fields)) keys.add(key);
8389
9129
  for (const key of this._declaredStateKeys) keys.add(key);
8390
9130
  for (const path of this.secretStatePaths) {
8391
9131
  const root = path.split(/[.[]/, 1)[0];
@@ -8481,7 +9221,11 @@ var BaseAddon = class {
8481
9221
  }
8482
9222
  /** The addon store's secret tree: schema fields by TYPE, plus `secretStatePaths`. */
8483
9223
  addonSecretTree() {
8484
- this._addonSecretTree ??= mergeSecretStatePaths(secretTreeFromSchema(this.globalSettingsSchema()), this.secretStatePaths);
9224
+ if (this._addonSecretTree === null) {
9225
+ const tree = new Map(secretTreeFromSchema(this.globalSettingsSchema()));
9226
+ for (const { schema } of this.loadedScopedSchemas()) for (const [key, node] of secretTreeFromSchema(schema)) tree.set(key, node);
9227
+ this._addonSecretTree = mergeSecretStatePaths(tree, this.secretStatePaths);
9228
+ }
8485
9229
  return this._addonSecretTree;
8486
9230
  }
8487
9231
  deviceSecretTree() {
@@ -8731,6 +9475,23 @@ function dropPerNodeFields(fields) {
8731
9475
  }
8732
9476
  return kept;
8733
9477
  }
9478
+ /** The keys of the value-holding fields, recursing into layout containers. */
9479
+ function collectValueFieldKeys(fields) {
9480
+ const collected = [];
9481
+ for (const field of fields) {
9482
+ if (field.type === "group") {
9483
+ collected.push(...collectValueFieldKeys(field.fields));
9484
+ continue;
9485
+ }
9486
+ if (field.type === "sub-tabs") {
9487
+ for (const tab of field.tabs) collected.push(...collectValueFieldKeys(tab.fields));
9488
+ continue;
9489
+ }
9490
+ if (field.type === "separator" || field.type === "info") continue;
9491
+ if ("key" in field && typeof field.key === "string") collected.push(field.key);
9492
+ }
9493
+ return collected;
9494
+ }
8734
9495
  function collectFieldKeys(fields) {
8735
9496
  const collected = [];
8736
9497
  for (const field of fields) {
@@ -8776,237 +9537,6 @@ function normalizeAddonInitResult(result) {
8776
9537
  if (Array.isArray(result)) return { providers: result };
8777
9538
  return result;
8778
9539
  }
8779
- var PREFIX = "records/";
8780
- /** The base of every records failure. `detail` is the human part of the message. */
8781
- var RecordsError = class extends Error {
8782
- code;
8783
- detail;
8784
- constructor(code, detail) {
8785
- super(`${PREFIX}${code}: ${detail}`);
8786
- this.name = "RecordsError";
8787
- this.code = code;
8788
- this.detail = detail;
8789
- }
8790
- };
8791
- /** A write guarded by `ifRev` found another revision (or an existing row for `ifRev: 0`). */
8792
- var RevConflictError = class extends RecordsError {
8793
- constructor(detail) {
8794
- super("rev-conflict", detail);
8795
- this.name = "RevConflictError";
8796
- }
8797
- };
8798
- /** The keychain could not store or serve a value: explicit, never an empty string. */
8799
- var RecordSecretUnavailableError = class extends RecordsError {
8800
- constructor(detail) {
8801
- super("secret-unavailable", detail);
8802
- this.name = "RecordSecretUnavailableError";
8803
- }
8804
- };
8805
- var InvalidRecordError = class extends RecordsError {
8806
- constructor(detail) {
8807
- super("invalid-record", detail);
8808
- this.name = "InvalidRecordError";
8809
- }
8810
- };
8811
- /** A kind declaration the engine refuses (non-additive change, bad shape, wrong file). */
8812
- var DeclarationRefusedError = class extends RecordsError {
8813
- constructor(detail) {
8814
- super("declaration-refused", detail);
8815
- this.name = "DeclarationRefusedError";
8816
- }
8817
- };
8818
- /** Limits and names of `ctx.records` (D881). One authority; the engine and the facade read it. */
8819
- /** The files a kind may live in. `history` is device-history's (D850), never records. */
8820
- var RECORD_DATABASES = ["settings", "events"];
8821
- /** The classes of a kind: the `@durable` vocabulary, one authority (replaces the annotation). */
8822
- var RECORD_CLASSES = [
8823
- "config",
8824
- "ledger",
8825
- "audit",
8826
- "mirror",
8827
- "ephemeral"
8828
- ];
8829
- var RECORD_DEFAULT_MAX_DATA_BYTES = 64 * 1024;
8830
- var RECORD_MAX_DATA_BYTES = 1024 * 1024;
8831
- var RECORD_BATCH_MAX = 1e3;
8832
- var RECORD_QUERY_MAX = 1e3;
8833
- /** A kind in the `settings` file may not bound itself above this (D447: high volume is `events`). */
8834
- var RECORD_SETTINGS_MAX_ROWS = 5e4;
8835
- /** The `Column`-free proof prefix: a ref collection for a kind's secret fields. */
8836
- var RECORD_SECRET_COLLECTION_PREFIX = "records:";
8837
- /**
8838
- * Secret fields of a record, addressed the way a Zod schema declares them
8839
- * (`collectZodSecretPaths`): dotted keys, `[]` for "each element of this array"
8840
- * (`auth.accessToken`, `headers[].value`).
8841
- *
8842
- * `{}` after a key means "each value of this map" (`applianceSecrets{}`): the map's own key
8843
- * names the value (`applianceSecrets{fridge}`), so no id key is declared and a body that drops a
8844
- * key releases exactly that key's secret.
8845
- *
8846
- * Array elements are matched by a DECLARED id key (`secretArrayKeys`:
8847
- * `{ headers: 'name' }`), never by index, so reordering a list keeps every
8848
- * keychain ref (the same rule as `arrayItemFieldPath`). The concrete path of a
8849
- * leaf names its element: `headers[X-Api].value`.
8850
- *
8851
- * Pure and browser-safe. Nothing here mutates: every transform returns a new value.
8852
- */
8853
- /** The array prefixes (declared form, e.g. `headers` or `a.headers`) of a path. */
8854
- function parseSecretPath(path) {
8855
- if (path.length === 0) throw new InvalidRecordError("an empty secret path");
8856
- return path.split(".").map((raw) => {
8857
- const each = raw.endsWith("[]");
8858
- const map = raw.endsWith("{}");
8859
- const key = each || map ? raw.slice(0, -2) : raw;
8860
- if (key.length === 0) throw new InvalidRecordError(`secret path "${path}" has an empty segment`);
8861
- return {
8862
- key,
8863
- each,
8864
- map
8865
- };
8866
- });
8867
- }
8868
- /** The declared array prefixes of `path` that need an id key (`headers`, `a.rows`). */
8869
- function secretArrayPrefixes(path) {
8870
- const segments = parseSecretPath(path);
8871
- const prefixes = [];
8872
- const walked = [];
8873
- for (const segment of segments) {
8874
- walked.push(segment.key);
8875
- if (segment.each) prefixes.push(walked.join("."));
8876
- }
8877
- return prefixes;
8878
- }
8879
- function isRecord$4(value) {
8880
- return typeof value === "object" && value !== null && !Array.isArray(value);
8881
- }
8882
- function elementId(element, idKey, declared, prefix) {
8883
- const id = isRecord$4(element) ? element[idKey] : void 0;
8884
- 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`);
8885
- return id;
8886
- }
8887
- /**
8888
- * Visit every secret leaf PRESENT in `data` (an absent branch has nothing to
8889
- * visit). `replace` returns the new leaf value, or {@link REMOVE_LEAF}; the
8890
- * result is a new body, `data` is untouched.
8891
- */
8892
- var REMOVE_LEAF = Symbol("remove-leaf");
8893
- function mapAt(node, segments, index, walkedKeys, concretePrefix, declared, arrayKeys, visit) {
8894
- if (!isRecord$4(node)) return node;
8895
- const segment = segments[index];
8896
- if (segment === void 0) return node;
8897
- if (!Object.prototype.hasOwnProperty.call(node, segment.key)) return node;
8898
- const child = node[segment.key];
8899
- const keys = [...walkedKeys, segment.key];
8900
- const last = index === segments.length - 1;
8901
- if (segment.each) {
8902
- if (!Array.isArray(child)) return node;
8903
- const prefix = keys.join(".");
8904
- const idKey = arrayKeys[prefix];
8905
- if (idKey === void 0) throw new InvalidRecordError(`"${declared}": no id key declared for the array "${prefix}"`);
8906
- const mapped = child.map((element) => {
8907
- const id = elementId(element, idKey, declared, prefix);
8908
- const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}[${encodeURIComponent(id)}]`;
8909
- return last ? element : mapAt(element, segments, index + 1, keys, concrete, declared, arrayKeys, visit);
8910
- });
8911
- return {
8912
- ...node,
8913
- [segment.key]: mapped
8914
- };
8915
- }
8916
- if (segment.map) {
8917
- if (!isRecord$4(child)) return node;
8918
- const kept = Object.entries(child).map(([mapKey, value]) => {
8919
- const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}{${encodeURIComponent(mapKey)}}`;
8920
- if (!last) return [mapKey, mapAt(value, segments, index + 1, keys, concrete, declared, arrayKeys, visit)];
8921
- return [mapKey, visit({
8922
- declared,
8923
- concrete,
8924
- value
8925
- })];
8926
- }).filter(([, value]) => value !== REMOVE_LEAF);
8927
- return {
8928
- ...node,
8929
- [segment.key]: Object.fromEntries(kept)
8930
- };
8931
- }
8932
- const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}`;
8933
- if (last) {
8934
- const replacement = visit({
8935
- declared,
8936
- concrete,
8937
- value: child
8938
- });
8939
- if (replacement === REMOVE_LEAF) return Object.fromEntries(Object.entries(node).filter(([key]) => key !== segment.key));
8940
- return {
8941
- ...node,
8942
- [segment.key]: replacement
8943
- };
8944
- }
8945
- return {
8946
- ...node,
8947
- [segment.key]: mapAt(child, segments, index + 1, keys, concrete, declared, arrayKeys, visit)
8948
- };
8949
- }
8950
- /** Replace/remove every present secret leaf; returns a NEW body. */
8951
- function mapSecretLeaves(data, paths, arrayKeys, visit) {
8952
- let current = data;
8953
- for (const declared of paths) current = mapAt(current, parseSecretPath(declared), 0, [], "", declared, arrayKeys, visit);
8954
- return current;
8955
- }
8956
- /** Every present secret leaf, read-only. */
8957
- function collectSecretLeaves(data, paths, arrayKeys) {
8958
- const found = [];
8959
- mapSecretLeaves(data, paths, arrayKeys, (leaf) => {
8960
- found.push(leaf);
8961
- return leaf.value;
8962
- });
8963
- return found;
8964
- }
8965
- /**
8966
- * The keychain collection name a kind's secrets live under. Prefixed so a
8967
- * record's refs never collide with the refs a legacy collection of the same name
8968
- * already holds during an adoption.
8969
- */
8970
- function recordSecretCollection(kind) {
8971
- return `${RECORD_SECRET_COLLECTION_PREFIX}${kind}`;
8972
- }
8973
- /** The ONE ref a row's secret field may carry: the engine and the facade both build it here. */
8974
- function recordSecretRef(owner, kind, rowId, concretePath) {
8975
- return buildSecretRef({
8976
- owner,
8977
- scope: {
8978
- kind: "row",
8979
- collection: recordSecretCollection(kind),
8980
- rowId
8981
- },
8982
- fieldPath: concretePath
8983
- });
8984
- }
8985
- /**
8986
- * A stored secret, as an admin read shows it: a VIEW naming the row's own
8987
- * keychain ref (`set: true`), never the value and no longer the bare redaction
8988
- * token. The form hands it to the secret field, which reveals the value by ref
8989
- * through the audited `keychain-admin.reveal`; sent back untouched it keeps the
8990
- * stored secret (the records door reads a view as KEEP).
8991
- *
8992
- * ONE implementation for the entries service and for every addon that serves
8993
- * its own instances (`RecordIntegrationInstances`).
8994
- */
8995
- function isRecord$3(value) {
8996
- return typeof value === "object" && value !== null && !Array.isArray(value);
8997
- }
8998
- function secretViewsOf(owner, kind, id, decl, data) {
8999
- if (decl.secretPaths.length === 0) return data;
9000
- const shown = mapSecretLeaves(data, decl.secretPaths, decl.secretArrayKeys, (leaf) => {
9001
- if (leaf.value !== "__camstack_redacted__") return leaf.value;
9002
- return {
9003
- $secret: recordSecretRef(owner, kind, id, leaf.concrete),
9004
- v: 1,
9005
- set: true
9006
- };
9007
- });
9008
- return isRecord$3(shown) ? shown : data;
9009
- }
9010
9540
  /**
9011
9541
  * The share-view scope kinds a share-link token can carry. The hub mints
9012
9542
  * and validates them (`ShareViewGrantSchema` builds its
@@ -9260,6 +9790,7 @@ function defineRecordKinds(specs) {
9260
9790
  function entryBody(shape) {
9261
9791
  return object({
9262
9792
  name: string().min(1),
9793
+ enabled: boolean().optional(),
9263
9794
  ...shape
9264
9795
  });
9265
9796
  }
@@ -11142,6 +11673,10 @@ Object.freeze({
11142
11673
  "all",
11143
11674
  "one"
11144
11675
  ]
11676
+ },
11677
+ {
11678
+ "path": "positionUpdatedAt",
11679
+ "valueType": "number"
11145
11680
  }
11146
11681
  ],
11147
11682
  "meter": [{
@@ -11396,22 +11931,6 @@ Object.freeze({
11396
11931
  "path": "pumpRunning",
11397
11932
  "valueType": "boolean"
11398
11933
  },
11399
- {
11400
- "path": "lastDrink",
11401
- "valueType": "number"
11402
- },
11403
- {
11404
- "path": "currentHourDrink",
11405
- "valueType": "number"
11406
- },
11407
- {
11408
- "path": "last24hDrink",
11409
- "valueType": "number"
11410
- },
11411
- {
11412
- "path": "todayDrink",
11413
- "valueType": "number"
11414
- },
11415
11934
  {
11416
11935
  "path": "error",
11417
11936
  "valueType": "string"
@@ -11977,12 +12496,66 @@ Object.freeze({
11977
12496
  }
11978
12497
  ]
11979
12498
  });
12499
+ Object.freeze({
12500
+ "actions": { "run": 363e4 },
12501
+ "audio-analyzer": { "classify": 3e4 },
12502
+ "custom-model-registry": { "importModelBundle": 18e5 },
12503
+ "database-snapshot": { "writeSnapshot": 18e5 },
12504
+ "device-manager": {
12505
+ "migrateDevice": 72e4,
12506
+ "runDiscoverySweep": 12e4
12507
+ },
12508
+ "device-provider": { "reloadDevice": 18e4 },
12509
+ "llm": {
12510
+ "generate": 6e5,
12511
+ "generateVision": 6e5,
12512
+ "testProfile": 6e5
12513
+ },
12514
+ "llm-runtime": {
12515
+ "complete": 6e5,
12516
+ "completeApple": 6e5,
12517
+ "ensureStarted": 6e5,
12518
+ "installModel": 36e5
12519
+ },
12520
+ "local-network": { "scanNetwork": 9e4 },
12521
+ "model-convert": { "convert": 6e5 },
12522
+ "pipeline-analytics": {
12523
+ "addRetrainFrameFromRecording": 6e4,
12524
+ "offerRetrainArchive": 12e4,
12525
+ "proposeRetrainAnnotationsWithLlm": 18e4,
12526
+ "resolveRetrainTrainingCorpus": 6e4,
12527
+ "writeRetrainArchive": 36e5
12528
+ },
12529
+ "server-management": { "applyServerUpdate": 96e4 },
12530
+ "terminal-session": { "pullOutput": 15e3 },
12531
+ "training": {
12532
+ "canaryResult": 12e4,
12533
+ "cancelJob": 12e4,
12534
+ "planJob": 6e4,
12535
+ "registerResult": 18e5,
12536
+ "rollbackCanary": 12e4,
12537
+ "startJob": 12e4,
12538
+ "startJobBatch": 12e4
12539
+ },
12540
+ "training-provider": {
12541
+ "cancelJob": 6e4,
12542
+ "cleanupJob": 3e5,
12543
+ "getJob": 6e4,
12544
+ "listJobEvents": 6e4,
12545
+ "listJobs": 12e4,
12546
+ "offerArtifact": 3e5,
12547
+ "readResult": 3e5,
12548
+ "submitJob": 18e5,
12549
+ "uploadDataset": 72e5,
12550
+ "validateCredentials": 3e4
12551
+ }
12552
+ });
11980
12553
  object({
11981
12554
  code: string().regex(/^[a-z][a-z0-9-]*(\.[a-z0-9-]+)+$/),
11982
12555
  params: record(string(), union([string(), number()])).optional()
11983
12556
  });
11984
12557
  //#endregion
11985
- //#region ../types/dist/composition-CRNwcFYY.mjs
12558
+ //#region ../types/dist/composition-BmBHuDTQ.mjs
11986
12559
  /**
11987
12560
  * The ffmpeg build every CamStack node downloads, per platform and arch.
11988
12561
  *
@@ -12286,7 +12859,7 @@ var table = {
12286
12859
  },
12287
12860
  dwell: {
12288
12861
  minArgs: 3,
12289
- maxArgs: 3,
12862
+ maxArgs: 4,
12290
12863
  apply: () => {
12291
12864
  throw new ExpressionEvalError("dwell: stateful evaluation context is required");
12292
12865
  }
@@ -13329,205 +13902,6 @@ var IntegrationInstanceRefSchema = object({
13329
13902
  ]),
13330
13903
  candidateStableId: string().optional()
13331
13904
  });
13332
- /**
13333
- * `RecordIntegrationInstances` - the `integration-instances` provider over ONE
13334
- * entry kind, so an addon that holds a connection serves it in ~30 lines.
13335
- *
13336
- * Every instance is one record of the addon's own kind, keyed by the
13337
- * `integrations` registry id. The records door does the secret work: a field the
13338
- * kind marks `.meta({ secret: true })` is a keychain marker bound to the row, so
13339
- * deleting the row deletes the secret, and one row's value is never another's.
13340
- *
13341
- * Patch rules for a secret (`updateInstance`): omitted, `''`, the redaction
13342
- * token or the view the form was given KEEP the stored secret;
13343
- * `{ $secretClear: true }` clears it; any other string replaces it.
13344
- */
13345
- /** The most instances one addon lists (an integrations page, not a table). */
13346
- var INSTANCES_LIST_MAX = 1e3;
13347
- /** The keys of the kind's secret fields that sit at the top level of the body. */
13348
- function topLevelSecretKeys(paths) {
13349
- return new Set(paths.filter((p) => !p.includes(".") && !p.includes("[") && !p.includes("{")));
13350
- }
13351
- /** The keys of the kind's top-level MAPS whose values are secrets (`applianceSecrets{}`). */
13352
- function secretMapKeys(paths) {
13353
- return new Set(paths.filter((p) => p.endsWith("{}") && !p.slice(0, -2).match(/[.[{]/)).map((p) => p.slice(0, -2)));
13354
- }
13355
- /**
13356
- * A patch value for a map of secrets: an entry that is omitted, `''`, the redaction token or the
13357
- * view the form was given KEEPS its stored secret (it is left out of the merge); `{ $secretClear }`
13358
- * or `null` removes the entry; any other string replaces it. Null when nothing is left to merge.
13359
- */
13360
- function secretMapPatch(value) {
13361
- if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
13362
- const out = {};
13363
- for (const [key, entry] of Object.entries(value)) if (entry === null || isSecretClear(entry)) out[key] = null;
13364
- else if (typeof entry === "string" && entry !== "" && entry !== "__camstack_redacted__" && !isSecretFieldView(entry)) out[key] = entry;
13365
- return Object.keys(out).length > 0 ? out : null;
13366
- }
13367
- /** Does the kind's body schema carry an `enabled` field? */
13368
- function declaresEnabled(kind) {
13369
- const json = toJSONSchema(kind.schema, {
13370
- unrepresentable: "any",
13371
- io: "input"
13372
- });
13373
- const properties = Reflect.get(json, "properties");
13374
- return typeof properties === "object" && properties !== null && "enabled" in properties;
13375
- }
13376
- var RecordIntegrationInstances = class {
13377
- records;
13378
- kind;
13379
- hooks;
13380
- handle;
13381
- secretKeys;
13382
- secretMaps;
13383
- nameField;
13384
- /** The `integrations` registry owns the on/off switch (`role: devices`); the body has none. */
13385
- registryOwnsEnabled;
13386
- constructor(records, kind, hooks) {
13387
- this.records = records;
13388
- this.kind = kind;
13389
- this.hooks = hooks;
13390
- this.handle = records.kind(kind);
13391
- this.secretKeys = topLevelSecretKeys(kind.declaration.secretPaths);
13392
- this.secretMaps = secretMapKeys(kind.declaration.secretPaths);
13393
- this.nameField = kind.declaration.entry?.nameField ?? "name";
13394
- this.registryOwnsEnabled = hooks.description.role === "devices";
13395
- 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"`);
13396
- }
13397
- /**
13398
- * One instance read for the addon's own runtime; null when absent. When the keychain is
13399
- * locked the row is served WITHOUT its secrets and says so (`secrets: 'unavailable'`), so the
13400
- * caller can keep what it had instead of reconfiguring with an empty secret (D49).
13401
- */
13402
- async readResolved(id) {
13403
- try {
13404
- const record = await this.handle.getResolved(id);
13405
- return record === null ? null : {
13406
- id,
13407
- body: record.data,
13408
- enabled: record.data.enabled !== false,
13409
- secrets: "resolved"
13410
- };
13411
- } catch (err) {
13412
- if (!(err instanceof RecordSecretUnavailableError)) throw err;
13413
- const stored = await this.handle.get(id);
13414
- if (stored === null) return null;
13415
- return {
13416
- id,
13417
- body: Object.fromEntries(Object.entries(stored.data).filter(([key]) => !this.secretKeys.has(key))),
13418
- enabled: stored.data.enabled !== false,
13419
- secrets: "unavailable"
13420
- };
13421
- }
13422
- }
13423
- /** The body of {@link readResolved} alone; a locked keychain yields the row without secrets. */
13424
- async getResolved(id) {
13425
- return (await this.readResolved(id))?.body ?? null;
13426
- }
13427
- /** Every instance, secrets resolved where the keychain allows; an absent one is skipped. */
13428
- async listResolved() {
13429
- const page = await this.handle.query({ limit: INSTANCES_LIST_MAX });
13430
- const out = [];
13431
- for (const record of page.records) {
13432
- const read = await this.readResolved(record.id);
13433
- if (read !== null) out.push(read);
13434
- }
13435
- return out;
13436
- }
13437
- viewOf(record) {
13438
- const shown = secretViewsOf(this.records.owner, this.kind.name, record.id, this.kind.declaration, record.data);
13439
- const rawName = record.data[this.nameField];
13440
- const kind = this.hooks.kindOf?.(record.data);
13441
- const health = this.hooks.health?.(record.data, record.id);
13442
- return {
13443
- id: record.id,
13444
- name: typeof rawName === "string" ? rawName : record.id,
13445
- configured: this.hooks.configured(record.data),
13446
- ...this.registryOwnsEnabled ? {} : { enabled: record.data.enabled !== false },
13447
- formValues: shown,
13448
- ...kind !== void 0 ? { kind } : {},
13449
- ...health?.status !== void 0 ? { status: health.status } : {},
13450
- ...health?.lastCheckedAt !== void 0 ? { lastCheckedAt: health.lastCheckedAt } : {}
13451
- };
13452
- }
13453
- describe = async () => this.hooks.mintId === void 0 ? this.hooks.description : {
13454
- ...this.hooks.description,
13455
- mintsId: true
13456
- };
13457
- instanceFormSchema = async ({ id }) => this.hooks.formSchema(id);
13458
- listInstances = async () => {
13459
- return (await this.handle.query({ limit: INSTANCES_LIST_MAX })).records.map((record) => this.viewOf(record));
13460
- };
13461
- getInstance = async ({ id }) => {
13462
- const record = await this.handle.get(id);
13463
- return record === null ? null : this.viewOf(record);
13464
- };
13465
- /** Insert ONE row (`ifRev: 0`: an existing id is refused, never overwritten). */
13466
- createInstance = async ({ id, name, kind }) => {
13467
- const minted = id ?? this.hooks.mintId?.({
13468
- name,
13469
- ...kind !== void 0 ? { kind } : {}
13470
- });
13471
- if (minted === void 0) throw new Error("createInstance needs an id: this provider does not mint one");
13472
- await this.handle.put({
13473
- id: minted,
13474
- data: this.hooks.initialBody(name, kind)
13475
- }, { ifRev: 0 });
13476
- await this.hooks.onChanged?.(minted, "created");
13477
- return { id: minted };
13478
- };
13479
- updateInstance = async ({ id, name, values }) => {
13480
- const patch = {};
13481
- for (const [key, value] of Object.entries(values)) {
13482
- if (value === void 0) continue;
13483
- if (this.secretMaps.has(key)) {
13484
- const entries = secretMapPatch(value);
13485
- if (entries !== null) patch[key] = entries;
13486
- } else if (!this.secretKeys.has(key)) patch[key] = value;
13487
- else if (isSecretClear(value)) patch[key] = null;
13488
- else if (typeof value === "string" && value !== "" && value !== "__camstack_redacted__" && !isSecretFieldView(value)) patch[key] = value;
13489
- }
13490
- if (name !== void 0) patch[this.nameField] = name;
13491
- await this.handle.patch(id, patch);
13492
- await this.hooks.onChanged?.(id, "updated");
13493
- return { ok: true };
13494
- };
13495
- /** The switch lives in the record body; the addon is told so it applies it (D996). */
13496
- setInstanceEnabled = async ({ id, enabled }) => {
13497
- if (this.registryOwnsEnabled) throw new Error(`instance "${id}": the integrations registry owns the on/off switch of this addon; set it with integrations.update`);
13498
- await this.handle.patch(id, { enabled });
13499
- await this.hooks.onChanged?.(id, "enabled");
13500
- return { ok: true };
13501
- };
13502
- /** The row and its keychain refs go together (the records door). */
13503
- deleteInstance = async ({ id }) => {
13504
- await this.handle.delete(id);
13505
- await this.hooks.onChanged?.(id, "deleted");
13506
- return { ok: true };
13507
- };
13508
- testInstance = async (input) => {
13509
- if (this.hooks.test === void 0) return {
13510
- success: false,
13511
- status: "unsupported",
13512
- error: "This integration declares no connection test"
13513
- };
13514
- return this.hooks.test(input);
13515
- };
13516
- /** The flat provider object to hand to `registerProvider`. */
13517
- toProvider() {
13518
- return {
13519
- describe: this.describe,
13520
- instanceFormSchema: this.instanceFormSchema,
13521
- listInstances: this.listInstances,
13522
- getInstance: this.getInstance,
13523
- createInstance: this.createInstance,
13524
- updateInstance: this.updateInstance,
13525
- setInstanceEnabled: this.setInstanceEnabled,
13526
- deleteInstance: this.deleteInstance,
13527
- testInstance: this.testInstance
13528
- };
13529
- }
13530
- };
13531
13905
  var EncodeProfileSchema = object({
13532
13906
  video: object({
13533
13907
  codec: _enum([
@@ -14690,20 +15064,28 @@ async function moveIntegrationRowsToRecords(ports, spec) {
14690
15064
  };
14691
15065
  }
14692
15066
  /**
14693
- * The addon-side ports of `moveIntegrationRowsToRecords` (planning#416): an addon runs the move
14694
- * from its own process, so the legacy rows are reached through the hub (`ctx.api.integrations`:
14695
- * `list`, `getSettings` - which answers the OWNER its secrets resolved - and `clearSettings`) and
14696
- * the new record through the addon's own records handle. The hub deletes the rows and their
14697
- * keychain values; the addon never touches the registry.
15067
+ * The addon-side ports of `moveIntegrationRowsToRecords` (planning#416). An addon runs the move
15068
+ * from its own process, so the leftover rows are reached through the migration-only door
15069
+ * (`migrations.readLegacyIntegrationRows` / `clearLegacyIntegrationRows`) on the hub's connection.
15070
+ * The door returns markers. This process is the owner, so it resolves and releases them with
15071
+ * `resolveSecretMarkers` — the same call the old settings door used — and only then asks the
15072
+ * door to delete the rows. The addon's own record kind is its records handle.
14698
15073
  */
15074
+ async function resolvedRows(stored, secrets) {
15075
+ if (secrets === null) return stored;
15076
+ const { value, unresolved } = await resolveSecretMarkers(stored, secrets);
15077
+ if (unresolved.length > 0) throw new Error(`${unresolved.length} secret(s) cannot be read from the keychain`);
15078
+ return value;
15079
+ }
14699
15080
  function integrationRowsPortsOverApi(deps) {
15081
+ const secrets = deps.secrets ?? null;
14700
15082
  return {
14701
15083
  warn: (message) => deps.log.warn(message),
14702
15084
  listIntegrations: async (addonId) => (await deps.api.list()).filter((i) => i.addonId === addonId).map((i) => ({
14703
15085
  id: i.id,
14704
15086
  name: i.name
14705
15087
  })),
14706
- readRows: (integrationId) => deps.api.getSettings({ id: integrationId }),
15088
+ readRows: async (integrationId) => resolvedRows(await deps.api.readLegacyIntegrationRows({ integrationId }), secrets),
14707
15089
  putRecord: async (id, body) => {
14708
15090
  if (await deps.records.get(id) !== null) return "exists";
14709
15091
  try {
@@ -14722,15 +15104,17 @@ function integrationRowsPortsOverApi(deps) {
14722
15104
  await deps.records.delete(id);
14723
15105
  },
14724
15106
  clearRows: async (integrationId) => {
14725
- await deps.api.clearSettings({ id: integrationId });
15107
+ const refs = collectSecretMarkerRefs(await deps.api.readLegacyIntegrationRows({ integrationId }));
15108
+ if (refs.length > 0 && secrets !== null) await secrets.delete(refs);
15109
+ await deps.api.clearLegacyIntegrationRows({ integrationId });
14726
15110
  }
14727
15111
  };
14728
15112
  }
14729
15113
  function defaultIntegrationApiOver(api) {
14730
15114
  return {
14731
15115
  list: () => api.integrations.list.query(),
14732
- getSettings: (input) => api.integrations.getSettings.query(input),
14733
- clearSettings: (input) => api.integrations.clearSettings.mutate(input),
15116
+ readLegacyIntegrationRows: (input) => api.migrations.readLegacyIntegrationRows.query(input),
15117
+ clearLegacyIntegrationRows: (input) => api.migrations.clearLegacyIntegrationRows.mutate(input),
14734
15118
  listDevices: (addonId) => api.deviceManager.listAll.query({
14735
15119
  addonId,
14736
15120
  projection: "slim"
@@ -15833,6 +16217,39 @@ var UnstampedEventMediaCountSchema = object({
15833
16217
  /** Sum across both, or `null` when either lane could not be counted. */
15834
16218
  total: number().int().nonnegative().nullable()
15835
16219
  }).nullable();
16220
+ /**
16221
+ * Where the stored event media sits, per storage location: how many media rows
16222
+ * and how many bytes carry each location id, how many carry none (legacy,
16223
+ * resolved to the default `eventMedia` location), and how many name a location
16224
+ * that was not asked about (a deleted or never-listed one).
16225
+ *
16226
+ * One covering-index aggregate per asked location plus the NULL one, and one
16227
+ * unfiltered total that scans the covering index: O(rows), not a walk of the
16228
+ * rows themselves. `unlisted` is total minus the ASKED locations minus NULL, so
16229
+ * it is a deleted location only when every location id was asked.
16230
+ * `null` is "could not be measured", never zero.
16231
+ */
16232
+ var MediaLocationCensusInputSchema = object({ locationIds: array(string().min(1)).max(50).readonly() });
16233
+ var MediaLocationCensusSchema = object({
16234
+ locations: array(object({
16235
+ locationId: string(),
16236
+ rows: number().int().nonnegative(),
16237
+ bytes: number().nonnegative()
16238
+ })).readonly(),
16239
+ unstamped: object({
16240
+ rows: number().int().nonnegative(),
16241
+ bytes: number().nonnegative()
16242
+ }),
16243
+ /** Rows stamped with a location id that was not in the asked list. */
16244
+ unlisted: object({
16245
+ rows: number().int().nonnegative(),
16246
+ bytes: number().nonnegative()
16247
+ }),
16248
+ total: object({
16249
+ rows: number().int().nonnegative(),
16250
+ bytes: number().nonnegative()
16251
+ })
16252
+ });
15836
16253
  var StorageMigrationMediaMoveInputSchema = RelocateMediaInputSchema.extend({ leaseId: string().min(1) });
15837
16254
  /** The independently selectable logical storage classes — every class
15838
16255
  * `storage.listLocationDeclarations` reports, so an operator never meets a
@@ -19812,31 +20229,21 @@ var APPLIANCE_CAP_VOCABULARY = {
19812
20229
  "pet-fountain": {
19813
20230
  scope: "device",
19814
20231
  noun: t("Pet fountain", "Fontana per animali"),
19815
- actions: [
19816
- {
19817
- id: "petFountain.pumpOn",
19818
- method: "setPump",
19819
- label: t("Pump on", "Pompa accesa"),
19820
- phrase: t("Start the pump of {device}", "Avvia la pompa di {device}"),
19821
- icon: "play",
19822
- args: { on: true }
19823
- },
19824
- {
19825
- id: "petFountain.pumpOff",
19826
- method: "setPump",
19827
- label: t("Pump off", "Pompa spenta"),
19828
- phrase: t("Stop the pump of {device}", "Ferma la pompa di {device}"),
19829
- icon: "square",
19830
- args: { on: false }
19831
- },
19832
- {
19833
- id: "petFountain.resetDailyConsumption",
19834
- method: "resetDailyConsumption",
19835
- label: t("Clear daily consumption", "Azzera il consumo giornaliero"),
19836
- phrase: t("Clear the daily water consumption of {device}", "Azzera il consumo giornaliero di acqua di {device}"),
19837
- icon: "rotate-ccw"
19838
- }
19839
- ],
20232
+ actions: [{
20233
+ id: "petFountain.pumpOn",
20234
+ method: "setPump",
20235
+ label: t("Pump on", "Pompa accesa"),
20236
+ phrase: t("Start the pump of {device}", "Avvia la pompa di {device}"),
20237
+ icon: "play",
20238
+ args: { on: true }
20239
+ }, {
20240
+ id: "petFountain.pumpOff",
20241
+ method: "setPump",
20242
+ label: t("Pump off", "Pompa spenta"),
20243
+ phrase: t("Stop the pump of {device}", "Ferma la pompa di {device}"),
20244
+ icon: "square",
20245
+ args: { on: false }
20246
+ }],
19840
20247
  state: [{
19841
20248
  kind: "boolean",
19842
20249
  field: "empty",
@@ -43869,8 +44276,15 @@ var ActionInputSchema = object({
43869
44276
  var ActionRunOriginSchema = object({
43870
44277
  /** The automation block whose step started it. */
43871
44278
  blockId: string().min(1).optional() });
43872
- /** `started` = the caller did not ask to wait. */
43873
- var ActionRunOutcomeSchema = union([AutomationRunOutcomeSchema, literal("started")]);
44279
+ /**
44280
+ * `started` = the caller did not ask to wait. `timed-out` = the run reached the
44281
+ * ceiling (`ACTION_RUN_MAX_MS`) and was stopped; it is never a `ran`.
44282
+ */
44283
+ var ActionRunOutcomeSchema = union([
44284
+ AutomationRunOutcomeSchema,
44285
+ literal("started"),
44286
+ literal("timed-out")
44287
+ ]);
43874
44288
  var ActionRunResultSchema = object({
43875
44289
  runId: string().min(1),
43876
44290
  outcome: ActionRunOutcomeSchema,
@@ -44392,6 +44806,8 @@ method(object({}), array(ActionEntrySchema), { auth: "admin" }), method(object({
44392
44806
  kind: "mutation",
44393
44807
  auth: "admin"
44394
44808
  });
44809
+ /** `timeoutMs` of `actions.run`: a waited call outlives any legal run. */
44810
+ var ACTION_RUN_TIMEOUT_MS = 363e4;
44395
44811
  /**
44396
44812
  * actions — the ONE surface for runnable actions, for the UI and for
44397
44813
  * automations. Provided by the core-blocks builtin on the hub.
@@ -44410,6 +44826,12 @@ method(object({}), array(ActionEntrySchema), { auth: "admin" }), method(object({
44410
44826
  * An admin, and an in-process caller (an automation block), may run any action.
44411
44827
  * Every refusal is typed (`[not-linked] …`) and logged.
44412
44828
  *
44829
+ * **A run lasts at most `ACTION_RUN_MAX_MS` (60 min).** The provider stops a
44830
+ * run that reaches it and answers `timed-out` (never `ran`); an action whose
44831
+ * `wait` steps alone add up to more is refused at create/update
44832
+ * (`[invalid-steps]`). `run` declares a `timeoutMs` above that ceiling, so a
44833
+ * waited call (an automation step) is never cut by the 60 s transport default.
44834
+ *
44413
44835
  * A second `run` of an action that is already running is REFUSED — traced and
44414
44836
  * logged — never queued.
44415
44837
  */
@@ -44436,7 +44858,8 @@ method(object({}), array(ActionEntrySchema), { auth: "admin" }), method(object({
44436
44858
  role: "viewer",
44437
44859
  auth: "protected",
44438
44860
  kind: "mutation",
44439
- caller: "required"
44861
+ caller: "required",
44862
+ timeoutMs: ACTION_RUN_TIMEOUT_MS
44440
44863
  }), method(ActionIdInput, _void(), {
44441
44864
  kind: "mutation",
44442
44865
  auth: "admin"
@@ -46948,52 +47371,7 @@ onBrightnessChanged: { data: object({
46948
47371
  minIntervalMs: 0
46949
47372
  } } }
46950
47373
  };
46951
- /**
46952
- * `broker` — unified pub/sub broker registry, system-scoped collection.
46953
- *
46954
- * The cap models any kind-tagged message broker the user wants to
46955
- * register and that other addons might consume. The first two kinds
46956
- * are MQTT (mosquitto / aedes embedded / cloud bridge) and
46957
- * Home Assistant (HA WebSocket — subscribe_entities + call_service).
46958
- * Future kinds (Zigbee2MQTT bridge, ZHA, KNX, Telegram, …) plug in
46959
- * the same surface.
46960
- *
46961
- * Why one cap, not one cap per kind:
46962
- * - The integrations page wants a single table of "every broker"
46963
- * across kinds; a unified cap drives it without join logic.
46964
- * - Generic admin operations (add / remove / test / status) are
46965
- * identical across kinds — duplicating them per cap was busywork.
46966
- * - The `network-access` cap precedent: same interface, many
46967
- * `providerKind: 'ingress'` implementations (Tailscale, ngrok, …).
46968
- *
46969
- * What stays kind-specific:
46970
- * - `getBrokerConfig` payload (kind decides whether it returns
46971
- * mqtt URL+creds, HA baseUrl+token, …) — typed as
46972
- * `Record<string, unknown>` at the wire; consumers narrow.
46973
- * - `publish` / `subscribe` / `getState` arguments (target / filter /
46974
- * key) — also typed as `Record<string, unknown>` so each kind can
46975
- * evolve its surface (MQTT topic+qos vs HA entity_id+domain)
46976
- * without rebreaking the cap signature.
46977
- * - `add` `settings` payload (different fields per kind, validated by
46978
- * the kind-specific provider).
46979
- *
46980
- * Bidirectionality:
46981
- * - `publish` is RPC — synchronous result (provider-defined).
46982
- * - `subscribe` returns a subscription handle; the actual message
46983
- * stream flows over the typed event-bus as `broker.message` events
46984
- * keyed by `(brokerId, subscriptionId)`. Consumers filter in their
46985
- * event handler. Subscriptions persist across reconnects — the
46986
- * provider re-subscribes upstream after a transport drop.
46987
- *
46988
- * Why event-bus push (not a subscription RPC stream):
46989
- * - Matches the rest of CamStack's D8 contract — events for telemetry,
46990
- * RPC for loss-is-a-bug. Broker messages are telemetry (a single
46991
- * drop is recoverable via `getState({key})`).
46992
- * - Frees `broker.subscribe` from holding a long-lived RPC channel.
46993
- * - Cross-process: events already route through `$event-bus`; no
46994
- * per-broker wire-shaping needed.
46995
- */
46996
- var BrokerStatusEnum = _enum([
47374
+ _enum([
46997
47375
  "connected",
46998
47376
  "disconnected",
46999
47377
  "connecting",
@@ -47001,141 +47379,12 @@ var BrokerStatusEnum = _enum([
47001
47379
  "unreachable",
47002
47380
  "error"
47003
47381
  ]);
47004
- var BrokerInfoSchema = object({
47005
- /** Stable broker id. Persisted; survives addon restarts. */
47006
- id: string(),
47007
- /** Addon id of the provider that OWNS this broker.
47008
- *
47009
- * The `broker` cap is a system-scoped collection: several addons
47010
- * register a `broker` provider, each owning a DISJOINT set of
47011
- * brokers (mqtt-broker owns `mqtt_*`, provider-homeassistant owns
47012
- * `ha_*`). A broker therefore belongs to exactly one addon — like a
47013
- * device belongs to one integration. The admin UI threads this id
47014
- * back as the `{ addonId }` system-collection selector on every
47015
- * id-keyed call (`get` / `getSettings` / `setSettings` / `remove` /
47016
- * `testConnection`), so the call routes to the OWNING provider
47017
- * instead of defaulting to the first-registered one. */
47018
- addonId: string(),
47019
- /** Human-readable name (operator-chosen at add-time). */
47020
- name: string(),
47021
- /** Provider-defined kind tag — `mqtt` / `home-assistant` / future. */
47022
- kind: string(),
47023
- status: BrokerStatusEnum,
47024
- /** Free-form provider-specific info (HA version, MQTT broker
47025
- * flavour, latency, mTLS active, …). */
47026
- info: record(string(), unknown()),
47027
- /** Ms epoch of the last connection probe / status update. */
47028
- lastCheckedAt: number().nullable(),
47029
- /** Last error message, when `status` indicates failure. */
47030
- error: string().nullable()
47031
- });
47032
47382
  var RegistryStatusSchema = object({
47033
47383
  brokerCount: number().int().nonnegative(),
47034
47384
  connectedCount: number().int().nonnegative()
47035
47385
  });
47036
- /**
47037
- * One entry per `broker` provider — which addon provides which broker
47038
- * kind(s). The unified create picker reads this to know, for each
47039
- * (addonId, kind) pair the operator can pick, where to route the
47040
- * follow-up `getSettingsSchema` / `testSettings` / `add` calls (via the
47041
- * `{ addonId }` selector). A provider only advertises a kind here when
47042
- * it implements `getSettingsSchema` for that kind (so the picker never
47043
- * offers a kind whose creation form can't be rendered).
47044
- */
47045
- var BrokerProviderInfoSchema = object({
47046
- /** Addon id of the `broker` provider this entry describes. */
47047
- addonId: string(),
47048
- /** Broker kinds this provider can create, with a display label. */
47049
- kinds: array(object({
47050
- kind: string(),
47051
- label: string(),
47052
- /**
47053
- * Relative hub path to start an interactive account link (OAuth popup).
47054
- * May include `{{brokerId}}`; admin-ui substitutes and appends `?popup=1`.
47055
- */
47056
- interactiveConnectPath: string().min(1).optional(),
47057
- /** Relative hub path to disconnect the linked account (same popup pattern). */
47058
- interactiveDisconnectPath: string().min(1).optional(),
47059
- /**
47060
- * The kind signs in through a server-held interactive session instead of
47061
- * (or before) typed credentials. `basePath` is a hub-relative route set
47062
- * served by the owning addon (`/addon/<id>/...`) speaking the sign-in
47063
- * contract: `POST {basePath}/start` (body: the form's settings) answers
47064
- * `{ sessionId, loginUrl }`; `GET {basePath}/status?sessionId=` answers
47065
- * `{ phase: 'starting' | 'awaiting-login' | 'captured' | 'error' |
47066
- * 'cancelled', loginUrl, error }`; `POST {basePath}/commit`
47067
- * (`{ sessionId, name, brokerId? }`) stores the credentials on a new or
47068
- * existing broker and answers `{ brokerId }`; `POST {basePath}/cancel`
47069
- * (`{ sessionId }`) drops the session. The dialog that edits a broker
47070
- * offers it as the default path; the fields the session fills are
47071
- * marked `filledBySignIn` in the kind's settings schema.
47072
- *
47073
- * `methods` lists the ways the session can sign in, recommended first:
47074
- * `'device-code'` adds `POST {basePath}/code/start` (body: the form's
47075
- * settings) answering `{ sessionId, userCode, verificationUrl,
47076
- * expiresAt }` — the operator types `userCode` at `verificationUrl` on
47077
- * any device, and the same `status` / `commit` / `cancel` routes follow
47078
- * (status then carries `method`, `userCode`, `verificationUrl`,
47079
- * `expiresAt` and the phases `'awaiting-code'` / `'expired'`);
47080
- * `'proxy'` is the `{basePath}/start` flow above. Absent means
47081
- * `['proxy']`.
47082
- */
47083
- signIn: object({
47084
- basePath: string().min(1),
47085
- methods: array(_enum(["device-code", "proxy"])).optional()
47086
- }).optional()
47087
- }))
47088
- });
47089
- var ListInputSchema = object({
47090
- /** Optional kind filter — `list({kind:'home-assistant'})` returns
47091
- * only HA brokers. Omit to list every broker. */
47092
- kind: string().optional() });
47093
47386
  var GetInputSchema = object({ id: string() });
47094
- var AddInputSchema = object({
47095
- kind: string().min(1),
47096
- name: string().min(1),
47097
- /**
47098
- * ADOPT an existing id instead of minting a new one.
47099
- *
47100
- * Written the day this cost an outage. A broker's id is not a detail: HA
47101
- * devices carry it inside their `stableId` (`ha:ha_004:dev:…`), so a broker
47102
- * lost from config and re-added as `ha_001` leaves every one of its devices
47103
- * bound to a broker that no longer exists. Re-entering the password under the
47104
- * ORIGINAL id turns a multi-step device migration back into re-entering a
47105
- * password.
47106
- *
47107
- * A provider MUST refuse an id that is already in use — adopting a live
47108
- * broker's id would silently take it over.
47109
- */
47110
- id: string().min(1).optional(),
47111
- /** Kind-specific settings (e.g. MQTT `{url,username,password}` or HA
47112
- * `{baseUrl,accessToken}`). Validated by the kind-specific provider
47113
- * branch on receipt — invalid shape rejects the add. */
47114
- settings: record(string(), unknown())
47115
- });
47116
- var AddResultSchema = object({ id: string() });
47117
- var RemoveInputSchema = object({ id: string() });
47118
- var TestConnectionResultSchema = discriminatedUnion("ok", [object({
47119
- ok: literal(true),
47120
- latencyMs: number().nonnegative()
47121
- }), object({
47122
- ok: literal(false),
47123
- error: string()
47124
- })]);
47125
47387
  var SettingsRecordSchema$1 = record(string(), unknown());
47126
- var SettingsSchemaInputSchema = object({ kind: string() });
47127
- var TestSettingsInputSchema = object({
47128
- kind: string(),
47129
- settings: SettingsRecordSchema$1
47130
- });
47131
- var TestSettingsResultSchema = discriminatedUnion("ok", [object({
47132
- ok: literal(true),
47133
- latencyMs: number().nonnegative().optional()
47134
- }).strict(), object({
47135
- ok: literal(false),
47136
- error: string()
47137
- })]);
47138
- var SettingsSchemaResultSchema = unknown().nullable();
47139
47388
  var PublishInputSchema = object({
47140
47389
  brokerId: string(),
47141
47390
  /** Kind-specific routing target.
@@ -47169,25 +47418,7 @@ var GetStateInputSchema = object({
47169
47418
  * HA: entity_id (returns the cached entity state). */
47170
47419
  key: string()
47171
47420
  });
47172
- method(ListInputSchema, array(BrokerInfoSchema)), method(GetInputSchema, BrokerInfoSchema.nullable()), method(_void(), array(BrokerProviderInfoSchema), { auth: "admin" }), method(AddInputSchema, AddResultSchema, {
47173
- kind: "mutation",
47174
- auth: "admin"
47175
- }), method(RemoveInputSchema, _void(), {
47176
- kind: "mutation",
47177
- auth: "admin"
47178
- }), method(GetInputSchema, TestConnectionResultSchema, {
47179
- kind: "mutation",
47180
- auth: "admin"
47181
- }), method(GetInputSchema, SettingsRecordSchema$1.nullable(), { auth: "admin" }), method(object({
47182
- id: string(),
47183
- settings: SettingsRecordSchema$1
47184
- }), _void(), {
47185
- kind: "mutation",
47186
- auth: "admin"
47187
- }), method(GetInputSchema, SettingsRecordSchema$1.nullable(), { auth: "admin" }), method(SettingsSchemaInputSchema, SettingsSchemaResultSchema, { auth: "admin" }), method(TestSettingsInputSchema, TestSettingsResultSchema, {
47188
- kind: "mutation",
47189
- auth: "admin"
47190
- }), method(PublishInputSchema, unknown(), {
47421
+ method(GetInputSchema, SettingsRecordSchema$1.nullable(), { auth: "admin" }), method(PublishInputSchema, unknown(), {
47191
47422
  kind: "mutation",
47192
47423
  auth: "admin"
47193
47424
  }), method(SubscribeInputSchema, SubscribeResultSchema, {
@@ -49663,6 +49894,9 @@ var MediaPlayerStatusSchema = object({
49663
49894
  /** Repeat mode. Null when no repeat surface.
49664
49895
  * Pair with `DeviceFeature.MediaPlayerRepeat`. */
49665
49896
  repeat: MediaPlayerRepeatSchema.nullable(),
49897
+ /** Ms epoch when `position` was read from the device. Null when the driver
49898
+ * does not say; a UI that advances the position while playing counts from it. */
49899
+ positionUpdatedAt: number().nullable().default(null),
49666
49900
  /** Ms epoch when the slice was last updated. */
49667
49901
  lastChangedAt: number()
49668
49902
  });
@@ -50298,7 +50532,9 @@ var ThresholdTransformDraftSchema = object({
50298
50532
  comparison: _enum(["gte", "lte"]),
50299
50533
  threshold: number(),
50300
50534
  startDwellMs: number().nonnegative(),
50301
- stopDwellMs: number().nonnegative()
50535
+ stopDwellMs: number().nonnegative(),
50536
+ /** Samples a start needs; absent = the compiler's default for the source (2 for running power, else 1). */
50537
+ minSamples: number().int().min(1).optional()
50302
50538
  });
50303
50539
  var CustomizeTransformDraftSchema = discriminatedUnion("kind", [
50304
50540
  IdentityTransformDraftSchema,
@@ -50416,6 +50652,9 @@ var RunningProposalEvidenceSchema = object({
50416
50652
  runsFound: number().int().nonnegative(),
50417
50653
  pausesFound: number().int().nonnegative(),
50418
50654
  longestPauseMs: number().nonnegative(),
50655
+ /** Episodes shorter than ~90 s (an anti-crease pulse, a display waking): never a run, never a pause. */
50656
+ pulsesFound: number().int().nonnegative(),
50657
+ longestPulseMs: number().nonnegative(),
50419
50658
  idleFloorW: number(),
50420
50659
  noiseCeilingW: number(),
50421
50660
  plateauW: number(),
@@ -52030,7 +52269,14 @@ var DiscoveryCandidateSchema = object({
52030
52269
  /** `stableId` of the gateway candidate this device was found BEHIND. */
52031
52270
  parentStableId: string().optional(),
52032
52271
  /** `false` = shown for context but not pickable. Default true. */
52033
- selectable: boolean().optional()
52272
+ selectable: boolean().optional(),
52273
+ /**
52274
+ * Keys of the provider's creation form (`getChildCreationSchema`) this candidate
52275
+ * cannot be adopted without — a key for an encrypted board, a pairing code. The
52276
+ * admin asks for exactly these, on the creation form prefilled with
52277
+ * `prefilledConfig`, before it adopts. Absent or empty = adopt as it is.
52278
+ */
52279
+ needsParams: array(string()).optional()
52034
52280
  });
52035
52281
  /**
52036
52282
  * Flat device summary returned by `createDevice` / `adoptDiscoveredDevice`.
@@ -52157,8 +52403,14 @@ var deviceProviderCapability = {
52157
52403
  * provider does not support manual creation. Lets the Add-Device dialog
52158
52404
  * pick the right type instead of assuming Camera.
52159
52405
  */
52160
- getManualCreationType: method(object({}), object({ deviceType: _enum(DeviceType).nullable() })),
52161
- adoptDiscoveredDevice: method(object({ candidate: DiscoveryCandidateSchema }), DeviceSummarySchema, {
52406
+ getManualCreationType: method(object({
52407
+ /** The integration asked about; a provider whose integrations differ answers per one. */
52408
+ integrationId: string().optional() }), object({ deviceType: _enum(DeviceType).nullable() })),
52409
+ adoptDiscoveredDevice: method(object({
52410
+ candidate: DiscoveryCandidateSchema,
52411
+ /** The integration the operator adopts into; a provider with several instances needs it. */
52412
+ integrationId: string().optional()
52413
+ }), DeviceSummarySchema, {
52162
52414
  kind: "mutation",
52163
52415
  auth: "admin"
52164
52416
  }),
@@ -52169,10 +52421,16 @@ var deviceProviderCapability = {
52169
52421
  * devices of that type. The output is a `ConfigUISchema` — the
52170
52422
  * router type-asserts it at the boundary.
52171
52423
  */
52172
- getChildCreationSchema: method(object({ type: _enum(DeviceType) }), CreationSchemaOutputSchema),
52424
+ getChildCreationSchema: method(object({
52425
+ type: _enum(DeviceType),
52426
+ /** The integration asked about; a provider whose integrations differ answers per one. */
52427
+ integrationId: string().optional()
52428
+ }), CreationSchemaOutputSchema),
52173
52429
  createDevice: method(object({
52174
52430
  type: _enum(DeviceType),
52175
- config: record(string(), unknown())
52431
+ config: record(string(), unknown()),
52432
+ /** The integration the operator adds the device to; a provider with several instances needs it. */
52433
+ integrationId: string().optional()
52176
52434
  }), DeviceSummarySchema, {
52177
52435
  kind: "mutation",
52178
52436
  auth: "admin"
@@ -52897,7 +53155,10 @@ method(object({
52897
53155
  auth: "admin"
52898
53156
  }), method(object({
52899
53157
  addonId: string(),
52900
- type: _enum(DeviceType)
53158
+ type: _enum(DeviceType),
53159
+ /** The integration the form is for; a provider whose integrations differ (a hub
53160
+ * integration takes no manual add) answers per integration. Absent = the addon's own. */
53161
+ integrationId: string().optional()
52901
53162
  }), unknown().nullable()), method(object({
52902
53163
  addonId: string(),
52903
53164
  type: _enum(DeviceType),
@@ -52981,7 +53242,11 @@ method(object({
52981
53242
  kind: "mutation",
52982
53243
  auth: "admin",
52983
53244
  timeoutMs: 12e4
52984
- }), method(object({ addonId: string() }), object({ deviceType: _enum(DeviceType).nullable() }), { auth: "admin" }), method(object({ addonId: string() }), unknown(), { auth: "admin" }), method(object({
53245
+ }), method(object({
53246
+ addonId: string(),
53247
+ /** The integration the Add-Device dialog is open on; absent = the addon's own. */
53248
+ integrationId: string().optional()
53249
+ }), object({ deviceType: _enum(DeviceType).nullable() }), { auth: "admin" }), method(object({ addonId: string() }), unknown(), { auth: "admin" }), method(object({
52985
53250
  deviceId: number(),
52986
53251
  key: string(),
52987
53252
  value: unknown()
@@ -56167,6 +56432,7 @@ var IntegrationWithStateSchema = object({
56167
56432
  id: string(),
56168
56433
  addonId: string(),
56169
56434
  name: string(),
56435
+ /** A projection of the instance body's switch (`setInstanceEnabled` is the only writer). */
56170
56436
  enabled: boolean(),
56171
56437
  info: record(string(), unknown()).readonly(),
56172
56438
  /** The discovery candidate this integration was set up from (D984). */
@@ -56179,6 +56445,7 @@ var IntegrationLiteSchema = object({
56179
56445
  id: string(),
56180
56446
  addonId: string(),
56181
56447
  name: string(),
56448
+ /** A projection of the instance body's switch (`setInstanceEnabled` is the only writer). */
56182
56449
  enabled: boolean(),
56183
56450
  info: record(string(), unknown()).readonly(),
56184
56451
  /** The discovery candidate this integration was set up from (D984). */
@@ -56261,7 +56528,7 @@ var TestConnectionStatusEnum = _enum([
56261
56528
  "inconclusive",
56262
56529
  "unsupported"
56263
56530
  ]);
56264
- var TestConnectionResultSchema$1 = object({
56531
+ var TestConnectionResultSchema = object({
56265
56532
  /** True ONLY for `validated`. Never true for a test that did not run. */
56266
56533
  success: boolean(),
56267
56534
  error: string().optional(),
@@ -56278,19 +56545,19 @@ var TestConnectionResultSchema$1 = object({
56278
56545
  var CreateIntegrationInputSchema = object({
56279
56546
  addonId: string(),
56280
56547
  name: string(),
56281
- enabled: boolean().optional(),
56282
56548
  info: record(string(), unknown()).optional(),
56283
56549
  /** `stableId` of the discovery candidate the form was seeded from (D984). */
56284
56550
  originStableId: string().optional(),
56285
- settings: record(string(), unknown()).optional(),
56286
- /** Keys of `settings` the form's schema declares secret (by type) — kept in
56287
- * the keychain, not the table (D787). */
56288
- secretKeys: array(string()).optional(),
56289
- skipRestart: boolean().optional()
56551
+ settings: record(string(), unknown()).optional()
56290
56552
  });
56291
56553
  var UpdateIntegrationInputSchema = object({
56292
56554
  id: string(),
56293
56555
  name: string().optional(),
56556
+ /**
56557
+ * Accepted for a FIXED builtin only (`info.fixed`: alarm panel, camera grid, core blocks,
56558
+ * terminal), which keeps no instance record: the registry flag is its one store. Any other
56559
+ * integration is switched through `integration-instances.setInstanceEnabled`.
56560
+ */
56294
56561
  enabled: boolean().optional(),
56295
56562
  info: record(string(), unknown()).optional()
56296
56563
  });
@@ -56307,26 +56574,10 @@ method(_void(), array(IntegrationWithStateSchema)), method(object({ id: string()
56307
56574
  }), method(object({ id: string() }), DeleteIntegrationResultSchema, {
56308
56575
  kind: "mutation",
56309
56576
  auth: "admin"
56310
- }), method(object({ id: string() }), record(string(), unknown()), { auth: "admin" }), method(object({
56311
- id: string(),
56312
- settings: record(string(), unknown()),
56313
- /** Keys the form's schema declares secret (by type) — keychain-stored (D787). */
56314
- secretKeys: array(string()).optional(),
56315
- /** The integration's own addon applies the change in-process and asks the hub not to respawn it. */
56316
- skipRestart: boolean().optional()
56317
- }), object({ success: boolean() }), {
56318
- kind: "mutation",
56319
- auth: "admin"
56320
- }), method(object({ id: string() }), object({
56321
- rows: number().int().nonnegative(),
56322
- secrets: number().int().nonnegative()
56323
- }), {
56324
- kind: "mutation",
56325
- auth: "admin"
56326
56577
  }), method(_void(), array(AvailableIntegrationTypeSchema), { auth: "admin" }), method(object({
56327
56578
  addonId: string(),
56328
56579
  settings: record(string(), unknown())
56329
- }), TestConnectionResultSchema$1, {
56580
+ }), TestConnectionResultSchema, {
56330
56581
  kind: "mutation",
56331
56582
  auth: "admin"
56332
56583
  });
@@ -56353,6 +56604,14 @@ var ConfigSchemaPassthrough$3 = custom();
56353
56604
  var IntegrationInstanceIdSchema = string().min(1);
56354
56605
  var IntegrationInstanceModeSchema = _enum(["single", "multiple"]);
56355
56606
  /**
56607
+ * What the addon's instances ARE for the Integrations page (planning#416). `devices`: each
56608
+ * instance is an integration that brings devices (its record body owns the on/off switch);
56609
+ * `services`: a connection configured from the addon's own function page, never listed on
56610
+ * Integrations.
56611
+ * It is the same vocabulary as the manifest's `integrationRole`, which stays as an override.
56612
+ */
56613
+ var IntegrationInstanceRoleSchema = _enum(["devices", "services"]);
56614
+ /**
56356
56615
  * One kind of instance a provider can create (an adapter, an account type). The sign-in and
56357
56616
  * connect fields follow the `broker` contract (`broker.cap.ts`): `signIn.basePath` is a
56358
56617
  * hub-relative route set speaking the sign-in contract, `connectPath` / `disconnectPath` open an
@@ -56363,6 +56622,22 @@ var IntegrationInstanceKindSchema = object({
56363
56622
  /** Stable id of the kind, sent back as `createInstance.kind`. */
56364
56623
  id: string().min(1),
56365
56624
  label: string().min(1),
56625
+ /**
56626
+ * The function capability this kind is configured for (`broker`, `smtp-provider`,
56627
+ * `device-provider`, ...). A page section is the kinds whose `functionCap` it names (D1013); a
56628
+ * provider with more than one section must name it on every kind.
56629
+ */
56630
+ functionCap: string().min(1),
56631
+ /**
56632
+ * For `functionCap: 'broker'`: the registry kind of the broker an instance of this kind is
56633
+ * (`matter`, `home-assistant`, ...). A caller that needs a broker of one kind (a link field)
56634
+ * finds the instances whose kind names it; absent takes the kind `id`.
56635
+ */
56636
+ brokerKind: string().min(1).optional(),
56637
+ /** What instances of this kind are for the Integrations page; absent takes the provider's `role`. */
56638
+ role: IntegrationInstanceRoleSchema.optional(),
56639
+ /** `testInstance` really probes the remote for this kind; absent takes the provider's `canTest`. */
56640
+ canTest: boolean().optional(),
56366
56641
  /** The kind signs in through a server-held interactive session. */
56367
56642
  signIn: object({
56368
56643
  basePath: string().min(1),
@@ -56373,22 +56648,38 @@ var IntegrationInstanceKindSchema = object({
56373
56648
  /** Relative hub path to disconnect that account. */
56374
56649
  disconnectPath: string().min(1).optional()
56375
56650
  });
56651
+ /**
56652
+ * How devices of an instance are found. `none`: the operator adds them by hand; `lan`: the addon
56653
+ * scans the network before any instance exists (the wizard offers the candidates); `account`: the
56654
+ * devices appear after the instance signs in. `scopedToInstance`: a discovery run belongs to ONE
56655
+ * instance and its candidates are claimed by it.
56656
+ */
56657
+ var IntegrationInstanceDiscoverySchema = object({
56658
+ mode: _enum([
56659
+ "none",
56660
+ "lan",
56661
+ "account"
56662
+ ]),
56663
+ scopedToInstance: boolean()
56664
+ });
56665
+ /**
56666
+ * One link a kind of this provider declares (D1013 rule 5): the body `field` of an instance of
56667
+ * `kind` holds the id of an instance of the function cap `to.cap` (of kind `to.kind`, when set).
56668
+ * The hub indexes these so the target's delete is refused while a link names it.
56669
+ */
56670
+ var IntegrationInstanceLinkSchema = object({
56671
+ kind: string().min(1),
56672
+ field: string().min(1),
56673
+ to: object({
56674
+ cap: string().min(1),
56675
+ kind: string().min(1).optional()
56676
+ })
56677
+ });
56376
56678
  var IntegrationInstanceDescriptionSchema = object({
56377
56679
  /** What the instances are for the Integrations page; see {@link IntegrationInstanceRoleSchema}. */
56378
- role: _enum([
56379
- "devices",
56380
- "services",
56381
- "both"
56382
- ]),
56680
+ role: IntegrationInstanceRoleSchema,
56383
56681
  /** How the devices of an instance are found; absent means `{ mode: 'none' }`. */
56384
- discovery: object({
56385
- mode: _enum([
56386
- "none",
56387
- "lan",
56388
- "account"
56389
- ]),
56390
- scopedToInstance: boolean()
56391
- }).optional(),
56682
+ discovery: IntegrationInstanceDiscoverySchema.optional(),
56392
56683
  /** `single`: at most one instance can exist (Loki). `multiple`: an account each. */
56393
56684
  instanceMode: IntegrationInstanceModeSchema,
56394
56685
  /** What the instance is, for the UI (`destination`, `relay`, `account`). */
@@ -56409,7 +56700,9 @@ var IntegrationInstanceDescriptionSchema = object({
56409
56700
  * `createInstance` without an `id` works: the provider mints it. Absent means the caller must
56410
56701
  * send an id (the UI then mints an opaque one).
56411
56702
  */
56412
- mintsId: boolean().optional()
56703
+ mintsId: boolean().optional(),
56704
+ /** The links to other instances the provider's kinds declare; absent means none. */
56705
+ links: array(IntegrationInstanceLinkSchema).optional()
56413
56706
  });
56414
56707
  var IntegrationInstanceStatusSchema = object({
56415
56708
  state: _enum([
@@ -56429,8 +56722,8 @@ var IntegrationInstanceSchema = object({
56429
56722
  configured: boolean(),
56430
56723
  /**
56431
56724
  * The instance's own on/off switch (D996), derived from the record body (`enabled !== false`,
56432
- * so a row written before the field existed is on). Absent when the `integrations` registry
56433
- * owns the switch (`describe().role` is `devices`): read it from the registry row.
56725
+ * so a row written before the field existed is on). The same for every role, `devices` included:
56726
+ * the body is the one store, `setInstanceEnabled` the one writer (epic #440, step 3).
56434
56727
  */
56435
56728
  enabled: boolean().optional(),
56436
56729
  /** The kind of this instance (one of `describe().kinds[].id`), when the provider has kinds. */
@@ -56454,7 +56747,11 @@ var integrationInstancesCapability = {
56454
56747
  methods: {
56455
56748
  describe: method(_void(), IntegrationInstanceDescriptionSchema, { auth: "admin" }),
56456
56749
  /** The form; `id: null` is the create form. */
56457
- instanceFormSchema: method(object({ id: IntegrationInstanceIdSchema.nullable() }), ConfigSchemaPassthrough$3, { auth: "admin" }),
56750
+ instanceFormSchema: method(object({
56751
+ id: IntegrationInstanceIdSchema.nullable(),
56752
+ /** The kind of the create form (`id: null`) of a provider with several. */
56753
+ kind: string().min(1).optional()
56754
+ }), ConfigSchemaPassthrough$3, { auth: "admin" }),
56458
56755
  listInstances: method(_void(), array(IntegrationInstanceSchema).readonly(), { auth: "admin" }),
56459
56756
  getInstance: method(object({ id: IntegrationInstanceIdSchema }), IntegrationInstanceSchema.nullable(), { auth: "admin" }),
56460
56757
  /**
@@ -56464,7 +56761,9 @@ var integrationInstancesCapability = {
56464
56761
  createInstance: method(object({
56465
56762
  id: IntegrationInstanceIdSchema.optional(),
56466
56763
  name: string().min(1),
56467
- kind: string().min(1).optional()
56764
+ kind: string().min(1).optional(),
56765
+ /** Form values written with the record (a link picked in the create dialog). */
56766
+ values: record(string(), unknown()).optional()
56468
56767
  }), object({ id: string() }), {
56469
56768
  kind: "mutation",
56470
56769
  auth: "admin"
@@ -56474,7 +56773,8 @@ var integrationInstancesCapability = {
56474
56773
  auth: "admin"
56475
56774
  }),
56476
56775
  /**
56477
- * Switch ONE instance on or off. A row control, not a form field: `updateInstance.values` is the
56776
+ * Switch ONE instance on or off, for every role; a missing record is created from the addon's
56777
+ * initial body. A row control, not a form field: `updateInstance.values` is the
56478
56778
  * form patch (D62, D996). An off instance keeps its record and secrets and does no work.
56479
56779
  */
56480
56780
  setInstanceEnabled: method(object({
@@ -56491,8 +56791,10 @@ var integrationInstancesCapability = {
56491
56791
  }),
56492
56792
  testInstance: optionalMethod(object({
56493
56793
  id: IntegrationInstanceIdSchema.nullable(),
56494
- values: record(string(), unknown())
56495
- }), TestConnectionResultSchema$1, {
56794
+ values: record(string(), unknown()),
56795
+ /** The kind to test when `id` is null and the provider has several. */
56796
+ kind: string().min(1).optional()
56797
+ }), TestConnectionResultSchema, {
56496
56798
  kind: "mutation",
56497
56799
  auth: "admin"
56498
56800
  })
@@ -59249,6 +59551,382 @@ var SystemMetricsSchema = object({
59249
59551
  gpuMemoryPercent: number().optional()
59250
59552
  });
59251
59553
  method(_void(), SystemResourceSnapshotSchema), method(_void(), SystemResourceSnapshotSchema.nullable()), method(_void(), SystemMetricsSchema), method(object({ dirPath: string() }), DiskSpaceInfoSchema), method(_void(), MetricsGpuInfoSchema.nullable()), method(_void(), number().nullable()), method(object({ pids: array(number()) }), array(PidResourceStatsSchema)), method(_void(), array(AddonInstanceSchema).readonly()), method(object({ addonId: string() }), PidResourceStatsSchema.nullable()), method(_void(), array(NodeProcessSchema).readonly()), method(GetLoadSeriesInputSchema, NodeLoadSeriesSchema);
59554
+ /**
59555
+ * records - an addon's own facts and documents (D881): ledgers, audit rows,
59556
+ * config documents, mirrors. The third storage API next to `ctx.settings`
59557
+ * (operator intent, D870) and device-history (numbers over time, D850).
59558
+ *
59559
+ * Who the OWNER is: `callerAddonId`, stamped by the transport on a call that
59560
+ * crossed a process and stated by a hub in-process caller (`ctx.records` does
59561
+ * that with the addon id closed over). It is deliberately NOT in any input
59562
+ * schema, so a session can never supply it, and a call with no stamp is refused
59563
+ * `records/no-caller`. A kind is readable and writable only by its owner; other
59564
+ * addons go through the owner's capability.
59565
+ *
59566
+ * Every read is three-way: a row, `null`, or the call THROWS. A failed read is
59567
+ * never `[]`. Secret fields are never on the wire: a read shows the
59568
+ * redaction token, `secretRefs` hands the owner's `ctx.secrets` the refs it
59569
+ * resolves itself, and a write may carry only a keychain marker bound to the
59570
+ * row's own ref.
59571
+ *
59572
+ * Internal: addons reach it through `ctx.records`, never directly.
59573
+ */
59574
+ var RecordIdSchema = string().min(1).max(256);
59575
+ /** A JSON object body. Size is the engine's check (`maxDataBytes`), not a schema's. */
59576
+ var RecordBodySchema = record(string(), unknown());
59577
+ var RecordInputSchema = object({
59578
+ id: RecordIdSchema,
59579
+ /** The device this row belongs to (D865 removal, per-device reads). */
59580
+ deviceId: number().int().optional(),
59581
+ /** The domain clock, ms: observed / created / opened. */
59582
+ at: number().int().optional(),
59583
+ /** Producer-set expiry, ms. Refused on a kind whose retention is an engine TTL. */
59584
+ expiresAt: number().int().optional(),
59585
+ data: RecordBodySchema
59586
+ });
59587
+ var RecordViewSchema = object({
59588
+ id: string(),
59589
+ deviceId: number().int().nullable(),
59590
+ at: number().nullable(),
59591
+ expiresAt: number().nullable(),
59592
+ rev: number().int(),
59593
+ updatedAt: number(),
59594
+ data: RecordBodySchema
59595
+ });
59596
+ /** Declared index fields only. Anything else does not compile, by design. */
59597
+ var RecordWhereSchema = record(RecordFieldPathSchema, union([
59598
+ string(),
59599
+ number(),
59600
+ boolean(),
59601
+ object({ in: array(union([
59602
+ string(),
59603
+ number(),
59604
+ boolean()
59605
+ ])).min(1).max(RECORD_BATCH_MAX) }),
59606
+ object({
59607
+ gt: union([string(), number()]).optional(),
59608
+ gte: union([string(), number()]).optional(),
59609
+ lt: union([string(), number()]).optional(),
59610
+ lte: union([string(), number()]).optional()
59611
+ }).refine((r) => Object.keys(r).length > 0, { message: "name at least one bound" })
59612
+ ]));
59613
+ var KindShape = { kind: RecordKindNameSchema };
59614
+ var TimeWindowShape = {
59615
+ deviceId: number().int().optional(),
59616
+ atFrom: number().optional(),
59617
+ atTo: number().optional()
59618
+ };
59619
+ var RecordQueryInputSchema = object({
59620
+ ...KindShape,
59621
+ ...TimeWindowShape,
59622
+ where: RecordWhereSchema.optional(),
59623
+ /** Without `where`: `at` (default for a kind with a clock) or `id`. With `where` the order is the index's. */
59624
+ order: _enum(["at", "id"]).optional(),
59625
+ desc: boolean().optional(),
59626
+ limit: number().int().min(1).max(RECORD_QUERY_MAX).default(100),
59627
+ /** Opaque keyset cursor from a previous answer. There is no offset. */
59628
+ cursor: string().min(1).optional()
59629
+ });
59630
+ var RecordQueryResultSchema = object({
59631
+ records: array(RecordViewSchema),
59632
+ nextCursor: string().nullable()
59633
+ });
59634
+ var RecordKindStateSchema = _enum([
59635
+ "created",
59636
+ "unchanged",
59637
+ "updated"
59638
+ ]);
59639
+ var DeclareKindResultSchema = object({
59640
+ kindId: number().int(),
59641
+ state: RecordKindStateSchema,
59642
+ createdIndexes: array(string())
59643
+ });
59644
+ /** Keychain refs a write released (the old marker is gone from the row): the owner deletes the values. */
59645
+ var SecretRefsList = array(string());
59646
+ /**
59647
+ * One op of a `transact`: the single-row writes, each on a kind of the caller.
59648
+ * All ops of one call share ONE database file and ONE `transactFamily`.
59649
+ */
59650
+ var RecordTransactOpSchema = discriminatedUnion("op", [
59651
+ object({
59652
+ op: literal("put"),
59653
+ kind: RecordKindNameSchema,
59654
+ record: RecordInputSchema,
59655
+ ifRev: number().int().min(0).optional()
59656
+ }),
59657
+ object({
59658
+ op: literal("patch"),
59659
+ kind: RecordKindNameSchema,
59660
+ id: RecordIdSchema,
59661
+ data: RecordBodySchema,
59662
+ at: number().int().nullable().optional(),
59663
+ expiresAt: number().int().nullable().optional(),
59664
+ ifRev: number().int().min(1).optional()
59665
+ }),
59666
+ object({
59667
+ op: literal("delete"),
59668
+ kind: RecordKindNameSchema,
59669
+ id: RecordIdSchema
59670
+ })
59671
+ ]);
59672
+ var RecordSecretRefsSchema = record(string(), record(string(), string()));
59673
+ method(object({ kinds: record(RecordKindNameSchema, RecordKindDeclarationSchema) }), object({ kinds: record(string(), DeclareKindResultSchema) }), {
59674
+ kind: "mutation",
59675
+ auth: "admin"
59676
+ }), method(object({
59677
+ ...KindShape,
59678
+ id: RecordIdSchema
59679
+ }), RecordViewSchema.nullable(), { auth: "admin" }), method(object({
59680
+ ...KindShape,
59681
+ ids: array(RecordIdSchema).min(1).max(RECORD_BATCH_MAX)
59682
+ }), array(RecordViewSchema), { auth: "admin" }), method(object({
59683
+ ...KindShape,
59684
+ ids: array(RecordIdSchema).min(1).max(RECORD_BATCH_MAX)
59685
+ }), RecordSecretRefsSchema, { auth: "admin" }), method(object({
59686
+ ...KindShape,
59687
+ record: RecordInputSchema,
59688
+ /** Compare-and-set. `0` means "the row must not exist". */
59689
+ ifRev: number().int().min(0).optional()
59690
+ }), object({
59691
+ rev: number().int(),
59692
+ releasedRefs: SecretRefsList
59693
+ }), {
59694
+ kind: "mutation",
59695
+ auth: "admin"
59696
+ }), method(object({
59697
+ ...KindShape,
59698
+ records: array(RecordInputSchema).min(1).max(RECORD_BATCH_MAX)
59699
+ }), object({
59700
+ count: number().int(),
59701
+ releasedRefs: SecretRefsList
59702
+ }), {
59703
+ kind: "mutation",
59704
+ auth: "admin"
59705
+ }), method(object({
59706
+ ...KindShape,
59707
+ id: RecordIdSchema,
59708
+ data: RecordBodySchema,
59709
+ at: number().int().nullable().optional(),
59710
+ expiresAt: number().int().nullable().optional(),
59711
+ ifRev: number().int().min(1).optional()
59712
+ }), object({
59713
+ rev: number().int(),
59714
+ releasedRefs: SecretRefsList
59715
+ }), {
59716
+ kind: "mutation",
59717
+ auth: "admin"
59718
+ }), method(object({
59719
+ ...KindShape,
59720
+ id: RecordIdSchema
59721
+ }), object({
59722
+ deleted: boolean(),
59723
+ secretRefs: SecretRefsList
59724
+ }), {
59725
+ kind: "mutation",
59726
+ auth: "admin"
59727
+ }), method(object({
59728
+ ...KindShape,
59729
+ ids: array(RecordIdSchema).min(1).max(RECORD_BATCH_MAX)
59730
+ }), object({
59731
+ deleted: number().int(),
59732
+ secretRefs: SecretRefsList
59733
+ }), {
59734
+ kind: "mutation",
59735
+ auth: "admin"
59736
+ }), method(RecordQueryInputSchema, RecordQueryResultSchema, { auth: "admin" }), method(object({
59737
+ ...KindShape,
59738
+ ...TimeWindowShape,
59739
+ where: RecordWhereSchema.optional()
59740
+ }), object({ count: number().int() }), { auth: "admin" }), method(object({
59741
+ ...KindShape,
59742
+ deviceId: number().int().optional(),
59743
+ from: number(),
59744
+ to: number(),
59745
+ bucketMs: number().int().positive()
59746
+ }), object({ buckets: array(object({
59747
+ bucketStart: number(),
59748
+ count: number().int()
59749
+ })) }), { auth: "admin" }), method(object({
59750
+ ...KindShape,
59751
+ op: _enum([
59752
+ "sum",
59753
+ "min",
59754
+ "max",
59755
+ "count"
59756
+ ]),
59757
+ field: RecordFieldPathSchema.optional(),
59758
+ groupBy: RecordFieldPathSchema.optional(),
59759
+ where: RecordWhereSchema.optional()
59760
+ }), object({ rows: array(object({
59761
+ group: union([
59762
+ string(),
59763
+ number(),
59764
+ _null()
59765
+ ]),
59766
+ value: number().nullable()
59767
+ })) }), { auth: "admin" }), method(object({
59768
+ ...KindShape,
59769
+ deviceId: number().int().optional(),
59770
+ atBefore: number().optional(),
59771
+ where: RecordWhereSchema.optional()
59772
+ }), object({
59773
+ deleted: number().int(),
59774
+ secretRefs: SecretRefsList
59775
+ }), {
59776
+ kind: "mutation",
59777
+ auth: "admin"
59778
+ }), method(object({ ops: array(RecordTransactOpSchema).min(1).max(RECORD_BATCH_MAX) }), object({
59779
+ results: array(object({
59780
+ rev: number().int().nullable(),
59781
+ deleted: boolean()
59782
+ })),
59783
+ releasedRefs: SecretRefsList,
59784
+ secretRefs: SecretRefsList
59785
+ }), {
59786
+ kind: "mutation",
59787
+ auth: "admin"
59788
+ }), method(object({
59789
+ deviceId: number().int(),
59790
+ kinds: array(RecordKindNameSchema).optional()
59791
+ }), object({
59792
+ deleted: record(string(), number().int()),
59793
+ secretRefs: SecretRefsList
59794
+ }), {
59795
+ kind: "mutation",
59796
+ auth: "admin"
59797
+ }), method(object(KindShape), object({ id: number().int() }), {
59798
+ kind: "mutation",
59799
+ auth: "admin"
59800
+ });
59801
+ /**
59802
+ * The wire shapes of the migration API, version 1 (planning#447).
59803
+ *
59804
+ * A migration is code that outlives the server it was written against: an addon at
59805
+ * version 1.4 that is brought to 1.9 in one jump still runs its 1.4 catalogue, against
59806
+ * the 1.9 kernel. The only thing that code may call is {@link MigrationApiV1}; this file
59807
+ * is the contract of every method of it, one Zod pair per method.
59808
+ *
59809
+ * APPEND-ONLY. A released method is never removed and never changes meaning: an input
59810
+ * field is never removed or made required, an enum never narrows, an output field is
59811
+ * never removed. A change that cannot be expressed that way is `migration-api.v2`, next
59812
+ * to this file. `scripts/check-migration-api-append-only.ts` holds the line against
59813
+ * `scripts/migration-api-contract.json`, and every `behaviours` id below must have an
59814
+ * `it('<id>'` in `migration-api.contract.spec.ts`.
59815
+ */
59816
+ var Rows = record(string(), unknown());
59817
+ var IntegrationId = object({ integrationId: string().min(1) });
59818
+ var RecordId = object({ id: string().min(1) });
59819
+ var RecordRowSchema = object({
59820
+ id: string(),
59821
+ deviceId: number().int().nullable(),
59822
+ at: number().nullable(),
59823
+ expiresAt: number().nullable(),
59824
+ rev: number().int(),
59825
+ updatedAt: number(),
59826
+ data: Rows
59827
+ });
59828
+ var RecordPutShape = {
59829
+ id: string().min(1),
59830
+ deviceId: number().int().optional(),
59831
+ at: number().int().optional(),
59832
+ expiresAt: number().int().optional(),
59833
+ data: Rows
59834
+ };
59835
+ var MigrationIntegrationSchema = object({
59836
+ id: string(),
59837
+ addonId: string(),
59838
+ name: string(),
59839
+ info: Rows,
59840
+ /** The registry's stored switch: read by the one-switch migration, nothing else. */
59841
+ enabled: boolean().optional(),
59842
+ originStableId: string().optional()
59843
+ });
59844
+ var MigrationDeviceSchema = object({
59845
+ id: number().int(),
59846
+ integrationId: string().nullable().optional(),
59847
+ /** The owning device; null or absent for a root. */
59848
+ parentDeviceId: number().int().nullable().optional(),
59849
+ type: string().optional(),
59850
+ name: string().optional(),
59851
+ stableId: string().optional()
59852
+ });
59853
+ /** What the engine says about the migration API it serves: lets an addon notice an older server. */
59854
+ var MigrationApiInfoSchema = object({
59855
+ version: number().int(),
59856
+ methods: array(string())
59857
+ });
59858
+ object({
59859
+ message: string(),
59860
+ meta: Rows.optional(),
59861
+ /** Grouping tags of the line; a line about a device carries `{ deviceId }`. */
59862
+ tags: object({ deviceId: number().int().optional() }).optional()
59863
+ });
59864
+ object({
59865
+ owner: string().min(1),
59866
+ metas: array(MigrationMetaSchema)
59867
+ }), object({
59868
+ bootId: string(),
59869
+ snapshot: _enum([
59870
+ "none",
59871
+ "written",
59872
+ "refused"
59873
+ ]),
59874
+ steps: array(MigrationOwnerStepSchema),
59875
+ /** The migration API the engine serves; absent from a server that predates it. */
59876
+ migrationApi: MigrationApiInfoSchema.optional()
59877
+ }), object({ id: string().min(1) }), object({
59878
+ proceed: boolean(),
59879
+ state: union([literal("pending"), MigrationStatusSchema]),
59880
+ reason: string().nullable()
59881
+ }), object({
59882
+ id: string().min(1),
59883
+ result: MigrationOwnerResultSchema
59884
+ }), object({
59885
+ status: MigrationStatusSchema,
59886
+ error: string().nullable(),
59887
+ rowsChanged: number().int().nonnegative()
59888
+ }), object({
59889
+ rows: number().int().nonnegative(),
59890
+ secrets: number().int().nonnegative()
59891
+ }), IntegrationId.extend({ patch: Rows }), object({ written: boolean() }), IntegrationId.extend({ keys: array(string().min(1)) }), object({
59892
+ present: boolean(),
59893
+ removed: Rows
59894
+ }), RecordRowSchema.nullable(), RecordRowSchema.nullable(), object({
59895
+ ...RecordPutShape,
59896
+ ifRev: number().int().optional()
59897
+ }), object({ rev: number().int() }), object({ records: array(object(RecordPutShape)) }), object({ count: number().int().nonnegative() }), RecordId.extend({
59898
+ partial: Rows,
59899
+ ifRev: number().int().optional()
59900
+ }), object({ rev: number().int() }), object({ deleted: boolean() }), object({
59901
+ deviceId: number().int().optional(),
59902
+ atFrom: number().optional(),
59903
+ atTo: number().optional(),
59904
+ where: RecordWhereSchema.optional(),
59905
+ limit: number().int().min(1).optional(),
59906
+ cursor: string().min(1).optional(),
59907
+ resolveSecrets: boolean().optional()
59908
+ }), object({
59909
+ records: array(RecordRowSchema),
59910
+ nextCursor: string().nullable()
59911
+ }), object({
59912
+ deviceId: number().int().optional(),
59913
+ atBefore: number().optional(),
59914
+ where: RecordWhereSchema.optional()
59915
+ }), object({ count: number().int().nonnegative() }), object({}), object({ store: Rows }), object({ patch: Rows }), object({}), object({ keys: array(string().min(1)) }), object({ removed: array(string()) }), object({ refs: array(string()) }), object({ values: record(string(), string().nullable()) }), object({
59916
+ ref: string().min(1),
59917
+ value: string()
59918
+ }), object({}), object({ refs: array(string()) }), object({ deleted: number().int().nonnegative() }), object({}), object({ integrations: array(MigrationIntegrationSchema) }), object({ id: string().min(1) }), MigrationIntegrationSchema.nullable(), object({
59919
+ addonId: string().min(1),
59920
+ integrationId: string().min(1).optional()
59921
+ }), object({ devices: array(MigrationDeviceSchema) }), object({ deviceId: number().int() }), object({
59922
+ id: number().int(),
59923
+ integrationId: string().nullable(),
59924
+ /** Whether the device carries any stored config; its content is not offered. */
59925
+ hasConfig: boolean()
59926
+ }).nullable(), object({
59927
+ deviceId: number().int(),
59928
+ integrationId: string().min(1)
59929
+ }), object({}), object({}), object({ nodeId: string() }), object({}), object({});
59252
59930
  method(object({}), object({ entries: array(MigrationLedgerEntrySchema) }), { auth: "admin" }), method(object({ owner: string().optional() }), object({ pending: array(MigrationPendingEntrySchema) }), { auth: "admin" }), method(object({ id: string().min(1) }), MigrationDryRunResultSchema, { auth: "admin" }), method(object({
59253
59931
  id: string().min(1),
59254
59932
  error: string().min(1)
@@ -59278,7 +59956,9 @@ method(object({}), object({ entries: array(MigrationLedgerEntrySchema) }), { aut
59278
59956
  "written",
59279
59957
  "refused"
59280
59958
  ]),
59281
- steps: array(MigrationOwnerStepSchema)
59959
+ steps: array(MigrationOwnerStepSchema),
59960
+ /** The migration API this engine serves (additive: a server that predates it omits it). */
59961
+ migrationApi: MigrationApiInfoSchema.optional()
59282
59962
  }), {
59283
59963
  kind: "mutation",
59284
59964
  auth: "admin"
@@ -59299,6 +59979,27 @@ method(object({}), object({ entries: array(MigrationLedgerEntrySchema) }), { aut
59299
59979
  }), {
59300
59980
  kind: "mutation",
59301
59981
  auth: "admin"
59982
+ }), method(object({ integrationId: string().min(1) }), record(string(), unknown()), { auth: "admin" }), method(object({ integrationId: string().min(1) }), object({
59983
+ rows: number().int().nonnegative(),
59984
+ secrets: number().int().nonnegative()
59985
+ }), {
59986
+ kind: "mutation",
59987
+ auth: "admin"
59988
+ }), method(object({
59989
+ integrationId: string().min(1),
59990
+ patch: record(string(), unknown())
59991
+ }), object({ written: boolean() }), {
59992
+ kind: "mutation",
59993
+ auth: "admin"
59994
+ }), method(object({
59995
+ integrationId: string().min(1),
59996
+ keys: array(string().min(1))
59997
+ }), object({
59998
+ present: boolean(),
59999
+ removed: record(string(), unknown())
60000
+ }), {
60001
+ kind: "mutation",
60002
+ auth: "admin"
59302
60003
  });
59303
60004
  method(object({
59304
60005
  sourceUrl: string(),
@@ -61924,7 +62625,10 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
61924
62625
  }), method(RelocateMediaInputSchema, object({ jobId: string() }), {
61925
62626
  kind: "mutation",
61926
62627
  auth: "admin"
61927
- }), method(object({}), UnstampedEventMediaCountSchema, { auth: "admin" }), method(RelocatableMediaCountInputSchema, RelocatableMediaCountSchema, {
62628
+ }), method(object({}), UnstampedEventMediaCountSchema, { auth: "admin" }), method(MediaLocationCensusInputSchema, MediaLocationCensusSchema, {
62629
+ kind: "query",
62630
+ auth: "admin"
62631
+ }), method(RelocatableMediaCountInputSchema, RelocatableMediaCountSchema, {
61928
62632
  kind: "query",
61929
62633
  auth: "admin"
61930
62634
  }), method(object({}), array(RelocateJobSchema).readonly(), {
@@ -64579,7 +65283,7 @@ var BrokerStatusSchema$1 = _enum([
64579
65283
  "unreachable",
64580
65284
  "tls-error"
64581
65285
  ]);
64582
- var BrokerInfoSchema$1 = object({
65286
+ var BrokerInfoSchema = object({
64583
65287
  id: string(),
64584
65288
  name: string(),
64585
65289
  url: string(),
@@ -64642,7 +65346,7 @@ var StatusSchema = object({
64642
65346
  brokerCount: number(),
64643
65347
  embeddedRunning: boolean()
64644
65348
  });
64645
- method(_void(), array(BrokerInfoSchema$1)), method(IdInputSchema, BrokerConnectionDetailsSchema, { auth: "admin" }), method(AddBrokerInputSchema, AddBrokerResultSchema, {
65349
+ method(_void(), array(BrokerInfoSchema)), method(IdInputSchema, BrokerConnectionDetailsSchema, { auth: "admin" }), method(AddBrokerInputSchema, AddBrokerResultSchema, {
64646
65350
  kind: "mutation",
64647
65351
  auth: "admin"
64648
65352
  }), method(IdInputSchema, _void(), {
@@ -69264,14 +69968,6 @@ var PetFountainStatusSchema = object({
69264
69968
  empty: boolean().nullable(),
69265
69969
  /** True while the pump is running. Null while unknown. */
69266
69970
  pumpRunning: boolean().nullable(),
69267
- /** Water drunk in the last drink, in litres. */
69268
- lastDrink: number().min(0).nullable().meta(readingMeta("volume")),
69269
- /** Water drunk in the current hour, in litres. */
69270
- currentHourDrink: number().min(0).nullable().meta(readingMeta("volume")),
69271
- /** Water drunk over the last 24 hours (rolling), in litres. */
69272
- last24hDrink: number().min(0).nullable().meta(readingMeta("volume")),
69273
- /** Water drunk since local midnight, in litres. Null when the fountain has no such sensor. */
69274
- todayDrink: number().min(0).nullable().meta(readingMeta("volume")),
69275
69971
  /** Decoded fault message. Null means healthy; a non-null string is an active fault. */
69276
69972
  error: string().nullable(),
69277
69973
  /** Ms epoch when the slice was last refreshed. */
@@ -69284,21 +69980,15 @@ var petFountainCapability = {
69284
69980
  deviceNative: true,
69285
69981
  mode: "singleton",
69286
69982
  deviceTypes: [DeviceType.PetFountain],
69287
- methods: {
69288
- /** Start or stop the pump. */
69289
- setPump: method(object({
69290
- deviceId: DeviceIdSchema$1,
69291
- on: boolean()
69292
- }), _void(), {
69293
- kind: "mutation",
69294
- auth: "protected"
69295
- }),
69296
- /** Clear the rolling daily consumption counters on the device. */
69297
- resetDailyConsumption: method(object({ deviceId: DeviceIdSchema$1 }), _void(), {
69298
- kind: "mutation",
69299
- auth: "protected"
69300
- })
69301
- },
69983
+ methods: {
69984
+ /** Start or stop the pump. */
69985
+ setPump: method(object({
69986
+ deviceId: DeviceIdSchema$1,
69987
+ on: boolean()
69988
+ }), _void(), {
69989
+ kind: "mutation",
69990
+ auth: "protected"
69991
+ }) },
69302
69992
  status: {
69303
69993
  schema: PetFountainStatusSchema,
69304
69994
  kind: "push"
@@ -69322,14 +70012,6 @@ var petFountainCapability = {
69322
70012
  waterVolume: {
69323
70013
  kind: "gauge",
69324
70014
  unit: "L"
69325
- },
69326
- todayDrink: {
69327
- kind: "gauge",
69328
- unit: "L"
69329
- },
69330
- last24hDrink: {
69331
- kind: "gauge",
69332
- unit: "L"
69333
70015
  }
69334
70016
  } }
69335
70017
  };
@@ -71824,253 +72506,6 @@ DeviceType.Camera, DeviceType.Sensor, DeviceType.Switch, DeviceType.Gateway, met
71824
72506
  auth: "admin"
71825
72507
  });
71826
72508
  /**
71827
- * records - an addon's own facts and documents (D881): ledgers, audit rows,
71828
- * config documents, mirrors. The third storage API next to `ctx.settings`
71829
- * (operator intent, D870) and device-history (numbers over time, D850).
71830
- *
71831
- * Who the OWNER is: `callerAddonId`, stamped by the transport on a call that
71832
- * crossed a process and stated by a hub in-process caller (`ctx.records` does
71833
- * that with the addon id closed over). It is deliberately NOT in any input
71834
- * schema, so a session can never supply it, and a call with no stamp is refused
71835
- * `records/no-caller`. A kind is readable and writable only by its owner; other
71836
- * addons go through the owner's capability.
71837
- *
71838
- * Every read is three-way: a row, `null`, or the call THROWS. A failed read is
71839
- * never `[]`. Secret fields are never on the wire: a read shows the
71840
- * redaction token, `secretRefs` hands the owner's `ctx.secrets` the refs it
71841
- * resolves itself, and a write may carry only a keychain marker bound to the
71842
- * row's own ref.
71843
- *
71844
- * Internal: addons reach it through `ctx.records`, never directly.
71845
- */
71846
- var RecordIdSchema = string().min(1).max(256);
71847
- /** A JSON object body. Size is the engine's check (`maxDataBytes`), not a schema's. */
71848
- var RecordBodySchema = record(string(), unknown());
71849
- var RecordInputSchema = object({
71850
- id: RecordIdSchema,
71851
- /** The device this row belongs to (D865 removal, per-device reads). */
71852
- deviceId: number().int().optional(),
71853
- /** The domain clock, ms: observed / created / opened. */
71854
- at: number().int().optional(),
71855
- /** Producer-set expiry, ms. Refused on a kind whose retention is an engine TTL. */
71856
- expiresAt: number().int().optional(),
71857
- data: RecordBodySchema
71858
- });
71859
- var RecordViewSchema = object({
71860
- id: string(),
71861
- deviceId: number().int().nullable(),
71862
- at: number().nullable(),
71863
- expiresAt: number().nullable(),
71864
- rev: number().int(),
71865
- updatedAt: number(),
71866
- data: RecordBodySchema
71867
- });
71868
- /** Declared index fields only. Anything else does not compile, by design. */
71869
- var RecordWhereSchema = record(RecordFieldPathSchema, union([
71870
- string(),
71871
- number(),
71872
- boolean(),
71873
- object({ in: array(union([
71874
- string(),
71875
- number(),
71876
- boolean()
71877
- ])).min(1).max(RECORD_BATCH_MAX) }),
71878
- object({
71879
- gt: union([string(), number()]).optional(),
71880
- gte: union([string(), number()]).optional(),
71881
- lt: union([string(), number()]).optional(),
71882
- lte: union([string(), number()]).optional()
71883
- }).refine((r) => Object.keys(r).length > 0, { message: "name at least one bound" })
71884
- ]));
71885
- var KindShape = { kind: RecordKindNameSchema };
71886
- var TimeWindowShape = {
71887
- deviceId: number().int().optional(),
71888
- atFrom: number().optional(),
71889
- atTo: number().optional()
71890
- };
71891
- var RecordQueryInputSchema = object({
71892
- ...KindShape,
71893
- ...TimeWindowShape,
71894
- where: RecordWhereSchema.optional(),
71895
- /** Without `where`: `at` (default for a kind with a clock) or `id`. With `where` the order is the index's. */
71896
- order: _enum(["at", "id"]).optional(),
71897
- desc: boolean().optional(),
71898
- limit: number().int().min(1).max(RECORD_QUERY_MAX).default(100),
71899
- /** Opaque keyset cursor from a previous answer. There is no offset. */
71900
- cursor: string().min(1).optional()
71901
- });
71902
- var RecordQueryResultSchema = object({
71903
- records: array(RecordViewSchema),
71904
- nextCursor: string().nullable()
71905
- });
71906
- var RecordKindStateSchema = _enum([
71907
- "created",
71908
- "unchanged",
71909
- "updated"
71910
- ]);
71911
- var DeclareKindResultSchema = object({
71912
- kindId: number().int(),
71913
- state: RecordKindStateSchema,
71914
- createdIndexes: array(string())
71915
- });
71916
- /** Keychain refs a write released (the old marker is gone from the row): the owner deletes the values. */
71917
- var SecretRefsList = array(string());
71918
- /**
71919
- * One op of a `transact`: the single-row writes, each on a kind of the caller.
71920
- * All ops of one call share ONE database file and ONE `transactFamily`.
71921
- */
71922
- var RecordTransactOpSchema = discriminatedUnion("op", [
71923
- object({
71924
- op: literal("put"),
71925
- kind: RecordKindNameSchema,
71926
- record: RecordInputSchema,
71927
- ifRev: number().int().min(0).optional()
71928
- }),
71929
- object({
71930
- op: literal("patch"),
71931
- kind: RecordKindNameSchema,
71932
- id: RecordIdSchema,
71933
- data: RecordBodySchema,
71934
- at: number().int().nullable().optional(),
71935
- expiresAt: number().int().nullable().optional(),
71936
- ifRev: number().int().min(1).optional()
71937
- }),
71938
- object({
71939
- op: literal("delete"),
71940
- kind: RecordKindNameSchema,
71941
- id: RecordIdSchema
71942
- })
71943
- ]);
71944
- var RecordSecretRefsSchema = record(string(), record(string(), string()));
71945
- method(object({ kinds: record(RecordKindNameSchema, RecordKindDeclarationSchema) }), object({ kinds: record(string(), DeclareKindResultSchema) }), {
71946
- kind: "mutation",
71947
- auth: "admin"
71948
- }), method(object({
71949
- ...KindShape,
71950
- id: RecordIdSchema
71951
- }), RecordViewSchema.nullable(), { auth: "admin" }), method(object({
71952
- ...KindShape,
71953
- ids: array(RecordIdSchema).min(1).max(RECORD_BATCH_MAX)
71954
- }), array(RecordViewSchema), { auth: "admin" }), method(object({
71955
- ...KindShape,
71956
- ids: array(RecordIdSchema).min(1).max(RECORD_BATCH_MAX)
71957
- }), RecordSecretRefsSchema, { auth: "admin" }), method(object({
71958
- ...KindShape,
71959
- record: RecordInputSchema,
71960
- /** Compare-and-set. `0` means "the row must not exist". */
71961
- ifRev: number().int().min(0).optional()
71962
- }), object({
71963
- rev: number().int(),
71964
- releasedRefs: SecretRefsList
71965
- }), {
71966
- kind: "mutation",
71967
- auth: "admin"
71968
- }), method(object({
71969
- ...KindShape,
71970
- records: array(RecordInputSchema).min(1).max(RECORD_BATCH_MAX)
71971
- }), object({
71972
- count: number().int(),
71973
- releasedRefs: SecretRefsList
71974
- }), {
71975
- kind: "mutation",
71976
- auth: "admin"
71977
- }), method(object({
71978
- ...KindShape,
71979
- id: RecordIdSchema,
71980
- data: RecordBodySchema,
71981
- at: number().int().nullable().optional(),
71982
- expiresAt: number().int().nullable().optional(),
71983
- ifRev: number().int().min(1).optional()
71984
- }), object({
71985
- rev: number().int(),
71986
- releasedRefs: SecretRefsList
71987
- }), {
71988
- kind: "mutation",
71989
- auth: "admin"
71990
- }), method(object({
71991
- ...KindShape,
71992
- id: RecordIdSchema
71993
- }), object({
71994
- deleted: boolean(),
71995
- secretRefs: SecretRefsList
71996
- }), {
71997
- kind: "mutation",
71998
- auth: "admin"
71999
- }), method(object({
72000
- ...KindShape,
72001
- ids: array(RecordIdSchema).min(1).max(RECORD_BATCH_MAX)
72002
- }), object({
72003
- deleted: number().int(),
72004
- secretRefs: SecretRefsList
72005
- }), {
72006
- kind: "mutation",
72007
- auth: "admin"
72008
- }), method(RecordQueryInputSchema, RecordQueryResultSchema, { auth: "admin" }), method(object({
72009
- ...KindShape,
72010
- ...TimeWindowShape,
72011
- where: RecordWhereSchema.optional()
72012
- }), object({ count: number().int() }), { auth: "admin" }), method(object({
72013
- ...KindShape,
72014
- deviceId: number().int().optional(),
72015
- from: number(),
72016
- to: number(),
72017
- bucketMs: number().int().positive()
72018
- }), object({ buckets: array(object({
72019
- bucketStart: number(),
72020
- count: number().int()
72021
- })) }), { auth: "admin" }), method(object({
72022
- ...KindShape,
72023
- op: _enum([
72024
- "sum",
72025
- "min",
72026
- "max",
72027
- "count"
72028
- ]),
72029
- field: RecordFieldPathSchema.optional(),
72030
- groupBy: RecordFieldPathSchema.optional(),
72031
- where: RecordWhereSchema.optional()
72032
- }), object({ rows: array(object({
72033
- group: union([
72034
- string(),
72035
- number(),
72036
- _null()
72037
- ]),
72038
- value: number().nullable()
72039
- })) }), { auth: "admin" }), method(object({
72040
- ...KindShape,
72041
- deviceId: number().int().optional(),
72042
- atBefore: number().optional(),
72043
- where: RecordWhereSchema.optional()
72044
- }), object({
72045
- deleted: number().int(),
72046
- secretRefs: SecretRefsList
72047
- }), {
72048
- kind: "mutation",
72049
- auth: "admin"
72050
- }), method(object({ ops: array(RecordTransactOpSchema).min(1).max(RECORD_BATCH_MAX) }), object({
72051
- results: array(object({
72052
- rev: number().int().nullable(),
72053
- deleted: boolean()
72054
- })),
72055
- releasedRefs: SecretRefsList,
72056
- secretRefs: SecretRefsList
72057
- }), {
72058
- kind: "mutation",
72059
- auth: "admin"
72060
- }), method(object({
72061
- deviceId: number().int(),
72062
- kinds: array(RecordKindNameSchema).optional()
72063
- }), object({
72064
- deleted: record(string(), number().int()),
72065
- secretRefs: SecretRefsList
72066
- }), {
72067
- kind: "mutation",
72068
- auth: "admin"
72069
- }), method(object(KindShape), object({ id: number().int() }), {
72070
- kind: "mutation",
72071
- auth: "admin"
72072
- });
72073
- /**
72074
72509
  * record-entries - the ONE admin surface for every list of user-created entries
72075
72510
  * (D881): notification targets, brokers, LLM profiles, anything an addon
72076
72511
  * declares as an ENTRY kind (`entry: { title }` in `defineRecordKinds`).
@@ -80717,11 +81152,15 @@ discriminatedUnion("kind", [object({
80717
81152
  * 1. idle floor F = time-weighted median; noise ceiling N = highest value seen
80718
81153
  * near F. A device that is not near one level most of the time has no floor.
80719
81154
  * 2. coarse activity = above max(2N, N + 5 W); consecutive stretches are episodes.
80720
- * 3. gaps between episodes split in two by the largest log-scale jump (>= 3x):
80721
- * the short ones are pauses INSIDE a run (a soak), the long ones separate runs.
81155
+ * 3. an episode shorter than `PULSE_MAX_MS` is a PULSE (an anti-crease tumble, a
81156
+ * display waking): it is neither a run nor a pause. Among the remaining
81157
+ * episodes, gaps over `PAUSE_MAX_MS` always separate runs; the rest split in
81158
+ * two by the largest log-scale jump (>= 3x): the short ones are pauses INSIDE
81159
+ * a run (a soak), the long ones separate runs. A stretch under `MIN_RUN_MS`
81160
+ * is no run.
80722
81161
  * 4. T = geometric mean of N and the plateau's 10th percentile, snapped to a
80723
- * grid a person would type; stop dwell covers the longest pause; start dwell
80724
- * covers the longest standby blip above T.
81162
+ * grid a person would type; stop dwell covers the longest pause and the
81163
+ * kind's floor; start dwell covers the longest pulse and standby blip above T.
80725
81164
  * 5. the numbers are proved by REPLAY through the real `dwell` evaluation: each
80726
81165
  * run must hold exactly one true interval and nothing may flap outside.
80727
81166
  */
@@ -80732,6 +81171,10 @@ var MINUTE_MS$1 = 60 * SECOND_MS;
80732
81171
  30 * SECOND_MS;
80733
81172
  60 * SECOND_MS;
80734
81173
  20 * MINUTE_MS$1;
81174
+ 90 * SECOND_MS;
81175
+ 30 * MINUTE_MS$1;
81176
+ 10 * MINUTE_MS$1;
81177
+ DeviceType.Dryer, 3 * MINUTE_MS$1, DeviceType.Dishwasher, 3 * MINUTE_MS$1, DeviceType.Washer, 10 * MINUTE_MS$1;
80735
81178
  10 * SECOND_MS;
80736
81179
  10 * SECOND_MS;
80737
81180
  DeviceFeature.FanSpeed, DeviceFeature.FanPreset, DeviceFeature.FanDirection, DeviceFeature.FanOscillating, DeviceFeature.CoverStoppable, DeviceFeature.CoverPositionable, DeviceFeature.CoverTilt, DeviceFeature.ValvePositionable, DeviceFeature.MediaPlayerVolume, DeviceFeature.ClimateFanMode;
@@ -81882,7 +82325,7 @@ var BaseDeviceProvider = class extends BaseAddon {
81882
82325
  * `deviceClasses` map (first registered type). `null` when manual creation is
81883
82326
  * unsupported. Lets the Add-Device dialog pick the right type per provider.
81884
82327
  */
81885
- async getManualCreationType() {
82328
+ async getManualCreationType(_input) {
81886
82329
  if (!await this.supportsManualCreation()) return { deviceType: null };
81887
82330
  return { deviceType: Object.values(DeviceType).find((t) => this.deviceClasses[t] !== void 0) ?? null };
81888
82331
  }
@@ -81893,7 +82336,7 @@ var BaseDeviceProvider = class extends BaseAddon {
81893
82336
  return true;
81894
82337
  }
81895
82338
  async getChildCreationSchema(input) {
81896
- return this.onGetCreationSchema(input.type);
82339
+ return this.onGetCreationSchema(input.type, { integrationId: input.integrationId });
81897
82340
  }
81898
82341
  /**
81899
82342
  * Default kernel-orchestrated `createDevice` implementation. The
@@ -81905,7 +82348,7 @@ var BaseDeviceProvider = class extends BaseAddon {
81905
82348
  * `deviceClasses` instead.
81906
82349
  */
81907
82350
  async createDevice(input) {
81908
- const spec = await this.onCreateDevice(input.type, input.config);
82351
+ const spec = await this.onCreateDevice(input.type, input.config, { ...input.integrationId !== void 0 ? { integrationId: input.integrationId } : {} });
81909
82352
  const Class = this.deviceClasses[spec.meta.type];
81910
82353
  if (!Class) throw new Error(`${this.providerName} provider: no device class registered for type "${spec.meta.type}" — add it to the deviceClasses map`);
81911
82354
  const stableId = this.generateStableId(spec.meta.type, spec.config);
@@ -83314,20 +83757,6 @@ Object.freeze({
83314
83757
  access: "create",
83315
83758
  role: "viewer"
83316
83759
  },
83317
- "broker.add": {
83318
- capName: "broker",
83319
- capScope: "system",
83320
- addonId: null,
83321
- access: "create",
83322
- role: "admin"
83323
- },
83324
- "broker.get": {
83325
- capName: "broker",
83326
- capScope: "system",
83327
- addonId: null,
83328
- access: "view",
83329
- role: "admin"
83330
- },
83331
83760
  "broker.getBrokerConfig": {
83332
83761
  capName: "broker",
83333
83762
  capScope: "system",
@@ -83335,20 +83764,6 @@ Object.freeze({
83335
83764
  access: "view",
83336
83765
  role: "admin"
83337
83766
  },
83338
- "broker.getSettings": {
83339
- capName: "broker",
83340
- capScope: "system",
83341
- addonId: null,
83342
- access: "view",
83343
- role: "admin"
83344
- },
83345
- "broker.getSettingsSchema": {
83346
- capName: "broker",
83347
- capScope: "system",
83348
- addonId: null,
83349
- access: "view",
83350
- role: "admin"
83351
- },
83352
83767
  "broker.getState": {
83353
83768
  capName: "broker",
83354
83769
  capScope: "system",
@@ -83363,20 +83778,6 @@ Object.freeze({
83363
83778
  access: "view",
83364
83779
  role: "admin"
83365
83780
  },
83366
- "broker.list": {
83367
- capName: "broker",
83368
- capScope: "system",
83369
- addonId: null,
83370
- access: "view",
83371
- role: "admin"
83372
- },
83373
- "broker.listProviders": {
83374
- capName: "broker",
83375
- capScope: "system",
83376
- addonId: null,
83377
- access: "view",
83378
- role: "admin"
83379
- },
83380
83781
  "broker.publish": {
83381
83782
  capName: "broker",
83382
83783
  capScope: "system",
@@ -83384,20 +83785,6 @@ Object.freeze({
83384
83785
  access: "create",
83385
83786
  role: "admin"
83386
83787
  },
83387
- "broker.remove": {
83388
- capName: "broker",
83389
- capScope: "system",
83390
- addonId: null,
83391
- access: "delete",
83392
- role: "admin"
83393
- },
83394
- "broker.setSettings": {
83395
- capName: "broker",
83396
- capScope: "system",
83397
- addonId: null,
83398
- access: "create",
83399
- role: "admin"
83400
- },
83401
83788
  "broker.subscribe": {
83402
83789
  capName: "broker",
83403
83790
  capScope: "system",
@@ -83405,20 +83792,6 @@ Object.freeze({
83405
83792
  access: "create",
83406
83793
  role: "admin"
83407
83794
  },
83408
- "broker.testConnection": {
83409
- capName: "broker",
83410
- capScope: "system",
83411
- addonId: null,
83412
- access: "create",
83413
- role: "admin"
83414
- },
83415
- "broker.testSettings": {
83416
- capName: "broker",
83417
- capScope: "system",
83418
- addonId: null,
83419
- access: "create",
83420
- role: "admin"
83421
- },
83422
83795
  "broker.unsubscribe": {
83423
83796
  capName: "broker",
83424
83797
  capScope: "system",
@@ -86016,13 +86389,6 @@ Object.freeze({
86016
86389
  access: "create",
86017
86390
  role: "admin"
86018
86391
  },
86019
- "integrations.clearSettings": {
86020
- capName: "integrations",
86021
- capScope: "system",
86022
- addonId: null,
86023
- access: "delete",
86024
- role: "admin"
86025
- },
86026
86392
  "integrations.create": {
86027
86393
  capName: "integrations",
86028
86394
  capScope: "system",
@@ -86058,13 +86424,6 @@ Object.freeze({
86058
86424
  access: "view",
86059
86425
  role: "admin"
86060
86426
  },
86061
- "integrations.getSettings": {
86062
- capName: "integrations",
86063
- capScope: "system",
86064
- addonId: null,
86065
- access: "view",
86066
- role: "admin"
86067
- },
86068
86427
  "integrations.list": {
86069
86428
  capName: "integrations",
86070
86429
  capScope: "system",
@@ -86072,13 +86431,6 @@ Object.freeze({
86072
86431
  access: "view",
86073
86432
  role: "admin"
86074
86433
  },
86075
- "integrations.setSettings": {
86076
- capName: "integrations",
86077
- capScope: "system",
86078
- addonId: null,
86079
- access: "create",
86080
- role: "admin"
86081
- },
86082
86434
  "integrations.testConnection": {
86083
86435
  capName: "integrations",
86084
86436
  capScope: "system",
@@ -87073,6 +87425,13 @@ Object.freeze({
87073
87425
  access: "view",
87074
87426
  role: "admin"
87075
87427
  },
87428
+ "migrations.clearLegacyIntegrationRows": {
87429
+ capName: "migrations",
87430
+ capScope: "system",
87431
+ addonId: null,
87432
+ access: "delete",
87433
+ role: "admin"
87434
+ },
87076
87435
  "migrations.declareOwner": {
87077
87436
  capName: "migrations",
87078
87437
  capScope: "system",
@@ -87080,6 +87439,13 @@ Object.freeze({
87080
87439
  access: "create",
87081
87440
  role: "admin"
87082
87441
  },
87442
+ "migrations.deleteLegacyIntegrationRowKeys": {
87443
+ capName: "migrations",
87444
+ capScope: "system",
87445
+ addonId: null,
87446
+ access: "delete",
87447
+ role: "admin"
87448
+ },
87083
87449
  "migrations.dryRun": {
87084
87450
  capName: "migrations",
87085
87451
  capScope: "system",
@@ -87115,6 +87481,20 @@ Object.freeze({
87115
87481
  access: "create",
87116
87482
  role: "admin"
87117
87483
  },
87484
+ "migrations.patchLegacyIntegrationRows": {
87485
+ capName: "migrations",
87486
+ capScope: "system",
87487
+ addonId: null,
87488
+ access: "create",
87489
+ role: "admin"
87490
+ },
87491
+ "migrations.readLegacyIntegrationRows": {
87492
+ capName: "migrations",
87493
+ capScope: "system",
87494
+ addonId: null,
87495
+ access: "view",
87496
+ role: "admin"
87497
+ },
87118
87498
  "migrations.restorePreMigration": {
87119
87499
  capName: "migrations",
87120
87500
  capScope: "system",
@@ -88172,13 +88552,6 @@ Object.freeze({
88172
88552
  access: "view",
88173
88553
  role: "viewer"
88174
88554
  },
88175
- "petFountain.resetDailyConsumption": {
88176
- capName: "pet-fountain",
88177
- capScope: "device",
88178
- addonId: null,
88179
- access: "delete",
88180
- role: "viewer"
88181
- },
88182
88555
  "petFountain.setPump": {
88183
88556
  capName: "pet-fountain",
88184
88557
  capScope: "device",
@@ -88375,6 +88748,13 @@ Object.freeze({
88375
88748
  access: "view",
88376
88749
  role: "viewer"
88377
88750
  },
88751
+ "pipelineAnalytics.getMediaLocationCensus": {
88752
+ capName: "pipeline-analytics",
88753
+ capScope: "device",
88754
+ addonId: null,
88755
+ access: "view",
88756
+ role: "admin"
88757
+ },
88378
88758
  "pipelineAnalytics.getMediaReclaimStatus": {
88379
88759
  capName: "pipeline-analytics",
88380
88760
  capScope: "device",
@@ -94568,11 +94948,6 @@ Object.freeze({
94568
94948
  form: "single",
94569
94949
  optional: false
94570
94950
  }],
94571
- "petFountain.resetDailyConsumption": [{
94572
- name: "deviceId",
94573
- form: "single",
94574
- optional: false
94575
- }],
94576
94951
  "petFountain.setPump": [{
94577
94952
  name: "deviceId",
94578
94953
  form: "single",
@@ -125546,8 +125921,13 @@ var HomematicProviderAddon = class extends BaseDeviceProvider {
125546
125921
  await records.declare(homematicRecordKinds);
125547
125922
  const instances = buildHomematicInstances(records, { onChanged: () => this.reconcileIntegrations() });
125548
125923
  this.instances = instances;
125924
+ this.declareRegistrySwitch({
125925
+ kind: homematicConnectionsEntryKind,
125926
+ initialBody: (name) => ({ name })
125927
+ });
125549
125928
  await this.runMigrations(defineAddonMigrations([HOMEMATIC_ROWS_TO_RECORD_MIGRATION], integrationRowsPortsOverApi({
125550
125929
  api: defaultIntegrationApiOver(this.ctx.api),
125930
+ secrets: this.ctx.secrets ?? null,
125551
125931
  records: records.kind({
125552
125932
  name: homematicConnectionsEntryKind.name,
125553
125933
  declaration: homematicConnectionsEntryKind.declaration,
@@ -125780,8 +126160,9 @@ var HomematicProviderAddon = class extends BaseDeviceProvider {
125780
126160
  const integrationId = event.data["integrationId"];
125781
126161
  this.reconciler().onLifecycle(kind, typeof integrationId === "string" ? integrationId : null);
125782
126162
  };
125783
- this.ctx.eventBus.subscribe({ category: EventCategory.IntegrationEnabled }, on("enabled"));
125784
- this.ctx.eventBus.subscribe({ category: EventCategory.IntegrationDisabled }, on("disabled"));
126163
+ this.requireInstances().onSwitched((id, enabled) => {
126164
+ this.reconciler().onLifecycle(enabled ? "enabled" : "disabled", id);
126165
+ });
125785
126166
  this.ctx.eventBus.subscribe({ category: EventCategory.IntegrationDeleted }, on("deleted"));
125786
126167
  }
125787
126168
  /** The integrations that own devices here, for the orphan sweep. */