@camstack/addon-provider-hikvision 1.2.182 → 1.2.184

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/addon.js +1666 -1253
  3. package/dist/addon.mjs +1666 -1253
  4. package/package.json +2 -2
package/dist/addon.js CHANGED
@@ -6014,7 +6014,7 @@ var ZodIssueCode = {
6014
6014
  var ZodFirstPartyTypeKind;
6015
6015
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
6016
6016
  //#endregion
6017
- //#region ../types/dist/sleep-9TIHFj1w.mjs
6017
+ //#region ../types/dist/sleep-CmjWurK5.mjs
6018
6018
  /**
6019
6019
  * The audio chunk plane's byte format, and the ONE expansion from a coded
6020
6020
  * window to float samples (D455).
@@ -6698,130 +6698,178 @@ async function runAddonMigrations(host, migrations, logger, options = {}) {
6698
6698
  blockOwner
6699
6699
  };
6700
6700
  }
6701
- /**
6702
- * Build a {@link DurableState} over a single store key. Transport-agnostic:
6703
- * `read`/`write` are the addon-store or device-store accessors. The whole
6704
- * validated value round-trips on every read/write — the schema is the
6705
- * single source of truth for what is persisted, so no hand-listed field
6706
- * set can drop a key on save.
6707
- */
6708
- function createDurableState(deps) {
6709
- const get = async () => {
6710
- const raw = (await deps.read())[deps.key];
6711
- if (raw === void 0) return deps.fallback;
6712
- const parsed = deps.schema.safeParse(raw);
6713
- if (!parsed.success) {
6714
- deps.onParseError?.(deps.key, parsed.error);
6715
- return deps.fallback;
6716
- }
6717
- return parsed.data;
6718
- };
6719
- const set = async (next) => {
6720
- const validated = deps.schema.parse(next);
6721
- await deps.write({ [deps.key]: validated });
6722
- };
6723
- const update = async (fn) => {
6724
- await set(fn(await get()));
6701
+ function secretsOverMigrationApi(api) {
6702
+ return {
6703
+ resolve: async (refs) => {
6704
+ const { values } = await api.secrets.resolve({ refs: [...refs] });
6705
+ const out = {};
6706
+ for (const ref of refs) {
6707
+ const value = values[ref];
6708
+ out[ref] = value === null || value === void 0 ? { kind: "missing" } : {
6709
+ kind: "value",
6710
+ value,
6711
+ version: 0
6712
+ };
6713
+ }
6714
+ return out;
6715
+ },
6716
+ delete: async (refs) => (await api.secrets.delete({ refs: [...refs] })).deleted
6725
6717
  };
6718
+ }
6719
+ /** The record calls the one-switch migration makes, over the migration API. */
6720
+ function switchRecordsOverMigrationApi(api) {
6721
+ return { kind: (definition) => {
6722
+ const handle = api.records.kind(definition);
6723
+ return {
6724
+ get: (id) => handle.get({ id }),
6725
+ put: (input, opts) => handle.put({
6726
+ ...input,
6727
+ ...opts?.ifRev === void 0 ? {} : { ifRev: opts.ifRev }
6728
+ }),
6729
+ patch: (id, partial) => handle.patch({
6730
+ id,
6731
+ partial
6732
+ })
6733
+ };
6734
+ } };
6735
+ }
6736
+ /** `ctx.records` as the migration API offers it: bind a kind, read and write by id. */
6737
+ function recordsOverMigrationApi(api) {
6738
+ return { kind: (definition) => {
6739
+ const handle = api.records.kind(definition);
6740
+ return {
6741
+ get: (id) => handle.get({ id }),
6742
+ getResolved: (id) => handle.getResolved({ id }),
6743
+ put: (input, opts) => handle.put({
6744
+ ...input,
6745
+ ...opts?.ifRev === void 0 ? {} : { ifRev: opts.ifRev }
6746
+ }),
6747
+ delete: (id) => handle.delete({ id })
6748
+ };
6749
+ } };
6750
+ }
6751
+ function integrationRowsApiOver(api) {
6726
6752
  return {
6727
- get,
6728
- set,
6729
- update
6753
+ list: async () => (await api.integrations.list({})).integrations,
6754
+ readLegacyIntegrationRows: (input) => api.legacyRows.read(input),
6755
+ clearLegacyIntegrationRows: (input) => api.legacyRows.clear(input)
6730
6756
  };
6731
6757
  }
6732
6758
  /**
6733
- * Per-node scoping for the shared addon-settings blob.
6734
- *
6735
- * An addon's settings store is hub-central (the `addon-settings` cap is
6736
- * hub-routed — the hub instance answers for every node), so fields whose
6737
- * value is a NODE fact (decoder backend, engine pick, probed hardware
6738
- * capabilities) persist under the node-scoped key `<key>@<nodeId>` inside
6739
- * the single shared blob. The SCHEMA field key stays bare: the write path
6740
- * ({@link scopePatch}) maps the bare field onto the target node's scoped
6741
- * key; the read/hydrate path ({@link projectStore}) maps THIS node's value
6742
- * back, so UI forms and `resolveConfig` only ever see the bare key.
6743
- *
6744
- * Fields opt in via the `perNode: true` schema marker on `ConfigFieldBase`
6745
- * (`interfaces/config-ui.ts`); `BaseAddon` derives the key set from the
6746
- * schema and routes reads/writes through these helpers.
6747
- *
6748
- * ## No bare-key fallback — deliberate
6749
- *
6750
- * {@link readNodeValue} reads the node-scoped key ONLY. A node with no
6751
- * scoped key resolves to `undefined` so the field's schema `default` wins —
6752
- * NEVER `store[base]` and never another node's value. A bare legacy key in
6753
- * the store is invisible to every node, hub included, so one node's
6754
- * selection can never leak onto another. (This generalizes the
6755
- * `decoder-backend-keys.ts` semantics — the no-fallback variant — over an
6756
- * arbitrary set of per-node field keys.)
6757
- *
6758
- * Pure functions only — no I/O, no imports beyond the language. This is a
6759
- * LEAF module: import it via its deep path, never from the root barrel.
6760
- */
6761
- /**
6762
- * Normalize a raw kernel node id to the bare node id used for scoping.
6763
- * `localNodeId` can carry a `<node>/<addon>` suffix on forked child
6764
- * processes; per-node settings are per-NODE, so strip the addon segment.
6765
- * `undefined` / `null` / empty falls back to `'hub'`.
6759
+ * One serial lane per migration API: a log line is delivered after the line before it, so the
6760
+ * order the steps wrote them in is the order the hub reads them in. A delivery that fails
6761
+ * is reported once through the same door; if that fails too nothing is left to tell, and the
6762
+ * line is dropped rather than thrown into a migration step or left as an unhandled rejection.
6766
6763
  */
6767
- function normalizeNodeId(raw) {
6768
- if (raw === void 0 || raw === null || raw === "") return "hub";
6769
- const slashIdx = raw.indexOf("/");
6770
- if (slashIdx < 0) return raw;
6771
- const bare = raw.slice(0, slashIdx);
6772
- return bare === "" ? "hub" : bare;
6764
+ var lanes = /* @__PURE__ */ new WeakMap();
6765
+ function deliver(api, send) {
6766
+ const next = (lanes.get(api) ?? Promise.resolve()).then(send).then(() => void 0).catch(async (error) => {
6767
+ const reason = error instanceof Error ? error.message : String(error);
6768
+ await api.log.warn({ message: `a migration log line could not be delivered: ${reason}` }).catch(() => void 0);
6769
+ });
6770
+ lanes.set(api, next);
6771
+ return next;
6773
6772
  }
6774
- /** The node-scoped store key for a per-node field: `<base>@<nodeId>`. */
6775
- function nodeScopedKey(base, nodeId) {
6776
- return `${base}@${normalizeNodeId(nodeId)}`;
6773
+ function warnOver(api) {
6774
+ return (message) => deliver(api, () => api.log.warn({ message }));
6777
6775
  }
6778
- /**
6779
- * Read a node's value for a per-node field from the raw shared store:
6780
- * the node-scoped key when present, otherwise `undefined`.
6781
- * Deliberately NO bare-key fallback (see module doc) — the caller lets the
6782
- * schema `default` win on `undefined`.
6783
- */
6784
- function readNodeValue(store, base, nodeId) {
6785
- return store[nodeScopedKey(base, nodeId)];
6776
+ /** What the rows-to-records move needs, over the migration API. */
6777
+ function rowsDepsOver(api) {
6778
+ return {
6779
+ api: integrationRowsApiOver(api),
6780
+ records: recordsOverMigrationApi(api),
6781
+ secrets: secretsOverMigrationApi(api),
6782
+ warn: warnOver(api)
6783
+ };
6786
6784
  }
6787
- /**
6788
- * Re-map a UI/settings patch so every bare perNode field persists under the
6789
- * TARGET node's scoped key; all other keys pass through unchanged. Used on
6790
- * the write path so a save for one node never clobbers another node's value
6791
- * (and the bare key is never written). Returns a new object — the input
6792
- * patch is not mutated.
6793
- */
6794
- function scopePatch(patch, perNodeKeys, nodeId) {
6795
- const out = {};
6796
- for (const [key, value] of Object.entries(patch)) out[perNodeKeys.has(key) ? nodeScopedKey(key, nodeId) : key] = value;
6797
- return out;
6785
+ function defaultIntegrationApiOver(api) {
6786
+ return {
6787
+ ...integrationRowsApiOver(api),
6788
+ listDevices: async (addonId) => (await api.devices.list({ addonId })).devices,
6789
+ readDeviceHasConfig: async (deviceId) => (await api.devices.get({ deviceId }))?.hasConfig ?? false,
6790
+ setDeviceIntegrationId: async (deviceId, integrationId) => {
6791
+ await api.devices.setIntegrationId({
6792
+ deviceId,
6793
+ integrationId
6794
+ });
6795
+ },
6796
+ readDeviceIntegrationId: async (deviceId) => (await api.devices.get({ deviceId }))?.integrationId ?? null
6797
+ };
6798
6798
  }
6799
- /**
6800
- * Project the raw shared store onto the bare schema keys for ONE node so a
6801
- * UI schema (whose field keys are bare) hydrates from that node's own
6802
- * values:
6803
- *
6804
- * - EVERY `@`-scoped key (any node's) is dropped from the pass-through.
6805
- * - Every bare perNode key is dropped from the pass-through (a stray bare
6806
- * legacy key must never hydrate any node — no bare fallback).
6807
- * - THIS node's effective value ({@link readNodeValue}) is then laid onto
6808
- * each bare perNode key; when the node has no scoped key the bare key is
6809
- * left ABSENT so the field's schema `default` wins.
6810
- *
6811
- * Returns a new object — the input store is not mutated.
6812
- */
6813
- function projectStore(store, perNodeKeys, nodeId) {
6814
- const out = {};
6815
- for (const [key, value] of Object.entries(store)) {
6816
- if (key.includes("@")) continue;
6817
- if (perNodeKeys.has(key)) continue;
6818
- out[key] = value;
6799
+ /** What the rows-to-records move and the device claim need, over the migration API. */
6800
+ function defaultIntegrationDepsOver(api) {
6801
+ return {
6802
+ ...rowsDepsOver(api),
6803
+ api: defaultIntegrationApiOver(api),
6804
+ info: (message) => deliver(api, () => api.log.info({ message })),
6805
+ warnDevice: (message, deviceId) => deliver(api, () => api.log.warn({
6806
+ message,
6807
+ tags: { deviceId }
6808
+ }))
6809
+ };
6810
+ }
6811
+ var PREFIX = "records/";
6812
+ /** The base of every records failure. `detail` is the human part of the message. */
6813
+ var RecordsError = class extends Error {
6814
+ code;
6815
+ detail;
6816
+ constructor(code, detail) {
6817
+ super(`${PREFIX}${code}: ${detail}`);
6818
+ this.name = "RecordsError";
6819
+ this.code = code;
6820
+ this.detail = detail;
6819
6821
  }
6820
- for (const base of perNodeKeys) {
6821
- const value = readNodeValue(store, base, nodeId);
6822
- if (value !== void 0) out[base] = value;
6822
+ };
6823
+ /** A write guarded by `ifRev` found another revision (or an existing row for `ifRev: 0`). */
6824
+ var RevConflictError = class extends RecordsError {
6825
+ constructor(detail) {
6826
+ super("rev-conflict", detail);
6827
+ this.name = "RevConflictError";
6823
6828
  }
6824
- return out;
6829
+ };
6830
+ /** The keychain could not store or serve a value: explicit, never an empty string. */
6831
+ var RecordSecretUnavailableError = class extends RecordsError {
6832
+ constructor(detail) {
6833
+ super("secret-unavailable", detail);
6834
+ this.name = "RecordSecretUnavailableError";
6835
+ }
6836
+ };
6837
+ var InvalidRecordError = class extends RecordsError {
6838
+ constructor(detail) {
6839
+ super("invalid-record", detail);
6840
+ this.name = "InvalidRecordError";
6841
+ }
6842
+ };
6843
+ /** A kind declaration the engine refuses (non-additive change, bad shape, wrong file). */
6844
+ var DeclarationRefusedError = class extends RecordsError {
6845
+ constructor(detail) {
6846
+ super("declaration-refused", detail);
6847
+ this.name = "DeclarationRefusedError";
6848
+ }
6849
+ };
6850
+ function linkTargetOf(meta) {
6851
+ if (typeof meta !== "object" || meta === null) return void 0;
6852
+ const link = Reflect.get(meta, "link");
6853
+ const parsed = LinkTargetSchema.safeParse(link);
6854
+ return parsed.success ? parsed.data : void 0;
6855
+ }
6856
+ var LinkTargetSchema = object({
6857
+ cap: string().min(1),
6858
+ kind: string().min(1).optional()
6859
+ });
6860
+ /** The links a kind declares, read from the meta of its body fields. */
6861
+ function linksOfKind(kind) {
6862
+ const schema = kind.schema;
6863
+ if (!(schema instanceof ZodObject)) return [];
6864
+ const links = [];
6865
+ for (const [field, fieldSchema] of Object.entries(schema.shape)) {
6866
+ const to = linkTargetOf(globalRegistry.get(fieldSchema));
6867
+ if (to !== void 0) links.push({
6868
+ field,
6869
+ to
6870
+ });
6871
+ }
6872
+ return links;
6825
6873
  }
6826
6874
  /**
6827
6875
  * The address of one keychain value: `secret://<owner>/<scope>/<fieldPath>`.
@@ -6957,6 +7005,652 @@ function parseSecretRef(ref) {
6957
7005
  fieldPath
6958
7006
  };
6959
7007
  }
7008
+ /** Limits and names of `ctx.records` (D881). One authority; the engine and the facade read it. */
7009
+ /** The files a kind may live in. `history` is device-history's (D850), never records. */
7010
+ var RECORD_DATABASES = ["settings", "events"];
7011
+ /** The classes of a kind: the `@durable` vocabulary, one authority (replaces the annotation). */
7012
+ var RECORD_CLASSES = [
7013
+ "config",
7014
+ "ledger",
7015
+ "audit",
7016
+ "mirror",
7017
+ "ephemeral"
7018
+ ];
7019
+ var RECORD_DEFAULT_MAX_DATA_BYTES = 64 * 1024;
7020
+ var RECORD_MAX_DATA_BYTES = 1024 * 1024;
7021
+ var RECORD_BATCH_MAX = 1e3;
7022
+ var RECORD_QUERY_MAX = 1e3;
7023
+ /** A kind in the `settings` file may not bound itself above this (D447: high volume is `events`). */
7024
+ var RECORD_SETTINGS_MAX_ROWS = 5e4;
7025
+ /** The `Column`-free proof prefix: a ref collection for a kind's secret fields. */
7026
+ var RECORD_SECRET_COLLECTION_PREFIX = "records:";
7027
+ /**
7028
+ * Secret fields of a record, addressed the way a Zod schema declares them
7029
+ * (`collectZodSecretPaths`): dotted keys, `[]` for "each element of this array"
7030
+ * (`auth.accessToken`, `headers[].value`).
7031
+ *
7032
+ * `{}` after a key means "each value of this map" (`applianceSecrets{}`): the map's own key
7033
+ * names the value (`applianceSecrets{fridge}`), so no id key is declared and a body that drops a
7034
+ * key releases exactly that key's secret.
7035
+ *
7036
+ * Array elements are matched by a DECLARED id key (`secretArrayKeys`:
7037
+ * `{ headers: 'name' }`), never by index, so reordering a list keeps every
7038
+ * keychain ref (the same rule as `arrayItemFieldPath`). The concrete path of a
7039
+ * leaf names its element: `headers[X-Api].value`.
7040
+ *
7041
+ * Pure and browser-safe. Nothing here mutates: every transform returns a new value.
7042
+ */
7043
+ /** The array prefixes (declared form, e.g. `headers` or `a.headers`) of a path. */
7044
+ function parseSecretPath(path) {
7045
+ if (path.length === 0) throw new InvalidRecordError("an empty secret path");
7046
+ return path.split(".").map((raw) => {
7047
+ const each = raw.endsWith("[]");
7048
+ const map = raw.endsWith("{}");
7049
+ const key = each || map ? raw.slice(0, -2) : raw;
7050
+ if (key.length === 0) throw new InvalidRecordError(`secret path "${path}" has an empty segment`);
7051
+ return {
7052
+ key,
7053
+ each,
7054
+ map
7055
+ };
7056
+ });
7057
+ }
7058
+ /** The declared array prefixes of `path` that need an id key (`headers`, `a.rows`). */
7059
+ function secretArrayPrefixes(path) {
7060
+ const segments = parseSecretPath(path);
7061
+ const prefixes = [];
7062
+ const walked = [];
7063
+ for (const segment of segments) {
7064
+ walked.push(segment.key);
7065
+ if (segment.each) prefixes.push(walked.join("."));
7066
+ }
7067
+ return prefixes;
7068
+ }
7069
+ function isRecord$6(value) {
7070
+ return typeof value === "object" && value !== null && !Array.isArray(value);
7071
+ }
7072
+ function elementId(element, idKey, declared, prefix) {
7073
+ const id = isRecord$6(element) ? element[idKey] : void 0;
7074
+ 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`);
7075
+ return id;
7076
+ }
7077
+ /**
7078
+ * Visit every secret leaf PRESENT in `data` (an absent branch has nothing to
7079
+ * visit). `replace` returns the new leaf value, or {@link REMOVE_LEAF}; the
7080
+ * result is a new body, `data` is untouched.
7081
+ */
7082
+ var REMOVE_LEAF = Symbol("remove-leaf");
7083
+ function mapAt(node, segments, index, walkedKeys, concretePrefix, declared, arrayKeys, visit) {
7084
+ if (!isRecord$6(node)) return node;
7085
+ const segment = segments[index];
7086
+ if (segment === void 0) return node;
7087
+ if (!Object.prototype.hasOwnProperty.call(node, segment.key)) return node;
7088
+ const child = node[segment.key];
7089
+ const keys = [...walkedKeys, segment.key];
7090
+ const last = index === segments.length - 1;
7091
+ if (segment.each) {
7092
+ if (!Array.isArray(child)) return node;
7093
+ const prefix = keys.join(".");
7094
+ const idKey = arrayKeys[prefix];
7095
+ if (idKey === void 0) throw new InvalidRecordError(`"${declared}": no id key declared for the array "${prefix}"`);
7096
+ const mapped = child.map((element) => {
7097
+ const id = elementId(element, idKey, declared, prefix);
7098
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}[${encodeURIComponent(id)}]`;
7099
+ return last ? element : mapAt(element, segments, index + 1, keys, concrete, declared, arrayKeys, visit);
7100
+ });
7101
+ return {
7102
+ ...node,
7103
+ [segment.key]: mapped
7104
+ };
7105
+ }
7106
+ if (segment.map) {
7107
+ if (!isRecord$6(child)) return node;
7108
+ const kept = Object.entries(child).map(([mapKey, value]) => {
7109
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}{${encodeURIComponent(mapKey)}}`;
7110
+ if (!last) return [mapKey, mapAt(value, segments, index + 1, keys, concrete, declared, arrayKeys, visit)];
7111
+ return [mapKey, visit({
7112
+ declared,
7113
+ concrete,
7114
+ value
7115
+ })];
7116
+ }).filter(([, value]) => value !== REMOVE_LEAF);
7117
+ return {
7118
+ ...node,
7119
+ [segment.key]: Object.fromEntries(kept)
7120
+ };
7121
+ }
7122
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}`;
7123
+ if (last) {
7124
+ const replacement = visit({
7125
+ declared,
7126
+ concrete,
7127
+ value: child
7128
+ });
7129
+ if (replacement === REMOVE_LEAF) return Object.fromEntries(Object.entries(node).filter(([key]) => key !== segment.key));
7130
+ return {
7131
+ ...node,
7132
+ [segment.key]: replacement
7133
+ };
7134
+ }
7135
+ return {
7136
+ ...node,
7137
+ [segment.key]: mapAt(child, segments, index + 1, keys, concrete, declared, arrayKeys, visit)
7138
+ };
7139
+ }
7140
+ /** Replace/remove every present secret leaf; returns a NEW body. */
7141
+ function mapSecretLeaves(data, paths, arrayKeys, visit) {
7142
+ let current = data;
7143
+ for (const declared of paths) current = mapAt(current, parseSecretPath(declared), 0, [], "", declared, arrayKeys, visit);
7144
+ return current;
7145
+ }
7146
+ /** Every present secret leaf, read-only. */
7147
+ function collectSecretLeaves(data, paths, arrayKeys) {
7148
+ const found = [];
7149
+ mapSecretLeaves(data, paths, arrayKeys, (leaf) => {
7150
+ found.push(leaf);
7151
+ return leaf.value;
7152
+ });
7153
+ return found;
7154
+ }
7155
+ /**
7156
+ * The keychain collection name a kind's secrets live under. Prefixed so a
7157
+ * record's refs never collide with the refs a legacy collection of the same name
7158
+ * already holds during an adoption.
7159
+ */
7160
+ function recordSecretCollection(kind) {
7161
+ return `${RECORD_SECRET_COLLECTION_PREFIX}${kind}`;
7162
+ }
7163
+ /** The ONE ref a row's secret field may carry: the engine and the facade both build it here. */
7164
+ function recordSecretRef(owner, kind, rowId, concretePath) {
7165
+ return buildSecretRef({
7166
+ owner,
7167
+ scope: {
7168
+ kind: "row",
7169
+ collection: recordSecretCollection(kind),
7170
+ rowId
7171
+ },
7172
+ fieldPath: concretePath
7173
+ });
7174
+ }
7175
+ /**
7176
+ * A stored secret, as an admin read shows it: a VIEW naming the row's own
7177
+ * keychain ref (`set: true`), never the value and no longer the bare redaction
7178
+ * token. The form hands it to the secret field, which reveals the value by ref
7179
+ * through the audited `keychain-admin.reveal`; sent back untouched it keeps the
7180
+ * stored secret (the records door reads a view as KEEP).
7181
+ *
7182
+ * ONE implementation for the entries service and for every addon that serves
7183
+ * its own instances (`RecordIntegrationInstances`).
7184
+ */
7185
+ function isRecord$5(value) {
7186
+ return typeof value === "object" && value !== null && !Array.isArray(value);
7187
+ }
7188
+ function secretViewsOf(owner, kind, id, decl, data) {
7189
+ if (decl.secretPaths.length === 0) return data;
7190
+ const shown = mapSecretLeaves(data, decl.secretPaths, decl.secretArrayKeys, (leaf) => {
7191
+ if (leaf.value !== "__camstack_redacted__") return leaf.value;
7192
+ return {
7193
+ $secret: recordSecretRef(owner, kind, id, leaf.concrete),
7194
+ v: 1,
7195
+ set: true
7196
+ };
7197
+ });
7198
+ return isRecord$5(shown) ? shown : data;
7199
+ }
7200
+ /** The most instances one addon lists (an integrations page, not a table). */
7201
+ var INSTANCES_LIST_MAX = 1e3;
7202
+ /**
7203
+ * The ONE reader of an instance's switch (D996): an absent field means on, so a row written
7204
+ * before the field existed needs no migration. Every consumer of an instance body asks this.
7205
+ */
7206
+ function isInstanceEnabled(body) {
7207
+ return body.enabled !== false;
7208
+ }
7209
+ /** The body key of the switch; only {@link RecordIntegrationInstances.setInstanceEnabled} writes it. */
7210
+ var SWITCH_KEY = "enabled";
7211
+ /** The keys of the kind's secret fields that sit at the top level of the body. */
7212
+ function topLevelSecretKeys(paths) {
7213
+ return new Set(paths.filter((p) => !p.includes(".") && !p.includes("[") && !p.includes("{")));
7214
+ }
7215
+ /** The keys of the kind's top-level MAPS whose values are secrets (`applianceSecrets{}`). */
7216
+ function secretMapKeys(paths) {
7217
+ return new Set(paths.filter((p) => p.endsWith("{}") && !p.slice(0, -2).match(/[.[{]/)).map((p) => p.slice(0, -2)));
7218
+ }
7219
+ /**
7220
+ * A patch value for a map of secrets: an entry that is omitted, `''`, the redaction token or the
7221
+ * view the form was given KEEPS its stored secret (it is left out of the merge); `{ $secretClear }`
7222
+ * or `null` removes the entry; any other string replaces it. Null when nothing is left to merge.
7223
+ */
7224
+ function secretMapPatch(value) {
7225
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
7226
+ const out = {};
7227
+ for (const [key, entry] of Object.entries(value)) if (entry === null || isSecretClear(entry)) out[key] = null;
7228
+ else if (typeof entry === "string" && entry !== "" && entry !== "__camstack_redacted__" && !isSecretFieldView(entry)) out[key] = entry;
7229
+ return Object.keys(out).length > 0 ? out : null;
7230
+ }
7231
+ var RecordIntegrationInstances = class {
7232
+ records;
7233
+ kind;
7234
+ hooks;
7235
+ handle;
7236
+ secretKeys;
7237
+ secretMaps;
7238
+ nameField;
7239
+ switchListeners = /* @__PURE__ */ new Set();
7240
+ constructor(records, kind, hooks) {
7241
+ this.records = records;
7242
+ this.kind = kind;
7243
+ this.hooks = hooks;
7244
+ this.handle = records.kind(kind);
7245
+ this.secretKeys = topLevelSecretKeys(kind.declaration.secretPaths);
7246
+ this.secretMaps = secretMapKeys(kind.declaration.secretPaths);
7247
+ this.nameField = kind.declaration.entry?.nameField ?? "name";
7248
+ }
7249
+ /**
7250
+ * One instance read for the addon's own runtime; null when absent. When the keychain is
7251
+ * locked the row is served WITHOUT its secrets and says so (`secrets: 'unavailable'`), so the
7252
+ * caller can keep what it had instead of reconfiguring with an empty secret (D49).
7253
+ */
7254
+ async readResolved(id) {
7255
+ try {
7256
+ const record = await this.handle.getResolved(id);
7257
+ return record === null ? null : {
7258
+ id,
7259
+ body: record.data,
7260
+ enabled: isInstanceEnabled(record.data),
7261
+ secrets: "resolved"
7262
+ };
7263
+ } catch (err) {
7264
+ if (!(err instanceof RecordSecretUnavailableError)) throw err;
7265
+ const stored = await this.handle.get(id);
7266
+ if (stored === null) return null;
7267
+ return {
7268
+ id,
7269
+ body: Object.fromEntries(Object.entries(stored.data).filter(([key]) => !this.secretKeys.has(key))),
7270
+ enabled: isInstanceEnabled(stored.data),
7271
+ secrets: "unavailable"
7272
+ };
7273
+ }
7274
+ }
7275
+ /** The body of {@link readResolved} alone; a locked keychain yields the row without secrets. */
7276
+ async getResolved(id) {
7277
+ return (await this.readResolved(id))?.body ?? null;
7278
+ }
7279
+ /** Every instance, secrets resolved where the keychain allows; an absent one is skipped. */
7280
+ async listResolved() {
7281
+ const page = await this.handle.query({ limit: INSTANCES_LIST_MAX });
7282
+ const out = [];
7283
+ for (const record of page.records) {
7284
+ const read = await this.readResolved(record.id);
7285
+ if (read !== null) out.push(read);
7286
+ }
7287
+ return out;
7288
+ }
7289
+ viewOf(record) {
7290
+ const shown = secretViewsOf(this.records.owner, this.kind.name, record.id, this.kind.declaration, record.data);
7291
+ const rawName = record.data[this.nameField];
7292
+ const kind = this.hooks.kindOf?.(record.data);
7293
+ const health = this.hooks.health?.(record.data, record.id);
7294
+ return {
7295
+ id: record.id,
7296
+ name: typeof rawName === "string" ? rawName : record.id,
7297
+ configured: this.hooks.configured(record.data),
7298
+ enabled: isInstanceEnabled(record.data),
7299
+ formValues: shown,
7300
+ ...kind !== void 0 ? { kind } : {},
7301
+ ...health?.status !== void 0 ? { status: health.status } : {},
7302
+ ...health?.lastCheckedAt !== void 0 ? { lastCheckedAt: health.lastCheckedAt } : {}
7303
+ };
7304
+ }
7305
+ describe = async () => {
7306
+ const declared = linksOfKind(this.kind);
7307
+ const links = this.hooks.description.links !== void 0 || declared.length === 0 ? {} : { links: declared.map((link) => ({
7308
+ kind: this.kind.name,
7309
+ field: link.field,
7310
+ to: link.to
7311
+ })) };
7312
+ return {
7313
+ ...this.hooks.description,
7314
+ ...links,
7315
+ ...this.hooks.mintId === void 0 ? {} : { mintsId: true }
7316
+ };
7317
+ };
7318
+ instanceFormSchema = async ({ id }) => this.hooks.formSchema(id);
7319
+ listInstances = async () => {
7320
+ return (await this.handle.query({ limit: INSTANCES_LIST_MAX })).records.map((record) => this.viewOf(record));
7321
+ };
7322
+ getInstance = async ({ id }) => {
7323
+ const record = await this.handle.get(id);
7324
+ return record === null ? null : this.viewOf(record);
7325
+ };
7326
+ /** Insert ONE row (`ifRev: 0`: an existing id is refused, never overwritten). */
7327
+ createInstance = async ({ id, name, kind, values }) => {
7328
+ const minted = id ?? this.hooks.mintId?.({
7329
+ name,
7330
+ ...kind !== void 0 ? { kind } : {}
7331
+ });
7332
+ if (minted === void 0) throw new Error("createInstance needs an id: this provider does not mint one");
7333
+ await this.handle.put({
7334
+ id: minted,
7335
+ data: this.hooks.initialBody(name, kind)
7336
+ }, { ifRev: 0 });
7337
+ const patch = this.patchOf(values ?? {});
7338
+ if (Object.keys(patch).length > 0) await this.handle.patch(minted, patch);
7339
+ await this.hooks.onChanged?.(minted, "created");
7340
+ return { id: minted };
7341
+ };
7342
+ updateInstance = async ({ id, name, values }) => {
7343
+ const patch = this.patchOf(values);
7344
+ if (name !== void 0) patch[this.nameField] = name;
7345
+ await this.handle.patch(id, patch);
7346
+ await this.hooks.onChanged?.(id, "updated");
7347
+ return { ok: true };
7348
+ };
7349
+ /** The record patch a form `values` object means: secrets kept, cleared or replaced. */
7350
+ patchOf(values) {
7351
+ const patch = {};
7352
+ for (const [key, value] of Object.entries(values)) {
7353
+ if (value === void 0) continue;
7354
+ if (key === "enabled") continue;
7355
+ if (this.secretMaps.has(key)) {
7356
+ const entries = secretMapPatch(value);
7357
+ if (entries !== null) patch[key] = entries;
7358
+ } else if (!this.secretKeys.has(key)) patch[key] = value;
7359
+ else if (isSecretClear(value)) patch[key] = null;
7360
+ else if (typeof value === "string" && value !== "" && value !== "__camstack_redacted__" && !isSecretFieldView(value)) patch[key] = value;
7361
+ }
7362
+ return patch;
7363
+ }
7364
+ /**
7365
+ * Listen to the switch of ANY instance of this helper (in the process that serves it). The
7366
+ * durable replacement of the `integration.enabled` / `integration.disabled` events (D8): the
7367
+ * addon reconciles from the record, whichever way it flipped.
7368
+ */
7369
+ onSwitched(listener) {
7370
+ this.switchListeners.add(listener);
7371
+ }
7372
+ /**
7373
+ * The ONE writer of the switch (D996, D1014): the record body's `enabled`, for every role. A
7374
+ * configured thing is an instance, so an id with no record yet (a default integration that was
7375
+ * never configured) gets its record from `initialBody` before the switch is written.
7376
+ */
7377
+ setInstanceEnabled = async ({ id, enabled }) => {
7378
+ if (await this.handle.get(id) === null) await this.handle.put({
7379
+ id,
7380
+ data: this.hooks.initialBody(id)
7381
+ }, { ifRev: 0 });
7382
+ await this.handle.patch(id, { [SWITCH_KEY]: enabled });
7383
+ await this.hooks.onChanged?.(id, "enabled");
7384
+ for (const listener of this.switchListeners) await listener(id, enabled);
7385
+ return { ok: true };
7386
+ };
7387
+ /** The row and its keychain refs go together (the records door). */
7388
+ deleteInstance = async ({ id }) => {
7389
+ await this.handle.delete(id);
7390
+ await this.hooks.onChanged?.(id, "deleted");
7391
+ return { ok: true };
7392
+ };
7393
+ testInstance = async (input) => {
7394
+ if (this.hooks.test === void 0) return {
7395
+ success: false,
7396
+ status: "unsupported",
7397
+ error: "This integration declares no connection test"
7398
+ };
7399
+ return this.hooks.test(input);
7400
+ };
7401
+ /** The flat provider object to hand to `registerProvider`. */
7402
+ toProvider() {
7403
+ return {
7404
+ describe: this.describe,
7405
+ instanceFormSchema: this.instanceFormSchema,
7406
+ listInstances: this.listInstances,
7407
+ getInstance: this.getInstance,
7408
+ createInstance: this.createInstance,
7409
+ updateInstance: this.updateInstance,
7410
+ setInstanceEnabled: this.setInstanceEnabled,
7411
+ deleteInstance: this.deleteInstance,
7412
+ testInstance: this.testInstance
7413
+ };
7414
+ }
7415
+ };
7416
+ /**
7417
+ * The one-switch migration (epic #440, step 3). An integration's on/off state used to live in the
7418
+ * registry's `enabled` column for a device addon; it now lives only in the instance record's
7419
+ * body (`enabled`, D1007 superseded). This moves a registry `enabled = false` into the body, once.
7420
+ *
7421
+ * For every registry row of the addon that is OFF:
7422
+ * - no record under its id: the record is created from `initialBody(name)` with `enabled: false`
7423
+ * (a default integration that never had settings, Reolink's among them);
7424
+ * - a record whose body states no `enabled`: `enabled: false` is written into it;
7425
+ * - a record that already states `enabled` (either way) is the newer truth and is left alone.
7426
+ * A row that is ON writes nothing: an absent field reads as on. A rerun finds every off row with
7427
+ * a stated switch and does nothing, so nothing switched off comes back on and nothing switched on
7428
+ * goes off. The registry column itself is neither read afterwards nor written; its drop is step 5.
7429
+ *
7430
+ * It runs in the addon process, BEFORE the addon registers its `integration-instances` provider,
7431
+ * which is also why `integrations.list` still answers the stored column at that point.
7432
+ */
7433
+ function registrySwitchToBodyId(addonId, date) {
7434
+ return `${addonId}/${date}-registry-switch-to-body`;
7435
+ }
7436
+ async function moveRegistrySwitchToBody(ports, spec) {
7437
+ const rows = await ports.listIntegrations(spec.addonId);
7438
+ let created = 0;
7439
+ let switched = 0;
7440
+ let kept = 0;
7441
+ for (const row of rows) {
7442
+ if (row.enabled) continue;
7443
+ const body = await ports.readBody(row.id);
7444
+ if (body === null) {
7445
+ if (await ports.createRecord(row.id, {
7446
+ ...spec.initialBody(row.name),
7447
+ ["enabled"]: false
7448
+ }) === "created") created += 1;
7449
+ else kept += 1;
7450
+ continue;
7451
+ }
7452
+ if ("enabled" in body) {
7453
+ kept += 1;
7454
+ continue;
7455
+ }
7456
+ await ports.switchOff(row.id);
7457
+ switched += 1;
7458
+ }
7459
+ const summary = {
7460
+ integrations: rows.length,
7461
+ off: rows.filter((r) => !r.enabled).length,
7462
+ created,
7463
+ switched,
7464
+ kept
7465
+ };
7466
+ return created === 0 && switched === 0 ? {
7467
+ outcome: "already-done",
7468
+ summary
7469
+ } : {
7470
+ outcome: "done",
7471
+ summary
7472
+ };
7473
+ }
7474
+ /** A migration entry: an addon states its kind and how a new body starts, nothing else. */
7475
+ function registrySwitchToBodyMigration(spec) {
7476
+ return {
7477
+ meta: {
7478
+ id: registrySwitchToBodyId(spec.addonId, spec.date),
7479
+ owner: spec.addonId,
7480
+ level: "addon-state",
7481
+ seq: spec.seq,
7482
+ dependsOn: [],
7483
+ store: "settings",
7484
+ scope: "cluster",
7485
+ onFailure: "block-owner",
7486
+ bodyKind: "procedure",
7487
+ description: "Move the registry enabled flag of every switched-off integration into its instance record body, creating the record when there is none",
7488
+ fixtureMark: "enabled"
7489
+ },
7490
+ procedure: (ports) => moveRegistrySwitchToBody(ports, {
7491
+ addonId: spec.addonId,
7492
+ initialBody: spec.initialBody
7493
+ })
7494
+ };
7495
+ }
7496
+ /** The hub and records sides of {@link registrySwitchToBodyMigration}. */
7497
+ function registrySwitchPortsOver(deps) {
7498
+ const handle = deps.records.kind({
7499
+ name: deps.kind.name,
7500
+ declaration: deps.kind.declaration,
7501
+ schema: record(string(), unknown())
7502
+ });
7503
+ return {
7504
+ listIntegrations: async (addonId) => (await deps.api.list()).filter((i) => i.addonId === addonId).map((i) => ({
7505
+ id: i.id,
7506
+ name: i.name,
7507
+ enabled: i.enabled !== false
7508
+ })),
7509
+ readBody: async (id) => (await handle.get(id))?.data ?? null,
7510
+ createRecord: async (id, body) => {
7511
+ if (await handle.get(id) !== null) return "exists";
7512
+ await handle.put({
7513
+ id,
7514
+ data: body
7515
+ }, { ifRev: 0 });
7516
+ return "created";
7517
+ },
7518
+ switchOff: async (id) => {
7519
+ await handle.patch(id, { [SWITCH_KEY]: false });
7520
+ }
7521
+ };
7522
+ }
7523
+ /**
7524
+ * Build a {@link DurableState} over a single store key. Transport-agnostic:
7525
+ * `read`/`write` are the addon-store or device-store accessors. The whole
7526
+ * validated value round-trips on every read/write — the schema is the
7527
+ * single source of truth for what is persisted, so no hand-listed field
7528
+ * set can drop a key on save.
7529
+ */
7530
+ function createDurableState(deps) {
7531
+ const get = async () => {
7532
+ const raw = (await deps.read())[deps.key];
7533
+ if (raw === void 0) return deps.fallback;
7534
+ const parsed = deps.schema.safeParse(raw);
7535
+ if (!parsed.success) {
7536
+ deps.onParseError?.(deps.key, parsed.error);
7537
+ return deps.fallback;
7538
+ }
7539
+ return parsed.data;
7540
+ };
7541
+ const set = async (next) => {
7542
+ const validated = deps.schema.parse(next);
7543
+ await deps.write({ [deps.key]: validated });
7544
+ };
7545
+ const update = async (fn) => {
7546
+ await set(fn(await get()));
7547
+ };
7548
+ return {
7549
+ get,
7550
+ set,
7551
+ update
7552
+ };
7553
+ }
7554
+ /**
7555
+ * Per-node scoping for the shared addon-settings blob.
7556
+ *
7557
+ * An addon's settings store is hub-central (the `addon-settings` cap is
7558
+ * hub-routed — the hub instance answers for every node), so fields whose
7559
+ * value is a NODE fact (decoder backend, engine pick, probed hardware
7560
+ * capabilities) persist under the node-scoped key `<key>@<nodeId>` inside
7561
+ * the single shared blob. The SCHEMA field key stays bare: the write path
7562
+ * ({@link scopePatch}) maps the bare field onto the target node's scoped
7563
+ * key; the read/hydrate path ({@link projectStore}) maps THIS node's value
7564
+ * back, so UI forms and `resolveConfig` only ever see the bare key.
7565
+ *
7566
+ * Fields opt in via the `perNode: true` schema marker on `ConfigFieldBase`
7567
+ * (`interfaces/config-ui.ts`); `BaseAddon` derives the key set from the
7568
+ * schema and routes reads/writes through these helpers.
7569
+ *
7570
+ * ## No bare-key fallback — deliberate
7571
+ *
7572
+ * {@link readNodeValue} reads the node-scoped key ONLY. A node with no
7573
+ * scoped key resolves to `undefined` so the field's schema `default` wins —
7574
+ * NEVER `store[base]` and never another node's value. A bare legacy key in
7575
+ * the store is invisible to every node, hub included, so one node's
7576
+ * selection can never leak onto another. (This generalizes the
7577
+ * `decoder-backend-keys.ts` semantics — the no-fallback variant — over an
7578
+ * arbitrary set of per-node field keys.)
7579
+ *
7580
+ * Pure functions only — no I/O, no imports beyond the language. This is a
7581
+ * LEAF module: import it via its deep path, never from the root barrel.
7582
+ */
7583
+ /**
7584
+ * Normalize a raw kernel node id to the bare node id used for scoping.
7585
+ * `localNodeId` can carry a `<node>/<addon>` suffix on forked child
7586
+ * processes; per-node settings are per-NODE, so strip the addon segment.
7587
+ * `undefined` / `null` / empty falls back to `'hub'`.
7588
+ */
7589
+ function normalizeNodeId(raw) {
7590
+ if (raw === void 0 || raw === null || raw === "") return "hub";
7591
+ const slashIdx = raw.indexOf("/");
7592
+ if (slashIdx < 0) return raw;
7593
+ const bare = raw.slice(0, slashIdx);
7594
+ return bare === "" ? "hub" : bare;
7595
+ }
7596
+ /** The node-scoped store key for a per-node field: `<base>@<nodeId>`. */
7597
+ function nodeScopedKey(base, nodeId) {
7598
+ return `${base}@${normalizeNodeId(nodeId)}`;
7599
+ }
7600
+ /**
7601
+ * Read a node's value for a per-node field from the raw shared store:
7602
+ * the node-scoped key when present, otherwise `undefined`.
7603
+ * Deliberately NO bare-key fallback (see module doc) — the caller lets the
7604
+ * schema `default` win on `undefined`.
7605
+ */
7606
+ function readNodeValue(store, base, nodeId) {
7607
+ return store[nodeScopedKey(base, nodeId)];
7608
+ }
7609
+ /**
7610
+ * Re-map a UI/settings patch so every bare perNode field persists under the
7611
+ * TARGET node's scoped key; all other keys pass through unchanged. Used on
7612
+ * the write path so a save for one node never clobbers another node's value
7613
+ * (and the bare key is never written). Returns a new object — the input
7614
+ * patch is not mutated.
7615
+ */
7616
+ function scopePatch(patch, perNodeKeys, nodeId) {
7617
+ const out = {};
7618
+ for (const [key, value] of Object.entries(patch)) out[perNodeKeys.has(key) ? nodeScopedKey(key, nodeId) : key] = value;
7619
+ return out;
7620
+ }
7621
+ /**
7622
+ * Project the raw shared store onto the bare schema keys for ONE node so a
7623
+ * UI schema (whose field keys are bare) hydrates from that node's own
7624
+ * values:
7625
+ *
7626
+ * - EVERY `@`-scoped key (any node's) is dropped from the pass-through.
7627
+ * - Every bare perNode key is dropped from the pass-through (a stray bare
7628
+ * legacy key must never hydrate any node — no bare fallback).
7629
+ * - THIS node's effective value ({@link readNodeValue}) is then laid onto
7630
+ * each bare perNode key; when the node has no scoped key the bare key is
7631
+ * left ABSENT so the field's schema `default` wins.
7632
+ *
7633
+ * Returns a new object — the input store is not mutated.
7634
+ */
7635
+ function projectStore(store, perNodeKeys, nodeId) {
7636
+ const out = {};
7637
+ for (const [key, value] of Object.entries(store)) {
7638
+ if (key.includes("@")) continue;
7639
+ if (perNodeKeys.has(key)) continue;
7640
+ out[key] = value;
7641
+ }
7642
+ for (const base of perNodeKeys) {
7643
+ const value = readNodeValue(store, base, nodeId);
7644
+ if (value !== void 0) out[base] = value;
7645
+ }
7646
+ return out;
7647
+ }
7648
+ /** Every scope, in the order the guard and the docs list them. */
7649
+ var SCOPED_SETTINGS_SCOPES = [
7650
+ "cluster",
7651
+ "device-defaults",
7652
+ "node"
7653
+ ];
6960
7654
  /** A write to a secret path could not be stored in the keychain, so it was refused. */
6961
7655
  var KeychainWriteRefusedError = class extends Error {
6962
7656
  fieldPath;
@@ -6967,7 +7661,7 @@ var KeychainWriteRefusedError = class extends Error {
6967
7661
  }
6968
7662
  };
6969
7663
  var KEEP = { kind: "keep" };
6970
- function isRecord$6(value) {
7664
+ function isRecord$4(value) {
6971
7665
  return typeof value === "object" && value !== null && !Array.isArray(value);
6972
7666
  }
6973
7667
  function defaultMintId() {
@@ -6980,7 +7674,7 @@ function collectSecretMarkerRefs(value, out = []) {
6980
7674
  return out;
6981
7675
  }
6982
7676
  if (Array.isArray(value)) for (const item of value) collectSecretMarkerRefs(item, out);
6983
- else if (isRecord$6(value)) for (const child of Object.values(value)) collectSecretMarkerRefs(child, out);
7677
+ else if (isRecord$4(value)) for (const child of Object.values(value)) collectSecretMarkerRefs(child, out);
6984
7678
  return out;
6985
7679
  }
6986
7680
  async function storedValueEquals(secrets, marker, candidate) {
@@ -7035,7 +7729,7 @@ function rowId(row, idKey) {
7035
7729
  return null;
7036
7730
  }
7037
7731
  async function writeArray(ctx, node, incoming, stored, fieldPath) {
7038
- const storedRows = Array.isArray(stored) ? stored.filter(isRecord$6) : [];
7732
+ const storedRows = Array.isArray(stored) ? stored.filter(isRecord$4) : [];
7039
7733
  if (!Array.isArray(incoming)) {
7040
7734
  ctx.deletes.push(...collectSecretMarkerRefs(storedRows));
7041
7735
  return {
@@ -7051,7 +7745,7 @@ async function writeArray(ctx, node, incoming, stored, fieldPath) {
7051
7745
  const kept = /* @__PURE__ */ new Set();
7052
7746
  const rows = [];
7053
7747
  for (const row of incoming) {
7054
- if (!isRecord$6(row)) {
7748
+ if (!isRecord$4(row)) {
7055
7749
  rows.push(row);
7056
7750
  continue;
7057
7751
  }
@@ -7076,7 +7770,7 @@ async function writeNode(ctx, node, incoming, stored, fieldPath) {
7076
7770
  case "leaf": return writeLeaf(ctx, incoming, stored, fieldPath);
7077
7771
  case "array": return writeArray(ctx, node, incoming, stored, fieldPath);
7078
7772
  case "object": {
7079
- if (!isRecord$6(incoming)) {
7773
+ if (!isRecord$4(incoming)) {
7080
7774
  if (incoming === void 0) return KEEP;
7081
7775
  ctx.deletes.push(...collectSecretMarkerRefs(stored));
7082
7776
  return {
@@ -7084,7 +7778,7 @@ async function writeNode(ctx, node, incoming, stored, fieldPath) {
7084
7778
  value: incoming
7085
7779
  };
7086
7780
  }
7087
- const storedObj = isRecord$6(stored) ? stored : {};
7781
+ const storedObj = isRecord$4(stored) ? stored : {};
7088
7782
  return {
7089
7783
  kind: "value",
7090
7784
  value: await writeMembers(ctx, node.children, incoming, storedObj, (m) => `${fieldPath}.${m}`)
@@ -7207,7 +7901,7 @@ async function resolveSecretMarkers(value, secrets, options = {}) {
7207
7901
  value: items
7208
7902
  };
7209
7903
  }
7210
- if (isRecord$6(v)) {
7904
+ if (isRecord$4(v)) {
7211
7905
  const out = {};
7212
7906
  for (const [k, child] of Object.entries(v)) {
7213
7907
  const s = substitute(child);
@@ -7239,7 +7933,7 @@ var SecretOverwriteRefusedError = class extends Error {
7239
7933
  this.name = "SecretOverwriteRefusedError";
7240
7934
  }
7241
7935
  };
7242
- function isRecord$5(value) {
7936
+ function isRecord$3(value) {
7243
7937
  return typeof value === "object" && value !== null && !Array.isArray(value);
7244
7938
  }
7245
7939
  function resolvedValue(pass, marker) {
@@ -7268,7 +7962,7 @@ function inArray(pass, incoming, stored) {
7268
7962
  return incoming.map((item, index) => {
7269
7963
  const twin = stored[index];
7270
7964
  if (isSecretMarker(twin)) return typeof item === "string" && item === resolvedValue(pass, twin) ? twin : item;
7271
- if (isRecord$5(item) && isRecord$5(twin)) return inArrayRow(pass, item, twin);
7965
+ if (isRecord$3(item) && isRecord$3(twin)) return inArrayRow(pass, item, twin);
7272
7966
  if (Array.isArray(item) && Array.isArray(twin)) return inArray(pass, item, twin);
7273
7967
  return item;
7274
7968
  });
@@ -7279,7 +7973,7 @@ function inArrayRow(pass, incoming, stored) {
7279
7973
  const twin = stored[key];
7280
7974
  if (isSecretMarker(twin)) {
7281
7975
  if (typeof value === "string" && value === resolvedValue(pass, twin)) out[key] = twin;
7282
- } else if (isRecord$5(value) && isRecord$5(twin)) out[key] = inArrayRow(pass, value, twin);
7976
+ } else if (isRecord$3(value) && isRecord$3(twin)) out[key] = inArrayRow(pass, value, twin);
7283
7977
  else if (Array.isArray(value) && Array.isArray(twin)) out[key] = inArray(pass, value, twin);
7284
7978
  }
7285
7979
  return out;
@@ -7287,7 +7981,7 @@ function inArrayRow(pass, incoming, stored) {
7287
7981
  async function walk(pass, incoming, stored) {
7288
7982
  if (isSecretMarker(stored)) return atMarker(pass, incoming, stored);
7289
7983
  if (Array.isArray(incoming) && Array.isArray(stored)) return inArray(pass, incoming, stored);
7290
- if (!isRecord$5(incoming) || !isRecord$5(stored)) return incoming;
7984
+ if (!isRecord$3(incoming) || !isRecord$3(stored)) return incoming;
7291
7985
  const out = { ...incoming };
7292
7986
  for (const [key, value] of Object.entries(incoming)) out[key] = await walk(pass, value, stored[key]);
7293
7987
  return out;
@@ -7318,7 +8012,7 @@ async function restoreUnchangedSecrets(input) {
7318
8012
  function isJsonEqual(a, b) {
7319
8013
  if (Object.is(a, b)) return true;
7320
8014
  if (Array.isArray(a)) return Array.isArray(b) && a.length === b.length && a.every((v, i) => isJsonEqual(v, b[i]));
7321
- if (isRecord$5(a) && isRecord$5(b)) {
8015
+ if (isRecord$3(a) && isRecord$3(b)) {
7322
8016
  const keys = Object.keys(a);
7323
8017
  if (keys.length !== Object.keys(b).length) return false;
7324
8018
  return keys.every((k) => Object.prototype.hasOwnProperty.call(b, k) && isJsonEqual(a[k], b[k]));
@@ -7342,7 +8036,7 @@ function markerKeysOf(blob, owner) {
7342
8036
  }
7343
8037
  function nodeFromStored(value, owner) {
7344
8038
  if (isSecretMarker(value)) return isSecretRefOwnedBy(value.$secret, owner) ? { kind: "leaf" } : null;
7345
- if (!isRecord$5(value)) return null;
8039
+ if (!isRecord$3(value)) return null;
7346
8040
  const children = /* @__PURE__ */ new Map();
7347
8041
  for (const [key, child] of Object.entries(value)) {
7348
8042
  const node = nodeFromStored(child, owner);
@@ -7637,6 +8331,28 @@ var SECRET_RETRY_MAX_MS = 5 * 6e4;
7637
8331
  /** Coalesces a burst of `keychain.changed` events into one re-resolve. */
7638
8332
  var SECRET_CHANGE_DEBOUNCE_MS = 250;
7639
8333
  /**
8334
+ * Pair a catalogue with the function that builds its ports FROM THE MIGRATION API. The one
8335
+ * place a catalogue is bound: a migration reaches nothing a ports binder cannot reach
8336
+ * through `api` (guard `check-migration-ports-surface`).
8337
+ */
8338
+ function migrationSet(catalogue, bindPorts) {
8339
+ return { bind: (api) => defineAddonMigrations(catalogue, bindPorts(api)) };
8340
+ }
8341
+ /** A mixed array is a mistake: the other kind would be dropped without a word. */
8342
+ function refuseMixed(form, kept, dropped) {
8343
+ 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`);
8344
+ }
8345
+ function catalogueOf(list) {
8346
+ const kept = list.filter((entry) => !("execute" in entry));
8347
+ refuseMixed("catalogue, (api) => ports", kept.length, list.length - kept.length);
8348
+ return kept;
8349
+ }
8350
+ function boundOf(list) {
8351
+ const kept = list.filter((entry) => "execute" in entry);
8352
+ refuseMixed("bound migrations", kept.length, list.length - kept.length);
8353
+ return kept;
8354
+ }
8355
+ /**
7640
8356
  * Base class for CamStack addons. Eliminates settings boilerplate:
7641
8357
  *
7642
8358
  * - Typed `config` property with automatic resolution from store + defaults
@@ -7714,6 +8430,13 @@ var BaseAddon = class {
7714
8430
  */
7715
8431
  secretStatePaths = [];
7716
8432
  _addonSecretTree = null;
8433
+ /**
8434
+ * D986 M4: the scoped schemas this addon declared, resolved once per capability
8435
+ * (`loadScopedSchemas`) so the sync readers (`perNodeKeys`, the secret tree, the restart check)
8436
+ * see them. Empty until loaded: the readers then fall back to {@link globalSettingsSchema}.
8437
+ */
8438
+ _scopedByCap = /* @__PURE__ */ new Map();
8439
+ _nodeKeysByCap = /* @__PURE__ */ new Map();
7717
8440
  _deviceSecretTree = null;
7718
8441
  /** Refs the last resolved config pointed at — a change to one re-resolves. */
7719
8442
  _configSecretRefs = /* @__PURE__ */ new Set();
@@ -7783,6 +8506,7 @@ var BaseAddon = class {
7783
8506
  this._ctx = context;
7784
8507
  this._secretSettings = null;
7785
8508
  }
8509
+ await this.loadScopedSchemas();
7786
8510
  await this.resolveConfig();
7787
8511
  if (secrets !== void 0) this._secretChangeUnsub = secrets.onChange((ref) => {
7788
8512
  if (this._configSecretRefs.has(ref)) this.scheduleSecretReresolve(SECRET_CHANGE_DEBOUNCE_MS);
@@ -7792,31 +8516,65 @@ var BaseAddon = class {
7792
8516
  const normalized = normalizeAddonInitResult(result);
7793
8517
  const providers = normalized && "providers" in normalized && normalized.providers ? normalized.providers : [];
7794
8518
  this._registeredCapNames = providers.map((p) => p.capability.name);
8519
+ await this.loadScopedSchemas();
7795
8520
  return normalized;
7796
8521
  }
8522
+ async runMigrations(first, second, third) {
8523
+ if (typeof second === "function") return this.runMigrationSets([migrationSet(catalogueOf(first), second)], third);
8524
+ return this.runBound(boundOf(first), second);
8525
+ }
7797
8526
  /**
7798
- * Run this addon's migration catalogue (D987 M3) through the hub's `migrations`
7799
- * engine. Call it at the point of the boot where the data must already have the new
7800
- * shape — `onInitialize`, or `onRestoreDevices` for a migration that needs the
7801
- * restored devices — with the catalogue bound to the addon's ports
7802
- * (`defineAddonMigrations(ADDON_MIGRATIONS, ports)`).
7803
- *
7804
- * An engine that cannot be reached or refuses the catalogue is logged and runs
7805
- * nothing; the boot continues. A migration that FAILED (or was blocked by one)
7806
- * and declares `onFailure: 'block-owner'` makes this throw, so the addon does not
7807
- * serve data whose shape it cannot trust; `tolerate` migrations never do.
7808
- *
7809
- * ALWAYS pass the whole catalogue; a phase that must run only some of it passes
7810
- * `{ only: [ids] }` — never a filtered catalogue (the engine would judge the
7811
- * omitted applied ids "newer").
8527
+ * Several catalogues of ONE owner in one declaration (the engine replaces an owner's
8528
+ * catalogue on every declare, so two calls would each judge the other's ids "newer").
8529
+ * Build each entry with `migrationSet(catalogue, (api) => ports)`.
8530
+ */
8531
+ async runMigrationSets(sets, options) {
8532
+ const api = this.ctx.migrationApi;
8533
+ if (api === void 0) throw new Error(`${this.ctx.id}: the migration API is not available on this context`);
8534
+ return this.runBound(sets.flatMap((set) => set.bind(api)), options);
8535
+ }
8536
+ /**
8537
+ * A device addon states its instance kind once, before its migrations run, and the one-switch
8538
+ * migration (registry `enabled` to the instance body, epic #440 step 3) joins whatever
8539
+ * catalogue the addon runs, in the SAME declaration (the engine replaces an owner's catalogue
8540
+ * on every declare).
7812
8541
  */
7813
- async runMigrations(migrations, options) {
8542
+ declareRegistrySwitch(spec) {
8543
+ this.registrySwitchSpec = spec;
8544
+ }
8545
+ registrySwitchSpec = null;
8546
+ registrySwitchBound() {
8547
+ const spec = this.registrySwitchSpec;
8548
+ if (spec === null) return [];
8549
+ const api = this.ctx.migrationApi;
8550
+ if (api === void 0) {
8551
+ this.ctx.logger.warn("the registry switch migration is skipped: the migration API is not available on this context");
8552
+ return [];
8553
+ }
8554
+ return migrationSet([registrySwitchToBodyMigration({
8555
+ addonId: this.ctx.id,
8556
+ date: "2026-11-06",
8557
+ seq: 1e3,
8558
+ initialBody: spec.initialBody
8559
+ })], (a) => registrySwitchPortsOver({
8560
+ api: integrationRowsApiOver(a),
8561
+ records: switchRecordsOverMigrationApi(a),
8562
+ kind: spec.kind
8563
+ })).bind(api);
8564
+ }
8565
+ async runBound(declared, options) {
8566
+ const added = this.registrySwitchBound();
8567
+ const migrations = [...declared, ...added];
8568
+ const phased = options?.only === void 0 || added.length === 0 ? options : {
8569
+ ...options,
8570
+ only: [...options.only, ...added.map((m) => m.meta.id)]
8571
+ };
7814
8572
  const api = this.ctx.api.migrations;
7815
8573
  const report = await runAddonMigrations({
7816
8574
  declareOwner: (input) => api.declareOwner.mutate(input),
7817
8575
  startMigration: (input) => api.startMigration.mutate(input),
7818
8576
  finishMigration: (input) => api.finishMigration.mutate(input)
7819
- }, migrations, this.ctx.logger, options);
8577
+ }, migrations, this.ctx.logger, phased);
7820
8578
  if (report.blockOwner.length > 0) throw new AddonMigrationsBlockedError(report.blockOwner);
7821
8579
  return report;
7822
8580
  }
@@ -7880,6 +8638,16 @@ var BaseAddon = class {
7880
8638
  schema(schema) {
7881
8639
  return schema;
7882
8640
  }
8641
+ /**
8642
+ * The capability names whose scoped settings schemas ({@link clusterSettingsSchema},
8643
+ * {@link nodeSettingsSchema}, {@link deviceDefaultsSchema}) this addon declares. Read BEFORE
8644
+ * `onInitialize`, when the providers it registers are not known yet: the first config resolve
8645
+ * must already know which keys are per node. Names the providers register at init are added
8646
+ * once known.
8647
+ */
8648
+ scopedSettingsCapabilities() {
8649
+ return [];
8650
+ }
7883
8651
  /** Override to provide global-level settings UI schema. */
7884
8652
  globalSettingsSchema(_cap) {
7885
8653
  return null;
@@ -7923,7 +8691,8 @@ var BaseAddon = class {
7923
8691
  return [];
7924
8692
  }
7925
8693
  async getGlobalSettings(overlay, cap, nodeId) {
7926
- const schema = this.globalSettingsSchema(cap);
8694
+ await this.loadScopedSchemas(cap);
8695
+ const schema = this.globalSettingsSchema(cap) ?? this.scopedFormSchema(cap);
7927
8696
  if (!schema) return { sections: [] };
7928
8697
  const projected = await this.readRawProjectedStore(nodeId, cap);
7929
8698
  return hydrateSchema(schema, overlay ? await this.overlayKeepingMarkers(projected, overlay) : projected, { inlineSecretsAsViews: true });
@@ -8054,6 +8823,7 @@ var BaseAddon = class {
8054
8823
  * resolved blob back is a no-op for every unchanged secret.
8055
8824
  */
8056
8825
  async resolveGlobalStore(nodeId, cap) {
8826
+ await this.loadScopedSchemas(cap);
8057
8827
  const raw = await this._ctx?.settings?.readAddonStore() ?? {};
8058
8828
  return this.projectForNode(raw, nodeId, cap);
8059
8829
  }
@@ -8064,6 +8834,7 @@ var BaseAddon = class {
8064
8834
  }
8065
8835
  /** The PROJECTED store with its markers — the form hydrate only (D798). */
8066
8836
  async readRawProjectedStore(nodeId, cap) {
8837
+ await this.loadScopedSchemas(cap);
8067
8838
  const raw = await this.rawSettings()?.readAddonStore() ?? {};
8068
8839
  return this.projectForNode(raw, nodeId, cap);
8069
8840
  }
@@ -8166,6 +8937,7 @@ var BaseAddon = class {
8166
8937
  await this.applyGlobalPatch(patch, nodeId);
8167
8938
  }
8168
8939
  async applyGlobalPatch(barePatch, nodeId) {
8940
+ await this.loadScopedSchemas();
8169
8941
  const keys = this.perNodeKeys();
8170
8942
  const localNode = normalizeNodeId(this._ctx?.kernel?.localNodeId);
8171
8943
  const target = normalizeNodeId(nodeId ?? this._ctx?.kernel?.localNodeId);
@@ -8179,7 +8951,8 @@ var BaseAddon = class {
8179
8951
  await this.resolveConfig();
8180
8952
  await this.onConfigChanged();
8181
8953
  this.emitLifecycle(EventCategory.AddonUpdated, { level: "global" });
8182
- this.maybeAutoRestart(Object.keys(barePatch), this.globalSettingsSchema());
8954
+ const legacy = this.globalSettingsSchema();
8955
+ this.maybeAutoRestart(Object.keys(barePatch), [...legacy === null ? [] : [legacy], ...this.loadedScopedSchemas().map((entry) => entry.schema)]);
8183
8956
  }
8184
8957
  /**
8185
8958
  * The set of field keys the global settings schema declares `perNode: true`
@@ -8187,14 +8960,67 @@ var BaseAddon = class {
8187
8960
  * declarations). Empty set ⇒ every per-node code path is bypassed and the
8188
8961
  * settings API behaves exactly like the legacy node-agnostic one.
8189
8962
  */
8190
- _perNodeKeysCache = /* @__PURE__ */ new Map();
8963
+ /**
8964
+ * Load the scoped schemas of every capability this addon declares (the override and the
8965
+ * providers registered at init, plus `extraCap`) that is not loaded yet, then drop what was
8966
+ * derived from the previous set. Idempotent.
8967
+ */
8968
+ async loadScopedSchemas(extraCap) {
8969
+ const caps = new Set([
8970
+ ...this.scopedSettingsCapabilities(),
8971
+ ...this._registeredCapNames,
8972
+ ...extraCap === void 0 ? [] : [extraCap]
8973
+ ]);
8974
+ let added = false;
8975
+ for (const cap of caps) {
8976
+ if (this._scopedByCap.has(cap)) continue;
8977
+ const loaded = [];
8978
+ for (const scope of SCOPED_SETTINGS_SCOPES) {
8979
+ const schema = await this.getScopedSettingsSchema(scope, cap);
8980
+ if (schema !== null) loaded.push({
8981
+ scope,
8982
+ schema
8983
+ });
8984
+ }
8985
+ this._scopedByCap.set(cap, loaded);
8986
+ added = true;
8987
+ }
8988
+ if (!added) return;
8989
+ this._nodeKeysByCap = /* @__PURE__ */ new Map();
8990
+ this._addonSecretTree = null;
8991
+ }
8992
+ /**
8993
+ * The form the settings API serves while an addon declares no {@link globalSettingsSchema}: the
8994
+ * sections of its scoped schemas, so dropping the old hook does not blank the form.
8995
+ */
8996
+ scopedFormSchema(cap) {
8997
+ const byId = /* @__PURE__ */ new Map();
8998
+ for (const entry of this.loadedScopedSchemas(cap)) for (const section of entry.schema.sections) if (!byId.has(section.id)) byId.set(section.id, section);
8999
+ return byId.size === 0 ? null : { sections: [...byId.values()] };
9000
+ }
9001
+ /** Every loaded scoped schema of `cap`, or of every loaded capability. */
9002
+ loadedScopedSchemas(cap) {
9003
+ if (cap !== void 0) return this._scopedByCap.get(cap) ?? [];
9004
+ return [...this._scopedByCap.values()].flat();
9005
+ }
9006
+ /**
9007
+ * The field keys that are stored per node: every field of a {@link nodeSettingsSchema}, plus
9008
+ * the fields the legacy {@link globalSettingsSchema} still marks `perNode: true`. Derived once
9009
+ * per `cap` argument and memoized (schemas are static declarations). Empty set ⇒ every
9010
+ * per-node code path is bypassed and the settings API behaves like the node-agnostic one.
9011
+ * Call {@link loadScopedSchemas} first (the async seams do).
9012
+ */
8191
9013
  perNodeKeys(cap) {
8192
9014
  const cacheKey = cap ?? "";
8193
- const cached = this._perNodeKeysCache.get(cacheKey);
9015
+ const cached = this._nodeKeysByCap.get(cacheKey);
8194
9016
  if (cached) return cached;
8195
- const schema = this.globalSettingsSchema(cap);
8196
- const keys = new Set(schema ? schema.sections.flatMap((section) => collectPerNodeFieldKeys(section.fields)) : []);
8197
- this._perNodeKeysCache.set(cacheKey, keys);
9017
+ const legacy = this.globalSettingsSchema(cap);
9018
+ const keys = new Set(legacy ? legacy.sections.flatMap((section) => collectPerNodeFieldKeys(section.fields)) : []);
9019
+ for (const { scope, schema } of this.loadedScopedSchemas(cap)) {
9020
+ if (scope !== "node") continue;
9021
+ for (const section of schema.sections) for (const key of collectValueFieldKeys(section.fields)) keys.add(key);
9022
+ }
9023
+ this._nodeKeysByCap.set(cacheKey, keys);
8198
9024
  return keys;
8199
9025
  }
8200
9026
  /**
@@ -8204,10 +9030,9 @@ var BaseAddon = class {
8204
9030
  * time to return its response before the addon is torn down and
8205
9031
  * re-initialised by `AddonRegistryService.restartAddon`.
8206
9032
  */
8207
- maybeAutoRestart(patchKeys, schema) {
8208
- if (!schema) return;
9033
+ maybeAutoRestart(patchKeys, schemas) {
8209
9034
  const restartKeys = /* @__PURE__ */ new Set();
8210
- for (const section of schema.sections) for (const field of section.fields) {
9035
+ for (const schema of schemas) for (const section of schema.sections) for (const field of section.fields) {
8211
9036
  if (field.type === "separator" || field.type === "info") continue;
8212
9037
  if (field.requiresRestart) restartKeys.add(field.key);
8213
9038
  }
@@ -8403,12 +9228,14 @@ var BaseAddon = class {
8403
9228
  * here, in the addon's own process, so the hub keeps no copy of it.
8404
9229
  */
8405
9230
  async getDeclaredSettingsKeys() {
9231
+ await this.loadScopedSchemas();
8406
9232
  return { keys: [...this.declaredKeySet()].toSorted() };
8407
9233
  }
8408
9234
  declaredKeySet() {
8409
9235
  const keys = new Set(Object.keys(this.defaults));
8410
9236
  const schema = this.globalSettingsSchema();
8411
9237
  if (schema) for (const section of schema.sections) for (const key of collectFieldKeys(section.fields)) keys.add(key);
9238
+ for (const { schema: scoped } of this.loadedScopedSchemas()) for (const section of scoped.sections) for (const key of collectFieldKeys(section.fields)) keys.add(key);
8412
9239
  for (const key of this._declaredStateKeys) keys.add(key);
8413
9240
  for (const path of this.secretStatePaths) {
8414
9241
  const root = path.split(/[.[]/, 1)[0];
@@ -8504,7 +9331,11 @@ var BaseAddon = class {
8504
9331
  }
8505
9332
  /** The addon store's secret tree: schema fields by TYPE, plus `secretStatePaths`. */
8506
9333
  addonSecretTree() {
8507
- this._addonSecretTree ??= mergeSecretStatePaths(secretTreeFromSchema(this.globalSettingsSchema()), this.secretStatePaths);
9334
+ if (this._addonSecretTree === null) {
9335
+ const tree = new Map(secretTreeFromSchema(this.globalSettingsSchema()));
9336
+ for (const { schema } of this.loadedScopedSchemas()) for (const [key, node] of secretTreeFromSchema(schema)) tree.set(key, node);
9337
+ this._addonSecretTree = mergeSecretStatePaths(tree, this.secretStatePaths);
9338
+ }
8508
9339
  return this._addonSecretTree;
8509
9340
  }
8510
9341
  deviceSecretTree() {
@@ -8754,6 +9585,23 @@ function dropPerNodeFields(fields) {
8754
9585
  }
8755
9586
  return kept;
8756
9587
  }
9588
+ /** The keys of the value-holding fields, recursing into layout containers. */
9589
+ function collectValueFieldKeys(fields) {
9590
+ const collected = [];
9591
+ for (const field of fields) {
9592
+ if (field.type === "group") {
9593
+ collected.push(...collectValueFieldKeys(field.fields));
9594
+ continue;
9595
+ }
9596
+ if (field.type === "sub-tabs") {
9597
+ for (const tab of field.tabs) collected.push(...collectValueFieldKeys(tab.fields));
9598
+ continue;
9599
+ }
9600
+ if (field.type === "separator" || field.type === "info") continue;
9601
+ if ("key" in field && typeof field.key === "string") collected.push(field.key);
9602
+ }
9603
+ return collected;
9604
+ }
8757
9605
  function collectFieldKeys(fields) {
8758
9606
  const collected = [];
8759
9607
  for (const field of fields) {
@@ -8799,237 +9647,6 @@ function normalizeAddonInitResult(result) {
8799
9647
  if (Array.isArray(result)) return { providers: result };
8800
9648
  return result;
8801
9649
  }
8802
- var PREFIX = "records/";
8803
- /** The base of every records failure. `detail` is the human part of the message. */
8804
- var RecordsError = class extends Error {
8805
- code;
8806
- detail;
8807
- constructor(code, detail) {
8808
- super(`${PREFIX}${code}: ${detail}`);
8809
- this.name = "RecordsError";
8810
- this.code = code;
8811
- this.detail = detail;
8812
- }
8813
- };
8814
- /** A write guarded by `ifRev` found another revision (or an existing row for `ifRev: 0`). */
8815
- var RevConflictError = class extends RecordsError {
8816
- constructor(detail) {
8817
- super("rev-conflict", detail);
8818
- this.name = "RevConflictError";
8819
- }
8820
- };
8821
- /** The keychain could not store or serve a value: explicit, never an empty string. */
8822
- var RecordSecretUnavailableError = class extends RecordsError {
8823
- constructor(detail) {
8824
- super("secret-unavailable", detail);
8825
- this.name = "RecordSecretUnavailableError";
8826
- }
8827
- };
8828
- var InvalidRecordError = class extends RecordsError {
8829
- constructor(detail) {
8830
- super("invalid-record", detail);
8831
- this.name = "InvalidRecordError";
8832
- }
8833
- };
8834
- /** A kind declaration the engine refuses (non-additive change, bad shape, wrong file). */
8835
- var DeclarationRefusedError = class extends RecordsError {
8836
- constructor(detail) {
8837
- super("declaration-refused", detail);
8838
- this.name = "DeclarationRefusedError";
8839
- }
8840
- };
8841
- /** Limits and names of `ctx.records` (D881). One authority; the engine and the facade read it. */
8842
- /** The files a kind may live in. `history` is device-history's (D850), never records. */
8843
- var RECORD_DATABASES = ["settings", "events"];
8844
- /** The classes of a kind: the `@durable` vocabulary, one authority (replaces the annotation). */
8845
- var RECORD_CLASSES = [
8846
- "config",
8847
- "ledger",
8848
- "audit",
8849
- "mirror",
8850
- "ephemeral"
8851
- ];
8852
- var RECORD_DEFAULT_MAX_DATA_BYTES = 64 * 1024;
8853
- var RECORD_MAX_DATA_BYTES = 1024 * 1024;
8854
- var RECORD_BATCH_MAX = 1e3;
8855
- var RECORD_QUERY_MAX = 1e3;
8856
- /** A kind in the `settings` file may not bound itself above this (D447: high volume is `events`). */
8857
- var RECORD_SETTINGS_MAX_ROWS = 5e4;
8858
- /** The `Column`-free proof prefix: a ref collection for a kind's secret fields. */
8859
- var RECORD_SECRET_COLLECTION_PREFIX = "records:";
8860
- /**
8861
- * Secret fields of a record, addressed the way a Zod schema declares them
8862
- * (`collectZodSecretPaths`): dotted keys, `[]` for "each element of this array"
8863
- * (`auth.accessToken`, `headers[].value`).
8864
- *
8865
- * `{}` after a key means "each value of this map" (`applianceSecrets{}`): the map's own key
8866
- * names the value (`applianceSecrets{fridge}`), so no id key is declared and a body that drops a
8867
- * key releases exactly that key's secret.
8868
- *
8869
- * Array elements are matched by a DECLARED id key (`secretArrayKeys`:
8870
- * `{ headers: 'name' }`), never by index, so reordering a list keeps every
8871
- * keychain ref (the same rule as `arrayItemFieldPath`). The concrete path of a
8872
- * leaf names its element: `headers[X-Api].value`.
8873
- *
8874
- * Pure and browser-safe. Nothing here mutates: every transform returns a new value.
8875
- */
8876
- /** The array prefixes (declared form, e.g. `headers` or `a.headers`) of a path. */
8877
- function parseSecretPath(path) {
8878
- if (path.length === 0) throw new InvalidRecordError("an empty secret path");
8879
- return path.split(".").map((raw) => {
8880
- const each = raw.endsWith("[]");
8881
- const map = raw.endsWith("{}");
8882
- const key = each || map ? raw.slice(0, -2) : raw;
8883
- if (key.length === 0) throw new InvalidRecordError(`secret path "${path}" has an empty segment`);
8884
- return {
8885
- key,
8886
- each,
8887
- map
8888
- };
8889
- });
8890
- }
8891
- /** The declared array prefixes of `path` that need an id key (`headers`, `a.rows`). */
8892
- function secretArrayPrefixes(path) {
8893
- const segments = parseSecretPath(path);
8894
- const prefixes = [];
8895
- const walked = [];
8896
- for (const segment of segments) {
8897
- walked.push(segment.key);
8898
- if (segment.each) prefixes.push(walked.join("."));
8899
- }
8900
- return prefixes;
8901
- }
8902
- function isRecord$4(value) {
8903
- return typeof value === "object" && value !== null && !Array.isArray(value);
8904
- }
8905
- function elementId(element, idKey, declared, prefix) {
8906
- const id = isRecord$4(element) ? element[idKey] : void 0;
8907
- 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`);
8908
- return id;
8909
- }
8910
- /**
8911
- * Visit every secret leaf PRESENT in `data` (an absent branch has nothing to
8912
- * visit). `replace` returns the new leaf value, or {@link REMOVE_LEAF}; the
8913
- * result is a new body, `data` is untouched.
8914
- */
8915
- var REMOVE_LEAF = Symbol("remove-leaf");
8916
- function mapAt(node, segments, index, walkedKeys, concretePrefix, declared, arrayKeys, visit) {
8917
- if (!isRecord$4(node)) return node;
8918
- const segment = segments[index];
8919
- if (segment === void 0) return node;
8920
- if (!Object.prototype.hasOwnProperty.call(node, segment.key)) return node;
8921
- const child = node[segment.key];
8922
- const keys = [...walkedKeys, segment.key];
8923
- const last = index === segments.length - 1;
8924
- if (segment.each) {
8925
- if (!Array.isArray(child)) return node;
8926
- const prefix = keys.join(".");
8927
- const idKey = arrayKeys[prefix];
8928
- if (idKey === void 0) throw new InvalidRecordError(`"${declared}": no id key declared for the array "${prefix}"`);
8929
- const mapped = child.map((element) => {
8930
- const id = elementId(element, idKey, declared, prefix);
8931
- const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}[${encodeURIComponent(id)}]`;
8932
- return last ? element : mapAt(element, segments, index + 1, keys, concrete, declared, arrayKeys, visit);
8933
- });
8934
- return {
8935
- ...node,
8936
- [segment.key]: mapped
8937
- };
8938
- }
8939
- if (segment.map) {
8940
- if (!isRecord$4(child)) return node;
8941
- const kept = Object.entries(child).map(([mapKey, value]) => {
8942
- const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}{${encodeURIComponent(mapKey)}}`;
8943
- if (!last) return [mapKey, mapAt(value, segments, index + 1, keys, concrete, declared, arrayKeys, visit)];
8944
- return [mapKey, visit({
8945
- declared,
8946
- concrete,
8947
- value
8948
- })];
8949
- }).filter(([, value]) => value !== REMOVE_LEAF);
8950
- return {
8951
- ...node,
8952
- [segment.key]: Object.fromEntries(kept)
8953
- };
8954
- }
8955
- const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}`;
8956
- if (last) {
8957
- const replacement = visit({
8958
- declared,
8959
- concrete,
8960
- value: child
8961
- });
8962
- if (replacement === REMOVE_LEAF) return Object.fromEntries(Object.entries(node).filter(([key]) => key !== segment.key));
8963
- return {
8964
- ...node,
8965
- [segment.key]: replacement
8966
- };
8967
- }
8968
- return {
8969
- ...node,
8970
- [segment.key]: mapAt(child, segments, index + 1, keys, concrete, declared, arrayKeys, visit)
8971
- };
8972
- }
8973
- /** Replace/remove every present secret leaf; returns a NEW body. */
8974
- function mapSecretLeaves(data, paths, arrayKeys, visit) {
8975
- let current = data;
8976
- for (const declared of paths) current = mapAt(current, parseSecretPath(declared), 0, [], "", declared, arrayKeys, visit);
8977
- return current;
8978
- }
8979
- /** Every present secret leaf, read-only. */
8980
- function collectSecretLeaves(data, paths, arrayKeys) {
8981
- const found = [];
8982
- mapSecretLeaves(data, paths, arrayKeys, (leaf) => {
8983
- found.push(leaf);
8984
- return leaf.value;
8985
- });
8986
- return found;
8987
- }
8988
- /**
8989
- * The keychain collection name a kind's secrets live under. Prefixed so a
8990
- * record's refs never collide with the refs a legacy collection of the same name
8991
- * already holds during an adoption.
8992
- */
8993
- function recordSecretCollection(kind) {
8994
- return `${RECORD_SECRET_COLLECTION_PREFIX}${kind}`;
8995
- }
8996
- /** The ONE ref a row's secret field may carry: the engine and the facade both build it here. */
8997
- function recordSecretRef(owner, kind, rowId, concretePath) {
8998
- return buildSecretRef({
8999
- owner,
9000
- scope: {
9001
- kind: "row",
9002
- collection: recordSecretCollection(kind),
9003
- rowId
9004
- },
9005
- fieldPath: concretePath
9006
- });
9007
- }
9008
- /**
9009
- * A stored secret, as an admin read shows it: a VIEW naming the row's own
9010
- * keychain ref (`set: true`), never the value and no longer the bare redaction
9011
- * token. The form hands it to the secret field, which reveals the value by ref
9012
- * through the audited `keychain-admin.reveal`; sent back untouched it keeps the
9013
- * stored secret (the records door reads a view as KEEP).
9014
- *
9015
- * ONE implementation for the entries service and for every addon that serves
9016
- * its own instances (`RecordIntegrationInstances`).
9017
- */
9018
- function isRecord$3(value) {
9019
- return typeof value === "object" && value !== null && !Array.isArray(value);
9020
- }
9021
- function secretViewsOf(owner, kind, id, decl, data) {
9022
- if (decl.secretPaths.length === 0) return data;
9023
- const shown = mapSecretLeaves(data, decl.secretPaths, decl.secretArrayKeys, (leaf) => {
9024
- if (leaf.value !== "__camstack_redacted__") return leaf.value;
9025
- return {
9026
- $secret: recordSecretRef(owner, kind, id, leaf.concrete),
9027
- v: 1,
9028
- set: true
9029
- };
9030
- });
9031
- return isRecord$3(shown) ? shown : data;
9032
- }
9033
9650
  /**
9034
9651
  * The share-view scope kinds a share-link token can carry. The hub mints
9035
9652
  * and validates them (`ShareViewGrantSchema` builds its
@@ -9283,6 +9900,7 @@ function defineRecordKinds(specs) {
9283
9900
  function entryBody(shape) {
9284
9901
  return object({
9285
9902
  name: string().min(1),
9903
+ enabled: boolean().optional(),
9286
9904
  ...shape
9287
9905
  });
9288
9906
  }
@@ -11138,6 +11756,10 @@ Object.freeze({
11138
11756
  "all",
11139
11757
  "one"
11140
11758
  ]
11759
+ },
11760
+ {
11761
+ "path": "positionUpdatedAt",
11762
+ "valueType": "number"
11141
11763
  }
11142
11764
  ],
11143
11765
  "meter": [{
@@ -11392,22 +12014,6 @@ Object.freeze({
11392
12014
  "path": "pumpRunning",
11393
12015
  "valueType": "boolean"
11394
12016
  },
11395
- {
11396
- "path": "lastDrink",
11397
- "valueType": "number"
11398
- },
11399
- {
11400
- "path": "currentHourDrink",
11401
- "valueType": "number"
11402
- },
11403
- {
11404
- "path": "last24hDrink",
11405
- "valueType": "number"
11406
- },
11407
- {
11408
- "path": "todayDrink",
11409
- "valueType": "number"
11410
- },
11411
12017
  {
11412
12018
  "path": "error",
11413
12019
  "valueType": "string"
@@ -11973,6 +12579,60 @@ Object.freeze({
11973
12579
  }
11974
12580
  ]
11975
12581
  });
12582
+ Object.freeze({
12583
+ "actions": { "run": 363e4 },
12584
+ "audio-analyzer": { "classify": 3e4 },
12585
+ "custom-model-registry": { "importModelBundle": 18e5 },
12586
+ "database-snapshot": { "writeSnapshot": 18e5 },
12587
+ "device-manager": {
12588
+ "migrateDevice": 72e4,
12589
+ "runDiscoverySweep": 12e4
12590
+ },
12591
+ "device-provider": { "reloadDevice": 18e4 },
12592
+ "llm": {
12593
+ "generate": 6e5,
12594
+ "generateVision": 6e5,
12595
+ "testProfile": 6e5
12596
+ },
12597
+ "llm-runtime": {
12598
+ "complete": 6e5,
12599
+ "completeApple": 6e5,
12600
+ "ensureStarted": 6e5,
12601
+ "installModel": 36e5
12602
+ },
12603
+ "local-network": { "scanNetwork": 9e4 },
12604
+ "model-convert": { "convert": 6e5 },
12605
+ "pipeline-analytics": {
12606
+ "addRetrainFrameFromRecording": 6e4,
12607
+ "offerRetrainArchive": 12e4,
12608
+ "proposeRetrainAnnotationsWithLlm": 18e4,
12609
+ "resolveRetrainTrainingCorpus": 6e4,
12610
+ "writeRetrainArchive": 36e5
12611
+ },
12612
+ "server-management": { "applyServerUpdate": 96e4 },
12613
+ "terminal-session": { "pullOutput": 15e3 },
12614
+ "training": {
12615
+ "canaryResult": 12e4,
12616
+ "cancelJob": 12e4,
12617
+ "planJob": 6e4,
12618
+ "registerResult": 18e5,
12619
+ "rollbackCanary": 12e4,
12620
+ "startJob": 12e4,
12621
+ "startJobBatch": 12e4
12622
+ },
12623
+ "training-provider": {
12624
+ "cancelJob": 6e4,
12625
+ "cleanupJob": 3e5,
12626
+ "getJob": 6e4,
12627
+ "listJobEvents": 6e4,
12628
+ "listJobs": 12e4,
12629
+ "offerArtifact": 3e5,
12630
+ "readResult": 3e5,
12631
+ "submitJob": 18e5,
12632
+ "uploadDataset": 72e5,
12633
+ "validateCredentials": 3e4
12634
+ }
12635
+ });
11976
12636
  object({
11977
12637
  code: string().regex(/^[a-z][a-z0-9-]*(\.[a-z0-9-]+)+$/),
11978
12638
  params: record(string(), union([string(), number()])).optional()
@@ -11992,7 +12652,7 @@ function userError(code, params, englishFallback) {
11992
12652
  return new CamstackError(code, params, englishFallback);
11993
12653
  }
11994
12654
  //#endregion
11995
- //#region ../types/dist/composition-pOHbTzRB.mjs
12655
+ //#region ../types/dist/composition-BmBHuDTQ.mjs
11996
12656
  /**
11997
12657
  * The ffmpeg build every CamStack node downloads, per platform and arch.
11998
12658
  *
@@ -12296,7 +12956,7 @@ var table = {
12296
12956
  },
12297
12957
  dwell: {
12298
12958
  minArgs: 3,
12299
- maxArgs: 3,
12959
+ maxArgs: 4,
12300
12960
  apply: () => {
12301
12961
  throw new ExpressionEvalError("dwell: stateful evaluation context is required");
12302
12962
  }
@@ -13339,205 +13999,6 @@ var IntegrationInstanceRefSchema = object({
13339
13999
  ]),
13340
14000
  candidateStableId: string().optional()
13341
14001
  });
13342
- /**
13343
- * `RecordIntegrationInstances` - the `integration-instances` provider over ONE
13344
- * entry kind, so an addon that holds a connection serves it in ~30 lines.
13345
- *
13346
- * Every instance is one record of the addon's own kind, keyed by the
13347
- * `integrations` registry id. The records door does the secret work: a field the
13348
- * kind marks `.meta({ secret: true })` is a keychain marker bound to the row, so
13349
- * deleting the row deletes the secret, and one row's value is never another's.
13350
- *
13351
- * Patch rules for a secret (`updateInstance`): omitted, `''`, the redaction
13352
- * token or the view the form was given KEEP the stored secret;
13353
- * `{ $secretClear: true }` clears it; any other string replaces it.
13354
- */
13355
- /** The most instances one addon lists (an integrations page, not a table). */
13356
- var INSTANCES_LIST_MAX = 1e3;
13357
- /** The keys of the kind's secret fields that sit at the top level of the body. */
13358
- function topLevelSecretKeys(paths) {
13359
- return new Set(paths.filter((p) => !p.includes(".") && !p.includes("[") && !p.includes("{")));
13360
- }
13361
- /** The keys of the kind's top-level MAPS whose values are secrets (`applianceSecrets{}`). */
13362
- function secretMapKeys(paths) {
13363
- return new Set(paths.filter((p) => p.endsWith("{}") && !p.slice(0, -2).match(/[.[{]/)).map((p) => p.slice(0, -2)));
13364
- }
13365
- /**
13366
- * A patch value for a map of secrets: an entry that is omitted, `''`, the redaction token or the
13367
- * view the form was given KEEPS its stored secret (it is left out of the merge); `{ $secretClear }`
13368
- * or `null` removes the entry; any other string replaces it. Null when nothing is left to merge.
13369
- */
13370
- function secretMapPatch(value) {
13371
- if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
13372
- const out = {};
13373
- for (const [key, entry] of Object.entries(value)) if (entry === null || isSecretClear(entry)) out[key] = null;
13374
- else if (typeof entry === "string" && entry !== "" && entry !== "__camstack_redacted__" && !isSecretFieldView(entry)) out[key] = entry;
13375
- return Object.keys(out).length > 0 ? out : null;
13376
- }
13377
- /** Does the kind's body schema carry an `enabled` field? */
13378
- function declaresEnabled(kind) {
13379
- const json = toJSONSchema(kind.schema, {
13380
- unrepresentable: "any",
13381
- io: "input"
13382
- });
13383
- const properties = Reflect.get(json, "properties");
13384
- return typeof properties === "object" && properties !== null && "enabled" in properties;
13385
- }
13386
- var RecordIntegrationInstances = class {
13387
- records;
13388
- kind;
13389
- hooks;
13390
- handle;
13391
- secretKeys;
13392
- secretMaps;
13393
- nameField;
13394
- /** The `integrations` registry owns the on/off switch (`role: devices`); the body has none. */
13395
- registryOwnsEnabled;
13396
- constructor(records, kind, hooks) {
13397
- this.records = records;
13398
- this.kind = kind;
13399
- this.hooks = hooks;
13400
- this.handle = records.kind(kind);
13401
- this.secretKeys = topLevelSecretKeys(kind.declaration.secretPaths);
13402
- this.secretMaps = secretMapKeys(kind.declaration.secretPaths);
13403
- this.nameField = kind.declaration.entry?.nameField ?? "name";
13404
- this.registryOwnsEnabled = hooks.description.role === "devices";
13405
- 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"`);
13406
- }
13407
- /**
13408
- * One instance read for the addon's own runtime; null when absent. When the keychain is
13409
- * locked the row is served WITHOUT its secrets and says so (`secrets: 'unavailable'`), so the
13410
- * caller can keep what it had instead of reconfiguring with an empty secret (D49).
13411
- */
13412
- async readResolved(id) {
13413
- try {
13414
- const record = await this.handle.getResolved(id);
13415
- return record === null ? null : {
13416
- id,
13417
- body: record.data,
13418
- enabled: record.data.enabled !== false,
13419
- secrets: "resolved"
13420
- };
13421
- } catch (err) {
13422
- if (!(err instanceof RecordSecretUnavailableError)) throw err;
13423
- const stored = await this.handle.get(id);
13424
- if (stored === null) return null;
13425
- return {
13426
- id,
13427
- body: Object.fromEntries(Object.entries(stored.data).filter(([key]) => !this.secretKeys.has(key))),
13428
- enabled: stored.data.enabled !== false,
13429
- secrets: "unavailable"
13430
- };
13431
- }
13432
- }
13433
- /** The body of {@link readResolved} alone; a locked keychain yields the row without secrets. */
13434
- async getResolved(id) {
13435
- return (await this.readResolved(id))?.body ?? null;
13436
- }
13437
- /** Every instance, secrets resolved where the keychain allows; an absent one is skipped. */
13438
- async listResolved() {
13439
- const page = await this.handle.query({ limit: INSTANCES_LIST_MAX });
13440
- const out = [];
13441
- for (const record of page.records) {
13442
- const read = await this.readResolved(record.id);
13443
- if (read !== null) out.push(read);
13444
- }
13445
- return out;
13446
- }
13447
- viewOf(record) {
13448
- const shown = secretViewsOf(this.records.owner, this.kind.name, record.id, this.kind.declaration, record.data);
13449
- const rawName = record.data[this.nameField];
13450
- const kind = this.hooks.kindOf?.(record.data);
13451
- const health = this.hooks.health?.(record.data, record.id);
13452
- return {
13453
- id: record.id,
13454
- name: typeof rawName === "string" ? rawName : record.id,
13455
- configured: this.hooks.configured(record.data),
13456
- ...this.registryOwnsEnabled ? {} : { enabled: record.data.enabled !== false },
13457
- formValues: shown,
13458
- ...kind !== void 0 ? { kind } : {},
13459
- ...health?.status !== void 0 ? { status: health.status } : {},
13460
- ...health?.lastCheckedAt !== void 0 ? { lastCheckedAt: health.lastCheckedAt } : {}
13461
- };
13462
- }
13463
- describe = async () => this.hooks.mintId === void 0 ? this.hooks.description : {
13464
- ...this.hooks.description,
13465
- mintsId: true
13466
- };
13467
- instanceFormSchema = async ({ id }) => this.hooks.formSchema(id);
13468
- listInstances = async () => {
13469
- return (await this.handle.query({ limit: INSTANCES_LIST_MAX })).records.map((record) => this.viewOf(record));
13470
- };
13471
- getInstance = async ({ id }) => {
13472
- const record = await this.handle.get(id);
13473
- return record === null ? null : this.viewOf(record);
13474
- };
13475
- /** Insert ONE row (`ifRev: 0`: an existing id is refused, never overwritten). */
13476
- createInstance = async ({ id, name, kind }) => {
13477
- const minted = id ?? this.hooks.mintId?.({
13478
- name,
13479
- ...kind !== void 0 ? { kind } : {}
13480
- });
13481
- if (minted === void 0) throw new Error("createInstance needs an id: this provider does not mint one");
13482
- await this.handle.put({
13483
- id: minted,
13484
- data: this.hooks.initialBody(name, kind)
13485
- }, { ifRev: 0 });
13486
- await this.hooks.onChanged?.(minted, "created");
13487
- return { id: minted };
13488
- };
13489
- updateInstance = async ({ id, name, values }) => {
13490
- const patch = {};
13491
- for (const [key, value] of Object.entries(values)) {
13492
- if (value === void 0) continue;
13493
- if (this.secretMaps.has(key)) {
13494
- const entries = secretMapPatch(value);
13495
- if (entries !== null) patch[key] = entries;
13496
- } else if (!this.secretKeys.has(key)) patch[key] = value;
13497
- else if (isSecretClear(value)) patch[key] = null;
13498
- else if (typeof value === "string" && value !== "" && value !== "__camstack_redacted__" && !isSecretFieldView(value)) patch[key] = value;
13499
- }
13500
- if (name !== void 0) patch[this.nameField] = name;
13501
- await this.handle.patch(id, patch);
13502
- await this.hooks.onChanged?.(id, "updated");
13503
- return { ok: true };
13504
- };
13505
- /** The switch lives in the record body; the addon is told so it applies it (D996). */
13506
- setInstanceEnabled = async ({ id, enabled }) => {
13507
- if (this.registryOwnsEnabled) throw new Error(`instance "${id}": the integrations registry owns the on/off switch of this addon; set it with integrations.update`);
13508
- await this.handle.patch(id, { enabled });
13509
- await this.hooks.onChanged?.(id, "enabled");
13510
- return { ok: true };
13511
- };
13512
- /** The row and its keychain refs go together (the records door). */
13513
- deleteInstance = async ({ id }) => {
13514
- await this.handle.delete(id);
13515
- await this.hooks.onChanged?.(id, "deleted");
13516
- return { ok: true };
13517
- };
13518
- testInstance = async (input) => {
13519
- if (this.hooks.test === void 0) return {
13520
- success: false,
13521
- status: "unsupported",
13522
- error: "This integration declares no connection test"
13523
- };
13524
- return this.hooks.test(input);
13525
- };
13526
- /** The flat provider object to hand to `registerProvider`. */
13527
- toProvider() {
13528
- return {
13529
- describe: this.describe,
13530
- instanceFormSchema: this.instanceFormSchema,
13531
- listInstances: this.listInstances,
13532
- getInstance: this.getInstance,
13533
- createInstance: this.createInstance,
13534
- updateInstance: this.updateInstance,
13535
- setInstanceEnabled: this.setInstanceEnabled,
13536
- deleteInstance: this.deleteInstance,
13537
- testInstance: this.testInstance
13538
- };
13539
- }
13540
- };
13541
14002
  var EncodeProfileSchema = object({
13542
14003
  video: object({
13543
14004
  codec: _enum([
@@ -14824,13 +15285,13 @@ async function claimDevicesToDefaultIntegration(ports, spec) {
14824
15285
  };
14825
15286
  if (orphans.some((d) => (d.parentDeviceId ?? null) === null) && fallback === null) throw new Error(`${orphans.length} device(s) of '${spec.addonId}' carry no integration and the addon has no integration to claim them to`);
14826
15287
  for (const device of orphans) if (resolve(device, new Set([device.id])) === null) unresolved.add(device.id);
14827
- for (const id of unresolved) ports.warnDevice(`device ${id} of '${spec.addonId}' carries no integration and its owner chain does not resolve to one: left unstamped`, id);
15288
+ for (const id of unresolved) await ports.warnDevice(`device ${id} of '${spec.addonId}' carries no integration and its owner chain does not resolve to one: left unstamped`, id);
14828
15289
  for (const [deviceId, integrationId] of plan) await ports.setIntegrationId(deviceId, integrationId);
14829
15290
  const wrong = [];
14830
15291
  for (const [deviceId, integrationId] of plan) if (await ports.readIntegrationId(deviceId) !== integrationId) wrong.push(deviceId);
14831
15292
  if (wrong.length > 0) throw new Error(`device(s) ${wrong.join(", ")} did not read back their integration after the claim`);
14832
15293
  const claimed = plan.size;
14833
- ports.info(`${claimed} device(s) of '${spec.addonId}' claimed to their owner's integration or the default; ${unresolved.size} unresolved, ${reservations.size} reservation(s) skipped`);
15294
+ await ports.info(`${claimed} device(s) of '${spec.addonId}' claimed to their owner's integration or the default; ${unresolved.size} unresolved, ${reservations.size} reservation(s) skipped`);
14834
15295
  return {
14835
15296
  outcome: claimed > 0 ? "done" : "already-done",
14836
15297
  summary: {
@@ -14956,25 +15417,6 @@ function defaultIntegrationMigrations(spec) {
14956
15417
  ...spec.eligible !== void 0 ? { eligible: spec.eligible } : {}
14957
15418
  })];
14958
15419
  }
14959
- function defaultIntegrationApiOver(api) {
14960
- return {
14961
- list: () => api.integrations.list.query(),
14962
- readLegacyIntegrationRows: (input) => api.migrations.readLegacyIntegrationRows.query(input),
14963
- clearLegacyIntegrationRows: (input) => api.migrations.clearLegacyIntegrationRows.mutate(input),
14964
- listDevices: (addonId) => api.deviceManager.listAll.query({
14965
- addonId,
14966
- projection: "slim"
14967
- }),
14968
- setDeviceIntegrationId: async (deviceId, integrationId) => {
14969
- await api.deviceManager.setIntegrationId.mutate({
14970
- deviceId,
14971
- integrationId
14972
- });
14973
- },
14974
- readDeviceHasConfig: async (deviceId) => Object.keys((await api.deviceManager.getDevice.query({ deviceId }))?.config ?? {}).length > 0,
14975
- readDeviceIntegrationId: async (deviceId) => (await api.deviceManager.getDevice.query({ deviceId }))?.integrationId ?? null
14976
- };
14977
- }
14978
15420
  /**
14979
15421
  * The trainer contract — what the hub hands the cloud trainer and what it
14980
15422
  * gets back (cloud training, D805+).
@@ -16081,6 +16523,39 @@ var UnstampedEventMediaCountSchema = object({
16081
16523
  /** Sum across both, or `null` when either lane could not be counted. */
16082
16524
  total: number().int().nonnegative().nullable()
16083
16525
  }).nullable();
16526
+ /**
16527
+ * Where the stored event media sits, per storage location: how many media rows
16528
+ * and how many bytes carry each location id, how many carry none (legacy,
16529
+ * resolved to the default `eventMedia` location), and how many name a location
16530
+ * that was not asked about (a deleted or never-listed one).
16531
+ *
16532
+ * One covering-index aggregate per asked location plus the NULL one, and one
16533
+ * unfiltered total that scans the covering index: O(rows), not a walk of the
16534
+ * rows themselves. `unlisted` is total minus the ASKED locations minus NULL, so
16535
+ * it is a deleted location only when every location id was asked.
16536
+ * `null` is "could not be measured", never zero.
16537
+ */
16538
+ var MediaLocationCensusInputSchema = object({ locationIds: array(string().min(1)).max(50).readonly() });
16539
+ var MediaLocationCensusSchema = object({
16540
+ locations: array(object({
16541
+ locationId: string(),
16542
+ rows: number().int().nonnegative(),
16543
+ bytes: number().nonnegative()
16544
+ })).readonly(),
16545
+ unstamped: object({
16546
+ rows: number().int().nonnegative(),
16547
+ bytes: number().nonnegative()
16548
+ }),
16549
+ /** Rows stamped with a location id that was not in the asked list. */
16550
+ unlisted: object({
16551
+ rows: number().int().nonnegative(),
16552
+ bytes: number().nonnegative()
16553
+ }),
16554
+ total: object({
16555
+ rows: number().int().nonnegative(),
16556
+ bytes: number().nonnegative()
16557
+ })
16558
+ });
16084
16559
  var StorageMigrationMediaMoveInputSchema = RelocateMediaInputSchema.extend({ leaseId: string().min(1) });
16085
16560
  /** The independently selectable logical storage classes — every class
16086
16561
  * `storage.listLocationDeclarations` reports, so an operator never meets a
@@ -20341,31 +20816,21 @@ var APPLIANCE_CAP_VOCABULARY = {
20341
20816
  "pet-fountain": {
20342
20817
  scope: "device",
20343
20818
  noun: t("Pet fountain", "Fontana per animali"),
20344
- actions: [
20345
- {
20346
- id: "petFountain.pumpOn",
20347
- method: "setPump",
20348
- label: t("Pump on", "Pompa accesa"),
20349
- phrase: t("Start the pump of {device}", "Avvia la pompa di {device}"),
20350
- icon: "play",
20351
- args: { on: true }
20352
- },
20353
- {
20354
- id: "petFountain.pumpOff",
20355
- method: "setPump",
20356
- label: t("Pump off", "Pompa spenta"),
20357
- phrase: t("Stop the pump of {device}", "Ferma la pompa di {device}"),
20358
- icon: "square",
20359
- args: { on: false }
20360
- },
20361
- {
20362
- id: "petFountain.resetDailyConsumption",
20363
- method: "resetDailyConsumption",
20364
- label: t("Clear daily consumption", "Azzera il consumo giornaliero"),
20365
- phrase: t("Clear the daily water consumption of {device}", "Azzera il consumo giornaliero di acqua di {device}"),
20366
- icon: "rotate-ccw"
20367
- }
20368
- ],
20819
+ actions: [{
20820
+ id: "petFountain.pumpOn",
20821
+ method: "setPump",
20822
+ label: t("Pump on", "Pompa accesa"),
20823
+ phrase: t("Start the pump of {device}", "Avvia la pompa di {device}"),
20824
+ icon: "play",
20825
+ args: { on: true }
20826
+ }, {
20827
+ id: "petFountain.pumpOff",
20828
+ method: "setPump",
20829
+ label: t("Pump off", "Pompa spenta"),
20830
+ phrase: t("Stop the pump of {device}", "Ferma la pompa di {device}"),
20831
+ icon: "square",
20832
+ args: { on: false }
20833
+ }],
20369
20834
  state: [{
20370
20835
  kind: "boolean",
20371
20836
  field: "empty",
@@ -44319,8 +44784,15 @@ var ActionInputSchema = object({
44319
44784
  var ActionRunOriginSchema = object({
44320
44785
  /** The automation block whose step started it. */
44321
44786
  blockId: string().min(1).optional() });
44322
- /** `started` = the caller did not ask to wait. */
44323
- var ActionRunOutcomeSchema = union([AutomationRunOutcomeSchema, literal("started")]);
44787
+ /**
44788
+ * `started` = the caller did not ask to wait. `timed-out` = the run reached the
44789
+ * ceiling (`ACTION_RUN_MAX_MS`) and was stopped; it is never a `ran`.
44790
+ */
44791
+ var ActionRunOutcomeSchema = union([
44792
+ AutomationRunOutcomeSchema,
44793
+ literal("started"),
44794
+ literal("timed-out")
44795
+ ]);
44324
44796
  var ActionRunResultSchema = object({
44325
44797
  runId: string().min(1),
44326
44798
  outcome: ActionRunOutcomeSchema,
@@ -44842,6 +45314,8 @@ method(object({}), array(ActionEntrySchema), { auth: "admin" }), method(object({
44842
45314
  kind: "mutation",
44843
45315
  auth: "admin"
44844
45316
  });
45317
+ /** `timeoutMs` of `actions.run`: a waited call outlives any legal run. */
45318
+ var ACTION_RUN_TIMEOUT_MS = 363e4;
44845
45319
  /**
44846
45320
  * actions — the ONE surface for runnable actions, for the UI and for
44847
45321
  * automations. Provided by the core-blocks builtin on the hub.
@@ -44860,6 +45334,12 @@ method(object({}), array(ActionEntrySchema), { auth: "admin" }), method(object({
44860
45334
  * An admin, and an in-process caller (an automation block), may run any action.
44861
45335
  * Every refusal is typed (`[not-linked] …`) and logged.
44862
45336
  *
45337
+ * **A run lasts at most `ACTION_RUN_MAX_MS` (60 min).** The provider stops a
45338
+ * run that reaches it and answers `timed-out` (never `ran`); an action whose
45339
+ * `wait` steps alone add up to more is refused at create/update
45340
+ * (`[invalid-steps]`). `run` declares a `timeoutMs` above that ceiling, so a
45341
+ * waited call (an automation step) is never cut by the 60 s transport default.
45342
+ *
44863
45343
  * A second `run` of an action that is already running is REFUSED — traced and
44864
45344
  * logged — never queued.
44865
45345
  */
@@ -44886,7 +45366,8 @@ method(object({}), array(ActionEntrySchema), { auth: "admin" }), method(object({
44886
45366
  role: "viewer",
44887
45367
  auth: "protected",
44888
45368
  kind: "mutation",
44889
- caller: "required"
45369
+ caller: "required",
45370
+ timeoutMs: ACTION_RUN_TIMEOUT_MS
44890
45371
  }), method(ActionIdInput, _void(), {
44891
45372
  kind: "mutation",
44892
45373
  auth: "admin"
@@ -47398,52 +47879,7 @@ onBrightnessChanged: { data: object({
47398
47879
  minIntervalMs: 0
47399
47880
  } } }
47400
47881
  };
47401
- /**
47402
- * `broker` — unified pub/sub broker registry, system-scoped collection.
47403
- *
47404
- * The cap models any kind-tagged message broker the user wants to
47405
- * register and that other addons might consume. The first two kinds
47406
- * are MQTT (mosquitto / aedes embedded / cloud bridge) and
47407
- * Home Assistant (HA WebSocket — subscribe_entities + call_service).
47408
- * Future kinds (Zigbee2MQTT bridge, ZHA, KNX, Telegram, …) plug in
47409
- * the same surface.
47410
- *
47411
- * Why one cap, not one cap per kind:
47412
- * - The integrations page wants a single table of "every broker"
47413
- * across kinds; a unified cap drives it without join logic.
47414
- * - Generic admin operations (add / remove / test / status) are
47415
- * identical across kinds — duplicating them per cap was busywork.
47416
- * - The `network-access` cap precedent: same interface, many
47417
- * `providerKind: 'ingress'` implementations (Tailscale, ngrok, …).
47418
- *
47419
- * What stays kind-specific:
47420
- * - `getBrokerConfig` payload (kind decides whether it returns
47421
- * mqtt URL+creds, HA baseUrl+token, …) — typed as
47422
- * `Record<string, unknown>` at the wire; consumers narrow.
47423
- * - `publish` / `subscribe` / `getState` arguments (target / filter /
47424
- * key) — also typed as `Record<string, unknown>` so each kind can
47425
- * evolve its surface (MQTT topic+qos vs HA entity_id+domain)
47426
- * without rebreaking the cap signature.
47427
- * - `add` `settings` payload (different fields per kind, validated by
47428
- * the kind-specific provider).
47429
- *
47430
- * Bidirectionality:
47431
- * - `publish` is RPC — synchronous result (provider-defined).
47432
- * - `subscribe` returns a subscription handle; the actual message
47433
- * stream flows over the typed event-bus as `broker.message` events
47434
- * keyed by `(brokerId, subscriptionId)`. Consumers filter in their
47435
- * event handler. Subscriptions persist across reconnects — the
47436
- * provider re-subscribes upstream after a transport drop.
47437
- *
47438
- * Why event-bus push (not a subscription RPC stream):
47439
- * - Matches the rest of CamStack's D8 contract — events for telemetry,
47440
- * RPC for loss-is-a-bug. Broker messages are telemetry (a single
47441
- * drop is recoverable via `getState({key})`).
47442
- * - Frees `broker.subscribe` from holding a long-lived RPC channel.
47443
- * - Cross-process: events already route through `$event-bus`; no
47444
- * per-broker wire-shaping needed.
47445
- */
47446
- var BrokerStatusEnum = _enum([
47882
+ _enum([
47447
47883
  "connected",
47448
47884
  "disconnected",
47449
47885
  "connecting",
@@ -47451,141 +47887,12 @@ var BrokerStatusEnum = _enum([
47451
47887
  "unreachable",
47452
47888
  "error"
47453
47889
  ]);
47454
- var BrokerInfoSchema = object({
47455
- /** Stable broker id. Persisted; survives addon restarts. */
47456
- id: string(),
47457
- /** Addon id of the provider that OWNS this broker.
47458
- *
47459
- * The `broker` cap is a system-scoped collection: several addons
47460
- * register a `broker` provider, each owning a DISJOINT set of
47461
- * brokers (mqtt-broker owns `mqtt_*`, provider-homeassistant owns
47462
- * `ha_*`). A broker therefore belongs to exactly one addon — like a
47463
- * device belongs to one integration. The admin UI threads this id
47464
- * back as the `{ addonId }` system-collection selector on every
47465
- * id-keyed call (`get` / `getSettings` / `setSettings` / `remove` /
47466
- * `testConnection`), so the call routes to the OWNING provider
47467
- * instead of defaulting to the first-registered one. */
47468
- addonId: string(),
47469
- /** Human-readable name (operator-chosen at add-time). */
47470
- name: string(),
47471
- /** Provider-defined kind tag — `mqtt` / `home-assistant` / future. */
47472
- kind: string(),
47473
- status: BrokerStatusEnum,
47474
- /** Free-form provider-specific info (HA version, MQTT broker
47475
- * flavour, latency, mTLS active, …). */
47476
- info: record(string(), unknown()),
47477
- /** Ms epoch of the last connection probe / status update. */
47478
- lastCheckedAt: number().nullable(),
47479
- /** Last error message, when `status` indicates failure. */
47480
- error: string().nullable()
47481
- });
47482
47890
  var RegistryStatusSchema = object({
47483
47891
  brokerCount: number().int().nonnegative(),
47484
47892
  connectedCount: number().int().nonnegative()
47485
47893
  });
47486
- /**
47487
- * One entry per `broker` provider — which addon provides which broker
47488
- * kind(s). The unified create picker reads this to know, for each
47489
- * (addonId, kind) pair the operator can pick, where to route the
47490
- * follow-up `getSettingsSchema` / `testSettings` / `add` calls (via the
47491
- * `{ addonId }` selector). A provider only advertises a kind here when
47492
- * it implements `getSettingsSchema` for that kind (so the picker never
47493
- * offers a kind whose creation form can't be rendered).
47494
- */
47495
- var BrokerProviderInfoSchema = object({
47496
- /** Addon id of the `broker` provider this entry describes. */
47497
- addonId: string(),
47498
- /** Broker kinds this provider can create, with a display label. */
47499
- kinds: array(object({
47500
- kind: string(),
47501
- label: string(),
47502
- /**
47503
- * Relative hub path to start an interactive account link (OAuth popup).
47504
- * May include `{{brokerId}}`; admin-ui substitutes and appends `?popup=1`.
47505
- */
47506
- interactiveConnectPath: string().min(1).optional(),
47507
- /** Relative hub path to disconnect the linked account (same popup pattern). */
47508
- interactiveDisconnectPath: string().min(1).optional(),
47509
- /**
47510
- * The kind signs in through a server-held interactive session instead of
47511
- * (or before) typed credentials. `basePath` is a hub-relative route set
47512
- * served by the owning addon (`/addon/<id>/...`) speaking the sign-in
47513
- * contract: `POST {basePath}/start` (body: the form's settings) answers
47514
- * `{ sessionId, loginUrl }`; `GET {basePath}/status?sessionId=` answers
47515
- * `{ phase: 'starting' | 'awaiting-login' | 'captured' | 'error' |
47516
- * 'cancelled', loginUrl, error }`; `POST {basePath}/commit`
47517
- * (`{ sessionId, name, brokerId? }`) stores the credentials on a new or
47518
- * existing broker and answers `{ brokerId }`; `POST {basePath}/cancel`
47519
- * (`{ sessionId }`) drops the session. The dialog that edits a broker
47520
- * offers it as the default path; the fields the session fills are
47521
- * marked `filledBySignIn` in the kind's settings schema.
47522
- *
47523
- * `methods` lists the ways the session can sign in, recommended first:
47524
- * `'device-code'` adds `POST {basePath}/code/start` (body: the form's
47525
- * settings) answering `{ sessionId, userCode, verificationUrl,
47526
- * expiresAt }` — the operator types `userCode` at `verificationUrl` on
47527
- * any device, and the same `status` / `commit` / `cancel` routes follow
47528
- * (status then carries `method`, `userCode`, `verificationUrl`,
47529
- * `expiresAt` and the phases `'awaiting-code'` / `'expired'`);
47530
- * `'proxy'` is the `{basePath}/start` flow above. Absent means
47531
- * `['proxy']`.
47532
- */
47533
- signIn: object({
47534
- basePath: string().min(1),
47535
- methods: array(_enum(["device-code", "proxy"])).optional()
47536
- }).optional()
47537
- }))
47538
- });
47539
- var ListInputSchema = object({
47540
- /** Optional kind filter — `list({kind:'home-assistant'})` returns
47541
- * only HA brokers. Omit to list every broker. */
47542
- kind: string().optional() });
47543
47894
  var GetInputSchema = object({ id: string() });
47544
- var AddInputSchema = object({
47545
- kind: string().min(1),
47546
- name: string().min(1),
47547
- /**
47548
- * ADOPT an existing id instead of minting a new one.
47549
- *
47550
- * Written the day this cost an outage. A broker's id is not a detail: HA
47551
- * devices carry it inside their `stableId` (`ha:ha_004:dev:…`), so a broker
47552
- * lost from config and re-added as `ha_001` leaves every one of its devices
47553
- * bound to a broker that no longer exists. Re-entering the password under the
47554
- * ORIGINAL id turns a multi-step device migration back into re-entering a
47555
- * password.
47556
- *
47557
- * A provider MUST refuse an id that is already in use — adopting a live
47558
- * broker's id would silently take it over.
47559
- */
47560
- id: string().min(1).optional(),
47561
- /** Kind-specific settings (e.g. MQTT `{url,username,password}` or HA
47562
- * `{baseUrl,accessToken}`). Validated by the kind-specific provider
47563
- * branch on receipt — invalid shape rejects the add. */
47564
- settings: record(string(), unknown())
47565
- });
47566
- var AddResultSchema = object({ id: string() });
47567
- var RemoveInputSchema = object({ id: string() });
47568
- var TestConnectionResultSchema = discriminatedUnion("ok", [object({
47569
- ok: literal(true),
47570
- latencyMs: number().nonnegative()
47571
- }), object({
47572
- ok: literal(false),
47573
- error: string()
47574
- })]);
47575
47895
  var SettingsRecordSchema$1 = record(string(), unknown());
47576
- var SettingsSchemaInputSchema = object({ kind: string() });
47577
- var TestSettingsInputSchema = object({
47578
- kind: string(),
47579
- settings: SettingsRecordSchema$1
47580
- });
47581
- var TestSettingsResultSchema = discriminatedUnion("ok", [object({
47582
- ok: literal(true),
47583
- latencyMs: number().nonnegative().optional()
47584
- }).strict(), object({
47585
- ok: literal(false),
47586
- error: string()
47587
- })]);
47588
- var SettingsSchemaResultSchema = unknown().nullable();
47589
47896
  var PublishInputSchema = object({
47590
47897
  brokerId: string(),
47591
47898
  /** Kind-specific routing target.
@@ -47619,25 +47926,7 @@ var GetStateInputSchema = object({
47619
47926
  * HA: entity_id (returns the cached entity state). */
47620
47927
  key: string()
47621
47928
  });
47622
- method(ListInputSchema, array(BrokerInfoSchema)), method(GetInputSchema, BrokerInfoSchema.nullable()), method(_void(), array(BrokerProviderInfoSchema), { auth: "admin" }), method(AddInputSchema, AddResultSchema, {
47623
- kind: "mutation",
47624
- auth: "admin"
47625
- }), method(RemoveInputSchema, _void(), {
47626
- kind: "mutation",
47627
- auth: "admin"
47628
- }), method(GetInputSchema, TestConnectionResultSchema, {
47629
- kind: "mutation",
47630
- auth: "admin"
47631
- }), method(GetInputSchema, SettingsRecordSchema$1.nullable(), { auth: "admin" }), method(object({
47632
- id: string(),
47633
- settings: SettingsRecordSchema$1
47634
- }), _void(), {
47635
- kind: "mutation",
47636
- auth: "admin"
47637
- }), method(GetInputSchema, SettingsRecordSchema$1.nullable(), { auth: "admin" }), method(SettingsSchemaInputSchema, SettingsSchemaResultSchema, { auth: "admin" }), method(TestSettingsInputSchema, TestSettingsResultSchema, {
47638
- kind: "mutation",
47639
- auth: "admin"
47640
- }), method(PublishInputSchema, unknown(), {
47929
+ method(GetInputSchema, SettingsRecordSchema$1.nullable(), { auth: "admin" }), method(PublishInputSchema, unknown(), {
47641
47930
  kind: "mutation",
47642
47931
  auth: "admin"
47643
47932
  }), method(SubscribeInputSchema, SubscribeResultSchema, {
@@ -50105,6 +50394,9 @@ var MediaPlayerStatusSchema = object({
50105
50394
  /** Repeat mode. Null when no repeat surface.
50106
50395
  * Pair with `DeviceFeature.MediaPlayerRepeat`. */
50107
50396
  repeat: MediaPlayerRepeatSchema.nullable(),
50397
+ /** Ms epoch when `position` was read from the device. Null when the driver
50398
+ * does not say; a UI that advances the position while playing counts from it. */
50399
+ positionUpdatedAt: number().nullable().default(null),
50108
50400
  /** Ms epoch when the slice was last updated. */
50109
50401
  lastChangedAt: number()
50110
50402
  });
@@ -50740,7 +51032,9 @@ var ThresholdTransformDraftSchema = object({
50740
51032
  comparison: _enum(["gte", "lte"]),
50741
51033
  threshold: number(),
50742
51034
  startDwellMs: number().nonnegative(),
50743
- stopDwellMs: number().nonnegative()
51035
+ stopDwellMs: number().nonnegative(),
51036
+ /** Samples a start needs; absent = the compiler's default for the source (2 for running power, else 1). */
51037
+ minSamples: number().int().min(1).optional()
50744
51038
  });
50745
51039
  var CustomizeTransformDraftSchema = discriminatedUnion("kind", [
50746
51040
  IdentityTransformDraftSchema,
@@ -52458,7 +52752,14 @@ var DiscoveryCandidateSchema = object({
52458
52752
  /** `stableId` of the gateway candidate this device was found BEHIND. */
52459
52753
  parentStableId: string().optional(),
52460
52754
  /** `false` = shown for context but not pickable. Default true. */
52461
- selectable: boolean().optional()
52755
+ selectable: boolean().optional(),
52756
+ /**
52757
+ * Keys of the provider's creation form (`getChildCreationSchema`) this candidate
52758
+ * cannot be adopted without — a key for an encrypted board, a pairing code. The
52759
+ * admin asks for exactly these, on the creation form prefilled with
52760
+ * `prefilledConfig`, before it adopts. Absent or empty = adopt as it is.
52761
+ */
52762
+ needsParams: array(string()).optional()
52462
52763
  });
52463
52764
  /**
52464
52765
  * Flat device summary returned by `createDevice` / `adoptDiscoveredDevice`.
@@ -52585,8 +52886,14 @@ var deviceProviderCapability = {
52585
52886
  * provider does not support manual creation. Lets the Add-Device dialog
52586
52887
  * pick the right type instead of assuming Camera.
52587
52888
  */
52588
- getManualCreationType: method(object({}), object({ deviceType: _enum(DeviceType).nullable() })),
52589
- adoptDiscoveredDevice: method(object({ candidate: DiscoveryCandidateSchema }), DeviceSummarySchema, {
52889
+ getManualCreationType: method(object({
52890
+ /** The integration asked about; a provider whose integrations differ answers per one. */
52891
+ integrationId: string().optional() }), object({ deviceType: _enum(DeviceType).nullable() })),
52892
+ adoptDiscoveredDevice: method(object({
52893
+ candidate: DiscoveryCandidateSchema,
52894
+ /** The integration the operator adopts into; a provider with several instances needs it. */
52895
+ integrationId: string().optional()
52896
+ }), DeviceSummarySchema, {
52590
52897
  kind: "mutation",
52591
52898
  auth: "admin"
52592
52899
  }),
@@ -52597,10 +52904,16 @@ var deviceProviderCapability = {
52597
52904
  * devices of that type. The output is a `ConfigUISchema` — the
52598
52905
  * router type-asserts it at the boundary.
52599
52906
  */
52600
- getChildCreationSchema: method(object({ type: _enum(DeviceType) }), CreationSchemaOutputSchema),
52907
+ getChildCreationSchema: method(object({
52908
+ type: _enum(DeviceType),
52909
+ /** The integration asked about; a provider whose integrations differ answers per one. */
52910
+ integrationId: string().optional()
52911
+ }), CreationSchemaOutputSchema),
52601
52912
  createDevice: method(object({
52602
52913
  type: _enum(DeviceType),
52603
- config: record(string(), unknown())
52914
+ config: record(string(), unknown()),
52915
+ /** The integration the operator adds the device to; a provider with several instances needs it. */
52916
+ integrationId: string().optional()
52604
52917
  }), DeviceSummarySchema, {
52605
52918
  kind: "mutation",
52606
52919
  auth: "admin"
@@ -53325,7 +53638,10 @@ method(object({
53325
53638
  auth: "admin"
53326
53639
  }), method(object({
53327
53640
  addonId: string(),
53328
- type: _enum(DeviceType)
53641
+ type: _enum(DeviceType),
53642
+ /** The integration the form is for; a provider whose integrations differ (a hub
53643
+ * integration takes no manual add) answers per integration. Absent = the addon's own. */
53644
+ integrationId: string().optional()
53329
53645
  }), unknown().nullable()), method(object({
53330
53646
  addonId: string(),
53331
53647
  type: _enum(DeviceType),
@@ -53409,7 +53725,11 @@ method(object({
53409
53725
  kind: "mutation",
53410
53726
  auth: "admin",
53411
53727
  timeoutMs: 12e4
53412
- }), method(object({ addonId: string() }), object({ deviceType: _enum(DeviceType).nullable() }), { auth: "admin" }), method(object({ addonId: string() }), unknown(), { auth: "admin" }), method(object({
53728
+ }), method(object({
53729
+ addonId: string(),
53730
+ /** The integration the Add-Device dialog is open on; absent = the addon's own. */
53731
+ integrationId: string().optional()
53732
+ }), object({ deviceType: _enum(DeviceType).nullable() }), { auth: "admin" }), method(object({ addonId: string() }), unknown(), { auth: "admin" }), method(object({
53413
53733
  deviceId: number(),
53414
53734
  key: string(),
53415
53735
  value: unknown()
@@ -56614,6 +56934,7 @@ var IntegrationWithStateSchema = object({
56614
56934
  id: string(),
56615
56935
  addonId: string(),
56616
56936
  name: string(),
56937
+ /** A projection of the instance body's switch (`setInstanceEnabled` is the only writer). */
56617
56938
  enabled: boolean(),
56618
56939
  info: record(string(), unknown()).readonly(),
56619
56940
  /** The discovery candidate this integration was set up from (D984). */
@@ -56626,6 +56947,7 @@ var IntegrationLiteSchema = object({
56626
56947
  id: string(),
56627
56948
  addonId: string(),
56628
56949
  name: string(),
56950
+ /** A projection of the instance body's switch (`setInstanceEnabled` is the only writer). */
56629
56951
  enabled: boolean(),
56630
56952
  info: record(string(), unknown()).readonly(),
56631
56953
  /** The discovery candidate this integration was set up from (D984). */
@@ -56708,7 +57030,7 @@ var TestConnectionStatusEnum = _enum([
56708
57030
  "inconclusive",
56709
57031
  "unsupported"
56710
57032
  ]);
56711
- var TestConnectionResultSchema$1 = object({
57033
+ var TestConnectionResultSchema = object({
56712
57034
  /** True ONLY for `validated`. Never true for a test that did not run. */
56713
57035
  success: boolean(),
56714
57036
  error: string().optional(),
@@ -56725,7 +57047,6 @@ var TestConnectionResultSchema$1 = object({
56725
57047
  var CreateIntegrationInputSchema = object({
56726
57048
  addonId: string(),
56727
57049
  name: string(),
56728
- enabled: boolean().optional(),
56729
57050
  info: record(string(), unknown()).optional(),
56730
57051
  /** `stableId` of the discovery candidate the form was seeded from (D984). */
56731
57052
  originStableId: string().optional(),
@@ -56734,6 +57055,11 @@ var CreateIntegrationInputSchema = object({
56734
57055
  var UpdateIntegrationInputSchema = object({
56735
57056
  id: string(),
56736
57057
  name: string().optional(),
57058
+ /**
57059
+ * Accepted for a FIXED builtin only (`info.fixed`: alarm panel, camera grid, core blocks,
57060
+ * terminal), which keeps no instance record: the registry flag is its one store. Any other
57061
+ * integration is switched through `integration-instances.setInstanceEnabled`.
57062
+ */
56737
57063
  enabled: boolean().optional(),
56738
57064
  info: record(string(), unknown()).optional()
56739
57065
  });
@@ -56753,7 +57079,7 @@ method(_void(), array(IntegrationWithStateSchema)), method(object({ id: string()
56753
57079
  }), method(_void(), array(AvailableIntegrationTypeSchema), { auth: "admin" }), method(object({
56754
57080
  addonId: string(),
56755
57081
  settings: record(string(), unknown())
56756
- }), TestConnectionResultSchema$1, {
57082
+ }), TestConnectionResultSchema, {
56757
57083
  kind: "mutation",
56758
57084
  auth: "admin"
56759
57085
  });
@@ -56780,6 +57106,14 @@ var ConfigSchemaPassthrough$3 = custom();
56780
57106
  var IntegrationInstanceIdSchema = string().min(1);
56781
57107
  var IntegrationInstanceModeSchema = _enum(["single", "multiple"]);
56782
57108
  /**
57109
+ * What the addon's instances ARE for the Integrations page (planning#416). `devices`: each
57110
+ * instance is an integration that brings devices (its record body owns the on/off switch);
57111
+ * `services`: a connection configured from the addon's own function page, never listed on
57112
+ * Integrations.
57113
+ * It is the same vocabulary as the manifest's `integrationRole`, which stays as an override.
57114
+ */
57115
+ var IntegrationInstanceRoleSchema = _enum(["devices", "services"]);
57116
+ /**
56783
57117
  * One kind of instance a provider can create (an adapter, an account type). The sign-in and
56784
57118
  * connect fields follow the `broker` contract (`broker.cap.ts`): `signIn.basePath` is a
56785
57119
  * hub-relative route set speaking the sign-in contract, `connectPath` / `disconnectPath` open an
@@ -56790,6 +57124,22 @@ var IntegrationInstanceKindSchema = object({
56790
57124
  /** Stable id of the kind, sent back as `createInstance.kind`. */
56791
57125
  id: string().min(1),
56792
57126
  label: string().min(1),
57127
+ /**
57128
+ * The function capability this kind is configured for (`broker`, `smtp-provider`,
57129
+ * `device-provider`, ...). A page section is the kinds whose `functionCap` it names (D1013); a
57130
+ * provider with more than one section must name it on every kind.
57131
+ */
57132
+ functionCap: string().min(1),
57133
+ /**
57134
+ * For `functionCap: 'broker'`: the registry kind of the broker an instance of this kind is
57135
+ * (`matter`, `home-assistant`, ...). A caller that needs a broker of one kind (a link field)
57136
+ * finds the instances whose kind names it; absent takes the kind `id`.
57137
+ */
57138
+ brokerKind: string().min(1).optional(),
57139
+ /** What instances of this kind are for the Integrations page; absent takes the provider's `role`. */
57140
+ role: IntegrationInstanceRoleSchema.optional(),
57141
+ /** `testInstance` really probes the remote for this kind; absent takes the provider's `canTest`. */
57142
+ canTest: boolean().optional(),
56793
57143
  /** The kind signs in through a server-held interactive session. */
56794
57144
  signIn: object({
56795
57145
  basePath: string().min(1),
@@ -56800,22 +57150,38 @@ var IntegrationInstanceKindSchema = object({
56800
57150
  /** Relative hub path to disconnect that account. */
56801
57151
  disconnectPath: string().min(1).optional()
56802
57152
  });
57153
+ /**
57154
+ * How devices of an instance are found. `none`: the operator adds them by hand; `lan`: the addon
57155
+ * scans the network before any instance exists (the wizard offers the candidates); `account`: the
57156
+ * devices appear after the instance signs in. `scopedToInstance`: a discovery run belongs to ONE
57157
+ * instance and its candidates are claimed by it.
57158
+ */
57159
+ var IntegrationInstanceDiscoverySchema = object({
57160
+ mode: _enum([
57161
+ "none",
57162
+ "lan",
57163
+ "account"
57164
+ ]),
57165
+ scopedToInstance: boolean()
57166
+ });
57167
+ /**
57168
+ * One link a kind of this provider declares (D1013 rule 5): the body `field` of an instance of
57169
+ * `kind` holds the id of an instance of the function cap `to.cap` (of kind `to.kind`, when set).
57170
+ * The hub indexes these so the target's delete is refused while a link names it.
57171
+ */
57172
+ var IntegrationInstanceLinkSchema = object({
57173
+ kind: string().min(1),
57174
+ field: string().min(1),
57175
+ to: object({
57176
+ cap: string().min(1),
57177
+ kind: string().min(1).optional()
57178
+ })
57179
+ });
56803
57180
  var IntegrationInstanceDescriptionSchema = object({
56804
57181
  /** What the instances are for the Integrations page; see {@link IntegrationInstanceRoleSchema}. */
56805
- role: _enum([
56806
- "devices",
56807
- "services",
56808
- "both"
56809
- ]),
57182
+ role: IntegrationInstanceRoleSchema,
56810
57183
  /** How the devices of an instance are found; absent means `{ mode: 'none' }`. */
56811
- discovery: object({
56812
- mode: _enum([
56813
- "none",
56814
- "lan",
56815
- "account"
56816
- ]),
56817
- scopedToInstance: boolean()
56818
- }).optional(),
57184
+ discovery: IntegrationInstanceDiscoverySchema.optional(),
56819
57185
  /** `single`: at most one instance can exist (Loki). `multiple`: an account each. */
56820
57186
  instanceMode: IntegrationInstanceModeSchema,
56821
57187
  /** What the instance is, for the UI (`destination`, `relay`, `account`). */
@@ -56836,7 +57202,9 @@ var IntegrationInstanceDescriptionSchema = object({
56836
57202
  * `createInstance` without an `id` works: the provider mints it. Absent means the caller must
56837
57203
  * send an id (the UI then mints an opaque one).
56838
57204
  */
56839
- mintsId: boolean().optional()
57205
+ mintsId: boolean().optional(),
57206
+ /** The links to other instances the provider's kinds declare; absent means none. */
57207
+ links: array(IntegrationInstanceLinkSchema).optional()
56840
57208
  });
56841
57209
  var IntegrationInstanceStatusSchema = object({
56842
57210
  state: _enum([
@@ -56856,8 +57224,8 @@ var IntegrationInstanceSchema = object({
56856
57224
  configured: boolean(),
56857
57225
  /**
56858
57226
  * The instance's own on/off switch (D996), derived from the record body (`enabled !== false`,
56859
- * so a row written before the field existed is on). Absent when the `integrations` registry
56860
- * owns the switch (`describe().role` is `devices`): read it from the registry row.
57227
+ * so a row written before the field existed is on). The same for every role, `devices` included:
57228
+ * the body is the one store, `setInstanceEnabled` the one writer (epic #440, step 3).
56861
57229
  */
56862
57230
  enabled: boolean().optional(),
56863
57231
  /** The kind of this instance (one of `describe().kinds[].id`), when the provider has kinds. */
@@ -56881,7 +57249,11 @@ var integrationInstancesCapability = {
56881
57249
  methods: {
56882
57250
  describe: method(_void(), IntegrationInstanceDescriptionSchema, { auth: "admin" }),
56883
57251
  /** The form; `id: null` is the create form. */
56884
- instanceFormSchema: method(object({ id: IntegrationInstanceIdSchema.nullable() }), ConfigSchemaPassthrough$3, { auth: "admin" }),
57252
+ instanceFormSchema: method(object({
57253
+ id: IntegrationInstanceIdSchema.nullable(),
57254
+ /** The kind of the create form (`id: null`) of a provider with several. */
57255
+ kind: string().min(1).optional()
57256
+ }), ConfigSchemaPassthrough$3, { auth: "admin" }),
56885
57257
  listInstances: method(_void(), array(IntegrationInstanceSchema).readonly(), { auth: "admin" }),
56886
57258
  getInstance: method(object({ id: IntegrationInstanceIdSchema }), IntegrationInstanceSchema.nullable(), { auth: "admin" }),
56887
57259
  /**
@@ -56891,7 +57263,9 @@ var integrationInstancesCapability = {
56891
57263
  createInstance: method(object({
56892
57264
  id: IntegrationInstanceIdSchema.optional(),
56893
57265
  name: string().min(1),
56894
- kind: string().min(1).optional()
57266
+ kind: string().min(1).optional(),
57267
+ /** Form values written with the record (a link picked in the create dialog). */
57268
+ values: record(string(), unknown()).optional()
56895
57269
  }), object({ id: string() }), {
56896
57270
  kind: "mutation",
56897
57271
  auth: "admin"
@@ -56901,7 +57275,8 @@ var integrationInstancesCapability = {
56901
57275
  auth: "admin"
56902
57276
  }),
56903
57277
  /**
56904
- * Switch ONE instance on or off. A row control, not a form field: `updateInstance.values` is the
57278
+ * Switch ONE instance on or off, for every role; a missing record is created from the addon's
57279
+ * initial body. A row control, not a form field: `updateInstance.values` is the
56905
57280
  * form patch (D62, D996). An off instance keeps its record and secrets and does no work.
56906
57281
  */
56907
57282
  setInstanceEnabled: method(object({
@@ -56918,8 +57293,10 @@ var integrationInstancesCapability = {
56918
57293
  }),
56919
57294
  testInstance: optionalMethod(object({
56920
57295
  id: IntegrationInstanceIdSchema.nullable(),
56921
- values: record(string(), unknown())
56922
- }), TestConnectionResultSchema$1, {
57296
+ values: record(string(), unknown()),
57297
+ /** The kind to test when `id` is null and the provider has several. */
57298
+ kind: string().min(1).optional()
57299
+ }), TestConnectionResultSchema, {
56923
57300
  kind: "mutation",
56924
57301
  auth: "admin"
56925
57302
  })
@@ -59676,6 +60053,382 @@ var SystemMetricsSchema = object({
59676
60053
  gpuMemoryPercent: number().optional()
59677
60054
  });
59678
60055
  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);
60056
+ /**
60057
+ * records - an addon's own facts and documents (D881): ledgers, audit rows,
60058
+ * config documents, mirrors. The third storage API next to `ctx.settings`
60059
+ * (operator intent, D870) and device-history (numbers over time, D850).
60060
+ *
60061
+ * Who the OWNER is: `callerAddonId`, stamped by the transport on a call that
60062
+ * crossed a process and stated by a hub in-process caller (`ctx.records` does
60063
+ * that with the addon id closed over). It is deliberately NOT in any input
60064
+ * schema, so a session can never supply it, and a call with no stamp is refused
60065
+ * `records/no-caller`. A kind is readable and writable only by its owner; other
60066
+ * addons go through the owner's capability.
60067
+ *
60068
+ * Every read is three-way: a row, `null`, or the call THROWS. A failed read is
60069
+ * never `[]`. Secret fields are never on the wire: a read shows the
60070
+ * redaction token, `secretRefs` hands the owner's `ctx.secrets` the refs it
60071
+ * resolves itself, and a write may carry only a keychain marker bound to the
60072
+ * row's own ref.
60073
+ *
60074
+ * Internal: addons reach it through `ctx.records`, never directly.
60075
+ */
60076
+ var RecordIdSchema = string().min(1).max(256);
60077
+ /** A JSON object body. Size is the engine's check (`maxDataBytes`), not a schema's. */
60078
+ var RecordBodySchema = record(string(), unknown());
60079
+ var RecordInputSchema = object({
60080
+ id: RecordIdSchema,
60081
+ /** The device this row belongs to (D865 removal, per-device reads). */
60082
+ deviceId: number().int().optional(),
60083
+ /** The domain clock, ms: observed / created / opened. */
60084
+ at: number().int().optional(),
60085
+ /** Producer-set expiry, ms. Refused on a kind whose retention is an engine TTL. */
60086
+ expiresAt: number().int().optional(),
60087
+ data: RecordBodySchema
60088
+ });
60089
+ var RecordViewSchema = object({
60090
+ id: string(),
60091
+ deviceId: number().int().nullable(),
60092
+ at: number().nullable(),
60093
+ expiresAt: number().nullable(),
60094
+ rev: number().int(),
60095
+ updatedAt: number(),
60096
+ data: RecordBodySchema
60097
+ });
60098
+ /** Declared index fields only. Anything else does not compile, by design. */
60099
+ var RecordWhereSchema = record(RecordFieldPathSchema, union([
60100
+ string(),
60101
+ number(),
60102
+ boolean(),
60103
+ object({ in: array(union([
60104
+ string(),
60105
+ number(),
60106
+ boolean()
60107
+ ])).min(1).max(RECORD_BATCH_MAX) }),
60108
+ object({
60109
+ gt: union([string(), number()]).optional(),
60110
+ gte: union([string(), number()]).optional(),
60111
+ lt: union([string(), number()]).optional(),
60112
+ lte: union([string(), number()]).optional()
60113
+ }).refine((r) => Object.keys(r).length > 0, { message: "name at least one bound" })
60114
+ ]));
60115
+ var KindShape = { kind: RecordKindNameSchema };
60116
+ var TimeWindowShape = {
60117
+ deviceId: number().int().optional(),
60118
+ atFrom: number().optional(),
60119
+ atTo: number().optional()
60120
+ };
60121
+ var RecordQueryInputSchema = object({
60122
+ ...KindShape,
60123
+ ...TimeWindowShape,
60124
+ where: RecordWhereSchema.optional(),
60125
+ /** Without `where`: `at` (default for a kind with a clock) or `id`. With `where` the order is the index's. */
60126
+ order: _enum(["at", "id"]).optional(),
60127
+ desc: boolean().optional(),
60128
+ limit: number().int().min(1).max(RECORD_QUERY_MAX).default(100),
60129
+ /** Opaque keyset cursor from a previous answer. There is no offset. */
60130
+ cursor: string().min(1).optional()
60131
+ });
60132
+ var RecordQueryResultSchema = object({
60133
+ records: array(RecordViewSchema),
60134
+ nextCursor: string().nullable()
60135
+ });
60136
+ var RecordKindStateSchema = _enum([
60137
+ "created",
60138
+ "unchanged",
60139
+ "updated"
60140
+ ]);
60141
+ var DeclareKindResultSchema = object({
60142
+ kindId: number().int(),
60143
+ state: RecordKindStateSchema,
60144
+ createdIndexes: array(string())
60145
+ });
60146
+ /** Keychain refs a write released (the old marker is gone from the row): the owner deletes the values. */
60147
+ var SecretRefsList = array(string());
60148
+ /**
60149
+ * One op of a `transact`: the single-row writes, each on a kind of the caller.
60150
+ * All ops of one call share ONE database file and ONE `transactFamily`.
60151
+ */
60152
+ var RecordTransactOpSchema = discriminatedUnion("op", [
60153
+ object({
60154
+ op: literal("put"),
60155
+ kind: RecordKindNameSchema,
60156
+ record: RecordInputSchema,
60157
+ ifRev: number().int().min(0).optional()
60158
+ }),
60159
+ object({
60160
+ op: literal("patch"),
60161
+ kind: RecordKindNameSchema,
60162
+ id: RecordIdSchema,
60163
+ data: RecordBodySchema,
60164
+ at: number().int().nullable().optional(),
60165
+ expiresAt: number().int().nullable().optional(),
60166
+ ifRev: number().int().min(1).optional()
60167
+ }),
60168
+ object({
60169
+ op: literal("delete"),
60170
+ kind: RecordKindNameSchema,
60171
+ id: RecordIdSchema
60172
+ })
60173
+ ]);
60174
+ var RecordSecretRefsSchema = record(string(), record(string(), string()));
60175
+ method(object({ kinds: record(RecordKindNameSchema, RecordKindDeclarationSchema) }), object({ kinds: record(string(), DeclareKindResultSchema) }), {
60176
+ kind: "mutation",
60177
+ auth: "admin"
60178
+ }), method(object({
60179
+ ...KindShape,
60180
+ id: RecordIdSchema
60181
+ }), RecordViewSchema.nullable(), { auth: "admin" }), method(object({
60182
+ ...KindShape,
60183
+ ids: array(RecordIdSchema).min(1).max(RECORD_BATCH_MAX)
60184
+ }), array(RecordViewSchema), { auth: "admin" }), method(object({
60185
+ ...KindShape,
60186
+ ids: array(RecordIdSchema).min(1).max(RECORD_BATCH_MAX)
60187
+ }), RecordSecretRefsSchema, { auth: "admin" }), method(object({
60188
+ ...KindShape,
60189
+ record: RecordInputSchema,
60190
+ /** Compare-and-set. `0` means "the row must not exist". */
60191
+ ifRev: number().int().min(0).optional()
60192
+ }), object({
60193
+ rev: number().int(),
60194
+ releasedRefs: SecretRefsList
60195
+ }), {
60196
+ kind: "mutation",
60197
+ auth: "admin"
60198
+ }), method(object({
60199
+ ...KindShape,
60200
+ records: array(RecordInputSchema).min(1).max(RECORD_BATCH_MAX)
60201
+ }), object({
60202
+ count: number().int(),
60203
+ releasedRefs: SecretRefsList
60204
+ }), {
60205
+ kind: "mutation",
60206
+ auth: "admin"
60207
+ }), method(object({
60208
+ ...KindShape,
60209
+ id: RecordIdSchema,
60210
+ data: RecordBodySchema,
60211
+ at: number().int().nullable().optional(),
60212
+ expiresAt: number().int().nullable().optional(),
60213
+ ifRev: number().int().min(1).optional()
60214
+ }), object({
60215
+ rev: number().int(),
60216
+ releasedRefs: SecretRefsList
60217
+ }), {
60218
+ kind: "mutation",
60219
+ auth: "admin"
60220
+ }), method(object({
60221
+ ...KindShape,
60222
+ id: RecordIdSchema
60223
+ }), object({
60224
+ deleted: boolean(),
60225
+ secretRefs: SecretRefsList
60226
+ }), {
60227
+ kind: "mutation",
60228
+ auth: "admin"
60229
+ }), method(object({
60230
+ ...KindShape,
60231
+ ids: array(RecordIdSchema).min(1).max(RECORD_BATCH_MAX)
60232
+ }), object({
60233
+ deleted: number().int(),
60234
+ secretRefs: SecretRefsList
60235
+ }), {
60236
+ kind: "mutation",
60237
+ auth: "admin"
60238
+ }), method(RecordQueryInputSchema, RecordQueryResultSchema, { auth: "admin" }), method(object({
60239
+ ...KindShape,
60240
+ ...TimeWindowShape,
60241
+ where: RecordWhereSchema.optional()
60242
+ }), object({ count: number().int() }), { auth: "admin" }), method(object({
60243
+ ...KindShape,
60244
+ deviceId: number().int().optional(),
60245
+ from: number(),
60246
+ to: number(),
60247
+ bucketMs: number().int().positive()
60248
+ }), object({ buckets: array(object({
60249
+ bucketStart: number(),
60250
+ count: number().int()
60251
+ })) }), { auth: "admin" }), method(object({
60252
+ ...KindShape,
60253
+ op: _enum([
60254
+ "sum",
60255
+ "min",
60256
+ "max",
60257
+ "count"
60258
+ ]),
60259
+ field: RecordFieldPathSchema.optional(),
60260
+ groupBy: RecordFieldPathSchema.optional(),
60261
+ where: RecordWhereSchema.optional()
60262
+ }), object({ rows: array(object({
60263
+ group: union([
60264
+ string(),
60265
+ number(),
60266
+ _null()
60267
+ ]),
60268
+ value: number().nullable()
60269
+ })) }), { auth: "admin" }), method(object({
60270
+ ...KindShape,
60271
+ deviceId: number().int().optional(),
60272
+ atBefore: number().optional(),
60273
+ where: RecordWhereSchema.optional()
60274
+ }), object({
60275
+ deleted: number().int(),
60276
+ secretRefs: SecretRefsList
60277
+ }), {
60278
+ kind: "mutation",
60279
+ auth: "admin"
60280
+ }), method(object({ ops: array(RecordTransactOpSchema).min(1).max(RECORD_BATCH_MAX) }), object({
60281
+ results: array(object({
60282
+ rev: number().int().nullable(),
60283
+ deleted: boolean()
60284
+ })),
60285
+ releasedRefs: SecretRefsList,
60286
+ secretRefs: SecretRefsList
60287
+ }), {
60288
+ kind: "mutation",
60289
+ auth: "admin"
60290
+ }), method(object({
60291
+ deviceId: number().int(),
60292
+ kinds: array(RecordKindNameSchema).optional()
60293
+ }), object({
60294
+ deleted: record(string(), number().int()),
60295
+ secretRefs: SecretRefsList
60296
+ }), {
60297
+ kind: "mutation",
60298
+ auth: "admin"
60299
+ }), method(object(KindShape), object({ id: number().int() }), {
60300
+ kind: "mutation",
60301
+ auth: "admin"
60302
+ });
60303
+ /**
60304
+ * The wire shapes of the migration API, version 1 (planning#447).
60305
+ *
60306
+ * A migration is code that outlives the server it was written against: an addon at
60307
+ * version 1.4 that is brought to 1.9 in one jump still runs its 1.4 catalogue, against
60308
+ * the 1.9 kernel. The only thing that code may call is {@link MigrationApiV1}; this file
60309
+ * is the contract of every method of it, one Zod pair per method.
60310
+ *
60311
+ * APPEND-ONLY. A released method is never removed and never changes meaning: an input
60312
+ * field is never removed or made required, an enum never narrows, an output field is
60313
+ * never removed. A change that cannot be expressed that way is `migration-api.v2`, next
60314
+ * to this file. `scripts/check-migration-api-append-only.ts` holds the line against
60315
+ * `scripts/migration-api-contract.json`, and every `behaviours` id below must have an
60316
+ * `it('<id>'` in `migration-api.contract.spec.ts`.
60317
+ */
60318
+ var Rows = record(string(), unknown());
60319
+ var IntegrationId = object({ integrationId: string().min(1) });
60320
+ var RecordId = object({ id: string().min(1) });
60321
+ var RecordRowSchema = object({
60322
+ id: string(),
60323
+ deviceId: number().int().nullable(),
60324
+ at: number().nullable(),
60325
+ expiresAt: number().nullable(),
60326
+ rev: number().int(),
60327
+ updatedAt: number(),
60328
+ data: Rows
60329
+ });
60330
+ var RecordPutShape = {
60331
+ id: string().min(1),
60332
+ deviceId: number().int().optional(),
60333
+ at: number().int().optional(),
60334
+ expiresAt: number().int().optional(),
60335
+ data: Rows
60336
+ };
60337
+ var MigrationIntegrationSchema = object({
60338
+ id: string(),
60339
+ addonId: string(),
60340
+ name: string(),
60341
+ info: Rows,
60342
+ /** The registry's stored switch: read by the one-switch migration, nothing else. */
60343
+ enabled: boolean().optional(),
60344
+ originStableId: string().optional()
60345
+ });
60346
+ var MigrationDeviceSchema = object({
60347
+ id: number().int(),
60348
+ integrationId: string().nullable().optional(),
60349
+ /** The owning device; null or absent for a root. */
60350
+ parentDeviceId: number().int().nullable().optional(),
60351
+ type: string().optional(),
60352
+ name: string().optional(),
60353
+ stableId: string().optional()
60354
+ });
60355
+ /** What the engine says about the migration API it serves: lets an addon notice an older server. */
60356
+ var MigrationApiInfoSchema = object({
60357
+ version: number().int(),
60358
+ methods: array(string())
60359
+ });
60360
+ object({
60361
+ message: string(),
60362
+ meta: Rows.optional(),
60363
+ /** Grouping tags of the line; a line about a device carries `{ deviceId }`. */
60364
+ tags: object({ deviceId: number().int().optional() }).optional()
60365
+ });
60366
+ object({
60367
+ owner: string().min(1),
60368
+ metas: array(MigrationMetaSchema)
60369
+ }), object({
60370
+ bootId: string(),
60371
+ snapshot: _enum([
60372
+ "none",
60373
+ "written",
60374
+ "refused"
60375
+ ]),
60376
+ steps: array(MigrationOwnerStepSchema),
60377
+ /** The migration API the engine serves; absent from a server that predates it. */
60378
+ migrationApi: MigrationApiInfoSchema.optional()
60379
+ }), object({ id: string().min(1) }), object({
60380
+ proceed: boolean(),
60381
+ state: union([literal("pending"), MigrationStatusSchema]),
60382
+ reason: string().nullable()
60383
+ }), object({
60384
+ id: string().min(1),
60385
+ result: MigrationOwnerResultSchema
60386
+ }), object({
60387
+ status: MigrationStatusSchema,
60388
+ error: string().nullable(),
60389
+ rowsChanged: number().int().nonnegative()
60390
+ }), object({
60391
+ rows: number().int().nonnegative(),
60392
+ secrets: number().int().nonnegative()
60393
+ }), IntegrationId.extend({ patch: Rows }), object({ written: boolean() }), IntegrationId.extend({ keys: array(string().min(1)) }), object({
60394
+ present: boolean(),
60395
+ removed: Rows
60396
+ }), RecordRowSchema.nullable(), RecordRowSchema.nullable(), object({
60397
+ ...RecordPutShape,
60398
+ ifRev: number().int().optional()
60399
+ }), object({ rev: number().int() }), object({ records: array(object(RecordPutShape)) }), object({ count: number().int().nonnegative() }), RecordId.extend({
60400
+ partial: Rows,
60401
+ ifRev: number().int().optional()
60402
+ }), object({ rev: number().int() }), object({ deleted: boolean() }), object({
60403
+ deviceId: number().int().optional(),
60404
+ atFrom: number().optional(),
60405
+ atTo: number().optional(),
60406
+ where: RecordWhereSchema.optional(),
60407
+ limit: number().int().min(1).optional(),
60408
+ cursor: string().min(1).optional(),
60409
+ resolveSecrets: boolean().optional()
60410
+ }), object({
60411
+ records: array(RecordRowSchema),
60412
+ nextCursor: string().nullable()
60413
+ }), object({
60414
+ deviceId: number().int().optional(),
60415
+ atBefore: number().optional(),
60416
+ where: RecordWhereSchema.optional()
60417
+ }), 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({
60418
+ ref: string().min(1),
60419
+ value: string()
60420
+ }), object({}), object({ refs: array(string()) }), object({ deleted: number().int().nonnegative() }), object({}), object({ integrations: array(MigrationIntegrationSchema) }), object({ id: string().min(1) }), MigrationIntegrationSchema.nullable(), object({
60421
+ addonId: string().min(1),
60422
+ integrationId: string().min(1).optional()
60423
+ }), object({ devices: array(MigrationDeviceSchema) }), object({ deviceId: number().int() }), object({
60424
+ id: number().int(),
60425
+ integrationId: string().nullable(),
60426
+ /** Whether the device carries any stored config; its content is not offered. */
60427
+ hasConfig: boolean()
60428
+ }).nullable(), object({
60429
+ deviceId: number().int(),
60430
+ integrationId: string().min(1)
60431
+ }), object({}), object({}), object({ nodeId: string() }), object({}), object({});
59679
60432
  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({
59680
60433
  id: string().min(1),
59681
60434
  error: string().min(1)
@@ -59705,7 +60458,9 @@ method(object({}), object({ entries: array(MigrationLedgerEntrySchema) }), { aut
59705
60458
  "written",
59706
60459
  "refused"
59707
60460
  ]),
59708
- steps: array(MigrationOwnerStepSchema)
60461
+ steps: array(MigrationOwnerStepSchema),
60462
+ /** The migration API this engine serves (additive: a server that predates it omits it). */
60463
+ migrationApi: MigrationApiInfoSchema.optional()
59709
60464
  }), {
59710
60465
  kind: "mutation",
59711
60466
  auth: "admin"
@@ -62372,7 +63127,10 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
62372
63127
  }), method(RelocateMediaInputSchema, object({ jobId: string() }), {
62373
63128
  kind: "mutation",
62374
63129
  auth: "admin"
62375
- }), method(object({}), UnstampedEventMediaCountSchema, { auth: "admin" }), method(RelocatableMediaCountInputSchema, RelocatableMediaCountSchema, {
63130
+ }), method(object({}), UnstampedEventMediaCountSchema, { auth: "admin" }), method(MediaLocationCensusInputSchema, MediaLocationCensusSchema, {
63131
+ kind: "query",
63132
+ auth: "admin"
63133
+ }), method(RelocatableMediaCountInputSchema, RelocatableMediaCountSchema, {
62376
63134
  kind: "query",
62377
63135
  auth: "admin"
62378
63136
  }), method(object({}), array(RelocateJobSchema).readonly(), {
@@ -65027,7 +65785,7 @@ var BrokerStatusSchema$1 = _enum([
65027
65785
  "unreachable",
65028
65786
  "tls-error"
65029
65787
  ]);
65030
- var BrokerInfoSchema$1 = object({
65788
+ var BrokerInfoSchema = object({
65031
65789
  id: string(),
65032
65790
  name: string(),
65033
65791
  url: string(),
@@ -65090,7 +65848,7 @@ var StatusSchema = object({
65090
65848
  brokerCount: number(),
65091
65849
  embeddedRunning: boolean()
65092
65850
  });
65093
- method(_void(), array(BrokerInfoSchema$1)), method(IdInputSchema, BrokerConnectionDetailsSchema, { auth: "admin" }), method(AddBrokerInputSchema, AddBrokerResultSchema, {
65851
+ method(_void(), array(BrokerInfoSchema)), method(IdInputSchema, BrokerConnectionDetailsSchema, { auth: "admin" }), method(AddBrokerInputSchema, AddBrokerResultSchema, {
65094
65852
  kind: "mutation",
65095
65853
  auth: "admin"
65096
65854
  }), method(IdInputSchema, _void(), {
@@ -69758,14 +70516,6 @@ var PetFountainStatusSchema = object({
69758
70516
  empty: boolean().nullable(),
69759
70517
  /** True while the pump is running. Null while unknown. */
69760
70518
  pumpRunning: boolean().nullable(),
69761
- /** Water drunk in the last drink, in litres. */
69762
- lastDrink: number().min(0).nullable().meta(readingMeta("volume")),
69763
- /** Water drunk in the current hour, in litres. */
69764
- currentHourDrink: number().min(0).nullable().meta(readingMeta("volume")),
69765
- /** Water drunk over the last 24 hours (rolling), in litres. */
69766
- last24hDrink: number().min(0).nullable().meta(readingMeta("volume")),
69767
- /** Water drunk since local midnight, in litres. Null when the fountain has no such sensor. */
69768
- todayDrink: number().min(0).nullable().meta(readingMeta("volume")),
69769
70519
  /** Decoded fault message. Null means healthy; a non-null string is an active fault. */
69770
70520
  error: string().nullable(),
69771
70521
  /** Ms epoch when the slice was last refreshed. */
@@ -69778,21 +70528,15 @@ var petFountainCapability = {
69778
70528
  deviceNative: true,
69779
70529
  mode: "singleton",
69780
70530
  deviceTypes: [DeviceType.PetFountain],
69781
- methods: {
69782
- /** Start or stop the pump. */
69783
- setPump: method(object({
69784
- deviceId: DeviceIdSchema$1,
69785
- on: boolean()
69786
- }), _void(), {
69787
- kind: "mutation",
69788
- auth: "protected"
69789
- }),
69790
- /** Clear the rolling daily consumption counters on the device. */
69791
- resetDailyConsumption: method(object({ deviceId: DeviceIdSchema$1 }), _void(), {
69792
- kind: "mutation",
69793
- auth: "protected"
69794
- })
69795
- },
70531
+ methods: {
70532
+ /** Start or stop the pump. */
70533
+ setPump: method(object({
70534
+ deviceId: DeviceIdSchema$1,
70535
+ on: boolean()
70536
+ }), _void(), {
70537
+ kind: "mutation",
70538
+ auth: "protected"
70539
+ }) },
69796
70540
  status: {
69797
70541
  schema: PetFountainStatusSchema,
69798
70542
  kind: "push"
@@ -69816,14 +70560,6 @@ var petFountainCapability = {
69816
70560
  waterVolume: {
69817
70561
  kind: "gauge",
69818
70562
  unit: "L"
69819
- },
69820
- todayDrink: {
69821
- kind: "gauge",
69822
- unit: "L"
69823
- },
69824
- last24hDrink: {
69825
- kind: "gauge",
69826
- unit: "L"
69827
70563
  }
69828
70564
  } }
69829
70565
  };
@@ -72456,253 +73192,6 @@ var rebootCapability = {
72456
73192
  }) }
72457
73193
  };
72458
73194
  /**
72459
- * records - an addon's own facts and documents (D881): ledgers, audit rows,
72460
- * config documents, mirrors. The third storage API next to `ctx.settings`
72461
- * (operator intent, D870) and device-history (numbers over time, D850).
72462
- *
72463
- * Who the OWNER is: `callerAddonId`, stamped by the transport on a call that
72464
- * crossed a process and stated by a hub in-process caller (`ctx.records` does
72465
- * that with the addon id closed over). It is deliberately NOT in any input
72466
- * schema, so a session can never supply it, and a call with no stamp is refused
72467
- * `records/no-caller`. A kind is readable and writable only by its owner; other
72468
- * addons go through the owner's capability.
72469
- *
72470
- * Every read is three-way: a row, `null`, or the call THROWS. A failed read is
72471
- * never `[]`. Secret fields are never on the wire: a read shows the
72472
- * redaction token, `secretRefs` hands the owner's `ctx.secrets` the refs it
72473
- * resolves itself, and a write may carry only a keychain marker bound to the
72474
- * row's own ref.
72475
- *
72476
- * Internal: addons reach it through `ctx.records`, never directly.
72477
- */
72478
- var RecordIdSchema = string().min(1).max(256);
72479
- /** A JSON object body. Size is the engine's check (`maxDataBytes`), not a schema's. */
72480
- var RecordBodySchema = record(string(), unknown());
72481
- var RecordInputSchema = object({
72482
- id: RecordIdSchema,
72483
- /** The device this row belongs to (D865 removal, per-device reads). */
72484
- deviceId: number().int().optional(),
72485
- /** The domain clock, ms: observed / created / opened. */
72486
- at: number().int().optional(),
72487
- /** Producer-set expiry, ms. Refused on a kind whose retention is an engine TTL. */
72488
- expiresAt: number().int().optional(),
72489
- data: RecordBodySchema
72490
- });
72491
- var RecordViewSchema = object({
72492
- id: string(),
72493
- deviceId: number().int().nullable(),
72494
- at: number().nullable(),
72495
- expiresAt: number().nullable(),
72496
- rev: number().int(),
72497
- updatedAt: number(),
72498
- data: RecordBodySchema
72499
- });
72500
- /** Declared index fields only. Anything else does not compile, by design. */
72501
- var RecordWhereSchema = record(RecordFieldPathSchema, union([
72502
- string(),
72503
- number(),
72504
- boolean(),
72505
- object({ in: array(union([
72506
- string(),
72507
- number(),
72508
- boolean()
72509
- ])).min(1).max(RECORD_BATCH_MAX) }),
72510
- object({
72511
- gt: union([string(), number()]).optional(),
72512
- gte: union([string(), number()]).optional(),
72513
- lt: union([string(), number()]).optional(),
72514
- lte: union([string(), number()]).optional()
72515
- }).refine((r) => Object.keys(r).length > 0, { message: "name at least one bound" })
72516
- ]));
72517
- var KindShape = { kind: RecordKindNameSchema };
72518
- var TimeWindowShape = {
72519
- deviceId: number().int().optional(),
72520
- atFrom: number().optional(),
72521
- atTo: number().optional()
72522
- };
72523
- var RecordQueryInputSchema = object({
72524
- ...KindShape,
72525
- ...TimeWindowShape,
72526
- where: RecordWhereSchema.optional(),
72527
- /** Without `where`: `at` (default for a kind with a clock) or `id`. With `where` the order is the index's. */
72528
- order: _enum(["at", "id"]).optional(),
72529
- desc: boolean().optional(),
72530
- limit: number().int().min(1).max(RECORD_QUERY_MAX).default(100),
72531
- /** Opaque keyset cursor from a previous answer. There is no offset. */
72532
- cursor: string().min(1).optional()
72533
- });
72534
- var RecordQueryResultSchema = object({
72535
- records: array(RecordViewSchema),
72536
- nextCursor: string().nullable()
72537
- });
72538
- var RecordKindStateSchema = _enum([
72539
- "created",
72540
- "unchanged",
72541
- "updated"
72542
- ]);
72543
- var DeclareKindResultSchema = object({
72544
- kindId: number().int(),
72545
- state: RecordKindStateSchema,
72546
- createdIndexes: array(string())
72547
- });
72548
- /** Keychain refs a write released (the old marker is gone from the row): the owner deletes the values. */
72549
- var SecretRefsList = array(string());
72550
- /**
72551
- * One op of a `transact`: the single-row writes, each on a kind of the caller.
72552
- * All ops of one call share ONE database file and ONE `transactFamily`.
72553
- */
72554
- var RecordTransactOpSchema = discriminatedUnion("op", [
72555
- object({
72556
- op: literal("put"),
72557
- kind: RecordKindNameSchema,
72558
- record: RecordInputSchema,
72559
- ifRev: number().int().min(0).optional()
72560
- }),
72561
- object({
72562
- op: literal("patch"),
72563
- kind: RecordKindNameSchema,
72564
- id: RecordIdSchema,
72565
- data: RecordBodySchema,
72566
- at: number().int().nullable().optional(),
72567
- expiresAt: number().int().nullable().optional(),
72568
- ifRev: number().int().min(1).optional()
72569
- }),
72570
- object({
72571
- op: literal("delete"),
72572
- kind: RecordKindNameSchema,
72573
- id: RecordIdSchema
72574
- })
72575
- ]);
72576
- var RecordSecretRefsSchema = record(string(), record(string(), string()));
72577
- method(object({ kinds: record(RecordKindNameSchema, RecordKindDeclarationSchema) }), object({ kinds: record(string(), DeclareKindResultSchema) }), {
72578
- kind: "mutation",
72579
- auth: "admin"
72580
- }), method(object({
72581
- ...KindShape,
72582
- id: RecordIdSchema
72583
- }), RecordViewSchema.nullable(), { auth: "admin" }), method(object({
72584
- ...KindShape,
72585
- ids: array(RecordIdSchema).min(1).max(RECORD_BATCH_MAX)
72586
- }), array(RecordViewSchema), { auth: "admin" }), method(object({
72587
- ...KindShape,
72588
- ids: array(RecordIdSchema).min(1).max(RECORD_BATCH_MAX)
72589
- }), RecordSecretRefsSchema, { auth: "admin" }), method(object({
72590
- ...KindShape,
72591
- record: RecordInputSchema,
72592
- /** Compare-and-set. `0` means "the row must not exist". */
72593
- ifRev: number().int().min(0).optional()
72594
- }), object({
72595
- rev: number().int(),
72596
- releasedRefs: SecretRefsList
72597
- }), {
72598
- kind: "mutation",
72599
- auth: "admin"
72600
- }), method(object({
72601
- ...KindShape,
72602
- records: array(RecordInputSchema).min(1).max(RECORD_BATCH_MAX)
72603
- }), object({
72604
- count: number().int(),
72605
- releasedRefs: SecretRefsList
72606
- }), {
72607
- kind: "mutation",
72608
- auth: "admin"
72609
- }), method(object({
72610
- ...KindShape,
72611
- id: RecordIdSchema,
72612
- data: RecordBodySchema,
72613
- at: number().int().nullable().optional(),
72614
- expiresAt: number().int().nullable().optional(),
72615
- ifRev: number().int().min(1).optional()
72616
- }), object({
72617
- rev: number().int(),
72618
- releasedRefs: SecretRefsList
72619
- }), {
72620
- kind: "mutation",
72621
- auth: "admin"
72622
- }), method(object({
72623
- ...KindShape,
72624
- id: RecordIdSchema
72625
- }), object({
72626
- deleted: boolean(),
72627
- secretRefs: SecretRefsList
72628
- }), {
72629
- kind: "mutation",
72630
- auth: "admin"
72631
- }), method(object({
72632
- ...KindShape,
72633
- ids: array(RecordIdSchema).min(1).max(RECORD_BATCH_MAX)
72634
- }), object({
72635
- deleted: number().int(),
72636
- secretRefs: SecretRefsList
72637
- }), {
72638
- kind: "mutation",
72639
- auth: "admin"
72640
- }), method(RecordQueryInputSchema, RecordQueryResultSchema, { auth: "admin" }), method(object({
72641
- ...KindShape,
72642
- ...TimeWindowShape,
72643
- where: RecordWhereSchema.optional()
72644
- }), object({ count: number().int() }), { auth: "admin" }), method(object({
72645
- ...KindShape,
72646
- deviceId: number().int().optional(),
72647
- from: number(),
72648
- to: number(),
72649
- bucketMs: number().int().positive()
72650
- }), object({ buckets: array(object({
72651
- bucketStart: number(),
72652
- count: number().int()
72653
- })) }), { auth: "admin" }), method(object({
72654
- ...KindShape,
72655
- op: _enum([
72656
- "sum",
72657
- "min",
72658
- "max",
72659
- "count"
72660
- ]),
72661
- field: RecordFieldPathSchema.optional(),
72662
- groupBy: RecordFieldPathSchema.optional(),
72663
- where: RecordWhereSchema.optional()
72664
- }), object({ rows: array(object({
72665
- group: union([
72666
- string(),
72667
- number(),
72668
- _null()
72669
- ]),
72670
- value: number().nullable()
72671
- })) }), { auth: "admin" }), method(object({
72672
- ...KindShape,
72673
- deviceId: number().int().optional(),
72674
- atBefore: number().optional(),
72675
- where: RecordWhereSchema.optional()
72676
- }), object({
72677
- deleted: number().int(),
72678
- secretRefs: SecretRefsList
72679
- }), {
72680
- kind: "mutation",
72681
- auth: "admin"
72682
- }), method(object({ ops: array(RecordTransactOpSchema).min(1).max(RECORD_BATCH_MAX) }), object({
72683
- results: array(object({
72684
- rev: number().int().nullable(),
72685
- deleted: boolean()
72686
- })),
72687
- releasedRefs: SecretRefsList,
72688
- secretRefs: SecretRefsList
72689
- }), {
72690
- kind: "mutation",
72691
- auth: "admin"
72692
- }), method(object({
72693
- deviceId: number().int(),
72694
- kinds: array(RecordKindNameSchema).optional()
72695
- }), object({
72696
- deleted: record(string(), number().int()),
72697
- secretRefs: SecretRefsList
72698
- }), {
72699
- kind: "mutation",
72700
- auth: "admin"
72701
- }), method(object(KindShape), object({ id: number().int() }), {
72702
- kind: "mutation",
72703
- auth: "admin"
72704
- });
72705
- /**
72706
73195
  * record-entries - the ONE admin surface for every list of user-created entries
72707
73196
  * (D881): notification targets, brokers, LLM profiles, anything an addon
72708
73197
  * declares as an ENTRY kind (`entry: { title }` in `defineRecordKinds`).
@@ -83570,7 +84059,7 @@ var BaseDeviceProvider = class extends BaseAddon {
83570
84059
  * `deviceClasses` map (first registered type). `null` when manual creation is
83571
84060
  * unsupported. Lets the Add-Device dialog pick the right type per provider.
83572
84061
  */
83573
- async getManualCreationType() {
84062
+ async getManualCreationType(_input) {
83574
84063
  if (!await this.supportsManualCreation()) return { deviceType: null };
83575
84064
  return { deviceType: Object.values(DeviceType).find((t) => this.deviceClasses[t] !== void 0) ?? null };
83576
84065
  }
@@ -83581,7 +84070,7 @@ var BaseDeviceProvider = class extends BaseAddon {
83581
84070
  return true;
83582
84071
  }
83583
84072
  async getChildCreationSchema(input) {
83584
- return this.onGetCreationSchema(input.type);
84073
+ return this.onGetCreationSchema(input.type, { integrationId: input.integrationId });
83585
84074
  }
83586
84075
  /**
83587
84076
  * Default kernel-orchestrated `createDevice` implementation. The
@@ -83593,7 +84082,7 @@ var BaseDeviceProvider = class extends BaseAddon {
83593
84082
  * `deviceClasses` instead.
83594
84083
  */
83595
84084
  async createDevice(input) {
83596
- const spec = await this.onCreateDevice(input.type, input.config);
84085
+ const spec = await this.onCreateDevice(input.type, input.config, { ...input.integrationId !== void 0 ? { integrationId: input.integrationId } : {} });
83597
84086
  const Class = this.deviceClasses[spec.meta.type];
83598
84087
  if (!Class) throw new Error(`${this.providerName} provider: no device class registered for type "${spec.meta.type}" — add it to the deviceClasses map`);
83599
84088
  const stableId = this.generateStableId(spec.meta.type, spec.config);
@@ -85006,20 +85495,6 @@ Object.freeze({
85006
85495
  access: "create",
85007
85496
  role: "viewer"
85008
85497
  },
85009
- "broker.add": {
85010
- capName: "broker",
85011
- capScope: "system",
85012
- addonId: null,
85013
- access: "create",
85014
- role: "admin"
85015
- },
85016
- "broker.get": {
85017
- capName: "broker",
85018
- capScope: "system",
85019
- addonId: null,
85020
- access: "view",
85021
- role: "admin"
85022
- },
85023
85498
  "broker.getBrokerConfig": {
85024
85499
  capName: "broker",
85025
85500
  capScope: "system",
@@ -85027,20 +85502,6 @@ Object.freeze({
85027
85502
  access: "view",
85028
85503
  role: "admin"
85029
85504
  },
85030
- "broker.getSettings": {
85031
- capName: "broker",
85032
- capScope: "system",
85033
- addonId: null,
85034
- access: "view",
85035
- role: "admin"
85036
- },
85037
- "broker.getSettingsSchema": {
85038
- capName: "broker",
85039
- capScope: "system",
85040
- addonId: null,
85041
- access: "view",
85042
- role: "admin"
85043
- },
85044
85505
  "broker.getState": {
85045
85506
  capName: "broker",
85046
85507
  capScope: "system",
@@ -85055,20 +85516,6 @@ Object.freeze({
85055
85516
  access: "view",
85056
85517
  role: "admin"
85057
85518
  },
85058
- "broker.list": {
85059
- capName: "broker",
85060
- capScope: "system",
85061
- addonId: null,
85062
- access: "view",
85063
- role: "admin"
85064
- },
85065
- "broker.listProviders": {
85066
- capName: "broker",
85067
- capScope: "system",
85068
- addonId: null,
85069
- access: "view",
85070
- role: "admin"
85071
- },
85072
85519
  "broker.publish": {
85073
85520
  capName: "broker",
85074
85521
  capScope: "system",
@@ -85076,20 +85523,6 @@ Object.freeze({
85076
85523
  access: "create",
85077
85524
  role: "admin"
85078
85525
  },
85079
- "broker.remove": {
85080
- capName: "broker",
85081
- capScope: "system",
85082
- addonId: null,
85083
- access: "delete",
85084
- role: "admin"
85085
- },
85086
- "broker.setSettings": {
85087
- capName: "broker",
85088
- capScope: "system",
85089
- addonId: null,
85090
- access: "create",
85091
- role: "admin"
85092
- },
85093
85526
  "broker.subscribe": {
85094
85527
  capName: "broker",
85095
85528
  capScope: "system",
@@ -85097,20 +85530,6 @@ Object.freeze({
85097
85530
  access: "create",
85098
85531
  role: "admin"
85099
85532
  },
85100
- "broker.testConnection": {
85101
- capName: "broker",
85102
- capScope: "system",
85103
- addonId: null,
85104
- access: "create",
85105
- role: "admin"
85106
- },
85107
- "broker.testSettings": {
85108
- capName: "broker",
85109
- capScope: "system",
85110
- addonId: null,
85111
- access: "create",
85112
- role: "admin"
85113
- },
85114
85533
  "broker.unsubscribe": {
85115
85534
  capName: "broker",
85116
85535
  capScope: "system",
@@ -89871,13 +90290,6 @@ Object.freeze({
89871
90290
  access: "view",
89872
90291
  role: "viewer"
89873
90292
  },
89874
- "petFountain.resetDailyConsumption": {
89875
- capName: "pet-fountain",
89876
- capScope: "device",
89877
- addonId: null,
89878
- access: "delete",
89879
- role: "viewer"
89880
- },
89881
90293
  "petFountain.setPump": {
89882
90294
  capName: "pet-fountain",
89883
90295
  capScope: "device",
@@ -90074,6 +90486,13 @@ Object.freeze({
90074
90486
  access: "view",
90075
90487
  role: "viewer"
90076
90488
  },
90489
+ "pipelineAnalytics.getMediaLocationCensus": {
90490
+ capName: "pipeline-analytics",
90491
+ capScope: "device",
90492
+ addonId: null,
90493
+ access: "view",
90494
+ role: "admin"
90495
+ },
90077
90496
  "pipelineAnalytics.getMediaReclaimStatus": {
90078
90497
  capName: "pipeline-analytics",
90079
90498
  capScope: "device",
@@ -96485,11 +96904,6 @@ Object.freeze({
96485
96904
  form: "single",
96486
96905
  optional: false
96487
96906
  }],
96488
- "petFountain.resetDailyConsumption": [{
96489
- name: "deviceId",
96490
- form: "single",
96491
- optional: false
96492
- }],
96493
96907
  "petFountain.setPump": [{
96494
96908
  name: "deviceId",
96495
96909
  form: "single",
@@ -113010,18 +113424,17 @@ var HikvisionProviderAddon = class extends BaseDeviceProvider {
113010
113424
  const records = this.ctx.records;
113011
113425
  if (records === void 0) throw new Error("provider-hikvision: ctx.records is required (hub-only addon)");
113012
113426
  await records.declare(hikvisionRecordKinds);
113013
- await this.runMigrations(defineAddonMigrations(defaultIntegrationMigrations({
113427
+ this.declareRegistrySwitch({
113428
+ kind: hikvisionConnectionsEntryKind,
113429
+ initialBody: (name) => ({ name })
113430
+ });
113431
+ await this.runMigrations(defaultIntegrationMigrations({
113014
113432
  addonId: this.addonId,
113015
113433
  date: HIKVISION_MIGRATIONS_DATE
113016
- }), defaultIntegrationPortsOver({
113017
- api: defaultIntegrationApiOver(this.ctx.api),
113018
- secrets: this.ctx.secrets ?? null,
113019
- records,
113020
- kind: hikvisionConnectionsEntryKind,
113021
- info: (message) => this.ctx.logger.info(message),
113022
- warn: (message) => this.ctx.logger.warn(message),
113023
- warnDevice: (message, deviceId) => this.ctx.logger.warn(message, { tags: { deviceId } })
113024
- })));
113434
+ }), (api) => defaultIntegrationPortsOver({
113435
+ ...defaultIntegrationDepsOver(api),
113436
+ kind: hikvisionConnectionsEntryKind
113437
+ }));
113025
113438
  regs.push({
113026
113439
  capability: failureContributionCapability,
113027
113440
  provider: { list: () => intercomFailureReport.list() }