@camstack/addon-provider-enpal 0.1.10 → 0.1.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/addon.js +1532 -1261
  3. package/dist/addon.mjs +1532 -1261
  4. package/package.json +2 -2
package/dist/addon.js CHANGED
@@ -5981,7 +5981,7 @@ var ZodIssueCode = {
5981
5981
  var ZodFirstPartyTypeKind;
5982
5982
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
5983
5983
  //#endregion
5984
- //#region ../types/dist/sleep-DEZaLbiu.mjs
5984
+ //#region ../types/dist/sleep-CmjWurK5.mjs
5985
5985
  /**
5986
5986
  * The audio chunk plane's byte format, and the ONE expansion from a coded
5987
5987
  * window to float samples (D455).
@@ -6665,137 +6665,153 @@ async function runAddonMigrations(host, migrations, logger, options = {}) {
6665
6665
  blockOwner
6666
6666
  };
6667
6667
  }
6668
- /**
6669
- * Build a {@link DurableState} over a single store key. Transport-agnostic:
6670
- * `read`/`write` are the addon-store or device-store accessors. The whole
6671
- * validated value round-trips on every read/write — the schema is the
6672
- * single source of truth for what is persisted, so no hand-listed field
6673
- * set can drop a key on save.
6674
- */
6675
- function createDurableState(deps) {
6676
- const get = async () => {
6677
- const raw = (await deps.read())[deps.key];
6678
- if (raw === void 0) return deps.fallback;
6679
- const parsed = deps.schema.safeParse(raw);
6680
- if (!parsed.success) {
6681
- deps.onParseError?.(deps.key, parsed.error);
6682
- return deps.fallback;
6683
- }
6684
- return parsed.data;
6685
- };
6686
- const set = async (next) => {
6687
- const validated = deps.schema.parse(next);
6688
- await deps.write({ [deps.key]: validated });
6689
- };
6690
- const update = async (fn) => {
6691
- await set(fn(await get()));
6692
- };
6668
+ function secretsOverMigrationApi(api) {
6693
6669
  return {
6694
- get,
6695
- set,
6696
- update
6670
+ resolve: async (refs) => {
6671
+ const { values } = await api.secrets.resolve({ refs: [...refs] });
6672
+ const out = {};
6673
+ for (const ref of refs) {
6674
+ const value = values[ref];
6675
+ out[ref] = value === null || value === void 0 ? { kind: "missing" } : {
6676
+ kind: "value",
6677
+ value,
6678
+ version: 0
6679
+ };
6680
+ }
6681
+ return out;
6682
+ },
6683
+ delete: async (refs) => (await api.secrets.delete({ refs: [...refs] })).deleted
6697
6684
  };
6698
6685
  }
6699
- /**
6700
- * Per-node scoping for the shared addon-settings blob.
6701
- *
6702
- * An addon's settings store is hub-central (the `addon-settings` cap is
6703
- * hub-routed — the hub instance answers for every node), so fields whose
6704
- * value is a NODE fact (decoder backend, engine pick, probed hardware
6705
- * capabilities) persist under the node-scoped key `<key>@<nodeId>` inside
6706
- * the single shared blob. The SCHEMA field key stays bare: the write path
6707
- * ({@link scopePatch}) maps the bare field onto the target node's scoped
6708
- * key; the read/hydrate path ({@link projectStore}) maps THIS node's value
6709
- * back, so UI forms and `resolveConfig` only ever see the bare key.
6710
- *
6711
- * Fields opt in via the `perNode: true` schema marker on `ConfigFieldBase`
6712
- * (`interfaces/config-ui.ts`); `BaseAddon` derives the key set from the
6713
- * schema and routes reads/writes through these helpers.
6714
- *
6715
- * ## No bare-key fallback — deliberate
6716
- *
6717
- * {@link readNodeValue} reads the node-scoped key ONLY. A node with no
6718
- * scoped key resolves to `undefined` so the field's schema `default` wins —
6719
- * NEVER `store[base]` and never another node's value. A bare legacy key in
6720
- * the store is invisible to every node, hub included, so one node's
6721
- * selection can never leak onto another. (This generalizes the
6722
- * `decoder-backend-keys.ts` semantics — the no-fallback variant — over an
6723
- * arbitrary set of per-node field keys.)
6724
- *
6725
- * Pure functions only — no I/O, no imports beyond the language. This is a
6726
- * LEAF module: import it via its deep path, never from the root barrel.
6727
- */
6728
- /**
6729
- * Normalize a raw kernel node id to the bare node id used for scoping.
6730
- * `localNodeId` can carry a `<node>/<addon>` suffix on forked child
6731
- * processes; per-node settings are per-NODE, so strip the addon segment.
6732
- * `undefined` / `null` / empty falls back to `'hub'`.
6733
- */
6734
- function normalizeNodeId(raw) {
6735
- if (raw === void 0 || raw === null || raw === "") return "hub";
6736
- const slashIdx = raw.indexOf("/");
6737
- if (slashIdx < 0) return raw;
6738
- const bare = raw.slice(0, slashIdx);
6739
- return bare === "" ? "hub" : bare;
6686
+ /** The record calls the one-switch migration makes, over the migration API. */
6687
+ function switchRecordsOverMigrationApi(api) {
6688
+ return { kind: (definition) => {
6689
+ const handle = api.records.kind(definition);
6690
+ return {
6691
+ get: (id) => handle.get({ id }),
6692
+ put: (input, opts) => handle.put({
6693
+ ...input,
6694
+ ...opts?.ifRev === void 0 ? {} : { ifRev: opts.ifRev }
6695
+ }),
6696
+ patch: (id, partial) => handle.patch({
6697
+ id,
6698
+ partial
6699
+ })
6700
+ };
6701
+ } };
6740
6702
  }
6741
- /** The node-scoped store key for a per-node field: `<base>@<nodeId>`. */
6742
- function nodeScopedKey(base, nodeId) {
6743
- return `${base}@${normalizeNodeId(nodeId)}`;
6703
+ /** `ctx.records` as the migration API offers it: bind a kind, read and write by id. */
6704
+ function recordsOverMigrationApi(api) {
6705
+ return { kind: (definition) => {
6706
+ const handle = api.records.kind(definition);
6707
+ return {
6708
+ get: (id) => handle.get({ id }),
6709
+ getResolved: (id) => handle.getResolved({ id }),
6710
+ put: (input, opts) => handle.put({
6711
+ ...input,
6712
+ ...opts?.ifRev === void 0 ? {} : { ifRev: opts.ifRev }
6713
+ }),
6714
+ delete: (id) => handle.delete({ id })
6715
+ };
6716
+ } };
6744
6717
  }
6745
- /**
6746
- * Read a node's value for a per-node field from the raw shared store:
6747
- * the node-scoped key when present, otherwise `undefined`.
6748
- * Deliberately NO bare-key fallback (see module doc) — the caller lets the
6749
- * schema `default` win on `undefined`.
6750
- */
6751
- function readNodeValue(store, base, nodeId) {
6752
- return store[nodeScopedKey(base, nodeId)];
6718
+ function integrationRowsApiOver(api) {
6719
+ return {
6720
+ list: async () => (await api.integrations.list({})).integrations,
6721
+ readLegacyIntegrationRows: (input) => api.legacyRows.read(input),
6722
+ clearLegacyIntegrationRows: (input) => api.legacyRows.clear(input)
6723
+ };
6753
6724
  }
6754
6725
  /**
6755
- * Re-map a UI/settings patch so every bare perNode field persists under the
6756
- * TARGET node's scoped key; all other keys pass through unchanged. Used on
6757
- * the write path so a save for one node never clobbers another node's value
6758
- * (and the bare key is never written). Returns a new object — the input
6759
- * patch is not mutated.
6726
+ * One serial lane per migration API: a log line is delivered after the line before it, so the
6727
+ * order the steps wrote them in is the order the hub reads them in. A delivery that fails
6728
+ * is reported once through the same door; if that fails too nothing is left to tell, and the
6729
+ * line is dropped rather than thrown into a migration step or left as an unhandled rejection.
6760
6730
  */
6761
- function scopePatch(patch, perNodeKeys, nodeId) {
6762
- const out = {};
6763
- for (const [key, value] of Object.entries(patch)) out[perNodeKeys.has(key) ? nodeScopedKey(key, nodeId) : key] = value;
6764
- return out;
6731
+ var lanes = /* @__PURE__ */ new WeakMap();
6732
+ function deliver(api, send) {
6733
+ const next = (lanes.get(api) ?? Promise.resolve()).then(send).then(() => void 0).catch(async (error) => {
6734
+ const reason = error instanceof Error ? error.message : String(error);
6735
+ await api.log.warn({ message: `a migration log line could not be delivered: ${reason}` }).catch(() => void 0);
6736
+ });
6737
+ lanes.set(api, next);
6738
+ return next;
6765
6739
  }
6766
- /**
6767
- * Project the raw shared store onto the bare schema keys for ONE node so a
6768
- * UI schema (whose field keys are bare) hydrates from that node's own
6769
- * values:
6770
- *
6771
- * - EVERY `@`-scoped key (any node's) is dropped from the pass-through.
6772
- * - Every bare perNode key is dropped from the pass-through (a stray bare
6773
- * legacy key must never hydrate any node — no bare fallback).
6774
- * - THIS node's effective value ({@link readNodeValue}) is then laid onto
6775
- * each bare perNode key; when the node has no scoped key the bare key is
6776
- * left ABSENT so the field's schema `default` wins.
6777
- *
6778
- * Returns a new object — the input store is not mutated.
6779
- */
6780
- function projectStore(store, perNodeKeys, nodeId) {
6781
- const out = {};
6782
- for (const [key, value] of Object.entries(store)) {
6783
- if (key.includes("@")) continue;
6784
- if (perNodeKeys.has(key)) continue;
6785
- out[key] = value;
6740
+ function warnOver(api) {
6741
+ return (message) => deliver(api, () => api.log.warn({ message }));
6742
+ }
6743
+ /** What the rows-to-records move needs, over the migration API. */
6744
+ function rowsDepsOver(api) {
6745
+ return {
6746
+ api: integrationRowsApiOver(api),
6747
+ records: recordsOverMigrationApi(api),
6748
+ secrets: secretsOverMigrationApi(api),
6749
+ warn: warnOver(api)
6750
+ };
6751
+ }
6752
+ var PREFIX = "records/";
6753
+ /** The base of every records failure. `detail` is the human part of the message. */
6754
+ var RecordsError = class extends Error {
6755
+ code;
6756
+ detail;
6757
+ constructor(code, detail) {
6758
+ super(`${PREFIX}${code}: ${detail}`);
6759
+ this.name = "RecordsError";
6760
+ this.code = code;
6761
+ this.detail = detail;
6786
6762
  }
6787
- for (const base of perNodeKeys) {
6788
- const value = readNodeValue(store, base, nodeId);
6789
- if (value !== void 0) out[base] = value;
6763
+ };
6764
+ /** A write guarded by `ifRev` found another revision (or an existing row for `ifRev: 0`). */
6765
+ var RevConflictError = class extends RecordsError {
6766
+ constructor(detail) {
6767
+ super("rev-conflict", detail);
6768
+ this.name = "RevConflictError";
6790
6769
  }
6791
- return out;
6770
+ };
6771
+ /** The keychain could not store or serve a value: explicit, never an empty string. */
6772
+ var RecordSecretUnavailableError = class extends RecordsError {
6773
+ constructor(detail) {
6774
+ super("secret-unavailable", detail);
6775
+ this.name = "RecordSecretUnavailableError";
6776
+ }
6777
+ };
6778
+ var InvalidRecordError = class extends RecordsError {
6779
+ constructor(detail) {
6780
+ super("invalid-record", detail);
6781
+ this.name = "InvalidRecordError";
6782
+ }
6783
+ };
6784
+ /** A kind declaration the engine refuses (non-additive change, bad shape, wrong file). */
6785
+ var DeclarationRefusedError = class extends RecordsError {
6786
+ constructor(detail) {
6787
+ super("declaration-refused", detail);
6788
+ this.name = "DeclarationRefusedError";
6789
+ }
6790
+ };
6791
+ function linkTargetOf(meta) {
6792
+ if (typeof meta !== "object" || meta === null) return void 0;
6793
+ const link = Reflect.get(meta, "link");
6794
+ const parsed = LinkTargetSchema.safeParse(link);
6795
+ return parsed.success ? parsed.data : void 0;
6796
+ }
6797
+ var LinkTargetSchema = object({
6798
+ cap: string().min(1),
6799
+ kind: string().min(1).optional()
6800
+ });
6801
+ /** The links a kind declares, read from the meta of its body fields. */
6802
+ function linksOfKind(kind) {
6803
+ const schema = kind.schema;
6804
+ if (!(schema instanceof ZodObject)) return [];
6805
+ const links = [];
6806
+ for (const [field, fieldSchema] of Object.entries(schema.shape)) {
6807
+ const to = linkTargetOf(globalRegistry.get(fieldSchema));
6808
+ if (to !== void 0) links.push({
6809
+ field,
6810
+ to
6811
+ });
6812
+ }
6813
+ return links;
6792
6814
  }
6793
- /** Every scope, in the order the guard and the docs list them. */
6794
- var SCOPED_SETTINGS_SCOPES = [
6795
- "cluster",
6796
- "device-defaults",
6797
- "node"
6798
- ];
6799
6815
  /**
6800
6816
  * The address of one keychain value: `secret://<owner>/<scope>/<fieldPath>`.
6801
6817
  *
@@ -6930,6 +6946,652 @@ function parseSecretRef(ref) {
6930
6946
  fieldPath
6931
6947
  };
6932
6948
  }
6949
+ /** Limits and names of `ctx.records` (D881). One authority; the engine and the facade read it. */
6950
+ /** The files a kind may live in. `history` is device-history's (D850), never records. */
6951
+ var RECORD_DATABASES = ["settings", "events"];
6952
+ /** The classes of a kind: the `@durable` vocabulary, one authority (replaces the annotation). */
6953
+ var RECORD_CLASSES = [
6954
+ "config",
6955
+ "ledger",
6956
+ "audit",
6957
+ "mirror",
6958
+ "ephemeral"
6959
+ ];
6960
+ var RECORD_DEFAULT_MAX_DATA_BYTES = 64 * 1024;
6961
+ var RECORD_MAX_DATA_BYTES = 1024 * 1024;
6962
+ var RECORD_BATCH_MAX = 1e3;
6963
+ var RECORD_QUERY_MAX = 1e3;
6964
+ /** A kind in the `settings` file may not bound itself above this (D447: high volume is `events`). */
6965
+ var RECORD_SETTINGS_MAX_ROWS = 5e4;
6966
+ /** The `Column`-free proof prefix: a ref collection for a kind's secret fields. */
6967
+ var RECORD_SECRET_COLLECTION_PREFIX = "records:";
6968
+ /**
6969
+ * Secret fields of a record, addressed the way a Zod schema declares them
6970
+ * (`collectZodSecretPaths`): dotted keys, `[]` for "each element of this array"
6971
+ * (`auth.accessToken`, `headers[].value`).
6972
+ *
6973
+ * `{}` after a key means "each value of this map" (`applianceSecrets{}`): the map's own key
6974
+ * names the value (`applianceSecrets{fridge}`), so no id key is declared and a body that drops a
6975
+ * key releases exactly that key's secret.
6976
+ *
6977
+ * Array elements are matched by a DECLARED id key (`secretArrayKeys`:
6978
+ * `{ headers: 'name' }`), never by index, so reordering a list keeps every
6979
+ * keychain ref (the same rule as `arrayItemFieldPath`). The concrete path of a
6980
+ * leaf names its element: `headers[X-Api].value`.
6981
+ *
6982
+ * Pure and browser-safe. Nothing here mutates: every transform returns a new value.
6983
+ */
6984
+ /** The array prefixes (declared form, e.g. `headers` or `a.headers`) of a path. */
6985
+ function parseSecretPath(path) {
6986
+ if (path.length === 0) throw new InvalidRecordError("an empty secret path");
6987
+ return path.split(".").map((raw) => {
6988
+ const each = raw.endsWith("[]");
6989
+ const map = raw.endsWith("{}");
6990
+ const key = each || map ? raw.slice(0, -2) : raw;
6991
+ if (key.length === 0) throw new InvalidRecordError(`secret path "${path}" has an empty segment`);
6992
+ return {
6993
+ key,
6994
+ each,
6995
+ map
6996
+ };
6997
+ });
6998
+ }
6999
+ /** The declared array prefixes of `path` that need an id key (`headers`, `a.rows`). */
7000
+ function secretArrayPrefixes(path) {
7001
+ const segments = parseSecretPath(path);
7002
+ const prefixes = [];
7003
+ const walked = [];
7004
+ for (const segment of segments) {
7005
+ walked.push(segment.key);
7006
+ if (segment.each) prefixes.push(walked.join("."));
7007
+ }
7008
+ return prefixes;
7009
+ }
7010
+ function isRecord$6(value) {
7011
+ return typeof value === "object" && value !== null && !Array.isArray(value);
7012
+ }
7013
+ function elementId(element, idKey, declared, prefix) {
7014
+ const id = isRecord$6(element) ? element[idKey] : void 0;
7015
+ 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`);
7016
+ return id;
7017
+ }
7018
+ /**
7019
+ * Visit every secret leaf PRESENT in `data` (an absent branch has nothing to
7020
+ * visit). `replace` returns the new leaf value, or {@link REMOVE_LEAF}; the
7021
+ * result is a new body, `data` is untouched.
7022
+ */
7023
+ var REMOVE_LEAF = Symbol("remove-leaf");
7024
+ function mapAt(node, segments, index, walkedKeys, concretePrefix, declared, arrayKeys, visit) {
7025
+ if (!isRecord$6(node)) return node;
7026
+ const segment = segments[index];
7027
+ if (segment === void 0) return node;
7028
+ if (!Object.prototype.hasOwnProperty.call(node, segment.key)) return node;
7029
+ const child = node[segment.key];
7030
+ const keys = [...walkedKeys, segment.key];
7031
+ const last = index === segments.length - 1;
7032
+ if (segment.each) {
7033
+ if (!Array.isArray(child)) return node;
7034
+ const prefix = keys.join(".");
7035
+ const idKey = arrayKeys[prefix];
7036
+ if (idKey === void 0) throw new InvalidRecordError(`"${declared}": no id key declared for the array "${prefix}"`);
7037
+ const mapped = child.map((element) => {
7038
+ const id = elementId(element, idKey, declared, prefix);
7039
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}[${encodeURIComponent(id)}]`;
7040
+ return last ? element : mapAt(element, segments, index + 1, keys, concrete, declared, arrayKeys, visit);
7041
+ });
7042
+ return {
7043
+ ...node,
7044
+ [segment.key]: mapped
7045
+ };
7046
+ }
7047
+ if (segment.map) {
7048
+ if (!isRecord$6(child)) return node;
7049
+ const kept = Object.entries(child).map(([mapKey, value]) => {
7050
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}{${encodeURIComponent(mapKey)}}`;
7051
+ if (!last) return [mapKey, mapAt(value, segments, index + 1, keys, concrete, declared, arrayKeys, visit)];
7052
+ return [mapKey, visit({
7053
+ declared,
7054
+ concrete,
7055
+ value
7056
+ })];
7057
+ }).filter(([, value]) => value !== REMOVE_LEAF);
7058
+ return {
7059
+ ...node,
7060
+ [segment.key]: Object.fromEntries(kept)
7061
+ };
7062
+ }
7063
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}`;
7064
+ if (last) {
7065
+ const replacement = visit({
7066
+ declared,
7067
+ concrete,
7068
+ value: child
7069
+ });
7070
+ if (replacement === REMOVE_LEAF) return Object.fromEntries(Object.entries(node).filter(([key]) => key !== segment.key));
7071
+ return {
7072
+ ...node,
7073
+ [segment.key]: replacement
7074
+ };
7075
+ }
7076
+ return {
7077
+ ...node,
7078
+ [segment.key]: mapAt(child, segments, index + 1, keys, concrete, declared, arrayKeys, visit)
7079
+ };
7080
+ }
7081
+ /** Replace/remove every present secret leaf; returns a NEW body. */
7082
+ function mapSecretLeaves(data, paths, arrayKeys, visit) {
7083
+ let current = data;
7084
+ for (const declared of paths) current = mapAt(current, parseSecretPath(declared), 0, [], "", declared, arrayKeys, visit);
7085
+ return current;
7086
+ }
7087
+ /** Every present secret leaf, read-only. */
7088
+ function collectSecretLeaves(data, paths, arrayKeys) {
7089
+ const found = [];
7090
+ mapSecretLeaves(data, paths, arrayKeys, (leaf) => {
7091
+ found.push(leaf);
7092
+ return leaf.value;
7093
+ });
7094
+ return found;
7095
+ }
7096
+ /**
7097
+ * The keychain collection name a kind's secrets live under. Prefixed so a
7098
+ * record's refs never collide with the refs a legacy collection of the same name
7099
+ * already holds during an adoption.
7100
+ */
7101
+ function recordSecretCollection(kind) {
7102
+ return `${RECORD_SECRET_COLLECTION_PREFIX}${kind}`;
7103
+ }
7104
+ /** The ONE ref a row's secret field may carry: the engine and the facade both build it here. */
7105
+ function recordSecretRef(owner, kind, rowId, concretePath) {
7106
+ return buildSecretRef({
7107
+ owner,
7108
+ scope: {
7109
+ kind: "row",
7110
+ collection: recordSecretCollection(kind),
7111
+ rowId
7112
+ },
7113
+ fieldPath: concretePath
7114
+ });
7115
+ }
7116
+ /**
7117
+ * A stored secret, as an admin read shows it: a VIEW naming the row's own
7118
+ * keychain ref (`set: true`), never the value and no longer the bare redaction
7119
+ * token. The form hands it to the secret field, which reveals the value by ref
7120
+ * through the audited `keychain-admin.reveal`; sent back untouched it keeps the
7121
+ * stored secret (the records door reads a view as KEEP).
7122
+ *
7123
+ * ONE implementation for the entries service and for every addon that serves
7124
+ * its own instances (`RecordIntegrationInstances`).
7125
+ */
7126
+ function isRecord$5(value) {
7127
+ return typeof value === "object" && value !== null && !Array.isArray(value);
7128
+ }
7129
+ function secretViewsOf(owner, kind, id, decl, data) {
7130
+ if (decl.secretPaths.length === 0) return data;
7131
+ const shown = mapSecretLeaves(data, decl.secretPaths, decl.secretArrayKeys, (leaf) => {
7132
+ if (leaf.value !== "__camstack_redacted__") return leaf.value;
7133
+ return {
7134
+ $secret: recordSecretRef(owner, kind, id, leaf.concrete),
7135
+ v: 1,
7136
+ set: true
7137
+ };
7138
+ });
7139
+ return isRecord$5(shown) ? shown : data;
7140
+ }
7141
+ /** The most instances one addon lists (an integrations page, not a table). */
7142
+ var INSTANCES_LIST_MAX = 1e3;
7143
+ /**
7144
+ * The ONE reader of an instance's switch (D996): an absent field means on, so a row written
7145
+ * before the field existed needs no migration. Every consumer of an instance body asks this.
7146
+ */
7147
+ function isInstanceEnabled(body) {
7148
+ return body.enabled !== false;
7149
+ }
7150
+ /** The body key of the switch; only {@link RecordIntegrationInstances.setInstanceEnabled} writes it. */
7151
+ var SWITCH_KEY = "enabled";
7152
+ /** The keys of the kind's secret fields that sit at the top level of the body. */
7153
+ function topLevelSecretKeys(paths) {
7154
+ return new Set(paths.filter((p) => !p.includes(".") && !p.includes("[") && !p.includes("{")));
7155
+ }
7156
+ /** The keys of the kind's top-level MAPS whose values are secrets (`applianceSecrets{}`). */
7157
+ function secretMapKeys(paths) {
7158
+ return new Set(paths.filter((p) => p.endsWith("{}") && !p.slice(0, -2).match(/[.[{]/)).map((p) => p.slice(0, -2)));
7159
+ }
7160
+ /**
7161
+ * A patch value for a map of secrets: an entry that is omitted, `''`, the redaction token or the
7162
+ * view the form was given KEEPS its stored secret (it is left out of the merge); `{ $secretClear }`
7163
+ * or `null` removes the entry; any other string replaces it. Null when nothing is left to merge.
7164
+ */
7165
+ function secretMapPatch(value) {
7166
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
7167
+ const out = {};
7168
+ for (const [key, entry] of Object.entries(value)) if (entry === null || isSecretClear(entry)) out[key] = null;
7169
+ else if (typeof entry === "string" && entry !== "" && entry !== "__camstack_redacted__" && !isSecretFieldView(entry)) out[key] = entry;
7170
+ return Object.keys(out).length > 0 ? out : null;
7171
+ }
7172
+ var RecordIntegrationInstances = class {
7173
+ records;
7174
+ kind;
7175
+ hooks;
7176
+ handle;
7177
+ secretKeys;
7178
+ secretMaps;
7179
+ nameField;
7180
+ switchListeners = /* @__PURE__ */ new Set();
7181
+ constructor(records, kind, hooks) {
7182
+ this.records = records;
7183
+ this.kind = kind;
7184
+ this.hooks = hooks;
7185
+ this.handle = records.kind(kind);
7186
+ this.secretKeys = topLevelSecretKeys(kind.declaration.secretPaths);
7187
+ this.secretMaps = secretMapKeys(kind.declaration.secretPaths);
7188
+ this.nameField = kind.declaration.entry?.nameField ?? "name";
7189
+ }
7190
+ /**
7191
+ * One instance read for the addon's own runtime; null when absent. When the keychain is
7192
+ * locked the row is served WITHOUT its secrets and says so (`secrets: 'unavailable'`), so the
7193
+ * caller can keep what it had instead of reconfiguring with an empty secret (D49).
7194
+ */
7195
+ async readResolved(id) {
7196
+ try {
7197
+ const record = await this.handle.getResolved(id);
7198
+ return record === null ? null : {
7199
+ id,
7200
+ body: record.data,
7201
+ enabled: isInstanceEnabled(record.data),
7202
+ secrets: "resolved"
7203
+ };
7204
+ } catch (err) {
7205
+ if (!(err instanceof RecordSecretUnavailableError)) throw err;
7206
+ const stored = await this.handle.get(id);
7207
+ if (stored === null) return null;
7208
+ return {
7209
+ id,
7210
+ body: Object.fromEntries(Object.entries(stored.data).filter(([key]) => !this.secretKeys.has(key))),
7211
+ enabled: isInstanceEnabled(stored.data),
7212
+ secrets: "unavailable"
7213
+ };
7214
+ }
7215
+ }
7216
+ /** The body of {@link readResolved} alone; a locked keychain yields the row without secrets. */
7217
+ async getResolved(id) {
7218
+ return (await this.readResolved(id))?.body ?? null;
7219
+ }
7220
+ /** Every instance, secrets resolved where the keychain allows; an absent one is skipped. */
7221
+ async listResolved() {
7222
+ const page = await this.handle.query({ limit: INSTANCES_LIST_MAX });
7223
+ const out = [];
7224
+ for (const record of page.records) {
7225
+ const read = await this.readResolved(record.id);
7226
+ if (read !== null) out.push(read);
7227
+ }
7228
+ return out;
7229
+ }
7230
+ viewOf(record) {
7231
+ const shown = secretViewsOf(this.records.owner, this.kind.name, record.id, this.kind.declaration, record.data);
7232
+ const rawName = record.data[this.nameField];
7233
+ const kind = this.hooks.kindOf?.(record.data);
7234
+ const health = this.hooks.health?.(record.data, record.id);
7235
+ return {
7236
+ id: record.id,
7237
+ name: typeof rawName === "string" ? rawName : record.id,
7238
+ configured: this.hooks.configured(record.data),
7239
+ enabled: isInstanceEnabled(record.data),
7240
+ formValues: shown,
7241
+ ...kind !== void 0 ? { kind } : {},
7242
+ ...health?.status !== void 0 ? { status: health.status } : {},
7243
+ ...health?.lastCheckedAt !== void 0 ? { lastCheckedAt: health.lastCheckedAt } : {}
7244
+ };
7245
+ }
7246
+ describe = async () => {
7247
+ const declared = linksOfKind(this.kind);
7248
+ const links = this.hooks.description.links !== void 0 || declared.length === 0 ? {} : { links: declared.map((link) => ({
7249
+ kind: this.kind.name,
7250
+ field: link.field,
7251
+ to: link.to
7252
+ })) };
7253
+ return {
7254
+ ...this.hooks.description,
7255
+ ...links,
7256
+ ...this.hooks.mintId === void 0 ? {} : { mintsId: true }
7257
+ };
7258
+ };
7259
+ instanceFormSchema = async ({ id }) => this.hooks.formSchema(id);
7260
+ listInstances = async () => {
7261
+ return (await this.handle.query({ limit: INSTANCES_LIST_MAX })).records.map((record) => this.viewOf(record));
7262
+ };
7263
+ getInstance = async ({ id }) => {
7264
+ const record = await this.handle.get(id);
7265
+ return record === null ? null : this.viewOf(record);
7266
+ };
7267
+ /** Insert ONE row (`ifRev: 0`: an existing id is refused, never overwritten). */
7268
+ createInstance = async ({ id, name, kind, values }) => {
7269
+ const minted = id ?? this.hooks.mintId?.({
7270
+ name,
7271
+ ...kind !== void 0 ? { kind } : {}
7272
+ });
7273
+ if (minted === void 0) throw new Error("createInstance needs an id: this provider does not mint one");
7274
+ await this.handle.put({
7275
+ id: minted,
7276
+ data: this.hooks.initialBody(name, kind)
7277
+ }, { ifRev: 0 });
7278
+ const patch = this.patchOf(values ?? {});
7279
+ if (Object.keys(patch).length > 0) await this.handle.patch(minted, patch);
7280
+ await this.hooks.onChanged?.(minted, "created");
7281
+ return { id: minted };
7282
+ };
7283
+ updateInstance = async ({ id, name, values }) => {
7284
+ const patch = this.patchOf(values);
7285
+ if (name !== void 0) patch[this.nameField] = name;
7286
+ await this.handle.patch(id, patch);
7287
+ await this.hooks.onChanged?.(id, "updated");
7288
+ return { ok: true };
7289
+ };
7290
+ /** The record patch a form `values` object means: secrets kept, cleared or replaced. */
7291
+ patchOf(values) {
7292
+ const patch = {};
7293
+ for (const [key, value] of Object.entries(values)) {
7294
+ if (value === void 0) continue;
7295
+ if (key === "enabled") continue;
7296
+ if (this.secretMaps.has(key)) {
7297
+ const entries = secretMapPatch(value);
7298
+ if (entries !== null) patch[key] = entries;
7299
+ } else if (!this.secretKeys.has(key)) patch[key] = value;
7300
+ else if (isSecretClear(value)) patch[key] = null;
7301
+ else if (typeof value === "string" && value !== "" && value !== "__camstack_redacted__" && !isSecretFieldView(value)) patch[key] = value;
7302
+ }
7303
+ return patch;
7304
+ }
7305
+ /**
7306
+ * Listen to the switch of ANY instance of this helper (in the process that serves it). The
7307
+ * durable replacement of the `integration.enabled` / `integration.disabled` events (D8): the
7308
+ * addon reconciles from the record, whichever way it flipped.
7309
+ */
7310
+ onSwitched(listener) {
7311
+ this.switchListeners.add(listener);
7312
+ }
7313
+ /**
7314
+ * The ONE writer of the switch (D996, D1014): the record body's `enabled`, for every role. A
7315
+ * configured thing is an instance, so an id with no record yet (a default integration that was
7316
+ * never configured) gets its record from `initialBody` before the switch is written.
7317
+ */
7318
+ setInstanceEnabled = async ({ id, enabled }) => {
7319
+ if (await this.handle.get(id) === null) await this.handle.put({
7320
+ id,
7321
+ data: this.hooks.initialBody(id)
7322
+ }, { ifRev: 0 });
7323
+ await this.handle.patch(id, { [SWITCH_KEY]: enabled });
7324
+ await this.hooks.onChanged?.(id, "enabled");
7325
+ for (const listener of this.switchListeners) await listener(id, enabled);
7326
+ return { ok: true };
7327
+ };
7328
+ /** The row and its keychain refs go together (the records door). */
7329
+ deleteInstance = async ({ id }) => {
7330
+ await this.handle.delete(id);
7331
+ await this.hooks.onChanged?.(id, "deleted");
7332
+ return { ok: true };
7333
+ };
7334
+ testInstance = async (input) => {
7335
+ if (this.hooks.test === void 0) return {
7336
+ success: false,
7337
+ status: "unsupported",
7338
+ error: "This integration declares no connection test"
7339
+ };
7340
+ return this.hooks.test(input);
7341
+ };
7342
+ /** The flat provider object to hand to `registerProvider`. */
7343
+ toProvider() {
7344
+ return {
7345
+ describe: this.describe,
7346
+ instanceFormSchema: this.instanceFormSchema,
7347
+ listInstances: this.listInstances,
7348
+ getInstance: this.getInstance,
7349
+ createInstance: this.createInstance,
7350
+ updateInstance: this.updateInstance,
7351
+ setInstanceEnabled: this.setInstanceEnabled,
7352
+ deleteInstance: this.deleteInstance,
7353
+ testInstance: this.testInstance
7354
+ };
7355
+ }
7356
+ };
7357
+ /**
7358
+ * The one-switch migration (epic #440, step 3). An integration's on/off state used to live in the
7359
+ * registry's `enabled` column for a device addon; it now lives only in the instance record's
7360
+ * body (`enabled`, D1007 superseded). This moves a registry `enabled = false` into the body, once.
7361
+ *
7362
+ * For every registry row of the addon that is OFF:
7363
+ * - no record under its id: the record is created from `initialBody(name)` with `enabled: false`
7364
+ * (a default integration that never had settings, Reolink's among them);
7365
+ * - a record whose body states no `enabled`: `enabled: false` is written into it;
7366
+ * - a record that already states `enabled` (either way) is the newer truth and is left alone.
7367
+ * A row that is ON writes nothing: an absent field reads as on. A rerun finds every off row with
7368
+ * a stated switch and does nothing, so nothing switched off comes back on and nothing switched on
7369
+ * goes off. The registry column itself is neither read afterwards nor written; its drop is step 5.
7370
+ *
7371
+ * It runs in the addon process, BEFORE the addon registers its `integration-instances` provider,
7372
+ * which is also why `integrations.list` still answers the stored column at that point.
7373
+ */
7374
+ function registrySwitchToBodyId(addonId, date) {
7375
+ return `${addonId}/${date}-registry-switch-to-body`;
7376
+ }
7377
+ async function moveRegistrySwitchToBody(ports, spec) {
7378
+ const rows = await ports.listIntegrations(spec.addonId);
7379
+ let created = 0;
7380
+ let switched = 0;
7381
+ let kept = 0;
7382
+ for (const row of rows) {
7383
+ if (row.enabled) continue;
7384
+ const body = await ports.readBody(row.id);
7385
+ if (body === null) {
7386
+ if (await ports.createRecord(row.id, {
7387
+ ...spec.initialBody(row.name),
7388
+ ["enabled"]: false
7389
+ }) === "created") created += 1;
7390
+ else kept += 1;
7391
+ continue;
7392
+ }
7393
+ if ("enabled" in body) {
7394
+ kept += 1;
7395
+ continue;
7396
+ }
7397
+ await ports.switchOff(row.id);
7398
+ switched += 1;
7399
+ }
7400
+ const summary = {
7401
+ integrations: rows.length,
7402
+ off: rows.filter((r) => !r.enabled).length,
7403
+ created,
7404
+ switched,
7405
+ kept
7406
+ };
7407
+ return created === 0 && switched === 0 ? {
7408
+ outcome: "already-done",
7409
+ summary
7410
+ } : {
7411
+ outcome: "done",
7412
+ summary
7413
+ };
7414
+ }
7415
+ /** A migration entry: an addon states its kind and how a new body starts, nothing else. */
7416
+ function registrySwitchToBodyMigration(spec) {
7417
+ return {
7418
+ meta: {
7419
+ id: registrySwitchToBodyId(spec.addonId, spec.date),
7420
+ owner: spec.addonId,
7421
+ level: "addon-state",
7422
+ seq: spec.seq,
7423
+ dependsOn: [],
7424
+ store: "settings",
7425
+ scope: "cluster",
7426
+ onFailure: "block-owner",
7427
+ bodyKind: "procedure",
7428
+ description: "Move the registry enabled flag of every switched-off integration into its instance record body, creating the record when there is none",
7429
+ fixtureMark: "enabled"
7430
+ },
7431
+ procedure: (ports) => moveRegistrySwitchToBody(ports, {
7432
+ addonId: spec.addonId,
7433
+ initialBody: spec.initialBody
7434
+ })
7435
+ };
7436
+ }
7437
+ /** The hub and records sides of {@link registrySwitchToBodyMigration}. */
7438
+ function registrySwitchPortsOver(deps) {
7439
+ const handle = deps.records.kind({
7440
+ name: deps.kind.name,
7441
+ declaration: deps.kind.declaration,
7442
+ schema: record(string(), unknown())
7443
+ });
7444
+ return {
7445
+ listIntegrations: async (addonId) => (await deps.api.list()).filter((i) => i.addonId === addonId).map((i) => ({
7446
+ id: i.id,
7447
+ name: i.name,
7448
+ enabled: i.enabled !== false
7449
+ })),
7450
+ readBody: async (id) => (await handle.get(id))?.data ?? null,
7451
+ createRecord: async (id, body) => {
7452
+ if (await handle.get(id) !== null) return "exists";
7453
+ await handle.put({
7454
+ id,
7455
+ data: body
7456
+ }, { ifRev: 0 });
7457
+ return "created";
7458
+ },
7459
+ switchOff: async (id) => {
7460
+ await handle.patch(id, { [SWITCH_KEY]: false });
7461
+ }
7462
+ };
7463
+ }
7464
+ /**
7465
+ * Build a {@link DurableState} over a single store key. Transport-agnostic:
7466
+ * `read`/`write` are the addon-store or device-store accessors. The whole
7467
+ * validated value round-trips on every read/write — the schema is the
7468
+ * single source of truth for what is persisted, so no hand-listed field
7469
+ * set can drop a key on save.
7470
+ */
7471
+ function createDurableState(deps) {
7472
+ const get = async () => {
7473
+ const raw = (await deps.read())[deps.key];
7474
+ if (raw === void 0) return deps.fallback;
7475
+ const parsed = deps.schema.safeParse(raw);
7476
+ if (!parsed.success) {
7477
+ deps.onParseError?.(deps.key, parsed.error);
7478
+ return deps.fallback;
7479
+ }
7480
+ return parsed.data;
7481
+ };
7482
+ const set = async (next) => {
7483
+ const validated = deps.schema.parse(next);
7484
+ await deps.write({ [deps.key]: validated });
7485
+ };
7486
+ const update = async (fn) => {
7487
+ await set(fn(await get()));
7488
+ };
7489
+ return {
7490
+ get,
7491
+ set,
7492
+ update
7493
+ };
7494
+ }
7495
+ /**
7496
+ * Per-node scoping for the shared addon-settings blob.
7497
+ *
7498
+ * An addon's settings store is hub-central (the `addon-settings` cap is
7499
+ * hub-routed — the hub instance answers for every node), so fields whose
7500
+ * value is a NODE fact (decoder backend, engine pick, probed hardware
7501
+ * capabilities) persist under the node-scoped key `<key>@<nodeId>` inside
7502
+ * the single shared blob. The SCHEMA field key stays bare: the write path
7503
+ * ({@link scopePatch}) maps the bare field onto the target node's scoped
7504
+ * key; the read/hydrate path ({@link projectStore}) maps THIS node's value
7505
+ * back, so UI forms and `resolveConfig` only ever see the bare key.
7506
+ *
7507
+ * Fields opt in via the `perNode: true` schema marker on `ConfigFieldBase`
7508
+ * (`interfaces/config-ui.ts`); `BaseAddon` derives the key set from the
7509
+ * schema and routes reads/writes through these helpers.
7510
+ *
7511
+ * ## No bare-key fallback — deliberate
7512
+ *
7513
+ * {@link readNodeValue} reads the node-scoped key ONLY. A node with no
7514
+ * scoped key resolves to `undefined` so the field's schema `default` wins —
7515
+ * NEVER `store[base]` and never another node's value. A bare legacy key in
7516
+ * the store is invisible to every node, hub included, so one node's
7517
+ * selection can never leak onto another. (This generalizes the
7518
+ * `decoder-backend-keys.ts` semantics — the no-fallback variant — over an
7519
+ * arbitrary set of per-node field keys.)
7520
+ *
7521
+ * Pure functions only — no I/O, no imports beyond the language. This is a
7522
+ * LEAF module: import it via its deep path, never from the root barrel.
7523
+ */
7524
+ /**
7525
+ * Normalize a raw kernel node id to the bare node id used for scoping.
7526
+ * `localNodeId` can carry a `<node>/<addon>` suffix on forked child
7527
+ * processes; per-node settings are per-NODE, so strip the addon segment.
7528
+ * `undefined` / `null` / empty falls back to `'hub'`.
7529
+ */
7530
+ function normalizeNodeId(raw) {
7531
+ if (raw === void 0 || raw === null || raw === "") return "hub";
7532
+ const slashIdx = raw.indexOf("/");
7533
+ if (slashIdx < 0) return raw;
7534
+ const bare = raw.slice(0, slashIdx);
7535
+ return bare === "" ? "hub" : bare;
7536
+ }
7537
+ /** The node-scoped store key for a per-node field: `<base>@<nodeId>`. */
7538
+ function nodeScopedKey(base, nodeId) {
7539
+ return `${base}@${normalizeNodeId(nodeId)}`;
7540
+ }
7541
+ /**
7542
+ * Read a node's value for a per-node field from the raw shared store:
7543
+ * the node-scoped key when present, otherwise `undefined`.
7544
+ * Deliberately NO bare-key fallback (see module doc) — the caller lets the
7545
+ * schema `default` win on `undefined`.
7546
+ */
7547
+ function readNodeValue(store, base, nodeId) {
7548
+ return store[nodeScopedKey(base, nodeId)];
7549
+ }
7550
+ /**
7551
+ * Re-map a UI/settings patch so every bare perNode field persists under the
7552
+ * TARGET node's scoped key; all other keys pass through unchanged. Used on
7553
+ * the write path so a save for one node never clobbers another node's value
7554
+ * (and the bare key is never written). Returns a new object — the input
7555
+ * patch is not mutated.
7556
+ */
7557
+ function scopePatch(patch, perNodeKeys, nodeId) {
7558
+ const out = {};
7559
+ for (const [key, value] of Object.entries(patch)) out[perNodeKeys.has(key) ? nodeScopedKey(key, nodeId) : key] = value;
7560
+ return out;
7561
+ }
7562
+ /**
7563
+ * Project the raw shared store onto the bare schema keys for ONE node so a
7564
+ * UI schema (whose field keys are bare) hydrates from that node's own
7565
+ * values:
7566
+ *
7567
+ * - EVERY `@`-scoped key (any node's) is dropped from the pass-through.
7568
+ * - Every bare perNode key is dropped from the pass-through (a stray bare
7569
+ * legacy key must never hydrate any node — no bare fallback).
7570
+ * - THIS node's effective value ({@link readNodeValue}) is then laid onto
7571
+ * each bare perNode key; when the node has no scoped key the bare key is
7572
+ * left ABSENT so the field's schema `default` wins.
7573
+ *
7574
+ * Returns a new object — the input store is not mutated.
7575
+ */
7576
+ function projectStore(store, perNodeKeys, nodeId) {
7577
+ const out = {};
7578
+ for (const [key, value] of Object.entries(store)) {
7579
+ if (key.includes("@")) continue;
7580
+ if (perNodeKeys.has(key)) continue;
7581
+ out[key] = value;
7582
+ }
7583
+ for (const base of perNodeKeys) {
7584
+ const value = readNodeValue(store, base, nodeId);
7585
+ if (value !== void 0) out[base] = value;
7586
+ }
7587
+ return out;
7588
+ }
7589
+ /** Every scope, in the order the guard and the docs list them. */
7590
+ var SCOPED_SETTINGS_SCOPES = [
7591
+ "cluster",
7592
+ "device-defaults",
7593
+ "node"
7594
+ ];
6933
7595
  /** A write to a secret path could not be stored in the keychain, so it was refused. */
6934
7596
  var KeychainWriteRefusedError = class extends Error {
6935
7597
  fieldPath;
@@ -6940,7 +7602,7 @@ var KeychainWriteRefusedError = class extends Error {
6940
7602
  }
6941
7603
  };
6942
7604
  var KEEP = { kind: "keep" };
6943
- function isRecord$6(value) {
7605
+ function isRecord$4(value) {
6944
7606
  return typeof value === "object" && value !== null && !Array.isArray(value);
6945
7607
  }
6946
7608
  function defaultMintId() {
@@ -6953,7 +7615,7 @@ function collectSecretMarkerRefs(value, out = []) {
6953
7615
  return out;
6954
7616
  }
6955
7617
  if (Array.isArray(value)) for (const item of value) collectSecretMarkerRefs(item, out);
6956
- else if (isRecord$6(value)) for (const child of Object.values(value)) collectSecretMarkerRefs(child, out);
7618
+ else if (isRecord$4(value)) for (const child of Object.values(value)) collectSecretMarkerRefs(child, out);
6957
7619
  return out;
6958
7620
  }
6959
7621
  async function storedValueEquals(secrets, marker, candidate) {
@@ -7008,7 +7670,7 @@ function rowId(row, idKey) {
7008
7670
  return null;
7009
7671
  }
7010
7672
  async function writeArray(ctx, node, incoming, stored, fieldPath) {
7011
- const storedRows = Array.isArray(stored) ? stored.filter(isRecord$6) : [];
7673
+ const storedRows = Array.isArray(stored) ? stored.filter(isRecord$4) : [];
7012
7674
  if (!Array.isArray(incoming)) {
7013
7675
  ctx.deletes.push(...collectSecretMarkerRefs(storedRows));
7014
7676
  return {
@@ -7024,7 +7686,7 @@ async function writeArray(ctx, node, incoming, stored, fieldPath) {
7024
7686
  const kept = /* @__PURE__ */ new Set();
7025
7687
  const rows = [];
7026
7688
  for (const row of incoming) {
7027
- if (!isRecord$6(row)) {
7689
+ if (!isRecord$4(row)) {
7028
7690
  rows.push(row);
7029
7691
  continue;
7030
7692
  }
@@ -7049,7 +7711,7 @@ async function writeNode(ctx, node, incoming, stored, fieldPath) {
7049
7711
  case "leaf": return writeLeaf(ctx, incoming, stored, fieldPath);
7050
7712
  case "array": return writeArray(ctx, node, incoming, stored, fieldPath);
7051
7713
  case "object": {
7052
- if (!isRecord$6(incoming)) {
7714
+ if (!isRecord$4(incoming)) {
7053
7715
  if (incoming === void 0) return KEEP;
7054
7716
  ctx.deletes.push(...collectSecretMarkerRefs(stored));
7055
7717
  return {
@@ -7057,7 +7719,7 @@ async function writeNode(ctx, node, incoming, stored, fieldPath) {
7057
7719
  value: incoming
7058
7720
  };
7059
7721
  }
7060
- const storedObj = isRecord$6(stored) ? stored : {};
7722
+ const storedObj = isRecord$4(stored) ? stored : {};
7061
7723
  return {
7062
7724
  kind: "value",
7063
7725
  value: await writeMembers(ctx, node.children, incoming, storedObj, (m) => `${fieldPath}.${m}`)
@@ -7180,7 +7842,7 @@ async function resolveSecretMarkers(value, secrets, options = {}) {
7180
7842
  value: items
7181
7843
  };
7182
7844
  }
7183
- if (isRecord$6(v)) {
7845
+ if (isRecord$4(v)) {
7184
7846
  const out = {};
7185
7847
  for (const [k, child] of Object.entries(v)) {
7186
7848
  const s = substitute(child);
@@ -7212,7 +7874,7 @@ var SecretOverwriteRefusedError = class extends Error {
7212
7874
  this.name = "SecretOverwriteRefusedError";
7213
7875
  }
7214
7876
  };
7215
- function isRecord$5(value) {
7877
+ function isRecord$3(value) {
7216
7878
  return typeof value === "object" && value !== null && !Array.isArray(value);
7217
7879
  }
7218
7880
  function resolvedValue(pass, marker) {
@@ -7241,7 +7903,7 @@ function inArray(pass, incoming, stored) {
7241
7903
  return incoming.map((item, index) => {
7242
7904
  const twin = stored[index];
7243
7905
  if (isSecretMarker(twin)) return typeof item === "string" && item === resolvedValue(pass, twin) ? twin : item;
7244
- if (isRecord$5(item) && isRecord$5(twin)) return inArrayRow(pass, item, twin);
7906
+ if (isRecord$3(item) && isRecord$3(twin)) return inArrayRow(pass, item, twin);
7245
7907
  if (Array.isArray(item) && Array.isArray(twin)) return inArray(pass, item, twin);
7246
7908
  return item;
7247
7909
  });
@@ -7252,7 +7914,7 @@ function inArrayRow(pass, incoming, stored) {
7252
7914
  const twin = stored[key];
7253
7915
  if (isSecretMarker(twin)) {
7254
7916
  if (typeof value === "string" && value === resolvedValue(pass, twin)) out[key] = twin;
7255
- } else if (isRecord$5(value) && isRecord$5(twin)) out[key] = inArrayRow(pass, value, twin);
7917
+ } else if (isRecord$3(value) && isRecord$3(twin)) out[key] = inArrayRow(pass, value, twin);
7256
7918
  else if (Array.isArray(value) && Array.isArray(twin)) out[key] = inArray(pass, value, twin);
7257
7919
  }
7258
7920
  return out;
@@ -7260,7 +7922,7 @@ function inArrayRow(pass, incoming, stored) {
7260
7922
  async function walk(pass, incoming, stored) {
7261
7923
  if (isSecretMarker(stored)) return atMarker(pass, incoming, stored);
7262
7924
  if (Array.isArray(incoming) && Array.isArray(stored)) return inArray(pass, incoming, stored);
7263
- if (!isRecord$5(incoming) || !isRecord$5(stored)) return incoming;
7925
+ if (!isRecord$3(incoming) || !isRecord$3(stored)) return incoming;
7264
7926
  const out = { ...incoming };
7265
7927
  for (const [key, value] of Object.entries(incoming)) out[key] = await walk(pass, value, stored[key]);
7266
7928
  return out;
@@ -7291,7 +7953,7 @@ async function restoreUnchangedSecrets(input) {
7291
7953
  function isJsonEqual(a, b) {
7292
7954
  if (Object.is(a, b)) return true;
7293
7955
  if (Array.isArray(a)) return Array.isArray(b) && a.length === b.length && a.every((v, i) => isJsonEqual(v, b[i]));
7294
- if (isRecord$5(a) && isRecord$5(b)) {
7956
+ if (isRecord$3(a) && isRecord$3(b)) {
7295
7957
  const keys = Object.keys(a);
7296
7958
  if (keys.length !== Object.keys(b).length) return false;
7297
7959
  return keys.every((k) => Object.prototype.hasOwnProperty.call(b, k) && isJsonEqual(a[k], b[k]));
@@ -7315,7 +7977,7 @@ function markerKeysOf(blob, owner) {
7315
7977
  }
7316
7978
  function nodeFromStored(value, owner) {
7317
7979
  if (isSecretMarker(value)) return isSecretRefOwnedBy(value.$secret, owner) ? { kind: "leaf" } : null;
7318
- if (!isRecord$5(value)) return null;
7980
+ if (!isRecord$3(value)) return null;
7319
7981
  const children = /* @__PURE__ */ new Map();
7320
7982
  for (const [key, child] of Object.entries(value)) {
7321
7983
  const node = nodeFromStored(child, owner);
@@ -7610,6 +8272,28 @@ var SECRET_RETRY_MAX_MS = 5 * 6e4;
7610
8272
  /** Coalesces a burst of `keychain.changed` events into one re-resolve. */
7611
8273
  var SECRET_CHANGE_DEBOUNCE_MS = 250;
7612
8274
  /**
8275
+ * Pair a catalogue with the function that builds its ports FROM THE MIGRATION API. The one
8276
+ * place a catalogue is bound: a migration reaches nothing a ports binder cannot reach
8277
+ * through `api` (guard `check-migration-ports-surface`).
8278
+ */
8279
+ function migrationSet(catalogue, bindPorts) {
8280
+ return { bind: (api) => defineAddonMigrations(catalogue, bindPorts(api)) };
8281
+ }
8282
+ /** A mixed array is a mistake: the other kind would be dropped without a word. */
8283
+ function refuseMixed(form, kept, dropped) {
8284
+ 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`);
8285
+ }
8286
+ function catalogueOf(list) {
8287
+ const kept = list.filter((entry) => !("execute" in entry));
8288
+ refuseMixed("catalogue, (api) => ports", kept.length, list.length - kept.length);
8289
+ return kept;
8290
+ }
8291
+ function boundOf(list) {
8292
+ const kept = list.filter((entry) => "execute" in entry);
8293
+ refuseMixed("bound migrations", kept.length, list.length - kept.length);
8294
+ return kept;
8295
+ }
8296
+ /**
7613
8297
  * Base class for CamStack addons. Eliminates settings boilerplate:
7614
8298
  *
7615
8299
  * - Typed `config` property with automatic resolution from store + defaults
@@ -7776,29 +8460,62 @@ var BaseAddon = class {
7776
8460
  await this.loadScopedSchemas();
7777
8461
  return normalized;
7778
8462
  }
8463
+ async runMigrations(first, second, third) {
8464
+ if (typeof second === "function") return this.runMigrationSets([migrationSet(catalogueOf(first), second)], third);
8465
+ return this.runBound(boundOf(first), second);
8466
+ }
7779
8467
  /**
7780
- * Run this addon's migration catalogue (D987 M3) through the hub's `migrations`
7781
- * engine. Call it at the point of the boot where the data must already have the new
7782
- * shape — `onInitialize`, or `onRestoreDevices` for a migration that needs the
7783
- * restored devices — with the catalogue bound to the addon's ports
7784
- * (`defineAddonMigrations(ADDON_MIGRATIONS, ports)`).
7785
- *
7786
- * An engine that cannot be reached or refuses the catalogue is logged and runs
7787
- * nothing; the boot continues. A migration that FAILED (or was blocked by one)
7788
- * and declares `onFailure: 'block-owner'` makes this throw, so the addon does not
7789
- * serve data whose shape it cannot trust; `tolerate` migrations never do.
7790
- *
7791
- * ALWAYS pass the whole catalogue; a phase that must run only some of it passes
7792
- * `{ only: [ids] }` — never a filtered catalogue (the engine would judge the
7793
- * omitted applied ids "newer").
8468
+ * Several catalogues of ONE owner in one declaration (the engine replaces an owner's
8469
+ * catalogue on every declare, so two calls would each judge the other's ids "newer").
8470
+ * Build each entry with `migrationSet(catalogue, (api) => ports)`.
7794
8471
  */
7795
- async runMigrations(migrations, options) {
8472
+ async runMigrationSets(sets, options) {
8473
+ const api = this.ctx.migrationApi;
8474
+ if (api === void 0) throw new Error(`${this.ctx.id}: the migration API is not available on this context`);
8475
+ return this.runBound(sets.flatMap((set) => set.bind(api)), options);
8476
+ }
8477
+ /**
8478
+ * A device addon states its instance kind once, before its migrations run, and the one-switch
8479
+ * migration (registry `enabled` to the instance body, epic #440 step 3) joins whatever
8480
+ * catalogue the addon runs, in the SAME declaration (the engine replaces an owner's catalogue
8481
+ * on every declare).
8482
+ */
8483
+ declareRegistrySwitch(spec) {
8484
+ this.registrySwitchSpec = spec;
8485
+ }
8486
+ registrySwitchSpec = null;
8487
+ registrySwitchBound() {
8488
+ const spec = this.registrySwitchSpec;
8489
+ if (spec === null) return [];
8490
+ const api = this.ctx.migrationApi;
8491
+ if (api === void 0) {
8492
+ this.ctx.logger.warn("the registry switch migration is skipped: the migration API is not available on this context");
8493
+ return [];
8494
+ }
8495
+ return migrationSet([registrySwitchToBodyMigration({
8496
+ addonId: this.ctx.id,
8497
+ date: "2026-11-06",
8498
+ seq: 1e3,
8499
+ initialBody: spec.initialBody
8500
+ })], (a) => registrySwitchPortsOver({
8501
+ api: integrationRowsApiOver(a),
8502
+ records: switchRecordsOverMigrationApi(a),
8503
+ kind: spec.kind
8504
+ })).bind(api);
8505
+ }
8506
+ async runBound(declared, options) {
8507
+ const added = this.registrySwitchBound();
8508
+ const migrations = [...declared, ...added];
8509
+ const phased = options?.only === void 0 || added.length === 0 ? options : {
8510
+ ...options,
8511
+ only: [...options.only, ...added.map((m) => m.meta.id)]
8512
+ };
7796
8513
  const api = this.ctx.api.migrations;
7797
8514
  const report = await runAddonMigrations({
7798
8515
  declareOwner: (input) => api.declareOwner.mutate(input),
7799
8516
  startMigration: (input) => api.startMigration.mutate(input),
7800
8517
  finishMigration: (input) => api.finishMigration.mutate(input)
7801
- }, migrations, this.ctx.logger, options);
8518
+ }, migrations, this.ctx.logger, phased);
7802
8519
  if (report.blockOwner.length > 0) throw new AddonMigrationsBlockedError(report.blockOwner);
7803
8520
  return report;
7804
8521
  }
@@ -8871,237 +9588,6 @@ function normalizeAddonInitResult(result) {
8871
9588
  if (Array.isArray(result)) return { providers: result };
8872
9589
  return result;
8873
9590
  }
8874
- var PREFIX = "records/";
8875
- /** The base of every records failure. `detail` is the human part of the message. */
8876
- var RecordsError = class extends Error {
8877
- code;
8878
- detail;
8879
- constructor(code, detail) {
8880
- super(`${PREFIX}${code}: ${detail}`);
8881
- this.name = "RecordsError";
8882
- this.code = code;
8883
- this.detail = detail;
8884
- }
8885
- };
8886
- /** A write guarded by `ifRev` found another revision (or an existing row for `ifRev: 0`). */
8887
- var RevConflictError = class extends RecordsError {
8888
- constructor(detail) {
8889
- super("rev-conflict", detail);
8890
- this.name = "RevConflictError";
8891
- }
8892
- };
8893
- /** The keychain could not store or serve a value: explicit, never an empty string. */
8894
- var RecordSecretUnavailableError = class extends RecordsError {
8895
- constructor(detail) {
8896
- super("secret-unavailable", detail);
8897
- this.name = "RecordSecretUnavailableError";
8898
- }
8899
- };
8900
- var InvalidRecordError = class extends RecordsError {
8901
- constructor(detail) {
8902
- super("invalid-record", detail);
8903
- this.name = "InvalidRecordError";
8904
- }
8905
- };
8906
- /** A kind declaration the engine refuses (non-additive change, bad shape, wrong file). */
8907
- var DeclarationRefusedError = class extends RecordsError {
8908
- constructor(detail) {
8909
- super("declaration-refused", detail);
8910
- this.name = "DeclarationRefusedError";
8911
- }
8912
- };
8913
- /** Limits and names of `ctx.records` (D881). One authority; the engine and the facade read it. */
8914
- /** The files a kind may live in. `history` is device-history's (D850), never records. */
8915
- var RECORD_DATABASES = ["settings", "events"];
8916
- /** The classes of a kind: the `@durable` vocabulary, one authority (replaces the annotation). */
8917
- var RECORD_CLASSES = [
8918
- "config",
8919
- "ledger",
8920
- "audit",
8921
- "mirror",
8922
- "ephemeral"
8923
- ];
8924
- var RECORD_DEFAULT_MAX_DATA_BYTES = 64 * 1024;
8925
- var RECORD_MAX_DATA_BYTES = 1024 * 1024;
8926
- var RECORD_BATCH_MAX = 1e3;
8927
- var RECORD_QUERY_MAX = 1e3;
8928
- /** A kind in the `settings` file may not bound itself above this (D447: high volume is `events`). */
8929
- var RECORD_SETTINGS_MAX_ROWS = 5e4;
8930
- /** The `Column`-free proof prefix: a ref collection for a kind's secret fields. */
8931
- var RECORD_SECRET_COLLECTION_PREFIX = "records:";
8932
- /**
8933
- * Secret fields of a record, addressed the way a Zod schema declares them
8934
- * (`collectZodSecretPaths`): dotted keys, `[]` for "each element of this array"
8935
- * (`auth.accessToken`, `headers[].value`).
8936
- *
8937
- * `{}` after a key means "each value of this map" (`applianceSecrets{}`): the map's own key
8938
- * names the value (`applianceSecrets{fridge}`), so no id key is declared and a body that drops a
8939
- * key releases exactly that key's secret.
8940
- *
8941
- * Array elements are matched by a DECLARED id key (`secretArrayKeys`:
8942
- * `{ headers: 'name' }`), never by index, so reordering a list keeps every
8943
- * keychain ref (the same rule as `arrayItemFieldPath`). The concrete path of a
8944
- * leaf names its element: `headers[X-Api].value`.
8945
- *
8946
- * Pure and browser-safe. Nothing here mutates: every transform returns a new value.
8947
- */
8948
- /** The array prefixes (declared form, e.g. `headers` or `a.headers`) of a path. */
8949
- function parseSecretPath(path) {
8950
- if (path.length === 0) throw new InvalidRecordError("an empty secret path");
8951
- return path.split(".").map((raw) => {
8952
- const each = raw.endsWith("[]");
8953
- const map = raw.endsWith("{}");
8954
- const key = each || map ? raw.slice(0, -2) : raw;
8955
- if (key.length === 0) throw new InvalidRecordError(`secret path "${path}" has an empty segment`);
8956
- return {
8957
- key,
8958
- each,
8959
- map
8960
- };
8961
- });
8962
- }
8963
- /** The declared array prefixes of `path` that need an id key (`headers`, `a.rows`). */
8964
- function secretArrayPrefixes(path) {
8965
- const segments = parseSecretPath(path);
8966
- const prefixes = [];
8967
- const walked = [];
8968
- for (const segment of segments) {
8969
- walked.push(segment.key);
8970
- if (segment.each) prefixes.push(walked.join("."));
8971
- }
8972
- return prefixes;
8973
- }
8974
- function isRecord$4(value) {
8975
- return typeof value === "object" && value !== null && !Array.isArray(value);
8976
- }
8977
- function elementId(element, idKey, declared, prefix) {
8978
- const id = isRecord$4(element) ? element[idKey] : void 0;
8979
- 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`);
8980
- return id;
8981
- }
8982
- /**
8983
- * Visit every secret leaf PRESENT in `data` (an absent branch has nothing to
8984
- * visit). `replace` returns the new leaf value, or {@link REMOVE_LEAF}; the
8985
- * result is a new body, `data` is untouched.
8986
- */
8987
- var REMOVE_LEAF = Symbol("remove-leaf");
8988
- function mapAt(node, segments, index, walkedKeys, concretePrefix, declared, arrayKeys, visit) {
8989
- if (!isRecord$4(node)) return node;
8990
- const segment = segments[index];
8991
- if (segment === void 0) return node;
8992
- if (!Object.prototype.hasOwnProperty.call(node, segment.key)) return node;
8993
- const child = node[segment.key];
8994
- const keys = [...walkedKeys, segment.key];
8995
- const last = index === segments.length - 1;
8996
- if (segment.each) {
8997
- if (!Array.isArray(child)) return node;
8998
- const prefix = keys.join(".");
8999
- const idKey = arrayKeys[prefix];
9000
- if (idKey === void 0) throw new InvalidRecordError(`"${declared}": no id key declared for the array "${prefix}"`);
9001
- const mapped = child.map((element) => {
9002
- const id = elementId(element, idKey, declared, prefix);
9003
- const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}[${encodeURIComponent(id)}]`;
9004
- return last ? element : mapAt(element, segments, index + 1, keys, concrete, declared, arrayKeys, visit);
9005
- });
9006
- return {
9007
- ...node,
9008
- [segment.key]: mapped
9009
- };
9010
- }
9011
- if (segment.map) {
9012
- if (!isRecord$4(child)) return node;
9013
- const kept = Object.entries(child).map(([mapKey, value]) => {
9014
- const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}{${encodeURIComponent(mapKey)}}`;
9015
- if (!last) return [mapKey, mapAt(value, segments, index + 1, keys, concrete, declared, arrayKeys, visit)];
9016
- return [mapKey, visit({
9017
- declared,
9018
- concrete,
9019
- value
9020
- })];
9021
- }).filter(([, value]) => value !== REMOVE_LEAF);
9022
- return {
9023
- ...node,
9024
- [segment.key]: Object.fromEntries(kept)
9025
- };
9026
- }
9027
- const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}`;
9028
- if (last) {
9029
- const replacement = visit({
9030
- declared,
9031
- concrete,
9032
- value: child
9033
- });
9034
- if (replacement === REMOVE_LEAF) return Object.fromEntries(Object.entries(node).filter(([key]) => key !== segment.key));
9035
- return {
9036
- ...node,
9037
- [segment.key]: replacement
9038
- };
9039
- }
9040
- return {
9041
- ...node,
9042
- [segment.key]: mapAt(child, segments, index + 1, keys, concrete, declared, arrayKeys, visit)
9043
- };
9044
- }
9045
- /** Replace/remove every present secret leaf; returns a NEW body. */
9046
- function mapSecretLeaves(data, paths, arrayKeys, visit) {
9047
- let current = data;
9048
- for (const declared of paths) current = mapAt(current, parseSecretPath(declared), 0, [], "", declared, arrayKeys, visit);
9049
- return current;
9050
- }
9051
- /** Every present secret leaf, read-only. */
9052
- function collectSecretLeaves(data, paths, arrayKeys) {
9053
- const found = [];
9054
- mapSecretLeaves(data, paths, arrayKeys, (leaf) => {
9055
- found.push(leaf);
9056
- return leaf.value;
9057
- });
9058
- return found;
9059
- }
9060
- /**
9061
- * The keychain collection name a kind's secrets live under. Prefixed so a
9062
- * record's refs never collide with the refs a legacy collection of the same name
9063
- * already holds during an adoption.
9064
- */
9065
- function recordSecretCollection(kind) {
9066
- return `${RECORD_SECRET_COLLECTION_PREFIX}${kind}`;
9067
- }
9068
- /** The ONE ref a row's secret field may carry: the engine and the facade both build it here. */
9069
- function recordSecretRef(owner, kind, rowId, concretePath) {
9070
- return buildSecretRef({
9071
- owner,
9072
- scope: {
9073
- kind: "row",
9074
- collection: recordSecretCollection(kind),
9075
- rowId
9076
- },
9077
- fieldPath: concretePath
9078
- });
9079
- }
9080
- /**
9081
- * A stored secret, as an admin read shows it: a VIEW naming the row's own
9082
- * keychain ref (`set: true`), never the value and no longer the bare redaction
9083
- * token. The form hands it to the secret field, which reveals the value by ref
9084
- * through the audited `keychain-admin.reveal`; sent back untouched it keeps the
9085
- * stored secret (the records door reads a view as KEEP).
9086
- *
9087
- * ONE implementation for the entries service and for every addon that serves
9088
- * its own instances (`RecordIntegrationInstances`).
9089
- */
9090
- function isRecord$3(value) {
9091
- return typeof value === "object" && value !== null && !Array.isArray(value);
9092
- }
9093
- function secretViewsOf(owner, kind, id, decl, data) {
9094
- if (decl.secretPaths.length === 0) return data;
9095
- const shown = mapSecretLeaves(data, decl.secretPaths, decl.secretArrayKeys, (leaf) => {
9096
- if (leaf.value !== "__camstack_redacted__") return leaf.value;
9097
- return {
9098
- $secret: recordSecretRef(owner, kind, id, leaf.concrete),
9099
- v: 1,
9100
- set: true
9101
- };
9102
- });
9103
- return isRecord$3(shown) ? shown : data;
9104
- }
9105
9591
  /**
9106
9592
  * The share-view scope kinds a share-link token can carry. The hub mints
9107
9593
  * and validates them (`ShareViewGrantSchema` builds its
@@ -9355,6 +9841,7 @@ function defineRecordKinds(specs) {
9355
9841
  function entryBody(shape) {
9356
9842
  return object({
9357
9843
  name: string().min(1),
9844
+ enabled: boolean().optional(),
9358
9845
  ...shape
9359
9846
  });
9360
9847
  }
@@ -11198,6 +11685,10 @@ Object.freeze({
11198
11685
  "all",
11199
11686
  "one"
11200
11687
  ]
11688
+ },
11689
+ {
11690
+ "path": "positionUpdatedAt",
11691
+ "valueType": "number"
11201
11692
  }
11202
11693
  ],
11203
11694
  "meter": [{
@@ -11452,22 +11943,6 @@ Object.freeze({
11452
11943
  "path": "pumpRunning",
11453
11944
  "valueType": "boolean"
11454
11945
  },
11455
- {
11456
- "path": "lastDrink",
11457
- "valueType": "number"
11458
- },
11459
- {
11460
- "path": "currentHourDrink",
11461
- "valueType": "number"
11462
- },
11463
- {
11464
- "path": "last24hDrink",
11465
- "valueType": "number"
11466
- },
11467
- {
11468
- "path": "todayDrink",
11469
- "valueType": "number"
11470
- },
11471
11946
  {
11472
11947
  "path": "error",
11473
11948
  "valueType": "string"
@@ -12033,12 +12508,66 @@ Object.freeze({
12033
12508
  }
12034
12509
  ]
12035
12510
  });
12511
+ Object.freeze({
12512
+ "actions": { "run": 363e4 },
12513
+ "audio-analyzer": { "classify": 3e4 },
12514
+ "custom-model-registry": { "importModelBundle": 18e5 },
12515
+ "database-snapshot": { "writeSnapshot": 18e5 },
12516
+ "device-manager": {
12517
+ "migrateDevice": 72e4,
12518
+ "runDiscoverySweep": 12e4
12519
+ },
12520
+ "device-provider": { "reloadDevice": 18e4 },
12521
+ "llm": {
12522
+ "generate": 6e5,
12523
+ "generateVision": 6e5,
12524
+ "testProfile": 6e5
12525
+ },
12526
+ "llm-runtime": {
12527
+ "complete": 6e5,
12528
+ "completeApple": 6e5,
12529
+ "ensureStarted": 6e5,
12530
+ "installModel": 36e5
12531
+ },
12532
+ "local-network": { "scanNetwork": 9e4 },
12533
+ "model-convert": { "convert": 6e5 },
12534
+ "pipeline-analytics": {
12535
+ "addRetrainFrameFromRecording": 6e4,
12536
+ "offerRetrainArchive": 12e4,
12537
+ "proposeRetrainAnnotationsWithLlm": 18e4,
12538
+ "resolveRetrainTrainingCorpus": 6e4,
12539
+ "writeRetrainArchive": 36e5
12540
+ },
12541
+ "server-management": { "applyServerUpdate": 96e4 },
12542
+ "terminal-session": { "pullOutput": 15e3 },
12543
+ "training": {
12544
+ "canaryResult": 12e4,
12545
+ "cancelJob": 12e4,
12546
+ "planJob": 6e4,
12547
+ "registerResult": 18e5,
12548
+ "rollbackCanary": 12e4,
12549
+ "startJob": 12e4,
12550
+ "startJobBatch": 12e4
12551
+ },
12552
+ "training-provider": {
12553
+ "cancelJob": 6e4,
12554
+ "cleanupJob": 3e5,
12555
+ "getJob": 6e4,
12556
+ "listJobEvents": 6e4,
12557
+ "listJobs": 12e4,
12558
+ "offerArtifact": 3e5,
12559
+ "readResult": 3e5,
12560
+ "submitJob": 18e5,
12561
+ "uploadDataset": 72e5,
12562
+ "validateCredentials": 3e4
12563
+ }
12564
+ });
12036
12565
  object({
12037
12566
  code: string().regex(/^[a-z][a-z0-9-]*(\.[a-z0-9-]+)+$/),
12038
12567
  params: record(string(), union([string(), number()])).optional()
12039
12568
  });
12040
12569
  //#endregion
12041
- //#region ../types/dist/composition-pOHbTzRB.mjs
12570
+ //#region ../types/dist/composition-BmBHuDTQ.mjs
12042
12571
  /**
12043
12572
  * The ffmpeg build every CamStack node downloads, per platform and arch.
12044
12573
  *
@@ -12342,7 +12871,7 @@ var table = {
12342
12871
  },
12343
12872
  dwell: {
12344
12873
  minArgs: 3,
12345
- maxArgs: 3,
12874
+ maxArgs: 4,
12346
12875
  apply: () => {
12347
12876
  throw new ExpressionEvalError("dwell: stateful evaluation context is required");
12348
12877
  }
@@ -13385,219 +13914,6 @@ var IntegrationInstanceRefSchema = object({
13385
13914
  ]),
13386
13915
  candidateStableId: string().optional()
13387
13916
  });
13388
- /**
13389
- * `RecordIntegrationInstances` - the `integration-instances` provider over ONE
13390
- * entry kind, so an addon that holds a connection serves it in ~30 lines.
13391
- *
13392
- * Every instance is one record of the addon's own kind, keyed by the
13393
- * `integrations` registry id. The records door does the secret work: a field the
13394
- * kind marks `.meta({ secret: true })` is a keychain marker bound to the row, so
13395
- * deleting the row deletes the secret, and one row's value is never another's.
13396
- *
13397
- * Patch rules for a secret (`updateInstance`): omitted, `''`, the redaction
13398
- * token or the view the form was given KEEP the stored secret;
13399
- * `{ $secretClear: true }` clears it; any other string replaces it.
13400
- */
13401
- /** The most instances one addon lists (an integrations page, not a table). */
13402
- var INSTANCES_LIST_MAX = 1e3;
13403
- /** The keys of the kind's secret fields that sit at the top level of the body. */
13404
- function topLevelSecretKeys(paths) {
13405
- return new Set(paths.filter((p) => !p.includes(".") && !p.includes("[") && !p.includes("{")));
13406
- }
13407
- /** The keys of the kind's top-level MAPS whose values are secrets (`applianceSecrets{}`). */
13408
- function secretMapKeys(paths) {
13409
- return new Set(paths.filter((p) => p.endsWith("{}") && !p.slice(0, -2).match(/[.[{]/)).map((p) => p.slice(0, -2)));
13410
- }
13411
- /**
13412
- * A patch value for a map of secrets: an entry that is omitted, `''`, the redaction token or the
13413
- * view the form was given KEEPS its stored secret (it is left out of the merge); `{ $secretClear }`
13414
- * or `null` removes the entry; any other string replaces it. Null when nothing is left to merge.
13415
- */
13416
- function secretMapPatch(value) {
13417
- if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
13418
- const out = {};
13419
- for (const [key, entry] of Object.entries(value)) if (entry === null || isSecretClear(entry)) out[key] = null;
13420
- else if (typeof entry === "string" && entry !== "" && entry !== "__camstack_redacted__" && !isSecretFieldView(entry)) out[key] = entry;
13421
- return Object.keys(out).length > 0 ? out : null;
13422
- }
13423
- /** Does the kind's body schema carry an `enabled` field? */
13424
- function declaresEnabled(kind) {
13425
- const json = toJSONSchema(kind.schema, {
13426
- unrepresentable: "any",
13427
- io: "input"
13428
- });
13429
- const properties = Reflect.get(json, "properties");
13430
- return typeof properties === "object" && properties !== null && "enabled" in properties;
13431
- }
13432
- var RecordIntegrationInstances = class {
13433
- records;
13434
- kind;
13435
- hooks;
13436
- handle;
13437
- secretKeys;
13438
- secretMaps;
13439
- nameField;
13440
- /** The `integrations` registry owns the on/off switch (`role: devices`); the body has none. */
13441
- registryOwnsEnabled;
13442
- constructor(records, kind, hooks) {
13443
- this.records = records;
13444
- this.kind = kind;
13445
- this.hooks = hooks;
13446
- this.handle = records.kind(kind);
13447
- this.secretKeys = topLevelSecretKeys(kind.declaration.secretPaths);
13448
- this.secretMaps = secretMapKeys(kind.declaration.secretPaths);
13449
- this.nameField = kind.declaration.entry?.nameField ?? "name";
13450
- this.registryOwnsEnabled = hooks.description.role === "devices";
13451
- 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"`);
13452
- }
13453
- /**
13454
- * One instance read for the addon's own runtime; null when absent. When the keychain is
13455
- * locked the row is served WITHOUT its secrets and says so (`secrets: 'unavailable'`), so the
13456
- * caller can keep what it had instead of reconfiguring with an empty secret (D49).
13457
- */
13458
- async readResolved(id) {
13459
- try {
13460
- const record = await this.handle.getResolved(id);
13461
- return record === null ? null : {
13462
- id,
13463
- body: record.data,
13464
- enabled: record.data.enabled !== false,
13465
- secrets: "resolved"
13466
- };
13467
- } catch (err) {
13468
- if (!(err instanceof RecordSecretUnavailableError)) throw err;
13469
- const stored = await this.handle.get(id);
13470
- if (stored === null) return null;
13471
- return {
13472
- id,
13473
- body: Object.fromEntries(Object.entries(stored.data).filter(([key]) => !this.secretKeys.has(key))),
13474
- enabled: stored.data.enabled !== false,
13475
- secrets: "unavailable"
13476
- };
13477
- }
13478
- }
13479
- /** The body of {@link readResolved} alone; a locked keychain yields the row without secrets. */
13480
- async getResolved(id) {
13481
- return (await this.readResolved(id))?.body ?? null;
13482
- }
13483
- /** Every instance, secrets resolved where the keychain allows; an absent one is skipped. */
13484
- async listResolved() {
13485
- const page = await this.handle.query({ limit: INSTANCES_LIST_MAX });
13486
- const out = [];
13487
- for (const record of page.records) {
13488
- const read = await this.readResolved(record.id);
13489
- if (read !== null) out.push(read);
13490
- }
13491
- return out;
13492
- }
13493
- viewOf(record) {
13494
- const shown = secretViewsOf(this.records.owner, this.kind.name, record.id, this.kind.declaration, record.data);
13495
- const rawName = record.data[this.nameField];
13496
- const kind = this.hooks.kindOf?.(record.data);
13497
- const health = this.hooks.health?.(record.data, record.id);
13498
- return {
13499
- id: record.id,
13500
- name: typeof rawName === "string" ? rawName : record.id,
13501
- configured: this.hooks.configured(record.data),
13502
- ...this.registryOwnsEnabled ? {} : { enabled: record.data.enabled !== false },
13503
- formValues: shown,
13504
- ...kind !== void 0 ? { kind } : {},
13505
- ...health?.status !== void 0 ? { status: health.status } : {},
13506
- ...health?.lastCheckedAt !== void 0 ? { lastCheckedAt: health.lastCheckedAt } : {}
13507
- };
13508
- }
13509
- describe = async () => this.hooks.mintId === void 0 ? this.hooks.description : {
13510
- ...this.hooks.description,
13511
- mintsId: true
13512
- };
13513
- /**
13514
- * The record an id names. A caller holding the `integrations` registry id (the Integrations
13515
- * page) reaches a kind whose body links to it through `integrationId`; an id that is itself a
13516
- * record id answers as it is. An id that names nothing comes back unchanged.
13517
- */
13518
- async resolveRecordId(id) {
13519
- if (await this.handle.get(id) !== null) return id;
13520
- const linked = (await this.handle.query({ limit: INSTANCES_LIST_MAX })).records.find((record) => record.data["integrationId"] === id);
13521
- return linked === void 0 ? id : linked.id;
13522
- }
13523
- instanceFormSchema = async ({ id }) => this.hooks.formSchema(id === null ? null : await this.resolveRecordId(id));
13524
- listInstances = async () => {
13525
- return (await this.handle.query({ limit: INSTANCES_LIST_MAX })).records.map((record) => this.viewOf(record));
13526
- };
13527
- getInstance = async ({ id }) => {
13528
- const record = await this.handle.get(await this.resolveRecordId(id));
13529
- return record === null ? null : this.viewOf(record);
13530
- };
13531
- /** Insert ONE row (`ifRev: 0`: an existing id is refused, never overwritten). */
13532
- createInstance = async ({ id, name, kind }) => {
13533
- const minted = id ?? this.hooks.mintId?.({
13534
- name,
13535
- ...kind !== void 0 ? { kind } : {}
13536
- });
13537
- if (minted === void 0) throw new Error("createInstance needs an id: this provider does not mint one");
13538
- await this.handle.put({
13539
- id: minted,
13540
- data: this.hooks.initialBody(name, kind)
13541
- }, { ifRev: 0 });
13542
- await this.hooks.onChanged?.(minted, "created");
13543
- return { id: minted };
13544
- };
13545
- updateInstance = async ({ id: askedId, name, values }) => {
13546
- const id = await this.resolveRecordId(askedId);
13547
- const patch = {};
13548
- for (const [key, value] of Object.entries(values)) {
13549
- if (value === void 0) continue;
13550
- if (this.secretMaps.has(key)) {
13551
- const entries = secretMapPatch(value);
13552
- if (entries !== null) patch[key] = entries;
13553
- } else if (!this.secretKeys.has(key)) patch[key] = value;
13554
- else if (isSecretClear(value)) patch[key] = null;
13555
- else if (typeof value === "string" && value !== "" && value !== "__camstack_redacted__" && !isSecretFieldView(value)) patch[key] = value;
13556
- }
13557
- if (name !== void 0) patch[this.nameField] = name;
13558
- await this.handle.patch(id, patch);
13559
- await this.hooks.onChanged?.(id, "updated");
13560
- return { ok: true };
13561
- };
13562
- /** The switch lives in the record body; the addon is told so it applies it (D996). */
13563
- setInstanceEnabled = async ({ id, enabled }) => {
13564
- if (this.registryOwnsEnabled) throw new Error(`instance "${id}": the integrations registry owns the on/off switch of this addon; set it with integrations.update`);
13565
- await this.handle.patch(id, { enabled });
13566
- await this.hooks.onChanged?.(id, "enabled");
13567
- return { ok: true };
13568
- };
13569
- /** The row and its keychain refs go together (the records door). */
13570
- deleteInstance = async ({ id }) => {
13571
- await this.handle.delete(id);
13572
- await this.hooks.onChanged?.(id, "deleted");
13573
- return { ok: true };
13574
- };
13575
- testInstance = async (input) => {
13576
- if (this.hooks.test === void 0) return {
13577
- success: false,
13578
- status: "unsupported",
13579
- error: "This integration declares no connection test"
13580
- };
13581
- return this.hooks.test(input.id === null ? input : {
13582
- ...input,
13583
- id: await this.resolveRecordId(input.id)
13584
- });
13585
- };
13586
- /** The flat provider object to hand to `registerProvider`. */
13587
- toProvider() {
13588
- return {
13589
- describe: this.describe,
13590
- instanceFormSchema: this.instanceFormSchema,
13591
- listInstances: this.listInstances,
13592
- getInstance: this.getInstance,
13593
- createInstance: this.createInstance,
13594
- updateInstance: this.updateInstance,
13595
- setInstanceEnabled: this.setInstanceEnabled,
13596
- deleteInstance: this.deleteInstance,
13597
- testInstance: this.testInstance
13598
- };
13599
- }
13600
- };
13601
13917
  var EncodeProfileSchema = object({
13602
13918
  video: object({
13603
13919
  codec: _enum([
@@ -14879,25 +15195,6 @@ function integrationRowsPortsOver(deps) {
14879
15195
  log: { warn: deps.warn }
14880
15196
  });
14881
15197
  }
14882
- function defaultIntegrationApiOver(api) {
14883
- return {
14884
- list: () => api.integrations.list.query(),
14885
- readLegacyIntegrationRows: (input) => api.migrations.readLegacyIntegrationRows.query(input),
14886
- clearLegacyIntegrationRows: (input) => api.migrations.clearLegacyIntegrationRows.mutate(input),
14887
- listDevices: (addonId) => api.deviceManager.listAll.query({
14888
- addonId,
14889
- projection: "slim"
14890
- }),
14891
- setDeviceIntegrationId: async (deviceId, integrationId) => {
14892
- await api.deviceManager.setIntegrationId.mutate({
14893
- deviceId,
14894
- integrationId
14895
- });
14896
- },
14897
- readDeviceHasConfig: async (deviceId) => Object.keys((await api.deviceManager.getDevice.query({ deviceId }))?.config ?? {}).length > 0,
14898
- readDeviceIntegrationId: async (deviceId) => (await api.deviceManager.getDevice.query({ deviceId }))?.integrationId ?? null
14899
- };
14900
- }
14901
15198
  /**
14902
15199
  * The trainer contract — what the hub hands the cloud trainer and what it
14903
15200
  * gets back (cloud training, D805+).
@@ -15986,6 +16283,39 @@ var UnstampedEventMediaCountSchema = object({
15986
16283
  /** Sum across both, or `null` when either lane could not be counted. */
15987
16284
  total: number().int().nonnegative().nullable()
15988
16285
  }).nullable();
16286
+ /**
16287
+ * Where the stored event media sits, per storage location: how many media rows
16288
+ * and how many bytes carry each location id, how many carry none (legacy,
16289
+ * resolved to the default `eventMedia` location), and how many name a location
16290
+ * that was not asked about (a deleted or never-listed one).
16291
+ *
16292
+ * One covering-index aggregate per asked location plus the NULL one, and one
16293
+ * unfiltered total that scans the covering index: O(rows), not a walk of the
16294
+ * rows themselves. `unlisted` is total minus the ASKED locations minus NULL, so
16295
+ * it is a deleted location only when every location id was asked.
16296
+ * `null` is "could not be measured", never zero.
16297
+ */
16298
+ var MediaLocationCensusInputSchema = object({ locationIds: array(string().min(1)).max(50).readonly() });
16299
+ var MediaLocationCensusSchema = object({
16300
+ locations: array(object({
16301
+ locationId: string(),
16302
+ rows: number().int().nonnegative(),
16303
+ bytes: number().nonnegative()
16304
+ })).readonly(),
16305
+ unstamped: object({
16306
+ rows: number().int().nonnegative(),
16307
+ bytes: number().nonnegative()
16308
+ }),
16309
+ /** Rows stamped with a location id that was not in the asked list. */
16310
+ unlisted: object({
16311
+ rows: number().int().nonnegative(),
16312
+ bytes: number().nonnegative()
16313
+ }),
16314
+ total: object({
16315
+ rows: number().int().nonnegative(),
16316
+ bytes: number().nonnegative()
16317
+ })
16318
+ });
15989
16319
  var StorageMigrationMediaMoveInputSchema = RelocateMediaInputSchema.extend({ leaseId: string().min(1) });
15990
16320
  /** The independently selectable logical storage classes — every class
15991
16321
  * `storage.listLocationDeclarations` reports, so an operator never meets a
@@ -19965,31 +20295,21 @@ var APPLIANCE_CAP_VOCABULARY = {
19965
20295
  "pet-fountain": {
19966
20296
  scope: "device",
19967
20297
  noun: t("Pet fountain", "Fontana per animali"),
19968
- actions: [
19969
- {
19970
- id: "petFountain.pumpOn",
19971
- method: "setPump",
19972
- label: t("Pump on", "Pompa accesa"),
19973
- phrase: t("Start the pump of {device}", "Avvia la pompa di {device}"),
19974
- icon: "play",
19975
- args: { on: true }
19976
- },
19977
- {
19978
- id: "petFountain.pumpOff",
19979
- method: "setPump",
19980
- label: t("Pump off", "Pompa spenta"),
19981
- phrase: t("Stop the pump of {device}", "Ferma la pompa di {device}"),
19982
- icon: "square",
19983
- args: { on: false }
19984
- },
19985
- {
19986
- id: "petFountain.resetDailyConsumption",
19987
- method: "resetDailyConsumption",
19988
- label: t("Clear daily consumption", "Azzera il consumo giornaliero"),
19989
- phrase: t("Clear the daily water consumption of {device}", "Azzera il consumo giornaliero di acqua di {device}"),
19990
- icon: "rotate-ccw"
19991
- }
19992
- ],
20298
+ actions: [{
20299
+ id: "petFountain.pumpOn",
20300
+ method: "setPump",
20301
+ label: t("Pump on", "Pompa accesa"),
20302
+ phrase: t("Start the pump of {device}", "Avvia la pompa di {device}"),
20303
+ icon: "play",
20304
+ args: { on: true }
20305
+ }, {
20306
+ id: "petFountain.pumpOff",
20307
+ method: "setPump",
20308
+ label: t("Pump off", "Pompa spenta"),
20309
+ phrase: t("Stop the pump of {device}", "Ferma la pompa di {device}"),
20310
+ icon: "square",
20311
+ args: { on: false }
20312
+ }],
19993
20313
  state: [{
19994
20314
  kind: "boolean",
19995
20315
  field: "empty",
@@ -44022,8 +44342,15 @@ var ActionInputSchema = object({
44022
44342
  var ActionRunOriginSchema = object({
44023
44343
  /** The automation block whose step started it. */
44024
44344
  blockId: string().min(1).optional() });
44025
- /** `started` = the caller did not ask to wait. */
44026
- var ActionRunOutcomeSchema = union([AutomationRunOutcomeSchema, literal("started")]);
44345
+ /**
44346
+ * `started` = the caller did not ask to wait. `timed-out` = the run reached the
44347
+ * ceiling (`ACTION_RUN_MAX_MS`) and was stopped; it is never a `ran`.
44348
+ */
44349
+ var ActionRunOutcomeSchema = union([
44350
+ AutomationRunOutcomeSchema,
44351
+ literal("started"),
44352
+ literal("timed-out")
44353
+ ]);
44027
44354
  var ActionRunResultSchema = object({
44028
44355
  runId: string().min(1),
44029
44356
  outcome: ActionRunOutcomeSchema,
@@ -44545,6 +44872,8 @@ method(object({}), array(ActionEntrySchema), { auth: "admin" }), method(object({
44545
44872
  kind: "mutation",
44546
44873
  auth: "admin"
44547
44874
  });
44875
+ /** `timeoutMs` of `actions.run`: a waited call outlives any legal run. */
44876
+ var ACTION_RUN_TIMEOUT_MS = 363e4;
44548
44877
  /**
44549
44878
  * actions — the ONE surface for runnable actions, for the UI and for
44550
44879
  * automations. Provided by the core-blocks builtin on the hub.
@@ -44563,6 +44892,12 @@ method(object({}), array(ActionEntrySchema), { auth: "admin" }), method(object({
44563
44892
  * An admin, and an in-process caller (an automation block), may run any action.
44564
44893
  * Every refusal is typed (`[not-linked] …`) and logged.
44565
44894
  *
44895
+ * **A run lasts at most `ACTION_RUN_MAX_MS` (60 min).** The provider stops a
44896
+ * run that reaches it and answers `timed-out` (never `ran`); an action whose
44897
+ * `wait` steps alone add up to more is refused at create/update
44898
+ * (`[invalid-steps]`). `run` declares a `timeoutMs` above that ceiling, so a
44899
+ * waited call (an automation step) is never cut by the 60 s transport default.
44900
+ *
44566
44901
  * A second `run` of an action that is already running is REFUSED — traced and
44567
44902
  * logged — never queued.
44568
44903
  */
@@ -44589,7 +44924,8 @@ method(object({}), array(ActionEntrySchema), { auth: "admin" }), method(object({
44589
44924
  role: "viewer",
44590
44925
  auth: "protected",
44591
44926
  kind: "mutation",
44592
- caller: "required"
44927
+ caller: "required",
44928
+ timeoutMs: ACTION_RUN_TIMEOUT_MS
44593
44929
  }), method(ActionIdInput, _void(), {
44594
44930
  kind: "mutation",
44595
44931
  auth: "admin"
@@ -47101,52 +47437,7 @@ onBrightnessChanged: { data: object({
47101
47437
  minIntervalMs: 0
47102
47438
  } } }
47103
47439
  };
47104
- /**
47105
- * `broker` — unified pub/sub broker registry, system-scoped collection.
47106
- *
47107
- * The cap models any kind-tagged message broker the user wants to
47108
- * register and that other addons might consume. The first two kinds
47109
- * are MQTT (mosquitto / aedes embedded / cloud bridge) and
47110
- * Home Assistant (HA WebSocket — subscribe_entities + call_service).
47111
- * Future kinds (Zigbee2MQTT bridge, ZHA, KNX, Telegram, …) plug in
47112
- * the same surface.
47113
- *
47114
- * Why one cap, not one cap per kind:
47115
- * - The integrations page wants a single table of "every broker"
47116
- * across kinds; a unified cap drives it without join logic.
47117
- * - Generic admin operations (add / remove / test / status) are
47118
- * identical across kinds — duplicating them per cap was busywork.
47119
- * - The `network-access` cap precedent: same interface, many
47120
- * `providerKind: 'ingress'` implementations (Tailscale, ngrok, …).
47121
- *
47122
- * What stays kind-specific:
47123
- * - `getBrokerConfig` payload (kind decides whether it returns
47124
- * mqtt URL+creds, HA baseUrl+token, …) — typed as
47125
- * `Record<string, unknown>` at the wire; consumers narrow.
47126
- * - `publish` / `subscribe` / `getState` arguments (target / filter /
47127
- * key) — also typed as `Record<string, unknown>` so each kind can
47128
- * evolve its surface (MQTT topic+qos vs HA entity_id+domain)
47129
- * without rebreaking the cap signature.
47130
- * - `add` `settings` payload (different fields per kind, validated by
47131
- * the kind-specific provider).
47132
- *
47133
- * Bidirectionality:
47134
- * - `publish` is RPC — synchronous result (provider-defined).
47135
- * - `subscribe` returns a subscription handle; the actual message
47136
- * stream flows over the typed event-bus as `broker.message` events
47137
- * keyed by `(brokerId, subscriptionId)`. Consumers filter in their
47138
- * event handler. Subscriptions persist across reconnects — the
47139
- * provider re-subscribes upstream after a transport drop.
47140
- *
47141
- * Why event-bus push (not a subscription RPC stream):
47142
- * - Matches the rest of CamStack's D8 contract — events for telemetry,
47143
- * RPC for loss-is-a-bug. Broker messages are telemetry (a single
47144
- * drop is recoverable via `getState({key})`).
47145
- * - Frees `broker.subscribe` from holding a long-lived RPC channel.
47146
- * - Cross-process: events already route through `$event-bus`; no
47147
- * per-broker wire-shaping needed.
47148
- */
47149
- var BrokerStatusEnum = _enum([
47440
+ _enum([
47150
47441
  "connected",
47151
47442
  "disconnected",
47152
47443
  "connecting",
@@ -47154,141 +47445,12 @@ var BrokerStatusEnum = _enum([
47154
47445
  "unreachable",
47155
47446
  "error"
47156
47447
  ]);
47157
- var BrokerInfoSchema = object({
47158
- /** Stable broker id. Persisted; survives addon restarts. */
47159
- id: string(),
47160
- /** Addon id of the provider that OWNS this broker.
47161
- *
47162
- * The `broker` cap is a system-scoped collection: several addons
47163
- * register a `broker` provider, each owning a DISJOINT set of
47164
- * brokers (mqtt-broker owns `mqtt_*`, provider-homeassistant owns
47165
- * `ha_*`). A broker therefore belongs to exactly one addon — like a
47166
- * device belongs to one integration. The admin UI threads this id
47167
- * back as the `{ addonId }` system-collection selector on every
47168
- * id-keyed call (`get` / `getSettings` / `setSettings` / `remove` /
47169
- * `testConnection`), so the call routes to the OWNING provider
47170
- * instead of defaulting to the first-registered one. */
47171
- addonId: string(),
47172
- /** Human-readable name (operator-chosen at add-time). */
47173
- name: string(),
47174
- /** Provider-defined kind tag — `mqtt` / `home-assistant` / future. */
47175
- kind: string(),
47176
- status: BrokerStatusEnum,
47177
- /** Free-form provider-specific info (HA version, MQTT broker
47178
- * flavour, latency, mTLS active, …). */
47179
- info: record(string(), unknown()),
47180
- /** Ms epoch of the last connection probe / status update. */
47181
- lastCheckedAt: number().nullable(),
47182
- /** Last error message, when `status` indicates failure. */
47183
- error: string().nullable()
47184
- });
47185
47448
  var RegistryStatusSchema = object({
47186
47449
  brokerCount: number().int().nonnegative(),
47187
47450
  connectedCount: number().int().nonnegative()
47188
47451
  });
47189
- /**
47190
- * One entry per `broker` provider — which addon provides which broker
47191
- * kind(s). The unified create picker reads this to know, for each
47192
- * (addonId, kind) pair the operator can pick, where to route the
47193
- * follow-up `getSettingsSchema` / `testSettings` / `add` calls (via the
47194
- * `{ addonId }` selector). A provider only advertises a kind here when
47195
- * it implements `getSettingsSchema` for that kind (so the picker never
47196
- * offers a kind whose creation form can't be rendered).
47197
- */
47198
- var BrokerProviderInfoSchema = object({
47199
- /** Addon id of the `broker` provider this entry describes. */
47200
- addonId: string(),
47201
- /** Broker kinds this provider can create, with a display label. */
47202
- kinds: array(object({
47203
- kind: string(),
47204
- label: string(),
47205
- /**
47206
- * Relative hub path to start an interactive account link (OAuth popup).
47207
- * May include `{{brokerId}}`; admin-ui substitutes and appends `?popup=1`.
47208
- */
47209
- interactiveConnectPath: string().min(1).optional(),
47210
- /** Relative hub path to disconnect the linked account (same popup pattern). */
47211
- interactiveDisconnectPath: string().min(1).optional(),
47212
- /**
47213
- * The kind signs in through a server-held interactive session instead of
47214
- * (or before) typed credentials. `basePath` is a hub-relative route set
47215
- * served by the owning addon (`/addon/<id>/...`) speaking the sign-in
47216
- * contract: `POST {basePath}/start` (body: the form's settings) answers
47217
- * `{ sessionId, loginUrl }`; `GET {basePath}/status?sessionId=` answers
47218
- * `{ phase: 'starting' | 'awaiting-login' | 'captured' | 'error' |
47219
- * 'cancelled', loginUrl, error }`; `POST {basePath}/commit`
47220
- * (`{ sessionId, name, brokerId? }`) stores the credentials on a new or
47221
- * existing broker and answers `{ brokerId }`; `POST {basePath}/cancel`
47222
- * (`{ sessionId }`) drops the session. The dialog that edits a broker
47223
- * offers it as the default path; the fields the session fills are
47224
- * marked `filledBySignIn` in the kind's settings schema.
47225
- *
47226
- * `methods` lists the ways the session can sign in, recommended first:
47227
- * `'device-code'` adds `POST {basePath}/code/start` (body: the form's
47228
- * settings) answering `{ sessionId, userCode, verificationUrl,
47229
- * expiresAt }` — the operator types `userCode` at `verificationUrl` on
47230
- * any device, and the same `status` / `commit` / `cancel` routes follow
47231
- * (status then carries `method`, `userCode`, `verificationUrl`,
47232
- * `expiresAt` and the phases `'awaiting-code'` / `'expired'`);
47233
- * `'proxy'` is the `{basePath}/start` flow above. Absent means
47234
- * `['proxy']`.
47235
- */
47236
- signIn: object({
47237
- basePath: string().min(1),
47238
- methods: array(_enum(["device-code", "proxy"])).optional()
47239
- }).optional()
47240
- }))
47241
- });
47242
- var ListInputSchema = object({
47243
- /** Optional kind filter — `list({kind:'home-assistant'})` returns
47244
- * only HA brokers. Omit to list every broker. */
47245
- kind: string().optional() });
47246
47452
  var GetInputSchema = object({ id: string() });
47247
- var AddInputSchema = object({
47248
- kind: string().min(1),
47249
- name: string().min(1),
47250
- /**
47251
- * ADOPT an existing id instead of minting a new one.
47252
- *
47253
- * Written the day this cost an outage. A broker's id is not a detail: HA
47254
- * devices carry it inside their `stableId` (`ha:ha_004:dev:…`), so a broker
47255
- * lost from config and re-added as `ha_001` leaves every one of its devices
47256
- * bound to a broker that no longer exists. Re-entering the password under the
47257
- * ORIGINAL id turns a multi-step device migration back into re-entering a
47258
- * password.
47259
- *
47260
- * A provider MUST refuse an id that is already in use — adopting a live
47261
- * broker's id would silently take it over.
47262
- */
47263
- id: string().min(1).optional(),
47264
- /** Kind-specific settings (e.g. MQTT `{url,username,password}` or HA
47265
- * `{baseUrl,accessToken}`). Validated by the kind-specific provider
47266
- * branch on receipt — invalid shape rejects the add. */
47267
- settings: record(string(), unknown())
47268
- });
47269
- var AddResultSchema = object({ id: string() });
47270
- var RemoveInputSchema = object({ id: string() });
47271
- var TestConnectionResultSchema = discriminatedUnion("ok", [object({
47272
- ok: literal(true),
47273
- latencyMs: number().nonnegative()
47274
- }), object({
47275
- ok: literal(false),
47276
- error: string()
47277
- })]);
47278
47453
  var SettingsRecordSchema$1 = record(string(), unknown());
47279
- var SettingsSchemaInputSchema = object({ kind: string() });
47280
- var TestSettingsInputSchema = object({
47281
- kind: string(),
47282
- settings: SettingsRecordSchema$1
47283
- });
47284
- var TestSettingsResultSchema = discriminatedUnion("ok", [object({
47285
- ok: literal(true),
47286
- latencyMs: number().nonnegative().optional()
47287
- }).strict(), object({
47288
- ok: literal(false),
47289
- error: string()
47290
- })]);
47291
- var SettingsSchemaResultSchema = unknown().nullable();
47292
47454
  var PublishInputSchema = object({
47293
47455
  brokerId: string(),
47294
47456
  /** Kind-specific routing target.
@@ -47322,25 +47484,7 @@ var GetStateInputSchema = object({
47322
47484
  * HA: entity_id (returns the cached entity state). */
47323
47485
  key: string()
47324
47486
  });
47325
- method(ListInputSchema, array(BrokerInfoSchema)), method(GetInputSchema, BrokerInfoSchema.nullable()), method(_void(), array(BrokerProviderInfoSchema), { auth: "admin" }), method(AddInputSchema, AddResultSchema, {
47326
- kind: "mutation",
47327
- auth: "admin"
47328
- }), method(RemoveInputSchema, _void(), {
47329
- kind: "mutation",
47330
- auth: "admin"
47331
- }), method(GetInputSchema, TestConnectionResultSchema, {
47332
- kind: "mutation",
47333
- auth: "admin"
47334
- }), method(GetInputSchema, SettingsRecordSchema$1.nullable(), { auth: "admin" }), method(object({
47335
- id: string(),
47336
- settings: SettingsRecordSchema$1
47337
- }), _void(), {
47338
- kind: "mutation",
47339
- auth: "admin"
47340
- }), method(GetInputSchema, SettingsRecordSchema$1.nullable(), { auth: "admin" }), method(SettingsSchemaInputSchema, SettingsSchemaResultSchema, { auth: "admin" }), method(TestSettingsInputSchema, TestSettingsResultSchema, {
47341
- kind: "mutation",
47342
- auth: "admin"
47343
- }), method(PublishInputSchema, unknown(), {
47487
+ method(GetInputSchema, SettingsRecordSchema$1.nullable(), { auth: "admin" }), method(PublishInputSchema, unknown(), {
47344
47488
  kind: "mutation",
47345
47489
  auth: "admin"
47346
47490
  }), method(SubscribeInputSchema, SubscribeResultSchema, {
@@ -49808,6 +49952,9 @@ var MediaPlayerStatusSchema = object({
49808
49952
  /** Repeat mode. Null when no repeat surface.
49809
49953
  * Pair with `DeviceFeature.MediaPlayerRepeat`. */
49810
49954
  repeat: MediaPlayerRepeatSchema.nullable(),
49955
+ /** Ms epoch when `position` was read from the device. Null when the driver
49956
+ * does not say; a UI that advances the position while playing counts from it. */
49957
+ positionUpdatedAt: number().nullable().default(null),
49811
49958
  /** Ms epoch when the slice was last updated. */
49812
49959
  lastChangedAt: number()
49813
49960
  });
@@ -50443,7 +50590,9 @@ var ThresholdTransformDraftSchema = object({
50443
50590
  comparison: _enum(["gte", "lte"]),
50444
50591
  threshold: number(),
50445
50592
  startDwellMs: number().nonnegative(),
50446
- stopDwellMs: number().nonnegative()
50593
+ stopDwellMs: number().nonnegative(),
50594
+ /** Samples a start needs; absent = the compiler's default for the source (2 for running power, else 1). */
50595
+ minSamples: number().int().min(1).optional()
50447
50596
  });
50448
50597
  var CustomizeTransformDraftSchema = discriminatedUnion("kind", [
50449
50598
  IdentityTransformDraftSchema,
@@ -52178,7 +52327,14 @@ var DiscoveryCandidateSchema = object({
52178
52327
  /** `stableId` of the gateway candidate this device was found BEHIND. */
52179
52328
  parentStableId: string().optional(),
52180
52329
  /** `false` = shown for context but not pickable. Default true. */
52181
- selectable: boolean().optional()
52330
+ selectable: boolean().optional(),
52331
+ /**
52332
+ * Keys of the provider's creation form (`getChildCreationSchema`) this candidate
52333
+ * cannot be adopted without — a key for an encrypted board, a pairing code. The
52334
+ * admin asks for exactly these, on the creation form prefilled with
52335
+ * `prefilledConfig`, before it adopts. Absent or empty = adopt as it is.
52336
+ */
52337
+ needsParams: array(string()).optional()
52182
52338
  });
52183
52339
  /**
52184
52340
  * Flat device summary returned by `createDevice` / `adoptDiscoveredDevice`.
@@ -52305,8 +52461,14 @@ var deviceProviderCapability = {
52305
52461
  * provider does not support manual creation. Lets the Add-Device dialog
52306
52462
  * pick the right type instead of assuming Camera.
52307
52463
  */
52308
- getManualCreationType: method(object({}), object({ deviceType: _enum(DeviceType).nullable() })),
52309
- adoptDiscoveredDevice: method(object({ candidate: DiscoveryCandidateSchema }), DeviceSummarySchema, {
52464
+ getManualCreationType: method(object({
52465
+ /** The integration asked about; a provider whose integrations differ answers per one. */
52466
+ integrationId: string().optional() }), object({ deviceType: _enum(DeviceType).nullable() })),
52467
+ adoptDiscoveredDevice: method(object({
52468
+ candidate: DiscoveryCandidateSchema,
52469
+ /** The integration the operator adopts into; a provider with several instances needs it. */
52470
+ integrationId: string().optional()
52471
+ }), DeviceSummarySchema, {
52310
52472
  kind: "mutation",
52311
52473
  auth: "admin"
52312
52474
  }),
@@ -52317,10 +52479,16 @@ var deviceProviderCapability = {
52317
52479
  * devices of that type. The output is a `ConfigUISchema` — the
52318
52480
  * router type-asserts it at the boundary.
52319
52481
  */
52320
- getChildCreationSchema: method(object({ type: _enum(DeviceType) }), CreationSchemaOutputSchema),
52482
+ getChildCreationSchema: method(object({
52483
+ type: _enum(DeviceType),
52484
+ /** The integration asked about; a provider whose integrations differ answers per one. */
52485
+ integrationId: string().optional()
52486
+ }), CreationSchemaOutputSchema),
52321
52487
  createDevice: method(object({
52322
52488
  type: _enum(DeviceType),
52323
- config: record(string(), unknown())
52489
+ config: record(string(), unknown()),
52490
+ /** The integration the operator adds the device to; a provider with several instances needs it. */
52491
+ integrationId: string().optional()
52324
52492
  }), DeviceSummarySchema, {
52325
52493
  kind: "mutation",
52326
52494
  auth: "admin"
@@ -53045,7 +53213,10 @@ method(object({
53045
53213
  auth: "admin"
53046
53214
  }), method(object({
53047
53215
  addonId: string(),
53048
- type: _enum(DeviceType)
53216
+ type: _enum(DeviceType),
53217
+ /** The integration the form is for; a provider whose integrations differ (a hub
53218
+ * integration takes no manual add) answers per integration. Absent = the addon's own. */
53219
+ integrationId: string().optional()
53049
53220
  }), unknown().nullable()), method(object({
53050
53221
  addonId: string(),
53051
53222
  type: _enum(DeviceType),
@@ -53129,7 +53300,11 @@ method(object({
53129
53300
  kind: "mutation",
53130
53301
  auth: "admin",
53131
53302
  timeoutMs: 12e4
53132
- }), method(object({ addonId: string() }), object({ deviceType: _enum(DeviceType).nullable() }), { auth: "admin" }), method(object({ addonId: string() }), unknown(), { auth: "admin" }), method(object({
53303
+ }), method(object({
53304
+ addonId: string(),
53305
+ /** The integration the Add-Device dialog is open on; absent = the addon's own. */
53306
+ integrationId: string().optional()
53307
+ }), object({ deviceType: _enum(DeviceType).nullable() }), { auth: "admin" }), method(object({ addonId: string() }), unknown(), { auth: "admin" }), method(object({
53133
53308
  deviceId: number(),
53134
53309
  key: string(),
53135
53310
  value: unknown()
@@ -56315,6 +56490,7 @@ var IntegrationWithStateSchema = object({
56315
56490
  id: string(),
56316
56491
  addonId: string(),
56317
56492
  name: string(),
56493
+ /** A projection of the instance body's switch (`setInstanceEnabled` is the only writer). */
56318
56494
  enabled: boolean(),
56319
56495
  info: record(string(), unknown()).readonly(),
56320
56496
  /** The discovery candidate this integration was set up from (D984). */
@@ -56327,6 +56503,7 @@ var IntegrationLiteSchema = object({
56327
56503
  id: string(),
56328
56504
  addonId: string(),
56329
56505
  name: string(),
56506
+ /** A projection of the instance body's switch (`setInstanceEnabled` is the only writer). */
56330
56507
  enabled: boolean(),
56331
56508
  info: record(string(), unknown()).readonly(),
56332
56509
  /** The discovery candidate this integration was set up from (D984). */
@@ -56409,7 +56586,7 @@ var TestConnectionStatusEnum = _enum([
56409
56586
  "inconclusive",
56410
56587
  "unsupported"
56411
56588
  ]);
56412
- var TestConnectionResultSchema$1 = object({
56589
+ var TestConnectionResultSchema = object({
56413
56590
  /** True ONLY for `validated`. Never true for a test that did not run. */
56414
56591
  success: boolean(),
56415
56592
  error: string().optional(),
@@ -56426,7 +56603,6 @@ var TestConnectionResultSchema$1 = object({
56426
56603
  var CreateIntegrationInputSchema = object({
56427
56604
  addonId: string(),
56428
56605
  name: string(),
56429
- enabled: boolean().optional(),
56430
56606
  info: record(string(), unknown()).optional(),
56431
56607
  /** `stableId` of the discovery candidate the form was seeded from (D984). */
56432
56608
  originStableId: string().optional(),
@@ -56435,6 +56611,11 @@ var CreateIntegrationInputSchema = object({
56435
56611
  var UpdateIntegrationInputSchema = object({
56436
56612
  id: string(),
56437
56613
  name: string().optional(),
56614
+ /**
56615
+ * Accepted for a FIXED builtin only (`info.fixed`: alarm panel, camera grid, core blocks,
56616
+ * terminal), which keeps no instance record: the registry flag is its one store. Any other
56617
+ * integration is switched through `integration-instances.setInstanceEnabled`.
56618
+ */
56438
56619
  enabled: boolean().optional(),
56439
56620
  info: record(string(), unknown()).optional()
56440
56621
  });
@@ -56454,7 +56635,7 @@ method(_void(), array(IntegrationWithStateSchema)), method(object({ id: string()
56454
56635
  }), method(_void(), array(AvailableIntegrationTypeSchema), { auth: "admin" }), method(object({
56455
56636
  addonId: string(),
56456
56637
  settings: record(string(), unknown())
56457
- }), TestConnectionResultSchema$1, {
56638
+ }), TestConnectionResultSchema, {
56458
56639
  kind: "mutation",
56459
56640
  auth: "admin"
56460
56641
  });
@@ -56481,6 +56662,14 @@ var ConfigSchemaPassthrough$3 = custom();
56481
56662
  var IntegrationInstanceIdSchema = string().min(1);
56482
56663
  var IntegrationInstanceModeSchema = _enum(["single", "multiple"]);
56483
56664
  /**
56665
+ * What the addon's instances ARE for the Integrations page (planning#416). `devices`: each
56666
+ * instance is an integration that brings devices (its record body owns the on/off switch);
56667
+ * `services`: a connection configured from the addon's own function page, never listed on
56668
+ * Integrations.
56669
+ * It is the same vocabulary as the manifest's `integrationRole`, which stays as an override.
56670
+ */
56671
+ var IntegrationInstanceRoleSchema = _enum(["devices", "services"]);
56672
+ /**
56484
56673
  * One kind of instance a provider can create (an adapter, an account type). The sign-in and
56485
56674
  * connect fields follow the `broker` contract (`broker.cap.ts`): `signIn.basePath` is a
56486
56675
  * hub-relative route set speaking the sign-in contract, `connectPath` / `disconnectPath` open an
@@ -56491,6 +56680,22 @@ var IntegrationInstanceKindSchema = object({
56491
56680
  /** Stable id of the kind, sent back as `createInstance.kind`. */
56492
56681
  id: string().min(1),
56493
56682
  label: string().min(1),
56683
+ /**
56684
+ * The function capability this kind is configured for (`broker`, `smtp-provider`,
56685
+ * `device-provider`, ...). A page section is the kinds whose `functionCap` it names (D1013); a
56686
+ * provider with more than one section must name it on every kind.
56687
+ */
56688
+ functionCap: string().min(1),
56689
+ /**
56690
+ * For `functionCap: 'broker'`: the registry kind of the broker an instance of this kind is
56691
+ * (`matter`, `home-assistant`, ...). A caller that needs a broker of one kind (a link field)
56692
+ * finds the instances whose kind names it; absent takes the kind `id`.
56693
+ */
56694
+ brokerKind: string().min(1).optional(),
56695
+ /** What instances of this kind are for the Integrations page; absent takes the provider's `role`. */
56696
+ role: IntegrationInstanceRoleSchema.optional(),
56697
+ /** `testInstance` really probes the remote for this kind; absent takes the provider's `canTest`. */
56698
+ canTest: boolean().optional(),
56494
56699
  /** The kind signs in through a server-held interactive session. */
56495
56700
  signIn: object({
56496
56701
  basePath: string().min(1),
@@ -56501,22 +56706,38 @@ var IntegrationInstanceKindSchema = object({
56501
56706
  /** Relative hub path to disconnect that account. */
56502
56707
  disconnectPath: string().min(1).optional()
56503
56708
  });
56709
+ /**
56710
+ * How devices of an instance are found. `none`: the operator adds them by hand; `lan`: the addon
56711
+ * scans the network before any instance exists (the wizard offers the candidates); `account`: the
56712
+ * devices appear after the instance signs in. `scopedToInstance`: a discovery run belongs to ONE
56713
+ * instance and its candidates are claimed by it.
56714
+ */
56715
+ var IntegrationInstanceDiscoverySchema = object({
56716
+ mode: _enum([
56717
+ "none",
56718
+ "lan",
56719
+ "account"
56720
+ ]),
56721
+ scopedToInstance: boolean()
56722
+ });
56723
+ /**
56724
+ * One link a kind of this provider declares (D1013 rule 5): the body `field` of an instance of
56725
+ * `kind` holds the id of an instance of the function cap `to.cap` (of kind `to.kind`, when set).
56726
+ * The hub indexes these so the target's delete is refused while a link names it.
56727
+ */
56728
+ var IntegrationInstanceLinkSchema = object({
56729
+ kind: string().min(1),
56730
+ field: string().min(1),
56731
+ to: object({
56732
+ cap: string().min(1),
56733
+ kind: string().min(1).optional()
56734
+ })
56735
+ });
56504
56736
  var IntegrationInstanceDescriptionSchema = object({
56505
56737
  /** What the instances are for the Integrations page; see {@link IntegrationInstanceRoleSchema}. */
56506
- role: _enum([
56507
- "devices",
56508
- "services",
56509
- "both"
56510
- ]),
56738
+ role: IntegrationInstanceRoleSchema,
56511
56739
  /** How the devices of an instance are found; absent means `{ mode: 'none' }`. */
56512
- discovery: object({
56513
- mode: _enum([
56514
- "none",
56515
- "lan",
56516
- "account"
56517
- ]),
56518
- scopedToInstance: boolean()
56519
- }).optional(),
56740
+ discovery: IntegrationInstanceDiscoverySchema.optional(),
56520
56741
  /** `single`: at most one instance can exist (Loki). `multiple`: an account each. */
56521
56742
  instanceMode: IntegrationInstanceModeSchema,
56522
56743
  /** What the instance is, for the UI (`destination`, `relay`, `account`). */
@@ -56537,7 +56758,9 @@ var IntegrationInstanceDescriptionSchema = object({
56537
56758
  * `createInstance` without an `id` works: the provider mints it. Absent means the caller must
56538
56759
  * send an id (the UI then mints an opaque one).
56539
56760
  */
56540
- mintsId: boolean().optional()
56761
+ mintsId: boolean().optional(),
56762
+ /** The links to other instances the provider's kinds declare; absent means none. */
56763
+ links: array(IntegrationInstanceLinkSchema).optional()
56541
56764
  });
56542
56765
  var IntegrationInstanceStatusSchema = object({
56543
56766
  state: _enum([
@@ -56557,8 +56780,8 @@ var IntegrationInstanceSchema = object({
56557
56780
  configured: boolean(),
56558
56781
  /**
56559
56782
  * The instance's own on/off switch (D996), derived from the record body (`enabled !== false`,
56560
- * so a row written before the field existed is on). Absent when the `integrations` registry
56561
- * owns the switch (`describe().role` is `devices`): read it from the registry row.
56783
+ * so a row written before the field existed is on). The same for every role, `devices` included:
56784
+ * the body is the one store, `setInstanceEnabled` the one writer (epic #440, step 3).
56562
56785
  */
56563
56786
  enabled: boolean().optional(),
56564
56787
  /** The kind of this instance (one of `describe().kinds[].id`), when the provider has kinds. */
@@ -56582,7 +56805,11 @@ var integrationInstancesCapability = {
56582
56805
  methods: {
56583
56806
  describe: method(_void(), IntegrationInstanceDescriptionSchema, { auth: "admin" }),
56584
56807
  /** The form; `id: null` is the create form. */
56585
- instanceFormSchema: method(object({ id: IntegrationInstanceIdSchema.nullable() }), ConfigSchemaPassthrough$3, { auth: "admin" }),
56808
+ instanceFormSchema: method(object({
56809
+ id: IntegrationInstanceIdSchema.nullable(),
56810
+ /** The kind of the create form (`id: null`) of a provider with several. */
56811
+ kind: string().min(1).optional()
56812
+ }), ConfigSchemaPassthrough$3, { auth: "admin" }),
56586
56813
  listInstances: method(_void(), array(IntegrationInstanceSchema).readonly(), { auth: "admin" }),
56587
56814
  getInstance: method(object({ id: IntegrationInstanceIdSchema }), IntegrationInstanceSchema.nullable(), { auth: "admin" }),
56588
56815
  /**
@@ -56592,7 +56819,9 @@ var integrationInstancesCapability = {
56592
56819
  createInstance: method(object({
56593
56820
  id: IntegrationInstanceIdSchema.optional(),
56594
56821
  name: string().min(1),
56595
- kind: string().min(1).optional()
56822
+ kind: string().min(1).optional(),
56823
+ /** Form values written with the record (a link picked in the create dialog). */
56824
+ values: record(string(), unknown()).optional()
56596
56825
  }), object({ id: string() }), {
56597
56826
  kind: "mutation",
56598
56827
  auth: "admin"
@@ -56602,7 +56831,8 @@ var integrationInstancesCapability = {
56602
56831
  auth: "admin"
56603
56832
  }),
56604
56833
  /**
56605
- * Switch ONE instance on or off. A row control, not a form field: `updateInstance.values` is the
56834
+ * Switch ONE instance on or off, for every role; a missing record is created from the addon's
56835
+ * initial body. A row control, not a form field: `updateInstance.values` is the
56606
56836
  * form patch (D62, D996). An off instance keeps its record and secrets and does no work.
56607
56837
  */
56608
56838
  setInstanceEnabled: method(object({
@@ -56619,8 +56849,10 @@ var integrationInstancesCapability = {
56619
56849
  }),
56620
56850
  testInstance: optionalMethod(object({
56621
56851
  id: IntegrationInstanceIdSchema.nullable(),
56622
- values: record(string(), unknown())
56623
- }), TestConnectionResultSchema$1, {
56852
+ values: record(string(), unknown()),
56853
+ /** The kind to test when `id` is null and the provider has several. */
56854
+ kind: string().min(1).optional()
56855
+ }), TestConnectionResultSchema, {
56624
56856
  kind: "mutation",
56625
56857
  auth: "admin"
56626
56858
  })
@@ -59377,6 +59609,382 @@ var SystemMetricsSchema = object({
59377
59609
  gpuMemoryPercent: number().optional()
59378
59610
  });
59379
59611
  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);
59612
+ /**
59613
+ * records - an addon's own facts and documents (D881): ledgers, audit rows,
59614
+ * config documents, mirrors. The third storage API next to `ctx.settings`
59615
+ * (operator intent, D870) and device-history (numbers over time, D850).
59616
+ *
59617
+ * Who the OWNER is: `callerAddonId`, stamped by the transport on a call that
59618
+ * crossed a process and stated by a hub in-process caller (`ctx.records` does
59619
+ * that with the addon id closed over). It is deliberately NOT in any input
59620
+ * schema, so a session can never supply it, and a call with no stamp is refused
59621
+ * `records/no-caller`. A kind is readable and writable only by its owner; other
59622
+ * addons go through the owner's capability.
59623
+ *
59624
+ * Every read is three-way: a row, `null`, or the call THROWS. A failed read is
59625
+ * never `[]`. Secret fields are never on the wire: a read shows the
59626
+ * redaction token, `secretRefs` hands the owner's `ctx.secrets` the refs it
59627
+ * resolves itself, and a write may carry only a keychain marker bound to the
59628
+ * row's own ref.
59629
+ *
59630
+ * Internal: addons reach it through `ctx.records`, never directly.
59631
+ */
59632
+ var RecordIdSchema = string().min(1).max(256);
59633
+ /** A JSON object body. Size is the engine's check (`maxDataBytes`), not a schema's. */
59634
+ var RecordBodySchema = record(string(), unknown());
59635
+ var RecordInputSchema = object({
59636
+ id: RecordIdSchema,
59637
+ /** The device this row belongs to (D865 removal, per-device reads). */
59638
+ deviceId: number().int().optional(),
59639
+ /** The domain clock, ms: observed / created / opened. */
59640
+ at: number().int().optional(),
59641
+ /** Producer-set expiry, ms. Refused on a kind whose retention is an engine TTL. */
59642
+ expiresAt: number().int().optional(),
59643
+ data: RecordBodySchema
59644
+ });
59645
+ var RecordViewSchema = object({
59646
+ id: string(),
59647
+ deviceId: number().int().nullable(),
59648
+ at: number().nullable(),
59649
+ expiresAt: number().nullable(),
59650
+ rev: number().int(),
59651
+ updatedAt: number(),
59652
+ data: RecordBodySchema
59653
+ });
59654
+ /** Declared index fields only. Anything else does not compile, by design. */
59655
+ var RecordWhereSchema = record(RecordFieldPathSchema, union([
59656
+ string(),
59657
+ number(),
59658
+ boolean(),
59659
+ object({ in: array(union([
59660
+ string(),
59661
+ number(),
59662
+ boolean()
59663
+ ])).min(1).max(RECORD_BATCH_MAX) }),
59664
+ object({
59665
+ gt: union([string(), number()]).optional(),
59666
+ gte: union([string(), number()]).optional(),
59667
+ lt: union([string(), number()]).optional(),
59668
+ lte: union([string(), number()]).optional()
59669
+ }).refine((r) => Object.keys(r).length > 0, { message: "name at least one bound" })
59670
+ ]));
59671
+ var KindShape = { kind: RecordKindNameSchema };
59672
+ var TimeWindowShape = {
59673
+ deviceId: number().int().optional(),
59674
+ atFrom: number().optional(),
59675
+ atTo: number().optional()
59676
+ };
59677
+ var RecordQueryInputSchema = object({
59678
+ ...KindShape,
59679
+ ...TimeWindowShape,
59680
+ where: RecordWhereSchema.optional(),
59681
+ /** Without `where`: `at` (default for a kind with a clock) or `id`. With `where` the order is the index's. */
59682
+ order: _enum(["at", "id"]).optional(),
59683
+ desc: boolean().optional(),
59684
+ limit: number().int().min(1).max(RECORD_QUERY_MAX).default(100),
59685
+ /** Opaque keyset cursor from a previous answer. There is no offset. */
59686
+ cursor: string().min(1).optional()
59687
+ });
59688
+ var RecordQueryResultSchema = object({
59689
+ records: array(RecordViewSchema),
59690
+ nextCursor: string().nullable()
59691
+ });
59692
+ var RecordKindStateSchema = _enum([
59693
+ "created",
59694
+ "unchanged",
59695
+ "updated"
59696
+ ]);
59697
+ var DeclareKindResultSchema = object({
59698
+ kindId: number().int(),
59699
+ state: RecordKindStateSchema,
59700
+ createdIndexes: array(string())
59701
+ });
59702
+ /** Keychain refs a write released (the old marker is gone from the row): the owner deletes the values. */
59703
+ var SecretRefsList = array(string());
59704
+ /**
59705
+ * One op of a `transact`: the single-row writes, each on a kind of the caller.
59706
+ * All ops of one call share ONE database file and ONE `transactFamily`.
59707
+ */
59708
+ var RecordTransactOpSchema = discriminatedUnion("op", [
59709
+ object({
59710
+ op: literal("put"),
59711
+ kind: RecordKindNameSchema,
59712
+ record: RecordInputSchema,
59713
+ ifRev: number().int().min(0).optional()
59714
+ }),
59715
+ object({
59716
+ op: literal("patch"),
59717
+ kind: RecordKindNameSchema,
59718
+ id: RecordIdSchema,
59719
+ data: RecordBodySchema,
59720
+ at: number().int().nullable().optional(),
59721
+ expiresAt: number().int().nullable().optional(),
59722
+ ifRev: number().int().min(1).optional()
59723
+ }),
59724
+ object({
59725
+ op: literal("delete"),
59726
+ kind: RecordKindNameSchema,
59727
+ id: RecordIdSchema
59728
+ })
59729
+ ]);
59730
+ var RecordSecretRefsSchema = record(string(), record(string(), string()));
59731
+ method(object({ kinds: record(RecordKindNameSchema, RecordKindDeclarationSchema) }), object({ kinds: record(string(), DeclareKindResultSchema) }), {
59732
+ kind: "mutation",
59733
+ auth: "admin"
59734
+ }), method(object({
59735
+ ...KindShape,
59736
+ id: RecordIdSchema
59737
+ }), RecordViewSchema.nullable(), { auth: "admin" }), method(object({
59738
+ ...KindShape,
59739
+ ids: array(RecordIdSchema).min(1).max(RECORD_BATCH_MAX)
59740
+ }), array(RecordViewSchema), { auth: "admin" }), method(object({
59741
+ ...KindShape,
59742
+ ids: array(RecordIdSchema).min(1).max(RECORD_BATCH_MAX)
59743
+ }), RecordSecretRefsSchema, { auth: "admin" }), method(object({
59744
+ ...KindShape,
59745
+ record: RecordInputSchema,
59746
+ /** Compare-and-set. `0` means "the row must not exist". */
59747
+ ifRev: number().int().min(0).optional()
59748
+ }), object({
59749
+ rev: number().int(),
59750
+ releasedRefs: SecretRefsList
59751
+ }), {
59752
+ kind: "mutation",
59753
+ auth: "admin"
59754
+ }), method(object({
59755
+ ...KindShape,
59756
+ records: array(RecordInputSchema).min(1).max(RECORD_BATCH_MAX)
59757
+ }), object({
59758
+ count: number().int(),
59759
+ releasedRefs: SecretRefsList
59760
+ }), {
59761
+ kind: "mutation",
59762
+ auth: "admin"
59763
+ }), method(object({
59764
+ ...KindShape,
59765
+ id: RecordIdSchema,
59766
+ data: RecordBodySchema,
59767
+ at: number().int().nullable().optional(),
59768
+ expiresAt: number().int().nullable().optional(),
59769
+ ifRev: number().int().min(1).optional()
59770
+ }), object({
59771
+ rev: number().int(),
59772
+ releasedRefs: SecretRefsList
59773
+ }), {
59774
+ kind: "mutation",
59775
+ auth: "admin"
59776
+ }), method(object({
59777
+ ...KindShape,
59778
+ id: RecordIdSchema
59779
+ }), object({
59780
+ deleted: boolean(),
59781
+ secretRefs: SecretRefsList
59782
+ }), {
59783
+ kind: "mutation",
59784
+ auth: "admin"
59785
+ }), method(object({
59786
+ ...KindShape,
59787
+ ids: array(RecordIdSchema).min(1).max(RECORD_BATCH_MAX)
59788
+ }), object({
59789
+ deleted: number().int(),
59790
+ secretRefs: SecretRefsList
59791
+ }), {
59792
+ kind: "mutation",
59793
+ auth: "admin"
59794
+ }), method(RecordQueryInputSchema, RecordQueryResultSchema, { auth: "admin" }), method(object({
59795
+ ...KindShape,
59796
+ ...TimeWindowShape,
59797
+ where: RecordWhereSchema.optional()
59798
+ }), object({ count: number().int() }), { auth: "admin" }), method(object({
59799
+ ...KindShape,
59800
+ deviceId: number().int().optional(),
59801
+ from: number(),
59802
+ to: number(),
59803
+ bucketMs: number().int().positive()
59804
+ }), object({ buckets: array(object({
59805
+ bucketStart: number(),
59806
+ count: number().int()
59807
+ })) }), { auth: "admin" }), method(object({
59808
+ ...KindShape,
59809
+ op: _enum([
59810
+ "sum",
59811
+ "min",
59812
+ "max",
59813
+ "count"
59814
+ ]),
59815
+ field: RecordFieldPathSchema.optional(),
59816
+ groupBy: RecordFieldPathSchema.optional(),
59817
+ where: RecordWhereSchema.optional()
59818
+ }), object({ rows: array(object({
59819
+ group: union([
59820
+ string(),
59821
+ number(),
59822
+ _null()
59823
+ ]),
59824
+ value: number().nullable()
59825
+ })) }), { auth: "admin" }), method(object({
59826
+ ...KindShape,
59827
+ deviceId: number().int().optional(),
59828
+ atBefore: number().optional(),
59829
+ where: RecordWhereSchema.optional()
59830
+ }), object({
59831
+ deleted: number().int(),
59832
+ secretRefs: SecretRefsList
59833
+ }), {
59834
+ kind: "mutation",
59835
+ auth: "admin"
59836
+ }), method(object({ ops: array(RecordTransactOpSchema).min(1).max(RECORD_BATCH_MAX) }), object({
59837
+ results: array(object({
59838
+ rev: number().int().nullable(),
59839
+ deleted: boolean()
59840
+ })),
59841
+ releasedRefs: SecretRefsList,
59842
+ secretRefs: SecretRefsList
59843
+ }), {
59844
+ kind: "mutation",
59845
+ auth: "admin"
59846
+ }), method(object({
59847
+ deviceId: number().int(),
59848
+ kinds: array(RecordKindNameSchema).optional()
59849
+ }), object({
59850
+ deleted: record(string(), number().int()),
59851
+ secretRefs: SecretRefsList
59852
+ }), {
59853
+ kind: "mutation",
59854
+ auth: "admin"
59855
+ }), method(object(KindShape), object({ id: number().int() }), {
59856
+ kind: "mutation",
59857
+ auth: "admin"
59858
+ });
59859
+ /**
59860
+ * The wire shapes of the migration API, version 1 (planning#447).
59861
+ *
59862
+ * A migration is code that outlives the server it was written against: an addon at
59863
+ * version 1.4 that is brought to 1.9 in one jump still runs its 1.4 catalogue, against
59864
+ * the 1.9 kernel. The only thing that code may call is {@link MigrationApiV1}; this file
59865
+ * is the contract of every method of it, one Zod pair per method.
59866
+ *
59867
+ * APPEND-ONLY. A released method is never removed and never changes meaning: an input
59868
+ * field is never removed or made required, an enum never narrows, an output field is
59869
+ * never removed. A change that cannot be expressed that way is `migration-api.v2`, next
59870
+ * to this file. `scripts/check-migration-api-append-only.ts` holds the line against
59871
+ * `scripts/migration-api-contract.json`, and every `behaviours` id below must have an
59872
+ * `it('<id>'` in `migration-api.contract.spec.ts`.
59873
+ */
59874
+ var Rows = record(string(), unknown());
59875
+ var IntegrationId = object({ integrationId: string().min(1) });
59876
+ var RecordId = object({ id: string().min(1) });
59877
+ var RecordRowSchema = object({
59878
+ id: string(),
59879
+ deviceId: number().int().nullable(),
59880
+ at: number().nullable(),
59881
+ expiresAt: number().nullable(),
59882
+ rev: number().int(),
59883
+ updatedAt: number(),
59884
+ data: Rows
59885
+ });
59886
+ var RecordPutShape = {
59887
+ id: string().min(1),
59888
+ deviceId: number().int().optional(),
59889
+ at: number().int().optional(),
59890
+ expiresAt: number().int().optional(),
59891
+ data: Rows
59892
+ };
59893
+ var MigrationIntegrationSchema = object({
59894
+ id: string(),
59895
+ addonId: string(),
59896
+ name: string(),
59897
+ info: Rows,
59898
+ /** The registry's stored switch: read by the one-switch migration, nothing else. */
59899
+ enabled: boolean().optional(),
59900
+ originStableId: string().optional()
59901
+ });
59902
+ var MigrationDeviceSchema = object({
59903
+ id: number().int(),
59904
+ integrationId: string().nullable().optional(),
59905
+ /** The owning device; null or absent for a root. */
59906
+ parentDeviceId: number().int().nullable().optional(),
59907
+ type: string().optional(),
59908
+ name: string().optional(),
59909
+ stableId: string().optional()
59910
+ });
59911
+ /** What the engine says about the migration API it serves: lets an addon notice an older server. */
59912
+ var MigrationApiInfoSchema = object({
59913
+ version: number().int(),
59914
+ methods: array(string())
59915
+ });
59916
+ object({
59917
+ message: string(),
59918
+ meta: Rows.optional(),
59919
+ /** Grouping tags of the line; a line about a device carries `{ deviceId }`. */
59920
+ tags: object({ deviceId: number().int().optional() }).optional()
59921
+ });
59922
+ object({
59923
+ owner: string().min(1),
59924
+ metas: array(MigrationMetaSchema)
59925
+ }), object({
59926
+ bootId: string(),
59927
+ snapshot: _enum([
59928
+ "none",
59929
+ "written",
59930
+ "refused"
59931
+ ]),
59932
+ steps: array(MigrationOwnerStepSchema),
59933
+ /** The migration API the engine serves; absent from a server that predates it. */
59934
+ migrationApi: MigrationApiInfoSchema.optional()
59935
+ }), object({ id: string().min(1) }), object({
59936
+ proceed: boolean(),
59937
+ state: union([literal("pending"), MigrationStatusSchema]),
59938
+ reason: string().nullable()
59939
+ }), object({
59940
+ id: string().min(1),
59941
+ result: MigrationOwnerResultSchema
59942
+ }), object({
59943
+ status: MigrationStatusSchema,
59944
+ error: string().nullable(),
59945
+ rowsChanged: number().int().nonnegative()
59946
+ }), object({
59947
+ rows: number().int().nonnegative(),
59948
+ secrets: number().int().nonnegative()
59949
+ }), IntegrationId.extend({ patch: Rows }), object({ written: boolean() }), IntegrationId.extend({ keys: array(string().min(1)) }), object({
59950
+ present: boolean(),
59951
+ removed: Rows
59952
+ }), RecordRowSchema.nullable(), RecordRowSchema.nullable(), object({
59953
+ ...RecordPutShape,
59954
+ ifRev: number().int().optional()
59955
+ }), object({ rev: number().int() }), object({ records: array(object(RecordPutShape)) }), object({ count: number().int().nonnegative() }), RecordId.extend({
59956
+ partial: Rows,
59957
+ ifRev: number().int().optional()
59958
+ }), object({ rev: number().int() }), object({ deleted: boolean() }), object({
59959
+ deviceId: number().int().optional(),
59960
+ atFrom: number().optional(),
59961
+ atTo: number().optional(),
59962
+ where: RecordWhereSchema.optional(),
59963
+ limit: number().int().min(1).optional(),
59964
+ cursor: string().min(1).optional(),
59965
+ resolveSecrets: boolean().optional()
59966
+ }), object({
59967
+ records: array(RecordRowSchema),
59968
+ nextCursor: string().nullable()
59969
+ }), object({
59970
+ deviceId: number().int().optional(),
59971
+ atBefore: number().optional(),
59972
+ where: RecordWhereSchema.optional()
59973
+ }), 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({
59974
+ ref: string().min(1),
59975
+ value: string()
59976
+ }), object({}), object({ refs: array(string()) }), object({ deleted: number().int().nonnegative() }), object({}), object({ integrations: array(MigrationIntegrationSchema) }), object({ id: string().min(1) }), MigrationIntegrationSchema.nullable(), object({
59977
+ addonId: string().min(1),
59978
+ integrationId: string().min(1).optional()
59979
+ }), object({ devices: array(MigrationDeviceSchema) }), object({ deviceId: number().int() }), object({
59980
+ id: number().int(),
59981
+ integrationId: string().nullable(),
59982
+ /** Whether the device carries any stored config; its content is not offered. */
59983
+ hasConfig: boolean()
59984
+ }).nullable(), object({
59985
+ deviceId: number().int(),
59986
+ integrationId: string().min(1)
59987
+ }), object({}), object({}), object({ nodeId: string() }), object({}), object({});
59380
59988
  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({
59381
59989
  id: string().min(1),
59382
59990
  error: string().min(1)
@@ -59406,7 +60014,9 @@ method(object({}), object({ entries: array(MigrationLedgerEntrySchema) }), { aut
59406
60014
  "written",
59407
60015
  "refused"
59408
60016
  ]),
59409
- steps: array(MigrationOwnerStepSchema)
60017
+ steps: array(MigrationOwnerStepSchema),
60018
+ /** The migration API this engine serves (additive: a server that predates it omits it). */
60019
+ migrationApi: MigrationApiInfoSchema.optional()
59410
60020
  }), {
59411
60021
  kind: "mutation",
59412
60022
  auth: "admin"
@@ -62073,7 +62683,10 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
62073
62683
  }), method(RelocateMediaInputSchema, object({ jobId: string() }), {
62074
62684
  kind: "mutation",
62075
62685
  auth: "admin"
62076
- }), method(object({}), UnstampedEventMediaCountSchema, { auth: "admin" }), method(RelocatableMediaCountInputSchema, RelocatableMediaCountSchema, {
62686
+ }), method(object({}), UnstampedEventMediaCountSchema, { auth: "admin" }), method(MediaLocationCensusInputSchema, MediaLocationCensusSchema, {
62687
+ kind: "query",
62688
+ auth: "admin"
62689
+ }), method(RelocatableMediaCountInputSchema, RelocatableMediaCountSchema, {
62077
62690
  kind: "query",
62078
62691
  auth: "admin"
62079
62692
  }), method(object({}), array(RelocateJobSchema).readonly(), {
@@ -64728,7 +65341,7 @@ var BrokerStatusSchema$1 = _enum([
64728
65341
  "unreachable",
64729
65342
  "tls-error"
64730
65343
  ]);
64731
- var BrokerInfoSchema$1 = object({
65344
+ var BrokerInfoSchema = object({
64732
65345
  id: string(),
64733
65346
  name: string(),
64734
65347
  url: string(),
@@ -64791,7 +65404,7 @@ var StatusSchema = object({
64791
65404
  brokerCount: number(),
64792
65405
  embeddedRunning: boolean()
64793
65406
  });
64794
- method(_void(), array(BrokerInfoSchema$1)), method(IdInputSchema, BrokerConnectionDetailsSchema, { auth: "admin" }), method(AddBrokerInputSchema, AddBrokerResultSchema, {
65407
+ method(_void(), array(BrokerInfoSchema)), method(IdInputSchema, BrokerConnectionDetailsSchema, { auth: "admin" }), method(AddBrokerInputSchema, AddBrokerResultSchema, {
64795
65408
  kind: "mutation",
64796
65409
  auth: "admin"
64797
65410
  }), method(IdInputSchema, _void(), {
@@ -69413,14 +70026,6 @@ var PetFountainStatusSchema = object({
69413
70026
  empty: boolean().nullable(),
69414
70027
  /** True while the pump is running. Null while unknown. */
69415
70028
  pumpRunning: boolean().nullable(),
69416
- /** Water drunk in the last drink, in litres. */
69417
- lastDrink: number().min(0).nullable().meta(readingMeta("volume")),
69418
- /** Water drunk in the current hour, in litres. */
69419
- currentHourDrink: number().min(0).nullable().meta(readingMeta("volume")),
69420
- /** Water drunk over the last 24 hours (rolling), in litres. */
69421
- last24hDrink: number().min(0).nullable().meta(readingMeta("volume")),
69422
- /** Water drunk since local midnight, in litres. Null when the fountain has no such sensor. */
69423
- todayDrink: number().min(0).nullable().meta(readingMeta("volume")),
69424
70029
  /** Decoded fault message. Null means healthy; a non-null string is an active fault. */
69425
70030
  error: string().nullable(),
69426
70031
  /** Ms epoch when the slice was last refreshed. */
@@ -69433,21 +70038,15 @@ var petFountainCapability = {
69433
70038
  deviceNative: true,
69434
70039
  mode: "singleton",
69435
70040
  deviceTypes: [DeviceType.PetFountain],
69436
- methods: {
69437
- /** Start or stop the pump. */
69438
- setPump: method(object({
69439
- deviceId: DeviceIdSchema$1,
69440
- on: boolean()
69441
- }), _void(), {
69442
- kind: "mutation",
69443
- auth: "protected"
69444
- }),
69445
- /** Clear the rolling daily consumption counters on the device. */
69446
- resetDailyConsumption: method(object({ deviceId: DeviceIdSchema$1 }), _void(), {
69447
- kind: "mutation",
69448
- auth: "protected"
69449
- })
69450
- },
70041
+ methods: {
70042
+ /** Start or stop the pump. */
70043
+ setPump: method(object({
70044
+ deviceId: DeviceIdSchema$1,
70045
+ on: boolean()
70046
+ }), _void(), {
70047
+ kind: "mutation",
70048
+ auth: "protected"
70049
+ }) },
69451
70050
  status: {
69452
70051
  schema: PetFountainStatusSchema,
69453
70052
  kind: "push"
@@ -69471,14 +70070,6 @@ var petFountainCapability = {
69471
70070
  waterVolume: {
69472
70071
  kind: "gauge",
69473
70072
  unit: "L"
69474
- },
69475
- todayDrink: {
69476
- kind: "gauge",
69477
- unit: "L"
69478
- },
69479
- last24hDrink: {
69480
- kind: "gauge",
69481
- unit: "L"
69482
70073
  }
69483
70074
  } }
69484
70075
  };
@@ -71973,253 +72564,6 @@ DeviceType.Camera, DeviceType.Sensor, DeviceType.Switch, DeviceType.Gateway, met
71973
72564
  auth: "admin"
71974
72565
  });
71975
72566
  /**
71976
- * records - an addon's own facts and documents (D881): ledgers, audit rows,
71977
- * config documents, mirrors. The third storage API next to `ctx.settings`
71978
- * (operator intent, D870) and device-history (numbers over time, D850).
71979
- *
71980
- * Who the OWNER is: `callerAddonId`, stamped by the transport on a call that
71981
- * crossed a process and stated by a hub in-process caller (`ctx.records` does
71982
- * that with the addon id closed over). It is deliberately NOT in any input
71983
- * schema, so a session can never supply it, and a call with no stamp is refused
71984
- * `records/no-caller`. A kind is readable and writable only by its owner; other
71985
- * addons go through the owner's capability.
71986
- *
71987
- * Every read is three-way: a row, `null`, or the call THROWS. A failed read is
71988
- * never `[]`. Secret fields are never on the wire: a read shows the
71989
- * redaction token, `secretRefs` hands the owner's `ctx.secrets` the refs it
71990
- * resolves itself, and a write may carry only a keychain marker bound to the
71991
- * row's own ref.
71992
- *
71993
- * Internal: addons reach it through `ctx.records`, never directly.
71994
- */
71995
- var RecordIdSchema = string().min(1).max(256);
71996
- /** A JSON object body. Size is the engine's check (`maxDataBytes`), not a schema's. */
71997
- var RecordBodySchema = record(string(), unknown());
71998
- var RecordInputSchema = object({
71999
- id: RecordIdSchema,
72000
- /** The device this row belongs to (D865 removal, per-device reads). */
72001
- deviceId: number().int().optional(),
72002
- /** The domain clock, ms: observed / created / opened. */
72003
- at: number().int().optional(),
72004
- /** Producer-set expiry, ms. Refused on a kind whose retention is an engine TTL. */
72005
- expiresAt: number().int().optional(),
72006
- data: RecordBodySchema
72007
- });
72008
- var RecordViewSchema = object({
72009
- id: string(),
72010
- deviceId: number().int().nullable(),
72011
- at: number().nullable(),
72012
- expiresAt: number().nullable(),
72013
- rev: number().int(),
72014
- updatedAt: number(),
72015
- data: RecordBodySchema
72016
- });
72017
- /** Declared index fields only. Anything else does not compile, by design. */
72018
- var RecordWhereSchema = record(RecordFieldPathSchema, union([
72019
- string(),
72020
- number(),
72021
- boolean(),
72022
- object({ in: array(union([
72023
- string(),
72024
- number(),
72025
- boolean()
72026
- ])).min(1).max(RECORD_BATCH_MAX) }),
72027
- object({
72028
- gt: union([string(), number()]).optional(),
72029
- gte: union([string(), number()]).optional(),
72030
- lt: union([string(), number()]).optional(),
72031
- lte: union([string(), number()]).optional()
72032
- }).refine((r) => Object.keys(r).length > 0, { message: "name at least one bound" })
72033
- ]));
72034
- var KindShape = { kind: RecordKindNameSchema };
72035
- var TimeWindowShape = {
72036
- deviceId: number().int().optional(),
72037
- atFrom: number().optional(),
72038
- atTo: number().optional()
72039
- };
72040
- var RecordQueryInputSchema = object({
72041
- ...KindShape,
72042
- ...TimeWindowShape,
72043
- where: RecordWhereSchema.optional(),
72044
- /** Without `where`: `at` (default for a kind with a clock) or `id`. With `where` the order is the index's. */
72045
- order: _enum(["at", "id"]).optional(),
72046
- desc: boolean().optional(),
72047
- limit: number().int().min(1).max(RECORD_QUERY_MAX).default(100),
72048
- /** Opaque keyset cursor from a previous answer. There is no offset. */
72049
- cursor: string().min(1).optional()
72050
- });
72051
- var RecordQueryResultSchema = object({
72052
- records: array(RecordViewSchema),
72053
- nextCursor: string().nullable()
72054
- });
72055
- var RecordKindStateSchema = _enum([
72056
- "created",
72057
- "unchanged",
72058
- "updated"
72059
- ]);
72060
- var DeclareKindResultSchema = object({
72061
- kindId: number().int(),
72062
- state: RecordKindStateSchema,
72063
- createdIndexes: array(string())
72064
- });
72065
- /** Keychain refs a write released (the old marker is gone from the row): the owner deletes the values. */
72066
- var SecretRefsList = array(string());
72067
- /**
72068
- * One op of a `transact`: the single-row writes, each on a kind of the caller.
72069
- * All ops of one call share ONE database file and ONE `transactFamily`.
72070
- */
72071
- var RecordTransactOpSchema = discriminatedUnion("op", [
72072
- object({
72073
- op: literal("put"),
72074
- kind: RecordKindNameSchema,
72075
- record: RecordInputSchema,
72076
- ifRev: number().int().min(0).optional()
72077
- }),
72078
- object({
72079
- op: literal("patch"),
72080
- kind: RecordKindNameSchema,
72081
- id: RecordIdSchema,
72082
- data: RecordBodySchema,
72083
- at: number().int().nullable().optional(),
72084
- expiresAt: number().int().nullable().optional(),
72085
- ifRev: number().int().min(1).optional()
72086
- }),
72087
- object({
72088
- op: literal("delete"),
72089
- kind: RecordKindNameSchema,
72090
- id: RecordIdSchema
72091
- })
72092
- ]);
72093
- var RecordSecretRefsSchema = record(string(), record(string(), string()));
72094
- method(object({ kinds: record(RecordKindNameSchema, RecordKindDeclarationSchema) }), object({ kinds: record(string(), DeclareKindResultSchema) }), {
72095
- kind: "mutation",
72096
- auth: "admin"
72097
- }), method(object({
72098
- ...KindShape,
72099
- id: RecordIdSchema
72100
- }), RecordViewSchema.nullable(), { auth: "admin" }), method(object({
72101
- ...KindShape,
72102
- ids: array(RecordIdSchema).min(1).max(RECORD_BATCH_MAX)
72103
- }), array(RecordViewSchema), { auth: "admin" }), method(object({
72104
- ...KindShape,
72105
- ids: array(RecordIdSchema).min(1).max(RECORD_BATCH_MAX)
72106
- }), RecordSecretRefsSchema, { auth: "admin" }), method(object({
72107
- ...KindShape,
72108
- record: RecordInputSchema,
72109
- /** Compare-and-set. `0` means "the row must not exist". */
72110
- ifRev: number().int().min(0).optional()
72111
- }), object({
72112
- rev: number().int(),
72113
- releasedRefs: SecretRefsList
72114
- }), {
72115
- kind: "mutation",
72116
- auth: "admin"
72117
- }), method(object({
72118
- ...KindShape,
72119
- records: array(RecordInputSchema).min(1).max(RECORD_BATCH_MAX)
72120
- }), object({
72121
- count: number().int(),
72122
- releasedRefs: SecretRefsList
72123
- }), {
72124
- kind: "mutation",
72125
- auth: "admin"
72126
- }), method(object({
72127
- ...KindShape,
72128
- id: RecordIdSchema,
72129
- data: RecordBodySchema,
72130
- at: number().int().nullable().optional(),
72131
- expiresAt: number().int().nullable().optional(),
72132
- ifRev: number().int().min(1).optional()
72133
- }), object({
72134
- rev: number().int(),
72135
- releasedRefs: SecretRefsList
72136
- }), {
72137
- kind: "mutation",
72138
- auth: "admin"
72139
- }), method(object({
72140
- ...KindShape,
72141
- id: RecordIdSchema
72142
- }), object({
72143
- deleted: boolean(),
72144
- secretRefs: SecretRefsList
72145
- }), {
72146
- kind: "mutation",
72147
- auth: "admin"
72148
- }), method(object({
72149
- ...KindShape,
72150
- ids: array(RecordIdSchema).min(1).max(RECORD_BATCH_MAX)
72151
- }), object({
72152
- deleted: number().int(),
72153
- secretRefs: SecretRefsList
72154
- }), {
72155
- kind: "mutation",
72156
- auth: "admin"
72157
- }), method(RecordQueryInputSchema, RecordQueryResultSchema, { auth: "admin" }), method(object({
72158
- ...KindShape,
72159
- ...TimeWindowShape,
72160
- where: RecordWhereSchema.optional()
72161
- }), object({ count: number().int() }), { auth: "admin" }), method(object({
72162
- ...KindShape,
72163
- deviceId: number().int().optional(),
72164
- from: number(),
72165
- to: number(),
72166
- bucketMs: number().int().positive()
72167
- }), object({ buckets: array(object({
72168
- bucketStart: number(),
72169
- count: number().int()
72170
- })) }), { auth: "admin" }), method(object({
72171
- ...KindShape,
72172
- op: _enum([
72173
- "sum",
72174
- "min",
72175
- "max",
72176
- "count"
72177
- ]),
72178
- field: RecordFieldPathSchema.optional(),
72179
- groupBy: RecordFieldPathSchema.optional(),
72180
- where: RecordWhereSchema.optional()
72181
- }), object({ rows: array(object({
72182
- group: union([
72183
- string(),
72184
- number(),
72185
- _null()
72186
- ]),
72187
- value: number().nullable()
72188
- })) }), { auth: "admin" }), method(object({
72189
- ...KindShape,
72190
- deviceId: number().int().optional(),
72191
- atBefore: number().optional(),
72192
- where: RecordWhereSchema.optional()
72193
- }), object({
72194
- deleted: number().int(),
72195
- secretRefs: SecretRefsList
72196
- }), {
72197
- kind: "mutation",
72198
- auth: "admin"
72199
- }), method(object({ ops: array(RecordTransactOpSchema).min(1).max(RECORD_BATCH_MAX) }), object({
72200
- results: array(object({
72201
- rev: number().int().nullable(),
72202
- deleted: boolean()
72203
- })),
72204
- releasedRefs: SecretRefsList,
72205
- secretRefs: SecretRefsList
72206
- }), {
72207
- kind: "mutation",
72208
- auth: "admin"
72209
- }), method(object({
72210
- deviceId: number().int(),
72211
- kinds: array(RecordKindNameSchema).optional()
72212
- }), object({
72213
- deleted: record(string(), number().int()),
72214
- secretRefs: SecretRefsList
72215
- }), {
72216
- kind: "mutation",
72217
- auth: "admin"
72218
- }), method(object(KindShape), object({ id: number().int() }), {
72219
- kind: "mutation",
72220
- auth: "admin"
72221
- });
72222
- /**
72223
72567
  * record-entries - the ONE admin surface for every list of user-created entries
72224
72568
  * (D881): notification targets, brokers, LLM profiles, anything an addon
72225
72569
  * declares as an ENTRY kind (`entry: { title }` in `defineRecordKinds`).
@@ -82039,7 +82383,7 @@ var BaseDeviceProvider = class extends BaseAddon {
82039
82383
  * `deviceClasses` map (first registered type). `null` when manual creation is
82040
82384
  * unsupported. Lets the Add-Device dialog pick the right type per provider.
82041
82385
  */
82042
- async getManualCreationType() {
82386
+ async getManualCreationType(_input) {
82043
82387
  if (!await this.supportsManualCreation()) return { deviceType: null };
82044
82388
  return { deviceType: Object.values(DeviceType).find((t) => this.deviceClasses[t] !== void 0) ?? null };
82045
82389
  }
@@ -82050,7 +82394,7 @@ var BaseDeviceProvider = class extends BaseAddon {
82050
82394
  return true;
82051
82395
  }
82052
82396
  async getChildCreationSchema(input) {
82053
- return this.onGetCreationSchema(input.type);
82397
+ return this.onGetCreationSchema(input.type, { integrationId: input.integrationId });
82054
82398
  }
82055
82399
  /**
82056
82400
  * Default kernel-orchestrated `createDevice` implementation. The
@@ -82062,7 +82406,7 @@ var BaseDeviceProvider = class extends BaseAddon {
82062
82406
  * `deviceClasses` instead.
82063
82407
  */
82064
82408
  async createDevice(input) {
82065
- const spec = await this.onCreateDevice(input.type, input.config);
82409
+ const spec = await this.onCreateDevice(input.type, input.config, { ...input.integrationId !== void 0 ? { integrationId: input.integrationId } : {} });
82066
82410
  const Class = this.deviceClasses[spec.meta.type];
82067
82411
  if (!Class) throw new Error(`${this.providerName} provider: no device class registered for type "${spec.meta.type}" — add it to the deviceClasses map`);
82068
82412
  const stableId = this.generateStableId(spec.meta.type, spec.config);
@@ -83471,20 +83815,6 @@ Object.freeze({
83471
83815
  access: "create",
83472
83816
  role: "viewer"
83473
83817
  },
83474
- "broker.add": {
83475
- capName: "broker",
83476
- capScope: "system",
83477
- addonId: null,
83478
- access: "create",
83479
- role: "admin"
83480
- },
83481
- "broker.get": {
83482
- capName: "broker",
83483
- capScope: "system",
83484
- addonId: null,
83485
- access: "view",
83486
- role: "admin"
83487
- },
83488
83818
  "broker.getBrokerConfig": {
83489
83819
  capName: "broker",
83490
83820
  capScope: "system",
@@ -83492,20 +83822,6 @@ Object.freeze({
83492
83822
  access: "view",
83493
83823
  role: "admin"
83494
83824
  },
83495
- "broker.getSettings": {
83496
- capName: "broker",
83497
- capScope: "system",
83498
- addonId: null,
83499
- access: "view",
83500
- role: "admin"
83501
- },
83502
- "broker.getSettingsSchema": {
83503
- capName: "broker",
83504
- capScope: "system",
83505
- addonId: null,
83506
- access: "view",
83507
- role: "admin"
83508
- },
83509
83825
  "broker.getState": {
83510
83826
  capName: "broker",
83511
83827
  capScope: "system",
@@ -83520,20 +83836,6 @@ Object.freeze({
83520
83836
  access: "view",
83521
83837
  role: "admin"
83522
83838
  },
83523
- "broker.list": {
83524
- capName: "broker",
83525
- capScope: "system",
83526
- addonId: null,
83527
- access: "view",
83528
- role: "admin"
83529
- },
83530
- "broker.listProviders": {
83531
- capName: "broker",
83532
- capScope: "system",
83533
- addonId: null,
83534
- access: "view",
83535
- role: "admin"
83536
- },
83537
83839
  "broker.publish": {
83538
83840
  capName: "broker",
83539
83841
  capScope: "system",
@@ -83541,20 +83843,6 @@ Object.freeze({
83541
83843
  access: "create",
83542
83844
  role: "admin"
83543
83845
  },
83544
- "broker.remove": {
83545
- capName: "broker",
83546
- capScope: "system",
83547
- addonId: null,
83548
- access: "delete",
83549
- role: "admin"
83550
- },
83551
- "broker.setSettings": {
83552
- capName: "broker",
83553
- capScope: "system",
83554
- addonId: null,
83555
- access: "create",
83556
- role: "admin"
83557
- },
83558
83846
  "broker.subscribe": {
83559
83847
  capName: "broker",
83560
83848
  capScope: "system",
@@ -83562,20 +83850,6 @@ Object.freeze({
83562
83850
  access: "create",
83563
83851
  role: "admin"
83564
83852
  },
83565
- "broker.testConnection": {
83566
- capName: "broker",
83567
- capScope: "system",
83568
- addonId: null,
83569
- access: "create",
83570
- role: "admin"
83571
- },
83572
- "broker.testSettings": {
83573
- capName: "broker",
83574
- capScope: "system",
83575
- addonId: null,
83576
- access: "create",
83577
- role: "admin"
83578
- },
83579
83853
  "broker.unsubscribe": {
83580
83854
  capName: "broker",
83581
83855
  capScope: "system",
@@ -88336,13 +88610,6 @@ Object.freeze({
88336
88610
  access: "view",
88337
88611
  role: "viewer"
88338
88612
  },
88339
- "petFountain.resetDailyConsumption": {
88340
- capName: "pet-fountain",
88341
- capScope: "device",
88342
- addonId: null,
88343
- access: "delete",
88344
- role: "viewer"
88345
- },
88346
88613
  "petFountain.setPump": {
88347
88614
  capName: "pet-fountain",
88348
88615
  capScope: "device",
@@ -88539,6 +88806,13 @@ Object.freeze({
88539
88806
  access: "view",
88540
88807
  role: "viewer"
88541
88808
  },
88809
+ "pipelineAnalytics.getMediaLocationCensus": {
88810
+ capName: "pipeline-analytics",
88811
+ capScope: "device",
88812
+ addonId: null,
88813
+ access: "view",
88814
+ role: "admin"
88815
+ },
88542
88816
  "pipelineAnalytics.getMediaReclaimStatus": {
88543
88817
  capName: "pipeline-analytics",
88544
88818
  capScope: "device",
@@ -94732,11 +95006,6 @@ Object.freeze({
94732
95006
  form: "single",
94733
95007
  optional: false
94734
95008
  }],
94735
- "petFountain.resetDailyConsumption": [{
94736
- name: "deviceId",
94737
- form: "single",
94738
- optional: false
94739
- }],
94740
95009
  "petFountain.setPump": [{
94741
95010
  name: "deviceId",
94742
95011
  form: "single",
@@ -99373,18 +99642,19 @@ var EnpalProviderAddon = class extends BaseDeviceProvider {
99373
99642
  const records = this.ctx.records;
99374
99643
  if (records === void 0) throw new Error("provider-enpal: ctx.records is required (hub-only addon)");
99375
99644
  await records.declare(enpalRecordKinds);
99376
- await this.runMigrations(defineAddonMigrations([integrationRowsMigration({
99645
+ this.declareRegistrySwitch({
99646
+ kind: enpalConnectionsEntryKind,
99647
+ initialBody: (name) => ({ name })
99648
+ });
99649
+ await this.runMigrations([integrationRowsMigration({
99377
99650
  addonId: this.addonId,
99378
99651
  date: ENPAL_MIGRATIONS_DATE,
99379
99652
  kind: enpalConnectionsEntryKind,
99380
99653
  fixtureMark: "host"
99381
- })], integrationRowsPortsOver({
99382
- api: defaultIntegrationApiOver(this.ctx.api),
99383
- secrets: this.ctx.secrets ?? null,
99384
- records,
99385
- kind: enpalConnectionsEntryKind,
99386
- warn: (message) => this.ctx.logger.warn(message)
99387
- })));
99654
+ })], (api) => integrationRowsPortsOver({
99655
+ ...rowsDepsOver(api),
99656
+ kind: enpalConnectionsEntryKind
99657
+ }));
99388
99658
  this.instances = buildEnpalInstances(records, { onChanged: () => this.reconcileIntegrations() });
99389
99659
  this.clients = new EnpalClientRegistry(this.ctx.logger, {
99390
99660
  onConnected: (integrationId) => this.setIntegrationDevicesOnline(integrationId, true),
@@ -99466,8 +99736,9 @@ var EnpalProviderAddon = class extends BaseDeviceProvider {
99466
99736
  const integrationId = event.data["integrationId"];
99467
99737
  this.reconciler().onLifecycle(kind, typeof integrationId === "string" ? integrationId : null);
99468
99738
  };
99469
- this.ctx.eventBus.subscribe({ category: EventCategory.IntegrationEnabled }, on("enabled"));
99470
- this.ctx.eventBus.subscribe({ category: EventCategory.IntegrationDisabled }, on("disabled"));
99739
+ this.requireInstances().onSwitched((id, enabled) => {
99740
+ this.reconciler().onLifecycle(enabled ? "enabled" : "disabled", id);
99741
+ });
99471
99742
  this.ctx.eventBus.subscribe({ category: EventCategory.IntegrationDeleted }, on("deleted"));
99472
99743
  }
99473
99744
  /** The integrations that own devices here, for the orphan sweep. */