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