@camstack/addon-mqtt-broker 1.2.152 → 1.2.154

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.
@@ -6028,7 +6028,7 @@ var ZodIssueCode = {
6028
6028
  var ZodFirstPartyTypeKind;
6029
6029
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
6030
6030
  //#endregion
6031
- //#region ../types/dist/sleep-BX_MqzUe.mjs
6031
+ //#region ../types/dist/sleep-CdKka2ri.mjs
6032
6032
  /**
6033
6033
  * The audio chunk plane's byte format, and the ONE expansion from a coded
6034
6034
  * window to float samples (D455).
@@ -6712,137 +6712,86 @@ async function runAddonMigrations(host, migrations, logger, options = {}) {
6712
6712
  blockOwner
6713
6713
  };
6714
6714
  }
6715
- /**
6716
- * Build a {@link DurableState} over a single store key. Transport-agnostic:
6717
- * `read`/`write` are the addon-store or device-store accessors. The whole
6718
- * validated value round-trips on every read/write — the schema is the
6719
- * single source of truth for what is persisted, so no hand-listed field
6720
- * set can drop a key on save.
6721
- */
6722
- function createDurableState(deps) {
6723
- const get = async () => {
6724
- const raw = (await deps.read())[deps.key];
6725
- if (raw === void 0) return deps.fallback;
6726
- const parsed = deps.schema.safeParse(raw);
6727
- if (!parsed.success) {
6728
- deps.onParseError?.(deps.key, parsed.error);
6729
- return deps.fallback;
6730
- }
6731
- return parsed.data;
6732
- };
6733
- const set = async (next) => {
6734
- const validated = deps.schema.parse(next);
6735
- await deps.write({ [deps.key]: validated });
6736
- };
6737
- const update = async (fn) => {
6738
- await set(fn(await get()));
6739
- };
6715
+ /** The record calls the one-switch migration makes, over the migration API. */
6716
+ function switchRecordsOverMigrationApi(api) {
6717
+ return { kind: (definition) => {
6718
+ const handle = api.records.kind(definition);
6719
+ return {
6720
+ get: (id) => handle.get({ id }),
6721
+ put: (input, opts) => handle.put({
6722
+ ...input,
6723
+ ...opts?.ifRev === void 0 ? {} : { ifRev: opts.ifRev }
6724
+ }),
6725
+ patch: (id, partial) => handle.patch({
6726
+ id,
6727
+ partial
6728
+ })
6729
+ };
6730
+ } };
6731
+ }
6732
+ function integrationRowsApiOver(api) {
6740
6733
  return {
6741
- get,
6742
- set,
6743
- update
6734
+ list: async () => (await api.integrations.list({})).integrations,
6735
+ readLegacyIntegrationRows: (input) => api.legacyRows.read(input),
6736
+ clearLegacyIntegrationRows: (input) => api.legacyRows.clear(input)
6744
6737
  };
6745
6738
  }
6746
- /**
6747
- * Per-node scoping for the shared addon-settings blob.
6748
- *
6749
- * An addon's settings store is hub-central (the `addon-settings` cap is
6750
- * hub-routed — the hub instance answers for every node), so fields whose
6751
- * value is a NODE fact (decoder backend, engine pick, probed hardware
6752
- * capabilities) persist under the node-scoped key `<key>@<nodeId>` inside
6753
- * the single shared blob. The SCHEMA field key stays bare: the write path
6754
- * ({@link scopePatch}) maps the bare field onto the target node's scoped
6755
- * key; the read/hydrate path ({@link projectStore}) maps THIS node's value
6756
- * back, so UI forms and `resolveConfig` only ever see the bare key.
6757
- *
6758
- * Fields opt in via the `perNode: true` schema marker on `ConfigFieldBase`
6759
- * (`interfaces/config-ui.ts`); `BaseAddon` derives the key set from the
6760
- * schema and routes reads/writes through these helpers.
6761
- *
6762
- * ## No bare-key fallback — deliberate
6763
- *
6764
- * {@link readNodeValue} reads the node-scoped key ONLY. A node with no
6765
- * scoped key resolves to `undefined` so the field's schema `default` wins —
6766
- * NEVER `store[base]` and never another node's value. A bare legacy key in
6767
- * the store is invisible to every node, hub included, so one node's
6768
- * selection can never leak onto another. (This generalizes the
6769
- * `decoder-backend-keys.ts` semantics — the no-fallback variant — over an
6770
- * arbitrary set of per-node field keys.)
6771
- *
6772
- * Pure functions only — no I/O, no imports beyond the language. This is a
6773
- * LEAF module: import it via its deep path, never from the root barrel.
6774
- */
6775
- /**
6776
- * Normalize a raw kernel node id to the bare node id used for scoping.
6777
- * `localNodeId` can carry a `<node>/<addon>` suffix on forked child
6778
- * processes; per-node settings are per-NODE, so strip the addon segment.
6779
- * `undefined` / `null` / empty falls back to `'hub'`.
6780
- */
6781
- function normalizeNodeId(raw) {
6782
- if (raw === void 0 || raw === null || raw === "") return "hub";
6783
- const slashIdx = raw.indexOf("/");
6784
- if (slashIdx < 0) return raw;
6785
- const bare = raw.slice(0, slashIdx);
6786
- return bare === "" ? "hub" : bare;
6787
- }
6788
- /** The node-scoped store key for a per-node field: `<base>@<nodeId>`. */
6789
- function nodeScopedKey(base, nodeId) {
6790
- return `${base}@${normalizeNodeId(nodeId)}`;
6791
- }
6792
- /**
6793
- * Read a node's value for a per-node field from the raw shared store:
6794
- * the node-scoped key when present, otherwise `undefined`.
6795
- * Deliberately NO bare-key fallback (see module doc) — the caller lets the
6796
- * schema `default` win on `undefined`.
6797
- */
6798
- function readNodeValue(store, base, nodeId) {
6799
- return store[nodeScopedKey(base, nodeId)];
6800
- }
6801
- /**
6802
- * Re-map a UI/settings patch so every bare perNode field persists under the
6803
- * TARGET node's scoped key; all other keys pass through unchanged. Used on
6804
- * the write path so a save for one node never clobbers another node's value
6805
- * (and the bare key is never written). Returns a new object — the input
6806
- * patch is not mutated.
6807
- */
6808
- function scopePatch(patch, perNodeKeys, nodeId) {
6809
- const out = {};
6810
- for (const [key, value] of Object.entries(patch)) out[perNodeKeys.has(key) ? nodeScopedKey(key, nodeId) : key] = value;
6811
- return out;
6812
- }
6813
- /**
6814
- * Project the raw shared store onto the bare schema keys for ONE node so a
6815
- * UI schema (whose field keys are bare) hydrates from that node's own
6816
- * values:
6817
- *
6818
- * - EVERY `@`-scoped key (any node's) is dropped from the pass-through.
6819
- * - Every bare perNode key is dropped from the pass-through (a stray bare
6820
- * legacy key must never hydrate any node — no bare fallback).
6821
- * - THIS node's effective value ({@link readNodeValue}) is then laid onto
6822
- * each bare perNode key; when the node has no scoped key the bare key is
6823
- * left ABSENT so the field's schema `default` wins.
6824
- *
6825
- * Returns a new object — the input store is not mutated.
6826
- */
6827
- function projectStore(store, perNodeKeys, nodeId) {
6828
- const out = {};
6829
- for (const [key, value] of Object.entries(store)) {
6830
- if (key.includes("@")) continue;
6831
- if (perNodeKeys.has(key)) continue;
6832
- out[key] = value;
6739
+ var PREFIX = "records/";
6740
+ /** The base of every records failure. `detail` is the human part of the message. */
6741
+ var RecordsError = class extends Error {
6742
+ code;
6743
+ detail;
6744
+ constructor(code, detail) {
6745
+ super(`${PREFIX}${code}: ${detail}`);
6746
+ this.name = "RecordsError";
6747
+ this.code = code;
6748
+ this.detail = detail;
6833
6749
  }
6834
- for (const base of perNodeKeys) {
6835
- const value = readNodeValue(store, base, nodeId);
6836
- if (value !== void 0) out[base] = value;
6750
+ };
6751
+ /** The keychain could not store or serve a value: explicit, never an empty string. */
6752
+ var RecordSecretUnavailableError = class extends RecordsError {
6753
+ constructor(detail) {
6754
+ super("secret-unavailable", detail);
6755
+ this.name = "RecordSecretUnavailableError";
6837
6756
  }
6838
- return out;
6757
+ };
6758
+ var InvalidRecordError = class extends RecordsError {
6759
+ constructor(detail) {
6760
+ super("invalid-record", detail);
6761
+ this.name = "InvalidRecordError";
6762
+ }
6763
+ };
6764
+ /** A kind declaration the engine refuses (non-additive change, bad shape, wrong file). */
6765
+ var DeclarationRefusedError = class extends RecordsError {
6766
+ constructor(detail) {
6767
+ super("declaration-refused", detail);
6768
+ this.name = "DeclarationRefusedError";
6769
+ }
6770
+ };
6771
+ function linkTargetOf(meta) {
6772
+ if (typeof meta !== "object" || meta === null) return void 0;
6773
+ const link = Reflect.get(meta, "link");
6774
+ const parsed = LinkTargetSchema.safeParse(link);
6775
+ return parsed.success ? parsed.data : void 0;
6776
+ }
6777
+ var LinkTargetSchema = object({
6778
+ cap: string().min(1),
6779
+ kind: string().min(1).optional()
6780
+ });
6781
+ /** The links a kind declares, read from the meta of its body fields. */
6782
+ function linksOfKind(kind) {
6783
+ const schema = kind.schema;
6784
+ if (!(schema instanceof ZodObject)) return [];
6785
+ const links = [];
6786
+ for (const [field, fieldSchema] of Object.entries(schema.shape)) {
6787
+ const to = linkTargetOf(globalRegistry.get(fieldSchema));
6788
+ if (to !== void 0) links.push({
6789
+ field,
6790
+ to
6791
+ });
6792
+ }
6793
+ return links;
6839
6794
  }
6840
- /** Every scope, in the order the guard and the docs list them. */
6841
- var SCOPED_SETTINGS_SCOPES = [
6842
- "cluster",
6843
- "device-defaults",
6844
- "node"
6845
- ];
6846
6795
  /**
6847
6796
  * The address of one keychain value: `secret://<owner>/<scope>/<fieldPath>`.
6848
6797
  *
@@ -6977,6 +6926,643 @@ function parseSecretRef(ref) {
6977
6926
  fieldPath
6978
6927
  };
6979
6928
  }
6929
+ /** Limits and names of `ctx.records` (D881). One authority; the engine and the facade read it. */
6930
+ /** The files a kind may live in. `history` is device-history's (D850), never records. */
6931
+ var RECORD_DATABASES = ["settings", "events"];
6932
+ /** The classes of a kind: the `@durable` vocabulary, one authority (replaces the annotation). */
6933
+ var RECORD_CLASSES = [
6934
+ "config",
6935
+ "ledger",
6936
+ "audit",
6937
+ "mirror",
6938
+ "ephemeral"
6939
+ ];
6940
+ var RECORD_DEFAULT_MAX_DATA_BYTES = 64 * 1024;
6941
+ var RECORD_MAX_DATA_BYTES = 1024 * 1024;
6942
+ var RECORD_BATCH_MAX = 1e3;
6943
+ var RECORD_QUERY_MAX = 1e3;
6944
+ /** A kind in the `settings` file may not bound itself above this (D447: high volume is `events`). */
6945
+ var RECORD_SETTINGS_MAX_ROWS = 5e4;
6946
+ /** The `Column`-free proof prefix: a ref collection for a kind's secret fields. */
6947
+ var RECORD_SECRET_COLLECTION_PREFIX = "records:";
6948
+ /**
6949
+ * Secret fields of a record, addressed the way a Zod schema declares them
6950
+ * (`collectZodSecretPaths`): dotted keys, `[]` for "each element of this array"
6951
+ * (`auth.accessToken`, `headers[].value`).
6952
+ *
6953
+ * `{}` after a key means "each value of this map" (`applianceSecrets{}`): the map's own key
6954
+ * names the value (`applianceSecrets{fridge}`), so no id key is declared and a body that drops a
6955
+ * key releases exactly that key's secret.
6956
+ *
6957
+ * Array elements are matched by a DECLARED id key (`secretArrayKeys`:
6958
+ * `{ headers: 'name' }`), never by index, so reordering a list keeps every
6959
+ * keychain ref (the same rule as `arrayItemFieldPath`). The concrete path of a
6960
+ * leaf names its element: `headers[X-Api].value`.
6961
+ *
6962
+ * Pure and browser-safe. Nothing here mutates: every transform returns a new value.
6963
+ */
6964
+ /** The array prefixes (declared form, e.g. `headers` or `a.headers`) of a path. */
6965
+ function parseSecretPath(path) {
6966
+ if (path.length === 0) throw new InvalidRecordError("an empty secret path");
6967
+ return path.split(".").map((raw) => {
6968
+ const each = raw.endsWith("[]");
6969
+ const map = raw.endsWith("{}");
6970
+ const key = each || map ? raw.slice(0, -2) : raw;
6971
+ if (key.length === 0) throw new InvalidRecordError(`secret path "${path}" has an empty segment`);
6972
+ return {
6973
+ key,
6974
+ each,
6975
+ map
6976
+ };
6977
+ });
6978
+ }
6979
+ /** The declared array prefixes of `path` that need an id key (`headers`, `a.rows`). */
6980
+ function secretArrayPrefixes(path) {
6981
+ const segments = parseSecretPath(path);
6982
+ const prefixes = [];
6983
+ const walked = [];
6984
+ for (const segment of segments) {
6985
+ walked.push(segment.key);
6986
+ if (segment.each) prefixes.push(walked.join("."));
6987
+ }
6988
+ return prefixes;
6989
+ }
6990
+ function isRecord$6(value) {
6991
+ return typeof value === "object" && value !== null && !Array.isArray(value);
6992
+ }
6993
+ function elementId(element, idKey, declared, prefix) {
6994
+ const id = isRecord$6(element) ? element[idKey] : void 0;
6995
+ 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`);
6996
+ return id;
6997
+ }
6998
+ /**
6999
+ * Visit every secret leaf PRESENT in `data` (an absent branch has nothing to
7000
+ * visit). `replace` returns the new leaf value, or {@link REMOVE_LEAF}; the
7001
+ * result is a new body, `data` is untouched.
7002
+ */
7003
+ var REMOVE_LEAF = Symbol("remove-leaf");
7004
+ function mapAt(node, segments, index, walkedKeys, concretePrefix, declared, arrayKeys, visit) {
7005
+ if (!isRecord$6(node)) return node;
7006
+ const segment = segments[index];
7007
+ if (segment === void 0) return node;
7008
+ if (!Object.prototype.hasOwnProperty.call(node, segment.key)) return node;
7009
+ const child = node[segment.key];
7010
+ const keys = [...walkedKeys, segment.key];
7011
+ const last = index === segments.length - 1;
7012
+ if (segment.each) {
7013
+ if (!Array.isArray(child)) return node;
7014
+ const prefix = keys.join(".");
7015
+ const idKey = arrayKeys[prefix];
7016
+ if (idKey === void 0) throw new InvalidRecordError(`"${declared}": no id key declared for the array "${prefix}"`);
7017
+ const mapped = child.map((element) => {
7018
+ const id = elementId(element, idKey, declared, prefix);
7019
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}[${encodeURIComponent(id)}]`;
7020
+ return last ? element : mapAt(element, segments, index + 1, keys, concrete, declared, arrayKeys, visit);
7021
+ });
7022
+ return {
7023
+ ...node,
7024
+ [segment.key]: mapped
7025
+ };
7026
+ }
7027
+ if (segment.map) {
7028
+ if (!isRecord$6(child)) return node;
7029
+ const kept = Object.entries(child).map(([mapKey, value]) => {
7030
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}{${encodeURIComponent(mapKey)}}`;
7031
+ if (!last) return [mapKey, mapAt(value, segments, index + 1, keys, concrete, declared, arrayKeys, visit)];
7032
+ return [mapKey, visit({
7033
+ declared,
7034
+ concrete,
7035
+ value
7036
+ })];
7037
+ }).filter(([, value]) => value !== REMOVE_LEAF);
7038
+ return {
7039
+ ...node,
7040
+ [segment.key]: Object.fromEntries(kept)
7041
+ };
7042
+ }
7043
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}`;
7044
+ if (last) {
7045
+ const replacement = visit({
7046
+ declared,
7047
+ concrete,
7048
+ value: child
7049
+ });
7050
+ if (replacement === REMOVE_LEAF) return Object.fromEntries(Object.entries(node).filter(([key]) => key !== segment.key));
7051
+ return {
7052
+ ...node,
7053
+ [segment.key]: replacement
7054
+ };
7055
+ }
7056
+ return {
7057
+ ...node,
7058
+ [segment.key]: mapAt(child, segments, index + 1, keys, concrete, declared, arrayKeys, visit)
7059
+ };
7060
+ }
7061
+ /** Replace/remove every present secret leaf; returns a NEW body. */
7062
+ function mapSecretLeaves(data, paths, arrayKeys, visit) {
7063
+ let current = data;
7064
+ for (const declared of paths) current = mapAt(current, parseSecretPath(declared), 0, [], "", declared, arrayKeys, visit);
7065
+ return current;
7066
+ }
7067
+ /**
7068
+ * The keychain collection name a kind's secrets live under. Prefixed so a
7069
+ * record's refs never collide with the refs a legacy collection of the same name
7070
+ * already holds during an adoption.
7071
+ */
7072
+ function recordSecretCollection(kind) {
7073
+ return `${RECORD_SECRET_COLLECTION_PREFIX}${kind}`;
7074
+ }
7075
+ /** The ONE ref a row's secret field may carry: the engine and the facade both build it here. */
7076
+ function recordSecretRef(owner, kind, rowId, concretePath) {
7077
+ return buildSecretRef({
7078
+ owner,
7079
+ scope: {
7080
+ kind: "row",
7081
+ collection: recordSecretCollection(kind),
7082
+ rowId
7083
+ },
7084
+ fieldPath: concretePath
7085
+ });
7086
+ }
7087
+ /**
7088
+ * A stored secret, as an admin read shows it: a VIEW naming the row's own
7089
+ * keychain ref (`set: true`), never the value and no longer the bare redaction
7090
+ * token. The form hands it to the secret field, which reveals the value by ref
7091
+ * through the audited `keychain-admin.reveal`; sent back untouched it keeps the
7092
+ * stored secret (the records door reads a view as KEEP).
7093
+ *
7094
+ * ONE implementation for the entries service and for every addon that serves
7095
+ * its own instances (`RecordIntegrationInstances`).
7096
+ */
7097
+ function isRecord$5(value) {
7098
+ return typeof value === "object" && value !== null && !Array.isArray(value);
7099
+ }
7100
+ function secretViewsOf(owner, kind, id, decl, data) {
7101
+ if (decl.secretPaths.length === 0) return data;
7102
+ const shown = mapSecretLeaves(data, decl.secretPaths, decl.secretArrayKeys, (leaf) => {
7103
+ if (leaf.value !== "__camstack_redacted__") return leaf.value;
7104
+ return {
7105
+ $secret: recordSecretRef(owner, kind, id, leaf.concrete),
7106
+ v: 1,
7107
+ set: true
7108
+ };
7109
+ });
7110
+ return isRecord$5(shown) ? shown : data;
7111
+ }
7112
+ /** The most instances one addon lists (an integrations page, not a table). */
7113
+ var INSTANCES_LIST_MAX = 1e3;
7114
+ /**
7115
+ * The ONE reader of an instance's switch (D996): an absent field means on, so a row written
7116
+ * before the field existed needs no migration. Every consumer of an instance body asks this.
7117
+ */
7118
+ function isInstanceEnabled(body) {
7119
+ return body.enabled !== false;
7120
+ }
7121
+ /** The body key of the switch; only {@link RecordIntegrationInstances.setInstanceEnabled} writes it. */
7122
+ var SWITCH_KEY = "enabled";
7123
+ /** The keys of the kind's secret fields that sit at the top level of the body. */
7124
+ function topLevelSecretKeys(paths) {
7125
+ return new Set(paths.filter((p) => !p.includes(".") && !p.includes("[") && !p.includes("{")));
7126
+ }
7127
+ /** The keys of the kind's top-level MAPS whose values are secrets (`applianceSecrets{}`). */
7128
+ function secretMapKeys(paths) {
7129
+ return new Set(paths.filter((p) => p.endsWith("{}") && !p.slice(0, -2).match(/[.[{]/)).map((p) => p.slice(0, -2)));
7130
+ }
7131
+ /**
7132
+ * A patch value for a map of secrets: an entry that is omitted, `''`, the redaction token or the
7133
+ * view the form was given KEEPS its stored secret (it is left out of the merge); `{ $secretClear }`
7134
+ * or `null` removes the entry; any other string replaces it. Null when nothing is left to merge.
7135
+ */
7136
+ function secretMapPatch(value) {
7137
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
7138
+ const out = {};
7139
+ for (const [key, entry] of Object.entries(value)) if (entry === null || isSecretClear(entry)) out[key] = null;
7140
+ else if (typeof entry === "string" && entry !== "" && entry !== "__camstack_redacted__" && !isSecretFieldView(entry)) out[key] = entry;
7141
+ return Object.keys(out).length > 0 ? out : null;
7142
+ }
7143
+ var RecordIntegrationInstances = class {
7144
+ records;
7145
+ kind;
7146
+ hooks;
7147
+ handle;
7148
+ secretKeys;
7149
+ secretMaps;
7150
+ nameField;
7151
+ switchListeners = /* @__PURE__ */ new Set();
7152
+ constructor(records, kind, hooks) {
7153
+ this.records = records;
7154
+ this.kind = kind;
7155
+ this.hooks = hooks;
7156
+ this.handle = records.kind(kind);
7157
+ this.secretKeys = topLevelSecretKeys(kind.declaration.secretPaths);
7158
+ this.secretMaps = secretMapKeys(kind.declaration.secretPaths);
7159
+ this.nameField = kind.declaration.entry?.nameField ?? "name";
7160
+ }
7161
+ /**
7162
+ * One instance read for the addon's own runtime; null when absent. When the keychain is
7163
+ * locked the row is served WITHOUT its secrets and says so (`secrets: 'unavailable'`), so the
7164
+ * caller can keep what it had instead of reconfiguring with an empty secret (D49).
7165
+ */
7166
+ async readResolved(id) {
7167
+ try {
7168
+ const record = await this.handle.getResolved(id);
7169
+ return record === null ? null : {
7170
+ id,
7171
+ body: record.data,
7172
+ enabled: isInstanceEnabled(record.data),
7173
+ secrets: "resolved"
7174
+ };
7175
+ } catch (err) {
7176
+ if (!(err instanceof RecordSecretUnavailableError)) throw err;
7177
+ const stored = await this.handle.get(id);
7178
+ if (stored === null) return null;
7179
+ return {
7180
+ id,
7181
+ body: Object.fromEntries(Object.entries(stored.data).filter(([key]) => !this.secretKeys.has(key))),
7182
+ enabled: isInstanceEnabled(stored.data),
7183
+ secrets: "unavailable"
7184
+ };
7185
+ }
7186
+ }
7187
+ /** The body of {@link readResolved} alone; a locked keychain yields the row without secrets. */
7188
+ async getResolved(id) {
7189
+ return (await this.readResolved(id))?.body ?? null;
7190
+ }
7191
+ /** Every instance, secrets resolved where the keychain allows; an absent one is skipped. */
7192
+ async listResolved() {
7193
+ const page = await this.handle.query({ limit: INSTANCES_LIST_MAX });
7194
+ const out = [];
7195
+ for (const record of page.records) {
7196
+ const read = await this.readResolved(record.id);
7197
+ if (read !== null) out.push(read);
7198
+ }
7199
+ return out;
7200
+ }
7201
+ viewOf(record) {
7202
+ const shown = secretViewsOf(this.records.owner, this.kind.name, record.id, this.kind.declaration, record.data);
7203
+ const rawName = record.data[this.nameField];
7204
+ const kind = this.hooks.kindOf?.(record.data);
7205
+ const health = this.hooks.health?.(record.data, record.id);
7206
+ return {
7207
+ id: record.id,
7208
+ name: typeof rawName === "string" ? rawName : record.id,
7209
+ configured: this.hooks.configured(record.data),
7210
+ enabled: isInstanceEnabled(record.data),
7211
+ formValues: shown,
7212
+ ...kind !== void 0 ? { kind } : {},
7213
+ ...health?.status !== void 0 ? { status: health.status } : {},
7214
+ ...health?.lastCheckedAt !== void 0 ? { lastCheckedAt: health.lastCheckedAt } : {}
7215
+ };
7216
+ }
7217
+ describe = async () => {
7218
+ const declared = linksOfKind(this.kind);
7219
+ const links = this.hooks.description.links !== void 0 || declared.length === 0 ? {} : { links: declared.map((link) => ({
7220
+ kind: this.kind.name,
7221
+ field: link.field,
7222
+ to: link.to
7223
+ })) };
7224
+ return {
7225
+ ...this.hooks.description,
7226
+ ...links,
7227
+ ...this.hooks.mintId === void 0 ? {} : { mintsId: true }
7228
+ };
7229
+ };
7230
+ instanceFormSchema = async ({ id }) => this.hooks.formSchema(id);
7231
+ listInstances = async () => {
7232
+ return (await this.handle.query({ limit: INSTANCES_LIST_MAX })).records.map((record) => this.viewOf(record));
7233
+ };
7234
+ getInstance = async ({ id }) => {
7235
+ const record = await this.handle.get(id);
7236
+ return record === null ? null : this.viewOf(record);
7237
+ };
7238
+ /** Insert ONE row (`ifRev: 0`: an existing id is refused, never overwritten). */
7239
+ createInstance = async ({ id, name, kind, values }) => {
7240
+ const minted = id ?? this.hooks.mintId?.({
7241
+ name,
7242
+ ...kind !== void 0 ? { kind } : {}
7243
+ });
7244
+ if (minted === void 0) throw new Error("createInstance needs an id: this provider does not mint one");
7245
+ await this.handle.put({
7246
+ id: minted,
7247
+ data: this.hooks.initialBody(name, kind)
7248
+ }, { ifRev: 0 });
7249
+ const patch = this.patchOf(values ?? {});
7250
+ if (Object.keys(patch).length > 0) await this.handle.patch(minted, patch);
7251
+ await this.hooks.onChanged?.(minted, "created");
7252
+ return { id: minted };
7253
+ };
7254
+ updateInstance = async ({ id, name, values }) => {
7255
+ const patch = this.patchOf(values);
7256
+ if (name !== void 0) patch[this.nameField] = name;
7257
+ await this.handle.patch(id, patch);
7258
+ await this.hooks.onChanged?.(id, "updated");
7259
+ return { ok: true };
7260
+ };
7261
+ /** The record patch a form `values` object means: secrets kept, cleared or replaced. */
7262
+ patchOf(values) {
7263
+ const patch = {};
7264
+ for (const [key, value] of Object.entries(values)) {
7265
+ if (value === void 0) continue;
7266
+ if (key === "enabled") continue;
7267
+ if (this.secretMaps.has(key)) {
7268
+ const entries = secretMapPatch(value);
7269
+ if (entries !== null) patch[key] = entries;
7270
+ } else if (!this.secretKeys.has(key)) patch[key] = value;
7271
+ else if (isSecretClear(value)) patch[key] = null;
7272
+ else if (typeof value === "string" && value !== "" && value !== "__camstack_redacted__" && !isSecretFieldView(value)) patch[key] = value;
7273
+ }
7274
+ return patch;
7275
+ }
7276
+ /**
7277
+ * Listen to the switch of ANY instance of this helper (in the process that serves it). The
7278
+ * durable replacement of the `integration.enabled` / `integration.disabled` events (D8): the
7279
+ * addon reconciles from the record, whichever way it flipped.
7280
+ */
7281
+ onSwitched(listener) {
7282
+ this.switchListeners.add(listener);
7283
+ }
7284
+ /**
7285
+ * The ONE writer of the switch (D996, D1014): the record body's `enabled`, for every role. A
7286
+ * configured thing is an instance, so an id with no record yet (a default integration that was
7287
+ * never configured) gets its record from `initialBody` before the switch is written.
7288
+ */
7289
+ setInstanceEnabled = async ({ id, enabled }) => {
7290
+ if (await this.handle.get(id) === null) await this.handle.put({
7291
+ id,
7292
+ data: this.hooks.initialBody(id)
7293
+ }, { ifRev: 0 });
7294
+ await this.handle.patch(id, { [SWITCH_KEY]: enabled });
7295
+ await this.hooks.onChanged?.(id, "enabled");
7296
+ for (const listener of this.switchListeners) await listener(id, enabled);
7297
+ return { ok: true };
7298
+ };
7299
+ /** The row and its keychain refs go together (the records door). */
7300
+ deleteInstance = async ({ id }) => {
7301
+ await this.handle.delete(id);
7302
+ await this.hooks.onChanged?.(id, "deleted");
7303
+ return { ok: true };
7304
+ };
7305
+ testInstance = async (input) => {
7306
+ if (this.hooks.test === void 0) return {
7307
+ success: false,
7308
+ status: "unsupported",
7309
+ error: "This integration declares no connection test"
7310
+ };
7311
+ return this.hooks.test(input);
7312
+ };
7313
+ /** The flat provider object to hand to `registerProvider`. */
7314
+ toProvider() {
7315
+ return {
7316
+ describe: this.describe,
7317
+ instanceFormSchema: this.instanceFormSchema,
7318
+ listInstances: this.listInstances,
7319
+ getInstance: this.getInstance,
7320
+ createInstance: this.createInstance,
7321
+ updateInstance: this.updateInstance,
7322
+ setInstanceEnabled: this.setInstanceEnabled,
7323
+ deleteInstance: this.deleteInstance,
7324
+ testInstance: this.testInstance
7325
+ };
7326
+ }
7327
+ };
7328
+ /**
7329
+ * The one-switch migration (epic #440, step 3). An integration's on/off state used to live in the
7330
+ * registry's `enabled` column for a device addon; it now lives only in the instance record's
7331
+ * body (`enabled`, D1007 superseded). This moves a registry `enabled = false` into the body, once.
7332
+ *
7333
+ * For every registry row of the addon that is OFF:
7334
+ * - no record under its id: the record is created from `initialBody(name)` with `enabled: false`
7335
+ * (a default integration that never had settings, Reolink's among them);
7336
+ * - a record whose body states no `enabled`: `enabled: false` is written into it;
7337
+ * - a record that already states `enabled` (either way) is the newer truth and is left alone.
7338
+ * A row that is ON writes nothing: an absent field reads as on. A rerun finds every off row with
7339
+ * a stated switch and does nothing, so nothing switched off comes back on and nothing switched on
7340
+ * goes off. The registry column itself is neither read afterwards nor written; its drop is step 5.
7341
+ *
7342
+ * It runs in the addon process, BEFORE the addon registers its `integration-instances` provider,
7343
+ * which is also why `integrations.list` still answers the stored column at that point.
7344
+ */
7345
+ function registrySwitchToBodyId(addonId, date) {
7346
+ return `${addonId}/${date}-registry-switch-to-body`;
7347
+ }
7348
+ async function moveRegistrySwitchToBody(ports, spec) {
7349
+ const rows = await ports.listIntegrations(spec.addonId);
7350
+ let created = 0;
7351
+ let switched = 0;
7352
+ let kept = 0;
7353
+ for (const row of rows) {
7354
+ if (row.enabled) continue;
7355
+ const body = await ports.readBody(row.id);
7356
+ if (body === null) {
7357
+ if (await ports.createRecord(row.id, {
7358
+ ...spec.initialBody(row.name),
7359
+ ["enabled"]: false
7360
+ }) === "created") created += 1;
7361
+ else kept += 1;
7362
+ continue;
7363
+ }
7364
+ if ("enabled" in body) {
7365
+ kept += 1;
7366
+ continue;
7367
+ }
7368
+ await ports.switchOff(row.id);
7369
+ switched += 1;
7370
+ }
7371
+ const summary = {
7372
+ integrations: rows.length,
7373
+ off: rows.filter((r) => !r.enabled).length,
7374
+ created,
7375
+ switched,
7376
+ kept
7377
+ };
7378
+ return created === 0 && switched === 0 ? {
7379
+ outcome: "already-done",
7380
+ summary
7381
+ } : {
7382
+ outcome: "done",
7383
+ summary
7384
+ };
7385
+ }
7386
+ /** A migration entry: an addon states its kind and how a new body starts, nothing else. */
7387
+ function registrySwitchToBodyMigration(spec) {
7388
+ return {
7389
+ meta: {
7390
+ id: registrySwitchToBodyId(spec.addonId, spec.date),
7391
+ owner: spec.addonId,
7392
+ level: "addon-state",
7393
+ seq: spec.seq,
7394
+ dependsOn: [],
7395
+ store: "settings",
7396
+ scope: "cluster",
7397
+ onFailure: "block-owner",
7398
+ bodyKind: "procedure",
7399
+ description: "Move the registry enabled flag of every switched-off integration into its instance record body, creating the record when there is none",
7400
+ fixtureMark: "enabled"
7401
+ },
7402
+ procedure: (ports) => moveRegistrySwitchToBody(ports, {
7403
+ addonId: spec.addonId,
7404
+ initialBody: spec.initialBody
7405
+ })
7406
+ };
7407
+ }
7408
+ /** The hub and records sides of {@link registrySwitchToBodyMigration}. */
7409
+ function registrySwitchPortsOver(deps) {
7410
+ const handle = deps.records.kind({
7411
+ name: deps.kind.name,
7412
+ declaration: deps.kind.declaration,
7413
+ schema: record(string(), unknown())
7414
+ });
7415
+ return {
7416
+ listIntegrations: async (addonId) => (await deps.api.list()).filter((i) => i.addonId === addonId).map((i) => ({
7417
+ id: i.id,
7418
+ name: i.name,
7419
+ enabled: i.enabled !== false
7420
+ })),
7421
+ readBody: async (id) => (await handle.get(id))?.data ?? null,
7422
+ createRecord: async (id, body) => {
7423
+ if (await handle.get(id) !== null) return "exists";
7424
+ await handle.put({
7425
+ id,
7426
+ data: body
7427
+ }, { ifRev: 0 });
7428
+ return "created";
7429
+ },
7430
+ switchOff: async (id) => {
7431
+ await handle.patch(id, { [SWITCH_KEY]: false });
7432
+ }
7433
+ };
7434
+ }
7435
+ /**
7436
+ * Build a {@link DurableState} over a single store key. Transport-agnostic:
7437
+ * `read`/`write` are the addon-store or device-store accessors. The whole
7438
+ * validated value round-trips on every read/write — the schema is the
7439
+ * single source of truth for what is persisted, so no hand-listed field
7440
+ * set can drop a key on save.
7441
+ */
7442
+ function createDurableState(deps) {
7443
+ const get = async () => {
7444
+ const raw = (await deps.read())[deps.key];
7445
+ if (raw === void 0) return deps.fallback;
7446
+ const parsed = deps.schema.safeParse(raw);
7447
+ if (!parsed.success) {
7448
+ deps.onParseError?.(deps.key, parsed.error);
7449
+ return deps.fallback;
7450
+ }
7451
+ return parsed.data;
7452
+ };
7453
+ const set = async (next) => {
7454
+ const validated = deps.schema.parse(next);
7455
+ await deps.write({ [deps.key]: validated });
7456
+ };
7457
+ const update = async (fn) => {
7458
+ await set(fn(await get()));
7459
+ };
7460
+ return {
7461
+ get,
7462
+ set,
7463
+ update
7464
+ };
7465
+ }
7466
+ /**
7467
+ * Per-node scoping for the shared addon-settings blob.
7468
+ *
7469
+ * An addon's settings store is hub-central (the `addon-settings` cap is
7470
+ * hub-routed — the hub instance answers for every node), so fields whose
7471
+ * value is a NODE fact (decoder backend, engine pick, probed hardware
7472
+ * capabilities) persist under the node-scoped key `<key>@<nodeId>` inside
7473
+ * the single shared blob. The SCHEMA field key stays bare: the write path
7474
+ * ({@link scopePatch}) maps the bare field onto the target node's scoped
7475
+ * key; the read/hydrate path ({@link projectStore}) maps THIS node's value
7476
+ * back, so UI forms and `resolveConfig` only ever see the bare key.
7477
+ *
7478
+ * Fields opt in via the `perNode: true` schema marker on `ConfigFieldBase`
7479
+ * (`interfaces/config-ui.ts`); `BaseAddon` derives the key set from the
7480
+ * schema and routes reads/writes through these helpers.
7481
+ *
7482
+ * ## No bare-key fallback — deliberate
7483
+ *
7484
+ * {@link readNodeValue} reads the node-scoped key ONLY. A node with no
7485
+ * scoped key resolves to `undefined` so the field's schema `default` wins —
7486
+ * NEVER `store[base]` and never another node's value. A bare legacy key in
7487
+ * the store is invisible to every node, hub included, so one node's
7488
+ * selection can never leak onto another. (This generalizes the
7489
+ * `decoder-backend-keys.ts` semantics — the no-fallback variant — over an
7490
+ * arbitrary set of per-node field keys.)
7491
+ *
7492
+ * Pure functions only — no I/O, no imports beyond the language. This is a
7493
+ * LEAF module: import it via its deep path, never from the root barrel.
7494
+ */
7495
+ /**
7496
+ * Normalize a raw kernel node id to the bare node id used for scoping.
7497
+ * `localNodeId` can carry a `<node>/<addon>` suffix on forked child
7498
+ * processes; per-node settings are per-NODE, so strip the addon segment.
7499
+ * `undefined` / `null` / empty falls back to `'hub'`.
7500
+ */
7501
+ function normalizeNodeId(raw) {
7502
+ if (raw === void 0 || raw === null || raw === "") return "hub";
7503
+ const slashIdx = raw.indexOf("/");
7504
+ if (slashIdx < 0) return raw;
7505
+ const bare = raw.slice(0, slashIdx);
7506
+ return bare === "" ? "hub" : bare;
7507
+ }
7508
+ /** The node-scoped store key for a per-node field: `<base>@<nodeId>`. */
7509
+ function nodeScopedKey(base, nodeId) {
7510
+ return `${base}@${normalizeNodeId(nodeId)}`;
7511
+ }
7512
+ /**
7513
+ * Read a node's value for a per-node field from the raw shared store:
7514
+ * the node-scoped key when present, otherwise `undefined`.
7515
+ * Deliberately NO bare-key fallback (see module doc) — the caller lets the
7516
+ * schema `default` win on `undefined`.
7517
+ */
7518
+ function readNodeValue(store, base, nodeId) {
7519
+ return store[nodeScopedKey(base, nodeId)];
7520
+ }
7521
+ /**
7522
+ * Re-map a UI/settings patch so every bare perNode field persists under the
7523
+ * TARGET node's scoped key; all other keys pass through unchanged. Used on
7524
+ * the write path so a save for one node never clobbers another node's value
7525
+ * (and the bare key is never written). Returns a new object — the input
7526
+ * patch is not mutated.
7527
+ */
7528
+ function scopePatch(patch, perNodeKeys, nodeId) {
7529
+ const out = {};
7530
+ for (const [key, value] of Object.entries(patch)) out[perNodeKeys.has(key) ? nodeScopedKey(key, nodeId) : key] = value;
7531
+ return out;
7532
+ }
7533
+ /**
7534
+ * Project the raw shared store onto the bare schema keys for ONE node so a
7535
+ * UI schema (whose field keys are bare) hydrates from that node's own
7536
+ * values:
7537
+ *
7538
+ * - EVERY `@`-scoped key (any node's) is dropped from the pass-through.
7539
+ * - Every bare perNode key is dropped from the pass-through (a stray bare
7540
+ * legacy key must never hydrate any node — no bare fallback).
7541
+ * - THIS node's effective value ({@link readNodeValue}) is then laid onto
7542
+ * each bare perNode key; when the node has no scoped key the bare key is
7543
+ * left ABSENT so the field's schema `default` wins.
7544
+ *
7545
+ * Returns a new object — the input store is not mutated.
7546
+ */
7547
+ function projectStore(store, perNodeKeys, nodeId) {
7548
+ const out = {};
7549
+ for (const [key, value] of Object.entries(store)) {
7550
+ if (key.includes("@")) continue;
7551
+ if (perNodeKeys.has(key)) continue;
7552
+ out[key] = value;
7553
+ }
7554
+ for (const base of perNodeKeys) {
7555
+ const value = readNodeValue(store, base, nodeId);
7556
+ if (value !== void 0) out[base] = value;
7557
+ }
7558
+ return out;
7559
+ }
7560
+ /** Every scope, in the order the guard and the docs list them. */
7561
+ var SCOPED_SETTINGS_SCOPES = [
7562
+ "cluster",
7563
+ "device-defaults",
7564
+ "node"
7565
+ ];
6980
7566
  /** A write to a secret path could not be stored in the keychain, so it was refused. */
6981
7567
  var KeychainWriteRefusedError = class extends Error {
6982
7568
  fieldPath;
@@ -6987,7 +7573,7 @@ var KeychainWriteRefusedError = class extends Error {
6987
7573
  }
6988
7574
  };
6989
7575
  var KEEP = { kind: "keep" };
6990
- function isRecord$6(value) {
7576
+ function isRecord$4(value) {
6991
7577
  return typeof value === "object" && value !== null && !Array.isArray(value);
6992
7578
  }
6993
7579
  function defaultMintId() {
@@ -7000,7 +7586,7 @@ function collectSecretMarkerRefs(value, out = []) {
7000
7586
  return out;
7001
7587
  }
7002
7588
  if (Array.isArray(value)) for (const item of value) collectSecretMarkerRefs(item, out);
7003
- else if (isRecord$6(value)) for (const child of Object.values(value)) collectSecretMarkerRefs(child, out);
7589
+ else if (isRecord$4(value)) for (const child of Object.values(value)) collectSecretMarkerRefs(child, out);
7004
7590
  return out;
7005
7591
  }
7006
7592
  async function storedValueEquals(secrets, marker, candidate) {
@@ -7055,7 +7641,7 @@ function rowId(row, idKey) {
7055
7641
  return null;
7056
7642
  }
7057
7643
  async function writeArray(ctx, node, incoming, stored, fieldPath) {
7058
- const storedRows = Array.isArray(stored) ? stored.filter(isRecord$6) : [];
7644
+ const storedRows = Array.isArray(stored) ? stored.filter(isRecord$4) : [];
7059
7645
  if (!Array.isArray(incoming)) {
7060
7646
  ctx.deletes.push(...collectSecretMarkerRefs(storedRows));
7061
7647
  return {
@@ -7071,7 +7657,7 @@ async function writeArray(ctx, node, incoming, stored, fieldPath) {
7071
7657
  const kept = /* @__PURE__ */ new Set();
7072
7658
  const rows = [];
7073
7659
  for (const row of incoming) {
7074
- if (!isRecord$6(row)) {
7660
+ if (!isRecord$4(row)) {
7075
7661
  rows.push(row);
7076
7662
  continue;
7077
7663
  }
@@ -7096,7 +7682,7 @@ async function writeNode(ctx, node, incoming, stored, fieldPath) {
7096
7682
  case "leaf": return writeLeaf(ctx, incoming, stored, fieldPath);
7097
7683
  case "array": return writeArray(ctx, node, incoming, stored, fieldPath);
7098
7684
  case "object": {
7099
- if (!isRecord$6(incoming)) {
7685
+ if (!isRecord$4(incoming)) {
7100
7686
  if (incoming === void 0) return KEEP;
7101
7687
  ctx.deletes.push(...collectSecretMarkerRefs(stored));
7102
7688
  return {
@@ -7104,7 +7690,7 @@ async function writeNode(ctx, node, incoming, stored, fieldPath) {
7104
7690
  value: incoming
7105
7691
  };
7106
7692
  }
7107
- const storedObj = isRecord$6(stored) ? stored : {};
7693
+ const storedObj = isRecord$4(stored) ? stored : {};
7108
7694
  return {
7109
7695
  kind: "value",
7110
7696
  value: await writeMembers(ctx, node.children, incoming, storedObj, (m) => `${fieldPath}.${m}`)
@@ -7227,7 +7813,7 @@ async function resolveSecretMarkers(value, secrets, options = {}) {
7227
7813
  value: items
7228
7814
  };
7229
7815
  }
7230
- if (isRecord$6(v)) {
7816
+ if (isRecord$4(v)) {
7231
7817
  const out = {};
7232
7818
  for (const [k, child] of Object.entries(v)) {
7233
7819
  const s = substitute(child);
@@ -7259,7 +7845,7 @@ var SecretOverwriteRefusedError = class extends Error {
7259
7845
  this.name = "SecretOverwriteRefusedError";
7260
7846
  }
7261
7847
  };
7262
- function isRecord$5(value) {
7848
+ function isRecord$3(value) {
7263
7849
  return typeof value === "object" && value !== null && !Array.isArray(value);
7264
7850
  }
7265
7851
  function resolvedValue(pass, marker) {
@@ -7288,7 +7874,7 @@ function inArray(pass, incoming, stored) {
7288
7874
  return incoming.map((item, index) => {
7289
7875
  const twin = stored[index];
7290
7876
  if (isSecretMarker(twin)) return typeof item === "string" && item === resolvedValue(pass, twin) ? twin : item;
7291
- if (isRecord$5(item) && isRecord$5(twin)) return inArrayRow(pass, item, twin);
7877
+ if (isRecord$3(item) && isRecord$3(twin)) return inArrayRow(pass, item, twin);
7292
7878
  if (Array.isArray(item) && Array.isArray(twin)) return inArray(pass, item, twin);
7293
7879
  return item;
7294
7880
  });
@@ -7299,7 +7885,7 @@ function inArrayRow(pass, incoming, stored) {
7299
7885
  const twin = stored[key];
7300
7886
  if (isSecretMarker(twin)) {
7301
7887
  if (typeof value === "string" && value === resolvedValue(pass, twin)) out[key] = twin;
7302
- } else if (isRecord$5(value) && isRecord$5(twin)) out[key] = inArrayRow(pass, value, twin);
7888
+ } else if (isRecord$3(value) && isRecord$3(twin)) out[key] = inArrayRow(pass, value, twin);
7303
7889
  else if (Array.isArray(value) && Array.isArray(twin)) out[key] = inArray(pass, value, twin);
7304
7890
  }
7305
7891
  return out;
@@ -7307,7 +7893,7 @@ function inArrayRow(pass, incoming, stored) {
7307
7893
  async function walk(pass, incoming, stored) {
7308
7894
  if (isSecretMarker(stored)) return atMarker(pass, incoming, stored);
7309
7895
  if (Array.isArray(incoming) && Array.isArray(stored)) return inArray(pass, incoming, stored);
7310
- if (!isRecord$5(incoming) || !isRecord$5(stored)) return incoming;
7896
+ if (!isRecord$3(incoming) || !isRecord$3(stored)) return incoming;
7311
7897
  const out = { ...incoming };
7312
7898
  for (const [key, value] of Object.entries(incoming)) out[key] = await walk(pass, value, stored[key]);
7313
7899
  return out;
@@ -7338,7 +7924,7 @@ async function restoreUnchangedSecrets(input) {
7338
7924
  function isJsonEqual(a, b) {
7339
7925
  if (Object.is(a, b)) return true;
7340
7926
  if (Array.isArray(a)) return Array.isArray(b) && a.length === b.length && a.every((v, i) => isJsonEqual(v, b[i]));
7341
- if (isRecord$5(a) && isRecord$5(b)) {
7927
+ if (isRecord$3(a) && isRecord$3(b)) {
7342
7928
  const keys = Object.keys(a);
7343
7929
  if (keys.length !== Object.keys(b).length) return false;
7344
7930
  return keys.every((k) => Object.prototype.hasOwnProperty.call(b, k) && isJsonEqual(a[k], b[k]));
@@ -7362,7 +7948,7 @@ function markerKeysOf(blob, owner) {
7362
7948
  }
7363
7949
  function nodeFromStored(value, owner) {
7364
7950
  if (isSecretMarker(value)) return isSecretRefOwnedBy(value.$secret, owner) ? { kind: "leaf" } : null;
7365
- if (!isRecord$5(value)) return null;
7951
+ if (!isRecord$3(value)) return null;
7366
7952
  const children = /* @__PURE__ */ new Map();
7367
7953
  for (const [key, child] of Object.entries(value)) {
7368
7954
  const node = nodeFromStored(child, owner);
@@ -7859,13 +8445,48 @@ var BaseAddon = class {
7859
8445
  if (api === void 0) throw new Error(`${this.ctx.id}: the migration API is not available on this context`);
7860
8446
  return this.runBound(sets.flatMap((set) => set.bind(api)), options);
7861
8447
  }
7862
- async runBound(migrations, options) {
8448
+ /**
8449
+ * A device addon states its instance kind once, before its migrations run, and the one-switch
8450
+ * migration (registry `enabled` to the instance body, epic #440 step 3) joins whatever
8451
+ * catalogue the addon runs, in the SAME declaration (the engine replaces an owner's catalogue
8452
+ * on every declare).
8453
+ */
8454
+ declareRegistrySwitch(spec) {
8455
+ this.registrySwitchSpec = spec;
8456
+ }
8457
+ registrySwitchSpec = null;
8458
+ registrySwitchBound() {
8459
+ const spec = this.registrySwitchSpec;
8460
+ if (spec === null) return [];
8461
+ const api = this.ctx.migrationApi;
8462
+ if (api === void 0) {
8463
+ this.ctx.logger.warn("the registry switch migration is skipped: the migration API is not available on this context");
8464
+ return [];
8465
+ }
8466
+ return migrationSet([registrySwitchToBodyMigration({
8467
+ addonId: this.ctx.id,
8468
+ date: "2026-11-06",
8469
+ seq: 1e3,
8470
+ initialBody: spec.initialBody
8471
+ })], (a) => registrySwitchPortsOver({
8472
+ api: integrationRowsApiOver(a),
8473
+ records: switchRecordsOverMigrationApi(a),
8474
+ kind: spec.kind
8475
+ })).bind(api);
8476
+ }
8477
+ async runBound(declared, options) {
8478
+ const added = this.registrySwitchBound();
8479
+ const migrations = [...declared, ...added];
8480
+ const phased = options?.only === void 0 || added.length === 0 ? options : {
8481
+ ...options,
8482
+ only: [...options.only, ...added.map((m) => m.meta.id)]
8483
+ };
7863
8484
  const api = this.ctx.api.migrations;
7864
8485
  const report = await runAddonMigrations({
7865
8486
  declareOwner: (input) => api.declareOwner.mutate(input),
7866
8487
  startMigration: (input) => api.startMigration.mutate(input),
7867
8488
  finishMigration: (input) => api.finishMigration.mutate(input)
7868
- }, migrations, this.ctx.logger, options);
8489
+ }, migrations, this.ctx.logger, phased);
7869
8490
  if (report.blockOwner.length > 0) throw new AddonMigrationsBlockedError(report.blockOwner);
7870
8491
  return report;
7871
8492
  }
@@ -8938,245 +9559,94 @@ function normalizeAddonInitResult(result) {
8938
9559
  if (Array.isArray(result)) return { providers: result };
8939
9560
  return result;
8940
9561
  }
8941
- var PREFIX = "records/";
8942
- /** The base of every records failure. `detail` is the human part of the message. */
8943
- var RecordsError = class extends Error {
8944
- code;
8945
- detail;
8946
- constructor(code, detail) {
8947
- super(`${PREFIX}${code}: ${detail}`);
8948
- this.name = "RecordsError";
8949
- this.code = code;
8950
- this.detail = detail;
8951
- }
8952
- };
8953
- /** The keychain could not store or serve a value: explicit, never an empty string. */
8954
- var RecordSecretUnavailableError = class extends RecordsError {
8955
- constructor(detail) {
8956
- super("secret-unavailable", detail);
8957
- this.name = "RecordSecretUnavailableError";
8958
- }
8959
- };
8960
- var InvalidRecordError = class extends RecordsError {
8961
- constructor(detail) {
8962
- super("invalid-record", detail);
8963
- this.name = "InvalidRecordError";
8964
- }
8965
- };
8966
- /** A kind declaration the engine refuses (non-additive change, bad shape, wrong file). */
8967
- var DeclarationRefusedError = class extends RecordsError {
8968
- constructor(detail) {
8969
- super("declaration-refused", detail);
8970
- this.name = "DeclarationRefusedError";
8971
- }
8972
- };
8973
- /** Limits and names of `ctx.records` (D881). One authority; the engine and the facade read it. */
8974
- /** The files a kind may live in. `history` is device-history's (D850), never records. */
8975
- var RECORD_DATABASES = ["settings", "events"];
8976
- /** The classes of a kind: the `@durable` vocabulary, one authority (replaces the annotation). */
8977
- var RECORD_CLASSES = [
8978
- "config",
8979
- "ledger",
8980
- "audit",
8981
- "mirror",
8982
- "ephemeral"
8983
- ];
8984
- var RECORD_DEFAULT_MAX_DATA_BYTES = 64 * 1024;
8985
- var RECORD_MAX_DATA_BYTES = 1024 * 1024;
8986
- var RECORD_BATCH_MAX = 1e3;
8987
- var RECORD_QUERY_MAX = 1e3;
8988
- /** A kind in the `settings` file may not bound itself above this (D447: high volume is `events`). */
8989
- var RECORD_SETTINGS_MAX_ROWS = 5e4;
8990
- /** The `Column`-free proof prefix: a ref collection for a kind's secret fields. */
8991
- var RECORD_SECRET_COLLECTION_PREFIX = "records:";
9562
+ object({
9563
+ field: string().min(1),
9564
+ on: literal("advance")
9565
+ });
8992
9566
  /**
8993
- * Secret fields of a record, addressed the way a Zod schema declares them
8994
- * (`collectZodSecretPaths`): dotted keys, `[]` for "each element of this array"
8995
- * (`auth.accessToken`, `headers[].value`).
8996
- *
8997
- * `{}` after a key means "each value of this map" (`applianceSecrets{}`): the map's own key
8998
- * names the value (`applianceSecrets{fridge}`), so no id key is declared and a body that drops a
8999
- * key releases exactly that key's secret.
9567
+ * Output schema shared by the contribution + live methods.
9000
9568
  *
9001
- * Array elements are matched by a DECLARED id key (`secretArrayKeys`:
9002
- * `{ headers: 'name' }`), never by index, so reordering a list keeps every
9003
- * keychain ref (the same rule as `arrayItemFieldPath`). The concrete path of a
9004
- * leaf names its element: `headers[X-Api].value`.
9569
+ * Mirrors the `ConfigUISchemaWithValues` shape (sections[] + optional
9570
+ * tabs[]) without importing from `../interfaces/config-ui.js` — a
9571
+ * concrete-but-lenient Zod object keeps tRPC output inference happy
9572
+ * (using `z.unknown()` here collapses unrelated router branches to
9573
+ * `unknown` when the generator re-inlines the huge AppRouter type).
9005
9574
  *
9006
- * Pure and browser-safe. Nothing here mutates: every transform returns a new value.
9007
- */
9008
- /** The array prefixes (declared form, e.g. `headers` or `a.headers`) of a path. */
9009
- function parseSecretPath(path) {
9010
- if (path.length === 0) throw new InvalidRecordError("an empty secret path");
9011
- return path.split(".").map((raw) => {
9012
- const each = raw.endsWith("[]");
9013
- const map = raw.endsWith("{}");
9014
- const key = each || map ? raw.slice(0, -2) : raw;
9015
- if (key.length === 0) throw new InvalidRecordError(`secret path "${path}" has an empty segment`);
9016
- return {
9017
- key,
9018
- each,
9019
- map
9020
- };
9021
- });
9022
- }
9023
- /** The declared array prefixes of `path` that need an id key (`headers`, `a.rows`). */
9024
- function secretArrayPrefixes(path) {
9025
- const segments = parseSecretPath(path);
9026
- const prefixes = [];
9027
- const walked = [];
9028
- for (const segment of segments) {
9029
- walked.push(segment.key);
9030
- if (segment.each) prefixes.push(walked.join("."));
9031
- }
9032
- return prefixes;
9033
- }
9034
- function isRecord$4(value) {
9035
- return typeof value === "object" && value !== null && !Array.isArray(value);
9036
- }
9037
- function elementId(element, idKey, declared, prefix) {
9038
- const id = isRecord$4(element) ? element[idKey] : void 0;
9039
- 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`);
9040
- return id;
9041
- }
9042
- /**
9043
- * Visit every secret leaf PRESENT in `data` (an absent branch has nothing to
9044
- * visit). `replace` returns the new leaf value, or {@link REMOVE_LEAF}; the
9045
- * result is a new body, `data` is untouched.
9575
+ * `.passthrough()` on sections/fields accepts whatever FormBuilder
9576
+ * extensions the caller adds (showWhen, displayScale, …) without
9577
+ * rebuilding every time a new field kind is introduced.
9046
9578
  */
9047
- var REMOVE_LEAF = Symbol("remove-leaf");
9048
- function mapAt(node, segments, index, walkedKeys, concretePrefix, declared, arrayKeys, visit) {
9049
- if (!isRecord$4(node)) return node;
9050
- const segment = segments[index];
9051
- if (segment === void 0) return node;
9052
- if (!Object.prototype.hasOwnProperty.call(node, segment.key)) return node;
9053
- const child = node[segment.key];
9054
- const keys = [...walkedKeys, segment.key];
9055
- const last = index === segments.length - 1;
9056
- if (segment.each) {
9057
- if (!Array.isArray(child)) return node;
9058
- const prefix = keys.join(".");
9059
- const idKey = arrayKeys[prefix];
9060
- if (idKey === void 0) throw new InvalidRecordError(`"${declared}": no id key declared for the array "${prefix}"`);
9061
- const mapped = child.map((element) => {
9062
- const id = elementId(element, idKey, declared, prefix);
9063
- const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}[${encodeURIComponent(id)}]`;
9064
- return last ? element : mapAt(element, segments, index + 1, keys, concrete, declared, arrayKeys, visit);
9065
- });
9066
- return {
9067
- ...node,
9068
- [segment.key]: mapped
9069
- };
9070
- }
9071
- if (segment.map) {
9072
- if (!isRecord$4(child)) return node;
9073
- const kept = Object.entries(child).map(([mapKey, value]) => {
9074
- const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}{${encodeURIComponent(mapKey)}}`;
9075
- if (!last) return [mapKey, mapAt(value, segments, index + 1, keys, concrete, declared, arrayKeys, visit)];
9076
- return [mapKey, visit({
9077
- declared,
9078
- concrete,
9079
- value
9080
- })];
9081
- }).filter(([, value]) => value !== REMOVE_LEAF);
9082
- return {
9083
- ...node,
9084
- [segment.key]: Object.fromEntries(kept)
9085
- };
9086
- }
9087
- const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}`;
9088
- if (last) {
9089
- const replacement = visit({
9090
- declared,
9091
- concrete,
9092
- value: child
9093
- });
9094
- if (replacement === REMOVE_LEAF) return Object.fromEntries(Object.entries(node).filter(([key]) => key !== segment.key));
9095
- return {
9096
- ...node,
9097
- [segment.key]: replacement
9098
- };
9099
- }
9579
+ var ContributionSectionSchema = object({
9580
+ id: string(),
9581
+ title: string(),
9582
+ description: string().optional(),
9583
+ style: _enum(["card", "accordion"]).optional(),
9584
+ defaultCollapsed: boolean().optional(),
9585
+ columns: union([
9586
+ literal(1),
9587
+ literal(2),
9588
+ literal(3),
9589
+ literal(4)
9590
+ ]).optional(),
9591
+ tab: string().optional(),
9592
+ location: _enum([
9593
+ "settings",
9594
+ "top-tab",
9595
+ "hero"
9596
+ ]).optional(),
9597
+ order: number().optional(),
9598
+ fields: array(any())
9599
+ });
9600
+ object({
9601
+ tabs: array(object({
9602
+ id: string(),
9603
+ label: string(),
9604
+ icon: string(),
9605
+ order: number().optional()
9606
+ })).optional(),
9607
+ sections: array(ContributionSectionSchema)
9608
+ }).nullable();
9609
+ object({ deviceId: number() }), object({ deviceId: number() }), object({
9610
+ deviceId: number(),
9611
+ patch: record(string(), unknown())
9612
+ }), object({ success: literal(true) });
9613
+ object({ deviceId: number() }), unknown().nullable();
9614
+ function method(input, output, options) {
9100
9615
  return {
9101
- ...node,
9102
- [segment.key]: mapAt(child, segments, index + 1, keys, concrete, declared, arrayKeys, visit)
9616
+ input,
9617
+ output,
9618
+ kind: options?.kind ?? "query",
9619
+ ...options?.auth !== void 0 ? { auth: options.auth } : {},
9620
+ ...options?.access !== void 0 ? { access: options.access } : {},
9621
+ ...options?.role !== void 0 ? { role: options.role } : {},
9622
+ ...options?.caller !== void 0 ? { caller: options.caller } : {},
9623
+ timeoutMs: options?.timeoutMs
9103
9624
  };
9104
9625
  }
9105
- /** Replace/remove every present secret leaf; returns a NEW body. */
9106
- function mapSecretLeaves(data, paths, arrayKeys, visit) {
9107
- let current = data;
9108
- for (const declared of paths) current = mapAt(current, parseSecretPath(declared), 0, [], "", declared, arrayKeys, visit);
9109
- return current;
9110
- }
9111
9626
  /**
9112
- * The keychain collection name a kind's secrets live under. Prefixed so a
9113
- * record's refs never collide with the refs a legacy collection of the same name
9114
- * already holds during an adoption.
9627
+ * A wrapper/system-only method: served exclusively by the cap's system-level
9628
+ * provider (`InferProvider`), and OPTIONAL on `InferNativeProvider` so per-device
9629
+ * driver natives don't stub out a wrapper concern (e.g. a cross-device cache
9630
+ * overview). The `systemOnly: true` literal is what `InferNativeProvider` keys on.
9115
9631
  */
9116
- function recordSecretCollection(kind) {
9117
- return `${RECORD_SECRET_COLLECTION_PREFIX}${kind}`;
9118
- }
9119
- /** The ONE ref a row's secret field may carry: the engine and the facade both build it here. */
9120
- function recordSecretRef(owner, kind, rowId, concretePath) {
9121
- return buildSecretRef({
9122
- owner,
9123
- scope: {
9124
- kind: "row",
9125
- collection: recordSecretCollection(kind),
9126
- rowId
9127
- },
9128
- fieldPath: concretePath
9129
- });
9632
+ function systemMethod(input, output, options) {
9633
+ return {
9634
+ ...method(input, output, options),
9635
+ systemOnly: true
9636
+ };
9130
9637
  }
9131
9638
  /**
9132
- * A stored secret, as an admin read shows it: a VIEW naming the row's own
9133
- * keychain ref (`set: true`), never the value and no longer the bare redaction
9134
- * token. The form hands it to the secret field, which reveals the value by ref
9135
- * through the audited `keychain-admin.reveal`; sent back untouched it keeps the
9136
- * stored secret (the records door reads a view as KEEP).
9137
- *
9138
- * ONE implementation for the entries service and for every addon that serves
9139
- * its own instances (`RecordIntegrationInstances`).
9639
+ * A method a SOURCE of a collection cap may legitimately not serve — OPTIONAL
9640
+ * on `InferProvider`. The `providerOptional: true` literal is what
9641
+ * `InferProvider` keys on; see {@link CapabilityMethodSchema.providerOptional}
9642
+ * for when this is the honest answer and when it is a soft stub.
9140
9643
  */
9141
- function isRecord$3(value) {
9142
- return typeof value === "object" && value !== null && !Array.isArray(value);
9143
- }
9144
- function secretViewsOf(owner, kind, id, decl, data) {
9145
- if (decl.secretPaths.length === 0) return data;
9146
- const shown = mapSecretLeaves(data, decl.secretPaths, decl.secretArrayKeys, (leaf) => {
9147
- if (leaf.value !== "__camstack_redacted__") return leaf.value;
9148
- return {
9149
- $secret: recordSecretRef(owner, kind, id, leaf.concrete),
9150
- v: 1,
9151
- set: true
9152
- };
9153
- });
9154
- return isRecord$3(shown) ? shown : data;
9644
+ function optionalMethod(input, output, options) {
9645
+ return {
9646
+ ...method(input, output, options),
9647
+ providerOptional: true
9648
+ };
9155
9649
  }
9156
- /**
9157
- * The share-view scope kinds a share-link token can carry. The hub mints
9158
- * and validates them (`ShareViewGrantSchema` builds its
9159
- * enum from this list); a data plane names the kinds it ACCEPTS in `share`.
9160
- */
9161
- var SHARE_VIEW_KINDS = ["grid-view", "events-view"];
9162
- /** The wire shape of {@link PeerBytesTicket} — see the type for what it is. */
9163
- var PeerBytesTicketSchema = object({
9164
- /** `http://127.0.0.1:<port>/<token>`. One `GET` takes it. */
9165
- url: string().min(1),
9166
- /**
9167
- * The HOST node this URL means something on — the hub or a named agent,
9168
- * never a runner. {@link AddonPeerBytes.open} compares it to its own and
9169
- * refuses `cross-node` by name when they differ, without dialling.
9170
- */
9171
- hostNodeId: string().min(1),
9172
- expiresAtMs: number().int().nonnegative(),
9173
- /**
9174
- * What the producer DECLARED the body to be, when it knows — `null` when it
9175
- * does not. Never `0` for unknown (D393): a consumer sizing a bound off this
9176
- * must be able to tell "the producer did not say" from "the body is empty".
9177
- */
9178
- declaredBytes: number().int().nonnegative().nullable()
9179
- });
9180
9650
  function defOf(schema) {
9181
9651
  const zodBag = Reflect.get(schema, "_zod");
9182
9652
  if (typeof zodBag !== "object" || zodBag === null) return {};
@@ -9406,6 +9876,7 @@ function defineRecordKinds(specs) {
9406
9876
  function entryBody(shape) {
9407
9877
  return object({
9408
9878
  name: string().min(1),
9879
+ enabled: boolean().optional(),
9409
9880
  ...shape
9410
9881
  });
9411
9882
  }
@@ -9432,94 +9903,30 @@ function defineEntryKind(name, spec) {
9432
9903
  if (defined === void 0) throw new DeclarationRefusedError(`entry kind "${name}" was not built`);
9433
9904
  return defined;
9434
9905
  }
9435
- object({
9436
- field: string().min(1),
9437
- on: literal("advance")
9438
- });
9439
9906
  /**
9440
- * Output schema shared by the contribution + live methods.
9441
- *
9442
- * Mirrors the `ConfigUISchemaWithValues` shape (sections[] + optional
9443
- * tabs[]) without importing from `../interfaces/config-ui.js` — a
9444
- * concrete-but-lenient Zod object keeps tRPC output inference happy
9445
- * (using `z.unknown()` here collapses unrelated router branches to
9446
- * `unknown` when the generator re-inlines the huge AppRouter type).
9447
- *
9448
- * `.passthrough()` on sections/fields accepts whatever FormBuilder
9449
- * extensions the caller adds (showWhen, displayScale, …) without
9450
- * rebuilding every time a new field kind is introduced.
9907
+ * The share-view scope kinds a share-link token can carry. The hub mints
9908
+ * and validates them (`ShareViewGrantSchema` builds its
9909
+ * enum from this list); a data plane names the kinds it ACCEPTS in `share`.
9451
9910
  */
9452
- var ContributionSectionSchema = object({
9453
- id: string(),
9454
- title: string(),
9455
- description: string().optional(),
9456
- style: _enum(["card", "accordion"]).optional(),
9457
- defaultCollapsed: boolean().optional(),
9458
- columns: union([
9459
- literal(1),
9460
- literal(2),
9461
- literal(3),
9462
- literal(4)
9463
- ]).optional(),
9464
- tab: string().optional(),
9465
- location: _enum([
9466
- "settings",
9467
- "top-tab",
9468
- "hero"
9469
- ]).optional(),
9470
- order: number().optional(),
9471
- fields: array(any())
9911
+ var SHARE_VIEW_KINDS = ["grid-view", "events-view"];
9912
+ /** The wire shape of {@link PeerBytesTicket} — see the type for what it is. */
9913
+ var PeerBytesTicketSchema = object({
9914
+ /** `http://127.0.0.1:<port>/<token>`. One `GET` takes it. */
9915
+ url: string().min(1),
9916
+ /**
9917
+ * The HOST node this URL means something on — the hub or a named agent,
9918
+ * never a runner. {@link AddonPeerBytes.open} compares it to its own and
9919
+ * refuses `cross-node` by name when they differ, without dialling.
9920
+ */
9921
+ hostNodeId: string().min(1),
9922
+ expiresAtMs: number().int().nonnegative(),
9923
+ /**
9924
+ * What the producer DECLARED the body to be, when it knows — `null` when it
9925
+ * does not. Never `0` for unknown (D393): a consumer sizing a bound off this
9926
+ * must be able to tell "the producer did not say" from "the body is empty".
9927
+ */
9928
+ declaredBytes: number().int().nonnegative().nullable()
9472
9929
  });
9473
- object({
9474
- tabs: array(object({
9475
- id: string(),
9476
- label: string(),
9477
- icon: string(),
9478
- order: number().optional()
9479
- })).optional(),
9480
- sections: array(ContributionSectionSchema)
9481
- }).nullable();
9482
- object({ deviceId: number() }), object({ deviceId: number() }), object({
9483
- deviceId: number(),
9484
- patch: record(string(), unknown())
9485
- }), object({ success: literal(true) });
9486
- object({ deviceId: number() }), unknown().nullable();
9487
- function method(input, output, options) {
9488
- return {
9489
- input,
9490
- output,
9491
- kind: options?.kind ?? "query",
9492
- ...options?.auth !== void 0 ? { auth: options.auth } : {},
9493
- ...options?.access !== void 0 ? { access: options.access } : {},
9494
- ...options?.role !== void 0 ? { role: options.role } : {},
9495
- ...options?.caller !== void 0 ? { caller: options.caller } : {},
9496
- timeoutMs: options?.timeoutMs
9497
- };
9498
- }
9499
- /**
9500
- * A wrapper/system-only method: served exclusively by the cap's system-level
9501
- * provider (`InferProvider`), and OPTIONAL on `InferNativeProvider` so per-device
9502
- * driver natives don't stub out a wrapper concern (e.g. a cross-device cache
9503
- * overview). The `systemOnly: true` literal is what `InferNativeProvider` keys on.
9504
- */
9505
- function systemMethod(input, output, options) {
9506
- return {
9507
- ...method(input, output, options),
9508
- systemOnly: true
9509
- };
9510
- }
9511
- /**
9512
- * A method a SOURCE of a collection cap may legitimately not serve — OPTIONAL
9513
- * on `InferProvider`. The `providerOptional: true` literal is what
9514
- * `InferProvider` keys on; see {@link CapabilityMethodSchema.providerOptional}
9515
- * for when this is the honest answer and when it is a soft stub.
9516
- */
9517
- function optionalMethod(input, output, options) {
9518
- return {
9519
- ...method(input, output, options),
9520
- providerOptional: true
9521
- };
9522
- }
9523
9930
  var READING_QUANTITIES = [
9524
9931
  "temperature",
9525
9932
  "pressure",
@@ -10098,7 +10505,6 @@ var CAP_NAMES = Object.freeze([
10098
10505
  "climate-control",
10099
10506
  "color",
10100
10507
  "composer",
10101
- "connection-test",
10102
10508
  "connectivity",
10103
10509
  "consumables",
10104
10510
  "contact",
@@ -11245,6 +11651,10 @@ Object.freeze({
11245
11651
  "all",
11246
11652
  "one"
11247
11653
  ]
11654
+ },
11655
+ {
11656
+ "path": "positionUpdatedAt",
11657
+ "valueType": "number"
11248
11658
  }
11249
11659
  ],
11250
11660
  "meter": [{
@@ -11499,22 +11909,6 @@ Object.freeze({
11499
11909
  "path": "pumpRunning",
11500
11910
  "valueType": "boolean"
11501
11911
  },
11502
- {
11503
- "path": "lastDrink",
11504
- "valueType": "number"
11505
- },
11506
- {
11507
- "path": "currentHourDrink",
11508
- "valueType": "number"
11509
- },
11510
- {
11511
- "path": "last24hDrink",
11512
- "valueType": "number"
11513
- },
11514
- {
11515
- "path": "todayDrink",
11516
- "valueType": "number"
11517
- },
11518
11912
  {
11519
11913
  "path": "error",
11520
11914
  "valueType": "string"
@@ -12080,12 +12474,65 @@ Object.freeze({
12080
12474
  }
12081
12475
  ]
12082
12476
  });
12477
+ Object.freeze({
12478
+ "actions": { "run": 363e4 },
12479
+ "audio-analyzer": { "classify": 3e4 },
12480
+ "custom-model-registry": { "importModelBundle": 18e5 },
12481
+ "database-snapshot": { "writeSnapshot": 18e5 },
12482
+ "device-manager": {
12483
+ "migrateDevice": 72e4,
12484
+ "runDiscoverySweep": 12e4
12485
+ },
12486
+ "device-provider": { "reloadDevice": 18e4 },
12487
+ "llm": {
12488
+ "generate": 6e5,
12489
+ "generateVision": 6e5,
12490
+ "testProfile": 6e5
12491
+ },
12492
+ "llm-runtime": {
12493
+ "complete": 6e5,
12494
+ "completeApple": 6e5,
12495
+ "ensureStarted": 6e5,
12496
+ "installModel": 36e5
12497
+ },
12498
+ "local-network": { "scanNetwork": 9e4 },
12499
+ "model-convert": { "convert": 6e5 },
12500
+ "pipeline-analytics": {
12501
+ "addRetrainFrameFromRecording": 6e4,
12502
+ "offerRetrainArchive": 12e4,
12503
+ "proposeRetrainAnnotationsWithLlm": 18e4,
12504
+ "resolveRetrainTrainingCorpus": 6e4,
12505
+ "writeRetrainArchive": 36e5
12506
+ },
12507
+ "server-management": { "applyServerUpdate": 96e4 },
12508
+ "terminal-session": { "pullOutput": 15e3 },
12509
+ "training": {
12510
+ "canaryResult": 12e4,
12511
+ "cancelJob": 12e4,
12512
+ "planJob": 6e4,
12513
+ "registerResult": 18e5,
12514
+ "rollbackCanary": 12e4,
12515
+ "startJob": 12e4,
12516
+ "startJobBatch": 12e4
12517
+ },
12518
+ "training-provider": {
12519
+ "cancelJob": 6e4,
12520
+ "cleanupJob": 3e5,
12521
+ "getJob": 6e4,
12522
+ "listJobEvents": 6e4,
12523
+ "listJobs": 12e4,
12524
+ "offerArtifact": 3e5,
12525
+ "readResult": 3e5,
12526
+ "submitJob": 18e5,
12527
+ "uploadDataset": 72e5
12528
+ }
12529
+ });
12083
12530
  object({
12084
12531
  code: string().regex(/^[a-z][a-z0-9-]*(\.[a-z0-9-]+)+$/),
12085
12532
  params: record(string(), union([string(), number()])).optional()
12086
12533
  });
12087
12534
  //#endregion
12088
- //#region ../types/dist/composition-pOHbTzRB.mjs
12535
+ //#region ../types/dist/composition-BmBHuDTQ.mjs
12089
12536
  /**
12090
12537
  * The ffmpeg build every CamStack node downloads, per platform and arch.
12091
12538
  *
@@ -12389,7 +12836,7 @@ var table = {
12389
12836
  },
12390
12837
  dwell: {
12391
12838
  minArgs: 3,
12392
- maxArgs: 3,
12839
+ maxArgs: 4,
12393
12840
  apply: () => {
12394
12841
  throw new ExpressionEvalError("dwell: stateful evaluation context is required");
12395
12842
  }
@@ -13366,278 +13813,498 @@ new Set(EVENT_OWNER_TYPES);
13366
13813
  * The publish workflow STAMPS these after the version bump
13367
13814
  * (`scripts/ci/stamp-requires.mjs`); nobody types a number by hand.
13368
13815
  *
13369
- * A requirement that cannot be checked is NOT met: a shell that reports no
13370
- * version counts as below the minimum, and an unreadable running version is
13371
- * named in the result (a failed read is never a pass).
13816
+ * A requirement that cannot be checked is NOT met: a shell that reports no
13817
+ * version counts as below the minimum, and an unreadable running version is
13818
+ * named in the result (a failed read is never a pass).
13819
+ */
13820
+ /** `>=MAJOR.MINOR.PATCH[-prerelease]` — the only range shape a requirement uses. */
13821
+ var MinVersionSchema = string().regex(/^>=\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/, "a minimum is written \">=X.Y.Z\"");
13822
+ object({
13823
+ /** The oldest `@camstack/server` this package runs on. */
13824
+ server: MinVersionSchema.optional(),
13825
+ /** The oldest installed version of each named addon package. */
13826
+ addons: record(string(), MinVersionSchema).optional(),
13827
+ /** The oldest shell around the server, per shell kind. */
13828
+ wrapper: object({
13829
+ desktop: MinVersionSchema.optional(),
13830
+ image: MinVersionSchema.optional()
13831
+ }).optional()
13832
+ });
13833
+ /** One unmet requirement; each names the versions on both sides. */
13834
+ var UnmetRequirementSchema = discriminatedUnion("kind", [
13835
+ object({
13836
+ kind: literal("server-too-old"),
13837
+ required: string(),
13838
+ /** `null` — the running server version could not be read. */
13839
+ running: string().nullable()
13840
+ }),
13841
+ object({
13842
+ kind: literal("addon-too-old"),
13843
+ packageName: string(),
13844
+ required: string(),
13845
+ /** `null` — the addon is not installed (or its version is unreadable). */
13846
+ running: string().nullable()
13847
+ }),
13848
+ object({
13849
+ kind: literal("wrapper-too-old"),
13850
+ wrapper: _enum(["desktop", "image"]),
13851
+ required: string(),
13852
+ /** `null` — the wrapper reported no version. */
13853
+ running: string().nullable()
13854
+ })
13855
+ ]);
13856
+ var RequiredAddonUpdateSchema = object({
13857
+ packageName: string(),
13858
+ /** The minimum the target server declares. */
13859
+ required: string(),
13860
+ /** What this node has; `null` when the addon is not installed. */
13861
+ installed: string().nullable()
13862
+ });
13863
+ /**
13864
+ * Which integration instance a settings form is for. An addon that serves several instances
13865
+ * (`instanceMode: multiple`) can show a different form per instance — an NVR integration
13866
+ * needs its connection, the default integration needs the addon's own sections.
13867
+ *
13868
+ * - `integrationId` is `null` in the create wizard: nothing exists yet, the operator is
13869
+ * setting up a NEW instance.
13870
+ * - `mode` is the wizard mode of the integration type (`getAvailableTypes`).
13871
+ * - `candidateStableId` is the discovery candidate a wizard was seeded from, if any.
13872
+ */
13873
+ var IntegrationInstanceRefSchema = object({
13874
+ integrationId: string().nullable(),
13875
+ mode: _enum([
13876
+ "standalone",
13877
+ "account",
13878
+ "broker"
13879
+ ]),
13880
+ candidateStableId: string().optional()
13881
+ });
13882
+ /**
13883
+ * notification-output — canonical, capability-gated notification delivery.
13884
+ *
13885
+ * Apprise-derived model (see
13886
+ * `docs/superpowers/specs/2026-07-03-notification-output-notifier-matrix.md`):
13887
+ * callers emit ONE canonical `Notification`; each provider declares a
13888
+ * per-kind capability descriptor (`TargetKind`), and the pure degrade
13889
+ * engine (`@camstack/types` `prepareNotification`) transcodes / degrades the
13890
+ * message to what the kind supports — callers never special-case a service.
13891
+ *
13892
+ * DESIGN DECISIONS (locked):
13893
+ * - Target CRUD lives on THIS cap (`upsertTarget` / `deleteTarget` /
13894
+ * `setTargetEnabled`), each provider persisting via the `settings-store`
13895
+ * cap. Rationale: the admin UI needs one uniform surface across the
13896
+ * notifiers addon AND the HA addon; the addon-`globalSettingsSchema`-array
13897
+ * alternative would fork the UI per addon and cannot host the
13898
+ * discovery→adopt flow.
13899
+ * - `listTargetKinds` / `listTargets` / `discoverTargets` return arrays →
13900
+ * the generated cap-mount auto-`concatCollection`-fans them across every
13901
+ * registered provider (notifiers addon + HA addon) so one catalog is
13902
+ * routable. `send` / `testTarget` / CRUD route to ONE provider by the
13903
+ * `addonId` the generated collection router extracts from the call input.
13904
+ * - `Attachment.bytes` is `Uint8Array`. Transport-safe: superjson (the tRPC
13905
+ * transformer) + UDS MsgPack both round-trip typed arrays — already used by
13906
+ * `storage` / `storage-provider` / `recording` caps over the same path. No
13907
+ * base64 fallback needed.
13908
+ *
13909
+ * TODO (deferred, closed-set change — separate decision): add
13910
+ * `providerKind: 'notify'` so notification providers surface on the unified
13911
+ * admin "Integrations" page.
13912
+ */
13913
+ /**
13914
+ * Zentik-derived typed-media enum — the superset across every kind. Each
13915
+ * adapter picks what it supports and the degrade engine filters the rest.
13916
+ */
13917
+ var AttachmentMediaTypeSchema = _enum([
13918
+ "image",
13919
+ "video",
13920
+ "gif",
13921
+ "audio",
13922
+ "icon"
13923
+ ]);
13924
+ /**
13925
+ * A single attachment. Exactly one of `url` (remote source, most adapters
13926
+ * prefer this) or `bytes` (inline source; required for Pushover-style
13927
+ * bytes-only kinds) MUST be present — the degrade engine expresses a
13928
+ * url→bytes fetch as a `needsFetch` directive the adapter executes.
13929
+ */
13930
+ var AttachmentSchema = object({
13931
+ mediaType: AttachmentMediaTypeSchema,
13932
+ url: string().optional(),
13933
+ bytes: _instanceof(Uint8Array).optional(),
13934
+ mime: string().optional(),
13935
+ name: string().optional()
13936
+ }).refine((a) => a.url !== void 0 || a.bytes !== void 0, { message: "Attachment requires either `url` or `bytes`" });
13937
+ var NotificationFormatSchema = _enum([
13938
+ "text",
13939
+ "markdown",
13940
+ "html"
13941
+ ]);
13942
+ /**
13943
+ * The CLOSED icon vocabulary an action button may use.
13944
+ *
13945
+ * A closed set, not a free string, and that is the whole point: an arbitrary
13946
+ * icon name is one that ntfy renders, zentik silently drops, and nobody
13947
+ * notices — the same class of gap as a zone vocabulary nothing produced
13948
+ * ([D35](../../../docs/decisions/adr-0035.md)). Every adapter maps this set or
13949
+ * declares `actionIcons: false` and the degrade engine strips the field.
13950
+ *
13951
+ * Named by INTENT, never by glyph. "check" would tie the vocabulary to one
13952
+ * renderer's icon set; "acknowledge" survives an adapter that draws it
13953
+ * differently.
13954
+ *
13955
+ * ── A TOKEN IS NOT A WIRE VALUE ─────────────────────────────────────
13956
+ *
13957
+ * These names are for US. **No adapter may forward one verbatim.** Each maps
13958
+ * the whole set onto its own renderer's vocabulary through a
13959
+ * `Record<NotificationActionIcon, string>` — a Record, never a lookup with a
13960
+ * fallback, so adding a member here fails every adapter's build until someone
13961
+ * decides its glyph, which is the only place that decision can be made
13962
+ * honestly.
13963
+ *
13964
+ * This paragraph is the bug. Zentik declared `actionIcons: true` and passed
13965
+ * `disarm` straight through; iOS feeds that string to
13966
+ * `UNNotificationActionIcon(systemImageName:)`, `disarm` is not an SF Symbol,
13967
+ * and every snooze and alarm button arrived BLANK. A pass-through is not a
13968
+ * mapping, and "the field is documented" is not "the value renders".
13969
+ *
13970
+ * Adding a member is TRAIN-BOUND. The enum lives in the published
13971
+ * `@camstack/server` closure and the cap seam validates against the HUB's copy,
13972
+ * so an addon that emits a token the running hub does not know does not lose an
13973
+ * icon — its whole `send` fails Zod validation and the notification never
13974
+ * arrives. Never emit a new token from an addon before the train carrying it.
13975
+ */
13976
+ var NotificationActionIconSchema = _enum([
13977
+ "acknowledge",
13978
+ "dismiss",
13979
+ "silence",
13980
+ "snooze",
13981
+ "view",
13982
+ "play",
13983
+ "open",
13984
+ "close",
13985
+ "lock",
13986
+ "unlock",
13987
+ "arm",
13988
+ "arm-home",
13989
+ "arm-away",
13990
+ "arm-night",
13991
+ "disarm",
13992
+ "light",
13993
+ "alert",
13994
+ "camera"
13995
+ ]);
13996
+ /** A single tap-through action button. */
13997
+ var NotificationActionSchema = object({
13998
+ id: string(),
13999
+ label: string(),
14000
+ url: string().optional(),
14001
+ /** Dropped by the degrade engine for a kind with `caps.actionIcons: false`. */
14002
+ icon: NotificationActionIconSchema.optional(),
14003
+ /**
14004
+ * Renders in a warning style where the notifier supports it.
14005
+ *
14006
+ * A HINT, never a gate. The callback's authority is its token and nothing
14007
+ * else — see `notification-center/action-token.ts` for what that does and
14008
+ * does not buy.
14009
+ */
14010
+ destructive: boolean().optional(),
14011
+ /**
14012
+ * How the tap should REACH the url.
14013
+ *
14014
+ * `navigate` (absent, and every button authored before this field) opens it:
14015
+ * the phone leaves the notification and shows whatever the callback returns.
14016
+ * That is right for a button whose answer the operator wants to read.
14017
+ *
14018
+ * `background` fires it as a POST and stays put. It exists for the buttons
14019
+ * whose whole point is not to interrupt — "silence this for 30 minutes" is
14020
+ * an answer to the notification, and being thrown into a browser tab to
14021
+ * confirm it costs more attention than the notification did. A backend that
14022
+ * cannot do a background call renders it as an ordinary link (the adapters
14023
+ * fall back rather than dropping the button), so this is a preference, never
14024
+ * a requirement.
14025
+ */
14026
+ mode: _enum(["navigate", "background"]).optional()
14027
+ });
14028
+ /** A delivery parameter value: what a notifier declared it takes. */
14029
+ var DeliveryParamValueSchema = union([
14030
+ string(),
14031
+ number(),
14032
+ boolean()
14033
+ ]);
14034
+ /**
14035
+ * One extra delivery parameter a notifier KIND declares (D938). A rule that
14036
+ * addresses a target of that kind may set it; a kind that declares nothing is
14037
+ * never handed one. The admin UI derives its control from this descriptor —
14038
+ * no editor knows a service by name.
14039
+ *
14040
+ * Optional fields are `.optional()`, never `.default()` (a Zod default does not
14041
+ * run on the addon cap path).
13372
14042
  */
13373
- /** `>=MAJOR.MINOR.PATCH[-prerelease]` — the only range shape a requirement uses. */
13374
- var MinVersionSchema = string().regex(/^>=\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/, "a minimum is written \">=X.Y.Z\"");
13375
- object({
13376
- /** The oldest `@camstack/server` this package runs on. */
13377
- server: MinVersionSchema.optional(),
13378
- /** The oldest installed version of each named addon package. */
13379
- addons: record(string(), MinVersionSchema).optional(),
13380
- /** The oldest shell around the server, per shell kind. */
13381
- wrapper: object({
13382
- desktop: MinVersionSchema.optional(),
13383
- image: MinVersionSchema.optional()
13384
- }).optional()
14043
+ var DeliveryParamSchema = object({
14044
+ key: string().min(1),
14045
+ label: string(),
14046
+ /** i18n key of the label, resolved by the declaring addon's namespace. */
14047
+ labelKey: string().optional(),
14048
+ type: _enum([
14049
+ "enum",
14050
+ "number",
14051
+ "boolean",
14052
+ "string"
14053
+ ]),
14054
+ /** `enum` only: the closed set of accepted values. */
14055
+ options: array(object({
14056
+ value: string(),
14057
+ label: string()
14058
+ })).optional(),
14059
+ /** `number` only. */
14060
+ min: number().optional(),
14061
+ max: number().optional(),
14062
+ /** What the notifier does when the rule sets nothing; shown as the placeholder. */
14063
+ default: DeliveryParamValueSchema.optional()
13385
14064
  });
13386
- /** One unmet requirement; each names the versions on both sides. */
13387
- var UnmetRequirementSchema = discriminatedUnion("kind", [
13388
- object({
13389
- kind: literal("server-too-old"),
13390
- required: string(),
13391
- /** `null` — the running server version could not be read. */
13392
- running: string().nullable()
13393
- }),
13394
- object({
13395
- kind: literal("addon-too-old"),
13396
- packageName: string(),
13397
- required: string(),
13398
- /** `null` — the addon is not installed (or its version is unreadable). */
13399
- running: string().nullable()
14065
+ /**
14066
+ * The canonical notification. `body` is the only hard field (Apprise model).
14067
+ * `priority` is a 5-level ORDINAL (1=lowest … 3=normal(default) … 5=urgent),
14068
+ * NOT a fixed severity enum — each kind declares its own `caps.levels` and
14069
+ * the adapter maps this ordinal onto its native level. `level?` is an
14070
+ * optional kind-native level id (`emergency`, `silent`, …) that overrides
14071
+ * `priority` for that one target.
14072
+ */
14073
+ var NotificationSchema = object({
14074
+ body: string(),
14075
+ title: string().optional(),
14076
+ format: NotificationFormatSchema.default("text"),
14077
+ priority: number().int().min(1).max(5).default(3),
14078
+ level: string().optional(),
14079
+ attachments: array(AttachmentSchema).optional(),
14080
+ clickUrl: string().optional(),
14081
+ actions: array(NotificationActionSchema).optional(),
14082
+ sound: string().optional(),
14083
+ ttl: number().optional(),
14084
+ tag: string().optional(),
14085
+ deviceId: number().optional(),
14086
+ eventId: string().optional(),
14087
+ metadata: record(string(), unknown()).optional(),
14088
+ /**
14089
+ * Values for the parameters the target's kind DECLARES in
14090
+ * {@link TargetKindSchema} `deliveryParams`. Already validated against the
14091
+ * declaration by the sender; a notifier reads only the keys it declared.
14092
+ */
14093
+ delivery: record(string(), DeliveryParamValueSchema).optional()
14094
+ });
14095
+ /** One declared native severity/priority level for a kind. */
14096
+ var TargetKindLevelSchema = object({
14097
+ id: string(),
14098
+ label: string(),
14099
+ /** Which canonical priority (1..5) this level maps to. `null` = qualitative-only. */
14100
+ ordinal: number().int().min(1).max(5).nullable(),
14101
+ flags: object({
14102
+ critical: boolean().optional(),
14103
+ silent: boolean().optional(),
14104
+ noPush: boolean().optional()
14105
+ }).optional(),
14106
+ /** e.g. Pushover `emergency` requires `retry` / `expire`. */
14107
+ requires: array(string()).optional(),
14108
+ description: string().optional()
14109
+ });
14110
+ /** The full capability block consulted before dispatch. */
14111
+ var TargetKindCapsSchema = object({
14112
+ attachments: object({
14113
+ mediaTypes: array(AttachmentMediaTypeSchema),
14114
+ mode: _enum([
14115
+ "url",
14116
+ "bytes",
14117
+ "both"
14118
+ ]),
14119
+ max: number().int().nonnegative(),
14120
+ maxBytes: number().int().positive().optional()
13400
14121
  }),
13401
- object({
13402
- kind: literal("wrapper-too-old"),
13403
- wrapper: _enum(["desktop", "image"]),
13404
- required: string(),
13405
- /** `null` — the wrapper reported no version. */
13406
- running: string().nullable()
13407
- })
13408
- ]);
13409
- var RequiredAddonUpdateSchema = object({
13410
- packageName: string(),
13411
- /** The minimum the target server declares. */
13412
- required: string(),
13413
- /** What this node has; `null` when the addon is not installed. */
13414
- installed: string().nullable()
14122
+ /** Max action buttons (0 = none). */
14123
+ actions: number().int().nonnegative(),
14124
+ /**
14125
+ * Whether this kind renders a per-action ICON.
14126
+ *
14127
+ * `.optional()`, deliberately NOT `.default(false)`: a Zod default does not
14128
+ * run on the addon cap path — three production failures in one day taught
14129
+ * this repo that once. Absent is read as false by the degrade engine, which
14130
+ * is the safe direction: an icon that is not rendered costs nothing, an icon
14131
+ * assumed and dropped costs the operator's trust in the field.
14132
+ */
14133
+ actionIcons: boolean().optional(),
14134
+ levels: array(TargetKindLevelSchema),
14135
+ format: array(NotificationFormatSchema),
14136
+ clickUrl: boolean(),
14137
+ sound: boolean(),
14138
+ ttl: boolean(),
14139
+ bodyMaxLen: number().int().positive()
13415
14140
  });
13416
14141
  /**
13417
- * Which integration instance a settings form is for. An addon that serves several instances
13418
- * (`instanceMode: multiple`) can show a different form per instance — an NVR integration
13419
- * needs its connection, the default integration needs the addon's own sections.
13420
- *
13421
- * - `integrationId` is `null` in the create wizard: nothing exists yet, the operator is
13422
- * setting up a NEW instance.
13423
- * - `mode` is the wizard mode of the integration type (`getAvailableTypes`).
13424
- * - `candidateStableId` is the discovery candidate a wizard was seeded from, if any.
14142
+ * `configSchema` is a `ConfigUISchema` tree passed through to the admin
14143
+ * FormBuilder. Stored as `z.unknown()` at the cap seam (mirrors
14144
+ * `device-provider.getChildCreationSchema` `CreationSchemaOutputSchema`) —
14145
+ * the union is large and not meant for runtime validation here; the exported
14146
+ * `TargetKind` type re-tightens `configSchema` to `ConfigUISchema`.
13425
14147
  */
13426
- var IntegrationInstanceRefSchema = object({
13427
- integrationId: string().nullable(),
13428
- mode: _enum([
13429
- "standalone",
13430
- "account",
13431
- "broker"
13432
- ]),
13433
- candidateStableId: string().optional()
14148
+ var ConfigSchemaPassthrough$4 = unknown();
14149
+ var TargetKindSchema = object({
14150
+ kind: string(),
14151
+ label: string(),
14152
+ icon: string(),
14153
+ /** Stamped by each provider so the concat-fanned catalog stays routable. */
14154
+ addonId: string(),
14155
+ /**
14156
+ * URL of the kind's bundled BRAND icon, served by the providing addon over
14157
+ * its own `addon-routes` surface (`/addon/<addonId>/icons/<kind>`). Absent
14158
+ * when the addon bundles no icon for that kind — the client then falls back
14159
+ * to a neutral glyph rather than rendering the raw `icon` NAME as text.
14160
+ *
14161
+ * Root-relative on purpose: it resolves against whatever origin serves a web
14162
+ * client, and a native client joins it onto its own hub base.
14163
+ *
14164
+ * DECLARED here deliberately. It used to travel as an undeclared passthrough
14165
+ * field that survived only because the runtime cap-router forwards provider
14166
+ * output verbatim — so every consumer had to re-declare it by hand to stop
14167
+ * its own Zod parse from stripping it, and the whole arrangement would have
14168
+ * broken silently the moment output validation was tightened anywhere.
14169
+ */
14170
+ iconUrl: string().optional(),
14171
+ /**
14172
+ * Media type of {@link iconUrl} (`image/svg+xml`, `image/png`, …).
14173
+ *
14174
+ * The server knows this and therefore says it, because the client cannot
14175
+ * safely guess: a React-Native client renders SVG and raster through two
14176
+ * DIFFERENT components (`react-native-svg` vs `expo-image` — expo-image does
14177
+ * not decode SVG on iOS/Android), so without this it silently fell back to a
14178
+ * placeholder glyph for every vector icon while the web build looked fine.
14179
+ *
14180
+ * Absent when {@link iconUrl} is absent, or for a legacy provider that has
14181
+ * not been updated — a client that cannot determine the type should prefer
14182
+ * its raster path, which is the safe default for an unknown image.
14183
+ */
14184
+ iconMediaType: string().optional(),
14185
+ configSchema: ConfigSchemaPassthrough$4,
14186
+ /**
14187
+ * The config keys that decide WHERE this kind's secrets are sent (server,
14188
+ * base URL, instance, chat, recipient). A save that changes any of them
14189
+ * while leaving a secret redacted is refused by the provider (D634), so an
14190
+ * editor uses this to ask for the secret on exactly those edits instead of
14191
+ * on every edit.
14192
+ *
14193
+ * Optional: absent from a provider that holds no secret (the Home Assistant
14194
+ * kinds) and from a provider older than this field — an editor that finds
14195
+ * it absent must assume ANY edit may need the secret.
14196
+ */
14197
+ destinationKeys: array(string()).optional(),
14198
+ supportsDiscovery: boolean(),
14199
+ /**
14200
+ * Extra delivery parameters a rule may set for a target of this kind (D938).
14201
+ * Absent = none; the rule editor then offers nothing.
14202
+ */
14203
+ deliveryParams: array(DeliveryParamSchema).optional(),
14204
+ caps: TargetKindCapsSchema
13434
14205
  });
13435
14206
  /**
13436
- * `RecordIntegrationInstances` - the `integration-instances` provider over ONE
13437
- * entry kind, so an addon that holds a connection serves it in ~30 lines.
13438
- *
13439
- * Every instance is one record of the addon's own kind, keyed by the
13440
- * `integrations` registry id. The records door does the secret work: a field the
13441
- * kind marks `.meta({ secret: true })` is a keychain marker bound to the row, so
13442
- * deleting the row deletes the secret, and one row's value is never another's.
13443
- *
13444
- * Patch rules for a secret (`updateInstance`): omitted, `''`, the redaction
13445
- * token or the view the form was given KEEP the stored secret;
13446
- * `{ $secretClear: true }` clears it; any other string replaces it.
14207
+ * A persisted target. `config` holds secrets; providers REDACT secret fields
14208
+ * (return a presence marker only) when serving `listTargets` — never
14209
+ * round-trip a stored secret to the UI.
13447
14210
  */
13448
- /** The most instances one addon lists (an integrations page, not a table). */
13449
- var INSTANCES_LIST_MAX = 1e3;
13450
- /** The keys of the kind's secret fields that sit at the top level of the body. */
13451
- function topLevelSecretKeys(paths) {
13452
- return new Set(paths.filter((p) => !p.includes(".") && !p.includes("[") && !p.includes("{")));
13453
- }
13454
- /** The keys of the kind's top-level MAPS whose values are secrets (`applianceSecrets{}`). */
13455
- function secretMapKeys(paths) {
13456
- return new Set(paths.filter((p) => p.endsWith("{}") && !p.slice(0, -2).match(/[.[{]/)).map((p) => p.slice(0, -2)));
13457
- }
14211
+ var TargetSchema = object({
14212
+ id: string(),
14213
+ name: string(),
14214
+ kind: string(),
14215
+ addonId: string(),
14216
+ enabled: boolean(),
14217
+ config: record(string(), unknown())
14218
+ });
14219
+ /** A discovery-surfaced candidate (config is partial + non-secret). */
14220
+ var DiscoveredTargetSchema = object({
14221
+ kind: string(),
14222
+ suggestedName: string(),
14223
+ config: record(string(), unknown())
14224
+ });
14225
+ /** The degrade engine's report — what was resolved / dropped / degraded. */
14226
+ var RenderedAsSchema = object({
14227
+ level: string(),
14228
+ format: NotificationFormatSchema,
14229
+ attachmentsSent: number().int().nonnegative(),
14230
+ actionsSent: number().int().nonnegative(),
14231
+ truncated: boolean(),
14232
+ dropped: array(string())
14233
+ });
14234
+ var SendResultSchema = object({
14235
+ success: boolean(),
14236
+ error: string().optional(),
14237
+ renderedAs: RenderedAsSchema.optional()
14238
+ });
14239
+ /** Same shape as SendResult — kept as a distinct name for the test panel. */
14240
+ var TestResultSchema = SendResultSchema;
13458
14241
  /**
13459
- * A patch value for a map of secrets: an entry that is omitted, `''`, the redaction token or the
13460
- * view the form was given KEEPS its stored secret (it is left out of the merge); `{ $secretClear }`
13461
- * or `null` removes the entry; any other string replaces it. Null when nothing is left to merge.
14242
+ * Pre-save credential probe against a partial (unsaved) target config.
14243
+ * `resolvedUrl` never includes secrets (token stripped from path).
13462
14244
  */
13463
- function secretMapPatch(value) {
13464
- if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
13465
- const out = {};
13466
- for (const [key, entry] of Object.entries(value)) if (entry === null || isSecretClear(entry)) out[key] = null;
13467
- else if (typeof entry === "string" && entry !== "" && entry !== "__camstack_redacted__" && !isSecretFieldView(entry)) out[key] = entry;
13468
- return Object.keys(out).length > 0 ? out : null;
13469
- }
13470
- /** Does the kind's body schema carry an `enabled` field? */
13471
- function declaresEnabled(kind) {
13472
- const json = toJSONSchema(kind.schema, {
13473
- unrepresentable: "any",
13474
- io: "input"
13475
- });
13476
- const properties = Reflect.get(json, "properties");
13477
- return typeof properties === "object" && properties !== null && "enabled" in properties;
13478
- }
13479
- var RecordIntegrationInstances = class {
13480
- records;
13481
- kind;
13482
- hooks;
13483
- handle;
13484
- secretKeys;
13485
- secretMaps;
13486
- nameField;
13487
- /** The `integrations` registry owns the on/off switch (`role: devices`); the body has none. */
13488
- registryOwnsEnabled;
13489
- constructor(records, kind, hooks) {
13490
- this.records = records;
13491
- this.kind = kind;
13492
- this.hooks = hooks;
13493
- this.handle = records.kind(kind);
13494
- this.secretKeys = topLevelSecretKeys(kind.declaration.secretPaths);
13495
- this.secretMaps = secretMapKeys(kind.declaration.secretPaths);
13496
- this.nameField = kind.declaration.entry?.nameField ?? "name";
13497
- this.registryOwnsEnabled = hooks.description.role === "devices";
13498
- 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"`);
13499
- }
14245
+ var ProbeTargetConfigResultSchema = object({
14246
+ ok: boolean(),
14247
+ resolvedUrl: string(),
14248
+ httpStatus: number().int().optional(),
14249
+ stateInstance: string().optional(),
14250
+ error: string().optional()
14251
+ });
14252
+ method(object({}), array(TargetKindSchema)), method(object({}), array(TargetSchema), { auth: "admin" }), method(object({ targetId: string() }), TargetSchema, { auth: "admin" }), method(object({
14253
+ kind: string(),
14254
+ config: record(string(), unknown()).optional(),
13500
14255
  /**
13501
- * One instance read for the addon's own runtime; null when absent. When the keychain is
13502
- * locked the row is served WITHOUT its secrets and says so (`secrets: 'unavailable'`), so the
13503
- * caller can keep what it had instead of reconfiguring with an empty secret (D49).
14256
+ * When editing / duplicating, the blank password field never round-trips
14257
+ * the stored token. Pass the source target id so the provider can restore
14258
+ * secrets server-side before dialling (same merge as upsert).
13504
14259
  */
13505
- async readResolved(id) {
13506
- try {
13507
- const record = await this.handle.getResolved(id);
13508
- return record === null ? null : {
13509
- id,
13510
- body: record.data,
13511
- enabled: record.data.enabled !== false,
13512
- secrets: "resolved"
13513
- };
13514
- } catch (err) {
13515
- if (!(err instanceof RecordSecretUnavailableError)) throw err;
13516
- const stored = await this.handle.get(id);
13517
- if (stored === null) return null;
13518
- return {
13519
- id,
13520
- body: Object.fromEntries(Object.entries(stored.data).filter(([key]) => !this.secretKeys.has(key))),
13521
- enabled: stored.data.enabled !== false,
13522
- secrets: "unavailable"
13523
- };
13524
- }
13525
- }
13526
- /** The body of {@link readResolved} alone; a locked keychain yields the row without secrets. */
13527
- async getResolved(id) {
13528
- return (await this.readResolved(id))?.body ?? null;
13529
- }
13530
- /** Every instance, secrets resolved where the keychain allows; an absent one is skipped. */
13531
- async listResolved() {
13532
- const page = await this.handle.query({ limit: INSTANCES_LIST_MAX });
13533
- const out = [];
13534
- for (const record of page.records) {
13535
- const read = await this.readResolved(record.id);
13536
- if (read !== null) out.push(read);
13537
- }
13538
- return out;
13539
- }
13540
- viewOf(record) {
13541
- const shown = secretViewsOf(this.records.owner, this.kind.name, record.id, this.kind.declaration, record.data);
13542
- const rawName = record.data[this.nameField];
13543
- const kind = this.hooks.kindOf?.(record.data);
13544
- const health = this.hooks.health?.(record.data, record.id);
13545
- return {
13546
- id: record.id,
13547
- name: typeof rawName === "string" ? rawName : record.id,
13548
- configured: this.hooks.configured(record.data),
13549
- ...this.registryOwnsEnabled ? {} : { enabled: record.data.enabled !== false },
13550
- formValues: shown,
13551
- ...kind !== void 0 ? { kind } : {},
13552
- ...health?.status !== void 0 ? { status: health.status } : {},
13553
- ...health?.lastCheckedAt !== void 0 ? { lastCheckedAt: health.lastCheckedAt } : {}
13554
- };
13555
- }
13556
- describe = async () => this.hooks.mintId === void 0 ? this.hooks.description : {
13557
- ...this.hooks.description,
13558
- mintsId: true
13559
- };
13560
- instanceFormSchema = async ({ id }) => this.hooks.formSchema(id);
13561
- listInstances = async () => {
13562
- return (await this.handle.query({ limit: INSTANCES_LIST_MAX })).records.map((record) => this.viewOf(record));
13563
- };
13564
- getInstance = async ({ id }) => {
13565
- const record = await this.handle.get(id);
13566
- return record === null ? null : this.viewOf(record);
13567
- };
13568
- /** Insert ONE row (`ifRev: 0`: an existing id is refused, never overwritten). */
13569
- createInstance = async ({ id, name, kind, values }) => {
13570
- const minted = id ?? this.hooks.mintId?.({
13571
- name,
13572
- ...kind !== void 0 ? { kind } : {}
13573
- });
13574
- if (minted === void 0) throw new Error("createInstance needs an id: this provider does not mint one");
13575
- await this.handle.put({
13576
- id: minted,
13577
- data: this.hooks.initialBody(name, kind)
13578
- }, { ifRev: 0 });
13579
- const patch = this.patchOf(values ?? {});
13580
- if (Object.keys(patch).length > 0) await this.handle.patch(minted, patch);
13581
- await this.hooks.onChanged?.(minted, "created");
13582
- return { id: minted };
13583
- };
13584
- updateInstance = async ({ id, name, values }) => {
13585
- const patch = this.patchOf(values);
13586
- if (name !== void 0) patch[this.nameField] = name;
13587
- await this.handle.patch(id, patch);
13588
- await this.hooks.onChanged?.(id, "updated");
13589
- return { ok: true };
13590
- };
13591
- /** The record patch a form `values` object means: secrets kept, cleared or replaced. */
13592
- patchOf(values) {
13593
- const patch = {};
13594
- for (const [key, value] of Object.entries(values)) {
13595
- if (value === void 0) continue;
13596
- if (this.secretMaps.has(key)) {
13597
- const entries = secretMapPatch(value);
13598
- if (entries !== null) patch[key] = entries;
13599
- } else if (!this.secretKeys.has(key)) patch[key] = value;
13600
- else if (isSecretClear(value)) patch[key] = null;
13601
- else if (typeof value === "string" && value !== "" && value !== "__camstack_redacted__" && !isSecretFieldView(value)) patch[key] = value;
13602
- }
13603
- return patch;
13604
- }
13605
- /** The switch lives in the record body; the addon is told so it applies it (D996). */
13606
- setInstanceEnabled = async ({ id, enabled }) => {
13607
- if (this.registryOwnsEnabled) throw new Error(`instance "${id}": the integrations registry owns the on/off switch of this addon; set it with integrations.update`);
13608
- await this.handle.patch(id, { enabled });
13609
- await this.hooks.onChanged?.(id, "enabled");
13610
- return { ok: true };
13611
- };
13612
- /** The row and its keychain refs go together (the records door). */
13613
- deleteInstance = async ({ id }) => {
13614
- await this.handle.delete(id);
13615
- await this.hooks.onChanged?.(id, "deleted");
13616
- return { ok: true };
13617
- };
13618
- testInstance = async (input) => {
13619
- if (this.hooks.test === void 0) return {
13620
- success: false,
13621
- status: "unsupported",
13622
- error: "This integration declares no connection test"
13623
- };
13624
- return this.hooks.test(input);
13625
- };
13626
- /** The flat provider object to hand to `registerProvider`. */
13627
- toProvider() {
13628
- return {
13629
- describe: this.describe,
13630
- instanceFormSchema: this.instanceFormSchema,
13631
- listInstances: this.listInstances,
13632
- getInstance: this.getInstance,
13633
- createInstance: this.createInstance,
13634
- updateInstance: this.updateInstance,
13635
- setInstanceEnabled: this.setInstanceEnabled,
13636
- deleteInstance: this.deleteInstance,
13637
- testInstance: this.testInstance
13638
- };
13639
- }
13640
- };
14260
+ targetId: string().optional()
14261
+ }), array(DiscoveredTargetSchema), { auth: "admin" }), method(object({
14262
+ kind: string(),
14263
+ config: record(string(), unknown()),
14264
+ /** See `discoverTargets.targetId` — restore stored secrets for a blank password. */
14265
+ targetId: string().optional()
14266
+ }), ProbeTargetConfigResultSchema, {
14267
+ kind: "mutation",
14268
+ auth: "admin"
14269
+ }), method(object({
14270
+ targetId: string(),
14271
+ notification: NotificationSchema
14272
+ }), SendResultSchema, {
14273
+ kind: "mutation",
14274
+ auth: "admin"
14275
+ }), method(object({
14276
+ targetId: string(),
14277
+ sample: NotificationSchema.optional()
14278
+ }), TestResultSchema, {
14279
+ kind: "mutation",
14280
+ auth: "admin"
14281
+ }), method(object({
14282
+ target: TargetSchema,
14283
+ /**
14284
+ * Duplicate flow: create a NEW target id while copying secrets from an
14285
+ * existing row. The UI never holds the stored token; blank / redacted
14286
+ * password fields are restored from this source (D634 still applies if
14287
+ * destinations diverge without a re-typed secret).
14288
+ */
14289
+ cloneSecretsFrom: string().optional()
14290
+ }), TargetSchema, {
14291
+ kind: "mutation",
14292
+ auth: "admin"
14293
+ }), method(object({ targetId: string() }), _void(), {
14294
+ kind: "mutation",
14295
+ auth: "admin"
14296
+ }), method(object({
14297
+ targetId: string(),
14298
+ enabled: boolean()
14299
+ }), _void(), {
14300
+ kind: "mutation",
14301
+ auth: "admin"
14302
+ });
14303
+ looseObject({
14304
+ name: string().min(1),
14305
+ enabled: boolean().optional()
14306
+ });
14307
+ TargetSchema.omit({ id: true });
13641
14308
  var EncodeProfileSchema = object({
13642
14309
  video: object({
13643
14310
  codec: _enum([
@@ -19822,31 +20489,21 @@ var APPLIANCE_CAP_VOCABULARY = {
19822
20489
  "pet-fountain": {
19823
20490
  scope: "device",
19824
20491
  noun: t("Pet fountain", "Fontana per animali"),
19825
- actions: [
19826
- {
19827
- id: "petFountain.pumpOn",
19828
- method: "setPump",
19829
- label: t("Pump on", "Pompa accesa"),
19830
- phrase: t("Start the pump of {device}", "Avvia la pompa di {device}"),
19831
- icon: "play",
19832
- args: { on: true }
19833
- },
19834
- {
19835
- id: "petFountain.pumpOff",
19836
- method: "setPump",
19837
- label: t("Pump off", "Pompa spenta"),
19838
- phrase: t("Stop the pump of {device}", "Ferma la pompa di {device}"),
19839
- icon: "square",
19840
- args: { on: false }
19841
- },
19842
- {
19843
- id: "petFountain.resetDailyConsumption",
19844
- method: "resetDailyConsumption",
19845
- label: t("Clear daily consumption", "Azzera il consumo giornaliero"),
19846
- phrase: t("Clear the daily water consumption of {device}", "Azzera il consumo giornaliero di acqua di {device}"),
19847
- icon: "rotate-ccw"
19848
- }
19849
- ],
20492
+ actions: [{
20493
+ id: "petFountain.pumpOn",
20494
+ method: "setPump",
20495
+ label: t("Pump on", "Pompa accesa"),
20496
+ phrase: t("Start the pump of {device}", "Avvia la pompa di {device}"),
20497
+ icon: "play",
20498
+ args: { on: true }
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
+ }],
19850
20507
  state: [{
19851
20508
  kind: "boolean",
19852
20509
  field: "empty",
@@ -21865,7 +22522,6 @@ var SYSTEM_CAP_VOCABULARY = {
21865
22522
  "calendar-source": system(INTERNAL),
21866
22523
  calendars: system("calendars feed schedules and conditions, not device actions"),
21867
22524
  composer: system("device composition — an authoring tool, not an action"),
21868
- "connection-test": system(INTERNAL),
21869
22525
  "core-blocks": system(INTERNAL),
21870
22526
  "custom-model-registry": system(ML),
21871
22527
  "data-store-provider": system(INTERNAL),
@@ -43563,638 +44219,224 @@ var AutomationStepTraceSchema = object({
43563
44219
  path: string().min(1),
43564
44220
  kind: string().min(1),
43565
44221
  cap: string().optional(),
43566
- method: string().optional(),
43567
- /** The vocabulary action the step performs (`cover.open`), when it names one. */
43568
- actionId: string().optional(),
43569
- deviceId: number().int().optional(),
43570
- /** What happened per device, when the step drove several (or a domain). */
43571
- devices: array(StepDeviceTraceSchema).optional(),
43572
- startedAt: number().optional(),
43573
- endedAt: number().optional(),
43574
- /**
43575
- * The parameters the step SENT, after `{{vars.x}}` substitution — what the
43576
- * device was actually asked. Bounded like trigger `vars`; a secret parameter
43577
- * is shown as {@link REDACTED_ARG}. Absent on traces written before it existed.
43578
- */
43579
- args: record(string(), TraceValueSchema).optional(),
43580
- /** `empty`: the target resolved to no device, so nothing was done — never silently `ok`. */
43581
- outcome: _enum([
43582
- "ok",
43583
- "error",
43584
- "not-run",
43585
- "empty"
43586
- ]),
43587
- message: string().optional()
43588
- });
43589
- var AutomationRunTraceSchema = object({
43590
- runId: string().min(1),
43591
- startedAt: number(),
43592
- endedAt: number(),
43593
- trigger: AutomationTriggerTraceSchema,
43594
- conditions: array(AutomationConditionTraceNodeSchema),
43595
- verdict: AutomationRunVerdictSchema.optional(),
43596
- steps: array(AutomationStepTraceSchema),
43597
- outcome: AutomationRunOutcomeSchema,
43598
- /** How many identical consecutive skips this trace stands for (>= 1). */
43599
- repeat: number().int().min(1),
43600
- /** When the latest of those repeats happened. */
43601
- lastAt: number(),
43602
- /**
43603
- * A scheduler point's own outcome (D983). `outcome` carries the closest
43604
- * automation outcome so a reader that does not know schedulers still reads
43605
- * the trace; this field says exactly what happened.
43606
- */
43607
- scheduler: SchedulerOutcomeSchema.optional()
43608
- });
43609
- /**
43610
- * What the hub's `runs` ledger holds for one owner (`automation:<blockId>` or
43611
- * `action:<actionId>`): the cooldown stamp and the trace ring.
43612
- */
43613
- var AutomationStateDocSchema = object({
43614
- version: literal(1),
43615
- lastRunStartedAt: number().nullable(),
43616
- traces: array(AutomationRunTraceSchema)
43617
- });
43618
- /**
43619
- * Actions — named, runnable things an operator (or an automation) can start,
43620
- * declared as LIST ENTRIES, never as devices.
43621
- *
43622
- * An entry is either **internal** (a short list of cap/wait steps kept in the
43623
- * hub's `actions` record kind) or declared by an addon through the
43624
- * `action-source` collection (a Home Assistant script, a scene …). The one
43625
- * surface the UI and automations talk to is the `actions` cap; it keeps no
43626
- * catalog of its own (D3) — every `list` asks the providers live.
43627
- *
43628
- * This file is the data half: the entry schema, the variables an entry may
43629
- * declare, and the pure resolution of the values a run was given. It holds no
43630
- * runtime.
43631
- */
43632
- /** What a variable's value is. `select` takes one of `options`. */
43633
- var ActionVariableTypeSchema = _enum([
43634
- "string",
43635
- "number",
43636
- "boolean",
43637
- "select"
43638
- ]);
43639
- var ACTION_VARIABLE_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
43640
- var ActionVariableValueSchema = union([
43641
- string(),
43642
- number(),
43643
- boolean()
43644
- ]);
43645
- /**
43646
- * One declared variable. Steps reference it as `{ $var: 'name' }` (the whole
43647
- * value) or `{{vars.name}}` (inside a string) in their args.
43648
- */
43649
- var ActionVariableSchema = object({
43650
- name: string().regex(ACTION_VARIABLE_NAME_RE),
43651
- label: string().min(1).max(120).optional(),
43652
- type: ActionVariableTypeSchema,
43653
- required: boolean().optional(),
43654
- default: ActionVariableValueSchema.optional(),
43655
- /** The allowed values of a `select`. */
43656
- options: array(string().min(1)).min(1).optional()
43657
- }).superRefine((v, ctx) => {
43658
- if (v.type === "select" && v.options === void 0) ctx.addIssue({
43659
- code: "custom",
43660
- message: "a select variable needs options",
43661
- path: ["options"]
43662
- });
43663
- if (v.default !== void 0 && variableValueError(v, v.default) !== null) ctx.addIssue({
43664
- code: "custom",
43665
- message: variableValueError(v, v.default) ?? "invalid default",
43666
- path: ["default"]
43667
- });
43668
- });
43669
- /** Why `value` is not a legal value for the variable, or null when it is. */
43670
- function variableValueError(variable, value) {
43671
- switch (variable.type) {
43672
- case "string": return typeof value === "string" ? null : `variable "${variable.name}" must be a string`;
43673
- case "number": return typeof value === "number" && Number.isFinite(value) ? null : `variable "${variable.name}" must be a number`;
43674
- case "boolean": return typeof value === "boolean" ? null : `variable "${variable.name}" must be true or false`;
43675
- case "select": return typeof value === "string" && (variable.options ?? []).includes(value) ? null : `variable "${variable.name}" must be one of ${(variable.options ?? []).join(", ")}`;
43676
- }
43677
- }
43678
- var ActionSourceKindSchema = _enum(["internal", "addon"]);
43679
- function isInternalActionId(actionId) {
43680
- return actionId.startsWith("internal:") && actionId.length > 9;
43681
- }
43682
- /** The addon behind a `<addonId>:<localId>` id, or null for anything else (internal included). */
43683
- function addonIdOfActionId(actionId) {
43684
- if (isInternalActionId(actionId)) return null;
43685
- const at = actionId.indexOf(":");
43686
- return at > 0 && at < actionId.length - 1 ? actionId.slice(0, at) : null;
43687
- }
43688
- var ActionStatusSchema = object({
43689
- isRunning: boolean(),
43690
- /** Ms epoch the latest run STARTED; null when it never ran. */
43691
- lastRunAt: number().nullable(),
43692
- /** The latest run's failure; null on success or when it never ran. */
43693
- lastError: string().nullable()
43694
- });
43695
- var ActionEntrySchema = object({
43696
- /** `internal:<uuid>` or `<addonId>:<localId>`. */
43697
- id: string().min(3),
43698
- name: string().min(1).max(120),
43699
- /** The addon that declared it; `core-blocks` for an internal one. */
43700
- addonId: string().min(1),
43701
- source: ActionSourceKindSchema,
43702
- /** An addon-declared entry is edited where it was declared. */
43703
- readOnly: boolean(),
43704
- /** Internal only: cap and wait steps. No action-in-action, so no cycles. */
43705
- steps: array(ActionStepSchema).min(1).max(50).optional(),
43706
- variables: array(ActionVariableSchema).max(20).optional(),
43707
- status: ActionStatusSchema
43708
- }).superRefine((entry, ctx) => {
43709
- if (entry.source === "internal") {
43710
- if (!isInternalActionId(entry.id)) ctx.addIssue({
43711
- code: "custom",
43712
- message: "an internal action id is internal:<uuid>",
43713
- path: ["id"]
43714
- });
43715
- return;
43716
- }
43717
- if (entry.steps !== void 0) ctx.addIssue({
43718
- code: "custom",
43719
- message: "only an internal action carries steps",
43720
- path: ["steps"]
43721
- });
43722
- if (!entry.readOnly) ctx.addIssue({
43723
- code: "custom",
43724
- message: "an addon action is read-only here",
43725
- path: ["readOnly"]
43726
- });
43727
- if (addonIdOfActionId(entry.id) === null) ctx.addIssue({
43728
- code: "custom",
43729
- message: "an addon action id is <addonId>:<localId>",
43730
- path: ["id"]
43731
- });
43732
- });
43733
- /** What an operator writes for an internal action. */
43734
- var ActionInputSchema = object({
43735
- name: string().min(1).max(120),
43736
- steps: array(ActionStepSchema).min(1).max(50),
43737
- variables: array(ActionVariableSchema).max(20).optional()
43738
- });
43739
- /** Who started a run. Absent = the operator pressed it. */
43740
- var ActionRunOriginSchema = object({
43741
- /** The automation block whose step started it. */
43742
- blockId: string().min(1).optional() });
43743
- /** `started` = the caller did not ask to wait. */
43744
- var ActionRunOutcomeSchema = union([AutomationRunOutcomeSchema, literal("started")]);
43745
- var ActionRunResultSchema = object({
43746
- runId: string().min(1),
43747
- outcome: ActionRunOutcomeSchema,
43748
- /** Why it did not run, or what failed. */
43749
- message: string().optional()
43750
- });
43751
- _enum([
43752
- "not-found",
43753
- "read-only",
43754
- "invalid-variables",
43755
- "invalid-steps",
43756
- "not-linked",
43757
- "busy"
43758
- ]);
43759
- object({
43760
- actionId: string(),
43761
- runId: string(),
43762
- isRunning: boolean(),
43763
- /** Set when the run ended. */
43764
- outcome: AutomationRunOutcomeSchema.optional(),
43765
- lastRunAt: number().nullable(),
43766
- lastError: string().nullable()
43767
- });
43768
- /** A bare number accepted as a base unit — the save succeeded, say so. */
43769
- var UnitWarningSchema = object({
43770
- /** Where in the saved record, e.g. `conditions.children.0` or `steps.2.args.grams`. */
43771
- path: string(),
43772
- deviceId: number().int().optional(),
43773
- field: string(),
43774
- value: number(),
43775
- assumedUnit: string(),
43776
- message: string()
43777
- });
43778
- /**
43779
- * notification-output — canonical, capability-gated notification delivery.
43780
- *
43781
- * Apprise-derived model (see
43782
- * `docs/superpowers/specs/2026-07-03-notification-output-notifier-matrix.md`):
43783
- * callers emit ONE canonical `Notification`; each provider declares a
43784
- * per-kind capability descriptor (`TargetKind`), and the pure degrade
43785
- * engine (`@camstack/types` `prepareNotification`) transcodes / degrades the
43786
- * message to what the kind supports — callers never special-case a service.
43787
- *
43788
- * DESIGN DECISIONS (locked):
43789
- * - Target CRUD lives on THIS cap (`upsertTarget` / `deleteTarget` /
43790
- * `setTargetEnabled`), each provider persisting via the `settings-store`
43791
- * cap. Rationale: the admin UI needs one uniform surface across the
43792
- * notifiers addon AND the HA addon; the addon-`globalSettingsSchema`-array
43793
- * alternative would fork the UI per addon and cannot host the
43794
- * discovery→adopt flow.
43795
- * - `listTargetKinds` / `listTargets` / `discoverTargets` return arrays →
43796
- * the generated cap-mount auto-`concatCollection`-fans them across every
43797
- * registered provider (notifiers addon + HA addon) so one catalog is
43798
- * routable. `send` / `testTarget` / CRUD route to ONE provider by the
43799
- * `addonId` the generated collection router extracts from the call input.
43800
- * - `Attachment.bytes` is `Uint8Array`. Transport-safe: superjson (the tRPC
43801
- * transformer) + UDS MsgPack both round-trip typed arrays — already used by
43802
- * `storage` / `storage-provider` / `recording` caps over the same path. No
43803
- * base64 fallback needed.
43804
- *
43805
- * TODO (deferred, closed-set change — separate decision): add
43806
- * `providerKind: 'notify'` so notification providers surface on the unified
43807
- * admin "Integrations" page.
43808
- */
43809
- /**
43810
- * Zentik-derived typed-media enum — the superset across every kind. Each
43811
- * adapter picks what it supports and the degrade engine filters the rest.
43812
- */
43813
- var AttachmentMediaTypeSchema = _enum([
43814
- "image",
43815
- "video",
43816
- "gif",
43817
- "audio",
43818
- "icon"
43819
- ]);
43820
- /**
43821
- * A single attachment. Exactly one of `url` (remote source, most adapters
43822
- * prefer this) or `bytes` (inline source; required for Pushover-style
43823
- * bytes-only kinds) MUST be present — the degrade engine expresses a
43824
- * url→bytes fetch as a `needsFetch` directive the adapter executes.
43825
- */
43826
- var AttachmentSchema = object({
43827
- mediaType: AttachmentMediaTypeSchema,
43828
- url: string().optional(),
43829
- bytes: _instanceof(Uint8Array).optional(),
43830
- mime: string().optional(),
43831
- name: string().optional()
43832
- }).refine((a) => a.url !== void 0 || a.bytes !== void 0, { message: "Attachment requires either `url` or `bytes`" });
43833
- var NotificationFormatSchema = _enum([
43834
- "text",
43835
- "markdown",
43836
- "html"
43837
- ]);
43838
- /**
43839
- * The CLOSED icon vocabulary an action button may use.
43840
- *
43841
- * A closed set, not a free string, and that is the whole point: an arbitrary
43842
- * icon name is one that ntfy renders, zentik silently drops, and nobody
43843
- * notices — the same class of gap as a zone vocabulary nothing produced
43844
- * ([D35](../../../docs/decisions/adr-0035.md)). Every adapter maps this set or
43845
- * declares `actionIcons: false` and the degrade engine strips the field.
43846
- *
43847
- * Named by INTENT, never by glyph. "check" would tie the vocabulary to one
43848
- * renderer's icon set; "acknowledge" survives an adapter that draws it
43849
- * differently.
43850
- *
43851
- * ── A TOKEN IS NOT A WIRE VALUE ─────────────────────────────────────
43852
- *
43853
- * These names are for US. **No adapter may forward one verbatim.** Each maps
43854
- * the whole set onto its own renderer's vocabulary through a
43855
- * `Record<NotificationActionIcon, string>` — a Record, never a lookup with a
43856
- * fallback, so adding a member here fails every adapter's build until someone
43857
- * decides its glyph, which is the only place that decision can be made
43858
- * honestly.
43859
- *
43860
- * This paragraph is the bug. Zentik declared `actionIcons: true` and passed
43861
- * `disarm` straight through; iOS feeds that string to
43862
- * `UNNotificationActionIcon(systemImageName:)`, `disarm` is not an SF Symbol,
43863
- * and every snooze and alarm button arrived BLANK. A pass-through is not a
43864
- * mapping, and "the field is documented" is not "the value renders".
43865
- *
43866
- * Adding a member is TRAIN-BOUND. The enum lives in the published
43867
- * `@camstack/server` closure and the cap seam validates against the HUB's copy,
43868
- * so an addon that emits a token the running hub does not know does not lose an
43869
- * icon — its whole `send` fails Zod validation and the notification never
43870
- * arrives. Never emit a new token from an addon before the train carrying it.
43871
- */
43872
- var NotificationActionIconSchema = _enum([
43873
- "acknowledge",
43874
- "dismiss",
43875
- "silence",
43876
- "snooze",
43877
- "view",
43878
- "play",
43879
- "open",
43880
- "close",
43881
- "lock",
43882
- "unlock",
43883
- "arm",
43884
- "arm-home",
43885
- "arm-away",
43886
- "arm-night",
43887
- "disarm",
43888
- "light",
43889
- "alert",
43890
- "camera"
43891
- ]);
43892
- /** A single tap-through action button. */
43893
- var NotificationActionSchema = object({
43894
- id: string(),
43895
- label: string(),
43896
- url: string().optional(),
43897
- /** Dropped by the degrade engine for a kind with `caps.actionIcons: false`. */
43898
- icon: NotificationActionIconSchema.optional(),
43899
- /**
43900
- * Renders in a warning style where the notifier supports it.
43901
- *
43902
- * A HINT, never a gate. The callback's authority is its token and nothing
43903
- * else — see `notification-center/action-token.ts` for what that does and
43904
- * does not buy.
43905
- */
43906
- destructive: boolean().optional(),
43907
- /**
43908
- * How the tap should REACH the url.
43909
- *
43910
- * `navigate` (absent, and every button authored before this field) opens it:
43911
- * the phone leaves the notification and shows whatever the callback returns.
43912
- * That is right for a button whose answer the operator wants to read.
43913
- *
43914
- * `background` fires it as a POST and stays put. It exists for the buttons
43915
- * whose whole point is not to interrupt — "silence this for 30 minutes" is
43916
- * an answer to the notification, and being thrown into a browser tab to
43917
- * confirm it costs more attention than the notification did. A backend that
43918
- * cannot do a background call renders it as an ordinary link (the adapters
43919
- * fall back rather than dropping the button), so this is a preference, never
43920
- * a requirement.
43921
- */
43922
- mode: _enum(["navigate", "background"]).optional()
43923
- });
43924
- /** A delivery parameter value: what a notifier declared it takes. */
43925
- var DeliveryParamValueSchema = union([
43926
- string(),
43927
- number(),
43928
- boolean()
43929
- ]);
43930
- /**
43931
- * One extra delivery parameter a notifier KIND declares (D938). A rule that
43932
- * addresses a target of that kind may set it; a kind that declares nothing is
43933
- * never handed one. The admin UI derives its control from this descriptor —
43934
- * no editor knows a service by name.
43935
- *
43936
- * Optional fields are `.optional()`, never `.default()` (a Zod default does not
43937
- * run on the addon cap path).
43938
- */
43939
- var DeliveryParamSchema = object({
43940
- key: string().min(1),
43941
- label: string(),
43942
- /** i18n key of the label, resolved by the declaring addon's namespace. */
43943
- labelKey: string().optional(),
43944
- type: _enum([
43945
- "enum",
43946
- "number",
43947
- "boolean",
43948
- "string"
43949
- ]),
43950
- /** `enum` only: the closed set of accepted values. */
43951
- options: array(object({
43952
- value: string(),
43953
- label: string()
43954
- })).optional(),
43955
- /** `number` only. */
43956
- min: number().optional(),
43957
- max: number().optional(),
43958
- /** What the notifier does when the rule sets nothing; shown as the placeholder. */
43959
- default: DeliveryParamValueSchema.optional()
43960
- });
43961
- /**
43962
- * The canonical notification. `body` is the only hard field (Apprise model).
43963
- * `priority` is a 5-level ORDINAL (1=lowest … 3=normal(default) … 5=urgent),
43964
- * NOT a fixed severity enum — each kind declares its own `caps.levels` and
43965
- * the adapter maps this ordinal onto its native level. `level?` is an
43966
- * optional kind-native level id (`emergency`, `silent`, …) that overrides
43967
- * `priority` for that one target.
43968
- */
43969
- var NotificationSchema = object({
43970
- body: string(),
43971
- title: string().optional(),
43972
- format: NotificationFormatSchema.default("text"),
43973
- priority: number().int().min(1).max(5).default(3),
43974
- level: string().optional(),
43975
- attachments: array(AttachmentSchema).optional(),
43976
- clickUrl: string().optional(),
43977
- actions: array(NotificationActionSchema).optional(),
43978
- sound: string().optional(),
43979
- ttl: number().optional(),
43980
- tag: string().optional(),
43981
- deviceId: number().optional(),
43982
- eventId: string().optional(),
43983
- metadata: record(string(), unknown()).optional(),
43984
- /**
43985
- * Values for the parameters the target's kind DECLARES in
43986
- * {@link TargetKindSchema} `deliveryParams`. Already validated against the
43987
- * declaration by the sender; a notifier reads only the keys it declared.
43988
- */
43989
- delivery: record(string(), DeliveryParamValueSchema).optional()
43990
- });
43991
- /** One declared native severity/priority level for a kind. */
43992
- var TargetKindLevelSchema = object({
43993
- id: string(),
43994
- label: string(),
43995
- /** Which canonical priority (1..5) this level maps to. `null` = qualitative-only. */
43996
- ordinal: number().int().min(1).max(5).nullable(),
43997
- flags: object({
43998
- critical: boolean().optional(),
43999
- silent: boolean().optional(),
44000
- noPush: boolean().optional()
44001
- }).optional(),
44002
- /** e.g. Pushover `emergency` requires `retry` / `expire`. */
44003
- requires: array(string()).optional(),
44004
- description: string().optional()
44222
+ method: string().optional(),
44223
+ /** The vocabulary action the step performs (`cover.open`), when it names one. */
44224
+ actionId: string().optional(),
44225
+ deviceId: number().int().optional(),
44226
+ /** What happened per device, when the step drove several (or a domain). */
44227
+ devices: array(StepDeviceTraceSchema).optional(),
44228
+ startedAt: number().optional(),
44229
+ endedAt: number().optional(),
44230
+ /**
44231
+ * The parameters the step SENT, after `{{vars.x}}` substitution — what the
44232
+ * device was actually asked. Bounded like trigger `vars`; a secret parameter
44233
+ * is shown as {@link REDACTED_ARG}. Absent on traces written before it existed.
44234
+ */
44235
+ args: record(string(), TraceValueSchema).optional(),
44236
+ /** `empty`: the target resolved to no device, so nothing was done — never silently `ok`. */
44237
+ outcome: _enum([
44238
+ "ok",
44239
+ "error",
44240
+ "not-run",
44241
+ "empty"
44242
+ ]),
44243
+ message: string().optional()
44005
44244
  });
44006
- /** The full capability block consulted before dispatch. */
44007
- var TargetKindCapsSchema = object({
44008
- attachments: object({
44009
- mediaTypes: array(AttachmentMediaTypeSchema),
44010
- mode: _enum([
44011
- "url",
44012
- "bytes",
44013
- "both"
44014
- ]),
44015
- max: number().int().nonnegative(),
44016
- maxBytes: number().int().positive().optional()
44017
- }),
44018
- /** Max action buttons (0 = none). */
44019
- actions: number().int().nonnegative(),
44245
+ var AutomationRunTraceSchema = object({
44246
+ runId: string().min(1),
44247
+ startedAt: number(),
44248
+ endedAt: number(),
44249
+ trigger: AutomationTriggerTraceSchema,
44250
+ conditions: array(AutomationConditionTraceNodeSchema),
44251
+ verdict: AutomationRunVerdictSchema.optional(),
44252
+ steps: array(AutomationStepTraceSchema),
44253
+ outcome: AutomationRunOutcomeSchema,
44254
+ /** How many identical consecutive skips this trace stands for (>= 1). */
44255
+ repeat: number().int().min(1),
44256
+ /** When the latest of those repeats happened. */
44257
+ lastAt: number(),
44020
44258
  /**
44021
- * Whether this kind renders a per-action ICON.
44022
- *
44023
- * `.optional()`, deliberately NOT `.default(false)`: a Zod default does not
44024
- * run on the addon cap path — three production failures in one day taught
44025
- * this repo that once. Absent is read as false by the degrade engine, which
44026
- * is the safe direction: an icon that is not rendered costs nothing, an icon
44027
- * assumed and dropped costs the operator's trust in the field.
44259
+ * A scheduler point's own outcome (D983). `outcome` carries the closest
44260
+ * automation outcome so a reader that does not know schedulers still reads
44261
+ * the trace; this field says exactly what happened.
44028
44262
  */
44029
- actionIcons: boolean().optional(),
44030
- levels: array(TargetKindLevelSchema),
44031
- format: array(NotificationFormatSchema),
44032
- clickUrl: boolean(),
44033
- sound: boolean(),
44034
- ttl: boolean(),
44035
- bodyMaxLen: number().int().positive()
44263
+ scheduler: SchedulerOutcomeSchema.optional()
44036
44264
  });
44037
44265
  /**
44038
- * `configSchema` is a `ConfigUISchema` tree passed through to the admin
44039
- * FormBuilder. Stored as `z.unknown()` at the cap seam (mirrors
44040
- * `device-provider.getChildCreationSchema` `CreationSchemaOutputSchema`) —
44041
- * the union is large and not meant for runtime validation here; the exported
44042
- * `TargetKind` type re-tightens `configSchema` to `ConfigUISchema`.
44266
+ * What the hub's `runs` ledger holds for one owner (`automation:<blockId>` or
44267
+ * `action:<actionId>`): the cooldown stamp and the trace ring.
44043
44268
  */
44044
- var ConfigSchemaPassthrough$4 = unknown();
44045
- var TargetKindSchema = object({
44046
- kind: string(),
44047
- label: string(),
44048
- icon: string(),
44049
- /** Stamped by each provider so the concat-fanned catalog stays routable. */
44050
- addonId: string(),
44051
- /**
44052
- * URL of the kind's bundled BRAND icon, served by the providing addon over
44053
- * its own `addon-routes` surface (`/addon/<addonId>/icons/<kind>`). Absent
44054
- * when the addon bundles no icon for that kind — the client then falls back
44055
- * to a neutral glyph rather than rendering the raw `icon` NAME as text.
44056
- *
44057
- * Root-relative on purpose: it resolves against whatever origin serves a web
44058
- * client, and a native client joins it onto its own hub base.
44059
- *
44060
- * DECLARED here deliberately. It used to travel as an undeclared passthrough
44061
- * field that survived only because the runtime cap-router forwards provider
44062
- * output verbatim — so every consumer had to re-declare it by hand to stop
44063
- * its own Zod parse from stripping it, and the whole arrangement would have
44064
- * broken silently the moment output validation was tightened anywhere.
44065
- */
44066
- iconUrl: string().optional(),
44067
- /**
44068
- * Media type of {@link iconUrl} (`image/svg+xml`, `image/png`, …).
44069
- *
44070
- * The server knows this and therefore says it, because the client cannot
44071
- * safely guess: a React-Native client renders SVG and raster through two
44072
- * DIFFERENT components (`react-native-svg` vs `expo-image` — expo-image does
44073
- * not decode SVG on iOS/Android), so without this it silently fell back to a
44074
- * placeholder glyph for every vector icon while the web build looked fine.
44075
- *
44076
- * Absent when {@link iconUrl} is absent, or for a legacy provider that has
44077
- * not been updated — a client that cannot determine the type should prefer
44078
- * its raster path, which is the safe default for an unknown image.
44079
- */
44080
- iconMediaType: string().optional(),
44081
- configSchema: ConfigSchemaPassthrough$4,
44082
- /**
44083
- * The config keys that decide WHERE this kind's secrets are sent (server,
44084
- * base URL, instance, chat, recipient). A save that changes any of them
44085
- * while leaving a secret redacted is refused by the provider (D634), so an
44086
- * editor uses this to ask for the secret on exactly those edits instead of
44087
- * on every edit.
44088
- *
44089
- * Optional: absent from a provider that holds no secret (the Home Assistant
44090
- * kinds) and from a provider older than this field — an editor that finds
44091
- * it absent must assume ANY edit may need the secret.
44092
- */
44093
- destinationKeys: array(string()).optional(),
44094
- supportsDiscovery: boolean(),
44095
- /**
44096
- * Extra delivery parameters a rule may set for a target of this kind (D938).
44097
- * Absent = none; the rule editor then offers nothing.
44098
- */
44099
- deliveryParams: array(DeliveryParamSchema).optional(),
44100
- caps: TargetKindCapsSchema
44269
+ var AutomationStateDocSchema = object({
44270
+ version: literal(1),
44271
+ lastRunStartedAt: number().nullable(),
44272
+ traces: array(AutomationRunTraceSchema)
44101
44273
  });
44102
44274
  /**
44103
- * A persisted target. `config` holds secrets; providers REDACT secret fields
44104
- * (return a presence marker only) when serving `listTargets` — never
44105
- * round-trip a stored secret to the UI.
44275
+ * Actions — named, runnable things an operator (or an automation) can start,
44276
+ * declared as LIST ENTRIES, never as devices.
44277
+ *
44278
+ * An entry is either **internal** (a short list of cap/wait steps kept in the
44279
+ * hub's `actions` record kind) or declared by an addon through the
44280
+ * `action-source` collection (a Home Assistant script, a scene …). The one
44281
+ * surface the UI and automations talk to is the `actions` cap; it keeps no
44282
+ * catalog of its own (D3) — every `list` asks the providers live.
44283
+ *
44284
+ * This file is the data half: the entry schema, the variables an entry may
44285
+ * declare, and the pure resolution of the values a run was given. It holds no
44286
+ * runtime.
44106
44287
  */
44107
- var TargetSchema = object({
44108
- id: string(),
44109
- name: string(),
44110
- kind: string(),
44111
- addonId: string(),
44112
- enabled: boolean(),
44113
- config: record(string(), unknown())
44288
+ /** What a variable's value is. `select` takes one of `options`. */
44289
+ var ActionVariableTypeSchema = _enum([
44290
+ "string",
44291
+ "number",
44292
+ "boolean",
44293
+ "select"
44294
+ ]);
44295
+ var ACTION_VARIABLE_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
44296
+ var ActionVariableValueSchema = union([
44297
+ string(),
44298
+ number(),
44299
+ boolean()
44300
+ ]);
44301
+ /**
44302
+ * One declared variable. Steps reference it as `{ $var: 'name' }` (the whole
44303
+ * value) or `{{vars.name}}` (inside a string) in their args.
44304
+ */
44305
+ var ActionVariableSchema = object({
44306
+ name: string().regex(ACTION_VARIABLE_NAME_RE),
44307
+ label: string().min(1).max(120).optional(),
44308
+ type: ActionVariableTypeSchema,
44309
+ required: boolean().optional(),
44310
+ default: ActionVariableValueSchema.optional(),
44311
+ /** The allowed values of a `select`. */
44312
+ options: array(string().min(1)).min(1).optional()
44313
+ }).superRefine((v, ctx) => {
44314
+ if (v.type === "select" && v.options === void 0) ctx.addIssue({
44315
+ code: "custom",
44316
+ message: "a select variable needs options",
44317
+ path: ["options"]
44318
+ });
44319
+ if (v.default !== void 0 && variableValueError(v, v.default) !== null) ctx.addIssue({
44320
+ code: "custom",
44321
+ message: variableValueError(v, v.default) ?? "invalid default",
44322
+ path: ["default"]
44323
+ });
44114
44324
  });
44115
- /** A discovery-surfaced candidate (config is partial + non-secret). */
44116
- var DiscoveredTargetSchema = object({
44117
- kind: string(),
44118
- suggestedName: string(),
44119
- config: record(string(), unknown())
44325
+ /** Why `value` is not a legal value for the variable, or null when it is. */
44326
+ function variableValueError(variable, value) {
44327
+ switch (variable.type) {
44328
+ case "string": return typeof value === "string" ? null : `variable "${variable.name}" must be a string`;
44329
+ case "number": return typeof value === "number" && Number.isFinite(value) ? null : `variable "${variable.name}" must be a number`;
44330
+ case "boolean": return typeof value === "boolean" ? null : `variable "${variable.name}" must be true or false`;
44331
+ case "select": return typeof value === "string" && (variable.options ?? []).includes(value) ? null : `variable "${variable.name}" must be one of ${(variable.options ?? []).join(", ")}`;
44332
+ }
44333
+ }
44334
+ var ActionSourceKindSchema = _enum(["internal", "addon"]);
44335
+ function isInternalActionId(actionId) {
44336
+ return actionId.startsWith("internal:") && actionId.length > 9;
44337
+ }
44338
+ /** The addon behind a `<addonId>:<localId>` id, or null for anything else (internal included). */
44339
+ function addonIdOfActionId(actionId) {
44340
+ if (isInternalActionId(actionId)) return null;
44341
+ const at = actionId.indexOf(":");
44342
+ return at > 0 && at < actionId.length - 1 ? actionId.slice(0, at) : null;
44343
+ }
44344
+ var ActionStatusSchema = object({
44345
+ isRunning: boolean(),
44346
+ /** Ms epoch the latest run STARTED; null when it never ran. */
44347
+ lastRunAt: number().nullable(),
44348
+ /** The latest run's failure; null on success or when it never ran. */
44349
+ lastError: string().nullable()
44120
44350
  });
44121
- /** The degrade engine's report — what was resolved / dropped / degraded. */
44122
- var RenderedAsSchema = object({
44123
- level: string(),
44124
- format: NotificationFormatSchema,
44125
- attachmentsSent: number().int().nonnegative(),
44126
- actionsSent: number().int().nonnegative(),
44127
- truncated: boolean(),
44128
- dropped: array(string())
44351
+ var ActionEntrySchema = object({
44352
+ /** `internal:<uuid>` or `<addonId>:<localId>`. */
44353
+ id: string().min(3),
44354
+ name: string().min(1).max(120),
44355
+ /** The addon that declared it; `core-blocks` for an internal one. */
44356
+ addonId: string().min(1),
44357
+ source: ActionSourceKindSchema,
44358
+ /** An addon-declared entry is edited where it was declared. */
44359
+ readOnly: boolean(),
44360
+ /** Internal only: cap and wait steps. No action-in-action, so no cycles. */
44361
+ steps: array(ActionStepSchema).min(1).max(50).optional(),
44362
+ variables: array(ActionVariableSchema).max(20).optional(),
44363
+ status: ActionStatusSchema
44364
+ }).superRefine((entry, ctx) => {
44365
+ if (entry.source === "internal") {
44366
+ if (!isInternalActionId(entry.id)) ctx.addIssue({
44367
+ code: "custom",
44368
+ message: "an internal action id is internal:<uuid>",
44369
+ path: ["id"]
44370
+ });
44371
+ return;
44372
+ }
44373
+ if (entry.steps !== void 0) ctx.addIssue({
44374
+ code: "custom",
44375
+ message: "only an internal action carries steps",
44376
+ path: ["steps"]
44377
+ });
44378
+ if (!entry.readOnly) ctx.addIssue({
44379
+ code: "custom",
44380
+ message: "an addon action is read-only here",
44381
+ path: ["readOnly"]
44382
+ });
44383
+ if (addonIdOfActionId(entry.id) === null) ctx.addIssue({
44384
+ code: "custom",
44385
+ message: "an addon action id is <addonId>:<localId>",
44386
+ path: ["id"]
44387
+ });
44129
44388
  });
44130
- var SendResultSchema = object({
44131
- success: boolean(),
44132
- error: string().optional(),
44133
- renderedAs: RenderedAsSchema.optional()
44389
+ /** What an operator writes for an internal action. */
44390
+ var ActionInputSchema = object({
44391
+ name: string().min(1).max(120),
44392
+ steps: array(ActionStepSchema).min(1).max(50),
44393
+ variables: array(ActionVariableSchema).max(20).optional()
44134
44394
  });
44135
- /** Same shape as SendResult — kept as a distinct name for the test panel. */
44136
- var TestResultSchema = SendResultSchema;
44395
+ /** Who started a run. Absent = the operator pressed it. */
44396
+ var ActionRunOriginSchema = object({
44397
+ /** The automation block whose step started it. */
44398
+ blockId: string().min(1).optional() });
44137
44399
  /**
44138
- * Pre-save credential probe against a partial (unsaved) target config.
44139
- * `resolvedUrl` never includes secrets (token stripped from path).
44400
+ * `started` = the caller did not ask to wait. `timed-out` = the run reached the
44401
+ * ceiling (`ACTION_RUN_MAX_MS`) and was stopped; it is never a `ran`.
44140
44402
  */
44141
- var ProbeTargetConfigResultSchema = object({
44142
- ok: boolean(),
44143
- resolvedUrl: string(),
44144
- httpStatus: number().int().optional(),
44145
- stateInstance: string().optional(),
44146
- error: string().optional()
44403
+ var ActionRunOutcomeSchema = union([
44404
+ AutomationRunOutcomeSchema,
44405
+ literal("started"),
44406
+ literal("timed-out")
44407
+ ]);
44408
+ var ActionRunResultSchema = object({
44409
+ runId: string().min(1),
44410
+ outcome: ActionRunOutcomeSchema,
44411
+ /** Why it did not run, or what failed. */
44412
+ message: string().optional()
44147
44413
  });
44148
- method(object({}), array(TargetKindSchema)), method(object({}), array(TargetSchema), { auth: "admin" }), method(object({ targetId: string() }), TargetSchema, { auth: "admin" }), method(object({
44149
- kind: string(),
44150
- config: record(string(), unknown()).optional(),
44151
- /**
44152
- * When editing / duplicating, the blank password field never round-trips
44153
- * the stored token. Pass the source target id so the provider can restore
44154
- * secrets server-side before dialling (same merge as upsert).
44155
- */
44156
- targetId: string().optional()
44157
- }), array(DiscoveredTargetSchema), { auth: "admin" }), method(object({
44158
- kind: string(),
44159
- config: record(string(), unknown()),
44160
- /** See `discoverTargets.targetId` — restore stored secrets for a blank password. */
44161
- targetId: string().optional()
44162
- }), ProbeTargetConfigResultSchema, {
44163
- kind: "mutation",
44164
- auth: "admin"
44165
- }), method(object({
44166
- targetId: string(),
44167
- notification: NotificationSchema
44168
- }), SendResultSchema, {
44169
- kind: "mutation",
44170
- auth: "admin"
44171
- }), method(object({
44172
- targetId: string(),
44173
- sample: NotificationSchema.optional()
44174
- }), TestResultSchema, {
44175
- kind: "mutation",
44176
- auth: "admin"
44177
- }), method(object({
44178
- target: TargetSchema,
44179
- /**
44180
- * Duplicate flow: create a NEW target id while copying secrets from an
44181
- * existing row. The UI never holds the stored token; blank / redacted
44182
- * password fields are restored from this source (D634 still applies if
44183
- * destinations diverge without a re-typed secret).
44184
- */
44185
- cloneSecretsFrom: string().optional()
44186
- }), TargetSchema, {
44187
- kind: "mutation",
44188
- auth: "admin"
44189
- }), method(object({ targetId: string() }), _void(), {
44190
- kind: "mutation",
44191
- auth: "admin"
44192
- }), method(object({
44193
- targetId: string(),
44194
- enabled: boolean()
44195
- }), _void(), {
44196
- kind: "mutation",
44197
- auth: "admin"
44414
+ _enum([
44415
+ "not-found",
44416
+ "read-only",
44417
+ "invalid-variables",
44418
+ "invalid-steps",
44419
+ "not-linked",
44420
+ "busy"
44421
+ ]);
44422
+ object({
44423
+ actionId: string(),
44424
+ runId: string(),
44425
+ isRunning: boolean(),
44426
+ /** Set when the run ended. */
44427
+ outcome: AutomationRunOutcomeSchema.optional(),
44428
+ lastRunAt: number().nullable(),
44429
+ lastError: string().nullable()
44430
+ });
44431
+ /** A bare number accepted as a base unit — the save succeeded, say so. */
44432
+ var UnitWarningSchema = object({
44433
+ /** Where in the saved record, e.g. `conditions.children.0` or `steps.2.args.grams`. */
44434
+ path: string(),
44435
+ deviceId: number().int().optional(),
44436
+ field: string(),
44437
+ value: number(),
44438
+ assumedUnit: string(),
44439
+ message: string()
44198
44440
  });
44199
44441
  _enum([
44200
44442
  "automation",
@@ -44263,6 +44505,8 @@ method(object({}), array(ActionEntrySchema), { auth: "admin" }), method(object({
44263
44505
  kind: "mutation",
44264
44506
  auth: "admin"
44265
44507
  });
44508
+ /** `timeoutMs` of `actions.run`: a waited call outlives any legal run. */
44509
+ var ACTION_RUN_TIMEOUT_MS = 363e4;
44266
44510
  /**
44267
44511
  * actions — the ONE surface for runnable actions, for the UI and for
44268
44512
  * automations. Provided by the core-blocks builtin on the hub.
@@ -44281,6 +44525,12 @@ method(object({}), array(ActionEntrySchema), { auth: "admin" }), method(object({
44281
44525
  * An admin, and an in-process caller (an automation block), may run any action.
44282
44526
  * Every refusal is typed (`[not-linked] …`) and logged.
44283
44527
  *
44528
+ * **A run lasts at most `ACTION_RUN_MAX_MS` (60 min).** The provider stops a
44529
+ * run that reaches it and answers `timed-out` (never `ran`); an action whose
44530
+ * `wait` steps alone add up to more is refused at create/update
44531
+ * (`[invalid-steps]`). `run` declares a `timeoutMs` above that ceiling, so a
44532
+ * waited call (an automation step) is never cut by the 60 s transport default.
44533
+ *
44284
44534
  * A second `run` of an action that is already running is REFUSED — traced and
44285
44535
  * logged — never queued.
44286
44536
  */
@@ -44307,7 +44557,8 @@ method(object({}), array(ActionEntrySchema), { auth: "admin" }), method(object({
44307
44557
  role: "viewer",
44308
44558
  auth: "protected",
44309
44559
  kind: "mutation",
44310
- caller: "required"
44560
+ caller: "required",
44561
+ timeoutMs: ACTION_RUN_TIMEOUT_MS
44311
44562
  }), method(ActionIdInput, _void(), {
44312
44563
  kind: "mutation",
44313
44564
  auth: "admin"
@@ -48064,37 +48315,6 @@ method(object({
48064
48315
  kind: "mutation",
48065
48316
  auth: "admin"
48066
48317
  }), method(object({ blockIds: array(string()) }), object({ states: array(CompositionBlockStateSchema) }), { auth: "admin" });
48067
- var ConnectionTestOutcomeSchema = discriminatedUnion("outcome", [
48068
- object({
48069
- outcome: literal("validated"),
48070
- /** Round-trip of the sign-in, when the provider measured it. */
48071
- latencyMs: number().nonnegative().optional(),
48072
- /** Optional human detail worth showing next to the tick
48073
- * ("3 devices visible on this account"). */
48074
- detail: string().optional()
48075
- }).strict(),
48076
- object({
48077
- outcome: literal("rejected"),
48078
- error: string()
48079
- }).strict(),
48080
- object({
48081
- outcome: literal("inconclusive"),
48082
- error: string()
48083
- }).strict()
48084
- ]);
48085
- var ConnectionTestInputSchema = object({
48086
- /** Candidate integration settings, exactly as the create form collected them. */
48087
- settings: record(string(), unknown()) });
48088
- /**
48089
- * What the provider's test actually DOES, so the UI can say it in words before
48090
- * the operator presses the button ("Signs in to the Dreo cloud"). Purely
48091
- * descriptive — it never changes routing.
48092
- */
48093
- var ConnectionTestDescriptorSchema = object({ label: string() });
48094
- method(ConnectionTestInputSchema, ConnectionTestOutcomeSchema, {
48095
- kind: "mutation",
48096
- auth: "admin"
48097
- }), method(_void(), ConnectionTestDescriptorSchema, { auth: "admin" });
48098
48318
  object({
48099
48319
  /** True when the upstream system considers the entity connected. */
48100
48320
  connected: boolean(),
@@ -48352,6 +48572,9 @@ var MediaPlayerStatusSchema = object({
48352
48572
  /** Repeat mode. Null when no repeat surface.
48353
48573
  * Pair with `DeviceFeature.MediaPlayerRepeat`. */
48354
48574
  repeat: MediaPlayerRepeatSchema.nullable(),
48575
+ /** Ms epoch when `position` was read from the device. Null when the driver
48576
+ * does not say; a UI that advances the position while playing counts from it. */
48577
+ positionUpdatedAt: number().nullable().default(null),
48355
48578
  /** Ms epoch when the slice was last updated. */
48356
48579
  lastChangedAt: number()
48357
48580
  });
@@ -48931,7 +49154,9 @@ var ThresholdTransformDraftSchema = object({
48931
49154
  comparison: _enum(["gte", "lte"]),
48932
49155
  threshold: number(),
48933
49156
  startDwellMs: number().nonnegative(),
48934
- stopDwellMs: number().nonnegative()
49157
+ stopDwellMs: number().nonnegative(),
49158
+ /** Samples a start needs; absent = the compiler's default for the source (2 for running power, else 1). */
49159
+ minSamples: number().int().min(1).optional()
48935
49160
  });
48936
49161
  var CustomizeTransformDraftSchema = discriminatedUnion("kind", [
48937
49162
  IdentityTransformDraftSchema,
@@ -53884,6 +54109,7 @@ var IntegrationWithStateSchema = object({
53884
54109
  id: string(),
53885
54110
  addonId: string(),
53886
54111
  name: string(),
54112
+ /** A projection of the instance body's switch (`setInstanceEnabled` is the only writer). */
53887
54113
  enabled: boolean(),
53888
54114
  info: record(string(), unknown()).readonly(),
53889
54115
  /** The discovery candidate this integration was set up from (D984). */
@@ -53896,6 +54122,7 @@ var IntegrationLiteSchema = object({
53896
54122
  id: string(),
53897
54123
  addonId: string(),
53898
54124
  name: string(),
54125
+ /** A projection of the instance body's switch (`setInstanceEnabled` is the only writer). */
53899
54126
  enabled: boolean(),
53900
54127
  info: record(string(), unknown()).readonly(),
53901
54128
  /** The discovery candidate this integration was set up from (D984). */
@@ -53941,10 +54168,9 @@ var AvailableIntegrationTypeSchema = object({
53941
54168
  * locations" checkbox. Provider-declared in the addon manifest. */
53942
54169
  supportsLocationImport: boolean(),
53943
54170
  /**
53944
- * True when this integration DECLARES a pre-creation test (the
53945
- * `connection-test` cap, or a broker whose settings it stores). Drives the
53946
- * Test button: an integration that cannot be tested must say so up front
53947
- * rather than offering a button that always answers the same nonsense.
54171
+ * True when this integration's instances declare a Test (`integration-instances.describe().canTest`,
54172
+ * D1016). An integration that cannot be tested must say so up front rather than offering a
54173
+ * button that always answers the same nonsense.
53948
54174
  */
53949
54175
  canTest: boolean(),
53950
54176
  existingInstances: array(object({
@@ -53995,15 +54221,21 @@ var TestConnectionResultSchema = object({
53995
54221
  var CreateIntegrationInputSchema = object({
53996
54222
  addonId: string(),
53997
54223
  name: string(),
53998
- enabled: boolean().optional(),
53999
54224
  info: record(string(), unknown()).optional(),
54000
54225
  /** `stableId` of the discovery candidate the form was seeded from (D984). */
54001
54226
  originStableId: string().optional(),
54002
- settings: record(string(), unknown()).optional()
54227
+ settings: record(string(), unknown()).optional(),
54228
+ /** The instance kind being created, for a provider with several; omitted = its only testable kind. */
54229
+ kind: string().min(1).optional()
54003
54230
  });
54004
54231
  var UpdateIntegrationInputSchema = object({
54005
54232
  id: string(),
54006
54233
  name: string().optional(),
54234
+ /**
54235
+ * Accepted for a FIXED builtin only (`info.fixed`: alarm panel, camera grid, core blocks,
54236
+ * terminal), which keeps no instance record: the registry flag is its one store. Any other
54237
+ * integration is switched through `integration-instances.setInstanceEnabled`.
54238
+ */
54007
54239
  enabled: boolean().optional(),
54008
54240
  info: record(string(), unknown()).optional()
54009
54241
  });
@@ -54020,13 +54252,7 @@ method(_void(), array(IntegrationWithStateSchema)), method(object({ id: string()
54020
54252
  }), method(object({ id: string() }), DeleteIntegrationResultSchema, {
54021
54253
  kind: "mutation",
54022
54254
  auth: "admin"
54023
- }), method(_void(), array(AvailableIntegrationTypeSchema), { auth: "admin" }), method(object({
54024
- addonId: string(),
54025
- settings: record(string(), unknown())
54026
- }), TestConnectionResultSchema, {
54027
- kind: "mutation",
54028
- auth: "admin"
54029
- });
54255
+ }), method(_void(), array(AvailableIntegrationTypeSchema), { auth: "admin" });
54030
54256
  /**
54031
54257
  * `integration-instances` - the connection of an addon that holds ONE or SEVERAL
54032
54258
  * (an account, a relay, a destination) as typed records (D985, D986). The addon's
@@ -54051,7 +54277,7 @@ var IntegrationInstanceIdSchema = string().min(1);
54051
54277
  var IntegrationInstanceModeSchema = _enum(["single", "multiple"]);
54052
54278
  /**
54053
54279
  * What the addon's instances ARE for the Integrations page (planning#416). `devices`: each
54054
- * instance is an integration that brings devices (the registry owns its on/off switch);
54280
+ * instance is an integration that brings devices (its record body owns the on/off switch);
54055
54281
  * `services`: a connection configured from the addon's own function page, never listed on
54056
54282
  * Integrations.
54057
54283
  * It is the same vocabulary as the manifest's `integrationRole`, which stays as an override.
@@ -54094,18 +54320,38 @@ var IntegrationInstanceKindSchema = object({
54094
54320
  /** Relative hub path to disconnect that account. */
54095
54321
  disconnectPath: string().min(1).optional()
54096
54322
  });
54323
+ /**
54324
+ * How devices of an instance are found. `none`: the operator adds them by hand; `lan`: the addon
54325
+ * scans the network before any instance exists (the wizard offers the candidates); `account`: the
54326
+ * devices appear after the instance signs in. `scopedToInstance`: a discovery run belongs to ONE
54327
+ * instance and its candidates are claimed by it.
54328
+ */
54329
+ var IntegrationInstanceDiscoverySchema = object({
54330
+ mode: _enum([
54331
+ "none",
54332
+ "lan",
54333
+ "account"
54334
+ ]),
54335
+ scopedToInstance: boolean()
54336
+ });
54337
+ /**
54338
+ * One link a kind of this provider declares (D1013 rule 5): the body `field` of an instance of
54339
+ * `kind` holds the id of an instance of the function cap `to.cap` (of kind `to.kind`, when set).
54340
+ * The hub indexes these so the target's delete is refused while a link names it.
54341
+ */
54342
+ var IntegrationInstanceLinkSchema = object({
54343
+ kind: string().min(1),
54344
+ field: string().min(1),
54345
+ to: object({
54346
+ cap: string().min(1),
54347
+ kind: string().min(1).optional()
54348
+ })
54349
+ });
54097
54350
  var IntegrationInstanceDescriptionSchema = object({
54098
54351
  /** What the instances are for the Integrations page; see {@link IntegrationInstanceRoleSchema}. */
54099
54352
  role: IntegrationInstanceRoleSchema,
54100
54353
  /** How the devices of an instance are found; absent means `{ mode: 'none' }`. */
54101
- discovery: object({
54102
- mode: _enum([
54103
- "none",
54104
- "lan",
54105
- "account"
54106
- ]),
54107
- scopedToInstance: boolean()
54108
- }).optional(),
54354
+ discovery: IntegrationInstanceDiscoverySchema.optional(),
54109
54355
  /** `single`: at most one instance can exist (Loki). `multiple`: an account each. */
54110
54356
  instanceMode: IntegrationInstanceModeSchema,
54111
54357
  /** What the instance is, for the UI (`destination`, `relay`, `account`). */
@@ -54126,7 +54372,9 @@ var IntegrationInstanceDescriptionSchema = object({
54126
54372
  * `createInstance` without an `id` works: the provider mints it. Absent means the caller must
54127
54373
  * send an id (the UI then mints an opaque one).
54128
54374
  */
54129
- mintsId: boolean().optional()
54375
+ mintsId: boolean().optional(),
54376
+ /** The links to other instances the provider's kinds declare; absent means none. */
54377
+ links: array(IntegrationInstanceLinkSchema).optional()
54130
54378
  });
54131
54379
  var IntegrationInstanceStatusSchema = object({
54132
54380
  state: _enum([
@@ -54146,8 +54394,8 @@ var IntegrationInstanceSchema = object({
54146
54394
  configured: boolean(),
54147
54395
  /**
54148
54396
  * The instance's own on/off switch (D996), derived from the record body (`enabled !== false`,
54149
- * so a row written before the field existed is on). Absent when the `integrations` registry
54150
- * owns the switch (`describe().role` is `devices`): read it from the registry row.
54397
+ * so a row written before the field existed is on). The same for every role, `devices` included:
54398
+ * the body is the one store, `setInstanceEnabled` the one writer (epic #440, step 3).
54151
54399
  */
54152
54400
  enabled: boolean().optional(),
54153
54401
  /** The kind of this instance (one of `describe().kinds[].id`), when the provider has kinds. */
@@ -54197,7 +54445,8 @@ var integrationInstancesCapability = {
54197
54445
  auth: "admin"
54198
54446
  }),
54199
54447
  /**
54200
- * Switch ONE instance on or off. A row control, not a form field: `updateInstance.values` is the
54448
+ * Switch ONE instance on or off, for every role; a missing record is created from the addon's
54449
+ * initial body. A row control, not a form field: `updateInstance.values` is the
54201
54450
  * form patch (D62, D996). An off instance keeps its record and secrets and does no work.
54202
54451
  */
54203
54452
  setInstanceEnabled: method(object({
@@ -57008,6 +57257,8 @@ var MigrationIntegrationSchema = object({
57008
57257
  addonId: string(),
57009
57258
  name: string(),
57010
57259
  info: Rows,
57260
+ /** The registry's stored switch: read by the one-switch migration, nothing else. */
57261
+ enabled: boolean().optional(),
57011
57262
  originStableId: string().optional()
57012
57263
  });
57013
57264
  var MigrationDeviceSchema = object({
@@ -62244,13 +62495,6 @@ var AddBrokerInputSchema = object({
62244
62495
  });
62245
62496
  var AddBrokerResultSchema = object({ id: string() });
62246
62497
  var IdInputSchema = object({ id: string() });
62247
- var TestResultSchema$1 = discriminatedUnion("ok", [object({
62248
- ok: literal(true),
62249
- latencyMs: number()
62250
- }), object({
62251
- ok: literal(false),
62252
- error: string()
62253
- })]);
62254
62498
  var StartEmbeddedInputSchema = object({
62255
62499
  port: number().int().min(1).max(65535).default(1883),
62256
62500
  /** Allow anonymous connect (no username/password). Default: false. */
@@ -62287,10 +62531,6 @@ var mqttBrokerCapability = {
62287
62531
  kind: "mutation",
62288
62532
  auth: "admin"
62289
62533
  }),
62290
- testConnection: method(IdInputSchema, TestResultSchema$1, {
62291
- kind: "mutation",
62292
- auth: "admin"
62293
- }),
62294
62534
  startEmbeddedBroker: method(StartEmbeddedInputSchema, StartEmbeddedResultSchema, {
62295
62535
  kind: "mutation",
62296
62536
  auth: "admin"
@@ -66545,14 +66785,6 @@ object({
66545
66785
  empty: boolean().nullable(),
66546
66786
  /** True while the pump is running. Null while unknown. */
66547
66787
  pumpRunning: boolean().nullable(),
66548
- /** Water drunk in the last drink, in litres. */
66549
- lastDrink: number().min(0).nullable().meta(readingMeta("volume")),
66550
- /** Water drunk in the current hour, in litres. */
66551
- currentHourDrink: number().min(0).nullable().meta(readingMeta("volume")),
66552
- /** Water drunk over the last 24 hours (rolling), in litres. */
66553
- last24hDrink: number().min(0).nullable().meta(readingMeta("volume")),
66554
- /** Water drunk since local midnight, in litres. Null when the fountain has no such sensor. */
66555
- todayDrink: number().min(0).nullable().meta(readingMeta("volume")),
66556
66788
  /** Decoded fault message. Null means healthy; a non-null string is an active fault. */
66557
66789
  error: string().nullable(),
66558
66790
  /** Ms epoch when the slice was last refreshed. */
@@ -66565,9 +66797,6 @@ DeviceType.PetFountain, method(object({
66565
66797
  }), _void(), {
66566
66798
  kind: "mutation",
66567
66799
  auth: "protected"
66568
- }), method(object({ deviceId: DeviceIdSchema$1 }), _void(), {
66569
- kind: "mutation",
66570
- auth: "protected"
66571
66800
  });
66572
66801
  /**
66573
66802
  * The wire shapes of the Auto tune plan and apply (D745), used by the
@@ -73917,7 +74146,7 @@ var TrainingProviderTypeSchema = object({
73917
74146
  label: string(),
73918
74147
  /** Path under the addon package (e.g. `assets/training-modal/icon.svg`). */
73919
74148
  iconAsset: string(),
73920
- /** Owning `training-provider` addon — collection selector for createEntry. */
74149
+ /** Owning `training-provider` addon. */
73921
74150
  addonId: string(),
73922
74151
  /**
73923
74152
  * Fields for one entry of this type (credentials + defaults). Absent on a
@@ -73962,36 +74191,6 @@ var TrainingProviderDescriptorSchema = object({
73962
74191
  */
73963
74192
  formValues: record(string(), unknown()).optional()
73964
74193
  });
73965
- /**
73966
- * Patch one entry's name, credentials and defaults. Pin with owning `{ addonId }`.
73967
- * An omitted or empty `tokenSecret` means KEEP the stored secret (D787).
73968
- * `{ $secretClear: true }` clears it.
73969
- */
73970
- var TrainingProviderUpdateEntryInputSchema = object({
73971
- entryId: string().min(1),
73972
- name: string().min(1),
73973
- tokenId: string().optional(),
73974
- tokenSecret: union([string(), object({ $secretClear: literal(true) })]).optional(),
73975
- environment: string().optional(),
73976
- gpuType: string().optional(),
73977
- region: string().optional(),
73978
- costCapUsd: number().nonnegative().optional(),
73979
- maxRuntimeSec: number().int().positive().optional(),
73980
- failedDatasetGraceHours: number().nonnegative().optional()
73981
- });
73982
- var TrainingCredentialCheckSchema = object({
73983
- ok: boolean(),
73984
- /** Workspace / account name, when the provider says. */
73985
- account: string().optional(),
73986
- reason: _enum([
73987
- "missing",
73988
- "invalid",
73989
- "forbidden",
73990
- "network",
73991
- "quota"
73992
- ]).optional(),
73993
- detail: string().optional()
73994
- });
73995
74194
  var ProviderJobStateSchema = _enum([
73996
74195
  "pending",
73997
74196
  "starting",
@@ -74039,22 +74238,6 @@ var TrainingLogLineSchema = object({
74039
74238
  text: string()
74040
74239
  });
74041
74240
  method(object({}), array(TrainingProviderDescriptorSchema).readonly(), { auth: "admin" }), method(object({}), array(TrainingProviderTypeSchema).readonly(), { auth: "admin" }), method(object({}), array(TrainingProviderEntrySchema).readonly(), { auth: "admin" }), method(object({
74042
- typeId: string().min(1),
74043
- name: string().min(1)
74044
- }), object({ entryId: string() }), {
74045
- kind: "mutation",
74046
- auth: "admin"
74047
- }), method(object({ entryId: string().min(1) }), object({ ok: literal(true) }), {
74048
- kind: "mutation",
74049
- auth: "admin"
74050
- }), method(TrainingProviderUpdateEntryInputSchema, object({ ok: literal(true) }), {
74051
- kind: "mutation",
74052
- auth: "admin"
74053
- }), method(object({ entryId: string().min(1) }), TrainingCredentialCheckSchema, {
74054
- kind: "mutation",
74055
- auth: "admin",
74056
- timeoutMs: 3e4
74057
- }), method(object({
74058
74241
  entryId: string().min(1),
74059
74242
  gpuType: string(),
74060
74243
  region: string(),
@@ -77440,20 +77623,6 @@ Object.freeze({
77440
77623
  access: "view",
77441
77624
  role: "admin"
77442
77625
  },
77443
- "connectionTest.describeTest": {
77444
- capName: "connection-test",
77445
- capScope: "system",
77446
- addonId: null,
77447
- access: "view",
77448
- role: "admin"
77449
- },
77450
- "connectionTest.testSettings": {
77451
- capName: "connection-test",
77452
- capScope: "system",
77453
- addonId: null,
77454
- access: "create",
77455
- role: "admin"
77456
- },
77457
77626
  "connectivity.getStatus": {
77458
77627
  capName: "connectivity",
77459
77628
  capScope: "device",
@@ -79820,13 +79989,6 @@ Object.freeze({
79820
79989
  access: "view",
79821
79990
  role: "admin"
79822
79991
  },
79823
- "integrations.testConnection": {
79824
- capName: "integrations",
79825
- capScope: "system",
79826
- addonId: null,
79827
- access: "create",
79828
- role: "admin"
79829
- },
79830
79992
  "integrations.update": {
79831
79993
  capName: "integrations",
79832
79994
  capScope: "system",
@@ -81059,13 +81221,6 @@ Object.freeze({
81059
81221
  access: "create",
81060
81222
  role: "admin"
81061
81223
  },
81062
- "mqttBroker.testConnection": {
81063
- capName: "mqtt-broker",
81064
- capScope: "system",
81065
- addonId: null,
81066
- access: "create",
81067
- role: "admin"
81068
- },
81069
81224
  "nativeObjectDetection.getOptions": {
81070
81225
  capName: "native-object-detection",
81071
81226
  capScope: "device",
@@ -81941,13 +82096,6 @@ Object.freeze({
81941
82096
  access: "view",
81942
82097
  role: "viewer"
81943
82098
  },
81944
- "petFountain.resetDailyConsumption": {
81945
- capName: "pet-fountain",
81946
- capScope: "device",
81947
- addonId: null,
81948
- access: "delete",
81949
- role: "viewer"
81950
- },
81951
82099
  "petFountain.setPump": {
81952
82100
  capName: "pet-fountain",
81953
82101
  capScope: "device",
@@ -85903,20 +86051,6 @@ Object.freeze({
85903
86051
  access: "create",
85904
86052
  role: "admin"
85905
86053
  },
85906
- "trainingProvider.createEntry": {
85907
- capName: "training-provider",
85908
- capScope: "system",
85909
- addonId: null,
85910
- access: "create",
85911
- role: "admin"
85912
- },
85913
- "trainingProvider.deleteEntry": {
85914
- capName: "training-provider",
85915
- capScope: "system",
85916
- addonId: null,
85917
- access: "delete",
85918
- role: "admin"
85919
- },
85920
86054
  "trainingProvider.describe": {
85921
86055
  capName: "training-provider",
85922
86056
  capScope: "system",
@@ -85987,13 +86121,6 @@ Object.freeze({
85987
86121
  access: "create",
85988
86122
  role: "admin"
85989
86123
  },
85990
- "trainingProvider.updateEntry": {
85991
- capName: "training-provider",
85992
- capScope: "system",
85993
- addonId: null,
85994
- access: "create",
85995
- role: "admin"
85996
- },
85997
86124
  "trainingProvider.uploadDataset": {
85998
86125
  capName: "training-provider",
85999
86126
  capScope: "system",
@@ -86001,13 +86128,6 @@ Object.freeze({
86001
86128
  access: "create",
86002
86129
  role: "admin"
86003
86130
  },
86004
- "trainingProvider.validateCredentials": {
86005
- capName: "training-provider",
86006
- capScope: "system",
86007
- addonId: null,
86008
- access: "create",
86009
- role: "admin"
86010
- },
86011
86131
  "turnProvider.getTurnServers": {
86012
86132
  capName: "turn-provider",
86013
86133
  capScope: "system",
@@ -88344,11 +88464,6 @@ Object.freeze({
88344
88464
  form: "single",
88345
88465
  optional: false
88346
88466
  }],
88347
- "petFountain.resetDailyConsumption": [{
88348
- name: "deviceId",
88349
- form: "single",
88350
- optional: false
88351
- }],
88352
88467
  "petFountain.setPump": [{
88353
88468
  name: "deviceId",
88354
88469
  form: "single",
@@ -91092,48 +91207,53 @@ object({
91092
91207
  delay: number().nonnegative().optional(),
91093
91208
  commands: record(string(), unknown())
91094
91209
  });
91095
- var BrokerInUseError = class extends Error {
91096
- brokerId;
91210
+ var InstanceInUseError = class extends Error {
91211
+ instanceId;
91097
91212
  users;
91098
- name = "BrokerInUseError";
91099
- constructor(brokerId, users) {
91100
- super(`broker '${brokerId}' is still in use by ${users.map((u) => `${u.kind} '${u.name ?? u.id}' (${u.id})`).join(", ")}; unlink them first`);
91101
- this.brokerId = brokerId;
91213
+ name = "InstanceInUseError";
91214
+ constructor(instanceId, users) {
91215
+ super(`instance '${instanceId}' is still in use by ${users.map((u) => `${u.kind} '${u.name ?? u.id}' (${u.id})`).join(", ")}; unlink them first`);
91216
+ this.instanceId = instanceId;
91102
91217
  this.users = users;
91103
91218
  }
91104
91219
  };
91105
- /** Throw {@link BrokerInUseError} when any finder names a user of `brokerId`. */
91106
- async function assertBrokerUnused(brokerId, finders) {
91220
+ /** Throw {@link InstanceInUseError} when any finder names a user of `instanceId`. */
91221
+ async function assertInstanceUnused(instanceId, finders) {
91107
91222
  const users = [];
91108
- for (const finder of finders) users.push(...await finder.find(brokerId));
91109
- if (users.length > 0) throw new BrokerInUseError(brokerId, users);
91223
+ for (const finder of finders) users.push(...await finder.find(instanceId));
91224
+ if (users.length > 0) throw new InstanceInUseError(instanceId, users);
91225
+ }
91226
+ function namesInstance(value, instanceId) {
91227
+ if (Array.isArray(value)) return value.includes(instanceId);
91228
+ return value === instanceId;
91110
91229
  }
91111
91230
  /**
91112
91231
  * Users reached through another addon's listed rows (an addon cannot read a record kind it does
91113
- * not own): every row whose `field` holds the broker id. `list` is a cap call the owner serves.
91232
+ * not own): every row whose `field` holds the instance id, as a string or in a string list.
91233
+ * `list` is a cap call the owner serves.
91114
91234
  */
91115
91235
  function fieldUserFinder(spec) {
91116
- return { find: async (brokerId) => (await spec.list()).filter((row) => row.formValues[spec.field] === brokerId).map((row) => ({
91236
+ const fields = typeof spec.field === "string" ? [spec.field] : spec.field;
91237
+ return { find: async (instanceId) => (await spec.list()).filter((row) => fields.some((f) => namesInstance(row.formValues[f], instanceId))).map((row) => ({
91117
91238
  kind: spec.kind,
91118
91239
  id: row.id,
91119
91240
  ...row.name !== void 0 ? { name: row.name } : {}
91120
91241
  })) };
91121
91242
  }
91122
91243
  /**
91123
- * An account provider whose `deleteInstance` is refused while anything still uses the account
91124
- * (D1012). The account is an `integration-instances` kind (D1013), so the refusal lives on the
91125
- * delete the instances page calls, not on a separate broker cap.
91244
+ * A provider whose `deleteInstance` is refused while anything still uses the instance. The
91245
+ * account is an `integration-instances` kind (D1013), so the refusal lives on the delete the
91246
+ * instances page calls.
91126
91247
  */
91127
- function guardBrokerDelete(base, users) {
91248
+ function guardInstanceDelete(base, users) {
91128
91249
  return {
91129
91250
  ...base,
91130
91251
  deleteInstance: async (input) => {
91131
- await assertBrokerUnused(input.id, users());
91252
+ await assertInstanceUnused(input.id, users());
91132
91253
  return base.deleteInstance(input);
91133
91254
  }
91134
91255
  };
91135
91256
  }
91136
- entryBody({ brokerId: string() });
91137
91257
  //#endregion
91138
91258
  //#region ../../node_modules/xtend/immutable.js
91139
91259
  var require_immutable = /* @__PURE__ */ __commonJSMin(((exports, module) => {
@@ -122995,7 +123115,7 @@ var BrokerProbeCache = class {
122995
123115
  }
122996
123116
  if (this.inflight) await this.inflight.catch(() => void 0);
122997
123117
  }
122998
- /** Force a refresh (used by `testConnection` and the page's Refresh button). */
123118
+ /** Force a refresh (used by the page's Refresh button). */
122999
123119
  async probeNow(id) {
123000
123120
  const broker = this.getBrokers().find((b) => b.id === id);
123001
123121
  if (!broker) return void 0;
@@ -123358,7 +123478,7 @@ var PROBE_LABELS = {
123358
123478
  };
123359
123479
  /** The instance's health word: connected / auth-failed / unreachable / tls-error, latency, clients. */
123360
123480
  function mqttHealthOf(body, live, now) {
123361
- if (body.enabled === false) return { status: {
123481
+ if (!isInstanceEnabled(body)) return { status: {
123362
123482
  state: "off",
123363
123483
  label: "Switched off"
123364
123484
  } };
@@ -123483,7 +123603,7 @@ function buildMqttBrokerInstances(records, deps) {
123483
123603
  onboard: built.onboard
123484
123604
  };
123485
123605
  };
123486
- return guardBrokerDelete({
123606
+ return guardInstanceDelete({
123487
123607
  ...base,
123488
123608
  instanceFormSchema: async ({ id }) => {
123489
123609
  const saved = id === null ? null : await instances.getResolved(id);
@@ -123977,8 +124097,8 @@ var MqttAclStore = class MqttAclStore {
123977
124097
  * - The legacy single embedded broker is an onboard `brokers` record (migrated from the flat
123978
124098
  * `embedded*` keys, same id); `startEmbeddedBroker` / `stopEmbeddedBroker` act on that record.
123979
124099
  * - `addBroker` / `removeBroker` mutate the records and the runtime state.
123980
- * - `testConnection` does a one-shot `mqtt.connect` race against a 3s
123981
- * timeout AND refreshes the probe cache for the broker.
124100
+ * - The instance test (`integration-instances.testInstance`) does a one-shot `mqtt.connect`
124101
+ * race against a 3s timeout.
123982
124102
  */
123983
124103
  /** bcrypt cost factor — exported for tests. */
123984
124104
  var MQTT_EMBEDDED_BCRYPT_ROUNDS = 10;
@@ -124114,7 +124234,6 @@ var MqttBrokerAddon = class extends BaseAddon {
124114
124234
  getBrokerConfig: async ({ id }) => this.getBrokerConfig(id),
124115
124235
  addBroker: async (input) => this.addBroker(input),
124116
124236
  removeBroker: async ({ id }) => this.removeBroker(id),
124117
- testConnection: async ({ id }) => this.testConnection(id),
124118
124237
  startEmbeddedBroker: async (input) => this.startEmbeddedBroker(input),
124119
124238
  stopEmbeddedBroker: async ({ id }) => this.stopEmbeddedBroker(id),
124120
124239
  getStatus: async () => ({
@@ -124217,7 +124336,7 @@ var MqttBrokerAddon = class extends BaseAddon {
124217
124336
  getBrokerConfig(id) {
124218
124337
  const external = this.activeExternalBrokers.find((b) => b.id === id);
124219
124338
  if (external) {
124220
- if (external.enabled === false) throw new Error(`mqtt-broker: broker '${id}' is switched off`);
124339
+ if (!isInstanceEnabled(external)) throw new Error(`mqtt-broker: broker '${id}' is switched off`);
124221
124340
  const password = this.storedPassword(external.password);
124222
124341
  return {
124223
124342
  url: external.url,
@@ -124257,24 +124376,10 @@ var MqttBrokerAddon = class extends BaseAddon {
124257
124376
  return;
124258
124377
  }
124259
124378
  }
124260
- async testConnection(id) {
124261
- let cfg;
124262
- try {
124263
- cfg = this.getBrokerConfig(id);
124264
- } catch (err) {
124265
- return {
124266
- ok: false,
124267
- error: errMsg(err)
124268
- };
124269
- }
124270
- this.probeCache?.probeNow(id).catch(() => void 0);
124271
- return this.probeMqtt(cfg);
124272
- }
124273
124379
  /**
124274
124380
  * One-shot connectivity probe against an MQTT endpoint built from a
124275
- * flat config (`{url, username?, password?}`). Shared by the
124276
- * id-keyed `testConnection` (existing broker) and the pre-creation
124277
- * the instance test (`testInstance`) of a broker not saved yet (the typed values).
124381
+ * flat config (`{url, username?, password?}`), used by the instance test
124382
+ * (`integration-instances.testInstance`), stored or draft.
124278
124383
  * Never throws — every failure resolves to `{ ok: false, error }`.
124279
124384
  */
124280
124385
  async probeMqtt(cfg) {
@@ -124473,7 +124578,7 @@ var MqttBrokerAddon = class extends BaseAddon {
124473
124578
  * entry disappeared, and respawn runtimes whose port changed.
124474
124579
  */
124475
124580
  async reconcileOnboardRuntimes() {
124476
- const desiredEntries = this.activeExternalBrokers.filter(hasOnboard).filter((b) => b.enabled !== false);
124581
+ const desiredEntries = this.activeExternalBrokers.filter(hasOnboard).filter((b) => isInstanceEnabled(b));
124477
124582
  const desired = desiredEntries.map((b) => ({
124478
124583
  id: b.id,
124479
124584
  port: b.onboard.port
@@ -124614,7 +124719,7 @@ var MqttBrokerAddon = class extends BaseAddon {
124614
124719
  collectExternalProbeInputs() {
124615
124720
  const out = [];
124616
124721
  for (const b of this.activeExternalBrokers) {
124617
- if (b.onboard !== void 0 || b.enabled === false) continue;
124722
+ if (b.onboard !== void 0 || !isInstanceEnabled(b)) continue;
124618
124723
  let password;
124619
124724
  try {
124620
124725
  password = this.storedPassword(b.password);