@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.
@@ -6021,7 +6021,7 @@ var ZodIssueCode = {
6021
6021
  var ZodFirstPartyTypeKind;
6022
6022
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
6023
6023
  //#endregion
6024
- //#region ../types/dist/sleep-BX_MqzUe.mjs
6024
+ //#region ../types/dist/sleep-CdKka2ri.mjs
6025
6025
  /**
6026
6026
  * The audio chunk plane's byte format, and the ONE expansion from a coded
6027
6027
  * window to float samples (D455).
@@ -6705,137 +6705,86 @@ async function runAddonMigrations(host, migrations, logger, options = {}) {
6705
6705
  blockOwner
6706
6706
  };
6707
6707
  }
6708
- /**
6709
- * Build a {@link DurableState} over a single store key. Transport-agnostic:
6710
- * `read`/`write` are the addon-store or device-store accessors. The whole
6711
- * validated value round-trips on every read/write — the schema is the
6712
- * single source of truth for what is persisted, so no hand-listed field
6713
- * set can drop a key on save.
6714
- */
6715
- function createDurableState(deps) {
6716
- const get = async () => {
6717
- const raw = (await deps.read())[deps.key];
6718
- if (raw === void 0) return deps.fallback;
6719
- const parsed = deps.schema.safeParse(raw);
6720
- if (!parsed.success) {
6721
- deps.onParseError?.(deps.key, parsed.error);
6722
- return deps.fallback;
6723
- }
6724
- return parsed.data;
6725
- };
6726
- const set = async (next) => {
6727
- const validated = deps.schema.parse(next);
6728
- await deps.write({ [deps.key]: validated });
6729
- };
6730
- const update = async (fn) => {
6731
- await set(fn(await get()));
6732
- };
6708
+ /** The record calls the one-switch migration makes, over the migration API. */
6709
+ function switchRecordsOverMigrationApi(api) {
6710
+ return { kind: (definition) => {
6711
+ const handle = api.records.kind(definition);
6712
+ return {
6713
+ get: (id) => handle.get({ id }),
6714
+ put: (input, opts) => handle.put({
6715
+ ...input,
6716
+ ...opts?.ifRev === void 0 ? {} : { ifRev: opts.ifRev }
6717
+ }),
6718
+ patch: (id, partial) => handle.patch({
6719
+ id,
6720
+ partial
6721
+ })
6722
+ };
6723
+ } };
6724
+ }
6725
+ function integrationRowsApiOver(api) {
6733
6726
  return {
6734
- get,
6735
- set,
6736
- update
6727
+ list: async () => (await api.integrations.list({})).integrations,
6728
+ readLegacyIntegrationRows: (input) => api.legacyRows.read(input),
6729
+ clearLegacyIntegrationRows: (input) => api.legacyRows.clear(input)
6737
6730
  };
6738
6731
  }
6739
- /**
6740
- * Per-node scoping for the shared addon-settings blob.
6741
- *
6742
- * An addon's settings store is hub-central (the `addon-settings` cap is
6743
- * hub-routed — the hub instance answers for every node), so fields whose
6744
- * value is a NODE fact (decoder backend, engine pick, probed hardware
6745
- * capabilities) persist under the node-scoped key `<key>@<nodeId>` inside
6746
- * the single shared blob. The SCHEMA field key stays bare: the write path
6747
- * ({@link scopePatch}) maps the bare field onto the target node's scoped
6748
- * key; the read/hydrate path ({@link projectStore}) maps THIS node's value
6749
- * back, so UI forms and `resolveConfig` only ever see the bare key.
6750
- *
6751
- * Fields opt in via the `perNode: true` schema marker on `ConfigFieldBase`
6752
- * (`interfaces/config-ui.ts`); `BaseAddon` derives the key set from the
6753
- * schema and routes reads/writes through these helpers.
6754
- *
6755
- * ## No bare-key fallback — deliberate
6756
- *
6757
- * {@link readNodeValue} reads the node-scoped key ONLY. A node with no
6758
- * scoped key resolves to `undefined` so the field's schema `default` wins —
6759
- * NEVER `store[base]` and never another node's value. A bare legacy key in
6760
- * the store is invisible to every node, hub included, so one node's
6761
- * selection can never leak onto another. (This generalizes the
6762
- * `decoder-backend-keys.ts` semantics — the no-fallback variant — over an
6763
- * arbitrary set of per-node field keys.)
6764
- *
6765
- * Pure functions only — no I/O, no imports beyond the language. This is a
6766
- * LEAF module: import it via its deep path, never from the root barrel.
6767
- */
6768
- /**
6769
- * Normalize a raw kernel node id to the bare node id used for scoping.
6770
- * `localNodeId` can carry a `<node>/<addon>` suffix on forked child
6771
- * processes; per-node settings are per-NODE, so strip the addon segment.
6772
- * `undefined` / `null` / empty falls back to `'hub'`.
6773
- */
6774
- function normalizeNodeId(raw) {
6775
- if (raw === void 0 || raw === null || raw === "") return "hub";
6776
- const slashIdx = raw.indexOf("/");
6777
- if (slashIdx < 0) return raw;
6778
- const bare = raw.slice(0, slashIdx);
6779
- return bare === "" ? "hub" : bare;
6780
- }
6781
- /** The node-scoped store key for a per-node field: `<base>@<nodeId>`. */
6782
- function nodeScopedKey(base, nodeId) {
6783
- return `${base}@${normalizeNodeId(nodeId)}`;
6784
- }
6785
- /**
6786
- * Read a node's value for a per-node field from the raw shared store:
6787
- * the node-scoped key when present, otherwise `undefined`.
6788
- * Deliberately NO bare-key fallback (see module doc) — the caller lets the
6789
- * schema `default` win on `undefined`.
6790
- */
6791
- function readNodeValue(store, base, nodeId) {
6792
- return store[nodeScopedKey(base, nodeId)];
6793
- }
6794
- /**
6795
- * Re-map a UI/settings patch so every bare perNode field persists under the
6796
- * TARGET node's scoped key; all other keys pass through unchanged. Used on
6797
- * the write path so a save for one node never clobbers another node's value
6798
- * (and the bare key is never written). Returns a new object — the input
6799
- * patch is not mutated.
6800
- */
6801
- function scopePatch(patch, perNodeKeys, nodeId) {
6802
- const out = {};
6803
- for (const [key, value] of Object.entries(patch)) out[perNodeKeys.has(key) ? nodeScopedKey(key, nodeId) : key] = value;
6804
- return out;
6805
- }
6806
- /**
6807
- * Project the raw shared store onto the bare schema keys for ONE node so a
6808
- * UI schema (whose field keys are bare) hydrates from that node's own
6809
- * values:
6810
- *
6811
- * - EVERY `@`-scoped key (any node's) is dropped from the pass-through.
6812
- * - Every bare perNode key is dropped from the pass-through (a stray bare
6813
- * legacy key must never hydrate any node — no bare fallback).
6814
- * - THIS node's effective value ({@link readNodeValue}) is then laid onto
6815
- * each bare perNode key; when the node has no scoped key the bare key is
6816
- * left ABSENT so the field's schema `default` wins.
6817
- *
6818
- * Returns a new object — the input store is not mutated.
6819
- */
6820
- function projectStore(store, perNodeKeys, nodeId) {
6821
- const out = {};
6822
- for (const [key, value] of Object.entries(store)) {
6823
- if (key.includes("@")) continue;
6824
- if (perNodeKeys.has(key)) continue;
6825
- out[key] = value;
6732
+ var PREFIX = "records/";
6733
+ /** The base of every records failure. `detail` is the human part of the message. */
6734
+ var RecordsError = class extends Error {
6735
+ code;
6736
+ detail;
6737
+ constructor(code, detail) {
6738
+ super(`${PREFIX}${code}: ${detail}`);
6739
+ this.name = "RecordsError";
6740
+ this.code = code;
6741
+ this.detail = detail;
6826
6742
  }
6827
- for (const base of perNodeKeys) {
6828
- const value = readNodeValue(store, base, nodeId);
6829
- if (value !== void 0) out[base] = value;
6743
+ };
6744
+ /** The keychain could not store or serve a value: explicit, never an empty string. */
6745
+ var RecordSecretUnavailableError = class extends RecordsError {
6746
+ constructor(detail) {
6747
+ super("secret-unavailable", detail);
6748
+ this.name = "RecordSecretUnavailableError";
6830
6749
  }
6831
- return out;
6750
+ };
6751
+ var InvalidRecordError = class extends RecordsError {
6752
+ constructor(detail) {
6753
+ super("invalid-record", detail);
6754
+ this.name = "InvalidRecordError";
6755
+ }
6756
+ };
6757
+ /** A kind declaration the engine refuses (non-additive change, bad shape, wrong file). */
6758
+ var DeclarationRefusedError = class extends RecordsError {
6759
+ constructor(detail) {
6760
+ super("declaration-refused", detail);
6761
+ this.name = "DeclarationRefusedError";
6762
+ }
6763
+ };
6764
+ function linkTargetOf(meta) {
6765
+ if (typeof meta !== "object" || meta === null) return void 0;
6766
+ const link = Reflect.get(meta, "link");
6767
+ const parsed = LinkTargetSchema.safeParse(link);
6768
+ return parsed.success ? parsed.data : void 0;
6769
+ }
6770
+ var LinkTargetSchema = object({
6771
+ cap: string().min(1),
6772
+ kind: string().min(1).optional()
6773
+ });
6774
+ /** The links a kind declares, read from the meta of its body fields. */
6775
+ function linksOfKind(kind) {
6776
+ const schema = kind.schema;
6777
+ if (!(schema instanceof ZodObject)) return [];
6778
+ const links = [];
6779
+ for (const [field, fieldSchema] of Object.entries(schema.shape)) {
6780
+ const to = linkTargetOf(globalRegistry.get(fieldSchema));
6781
+ if (to !== void 0) links.push({
6782
+ field,
6783
+ to
6784
+ });
6785
+ }
6786
+ return links;
6832
6787
  }
6833
- /** Every scope, in the order the guard and the docs list them. */
6834
- var SCOPED_SETTINGS_SCOPES = [
6835
- "cluster",
6836
- "device-defaults",
6837
- "node"
6838
- ];
6839
6788
  /**
6840
6789
  * The address of one keychain value: `secret://<owner>/<scope>/<fieldPath>`.
6841
6790
  *
@@ -6970,6 +6919,643 @@ function parseSecretRef(ref) {
6970
6919
  fieldPath
6971
6920
  };
6972
6921
  }
6922
+ /** Limits and names of `ctx.records` (D881). One authority; the engine and the facade read it. */
6923
+ /** The files a kind may live in. `history` is device-history's (D850), never records. */
6924
+ var RECORD_DATABASES = ["settings", "events"];
6925
+ /** The classes of a kind: the `@durable` vocabulary, one authority (replaces the annotation). */
6926
+ var RECORD_CLASSES = [
6927
+ "config",
6928
+ "ledger",
6929
+ "audit",
6930
+ "mirror",
6931
+ "ephemeral"
6932
+ ];
6933
+ var RECORD_DEFAULT_MAX_DATA_BYTES = 64 * 1024;
6934
+ var RECORD_MAX_DATA_BYTES = 1024 * 1024;
6935
+ var RECORD_BATCH_MAX = 1e3;
6936
+ var RECORD_QUERY_MAX = 1e3;
6937
+ /** A kind in the `settings` file may not bound itself above this (D447: high volume is `events`). */
6938
+ var RECORD_SETTINGS_MAX_ROWS = 5e4;
6939
+ /** The `Column`-free proof prefix: a ref collection for a kind's secret fields. */
6940
+ var RECORD_SECRET_COLLECTION_PREFIX = "records:";
6941
+ /**
6942
+ * Secret fields of a record, addressed the way a Zod schema declares them
6943
+ * (`collectZodSecretPaths`): dotted keys, `[]` for "each element of this array"
6944
+ * (`auth.accessToken`, `headers[].value`).
6945
+ *
6946
+ * `{}` after a key means "each value of this map" (`applianceSecrets{}`): the map's own key
6947
+ * names the value (`applianceSecrets{fridge}`), so no id key is declared and a body that drops a
6948
+ * key releases exactly that key's secret.
6949
+ *
6950
+ * Array elements are matched by a DECLARED id key (`secretArrayKeys`:
6951
+ * `{ headers: 'name' }`), never by index, so reordering a list keeps every
6952
+ * keychain ref (the same rule as `arrayItemFieldPath`). The concrete path of a
6953
+ * leaf names its element: `headers[X-Api].value`.
6954
+ *
6955
+ * Pure and browser-safe. Nothing here mutates: every transform returns a new value.
6956
+ */
6957
+ /** The array prefixes (declared form, e.g. `headers` or `a.headers`) of a path. */
6958
+ function parseSecretPath(path) {
6959
+ if (path.length === 0) throw new InvalidRecordError("an empty secret path");
6960
+ return path.split(".").map((raw) => {
6961
+ const each = raw.endsWith("[]");
6962
+ const map = raw.endsWith("{}");
6963
+ const key = each || map ? raw.slice(0, -2) : raw;
6964
+ if (key.length === 0) throw new InvalidRecordError(`secret path "${path}" has an empty segment`);
6965
+ return {
6966
+ key,
6967
+ each,
6968
+ map
6969
+ };
6970
+ });
6971
+ }
6972
+ /** The declared array prefixes of `path` that need an id key (`headers`, `a.rows`). */
6973
+ function secretArrayPrefixes(path) {
6974
+ const segments = parseSecretPath(path);
6975
+ const prefixes = [];
6976
+ const walked = [];
6977
+ for (const segment of segments) {
6978
+ walked.push(segment.key);
6979
+ if (segment.each) prefixes.push(walked.join("."));
6980
+ }
6981
+ return prefixes;
6982
+ }
6983
+ function isRecord$6(value) {
6984
+ return typeof value === "object" && value !== null && !Array.isArray(value);
6985
+ }
6986
+ function elementId(element, idKey, declared, prefix) {
6987
+ const id = isRecord$6(element) ? element[idKey] : void 0;
6988
+ 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`);
6989
+ return id;
6990
+ }
6991
+ /**
6992
+ * Visit every secret leaf PRESENT in `data` (an absent branch has nothing to
6993
+ * visit). `replace` returns the new leaf value, or {@link REMOVE_LEAF}; the
6994
+ * result is a new body, `data` is untouched.
6995
+ */
6996
+ var REMOVE_LEAF = Symbol("remove-leaf");
6997
+ function mapAt(node, segments, index, walkedKeys, concretePrefix, declared, arrayKeys, visit) {
6998
+ if (!isRecord$6(node)) return node;
6999
+ const segment = segments[index];
7000
+ if (segment === void 0) return node;
7001
+ if (!Object.prototype.hasOwnProperty.call(node, segment.key)) return node;
7002
+ const child = node[segment.key];
7003
+ const keys = [...walkedKeys, segment.key];
7004
+ const last = index === segments.length - 1;
7005
+ if (segment.each) {
7006
+ if (!Array.isArray(child)) return node;
7007
+ const prefix = keys.join(".");
7008
+ const idKey = arrayKeys[prefix];
7009
+ if (idKey === void 0) throw new InvalidRecordError(`"${declared}": no id key declared for the array "${prefix}"`);
7010
+ const mapped = child.map((element) => {
7011
+ const id = elementId(element, idKey, declared, prefix);
7012
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}[${encodeURIComponent(id)}]`;
7013
+ return last ? element : mapAt(element, segments, index + 1, keys, concrete, declared, arrayKeys, visit);
7014
+ });
7015
+ return {
7016
+ ...node,
7017
+ [segment.key]: mapped
7018
+ };
7019
+ }
7020
+ if (segment.map) {
7021
+ if (!isRecord$6(child)) return node;
7022
+ const kept = Object.entries(child).map(([mapKey, value]) => {
7023
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}{${encodeURIComponent(mapKey)}}`;
7024
+ if (!last) return [mapKey, mapAt(value, segments, index + 1, keys, concrete, declared, arrayKeys, visit)];
7025
+ return [mapKey, visit({
7026
+ declared,
7027
+ concrete,
7028
+ value
7029
+ })];
7030
+ }).filter(([, value]) => value !== REMOVE_LEAF);
7031
+ return {
7032
+ ...node,
7033
+ [segment.key]: Object.fromEntries(kept)
7034
+ };
7035
+ }
7036
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}`;
7037
+ if (last) {
7038
+ const replacement = visit({
7039
+ declared,
7040
+ concrete,
7041
+ value: child
7042
+ });
7043
+ if (replacement === REMOVE_LEAF) return Object.fromEntries(Object.entries(node).filter(([key]) => key !== segment.key));
7044
+ return {
7045
+ ...node,
7046
+ [segment.key]: replacement
7047
+ };
7048
+ }
7049
+ return {
7050
+ ...node,
7051
+ [segment.key]: mapAt(child, segments, index + 1, keys, concrete, declared, arrayKeys, visit)
7052
+ };
7053
+ }
7054
+ /** Replace/remove every present secret leaf; returns a NEW body. */
7055
+ function mapSecretLeaves(data, paths, arrayKeys, visit) {
7056
+ let current = data;
7057
+ for (const declared of paths) current = mapAt(current, parseSecretPath(declared), 0, [], "", declared, arrayKeys, visit);
7058
+ return current;
7059
+ }
7060
+ /**
7061
+ * The keychain collection name a kind's secrets live under. Prefixed so a
7062
+ * record's refs never collide with the refs a legacy collection of the same name
7063
+ * already holds during an adoption.
7064
+ */
7065
+ function recordSecretCollection(kind) {
7066
+ return `${RECORD_SECRET_COLLECTION_PREFIX}${kind}`;
7067
+ }
7068
+ /** The ONE ref a row's secret field may carry: the engine and the facade both build it here. */
7069
+ function recordSecretRef(owner, kind, rowId, concretePath) {
7070
+ return buildSecretRef({
7071
+ owner,
7072
+ scope: {
7073
+ kind: "row",
7074
+ collection: recordSecretCollection(kind),
7075
+ rowId
7076
+ },
7077
+ fieldPath: concretePath
7078
+ });
7079
+ }
7080
+ /**
7081
+ * A stored secret, as an admin read shows it: a VIEW naming the row's own
7082
+ * keychain ref (`set: true`), never the value and no longer the bare redaction
7083
+ * token. The form hands it to the secret field, which reveals the value by ref
7084
+ * through the audited `keychain-admin.reveal`; sent back untouched it keeps the
7085
+ * stored secret (the records door reads a view as KEEP).
7086
+ *
7087
+ * ONE implementation for the entries service and for every addon that serves
7088
+ * its own instances (`RecordIntegrationInstances`).
7089
+ */
7090
+ function isRecord$5(value) {
7091
+ return typeof value === "object" && value !== null && !Array.isArray(value);
7092
+ }
7093
+ function secretViewsOf(owner, kind, id, decl, data) {
7094
+ if (decl.secretPaths.length === 0) return data;
7095
+ const shown = mapSecretLeaves(data, decl.secretPaths, decl.secretArrayKeys, (leaf) => {
7096
+ if (leaf.value !== "__camstack_redacted__") return leaf.value;
7097
+ return {
7098
+ $secret: recordSecretRef(owner, kind, id, leaf.concrete),
7099
+ v: 1,
7100
+ set: true
7101
+ };
7102
+ });
7103
+ return isRecord$5(shown) ? shown : data;
7104
+ }
7105
+ /** The most instances one addon lists (an integrations page, not a table). */
7106
+ var INSTANCES_LIST_MAX = 1e3;
7107
+ /**
7108
+ * The ONE reader of an instance's switch (D996): an absent field means on, so a row written
7109
+ * before the field existed needs no migration. Every consumer of an instance body asks this.
7110
+ */
7111
+ function isInstanceEnabled(body) {
7112
+ return body.enabled !== false;
7113
+ }
7114
+ /** The body key of the switch; only {@link RecordIntegrationInstances.setInstanceEnabled} writes it. */
7115
+ var SWITCH_KEY = "enabled";
7116
+ /** The keys of the kind's secret fields that sit at the top level of the body. */
7117
+ function topLevelSecretKeys(paths) {
7118
+ return new Set(paths.filter((p) => !p.includes(".") && !p.includes("[") && !p.includes("{")));
7119
+ }
7120
+ /** The keys of the kind's top-level MAPS whose values are secrets (`applianceSecrets{}`). */
7121
+ function secretMapKeys(paths) {
7122
+ return new Set(paths.filter((p) => p.endsWith("{}") && !p.slice(0, -2).match(/[.[{]/)).map((p) => p.slice(0, -2)));
7123
+ }
7124
+ /**
7125
+ * A patch value for a map of secrets: an entry that is omitted, `''`, the redaction token or the
7126
+ * view the form was given KEEPS its stored secret (it is left out of the merge); `{ $secretClear }`
7127
+ * or `null` removes the entry; any other string replaces it. Null when nothing is left to merge.
7128
+ */
7129
+ function secretMapPatch(value) {
7130
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
7131
+ const out = {};
7132
+ for (const [key, entry] of Object.entries(value)) if (entry === null || isSecretClear(entry)) out[key] = null;
7133
+ else if (typeof entry === "string" && entry !== "" && entry !== "__camstack_redacted__" && !isSecretFieldView(entry)) out[key] = entry;
7134
+ return Object.keys(out).length > 0 ? out : null;
7135
+ }
7136
+ var RecordIntegrationInstances = class {
7137
+ records;
7138
+ kind;
7139
+ hooks;
7140
+ handle;
7141
+ secretKeys;
7142
+ secretMaps;
7143
+ nameField;
7144
+ switchListeners = /* @__PURE__ */ new Set();
7145
+ constructor(records, kind, hooks) {
7146
+ this.records = records;
7147
+ this.kind = kind;
7148
+ this.hooks = hooks;
7149
+ this.handle = records.kind(kind);
7150
+ this.secretKeys = topLevelSecretKeys(kind.declaration.secretPaths);
7151
+ this.secretMaps = secretMapKeys(kind.declaration.secretPaths);
7152
+ this.nameField = kind.declaration.entry?.nameField ?? "name";
7153
+ }
7154
+ /**
7155
+ * One instance read for the addon's own runtime; null when absent. When the keychain is
7156
+ * locked the row is served WITHOUT its secrets and says so (`secrets: 'unavailable'`), so the
7157
+ * caller can keep what it had instead of reconfiguring with an empty secret (D49).
7158
+ */
7159
+ async readResolved(id) {
7160
+ try {
7161
+ const record = await this.handle.getResolved(id);
7162
+ return record === null ? null : {
7163
+ id,
7164
+ body: record.data,
7165
+ enabled: isInstanceEnabled(record.data),
7166
+ secrets: "resolved"
7167
+ };
7168
+ } catch (err) {
7169
+ if (!(err instanceof RecordSecretUnavailableError)) throw err;
7170
+ const stored = await this.handle.get(id);
7171
+ if (stored === null) return null;
7172
+ return {
7173
+ id,
7174
+ body: Object.fromEntries(Object.entries(stored.data).filter(([key]) => !this.secretKeys.has(key))),
7175
+ enabled: isInstanceEnabled(stored.data),
7176
+ secrets: "unavailable"
7177
+ };
7178
+ }
7179
+ }
7180
+ /** The body of {@link readResolved} alone; a locked keychain yields the row without secrets. */
7181
+ async getResolved(id) {
7182
+ return (await this.readResolved(id))?.body ?? null;
7183
+ }
7184
+ /** Every instance, secrets resolved where the keychain allows; an absent one is skipped. */
7185
+ async listResolved() {
7186
+ const page = await this.handle.query({ limit: INSTANCES_LIST_MAX });
7187
+ const out = [];
7188
+ for (const record of page.records) {
7189
+ const read = await this.readResolved(record.id);
7190
+ if (read !== null) out.push(read);
7191
+ }
7192
+ return out;
7193
+ }
7194
+ viewOf(record) {
7195
+ const shown = secretViewsOf(this.records.owner, this.kind.name, record.id, this.kind.declaration, record.data);
7196
+ const rawName = record.data[this.nameField];
7197
+ const kind = this.hooks.kindOf?.(record.data);
7198
+ const health = this.hooks.health?.(record.data, record.id);
7199
+ return {
7200
+ id: record.id,
7201
+ name: typeof rawName === "string" ? rawName : record.id,
7202
+ configured: this.hooks.configured(record.data),
7203
+ enabled: isInstanceEnabled(record.data),
7204
+ formValues: shown,
7205
+ ...kind !== void 0 ? { kind } : {},
7206
+ ...health?.status !== void 0 ? { status: health.status } : {},
7207
+ ...health?.lastCheckedAt !== void 0 ? { lastCheckedAt: health.lastCheckedAt } : {}
7208
+ };
7209
+ }
7210
+ describe = async () => {
7211
+ const declared = linksOfKind(this.kind);
7212
+ const links = this.hooks.description.links !== void 0 || declared.length === 0 ? {} : { links: declared.map((link) => ({
7213
+ kind: this.kind.name,
7214
+ field: link.field,
7215
+ to: link.to
7216
+ })) };
7217
+ return {
7218
+ ...this.hooks.description,
7219
+ ...links,
7220
+ ...this.hooks.mintId === void 0 ? {} : { mintsId: true }
7221
+ };
7222
+ };
7223
+ instanceFormSchema = async ({ id }) => this.hooks.formSchema(id);
7224
+ listInstances = async () => {
7225
+ return (await this.handle.query({ limit: INSTANCES_LIST_MAX })).records.map((record) => this.viewOf(record));
7226
+ };
7227
+ getInstance = async ({ id }) => {
7228
+ const record = await this.handle.get(id);
7229
+ return record === null ? null : this.viewOf(record);
7230
+ };
7231
+ /** Insert ONE row (`ifRev: 0`: an existing id is refused, never overwritten). */
7232
+ createInstance = async ({ id, name, kind, values }) => {
7233
+ const minted = id ?? this.hooks.mintId?.({
7234
+ name,
7235
+ ...kind !== void 0 ? { kind } : {}
7236
+ });
7237
+ if (minted === void 0) throw new Error("createInstance needs an id: this provider does not mint one");
7238
+ await this.handle.put({
7239
+ id: minted,
7240
+ data: this.hooks.initialBody(name, kind)
7241
+ }, { ifRev: 0 });
7242
+ const patch = this.patchOf(values ?? {});
7243
+ if (Object.keys(patch).length > 0) await this.handle.patch(minted, patch);
7244
+ await this.hooks.onChanged?.(minted, "created");
7245
+ return { id: minted };
7246
+ };
7247
+ updateInstance = async ({ id, name, values }) => {
7248
+ const patch = this.patchOf(values);
7249
+ if (name !== void 0) patch[this.nameField] = name;
7250
+ await this.handle.patch(id, patch);
7251
+ await this.hooks.onChanged?.(id, "updated");
7252
+ return { ok: true };
7253
+ };
7254
+ /** The record patch a form `values` object means: secrets kept, cleared or replaced. */
7255
+ patchOf(values) {
7256
+ const patch = {};
7257
+ for (const [key, value] of Object.entries(values)) {
7258
+ if (value === void 0) continue;
7259
+ if (key === "enabled") continue;
7260
+ if (this.secretMaps.has(key)) {
7261
+ const entries = secretMapPatch(value);
7262
+ if (entries !== null) patch[key] = entries;
7263
+ } else if (!this.secretKeys.has(key)) patch[key] = value;
7264
+ else if (isSecretClear(value)) patch[key] = null;
7265
+ else if (typeof value === "string" && value !== "" && value !== "__camstack_redacted__" && !isSecretFieldView(value)) patch[key] = value;
7266
+ }
7267
+ return patch;
7268
+ }
7269
+ /**
7270
+ * Listen to the switch of ANY instance of this helper (in the process that serves it). The
7271
+ * durable replacement of the `integration.enabled` / `integration.disabled` events (D8): the
7272
+ * addon reconciles from the record, whichever way it flipped.
7273
+ */
7274
+ onSwitched(listener) {
7275
+ this.switchListeners.add(listener);
7276
+ }
7277
+ /**
7278
+ * The ONE writer of the switch (D996, D1014): the record body's `enabled`, for every role. A
7279
+ * configured thing is an instance, so an id with no record yet (a default integration that was
7280
+ * never configured) gets its record from `initialBody` before the switch is written.
7281
+ */
7282
+ setInstanceEnabled = async ({ id, enabled }) => {
7283
+ if (await this.handle.get(id) === null) await this.handle.put({
7284
+ id,
7285
+ data: this.hooks.initialBody(id)
7286
+ }, { ifRev: 0 });
7287
+ await this.handle.patch(id, { [SWITCH_KEY]: enabled });
7288
+ await this.hooks.onChanged?.(id, "enabled");
7289
+ for (const listener of this.switchListeners) await listener(id, enabled);
7290
+ return { ok: true };
7291
+ };
7292
+ /** The row and its keychain refs go together (the records door). */
7293
+ deleteInstance = async ({ id }) => {
7294
+ await this.handle.delete(id);
7295
+ await this.hooks.onChanged?.(id, "deleted");
7296
+ return { ok: true };
7297
+ };
7298
+ testInstance = async (input) => {
7299
+ if (this.hooks.test === void 0) return {
7300
+ success: false,
7301
+ status: "unsupported",
7302
+ error: "This integration declares no connection test"
7303
+ };
7304
+ return this.hooks.test(input);
7305
+ };
7306
+ /** The flat provider object to hand to `registerProvider`. */
7307
+ toProvider() {
7308
+ return {
7309
+ describe: this.describe,
7310
+ instanceFormSchema: this.instanceFormSchema,
7311
+ listInstances: this.listInstances,
7312
+ getInstance: this.getInstance,
7313
+ createInstance: this.createInstance,
7314
+ updateInstance: this.updateInstance,
7315
+ setInstanceEnabled: this.setInstanceEnabled,
7316
+ deleteInstance: this.deleteInstance,
7317
+ testInstance: this.testInstance
7318
+ };
7319
+ }
7320
+ };
7321
+ /**
7322
+ * The one-switch migration (epic #440, step 3). An integration's on/off state used to live in the
7323
+ * registry's `enabled` column for a device addon; it now lives only in the instance record's
7324
+ * body (`enabled`, D1007 superseded). This moves a registry `enabled = false` into the body, once.
7325
+ *
7326
+ * For every registry row of the addon that is OFF:
7327
+ * - no record under its id: the record is created from `initialBody(name)` with `enabled: false`
7328
+ * (a default integration that never had settings, Reolink's among them);
7329
+ * - a record whose body states no `enabled`: `enabled: false` is written into it;
7330
+ * - a record that already states `enabled` (either way) is the newer truth and is left alone.
7331
+ * A row that is ON writes nothing: an absent field reads as on. A rerun finds every off row with
7332
+ * a stated switch and does nothing, so nothing switched off comes back on and nothing switched on
7333
+ * goes off. The registry column itself is neither read afterwards nor written; its drop is step 5.
7334
+ *
7335
+ * It runs in the addon process, BEFORE the addon registers its `integration-instances` provider,
7336
+ * which is also why `integrations.list` still answers the stored column at that point.
7337
+ */
7338
+ function registrySwitchToBodyId(addonId, date) {
7339
+ return `${addonId}/${date}-registry-switch-to-body`;
7340
+ }
7341
+ async function moveRegistrySwitchToBody(ports, spec) {
7342
+ const rows = await ports.listIntegrations(spec.addonId);
7343
+ let created = 0;
7344
+ let switched = 0;
7345
+ let kept = 0;
7346
+ for (const row of rows) {
7347
+ if (row.enabled) continue;
7348
+ const body = await ports.readBody(row.id);
7349
+ if (body === null) {
7350
+ if (await ports.createRecord(row.id, {
7351
+ ...spec.initialBody(row.name),
7352
+ ["enabled"]: false
7353
+ }) === "created") created += 1;
7354
+ else kept += 1;
7355
+ continue;
7356
+ }
7357
+ if ("enabled" in body) {
7358
+ kept += 1;
7359
+ continue;
7360
+ }
7361
+ await ports.switchOff(row.id);
7362
+ switched += 1;
7363
+ }
7364
+ const summary = {
7365
+ integrations: rows.length,
7366
+ off: rows.filter((r) => !r.enabled).length,
7367
+ created,
7368
+ switched,
7369
+ kept
7370
+ };
7371
+ return created === 0 && switched === 0 ? {
7372
+ outcome: "already-done",
7373
+ summary
7374
+ } : {
7375
+ outcome: "done",
7376
+ summary
7377
+ };
7378
+ }
7379
+ /** A migration entry: an addon states its kind and how a new body starts, nothing else. */
7380
+ function registrySwitchToBodyMigration(spec) {
7381
+ return {
7382
+ meta: {
7383
+ id: registrySwitchToBodyId(spec.addonId, spec.date),
7384
+ owner: spec.addonId,
7385
+ level: "addon-state",
7386
+ seq: spec.seq,
7387
+ dependsOn: [],
7388
+ store: "settings",
7389
+ scope: "cluster",
7390
+ onFailure: "block-owner",
7391
+ bodyKind: "procedure",
7392
+ description: "Move the registry enabled flag of every switched-off integration into its instance record body, creating the record when there is none",
7393
+ fixtureMark: "enabled"
7394
+ },
7395
+ procedure: (ports) => moveRegistrySwitchToBody(ports, {
7396
+ addonId: spec.addonId,
7397
+ initialBody: spec.initialBody
7398
+ })
7399
+ };
7400
+ }
7401
+ /** The hub and records sides of {@link registrySwitchToBodyMigration}. */
7402
+ function registrySwitchPortsOver(deps) {
7403
+ const handle = deps.records.kind({
7404
+ name: deps.kind.name,
7405
+ declaration: deps.kind.declaration,
7406
+ schema: record(string(), unknown())
7407
+ });
7408
+ return {
7409
+ listIntegrations: async (addonId) => (await deps.api.list()).filter((i) => i.addonId === addonId).map((i) => ({
7410
+ id: i.id,
7411
+ name: i.name,
7412
+ enabled: i.enabled !== false
7413
+ })),
7414
+ readBody: async (id) => (await handle.get(id))?.data ?? null,
7415
+ createRecord: async (id, body) => {
7416
+ if (await handle.get(id) !== null) return "exists";
7417
+ await handle.put({
7418
+ id,
7419
+ data: body
7420
+ }, { ifRev: 0 });
7421
+ return "created";
7422
+ },
7423
+ switchOff: async (id) => {
7424
+ await handle.patch(id, { [SWITCH_KEY]: false });
7425
+ }
7426
+ };
7427
+ }
7428
+ /**
7429
+ * Build a {@link DurableState} over a single store key. Transport-agnostic:
7430
+ * `read`/`write` are the addon-store or device-store accessors. The whole
7431
+ * validated value round-trips on every read/write — the schema is the
7432
+ * single source of truth for what is persisted, so no hand-listed field
7433
+ * set can drop a key on save.
7434
+ */
7435
+ function createDurableState(deps) {
7436
+ const get = async () => {
7437
+ const raw = (await deps.read())[deps.key];
7438
+ if (raw === void 0) return deps.fallback;
7439
+ const parsed = deps.schema.safeParse(raw);
7440
+ if (!parsed.success) {
7441
+ deps.onParseError?.(deps.key, parsed.error);
7442
+ return deps.fallback;
7443
+ }
7444
+ return parsed.data;
7445
+ };
7446
+ const set = async (next) => {
7447
+ const validated = deps.schema.parse(next);
7448
+ await deps.write({ [deps.key]: validated });
7449
+ };
7450
+ const update = async (fn) => {
7451
+ await set(fn(await get()));
7452
+ };
7453
+ return {
7454
+ get,
7455
+ set,
7456
+ update
7457
+ };
7458
+ }
7459
+ /**
7460
+ * Per-node scoping for the shared addon-settings blob.
7461
+ *
7462
+ * An addon's settings store is hub-central (the `addon-settings` cap is
7463
+ * hub-routed — the hub instance answers for every node), so fields whose
7464
+ * value is a NODE fact (decoder backend, engine pick, probed hardware
7465
+ * capabilities) persist under the node-scoped key `<key>@<nodeId>` inside
7466
+ * the single shared blob. The SCHEMA field key stays bare: the write path
7467
+ * ({@link scopePatch}) maps the bare field onto the target node's scoped
7468
+ * key; the read/hydrate path ({@link projectStore}) maps THIS node's value
7469
+ * back, so UI forms and `resolveConfig` only ever see the bare key.
7470
+ *
7471
+ * Fields opt in via the `perNode: true` schema marker on `ConfigFieldBase`
7472
+ * (`interfaces/config-ui.ts`); `BaseAddon` derives the key set from the
7473
+ * schema and routes reads/writes through these helpers.
7474
+ *
7475
+ * ## No bare-key fallback — deliberate
7476
+ *
7477
+ * {@link readNodeValue} reads the node-scoped key ONLY. A node with no
7478
+ * scoped key resolves to `undefined` so the field's schema `default` wins —
7479
+ * NEVER `store[base]` and never another node's value. A bare legacy key in
7480
+ * the store is invisible to every node, hub included, so one node's
7481
+ * selection can never leak onto another. (This generalizes the
7482
+ * `decoder-backend-keys.ts` semantics — the no-fallback variant — over an
7483
+ * arbitrary set of per-node field keys.)
7484
+ *
7485
+ * Pure functions only — no I/O, no imports beyond the language. This is a
7486
+ * LEAF module: import it via its deep path, never from the root barrel.
7487
+ */
7488
+ /**
7489
+ * Normalize a raw kernel node id to the bare node id used for scoping.
7490
+ * `localNodeId` can carry a `<node>/<addon>` suffix on forked child
7491
+ * processes; per-node settings are per-NODE, so strip the addon segment.
7492
+ * `undefined` / `null` / empty falls back to `'hub'`.
7493
+ */
7494
+ function normalizeNodeId(raw) {
7495
+ if (raw === void 0 || raw === null || raw === "") return "hub";
7496
+ const slashIdx = raw.indexOf("/");
7497
+ if (slashIdx < 0) return raw;
7498
+ const bare = raw.slice(0, slashIdx);
7499
+ return bare === "" ? "hub" : bare;
7500
+ }
7501
+ /** The node-scoped store key for a per-node field: `<base>@<nodeId>`. */
7502
+ function nodeScopedKey(base, nodeId) {
7503
+ return `${base}@${normalizeNodeId(nodeId)}`;
7504
+ }
7505
+ /**
7506
+ * Read a node's value for a per-node field from the raw shared store:
7507
+ * the node-scoped key when present, otherwise `undefined`.
7508
+ * Deliberately NO bare-key fallback (see module doc) — the caller lets the
7509
+ * schema `default` win on `undefined`.
7510
+ */
7511
+ function readNodeValue(store, base, nodeId) {
7512
+ return store[nodeScopedKey(base, nodeId)];
7513
+ }
7514
+ /**
7515
+ * Re-map a UI/settings patch so every bare perNode field persists under the
7516
+ * TARGET node's scoped key; all other keys pass through unchanged. Used on
7517
+ * the write path so a save for one node never clobbers another node's value
7518
+ * (and the bare key is never written). Returns a new object — the input
7519
+ * patch is not mutated.
7520
+ */
7521
+ function scopePatch(patch, perNodeKeys, nodeId) {
7522
+ const out = {};
7523
+ for (const [key, value] of Object.entries(patch)) out[perNodeKeys.has(key) ? nodeScopedKey(key, nodeId) : key] = value;
7524
+ return out;
7525
+ }
7526
+ /**
7527
+ * Project the raw shared store onto the bare schema keys for ONE node so a
7528
+ * UI schema (whose field keys are bare) hydrates from that node's own
7529
+ * values:
7530
+ *
7531
+ * - EVERY `@`-scoped key (any node's) is dropped from the pass-through.
7532
+ * - Every bare perNode key is dropped from the pass-through (a stray bare
7533
+ * legacy key must never hydrate any node — no bare fallback).
7534
+ * - THIS node's effective value ({@link readNodeValue}) is then laid onto
7535
+ * each bare perNode key; when the node has no scoped key the bare key is
7536
+ * left ABSENT so the field's schema `default` wins.
7537
+ *
7538
+ * Returns a new object — the input store is not mutated.
7539
+ */
7540
+ function projectStore(store, perNodeKeys, nodeId) {
7541
+ const out = {};
7542
+ for (const [key, value] of Object.entries(store)) {
7543
+ if (key.includes("@")) continue;
7544
+ if (perNodeKeys.has(key)) continue;
7545
+ out[key] = value;
7546
+ }
7547
+ for (const base of perNodeKeys) {
7548
+ const value = readNodeValue(store, base, nodeId);
7549
+ if (value !== void 0) out[base] = value;
7550
+ }
7551
+ return out;
7552
+ }
7553
+ /** Every scope, in the order the guard and the docs list them. */
7554
+ var SCOPED_SETTINGS_SCOPES = [
7555
+ "cluster",
7556
+ "device-defaults",
7557
+ "node"
7558
+ ];
6973
7559
  /** A write to a secret path could not be stored in the keychain, so it was refused. */
6974
7560
  var KeychainWriteRefusedError = class extends Error {
6975
7561
  fieldPath;
@@ -6980,7 +7566,7 @@ var KeychainWriteRefusedError = class extends Error {
6980
7566
  }
6981
7567
  };
6982
7568
  var KEEP = { kind: "keep" };
6983
- function isRecord$6(value) {
7569
+ function isRecord$4(value) {
6984
7570
  return typeof value === "object" && value !== null && !Array.isArray(value);
6985
7571
  }
6986
7572
  function defaultMintId() {
@@ -6993,7 +7579,7 @@ function collectSecretMarkerRefs(value, out = []) {
6993
7579
  return out;
6994
7580
  }
6995
7581
  if (Array.isArray(value)) for (const item of value) collectSecretMarkerRefs(item, out);
6996
- else if (isRecord$6(value)) for (const child of Object.values(value)) collectSecretMarkerRefs(child, out);
7582
+ else if (isRecord$4(value)) for (const child of Object.values(value)) collectSecretMarkerRefs(child, out);
6997
7583
  return out;
6998
7584
  }
6999
7585
  async function storedValueEquals(secrets, marker, candidate) {
@@ -7048,7 +7634,7 @@ function rowId(row, idKey) {
7048
7634
  return null;
7049
7635
  }
7050
7636
  async function writeArray(ctx, node, incoming, stored, fieldPath) {
7051
- const storedRows = Array.isArray(stored) ? stored.filter(isRecord$6) : [];
7637
+ const storedRows = Array.isArray(stored) ? stored.filter(isRecord$4) : [];
7052
7638
  if (!Array.isArray(incoming)) {
7053
7639
  ctx.deletes.push(...collectSecretMarkerRefs(storedRows));
7054
7640
  return {
@@ -7064,7 +7650,7 @@ async function writeArray(ctx, node, incoming, stored, fieldPath) {
7064
7650
  const kept = /* @__PURE__ */ new Set();
7065
7651
  const rows = [];
7066
7652
  for (const row of incoming) {
7067
- if (!isRecord$6(row)) {
7653
+ if (!isRecord$4(row)) {
7068
7654
  rows.push(row);
7069
7655
  continue;
7070
7656
  }
@@ -7089,7 +7675,7 @@ async function writeNode(ctx, node, incoming, stored, fieldPath) {
7089
7675
  case "leaf": return writeLeaf(ctx, incoming, stored, fieldPath);
7090
7676
  case "array": return writeArray(ctx, node, incoming, stored, fieldPath);
7091
7677
  case "object": {
7092
- if (!isRecord$6(incoming)) {
7678
+ if (!isRecord$4(incoming)) {
7093
7679
  if (incoming === void 0) return KEEP;
7094
7680
  ctx.deletes.push(...collectSecretMarkerRefs(stored));
7095
7681
  return {
@@ -7097,7 +7683,7 @@ async function writeNode(ctx, node, incoming, stored, fieldPath) {
7097
7683
  value: incoming
7098
7684
  };
7099
7685
  }
7100
- const storedObj = isRecord$6(stored) ? stored : {};
7686
+ const storedObj = isRecord$4(stored) ? stored : {};
7101
7687
  return {
7102
7688
  kind: "value",
7103
7689
  value: await writeMembers(ctx, node.children, incoming, storedObj, (m) => `${fieldPath}.${m}`)
@@ -7220,7 +7806,7 @@ async function resolveSecretMarkers(value, secrets, options = {}) {
7220
7806
  value: items
7221
7807
  };
7222
7808
  }
7223
- if (isRecord$6(v)) {
7809
+ if (isRecord$4(v)) {
7224
7810
  const out = {};
7225
7811
  for (const [k, child] of Object.entries(v)) {
7226
7812
  const s = substitute(child);
@@ -7252,7 +7838,7 @@ var SecretOverwriteRefusedError = class extends Error {
7252
7838
  this.name = "SecretOverwriteRefusedError";
7253
7839
  }
7254
7840
  };
7255
- function isRecord$5(value) {
7841
+ function isRecord$3(value) {
7256
7842
  return typeof value === "object" && value !== null && !Array.isArray(value);
7257
7843
  }
7258
7844
  function resolvedValue(pass, marker) {
@@ -7281,7 +7867,7 @@ function inArray(pass, incoming, stored) {
7281
7867
  return incoming.map((item, index) => {
7282
7868
  const twin = stored[index];
7283
7869
  if (isSecretMarker(twin)) return typeof item === "string" && item === resolvedValue(pass, twin) ? twin : item;
7284
- if (isRecord$5(item) && isRecord$5(twin)) return inArrayRow(pass, item, twin);
7870
+ if (isRecord$3(item) && isRecord$3(twin)) return inArrayRow(pass, item, twin);
7285
7871
  if (Array.isArray(item) && Array.isArray(twin)) return inArray(pass, item, twin);
7286
7872
  return item;
7287
7873
  });
@@ -7292,7 +7878,7 @@ function inArrayRow(pass, incoming, stored) {
7292
7878
  const twin = stored[key];
7293
7879
  if (isSecretMarker(twin)) {
7294
7880
  if (typeof value === "string" && value === resolvedValue(pass, twin)) out[key] = twin;
7295
- } else if (isRecord$5(value) && isRecord$5(twin)) out[key] = inArrayRow(pass, value, twin);
7881
+ } else if (isRecord$3(value) && isRecord$3(twin)) out[key] = inArrayRow(pass, value, twin);
7296
7882
  else if (Array.isArray(value) && Array.isArray(twin)) out[key] = inArray(pass, value, twin);
7297
7883
  }
7298
7884
  return out;
@@ -7300,7 +7886,7 @@ function inArrayRow(pass, incoming, stored) {
7300
7886
  async function walk(pass, incoming, stored) {
7301
7887
  if (isSecretMarker(stored)) return atMarker(pass, incoming, stored);
7302
7888
  if (Array.isArray(incoming) && Array.isArray(stored)) return inArray(pass, incoming, stored);
7303
- if (!isRecord$5(incoming) || !isRecord$5(stored)) return incoming;
7889
+ if (!isRecord$3(incoming) || !isRecord$3(stored)) return incoming;
7304
7890
  const out = { ...incoming };
7305
7891
  for (const [key, value] of Object.entries(incoming)) out[key] = await walk(pass, value, stored[key]);
7306
7892
  return out;
@@ -7331,7 +7917,7 @@ async function restoreUnchangedSecrets(input) {
7331
7917
  function isJsonEqual(a, b) {
7332
7918
  if (Object.is(a, b)) return true;
7333
7919
  if (Array.isArray(a)) return Array.isArray(b) && a.length === b.length && a.every((v, i) => isJsonEqual(v, b[i]));
7334
- if (isRecord$5(a) && isRecord$5(b)) {
7920
+ if (isRecord$3(a) && isRecord$3(b)) {
7335
7921
  const keys = Object.keys(a);
7336
7922
  if (keys.length !== Object.keys(b).length) return false;
7337
7923
  return keys.every((k) => Object.prototype.hasOwnProperty.call(b, k) && isJsonEqual(a[k], b[k]));
@@ -7355,7 +7941,7 @@ function markerKeysOf(blob, owner) {
7355
7941
  }
7356
7942
  function nodeFromStored(value, owner) {
7357
7943
  if (isSecretMarker(value)) return isSecretRefOwnedBy(value.$secret, owner) ? { kind: "leaf" } : null;
7358
- if (!isRecord$5(value)) return null;
7944
+ if (!isRecord$3(value)) return null;
7359
7945
  const children = /* @__PURE__ */ new Map();
7360
7946
  for (const [key, child] of Object.entries(value)) {
7361
7947
  const node = nodeFromStored(child, owner);
@@ -7852,13 +8438,48 @@ var BaseAddon = class {
7852
8438
  if (api === void 0) throw new Error(`${this.ctx.id}: the migration API is not available on this context`);
7853
8439
  return this.runBound(sets.flatMap((set) => set.bind(api)), options);
7854
8440
  }
7855
- async runBound(migrations, options) {
8441
+ /**
8442
+ * A device addon states its instance kind once, before its migrations run, and the one-switch
8443
+ * migration (registry `enabled` to the instance body, epic #440 step 3) joins whatever
8444
+ * catalogue the addon runs, in the SAME declaration (the engine replaces an owner's catalogue
8445
+ * on every declare).
8446
+ */
8447
+ declareRegistrySwitch(spec) {
8448
+ this.registrySwitchSpec = spec;
8449
+ }
8450
+ registrySwitchSpec = null;
8451
+ registrySwitchBound() {
8452
+ const spec = this.registrySwitchSpec;
8453
+ if (spec === null) return [];
8454
+ const api = this.ctx.migrationApi;
8455
+ if (api === void 0) {
8456
+ this.ctx.logger.warn("the registry switch migration is skipped: the migration API is not available on this context");
8457
+ return [];
8458
+ }
8459
+ return migrationSet([registrySwitchToBodyMigration({
8460
+ addonId: this.ctx.id,
8461
+ date: "2026-11-06",
8462
+ seq: 1e3,
8463
+ initialBody: spec.initialBody
8464
+ })], (a) => registrySwitchPortsOver({
8465
+ api: integrationRowsApiOver(a),
8466
+ records: switchRecordsOverMigrationApi(a),
8467
+ kind: spec.kind
8468
+ })).bind(api);
8469
+ }
8470
+ async runBound(declared, options) {
8471
+ const added = this.registrySwitchBound();
8472
+ const migrations = [...declared, ...added];
8473
+ const phased = options?.only === void 0 || added.length === 0 ? options : {
8474
+ ...options,
8475
+ only: [...options.only, ...added.map((m) => m.meta.id)]
8476
+ };
7856
8477
  const api = this.ctx.api.migrations;
7857
8478
  const report = await runAddonMigrations({
7858
8479
  declareOwner: (input) => api.declareOwner.mutate(input),
7859
8480
  startMigration: (input) => api.startMigration.mutate(input),
7860
8481
  finishMigration: (input) => api.finishMigration.mutate(input)
7861
- }, migrations, this.ctx.logger, options);
8482
+ }, migrations, this.ctx.logger, phased);
7862
8483
  if (report.blockOwner.length > 0) throw new AddonMigrationsBlockedError(report.blockOwner);
7863
8484
  return report;
7864
8485
  }
@@ -8931,245 +9552,94 @@ function normalizeAddonInitResult(result) {
8931
9552
  if (Array.isArray(result)) return { providers: result };
8932
9553
  return result;
8933
9554
  }
8934
- var PREFIX = "records/";
8935
- /** The base of every records failure. `detail` is the human part of the message. */
8936
- var RecordsError = class extends Error {
8937
- code;
8938
- detail;
8939
- constructor(code, detail) {
8940
- super(`${PREFIX}${code}: ${detail}`);
8941
- this.name = "RecordsError";
8942
- this.code = code;
8943
- this.detail = detail;
8944
- }
8945
- };
8946
- /** The keychain could not store or serve a value: explicit, never an empty string. */
8947
- var RecordSecretUnavailableError = class extends RecordsError {
8948
- constructor(detail) {
8949
- super("secret-unavailable", detail);
8950
- this.name = "RecordSecretUnavailableError";
8951
- }
8952
- };
8953
- var InvalidRecordError = class extends RecordsError {
8954
- constructor(detail) {
8955
- super("invalid-record", detail);
8956
- this.name = "InvalidRecordError";
8957
- }
8958
- };
8959
- /** A kind declaration the engine refuses (non-additive change, bad shape, wrong file). */
8960
- var DeclarationRefusedError = class extends RecordsError {
8961
- constructor(detail) {
8962
- super("declaration-refused", detail);
8963
- this.name = "DeclarationRefusedError";
8964
- }
8965
- };
8966
- /** Limits and names of `ctx.records` (D881). One authority; the engine and the facade read it. */
8967
- /** The files a kind may live in. `history` is device-history's (D850), never records. */
8968
- var RECORD_DATABASES = ["settings", "events"];
8969
- /** The classes of a kind: the `@durable` vocabulary, one authority (replaces the annotation). */
8970
- var RECORD_CLASSES = [
8971
- "config",
8972
- "ledger",
8973
- "audit",
8974
- "mirror",
8975
- "ephemeral"
8976
- ];
8977
- var RECORD_DEFAULT_MAX_DATA_BYTES = 64 * 1024;
8978
- var RECORD_MAX_DATA_BYTES = 1024 * 1024;
8979
- var RECORD_BATCH_MAX = 1e3;
8980
- var RECORD_QUERY_MAX = 1e3;
8981
- /** A kind in the `settings` file may not bound itself above this (D447: high volume is `events`). */
8982
- var RECORD_SETTINGS_MAX_ROWS = 5e4;
8983
- /** The `Column`-free proof prefix: a ref collection for a kind's secret fields. */
8984
- var RECORD_SECRET_COLLECTION_PREFIX = "records:";
9555
+ object({
9556
+ field: string().min(1),
9557
+ on: literal("advance")
9558
+ });
8985
9559
  /**
8986
- * Secret fields of a record, addressed the way a Zod schema declares them
8987
- * (`collectZodSecretPaths`): dotted keys, `[]` for "each element of this array"
8988
- * (`auth.accessToken`, `headers[].value`).
8989
- *
8990
- * `{}` after a key means "each value of this map" (`applianceSecrets{}`): the map's own key
8991
- * names the value (`applianceSecrets{fridge}`), so no id key is declared and a body that drops a
8992
- * key releases exactly that key's secret.
9560
+ * Output schema shared by the contribution + live methods.
8993
9561
  *
8994
- * Array elements are matched by a DECLARED id key (`secretArrayKeys`:
8995
- * `{ headers: 'name' }`), never by index, so reordering a list keeps every
8996
- * keychain ref (the same rule as `arrayItemFieldPath`). The concrete path of a
8997
- * leaf names its element: `headers[X-Api].value`.
9562
+ * Mirrors the `ConfigUISchemaWithValues` shape (sections[] + optional
9563
+ * tabs[]) without importing from `../interfaces/config-ui.js` — a
9564
+ * concrete-but-lenient Zod object keeps tRPC output inference happy
9565
+ * (using `z.unknown()` here collapses unrelated router branches to
9566
+ * `unknown` when the generator re-inlines the huge AppRouter type).
8998
9567
  *
8999
- * Pure and browser-safe. Nothing here mutates: every transform returns a new value.
9000
- */
9001
- /** The array prefixes (declared form, e.g. `headers` or `a.headers`) of a path. */
9002
- function parseSecretPath(path) {
9003
- if (path.length === 0) throw new InvalidRecordError("an empty secret path");
9004
- return path.split(".").map((raw) => {
9005
- const each = raw.endsWith("[]");
9006
- const map = raw.endsWith("{}");
9007
- const key = each || map ? raw.slice(0, -2) : raw;
9008
- if (key.length === 0) throw new InvalidRecordError(`secret path "${path}" has an empty segment`);
9009
- return {
9010
- key,
9011
- each,
9012
- map
9013
- };
9014
- });
9015
- }
9016
- /** The declared array prefixes of `path` that need an id key (`headers`, `a.rows`). */
9017
- function secretArrayPrefixes(path) {
9018
- const segments = parseSecretPath(path);
9019
- const prefixes = [];
9020
- const walked = [];
9021
- for (const segment of segments) {
9022
- walked.push(segment.key);
9023
- if (segment.each) prefixes.push(walked.join("."));
9024
- }
9025
- return prefixes;
9026
- }
9027
- function isRecord$4(value) {
9028
- return typeof value === "object" && value !== null && !Array.isArray(value);
9029
- }
9030
- function elementId(element, idKey, declared, prefix) {
9031
- const id = isRecord$4(element) ? element[idKey] : void 0;
9032
- if (typeof id !== "string" || id.length === 0) throw new InvalidRecordError(`"${declared}": every element of "${prefix}" needs a non-empty string "${idKey}" to carry a secret`);
9033
- return id;
9034
- }
9035
- /**
9036
- * Visit every secret leaf PRESENT in `data` (an absent branch has nothing to
9037
- * visit). `replace` returns the new leaf value, or {@link REMOVE_LEAF}; the
9038
- * result is a new body, `data` is untouched.
9568
+ * `.passthrough()` on sections/fields accepts whatever FormBuilder
9569
+ * extensions the caller adds (showWhen, displayScale, …) without
9570
+ * rebuilding every time a new field kind is introduced.
9039
9571
  */
9040
- var REMOVE_LEAF = Symbol("remove-leaf");
9041
- function mapAt(node, segments, index, walkedKeys, concretePrefix, declared, arrayKeys, visit) {
9042
- if (!isRecord$4(node)) return node;
9043
- const segment = segments[index];
9044
- if (segment === void 0) return node;
9045
- if (!Object.prototype.hasOwnProperty.call(node, segment.key)) return node;
9046
- const child = node[segment.key];
9047
- const keys = [...walkedKeys, segment.key];
9048
- const last = index === segments.length - 1;
9049
- if (segment.each) {
9050
- if (!Array.isArray(child)) return node;
9051
- const prefix = keys.join(".");
9052
- const idKey = arrayKeys[prefix];
9053
- if (idKey === void 0) throw new InvalidRecordError(`"${declared}": no id key declared for the array "${prefix}"`);
9054
- const mapped = child.map((element) => {
9055
- const id = elementId(element, idKey, declared, prefix);
9056
- const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}[${encodeURIComponent(id)}]`;
9057
- return last ? element : mapAt(element, segments, index + 1, keys, concrete, declared, arrayKeys, visit);
9058
- });
9059
- return {
9060
- ...node,
9061
- [segment.key]: mapped
9062
- };
9063
- }
9064
- if (segment.map) {
9065
- if (!isRecord$4(child)) return node;
9066
- const kept = Object.entries(child).map(([mapKey, value]) => {
9067
- const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}{${encodeURIComponent(mapKey)}}`;
9068
- if (!last) return [mapKey, mapAt(value, segments, index + 1, keys, concrete, declared, arrayKeys, visit)];
9069
- return [mapKey, visit({
9070
- declared,
9071
- concrete,
9072
- value
9073
- })];
9074
- }).filter(([, value]) => value !== REMOVE_LEAF);
9075
- return {
9076
- ...node,
9077
- [segment.key]: Object.fromEntries(kept)
9078
- };
9079
- }
9080
- const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}`;
9081
- if (last) {
9082
- const replacement = visit({
9083
- declared,
9084
- concrete,
9085
- value: child
9086
- });
9087
- if (replacement === REMOVE_LEAF) return Object.fromEntries(Object.entries(node).filter(([key]) => key !== segment.key));
9088
- return {
9089
- ...node,
9090
- [segment.key]: replacement
9091
- };
9092
- }
9572
+ var ContributionSectionSchema = object({
9573
+ id: string(),
9574
+ title: string(),
9575
+ description: string().optional(),
9576
+ style: _enum(["card", "accordion"]).optional(),
9577
+ defaultCollapsed: boolean().optional(),
9578
+ columns: union([
9579
+ literal(1),
9580
+ literal(2),
9581
+ literal(3),
9582
+ literal(4)
9583
+ ]).optional(),
9584
+ tab: string().optional(),
9585
+ location: _enum([
9586
+ "settings",
9587
+ "top-tab",
9588
+ "hero"
9589
+ ]).optional(),
9590
+ order: number().optional(),
9591
+ fields: array(any())
9592
+ });
9593
+ object({
9594
+ tabs: array(object({
9595
+ id: string(),
9596
+ label: string(),
9597
+ icon: string(),
9598
+ order: number().optional()
9599
+ })).optional(),
9600
+ sections: array(ContributionSectionSchema)
9601
+ }).nullable();
9602
+ object({ deviceId: number() }), object({ deviceId: number() }), object({
9603
+ deviceId: number(),
9604
+ patch: record(string(), unknown())
9605
+ }), object({ success: literal(true) });
9606
+ object({ deviceId: number() }), unknown().nullable();
9607
+ function method(input, output, options) {
9093
9608
  return {
9094
- ...node,
9095
- [segment.key]: mapAt(child, segments, index + 1, keys, concrete, declared, arrayKeys, visit)
9609
+ input,
9610
+ output,
9611
+ kind: options?.kind ?? "query",
9612
+ ...options?.auth !== void 0 ? { auth: options.auth } : {},
9613
+ ...options?.access !== void 0 ? { access: options.access } : {},
9614
+ ...options?.role !== void 0 ? { role: options.role } : {},
9615
+ ...options?.caller !== void 0 ? { caller: options.caller } : {},
9616
+ timeoutMs: options?.timeoutMs
9096
9617
  };
9097
9618
  }
9098
- /** Replace/remove every present secret leaf; returns a NEW body. */
9099
- function mapSecretLeaves(data, paths, arrayKeys, visit) {
9100
- let current = data;
9101
- for (const declared of paths) current = mapAt(current, parseSecretPath(declared), 0, [], "", declared, arrayKeys, visit);
9102
- return current;
9103
- }
9104
9619
  /**
9105
- * The keychain collection name a kind's secrets live under. Prefixed so a
9106
- * record's refs never collide with the refs a legacy collection of the same name
9107
- * already holds during an adoption.
9620
+ * A wrapper/system-only method: served exclusively by the cap's system-level
9621
+ * provider (`InferProvider`), and OPTIONAL on `InferNativeProvider` so per-device
9622
+ * driver natives don't stub out a wrapper concern (e.g. a cross-device cache
9623
+ * overview). The `systemOnly: true` literal is what `InferNativeProvider` keys on.
9108
9624
  */
9109
- function recordSecretCollection(kind) {
9110
- return `${RECORD_SECRET_COLLECTION_PREFIX}${kind}`;
9111
- }
9112
- /** The ONE ref a row's secret field may carry: the engine and the facade both build it here. */
9113
- function recordSecretRef(owner, kind, rowId, concretePath) {
9114
- return buildSecretRef({
9115
- owner,
9116
- scope: {
9117
- kind: "row",
9118
- collection: recordSecretCollection(kind),
9119
- rowId
9120
- },
9121
- fieldPath: concretePath
9122
- });
9625
+ function systemMethod(input, output, options) {
9626
+ return {
9627
+ ...method(input, output, options),
9628
+ systemOnly: true
9629
+ };
9123
9630
  }
9124
9631
  /**
9125
- * A stored secret, as an admin read shows it: a VIEW naming the row's own
9126
- * keychain ref (`set: true`), never the value and no longer the bare redaction
9127
- * token. The form hands it to the secret field, which reveals the value by ref
9128
- * through the audited `keychain-admin.reveal`; sent back untouched it keeps the
9129
- * stored secret (the records door reads a view as KEEP).
9130
- *
9131
- * ONE implementation for the entries service and for every addon that serves
9132
- * its own instances (`RecordIntegrationInstances`).
9632
+ * A method a SOURCE of a collection cap may legitimately not serve — OPTIONAL
9633
+ * on `InferProvider`. The `providerOptional: true` literal is what
9634
+ * `InferProvider` keys on; see {@link CapabilityMethodSchema.providerOptional}
9635
+ * for when this is the honest answer and when it is a soft stub.
9133
9636
  */
9134
- function isRecord$3(value) {
9135
- return typeof value === "object" && value !== null && !Array.isArray(value);
9136
- }
9137
- function secretViewsOf(owner, kind, id, decl, data) {
9138
- if (decl.secretPaths.length === 0) return data;
9139
- const shown = mapSecretLeaves(data, decl.secretPaths, decl.secretArrayKeys, (leaf) => {
9140
- if (leaf.value !== "__camstack_redacted__") return leaf.value;
9141
- return {
9142
- $secret: recordSecretRef(owner, kind, id, leaf.concrete),
9143
- v: 1,
9144
- set: true
9145
- };
9146
- });
9147
- return isRecord$3(shown) ? shown : data;
9637
+ function optionalMethod(input, output, options) {
9638
+ return {
9639
+ ...method(input, output, options),
9640
+ providerOptional: true
9641
+ };
9148
9642
  }
9149
- /**
9150
- * The share-view scope kinds a share-link token can carry. The hub mints
9151
- * and validates them (`ShareViewGrantSchema` builds its
9152
- * enum from this list); a data plane names the kinds it ACCEPTS in `share`.
9153
- */
9154
- var SHARE_VIEW_KINDS = ["grid-view", "events-view"];
9155
- /** The wire shape of {@link PeerBytesTicket} — see the type for what it is. */
9156
- var PeerBytesTicketSchema = object({
9157
- /** `http://127.0.0.1:<port>/<token>`. One `GET` takes it. */
9158
- url: string().min(1),
9159
- /**
9160
- * The HOST node this URL means something on — the hub or a named agent,
9161
- * never a runner. {@link AddonPeerBytes.open} compares it to its own and
9162
- * refuses `cross-node` by name when they differ, without dialling.
9163
- */
9164
- hostNodeId: string().min(1),
9165
- expiresAtMs: number().int().nonnegative(),
9166
- /**
9167
- * What the producer DECLARED the body to be, when it knows — `null` when it
9168
- * does not. Never `0` for unknown (D393): a consumer sizing a bound off this
9169
- * must be able to tell "the producer did not say" from "the body is empty".
9170
- */
9171
- declaredBytes: number().int().nonnegative().nullable()
9172
- });
9173
9643
  function defOf(schema) {
9174
9644
  const zodBag = Reflect.get(schema, "_zod");
9175
9645
  if (typeof zodBag !== "object" || zodBag === null) return {};
@@ -9399,6 +9869,7 @@ function defineRecordKinds(specs) {
9399
9869
  function entryBody(shape) {
9400
9870
  return object({
9401
9871
  name: string().min(1),
9872
+ enabled: boolean().optional(),
9402
9873
  ...shape
9403
9874
  });
9404
9875
  }
@@ -9425,94 +9896,30 @@ function defineEntryKind(name, spec) {
9425
9896
  if (defined === void 0) throw new DeclarationRefusedError(`entry kind "${name}" was not built`);
9426
9897
  return defined;
9427
9898
  }
9428
- object({
9429
- field: string().min(1),
9430
- on: literal("advance")
9431
- });
9432
9899
  /**
9433
- * Output schema shared by the contribution + live methods.
9434
- *
9435
- * Mirrors the `ConfigUISchemaWithValues` shape (sections[] + optional
9436
- * tabs[]) without importing from `../interfaces/config-ui.js` — a
9437
- * concrete-but-lenient Zod object keeps tRPC output inference happy
9438
- * (using `z.unknown()` here collapses unrelated router branches to
9439
- * `unknown` when the generator re-inlines the huge AppRouter type).
9440
- *
9441
- * `.passthrough()` on sections/fields accepts whatever FormBuilder
9442
- * extensions the caller adds (showWhen, displayScale, …) without
9443
- * rebuilding every time a new field kind is introduced.
9900
+ * The share-view scope kinds a share-link token can carry. The hub mints
9901
+ * and validates them (`ShareViewGrantSchema` builds its
9902
+ * enum from this list); a data plane names the kinds it ACCEPTS in `share`.
9444
9903
  */
9445
- var ContributionSectionSchema = object({
9446
- id: string(),
9447
- title: string(),
9448
- description: string().optional(),
9449
- style: _enum(["card", "accordion"]).optional(),
9450
- defaultCollapsed: boolean().optional(),
9451
- columns: union([
9452
- literal(1),
9453
- literal(2),
9454
- literal(3),
9455
- literal(4)
9456
- ]).optional(),
9457
- tab: string().optional(),
9458
- location: _enum([
9459
- "settings",
9460
- "top-tab",
9461
- "hero"
9462
- ]).optional(),
9463
- order: number().optional(),
9464
- fields: array(any())
9904
+ var SHARE_VIEW_KINDS = ["grid-view", "events-view"];
9905
+ /** The wire shape of {@link PeerBytesTicket} — see the type for what it is. */
9906
+ var PeerBytesTicketSchema = object({
9907
+ /** `http://127.0.0.1:<port>/<token>`. One `GET` takes it. */
9908
+ url: string().min(1),
9909
+ /**
9910
+ * The HOST node this URL means something on — the hub or a named agent,
9911
+ * never a runner. {@link AddonPeerBytes.open} compares it to its own and
9912
+ * refuses `cross-node` by name when they differ, without dialling.
9913
+ */
9914
+ hostNodeId: string().min(1),
9915
+ expiresAtMs: number().int().nonnegative(),
9916
+ /**
9917
+ * What the producer DECLARED the body to be, when it knows — `null` when it
9918
+ * does not. Never `0` for unknown (D393): a consumer sizing a bound off this
9919
+ * must be able to tell "the producer did not say" from "the body is empty".
9920
+ */
9921
+ declaredBytes: number().int().nonnegative().nullable()
9465
9922
  });
9466
- object({
9467
- tabs: array(object({
9468
- id: string(),
9469
- label: string(),
9470
- icon: string(),
9471
- order: number().optional()
9472
- })).optional(),
9473
- sections: array(ContributionSectionSchema)
9474
- }).nullable();
9475
- object({ deviceId: number() }), object({ deviceId: number() }), object({
9476
- deviceId: number(),
9477
- patch: record(string(), unknown())
9478
- }), object({ success: literal(true) });
9479
- object({ deviceId: number() }), unknown().nullable();
9480
- function method(input, output, options) {
9481
- return {
9482
- input,
9483
- output,
9484
- kind: options?.kind ?? "query",
9485
- ...options?.auth !== void 0 ? { auth: options.auth } : {},
9486
- ...options?.access !== void 0 ? { access: options.access } : {},
9487
- ...options?.role !== void 0 ? { role: options.role } : {},
9488
- ...options?.caller !== void 0 ? { caller: options.caller } : {},
9489
- timeoutMs: options?.timeoutMs
9490
- };
9491
- }
9492
- /**
9493
- * A wrapper/system-only method: served exclusively by the cap's system-level
9494
- * provider (`InferProvider`), and OPTIONAL on `InferNativeProvider` so per-device
9495
- * driver natives don't stub out a wrapper concern (e.g. a cross-device cache
9496
- * overview). The `systemOnly: true` literal is what `InferNativeProvider` keys on.
9497
- */
9498
- function systemMethod(input, output, options) {
9499
- return {
9500
- ...method(input, output, options),
9501
- systemOnly: true
9502
- };
9503
- }
9504
- /**
9505
- * A method a SOURCE of a collection cap may legitimately not serve — OPTIONAL
9506
- * on `InferProvider`. The `providerOptional: true` literal is what
9507
- * `InferProvider` keys on; see {@link CapabilityMethodSchema.providerOptional}
9508
- * for when this is the honest answer and when it is a soft stub.
9509
- */
9510
- function optionalMethod(input, output, options) {
9511
- return {
9512
- ...method(input, output, options),
9513
- providerOptional: true
9514
- };
9515
- }
9516
9923
  var READING_QUANTITIES = [
9517
9924
  "temperature",
9518
9925
  "pressure",
@@ -10091,7 +10498,6 @@ var CAP_NAMES = Object.freeze([
10091
10498
  "climate-control",
10092
10499
  "color",
10093
10500
  "composer",
10094
- "connection-test",
10095
10501
  "connectivity",
10096
10502
  "consumables",
10097
10503
  "contact",
@@ -11238,6 +11644,10 @@ Object.freeze({
11238
11644
  "all",
11239
11645
  "one"
11240
11646
  ]
11647
+ },
11648
+ {
11649
+ "path": "positionUpdatedAt",
11650
+ "valueType": "number"
11241
11651
  }
11242
11652
  ],
11243
11653
  "meter": [{
@@ -11492,22 +11902,6 @@ Object.freeze({
11492
11902
  "path": "pumpRunning",
11493
11903
  "valueType": "boolean"
11494
11904
  },
11495
- {
11496
- "path": "lastDrink",
11497
- "valueType": "number"
11498
- },
11499
- {
11500
- "path": "currentHourDrink",
11501
- "valueType": "number"
11502
- },
11503
- {
11504
- "path": "last24hDrink",
11505
- "valueType": "number"
11506
- },
11507
- {
11508
- "path": "todayDrink",
11509
- "valueType": "number"
11510
- },
11511
11905
  {
11512
11906
  "path": "error",
11513
11907
  "valueType": "string"
@@ -12073,12 +12467,65 @@ Object.freeze({
12073
12467
  }
12074
12468
  ]
12075
12469
  });
12470
+ Object.freeze({
12471
+ "actions": { "run": 363e4 },
12472
+ "audio-analyzer": { "classify": 3e4 },
12473
+ "custom-model-registry": { "importModelBundle": 18e5 },
12474
+ "database-snapshot": { "writeSnapshot": 18e5 },
12475
+ "device-manager": {
12476
+ "migrateDevice": 72e4,
12477
+ "runDiscoverySweep": 12e4
12478
+ },
12479
+ "device-provider": { "reloadDevice": 18e4 },
12480
+ "llm": {
12481
+ "generate": 6e5,
12482
+ "generateVision": 6e5,
12483
+ "testProfile": 6e5
12484
+ },
12485
+ "llm-runtime": {
12486
+ "complete": 6e5,
12487
+ "completeApple": 6e5,
12488
+ "ensureStarted": 6e5,
12489
+ "installModel": 36e5
12490
+ },
12491
+ "local-network": { "scanNetwork": 9e4 },
12492
+ "model-convert": { "convert": 6e5 },
12493
+ "pipeline-analytics": {
12494
+ "addRetrainFrameFromRecording": 6e4,
12495
+ "offerRetrainArchive": 12e4,
12496
+ "proposeRetrainAnnotationsWithLlm": 18e4,
12497
+ "resolveRetrainTrainingCorpus": 6e4,
12498
+ "writeRetrainArchive": 36e5
12499
+ },
12500
+ "server-management": { "applyServerUpdate": 96e4 },
12501
+ "terminal-session": { "pullOutput": 15e3 },
12502
+ "training": {
12503
+ "canaryResult": 12e4,
12504
+ "cancelJob": 12e4,
12505
+ "planJob": 6e4,
12506
+ "registerResult": 18e5,
12507
+ "rollbackCanary": 12e4,
12508
+ "startJob": 12e4,
12509
+ "startJobBatch": 12e4
12510
+ },
12511
+ "training-provider": {
12512
+ "cancelJob": 6e4,
12513
+ "cleanupJob": 3e5,
12514
+ "getJob": 6e4,
12515
+ "listJobEvents": 6e4,
12516
+ "listJobs": 12e4,
12517
+ "offerArtifact": 3e5,
12518
+ "readResult": 3e5,
12519
+ "submitJob": 18e5,
12520
+ "uploadDataset": 72e5
12521
+ }
12522
+ });
12076
12523
  object({
12077
12524
  code: string().regex(/^[a-z][a-z0-9-]*(\.[a-z0-9-]+)+$/),
12078
12525
  params: record(string(), union([string(), number()])).optional()
12079
12526
  });
12080
12527
  //#endregion
12081
- //#region ../types/dist/composition-pOHbTzRB.mjs
12528
+ //#region ../types/dist/composition-BmBHuDTQ.mjs
12082
12529
  /**
12083
12530
  * The ffmpeg build every CamStack node downloads, per platform and arch.
12084
12531
  *
@@ -12382,7 +12829,7 @@ var table = {
12382
12829
  },
12383
12830
  dwell: {
12384
12831
  minArgs: 3,
12385
- maxArgs: 3,
12832
+ maxArgs: 4,
12386
12833
  apply: () => {
12387
12834
  throw new ExpressionEvalError("dwell: stateful evaluation context is required");
12388
12835
  }
@@ -13359,278 +13806,498 @@ new Set(EVENT_OWNER_TYPES);
13359
13806
  * The publish workflow STAMPS these after the version bump
13360
13807
  * (`scripts/ci/stamp-requires.mjs`); nobody types a number by hand.
13361
13808
  *
13362
- * A requirement that cannot be checked is NOT met: a shell that reports no
13363
- * version counts as below the minimum, and an unreadable running version is
13364
- * named in the result (a failed read is never a pass).
13809
+ * A requirement that cannot be checked is NOT met: a shell that reports no
13810
+ * version counts as below the minimum, and an unreadable running version is
13811
+ * named in the result (a failed read is never a pass).
13812
+ */
13813
+ /** `>=MAJOR.MINOR.PATCH[-prerelease]` — the only range shape a requirement uses. */
13814
+ var MinVersionSchema = string().regex(/^>=\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/, "a minimum is written \">=X.Y.Z\"");
13815
+ object({
13816
+ /** The oldest `@camstack/server` this package runs on. */
13817
+ server: MinVersionSchema.optional(),
13818
+ /** The oldest installed version of each named addon package. */
13819
+ addons: record(string(), MinVersionSchema).optional(),
13820
+ /** The oldest shell around the server, per shell kind. */
13821
+ wrapper: object({
13822
+ desktop: MinVersionSchema.optional(),
13823
+ image: MinVersionSchema.optional()
13824
+ }).optional()
13825
+ });
13826
+ /** One unmet requirement; each names the versions on both sides. */
13827
+ var UnmetRequirementSchema = discriminatedUnion("kind", [
13828
+ object({
13829
+ kind: literal("server-too-old"),
13830
+ required: string(),
13831
+ /** `null` — the running server version could not be read. */
13832
+ running: string().nullable()
13833
+ }),
13834
+ object({
13835
+ kind: literal("addon-too-old"),
13836
+ packageName: string(),
13837
+ required: string(),
13838
+ /** `null` — the addon is not installed (or its version is unreadable). */
13839
+ running: string().nullable()
13840
+ }),
13841
+ object({
13842
+ kind: literal("wrapper-too-old"),
13843
+ wrapper: _enum(["desktop", "image"]),
13844
+ required: string(),
13845
+ /** `null` — the wrapper reported no version. */
13846
+ running: string().nullable()
13847
+ })
13848
+ ]);
13849
+ var RequiredAddonUpdateSchema = object({
13850
+ packageName: string(),
13851
+ /** The minimum the target server declares. */
13852
+ required: string(),
13853
+ /** What this node has; `null` when the addon is not installed. */
13854
+ installed: string().nullable()
13855
+ });
13856
+ /**
13857
+ * Which integration instance a settings form is for. An addon that serves several instances
13858
+ * (`instanceMode: multiple`) can show a different form per instance — an NVR integration
13859
+ * needs its connection, the default integration needs the addon's own sections.
13860
+ *
13861
+ * - `integrationId` is `null` in the create wizard: nothing exists yet, the operator is
13862
+ * setting up a NEW instance.
13863
+ * - `mode` is the wizard mode of the integration type (`getAvailableTypes`).
13864
+ * - `candidateStableId` is the discovery candidate a wizard was seeded from, if any.
13865
+ */
13866
+ var IntegrationInstanceRefSchema = object({
13867
+ integrationId: string().nullable(),
13868
+ mode: _enum([
13869
+ "standalone",
13870
+ "account",
13871
+ "broker"
13872
+ ]),
13873
+ candidateStableId: string().optional()
13874
+ });
13875
+ /**
13876
+ * notification-output — canonical, capability-gated notification delivery.
13877
+ *
13878
+ * Apprise-derived model (see
13879
+ * `docs/superpowers/specs/2026-07-03-notification-output-notifier-matrix.md`):
13880
+ * callers emit ONE canonical `Notification`; each provider declares a
13881
+ * per-kind capability descriptor (`TargetKind`), and the pure degrade
13882
+ * engine (`@camstack/types` `prepareNotification`) transcodes / degrades the
13883
+ * message to what the kind supports — callers never special-case a service.
13884
+ *
13885
+ * DESIGN DECISIONS (locked):
13886
+ * - Target CRUD lives on THIS cap (`upsertTarget` / `deleteTarget` /
13887
+ * `setTargetEnabled`), each provider persisting via the `settings-store`
13888
+ * cap. Rationale: the admin UI needs one uniform surface across the
13889
+ * notifiers addon AND the HA addon; the addon-`globalSettingsSchema`-array
13890
+ * alternative would fork the UI per addon and cannot host the
13891
+ * discovery→adopt flow.
13892
+ * - `listTargetKinds` / `listTargets` / `discoverTargets` return arrays →
13893
+ * the generated cap-mount auto-`concatCollection`-fans them across every
13894
+ * registered provider (notifiers addon + HA addon) so one catalog is
13895
+ * routable. `send` / `testTarget` / CRUD route to ONE provider by the
13896
+ * `addonId` the generated collection router extracts from the call input.
13897
+ * - `Attachment.bytes` is `Uint8Array`. Transport-safe: superjson (the tRPC
13898
+ * transformer) + UDS MsgPack both round-trip typed arrays — already used by
13899
+ * `storage` / `storage-provider` / `recording` caps over the same path. No
13900
+ * base64 fallback needed.
13901
+ *
13902
+ * TODO (deferred, closed-set change — separate decision): add
13903
+ * `providerKind: 'notify'` so notification providers surface on the unified
13904
+ * admin "Integrations" page.
13905
+ */
13906
+ /**
13907
+ * Zentik-derived typed-media enum — the superset across every kind. Each
13908
+ * adapter picks what it supports and the degrade engine filters the rest.
13909
+ */
13910
+ var AttachmentMediaTypeSchema = _enum([
13911
+ "image",
13912
+ "video",
13913
+ "gif",
13914
+ "audio",
13915
+ "icon"
13916
+ ]);
13917
+ /**
13918
+ * A single attachment. Exactly one of `url` (remote source, most adapters
13919
+ * prefer this) or `bytes` (inline source; required for Pushover-style
13920
+ * bytes-only kinds) MUST be present — the degrade engine expresses a
13921
+ * url→bytes fetch as a `needsFetch` directive the adapter executes.
13922
+ */
13923
+ var AttachmentSchema = object({
13924
+ mediaType: AttachmentMediaTypeSchema,
13925
+ url: string().optional(),
13926
+ bytes: _instanceof(Uint8Array).optional(),
13927
+ mime: string().optional(),
13928
+ name: string().optional()
13929
+ }).refine((a) => a.url !== void 0 || a.bytes !== void 0, { message: "Attachment requires either `url` or `bytes`" });
13930
+ var NotificationFormatSchema = _enum([
13931
+ "text",
13932
+ "markdown",
13933
+ "html"
13934
+ ]);
13935
+ /**
13936
+ * The CLOSED icon vocabulary an action button may use.
13937
+ *
13938
+ * A closed set, not a free string, and that is the whole point: an arbitrary
13939
+ * icon name is one that ntfy renders, zentik silently drops, and nobody
13940
+ * notices — the same class of gap as a zone vocabulary nothing produced
13941
+ * ([D35](../../../docs/decisions/adr-0035.md)). Every adapter maps this set or
13942
+ * declares `actionIcons: false` and the degrade engine strips the field.
13943
+ *
13944
+ * Named by INTENT, never by glyph. "check" would tie the vocabulary to one
13945
+ * renderer's icon set; "acknowledge" survives an adapter that draws it
13946
+ * differently.
13947
+ *
13948
+ * ── A TOKEN IS NOT A WIRE VALUE ─────────────────────────────────────
13949
+ *
13950
+ * These names are for US. **No adapter may forward one verbatim.** Each maps
13951
+ * the whole set onto its own renderer's vocabulary through a
13952
+ * `Record<NotificationActionIcon, string>` — a Record, never a lookup with a
13953
+ * fallback, so adding a member here fails every adapter's build until someone
13954
+ * decides its glyph, which is the only place that decision can be made
13955
+ * honestly.
13956
+ *
13957
+ * This paragraph is the bug. Zentik declared `actionIcons: true` and passed
13958
+ * `disarm` straight through; iOS feeds that string to
13959
+ * `UNNotificationActionIcon(systemImageName:)`, `disarm` is not an SF Symbol,
13960
+ * and every snooze and alarm button arrived BLANK. A pass-through is not a
13961
+ * mapping, and "the field is documented" is not "the value renders".
13962
+ *
13963
+ * Adding a member is TRAIN-BOUND. The enum lives in the published
13964
+ * `@camstack/server` closure and the cap seam validates against the HUB's copy,
13965
+ * so an addon that emits a token the running hub does not know does not lose an
13966
+ * icon — its whole `send` fails Zod validation and the notification never
13967
+ * arrives. Never emit a new token from an addon before the train carrying it.
13968
+ */
13969
+ var NotificationActionIconSchema = _enum([
13970
+ "acknowledge",
13971
+ "dismiss",
13972
+ "silence",
13973
+ "snooze",
13974
+ "view",
13975
+ "play",
13976
+ "open",
13977
+ "close",
13978
+ "lock",
13979
+ "unlock",
13980
+ "arm",
13981
+ "arm-home",
13982
+ "arm-away",
13983
+ "arm-night",
13984
+ "disarm",
13985
+ "light",
13986
+ "alert",
13987
+ "camera"
13988
+ ]);
13989
+ /** A single tap-through action button. */
13990
+ var NotificationActionSchema = object({
13991
+ id: string(),
13992
+ label: string(),
13993
+ url: string().optional(),
13994
+ /** Dropped by the degrade engine for a kind with `caps.actionIcons: false`. */
13995
+ icon: NotificationActionIconSchema.optional(),
13996
+ /**
13997
+ * Renders in a warning style where the notifier supports it.
13998
+ *
13999
+ * A HINT, never a gate. The callback's authority is its token and nothing
14000
+ * else — see `notification-center/action-token.ts` for what that does and
14001
+ * does not buy.
14002
+ */
14003
+ destructive: boolean().optional(),
14004
+ /**
14005
+ * How the tap should REACH the url.
14006
+ *
14007
+ * `navigate` (absent, and every button authored before this field) opens it:
14008
+ * the phone leaves the notification and shows whatever the callback returns.
14009
+ * That is right for a button whose answer the operator wants to read.
14010
+ *
14011
+ * `background` fires it as a POST and stays put. It exists for the buttons
14012
+ * whose whole point is not to interrupt — "silence this for 30 minutes" is
14013
+ * an answer to the notification, and being thrown into a browser tab to
14014
+ * confirm it costs more attention than the notification did. A backend that
14015
+ * cannot do a background call renders it as an ordinary link (the adapters
14016
+ * fall back rather than dropping the button), so this is a preference, never
14017
+ * a requirement.
14018
+ */
14019
+ mode: _enum(["navigate", "background"]).optional()
14020
+ });
14021
+ /** A delivery parameter value: what a notifier declared it takes. */
14022
+ var DeliveryParamValueSchema = union([
14023
+ string(),
14024
+ number(),
14025
+ boolean()
14026
+ ]);
14027
+ /**
14028
+ * One extra delivery parameter a notifier KIND declares (D938). A rule that
14029
+ * addresses a target of that kind may set it; a kind that declares nothing is
14030
+ * never handed one. The admin UI derives its control from this descriptor —
14031
+ * no editor knows a service by name.
14032
+ *
14033
+ * Optional fields are `.optional()`, never `.default()` (a Zod default does not
14034
+ * run on the addon cap path).
13365
14035
  */
13366
- /** `>=MAJOR.MINOR.PATCH[-prerelease]` — the only range shape a requirement uses. */
13367
- var MinVersionSchema = string().regex(/^>=\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/, "a minimum is written \">=X.Y.Z\"");
13368
- object({
13369
- /** The oldest `@camstack/server` this package runs on. */
13370
- server: MinVersionSchema.optional(),
13371
- /** The oldest installed version of each named addon package. */
13372
- addons: record(string(), MinVersionSchema).optional(),
13373
- /** The oldest shell around the server, per shell kind. */
13374
- wrapper: object({
13375
- desktop: MinVersionSchema.optional(),
13376
- image: MinVersionSchema.optional()
13377
- }).optional()
14036
+ var DeliveryParamSchema = object({
14037
+ key: string().min(1),
14038
+ label: string(),
14039
+ /** i18n key of the label, resolved by the declaring addon's namespace. */
14040
+ labelKey: string().optional(),
14041
+ type: _enum([
14042
+ "enum",
14043
+ "number",
14044
+ "boolean",
14045
+ "string"
14046
+ ]),
14047
+ /** `enum` only: the closed set of accepted values. */
14048
+ options: array(object({
14049
+ value: string(),
14050
+ label: string()
14051
+ })).optional(),
14052
+ /** `number` only. */
14053
+ min: number().optional(),
14054
+ max: number().optional(),
14055
+ /** What the notifier does when the rule sets nothing; shown as the placeholder. */
14056
+ default: DeliveryParamValueSchema.optional()
13378
14057
  });
13379
- /** One unmet requirement; each names the versions on both sides. */
13380
- var UnmetRequirementSchema = discriminatedUnion("kind", [
13381
- object({
13382
- kind: literal("server-too-old"),
13383
- required: string(),
13384
- /** `null` — the running server version could not be read. */
13385
- running: string().nullable()
13386
- }),
13387
- object({
13388
- kind: literal("addon-too-old"),
13389
- packageName: string(),
13390
- required: string(),
13391
- /** `null` — the addon is not installed (or its version is unreadable). */
13392
- running: string().nullable()
14058
+ /**
14059
+ * The canonical notification. `body` is the only hard field (Apprise model).
14060
+ * `priority` is a 5-level ORDINAL (1=lowest … 3=normal(default) … 5=urgent),
14061
+ * NOT a fixed severity enum — each kind declares its own `caps.levels` and
14062
+ * the adapter maps this ordinal onto its native level. `level?` is an
14063
+ * optional kind-native level id (`emergency`, `silent`, …) that overrides
14064
+ * `priority` for that one target.
14065
+ */
14066
+ var NotificationSchema = object({
14067
+ body: string(),
14068
+ title: string().optional(),
14069
+ format: NotificationFormatSchema.default("text"),
14070
+ priority: number().int().min(1).max(5).default(3),
14071
+ level: string().optional(),
14072
+ attachments: array(AttachmentSchema).optional(),
14073
+ clickUrl: string().optional(),
14074
+ actions: array(NotificationActionSchema).optional(),
14075
+ sound: string().optional(),
14076
+ ttl: number().optional(),
14077
+ tag: string().optional(),
14078
+ deviceId: number().optional(),
14079
+ eventId: string().optional(),
14080
+ metadata: record(string(), unknown()).optional(),
14081
+ /**
14082
+ * Values for the parameters the target's kind DECLARES in
14083
+ * {@link TargetKindSchema} `deliveryParams`. Already validated against the
14084
+ * declaration by the sender; a notifier reads only the keys it declared.
14085
+ */
14086
+ delivery: record(string(), DeliveryParamValueSchema).optional()
14087
+ });
14088
+ /** One declared native severity/priority level for a kind. */
14089
+ var TargetKindLevelSchema = object({
14090
+ id: string(),
14091
+ label: string(),
14092
+ /** Which canonical priority (1..5) this level maps to. `null` = qualitative-only. */
14093
+ ordinal: number().int().min(1).max(5).nullable(),
14094
+ flags: object({
14095
+ critical: boolean().optional(),
14096
+ silent: boolean().optional(),
14097
+ noPush: boolean().optional()
14098
+ }).optional(),
14099
+ /** e.g. Pushover `emergency` requires `retry` / `expire`. */
14100
+ requires: array(string()).optional(),
14101
+ description: string().optional()
14102
+ });
14103
+ /** The full capability block consulted before dispatch. */
14104
+ var TargetKindCapsSchema = object({
14105
+ attachments: object({
14106
+ mediaTypes: array(AttachmentMediaTypeSchema),
14107
+ mode: _enum([
14108
+ "url",
14109
+ "bytes",
14110
+ "both"
14111
+ ]),
14112
+ max: number().int().nonnegative(),
14113
+ maxBytes: number().int().positive().optional()
13393
14114
  }),
13394
- object({
13395
- kind: literal("wrapper-too-old"),
13396
- wrapper: _enum(["desktop", "image"]),
13397
- required: string(),
13398
- /** `null` — the wrapper reported no version. */
13399
- running: string().nullable()
13400
- })
13401
- ]);
13402
- var RequiredAddonUpdateSchema = object({
13403
- packageName: string(),
13404
- /** The minimum the target server declares. */
13405
- required: string(),
13406
- /** What this node has; `null` when the addon is not installed. */
13407
- installed: string().nullable()
14115
+ /** Max action buttons (0 = none). */
14116
+ actions: number().int().nonnegative(),
14117
+ /**
14118
+ * Whether this kind renders a per-action ICON.
14119
+ *
14120
+ * `.optional()`, deliberately NOT `.default(false)`: a Zod default does not
14121
+ * run on the addon cap path — three production failures in one day taught
14122
+ * this repo that once. Absent is read as false by the degrade engine, which
14123
+ * is the safe direction: an icon that is not rendered costs nothing, an icon
14124
+ * assumed and dropped costs the operator's trust in the field.
14125
+ */
14126
+ actionIcons: boolean().optional(),
14127
+ levels: array(TargetKindLevelSchema),
14128
+ format: array(NotificationFormatSchema),
14129
+ clickUrl: boolean(),
14130
+ sound: boolean(),
14131
+ ttl: boolean(),
14132
+ bodyMaxLen: number().int().positive()
13408
14133
  });
13409
14134
  /**
13410
- * Which integration instance a settings form is for. An addon that serves several instances
13411
- * (`instanceMode: multiple`) can show a different form per instance — an NVR integration
13412
- * needs its connection, the default integration needs the addon's own sections.
13413
- *
13414
- * - `integrationId` is `null` in the create wizard: nothing exists yet, the operator is
13415
- * setting up a NEW instance.
13416
- * - `mode` is the wizard mode of the integration type (`getAvailableTypes`).
13417
- * - `candidateStableId` is the discovery candidate a wizard was seeded from, if any.
14135
+ * `configSchema` is a `ConfigUISchema` tree passed through to the admin
14136
+ * FormBuilder. Stored as `z.unknown()` at the cap seam (mirrors
14137
+ * `device-provider.getChildCreationSchema` `CreationSchemaOutputSchema`) —
14138
+ * the union is large and not meant for runtime validation here; the exported
14139
+ * `TargetKind` type re-tightens `configSchema` to `ConfigUISchema`.
13418
14140
  */
13419
- var IntegrationInstanceRefSchema = object({
13420
- integrationId: string().nullable(),
13421
- mode: _enum([
13422
- "standalone",
13423
- "account",
13424
- "broker"
13425
- ]),
13426
- candidateStableId: string().optional()
14141
+ var ConfigSchemaPassthrough$4 = unknown();
14142
+ var TargetKindSchema = object({
14143
+ kind: string(),
14144
+ label: string(),
14145
+ icon: string(),
14146
+ /** Stamped by each provider so the concat-fanned catalog stays routable. */
14147
+ addonId: string(),
14148
+ /**
14149
+ * URL of the kind's bundled BRAND icon, served by the providing addon over
14150
+ * its own `addon-routes` surface (`/addon/<addonId>/icons/<kind>`). Absent
14151
+ * when the addon bundles no icon for that kind — the client then falls back
14152
+ * to a neutral glyph rather than rendering the raw `icon` NAME as text.
14153
+ *
14154
+ * Root-relative on purpose: it resolves against whatever origin serves a web
14155
+ * client, and a native client joins it onto its own hub base.
14156
+ *
14157
+ * DECLARED here deliberately. It used to travel as an undeclared passthrough
14158
+ * field that survived only because the runtime cap-router forwards provider
14159
+ * output verbatim — so every consumer had to re-declare it by hand to stop
14160
+ * its own Zod parse from stripping it, and the whole arrangement would have
14161
+ * broken silently the moment output validation was tightened anywhere.
14162
+ */
14163
+ iconUrl: string().optional(),
14164
+ /**
14165
+ * Media type of {@link iconUrl} (`image/svg+xml`, `image/png`, …).
14166
+ *
14167
+ * The server knows this and therefore says it, because the client cannot
14168
+ * safely guess: a React-Native client renders SVG and raster through two
14169
+ * DIFFERENT components (`react-native-svg` vs `expo-image` — expo-image does
14170
+ * not decode SVG on iOS/Android), so without this it silently fell back to a
14171
+ * placeholder glyph for every vector icon while the web build looked fine.
14172
+ *
14173
+ * Absent when {@link iconUrl} is absent, or for a legacy provider that has
14174
+ * not been updated — a client that cannot determine the type should prefer
14175
+ * its raster path, which is the safe default for an unknown image.
14176
+ */
14177
+ iconMediaType: string().optional(),
14178
+ configSchema: ConfigSchemaPassthrough$4,
14179
+ /**
14180
+ * The config keys that decide WHERE this kind's secrets are sent (server,
14181
+ * base URL, instance, chat, recipient). A save that changes any of them
14182
+ * while leaving a secret redacted is refused by the provider (D634), so an
14183
+ * editor uses this to ask for the secret on exactly those edits instead of
14184
+ * on every edit.
14185
+ *
14186
+ * Optional: absent from a provider that holds no secret (the Home Assistant
14187
+ * kinds) and from a provider older than this field — an editor that finds
14188
+ * it absent must assume ANY edit may need the secret.
14189
+ */
14190
+ destinationKeys: array(string()).optional(),
14191
+ supportsDiscovery: boolean(),
14192
+ /**
14193
+ * Extra delivery parameters a rule may set for a target of this kind (D938).
14194
+ * Absent = none; the rule editor then offers nothing.
14195
+ */
14196
+ deliveryParams: array(DeliveryParamSchema).optional(),
14197
+ caps: TargetKindCapsSchema
13427
14198
  });
13428
14199
  /**
13429
- * `RecordIntegrationInstances` - the `integration-instances` provider over ONE
13430
- * entry kind, so an addon that holds a connection serves it in ~30 lines.
13431
- *
13432
- * Every instance is one record of the addon's own kind, keyed by the
13433
- * `integrations` registry id. The records door does the secret work: a field the
13434
- * kind marks `.meta({ secret: true })` is a keychain marker bound to the row, so
13435
- * deleting the row deletes the secret, and one row's value is never another's.
13436
- *
13437
- * Patch rules for a secret (`updateInstance`): omitted, `''`, the redaction
13438
- * token or the view the form was given KEEP the stored secret;
13439
- * `{ $secretClear: true }` clears it; any other string replaces it.
14200
+ * A persisted target. `config` holds secrets; providers REDACT secret fields
14201
+ * (return a presence marker only) when serving `listTargets` — never
14202
+ * round-trip a stored secret to the UI.
13440
14203
  */
13441
- /** The most instances one addon lists (an integrations page, not a table). */
13442
- var INSTANCES_LIST_MAX = 1e3;
13443
- /** The keys of the kind's secret fields that sit at the top level of the body. */
13444
- function topLevelSecretKeys(paths) {
13445
- return new Set(paths.filter((p) => !p.includes(".") && !p.includes("[") && !p.includes("{")));
13446
- }
13447
- /** The keys of the kind's top-level MAPS whose values are secrets (`applianceSecrets{}`). */
13448
- function secretMapKeys(paths) {
13449
- return new Set(paths.filter((p) => p.endsWith("{}") && !p.slice(0, -2).match(/[.[{]/)).map((p) => p.slice(0, -2)));
13450
- }
14204
+ var TargetSchema = object({
14205
+ id: string(),
14206
+ name: string(),
14207
+ kind: string(),
14208
+ addonId: string(),
14209
+ enabled: boolean(),
14210
+ config: record(string(), unknown())
14211
+ });
14212
+ /** A discovery-surfaced candidate (config is partial + non-secret). */
14213
+ var DiscoveredTargetSchema = object({
14214
+ kind: string(),
14215
+ suggestedName: string(),
14216
+ config: record(string(), unknown())
14217
+ });
14218
+ /** The degrade engine's report — what was resolved / dropped / degraded. */
14219
+ var RenderedAsSchema = object({
14220
+ level: string(),
14221
+ format: NotificationFormatSchema,
14222
+ attachmentsSent: number().int().nonnegative(),
14223
+ actionsSent: number().int().nonnegative(),
14224
+ truncated: boolean(),
14225
+ dropped: array(string())
14226
+ });
14227
+ var SendResultSchema = object({
14228
+ success: boolean(),
14229
+ error: string().optional(),
14230
+ renderedAs: RenderedAsSchema.optional()
14231
+ });
14232
+ /** Same shape as SendResult — kept as a distinct name for the test panel. */
14233
+ var TestResultSchema = SendResultSchema;
13451
14234
  /**
13452
- * A patch value for a map of secrets: an entry that is omitted, `''`, the redaction token or the
13453
- * view the form was given KEEPS its stored secret (it is left out of the merge); `{ $secretClear }`
13454
- * or `null` removes the entry; any other string replaces it. Null when nothing is left to merge.
14235
+ * Pre-save credential probe against a partial (unsaved) target config.
14236
+ * `resolvedUrl` never includes secrets (token stripped from path).
13455
14237
  */
13456
- function secretMapPatch(value) {
13457
- if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
13458
- const out = {};
13459
- for (const [key, entry] of Object.entries(value)) if (entry === null || isSecretClear(entry)) out[key] = null;
13460
- else if (typeof entry === "string" && entry !== "" && entry !== "__camstack_redacted__" && !isSecretFieldView(entry)) out[key] = entry;
13461
- return Object.keys(out).length > 0 ? out : null;
13462
- }
13463
- /** Does the kind's body schema carry an `enabled` field? */
13464
- function declaresEnabled(kind) {
13465
- const json = toJSONSchema(kind.schema, {
13466
- unrepresentable: "any",
13467
- io: "input"
13468
- });
13469
- const properties = Reflect.get(json, "properties");
13470
- return typeof properties === "object" && properties !== null && "enabled" in properties;
13471
- }
13472
- var RecordIntegrationInstances = class {
13473
- records;
13474
- kind;
13475
- hooks;
13476
- handle;
13477
- secretKeys;
13478
- secretMaps;
13479
- nameField;
13480
- /** The `integrations` registry owns the on/off switch (`role: devices`); the body has none. */
13481
- registryOwnsEnabled;
13482
- constructor(records, kind, hooks) {
13483
- this.records = records;
13484
- this.kind = kind;
13485
- this.hooks = hooks;
13486
- this.handle = records.kind(kind);
13487
- this.secretKeys = topLevelSecretKeys(kind.declaration.secretPaths);
13488
- this.secretMaps = secretMapKeys(kind.declaration.secretPaths);
13489
- this.nameField = kind.declaration.entry?.nameField ?? "name";
13490
- this.registryOwnsEnabled = hooks.description.role === "devices";
13491
- 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"`);
13492
- }
14238
+ var ProbeTargetConfigResultSchema = object({
14239
+ ok: boolean(),
14240
+ resolvedUrl: string(),
14241
+ httpStatus: number().int().optional(),
14242
+ stateInstance: string().optional(),
14243
+ error: string().optional()
14244
+ });
14245
+ method(object({}), array(TargetKindSchema)), method(object({}), array(TargetSchema), { auth: "admin" }), method(object({ targetId: string() }), TargetSchema, { auth: "admin" }), method(object({
14246
+ kind: string(),
14247
+ config: record(string(), unknown()).optional(),
13493
14248
  /**
13494
- * One instance read for the addon's own runtime; null when absent. When the keychain is
13495
- * locked the row is served WITHOUT its secrets and says so (`secrets: 'unavailable'`), so the
13496
- * caller can keep what it had instead of reconfiguring with an empty secret (D49).
14249
+ * When editing / duplicating, the blank password field never round-trips
14250
+ * the stored token. Pass the source target id so the provider can restore
14251
+ * secrets server-side before dialling (same merge as upsert).
13497
14252
  */
13498
- async readResolved(id) {
13499
- try {
13500
- const record = await this.handle.getResolved(id);
13501
- return record === null ? null : {
13502
- id,
13503
- body: record.data,
13504
- enabled: record.data.enabled !== false,
13505
- secrets: "resolved"
13506
- };
13507
- } catch (err) {
13508
- if (!(err instanceof RecordSecretUnavailableError)) throw err;
13509
- const stored = await this.handle.get(id);
13510
- if (stored === null) return null;
13511
- return {
13512
- id,
13513
- body: Object.fromEntries(Object.entries(stored.data).filter(([key]) => !this.secretKeys.has(key))),
13514
- enabled: stored.data.enabled !== false,
13515
- secrets: "unavailable"
13516
- };
13517
- }
13518
- }
13519
- /** The body of {@link readResolved} alone; a locked keychain yields the row without secrets. */
13520
- async getResolved(id) {
13521
- return (await this.readResolved(id))?.body ?? null;
13522
- }
13523
- /** Every instance, secrets resolved where the keychain allows; an absent one is skipped. */
13524
- async listResolved() {
13525
- const page = await this.handle.query({ limit: INSTANCES_LIST_MAX });
13526
- const out = [];
13527
- for (const record of page.records) {
13528
- const read = await this.readResolved(record.id);
13529
- if (read !== null) out.push(read);
13530
- }
13531
- return out;
13532
- }
13533
- viewOf(record) {
13534
- const shown = secretViewsOf(this.records.owner, this.kind.name, record.id, this.kind.declaration, record.data);
13535
- const rawName = record.data[this.nameField];
13536
- const kind = this.hooks.kindOf?.(record.data);
13537
- const health = this.hooks.health?.(record.data, record.id);
13538
- return {
13539
- id: record.id,
13540
- name: typeof rawName === "string" ? rawName : record.id,
13541
- configured: this.hooks.configured(record.data),
13542
- ...this.registryOwnsEnabled ? {} : { enabled: record.data.enabled !== false },
13543
- formValues: shown,
13544
- ...kind !== void 0 ? { kind } : {},
13545
- ...health?.status !== void 0 ? { status: health.status } : {},
13546
- ...health?.lastCheckedAt !== void 0 ? { lastCheckedAt: health.lastCheckedAt } : {}
13547
- };
13548
- }
13549
- describe = async () => this.hooks.mintId === void 0 ? this.hooks.description : {
13550
- ...this.hooks.description,
13551
- mintsId: true
13552
- };
13553
- instanceFormSchema = async ({ id }) => this.hooks.formSchema(id);
13554
- listInstances = async () => {
13555
- return (await this.handle.query({ limit: INSTANCES_LIST_MAX })).records.map((record) => this.viewOf(record));
13556
- };
13557
- getInstance = async ({ id }) => {
13558
- const record = await this.handle.get(id);
13559
- return record === null ? null : this.viewOf(record);
13560
- };
13561
- /** Insert ONE row (`ifRev: 0`: an existing id is refused, never overwritten). */
13562
- createInstance = async ({ id, name, kind, values }) => {
13563
- const minted = id ?? this.hooks.mintId?.({
13564
- name,
13565
- ...kind !== void 0 ? { kind } : {}
13566
- });
13567
- if (minted === void 0) throw new Error("createInstance needs an id: this provider does not mint one");
13568
- await this.handle.put({
13569
- id: minted,
13570
- data: this.hooks.initialBody(name, kind)
13571
- }, { ifRev: 0 });
13572
- const patch = this.patchOf(values ?? {});
13573
- if (Object.keys(patch).length > 0) await this.handle.patch(minted, patch);
13574
- await this.hooks.onChanged?.(minted, "created");
13575
- return { id: minted };
13576
- };
13577
- updateInstance = async ({ id, name, values }) => {
13578
- const patch = this.patchOf(values);
13579
- if (name !== void 0) patch[this.nameField] = name;
13580
- await this.handle.patch(id, patch);
13581
- await this.hooks.onChanged?.(id, "updated");
13582
- return { ok: true };
13583
- };
13584
- /** The record patch a form `values` object means: secrets kept, cleared or replaced. */
13585
- patchOf(values) {
13586
- const patch = {};
13587
- for (const [key, value] of Object.entries(values)) {
13588
- if (value === void 0) continue;
13589
- if (this.secretMaps.has(key)) {
13590
- const entries = secretMapPatch(value);
13591
- if (entries !== null) patch[key] = entries;
13592
- } else if (!this.secretKeys.has(key)) patch[key] = value;
13593
- else if (isSecretClear(value)) patch[key] = null;
13594
- else if (typeof value === "string" && value !== "" && value !== "__camstack_redacted__" && !isSecretFieldView(value)) patch[key] = value;
13595
- }
13596
- return patch;
13597
- }
13598
- /** The switch lives in the record body; the addon is told so it applies it (D996). */
13599
- setInstanceEnabled = async ({ id, enabled }) => {
13600
- if (this.registryOwnsEnabled) throw new Error(`instance "${id}": the integrations registry owns the on/off switch of this addon; set it with integrations.update`);
13601
- await this.handle.patch(id, { enabled });
13602
- await this.hooks.onChanged?.(id, "enabled");
13603
- return { ok: true };
13604
- };
13605
- /** The row and its keychain refs go together (the records door). */
13606
- deleteInstance = async ({ id }) => {
13607
- await this.handle.delete(id);
13608
- await this.hooks.onChanged?.(id, "deleted");
13609
- return { ok: true };
13610
- };
13611
- testInstance = async (input) => {
13612
- if (this.hooks.test === void 0) return {
13613
- success: false,
13614
- status: "unsupported",
13615
- error: "This integration declares no connection test"
13616
- };
13617
- return this.hooks.test(input);
13618
- };
13619
- /** The flat provider object to hand to `registerProvider`. */
13620
- toProvider() {
13621
- return {
13622
- describe: this.describe,
13623
- instanceFormSchema: this.instanceFormSchema,
13624
- listInstances: this.listInstances,
13625
- getInstance: this.getInstance,
13626
- createInstance: this.createInstance,
13627
- updateInstance: this.updateInstance,
13628
- setInstanceEnabled: this.setInstanceEnabled,
13629
- deleteInstance: this.deleteInstance,
13630
- testInstance: this.testInstance
13631
- };
13632
- }
13633
- };
14253
+ targetId: string().optional()
14254
+ }), array(DiscoveredTargetSchema), { auth: "admin" }), method(object({
14255
+ kind: string(),
14256
+ config: record(string(), unknown()),
14257
+ /** See `discoverTargets.targetId` — restore stored secrets for a blank password. */
14258
+ targetId: string().optional()
14259
+ }), ProbeTargetConfigResultSchema, {
14260
+ kind: "mutation",
14261
+ auth: "admin"
14262
+ }), method(object({
14263
+ targetId: string(),
14264
+ notification: NotificationSchema
14265
+ }), SendResultSchema, {
14266
+ kind: "mutation",
14267
+ auth: "admin"
14268
+ }), method(object({
14269
+ targetId: string(),
14270
+ sample: NotificationSchema.optional()
14271
+ }), TestResultSchema, {
14272
+ kind: "mutation",
14273
+ auth: "admin"
14274
+ }), method(object({
14275
+ target: TargetSchema,
14276
+ /**
14277
+ * Duplicate flow: create a NEW target id while copying secrets from an
14278
+ * existing row. The UI never holds the stored token; blank / redacted
14279
+ * password fields are restored from this source (D634 still applies if
14280
+ * destinations diverge without a re-typed secret).
14281
+ */
14282
+ cloneSecretsFrom: string().optional()
14283
+ }), TargetSchema, {
14284
+ kind: "mutation",
14285
+ auth: "admin"
14286
+ }), method(object({ targetId: string() }), _void(), {
14287
+ kind: "mutation",
14288
+ auth: "admin"
14289
+ }), method(object({
14290
+ targetId: string(),
14291
+ enabled: boolean()
14292
+ }), _void(), {
14293
+ kind: "mutation",
14294
+ auth: "admin"
14295
+ });
14296
+ looseObject({
14297
+ name: string().min(1),
14298
+ enabled: boolean().optional()
14299
+ });
14300
+ TargetSchema.omit({ id: true });
13634
14301
  var EncodeProfileSchema = object({
13635
14302
  video: object({
13636
14303
  codec: _enum([
@@ -19815,31 +20482,21 @@ var APPLIANCE_CAP_VOCABULARY = {
19815
20482
  "pet-fountain": {
19816
20483
  scope: "device",
19817
20484
  noun: t("Pet fountain", "Fontana per animali"),
19818
- actions: [
19819
- {
19820
- id: "petFountain.pumpOn",
19821
- method: "setPump",
19822
- label: t("Pump on", "Pompa accesa"),
19823
- phrase: t("Start the pump of {device}", "Avvia la pompa di {device}"),
19824
- icon: "play",
19825
- args: { on: true }
19826
- },
19827
- {
19828
- id: "petFountain.pumpOff",
19829
- method: "setPump",
19830
- label: t("Pump off", "Pompa spenta"),
19831
- phrase: t("Stop the pump of {device}", "Ferma la pompa di {device}"),
19832
- icon: "square",
19833
- args: { on: false }
19834
- },
19835
- {
19836
- id: "petFountain.resetDailyConsumption",
19837
- method: "resetDailyConsumption",
19838
- label: t("Clear daily consumption", "Azzera il consumo giornaliero"),
19839
- phrase: t("Clear the daily water consumption of {device}", "Azzera il consumo giornaliero di acqua di {device}"),
19840
- icon: "rotate-ccw"
19841
- }
19842
- ],
20485
+ actions: [{
20486
+ id: "petFountain.pumpOn",
20487
+ method: "setPump",
20488
+ label: t("Pump on", "Pompa accesa"),
20489
+ phrase: t("Start the pump of {device}", "Avvia la pompa di {device}"),
20490
+ icon: "play",
20491
+ args: { on: true }
20492
+ }, {
20493
+ id: "petFountain.pumpOff",
20494
+ method: "setPump",
20495
+ label: t("Pump off", "Pompa spenta"),
20496
+ phrase: t("Stop the pump of {device}", "Ferma la pompa di {device}"),
20497
+ icon: "square",
20498
+ args: { on: false }
20499
+ }],
19843
20500
  state: [{
19844
20501
  kind: "boolean",
19845
20502
  field: "empty",
@@ -21858,7 +22515,6 @@ var SYSTEM_CAP_VOCABULARY = {
21858
22515
  "calendar-source": system(INTERNAL),
21859
22516
  calendars: system("calendars feed schedules and conditions, not device actions"),
21860
22517
  composer: system("device composition — an authoring tool, not an action"),
21861
- "connection-test": system(INTERNAL),
21862
22518
  "core-blocks": system(INTERNAL),
21863
22519
  "custom-model-registry": system(ML),
21864
22520
  "data-store-provider": system(INTERNAL),
@@ -43556,638 +44212,224 @@ var AutomationStepTraceSchema = object({
43556
44212
  path: string().min(1),
43557
44213
  kind: string().min(1),
43558
44214
  cap: string().optional(),
43559
- method: string().optional(),
43560
- /** The vocabulary action the step performs (`cover.open`), when it names one. */
43561
- actionId: string().optional(),
43562
- deviceId: number().int().optional(),
43563
- /** What happened per device, when the step drove several (or a domain). */
43564
- devices: array(StepDeviceTraceSchema).optional(),
43565
- startedAt: number().optional(),
43566
- endedAt: number().optional(),
43567
- /**
43568
- * The parameters the step SENT, after `{{vars.x}}` substitution — what the
43569
- * device was actually asked. Bounded like trigger `vars`; a secret parameter
43570
- * is shown as {@link REDACTED_ARG}. Absent on traces written before it existed.
43571
- */
43572
- args: record(string(), TraceValueSchema).optional(),
43573
- /** `empty`: the target resolved to no device, so nothing was done — never silently `ok`. */
43574
- outcome: _enum([
43575
- "ok",
43576
- "error",
43577
- "not-run",
43578
- "empty"
43579
- ]),
43580
- message: string().optional()
43581
- });
43582
- var AutomationRunTraceSchema = object({
43583
- runId: string().min(1),
43584
- startedAt: number(),
43585
- endedAt: number(),
43586
- trigger: AutomationTriggerTraceSchema,
43587
- conditions: array(AutomationConditionTraceNodeSchema),
43588
- verdict: AutomationRunVerdictSchema.optional(),
43589
- steps: array(AutomationStepTraceSchema),
43590
- outcome: AutomationRunOutcomeSchema,
43591
- /** How many identical consecutive skips this trace stands for (>= 1). */
43592
- repeat: number().int().min(1),
43593
- /** When the latest of those repeats happened. */
43594
- lastAt: number(),
43595
- /**
43596
- * A scheduler point's own outcome (D983). `outcome` carries the closest
43597
- * automation outcome so a reader that does not know schedulers still reads
43598
- * the trace; this field says exactly what happened.
43599
- */
43600
- scheduler: SchedulerOutcomeSchema.optional()
43601
- });
43602
- /**
43603
- * What the hub's `runs` ledger holds for one owner (`automation:<blockId>` or
43604
- * `action:<actionId>`): the cooldown stamp and the trace ring.
43605
- */
43606
- var AutomationStateDocSchema = object({
43607
- version: literal(1),
43608
- lastRunStartedAt: number().nullable(),
43609
- traces: array(AutomationRunTraceSchema)
43610
- });
43611
- /**
43612
- * Actions — named, runnable things an operator (or an automation) can start,
43613
- * declared as LIST ENTRIES, never as devices.
43614
- *
43615
- * An entry is either **internal** (a short list of cap/wait steps kept in the
43616
- * hub's `actions` record kind) or declared by an addon through the
43617
- * `action-source` collection (a Home Assistant script, a scene …). The one
43618
- * surface the UI and automations talk to is the `actions` cap; it keeps no
43619
- * catalog of its own (D3) — every `list` asks the providers live.
43620
- *
43621
- * This file is the data half: the entry schema, the variables an entry may
43622
- * declare, and the pure resolution of the values a run was given. It holds no
43623
- * runtime.
43624
- */
43625
- /** What a variable's value is. `select` takes one of `options`. */
43626
- var ActionVariableTypeSchema = _enum([
43627
- "string",
43628
- "number",
43629
- "boolean",
43630
- "select"
43631
- ]);
43632
- var ACTION_VARIABLE_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
43633
- var ActionVariableValueSchema = union([
43634
- string(),
43635
- number(),
43636
- boolean()
43637
- ]);
43638
- /**
43639
- * One declared variable. Steps reference it as `{ $var: 'name' }` (the whole
43640
- * value) or `{{vars.name}}` (inside a string) in their args.
43641
- */
43642
- var ActionVariableSchema = object({
43643
- name: string().regex(ACTION_VARIABLE_NAME_RE),
43644
- label: string().min(1).max(120).optional(),
43645
- type: ActionVariableTypeSchema,
43646
- required: boolean().optional(),
43647
- default: ActionVariableValueSchema.optional(),
43648
- /** The allowed values of a `select`. */
43649
- options: array(string().min(1)).min(1).optional()
43650
- }).superRefine((v, ctx) => {
43651
- if (v.type === "select" && v.options === void 0) ctx.addIssue({
43652
- code: "custom",
43653
- message: "a select variable needs options",
43654
- path: ["options"]
43655
- });
43656
- if (v.default !== void 0 && variableValueError(v, v.default) !== null) ctx.addIssue({
43657
- code: "custom",
43658
- message: variableValueError(v, v.default) ?? "invalid default",
43659
- path: ["default"]
43660
- });
43661
- });
43662
- /** Why `value` is not a legal value for the variable, or null when it is. */
43663
- function variableValueError(variable, value) {
43664
- switch (variable.type) {
43665
- case "string": return typeof value === "string" ? null : `variable "${variable.name}" must be a string`;
43666
- case "number": return typeof value === "number" && Number.isFinite(value) ? null : `variable "${variable.name}" must be a number`;
43667
- case "boolean": return typeof value === "boolean" ? null : `variable "${variable.name}" must be true or false`;
43668
- case "select": return typeof value === "string" && (variable.options ?? []).includes(value) ? null : `variable "${variable.name}" must be one of ${(variable.options ?? []).join(", ")}`;
43669
- }
43670
- }
43671
- var ActionSourceKindSchema = _enum(["internal", "addon"]);
43672
- function isInternalActionId(actionId) {
43673
- return actionId.startsWith("internal:") && actionId.length > 9;
43674
- }
43675
- /** The addon behind a `<addonId>:<localId>` id, or null for anything else (internal included). */
43676
- function addonIdOfActionId(actionId) {
43677
- if (isInternalActionId(actionId)) return null;
43678
- const at = actionId.indexOf(":");
43679
- return at > 0 && at < actionId.length - 1 ? actionId.slice(0, at) : null;
43680
- }
43681
- var ActionStatusSchema = object({
43682
- isRunning: boolean(),
43683
- /** Ms epoch the latest run STARTED; null when it never ran. */
43684
- lastRunAt: number().nullable(),
43685
- /** The latest run's failure; null on success or when it never ran. */
43686
- lastError: string().nullable()
43687
- });
43688
- var ActionEntrySchema = object({
43689
- /** `internal:<uuid>` or `<addonId>:<localId>`. */
43690
- id: string().min(3),
43691
- name: string().min(1).max(120),
43692
- /** The addon that declared it; `core-blocks` for an internal one. */
43693
- addonId: string().min(1),
43694
- source: ActionSourceKindSchema,
43695
- /** An addon-declared entry is edited where it was declared. */
43696
- readOnly: boolean(),
43697
- /** Internal only: cap and wait steps. No action-in-action, so no cycles. */
43698
- steps: array(ActionStepSchema).min(1).max(50).optional(),
43699
- variables: array(ActionVariableSchema).max(20).optional(),
43700
- status: ActionStatusSchema
43701
- }).superRefine((entry, ctx) => {
43702
- if (entry.source === "internal") {
43703
- if (!isInternalActionId(entry.id)) ctx.addIssue({
43704
- code: "custom",
43705
- message: "an internal action id is internal:<uuid>",
43706
- path: ["id"]
43707
- });
43708
- return;
43709
- }
43710
- if (entry.steps !== void 0) ctx.addIssue({
43711
- code: "custom",
43712
- message: "only an internal action carries steps",
43713
- path: ["steps"]
43714
- });
43715
- if (!entry.readOnly) ctx.addIssue({
43716
- code: "custom",
43717
- message: "an addon action is read-only here",
43718
- path: ["readOnly"]
43719
- });
43720
- if (addonIdOfActionId(entry.id) === null) ctx.addIssue({
43721
- code: "custom",
43722
- message: "an addon action id is <addonId>:<localId>",
43723
- path: ["id"]
43724
- });
43725
- });
43726
- /** What an operator writes for an internal action. */
43727
- var ActionInputSchema = object({
43728
- name: string().min(1).max(120),
43729
- steps: array(ActionStepSchema).min(1).max(50),
43730
- variables: array(ActionVariableSchema).max(20).optional()
43731
- });
43732
- /** Who started a run. Absent = the operator pressed it. */
43733
- var ActionRunOriginSchema = object({
43734
- /** The automation block whose step started it. */
43735
- blockId: string().min(1).optional() });
43736
- /** `started` = the caller did not ask to wait. */
43737
- var ActionRunOutcomeSchema = union([AutomationRunOutcomeSchema, literal("started")]);
43738
- var ActionRunResultSchema = object({
43739
- runId: string().min(1),
43740
- outcome: ActionRunOutcomeSchema,
43741
- /** Why it did not run, or what failed. */
43742
- message: string().optional()
43743
- });
43744
- _enum([
43745
- "not-found",
43746
- "read-only",
43747
- "invalid-variables",
43748
- "invalid-steps",
43749
- "not-linked",
43750
- "busy"
43751
- ]);
43752
- object({
43753
- actionId: string(),
43754
- runId: string(),
43755
- isRunning: boolean(),
43756
- /** Set when the run ended. */
43757
- outcome: AutomationRunOutcomeSchema.optional(),
43758
- lastRunAt: number().nullable(),
43759
- lastError: string().nullable()
43760
- });
43761
- /** A bare number accepted as a base unit — the save succeeded, say so. */
43762
- var UnitWarningSchema = object({
43763
- /** Where in the saved record, e.g. `conditions.children.0` or `steps.2.args.grams`. */
43764
- path: string(),
43765
- deviceId: number().int().optional(),
43766
- field: string(),
43767
- value: number(),
43768
- assumedUnit: string(),
43769
- message: string()
43770
- });
43771
- /**
43772
- * notification-output — canonical, capability-gated notification delivery.
43773
- *
43774
- * Apprise-derived model (see
43775
- * `docs/superpowers/specs/2026-07-03-notification-output-notifier-matrix.md`):
43776
- * callers emit ONE canonical `Notification`; each provider declares a
43777
- * per-kind capability descriptor (`TargetKind`), and the pure degrade
43778
- * engine (`@camstack/types` `prepareNotification`) transcodes / degrades the
43779
- * message to what the kind supports — callers never special-case a service.
43780
- *
43781
- * DESIGN DECISIONS (locked):
43782
- * - Target CRUD lives on THIS cap (`upsertTarget` / `deleteTarget` /
43783
- * `setTargetEnabled`), each provider persisting via the `settings-store`
43784
- * cap. Rationale: the admin UI needs one uniform surface across the
43785
- * notifiers addon AND the HA addon; the addon-`globalSettingsSchema`-array
43786
- * alternative would fork the UI per addon and cannot host the
43787
- * discovery→adopt flow.
43788
- * - `listTargetKinds` / `listTargets` / `discoverTargets` return arrays →
43789
- * the generated cap-mount auto-`concatCollection`-fans them across every
43790
- * registered provider (notifiers addon + HA addon) so one catalog is
43791
- * routable. `send` / `testTarget` / CRUD route to ONE provider by the
43792
- * `addonId` the generated collection router extracts from the call input.
43793
- * - `Attachment.bytes` is `Uint8Array`. Transport-safe: superjson (the tRPC
43794
- * transformer) + UDS MsgPack both round-trip typed arrays — already used by
43795
- * `storage` / `storage-provider` / `recording` caps over the same path. No
43796
- * base64 fallback needed.
43797
- *
43798
- * TODO (deferred, closed-set change — separate decision): add
43799
- * `providerKind: 'notify'` so notification providers surface on the unified
43800
- * admin "Integrations" page.
43801
- */
43802
- /**
43803
- * Zentik-derived typed-media enum — the superset across every kind. Each
43804
- * adapter picks what it supports and the degrade engine filters the rest.
43805
- */
43806
- var AttachmentMediaTypeSchema = _enum([
43807
- "image",
43808
- "video",
43809
- "gif",
43810
- "audio",
43811
- "icon"
43812
- ]);
43813
- /**
43814
- * A single attachment. Exactly one of `url` (remote source, most adapters
43815
- * prefer this) or `bytes` (inline source; required for Pushover-style
43816
- * bytes-only kinds) MUST be present — the degrade engine expresses a
43817
- * url→bytes fetch as a `needsFetch` directive the adapter executes.
43818
- */
43819
- var AttachmentSchema = object({
43820
- mediaType: AttachmentMediaTypeSchema,
43821
- url: string().optional(),
43822
- bytes: _instanceof(Uint8Array).optional(),
43823
- mime: string().optional(),
43824
- name: string().optional()
43825
- }).refine((a) => a.url !== void 0 || a.bytes !== void 0, { message: "Attachment requires either `url` or `bytes`" });
43826
- var NotificationFormatSchema = _enum([
43827
- "text",
43828
- "markdown",
43829
- "html"
43830
- ]);
43831
- /**
43832
- * The CLOSED icon vocabulary an action button may use.
43833
- *
43834
- * A closed set, not a free string, and that is the whole point: an arbitrary
43835
- * icon name is one that ntfy renders, zentik silently drops, and nobody
43836
- * notices — the same class of gap as a zone vocabulary nothing produced
43837
- * ([D35](../../../docs/decisions/adr-0035.md)). Every adapter maps this set or
43838
- * declares `actionIcons: false` and the degrade engine strips the field.
43839
- *
43840
- * Named by INTENT, never by glyph. "check" would tie the vocabulary to one
43841
- * renderer's icon set; "acknowledge" survives an adapter that draws it
43842
- * differently.
43843
- *
43844
- * ── A TOKEN IS NOT A WIRE VALUE ─────────────────────────────────────
43845
- *
43846
- * These names are for US. **No adapter may forward one verbatim.** Each maps
43847
- * the whole set onto its own renderer's vocabulary through a
43848
- * `Record<NotificationActionIcon, string>` — a Record, never a lookup with a
43849
- * fallback, so adding a member here fails every adapter's build until someone
43850
- * decides its glyph, which is the only place that decision can be made
43851
- * honestly.
43852
- *
43853
- * This paragraph is the bug. Zentik declared `actionIcons: true` and passed
43854
- * `disarm` straight through; iOS feeds that string to
43855
- * `UNNotificationActionIcon(systemImageName:)`, `disarm` is not an SF Symbol,
43856
- * and every snooze and alarm button arrived BLANK. A pass-through is not a
43857
- * mapping, and "the field is documented" is not "the value renders".
43858
- *
43859
- * Adding a member is TRAIN-BOUND. The enum lives in the published
43860
- * `@camstack/server` closure and the cap seam validates against the HUB's copy,
43861
- * so an addon that emits a token the running hub does not know does not lose an
43862
- * icon — its whole `send` fails Zod validation and the notification never
43863
- * arrives. Never emit a new token from an addon before the train carrying it.
43864
- */
43865
- var NotificationActionIconSchema = _enum([
43866
- "acknowledge",
43867
- "dismiss",
43868
- "silence",
43869
- "snooze",
43870
- "view",
43871
- "play",
43872
- "open",
43873
- "close",
43874
- "lock",
43875
- "unlock",
43876
- "arm",
43877
- "arm-home",
43878
- "arm-away",
43879
- "arm-night",
43880
- "disarm",
43881
- "light",
43882
- "alert",
43883
- "camera"
43884
- ]);
43885
- /** A single tap-through action button. */
43886
- var NotificationActionSchema = object({
43887
- id: string(),
43888
- label: string(),
43889
- url: string().optional(),
43890
- /** Dropped by the degrade engine for a kind with `caps.actionIcons: false`. */
43891
- icon: NotificationActionIconSchema.optional(),
43892
- /**
43893
- * Renders in a warning style where the notifier supports it.
43894
- *
43895
- * A HINT, never a gate. The callback's authority is its token and nothing
43896
- * else — see `notification-center/action-token.ts` for what that does and
43897
- * does not buy.
43898
- */
43899
- destructive: boolean().optional(),
43900
- /**
43901
- * How the tap should REACH the url.
43902
- *
43903
- * `navigate` (absent, and every button authored before this field) opens it:
43904
- * the phone leaves the notification and shows whatever the callback returns.
43905
- * That is right for a button whose answer the operator wants to read.
43906
- *
43907
- * `background` fires it as a POST and stays put. It exists for the buttons
43908
- * whose whole point is not to interrupt — "silence this for 30 minutes" is
43909
- * an answer to the notification, and being thrown into a browser tab to
43910
- * confirm it costs more attention than the notification did. A backend that
43911
- * cannot do a background call renders it as an ordinary link (the adapters
43912
- * fall back rather than dropping the button), so this is a preference, never
43913
- * a requirement.
43914
- */
43915
- mode: _enum(["navigate", "background"]).optional()
43916
- });
43917
- /** A delivery parameter value: what a notifier declared it takes. */
43918
- var DeliveryParamValueSchema = union([
43919
- string(),
43920
- number(),
43921
- boolean()
43922
- ]);
43923
- /**
43924
- * One extra delivery parameter a notifier KIND declares (D938). A rule that
43925
- * addresses a target of that kind may set it; a kind that declares nothing is
43926
- * never handed one. The admin UI derives its control from this descriptor —
43927
- * no editor knows a service by name.
43928
- *
43929
- * Optional fields are `.optional()`, never `.default()` (a Zod default does not
43930
- * run on the addon cap path).
43931
- */
43932
- var DeliveryParamSchema = object({
43933
- key: string().min(1),
43934
- label: string(),
43935
- /** i18n key of the label, resolved by the declaring addon's namespace. */
43936
- labelKey: string().optional(),
43937
- type: _enum([
43938
- "enum",
43939
- "number",
43940
- "boolean",
43941
- "string"
43942
- ]),
43943
- /** `enum` only: the closed set of accepted values. */
43944
- options: array(object({
43945
- value: string(),
43946
- label: string()
43947
- })).optional(),
43948
- /** `number` only. */
43949
- min: number().optional(),
43950
- max: number().optional(),
43951
- /** What the notifier does when the rule sets nothing; shown as the placeholder. */
43952
- default: DeliveryParamValueSchema.optional()
43953
- });
43954
- /**
43955
- * The canonical notification. `body` is the only hard field (Apprise model).
43956
- * `priority` is a 5-level ORDINAL (1=lowest … 3=normal(default) … 5=urgent),
43957
- * NOT a fixed severity enum — each kind declares its own `caps.levels` and
43958
- * the adapter maps this ordinal onto its native level. `level?` is an
43959
- * optional kind-native level id (`emergency`, `silent`, …) that overrides
43960
- * `priority` for that one target.
43961
- */
43962
- var NotificationSchema = object({
43963
- body: string(),
43964
- title: string().optional(),
43965
- format: NotificationFormatSchema.default("text"),
43966
- priority: number().int().min(1).max(5).default(3),
43967
- level: string().optional(),
43968
- attachments: array(AttachmentSchema).optional(),
43969
- clickUrl: string().optional(),
43970
- actions: array(NotificationActionSchema).optional(),
43971
- sound: string().optional(),
43972
- ttl: number().optional(),
43973
- tag: string().optional(),
43974
- deviceId: number().optional(),
43975
- eventId: string().optional(),
43976
- metadata: record(string(), unknown()).optional(),
43977
- /**
43978
- * Values for the parameters the target's kind DECLARES in
43979
- * {@link TargetKindSchema} `deliveryParams`. Already validated against the
43980
- * declaration by the sender; a notifier reads only the keys it declared.
43981
- */
43982
- delivery: record(string(), DeliveryParamValueSchema).optional()
43983
- });
43984
- /** One declared native severity/priority level for a kind. */
43985
- var TargetKindLevelSchema = object({
43986
- id: string(),
43987
- label: string(),
43988
- /** Which canonical priority (1..5) this level maps to. `null` = qualitative-only. */
43989
- ordinal: number().int().min(1).max(5).nullable(),
43990
- flags: object({
43991
- critical: boolean().optional(),
43992
- silent: boolean().optional(),
43993
- noPush: boolean().optional()
43994
- }).optional(),
43995
- /** e.g. Pushover `emergency` requires `retry` / `expire`. */
43996
- requires: array(string()).optional(),
43997
- description: string().optional()
44215
+ method: string().optional(),
44216
+ /** The vocabulary action the step performs (`cover.open`), when it names one. */
44217
+ actionId: string().optional(),
44218
+ deviceId: number().int().optional(),
44219
+ /** What happened per device, when the step drove several (or a domain). */
44220
+ devices: array(StepDeviceTraceSchema).optional(),
44221
+ startedAt: number().optional(),
44222
+ endedAt: number().optional(),
44223
+ /**
44224
+ * The parameters the step SENT, after `{{vars.x}}` substitution — what the
44225
+ * device was actually asked. Bounded like trigger `vars`; a secret parameter
44226
+ * is shown as {@link REDACTED_ARG}. Absent on traces written before it existed.
44227
+ */
44228
+ args: record(string(), TraceValueSchema).optional(),
44229
+ /** `empty`: the target resolved to no device, so nothing was done — never silently `ok`. */
44230
+ outcome: _enum([
44231
+ "ok",
44232
+ "error",
44233
+ "not-run",
44234
+ "empty"
44235
+ ]),
44236
+ message: string().optional()
43998
44237
  });
43999
- /** The full capability block consulted before dispatch. */
44000
- var TargetKindCapsSchema = object({
44001
- attachments: object({
44002
- mediaTypes: array(AttachmentMediaTypeSchema),
44003
- mode: _enum([
44004
- "url",
44005
- "bytes",
44006
- "both"
44007
- ]),
44008
- max: number().int().nonnegative(),
44009
- maxBytes: number().int().positive().optional()
44010
- }),
44011
- /** Max action buttons (0 = none). */
44012
- actions: number().int().nonnegative(),
44238
+ var AutomationRunTraceSchema = object({
44239
+ runId: string().min(1),
44240
+ startedAt: number(),
44241
+ endedAt: number(),
44242
+ trigger: AutomationTriggerTraceSchema,
44243
+ conditions: array(AutomationConditionTraceNodeSchema),
44244
+ verdict: AutomationRunVerdictSchema.optional(),
44245
+ steps: array(AutomationStepTraceSchema),
44246
+ outcome: AutomationRunOutcomeSchema,
44247
+ /** How many identical consecutive skips this trace stands for (>= 1). */
44248
+ repeat: number().int().min(1),
44249
+ /** When the latest of those repeats happened. */
44250
+ lastAt: number(),
44013
44251
  /**
44014
- * Whether this kind renders a per-action ICON.
44015
- *
44016
- * `.optional()`, deliberately NOT `.default(false)`: a Zod default does not
44017
- * run on the addon cap path — three production failures in one day taught
44018
- * this repo that once. Absent is read as false by the degrade engine, which
44019
- * is the safe direction: an icon that is not rendered costs nothing, an icon
44020
- * assumed and dropped costs the operator's trust in the field.
44252
+ * A scheduler point's own outcome (D983). `outcome` carries the closest
44253
+ * automation outcome so a reader that does not know schedulers still reads
44254
+ * the trace; this field says exactly what happened.
44021
44255
  */
44022
- actionIcons: boolean().optional(),
44023
- levels: array(TargetKindLevelSchema),
44024
- format: array(NotificationFormatSchema),
44025
- clickUrl: boolean(),
44026
- sound: boolean(),
44027
- ttl: boolean(),
44028
- bodyMaxLen: number().int().positive()
44256
+ scheduler: SchedulerOutcomeSchema.optional()
44029
44257
  });
44030
44258
  /**
44031
- * `configSchema` is a `ConfigUISchema` tree passed through to the admin
44032
- * FormBuilder. Stored as `z.unknown()` at the cap seam (mirrors
44033
- * `device-provider.getChildCreationSchema` `CreationSchemaOutputSchema`) —
44034
- * the union is large and not meant for runtime validation here; the exported
44035
- * `TargetKind` type re-tightens `configSchema` to `ConfigUISchema`.
44259
+ * What the hub's `runs` ledger holds for one owner (`automation:<blockId>` or
44260
+ * `action:<actionId>`): the cooldown stamp and the trace ring.
44036
44261
  */
44037
- var ConfigSchemaPassthrough$4 = unknown();
44038
- var TargetKindSchema = object({
44039
- kind: string(),
44040
- label: string(),
44041
- icon: string(),
44042
- /** Stamped by each provider so the concat-fanned catalog stays routable. */
44043
- addonId: string(),
44044
- /**
44045
- * URL of the kind's bundled BRAND icon, served by the providing addon over
44046
- * its own `addon-routes` surface (`/addon/<addonId>/icons/<kind>`). Absent
44047
- * when the addon bundles no icon for that kind — the client then falls back
44048
- * to a neutral glyph rather than rendering the raw `icon` NAME as text.
44049
- *
44050
- * Root-relative on purpose: it resolves against whatever origin serves a web
44051
- * client, and a native client joins it onto its own hub base.
44052
- *
44053
- * DECLARED here deliberately. It used to travel as an undeclared passthrough
44054
- * field that survived only because the runtime cap-router forwards provider
44055
- * output verbatim — so every consumer had to re-declare it by hand to stop
44056
- * its own Zod parse from stripping it, and the whole arrangement would have
44057
- * broken silently the moment output validation was tightened anywhere.
44058
- */
44059
- iconUrl: string().optional(),
44060
- /**
44061
- * Media type of {@link iconUrl} (`image/svg+xml`, `image/png`, …).
44062
- *
44063
- * The server knows this and therefore says it, because the client cannot
44064
- * safely guess: a React-Native client renders SVG and raster through two
44065
- * DIFFERENT components (`react-native-svg` vs `expo-image` — expo-image does
44066
- * not decode SVG on iOS/Android), so without this it silently fell back to a
44067
- * placeholder glyph for every vector icon while the web build looked fine.
44068
- *
44069
- * Absent when {@link iconUrl} is absent, or for a legacy provider that has
44070
- * not been updated — a client that cannot determine the type should prefer
44071
- * its raster path, which is the safe default for an unknown image.
44072
- */
44073
- iconMediaType: string().optional(),
44074
- configSchema: ConfigSchemaPassthrough$4,
44075
- /**
44076
- * The config keys that decide WHERE this kind's secrets are sent (server,
44077
- * base URL, instance, chat, recipient). A save that changes any of them
44078
- * while leaving a secret redacted is refused by the provider (D634), so an
44079
- * editor uses this to ask for the secret on exactly those edits instead of
44080
- * on every edit.
44081
- *
44082
- * Optional: absent from a provider that holds no secret (the Home Assistant
44083
- * kinds) and from a provider older than this field — an editor that finds
44084
- * it absent must assume ANY edit may need the secret.
44085
- */
44086
- destinationKeys: array(string()).optional(),
44087
- supportsDiscovery: boolean(),
44088
- /**
44089
- * Extra delivery parameters a rule may set for a target of this kind (D938).
44090
- * Absent = none; the rule editor then offers nothing.
44091
- */
44092
- deliveryParams: array(DeliveryParamSchema).optional(),
44093
- caps: TargetKindCapsSchema
44262
+ var AutomationStateDocSchema = object({
44263
+ version: literal(1),
44264
+ lastRunStartedAt: number().nullable(),
44265
+ traces: array(AutomationRunTraceSchema)
44094
44266
  });
44095
44267
  /**
44096
- * A persisted target. `config` holds secrets; providers REDACT secret fields
44097
- * (return a presence marker only) when serving `listTargets` — never
44098
- * round-trip a stored secret to the UI.
44268
+ * Actions — named, runnable things an operator (or an automation) can start,
44269
+ * declared as LIST ENTRIES, never as devices.
44270
+ *
44271
+ * An entry is either **internal** (a short list of cap/wait steps kept in the
44272
+ * hub's `actions` record kind) or declared by an addon through the
44273
+ * `action-source` collection (a Home Assistant script, a scene …). The one
44274
+ * surface the UI and automations talk to is the `actions` cap; it keeps no
44275
+ * catalog of its own (D3) — every `list` asks the providers live.
44276
+ *
44277
+ * This file is the data half: the entry schema, the variables an entry may
44278
+ * declare, and the pure resolution of the values a run was given. It holds no
44279
+ * runtime.
44099
44280
  */
44100
- var TargetSchema = object({
44101
- id: string(),
44102
- name: string(),
44103
- kind: string(),
44104
- addonId: string(),
44105
- enabled: boolean(),
44106
- config: record(string(), unknown())
44281
+ /** What a variable's value is. `select` takes one of `options`. */
44282
+ var ActionVariableTypeSchema = _enum([
44283
+ "string",
44284
+ "number",
44285
+ "boolean",
44286
+ "select"
44287
+ ]);
44288
+ var ACTION_VARIABLE_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
44289
+ var ActionVariableValueSchema = union([
44290
+ string(),
44291
+ number(),
44292
+ boolean()
44293
+ ]);
44294
+ /**
44295
+ * One declared variable. Steps reference it as `{ $var: 'name' }` (the whole
44296
+ * value) or `{{vars.name}}` (inside a string) in their args.
44297
+ */
44298
+ var ActionVariableSchema = object({
44299
+ name: string().regex(ACTION_VARIABLE_NAME_RE),
44300
+ label: string().min(1).max(120).optional(),
44301
+ type: ActionVariableTypeSchema,
44302
+ required: boolean().optional(),
44303
+ default: ActionVariableValueSchema.optional(),
44304
+ /** The allowed values of a `select`. */
44305
+ options: array(string().min(1)).min(1).optional()
44306
+ }).superRefine((v, ctx) => {
44307
+ if (v.type === "select" && v.options === void 0) ctx.addIssue({
44308
+ code: "custom",
44309
+ message: "a select variable needs options",
44310
+ path: ["options"]
44311
+ });
44312
+ if (v.default !== void 0 && variableValueError(v, v.default) !== null) ctx.addIssue({
44313
+ code: "custom",
44314
+ message: variableValueError(v, v.default) ?? "invalid default",
44315
+ path: ["default"]
44316
+ });
44107
44317
  });
44108
- /** A discovery-surfaced candidate (config is partial + non-secret). */
44109
- var DiscoveredTargetSchema = object({
44110
- kind: string(),
44111
- suggestedName: string(),
44112
- config: record(string(), unknown())
44318
+ /** Why `value` is not a legal value for the variable, or null when it is. */
44319
+ function variableValueError(variable, value) {
44320
+ switch (variable.type) {
44321
+ case "string": return typeof value === "string" ? null : `variable "${variable.name}" must be a string`;
44322
+ case "number": return typeof value === "number" && Number.isFinite(value) ? null : `variable "${variable.name}" must be a number`;
44323
+ case "boolean": return typeof value === "boolean" ? null : `variable "${variable.name}" must be true or false`;
44324
+ case "select": return typeof value === "string" && (variable.options ?? []).includes(value) ? null : `variable "${variable.name}" must be one of ${(variable.options ?? []).join(", ")}`;
44325
+ }
44326
+ }
44327
+ var ActionSourceKindSchema = _enum(["internal", "addon"]);
44328
+ function isInternalActionId(actionId) {
44329
+ return actionId.startsWith("internal:") && actionId.length > 9;
44330
+ }
44331
+ /** The addon behind a `<addonId>:<localId>` id, or null for anything else (internal included). */
44332
+ function addonIdOfActionId(actionId) {
44333
+ if (isInternalActionId(actionId)) return null;
44334
+ const at = actionId.indexOf(":");
44335
+ return at > 0 && at < actionId.length - 1 ? actionId.slice(0, at) : null;
44336
+ }
44337
+ var ActionStatusSchema = object({
44338
+ isRunning: boolean(),
44339
+ /** Ms epoch the latest run STARTED; null when it never ran. */
44340
+ lastRunAt: number().nullable(),
44341
+ /** The latest run's failure; null on success or when it never ran. */
44342
+ lastError: string().nullable()
44113
44343
  });
44114
- /** The degrade engine's report — what was resolved / dropped / degraded. */
44115
- var RenderedAsSchema = object({
44116
- level: string(),
44117
- format: NotificationFormatSchema,
44118
- attachmentsSent: number().int().nonnegative(),
44119
- actionsSent: number().int().nonnegative(),
44120
- truncated: boolean(),
44121
- dropped: array(string())
44344
+ var ActionEntrySchema = object({
44345
+ /** `internal:<uuid>` or `<addonId>:<localId>`. */
44346
+ id: string().min(3),
44347
+ name: string().min(1).max(120),
44348
+ /** The addon that declared it; `core-blocks` for an internal one. */
44349
+ addonId: string().min(1),
44350
+ source: ActionSourceKindSchema,
44351
+ /** An addon-declared entry is edited where it was declared. */
44352
+ readOnly: boolean(),
44353
+ /** Internal only: cap and wait steps. No action-in-action, so no cycles. */
44354
+ steps: array(ActionStepSchema).min(1).max(50).optional(),
44355
+ variables: array(ActionVariableSchema).max(20).optional(),
44356
+ status: ActionStatusSchema
44357
+ }).superRefine((entry, ctx) => {
44358
+ if (entry.source === "internal") {
44359
+ if (!isInternalActionId(entry.id)) ctx.addIssue({
44360
+ code: "custom",
44361
+ message: "an internal action id is internal:<uuid>",
44362
+ path: ["id"]
44363
+ });
44364
+ return;
44365
+ }
44366
+ if (entry.steps !== void 0) ctx.addIssue({
44367
+ code: "custom",
44368
+ message: "only an internal action carries steps",
44369
+ path: ["steps"]
44370
+ });
44371
+ if (!entry.readOnly) ctx.addIssue({
44372
+ code: "custom",
44373
+ message: "an addon action is read-only here",
44374
+ path: ["readOnly"]
44375
+ });
44376
+ if (addonIdOfActionId(entry.id) === null) ctx.addIssue({
44377
+ code: "custom",
44378
+ message: "an addon action id is <addonId>:<localId>",
44379
+ path: ["id"]
44380
+ });
44122
44381
  });
44123
- var SendResultSchema = object({
44124
- success: boolean(),
44125
- error: string().optional(),
44126
- renderedAs: RenderedAsSchema.optional()
44382
+ /** What an operator writes for an internal action. */
44383
+ var ActionInputSchema = object({
44384
+ name: string().min(1).max(120),
44385
+ steps: array(ActionStepSchema).min(1).max(50),
44386
+ variables: array(ActionVariableSchema).max(20).optional()
44127
44387
  });
44128
- /** Same shape as SendResult — kept as a distinct name for the test panel. */
44129
- var TestResultSchema = SendResultSchema;
44388
+ /** Who started a run. Absent = the operator pressed it. */
44389
+ var ActionRunOriginSchema = object({
44390
+ /** The automation block whose step started it. */
44391
+ blockId: string().min(1).optional() });
44130
44392
  /**
44131
- * Pre-save credential probe against a partial (unsaved) target config.
44132
- * `resolvedUrl` never includes secrets (token stripped from path).
44393
+ * `started` = the caller did not ask to wait. `timed-out` = the run reached the
44394
+ * ceiling (`ACTION_RUN_MAX_MS`) and was stopped; it is never a `ran`.
44133
44395
  */
44134
- var ProbeTargetConfigResultSchema = object({
44135
- ok: boolean(),
44136
- resolvedUrl: string(),
44137
- httpStatus: number().int().optional(),
44138
- stateInstance: string().optional(),
44139
- error: string().optional()
44396
+ var ActionRunOutcomeSchema = union([
44397
+ AutomationRunOutcomeSchema,
44398
+ literal("started"),
44399
+ literal("timed-out")
44400
+ ]);
44401
+ var ActionRunResultSchema = object({
44402
+ runId: string().min(1),
44403
+ outcome: ActionRunOutcomeSchema,
44404
+ /** Why it did not run, or what failed. */
44405
+ message: string().optional()
44140
44406
  });
44141
- method(object({}), array(TargetKindSchema)), method(object({}), array(TargetSchema), { auth: "admin" }), method(object({ targetId: string() }), TargetSchema, { auth: "admin" }), method(object({
44142
- kind: string(),
44143
- config: record(string(), unknown()).optional(),
44144
- /**
44145
- * When editing / duplicating, the blank password field never round-trips
44146
- * the stored token. Pass the source target id so the provider can restore
44147
- * secrets server-side before dialling (same merge as upsert).
44148
- */
44149
- targetId: string().optional()
44150
- }), array(DiscoveredTargetSchema), { auth: "admin" }), method(object({
44151
- kind: string(),
44152
- config: record(string(), unknown()),
44153
- /** See `discoverTargets.targetId` — restore stored secrets for a blank password. */
44154
- targetId: string().optional()
44155
- }), ProbeTargetConfigResultSchema, {
44156
- kind: "mutation",
44157
- auth: "admin"
44158
- }), method(object({
44159
- targetId: string(),
44160
- notification: NotificationSchema
44161
- }), SendResultSchema, {
44162
- kind: "mutation",
44163
- auth: "admin"
44164
- }), method(object({
44165
- targetId: string(),
44166
- sample: NotificationSchema.optional()
44167
- }), TestResultSchema, {
44168
- kind: "mutation",
44169
- auth: "admin"
44170
- }), method(object({
44171
- target: TargetSchema,
44172
- /**
44173
- * Duplicate flow: create a NEW target id while copying secrets from an
44174
- * existing row. The UI never holds the stored token; blank / redacted
44175
- * password fields are restored from this source (D634 still applies if
44176
- * destinations diverge without a re-typed secret).
44177
- */
44178
- cloneSecretsFrom: string().optional()
44179
- }), TargetSchema, {
44180
- kind: "mutation",
44181
- auth: "admin"
44182
- }), method(object({ targetId: string() }), _void(), {
44183
- kind: "mutation",
44184
- auth: "admin"
44185
- }), method(object({
44186
- targetId: string(),
44187
- enabled: boolean()
44188
- }), _void(), {
44189
- kind: "mutation",
44190
- auth: "admin"
44407
+ _enum([
44408
+ "not-found",
44409
+ "read-only",
44410
+ "invalid-variables",
44411
+ "invalid-steps",
44412
+ "not-linked",
44413
+ "busy"
44414
+ ]);
44415
+ object({
44416
+ actionId: string(),
44417
+ runId: string(),
44418
+ isRunning: boolean(),
44419
+ /** Set when the run ended. */
44420
+ outcome: AutomationRunOutcomeSchema.optional(),
44421
+ lastRunAt: number().nullable(),
44422
+ lastError: string().nullable()
44423
+ });
44424
+ /** A bare number accepted as a base unit — the save succeeded, say so. */
44425
+ var UnitWarningSchema = object({
44426
+ /** Where in the saved record, e.g. `conditions.children.0` or `steps.2.args.grams`. */
44427
+ path: string(),
44428
+ deviceId: number().int().optional(),
44429
+ field: string(),
44430
+ value: number(),
44431
+ assumedUnit: string(),
44432
+ message: string()
44191
44433
  });
44192
44434
  _enum([
44193
44435
  "automation",
@@ -44256,6 +44498,8 @@ method(object({}), array(ActionEntrySchema), { auth: "admin" }), method(object({
44256
44498
  kind: "mutation",
44257
44499
  auth: "admin"
44258
44500
  });
44501
+ /** `timeoutMs` of `actions.run`: a waited call outlives any legal run. */
44502
+ var ACTION_RUN_TIMEOUT_MS = 363e4;
44259
44503
  /**
44260
44504
  * actions — the ONE surface for runnable actions, for the UI and for
44261
44505
  * automations. Provided by the core-blocks builtin on the hub.
@@ -44274,6 +44518,12 @@ method(object({}), array(ActionEntrySchema), { auth: "admin" }), method(object({
44274
44518
  * An admin, and an in-process caller (an automation block), may run any action.
44275
44519
  * Every refusal is typed (`[not-linked] …`) and logged.
44276
44520
  *
44521
+ * **A run lasts at most `ACTION_RUN_MAX_MS` (60 min).** The provider stops a
44522
+ * run that reaches it and answers `timed-out` (never `ran`); an action whose
44523
+ * `wait` steps alone add up to more is refused at create/update
44524
+ * (`[invalid-steps]`). `run` declares a `timeoutMs` above that ceiling, so a
44525
+ * waited call (an automation step) is never cut by the 60 s transport default.
44526
+ *
44277
44527
  * A second `run` of an action that is already running is REFUSED — traced and
44278
44528
  * logged — never queued.
44279
44529
  */
@@ -44300,7 +44550,8 @@ method(object({}), array(ActionEntrySchema), { auth: "admin" }), method(object({
44300
44550
  role: "viewer",
44301
44551
  auth: "protected",
44302
44552
  kind: "mutation",
44303
- caller: "required"
44553
+ caller: "required",
44554
+ timeoutMs: ACTION_RUN_TIMEOUT_MS
44304
44555
  }), method(ActionIdInput, _void(), {
44305
44556
  kind: "mutation",
44306
44557
  auth: "admin"
@@ -48057,37 +48308,6 @@ method(object({
48057
48308
  kind: "mutation",
48058
48309
  auth: "admin"
48059
48310
  }), method(object({ blockIds: array(string()) }), object({ states: array(CompositionBlockStateSchema) }), { auth: "admin" });
48060
- var ConnectionTestOutcomeSchema = discriminatedUnion("outcome", [
48061
- object({
48062
- outcome: literal("validated"),
48063
- /** Round-trip of the sign-in, when the provider measured it. */
48064
- latencyMs: number().nonnegative().optional(),
48065
- /** Optional human detail worth showing next to the tick
48066
- * ("3 devices visible on this account"). */
48067
- detail: string().optional()
48068
- }).strict(),
48069
- object({
48070
- outcome: literal("rejected"),
48071
- error: string()
48072
- }).strict(),
48073
- object({
48074
- outcome: literal("inconclusive"),
48075
- error: string()
48076
- }).strict()
48077
- ]);
48078
- var ConnectionTestInputSchema = object({
48079
- /** Candidate integration settings, exactly as the create form collected them. */
48080
- settings: record(string(), unknown()) });
48081
- /**
48082
- * What the provider's test actually DOES, so the UI can say it in words before
48083
- * the operator presses the button ("Signs in to the Dreo cloud"). Purely
48084
- * descriptive — it never changes routing.
48085
- */
48086
- var ConnectionTestDescriptorSchema = object({ label: string() });
48087
- method(ConnectionTestInputSchema, ConnectionTestOutcomeSchema, {
48088
- kind: "mutation",
48089
- auth: "admin"
48090
- }), method(_void(), ConnectionTestDescriptorSchema, { auth: "admin" });
48091
48311
  object({
48092
48312
  /** True when the upstream system considers the entity connected. */
48093
48313
  connected: boolean(),
@@ -48345,6 +48565,9 @@ var MediaPlayerStatusSchema = object({
48345
48565
  /** Repeat mode. Null when no repeat surface.
48346
48566
  * Pair with `DeviceFeature.MediaPlayerRepeat`. */
48347
48567
  repeat: MediaPlayerRepeatSchema.nullable(),
48568
+ /** Ms epoch when `position` was read from the device. Null when the driver
48569
+ * does not say; a UI that advances the position while playing counts from it. */
48570
+ positionUpdatedAt: number().nullable().default(null),
48348
48571
  /** Ms epoch when the slice was last updated. */
48349
48572
  lastChangedAt: number()
48350
48573
  });
@@ -48924,7 +49147,9 @@ var ThresholdTransformDraftSchema = object({
48924
49147
  comparison: _enum(["gte", "lte"]),
48925
49148
  threshold: number(),
48926
49149
  startDwellMs: number().nonnegative(),
48927
- stopDwellMs: number().nonnegative()
49150
+ stopDwellMs: number().nonnegative(),
49151
+ /** Samples a start needs; absent = the compiler's default for the source (2 for running power, else 1). */
49152
+ minSamples: number().int().min(1).optional()
48928
49153
  });
48929
49154
  var CustomizeTransformDraftSchema = discriminatedUnion("kind", [
48930
49155
  IdentityTransformDraftSchema,
@@ -53877,6 +54102,7 @@ var IntegrationWithStateSchema = object({
53877
54102
  id: string(),
53878
54103
  addonId: string(),
53879
54104
  name: string(),
54105
+ /** A projection of the instance body's switch (`setInstanceEnabled` is the only writer). */
53880
54106
  enabled: boolean(),
53881
54107
  info: record(string(), unknown()).readonly(),
53882
54108
  /** The discovery candidate this integration was set up from (D984). */
@@ -53889,6 +54115,7 @@ var IntegrationLiteSchema = object({
53889
54115
  id: string(),
53890
54116
  addonId: string(),
53891
54117
  name: string(),
54118
+ /** A projection of the instance body's switch (`setInstanceEnabled` is the only writer). */
53892
54119
  enabled: boolean(),
53893
54120
  info: record(string(), unknown()).readonly(),
53894
54121
  /** The discovery candidate this integration was set up from (D984). */
@@ -53934,10 +54161,9 @@ var AvailableIntegrationTypeSchema = object({
53934
54161
  * locations" checkbox. Provider-declared in the addon manifest. */
53935
54162
  supportsLocationImport: boolean(),
53936
54163
  /**
53937
- * True when this integration DECLARES a pre-creation test (the
53938
- * `connection-test` cap, or a broker whose settings it stores). Drives the
53939
- * Test button: an integration that cannot be tested must say so up front
53940
- * rather than offering a button that always answers the same nonsense.
54164
+ * True when this integration's instances declare a Test (`integration-instances.describe().canTest`,
54165
+ * D1016). An integration that cannot be tested must say so up front rather than offering a
54166
+ * button that always answers the same nonsense.
53941
54167
  */
53942
54168
  canTest: boolean(),
53943
54169
  existingInstances: array(object({
@@ -53988,15 +54214,21 @@ var TestConnectionResultSchema = object({
53988
54214
  var CreateIntegrationInputSchema = object({
53989
54215
  addonId: string(),
53990
54216
  name: string(),
53991
- enabled: boolean().optional(),
53992
54217
  info: record(string(), unknown()).optional(),
53993
54218
  /** `stableId` of the discovery candidate the form was seeded from (D984). */
53994
54219
  originStableId: string().optional(),
53995
- settings: record(string(), unknown()).optional()
54220
+ settings: record(string(), unknown()).optional(),
54221
+ /** The instance kind being created, for a provider with several; omitted = its only testable kind. */
54222
+ kind: string().min(1).optional()
53996
54223
  });
53997
54224
  var UpdateIntegrationInputSchema = object({
53998
54225
  id: string(),
53999
54226
  name: string().optional(),
54227
+ /**
54228
+ * Accepted for a FIXED builtin only (`info.fixed`: alarm panel, camera grid, core blocks,
54229
+ * terminal), which keeps no instance record: the registry flag is its one store. Any other
54230
+ * integration is switched through `integration-instances.setInstanceEnabled`.
54231
+ */
54000
54232
  enabled: boolean().optional(),
54001
54233
  info: record(string(), unknown()).optional()
54002
54234
  });
@@ -54013,13 +54245,7 @@ method(_void(), array(IntegrationWithStateSchema)), method(object({ id: string()
54013
54245
  }), method(object({ id: string() }), DeleteIntegrationResultSchema, {
54014
54246
  kind: "mutation",
54015
54247
  auth: "admin"
54016
- }), method(_void(), array(AvailableIntegrationTypeSchema), { auth: "admin" }), method(object({
54017
- addonId: string(),
54018
- settings: record(string(), unknown())
54019
- }), TestConnectionResultSchema, {
54020
- kind: "mutation",
54021
- auth: "admin"
54022
- });
54248
+ }), method(_void(), array(AvailableIntegrationTypeSchema), { auth: "admin" });
54023
54249
  /**
54024
54250
  * `integration-instances` - the connection of an addon that holds ONE or SEVERAL
54025
54251
  * (an account, a relay, a destination) as typed records (D985, D986). The addon's
@@ -54044,7 +54270,7 @@ var IntegrationInstanceIdSchema = string().min(1);
54044
54270
  var IntegrationInstanceModeSchema = _enum(["single", "multiple"]);
54045
54271
  /**
54046
54272
  * What the addon's instances ARE for the Integrations page (planning#416). `devices`: each
54047
- * instance is an integration that brings devices (the registry owns its on/off switch);
54273
+ * instance is an integration that brings devices (its record body owns the on/off switch);
54048
54274
  * `services`: a connection configured from the addon's own function page, never listed on
54049
54275
  * Integrations.
54050
54276
  * It is the same vocabulary as the manifest's `integrationRole`, which stays as an override.
@@ -54087,18 +54313,38 @@ var IntegrationInstanceKindSchema = object({
54087
54313
  /** Relative hub path to disconnect that account. */
54088
54314
  disconnectPath: string().min(1).optional()
54089
54315
  });
54316
+ /**
54317
+ * How devices of an instance are found. `none`: the operator adds them by hand; `lan`: the addon
54318
+ * scans the network before any instance exists (the wizard offers the candidates); `account`: the
54319
+ * devices appear after the instance signs in. `scopedToInstance`: a discovery run belongs to ONE
54320
+ * instance and its candidates are claimed by it.
54321
+ */
54322
+ var IntegrationInstanceDiscoverySchema = object({
54323
+ mode: _enum([
54324
+ "none",
54325
+ "lan",
54326
+ "account"
54327
+ ]),
54328
+ scopedToInstance: boolean()
54329
+ });
54330
+ /**
54331
+ * One link a kind of this provider declares (D1013 rule 5): the body `field` of an instance of
54332
+ * `kind` holds the id of an instance of the function cap `to.cap` (of kind `to.kind`, when set).
54333
+ * The hub indexes these so the target's delete is refused while a link names it.
54334
+ */
54335
+ var IntegrationInstanceLinkSchema = object({
54336
+ kind: string().min(1),
54337
+ field: string().min(1),
54338
+ to: object({
54339
+ cap: string().min(1),
54340
+ kind: string().min(1).optional()
54341
+ })
54342
+ });
54090
54343
  var IntegrationInstanceDescriptionSchema = object({
54091
54344
  /** What the instances are for the Integrations page; see {@link IntegrationInstanceRoleSchema}. */
54092
54345
  role: IntegrationInstanceRoleSchema,
54093
54346
  /** How the devices of an instance are found; absent means `{ mode: 'none' }`. */
54094
- discovery: object({
54095
- mode: _enum([
54096
- "none",
54097
- "lan",
54098
- "account"
54099
- ]),
54100
- scopedToInstance: boolean()
54101
- }).optional(),
54347
+ discovery: IntegrationInstanceDiscoverySchema.optional(),
54102
54348
  /** `single`: at most one instance can exist (Loki). `multiple`: an account each. */
54103
54349
  instanceMode: IntegrationInstanceModeSchema,
54104
54350
  /** What the instance is, for the UI (`destination`, `relay`, `account`). */
@@ -54119,7 +54365,9 @@ var IntegrationInstanceDescriptionSchema = object({
54119
54365
  * `createInstance` without an `id` works: the provider mints it. Absent means the caller must
54120
54366
  * send an id (the UI then mints an opaque one).
54121
54367
  */
54122
- mintsId: boolean().optional()
54368
+ mintsId: boolean().optional(),
54369
+ /** The links to other instances the provider's kinds declare; absent means none. */
54370
+ links: array(IntegrationInstanceLinkSchema).optional()
54123
54371
  });
54124
54372
  var IntegrationInstanceStatusSchema = object({
54125
54373
  state: _enum([
@@ -54139,8 +54387,8 @@ var IntegrationInstanceSchema = object({
54139
54387
  configured: boolean(),
54140
54388
  /**
54141
54389
  * The instance's own on/off switch (D996), derived from the record body (`enabled !== false`,
54142
- * so a row written before the field existed is on). Absent when the `integrations` registry
54143
- * owns the switch (`describe().role` is `devices`): read it from the registry row.
54390
+ * so a row written before the field existed is on). The same for every role, `devices` included:
54391
+ * the body is the one store, `setInstanceEnabled` the one writer (epic #440, step 3).
54144
54392
  */
54145
54393
  enabled: boolean().optional(),
54146
54394
  /** The kind of this instance (one of `describe().kinds[].id`), when the provider has kinds. */
@@ -54190,7 +54438,8 @@ var integrationInstancesCapability = {
54190
54438
  auth: "admin"
54191
54439
  }),
54192
54440
  /**
54193
- * Switch ONE instance on or off. A row control, not a form field: `updateInstance.values` is the
54441
+ * Switch ONE instance on or off, for every role; a missing record is created from the addon's
54442
+ * initial body. A row control, not a form field: `updateInstance.values` is the
54194
54443
  * form patch (D62, D996). An off instance keeps its record and secrets and does no work.
54195
54444
  */
54196
54445
  setInstanceEnabled: method(object({
@@ -57001,6 +57250,8 @@ var MigrationIntegrationSchema = object({
57001
57250
  addonId: string(),
57002
57251
  name: string(),
57003
57252
  info: Rows,
57253
+ /** The registry's stored switch: read by the one-switch migration, nothing else. */
57254
+ enabled: boolean().optional(),
57004
57255
  originStableId: string().optional()
57005
57256
  });
57006
57257
  var MigrationDeviceSchema = object({
@@ -62237,13 +62488,6 @@ var AddBrokerInputSchema = object({
62237
62488
  });
62238
62489
  var AddBrokerResultSchema = object({ id: string() });
62239
62490
  var IdInputSchema = object({ id: string() });
62240
- var TestResultSchema$1 = discriminatedUnion("ok", [object({
62241
- ok: literal(true),
62242
- latencyMs: number()
62243
- }), object({
62244
- ok: literal(false),
62245
- error: string()
62246
- })]);
62247
62491
  var StartEmbeddedInputSchema = object({
62248
62492
  port: number().int().min(1).max(65535).default(1883),
62249
62493
  /** Allow anonymous connect (no username/password). Default: false. */
@@ -62280,10 +62524,6 @@ var mqttBrokerCapability = {
62280
62524
  kind: "mutation",
62281
62525
  auth: "admin"
62282
62526
  }),
62283
- testConnection: method(IdInputSchema, TestResultSchema$1, {
62284
- kind: "mutation",
62285
- auth: "admin"
62286
- }),
62287
62527
  startEmbeddedBroker: method(StartEmbeddedInputSchema, StartEmbeddedResultSchema, {
62288
62528
  kind: "mutation",
62289
62529
  auth: "admin"
@@ -66538,14 +66778,6 @@ object({
66538
66778
  empty: boolean().nullable(),
66539
66779
  /** True while the pump is running. Null while unknown. */
66540
66780
  pumpRunning: boolean().nullable(),
66541
- /** Water drunk in the last drink, in litres. */
66542
- lastDrink: number().min(0).nullable().meta(readingMeta("volume")),
66543
- /** Water drunk in the current hour, in litres. */
66544
- currentHourDrink: number().min(0).nullable().meta(readingMeta("volume")),
66545
- /** Water drunk over the last 24 hours (rolling), in litres. */
66546
- last24hDrink: number().min(0).nullable().meta(readingMeta("volume")),
66547
- /** Water drunk since local midnight, in litres. Null when the fountain has no such sensor. */
66548
- todayDrink: number().min(0).nullable().meta(readingMeta("volume")),
66549
66781
  /** Decoded fault message. Null means healthy; a non-null string is an active fault. */
66550
66782
  error: string().nullable(),
66551
66783
  /** Ms epoch when the slice was last refreshed. */
@@ -66558,9 +66790,6 @@ DeviceType.PetFountain, method(object({
66558
66790
  }), _void(), {
66559
66791
  kind: "mutation",
66560
66792
  auth: "protected"
66561
- }), method(object({ deviceId: DeviceIdSchema$1 }), _void(), {
66562
- kind: "mutation",
66563
- auth: "protected"
66564
66793
  });
66565
66794
  /**
66566
66795
  * The wire shapes of the Auto tune plan and apply (D745), used by the
@@ -73910,7 +74139,7 @@ var TrainingProviderTypeSchema = object({
73910
74139
  label: string(),
73911
74140
  /** Path under the addon package (e.g. `assets/training-modal/icon.svg`). */
73912
74141
  iconAsset: string(),
73913
- /** Owning `training-provider` addon — collection selector for createEntry. */
74142
+ /** Owning `training-provider` addon. */
73914
74143
  addonId: string(),
73915
74144
  /**
73916
74145
  * Fields for one entry of this type (credentials + defaults). Absent on a
@@ -73955,36 +74184,6 @@ var TrainingProviderDescriptorSchema = object({
73955
74184
  */
73956
74185
  formValues: record(string(), unknown()).optional()
73957
74186
  });
73958
- /**
73959
- * Patch one entry's name, credentials and defaults. Pin with owning `{ addonId }`.
73960
- * An omitted or empty `tokenSecret` means KEEP the stored secret (D787).
73961
- * `{ $secretClear: true }` clears it.
73962
- */
73963
- var TrainingProviderUpdateEntryInputSchema = object({
73964
- entryId: string().min(1),
73965
- name: string().min(1),
73966
- tokenId: string().optional(),
73967
- tokenSecret: union([string(), object({ $secretClear: literal(true) })]).optional(),
73968
- environment: string().optional(),
73969
- gpuType: string().optional(),
73970
- region: string().optional(),
73971
- costCapUsd: number().nonnegative().optional(),
73972
- maxRuntimeSec: number().int().positive().optional(),
73973
- failedDatasetGraceHours: number().nonnegative().optional()
73974
- });
73975
- var TrainingCredentialCheckSchema = object({
73976
- ok: boolean(),
73977
- /** Workspace / account name, when the provider says. */
73978
- account: string().optional(),
73979
- reason: _enum([
73980
- "missing",
73981
- "invalid",
73982
- "forbidden",
73983
- "network",
73984
- "quota"
73985
- ]).optional(),
73986
- detail: string().optional()
73987
- });
73988
74187
  var ProviderJobStateSchema = _enum([
73989
74188
  "pending",
73990
74189
  "starting",
@@ -74032,22 +74231,6 @@ var TrainingLogLineSchema = object({
74032
74231
  text: string()
74033
74232
  });
74034
74233
  method(object({}), array(TrainingProviderDescriptorSchema).readonly(), { auth: "admin" }), method(object({}), array(TrainingProviderTypeSchema).readonly(), { auth: "admin" }), method(object({}), array(TrainingProviderEntrySchema).readonly(), { auth: "admin" }), method(object({
74035
- typeId: string().min(1),
74036
- name: string().min(1)
74037
- }), object({ entryId: string() }), {
74038
- kind: "mutation",
74039
- auth: "admin"
74040
- }), method(object({ entryId: string().min(1) }), object({ ok: literal(true) }), {
74041
- kind: "mutation",
74042
- auth: "admin"
74043
- }), method(TrainingProviderUpdateEntryInputSchema, object({ ok: literal(true) }), {
74044
- kind: "mutation",
74045
- auth: "admin"
74046
- }), method(object({ entryId: string().min(1) }), TrainingCredentialCheckSchema, {
74047
- kind: "mutation",
74048
- auth: "admin",
74049
- timeoutMs: 3e4
74050
- }), method(object({
74051
74234
  entryId: string().min(1),
74052
74235
  gpuType: string(),
74053
74236
  region: string(),
@@ -77433,20 +77616,6 @@ Object.freeze({
77433
77616
  access: "view",
77434
77617
  role: "admin"
77435
77618
  },
77436
- "connectionTest.describeTest": {
77437
- capName: "connection-test",
77438
- capScope: "system",
77439
- addonId: null,
77440
- access: "view",
77441
- role: "admin"
77442
- },
77443
- "connectionTest.testSettings": {
77444
- capName: "connection-test",
77445
- capScope: "system",
77446
- addonId: null,
77447
- access: "create",
77448
- role: "admin"
77449
- },
77450
77619
  "connectivity.getStatus": {
77451
77620
  capName: "connectivity",
77452
77621
  capScope: "device",
@@ -79813,13 +79982,6 @@ Object.freeze({
79813
79982
  access: "view",
79814
79983
  role: "admin"
79815
79984
  },
79816
- "integrations.testConnection": {
79817
- capName: "integrations",
79818
- capScope: "system",
79819
- addonId: null,
79820
- access: "create",
79821
- role: "admin"
79822
- },
79823
79985
  "integrations.update": {
79824
79986
  capName: "integrations",
79825
79987
  capScope: "system",
@@ -81052,13 +81214,6 @@ Object.freeze({
81052
81214
  access: "create",
81053
81215
  role: "admin"
81054
81216
  },
81055
- "mqttBroker.testConnection": {
81056
- capName: "mqtt-broker",
81057
- capScope: "system",
81058
- addonId: null,
81059
- access: "create",
81060
- role: "admin"
81061
- },
81062
81217
  "nativeObjectDetection.getOptions": {
81063
81218
  capName: "native-object-detection",
81064
81219
  capScope: "device",
@@ -81934,13 +82089,6 @@ Object.freeze({
81934
82089
  access: "view",
81935
82090
  role: "viewer"
81936
82091
  },
81937
- "petFountain.resetDailyConsumption": {
81938
- capName: "pet-fountain",
81939
- capScope: "device",
81940
- addonId: null,
81941
- access: "delete",
81942
- role: "viewer"
81943
- },
81944
82092
  "petFountain.setPump": {
81945
82093
  capName: "pet-fountain",
81946
82094
  capScope: "device",
@@ -85896,20 +86044,6 @@ Object.freeze({
85896
86044
  access: "create",
85897
86045
  role: "admin"
85898
86046
  },
85899
- "trainingProvider.createEntry": {
85900
- capName: "training-provider",
85901
- capScope: "system",
85902
- addonId: null,
85903
- access: "create",
85904
- role: "admin"
85905
- },
85906
- "trainingProvider.deleteEntry": {
85907
- capName: "training-provider",
85908
- capScope: "system",
85909
- addonId: null,
85910
- access: "delete",
85911
- role: "admin"
85912
- },
85913
86047
  "trainingProvider.describe": {
85914
86048
  capName: "training-provider",
85915
86049
  capScope: "system",
@@ -85980,13 +86114,6 @@ Object.freeze({
85980
86114
  access: "create",
85981
86115
  role: "admin"
85982
86116
  },
85983
- "trainingProvider.updateEntry": {
85984
- capName: "training-provider",
85985
- capScope: "system",
85986
- addonId: null,
85987
- access: "create",
85988
- role: "admin"
85989
- },
85990
86117
  "trainingProvider.uploadDataset": {
85991
86118
  capName: "training-provider",
85992
86119
  capScope: "system",
@@ -85994,13 +86121,6 @@ Object.freeze({
85994
86121
  access: "create",
85995
86122
  role: "admin"
85996
86123
  },
85997
- "trainingProvider.validateCredentials": {
85998
- capName: "training-provider",
85999
- capScope: "system",
86000
- addonId: null,
86001
- access: "create",
86002
- role: "admin"
86003
- },
86004
86124
  "turnProvider.getTurnServers": {
86005
86125
  capName: "turn-provider",
86006
86126
  capScope: "system",
@@ -88337,11 +88457,6 @@ Object.freeze({
88337
88457
  form: "single",
88338
88458
  optional: false
88339
88459
  }],
88340
- "petFountain.resetDailyConsumption": [{
88341
- name: "deviceId",
88342
- form: "single",
88343
- optional: false
88344
- }],
88345
88460
  "petFountain.setPump": [{
88346
88461
  name: "deviceId",
88347
88462
  form: "single",
@@ -91085,48 +91200,53 @@ object({
91085
91200
  delay: number().nonnegative().optional(),
91086
91201
  commands: record(string(), unknown())
91087
91202
  });
91088
- var BrokerInUseError = class extends Error {
91089
- brokerId;
91203
+ var InstanceInUseError = class extends Error {
91204
+ instanceId;
91090
91205
  users;
91091
- name = "BrokerInUseError";
91092
- constructor(brokerId, users) {
91093
- super(`broker '${brokerId}' is still in use by ${users.map((u) => `${u.kind} '${u.name ?? u.id}' (${u.id})`).join(", ")}; unlink them first`);
91094
- this.brokerId = brokerId;
91206
+ name = "InstanceInUseError";
91207
+ constructor(instanceId, users) {
91208
+ super(`instance '${instanceId}' is still in use by ${users.map((u) => `${u.kind} '${u.name ?? u.id}' (${u.id})`).join(", ")}; unlink them first`);
91209
+ this.instanceId = instanceId;
91095
91210
  this.users = users;
91096
91211
  }
91097
91212
  };
91098
- /** Throw {@link BrokerInUseError} when any finder names a user of `brokerId`. */
91099
- async function assertBrokerUnused(brokerId, finders) {
91213
+ /** Throw {@link InstanceInUseError} when any finder names a user of `instanceId`. */
91214
+ async function assertInstanceUnused(instanceId, finders) {
91100
91215
  const users = [];
91101
- for (const finder of finders) users.push(...await finder.find(brokerId));
91102
- if (users.length > 0) throw new BrokerInUseError(brokerId, users);
91216
+ for (const finder of finders) users.push(...await finder.find(instanceId));
91217
+ if (users.length > 0) throw new InstanceInUseError(instanceId, users);
91218
+ }
91219
+ function namesInstance(value, instanceId) {
91220
+ if (Array.isArray(value)) return value.includes(instanceId);
91221
+ return value === instanceId;
91103
91222
  }
91104
91223
  /**
91105
91224
  * Users reached through another addon's listed rows (an addon cannot read a record kind it does
91106
- * not own): every row whose `field` holds the broker id. `list` is a cap call the owner serves.
91225
+ * not own): every row whose `field` holds the instance id, as a string or in a string list.
91226
+ * `list` is a cap call the owner serves.
91107
91227
  */
91108
91228
  function fieldUserFinder(spec) {
91109
- return { find: async (brokerId) => (await spec.list()).filter((row) => row.formValues[spec.field] === brokerId).map((row) => ({
91229
+ const fields = typeof spec.field === "string" ? [spec.field] : spec.field;
91230
+ return { find: async (instanceId) => (await spec.list()).filter((row) => fields.some((f) => namesInstance(row.formValues[f], instanceId))).map((row) => ({
91110
91231
  kind: spec.kind,
91111
91232
  id: row.id,
91112
91233
  ...row.name !== void 0 ? { name: row.name } : {}
91113
91234
  })) };
91114
91235
  }
91115
91236
  /**
91116
- * An account provider whose `deleteInstance` is refused while anything still uses the account
91117
- * (D1012). The account is an `integration-instances` kind (D1013), so the refusal lives on the
91118
- * delete the instances page calls, not on a separate broker cap.
91237
+ * A provider whose `deleteInstance` is refused while anything still uses the instance. The
91238
+ * account is an `integration-instances` kind (D1013), so the refusal lives on the delete the
91239
+ * instances page calls.
91119
91240
  */
91120
- function guardBrokerDelete(base, users) {
91241
+ function guardInstanceDelete(base, users) {
91121
91242
  return {
91122
91243
  ...base,
91123
91244
  deleteInstance: async (input) => {
91124
- await assertBrokerUnused(input.id, users());
91245
+ await assertInstanceUnused(input.id, users());
91125
91246
  return base.deleteInstance(input);
91126
91247
  }
91127
91248
  };
91128
91249
  }
91129
- entryBody({ brokerId: string() });
91130
91250
  //#endregion
91131
91251
  //#region ../../node_modules/xtend/immutable.js
91132
91252
  var require_immutable = /* @__PURE__ */ __commonJSMin(((exports, module) => {
@@ -122988,7 +123108,7 @@ var BrokerProbeCache = class {
122988
123108
  }
122989
123109
  if (this.inflight) await this.inflight.catch(() => void 0);
122990
123110
  }
122991
- /** Force a refresh (used by `testConnection` and the page's Refresh button). */
123111
+ /** Force a refresh (used by the page's Refresh button). */
122992
123112
  async probeNow(id) {
122993
123113
  const broker = this.getBrokers().find((b) => b.id === id);
122994
123114
  if (!broker) return void 0;
@@ -123351,7 +123471,7 @@ var PROBE_LABELS = {
123351
123471
  };
123352
123472
  /** The instance's health word: connected / auth-failed / unreachable / tls-error, latency, clients. */
123353
123473
  function mqttHealthOf(body, live, now) {
123354
- if (body.enabled === false) return { status: {
123474
+ if (!isInstanceEnabled(body)) return { status: {
123355
123475
  state: "off",
123356
123476
  label: "Switched off"
123357
123477
  } };
@@ -123476,7 +123596,7 @@ function buildMqttBrokerInstances(records, deps) {
123476
123596
  onboard: built.onboard
123477
123597
  };
123478
123598
  };
123479
- return guardBrokerDelete({
123599
+ return guardInstanceDelete({
123480
123600
  ...base,
123481
123601
  instanceFormSchema: async ({ id }) => {
123482
123602
  const saved = id === null ? null : await instances.getResolved(id);
@@ -123970,8 +124090,8 @@ var MqttAclStore = class MqttAclStore {
123970
124090
  * - The legacy single embedded broker is an onboard `brokers` record (migrated from the flat
123971
124091
  * `embedded*` keys, same id); `startEmbeddedBroker` / `stopEmbeddedBroker` act on that record.
123972
124092
  * - `addBroker` / `removeBroker` mutate the records and the runtime state.
123973
- * - `testConnection` does a one-shot `mqtt.connect` race against a 3s
123974
- * timeout AND refreshes the probe cache for the broker.
124093
+ * - The instance test (`integration-instances.testInstance`) does a one-shot `mqtt.connect`
124094
+ * race against a 3s timeout.
123975
124095
  */
123976
124096
  /** bcrypt cost factor — exported for tests. */
123977
124097
  var MQTT_EMBEDDED_BCRYPT_ROUNDS = 10;
@@ -124107,7 +124227,6 @@ var MqttBrokerAddon = class extends BaseAddon {
124107
124227
  getBrokerConfig: async ({ id }) => this.getBrokerConfig(id),
124108
124228
  addBroker: async (input) => this.addBroker(input),
124109
124229
  removeBroker: async ({ id }) => this.removeBroker(id),
124110
- testConnection: async ({ id }) => this.testConnection(id),
124111
124230
  startEmbeddedBroker: async (input) => this.startEmbeddedBroker(input),
124112
124231
  stopEmbeddedBroker: async ({ id }) => this.stopEmbeddedBroker(id),
124113
124232
  getStatus: async () => ({
@@ -124210,7 +124329,7 @@ var MqttBrokerAddon = class extends BaseAddon {
124210
124329
  getBrokerConfig(id) {
124211
124330
  const external = this.activeExternalBrokers.find((b) => b.id === id);
124212
124331
  if (external) {
124213
- if (external.enabled === false) throw new Error(`mqtt-broker: broker '${id}' is switched off`);
124332
+ if (!isInstanceEnabled(external)) throw new Error(`mqtt-broker: broker '${id}' is switched off`);
124214
124333
  const password = this.storedPassword(external.password);
124215
124334
  return {
124216
124335
  url: external.url,
@@ -124250,24 +124369,10 @@ var MqttBrokerAddon = class extends BaseAddon {
124250
124369
  return;
124251
124370
  }
124252
124371
  }
124253
- async testConnection(id) {
124254
- let cfg;
124255
- try {
124256
- cfg = this.getBrokerConfig(id);
124257
- } catch (err) {
124258
- return {
124259
- ok: false,
124260
- error: errMsg(err)
124261
- };
124262
- }
124263
- this.probeCache?.probeNow(id).catch(() => void 0);
124264
- return this.probeMqtt(cfg);
124265
- }
124266
124372
  /**
124267
124373
  * One-shot connectivity probe against an MQTT endpoint built from a
124268
- * flat config (`{url, username?, password?}`). Shared by the
124269
- * id-keyed `testConnection` (existing broker) and the pre-creation
124270
- * the instance test (`testInstance`) of a broker not saved yet (the typed values).
124374
+ * flat config (`{url, username?, password?}`), used by the instance test
124375
+ * (`integration-instances.testInstance`), stored or draft.
124271
124376
  * Never throws — every failure resolves to `{ ok: false, error }`.
124272
124377
  */
124273
124378
  async probeMqtt(cfg) {
@@ -124466,7 +124571,7 @@ var MqttBrokerAddon = class extends BaseAddon {
124466
124571
  * entry disappeared, and respawn runtimes whose port changed.
124467
124572
  */
124468
124573
  async reconcileOnboardRuntimes() {
124469
- const desiredEntries = this.activeExternalBrokers.filter(hasOnboard).filter((b) => b.enabled !== false);
124574
+ const desiredEntries = this.activeExternalBrokers.filter(hasOnboard).filter((b) => isInstanceEnabled(b));
124470
124575
  const desired = desiredEntries.map((b) => ({
124471
124576
  id: b.id,
124472
124577
  port: b.onboard.port
@@ -124607,7 +124712,7 @@ var MqttBrokerAddon = class extends BaseAddon {
124607
124712
  collectExternalProbeInputs() {
124608
124713
  const out = [];
124609
124714
  for (const b of this.activeExternalBrokers) {
124610
- if (b.onboard !== void 0 || b.enabled === false) continue;
124715
+ if (b.onboard !== void 0 || !isInstanceEnabled(b)) continue;
124611
124716
  let password;
124612
124717
  try {
124613
124718
  password = this.storedPassword(b.password);