@camstack/addon-provider-hikvision 1.2.183 → 1.2.185

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 +1801 -1673
  3. package/dist/addon.mjs +1801 -1673
  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-BX_MqzUe.mjs
6017
+ //#region ../types/dist/sleep-D7ZKm4nb.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,137 +6698,206 @@ 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
+ }
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
+ };
6798
6810
  }
6811
+ var PREFIX = "records/";
6799
6812
  /**
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.
6813
+ * Cross-realm brand. An addon bundles its own copy of this module (D15) while
6814
+ * `ctx.records` is the HOST's door, so an error thrown by the host is an
6815
+ * instance of the host's classes, not of the addon's. The brand plus the code
6816
+ * make `instanceof` answer by identity of the failure, not of the copy.
6812
6817
  */
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;
6818
+ var RECORDS_ERROR_BRAND = Symbol.for("camstack.records-error");
6819
+ function carriesBrand(value) {
6820
+ return typeof value === "object" && value !== null && Reflect.get(value, RECORDS_ERROR_BRAND) === true;
6821
+ }
6822
+ /** The base of every records failure. `detail` is the human part of the message. */
6823
+ var RecordsError = class extends Error {
6824
+ /** The code a subclass stands for; the base stands for every code. */
6825
+ static code = void 0;
6826
+ /**
6827
+ * `instanceof` across copies of this module: any branded error is a
6828
+ * `RecordsError`, and is an instance of a subclass only when its code is the
6829
+ * subclass's code. Same-copy answers are unchanged.
6830
+ */
6831
+ static [Symbol.hasInstance](value) {
6832
+ if (Function.prototype[Symbol.hasInstance].call(this, value)) return true;
6833
+ if (!carriesBrand(value)) return false;
6834
+ return this.code === void 0 || value.code === this.code;
6819
6835
  }
6820
- for (const base of perNodeKeys) {
6821
- const value = readNodeValue(store, base, nodeId);
6822
- if (value !== void 0) out[base] = value;
6836
+ code;
6837
+ detail;
6838
+ [RECORDS_ERROR_BRAND] = true;
6839
+ constructor(code, detail) {
6840
+ super(`${PREFIX}${code}: ${detail}`);
6841
+ this.name = "RecordsError";
6842
+ this.code = code;
6843
+ this.detail = detail;
6823
6844
  }
6824
- return out;
6845
+ };
6846
+ /** A write guarded by `ifRev` found another revision (or an existing row for `ifRev: 0`). */
6847
+ var RevConflictError = class RevConflictError extends RecordsError {
6848
+ static code = "rev-conflict";
6849
+ constructor(detail) {
6850
+ super(RevConflictError.code, detail);
6851
+ this.name = "RevConflictError";
6852
+ }
6853
+ };
6854
+ /** The keychain could not store or serve a value: explicit, never an empty string. */
6855
+ var RecordSecretUnavailableError = class RecordSecretUnavailableError extends RecordsError {
6856
+ static code = "secret-unavailable";
6857
+ constructor(detail) {
6858
+ super(RecordSecretUnavailableError.code, detail);
6859
+ this.name = "RecordSecretUnavailableError";
6860
+ }
6861
+ };
6862
+ var InvalidRecordError = class InvalidRecordError extends RecordsError {
6863
+ static code = "invalid-record";
6864
+ constructor(detail) {
6865
+ super(InvalidRecordError.code, detail);
6866
+ this.name = "InvalidRecordError";
6867
+ }
6868
+ };
6869
+ /** A kind declaration the engine refuses (non-additive change, bad shape, wrong file). */
6870
+ var DeclarationRefusedError = class DeclarationRefusedError extends RecordsError {
6871
+ static code = "declaration-refused";
6872
+ constructor(detail) {
6873
+ super(DeclarationRefusedError.code, detail);
6874
+ this.name = "DeclarationRefusedError";
6875
+ }
6876
+ };
6877
+ function linkTargetOf(meta) {
6878
+ if (typeof meta !== "object" || meta === null) return void 0;
6879
+ const link = Reflect.get(meta, "link");
6880
+ const parsed = LinkTargetSchema.safeParse(link);
6881
+ return parsed.success ? parsed.data : void 0;
6882
+ }
6883
+ var LinkTargetSchema = object({
6884
+ cap: string().min(1),
6885
+ kind: string().min(1).optional()
6886
+ });
6887
+ /** The links a kind declares, read from the meta of its body fields. */
6888
+ function linksOfKind(kind) {
6889
+ const schema = kind.schema;
6890
+ if (!(schema instanceof ZodObject)) return [];
6891
+ const links = [];
6892
+ for (const [field, fieldSchema] of Object.entries(schema.shape)) {
6893
+ const to = linkTargetOf(globalRegistry.get(fieldSchema));
6894
+ if (to !== void 0) links.push({
6895
+ field,
6896
+ to
6897
+ });
6898
+ }
6899
+ return links;
6825
6900
  }
6826
- /** Every scope, in the order the guard and the docs list them. */
6827
- var SCOPED_SETTINGS_SCOPES = [
6828
- "cluster",
6829
- "device-defaults",
6830
- "node"
6831
- ];
6832
6901
  /**
6833
6902
  * The address of one keychain value: `secret://<owner>/<scope>/<fieldPath>`.
6834
6903
  *
@@ -6963,6 +7032,652 @@ function parseSecretRef(ref) {
6963
7032
  fieldPath
6964
7033
  };
6965
7034
  }
7035
+ /** Limits and names of `ctx.records` (D881). One authority; the engine and the facade read it. */
7036
+ /** The files a kind may live in. `history` is device-history's (D850), never records. */
7037
+ var RECORD_DATABASES = ["settings", "events"];
7038
+ /** The classes of a kind: the `@durable` vocabulary, one authority (replaces the annotation). */
7039
+ var RECORD_CLASSES = [
7040
+ "config",
7041
+ "ledger",
7042
+ "audit",
7043
+ "mirror",
7044
+ "ephemeral"
7045
+ ];
7046
+ var RECORD_DEFAULT_MAX_DATA_BYTES = 64 * 1024;
7047
+ var RECORD_MAX_DATA_BYTES = 1024 * 1024;
7048
+ var RECORD_BATCH_MAX = 1e3;
7049
+ var RECORD_QUERY_MAX = 1e3;
7050
+ /** A kind in the `settings` file may not bound itself above this (D447: high volume is `events`). */
7051
+ var RECORD_SETTINGS_MAX_ROWS = 5e4;
7052
+ /** The `Column`-free proof prefix: a ref collection for a kind's secret fields. */
7053
+ var RECORD_SECRET_COLLECTION_PREFIX = "records:";
7054
+ /**
7055
+ * Secret fields of a record, addressed the way a Zod schema declares them
7056
+ * (`collectZodSecretPaths`): dotted keys, `[]` for "each element of this array"
7057
+ * (`auth.accessToken`, `headers[].value`).
7058
+ *
7059
+ * `{}` after a key means "each value of this map" (`applianceSecrets{}`): the map's own key
7060
+ * names the value (`applianceSecrets{fridge}`), so no id key is declared and a body that drops a
7061
+ * key releases exactly that key's secret.
7062
+ *
7063
+ * Array elements are matched by a DECLARED id key (`secretArrayKeys`:
7064
+ * `{ headers: 'name' }`), never by index, so reordering a list keeps every
7065
+ * keychain ref (the same rule as `arrayItemFieldPath`). The concrete path of a
7066
+ * leaf names its element: `headers[X-Api].value`.
7067
+ *
7068
+ * Pure and browser-safe. Nothing here mutates: every transform returns a new value.
7069
+ */
7070
+ /** The array prefixes (declared form, e.g. `headers` or `a.headers`) of a path. */
7071
+ function parseSecretPath(path) {
7072
+ if (path.length === 0) throw new InvalidRecordError("an empty secret path");
7073
+ return path.split(".").map((raw) => {
7074
+ const each = raw.endsWith("[]");
7075
+ const map = raw.endsWith("{}");
7076
+ const key = each || map ? raw.slice(0, -2) : raw;
7077
+ if (key.length === 0) throw new InvalidRecordError(`secret path "${path}" has an empty segment`);
7078
+ return {
7079
+ key,
7080
+ each,
7081
+ map
7082
+ };
7083
+ });
7084
+ }
7085
+ /** The declared array prefixes of `path` that need an id key (`headers`, `a.rows`). */
7086
+ function secretArrayPrefixes(path) {
7087
+ const segments = parseSecretPath(path);
7088
+ const prefixes = [];
7089
+ const walked = [];
7090
+ for (const segment of segments) {
7091
+ walked.push(segment.key);
7092
+ if (segment.each) prefixes.push(walked.join("."));
7093
+ }
7094
+ return prefixes;
7095
+ }
7096
+ function isRecord$6(value) {
7097
+ return typeof value === "object" && value !== null && !Array.isArray(value);
7098
+ }
7099
+ function elementId(element, idKey, declared, prefix) {
7100
+ const id = isRecord$6(element) ? element[idKey] : void 0;
7101
+ 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`);
7102
+ return id;
7103
+ }
7104
+ /**
7105
+ * Visit every secret leaf PRESENT in `data` (an absent branch has nothing to
7106
+ * visit). `replace` returns the new leaf value, or {@link REMOVE_LEAF}; the
7107
+ * result is a new body, `data` is untouched.
7108
+ */
7109
+ var REMOVE_LEAF = Symbol("remove-leaf");
7110
+ function mapAt(node, segments, index, walkedKeys, concretePrefix, declared, arrayKeys, visit) {
7111
+ if (!isRecord$6(node)) return node;
7112
+ const segment = segments[index];
7113
+ if (segment === void 0) return node;
7114
+ if (!Object.prototype.hasOwnProperty.call(node, segment.key)) return node;
7115
+ const child = node[segment.key];
7116
+ const keys = [...walkedKeys, segment.key];
7117
+ const last = index === segments.length - 1;
7118
+ if (segment.each) {
7119
+ if (!Array.isArray(child)) return node;
7120
+ const prefix = keys.join(".");
7121
+ const idKey = arrayKeys[prefix];
7122
+ if (idKey === void 0) throw new InvalidRecordError(`"${declared}": no id key declared for the array "${prefix}"`);
7123
+ const mapped = child.map((element) => {
7124
+ const id = elementId(element, idKey, declared, prefix);
7125
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}[${encodeURIComponent(id)}]`;
7126
+ return last ? element : mapAt(element, segments, index + 1, keys, concrete, declared, arrayKeys, visit);
7127
+ });
7128
+ return {
7129
+ ...node,
7130
+ [segment.key]: mapped
7131
+ };
7132
+ }
7133
+ if (segment.map) {
7134
+ if (!isRecord$6(child)) return node;
7135
+ const kept = Object.entries(child).map(([mapKey, value]) => {
7136
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}{${encodeURIComponent(mapKey)}}`;
7137
+ if (!last) return [mapKey, mapAt(value, segments, index + 1, keys, concrete, declared, arrayKeys, visit)];
7138
+ return [mapKey, visit({
7139
+ declared,
7140
+ concrete,
7141
+ value
7142
+ })];
7143
+ }).filter(([, value]) => value !== REMOVE_LEAF);
7144
+ return {
7145
+ ...node,
7146
+ [segment.key]: Object.fromEntries(kept)
7147
+ };
7148
+ }
7149
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}`;
7150
+ if (last) {
7151
+ const replacement = visit({
7152
+ declared,
7153
+ concrete,
7154
+ value: child
7155
+ });
7156
+ if (replacement === REMOVE_LEAF) return Object.fromEntries(Object.entries(node).filter(([key]) => key !== segment.key));
7157
+ return {
7158
+ ...node,
7159
+ [segment.key]: replacement
7160
+ };
7161
+ }
7162
+ return {
7163
+ ...node,
7164
+ [segment.key]: mapAt(child, segments, index + 1, keys, concrete, declared, arrayKeys, visit)
7165
+ };
7166
+ }
7167
+ /** Replace/remove every present secret leaf; returns a NEW body. */
7168
+ function mapSecretLeaves(data, paths, arrayKeys, visit) {
7169
+ let current = data;
7170
+ for (const declared of paths) current = mapAt(current, parseSecretPath(declared), 0, [], "", declared, arrayKeys, visit);
7171
+ return current;
7172
+ }
7173
+ /** Every present secret leaf, read-only. */
7174
+ function collectSecretLeaves(data, paths, arrayKeys) {
7175
+ const found = [];
7176
+ mapSecretLeaves(data, paths, arrayKeys, (leaf) => {
7177
+ found.push(leaf);
7178
+ return leaf.value;
7179
+ });
7180
+ return found;
7181
+ }
7182
+ /**
7183
+ * The keychain collection name a kind's secrets live under. Prefixed so a
7184
+ * record's refs never collide with the refs a legacy collection of the same name
7185
+ * already holds during an adoption.
7186
+ */
7187
+ function recordSecretCollection(kind) {
7188
+ return `${RECORD_SECRET_COLLECTION_PREFIX}${kind}`;
7189
+ }
7190
+ /** The ONE ref a row's secret field may carry: the engine and the facade both build it here. */
7191
+ function recordSecretRef(owner, kind, rowId, concretePath) {
7192
+ return buildSecretRef({
7193
+ owner,
7194
+ scope: {
7195
+ kind: "row",
7196
+ collection: recordSecretCollection(kind),
7197
+ rowId
7198
+ },
7199
+ fieldPath: concretePath
7200
+ });
7201
+ }
7202
+ /**
7203
+ * A stored secret, as an admin read shows it: a VIEW naming the row's own
7204
+ * keychain ref (`set: true`), never the value and no longer the bare redaction
7205
+ * token. The form hands it to the secret field, which reveals the value by ref
7206
+ * through the audited `keychain-admin.reveal`; sent back untouched it keeps the
7207
+ * stored secret (the records door reads a view as KEEP).
7208
+ *
7209
+ * ONE implementation for the entries service and for every addon that serves
7210
+ * its own instances (`RecordIntegrationInstances`).
7211
+ */
7212
+ function isRecord$5(value) {
7213
+ return typeof value === "object" && value !== null && !Array.isArray(value);
7214
+ }
7215
+ function secretViewsOf(owner, kind, id, decl, data) {
7216
+ if (decl.secretPaths.length === 0) return data;
7217
+ const shown = mapSecretLeaves(data, decl.secretPaths, decl.secretArrayKeys, (leaf) => {
7218
+ if (leaf.value !== "__camstack_redacted__") return leaf.value;
7219
+ return {
7220
+ $secret: recordSecretRef(owner, kind, id, leaf.concrete),
7221
+ v: 1,
7222
+ set: true
7223
+ };
7224
+ });
7225
+ return isRecord$5(shown) ? shown : data;
7226
+ }
7227
+ /** The most instances one addon lists (an integrations page, not a table). */
7228
+ var INSTANCES_LIST_MAX = 1e3;
7229
+ /**
7230
+ * The ONE reader of an instance's switch (D996): an absent field means on, so a row written
7231
+ * before the field existed needs no migration. Every consumer of an instance body asks this.
7232
+ */
7233
+ function isInstanceEnabled(body) {
7234
+ return body.enabled !== false;
7235
+ }
7236
+ /** The body key of the switch; only {@link RecordIntegrationInstances.setInstanceEnabled} writes it. */
7237
+ var SWITCH_KEY = "enabled";
7238
+ /** The keys of the kind's secret fields that sit at the top level of the body. */
7239
+ function topLevelSecretKeys(paths) {
7240
+ return new Set(paths.filter((p) => !p.includes(".") && !p.includes("[") && !p.includes("{")));
7241
+ }
7242
+ /** The keys of the kind's top-level MAPS whose values are secrets (`applianceSecrets{}`). */
7243
+ function secretMapKeys(paths) {
7244
+ return new Set(paths.filter((p) => p.endsWith("{}") && !p.slice(0, -2).match(/[.[{]/)).map((p) => p.slice(0, -2)));
7245
+ }
7246
+ /**
7247
+ * A patch value for a map of secrets: an entry that is omitted, `''`, the redaction token or the
7248
+ * view the form was given KEEPS its stored secret (it is left out of the merge); `{ $secretClear }`
7249
+ * or `null` removes the entry; any other string replaces it. Null when nothing is left to merge.
7250
+ */
7251
+ function secretMapPatch(value) {
7252
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
7253
+ const out = {};
7254
+ for (const [key, entry] of Object.entries(value)) if (entry === null || isSecretClear(entry)) out[key] = null;
7255
+ else if (typeof entry === "string" && entry !== "" && entry !== "__camstack_redacted__" && !isSecretFieldView(entry)) out[key] = entry;
7256
+ return Object.keys(out).length > 0 ? out : null;
7257
+ }
7258
+ var RecordIntegrationInstances = class {
7259
+ records;
7260
+ kind;
7261
+ hooks;
7262
+ handle;
7263
+ secretKeys;
7264
+ secretMaps;
7265
+ nameField;
7266
+ switchListeners = /* @__PURE__ */ new Set();
7267
+ constructor(records, kind, hooks) {
7268
+ this.records = records;
7269
+ this.kind = kind;
7270
+ this.hooks = hooks;
7271
+ this.handle = records.kind(kind);
7272
+ this.secretKeys = topLevelSecretKeys(kind.declaration.secretPaths);
7273
+ this.secretMaps = secretMapKeys(kind.declaration.secretPaths);
7274
+ this.nameField = kind.declaration.entry?.nameField ?? "name";
7275
+ }
7276
+ /**
7277
+ * One instance read for the addon's own runtime; null when absent. When the keychain is
7278
+ * locked the row is served WITHOUT its secrets and says so (`secrets: 'unavailable'`), so the
7279
+ * caller can keep what it had instead of reconfiguring with an empty secret (D49).
7280
+ */
7281
+ async readResolved(id) {
7282
+ try {
7283
+ const record = await this.handle.getResolved(id);
7284
+ return record === null ? null : {
7285
+ id,
7286
+ body: record.data,
7287
+ enabled: isInstanceEnabled(record.data),
7288
+ secrets: "resolved"
7289
+ };
7290
+ } catch (err) {
7291
+ if (!(err instanceof RecordSecretUnavailableError)) throw err;
7292
+ const stored = await this.handle.get(id);
7293
+ if (stored === null) return null;
7294
+ return {
7295
+ id,
7296
+ body: Object.fromEntries(Object.entries(stored.data).filter(([key]) => !this.secretKeys.has(key))),
7297
+ enabled: isInstanceEnabled(stored.data),
7298
+ secrets: "unavailable"
7299
+ };
7300
+ }
7301
+ }
7302
+ /** The body of {@link readResolved} alone; a locked keychain yields the row without secrets. */
7303
+ async getResolved(id) {
7304
+ return (await this.readResolved(id))?.body ?? null;
7305
+ }
7306
+ /** Every instance, secrets resolved where the keychain allows; an absent one is skipped. */
7307
+ async listResolved() {
7308
+ const page = await this.handle.query({ limit: INSTANCES_LIST_MAX });
7309
+ const out = [];
7310
+ for (const record of page.records) {
7311
+ const read = await this.readResolved(record.id);
7312
+ if (read !== null) out.push(read);
7313
+ }
7314
+ return out;
7315
+ }
7316
+ viewOf(record) {
7317
+ const shown = secretViewsOf(this.records.owner, this.kind.name, record.id, this.kind.declaration, record.data);
7318
+ const rawName = record.data[this.nameField];
7319
+ const kind = this.hooks.kindOf?.(record.data);
7320
+ const health = this.hooks.health?.(record.data, record.id);
7321
+ return {
7322
+ id: record.id,
7323
+ name: typeof rawName === "string" ? rawName : record.id,
7324
+ configured: this.hooks.configured(record.data),
7325
+ enabled: isInstanceEnabled(record.data),
7326
+ formValues: shown,
7327
+ ...kind !== void 0 ? { kind } : {},
7328
+ ...health?.status !== void 0 ? { status: health.status } : {},
7329
+ ...health?.lastCheckedAt !== void 0 ? { lastCheckedAt: health.lastCheckedAt } : {}
7330
+ };
7331
+ }
7332
+ describe = async () => {
7333
+ const declared = linksOfKind(this.kind);
7334
+ const links = this.hooks.description.links !== void 0 || declared.length === 0 ? {} : { links: declared.map((link) => ({
7335
+ kind: this.kind.name,
7336
+ field: link.field,
7337
+ to: link.to
7338
+ })) };
7339
+ return {
7340
+ ...this.hooks.description,
7341
+ ...links,
7342
+ ...this.hooks.mintId === void 0 ? {} : { mintsId: true }
7343
+ };
7344
+ };
7345
+ instanceFormSchema = async ({ id }) => this.hooks.formSchema(id);
7346
+ listInstances = async () => {
7347
+ return (await this.handle.query({ limit: INSTANCES_LIST_MAX })).records.map((record) => this.viewOf(record));
7348
+ };
7349
+ getInstance = async ({ id }) => {
7350
+ const record = await this.handle.get(id);
7351
+ return record === null ? null : this.viewOf(record);
7352
+ };
7353
+ /** Insert ONE row (`ifRev: 0`: an existing id is refused, never overwritten). */
7354
+ createInstance = async ({ id, name, kind, values }) => {
7355
+ const minted = id ?? this.hooks.mintId?.({
7356
+ name,
7357
+ ...kind !== void 0 ? { kind } : {}
7358
+ });
7359
+ if (minted === void 0) throw new Error("createInstance needs an id: this provider does not mint one");
7360
+ await this.handle.put({
7361
+ id: minted,
7362
+ data: this.hooks.initialBody(name, kind)
7363
+ }, { ifRev: 0 });
7364
+ const patch = this.patchOf(values ?? {});
7365
+ if (Object.keys(patch).length > 0) await this.handle.patch(minted, patch);
7366
+ await this.hooks.onChanged?.(minted, "created");
7367
+ return { id: minted };
7368
+ };
7369
+ updateInstance = async ({ id, name, values }) => {
7370
+ const patch = this.patchOf(values);
7371
+ if (name !== void 0) patch[this.nameField] = name;
7372
+ await this.handle.patch(id, patch);
7373
+ await this.hooks.onChanged?.(id, "updated");
7374
+ return { ok: true };
7375
+ };
7376
+ /** The record patch a form `values` object means: secrets kept, cleared or replaced. */
7377
+ patchOf(values) {
7378
+ const patch = {};
7379
+ for (const [key, value] of Object.entries(values)) {
7380
+ if (value === void 0) continue;
7381
+ if (key === "enabled") continue;
7382
+ if (this.secretMaps.has(key)) {
7383
+ const entries = secretMapPatch(value);
7384
+ if (entries !== null) patch[key] = entries;
7385
+ } else if (!this.secretKeys.has(key)) patch[key] = value;
7386
+ else if (isSecretClear(value)) patch[key] = null;
7387
+ else if (typeof value === "string" && value !== "" && value !== "__camstack_redacted__" && !isSecretFieldView(value)) patch[key] = value;
7388
+ }
7389
+ return patch;
7390
+ }
7391
+ /**
7392
+ * Listen to the switch of ANY instance of this helper (in the process that serves it). The
7393
+ * durable replacement of the `integration.enabled` / `integration.disabled` events (D8): the
7394
+ * addon reconciles from the record, whichever way it flipped.
7395
+ */
7396
+ onSwitched(listener) {
7397
+ this.switchListeners.add(listener);
7398
+ }
7399
+ /**
7400
+ * The ONE writer of the switch (D996, D1014): the record body's `enabled`, for every role. A
7401
+ * configured thing is an instance, so an id with no record yet (a default integration that was
7402
+ * never configured) gets its record from `initialBody` before the switch is written.
7403
+ */
7404
+ setInstanceEnabled = async ({ id, enabled }) => {
7405
+ if (await this.handle.get(id) === null) await this.handle.put({
7406
+ id,
7407
+ data: this.hooks.initialBody(id)
7408
+ }, { ifRev: 0 });
7409
+ await this.handle.patch(id, { [SWITCH_KEY]: enabled });
7410
+ await this.hooks.onChanged?.(id, "enabled");
7411
+ for (const listener of this.switchListeners) await listener(id, enabled);
7412
+ return { ok: true };
7413
+ };
7414
+ /** The row and its keychain refs go together (the records door). */
7415
+ deleteInstance = async ({ id }) => {
7416
+ await this.handle.delete(id);
7417
+ await this.hooks.onChanged?.(id, "deleted");
7418
+ return { ok: true };
7419
+ };
7420
+ testInstance = async (input) => {
7421
+ if (this.hooks.test === void 0) return {
7422
+ success: false,
7423
+ status: "unsupported",
7424
+ error: "This integration declares no connection test"
7425
+ };
7426
+ return this.hooks.test(input);
7427
+ };
7428
+ /** The flat provider object to hand to `registerProvider`. */
7429
+ toProvider() {
7430
+ return {
7431
+ describe: this.describe,
7432
+ instanceFormSchema: this.instanceFormSchema,
7433
+ listInstances: this.listInstances,
7434
+ getInstance: this.getInstance,
7435
+ createInstance: this.createInstance,
7436
+ updateInstance: this.updateInstance,
7437
+ setInstanceEnabled: this.setInstanceEnabled,
7438
+ deleteInstance: this.deleteInstance,
7439
+ testInstance: this.testInstance
7440
+ };
7441
+ }
7442
+ };
7443
+ /**
7444
+ * The one-switch migration (epic #440, step 3). An integration's on/off state used to live in the
7445
+ * registry's `enabled` column for a device addon; it now lives only in the instance record's
7446
+ * body (`enabled`, D1007 superseded). This moves a registry `enabled = false` into the body, once.
7447
+ *
7448
+ * For every registry row of the addon that is OFF:
7449
+ * - no record under its id: the record is created from `initialBody(name)` with `enabled: false`
7450
+ * (a default integration that never had settings, Reolink's among them);
7451
+ * - a record whose body states no `enabled`: `enabled: false` is written into it;
7452
+ * - a record that already states `enabled` (either way) is the newer truth and is left alone.
7453
+ * A row that is ON writes nothing: an absent field reads as on. A rerun finds every off row with
7454
+ * a stated switch and does nothing, so nothing switched off comes back on and nothing switched on
7455
+ * goes off. The registry column itself is neither read afterwards nor written; its drop is step 5.
7456
+ *
7457
+ * It runs in the addon process, BEFORE the addon registers its `integration-instances` provider,
7458
+ * which is also why `integrations.list` still answers the stored column at that point.
7459
+ */
7460
+ function registrySwitchToBodyId(addonId, date) {
7461
+ return `${addonId}/${date}-registry-switch-to-body`;
7462
+ }
7463
+ async function moveRegistrySwitchToBody(ports, spec) {
7464
+ const rows = await ports.listIntegrations(spec.addonId);
7465
+ let created = 0;
7466
+ let switched = 0;
7467
+ let kept = 0;
7468
+ for (const row of rows) {
7469
+ if (row.enabled) continue;
7470
+ const body = await ports.readBody(row.id);
7471
+ if (body === null) {
7472
+ if (await ports.createRecord(row.id, {
7473
+ ...spec.initialBody(row.name),
7474
+ ["enabled"]: false
7475
+ }) === "created") created += 1;
7476
+ else kept += 1;
7477
+ continue;
7478
+ }
7479
+ if ("enabled" in body) {
7480
+ kept += 1;
7481
+ continue;
7482
+ }
7483
+ await ports.switchOff(row.id);
7484
+ switched += 1;
7485
+ }
7486
+ const summary = {
7487
+ integrations: rows.length,
7488
+ off: rows.filter((r) => !r.enabled).length,
7489
+ created,
7490
+ switched,
7491
+ kept
7492
+ };
7493
+ return created === 0 && switched === 0 ? {
7494
+ outcome: "already-done",
7495
+ summary
7496
+ } : {
7497
+ outcome: "done",
7498
+ summary
7499
+ };
7500
+ }
7501
+ /** A migration entry: an addon states its kind and how a new body starts, nothing else. */
7502
+ function registrySwitchToBodyMigration(spec) {
7503
+ return {
7504
+ meta: {
7505
+ id: registrySwitchToBodyId(spec.addonId, spec.date),
7506
+ owner: spec.addonId,
7507
+ level: "addon-state",
7508
+ seq: spec.seq,
7509
+ dependsOn: [],
7510
+ store: "settings",
7511
+ scope: "cluster",
7512
+ onFailure: "block-owner",
7513
+ bodyKind: "procedure",
7514
+ description: "Move the registry enabled flag of every switched-off integration into its instance record body, creating the record when there is none",
7515
+ fixtureMark: "enabled"
7516
+ },
7517
+ procedure: (ports) => moveRegistrySwitchToBody(ports, {
7518
+ addonId: spec.addonId,
7519
+ initialBody: spec.initialBody
7520
+ })
7521
+ };
7522
+ }
7523
+ /** The hub and records sides of {@link registrySwitchToBodyMigration}. */
7524
+ function registrySwitchPortsOver(deps) {
7525
+ const handle = deps.records.kind({
7526
+ name: deps.kind.name,
7527
+ declaration: deps.kind.declaration,
7528
+ schema: record(string(), unknown())
7529
+ });
7530
+ return {
7531
+ listIntegrations: async (addonId) => (await deps.api.list()).filter((i) => i.addonId === addonId).map((i) => ({
7532
+ id: i.id,
7533
+ name: i.name,
7534
+ enabled: i.enabled !== false
7535
+ })),
7536
+ readBody: async (id) => (await handle.get(id))?.data ?? null,
7537
+ createRecord: async (id, body) => {
7538
+ if (await handle.get(id) !== null) return "exists";
7539
+ await handle.put({
7540
+ id,
7541
+ data: body
7542
+ }, { ifRev: 0 });
7543
+ return "created";
7544
+ },
7545
+ switchOff: async (id) => {
7546
+ await handle.patch(id, { [SWITCH_KEY]: false });
7547
+ }
7548
+ };
7549
+ }
7550
+ /**
7551
+ * Build a {@link DurableState} over a single store key. Transport-agnostic:
7552
+ * `read`/`write` are the addon-store or device-store accessors. The whole
7553
+ * validated value round-trips on every read/write — the schema is the
7554
+ * single source of truth for what is persisted, so no hand-listed field
7555
+ * set can drop a key on save.
7556
+ */
7557
+ function createDurableState(deps) {
7558
+ const get = async () => {
7559
+ const raw = (await deps.read())[deps.key];
7560
+ if (raw === void 0) return deps.fallback;
7561
+ const parsed = deps.schema.safeParse(raw);
7562
+ if (!parsed.success) {
7563
+ deps.onParseError?.(deps.key, parsed.error);
7564
+ return deps.fallback;
7565
+ }
7566
+ return parsed.data;
7567
+ };
7568
+ const set = async (next) => {
7569
+ const validated = deps.schema.parse(next);
7570
+ await deps.write({ [deps.key]: validated });
7571
+ };
7572
+ const update = async (fn) => {
7573
+ await set(fn(await get()));
7574
+ };
7575
+ return {
7576
+ get,
7577
+ set,
7578
+ update
7579
+ };
7580
+ }
7581
+ /**
7582
+ * Per-node scoping for the shared addon-settings blob.
7583
+ *
7584
+ * An addon's settings store is hub-central (the `addon-settings` cap is
7585
+ * hub-routed — the hub instance answers for every node), so fields whose
7586
+ * value is a NODE fact (decoder backend, engine pick, probed hardware
7587
+ * capabilities) persist under the node-scoped key `<key>@<nodeId>` inside
7588
+ * the single shared blob. The SCHEMA field key stays bare: the write path
7589
+ * ({@link scopePatch}) maps the bare field onto the target node's scoped
7590
+ * key; the read/hydrate path ({@link projectStore}) maps THIS node's value
7591
+ * back, so UI forms and `resolveConfig` only ever see the bare key.
7592
+ *
7593
+ * Fields opt in via the `perNode: true` schema marker on `ConfigFieldBase`
7594
+ * (`interfaces/config-ui.ts`); `BaseAddon` derives the key set from the
7595
+ * schema and routes reads/writes through these helpers.
7596
+ *
7597
+ * ## No bare-key fallback — deliberate
7598
+ *
7599
+ * {@link readNodeValue} reads the node-scoped key ONLY. A node with no
7600
+ * scoped key resolves to `undefined` so the field's schema `default` wins —
7601
+ * NEVER `store[base]` and never another node's value. A bare legacy key in
7602
+ * the store is invisible to every node, hub included, so one node's
7603
+ * selection can never leak onto another. (This generalizes the
7604
+ * `decoder-backend-keys.ts` semantics — the no-fallback variant — over an
7605
+ * arbitrary set of per-node field keys.)
7606
+ *
7607
+ * Pure functions only — no I/O, no imports beyond the language. This is a
7608
+ * LEAF module: import it via its deep path, never from the root barrel.
7609
+ */
7610
+ /**
7611
+ * Normalize a raw kernel node id to the bare node id used for scoping.
7612
+ * `localNodeId` can carry a `<node>/<addon>` suffix on forked child
7613
+ * processes; per-node settings are per-NODE, so strip the addon segment.
7614
+ * `undefined` / `null` / empty falls back to `'hub'`.
7615
+ */
7616
+ function normalizeNodeId(raw) {
7617
+ if (raw === void 0 || raw === null || raw === "") return "hub";
7618
+ const slashIdx = raw.indexOf("/");
7619
+ if (slashIdx < 0) return raw;
7620
+ const bare = raw.slice(0, slashIdx);
7621
+ return bare === "" ? "hub" : bare;
7622
+ }
7623
+ /** The node-scoped store key for a per-node field: `<base>@<nodeId>`. */
7624
+ function nodeScopedKey(base, nodeId) {
7625
+ return `${base}@${normalizeNodeId(nodeId)}`;
7626
+ }
7627
+ /**
7628
+ * Read a node's value for a per-node field from the raw shared store:
7629
+ * the node-scoped key when present, otherwise `undefined`.
7630
+ * Deliberately NO bare-key fallback (see module doc) — the caller lets the
7631
+ * schema `default` win on `undefined`.
7632
+ */
7633
+ function readNodeValue(store, base, nodeId) {
7634
+ return store[nodeScopedKey(base, nodeId)];
7635
+ }
7636
+ /**
7637
+ * Re-map a UI/settings patch so every bare perNode field persists under the
7638
+ * TARGET node's scoped key; all other keys pass through unchanged. Used on
7639
+ * the write path so a save for one node never clobbers another node's value
7640
+ * (and the bare key is never written). Returns a new object — the input
7641
+ * patch is not mutated.
7642
+ */
7643
+ function scopePatch(patch, perNodeKeys, nodeId) {
7644
+ const out = {};
7645
+ for (const [key, value] of Object.entries(patch)) out[perNodeKeys.has(key) ? nodeScopedKey(key, nodeId) : key] = value;
7646
+ return out;
7647
+ }
7648
+ /**
7649
+ * Project the raw shared store onto the bare schema keys for ONE node so a
7650
+ * UI schema (whose field keys are bare) hydrates from that node's own
7651
+ * values:
7652
+ *
7653
+ * - EVERY `@`-scoped key (any node's) is dropped from the pass-through.
7654
+ * - Every bare perNode key is dropped from the pass-through (a stray bare
7655
+ * legacy key must never hydrate any node — no bare fallback).
7656
+ * - THIS node's effective value ({@link readNodeValue}) is then laid onto
7657
+ * each bare perNode key; when the node has no scoped key the bare key is
7658
+ * left ABSENT so the field's schema `default` wins.
7659
+ *
7660
+ * Returns a new object — the input store is not mutated.
7661
+ */
7662
+ function projectStore(store, perNodeKeys, nodeId) {
7663
+ const out = {};
7664
+ for (const [key, value] of Object.entries(store)) {
7665
+ if (key.includes("@")) continue;
7666
+ if (perNodeKeys.has(key)) continue;
7667
+ out[key] = value;
7668
+ }
7669
+ for (const base of perNodeKeys) {
7670
+ const value = readNodeValue(store, base, nodeId);
7671
+ if (value !== void 0) out[base] = value;
7672
+ }
7673
+ return out;
7674
+ }
7675
+ /** Every scope, in the order the guard and the docs list them. */
7676
+ var SCOPED_SETTINGS_SCOPES = [
7677
+ "cluster",
7678
+ "device-defaults",
7679
+ "node"
7680
+ ];
6966
7681
  /** A write to a secret path could not be stored in the keychain, so it was refused. */
6967
7682
  var KeychainWriteRefusedError = class extends Error {
6968
7683
  fieldPath;
@@ -6973,7 +7688,7 @@ var KeychainWriteRefusedError = class extends Error {
6973
7688
  }
6974
7689
  };
6975
7690
  var KEEP = { kind: "keep" };
6976
- function isRecord$6(value) {
7691
+ function isRecord$4(value) {
6977
7692
  return typeof value === "object" && value !== null && !Array.isArray(value);
6978
7693
  }
6979
7694
  function defaultMintId() {
@@ -6986,7 +7701,7 @@ function collectSecretMarkerRefs(value, out = []) {
6986
7701
  return out;
6987
7702
  }
6988
7703
  if (Array.isArray(value)) for (const item of value) collectSecretMarkerRefs(item, out);
6989
- else if (isRecord$6(value)) for (const child of Object.values(value)) collectSecretMarkerRefs(child, out);
7704
+ else if (isRecord$4(value)) for (const child of Object.values(value)) collectSecretMarkerRefs(child, out);
6990
7705
  return out;
6991
7706
  }
6992
7707
  async function storedValueEquals(secrets, marker, candidate) {
@@ -7041,7 +7756,7 @@ function rowId(row, idKey) {
7041
7756
  return null;
7042
7757
  }
7043
7758
  async function writeArray(ctx, node, incoming, stored, fieldPath) {
7044
- const storedRows = Array.isArray(stored) ? stored.filter(isRecord$6) : [];
7759
+ const storedRows = Array.isArray(stored) ? stored.filter(isRecord$4) : [];
7045
7760
  if (!Array.isArray(incoming)) {
7046
7761
  ctx.deletes.push(...collectSecretMarkerRefs(storedRows));
7047
7762
  return {
@@ -7057,7 +7772,7 @@ async function writeArray(ctx, node, incoming, stored, fieldPath) {
7057
7772
  const kept = /* @__PURE__ */ new Set();
7058
7773
  const rows = [];
7059
7774
  for (const row of incoming) {
7060
- if (!isRecord$6(row)) {
7775
+ if (!isRecord$4(row)) {
7061
7776
  rows.push(row);
7062
7777
  continue;
7063
7778
  }
@@ -7082,7 +7797,7 @@ async function writeNode(ctx, node, incoming, stored, fieldPath) {
7082
7797
  case "leaf": return writeLeaf(ctx, incoming, stored, fieldPath);
7083
7798
  case "array": return writeArray(ctx, node, incoming, stored, fieldPath);
7084
7799
  case "object": {
7085
- if (!isRecord$6(incoming)) {
7800
+ if (!isRecord$4(incoming)) {
7086
7801
  if (incoming === void 0) return KEEP;
7087
7802
  ctx.deletes.push(...collectSecretMarkerRefs(stored));
7088
7803
  return {
@@ -7090,7 +7805,7 @@ async function writeNode(ctx, node, incoming, stored, fieldPath) {
7090
7805
  value: incoming
7091
7806
  };
7092
7807
  }
7093
- const storedObj = isRecord$6(stored) ? stored : {};
7808
+ const storedObj = isRecord$4(stored) ? stored : {};
7094
7809
  return {
7095
7810
  kind: "value",
7096
7811
  value: await writeMembers(ctx, node.children, incoming, storedObj, (m) => `${fieldPath}.${m}`)
@@ -7213,7 +7928,7 @@ async function resolveSecretMarkers(value, secrets, options = {}) {
7213
7928
  value: items
7214
7929
  };
7215
7930
  }
7216
- if (isRecord$6(v)) {
7931
+ if (isRecord$4(v)) {
7217
7932
  const out = {};
7218
7933
  for (const [k, child] of Object.entries(v)) {
7219
7934
  const s = substitute(child);
@@ -7245,7 +7960,7 @@ var SecretOverwriteRefusedError = class extends Error {
7245
7960
  this.name = "SecretOverwriteRefusedError";
7246
7961
  }
7247
7962
  };
7248
- function isRecord$5(value) {
7963
+ function isRecord$3(value) {
7249
7964
  return typeof value === "object" && value !== null && !Array.isArray(value);
7250
7965
  }
7251
7966
  function resolvedValue(pass, marker) {
@@ -7274,7 +7989,7 @@ function inArray(pass, incoming, stored) {
7274
7989
  return incoming.map((item, index) => {
7275
7990
  const twin = stored[index];
7276
7991
  if (isSecretMarker(twin)) return typeof item === "string" && item === resolvedValue(pass, twin) ? twin : item;
7277
- if (isRecord$5(item) && isRecord$5(twin)) return inArrayRow(pass, item, twin);
7992
+ if (isRecord$3(item) && isRecord$3(twin)) return inArrayRow(pass, item, twin);
7278
7993
  if (Array.isArray(item) && Array.isArray(twin)) return inArray(pass, item, twin);
7279
7994
  return item;
7280
7995
  });
@@ -7285,7 +8000,7 @@ function inArrayRow(pass, incoming, stored) {
7285
8000
  const twin = stored[key];
7286
8001
  if (isSecretMarker(twin)) {
7287
8002
  if (typeof value === "string" && value === resolvedValue(pass, twin)) out[key] = twin;
7288
- } else if (isRecord$5(value) && isRecord$5(twin)) out[key] = inArrayRow(pass, value, twin);
8003
+ } else if (isRecord$3(value) && isRecord$3(twin)) out[key] = inArrayRow(pass, value, twin);
7289
8004
  else if (Array.isArray(value) && Array.isArray(twin)) out[key] = inArray(pass, value, twin);
7290
8005
  }
7291
8006
  return out;
@@ -7293,7 +8008,7 @@ function inArrayRow(pass, incoming, stored) {
7293
8008
  async function walk(pass, incoming, stored) {
7294
8009
  if (isSecretMarker(stored)) return atMarker(pass, incoming, stored);
7295
8010
  if (Array.isArray(incoming) && Array.isArray(stored)) return inArray(pass, incoming, stored);
7296
- if (!isRecord$5(incoming) || !isRecord$5(stored)) return incoming;
8011
+ if (!isRecord$3(incoming) || !isRecord$3(stored)) return incoming;
7297
8012
  const out = { ...incoming };
7298
8013
  for (const [key, value] of Object.entries(incoming)) out[key] = await walk(pass, value, stored[key]);
7299
8014
  return out;
@@ -7324,7 +8039,7 @@ async function restoreUnchangedSecrets(input) {
7324
8039
  function isJsonEqual(a, b) {
7325
8040
  if (Object.is(a, b)) return true;
7326
8041
  if (Array.isArray(a)) return Array.isArray(b) && a.length === b.length && a.every((v, i) => isJsonEqual(v, b[i]));
7327
- if (isRecord$5(a) && isRecord$5(b)) {
8042
+ if (isRecord$3(a) && isRecord$3(b)) {
7328
8043
  const keys = Object.keys(a);
7329
8044
  if (keys.length !== Object.keys(b).length) return false;
7330
8045
  return keys.every((k) => Object.prototype.hasOwnProperty.call(b, k) && isJsonEqual(a[k], b[k]));
@@ -7348,7 +8063,7 @@ function markerKeysOf(blob, owner) {
7348
8063
  }
7349
8064
  function nodeFromStored(value, owner) {
7350
8065
  if (isSecretMarker(value)) return isSecretRefOwnedBy(value.$secret, owner) ? { kind: "leaf" } : null;
7351
- if (!isRecord$5(value)) return null;
8066
+ if (!isRecord$3(value)) return null;
7352
8067
  const children = /* @__PURE__ */ new Map();
7353
8068
  for (const [key, child] of Object.entries(value)) {
7354
8069
  const node = nodeFromStored(child, owner);
@@ -7845,13 +8560,48 @@ var BaseAddon = class {
7845
8560
  if (api === void 0) throw new Error(`${this.ctx.id}: the migration API is not available on this context`);
7846
8561
  return this.runBound(sets.flatMap((set) => set.bind(api)), options);
7847
8562
  }
7848
- async runBound(migrations, options) {
8563
+ /**
8564
+ * A device addon states its instance kind once, before its migrations run, and the one-switch
8565
+ * migration (registry `enabled` to the instance body, epic #440 step 3) joins whatever
8566
+ * catalogue the addon runs, in the SAME declaration (the engine replaces an owner's catalogue
8567
+ * on every declare).
8568
+ */
8569
+ declareRegistrySwitch(spec) {
8570
+ this.registrySwitchSpec = spec;
8571
+ }
8572
+ registrySwitchSpec = null;
8573
+ registrySwitchBound() {
8574
+ const spec = this.registrySwitchSpec;
8575
+ if (spec === null) return [];
8576
+ const api = this.ctx.migrationApi;
8577
+ if (api === void 0) {
8578
+ this.ctx.logger.warn("the registry switch migration is skipped: the migration API is not available on this context");
8579
+ return [];
8580
+ }
8581
+ return migrationSet([registrySwitchToBodyMigration({
8582
+ addonId: this.ctx.id,
8583
+ date: "2026-11-06",
8584
+ seq: 1e3,
8585
+ initialBody: spec.initialBody
8586
+ })], (a) => registrySwitchPortsOver({
8587
+ api: integrationRowsApiOver(a),
8588
+ records: switchRecordsOverMigrationApi(a),
8589
+ kind: spec.kind
8590
+ })).bind(api);
8591
+ }
8592
+ async runBound(declared, options) {
8593
+ const added = this.registrySwitchBound();
8594
+ const migrations = [...declared, ...added];
8595
+ const phased = options?.only === void 0 || added.length === 0 ? options : {
8596
+ ...options,
8597
+ only: [...options.only, ...added.map((m) => m.meta.id)]
8598
+ };
7849
8599
  const api = this.ctx.api.migrations;
7850
8600
  const report = await runAddonMigrations({
7851
8601
  declareOwner: (input) => api.declareOwner.mutate(input),
7852
8602
  startMigration: (input) => api.startMigration.mutate(input),
7853
8603
  finishMigration: (input) => api.finishMigration.mutate(input)
7854
- }, migrations, this.ctx.logger, options);
8604
+ }, migrations, this.ctx.logger, phased);
7855
8605
  if (report.blockOwner.length > 0) throw new AddonMigrationsBlockedError(report.blockOwner);
7856
8606
  return report;
7857
8607
  }
@@ -8924,261 +9674,98 @@ function normalizeAddonInitResult(result) {
8924
9674
  if (Array.isArray(result)) return { providers: result };
8925
9675
  return result;
8926
9676
  }
8927
- var PREFIX = "records/";
8928
- /** The base of every records failure. `detail` is the human part of the message. */
8929
- var RecordsError = class extends Error {
8930
- code;
8931
- detail;
8932
- constructor(code, detail) {
8933
- super(`${PREFIX}${code}: ${detail}`);
8934
- this.name = "RecordsError";
8935
- this.code = code;
8936
- this.detail = detail;
8937
- }
8938
- };
8939
- /** A write guarded by `ifRev` found another revision (or an existing row for `ifRev: 0`). */
8940
- var RevConflictError = class extends RecordsError {
8941
- constructor(detail) {
8942
- super("rev-conflict", detail);
8943
- this.name = "RevConflictError";
8944
- }
8945
- };
8946
- /** The keychain could not store or serve a value: explicit, never an empty string. */
8947
- var RecordSecretUnavailableError = class extends RecordsError {
8948
- constructor(detail) {
8949
- super("secret-unavailable", detail);
8950
- this.name = "RecordSecretUnavailableError";
8951
- }
8952
- };
8953
- var InvalidRecordError = class extends RecordsError {
8954
- constructor(detail) {
8955
- super("invalid-record", detail);
8956
- this.name = "InvalidRecordError";
8957
- }
8958
- };
8959
- /** A kind declaration the engine refuses (non-additive change, bad shape, wrong file). */
8960
- var DeclarationRefusedError = class extends RecordsError {
8961
- constructor(detail) {
8962
- super("declaration-refused", detail);
8963
- this.name = "DeclarationRefusedError";
8964
- }
8965
- };
8966
- /** Limits and names of `ctx.records` (D881). One authority; the engine and the facade read it. */
8967
- /** The files a kind may live in. `history` is device-history's (D850), never records. */
8968
- var RECORD_DATABASES = ["settings", "events"];
8969
- /** The classes of a kind: the `@durable` vocabulary, one authority (replaces the annotation). */
8970
- var RECORD_CLASSES = [
8971
- "config",
8972
- "ledger",
8973
- "audit",
8974
- "mirror",
8975
- "ephemeral"
8976
- ];
8977
- var RECORD_DEFAULT_MAX_DATA_BYTES = 64 * 1024;
8978
- var RECORD_MAX_DATA_BYTES = 1024 * 1024;
8979
- var RECORD_BATCH_MAX = 1e3;
8980
- var RECORD_QUERY_MAX = 1e3;
8981
- /** A kind in the `settings` file may not bound itself above this (D447: high volume is `events`). */
8982
- var RECORD_SETTINGS_MAX_ROWS = 5e4;
8983
- /** The `Column`-free proof prefix: a ref collection for a kind's secret fields. */
8984
- var RECORD_SECRET_COLLECTION_PREFIX = "records:";
9677
+ object({
9678
+ field: string().min(1),
9679
+ on: literal("advance")
9680
+ });
8985
9681
  /**
8986
- * Secret fields of a record, addressed the way a Zod schema declares them
8987
- * (`collectZodSecretPaths`): dotted keys, `[]` for "each element of this array"
8988
- * (`auth.accessToken`, `headers[].value`).
8989
- *
8990
- * `{}` after a key means "each value of this map" (`applianceSecrets{}`): the map's own key
8991
- * names the value (`applianceSecrets{fridge}`), so no id key is declared and a body that drops a
8992
- * key releases exactly that key's secret.
9682
+ * Output schema shared by the contribution + live methods.
8993
9683
  *
8994
- * Array elements are matched by a DECLARED id key (`secretArrayKeys`:
8995
- * `{ headers: 'name' }`), never by index, so reordering a list keeps every
8996
- * keychain ref (the same rule as `arrayItemFieldPath`). The concrete path of a
8997
- * leaf names its element: `headers[X-Api].value`.
9684
+ * Mirrors the `ConfigUISchemaWithValues` shape (sections[] + optional
9685
+ * tabs[]) without importing from `../interfaces/config-ui.js` — a
9686
+ * concrete-but-lenient Zod object keeps tRPC output inference happy
9687
+ * (using `z.unknown()` here collapses unrelated router branches to
9688
+ * `unknown` when the generator re-inlines the huge AppRouter type).
8998
9689
  *
8999
- * Pure and browser-safe. Nothing here mutates: every transform returns a new value.
9000
- */
9001
- /** The array prefixes (declared form, e.g. `headers` or `a.headers`) of a path. */
9002
- function parseSecretPath(path) {
9003
- if (path.length === 0) throw new InvalidRecordError("an empty secret path");
9004
- return path.split(".").map((raw) => {
9005
- const each = raw.endsWith("[]");
9006
- const map = raw.endsWith("{}");
9007
- const key = each || map ? raw.slice(0, -2) : raw;
9008
- if (key.length === 0) throw new InvalidRecordError(`secret path "${path}" has an empty segment`);
9009
- return {
9010
- key,
9011
- each,
9012
- map
9013
- };
9014
- });
9015
- }
9016
- /** The declared array prefixes of `path` that need an id key (`headers`, `a.rows`). */
9017
- function secretArrayPrefixes(path) {
9018
- const segments = parseSecretPath(path);
9019
- const prefixes = [];
9020
- const walked = [];
9021
- for (const segment of segments) {
9022
- walked.push(segment.key);
9023
- if (segment.each) prefixes.push(walked.join("."));
9024
- }
9025
- return prefixes;
9026
- }
9027
- function isRecord$4(value) {
9028
- return typeof value === "object" && value !== null && !Array.isArray(value);
9029
- }
9030
- function elementId(element, idKey, declared, prefix) {
9031
- const id = isRecord$4(element) ? element[idKey] : void 0;
9032
- 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`);
9033
- return id;
9034
- }
9035
- /**
9036
- * Visit every secret leaf PRESENT in `data` (an absent branch has nothing to
9037
- * visit). `replace` returns the new leaf value, or {@link REMOVE_LEAF}; the
9038
- * result is a new body, `data` is untouched.
9690
+ * `.passthrough()` on sections/fields accepts whatever FormBuilder
9691
+ * extensions the caller adds (showWhen, displayScale, …) without
9692
+ * rebuilding every time a new field kind is introduced.
9039
9693
  */
9040
- var REMOVE_LEAF = Symbol("remove-leaf");
9041
- function mapAt(node, segments, index, walkedKeys, concretePrefix, declared, arrayKeys, visit) {
9042
- if (!isRecord$4(node)) return node;
9043
- const segment = segments[index];
9044
- if (segment === void 0) return node;
9045
- if (!Object.prototype.hasOwnProperty.call(node, segment.key)) return node;
9046
- const child = node[segment.key];
9047
- const keys = [...walkedKeys, segment.key];
9048
- const last = index === segments.length - 1;
9049
- if (segment.each) {
9050
- if (!Array.isArray(child)) return node;
9051
- const prefix = keys.join(".");
9052
- const idKey = arrayKeys[prefix];
9053
- if (idKey === void 0) throw new InvalidRecordError(`"${declared}": no id key declared for the array "${prefix}"`);
9054
- const mapped = child.map((element) => {
9055
- const id = elementId(element, idKey, declared, prefix);
9056
- const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}[${encodeURIComponent(id)}]`;
9057
- return last ? element : mapAt(element, segments, index + 1, keys, concrete, declared, arrayKeys, visit);
9058
- });
9059
- return {
9060
- ...node,
9061
- [segment.key]: mapped
9062
- };
9063
- }
9064
- if (segment.map) {
9065
- if (!isRecord$4(child)) return node;
9066
- const kept = Object.entries(child).map(([mapKey, value]) => {
9067
- const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}{${encodeURIComponent(mapKey)}}`;
9068
- if (!last) return [mapKey, mapAt(value, segments, index + 1, keys, concrete, declared, arrayKeys, visit)];
9069
- return [mapKey, visit({
9070
- declared,
9071
- concrete,
9072
- value
9073
- })];
9074
- }).filter(([, value]) => value !== REMOVE_LEAF);
9075
- return {
9076
- ...node,
9077
- [segment.key]: Object.fromEntries(kept)
9078
- };
9079
- }
9080
- const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}`;
9081
- if (last) {
9082
- const replacement = visit({
9083
- declared,
9084
- concrete,
9085
- value: child
9086
- });
9087
- if (replacement === REMOVE_LEAF) return Object.fromEntries(Object.entries(node).filter(([key]) => key !== segment.key));
9088
- return {
9089
- ...node,
9090
- [segment.key]: replacement
9091
- };
9092
- }
9694
+ var ContributionSectionSchema = object({
9695
+ id: string(),
9696
+ title: string(),
9697
+ description: string().optional(),
9698
+ style: _enum(["card", "accordion"]).optional(),
9699
+ defaultCollapsed: boolean().optional(),
9700
+ columns: union([
9701
+ literal(1),
9702
+ literal(2),
9703
+ literal(3),
9704
+ literal(4)
9705
+ ]).optional(),
9706
+ tab: string().optional(),
9707
+ location: _enum([
9708
+ "settings",
9709
+ "top-tab",
9710
+ "hero"
9711
+ ]).optional(),
9712
+ order: number().optional(),
9713
+ fields: array(any())
9714
+ });
9715
+ object({
9716
+ tabs: array(object({
9717
+ id: string(),
9718
+ label: string(),
9719
+ icon: string(),
9720
+ order: number().optional()
9721
+ })).optional(),
9722
+ sections: array(ContributionSectionSchema)
9723
+ }).nullable();
9724
+ object({ deviceId: number() }), object({ deviceId: number() }), object({
9725
+ deviceId: number(),
9726
+ patch: record(string(), unknown())
9727
+ }), object({ success: literal(true) });
9728
+ object({ deviceId: number() }), unknown().nullable();
9729
+ function method(input, output, options) {
9093
9730
  return {
9094
- ...node,
9095
- [segment.key]: mapAt(child, segments, index + 1, keys, concrete, declared, arrayKeys, visit)
9731
+ input,
9732
+ output,
9733
+ kind: options?.kind ?? "query",
9734
+ ...options?.auth !== void 0 ? { auth: options.auth } : {},
9735
+ ...options?.access !== void 0 ? { access: options.access } : {},
9736
+ ...options?.role !== void 0 ? { role: options.role } : {},
9737
+ ...options?.caller !== void 0 ? { caller: options.caller } : {},
9738
+ timeoutMs: options?.timeoutMs
9096
9739
  };
9097
9740
  }
9098
- /** Replace/remove every present secret leaf; returns a NEW body. */
9099
- function mapSecretLeaves(data, paths, arrayKeys, visit) {
9100
- let current = data;
9101
- for (const declared of paths) current = mapAt(current, parseSecretPath(declared), 0, [], "", declared, arrayKeys, visit);
9102
- return current;
9103
- }
9104
- /** Every present secret leaf, read-only. */
9105
- function collectSecretLeaves(data, paths, arrayKeys) {
9106
- const found = [];
9107
- mapSecretLeaves(data, paths, arrayKeys, (leaf) => {
9108
- found.push(leaf);
9109
- return leaf.value;
9110
- });
9111
- return found;
9112
- }
9113
9741
  /**
9114
- * The keychain collection name a kind's secrets live under. Prefixed so a
9115
- * record's refs never collide with the refs a legacy collection of the same name
9116
- * already holds during an adoption.
9742
+ * A wrapper/system-only method: served exclusively by the cap's system-level
9743
+ * provider (`InferProvider`), and OPTIONAL on `InferNativeProvider` so per-device
9744
+ * driver natives don't stub out a wrapper concern (e.g. a cross-device cache
9745
+ * overview). The `systemOnly: true` literal is what `InferNativeProvider` keys on.
9117
9746
  */
9118
- function recordSecretCollection(kind) {
9119
- return `${RECORD_SECRET_COLLECTION_PREFIX}${kind}`;
9120
- }
9121
- /** The ONE ref a row's secret field may carry: the engine and the facade both build it here. */
9122
- function recordSecretRef(owner, kind, rowId, concretePath) {
9123
- return buildSecretRef({
9124
- owner,
9125
- scope: {
9126
- kind: "row",
9127
- collection: recordSecretCollection(kind),
9128
- rowId
9129
- },
9130
- fieldPath: concretePath
9131
- });
9747
+ function systemMethod(input, output, options) {
9748
+ return {
9749
+ ...method(input, output, options),
9750
+ systemOnly: true
9751
+ };
9132
9752
  }
9133
9753
  /**
9134
- * A stored secret, as an admin read shows it: a VIEW naming the row's own
9135
- * keychain ref (`set: true`), never the value and no longer the bare redaction
9136
- * token. The form hands it to the secret field, which reveals the value by ref
9137
- * through the audited `keychain-admin.reveal`; sent back untouched it keeps the
9138
- * stored secret (the records door reads a view as KEEP).
9139
- *
9140
- * ONE implementation for the entries service and for every addon that serves
9141
- * its own instances (`RecordIntegrationInstances`).
9754
+ * A method a SOURCE of a collection cap may legitimately not serve — OPTIONAL
9755
+ * on `InferProvider`. The `providerOptional: true` literal is what
9756
+ * `InferProvider` keys on; see {@link CapabilityMethodSchema.providerOptional}
9757
+ * for when this is the honest answer and when it is a soft stub.
9142
9758
  */
9143
- function isRecord$3(value) {
9144
- return typeof value === "object" && value !== null && !Array.isArray(value);
9759
+ function optionalMethod(input, output, options) {
9760
+ return {
9761
+ ...method(input, output, options),
9762
+ providerOptional: true
9763
+ };
9145
9764
  }
9146
- function secretViewsOf(owner, kind, id, decl, data) {
9147
- if (decl.secretPaths.length === 0) return data;
9148
- const shown = mapSecretLeaves(data, decl.secretPaths, decl.secretArrayKeys, (leaf) => {
9149
- if (leaf.value !== "__camstack_redacted__") return leaf.value;
9150
- return {
9151
- $secret: recordSecretRef(owner, kind, id, leaf.concrete),
9152
- v: 1,
9153
- set: true
9154
- };
9155
- });
9156
- return isRecord$3(shown) ? shown : data;
9765
+ /** Shorthand to define an event schema */
9766
+ function event(data) {
9767
+ return { data };
9157
9768
  }
9158
- /**
9159
- * The share-view scope kinds a share-link token can carry. The hub mints
9160
- * and validates them (`ShareViewGrantSchema` builds its
9161
- * enum from this list); a data plane names the kinds it ACCEPTS in `share`.
9162
- */
9163
- var SHARE_VIEW_KINDS = ["grid-view", "events-view"];
9164
- /** The wire shape of {@link PeerBytesTicket} — see the type for what it is. */
9165
- var PeerBytesTicketSchema = object({
9166
- /** `http://127.0.0.1:<port>/<token>`. One `GET` takes it. */
9167
- url: string().min(1),
9168
- /**
9169
- * The HOST node this URL means something on — the hub or a named agent,
9170
- * never a runner. {@link AddonPeerBytes.open} compares it to its own and
9171
- * refuses `cross-node` by name when they differ, without dialling.
9172
- */
9173
- hostNodeId: string().min(1),
9174
- expiresAtMs: number().int().nonnegative(),
9175
- /**
9176
- * What the producer DECLARED the body to be, when it knows — `null` when it
9177
- * does not. Never `0` for unknown (D393): a consumer sizing a bound off this
9178
- * must be able to tell "the producer did not say" from "the body is empty".
9179
- */
9180
- declaredBytes: number().int().nonnegative().nullable()
9181
- });
9182
9769
  function defOf(schema) {
9183
9770
  const zodBag = Reflect.get(schema, "_zod");
9184
9771
  if (typeof zodBag !== "object" || zodBag === null) return {};
@@ -9408,6 +9995,7 @@ function defineRecordKinds(specs) {
9408
9995
  function entryBody(shape) {
9409
9996
  return object({
9410
9997
  name: string().min(1),
9998
+ enabled: boolean().optional(),
9411
9999
  ...shape
9412
10000
  });
9413
10001
  }
@@ -9434,98 +10022,30 @@ function defineEntryKind(name, spec) {
9434
10022
  if (defined === void 0) throw new DeclarationRefusedError(`entry kind "${name}" was not built`);
9435
10023
  return defined;
9436
10024
  }
9437
- object({
9438
- field: string().min(1),
9439
- on: literal("advance")
9440
- });
9441
10025
  /**
9442
- * Output schema shared by the contribution + live methods.
9443
- *
9444
- * Mirrors the `ConfigUISchemaWithValues` shape (sections[] + optional
9445
- * tabs[]) without importing from `../interfaces/config-ui.js` — a
9446
- * concrete-but-lenient Zod object keeps tRPC output inference happy
9447
- * (using `z.unknown()` here collapses unrelated router branches to
9448
- * `unknown` when the generator re-inlines the huge AppRouter type).
9449
- *
9450
- * `.passthrough()` on sections/fields accepts whatever FormBuilder
9451
- * extensions the caller adds (showWhen, displayScale, …) without
9452
- * rebuilding every time a new field kind is introduced.
10026
+ * The share-view scope kinds a share-link token can carry. The hub mints
10027
+ * and validates them (`ShareViewGrantSchema` builds its
10028
+ * enum from this list); a data plane names the kinds it ACCEPTS in `share`.
9453
10029
  */
9454
- var ContributionSectionSchema = object({
9455
- id: string(),
9456
- title: string(),
9457
- description: string().optional(),
9458
- style: _enum(["card", "accordion"]).optional(),
9459
- defaultCollapsed: boolean().optional(),
9460
- columns: union([
9461
- literal(1),
9462
- literal(2),
9463
- literal(3),
9464
- literal(4)
9465
- ]).optional(),
9466
- tab: string().optional(),
9467
- location: _enum([
9468
- "settings",
9469
- "top-tab",
9470
- "hero"
9471
- ]).optional(),
9472
- order: number().optional(),
9473
- fields: array(any())
10030
+ var SHARE_VIEW_KINDS = ["grid-view", "events-view"];
10031
+ /** The wire shape of {@link PeerBytesTicket} — see the type for what it is. */
10032
+ var PeerBytesTicketSchema = object({
10033
+ /** `http://127.0.0.1:<port>/<token>`. One `GET` takes it. */
10034
+ url: string().min(1),
10035
+ /**
10036
+ * The HOST node this URL means something on — the hub or a named agent,
10037
+ * never a runner. {@link AddonPeerBytes.open} compares it to its own and
10038
+ * refuses `cross-node` by name when they differ, without dialling.
10039
+ */
10040
+ hostNodeId: string().min(1),
10041
+ expiresAtMs: number().int().nonnegative(),
10042
+ /**
10043
+ * What the producer DECLARED the body to be, when it knows — `null` when it
10044
+ * does not. Never `0` for unknown (D393): a consumer sizing a bound off this
10045
+ * must be able to tell "the producer did not say" from "the body is empty".
10046
+ */
10047
+ declaredBytes: number().int().nonnegative().nullable()
9474
10048
  });
9475
- object({
9476
- tabs: array(object({
9477
- id: string(),
9478
- label: string(),
9479
- icon: string(),
9480
- order: number().optional()
9481
- })).optional(),
9482
- sections: array(ContributionSectionSchema)
9483
- }).nullable();
9484
- object({ deviceId: number() }), object({ deviceId: number() }), object({
9485
- deviceId: number(),
9486
- patch: record(string(), unknown())
9487
- }), object({ success: literal(true) });
9488
- object({ deviceId: number() }), unknown().nullable();
9489
- function method(input, output, options) {
9490
- return {
9491
- input,
9492
- output,
9493
- kind: options?.kind ?? "query",
9494
- ...options?.auth !== void 0 ? { auth: options.auth } : {},
9495
- ...options?.access !== void 0 ? { access: options.access } : {},
9496
- ...options?.role !== void 0 ? { role: options.role } : {},
9497
- ...options?.caller !== void 0 ? { caller: options.caller } : {},
9498
- timeoutMs: options?.timeoutMs
9499
- };
9500
- }
9501
- /**
9502
- * A wrapper/system-only method: served exclusively by the cap's system-level
9503
- * provider (`InferProvider`), and OPTIONAL on `InferNativeProvider` so per-device
9504
- * driver natives don't stub out a wrapper concern (e.g. a cross-device cache
9505
- * overview). The `systemOnly: true` literal is what `InferNativeProvider` keys on.
9506
- */
9507
- function systemMethod(input, output, options) {
9508
- return {
9509
- ...method(input, output, options),
9510
- systemOnly: true
9511
- };
9512
- }
9513
- /**
9514
- * A method a SOURCE of a collection cap may legitimately not serve — OPTIONAL
9515
- * on `InferProvider`. The `providerOptional: true` literal is what
9516
- * `InferProvider` keys on; see {@link CapabilityMethodSchema.providerOptional}
9517
- * for when this is the honest answer and when it is a soft stub.
9518
- */
9519
- function optionalMethod(input, output, options) {
9520
- return {
9521
- ...method(input, output, options),
9522
- providerOptional: true
9523
- };
9524
- }
9525
- /** Shorthand to define an event schema */
9526
- function event(data) {
9527
- return { data };
9528
- }
9529
10049
  var READING_QUANTITIES = [
9530
10050
  "temperature",
9531
10051
  "pressure",
@@ -10116,7 +10636,6 @@ var CAP_NAMES = Object.freeze([
10116
10636
  "climate-control",
10117
10637
  "color",
10118
10638
  "composer",
10119
- "connection-test",
10120
10639
  "connectivity",
10121
10640
  "consumables",
10122
10641
  "contact",
@@ -11263,6 +11782,10 @@ Object.freeze({
11263
11782
  "all",
11264
11783
  "one"
11265
11784
  ]
11785
+ },
11786
+ {
11787
+ "path": "positionUpdatedAt",
11788
+ "valueType": "number"
11266
11789
  }
11267
11790
  ],
11268
11791
  "meter": [{
@@ -11517,22 +12040,6 @@ Object.freeze({
11517
12040
  "path": "pumpRunning",
11518
12041
  "valueType": "boolean"
11519
12042
  },
11520
- {
11521
- "path": "lastDrink",
11522
- "valueType": "number"
11523
- },
11524
- {
11525
- "path": "currentHourDrink",
11526
- "valueType": "number"
11527
- },
11528
- {
11529
- "path": "last24hDrink",
11530
- "valueType": "number"
11531
- },
11532
- {
11533
- "path": "todayDrink",
11534
- "valueType": "number"
11535
- },
11536
12043
  {
11537
12044
  "path": "error",
11538
12045
  "valueType": "string"
@@ -12098,6 +12605,59 @@ Object.freeze({
12098
12605
  }
12099
12606
  ]
12100
12607
  });
12608
+ Object.freeze({
12609
+ "actions": { "run": 363e4 },
12610
+ "audio-analyzer": { "classify": 3e4 },
12611
+ "custom-model-registry": { "importModelBundle": 18e5 },
12612
+ "database-snapshot": { "writeSnapshot": 18e5 },
12613
+ "device-manager": {
12614
+ "migrateDevice": 72e4,
12615
+ "runDiscoverySweep": 12e4
12616
+ },
12617
+ "device-provider": { "reloadDevice": 18e4 },
12618
+ "llm": {
12619
+ "generate": 6e5,
12620
+ "generateVision": 6e5,
12621
+ "testProfile": 6e5
12622
+ },
12623
+ "llm-runtime": {
12624
+ "complete": 6e5,
12625
+ "completeApple": 6e5,
12626
+ "ensureStarted": 6e5,
12627
+ "installModel": 36e5
12628
+ },
12629
+ "local-network": { "scanNetwork": 9e4 },
12630
+ "model-convert": { "convert": 6e5 },
12631
+ "pipeline-analytics": {
12632
+ "addRetrainFrameFromRecording": 6e4,
12633
+ "offerRetrainArchive": 12e4,
12634
+ "proposeRetrainAnnotationsWithLlm": 18e4,
12635
+ "resolveRetrainTrainingCorpus": 6e4,
12636
+ "writeRetrainArchive": 36e5
12637
+ },
12638
+ "server-management": { "applyServerUpdate": 96e4 },
12639
+ "terminal-session": { "pullOutput": 15e3 },
12640
+ "training": {
12641
+ "canaryResult": 12e4,
12642
+ "cancelJob": 12e4,
12643
+ "planJob": 6e4,
12644
+ "registerResult": 18e5,
12645
+ "rollbackCanary": 12e4,
12646
+ "startJob": 12e4,
12647
+ "startJobBatch": 12e4
12648
+ },
12649
+ "training-provider": {
12650
+ "cancelJob": 6e4,
12651
+ "cleanupJob": 3e5,
12652
+ "getJob": 6e4,
12653
+ "listJobEvents": 6e4,
12654
+ "listJobs": 12e4,
12655
+ "offerArtifact": 3e5,
12656
+ "readResult": 3e5,
12657
+ "submitJob": 18e5,
12658
+ "uploadDataset": 72e5
12659
+ }
12660
+ });
12101
12661
  object({
12102
12662
  code: string().regex(/^[a-z][a-z0-9-]*(\.[a-z0-9-]+)+$/),
12103
12663
  params: record(string(), union([string(), number()])).optional()
@@ -12117,7 +12677,7 @@ function userError(code, params, englishFallback) {
12117
12677
  return new CamstackError(code, params, englishFallback);
12118
12678
  }
12119
12679
  //#endregion
12120
- //#region ../types/dist/composition-pOHbTzRB.mjs
12680
+ //#region ../types/dist/composition-BmBHuDTQ.mjs
12121
12681
  /**
12122
12682
  * The ffmpeg build every CamStack node downloads, per platform and arch.
12123
12683
  *
@@ -12421,7 +12981,7 @@ var table = {
12421
12981
  },
12422
12982
  dwell: {
12423
12983
  minArgs: 3,
12424
- maxArgs: 3,
12984
+ maxArgs: 4,
12425
12985
  apply: () => {
12426
12986
  throw new ExpressionEvalError("dwell: stateful evaluation context is required");
12427
12987
  }
@@ -13398,278 +13958,498 @@ new Set(EVENT_OWNER_TYPES);
13398
13958
  * The publish workflow STAMPS these after the version bump
13399
13959
  * (`scripts/ci/stamp-requires.mjs`); nobody types a number by hand.
13400
13960
  *
13401
- * A requirement that cannot be checked is NOT met: a shell that reports no
13402
- * version counts as below the minimum, and an unreadable running version is
13403
- * named in the result (a failed read is never a pass).
13961
+ * A requirement that cannot be checked is NOT met: a shell that reports no
13962
+ * version counts as below the minimum, and an unreadable running version is
13963
+ * named in the result (a failed read is never a pass).
13964
+ */
13965
+ /** `>=MAJOR.MINOR.PATCH[-prerelease]` — the only range shape a requirement uses. */
13966
+ var MinVersionSchema = string().regex(/^>=\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/, "a minimum is written \">=X.Y.Z\"");
13967
+ object({
13968
+ /** The oldest `@camstack/server` this package runs on. */
13969
+ server: MinVersionSchema.optional(),
13970
+ /** The oldest installed version of each named addon package. */
13971
+ addons: record(string(), MinVersionSchema).optional(),
13972
+ /** The oldest shell around the server, per shell kind. */
13973
+ wrapper: object({
13974
+ desktop: MinVersionSchema.optional(),
13975
+ image: MinVersionSchema.optional()
13976
+ }).optional()
13977
+ });
13978
+ /** One unmet requirement; each names the versions on both sides. */
13979
+ var UnmetRequirementSchema = discriminatedUnion("kind", [
13980
+ object({
13981
+ kind: literal("server-too-old"),
13982
+ required: string(),
13983
+ /** `null` — the running server version could not be read. */
13984
+ running: string().nullable()
13985
+ }),
13986
+ object({
13987
+ kind: literal("addon-too-old"),
13988
+ packageName: string(),
13989
+ required: string(),
13990
+ /** `null` — the addon is not installed (or its version is unreadable). */
13991
+ running: string().nullable()
13992
+ }),
13993
+ object({
13994
+ kind: literal("wrapper-too-old"),
13995
+ wrapper: _enum(["desktop", "image"]),
13996
+ required: string(),
13997
+ /** `null` — the wrapper reported no version. */
13998
+ running: string().nullable()
13999
+ })
14000
+ ]);
14001
+ var RequiredAddonUpdateSchema = object({
14002
+ packageName: string(),
14003
+ /** The minimum the target server declares. */
14004
+ required: string(),
14005
+ /** What this node has; `null` when the addon is not installed. */
14006
+ installed: string().nullable()
14007
+ });
14008
+ /**
14009
+ * Which integration instance a settings form is for. An addon that serves several instances
14010
+ * (`instanceMode: multiple`) can show a different form per instance — an NVR integration
14011
+ * needs its connection, the default integration needs the addon's own sections.
14012
+ *
14013
+ * - `integrationId` is `null` in the create wizard: nothing exists yet, the operator is
14014
+ * setting up a NEW instance.
14015
+ * - `mode` is the wizard mode of the integration type (`getAvailableTypes`).
14016
+ * - `candidateStableId` is the discovery candidate a wizard was seeded from, if any.
14017
+ */
14018
+ var IntegrationInstanceRefSchema = object({
14019
+ integrationId: string().nullable(),
14020
+ mode: _enum([
14021
+ "standalone",
14022
+ "account",
14023
+ "broker"
14024
+ ]),
14025
+ candidateStableId: string().optional()
14026
+ });
14027
+ /**
14028
+ * notification-output — canonical, capability-gated notification delivery.
14029
+ *
14030
+ * Apprise-derived model (see
14031
+ * `docs/superpowers/specs/2026-07-03-notification-output-notifier-matrix.md`):
14032
+ * callers emit ONE canonical `Notification`; each provider declares a
14033
+ * per-kind capability descriptor (`TargetKind`), and the pure degrade
14034
+ * engine (`@camstack/types` `prepareNotification`) transcodes / degrades the
14035
+ * message to what the kind supports — callers never special-case a service.
14036
+ *
14037
+ * DESIGN DECISIONS (locked):
14038
+ * - Target CRUD lives on THIS cap (`upsertTarget` / `deleteTarget` /
14039
+ * `setTargetEnabled`), each provider persisting via the `settings-store`
14040
+ * cap. Rationale: the admin UI needs one uniform surface across the
14041
+ * notifiers addon AND the HA addon; the addon-`globalSettingsSchema`-array
14042
+ * alternative would fork the UI per addon and cannot host the
14043
+ * discovery→adopt flow.
14044
+ * - `listTargetKinds` / `listTargets` / `discoverTargets` return arrays →
14045
+ * the generated cap-mount auto-`concatCollection`-fans them across every
14046
+ * registered provider (notifiers addon + HA addon) so one catalog is
14047
+ * routable. `send` / `testTarget` / CRUD route to ONE provider by the
14048
+ * `addonId` the generated collection router extracts from the call input.
14049
+ * - `Attachment.bytes` is `Uint8Array`. Transport-safe: superjson (the tRPC
14050
+ * transformer) + UDS MsgPack both round-trip typed arrays — already used by
14051
+ * `storage` / `storage-provider` / `recording` caps over the same path. No
14052
+ * base64 fallback needed.
14053
+ *
14054
+ * TODO (deferred, closed-set change — separate decision): add
14055
+ * `providerKind: 'notify'` so notification providers surface on the unified
14056
+ * admin "Integrations" page.
14057
+ */
14058
+ /**
14059
+ * Zentik-derived typed-media enum — the superset across every kind. Each
14060
+ * adapter picks what it supports and the degrade engine filters the rest.
14061
+ */
14062
+ var AttachmentMediaTypeSchema = _enum([
14063
+ "image",
14064
+ "video",
14065
+ "gif",
14066
+ "audio",
14067
+ "icon"
14068
+ ]);
14069
+ /**
14070
+ * A single attachment. Exactly one of `url` (remote source, most adapters
14071
+ * prefer this) or `bytes` (inline source; required for Pushover-style
14072
+ * bytes-only kinds) MUST be present — the degrade engine expresses a
14073
+ * url→bytes fetch as a `needsFetch` directive the adapter executes.
14074
+ */
14075
+ var AttachmentSchema = object({
14076
+ mediaType: AttachmentMediaTypeSchema,
14077
+ url: string().optional(),
14078
+ bytes: _instanceof(Uint8Array).optional(),
14079
+ mime: string().optional(),
14080
+ name: string().optional()
14081
+ }).refine((a) => a.url !== void 0 || a.bytes !== void 0, { message: "Attachment requires either `url` or `bytes`" });
14082
+ var NotificationFormatSchema = _enum([
14083
+ "text",
14084
+ "markdown",
14085
+ "html"
14086
+ ]);
14087
+ /**
14088
+ * The CLOSED icon vocabulary an action button may use.
14089
+ *
14090
+ * A closed set, not a free string, and that is the whole point: an arbitrary
14091
+ * icon name is one that ntfy renders, zentik silently drops, and nobody
14092
+ * notices — the same class of gap as a zone vocabulary nothing produced
14093
+ * ([D35](../../../docs/decisions/adr-0035.md)). Every adapter maps this set or
14094
+ * declares `actionIcons: false` and the degrade engine strips the field.
14095
+ *
14096
+ * Named by INTENT, never by glyph. "check" would tie the vocabulary to one
14097
+ * renderer's icon set; "acknowledge" survives an adapter that draws it
14098
+ * differently.
14099
+ *
14100
+ * ── A TOKEN IS NOT A WIRE VALUE ─────────────────────────────────────
14101
+ *
14102
+ * These names are for US. **No adapter may forward one verbatim.** Each maps
14103
+ * the whole set onto its own renderer's vocabulary through a
14104
+ * `Record<NotificationActionIcon, string>` — a Record, never a lookup with a
14105
+ * fallback, so adding a member here fails every adapter's build until someone
14106
+ * decides its glyph, which is the only place that decision can be made
14107
+ * honestly.
14108
+ *
14109
+ * This paragraph is the bug. Zentik declared `actionIcons: true` and passed
14110
+ * `disarm` straight through; iOS feeds that string to
14111
+ * `UNNotificationActionIcon(systemImageName:)`, `disarm` is not an SF Symbol,
14112
+ * and every snooze and alarm button arrived BLANK. A pass-through is not a
14113
+ * mapping, and "the field is documented" is not "the value renders".
14114
+ *
14115
+ * Adding a member is TRAIN-BOUND. The enum lives in the published
14116
+ * `@camstack/server` closure and the cap seam validates against the HUB's copy,
14117
+ * so an addon that emits a token the running hub does not know does not lose an
14118
+ * icon — its whole `send` fails Zod validation and the notification never
14119
+ * arrives. Never emit a new token from an addon before the train carrying it.
14120
+ */
14121
+ var NotificationActionIconSchema = _enum([
14122
+ "acknowledge",
14123
+ "dismiss",
14124
+ "silence",
14125
+ "snooze",
14126
+ "view",
14127
+ "play",
14128
+ "open",
14129
+ "close",
14130
+ "lock",
14131
+ "unlock",
14132
+ "arm",
14133
+ "arm-home",
14134
+ "arm-away",
14135
+ "arm-night",
14136
+ "disarm",
14137
+ "light",
14138
+ "alert",
14139
+ "camera"
14140
+ ]);
14141
+ /** A single tap-through action button. */
14142
+ var NotificationActionSchema = object({
14143
+ id: string(),
14144
+ label: string(),
14145
+ url: string().optional(),
14146
+ /** Dropped by the degrade engine for a kind with `caps.actionIcons: false`. */
14147
+ icon: NotificationActionIconSchema.optional(),
14148
+ /**
14149
+ * Renders in a warning style where the notifier supports it.
14150
+ *
14151
+ * A HINT, never a gate. The callback's authority is its token and nothing
14152
+ * else — see `notification-center/action-token.ts` for what that does and
14153
+ * does not buy.
14154
+ */
14155
+ destructive: boolean().optional(),
14156
+ /**
14157
+ * How the tap should REACH the url.
14158
+ *
14159
+ * `navigate` (absent, and every button authored before this field) opens it:
14160
+ * the phone leaves the notification and shows whatever the callback returns.
14161
+ * That is right for a button whose answer the operator wants to read.
14162
+ *
14163
+ * `background` fires it as a POST and stays put. It exists for the buttons
14164
+ * whose whole point is not to interrupt — "silence this for 30 minutes" is
14165
+ * an answer to the notification, and being thrown into a browser tab to
14166
+ * confirm it costs more attention than the notification did. A backend that
14167
+ * cannot do a background call renders it as an ordinary link (the adapters
14168
+ * fall back rather than dropping the button), so this is a preference, never
14169
+ * a requirement.
14170
+ */
14171
+ mode: _enum(["navigate", "background"]).optional()
14172
+ });
14173
+ /** A delivery parameter value: what a notifier declared it takes. */
14174
+ var DeliveryParamValueSchema = union([
14175
+ string(),
14176
+ number(),
14177
+ boolean()
14178
+ ]);
14179
+ /**
14180
+ * One extra delivery parameter a notifier KIND declares (D938). A rule that
14181
+ * addresses a target of that kind may set it; a kind that declares nothing is
14182
+ * never handed one. The admin UI derives its control from this descriptor —
14183
+ * no editor knows a service by name.
14184
+ *
14185
+ * Optional fields are `.optional()`, never `.default()` (a Zod default does not
14186
+ * run on the addon cap path).
13404
14187
  */
13405
- /** `>=MAJOR.MINOR.PATCH[-prerelease]` — the only range shape a requirement uses. */
13406
- var MinVersionSchema = string().regex(/^>=\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/, "a minimum is written \">=X.Y.Z\"");
13407
- object({
13408
- /** The oldest `@camstack/server` this package runs on. */
13409
- server: MinVersionSchema.optional(),
13410
- /** The oldest installed version of each named addon package. */
13411
- addons: record(string(), MinVersionSchema).optional(),
13412
- /** The oldest shell around the server, per shell kind. */
13413
- wrapper: object({
13414
- desktop: MinVersionSchema.optional(),
13415
- image: MinVersionSchema.optional()
13416
- }).optional()
14188
+ var DeliveryParamSchema = object({
14189
+ key: string().min(1),
14190
+ label: string(),
14191
+ /** i18n key of the label, resolved by the declaring addon's namespace. */
14192
+ labelKey: string().optional(),
14193
+ type: _enum([
14194
+ "enum",
14195
+ "number",
14196
+ "boolean",
14197
+ "string"
14198
+ ]),
14199
+ /** `enum` only: the closed set of accepted values. */
14200
+ options: array(object({
14201
+ value: string(),
14202
+ label: string()
14203
+ })).optional(),
14204
+ /** `number` only. */
14205
+ min: number().optional(),
14206
+ max: number().optional(),
14207
+ /** What the notifier does when the rule sets nothing; shown as the placeholder. */
14208
+ default: DeliveryParamValueSchema.optional()
13417
14209
  });
13418
- /** One unmet requirement; each names the versions on both sides. */
13419
- var UnmetRequirementSchema = discriminatedUnion("kind", [
13420
- object({
13421
- kind: literal("server-too-old"),
13422
- required: string(),
13423
- /** `null` — the running server version could not be read. */
13424
- running: string().nullable()
13425
- }),
13426
- object({
13427
- kind: literal("addon-too-old"),
13428
- packageName: string(),
13429
- required: string(),
13430
- /** `null` — the addon is not installed (or its version is unreadable). */
13431
- running: string().nullable()
14210
+ /**
14211
+ * The canonical notification. `body` is the only hard field (Apprise model).
14212
+ * `priority` is a 5-level ORDINAL (1=lowest … 3=normal(default) … 5=urgent),
14213
+ * NOT a fixed severity enum — each kind declares its own `caps.levels` and
14214
+ * the adapter maps this ordinal onto its native level. `level?` is an
14215
+ * optional kind-native level id (`emergency`, `silent`, …) that overrides
14216
+ * `priority` for that one target.
14217
+ */
14218
+ var NotificationSchema = object({
14219
+ body: string(),
14220
+ title: string().optional(),
14221
+ format: NotificationFormatSchema.default("text"),
14222
+ priority: number().int().min(1).max(5).default(3),
14223
+ level: string().optional(),
14224
+ attachments: array(AttachmentSchema).optional(),
14225
+ clickUrl: string().optional(),
14226
+ actions: array(NotificationActionSchema).optional(),
14227
+ sound: string().optional(),
14228
+ ttl: number().optional(),
14229
+ tag: string().optional(),
14230
+ deviceId: number().optional(),
14231
+ eventId: string().optional(),
14232
+ metadata: record(string(), unknown()).optional(),
14233
+ /**
14234
+ * Values for the parameters the target's kind DECLARES in
14235
+ * {@link TargetKindSchema} `deliveryParams`. Already validated against the
14236
+ * declaration by the sender; a notifier reads only the keys it declared.
14237
+ */
14238
+ delivery: record(string(), DeliveryParamValueSchema).optional()
14239
+ });
14240
+ /** One declared native severity/priority level for a kind. */
14241
+ var TargetKindLevelSchema = object({
14242
+ id: string(),
14243
+ label: string(),
14244
+ /** Which canonical priority (1..5) this level maps to. `null` = qualitative-only. */
14245
+ ordinal: number().int().min(1).max(5).nullable(),
14246
+ flags: object({
14247
+ critical: boolean().optional(),
14248
+ silent: boolean().optional(),
14249
+ noPush: boolean().optional()
14250
+ }).optional(),
14251
+ /** e.g. Pushover `emergency` requires `retry` / `expire`. */
14252
+ requires: array(string()).optional(),
14253
+ description: string().optional()
14254
+ });
14255
+ /** The full capability block consulted before dispatch. */
14256
+ var TargetKindCapsSchema = object({
14257
+ attachments: object({
14258
+ mediaTypes: array(AttachmentMediaTypeSchema),
14259
+ mode: _enum([
14260
+ "url",
14261
+ "bytes",
14262
+ "both"
14263
+ ]),
14264
+ max: number().int().nonnegative(),
14265
+ maxBytes: number().int().positive().optional()
13432
14266
  }),
13433
- object({
13434
- kind: literal("wrapper-too-old"),
13435
- wrapper: _enum(["desktop", "image"]),
13436
- required: string(),
13437
- /** `null` — the wrapper reported no version. */
13438
- running: string().nullable()
13439
- })
13440
- ]);
13441
- var RequiredAddonUpdateSchema = object({
13442
- packageName: string(),
13443
- /** The minimum the target server declares. */
13444
- required: string(),
13445
- /** What this node has; `null` when the addon is not installed. */
13446
- installed: string().nullable()
14267
+ /** Max action buttons (0 = none). */
14268
+ actions: number().int().nonnegative(),
14269
+ /**
14270
+ * Whether this kind renders a per-action ICON.
14271
+ *
14272
+ * `.optional()`, deliberately NOT `.default(false)`: a Zod default does not
14273
+ * run on the addon cap path — three production failures in one day taught
14274
+ * this repo that once. Absent is read as false by the degrade engine, which
14275
+ * is the safe direction: an icon that is not rendered costs nothing, an icon
14276
+ * assumed and dropped costs the operator's trust in the field.
14277
+ */
14278
+ actionIcons: boolean().optional(),
14279
+ levels: array(TargetKindLevelSchema),
14280
+ format: array(NotificationFormatSchema),
14281
+ clickUrl: boolean(),
14282
+ sound: boolean(),
14283
+ ttl: boolean(),
14284
+ bodyMaxLen: number().int().positive()
13447
14285
  });
13448
14286
  /**
13449
- * Which integration instance a settings form is for. An addon that serves several instances
13450
- * (`instanceMode: multiple`) can show a different form per instance — an NVR integration
13451
- * needs its connection, the default integration needs the addon's own sections.
13452
- *
13453
- * - `integrationId` is `null` in the create wizard: nothing exists yet, the operator is
13454
- * setting up a NEW instance.
13455
- * - `mode` is the wizard mode of the integration type (`getAvailableTypes`).
13456
- * - `candidateStableId` is the discovery candidate a wizard was seeded from, if any.
14287
+ * `configSchema` is a `ConfigUISchema` tree passed through to the admin
14288
+ * FormBuilder. Stored as `z.unknown()` at the cap seam (mirrors
14289
+ * `device-provider.getChildCreationSchema` `CreationSchemaOutputSchema`) —
14290
+ * the union is large and not meant for runtime validation here; the exported
14291
+ * `TargetKind` type re-tightens `configSchema` to `ConfigUISchema`.
13457
14292
  */
13458
- var IntegrationInstanceRefSchema = object({
13459
- integrationId: string().nullable(),
13460
- mode: _enum([
13461
- "standalone",
13462
- "account",
13463
- "broker"
13464
- ]),
13465
- candidateStableId: string().optional()
14293
+ var ConfigSchemaPassthrough$4 = unknown();
14294
+ var TargetKindSchema = object({
14295
+ kind: string(),
14296
+ label: string(),
14297
+ icon: string(),
14298
+ /** Stamped by each provider so the concat-fanned catalog stays routable. */
14299
+ addonId: string(),
14300
+ /**
14301
+ * URL of the kind's bundled BRAND icon, served by the providing addon over
14302
+ * its own `addon-routes` surface (`/addon/<addonId>/icons/<kind>`). Absent
14303
+ * when the addon bundles no icon for that kind — the client then falls back
14304
+ * to a neutral glyph rather than rendering the raw `icon` NAME as text.
14305
+ *
14306
+ * Root-relative on purpose: it resolves against whatever origin serves a web
14307
+ * client, and a native client joins it onto its own hub base.
14308
+ *
14309
+ * DECLARED here deliberately. It used to travel as an undeclared passthrough
14310
+ * field that survived only because the runtime cap-router forwards provider
14311
+ * output verbatim — so every consumer had to re-declare it by hand to stop
14312
+ * its own Zod parse from stripping it, and the whole arrangement would have
14313
+ * broken silently the moment output validation was tightened anywhere.
14314
+ */
14315
+ iconUrl: string().optional(),
14316
+ /**
14317
+ * Media type of {@link iconUrl} (`image/svg+xml`, `image/png`, …).
14318
+ *
14319
+ * The server knows this and therefore says it, because the client cannot
14320
+ * safely guess: a React-Native client renders SVG and raster through two
14321
+ * DIFFERENT components (`react-native-svg` vs `expo-image` — expo-image does
14322
+ * not decode SVG on iOS/Android), so without this it silently fell back to a
14323
+ * placeholder glyph for every vector icon while the web build looked fine.
14324
+ *
14325
+ * Absent when {@link iconUrl} is absent, or for a legacy provider that has
14326
+ * not been updated — a client that cannot determine the type should prefer
14327
+ * its raster path, which is the safe default for an unknown image.
14328
+ */
14329
+ iconMediaType: string().optional(),
14330
+ configSchema: ConfigSchemaPassthrough$4,
14331
+ /**
14332
+ * The config keys that decide WHERE this kind's secrets are sent (server,
14333
+ * base URL, instance, chat, recipient). A save that changes any of them
14334
+ * while leaving a secret redacted is refused by the provider (D634), so an
14335
+ * editor uses this to ask for the secret on exactly those edits instead of
14336
+ * on every edit.
14337
+ *
14338
+ * Optional: absent from a provider that holds no secret (the Home Assistant
14339
+ * kinds) and from a provider older than this field — an editor that finds
14340
+ * it absent must assume ANY edit may need the secret.
14341
+ */
14342
+ destinationKeys: array(string()).optional(),
14343
+ supportsDiscovery: boolean(),
14344
+ /**
14345
+ * Extra delivery parameters a rule may set for a target of this kind (D938).
14346
+ * Absent = none; the rule editor then offers nothing.
14347
+ */
14348
+ deliveryParams: array(DeliveryParamSchema).optional(),
14349
+ caps: TargetKindCapsSchema
13466
14350
  });
13467
14351
  /**
13468
- * `RecordIntegrationInstances` - the `integration-instances` provider over ONE
13469
- * entry kind, so an addon that holds a connection serves it in ~30 lines.
13470
- *
13471
- * Every instance is one record of the addon's own kind, keyed by the
13472
- * `integrations` registry id. The records door does the secret work: a field the
13473
- * kind marks `.meta({ secret: true })` is a keychain marker bound to the row, so
13474
- * deleting the row deletes the secret, and one row's value is never another's.
13475
- *
13476
- * Patch rules for a secret (`updateInstance`): omitted, `''`, the redaction
13477
- * token or the view the form was given KEEP the stored secret;
13478
- * `{ $secretClear: true }` clears it; any other string replaces it.
14352
+ * A persisted target. `config` holds secrets; providers REDACT secret fields
14353
+ * (return a presence marker only) when serving `listTargets` — never
14354
+ * round-trip a stored secret to the UI.
13479
14355
  */
13480
- /** The most instances one addon lists (an integrations page, not a table). */
13481
- var INSTANCES_LIST_MAX = 1e3;
13482
- /** The keys of the kind's secret fields that sit at the top level of the body. */
13483
- function topLevelSecretKeys(paths) {
13484
- return new Set(paths.filter((p) => !p.includes(".") && !p.includes("[") && !p.includes("{")));
13485
- }
13486
- /** The keys of the kind's top-level MAPS whose values are secrets (`applianceSecrets{}`). */
13487
- function secretMapKeys(paths) {
13488
- return new Set(paths.filter((p) => p.endsWith("{}") && !p.slice(0, -2).match(/[.[{]/)).map((p) => p.slice(0, -2)));
13489
- }
14356
+ var TargetSchema = object({
14357
+ id: string(),
14358
+ name: string(),
14359
+ kind: string(),
14360
+ addonId: string(),
14361
+ enabled: boolean(),
14362
+ config: record(string(), unknown())
14363
+ });
14364
+ /** A discovery-surfaced candidate (config is partial + non-secret). */
14365
+ var DiscoveredTargetSchema = object({
14366
+ kind: string(),
14367
+ suggestedName: string(),
14368
+ config: record(string(), unknown())
14369
+ });
14370
+ /** The degrade engine's report — what was resolved / dropped / degraded. */
14371
+ var RenderedAsSchema = object({
14372
+ level: string(),
14373
+ format: NotificationFormatSchema,
14374
+ attachmentsSent: number().int().nonnegative(),
14375
+ actionsSent: number().int().nonnegative(),
14376
+ truncated: boolean(),
14377
+ dropped: array(string())
14378
+ });
14379
+ var SendResultSchema = object({
14380
+ success: boolean(),
14381
+ error: string().optional(),
14382
+ renderedAs: RenderedAsSchema.optional()
14383
+ });
14384
+ /** Same shape as SendResult — kept as a distinct name for the test panel. */
14385
+ var TestResultSchema = SendResultSchema;
13490
14386
  /**
13491
- * A patch value for a map of secrets: an entry that is omitted, `''`, the redaction token or the
13492
- * view the form was given KEEPS its stored secret (it is left out of the merge); `{ $secretClear }`
13493
- * or `null` removes the entry; any other string replaces it. Null when nothing is left to merge.
14387
+ * Pre-save credential probe against a partial (unsaved) target config.
14388
+ * `resolvedUrl` never includes secrets (token stripped from path).
13494
14389
  */
13495
- function secretMapPatch(value) {
13496
- if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
13497
- const out = {};
13498
- for (const [key, entry] of Object.entries(value)) if (entry === null || isSecretClear(entry)) out[key] = null;
13499
- else if (typeof entry === "string" && entry !== "" && entry !== "__camstack_redacted__" && !isSecretFieldView(entry)) out[key] = entry;
13500
- return Object.keys(out).length > 0 ? out : null;
13501
- }
13502
- /** Does the kind's body schema carry an `enabled` field? */
13503
- function declaresEnabled(kind) {
13504
- const json = toJSONSchema(kind.schema, {
13505
- unrepresentable: "any",
13506
- io: "input"
13507
- });
13508
- const properties = Reflect.get(json, "properties");
13509
- return typeof properties === "object" && properties !== null && "enabled" in properties;
13510
- }
13511
- var RecordIntegrationInstances = class {
13512
- records;
13513
- kind;
13514
- hooks;
13515
- handle;
13516
- secretKeys;
13517
- secretMaps;
13518
- nameField;
13519
- /** The `integrations` registry owns the on/off switch (`role: devices`); the body has none. */
13520
- registryOwnsEnabled;
13521
- constructor(records, kind, hooks) {
13522
- this.records = records;
13523
- this.kind = kind;
13524
- this.hooks = hooks;
13525
- this.handle = records.kind(kind);
13526
- this.secretKeys = topLevelSecretKeys(kind.declaration.secretPaths);
13527
- this.secretMaps = secretMapKeys(kind.declaration.secretPaths);
13528
- this.nameField = kind.declaration.entry?.nameField ?? "name";
13529
- this.registryOwnsEnabled = hooks.description.role === "devices";
13530
- 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"`);
13531
- }
14390
+ var ProbeTargetConfigResultSchema = object({
14391
+ ok: boolean(),
14392
+ resolvedUrl: string(),
14393
+ httpStatus: number().int().optional(),
14394
+ stateInstance: string().optional(),
14395
+ error: string().optional()
14396
+ });
14397
+ method(object({}), array(TargetKindSchema)), method(object({}), array(TargetSchema), { auth: "admin" }), method(object({ targetId: string() }), TargetSchema, { auth: "admin" }), method(object({
14398
+ kind: string(),
14399
+ config: record(string(), unknown()).optional(),
13532
14400
  /**
13533
- * One instance read for the addon's own runtime; null when absent. When the keychain is
13534
- * locked the row is served WITHOUT its secrets and says so (`secrets: 'unavailable'`), so the
13535
- * caller can keep what it had instead of reconfiguring with an empty secret (D49).
14401
+ * When editing / duplicating, the blank password field never round-trips
14402
+ * the stored token. Pass the source target id so the provider can restore
14403
+ * secrets server-side before dialling (same merge as upsert).
13536
14404
  */
13537
- async readResolved(id) {
13538
- try {
13539
- const record = await this.handle.getResolved(id);
13540
- return record === null ? null : {
13541
- id,
13542
- body: record.data,
13543
- enabled: record.data.enabled !== false,
13544
- secrets: "resolved"
13545
- };
13546
- } catch (err) {
13547
- if (!(err instanceof RecordSecretUnavailableError)) throw err;
13548
- const stored = await this.handle.get(id);
13549
- if (stored === null) return null;
13550
- return {
13551
- id,
13552
- body: Object.fromEntries(Object.entries(stored.data).filter(([key]) => !this.secretKeys.has(key))),
13553
- enabled: stored.data.enabled !== false,
13554
- secrets: "unavailable"
13555
- };
13556
- }
13557
- }
13558
- /** The body of {@link readResolved} alone; a locked keychain yields the row without secrets. */
13559
- async getResolved(id) {
13560
- return (await this.readResolved(id))?.body ?? null;
13561
- }
13562
- /** Every instance, secrets resolved where the keychain allows; an absent one is skipped. */
13563
- async listResolved() {
13564
- const page = await this.handle.query({ limit: INSTANCES_LIST_MAX });
13565
- const out = [];
13566
- for (const record of page.records) {
13567
- const read = await this.readResolved(record.id);
13568
- if (read !== null) out.push(read);
13569
- }
13570
- return out;
13571
- }
13572
- viewOf(record) {
13573
- const shown = secretViewsOf(this.records.owner, this.kind.name, record.id, this.kind.declaration, record.data);
13574
- const rawName = record.data[this.nameField];
13575
- const kind = this.hooks.kindOf?.(record.data);
13576
- const health = this.hooks.health?.(record.data, record.id);
13577
- return {
13578
- id: record.id,
13579
- name: typeof rawName === "string" ? rawName : record.id,
13580
- configured: this.hooks.configured(record.data),
13581
- ...this.registryOwnsEnabled ? {} : { enabled: record.data.enabled !== false },
13582
- formValues: shown,
13583
- ...kind !== void 0 ? { kind } : {},
13584
- ...health?.status !== void 0 ? { status: health.status } : {},
13585
- ...health?.lastCheckedAt !== void 0 ? { lastCheckedAt: health.lastCheckedAt } : {}
13586
- };
13587
- }
13588
- describe = async () => this.hooks.mintId === void 0 ? this.hooks.description : {
13589
- ...this.hooks.description,
13590
- mintsId: true
13591
- };
13592
- instanceFormSchema = async ({ id }) => this.hooks.formSchema(id);
13593
- listInstances = async () => {
13594
- return (await this.handle.query({ limit: INSTANCES_LIST_MAX })).records.map((record) => this.viewOf(record));
13595
- };
13596
- getInstance = async ({ id }) => {
13597
- const record = await this.handle.get(id);
13598
- return record === null ? null : this.viewOf(record);
13599
- };
13600
- /** Insert ONE row (`ifRev: 0`: an existing id is refused, never overwritten). */
13601
- createInstance = async ({ id, name, kind, values }) => {
13602
- const minted = id ?? this.hooks.mintId?.({
13603
- name,
13604
- ...kind !== void 0 ? { kind } : {}
13605
- });
13606
- if (minted === void 0) throw new Error("createInstance needs an id: this provider does not mint one");
13607
- await this.handle.put({
13608
- id: minted,
13609
- data: this.hooks.initialBody(name, kind)
13610
- }, { ifRev: 0 });
13611
- const patch = this.patchOf(values ?? {});
13612
- if (Object.keys(patch).length > 0) await this.handle.patch(minted, patch);
13613
- await this.hooks.onChanged?.(minted, "created");
13614
- return { id: minted };
13615
- };
13616
- updateInstance = async ({ id, name, values }) => {
13617
- const patch = this.patchOf(values);
13618
- if (name !== void 0) patch[this.nameField] = name;
13619
- await this.handle.patch(id, patch);
13620
- await this.hooks.onChanged?.(id, "updated");
13621
- return { ok: true };
13622
- };
13623
- /** The record patch a form `values` object means: secrets kept, cleared or replaced. */
13624
- patchOf(values) {
13625
- const patch = {};
13626
- for (const [key, value] of Object.entries(values)) {
13627
- if (value === void 0) continue;
13628
- if (this.secretMaps.has(key)) {
13629
- const entries = secretMapPatch(value);
13630
- if (entries !== null) patch[key] = entries;
13631
- } else if (!this.secretKeys.has(key)) patch[key] = value;
13632
- else if (isSecretClear(value)) patch[key] = null;
13633
- else if (typeof value === "string" && value !== "" && value !== "__camstack_redacted__" && !isSecretFieldView(value)) patch[key] = value;
13634
- }
13635
- return patch;
13636
- }
13637
- /** The switch lives in the record body; the addon is told so it applies it (D996). */
13638
- setInstanceEnabled = async ({ id, enabled }) => {
13639
- if (this.registryOwnsEnabled) throw new Error(`instance "${id}": the integrations registry owns the on/off switch of this addon; set it with integrations.update`);
13640
- await this.handle.patch(id, { enabled });
13641
- await this.hooks.onChanged?.(id, "enabled");
13642
- return { ok: true };
13643
- };
13644
- /** The row and its keychain refs go together (the records door). */
13645
- deleteInstance = async ({ id }) => {
13646
- await this.handle.delete(id);
13647
- await this.hooks.onChanged?.(id, "deleted");
13648
- return { ok: true };
13649
- };
13650
- testInstance = async (input) => {
13651
- if (this.hooks.test === void 0) return {
13652
- success: false,
13653
- status: "unsupported",
13654
- error: "This integration declares no connection test"
13655
- };
13656
- return this.hooks.test(input);
13657
- };
13658
- /** The flat provider object to hand to `registerProvider`. */
13659
- toProvider() {
13660
- return {
13661
- describe: this.describe,
13662
- instanceFormSchema: this.instanceFormSchema,
13663
- listInstances: this.listInstances,
13664
- getInstance: this.getInstance,
13665
- createInstance: this.createInstance,
13666
- updateInstance: this.updateInstance,
13667
- setInstanceEnabled: this.setInstanceEnabled,
13668
- deleteInstance: this.deleteInstance,
13669
- testInstance: this.testInstance
13670
- };
13671
- }
13672
- };
14405
+ targetId: string().optional()
14406
+ }), array(DiscoveredTargetSchema), { auth: "admin" }), method(object({
14407
+ kind: string(),
14408
+ config: record(string(), unknown()),
14409
+ /** See `discoverTargets.targetId` — restore stored secrets for a blank password. */
14410
+ targetId: string().optional()
14411
+ }), ProbeTargetConfigResultSchema, {
14412
+ kind: "mutation",
14413
+ auth: "admin"
14414
+ }), method(object({
14415
+ targetId: string(),
14416
+ notification: NotificationSchema
14417
+ }), SendResultSchema, {
14418
+ kind: "mutation",
14419
+ auth: "admin"
14420
+ }), method(object({
14421
+ targetId: string(),
14422
+ sample: NotificationSchema.optional()
14423
+ }), TestResultSchema, {
14424
+ kind: "mutation",
14425
+ auth: "admin"
14426
+ }), method(object({
14427
+ target: TargetSchema,
14428
+ /**
14429
+ * Duplicate flow: create a NEW target id while copying secrets from an
14430
+ * existing row. The UI never holds the stored token; blank / redacted
14431
+ * password fields are restored from this source (D634 still applies if
14432
+ * destinations diverge without a re-typed secret).
14433
+ */
14434
+ cloneSecretsFrom: string().optional()
14435
+ }), TargetSchema, {
14436
+ kind: "mutation",
14437
+ auth: "admin"
14438
+ }), method(object({ targetId: string() }), _void(), {
14439
+ kind: "mutation",
14440
+ auth: "admin"
14441
+ }), method(object({
14442
+ targetId: string(),
14443
+ enabled: boolean()
14444
+ }), _void(), {
14445
+ kind: "mutation",
14446
+ auth: "admin"
14447
+ });
14448
+ looseObject({
14449
+ name: string().min(1),
14450
+ enabled: boolean().optional()
14451
+ });
14452
+ TargetSchema.omit({ id: true });
13673
14453
  var EncodeProfileSchema = object({
13674
14454
  video: object({
13675
14455
  codec: _enum([
@@ -20487,31 +21267,21 @@ var APPLIANCE_CAP_VOCABULARY = {
20487
21267
  "pet-fountain": {
20488
21268
  scope: "device",
20489
21269
  noun: t("Pet fountain", "Fontana per animali"),
20490
- actions: [
20491
- {
20492
- id: "petFountain.pumpOn",
20493
- method: "setPump",
20494
- label: t("Pump on", "Pompa accesa"),
20495
- phrase: t("Start the pump of {device}", "Avvia la pompa di {device}"),
20496
- icon: "play",
20497
- args: { on: true }
20498
- },
20499
- {
20500
- id: "petFountain.pumpOff",
20501
- method: "setPump",
20502
- label: t("Pump off", "Pompa spenta"),
20503
- phrase: t("Stop the pump of {device}", "Ferma la pompa di {device}"),
20504
- icon: "square",
20505
- args: { on: false }
20506
- },
20507
- {
20508
- id: "petFountain.resetDailyConsumption",
20509
- method: "resetDailyConsumption",
20510
- label: t("Clear daily consumption", "Azzera il consumo giornaliero"),
20511
- phrase: t("Clear the daily water consumption of {device}", "Azzera il consumo giornaliero di acqua di {device}"),
20512
- icon: "rotate-ccw"
20513
- }
20514
- ],
21270
+ actions: [{
21271
+ id: "petFountain.pumpOn",
21272
+ method: "setPump",
21273
+ label: t("Pump on", "Pompa accesa"),
21274
+ phrase: t("Start the pump of {device}", "Avvia la pompa di {device}"),
21275
+ icon: "play",
21276
+ args: { on: true }
21277
+ }, {
21278
+ id: "petFountain.pumpOff",
21279
+ method: "setPump",
21280
+ label: t("Pump off", "Pompa spenta"),
21281
+ phrase: t("Stop the pump of {device}", "Ferma la pompa di {device}"),
21282
+ icon: "square",
21283
+ args: { on: false }
21284
+ }],
20515
21285
  state: [{
20516
21286
  kind: "boolean",
20517
21287
  field: "empty",
@@ -22530,7 +23300,6 @@ var SYSTEM_CAP_VOCABULARY = {
22530
23300
  "calendar-source": system(INTERNAL),
22531
23301
  calendars: system("calendars feed schedules and conditions, not device actions"),
22532
23302
  composer: system("device composition — an authoring tool, not an action"),
22533
- "connection-test": system(INTERNAL),
22534
23303
  "core-blocks": system(INTERNAL),
22535
23304
  "custom-model-registry": system(ML),
22536
23305
  "data-store-provider": system(INTERNAL),
@@ -44310,616 +45079,202 @@ var AutomationStepTraceSchema = object({
44310
45079
  "empty"
44311
45080
  ]),
44312
45081
  message: string().optional()
44313
- });
44314
- var AutomationRunTraceSchema = object({
44315
- runId: string().min(1),
44316
- startedAt: number(),
44317
- endedAt: number(),
44318
- trigger: AutomationTriggerTraceSchema,
44319
- conditions: array(AutomationConditionTraceNodeSchema),
44320
- verdict: AutomationRunVerdictSchema.optional(),
44321
- steps: array(AutomationStepTraceSchema),
44322
- outcome: AutomationRunOutcomeSchema,
44323
- /** How many identical consecutive skips this trace stands for (>= 1). */
44324
- repeat: number().int().min(1),
44325
- /** When the latest of those repeats happened. */
44326
- lastAt: number(),
44327
- /**
44328
- * A scheduler point's own outcome (D983). `outcome` carries the closest
44329
- * automation outcome so a reader that does not know schedulers still reads
44330
- * the trace; this field says exactly what happened.
44331
- */
44332
- scheduler: SchedulerOutcomeSchema.optional()
44333
- });
44334
- /**
44335
- * What the hub's `runs` ledger holds for one owner (`automation:<blockId>` or
44336
- * `action:<actionId>`): the cooldown stamp and the trace ring.
44337
- */
44338
- var AutomationStateDocSchema = object({
44339
- version: literal(1),
44340
- lastRunStartedAt: number().nullable(),
44341
- traces: array(AutomationRunTraceSchema)
44342
- });
44343
- /**
44344
- * Actions — named, runnable things an operator (or an automation) can start,
44345
- * declared as LIST ENTRIES, never as devices.
44346
- *
44347
- * An entry is either **internal** (a short list of cap/wait steps kept in the
44348
- * hub's `actions` record kind) or declared by an addon through the
44349
- * `action-source` collection (a Home Assistant script, a scene …). The one
44350
- * surface the UI and automations talk to is the `actions` cap; it keeps no
44351
- * catalog of its own (D3) — every `list` asks the providers live.
44352
- *
44353
- * This file is the data half: the entry schema, the variables an entry may
44354
- * declare, and the pure resolution of the values a run was given. It holds no
44355
- * runtime.
44356
- */
44357
- /** What a variable's value is. `select` takes one of `options`. */
44358
- var ActionVariableTypeSchema = _enum([
44359
- "string",
44360
- "number",
44361
- "boolean",
44362
- "select"
44363
- ]);
44364
- var ACTION_VARIABLE_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
44365
- var ActionVariableValueSchema = union([
44366
- string(),
44367
- number(),
44368
- boolean()
44369
- ]);
44370
- /**
44371
- * One declared variable. Steps reference it as `{ $var: 'name' }` (the whole
44372
- * value) or `{{vars.name}}` (inside a string) in their args.
44373
- */
44374
- var ActionVariableSchema = object({
44375
- name: string().regex(ACTION_VARIABLE_NAME_RE),
44376
- label: string().min(1).max(120).optional(),
44377
- type: ActionVariableTypeSchema,
44378
- required: boolean().optional(),
44379
- default: ActionVariableValueSchema.optional(),
44380
- /** The allowed values of a `select`. */
44381
- options: array(string().min(1)).min(1).optional()
44382
- }).superRefine((v, ctx) => {
44383
- if (v.type === "select" && v.options === void 0) ctx.addIssue({
44384
- code: "custom",
44385
- message: "a select variable needs options",
44386
- path: ["options"]
44387
- });
44388
- if (v.default !== void 0 && variableValueError(v, v.default) !== null) ctx.addIssue({
44389
- code: "custom",
44390
- message: variableValueError(v, v.default) ?? "invalid default",
44391
- path: ["default"]
44392
- });
44393
- });
44394
- /** Why `value` is not a legal value for the variable, or null when it is. */
44395
- function variableValueError(variable, value) {
44396
- switch (variable.type) {
44397
- case "string": return typeof value === "string" ? null : `variable "${variable.name}" must be a string`;
44398
- case "number": return typeof value === "number" && Number.isFinite(value) ? null : `variable "${variable.name}" must be a number`;
44399
- case "boolean": return typeof value === "boolean" ? null : `variable "${variable.name}" must be true or false`;
44400
- case "select": return typeof value === "string" && (variable.options ?? []).includes(value) ? null : `variable "${variable.name}" must be one of ${(variable.options ?? []).join(", ")}`;
44401
- }
44402
- }
44403
- var ActionSourceKindSchema = _enum(["internal", "addon"]);
44404
- function isInternalActionId(actionId) {
44405
- return actionId.startsWith("internal:") && actionId.length > 9;
44406
- }
44407
- /** The addon behind a `<addonId>:<localId>` id, or null for anything else (internal included). */
44408
- function addonIdOfActionId(actionId) {
44409
- if (isInternalActionId(actionId)) return null;
44410
- const at = actionId.indexOf(":");
44411
- return at > 0 && at < actionId.length - 1 ? actionId.slice(0, at) : null;
44412
- }
44413
- var ActionStatusSchema = object({
44414
- isRunning: boolean(),
44415
- /** Ms epoch the latest run STARTED; null when it never ran. */
44416
- lastRunAt: number().nullable(),
44417
- /** The latest run's failure; null on success or when it never ran. */
44418
- lastError: string().nullable()
44419
- });
44420
- var ActionEntrySchema = object({
44421
- /** `internal:<uuid>` or `<addonId>:<localId>`. */
44422
- id: string().min(3),
44423
- name: string().min(1).max(120),
44424
- /** The addon that declared it; `core-blocks` for an internal one. */
44425
- addonId: string().min(1),
44426
- source: ActionSourceKindSchema,
44427
- /** An addon-declared entry is edited where it was declared. */
44428
- readOnly: boolean(),
44429
- /** Internal only: cap and wait steps. No action-in-action, so no cycles. */
44430
- steps: array(ActionStepSchema).min(1).max(50).optional(),
44431
- variables: array(ActionVariableSchema).max(20).optional(),
44432
- status: ActionStatusSchema
44433
- }).superRefine((entry, ctx) => {
44434
- if (entry.source === "internal") {
44435
- if (!isInternalActionId(entry.id)) ctx.addIssue({
44436
- code: "custom",
44437
- message: "an internal action id is internal:<uuid>",
44438
- path: ["id"]
44439
- });
44440
- return;
44441
- }
44442
- if (entry.steps !== void 0) ctx.addIssue({
44443
- code: "custom",
44444
- message: "only an internal action carries steps",
44445
- path: ["steps"]
44446
- });
44447
- if (!entry.readOnly) ctx.addIssue({
44448
- code: "custom",
44449
- message: "an addon action is read-only here",
44450
- path: ["readOnly"]
44451
- });
44452
- if (addonIdOfActionId(entry.id) === null) ctx.addIssue({
44453
- code: "custom",
44454
- message: "an addon action id is <addonId>:<localId>",
44455
- path: ["id"]
44456
- });
44457
- });
44458
- /** What an operator writes for an internal action. */
44459
- var ActionInputSchema = object({
44460
- name: string().min(1).max(120),
44461
- steps: array(ActionStepSchema).min(1).max(50),
44462
- variables: array(ActionVariableSchema).max(20).optional()
44463
- });
44464
- /** Who started a run. Absent = the operator pressed it. */
44465
- var ActionRunOriginSchema = object({
44466
- /** The automation block whose step started it. */
44467
- blockId: string().min(1).optional() });
44468
- /** `started` = the caller did not ask to wait. */
44469
- var ActionRunOutcomeSchema = union([AutomationRunOutcomeSchema, literal("started")]);
44470
- var ActionRunResultSchema = object({
44471
- runId: string().min(1),
44472
- outcome: ActionRunOutcomeSchema,
44473
- /** Why it did not run, or what failed. */
44474
- message: string().optional()
44475
- });
44476
- _enum([
44477
- "not-found",
44478
- "read-only",
44479
- "invalid-variables",
44480
- "invalid-steps",
44481
- "not-linked",
44482
- "busy"
44483
- ]);
44484
- object({
44485
- actionId: string(),
44486
- runId: string(),
44487
- isRunning: boolean(),
44488
- /** Set when the run ended. */
44489
- outcome: AutomationRunOutcomeSchema.optional(),
44490
- lastRunAt: number().nullable(),
44491
- lastError: string().nullable()
44492
- });
44493
- /** A bare number accepted as a base unit — the save succeeded, say so. */
44494
- var UnitWarningSchema = object({
44495
- /** Where in the saved record, e.g. `conditions.children.0` or `steps.2.args.grams`. */
44496
- path: string(),
44497
- deviceId: number().int().optional(),
44498
- field: string(),
44499
- value: number(),
44500
- assumedUnit: string(),
44501
- message: string()
44502
- });
44503
- /**
44504
- * notification-output — canonical, capability-gated notification delivery.
44505
- *
44506
- * Apprise-derived model (see
44507
- * `docs/superpowers/specs/2026-07-03-notification-output-notifier-matrix.md`):
44508
- * callers emit ONE canonical `Notification`; each provider declares a
44509
- * per-kind capability descriptor (`TargetKind`), and the pure degrade
44510
- * engine (`@camstack/types` `prepareNotification`) transcodes / degrades the
44511
- * message to what the kind supports — callers never special-case a service.
44512
- *
44513
- * DESIGN DECISIONS (locked):
44514
- * - Target CRUD lives on THIS cap (`upsertTarget` / `deleteTarget` /
44515
- * `setTargetEnabled`), each provider persisting via the `settings-store`
44516
- * cap. Rationale: the admin UI needs one uniform surface across the
44517
- * notifiers addon AND the HA addon; the addon-`globalSettingsSchema`-array
44518
- * alternative would fork the UI per addon and cannot host the
44519
- * discovery→adopt flow.
44520
- * - `listTargetKinds` / `listTargets` / `discoverTargets` return arrays →
44521
- * the generated cap-mount auto-`concatCollection`-fans them across every
44522
- * registered provider (notifiers addon + HA addon) so one catalog is
44523
- * routable. `send` / `testTarget` / CRUD route to ONE provider by the
44524
- * `addonId` the generated collection router extracts from the call input.
44525
- * - `Attachment.bytes` is `Uint8Array`. Transport-safe: superjson (the tRPC
44526
- * transformer) + UDS MsgPack both round-trip typed arrays — already used by
44527
- * `storage` / `storage-provider` / `recording` caps over the same path. No
44528
- * base64 fallback needed.
44529
- *
44530
- * TODO (deferred, closed-set change — separate decision): add
44531
- * `providerKind: 'notify'` so notification providers surface on the unified
44532
- * admin "Integrations" page.
44533
- */
44534
- /**
44535
- * Zentik-derived typed-media enum — the superset across every kind. Each
44536
- * adapter picks what it supports and the degrade engine filters the rest.
44537
- */
44538
- var AttachmentMediaTypeSchema = _enum([
44539
- "image",
44540
- "video",
44541
- "gif",
44542
- "audio",
44543
- "icon"
44544
- ]);
44545
- /**
44546
- * A single attachment. Exactly one of `url` (remote source, most adapters
44547
- * prefer this) or `bytes` (inline source; required for Pushover-style
44548
- * bytes-only kinds) MUST be present — the degrade engine expresses a
44549
- * url→bytes fetch as a `needsFetch` directive the adapter executes.
44550
- */
44551
- var AttachmentSchema = object({
44552
- mediaType: AttachmentMediaTypeSchema,
44553
- url: string().optional(),
44554
- bytes: _instanceof(Uint8Array).optional(),
44555
- mime: string().optional(),
44556
- name: string().optional()
44557
- }).refine((a) => a.url !== void 0 || a.bytes !== void 0, { message: "Attachment requires either `url` or `bytes`" });
44558
- var NotificationFormatSchema = _enum([
44559
- "text",
44560
- "markdown",
44561
- "html"
44562
- ]);
44563
- /**
44564
- * The CLOSED icon vocabulary an action button may use.
44565
- *
44566
- * A closed set, not a free string, and that is the whole point: an arbitrary
44567
- * icon name is one that ntfy renders, zentik silently drops, and nobody
44568
- * notices — the same class of gap as a zone vocabulary nothing produced
44569
- * ([D35](../../../docs/decisions/adr-0035.md)). Every adapter maps this set or
44570
- * declares `actionIcons: false` and the degrade engine strips the field.
44571
- *
44572
- * Named by INTENT, never by glyph. "check" would tie the vocabulary to one
44573
- * renderer's icon set; "acknowledge" survives an adapter that draws it
44574
- * differently.
44575
- *
44576
- * ── A TOKEN IS NOT A WIRE VALUE ─────────────────────────────────────
44577
- *
44578
- * These names are for US. **No adapter may forward one verbatim.** Each maps
44579
- * the whole set onto its own renderer's vocabulary through a
44580
- * `Record<NotificationActionIcon, string>` — a Record, never a lookup with a
44581
- * fallback, so adding a member here fails every adapter's build until someone
44582
- * decides its glyph, which is the only place that decision can be made
44583
- * honestly.
44584
- *
44585
- * This paragraph is the bug. Zentik declared `actionIcons: true` and passed
44586
- * `disarm` straight through; iOS feeds that string to
44587
- * `UNNotificationActionIcon(systemImageName:)`, `disarm` is not an SF Symbol,
44588
- * and every snooze and alarm button arrived BLANK. A pass-through is not a
44589
- * mapping, and "the field is documented" is not "the value renders".
44590
- *
44591
- * Adding a member is TRAIN-BOUND. The enum lives in the published
44592
- * `@camstack/server` closure and the cap seam validates against the HUB's copy,
44593
- * so an addon that emits a token the running hub does not know does not lose an
44594
- * icon — its whole `send` fails Zod validation and the notification never
44595
- * arrives. Never emit a new token from an addon before the train carrying it.
44596
- */
44597
- var NotificationActionIconSchema = _enum([
44598
- "acknowledge",
44599
- "dismiss",
44600
- "silence",
44601
- "snooze",
44602
- "view",
44603
- "play",
44604
- "open",
44605
- "close",
44606
- "lock",
44607
- "unlock",
44608
- "arm",
44609
- "arm-home",
44610
- "arm-away",
44611
- "arm-night",
44612
- "disarm",
44613
- "light",
44614
- "alert",
44615
- "camera"
44616
- ]);
44617
- /** A single tap-through action button. */
44618
- var NotificationActionSchema = object({
44619
- id: string(),
44620
- label: string(),
44621
- url: string().optional(),
44622
- /** Dropped by the degrade engine for a kind with `caps.actionIcons: false`. */
44623
- icon: NotificationActionIconSchema.optional(),
44624
- /**
44625
- * Renders in a warning style where the notifier supports it.
44626
- *
44627
- * A HINT, never a gate. The callback's authority is its token and nothing
44628
- * else — see `notification-center/action-token.ts` for what that does and
44629
- * does not buy.
44630
- */
44631
- destructive: boolean().optional(),
44632
- /**
44633
- * How the tap should REACH the url.
44634
- *
44635
- * `navigate` (absent, and every button authored before this field) opens it:
44636
- * the phone leaves the notification and shows whatever the callback returns.
44637
- * That is right for a button whose answer the operator wants to read.
44638
- *
44639
- * `background` fires it as a POST and stays put. It exists for the buttons
44640
- * whose whole point is not to interrupt — "silence this for 30 minutes" is
44641
- * an answer to the notification, and being thrown into a browser tab to
44642
- * confirm it costs more attention than the notification did. A backend that
44643
- * cannot do a background call renders it as an ordinary link (the adapters
44644
- * fall back rather than dropping the button), so this is a preference, never
44645
- * a requirement.
44646
- */
44647
- mode: _enum(["navigate", "background"]).optional()
44648
- });
44649
- /** A delivery parameter value: what a notifier declared it takes. */
44650
- var DeliveryParamValueSchema = union([
44651
- string(),
44652
- number(),
44653
- boolean()
44654
- ]);
44655
- /**
44656
- * One extra delivery parameter a notifier KIND declares (D938). A rule that
44657
- * addresses a target of that kind may set it; a kind that declares nothing is
44658
- * never handed one. The admin UI derives its control from this descriptor —
44659
- * no editor knows a service by name.
44660
- *
44661
- * Optional fields are `.optional()`, never `.default()` (a Zod default does not
44662
- * run on the addon cap path).
44663
- */
44664
- var DeliveryParamSchema = object({
44665
- key: string().min(1),
44666
- label: string(),
44667
- /** i18n key of the label, resolved by the declaring addon's namespace. */
44668
- labelKey: string().optional(),
44669
- type: _enum([
44670
- "enum",
44671
- "number",
44672
- "boolean",
44673
- "string"
44674
- ]),
44675
- /** `enum` only: the closed set of accepted values. */
44676
- options: array(object({
44677
- value: string(),
44678
- label: string()
44679
- })).optional(),
44680
- /** `number` only. */
44681
- min: number().optional(),
44682
- max: number().optional(),
44683
- /** What the notifier does when the rule sets nothing; shown as the placeholder. */
44684
- default: DeliveryParamValueSchema.optional()
44685
- });
44686
- /**
44687
- * The canonical notification. `body` is the only hard field (Apprise model).
44688
- * `priority` is a 5-level ORDINAL (1=lowest … 3=normal(default) … 5=urgent),
44689
- * NOT a fixed severity enum — each kind declares its own `caps.levels` and
44690
- * the adapter maps this ordinal onto its native level. `level?` is an
44691
- * optional kind-native level id (`emergency`, `silent`, …) that overrides
44692
- * `priority` for that one target.
44693
- */
44694
- var NotificationSchema = object({
44695
- body: string(),
44696
- title: string().optional(),
44697
- format: NotificationFormatSchema.default("text"),
44698
- priority: number().int().min(1).max(5).default(3),
44699
- level: string().optional(),
44700
- attachments: array(AttachmentSchema).optional(),
44701
- clickUrl: string().optional(),
44702
- actions: array(NotificationActionSchema).optional(),
44703
- sound: string().optional(),
44704
- ttl: number().optional(),
44705
- tag: string().optional(),
44706
- deviceId: number().optional(),
44707
- eventId: string().optional(),
44708
- metadata: record(string(), unknown()).optional(),
44709
- /**
44710
- * Values for the parameters the target's kind DECLARES in
44711
- * {@link TargetKindSchema} `deliveryParams`. Already validated against the
44712
- * declaration by the sender; a notifier reads only the keys it declared.
44713
- */
44714
- delivery: record(string(), DeliveryParamValueSchema).optional()
44715
- });
44716
- /** One declared native severity/priority level for a kind. */
44717
- var TargetKindLevelSchema = object({
44718
- id: string(),
44719
- label: string(),
44720
- /** Which canonical priority (1..5) this level maps to. `null` = qualitative-only. */
44721
- ordinal: number().int().min(1).max(5).nullable(),
44722
- flags: object({
44723
- critical: boolean().optional(),
44724
- silent: boolean().optional(),
44725
- noPush: boolean().optional()
44726
- }).optional(),
44727
- /** e.g. Pushover `emergency` requires `retry` / `expire`. */
44728
- requires: array(string()).optional(),
44729
- description: string().optional()
44730
- });
44731
- /** The full capability block consulted before dispatch. */
44732
- var TargetKindCapsSchema = object({
44733
- attachments: object({
44734
- mediaTypes: array(AttachmentMediaTypeSchema),
44735
- mode: _enum([
44736
- "url",
44737
- "bytes",
44738
- "both"
44739
- ]),
44740
- max: number().int().nonnegative(),
44741
- maxBytes: number().int().positive().optional()
44742
- }),
44743
- /** Max action buttons (0 = none). */
44744
- actions: number().int().nonnegative(),
44745
- /**
44746
- * Whether this kind renders a per-action ICON.
44747
- *
44748
- * `.optional()`, deliberately NOT `.default(false)`: a Zod default does not
44749
- * run on the addon cap path — three production failures in one day taught
44750
- * this repo that once. Absent is read as false by the degrade engine, which
44751
- * is the safe direction: an icon that is not rendered costs nothing, an icon
44752
- * assumed and dropped costs the operator's trust in the field.
44753
- */
44754
- actionIcons: boolean().optional(),
44755
- levels: array(TargetKindLevelSchema),
44756
- format: array(NotificationFormatSchema),
44757
- clickUrl: boolean(),
44758
- sound: boolean(),
44759
- ttl: boolean(),
44760
- bodyMaxLen: number().int().positive()
44761
- });
44762
- /**
44763
- * `configSchema` is a `ConfigUISchema` tree passed through to the admin
44764
- * FormBuilder. Stored as `z.unknown()` at the cap seam (mirrors
44765
- * `device-provider.getChildCreationSchema` `CreationSchemaOutputSchema`) —
44766
- * the union is large and not meant for runtime validation here; the exported
44767
- * `TargetKind` type re-tightens `configSchema` to `ConfigUISchema`.
44768
- */
44769
- var ConfigSchemaPassthrough$4 = unknown();
44770
- var TargetKindSchema = object({
44771
- kind: string(),
44772
- label: string(),
44773
- icon: string(),
44774
- /** Stamped by each provider so the concat-fanned catalog stays routable. */
44775
- addonId: string(),
44776
- /**
44777
- * URL of the kind's bundled BRAND icon, served by the providing addon over
44778
- * its own `addon-routes` surface (`/addon/<addonId>/icons/<kind>`). Absent
44779
- * when the addon bundles no icon for that kind — the client then falls back
44780
- * to a neutral glyph rather than rendering the raw `icon` NAME as text.
44781
- *
44782
- * Root-relative on purpose: it resolves against whatever origin serves a web
44783
- * client, and a native client joins it onto its own hub base.
44784
- *
44785
- * DECLARED here deliberately. It used to travel as an undeclared passthrough
44786
- * field that survived only because the runtime cap-router forwards provider
44787
- * output verbatim — so every consumer had to re-declare it by hand to stop
44788
- * its own Zod parse from stripping it, and the whole arrangement would have
44789
- * broken silently the moment output validation was tightened anywhere.
44790
- */
44791
- iconUrl: string().optional(),
44792
- /**
44793
- * Media type of {@link iconUrl} (`image/svg+xml`, `image/png`, …).
44794
- *
44795
- * The server knows this and therefore says it, because the client cannot
44796
- * safely guess: a React-Native client renders SVG and raster through two
44797
- * DIFFERENT components (`react-native-svg` vs `expo-image` — expo-image does
44798
- * not decode SVG on iOS/Android), so without this it silently fell back to a
44799
- * placeholder glyph for every vector icon while the web build looked fine.
44800
- *
44801
- * Absent when {@link iconUrl} is absent, or for a legacy provider that has
44802
- * not been updated — a client that cannot determine the type should prefer
44803
- * its raster path, which is the safe default for an unknown image.
44804
- */
44805
- iconMediaType: string().optional(),
44806
- configSchema: ConfigSchemaPassthrough$4,
44807
- /**
44808
- * The config keys that decide WHERE this kind's secrets are sent (server,
44809
- * base URL, instance, chat, recipient). A save that changes any of them
44810
- * while leaving a secret redacted is refused by the provider (D634), so an
44811
- * editor uses this to ask for the secret on exactly those edits instead of
44812
- * on every edit.
44813
- *
44814
- * Optional: absent from a provider that holds no secret (the Home Assistant
44815
- * kinds) and from a provider older than this field — an editor that finds
44816
- * it absent must assume ANY edit may need the secret.
44817
- */
44818
- destinationKeys: array(string()).optional(),
44819
- supportsDiscovery: boolean(),
45082
+ });
45083
+ var AutomationRunTraceSchema = object({
45084
+ runId: string().min(1),
45085
+ startedAt: number(),
45086
+ endedAt: number(),
45087
+ trigger: AutomationTriggerTraceSchema,
45088
+ conditions: array(AutomationConditionTraceNodeSchema),
45089
+ verdict: AutomationRunVerdictSchema.optional(),
45090
+ steps: array(AutomationStepTraceSchema),
45091
+ outcome: AutomationRunOutcomeSchema,
45092
+ /** How many identical consecutive skips this trace stands for (>= 1). */
45093
+ repeat: number().int().min(1),
45094
+ /** When the latest of those repeats happened. */
45095
+ lastAt: number(),
44820
45096
  /**
44821
- * Extra delivery parameters a rule may set for a target of this kind (D938).
44822
- * Absent = none; the rule editor then offers nothing.
45097
+ * A scheduler point's own outcome (D983). `outcome` carries the closest
45098
+ * automation outcome so a reader that does not know schedulers still reads
45099
+ * the trace; this field says exactly what happened.
44823
45100
  */
44824
- deliveryParams: array(DeliveryParamSchema).optional(),
44825
- caps: TargetKindCapsSchema
45101
+ scheduler: SchedulerOutcomeSchema.optional()
44826
45102
  });
44827
45103
  /**
44828
- * A persisted target. `config` holds secrets; providers REDACT secret fields
44829
- * (return a presence marker only) when serving `listTargets` — never
44830
- * round-trip a stored secret to the UI.
45104
+ * What the hub's `runs` ledger holds for one owner (`automation:<blockId>` or
45105
+ * `action:<actionId>`): the cooldown stamp and the trace ring.
44831
45106
  */
44832
- var TargetSchema = object({
44833
- id: string(),
44834
- name: string(),
44835
- kind: string(),
44836
- addonId: string(),
44837
- enabled: boolean(),
44838
- config: record(string(), unknown())
45107
+ var AutomationStateDocSchema = object({
45108
+ version: literal(1),
45109
+ lastRunStartedAt: number().nullable(),
45110
+ traces: array(AutomationRunTraceSchema)
44839
45111
  });
44840
- /** A discovery-surfaced candidate (config is partial + non-secret). */
44841
- var DiscoveredTargetSchema = object({
44842
- kind: string(),
44843
- suggestedName: string(),
44844
- config: record(string(), unknown())
45112
+ /**
45113
+ * Actions — named, runnable things an operator (or an automation) can start,
45114
+ * declared as LIST ENTRIES, never as devices.
45115
+ *
45116
+ * An entry is either **internal** (a short list of cap/wait steps kept in the
45117
+ * hub's `actions` record kind) or declared by an addon through the
45118
+ * `action-source` collection (a Home Assistant script, a scene …). The one
45119
+ * surface the UI and automations talk to is the `actions` cap; it keeps no
45120
+ * catalog of its own (D3) — every `list` asks the providers live.
45121
+ *
45122
+ * This file is the data half: the entry schema, the variables an entry may
45123
+ * declare, and the pure resolution of the values a run was given. It holds no
45124
+ * runtime.
45125
+ */
45126
+ /** What a variable's value is. `select` takes one of `options`. */
45127
+ var ActionVariableTypeSchema = _enum([
45128
+ "string",
45129
+ "number",
45130
+ "boolean",
45131
+ "select"
45132
+ ]);
45133
+ var ACTION_VARIABLE_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
45134
+ var ActionVariableValueSchema = union([
45135
+ string(),
45136
+ number(),
45137
+ boolean()
45138
+ ]);
45139
+ /**
45140
+ * One declared variable. Steps reference it as `{ $var: 'name' }` (the whole
45141
+ * value) or `{{vars.name}}` (inside a string) in their args.
45142
+ */
45143
+ var ActionVariableSchema = object({
45144
+ name: string().regex(ACTION_VARIABLE_NAME_RE),
45145
+ label: string().min(1).max(120).optional(),
45146
+ type: ActionVariableTypeSchema,
45147
+ required: boolean().optional(),
45148
+ default: ActionVariableValueSchema.optional(),
45149
+ /** The allowed values of a `select`. */
45150
+ options: array(string().min(1)).min(1).optional()
45151
+ }).superRefine((v, ctx) => {
45152
+ if (v.type === "select" && v.options === void 0) ctx.addIssue({
45153
+ code: "custom",
45154
+ message: "a select variable needs options",
45155
+ path: ["options"]
45156
+ });
45157
+ if (v.default !== void 0 && variableValueError(v, v.default) !== null) ctx.addIssue({
45158
+ code: "custom",
45159
+ message: variableValueError(v, v.default) ?? "invalid default",
45160
+ path: ["default"]
45161
+ });
44845
45162
  });
44846
- /** The degrade engine's report — what was resolved / dropped / degraded. */
44847
- var RenderedAsSchema = object({
44848
- level: string(),
44849
- format: NotificationFormatSchema,
44850
- attachmentsSent: number().int().nonnegative(),
44851
- actionsSent: number().int().nonnegative(),
44852
- truncated: boolean(),
44853
- dropped: array(string())
45163
+ /** Why `value` is not a legal value for the variable, or null when it is. */
45164
+ function variableValueError(variable, value) {
45165
+ switch (variable.type) {
45166
+ case "string": return typeof value === "string" ? null : `variable "${variable.name}" must be a string`;
45167
+ case "number": return typeof value === "number" && Number.isFinite(value) ? null : `variable "${variable.name}" must be a number`;
45168
+ case "boolean": return typeof value === "boolean" ? null : `variable "${variable.name}" must be true or false`;
45169
+ case "select": return typeof value === "string" && (variable.options ?? []).includes(value) ? null : `variable "${variable.name}" must be one of ${(variable.options ?? []).join(", ")}`;
45170
+ }
45171
+ }
45172
+ var ActionSourceKindSchema = _enum(["internal", "addon"]);
45173
+ function isInternalActionId(actionId) {
45174
+ return actionId.startsWith("internal:") && actionId.length > 9;
45175
+ }
45176
+ /** The addon behind a `<addonId>:<localId>` id, or null for anything else (internal included). */
45177
+ function addonIdOfActionId(actionId) {
45178
+ if (isInternalActionId(actionId)) return null;
45179
+ const at = actionId.indexOf(":");
45180
+ return at > 0 && at < actionId.length - 1 ? actionId.slice(0, at) : null;
45181
+ }
45182
+ var ActionStatusSchema = object({
45183
+ isRunning: boolean(),
45184
+ /** Ms epoch the latest run STARTED; null when it never ran. */
45185
+ lastRunAt: number().nullable(),
45186
+ /** The latest run's failure; null on success or when it never ran. */
45187
+ lastError: string().nullable()
44854
45188
  });
44855
- var SendResultSchema = object({
44856
- success: boolean(),
44857
- error: string().optional(),
44858
- renderedAs: RenderedAsSchema.optional()
45189
+ var ActionEntrySchema = object({
45190
+ /** `internal:<uuid>` or `<addonId>:<localId>`. */
45191
+ id: string().min(3),
45192
+ name: string().min(1).max(120),
45193
+ /** The addon that declared it; `core-blocks` for an internal one. */
45194
+ addonId: string().min(1),
45195
+ source: ActionSourceKindSchema,
45196
+ /** An addon-declared entry is edited where it was declared. */
45197
+ readOnly: boolean(),
45198
+ /** Internal only: cap and wait steps. No action-in-action, so no cycles. */
45199
+ steps: array(ActionStepSchema).min(1).max(50).optional(),
45200
+ variables: array(ActionVariableSchema).max(20).optional(),
45201
+ status: ActionStatusSchema
45202
+ }).superRefine((entry, ctx) => {
45203
+ if (entry.source === "internal") {
45204
+ if (!isInternalActionId(entry.id)) ctx.addIssue({
45205
+ code: "custom",
45206
+ message: "an internal action id is internal:<uuid>",
45207
+ path: ["id"]
45208
+ });
45209
+ return;
45210
+ }
45211
+ if (entry.steps !== void 0) ctx.addIssue({
45212
+ code: "custom",
45213
+ message: "only an internal action carries steps",
45214
+ path: ["steps"]
45215
+ });
45216
+ if (!entry.readOnly) ctx.addIssue({
45217
+ code: "custom",
45218
+ message: "an addon action is read-only here",
45219
+ path: ["readOnly"]
45220
+ });
45221
+ if (addonIdOfActionId(entry.id) === null) ctx.addIssue({
45222
+ code: "custom",
45223
+ message: "an addon action id is <addonId>:<localId>",
45224
+ path: ["id"]
45225
+ });
44859
45226
  });
44860
- /** Same shape as SendResult — kept as a distinct name for the test panel. */
44861
- var TestResultSchema = SendResultSchema;
45227
+ /** What an operator writes for an internal action. */
45228
+ var ActionInputSchema = object({
45229
+ name: string().min(1).max(120),
45230
+ steps: array(ActionStepSchema).min(1).max(50),
45231
+ variables: array(ActionVariableSchema).max(20).optional()
45232
+ });
45233
+ /** Who started a run. Absent = the operator pressed it. */
45234
+ var ActionRunOriginSchema = object({
45235
+ /** The automation block whose step started it. */
45236
+ blockId: string().min(1).optional() });
44862
45237
  /**
44863
- * Pre-save credential probe against a partial (unsaved) target config.
44864
- * `resolvedUrl` never includes secrets (token stripped from path).
45238
+ * `started` = the caller did not ask to wait. `timed-out` = the run reached the
45239
+ * ceiling (`ACTION_RUN_MAX_MS`) and was stopped; it is never a `ran`.
44865
45240
  */
44866
- var ProbeTargetConfigResultSchema = object({
44867
- ok: boolean(),
44868
- resolvedUrl: string(),
44869
- httpStatus: number().int().optional(),
44870
- stateInstance: string().optional(),
44871
- error: string().optional()
45241
+ var ActionRunOutcomeSchema = union([
45242
+ AutomationRunOutcomeSchema,
45243
+ literal("started"),
45244
+ literal("timed-out")
45245
+ ]);
45246
+ var ActionRunResultSchema = object({
45247
+ runId: string().min(1),
45248
+ outcome: ActionRunOutcomeSchema,
45249
+ /** Why it did not run, or what failed. */
45250
+ message: string().optional()
44872
45251
  });
44873
- method(object({}), array(TargetKindSchema)), method(object({}), array(TargetSchema), { auth: "admin" }), method(object({ targetId: string() }), TargetSchema, { auth: "admin" }), method(object({
44874
- kind: string(),
44875
- config: record(string(), unknown()).optional(),
44876
- /**
44877
- * When editing / duplicating, the blank password field never round-trips
44878
- * the stored token. Pass the source target id so the provider can restore
44879
- * secrets server-side before dialling (same merge as upsert).
44880
- */
44881
- targetId: string().optional()
44882
- }), array(DiscoveredTargetSchema), { auth: "admin" }), method(object({
44883
- kind: string(),
44884
- config: record(string(), unknown()),
44885
- /** See `discoverTargets.targetId` — restore stored secrets for a blank password. */
44886
- targetId: string().optional()
44887
- }), ProbeTargetConfigResultSchema, {
44888
- kind: "mutation",
44889
- auth: "admin"
44890
- }), method(object({
44891
- targetId: string(),
44892
- notification: NotificationSchema
44893
- }), SendResultSchema, {
44894
- kind: "mutation",
44895
- auth: "admin"
44896
- }), method(object({
44897
- targetId: string(),
44898
- sample: NotificationSchema.optional()
44899
- }), TestResultSchema, {
44900
- kind: "mutation",
44901
- auth: "admin"
44902
- }), method(object({
44903
- target: TargetSchema,
44904
- /**
44905
- * Duplicate flow: create a NEW target id while copying secrets from an
44906
- * existing row. The UI never holds the stored token; blank / redacted
44907
- * password fields are restored from this source (D634 still applies if
44908
- * destinations diverge without a re-typed secret).
44909
- */
44910
- cloneSecretsFrom: string().optional()
44911
- }), TargetSchema, {
44912
- kind: "mutation",
44913
- auth: "admin"
44914
- }), method(object({ targetId: string() }), _void(), {
44915
- kind: "mutation",
44916
- auth: "admin"
44917
- }), method(object({
44918
- targetId: string(),
44919
- enabled: boolean()
44920
- }), _void(), {
44921
- kind: "mutation",
44922
- auth: "admin"
45252
+ _enum([
45253
+ "not-found",
45254
+ "read-only",
45255
+ "invalid-variables",
45256
+ "invalid-steps",
45257
+ "not-linked",
45258
+ "busy"
45259
+ ]);
45260
+ object({
45261
+ actionId: string(),
45262
+ runId: string(),
45263
+ isRunning: boolean(),
45264
+ /** Set when the run ended. */
45265
+ outcome: AutomationRunOutcomeSchema.optional(),
45266
+ lastRunAt: number().nullable(),
45267
+ lastError: string().nullable()
45268
+ });
45269
+ /** A bare number accepted as a base unit — the save succeeded, say so. */
45270
+ var UnitWarningSchema = object({
45271
+ /** Where in the saved record, e.g. `conditions.children.0` or `steps.2.args.grams`. */
45272
+ path: string(),
45273
+ deviceId: number().int().optional(),
45274
+ field: string(),
45275
+ value: number(),
45276
+ assumedUnit: string(),
45277
+ message: string()
44923
45278
  });
44924
45279
  _enum([
44925
45280
  "automation",
@@ -44988,6 +45343,8 @@ method(object({}), array(ActionEntrySchema), { auth: "admin" }), method(object({
44988
45343
  kind: "mutation",
44989
45344
  auth: "admin"
44990
45345
  });
45346
+ /** `timeoutMs` of `actions.run`: a waited call outlives any legal run. */
45347
+ var ACTION_RUN_TIMEOUT_MS = 363e4;
44991
45348
  /**
44992
45349
  * actions — the ONE surface for runnable actions, for the UI and for
44993
45350
  * automations. Provided by the core-blocks builtin on the hub.
@@ -45006,6 +45363,12 @@ method(object({}), array(ActionEntrySchema), { auth: "admin" }), method(object({
45006
45363
  * An admin, and an in-process caller (an automation block), may run any action.
45007
45364
  * Every refusal is typed (`[not-linked] …`) and logged.
45008
45365
  *
45366
+ * **A run lasts at most `ACTION_RUN_MAX_MS` (60 min).** The provider stops a
45367
+ * run that reaches it and answers `timed-out` (never `ran`); an action whose
45368
+ * `wait` steps alone add up to more is refused at create/update
45369
+ * (`[invalid-steps]`). `run` declares a `timeoutMs` above that ceiling, so a
45370
+ * waited call (an automation step) is never cut by the 60 s transport default.
45371
+ *
45009
45372
  * A second `run` of an action that is already running is REFUSED — traced and
45010
45373
  * logged — never queued.
45011
45374
  */
@@ -45032,7 +45395,8 @@ method(object({}), array(ActionEntrySchema), { auth: "admin" }), method(object({
45032
45395
  role: "viewer",
45033
45396
  auth: "protected",
45034
45397
  kind: "mutation",
45035
- caller: "required"
45398
+ caller: "required",
45399
+ timeoutMs: ACTION_RUN_TIMEOUT_MS
45036
45400
  }), method(ActionIdInput, _void(), {
45037
45401
  kind: "mutation",
45038
45402
  auth: "admin"
@@ -49451,37 +49815,6 @@ method(object({
49451
49815
  kind: "mutation",
49452
49816
  auth: "admin"
49453
49817
  }), method(object({ blockIds: array(string()) }), object({ states: array(CompositionBlockStateSchema) }), { auth: "admin" });
49454
- var ConnectionTestOutcomeSchema = discriminatedUnion("outcome", [
49455
- object({
49456
- outcome: literal("validated"),
49457
- /** Round-trip of the sign-in, when the provider measured it. */
49458
- latencyMs: number().nonnegative().optional(),
49459
- /** Optional human detail worth showing next to the tick
49460
- * ("3 devices visible on this account"). */
49461
- detail: string().optional()
49462
- }).strict(),
49463
- object({
49464
- outcome: literal("rejected"),
49465
- error: string()
49466
- }).strict(),
49467
- object({
49468
- outcome: literal("inconclusive"),
49469
- error: string()
49470
- }).strict()
49471
- ]);
49472
- var ConnectionTestInputSchema = object({
49473
- /** Candidate integration settings, exactly as the create form collected them. */
49474
- settings: record(string(), unknown()) });
49475
- /**
49476
- * What the provider's test actually DOES, so the UI can say it in words before
49477
- * the operator presses the button ("Signs in to the Dreo cloud"). Purely
49478
- * descriptive — it never changes routing.
49479
- */
49480
- var ConnectionTestDescriptorSchema = object({ label: string() });
49481
- method(ConnectionTestInputSchema, ConnectionTestOutcomeSchema, {
49482
- kind: "mutation",
49483
- auth: "admin"
49484
- }), method(_void(), ConnectionTestDescriptorSchema, { auth: "admin" });
49485
49818
  /**
49486
49819
  * Upstream-system connectivity sensor — distinct from `device-status`,
49487
49820
  * which is the kernel-managed online/offline flag for the device's
@@ -50059,6 +50392,9 @@ var MediaPlayerStatusSchema = object({
50059
50392
  /** Repeat mode. Null when no repeat surface.
50060
50393
  * Pair with `DeviceFeature.MediaPlayerRepeat`. */
50061
50394
  repeat: MediaPlayerRepeatSchema.nullable(),
50395
+ /** Ms epoch when `position` was read from the device. Null when the driver
50396
+ * does not say; a UI that advances the position while playing counts from it. */
50397
+ positionUpdatedAt: number().nullable().default(null),
50062
50398
  /** Ms epoch when the slice was last updated. */
50063
50399
  lastChangedAt: number()
50064
50400
  });
@@ -50694,7 +51030,9 @@ var ThresholdTransformDraftSchema = object({
50694
51030
  comparison: _enum(["gte", "lte"]),
50695
51031
  threshold: number(),
50696
51032
  startDwellMs: number().nonnegative(),
50697
- stopDwellMs: number().nonnegative()
51033
+ stopDwellMs: number().nonnegative(),
51034
+ /** Samples a start needs; absent = the compiler's default for the source (2 for running power, else 1). */
51035
+ minSamples: number().int().min(1).optional()
50698
51036
  });
50699
51037
  var CustomizeTransformDraftSchema = discriminatedUnion("kind", [
50700
51038
  IdentityTransformDraftSchema,
@@ -56594,6 +56932,7 @@ var IntegrationWithStateSchema = object({
56594
56932
  id: string(),
56595
56933
  addonId: string(),
56596
56934
  name: string(),
56935
+ /** A projection of the instance body's switch (`setInstanceEnabled` is the only writer). */
56597
56936
  enabled: boolean(),
56598
56937
  info: record(string(), unknown()).readonly(),
56599
56938
  /** The discovery candidate this integration was set up from (D984). */
@@ -56606,6 +56945,7 @@ var IntegrationLiteSchema = object({
56606
56945
  id: string(),
56607
56946
  addonId: string(),
56608
56947
  name: string(),
56948
+ /** A projection of the instance body's switch (`setInstanceEnabled` is the only writer). */
56609
56949
  enabled: boolean(),
56610
56950
  info: record(string(), unknown()).readonly(),
56611
56951
  /** The discovery candidate this integration was set up from (D984). */
@@ -56651,10 +56991,9 @@ var AvailableIntegrationTypeSchema = object({
56651
56991
  * locations" checkbox. Provider-declared in the addon manifest. */
56652
56992
  supportsLocationImport: boolean(),
56653
56993
  /**
56654
- * True when this integration DECLARES a pre-creation test (the
56655
- * `connection-test` cap, or a broker whose settings it stores). Drives the
56656
- * Test button: an integration that cannot be tested must say so up front
56657
- * rather than offering a button that always answers the same nonsense.
56994
+ * True when this integration's instances declare a Test (`integration-instances.describe().canTest`,
56995
+ * D1016). An integration that cannot be tested must say so up front rather than offering a
56996
+ * button that always answers the same nonsense.
56658
56997
  */
56659
56998
  canTest: boolean(),
56660
56999
  existingInstances: array(object({
@@ -56705,15 +57044,21 @@ var TestConnectionResultSchema = object({
56705
57044
  var CreateIntegrationInputSchema = object({
56706
57045
  addonId: string(),
56707
57046
  name: string(),
56708
- enabled: boolean().optional(),
56709
57047
  info: record(string(), unknown()).optional(),
56710
57048
  /** `stableId` of the discovery candidate the form was seeded from (D984). */
56711
57049
  originStableId: string().optional(),
56712
- settings: record(string(), unknown()).optional()
57050
+ settings: record(string(), unknown()).optional(),
57051
+ /** The instance kind being created, for a provider with several; omitted = its only testable kind. */
57052
+ kind: string().min(1).optional()
56713
57053
  });
56714
57054
  var UpdateIntegrationInputSchema = object({
56715
57055
  id: string(),
56716
57056
  name: string().optional(),
57057
+ /**
57058
+ * Accepted for a FIXED builtin only (`info.fixed`: alarm panel, camera grid, core blocks,
57059
+ * terminal), which keeps no instance record: the registry flag is its one store. Any other
57060
+ * integration is switched through `integration-instances.setInstanceEnabled`.
57061
+ */
56717
57062
  enabled: boolean().optional(),
56718
57063
  info: record(string(), unknown()).optional()
56719
57064
  });
@@ -56730,13 +57075,7 @@ method(_void(), array(IntegrationWithStateSchema)), method(object({ id: string()
56730
57075
  }), method(object({ id: string() }), DeleteIntegrationResultSchema, {
56731
57076
  kind: "mutation",
56732
57077
  auth: "admin"
56733
- }), method(_void(), array(AvailableIntegrationTypeSchema), { auth: "admin" }), method(object({
56734
- addonId: string(),
56735
- settings: record(string(), unknown())
56736
- }), TestConnectionResultSchema, {
56737
- kind: "mutation",
56738
- auth: "admin"
56739
- });
57078
+ }), method(_void(), array(AvailableIntegrationTypeSchema), { auth: "admin" });
56740
57079
  /**
56741
57080
  * `integration-instances` - the connection of an addon that holds ONE or SEVERAL
56742
57081
  * (an account, a relay, a destination) as typed records (D985, D986). The addon's
@@ -56761,7 +57100,7 @@ var IntegrationInstanceIdSchema = string().min(1);
56761
57100
  var IntegrationInstanceModeSchema = _enum(["single", "multiple"]);
56762
57101
  /**
56763
57102
  * What the addon's instances ARE for the Integrations page (planning#416). `devices`: each
56764
- * instance is an integration that brings devices (the registry owns its on/off switch);
57103
+ * instance is an integration that brings devices (its record body owns the on/off switch);
56765
57104
  * `services`: a connection configured from the addon's own function page, never listed on
56766
57105
  * Integrations.
56767
57106
  * It is the same vocabulary as the manifest's `integrationRole`, which stays as an override.
@@ -56804,18 +57143,38 @@ var IntegrationInstanceKindSchema = object({
56804
57143
  /** Relative hub path to disconnect that account. */
56805
57144
  disconnectPath: string().min(1).optional()
56806
57145
  });
57146
+ /**
57147
+ * How devices of an instance are found. `none`: the operator adds them by hand; `lan`: the addon
57148
+ * scans the network before any instance exists (the wizard offers the candidates); `account`: the
57149
+ * devices appear after the instance signs in. `scopedToInstance`: a discovery run belongs to ONE
57150
+ * instance and its candidates are claimed by it.
57151
+ */
57152
+ var IntegrationInstanceDiscoverySchema = object({
57153
+ mode: _enum([
57154
+ "none",
57155
+ "lan",
57156
+ "account"
57157
+ ]),
57158
+ scopedToInstance: boolean()
57159
+ });
57160
+ /**
57161
+ * One link a kind of this provider declares (D1013 rule 5): the body `field` of an instance of
57162
+ * `kind` holds the id of an instance of the function cap `to.cap` (of kind `to.kind`, when set).
57163
+ * The hub indexes these so the target's delete is refused while a link names it.
57164
+ */
57165
+ var IntegrationInstanceLinkSchema = object({
57166
+ kind: string().min(1),
57167
+ field: string().min(1),
57168
+ to: object({
57169
+ cap: string().min(1),
57170
+ kind: string().min(1).optional()
57171
+ })
57172
+ });
56807
57173
  var IntegrationInstanceDescriptionSchema = object({
56808
57174
  /** What the instances are for the Integrations page; see {@link IntegrationInstanceRoleSchema}. */
56809
57175
  role: IntegrationInstanceRoleSchema,
56810
57176
  /** 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(),
57177
+ discovery: IntegrationInstanceDiscoverySchema.optional(),
56819
57178
  /** `single`: at most one instance can exist (Loki). `multiple`: an account each. */
56820
57179
  instanceMode: IntegrationInstanceModeSchema,
56821
57180
  /** What the instance is, for the UI (`destination`, `relay`, `account`). */
@@ -56836,7 +57195,9 @@ var IntegrationInstanceDescriptionSchema = object({
56836
57195
  * `createInstance` without an `id` works: the provider mints it. Absent means the caller must
56837
57196
  * send an id (the UI then mints an opaque one).
56838
57197
  */
56839
- mintsId: boolean().optional()
57198
+ mintsId: boolean().optional(),
57199
+ /** The links to other instances the provider's kinds declare; absent means none. */
57200
+ links: array(IntegrationInstanceLinkSchema).optional()
56840
57201
  });
56841
57202
  var IntegrationInstanceStatusSchema = object({
56842
57203
  state: _enum([
@@ -56856,8 +57217,8 @@ var IntegrationInstanceSchema = object({
56856
57217
  configured: boolean(),
56857
57218
  /**
56858
57219
  * 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.
57220
+ * so a row written before the field existed is on). The same for every role, `devices` included:
57221
+ * the body is the one store, `setInstanceEnabled` the one writer (epic #440, step 3).
56861
57222
  */
56862
57223
  enabled: boolean().optional(),
56863
57224
  /** The kind of this instance (one of `describe().kinds[].id`), when the provider has kinds. */
@@ -56907,7 +57268,8 @@ var integrationInstancesCapability = {
56907
57268
  auth: "admin"
56908
57269
  }),
56909
57270
  /**
56910
- * Switch ONE instance on or off. A row control, not a form field: `updateInstance.values` is the
57271
+ * Switch ONE instance on or off, for every role; a missing record is created from the addon's
57272
+ * initial body. A row control, not a form field: `updateInstance.values` is the
56911
57273
  * form patch (D62, D996). An off instance keeps its record and secrets and does no work.
56912
57274
  */
56913
57275
  setInstanceEnabled: method(object({
@@ -59970,6 +60332,8 @@ var MigrationIntegrationSchema = object({
59970
60332
  addonId: string(),
59971
60333
  name: string(),
59972
60334
  info: Rows,
60335
+ /** The registry's stored switch: read by the one-switch migration, nothing else. */
60336
+ enabled: boolean().optional(),
59973
60337
  originStableId: string().optional()
59974
60338
  });
59975
60339
  var MigrationDeviceSchema = object({
@@ -65454,13 +65818,6 @@ var AddBrokerInputSchema = object({
65454
65818
  });
65455
65819
  var AddBrokerResultSchema = object({ id: string() });
65456
65820
  var IdInputSchema = object({ id: string() });
65457
- var TestResultSchema$1 = discriminatedUnion("ok", [object({
65458
- ok: literal(true),
65459
- latencyMs: number()
65460
- }), object({
65461
- ok: literal(false),
65462
- error: string()
65463
- })]);
65464
65821
  var StartEmbeddedInputSchema = object({
65465
65822
  port: number().int().min(1).max(65535).default(1883),
65466
65823
  /** Allow anonymous connect (no username/password). Default: false. */
@@ -65483,9 +65840,6 @@ method(_void(), array(BrokerInfoSchema)), method(IdInputSchema, BrokerConnection
65483
65840
  }), method(IdInputSchema, _void(), {
65484
65841
  kind: "mutation",
65485
65842
  auth: "admin"
65486
- }), method(IdInputSchema, TestResultSchema$1, {
65487
- kind: "mutation",
65488
- auth: "admin"
65489
65843
  }), method(StartEmbeddedInputSchema, StartEmbeddedResultSchema, {
65490
65844
  kind: "mutation",
65491
65845
  auth: "admin"
@@ -70145,14 +70499,6 @@ var PetFountainStatusSchema = object({
70145
70499
  empty: boolean().nullable(),
70146
70500
  /** True while the pump is running. Null while unknown. */
70147
70501
  pumpRunning: boolean().nullable(),
70148
- /** Water drunk in the last drink, in litres. */
70149
- lastDrink: number().min(0).nullable().meta(readingMeta("volume")),
70150
- /** Water drunk in the current hour, in litres. */
70151
- currentHourDrink: number().min(0).nullable().meta(readingMeta("volume")),
70152
- /** Water drunk over the last 24 hours (rolling), in litres. */
70153
- last24hDrink: number().min(0).nullable().meta(readingMeta("volume")),
70154
- /** Water drunk since local midnight, in litres. Null when the fountain has no such sensor. */
70155
- todayDrink: number().min(0).nullable().meta(readingMeta("volume")),
70156
70502
  /** Decoded fault message. Null means healthy; a non-null string is an active fault. */
70157
70503
  error: string().nullable(),
70158
70504
  /** Ms epoch when the slice was last refreshed. */
@@ -70165,21 +70511,15 @@ var petFountainCapability = {
70165
70511
  deviceNative: true,
70166
70512
  mode: "singleton",
70167
70513
  deviceTypes: [DeviceType.PetFountain],
70168
- methods: {
70169
- /** Start or stop the pump. */
70170
- setPump: method(object({
70171
- deviceId: DeviceIdSchema$1,
70172
- on: boolean()
70173
- }), _void(), {
70174
- kind: "mutation",
70175
- auth: "protected"
70176
- }),
70177
- /** Clear the rolling daily consumption counters on the device. */
70178
- resetDailyConsumption: method(object({ deviceId: DeviceIdSchema$1 }), _void(), {
70179
- kind: "mutation",
70180
- auth: "protected"
70181
- })
70182
- },
70514
+ methods: {
70515
+ /** Start or stop the pump. */
70516
+ setPump: method(object({
70517
+ deviceId: DeviceIdSchema$1,
70518
+ on: boolean()
70519
+ }), _void(), {
70520
+ kind: "mutation",
70521
+ auth: "protected"
70522
+ }) },
70183
70523
  status: {
70184
70524
  schema: PetFountainStatusSchema,
70185
70525
  kind: "push"
@@ -70203,14 +70543,6 @@ var petFountainCapability = {
70203
70543
  waterVolume: {
70204
70544
  kind: "gauge",
70205
70545
  unit: "L"
70206
- },
70207
- todayDrink: {
70208
- kind: "gauge",
70209
- unit: "L"
70210
- },
70211
- last24hDrink: {
70212
- kind: "gauge",
70213
- unit: "L"
70214
70546
  }
70215
70547
  } }
70216
70548
  };
@@ -79324,7 +79656,7 @@ var TrainingProviderTypeSchema = object({
79324
79656
  label: string(),
79325
79657
  /** Path under the addon package (e.g. `assets/training-modal/icon.svg`). */
79326
79658
  iconAsset: string(),
79327
- /** Owning `training-provider` addon — collection selector for createEntry. */
79659
+ /** Owning `training-provider` addon. */
79328
79660
  addonId: string(),
79329
79661
  /**
79330
79662
  * Fields for one entry of this type (credentials + defaults). Absent on a
@@ -79369,36 +79701,6 @@ var TrainingProviderDescriptorSchema = object({
79369
79701
  */
79370
79702
  formValues: record(string(), unknown()).optional()
79371
79703
  });
79372
- /**
79373
- * Patch one entry's name, credentials and defaults. Pin with owning `{ addonId }`.
79374
- * An omitted or empty `tokenSecret` means KEEP the stored secret (D787).
79375
- * `{ $secretClear: true }` clears it.
79376
- */
79377
- var TrainingProviderUpdateEntryInputSchema = object({
79378
- entryId: string().min(1),
79379
- name: string().min(1),
79380
- tokenId: string().optional(),
79381
- tokenSecret: union([string(), object({ $secretClear: literal(true) })]).optional(),
79382
- environment: string().optional(),
79383
- gpuType: string().optional(),
79384
- region: string().optional(),
79385
- costCapUsd: number().nonnegative().optional(),
79386
- maxRuntimeSec: number().int().positive().optional(),
79387
- failedDatasetGraceHours: number().nonnegative().optional()
79388
- });
79389
- var TrainingCredentialCheckSchema = object({
79390
- ok: boolean(),
79391
- /** Workspace / account name, when the provider says. */
79392
- account: string().optional(),
79393
- reason: _enum([
79394
- "missing",
79395
- "invalid",
79396
- "forbidden",
79397
- "network",
79398
- "quota"
79399
- ]).optional(),
79400
- detail: string().optional()
79401
- });
79402
79704
  var ProviderJobStateSchema = _enum([
79403
79705
  "pending",
79404
79706
  "starting",
@@ -79446,22 +79748,6 @@ var TrainingLogLineSchema = object({
79446
79748
  text: string()
79447
79749
  });
79448
79750
  method(object({}), array(TrainingProviderDescriptorSchema).readonly(), { auth: "admin" }), method(object({}), array(TrainingProviderTypeSchema).readonly(), { auth: "admin" }), method(object({}), array(TrainingProviderEntrySchema).readonly(), { auth: "admin" }), method(object({
79449
- typeId: string().min(1),
79450
- name: string().min(1)
79451
- }), object({ entryId: string() }), {
79452
- kind: "mutation",
79453
- auth: "admin"
79454
- }), method(object({ entryId: string().min(1) }), object({ ok: literal(true) }), {
79455
- kind: "mutation",
79456
- auth: "admin"
79457
- }), method(TrainingProviderUpdateEntryInputSchema, object({ ok: literal(true) }), {
79458
- kind: "mutation",
79459
- auth: "admin"
79460
- }), method(object({ entryId: string().min(1) }), TrainingCredentialCheckSchema, {
79461
- kind: "mutation",
79462
- auth: "admin",
79463
- timeoutMs: 3e4
79464
- }), method(object({
79465
79751
  entryId: string().min(1),
79466
79752
  gpuType: string(),
79467
79753
  region: string(),
@@ -85440,20 +85726,6 @@ Object.freeze({
85440
85726
  access: "view",
85441
85727
  role: "admin"
85442
85728
  },
85443
- "connectionTest.describeTest": {
85444
- capName: "connection-test",
85445
- capScope: "system",
85446
- addonId: null,
85447
- access: "view",
85448
- role: "admin"
85449
- },
85450
- "connectionTest.testSettings": {
85451
- capName: "connection-test",
85452
- capScope: "system",
85453
- addonId: null,
85454
- access: "create",
85455
- role: "admin"
85456
- },
85457
85729
  "connectivity.getStatus": {
85458
85730
  capName: "connectivity",
85459
85731
  capScope: "device",
@@ -87820,13 +88092,6 @@ Object.freeze({
87820
88092
  access: "view",
87821
88093
  role: "admin"
87822
88094
  },
87823
- "integrations.testConnection": {
87824
- capName: "integrations",
87825
- capScope: "system",
87826
- addonId: null,
87827
- access: "create",
87828
- role: "admin"
87829
- },
87830
88095
  "integrations.update": {
87831
88096
  capName: "integrations",
87832
88097
  capScope: "system",
@@ -89059,13 +89324,6 @@ Object.freeze({
89059
89324
  access: "create",
89060
89325
  role: "admin"
89061
89326
  },
89062
- "mqttBroker.testConnection": {
89063
- capName: "mqtt-broker",
89064
- capScope: "system",
89065
- addonId: null,
89066
- access: "create",
89067
- role: "admin"
89068
- },
89069
89327
  "nativeObjectDetection.getOptions": {
89070
89328
  capName: "native-object-detection",
89071
89329
  capScope: "device",
@@ -89941,13 +90199,6 @@ Object.freeze({
89941
90199
  access: "view",
89942
90200
  role: "viewer"
89943
90201
  },
89944
- "petFountain.resetDailyConsumption": {
89945
- capName: "pet-fountain",
89946
- capScope: "device",
89947
- addonId: null,
89948
- access: "delete",
89949
- role: "viewer"
89950
- },
89951
90202
  "petFountain.setPump": {
89952
90203
  capName: "pet-fountain",
89953
90204
  capScope: "device",
@@ -93903,20 +94154,6 @@ Object.freeze({
93903
94154
  access: "create",
93904
94155
  role: "admin"
93905
94156
  },
93906
- "trainingProvider.createEntry": {
93907
- capName: "training-provider",
93908
- capScope: "system",
93909
- addonId: null,
93910
- access: "create",
93911
- role: "admin"
93912
- },
93913
- "trainingProvider.deleteEntry": {
93914
- capName: "training-provider",
93915
- capScope: "system",
93916
- addonId: null,
93917
- access: "delete",
93918
- role: "admin"
93919
- },
93920
94157
  "trainingProvider.describe": {
93921
94158
  capName: "training-provider",
93922
94159
  capScope: "system",
@@ -93987,13 +94224,6 @@ Object.freeze({
93987
94224
  access: "create",
93988
94225
  role: "admin"
93989
94226
  },
93990
- "trainingProvider.updateEntry": {
93991
- capName: "training-provider",
93992
- capScope: "system",
93993
- addonId: null,
93994
- access: "create",
93995
- role: "admin"
93996
- },
93997
94227
  "trainingProvider.uploadDataset": {
93998
94228
  capName: "training-provider",
93999
94229
  capScope: "system",
@@ -94001,13 +94231,6 @@ Object.freeze({
94001
94231
  access: "create",
94002
94232
  role: "admin"
94003
94233
  },
94004
- "trainingProvider.validateCredentials": {
94005
- capName: "training-provider",
94006
- capScope: "system",
94007
- addonId: null,
94008
- access: "create",
94009
- role: "admin"
94010
- },
94011
94234
  "turnProvider.getTurnServers": {
94012
94235
  capName: "turn-provider",
94013
94236
  capScope: "system",
@@ -96562,11 +96785,6 @@ Object.freeze({
96562
96785
  form: "single",
96563
96786
  optional: false
96564
96787
  }],
96565
- "petFountain.resetDailyConsumption": [{
96566
- name: "deviceId",
96567
- form: "single",
96568
- optional: false
96569
- }],
96570
96788
  "petFountain.setPump": [{
96571
96789
  name: "deviceId",
96572
96790
  form: "single",
@@ -99361,100 +99579,6 @@ object({
99361
99579
  delay: number().nonnegative().optional(),
99362
99580
  commands: record(string(), unknown())
99363
99581
  });
99364
- entryBody({ brokerId: string() });
99365
- function secretsOverMigrationApi(api) {
99366
- return {
99367
- resolve: async (refs) => {
99368
- const { values } = await api.secrets.resolve({ refs: [...refs] });
99369
- const out = {};
99370
- for (const ref of refs) {
99371
- const value = values[ref];
99372
- out[ref] = value === null || value === void 0 ? { kind: "missing" } : {
99373
- kind: "value",
99374
- value,
99375
- version: 0
99376
- };
99377
- }
99378
- return out;
99379
- },
99380
- delete: async (refs) => (await api.secrets.delete({ refs: [...refs] })).deleted
99381
- };
99382
- }
99383
- /** `ctx.records` as the migration API offers it: bind a kind, read and write by id. */
99384
- function recordsOverMigrationApi(api) {
99385
- return { kind: (definition) => {
99386
- const handle = api.records.kind(definition);
99387
- return {
99388
- get: (id) => handle.get({ id }),
99389
- getResolved: (id) => handle.getResolved({ id }),
99390
- put: (input, opts) => handle.put({
99391
- ...input,
99392
- ...opts?.ifRev === void 0 ? {} : { ifRev: opts.ifRev }
99393
- }),
99394
- delete: (id) => handle.delete({ id })
99395
- };
99396
- } };
99397
- }
99398
- function integrationRowsApiOver(api) {
99399
- return {
99400
- list: async () => (await api.integrations.list({})).integrations,
99401
- readLegacyIntegrationRows: (input) => api.legacyRows.read(input),
99402
- clearLegacyIntegrationRows: (input) => api.legacyRows.clear(input)
99403
- };
99404
- }
99405
- /**
99406
- * One serial lane per migration API: a log line is delivered after the line before it, so the
99407
- * order the steps wrote them in is the order the hub reads them in. A delivery that fails
99408
- * is reported once through the same door; if that fails too nothing is left to tell, and the
99409
- * line is dropped rather than thrown into a migration step or left as an unhandled rejection.
99410
- */
99411
- var lanes = /* @__PURE__ */ new WeakMap();
99412
- function deliver(api, send) {
99413
- const next = (lanes.get(api) ?? Promise.resolve()).then(send).then(() => void 0).catch(async (error) => {
99414
- const reason = error instanceof Error ? error.message : String(error);
99415
- await api.log.warn({ message: `a migration log line could not be delivered: ${reason}` }).catch(() => void 0);
99416
- });
99417
- lanes.set(api, next);
99418
- return next;
99419
- }
99420
- function warnOver(api) {
99421
- return (message) => deliver(api, () => api.log.warn({ message }));
99422
- }
99423
- /** What the rows-to-records move needs, over the migration API. */
99424
- function rowsDepsOver(api) {
99425
- return {
99426
- api: integrationRowsApiOver(api),
99427
- records: recordsOverMigrationApi(api),
99428
- secrets: secretsOverMigrationApi(api),
99429
- warn: warnOver(api)
99430
- };
99431
- }
99432
- function defaultIntegrationApiOver$1(api) {
99433
- return {
99434
- ...integrationRowsApiOver(api),
99435
- listDevices: async (addonId) => (await api.devices.list({ addonId })).devices,
99436
- readDeviceHasConfig: async (deviceId) => (await api.devices.get({ deviceId }))?.hasConfig ?? false,
99437
- setDeviceIntegrationId: async (deviceId, integrationId) => {
99438
- await api.devices.setIntegrationId({
99439
- deviceId,
99440
- integrationId
99441
- });
99442
- },
99443
- readDeviceIntegrationId: async (deviceId) => (await api.devices.get({ deviceId }))?.integrationId ?? null
99444
- };
99445
- }
99446
- /** What the rows-to-records move and the device claim need, over the migration API. */
99447
- function defaultIntegrationDepsOver(api) {
99448
- return {
99449
- ...rowsDepsOver(api),
99450
- api: defaultIntegrationApiOver$1(api),
99451
- info: (message) => deliver(api, () => api.log.info({ message })),
99452
- warnDevice: (message, deviceId) => deliver(api, () => api.log.warn({
99453
- message,
99454
- tags: { deviceId }
99455
- }))
99456
- };
99457
- }
99458
99582
  /**
99459
99583
  * Per-device bounds for the STILLS, which are a different artifact entirely.
99460
99584
  *
@@ -113181,6 +113305,10 @@ var HikvisionProviderAddon = class extends BaseDeviceProvider {
113181
113305
  const records = this.ctx.records;
113182
113306
  if (records === void 0) throw new Error("provider-hikvision: ctx.records is required (hub-only addon)");
113183
113307
  await records.declare(hikvisionRecordKinds);
113308
+ this.declareRegistrySwitch({
113309
+ kind: hikvisionConnectionsEntryKind,
113310
+ initialBody: (name) => ({ name })
113311
+ });
113184
113312
  await this.runMigrations(defaultIntegrationMigrations({
113185
113313
  addonId: this.addonId,
113186
113314
  date: HIKVISION_MIGRATIONS_DATE