@camstack/addon-provider-reolink 1.2.230 → 1.2.232

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.
package/dist/addon.js CHANGED
@@ -106677,7 +106677,7 @@ var ZodIssueCode = {
106677
106677
  var ZodFirstPartyTypeKind;
106678
106678
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
106679
106679
  //#endregion
106680
- //#region ../types/dist/sleep-BX_MqzUe.mjs
106680
+ //#region ../types/dist/sleep-D7ZKm4nb.mjs
106681
106681
  /**
106682
106682
  * The audio chunk plane's byte format, and the ONE expansion from a coded
106683
106683
  * window to float samples (D455).
@@ -107361,137 +107361,127 @@ async function runAddonMigrations(host, migrations, logger, options = {}) {
107361
107361
  blockOwner
107362
107362
  };
107363
107363
  }
107364
- /**
107365
- * Build a {@link DurableState} over a single store key. Transport-agnostic:
107366
- * `read`/`write` are the addon-store or device-store accessors. The whole
107367
- * validated value round-trips on every read/write — the schema is the
107368
- * single source of truth for what is persisted, so no hand-listed field
107369
- * set can drop a key on save.
107370
- */
107371
- function createDurableState(deps) {
107372
- const get = async () => {
107373
- const raw = (await deps.read())[deps.key];
107374
- if (raw === void 0) return deps.fallback;
107375
- const parsed = deps.schema.safeParse(raw);
107376
- if (!parsed.success) {
107377
- deps.onParseError?.(deps.key, parsed.error);
107378
- return deps.fallback;
107379
- }
107380
- return parsed.data;
107381
- };
107382
- const set = async (next) => {
107383
- const validated = deps.schema.parse(next);
107384
- await deps.write({ [deps.key]: validated });
107385
- };
107386
- const update = async (fn) => {
107387
- await set(fn(await get()));
107388
- };
107364
+ /** The record calls the one-switch migration makes, over the migration API. */
107365
+ function switchRecordsOverMigrationApi(api) {
107366
+ return { kind: (definition) => {
107367
+ const handle = api.records.kind(definition);
107368
+ return {
107369
+ get: (id) => handle.get({ id }),
107370
+ put: (input, opts) => handle.put({
107371
+ ...input,
107372
+ ...opts?.ifRev === void 0 ? {} : { ifRev: opts.ifRev }
107373
+ }),
107374
+ patch: (id, partial) => handle.patch({
107375
+ id,
107376
+ partial
107377
+ })
107378
+ };
107379
+ } };
107380
+ }
107381
+ function integrationRowsApiOver(api) {
107389
107382
  return {
107390
- get,
107391
- set,
107392
- update
107383
+ list: async () => (await api.integrations.list({})).integrations,
107384
+ readLegacyIntegrationRows: (input) => api.legacyRows.read(input),
107385
+ clearLegacyIntegrationRows: (input) => api.legacyRows.clear(input)
107393
107386
  };
107394
107387
  }
107388
+ var PREFIX = "records/";
107395
107389
  /**
107396
- * Per-node scoping for the shared addon-settings blob.
107397
- *
107398
- * An addon's settings store is hub-central (the `addon-settings` cap is
107399
- * hub-routed — the hub instance answers for every node), so fields whose
107400
- * value is a NODE fact (decoder backend, engine pick, probed hardware
107401
- * capabilities) persist under the node-scoped key `<key>@<nodeId>` inside
107402
- * the single shared blob. The SCHEMA field key stays bare: the write path
107403
- * ({@link scopePatch}) maps the bare field onto the target node's scoped
107404
- * key; the read/hydrate path ({@link projectStore}) maps THIS node's value
107405
- * back, so UI forms and `resolveConfig` only ever see the bare key.
107406
- *
107407
- * Fields opt in via the `perNode: true` schema marker on `ConfigFieldBase`
107408
- * (`interfaces/config-ui.ts`); `BaseAddon` derives the key set from the
107409
- * schema and routes reads/writes through these helpers.
107410
- *
107411
- * ## No bare-key fallback — deliberate
107412
- *
107413
- * {@link readNodeValue} reads the node-scoped key ONLY. A node with no
107414
- * scoped key resolves to `undefined` so the field's schema `default` wins —
107415
- * NEVER `store[base]` and never another node's value. A bare legacy key in
107416
- * the store is invisible to every node, hub included, so one node's
107417
- * selection can never leak onto another. (This generalizes the
107418
- * `decoder-backend-keys.ts` semantics — the no-fallback variant — over an
107419
- * arbitrary set of per-node field keys.)
107420
- *
107421
- * Pure functions only — no I/O, no imports beyond the language. This is a
107422
- * LEAF module: import it via its deep path, never from the root barrel.
107423
- */
107424
- /**
107425
- * Normalize a raw kernel node id to the bare node id used for scoping.
107426
- * `localNodeId` can carry a `<node>/<addon>` suffix on forked child
107427
- * processes; per-node settings are per-NODE, so strip the addon segment.
107428
- * `undefined` / `null` / empty falls back to `'hub'`.
107390
+ * Cross-realm brand. An addon bundles its own copy of this module (D15) while
107391
+ * `ctx.records` is the HOST's door, so an error thrown by the host is an
107392
+ * instance of the host's classes, not of the addon's. The brand plus the code
107393
+ * make `instanceof` answer by identity of the failure, not of the copy.
107429
107394
  */
107430
- function normalizeNodeId(raw) {
107431
- if (raw === void 0 || raw === null || raw === "") return "hub";
107432
- const slashIdx = raw.indexOf("/");
107433
- if (slashIdx < 0) return raw;
107434
- const bare = raw.slice(0, slashIdx);
107435
- return bare === "" ? "hub" : bare;
107436
- }
107437
- /** The node-scoped store key for a per-node field: `<base>@<nodeId>`. */
107438
- function nodeScopedKey(base, nodeId) {
107439
- return `${base}@${normalizeNodeId(nodeId)}`;
107395
+ var RECORDS_ERROR_BRAND = Symbol.for("camstack.records-error");
107396
+ function carriesBrand(value) {
107397
+ return typeof value === "object" && value !== null && Reflect.get(value, RECORDS_ERROR_BRAND) === true;
107440
107398
  }
107399
+ /** The base of every records failure. `detail` is the human part of the message. */
107400
+ var RecordsError = class extends Error {
107401
+ /** The code a subclass stands for; the base stands for every code. */
107402
+ static code = void 0;
107403
+ /**
107404
+ * `instanceof` across copies of this module: any branded error is a
107405
+ * `RecordsError`, and is an instance of a subclass only when its code is the
107406
+ * subclass's code. Same-copy answers are unchanged.
107407
+ */
107408
+ static [Symbol.hasInstance](value) {
107409
+ if (Function.prototype[Symbol.hasInstance].call(this, value)) return true;
107410
+ if (!carriesBrand(value)) return false;
107411
+ return this.code === void 0 || value.code === this.code;
107412
+ }
107413
+ code;
107414
+ detail;
107415
+ [RECORDS_ERROR_BRAND] = true;
107416
+ constructor(code, detail) {
107417
+ super(`${PREFIX}${code}: ${detail}`);
107418
+ this.name = "RecordsError";
107419
+ this.code = code;
107420
+ this.detail = detail;
107421
+ }
107422
+ };
107423
+ /** A write guarded by `ifRev` found another revision (or an existing row for `ifRev: 0`). */
107424
+ var RevConflictError = class RevConflictError extends RecordsError {
107425
+ static code = "rev-conflict";
107426
+ constructor(detail) {
107427
+ super(RevConflictError.code, detail);
107428
+ this.name = "RevConflictError";
107429
+ }
107430
+ };
107431
+ /** The keychain could not store or serve a value: explicit, never an empty string. */
107432
+ var RecordSecretUnavailableError = class RecordSecretUnavailableError extends RecordsError {
107433
+ static code = "secret-unavailable";
107434
+ constructor(detail) {
107435
+ super(RecordSecretUnavailableError.code, detail);
107436
+ this.name = "RecordSecretUnavailableError";
107437
+ }
107438
+ };
107439
+ var InvalidRecordError = class InvalidRecordError extends RecordsError {
107440
+ static code = "invalid-record";
107441
+ constructor(detail) {
107442
+ super(InvalidRecordError.code, detail);
107443
+ this.name = "InvalidRecordError";
107444
+ }
107445
+ };
107446
+ /** A kind declaration the engine refuses (non-additive change, bad shape, wrong file). */
107447
+ var DeclarationRefusedError = class DeclarationRefusedError extends RecordsError {
107448
+ static code = "declaration-refused";
107449
+ constructor(detail) {
107450
+ super(DeclarationRefusedError.code, detail);
107451
+ this.name = "DeclarationRefusedError";
107452
+ }
107453
+ };
107441
107454
  /**
107442
- * Read a node's value for a per-node field from the raw shared store:
107443
- * the node-scoped key when present, otherwise `undefined`.
107444
- * Deliberately NO bare-key fallback (see module doc) — the caller lets the
107445
- * schema `default` win on `undefined`.
107455
+ * A link that may stay empty (absent): for a link the addon fills itself, or one an instance does not
107456
+ * always need. The meta rides on the optional wrapper, where {@link linksOfKind} reads it.
107446
107457
  */
107447
- function readNodeValue(store, base, nodeId) {
107448
- return store[nodeScopedKey(base, nodeId)];
107458
+ function optionalLinkField(target) {
107459
+ return string().optional().meta({ link: target });
107449
107460
  }
107450
- /**
107451
- * Re-map a UI/settings patch so every bare perNode field persists under the
107452
- * TARGET node's scoped key; all other keys pass through unchanged. Used on
107453
- * the write path so a save for one node never clobbers another node's value
107454
- * (and the bare key is never written). Returns a new object — the input
107455
- * patch is not mutated.
107456
- */
107457
- function scopePatch(patch, perNodeKeys, nodeId) {
107458
- const out = {};
107459
- for (const [key, value] of Object.entries(patch)) out[perNodeKeys.has(key) ? nodeScopedKey(key, nodeId) : key] = value;
107460
- return out;
107461
+ function linkTargetOf(meta) {
107462
+ if (typeof meta !== "object" || meta === null) return void 0;
107463
+ const link = Reflect.get(meta, "link");
107464
+ const parsed = LinkTargetSchema.safeParse(link);
107465
+ return parsed.success ? parsed.data : void 0;
107461
107466
  }
107462
- /**
107463
- * Project the raw shared store onto the bare schema keys for ONE node so a
107464
- * UI schema (whose field keys are bare) hydrates from that node's own
107465
- * values:
107466
- *
107467
- * - EVERY `@`-scoped key (any node's) is dropped from the pass-through.
107468
- * - Every bare perNode key is dropped from the pass-through (a stray bare
107469
- * legacy key must never hydrate any node — no bare fallback).
107470
- * - THIS node's effective value ({@link readNodeValue}) is then laid onto
107471
- * each bare perNode key; when the node has no scoped key the bare key is
107472
- * left ABSENT so the field's schema `default` wins.
107473
- *
107474
- * Returns a new object — the input store is not mutated.
107475
- */
107476
- function projectStore(store, perNodeKeys, nodeId) {
107477
- const out = {};
107478
- for (const [key, value] of Object.entries(store)) {
107479
- if (key.includes("@")) continue;
107480
- if (perNodeKeys.has(key)) continue;
107481
- out[key] = value;
107482
- }
107483
- for (const base of perNodeKeys) {
107484
- const value = readNodeValue(store, base, nodeId);
107485
- if (value !== void 0) out[base] = value;
107467
+ var LinkTargetSchema = object({
107468
+ cap: string().min(1),
107469
+ kind: string().min(1).optional()
107470
+ });
107471
+ /** The links a kind declares, read from the meta of its body fields. */
107472
+ function linksOfKind(kind) {
107473
+ const schema = kind.schema;
107474
+ if (!(schema instanceof ZodObject)) return [];
107475
+ const links = [];
107476
+ for (const [field, fieldSchema] of Object.entries(schema.shape)) {
107477
+ const to = linkTargetOf(globalRegistry.get(fieldSchema));
107478
+ if (to !== void 0) links.push({
107479
+ field,
107480
+ to
107481
+ });
107486
107482
  }
107487
- return out;
107483
+ return links;
107488
107484
  }
107489
- /** Every scope, in the order the guard and the docs list them. */
107490
- var SCOPED_SETTINGS_SCOPES = [
107491
- "cluster",
107492
- "device-defaults",
107493
- "node"
107494
- ];
107495
107485
  /**
107496
107486
  * The address of one keychain value: `secret://<owner>/<scope>/<fieldPath>`.
107497
107487
  *
@@ -107626,6 +107616,652 @@ function parseSecretRef(ref) {
107626
107616
  fieldPath
107627
107617
  };
107628
107618
  }
107619
+ /** Limits and names of `ctx.records` (D881). One authority; the engine and the facade read it. */
107620
+ /** The files a kind may live in. `history` is device-history's (D850), never records. */
107621
+ var RECORD_DATABASES = ["settings", "events"];
107622
+ /** The classes of a kind: the `@durable` vocabulary, one authority (replaces the annotation). */
107623
+ var RECORD_CLASSES = [
107624
+ "config",
107625
+ "ledger",
107626
+ "audit",
107627
+ "mirror",
107628
+ "ephemeral"
107629
+ ];
107630
+ var RECORD_DEFAULT_MAX_DATA_BYTES = 64 * 1024;
107631
+ var RECORD_MAX_DATA_BYTES = 1024 * 1024;
107632
+ var RECORD_BATCH_MAX = 1e3;
107633
+ var RECORD_QUERY_MAX = 1e3;
107634
+ /** A kind in the `settings` file may not bound itself above this (D447: high volume is `events`). */
107635
+ var RECORD_SETTINGS_MAX_ROWS = 5e4;
107636
+ /** The `Column`-free proof prefix: a ref collection for a kind's secret fields. */
107637
+ var RECORD_SECRET_COLLECTION_PREFIX = "records:";
107638
+ /**
107639
+ * Secret fields of a record, addressed the way a Zod schema declares them
107640
+ * (`collectZodSecretPaths`): dotted keys, `[]` for "each element of this array"
107641
+ * (`auth.accessToken`, `headers[].value`).
107642
+ *
107643
+ * `{}` after a key means "each value of this map" (`applianceSecrets{}`): the map's own key
107644
+ * names the value (`applianceSecrets{fridge}`), so no id key is declared and a body that drops a
107645
+ * key releases exactly that key's secret.
107646
+ *
107647
+ * Array elements are matched by a DECLARED id key (`secretArrayKeys`:
107648
+ * `{ headers: 'name' }`), never by index, so reordering a list keeps every
107649
+ * keychain ref (the same rule as `arrayItemFieldPath`). The concrete path of a
107650
+ * leaf names its element: `headers[X-Api].value`.
107651
+ *
107652
+ * Pure and browser-safe. Nothing here mutates: every transform returns a new value.
107653
+ */
107654
+ /** The array prefixes (declared form, e.g. `headers` or `a.headers`) of a path. */
107655
+ function parseSecretPath(path) {
107656
+ if (path.length === 0) throw new InvalidRecordError("an empty secret path");
107657
+ return path.split(".").map((raw) => {
107658
+ const each = raw.endsWith("[]");
107659
+ const map = raw.endsWith("{}");
107660
+ const key = each || map ? raw.slice(0, -2) : raw;
107661
+ if (key.length === 0) throw new InvalidRecordError(`secret path "${path}" has an empty segment`);
107662
+ return {
107663
+ key,
107664
+ each,
107665
+ map
107666
+ };
107667
+ });
107668
+ }
107669
+ /** The declared array prefixes of `path` that need an id key (`headers`, `a.rows`). */
107670
+ function secretArrayPrefixes(path) {
107671
+ const segments = parseSecretPath(path);
107672
+ const prefixes = [];
107673
+ const walked = [];
107674
+ for (const segment of segments) {
107675
+ walked.push(segment.key);
107676
+ if (segment.each) prefixes.push(walked.join("."));
107677
+ }
107678
+ return prefixes;
107679
+ }
107680
+ function isRecord$6(value) {
107681
+ return typeof value === "object" && value !== null && !Array.isArray(value);
107682
+ }
107683
+ function elementId(element, idKey, declared, prefix) {
107684
+ const id = isRecord$6(element) ? element[idKey] : void 0;
107685
+ 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`);
107686
+ return id;
107687
+ }
107688
+ /**
107689
+ * Visit every secret leaf PRESENT in `data` (an absent branch has nothing to
107690
+ * visit). `replace` returns the new leaf value, or {@link REMOVE_LEAF}; the
107691
+ * result is a new body, `data` is untouched.
107692
+ */
107693
+ var REMOVE_LEAF = Symbol("remove-leaf");
107694
+ function mapAt(node, segments, index, walkedKeys, concretePrefix, declared, arrayKeys, visit) {
107695
+ if (!isRecord$6(node)) return node;
107696
+ const segment = segments[index];
107697
+ if (segment === void 0) return node;
107698
+ if (!Object.prototype.hasOwnProperty.call(node, segment.key)) return node;
107699
+ const child = node[segment.key];
107700
+ const keys = [...walkedKeys, segment.key];
107701
+ const last = index === segments.length - 1;
107702
+ if (segment.each) {
107703
+ if (!Array.isArray(child)) return node;
107704
+ const prefix = keys.join(".");
107705
+ const idKey = arrayKeys[prefix];
107706
+ if (idKey === void 0) throw new InvalidRecordError(`"${declared}": no id key declared for the array "${prefix}"`);
107707
+ const mapped = child.map((element) => {
107708
+ const id = elementId(element, idKey, declared, prefix);
107709
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}[${encodeURIComponent(id)}]`;
107710
+ return last ? element : mapAt(element, segments, index + 1, keys, concrete, declared, arrayKeys, visit);
107711
+ });
107712
+ return {
107713
+ ...node,
107714
+ [segment.key]: mapped
107715
+ };
107716
+ }
107717
+ if (segment.map) {
107718
+ if (!isRecord$6(child)) return node;
107719
+ const kept = Object.entries(child).map(([mapKey, value]) => {
107720
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}{${encodeURIComponent(mapKey)}}`;
107721
+ if (!last) return [mapKey, mapAt(value, segments, index + 1, keys, concrete, declared, arrayKeys, visit)];
107722
+ return [mapKey, visit({
107723
+ declared,
107724
+ concrete,
107725
+ value
107726
+ })];
107727
+ }).filter(([, value]) => value !== REMOVE_LEAF);
107728
+ return {
107729
+ ...node,
107730
+ [segment.key]: Object.fromEntries(kept)
107731
+ };
107732
+ }
107733
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}`;
107734
+ if (last) {
107735
+ const replacement = visit({
107736
+ declared,
107737
+ concrete,
107738
+ value: child
107739
+ });
107740
+ if (replacement === REMOVE_LEAF) return Object.fromEntries(Object.entries(node).filter(([key]) => key !== segment.key));
107741
+ return {
107742
+ ...node,
107743
+ [segment.key]: replacement
107744
+ };
107745
+ }
107746
+ return {
107747
+ ...node,
107748
+ [segment.key]: mapAt(child, segments, index + 1, keys, concrete, declared, arrayKeys, visit)
107749
+ };
107750
+ }
107751
+ /** Replace/remove every present secret leaf; returns a NEW body. */
107752
+ function mapSecretLeaves(data, paths, arrayKeys, visit) {
107753
+ let current = data;
107754
+ for (const declared of paths) current = mapAt(current, parseSecretPath(declared), 0, [], "", declared, arrayKeys, visit);
107755
+ return current;
107756
+ }
107757
+ /** Every present secret leaf, read-only. */
107758
+ function collectSecretLeaves(data, paths, arrayKeys) {
107759
+ const found = [];
107760
+ mapSecretLeaves(data, paths, arrayKeys, (leaf) => {
107761
+ found.push(leaf);
107762
+ return leaf.value;
107763
+ });
107764
+ return found;
107765
+ }
107766
+ /**
107767
+ * The keychain collection name a kind's secrets live under. Prefixed so a
107768
+ * record's refs never collide with the refs a legacy collection of the same name
107769
+ * already holds during an adoption.
107770
+ */
107771
+ function recordSecretCollection(kind) {
107772
+ return `${RECORD_SECRET_COLLECTION_PREFIX}${kind}`;
107773
+ }
107774
+ /** The ONE ref a row's secret field may carry: the engine and the facade both build it here. */
107775
+ function recordSecretRef(owner, kind, rowId, concretePath) {
107776
+ return buildSecretRef({
107777
+ owner,
107778
+ scope: {
107779
+ kind: "row",
107780
+ collection: recordSecretCollection(kind),
107781
+ rowId
107782
+ },
107783
+ fieldPath: concretePath
107784
+ });
107785
+ }
107786
+ /**
107787
+ * A stored secret, as an admin read shows it: a VIEW naming the row's own
107788
+ * keychain ref (`set: true`), never the value and no longer the bare redaction
107789
+ * token. The form hands it to the secret field, which reveals the value by ref
107790
+ * through the audited `keychain-admin.reveal`; sent back untouched it keeps the
107791
+ * stored secret (the records door reads a view as KEEP).
107792
+ *
107793
+ * ONE implementation for the entries service and for every addon that serves
107794
+ * its own instances (`RecordIntegrationInstances`).
107795
+ */
107796
+ function isRecord$5(value) {
107797
+ return typeof value === "object" && value !== null && !Array.isArray(value);
107798
+ }
107799
+ function secretViewsOf(owner, kind, id, decl, data) {
107800
+ if (decl.secretPaths.length === 0) return data;
107801
+ const shown = mapSecretLeaves(data, decl.secretPaths, decl.secretArrayKeys, (leaf) => {
107802
+ if (leaf.value !== "__camstack_redacted__") return leaf.value;
107803
+ return {
107804
+ $secret: recordSecretRef(owner, kind, id, leaf.concrete),
107805
+ v: 1,
107806
+ set: true
107807
+ };
107808
+ });
107809
+ return isRecord$5(shown) ? shown : data;
107810
+ }
107811
+ /** The most instances one addon lists (an integrations page, not a table). */
107812
+ var INSTANCES_LIST_MAX = 1e3;
107813
+ /**
107814
+ * The ONE reader of an instance's switch (D996): an absent field means on, so a row written
107815
+ * before the field existed needs no migration. Every consumer of an instance body asks this.
107816
+ */
107817
+ function isInstanceEnabled(body) {
107818
+ return body.enabled !== false;
107819
+ }
107820
+ /** The body key of the switch; only {@link RecordIntegrationInstances.setInstanceEnabled} writes it. */
107821
+ var SWITCH_KEY = "enabled";
107822
+ /** The keys of the kind's secret fields that sit at the top level of the body. */
107823
+ function topLevelSecretKeys(paths) {
107824
+ return new Set(paths.filter((p) => !p.includes(".") && !p.includes("[") && !p.includes("{")));
107825
+ }
107826
+ /** The keys of the kind's top-level MAPS whose values are secrets (`applianceSecrets{}`). */
107827
+ function secretMapKeys(paths) {
107828
+ return new Set(paths.filter((p) => p.endsWith("{}") && !p.slice(0, -2).match(/[.[{]/)).map((p) => p.slice(0, -2)));
107829
+ }
107830
+ /**
107831
+ * A patch value for a map of secrets: an entry that is omitted, `''`, the redaction token or the
107832
+ * view the form was given KEEPS its stored secret (it is left out of the merge); `{ $secretClear }`
107833
+ * or `null` removes the entry; any other string replaces it. Null when nothing is left to merge.
107834
+ */
107835
+ function secretMapPatch(value) {
107836
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
107837
+ const out = {};
107838
+ for (const [key, entry] of Object.entries(value)) if (entry === null || isSecretClear(entry)) out[key] = null;
107839
+ else if (typeof entry === "string" && entry !== "" && entry !== "__camstack_redacted__" && !isSecretFieldView(entry)) out[key] = entry;
107840
+ return Object.keys(out).length > 0 ? out : null;
107841
+ }
107842
+ var RecordIntegrationInstances = class {
107843
+ records;
107844
+ kind;
107845
+ hooks;
107846
+ handle;
107847
+ secretKeys;
107848
+ secretMaps;
107849
+ nameField;
107850
+ switchListeners = /* @__PURE__ */ new Set();
107851
+ constructor(records, kind, hooks) {
107852
+ this.records = records;
107853
+ this.kind = kind;
107854
+ this.hooks = hooks;
107855
+ this.handle = records.kind(kind);
107856
+ this.secretKeys = topLevelSecretKeys(kind.declaration.secretPaths);
107857
+ this.secretMaps = secretMapKeys(kind.declaration.secretPaths);
107858
+ this.nameField = kind.declaration.entry?.nameField ?? "name";
107859
+ }
107860
+ /**
107861
+ * One instance read for the addon's own runtime; null when absent. When the keychain is
107862
+ * locked the row is served WITHOUT its secrets and says so (`secrets: 'unavailable'`), so the
107863
+ * caller can keep what it had instead of reconfiguring with an empty secret (D49).
107864
+ */
107865
+ async readResolved(id) {
107866
+ try {
107867
+ const record = await this.handle.getResolved(id);
107868
+ return record === null ? null : {
107869
+ id,
107870
+ body: record.data,
107871
+ enabled: isInstanceEnabled(record.data),
107872
+ secrets: "resolved"
107873
+ };
107874
+ } catch (err) {
107875
+ if (!(err instanceof RecordSecretUnavailableError)) throw err;
107876
+ const stored = await this.handle.get(id);
107877
+ if (stored === null) return null;
107878
+ return {
107879
+ id,
107880
+ body: Object.fromEntries(Object.entries(stored.data).filter(([key]) => !this.secretKeys.has(key))),
107881
+ enabled: isInstanceEnabled(stored.data),
107882
+ secrets: "unavailable"
107883
+ };
107884
+ }
107885
+ }
107886
+ /** The body of {@link readResolved} alone; a locked keychain yields the row without secrets. */
107887
+ async getResolved(id) {
107888
+ return (await this.readResolved(id))?.body ?? null;
107889
+ }
107890
+ /** Every instance, secrets resolved where the keychain allows; an absent one is skipped. */
107891
+ async listResolved() {
107892
+ const page = await this.handle.query({ limit: INSTANCES_LIST_MAX });
107893
+ const out = [];
107894
+ for (const record of page.records) {
107895
+ const read = await this.readResolved(record.id);
107896
+ if (read !== null) out.push(read);
107897
+ }
107898
+ return out;
107899
+ }
107900
+ viewOf(record) {
107901
+ const shown = secretViewsOf(this.records.owner, this.kind.name, record.id, this.kind.declaration, record.data);
107902
+ const rawName = record.data[this.nameField];
107903
+ const kind = this.hooks.kindOf?.(record.data);
107904
+ const health = this.hooks.health?.(record.data, record.id);
107905
+ return {
107906
+ id: record.id,
107907
+ name: typeof rawName === "string" ? rawName : record.id,
107908
+ configured: this.hooks.configured(record.data),
107909
+ enabled: isInstanceEnabled(record.data),
107910
+ formValues: shown,
107911
+ ...kind !== void 0 ? { kind } : {},
107912
+ ...health?.status !== void 0 ? { status: health.status } : {},
107913
+ ...health?.lastCheckedAt !== void 0 ? { lastCheckedAt: health.lastCheckedAt } : {}
107914
+ };
107915
+ }
107916
+ describe = async () => {
107917
+ const declared = linksOfKind(this.kind);
107918
+ const links = this.hooks.description.links !== void 0 || declared.length === 0 ? {} : { links: declared.map((link) => ({
107919
+ kind: this.kind.name,
107920
+ field: link.field,
107921
+ to: link.to
107922
+ })) };
107923
+ return {
107924
+ ...this.hooks.description,
107925
+ ...links,
107926
+ ...this.hooks.mintId === void 0 ? {} : { mintsId: true }
107927
+ };
107928
+ };
107929
+ instanceFormSchema = async ({ id }) => this.hooks.formSchema(id);
107930
+ listInstances = async () => {
107931
+ return (await this.handle.query({ limit: INSTANCES_LIST_MAX })).records.map((record) => this.viewOf(record));
107932
+ };
107933
+ getInstance = async ({ id }) => {
107934
+ const record = await this.handle.get(id);
107935
+ return record === null ? null : this.viewOf(record);
107936
+ };
107937
+ /** Insert ONE row (`ifRev: 0`: an existing id is refused, never overwritten). */
107938
+ createInstance = async ({ id, name, kind, values }) => {
107939
+ const minted = id ?? this.hooks.mintId?.({
107940
+ name,
107941
+ ...kind !== void 0 ? { kind } : {}
107942
+ });
107943
+ if (minted === void 0) throw new Error("createInstance needs an id: this provider does not mint one");
107944
+ await this.handle.put({
107945
+ id: minted,
107946
+ data: this.hooks.initialBody(name, kind)
107947
+ }, { ifRev: 0 });
107948
+ const patch = this.patchOf(values ?? {});
107949
+ if (Object.keys(patch).length > 0) await this.handle.patch(minted, patch);
107950
+ await this.hooks.onChanged?.(minted, "created");
107951
+ return { id: minted };
107952
+ };
107953
+ updateInstance = async ({ id, name, values }) => {
107954
+ const patch = this.patchOf(values);
107955
+ if (name !== void 0) patch[this.nameField] = name;
107956
+ await this.handle.patch(id, patch);
107957
+ await this.hooks.onChanged?.(id, "updated");
107958
+ return { ok: true };
107959
+ };
107960
+ /** The record patch a form `values` object means: secrets kept, cleared or replaced. */
107961
+ patchOf(values) {
107962
+ const patch = {};
107963
+ for (const [key, value] of Object.entries(values)) {
107964
+ if (value === void 0) continue;
107965
+ if (key === "enabled") continue;
107966
+ if (this.secretMaps.has(key)) {
107967
+ const entries = secretMapPatch(value);
107968
+ if (entries !== null) patch[key] = entries;
107969
+ } else if (!this.secretKeys.has(key)) patch[key] = value;
107970
+ else if (isSecretClear(value)) patch[key] = null;
107971
+ else if (typeof value === "string" && value !== "" && value !== "__camstack_redacted__" && !isSecretFieldView(value)) patch[key] = value;
107972
+ }
107973
+ return patch;
107974
+ }
107975
+ /**
107976
+ * Listen to the switch of ANY instance of this helper (in the process that serves it). The
107977
+ * durable replacement of the `integration.enabled` / `integration.disabled` events (D8): the
107978
+ * addon reconciles from the record, whichever way it flipped.
107979
+ */
107980
+ onSwitched(listener) {
107981
+ this.switchListeners.add(listener);
107982
+ }
107983
+ /**
107984
+ * The ONE writer of the switch (D996, D1014): the record body's `enabled`, for every role. A
107985
+ * configured thing is an instance, so an id with no record yet (a default integration that was
107986
+ * never configured) gets its record from `initialBody` before the switch is written.
107987
+ */
107988
+ setInstanceEnabled = async ({ id, enabled }) => {
107989
+ if (await this.handle.get(id) === null) await this.handle.put({
107990
+ id,
107991
+ data: this.hooks.initialBody(id)
107992
+ }, { ifRev: 0 });
107993
+ await this.handle.patch(id, { [SWITCH_KEY]: enabled });
107994
+ await this.hooks.onChanged?.(id, "enabled");
107995
+ for (const listener of this.switchListeners) await listener(id, enabled);
107996
+ return { ok: true };
107997
+ };
107998
+ /** The row and its keychain refs go together (the records door). */
107999
+ deleteInstance = async ({ id }) => {
108000
+ await this.handle.delete(id);
108001
+ await this.hooks.onChanged?.(id, "deleted");
108002
+ return { ok: true };
108003
+ };
108004
+ testInstance = async (input) => {
108005
+ if (this.hooks.test === void 0) return {
108006
+ success: false,
108007
+ status: "unsupported",
108008
+ error: "This integration declares no connection test"
108009
+ };
108010
+ return this.hooks.test(input);
108011
+ };
108012
+ /** The flat provider object to hand to `registerProvider`. */
108013
+ toProvider() {
108014
+ return {
108015
+ describe: this.describe,
108016
+ instanceFormSchema: this.instanceFormSchema,
108017
+ listInstances: this.listInstances,
108018
+ getInstance: this.getInstance,
108019
+ createInstance: this.createInstance,
108020
+ updateInstance: this.updateInstance,
108021
+ setInstanceEnabled: this.setInstanceEnabled,
108022
+ deleteInstance: this.deleteInstance,
108023
+ testInstance: this.testInstance
108024
+ };
108025
+ }
108026
+ };
108027
+ /**
108028
+ * The one-switch migration (epic #440, step 3). An integration's on/off state used to live in the
108029
+ * registry's `enabled` column for a device addon; it now lives only in the instance record's
108030
+ * body (`enabled`, D1007 superseded). This moves a registry `enabled = false` into the body, once.
108031
+ *
108032
+ * For every registry row of the addon that is OFF:
108033
+ * - no record under its id: the record is created from `initialBody(name)` with `enabled: false`
108034
+ * (a default integration that never had settings, Reolink's among them);
108035
+ * - a record whose body states no `enabled`: `enabled: false` is written into it;
108036
+ * - a record that already states `enabled` (either way) is the newer truth and is left alone.
108037
+ * A row that is ON writes nothing: an absent field reads as on. A rerun finds every off row with
108038
+ * a stated switch and does nothing, so nothing switched off comes back on and nothing switched on
108039
+ * goes off. The registry column itself is neither read afterwards nor written; its drop is step 5.
108040
+ *
108041
+ * It runs in the addon process, BEFORE the addon registers its `integration-instances` provider,
108042
+ * which is also why `integrations.list` still answers the stored column at that point.
108043
+ */
108044
+ function registrySwitchToBodyId(addonId, date) {
108045
+ return `${addonId}/${date}-registry-switch-to-body`;
108046
+ }
108047
+ async function moveRegistrySwitchToBody(ports, spec) {
108048
+ const rows = await ports.listIntegrations(spec.addonId);
108049
+ let created = 0;
108050
+ let switched = 0;
108051
+ let kept = 0;
108052
+ for (const row of rows) {
108053
+ if (row.enabled) continue;
108054
+ const body = await ports.readBody(row.id);
108055
+ if (body === null) {
108056
+ if (await ports.createRecord(row.id, {
108057
+ ...spec.initialBody(row.name),
108058
+ ["enabled"]: false
108059
+ }) === "created") created += 1;
108060
+ else kept += 1;
108061
+ continue;
108062
+ }
108063
+ if ("enabled" in body) {
108064
+ kept += 1;
108065
+ continue;
108066
+ }
108067
+ await ports.switchOff(row.id);
108068
+ switched += 1;
108069
+ }
108070
+ const summary = {
108071
+ integrations: rows.length,
108072
+ off: rows.filter((r) => !r.enabled).length,
108073
+ created,
108074
+ switched,
108075
+ kept
108076
+ };
108077
+ return created === 0 && switched === 0 ? {
108078
+ outcome: "already-done",
108079
+ summary
108080
+ } : {
108081
+ outcome: "done",
108082
+ summary
108083
+ };
108084
+ }
108085
+ /** A migration entry: an addon states its kind and how a new body starts, nothing else. */
108086
+ function registrySwitchToBodyMigration(spec) {
108087
+ return {
108088
+ meta: {
108089
+ id: registrySwitchToBodyId(spec.addonId, spec.date),
108090
+ owner: spec.addonId,
108091
+ level: "addon-state",
108092
+ seq: spec.seq,
108093
+ dependsOn: [],
108094
+ store: "settings",
108095
+ scope: "cluster",
108096
+ onFailure: "block-owner",
108097
+ bodyKind: "procedure",
108098
+ description: "Move the registry enabled flag of every switched-off integration into its instance record body, creating the record when there is none",
108099
+ fixtureMark: "enabled"
108100
+ },
108101
+ procedure: (ports) => moveRegistrySwitchToBody(ports, {
108102
+ addonId: spec.addonId,
108103
+ initialBody: spec.initialBody
108104
+ })
108105
+ };
108106
+ }
108107
+ /** The hub and records sides of {@link registrySwitchToBodyMigration}. */
108108
+ function registrySwitchPortsOver(deps) {
108109
+ const handle = deps.records.kind({
108110
+ name: deps.kind.name,
108111
+ declaration: deps.kind.declaration,
108112
+ schema: record(string(), unknown())
108113
+ });
108114
+ return {
108115
+ listIntegrations: async (addonId) => (await deps.api.list()).filter((i) => i.addonId === addonId).map((i) => ({
108116
+ id: i.id,
108117
+ name: i.name,
108118
+ enabled: i.enabled !== false
108119
+ })),
108120
+ readBody: async (id) => (await handle.get(id))?.data ?? null,
108121
+ createRecord: async (id, body) => {
108122
+ if (await handle.get(id) !== null) return "exists";
108123
+ await handle.put({
108124
+ id,
108125
+ data: body
108126
+ }, { ifRev: 0 });
108127
+ return "created";
108128
+ },
108129
+ switchOff: async (id) => {
108130
+ await handle.patch(id, { [SWITCH_KEY]: false });
108131
+ }
108132
+ };
108133
+ }
108134
+ /**
108135
+ * Build a {@link DurableState} over a single store key. Transport-agnostic:
108136
+ * `read`/`write` are the addon-store or device-store accessors. The whole
108137
+ * validated value round-trips on every read/write — the schema is the
108138
+ * single source of truth for what is persisted, so no hand-listed field
108139
+ * set can drop a key on save.
108140
+ */
108141
+ function createDurableState(deps) {
108142
+ const get = async () => {
108143
+ const raw = (await deps.read())[deps.key];
108144
+ if (raw === void 0) return deps.fallback;
108145
+ const parsed = deps.schema.safeParse(raw);
108146
+ if (!parsed.success) {
108147
+ deps.onParseError?.(deps.key, parsed.error);
108148
+ return deps.fallback;
108149
+ }
108150
+ return parsed.data;
108151
+ };
108152
+ const set = async (next) => {
108153
+ const validated = deps.schema.parse(next);
108154
+ await deps.write({ [deps.key]: validated });
108155
+ };
108156
+ const update = async (fn) => {
108157
+ await set(fn(await get()));
108158
+ };
108159
+ return {
108160
+ get,
108161
+ set,
108162
+ update
108163
+ };
108164
+ }
108165
+ /**
108166
+ * Per-node scoping for the shared addon-settings blob.
108167
+ *
108168
+ * An addon's settings store is hub-central (the `addon-settings` cap is
108169
+ * hub-routed — the hub instance answers for every node), so fields whose
108170
+ * value is a NODE fact (decoder backend, engine pick, probed hardware
108171
+ * capabilities) persist under the node-scoped key `<key>@<nodeId>` inside
108172
+ * the single shared blob. The SCHEMA field key stays bare: the write path
108173
+ * ({@link scopePatch}) maps the bare field onto the target node's scoped
108174
+ * key; the read/hydrate path ({@link projectStore}) maps THIS node's value
108175
+ * back, so UI forms and `resolveConfig` only ever see the bare key.
108176
+ *
108177
+ * Fields opt in via the `perNode: true` schema marker on `ConfigFieldBase`
108178
+ * (`interfaces/config-ui.ts`); `BaseAddon` derives the key set from the
108179
+ * schema and routes reads/writes through these helpers.
108180
+ *
108181
+ * ## No bare-key fallback — deliberate
108182
+ *
108183
+ * {@link readNodeValue} reads the node-scoped key ONLY. A node with no
108184
+ * scoped key resolves to `undefined` so the field's schema `default` wins —
108185
+ * NEVER `store[base]` and never another node's value. A bare legacy key in
108186
+ * the store is invisible to every node, hub included, so one node's
108187
+ * selection can never leak onto another. (This generalizes the
108188
+ * `decoder-backend-keys.ts` semantics — the no-fallback variant — over an
108189
+ * arbitrary set of per-node field keys.)
108190
+ *
108191
+ * Pure functions only — no I/O, no imports beyond the language. This is a
108192
+ * LEAF module: import it via its deep path, never from the root barrel.
108193
+ */
108194
+ /**
108195
+ * Normalize a raw kernel node id to the bare node id used for scoping.
108196
+ * `localNodeId` can carry a `<node>/<addon>` suffix on forked child
108197
+ * processes; per-node settings are per-NODE, so strip the addon segment.
108198
+ * `undefined` / `null` / empty falls back to `'hub'`.
108199
+ */
108200
+ function normalizeNodeId(raw) {
108201
+ if (raw === void 0 || raw === null || raw === "") return "hub";
108202
+ const slashIdx = raw.indexOf("/");
108203
+ if (slashIdx < 0) return raw;
108204
+ const bare = raw.slice(0, slashIdx);
108205
+ return bare === "" ? "hub" : bare;
108206
+ }
108207
+ /** The node-scoped store key for a per-node field: `<base>@<nodeId>`. */
108208
+ function nodeScopedKey(base, nodeId) {
108209
+ return `${base}@${normalizeNodeId(nodeId)}`;
108210
+ }
108211
+ /**
108212
+ * Read a node's value for a per-node field from the raw shared store:
108213
+ * the node-scoped key when present, otherwise `undefined`.
108214
+ * Deliberately NO bare-key fallback (see module doc) — the caller lets the
108215
+ * schema `default` win on `undefined`.
108216
+ */
108217
+ function readNodeValue(store, base, nodeId) {
108218
+ return store[nodeScopedKey(base, nodeId)];
108219
+ }
108220
+ /**
108221
+ * Re-map a UI/settings patch so every bare perNode field persists under the
108222
+ * TARGET node's scoped key; all other keys pass through unchanged. Used on
108223
+ * the write path so a save for one node never clobbers another node's value
108224
+ * (and the bare key is never written). Returns a new object — the input
108225
+ * patch is not mutated.
108226
+ */
108227
+ function scopePatch(patch, perNodeKeys, nodeId) {
108228
+ const out = {};
108229
+ for (const [key, value] of Object.entries(patch)) out[perNodeKeys.has(key) ? nodeScopedKey(key, nodeId) : key] = value;
108230
+ return out;
108231
+ }
108232
+ /**
108233
+ * Project the raw shared store onto the bare schema keys for ONE node so a
108234
+ * UI schema (whose field keys are bare) hydrates from that node's own
108235
+ * values:
108236
+ *
108237
+ * - EVERY `@`-scoped key (any node's) is dropped from the pass-through.
108238
+ * - Every bare perNode key is dropped from the pass-through (a stray bare
108239
+ * legacy key must never hydrate any node — no bare fallback).
108240
+ * - THIS node's effective value ({@link readNodeValue}) is then laid onto
108241
+ * each bare perNode key; when the node has no scoped key the bare key is
108242
+ * left ABSENT so the field's schema `default` wins.
108243
+ *
108244
+ * Returns a new object — the input store is not mutated.
108245
+ */
108246
+ function projectStore(store, perNodeKeys, nodeId) {
108247
+ const out = {};
108248
+ for (const [key, value] of Object.entries(store)) {
108249
+ if (key.includes("@")) continue;
108250
+ if (perNodeKeys.has(key)) continue;
108251
+ out[key] = value;
108252
+ }
108253
+ for (const base of perNodeKeys) {
108254
+ const value = readNodeValue(store, base, nodeId);
108255
+ if (value !== void 0) out[base] = value;
108256
+ }
108257
+ return out;
108258
+ }
108259
+ /** Every scope, in the order the guard and the docs list them. */
108260
+ var SCOPED_SETTINGS_SCOPES = [
108261
+ "cluster",
108262
+ "device-defaults",
108263
+ "node"
108264
+ ];
107629
108265
  /** A write to a secret path could not be stored in the keychain, so it was refused. */
107630
108266
  var KeychainWriteRefusedError = class extends Error {
107631
108267
  fieldPath;
@@ -107636,7 +108272,7 @@ var KeychainWriteRefusedError = class extends Error {
107636
108272
  }
107637
108273
  };
107638
108274
  var KEEP = { kind: "keep" };
107639
- function isRecord$6(value) {
108275
+ function isRecord$4(value) {
107640
108276
  return typeof value === "object" && value !== null && !Array.isArray(value);
107641
108277
  }
107642
108278
  function defaultMintId() {
@@ -107649,7 +108285,7 @@ function collectSecretMarkerRefs(value, out = []) {
107649
108285
  return out;
107650
108286
  }
107651
108287
  if (Array.isArray(value)) for (const item of value) collectSecretMarkerRefs(item, out);
107652
- else if (isRecord$6(value)) for (const child of Object.values(value)) collectSecretMarkerRefs(child, out);
108288
+ else if (isRecord$4(value)) for (const child of Object.values(value)) collectSecretMarkerRefs(child, out);
107653
108289
  return out;
107654
108290
  }
107655
108291
  async function storedValueEquals(secrets, marker, candidate) {
@@ -107704,7 +108340,7 @@ function rowId(row, idKey) {
107704
108340
  return null;
107705
108341
  }
107706
108342
  async function writeArray(ctx, node, incoming, stored, fieldPath) {
107707
- const storedRows = Array.isArray(stored) ? stored.filter(isRecord$6) : [];
108343
+ const storedRows = Array.isArray(stored) ? stored.filter(isRecord$4) : [];
107708
108344
  if (!Array.isArray(incoming)) {
107709
108345
  ctx.deletes.push(...collectSecretMarkerRefs(storedRows));
107710
108346
  return {
@@ -107720,7 +108356,7 @@ async function writeArray(ctx, node, incoming, stored, fieldPath) {
107720
108356
  const kept = /* @__PURE__ */ new Set();
107721
108357
  const rows = [];
107722
108358
  for (const row of incoming) {
107723
- if (!isRecord$6(row)) {
108359
+ if (!isRecord$4(row)) {
107724
108360
  rows.push(row);
107725
108361
  continue;
107726
108362
  }
@@ -107745,7 +108381,7 @@ async function writeNode(ctx, node, incoming, stored, fieldPath) {
107745
108381
  case "leaf": return writeLeaf(ctx, incoming, stored, fieldPath);
107746
108382
  case "array": return writeArray(ctx, node, incoming, stored, fieldPath);
107747
108383
  case "object": {
107748
- if (!isRecord$6(incoming)) {
108384
+ if (!isRecord$4(incoming)) {
107749
108385
  if (incoming === void 0) return KEEP;
107750
108386
  ctx.deletes.push(...collectSecretMarkerRefs(stored));
107751
108387
  return {
@@ -107753,7 +108389,7 @@ async function writeNode(ctx, node, incoming, stored, fieldPath) {
107753
108389
  value: incoming
107754
108390
  };
107755
108391
  }
107756
- const storedObj = isRecord$6(stored) ? stored : {};
108392
+ const storedObj = isRecord$4(stored) ? stored : {};
107757
108393
  return {
107758
108394
  kind: "value",
107759
108395
  value: await writeMembers(ctx, node.children, incoming, storedObj, (m) => `${fieldPath}.${m}`)
@@ -107876,7 +108512,7 @@ async function resolveSecretMarkers(value, secrets, options = {}) {
107876
108512
  value: items
107877
108513
  };
107878
108514
  }
107879
- if (isRecord$6(v)) {
108515
+ if (isRecord$4(v)) {
107880
108516
  const out = {};
107881
108517
  for (const [k, child] of Object.entries(v)) {
107882
108518
  const s = substitute(child);
@@ -107908,7 +108544,7 @@ var SecretOverwriteRefusedError = class extends Error {
107908
108544
  this.name = "SecretOverwriteRefusedError";
107909
108545
  }
107910
108546
  };
107911
- function isRecord$5(value) {
108547
+ function isRecord$3(value) {
107912
108548
  return typeof value === "object" && value !== null && !Array.isArray(value);
107913
108549
  }
107914
108550
  function resolvedValue(pass, marker) {
@@ -107937,7 +108573,7 @@ function inArray(pass, incoming, stored) {
107937
108573
  return incoming.map((item, index) => {
107938
108574
  const twin = stored[index];
107939
108575
  if (isSecretMarker(twin)) return typeof item === "string" && item === resolvedValue(pass, twin) ? twin : item;
107940
- if (isRecord$5(item) && isRecord$5(twin)) return inArrayRow(pass, item, twin);
108576
+ if (isRecord$3(item) && isRecord$3(twin)) return inArrayRow(pass, item, twin);
107941
108577
  if (Array.isArray(item) && Array.isArray(twin)) return inArray(pass, item, twin);
107942
108578
  return item;
107943
108579
  });
@@ -107948,7 +108584,7 @@ function inArrayRow(pass, incoming, stored) {
107948
108584
  const twin = stored[key];
107949
108585
  if (isSecretMarker(twin)) {
107950
108586
  if (typeof value === "string" && value === resolvedValue(pass, twin)) out[key] = twin;
107951
- } else if (isRecord$5(value) && isRecord$5(twin)) out[key] = inArrayRow(pass, value, twin);
108587
+ } else if (isRecord$3(value) && isRecord$3(twin)) out[key] = inArrayRow(pass, value, twin);
107952
108588
  else if (Array.isArray(value) && Array.isArray(twin)) out[key] = inArray(pass, value, twin);
107953
108589
  }
107954
108590
  return out;
@@ -107956,7 +108592,7 @@ function inArrayRow(pass, incoming, stored) {
107956
108592
  async function walk(pass, incoming, stored) {
107957
108593
  if (isSecretMarker(stored)) return atMarker(pass, incoming, stored);
107958
108594
  if (Array.isArray(incoming) && Array.isArray(stored)) return inArray(pass, incoming, stored);
107959
- if (!isRecord$5(incoming) || !isRecord$5(stored)) return incoming;
108595
+ if (!isRecord$3(incoming) || !isRecord$3(stored)) return incoming;
107960
108596
  const out = { ...incoming };
107961
108597
  for (const [key, value] of Object.entries(incoming)) out[key] = await walk(pass, value, stored[key]);
107962
108598
  return out;
@@ -107987,7 +108623,7 @@ async function restoreUnchangedSecrets(input) {
107987
108623
  function isJsonEqual(a, b) {
107988
108624
  if (Object.is(a, b)) return true;
107989
108625
  if (Array.isArray(a)) return Array.isArray(b) && a.length === b.length && a.every((v, i) => isJsonEqual(v, b[i]));
107990
- if (isRecord$5(a) && isRecord$5(b)) {
108626
+ if (isRecord$3(a) && isRecord$3(b)) {
107991
108627
  const keys = Object.keys(a);
107992
108628
  if (keys.length !== Object.keys(b).length) return false;
107993
108629
  return keys.every((k) => Object.prototype.hasOwnProperty.call(b, k) && isJsonEqual(a[k], b[k]));
@@ -108011,7 +108647,7 @@ function markerKeysOf(blob, owner) {
108011
108647
  }
108012
108648
  function nodeFromStored(value, owner) {
108013
108649
  if (isSecretMarker(value)) return isSecretRefOwnedBy(value.$secret, owner) ? { kind: "leaf" } : null;
108014
- if (!isRecord$5(value)) return null;
108650
+ if (!isRecord$3(value)) return null;
108015
108651
  const children = /* @__PURE__ */ new Map();
108016
108652
  for (const [key, child] of Object.entries(value)) {
108017
108653
  const node = nodeFromStored(child, owner);
@@ -108508,13 +109144,48 @@ var BaseAddon = class {
108508
109144
  if (api === void 0) throw new Error(`${this.ctx.id}: the migration API is not available on this context`);
108509
109145
  return this.runBound(sets.flatMap((set) => set.bind(api)), options);
108510
109146
  }
108511
- async runBound(migrations, options) {
109147
+ /**
109148
+ * A device addon states its instance kind once, before its migrations run, and the one-switch
109149
+ * migration (registry `enabled` to the instance body, epic #440 step 3) joins whatever
109150
+ * catalogue the addon runs, in the SAME declaration (the engine replaces an owner's catalogue
109151
+ * on every declare).
109152
+ */
109153
+ declareRegistrySwitch(spec) {
109154
+ this.registrySwitchSpec = spec;
109155
+ }
109156
+ registrySwitchSpec = null;
109157
+ registrySwitchBound() {
109158
+ const spec = this.registrySwitchSpec;
109159
+ if (spec === null) return [];
109160
+ const api = this.ctx.migrationApi;
109161
+ if (api === void 0) {
109162
+ this.ctx.logger.warn("the registry switch migration is skipped: the migration API is not available on this context");
109163
+ return [];
109164
+ }
109165
+ return migrationSet([registrySwitchToBodyMigration({
109166
+ addonId: this.ctx.id,
109167
+ date: "2026-11-06",
109168
+ seq: 1e3,
109169
+ initialBody: spec.initialBody
109170
+ })], (a) => registrySwitchPortsOver({
109171
+ api: integrationRowsApiOver(a),
109172
+ records: switchRecordsOverMigrationApi(a),
109173
+ kind: spec.kind
109174
+ })).bind(api);
109175
+ }
109176
+ async runBound(declared, options) {
109177
+ const added = this.registrySwitchBound();
109178
+ const migrations = [...declared, ...added];
109179
+ const phased = options?.only === void 0 || added.length === 0 ? options : {
109180
+ ...options,
109181
+ only: [...options.only, ...added.map((m) => m.meta.id)]
109182
+ };
108512
109183
  const api = this.ctx.api.migrations;
108513
109184
  const report = await runAddonMigrations({
108514
109185
  declareOwner: (input) => api.declareOwner.mutate(input),
108515
109186
  startMigration: (input) => api.startMigration.mutate(input),
108516
109187
  finishMigration: (input) => api.finishMigration.mutate(input)
108517
- }, migrations, this.ctx.logger, options);
109188
+ }, migrations, this.ctx.logger, phased);
108518
109189
  if (report.blockOwner.length > 0) throw new AddonMigrationsBlockedError(report.blockOwner);
108519
109190
  return report;
108520
109191
  }
@@ -109587,516 +110258,6 @@ function normalizeAddonInitResult(result) {
109587
110258
  if (Array.isArray(result)) return { providers: result };
109588
110259
  return result;
109589
110260
  }
109590
- var PREFIX = "records/";
109591
- /** The base of every records failure. `detail` is the human part of the message. */
109592
- var RecordsError = class extends Error {
109593
- code;
109594
- detail;
109595
- constructor(code, detail) {
109596
- super(`${PREFIX}${code}: ${detail}`);
109597
- this.name = "RecordsError";
109598
- this.code = code;
109599
- this.detail = detail;
109600
- }
109601
- };
109602
- /** A write guarded by `ifRev` found another revision (or an existing row for `ifRev: 0`). */
109603
- var RevConflictError = class extends RecordsError {
109604
- constructor(detail) {
109605
- super("rev-conflict", detail);
109606
- this.name = "RevConflictError";
109607
- }
109608
- };
109609
- /** The keychain could not store or serve a value: explicit, never an empty string. */
109610
- var RecordSecretUnavailableError = class extends RecordsError {
109611
- constructor(detail) {
109612
- super("secret-unavailable", detail);
109613
- this.name = "RecordSecretUnavailableError";
109614
- }
109615
- };
109616
- var InvalidRecordError = class extends RecordsError {
109617
- constructor(detail) {
109618
- super("invalid-record", detail);
109619
- this.name = "InvalidRecordError";
109620
- }
109621
- };
109622
- /** A kind declaration the engine refuses (non-additive change, bad shape, wrong file). */
109623
- var DeclarationRefusedError = class extends RecordsError {
109624
- constructor(detail) {
109625
- super("declaration-refused", detail);
109626
- this.name = "DeclarationRefusedError";
109627
- }
109628
- };
109629
- /** Limits and names of `ctx.records` (D881). One authority; the engine and the facade read it. */
109630
- /** The files a kind may live in. `history` is device-history's (D850), never records. */
109631
- var RECORD_DATABASES = ["settings", "events"];
109632
- /** The classes of a kind: the `@durable` vocabulary, one authority (replaces the annotation). */
109633
- var RECORD_CLASSES = [
109634
- "config",
109635
- "ledger",
109636
- "audit",
109637
- "mirror",
109638
- "ephemeral"
109639
- ];
109640
- var RECORD_DEFAULT_MAX_DATA_BYTES = 64 * 1024;
109641
- var RECORD_MAX_DATA_BYTES = 1024 * 1024;
109642
- var RECORD_BATCH_MAX = 1e3;
109643
- var RECORD_QUERY_MAX = 1e3;
109644
- /** A kind in the `settings` file may not bound itself above this (D447: high volume is `events`). */
109645
- var RECORD_SETTINGS_MAX_ROWS = 5e4;
109646
- /** The `Column`-free proof prefix: a ref collection for a kind's secret fields. */
109647
- var RECORD_SECRET_COLLECTION_PREFIX = "records:";
109648
- /**
109649
- * Secret fields of a record, addressed the way a Zod schema declares them
109650
- * (`collectZodSecretPaths`): dotted keys, `[]` for "each element of this array"
109651
- * (`auth.accessToken`, `headers[].value`).
109652
- *
109653
- * `{}` after a key means "each value of this map" (`applianceSecrets{}`): the map's own key
109654
- * names the value (`applianceSecrets{fridge}`), so no id key is declared and a body that drops a
109655
- * key releases exactly that key's secret.
109656
- *
109657
- * Array elements are matched by a DECLARED id key (`secretArrayKeys`:
109658
- * `{ headers: 'name' }`), never by index, so reordering a list keeps every
109659
- * keychain ref (the same rule as `arrayItemFieldPath`). The concrete path of a
109660
- * leaf names its element: `headers[X-Api].value`.
109661
- *
109662
- * Pure and browser-safe. Nothing here mutates: every transform returns a new value.
109663
- */
109664
- /** The array prefixes (declared form, e.g. `headers` or `a.headers`) of a path. */
109665
- function parseSecretPath(path) {
109666
- if (path.length === 0) throw new InvalidRecordError("an empty secret path");
109667
- return path.split(".").map((raw) => {
109668
- const each = raw.endsWith("[]");
109669
- const map = raw.endsWith("{}");
109670
- const key = each || map ? raw.slice(0, -2) : raw;
109671
- if (key.length === 0) throw new InvalidRecordError(`secret path "${path}" has an empty segment`);
109672
- return {
109673
- key,
109674
- each,
109675
- map
109676
- };
109677
- });
109678
- }
109679
- /** The declared array prefixes of `path` that need an id key (`headers`, `a.rows`). */
109680
- function secretArrayPrefixes(path) {
109681
- const segments = parseSecretPath(path);
109682
- const prefixes = [];
109683
- const walked = [];
109684
- for (const segment of segments) {
109685
- walked.push(segment.key);
109686
- if (segment.each) prefixes.push(walked.join("."));
109687
- }
109688
- return prefixes;
109689
- }
109690
- function isRecord$4(value) {
109691
- return typeof value === "object" && value !== null && !Array.isArray(value);
109692
- }
109693
- function elementId(element, idKey, declared, prefix) {
109694
- const id = isRecord$4(element) ? element[idKey] : void 0;
109695
- 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`);
109696
- return id;
109697
- }
109698
- /**
109699
- * Visit every secret leaf PRESENT in `data` (an absent branch has nothing to
109700
- * visit). `replace` returns the new leaf value, or {@link REMOVE_LEAF}; the
109701
- * result is a new body, `data` is untouched.
109702
- */
109703
- var REMOVE_LEAF = Symbol("remove-leaf");
109704
- function mapAt(node, segments, index, walkedKeys, concretePrefix, declared, arrayKeys, visit) {
109705
- if (!isRecord$4(node)) return node;
109706
- const segment = segments[index];
109707
- if (segment === void 0) return node;
109708
- if (!Object.prototype.hasOwnProperty.call(node, segment.key)) return node;
109709
- const child = node[segment.key];
109710
- const keys = [...walkedKeys, segment.key];
109711
- const last = index === segments.length - 1;
109712
- if (segment.each) {
109713
- if (!Array.isArray(child)) return node;
109714
- const prefix = keys.join(".");
109715
- const idKey = arrayKeys[prefix];
109716
- if (idKey === void 0) throw new InvalidRecordError(`"${declared}": no id key declared for the array "${prefix}"`);
109717
- const mapped = child.map((element) => {
109718
- const id = elementId(element, idKey, declared, prefix);
109719
- const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}[${encodeURIComponent(id)}]`;
109720
- return last ? element : mapAt(element, segments, index + 1, keys, concrete, declared, arrayKeys, visit);
109721
- });
109722
- return {
109723
- ...node,
109724
- [segment.key]: mapped
109725
- };
109726
- }
109727
- if (segment.map) {
109728
- if (!isRecord$4(child)) return node;
109729
- const kept = Object.entries(child).map(([mapKey, value]) => {
109730
- const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}{${encodeURIComponent(mapKey)}}`;
109731
- if (!last) return [mapKey, mapAt(value, segments, index + 1, keys, concrete, declared, arrayKeys, visit)];
109732
- return [mapKey, visit({
109733
- declared,
109734
- concrete,
109735
- value
109736
- })];
109737
- }).filter(([, value]) => value !== REMOVE_LEAF);
109738
- return {
109739
- ...node,
109740
- [segment.key]: Object.fromEntries(kept)
109741
- };
109742
- }
109743
- const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}`;
109744
- if (last) {
109745
- const replacement = visit({
109746
- declared,
109747
- concrete,
109748
- value: child
109749
- });
109750
- if (replacement === REMOVE_LEAF) return Object.fromEntries(Object.entries(node).filter(([key]) => key !== segment.key));
109751
- return {
109752
- ...node,
109753
- [segment.key]: replacement
109754
- };
109755
- }
109756
- return {
109757
- ...node,
109758
- [segment.key]: mapAt(child, segments, index + 1, keys, concrete, declared, arrayKeys, visit)
109759
- };
109760
- }
109761
- /** Replace/remove every present secret leaf; returns a NEW body. */
109762
- function mapSecretLeaves(data, paths, arrayKeys, visit) {
109763
- let current = data;
109764
- for (const declared of paths) current = mapAt(current, parseSecretPath(declared), 0, [], "", declared, arrayKeys, visit);
109765
- return current;
109766
- }
109767
- /** Every present secret leaf, read-only. */
109768
- function collectSecretLeaves(data, paths, arrayKeys) {
109769
- const found = [];
109770
- mapSecretLeaves(data, paths, arrayKeys, (leaf) => {
109771
- found.push(leaf);
109772
- return leaf.value;
109773
- });
109774
- return found;
109775
- }
109776
- /**
109777
- * The keychain collection name a kind's secrets live under. Prefixed so a
109778
- * record's refs never collide with the refs a legacy collection of the same name
109779
- * already holds during an adoption.
109780
- */
109781
- function recordSecretCollection(kind) {
109782
- return `${RECORD_SECRET_COLLECTION_PREFIX}${kind}`;
109783
- }
109784
- /** The ONE ref a row's secret field may carry: the engine and the facade both build it here. */
109785
- function recordSecretRef(owner, kind, rowId, concretePath) {
109786
- return buildSecretRef({
109787
- owner,
109788
- scope: {
109789
- kind: "row",
109790
- collection: recordSecretCollection(kind),
109791
- rowId
109792
- },
109793
- fieldPath: concretePath
109794
- });
109795
- }
109796
- /**
109797
- * A stored secret, as an admin read shows it: a VIEW naming the row's own
109798
- * keychain ref (`set: true`), never the value and no longer the bare redaction
109799
- * token. The form hands it to the secret field, which reveals the value by ref
109800
- * through the audited `keychain-admin.reveal`; sent back untouched it keeps the
109801
- * stored secret (the records door reads a view as KEEP).
109802
- *
109803
- * ONE implementation for the entries service and for every addon that serves
109804
- * its own instances (`RecordIntegrationInstances`).
109805
- */
109806
- function isRecord$3(value) {
109807
- return typeof value === "object" && value !== null && !Array.isArray(value);
109808
- }
109809
- function secretViewsOf(owner, kind, id, decl, data) {
109810
- if (decl.secretPaths.length === 0) return data;
109811
- const shown = mapSecretLeaves(data, decl.secretPaths, decl.secretArrayKeys, (leaf) => {
109812
- if (leaf.value !== "__camstack_redacted__") return leaf.value;
109813
- return {
109814
- $secret: recordSecretRef(owner, kind, id, leaf.concrete),
109815
- v: 1,
109816
- set: true
109817
- };
109818
- });
109819
- return isRecord$3(shown) ? shown : data;
109820
- }
109821
- /**
109822
- * The share-view scope kinds a share-link token can carry. The hub mints
109823
- * and validates them (`ShareViewGrantSchema` builds its
109824
- * enum from this list); a data plane names the kinds it ACCEPTS in `share`.
109825
- */
109826
- var SHARE_VIEW_KINDS = ["grid-view", "events-view"];
109827
- /** The wire shape of {@link PeerBytesTicket} — see the type for what it is. */
109828
- var PeerBytesTicketSchema = object({
109829
- /** `http://127.0.0.1:<port>/<token>`. One `GET` takes it. */
109830
- url: string().min(1),
109831
- /**
109832
- * The HOST node this URL means something on — the hub or a named agent,
109833
- * never a runner. {@link AddonPeerBytes.open} compares it to its own and
109834
- * refuses `cross-node` by name when they differ, without dialling.
109835
- */
109836
- hostNodeId: string().min(1),
109837
- expiresAtMs: number().int().nonnegative(),
109838
- /**
109839
- * What the producer DECLARED the body to be, when it knows — `null` when it
109840
- * does not. Never `0` for unknown (D393): a consumer sizing a bound off this
109841
- * must be able to tell "the producer did not say" from "the body is empty".
109842
- */
109843
- declaredBytes: number().int().nonnegative().nullable()
109844
- });
109845
- function defOf(schema) {
109846
- const zodBag = Reflect.get(schema, "_zod");
109847
- if (typeof zodBag !== "object" || zodBag === null) return {};
109848
- const def = Reflect.get(zodBag, "def");
109849
- if (typeof def !== "object" || def === null) return {};
109850
- return def;
109851
- }
109852
- function declaredHere(schema) {
109853
- return globalRegistry.get(schema)?.secret === true;
109854
- }
109855
- /** Wrapper kinds whose `innerType` is the field itself. */
109856
- var WRAPPERS = new Set([
109857
- "optional",
109858
- "nullable",
109859
- "default",
109860
- "prefault",
109861
- "catch",
109862
- "readonly",
109863
- "nonoptional"
109864
- ]);
109865
- /**
109866
- * The schema layers that make up ONE field: the schema itself and every
109867
- * wrapper below it (optional / default / nullable / readonly / catch), plus
109868
- * both sides of a pipe (`z.preprocess` puts the real schema on `out`,
109869
- * `.transform` on `in`).
109870
- */
109871
- function layersOf(schema) {
109872
- const out = [];
109873
- const queue = [schema];
109874
- while (queue.length > 0) {
109875
- const s = queue.shift();
109876
- if (!s || out.includes(s)) continue;
109877
- out.push(s);
109878
- const def = defOf(s);
109879
- if (def.type !== void 0 && WRAPPERS.has(def.type) && def.innerType) queue.push(def.innerType);
109880
- if (def.type === "pipe") {
109881
- if (def.in) queue.push(def.in);
109882
- if (def.out) queue.push(def.out);
109883
- }
109884
- }
109885
- return out;
109886
- }
109887
- /** True when any layer of this field declares `.meta({ secret: true })`. */
109888
- function isZodSecret(schema) {
109889
- return layersOf(schema).some(declaredHere);
109890
- }
109891
- /**
109892
- * Every declared secret path in a config schema: dotted keys, `[]` for "each
109893
- * element of this array" (`connection.password`, `rows[].token`), `{}` for "each value of this
109894
- * map" (`applianceSecrets{}`). A declared
109895
- * object or array is reported as one path and not descended into — everything
109896
- * under it is secret.
109897
- */
109898
- function collectZodSecretPaths(schema, prefix = "") {
109899
- if (isZodSecret(schema)) return prefix.length > 0 ? [prefix] : [];
109900
- const paths = [];
109901
- for (const layer of layersOf(schema)) {
109902
- const def = defOf(layer);
109903
- if (def.type === "object" && def.shape) for (const [key, child] of Object.entries(def.shape)) paths.push(...collectZodSecretPaths(child, prefix ? `${prefix}.${key}` : key));
109904
- else if (def.type === "array" && def.element) paths.push(...collectZodSecretPaths(def.element, `${prefix}[]`));
109905
- else if (def.type === "record" && def.valueType) paths.push(...collectZodSecretPaths(def.valueType, `${prefix}{}`));
109906
- else if (def.type === "union" && def.options) for (const option of def.options) paths.push(...collectZodSecretPaths(option, prefix));
109907
- else if (def.type === "intersection") {
109908
- if (def.left) paths.push(...collectZodSecretPaths(def.left, prefix));
109909
- if (def.right) paths.push(...collectZodSecretPaths(def.right, prefix));
109910
- }
109911
- }
109912
- return [...new Set(paths)];
109913
- }
109914
- /**
109915
- * Record kinds (D881): the declaration an addon makes of one kind of fact, the
109916
- * Zod row schema that describes it, and the helper that turns the two into the
109917
- * JSON the engine stores.
109918
- *
109919
- * A kind is declared ONCE, next to the code that owns it, and the engine's
109920
- * reconciler creates its indexes - nothing creates DDL at runtime from a write.
109921
- * Everything the generic machinery needs (secret fields, the entry descriptor)
109922
- * is DERIVED from the Zod schema: `.meta({ secret: true })` marks a credential,
109923
- * never a field name (D879).
109924
- */
109925
- /** A JSON field path: `trackId`, `auth.accessToken`. Charset-restricted: it is rendered into DDL. */
109926
- var RecordFieldPathSchema = string().regex(/^[A-Za-z_][A-Za-z0-9_]{0,63}(\.[A-Za-z_][A-Za-z0-9_]{0,63}){0,3}$/);
109927
- var RecordIndexSchema = object({
109928
- name: string().regex(/^[a-z][a-z0-9_]{0,31}$/),
109929
- fields: array(RecordFieldPathSchema).min(1).max(4),
109930
- unique: boolean().optional()
109931
- }).strict();
109932
- var RecordRetentionSchema = union([
109933
- object({
109934
- ttlMs: number().int().positive(),
109935
- from: _enum(["at", "write"])
109936
- }).strict(),
109937
- object({
109938
- maxRows: number().int().positive().optional(),
109939
- maxRowsPerDevice: number().int().positive().optional()
109940
- }).strict().refine((r) => r.maxRows !== void 0 || r.maxRowsPerDevice !== void 0, { message: "name maxRows, maxRowsPerDevice or both" }),
109941
- object({
109942
- owner: string().min(1),
109943
- reason: string().min(1)
109944
- }).strict(),
109945
- object({ none: string().min(1) }).strict()
109946
- ]);
109947
- /** The descriptor a generic entries UI reads (D881 "generic entries"). */
109948
- var EntryDescriptorSchema = object({
109949
- title: string().min(1),
109950
- /** The record body field shown as the entry's name. */
109951
- nameField: string().min(1),
109952
- /** JSON Schema of the entry body; `secret: true` marks a password field. */
109953
- fields: record(string(), unknown())
109954
- }).strict();
109955
- /** What crosses the wire from an addon: JSON only, no Zod. An unknown key is refused. */
109956
- var RecordKindDeclarationSchema = object({
109957
- database: _enum(RECORD_DATABASES).default("settings"),
109958
- class: _enum(RECORD_CLASSES),
109959
- writeTrigger: string().min(1),
109960
- device: _enum([
109961
- "required",
109962
- "optional",
109963
- "none"
109964
- ]).default("none"),
109965
- at: _enum(["required", "none"]).default("none"),
109966
- indexes: array(RecordIndexSchema).max(8).default([]),
109967
- retention: RecordRetentionSchema,
109968
- deviceRemoval: _enum(["delete", "none"]).default("none"),
109969
- maxDataBytes: number().int().positive().max(RECORD_MAX_DATA_BYTES).default(RECORD_DEFAULT_MAX_DATA_BYTES),
109970
- /** Derived from the Zod schema; never written by hand. */
109971
- secretPaths: array(string().min(1)).default([]),
109972
- /** The id key of each array that carries a secret (`{ headers: 'name' }`). */
109973
- secretArrayKeys: record(string(), string()).default({}),
109974
- /** Kinds that must agree through `transact` sit in one file under one family name. */
109975
- transactFamily: string().min(1).optional(),
109976
- entry: EntryDescriptorSchema.optional()
109977
- }).strict();
109978
- /** The kind names: lower-case, dash separated, short enough for an index name. */
109979
- var RecordKindNameSchema = string().regex(/^[a-z][a-z0-9-]{0,47}$/);
109980
- /** Cross-field rules a declaration must satisfy. Throws {@link DeclarationRefusedError}. */
109981
- function assertValidDeclaration(name, decl) {
109982
- const refuse = (why) => {
109983
- throw new DeclarationRefusedError(`kind "${name}": ${why}`);
109984
- };
109985
- if (!RecordKindNameSchema.safeParse(name).success) refuse("the name must be lower-case-dashed");
109986
- const seen = /* @__PURE__ */ new Set();
109987
- for (const index of decl.indexes) {
109988
- if (seen.has(index.name)) refuse(`index name "${index.name}" is declared twice`);
109989
- seen.add(index.name);
109990
- }
109991
- const { retention } = decl;
109992
- const hasSecrets = decl.secretPaths.length > 0;
109993
- if ("ttlMs" in retention) {
109994
- if (retention.from === "at" && decl.at !== "required") refuse("a ttl from \"at\" needs at: \"required\"");
109995
- if (hasSecrets) refuse("a kind with secret fields cannot use engine TTL (its keychain values would be orphaned)");
109996
- }
109997
- if ("maxRows" in retention || "maxRowsPerDevice" in retention) {
109998
- if (retention.maxRowsPerDevice !== void 0 && decl.device !== "required") refuse("maxRowsPerDevice needs device: \"required\"");
109999
- if (decl.at !== "required") refuse("a row bound trims the oldest \"at\": it needs at: \"required\"");
110000
- if (hasSecrets) refuse("a kind with secret fields cannot use an engine row bound");
110001
- const bound = Math.max(retention.maxRows ?? 0, retention.maxRowsPerDevice ?? 0);
110002
- if (decl.database === "settings" && bound > 5e4) refuse(`a row bound above ${RECORD_SETTINGS_MAX_ROWS} belongs in database: "events" (a big delete on the settings thread stalls every configuration read)`);
110003
- }
110004
- if (decl.deviceRemoval === "delete" && decl.device === "none") refuse("deviceRemoval: \"delete\" needs a device: \"required\" or \"optional\"");
110005
- for (const path of decl.secretPaths) for (const prefix of secretArrayPrefixes(path)) if (decl.secretArrayKeys[prefix] === void 0) refuse(`secret path "${path}" crosses the array "${prefix}": declare its id key in secretArrayKeys`);
110006
- }
110007
- function bodyFieldsOf(schema) {
110008
- return { ...toJSONSchema(schema, {
110009
- unrepresentable: "any",
110010
- io: "input"
110011
- }) };
110012
- }
110013
- function isRecordLike(value) {
110014
- return typeof value === "object" && value !== null && !Array.isArray(value);
110015
- }
110016
- /** Does every branch of the body schema carry `field`? (A discriminated union has several.) */
110017
- function hasNameField(json, field) {
110018
- const branches = json["oneOf"] ?? json["anyOf"];
110019
- if (Array.isArray(branches)) return branches.length > 0 && branches.every((b) => isRecordLike(b) && hasNameField(b, field));
110020
- const properties = json["properties"];
110021
- return isRecordLike(properties) && Object.prototype.hasOwnProperty.call(properties, field);
110022
- }
110023
- /**
110024
- * Declare the kinds of a package. The keys are the kind names. The result is
110025
- * what `ctx.records.declare` sends to the engine and what `ctx.records.kind`
110026
- * types its handle from.
110027
- */
110028
- function defineRecordKinds(specs) {
110029
- const out = {};
110030
- for (const [name, spec] of Object.entries(specs)) {
110031
- const secretPaths = collectZodSecretPaths(spec.schema);
110032
- const nameField = spec.entry?.nameField ?? "name";
110033
- const fields = bodyFieldsOf(spec.schema);
110034
- if (spec.entry !== void 0 && !hasNameField(fields, nameField)) throw new DeclarationRefusedError(`kind "${name}": an entry kind's schema needs a "${nameField}" field`);
110035
- const parsed = RecordKindDeclarationSchema.parse({
110036
- database: spec.database,
110037
- class: spec.class,
110038
- writeTrigger: spec.writeTrigger,
110039
- device: spec.device,
110040
- at: spec.at,
110041
- indexes: spec.indexes === void 0 ? void 0 : [...spec.indexes],
110042
- retention: spec.retention,
110043
- deviceRemoval: spec.deviceRemoval,
110044
- maxDataBytes: spec.maxDataBytes,
110045
- secretPaths: [...new Set([...secretPaths, ...spec.retiredSecretPaths ?? []])],
110046
- secretArrayKeys: spec.secretArrayKeys === void 0 ? void 0 : { ...spec.secretArrayKeys },
110047
- transactFamily: spec.transactFamily,
110048
- entry: spec.entry === void 0 ? void 0 : {
110049
- title: spec.entry.title,
110050
- nameField,
110051
- fields
110052
- }
110053
- });
110054
- assertValidDeclaration(name, parsed);
110055
- out[name] = {
110056
- name,
110057
- schema: spec.schema,
110058
- declaration: parsed
110059
- };
110060
- }
110061
- return out;
110062
- }
110063
- /**
110064
- * Entry kinds (D881): every list of user-created entries (notification
110065
- * targets, brokers, LLM profiles) is ONE record kind with an id, a name and a
110066
- * kind-specific body, and the admin UI lists/adds/edits/deletes all of them
110067
- * through the `record-entries` capability with password fields derived from
110068
- * the schema (`.meta({ secret: true })`).
110069
- */
110070
- /** The body of a plain entry: a name and the fields the kind adds. */
110071
- function entryBody(shape) {
110072
- return object({
110073
- name: string().min(1),
110074
- ...shape
110075
- });
110076
- }
110077
- /**
110078
- * Declare one entry kind. An entry is configuration: never trimmed by the
110079
- * engine, never aged, belonging to no device.
110080
- */
110081
- function defineEntryKind(name, spec) {
110082
- const defined = defineRecordKinds({ [name]: {
110083
- schema: spec.schema,
110084
- class: "config",
110085
- writeTrigger: spec.writeTrigger ?? "an operator adds or edits an entry in the entries UI",
110086
- retention: { none: "an entry goes only when the operator deletes it" },
110087
- ...spec.maxDataBytes === void 0 ? {} : { maxDataBytes: spec.maxDataBytes },
110088
- ...spec.database === void 0 ? {} : { database: spec.database },
110089
- ...spec.indexes === void 0 ? {} : { indexes: spec.indexes },
110090
- ...spec.secretArrayKeys === void 0 ? {} : { secretArrayKeys: spec.secretArrayKeys },
110091
- ...spec.retiredSecretPaths === void 0 ? {} : { retiredSecretPaths: spec.retiredSecretPaths },
110092
- entry: {
110093
- title: spec.title,
110094
- ...spec.nameField === void 0 ? {} : { nameField: spec.nameField }
110095
- }
110096
- } })[name];
110097
- if (defined === void 0) throw new DeclarationRefusedError(`entry kind "${name}" was not built`);
110098
- return defined;
110099
- }
110100
110261
  object({
110101
110262
  field: string().min(1),
110102
110263
  on: literal("advance")
@@ -110189,6 +110350,286 @@ function optionalMethod(input, output, options) {
110189
110350
  function event(data) {
110190
110351
  return { data };
110191
110352
  }
110353
+ function defOf(schema) {
110354
+ const zodBag = Reflect.get(schema, "_zod");
110355
+ if (typeof zodBag !== "object" || zodBag === null) return {};
110356
+ const def = Reflect.get(zodBag, "def");
110357
+ if (typeof def !== "object" || def === null) return {};
110358
+ return def;
110359
+ }
110360
+ function declaredHere(schema) {
110361
+ return globalRegistry.get(schema)?.secret === true;
110362
+ }
110363
+ /** Wrapper kinds whose `innerType` is the field itself. */
110364
+ var WRAPPERS = new Set([
110365
+ "optional",
110366
+ "nullable",
110367
+ "default",
110368
+ "prefault",
110369
+ "catch",
110370
+ "readonly",
110371
+ "nonoptional"
110372
+ ]);
110373
+ /**
110374
+ * The schema layers that make up ONE field: the schema itself and every
110375
+ * wrapper below it (optional / default / nullable / readonly / catch), plus
110376
+ * both sides of a pipe (`z.preprocess` puts the real schema on `out`,
110377
+ * `.transform` on `in`).
110378
+ */
110379
+ function layersOf(schema) {
110380
+ const out = [];
110381
+ const queue = [schema];
110382
+ while (queue.length > 0) {
110383
+ const s = queue.shift();
110384
+ if (!s || out.includes(s)) continue;
110385
+ out.push(s);
110386
+ const def = defOf(s);
110387
+ if (def.type !== void 0 && WRAPPERS.has(def.type) && def.innerType) queue.push(def.innerType);
110388
+ if (def.type === "pipe") {
110389
+ if (def.in) queue.push(def.in);
110390
+ if (def.out) queue.push(def.out);
110391
+ }
110392
+ }
110393
+ return out;
110394
+ }
110395
+ /** True when any layer of this field declares `.meta({ secret: true })`. */
110396
+ function isZodSecret(schema) {
110397
+ return layersOf(schema).some(declaredHere);
110398
+ }
110399
+ /**
110400
+ * Every declared secret path in a config schema: dotted keys, `[]` for "each
110401
+ * element of this array" (`connection.password`, `rows[].token`), `{}` for "each value of this
110402
+ * map" (`applianceSecrets{}`). A declared
110403
+ * object or array is reported as one path and not descended into — everything
110404
+ * under it is secret.
110405
+ */
110406
+ function collectZodSecretPaths(schema, prefix = "") {
110407
+ if (isZodSecret(schema)) return prefix.length > 0 ? [prefix] : [];
110408
+ const paths = [];
110409
+ for (const layer of layersOf(schema)) {
110410
+ const def = defOf(layer);
110411
+ if (def.type === "object" && def.shape) for (const [key, child] of Object.entries(def.shape)) paths.push(...collectZodSecretPaths(child, prefix ? `${prefix}.${key}` : key));
110412
+ else if (def.type === "array" && def.element) paths.push(...collectZodSecretPaths(def.element, `${prefix}[]`));
110413
+ else if (def.type === "record" && def.valueType) paths.push(...collectZodSecretPaths(def.valueType, `${prefix}{}`));
110414
+ else if (def.type === "union" && def.options) for (const option of def.options) paths.push(...collectZodSecretPaths(option, prefix));
110415
+ else if (def.type === "intersection") {
110416
+ if (def.left) paths.push(...collectZodSecretPaths(def.left, prefix));
110417
+ if (def.right) paths.push(...collectZodSecretPaths(def.right, prefix));
110418
+ }
110419
+ }
110420
+ return [...new Set(paths)];
110421
+ }
110422
+ /**
110423
+ * Record kinds (D881): the declaration an addon makes of one kind of fact, the
110424
+ * Zod row schema that describes it, and the helper that turns the two into the
110425
+ * JSON the engine stores.
110426
+ *
110427
+ * A kind is declared ONCE, next to the code that owns it, and the engine's
110428
+ * reconciler creates its indexes - nothing creates DDL at runtime from a write.
110429
+ * Everything the generic machinery needs (secret fields, the entry descriptor)
110430
+ * is DERIVED from the Zod schema: `.meta({ secret: true })` marks a credential,
110431
+ * never a field name (D879).
110432
+ */
110433
+ /** A JSON field path: `trackId`, `auth.accessToken`. Charset-restricted: it is rendered into DDL. */
110434
+ var RecordFieldPathSchema = string().regex(/^[A-Za-z_][A-Za-z0-9_]{0,63}(\.[A-Za-z_][A-Za-z0-9_]{0,63}){0,3}$/);
110435
+ var RecordIndexSchema = object({
110436
+ name: string().regex(/^[a-z][a-z0-9_]{0,31}$/),
110437
+ fields: array(RecordFieldPathSchema).min(1).max(4),
110438
+ unique: boolean().optional()
110439
+ }).strict();
110440
+ var RecordRetentionSchema = union([
110441
+ object({
110442
+ ttlMs: number().int().positive(),
110443
+ from: _enum(["at", "write"])
110444
+ }).strict(),
110445
+ object({
110446
+ maxRows: number().int().positive().optional(),
110447
+ maxRowsPerDevice: number().int().positive().optional()
110448
+ }).strict().refine((r) => r.maxRows !== void 0 || r.maxRowsPerDevice !== void 0, { message: "name maxRows, maxRowsPerDevice or both" }),
110449
+ object({
110450
+ owner: string().min(1),
110451
+ reason: string().min(1)
110452
+ }).strict(),
110453
+ object({ none: string().min(1) }).strict()
110454
+ ]);
110455
+ /** The descriptor a generic entries UI reads (D881 "generic entries"). */
110456
+ var EntryDescriptorSchema = object({
110457
+ title: string().min(1),
110458
+ /** The record body field shown as the entry's name. */
110459
+ nameField: string().min(1),
110460
+ /** JSON Schema of the entry body; `secret: true` marks a password field. */
110461
+ fields: record(string(), unknown())
110462
+ }).strict();
110463
+ /** What crosses the wire from an addon: JSON only, no Zod. An unknown key is refused. */
110464
+ var RecordKindDeclarationSchema = object({
110465
+ database: _enum(RECORD_DATABASES).default("settings"),
110466
+ class: _enum(RECORD_CLASSES),
110467
+ writeTrigger: string().min(1),
110468
+ device: _enum([
110469
+ "required",
110470
+ "optional",
110471
+ "none"
110472
+ ]).default("none"),
110473
+ at: _enum(["required", "none"]).default("none"),
110474
+ indexes: array(RecordIndexSchema).max(8).default([]),
110475
+ retention: RecordRetentionSchema,
110476
+ deviceRemoval: _enum(["delete", "none"]).default("none"),
110477
+ maxDataBytes: number().int().positive().max(RECORD_MAX_DATA_BYTES).default(RECORD_DEFAULT_MAX_DATA_BYTES),
110478
+ /** Derived from the Zod schema; never written by hand. */
110479
+ secretPaths: array(string().min(1)).default([]),
110480
+ /** The id key of each array that carries a secret (`{ headers: 'name' }`). */
110481
+ secretArrayKeys: record(string(), string()).default({}),
110482
+ /** Kinds that must agree through `transact` sit in one file under one family name. */
110483
+ transactFamily: string().min(1).optional(),
110484
+ entry: EntryDescriptorSchema.optional()
110485
+ }).strict();
110486
+ /** The kind names: lower-case, dash separated, short enough for an index name. */
110487
+ var RecordKindNameSchema = string().regex(/^[a-z][a-z0-9-]{0,47}$/);
110488
+ /** Cross-field rules a declaration must satisfy. Throws {@link DeclarationRefusedError}. */
110489
+ function assertValidDeclaration(name, decl) {
110490
+ const refuse = (why) => {
110491
+ throw new DeclarationRefusedError(`kind "${name}": ${why}`);
110492
+ };
110493
+ if (!RecordKindNameSchema.safeParse(name).success) refuse("the name must be lower-case-dashed");
110494
+ const seen = /* @__PURE__ */ new Set();
110495
+ for (const index of decl.indexes) {
110496
+ if (seen.has(index.name)) refuse(`index name "${index.name}" is declared twice`);
110497
+ seen.add(index.name);
110498
+ }
110499
+ const { retention } = decl;
110500
+ const hasSecrets = decl.secretPaths.length > 0;
110501
+ if ("ttlMs" in retention) {
110502
+ if (retention.from === "at" && decl.at !== "required") refuse("a ttl from \"at\" needs at: \"required\"");
110503
+ if (hasSecrets) refuse("a kind with secret fields cannot use engine TTL (its keychain values would be orphaned)");
110504
+ }
110505
+ if ("maxRows" in retention || "maxRowsPerDevice" in retention) {
110506
+ if (retention.maxRowsPerDevice !== void 0 && decl.device !== "required") refuse("maxRowsPerDevice needs device: \"required\"");
110507
+ if (decl.at !== "required") refuse("a row bound trims the oldest \"at\": it needs at: \"required\"");
110508
+ if (hasSecrets) refuse("a kind with secret fields cannot use an engine row bound");
110509
+ const bound = Math.max(retention.maxRows ?? 0, retention.maxRowsPerDevice ?? 0);
110510
+ if (decl.database === "settings" && bound > 5e4) refuse(`a row bound above ${RECORD_SETTINGS_MAX_ROWS} belongs in database: "events" (a big delete on the settings thread stalls every configuration read)`);
110511
+ }
110512
+ if (decl.deviceRemoval === "delete" && decl.device === "none") refuse("deviceRemoval: \"delete\" needs a device: \"required\" or \"optional\"");
110513
+ for (const path of decl.secretPaths) for (const prefix of secretArrayPrefixes(path)) if (decl.secretArrayKeys[prefix] === void 0) refuse(`secret path "${path}" crosses the array "${prefix}": declare its id key in secretArrayKeys`);
110514
+ }
110515
+ function bodyFieldsOf(schema) {
110516
+ return { ...toJSONSchema(schema, {
110517
+ unrepresentable: "any",
110518
+ io: "input"
110519
+ }) };
110520
+ }
110521
+ function isRecordLike(value) {
110522
+ return typeof value === "object" && value !== null && !Array.isArray(value);
110523
+ }
110524
+ /** Does every branch of the body schema carry `field`? (A discriminated union has several.) */
110525
+ function hasNameField(json, field) {
110526
+ const branches = json["oneOf"] ?? json["anyOf"];
110527
+ if (Array.isArray(branches)) return branches.length > 0 && branches.every((b) => isRecordLike(b) && hasNameField(b, field));
110528
+ const properties = json["properties"];
110529
+ return isRecordLike(properties) && Object.prototype.hasOwnProperty.call(properties, field);
110530
+ }
110531
+ /**
110532
+ * Declare the kinds of a package. The keys are the kind names. The result is
110533
+ * what `ctx.records.declare` sends to the engine and what `ctx.records.kind`
110534
+ * types its handle from.
110535
+ */
110536
+ function defineRecordKinds(specs) {
110537
+ const out = {};
110538
+ for (const [name, spec] of Object.entries(specs)) {
110539
+ const secretPaths = collectZodSecretPaths(spec.schema);
110540
+ const nameField = spec.entry?.nameField ?? "name";
110541
+ const fields = bodyFieldsOf(spec.schema);
110542
+ if (spec.entry !== void 0 && !hasNameField(fields, nameField)) throw new DeclarationRefusedError(`kind "${name}": an entry kind's schema needs a "${nameField}" field`);
110543
+ const parsed = RecordKindDeclarationSchema.parse({
110544
+ database: spec.database,
110545
+ class: spec.class,
110546
+ writeTrigger: spec.writeTrigger,
110547
+ device: spec.device,
110548
+ at: spec.at,
110549
+ indexes: spec.indexes === void 0 ? void 0 : [...spec.indexes],
110550
+ retention: spec.retention,
110551
+ deviceRemoval: spec.deviceRemoval,
110552
+ maxDataBytes: spec.maxDataBytes,
110553
+ secretPaths: [...new Set([...secretPaths, ...spec.retiredSecretPaths ?? []])],
110554
+ secretArrayKeys: spec.secretArrayKeys === void 0 ? void 0 : { ...spec.secretArrayKeys },
110555
+ transactFamily: spec.transactFamily,
110556
+ entry: spec.entry === void 0 ? void 0 : {
110557
+ title: spec.entry.title,
110558
+ nameField,
110559
+ fields
110560
+ }
110561
+ });
110562
+ assertValidDeclaration(name, parsed);
110563
+ out[name] = {
110564
+ name,
110565
+ schema: spec.schema,
110566
+ declaration: parsed
110567
+ };
110568
+ }
110569
+ return out;
110570
+ }
110571
+ /**
110572
+ * Entry kinds (D881): every list of user-created entries (notification
110573
+ * targets, brokers, LLM profiles) is ONE record kind with an id, a name and a
110574
+ * kind-specific body, and the admin UI lists/adds/edits/deletes all of them
110575
+ * through the `record-entries` capability with password fields derived from
110576
+ * the schema (`.meta({ secret: true })`).
110577
+ */
110578
+ /** The body of a plain entry: a name and the fields the kind adds. */
110579
+ function entryBody(shape) {
110580
+ return object({
110581
+ name: string().min(1),
110582
+ enabled: boolean().optional(),
110583
+ ...shape
110584
+ });
110585
+ }
110586
+ /**
110587
+ * Declare one entry kind. An entry is configuration: never trimmed by the
110588
+ * engine, never aged, belonging to no device.
110589
+ */
110590
+ function defineEntryKind(name, spec) {
110591
+ const defined = defineRecordKinds({ [name]: {
110592
+ schema: spec.schema,
110593
+ class: "config",
110594
+ writeTrigger: spec.writeTrigger ?? "an operator adds or edits an entry in the entries UI",
110595
+ retention: { none: "an entry goes only when the operator deletes it" },
110596
+ ...spec.maxDataBytes === void 0 ? {} : { maxDataBytes: spec.maxDataBytes },
110597
+ ...spec.database === void 0 ? {} : { database: spec.database },
110598
+ ...spec.indexes === void 0 ? {} : { indexes: spec.indexes },
110599
+ ...spec.secretArrayKeys === void 0 ? {} : { secretArrayKeys: spec.secretArrayKeys },
110600
+ ...spec.retiredSecretPaths === void 0 ? {} : { retiredSecretPaths: spec.retiredSecretPaths },
110601
+ entry: {
110602
+ title: spec.title,
110603
+ ...spec.nameField === void 0 ? {} : { nameField: spec.nameField }
110604
+ }
110605
+ } })[name];
110606
+ if (defined === void 0) throw new DeclarationRefusedError(`entry kind "${name}" was not built`);
110607
+ return defined;
110608
+ }
110609
+ /**
110610
+ * The share-view scope kinds a share-link token can carry. The hub mints
110611
+ * and validates them (`ShareViewGrantSchema` builds its
110612
+ * enum from this list); a data plane names the kinds it ACCEPTS in `share`.
110613
+ */
110614
+ var SHARE_VIEW_KINDS = ["grid-view", "events-view"];
110615
+ /** The wire shape of {@link PeerBytesTicket} — see the type for what it is. */
110616
+ var PeerBytesTicketSchema = object({
110617
+ /** `http://127.0.0.1:<port>/<token>`. One `GET` takes it. */
110618
+ url: string().min(1),
110619
+ /**
110620
+ * The HOST node this URL means something on — the hub or a named agent,
110621
+ * never a runner. {@link AddonPeerBytes.open} compares it to its own and
110622
+ * refuses `cross-node` by name when they differ, without dialling.
110623
+ */
110624
+ hostNodeId: string().min(1),
110625
+ expiresAtMs: number().int().nonnegative(),
110626
+ /**
110627
+ * What the producer DECLARED the body to be, when it knows — `null` when it
110628
+ * does not. Never `0` for unknown (D393): a consumer sizing a bound off this
110629
+ * must be able to tell "the producer did not say" from "the body is empty".
110630
+ */
110631
+ declaredBytes: number().int().nonnegative().nullable()
110632
+ });
110192
110633
  var READING_QUANTITIES = [
110193
110634
  "temperature",
110194
110635
  "pressure",
@@ -110876,7 +111317,6 @@ var CAP_NAMES = Object.freeze([
110876
111317
  "climate-control",
110877
111318
  "color",
110878
111319
  "composer",
110879
- "connection-test",
110880
111320
  "connectivity",
110881
111321
  "consumables",
110882
111322
  "contact",
@@ -112023,6 +112463,10 @@ Object.freeze({
112023
112463
  "all",
112024
112464
  "one"
112025
112465
  ]
112466
+ },
112467
+ {
112468
+ "path": "positionUpdatedAt",
112469
+ "valueType": "number"
112026
112470
  }
112027
112471
  ],
112028
112472
  "meter": [{
@@ -112277,22 +112721,6 @@ Object.freeze({
112277
112721
  "path": "pumpRunning",
112278
112722
  "valueType": "boolean"
112279
112723
  },
112280
- {
112281
- "path": "lastDrink",
112282
- "valueType": "number"
112283
- },
112284
- {
112285
- "path": "currentHourDrink",
112286
- "valueType": "number"
112287
- },
112288
- {
112289
- "path": "last24hDrink",
112290
- "valueType": "number"
112291
- },
112292
- {
112293
- "path": "todayDrink",
112294
- "valueType": "number"
112295
- },
112296
112724
  {
112297
112725
  "path": "error",
112298
112726
  "valueType": "string"
@@ -112858,6 +113286,59 @@ Object.freeze({
112858
113286
  }
112859
113287
  ]
112860
113288
  });
113289
+ Object.freeze({
113290
+ "actions": { "run": 363e4 },
113291
+ "audio-analyzer": { "classify": 3e4 },
113292
+ "custom-model-registry": { "importModelBundle": 18e5 },
113293
+ "database-snapshot": { "writeSnapshot": 18e5 },
113294
+ "device-manager": {
113295
+ "migrateDevice": 72e4,
113296
+ "runDiscoverySweep": 12e4
113297
+ },
113298
+ "device-provider": { "reloadDevice": 18e4 },
113299
+ "llm": {
113300
+ "generate": 6e5,
113301
+ "generateVision": 6e5,
113302
+ "testProfile": 6e5
113303
+ },
113304
+ "llm-runtime": {
113305
+ "complete": 6e5,
113306
+ "completeApple": 6e5,
113307
+ "ensureStarted": 6e5,
113308
+ "installModel": 36e5
113309
+ },
113310
+ "local-network": { "scanNetwork": 9e4 },
113311
+ "model-convert": { "convert": 6e5 },
113312
+ "pipeline-analytics": {
113313
+ "addRetrainFrameFromRecording": 6e4,
113314
+ "offerRetrainArchive": 12e4,
113315
+ "proposeRetrainAnnotationsWithLlm": 18e4,
113316
+ "resolveRetrainTrainingCorpus": 6e4,
113317
+ "writeRetrainArchive": 36e5
113318
+ },
113319
+ "server-management": { "applyServerUpdate": 96e4 },
113320
+ "terminal-session": { "pullOutput": 15e3 },
113321
+ "training": {
113322
+ "canaryResult": 12e4,
113323
+ "cancelJob": 12e4,
113324
+ "planJob": 6e4,
113325
+ "registerResult": 18e5,
113326
+ "rollbackCanary": 12e4,
113327
+ "startJob": 12e4,
113328
+ "startJobBatch": 12e4
113329
+ },
113330
+ "training-provider": {
113331
+ "cancelJob": 6e4,
113332
+ "cleanupJob": 3e5,
113333
+ "getJob": 6e4,
113334
+ "listJobEvents": 6e4,
113335
+ "listJobs": 12e4,
113336
+ "offerArtifact": 3e5,
113337
+ "readResult": 3e5,
113338
+ "submitJob": 18e5,
113339
+ "uploadDataset": 72e5
113340
+ }
113341
+ });
112861
113342
  object({
112862
113343
  code: string().regex(/^[a-z][a-z0-9-]*(\.[a-z0-9-]+)+$/),
112863
113344
  params: record(string(), union([string(), number()])).optional()
@@ -112901,7 +113382,7 @@ function sleep(ms) {
112901
113382
  return new Promise((resolve) => setTimeout(resolve, Math.max(0, ms)));
112902
113383
  }
112903
113384
  //#endregion
112904
- //#region ../types/dist/composition-pOHbTzRB.mjs
113385
+ //#region ../types/dist/composition-BmBHuDTQ.mjs
112905
113386
  /**
112906
113387
  * The ffmpeg build every CamStack node downloads, per platform and arch.
112907
113388
  *
@@ -113205,7 +113686,7 @@ var table = {
113205
113686
  },
113206
113687
  dwell: {
113207
113688
  minArgs: 3,
113208
- maxArgs: 3,
113689
+ maxArgs: 4,
113209
113690
  apply: () => {
113210
113691
  throw new ExpressionEvalError("dwell: stateful evaluation context is required");
113211
113692
  }
@@ -114062,6 +114543,17 @@ var NodeColorIdSchema = _enum([
114062
114543
  "node-g",
114063
114544
  "node-h"
114064
114545
  ]);
114546
+ //#endregion
114547
+ //#region ../types/dist/index.mjs
114548
+ /**
114549
+ * The `smtp-inbound` broker kind (D999): a mailbox a device can send mail to.
114550
+ *
114551
+ * The `broker` cap carries these as `Record<string, unknown>` on the wire; the
114552
+ * provider and its consumers parse them with the schemas below at BOTH ends, so
114553
+ * the shape is declared once.
114554
+ */
114555
+ /** The broker kind tag. */
114556
+ var SMTP_INBOUND_KIND = "smtp-inbound";
114065
114557
  /** The id the first mailbox is minted under (adopt-id), so a consumer can find it again. */
114066
114558
  var SMTP_INBOUND_DEFAULT_ID = "smtp-inbound-default";
114067
114559
  var SMTP_INBOUND_DEFAULT_PORT = 2525;
@@ -114083,387 +114575,607 @@ object({
114083
114575
  maxMessageBytes: number().int().positive().default(SMTP_INBOUND_DEFAULT_MAX_MESSAGE_BYTES)
114084
114576
  });
114085
114577
  /**
114086
- * What `getBrokerConfig` answers: what a device needs to send mail here.
114087
- * `host` is null when the `internal` role of the network palette is not set;
114088
- * `hostReason` then says where to set it.
114578
+ * What `getBrokerConfig` answers: what a device needs to send mail here.
114579
+ * `host` is null when the `internal` role of the network palette is not set;
114580
+ * `hostReason` then says where to set it.
114581
+ */
114582
+ var SmtpInboundConfigSchema = object({
114583
+ host: string().min(1).nullable(),
114584
+ hostReason: string().nullable(),
114585
+ port: PortSchema,
114586
+ domain: string().min(1),
114587
+ requireAuth: boolean(),
114588
+ username: string(),
114589
+ password: string(),
114590
+ starttls: boolean()
114591
+ });
114592
+ object({
114593
+ recipients: array(SmtpRecipientSchema).min(1),
114594
+ /**
114595
+ * Who is subscribing. A second `subscribe` with the same id REPLACES that subscriber's
114596
+ * recipients (the way a consumer that restarted, or lost a device, declares its set again);
114597
+ * a recipient held by another subscriber is refused with `smtp-inbound/recipient-claimed`.
114598
+ * Absent, the subscriber is anonymous and unique.
114599
+ */
114600
+ subscriberId: string().min(1).max(64).optional()
114601
+ });
114602
+ var SmtpInboundAttachmentSchema = object({
114603
+ filename: string(),
114604
+ contentType: string(),
114605
+ bytes: number().int().nonnegative()
114606
+ });
114607
+ /** The payload of one `broker.message` (the key is the recipient local-part). */
114608
+ var SmtpInboundMessageSchema = object({
114609
+ /** Monotonic per mailbox; a gap tells a consumer it missed an event. */
114610
+ seq: number().int().positive(),
114611
+ messageId: string(),
114612
+ receivedAt: number().int().nonnegative(),
114613
+ from: string(),
114614
+ to: string(),
114615
+ subject: string(),
114616
+ text: string().max(SMTP_INBOUND_TEXT_MAX_CHARS),
114617
+ attachments: array(SmtpInboundAttachmentSchema)
114618
+ });
114619
+ /** What `getState('since:<seq>')` answers: every retained message after `seq`. */
114620
+ var SmtpInboundSinceSchema = object({
114621
+ /** The newest seq issued so far (0 before any mail). */
114622
+ lastSeq: number().int().nonnegative(),
114623
+ /** The oldest seq still retained; messages below it are gone. */
114624
+ oldestSeq: number().int().nonnegative(),
114625
+ messages: array(object({
114626
+ key: string(),
114627
+ message: SmtpInboundMessageSchema
114628
+ }))
114629
+ });
114630
+ /** The key a consumer passes to `getState` to replay the ring, and its parser. */
114631
+ function smtpSinceKey(seq) {
114632
+ return `since:${seq}`;
114633
+ }
114634
+ new Set([
114635
+ "track",
114636
+ "face",
114637
+ "identity",
114638
+ "plate",
114639
+ "vehicle",
114640
+ "scene",
114641
+ "motion",
114642
+ "object",
114643
+ "audio",
114644
+ "mosaic"
114645
+ ]);
114646
+ /**
114647
+ * The owner types that are event tables, in the order the event-media resolver
114648
+ * should consider them. Exported so a consumer asking "is this key an event?"
114649
+ * does not re-spell the list and drift from it.
114650
+ */
114651
+ var EVENT_OWNER_TYPES = [
114652
+ "motion",
114653
+ "object",
114654
+ "audio"
114655
+ ];
114656
+ /**
114657
+ * The same list as a Zod enum, for the cap inputs that must NAME the table
114658
+ * (D482: `getEventMedia` / `listEventMedia` take an owner, and an owner is
114659
+ * `(table, id)`).
114660
+ *
114661
+ * Built FROM {@link EVENT_OWNER_TYPES} rather than re-spelled: a fourth event
114662
+ * table would otherwise be accepted by the codec and refused at the door, with
114663
+ * nothing failing until a caller asked.
114664
+ */
114665
+ var EventOwnerTypeSchema = _enum(EVENT_OWNER_TYPES);
114666
+ /** The same list as a Zod enum, for the cap input that carries it. */
114667
+ var MediaPresenceOwnerKindSchema = _enum([...EVENT_OWNER_TYPES, "track"]);
114668
+ new Set(EVENT_OWNER_TYPES);
114669
+ /**
114670
+ * What a published package needs from the rest of the install (D989).
114671
+ *
114672
+ * One published framework package (`@camstack/server`) carries the kernel, the
114673
+ * builtins and the capability contracts, so "which addon runs on which
114674
+ * framework" is a question of version, and the answer is DECLARED by the
114675
+ * package that knows it:
114676
+ *
114677
+ * - an addon says the oldest server it runs on (`requires.server: ">=X"`);
114678
+ * - the server says the oldest addon it works with
114679
+ * (`requires.addons: { "@camstack/addon-x": ">=Y" }`) and the oldest shell
114680
+ * around it (`requires.wrapper: { desktop, image }`);
114681
+ * - a wrapper (the desktop app, the container starter) says which server
114682
+ * range it can host, and reports its own kind and version.
114683
+ *
114684
+ * The publish workflow STAMPS these after the version bump
114685
+ * (`scripts/ci/stamp-requires.mjs`); nobody types a number by hand.
114686
+ *
114687
+ * A requirement that cannot be checked is NOT met: a shell that reports no
114688
+ * version counts as below the minimum, and an unreadable running version is
114689
+ * named in the result (a failed read is never a pass).
114690
+ */
114691
+ /** `>=MAJOR.MINOR.PATCH[-prerelease]` — the only range shape a requirement uses. */
114692
+ var MinVersionSchema = string().regex(/^>=\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/, "a minimum is written \">=X.Y.Z\"");
114693
+ object({
114694
+ /** The oldest `@camstack/server` this package runs on. */
114695
+ server: MinVersionSchema.optional(),
114696
+ /** The oldest installed version of each named addon package. */
114697
+ addons: record(string(), MinVersionSchema).optional(),
114698
+ /** The oldest shell around the server, per shell kind. */
114699
+ wrapper: object({
114700
+ desktop: MinVersionSchema.optional(),
114701
+ image: MinVersionSchema.optional()
114702
+ }).optional()
114703
+ });
114704
+ /** One unmet requirement; each names the versions on both sides. */
114705
+ var UnmetRequirementSchema = discriminatedUnion("kind", [
114706
+ object({
114707
+ kind: literal("server-too-old"),
114708
+ required: string(),
114709
+ /** `null` — the running server version could not be read. */
114710
+ running: string().nullable()
114711
+ }),
114712
+ object({
114713
+ kind: literal("addon-too-old"),
114714
+ packageName: string(),
114715
+ required: string(),
114716
+ /** `null` — the addon is not installed (or its version is unreadable). */
114717
+ running: string().nullable()
114718
+ }),
114719
+ object({
114720
+ kind: literal("wrapper-too-old"),
114721
+ wrapper: _enum(["desktop", "image"]),
114722
+ required: string(),
114723
+ /** `null` — the wrapper reported no version. */
114724
+ running: string().nullable()
114725
+ })
114726
+ ]);
114727
+ var RequiredAddonUpdateSchema = object({
114728
+ packageName: string(),
114729
+ /** The minimum the target server declares. */
114730
+ required: string(),
114731
+ /** What this node has; `null` when the addon is not installed. */
114732
+ installed: string().nullable()
114733
+ });
114734
+ /**
114735
+ * Which integration instance a settings form is for. An addon that serves several instances
114736
+ * (`instanceMode: multiple`) can show a different form per instance — an NVR integration
114737
+ * needs its connection, the default integration needs the addon's own sections.
114738
+ *
114739
+ * - `integrationId` is `null` in the create wizard: nothing exists yet, the operator is
114740
+ * setting up a NEW instance.
114741
+ * - `mode` is the wizard mode of the integration type (`getAvailableTypes`).
114742
+ * - `candidateStableId` is the discovery candidate a wizard was seeded from, if any.
114743
+ */
114744
+ var IntegrationInstanceRefSchema = object({
114745
+ integrationId: string().nullable(),
114746
+ mode: _enum([
114747
+ "standalone",
114748
+ "account",
114749
+ "broker"
114750
+ ]),
114751
+ candidateStableId: string().optional()
114752
+ });
114753
+ /**
114754
+ * notification-output — canonical, capability-gated notification delivery.
114755
+ *
114756
+ * Apprise-derived model (see
114757
+ * `docs/superpowers/specs/2026-07-03-notification-output-notifier-matrix.md`):
114758
+ * callers emit ONE canonical `Notification`; each provider declares a
114759
+ * per-kind capability descriptor (`TargetKind`), and the pure degrade
114760
+ * engine (`@camstack/types` `prepareNotification`) transcodes / degrades the
114761
+ * message to what the kind supports — callers never special-case a service.
114762
+ *
114763
+ * DESIGN DECISIONS (locked):
114764
+ * - Target CRUD lives on THIS cap (`upsertTarget` / `deleteTarget` /
114765
+ * `setTargetEnabled`), each provider persisting via the `settings-store`
114766
+ * cap. Rationale: the admin UI needs one uniform surface across the
114767
+ * notifiers addon AND the HA addon; the addon-`globalSettingsSchema`-array
114768
+ * alternative would fork the UI per addon and cannot host the
114769
+ * discovery→adopt flow.
114770
+ * - `listTargetKinds` / `listTargets` / `discoverTargets` return arrays →
114771
+ * the generated cap-mount auto-`concatCollection`-fans them across every
114772
+ * registered provider (notifiers addon + HA addon) so one catalog is
114773
+ * routable. `send` / `testTarget` / CRUD route to ONE provider by the
114774
+ * `addonId` the generated collection router extracts from the call input.
114775
+ * - `Attachment.bytes` is `Uint8Array`. Transport-safe: superjson (the tRPC
114776
+ * transformer) + UDS MsgPack both round-trip typed arrays — already used by
114777
+ * `storage` / `storage-provider` / `recording` caps over the same path. No
114778
+ * base64 fallback needed.
114779
+ *
114780
+ * TODO (deferred, closed-set change — separate decision): add
114781
+ * `providerKind: 'notify'` so notification providers surface on the unified
114782
+ * admin "Integrations" page.
114783
+ */
114784
+ /**
114785
+ * Zentik-derived typed-media enum — the superset across every kind. Each
114786
+ * adapter picks what it supports and the degrade engine filters the rest.
114787
+ */
114788
+ var AttachmentMediaTypeSchema = _enum([
114789
+ "image",
114790
+ "video",
114791
+ "gif",
114792
+ "audio",
114793
+ "icon"
114794
+ ]);
114795
+ /**
114796
+ * A single attachment. Exactly one of `url` (remote source, most adapters
114797
+ * prefer this) or `bytes` (inline source; required for Pushover-style
114798
+ * bytes-only kinds) MUST be present — the degrade engine expresses a
114799
+ * url→bytes fetch as a `needsFetch` directive the adapter executes.
114800
+ */
114801
+ var AttachmentSchema = object({
114802
+ mediaType: AttachmentMediaTypeSchema,
114803
+ url: string().optional(),
114804
+ bytes: _instanceof(Uint8Array).optional(),
114805
+ mime: string().optional(),
114806
+ name: string().optional()
114807
+ }).refine((a) => a.url !== void 0 || a.bytes !== void 0, { message: "Attachment requires either `url` or `bytes`" });
114808
+ var NotificationFormatSchema = _enum([
114809
+ "text",
114810
+ "markdown",
114811
+ "html"
114812
+ ]);
114813
+ /**
114814
+ * The CLOSED icon vocabulary an action button may use.
114815
+ *
114816
+ * A closed set, not a free string, and that is the whole point: an arbitrary
114817
+ * icon name is one that ntfy renders, zentik silently drops, and nobody
114818
+ * notices — the same class of gap as a zone vocabulary nothing produced
114819
+ * ([D35](../../../docs/decisions/adr-0035.md)). Every adapter maps this set or
114820
+ * declares `actionIcons: false` and the degrade engine strips the field.
114821
+ *
114822
+ * Named by INTENT, never by glyph. "check" would tie the vocabulary to one
114823
+ * renderer's icon set; "acknowledge" survives an adapter that draws it
114824
+ * differently.
114825
+ *
114826
+ * ── A TOKEN IS NOT A WIRE VALUE ─────────────────────────────────────
114827
+ *
114828
+ * These names are for US. **No adapter may forward one verbatim.** Each maps
114829
+ * the whole set onto its own renderer's vocabulary through a
114830
+ * `Record<NotificationActionIcon, string>` — a Record, never a lookup with a
114831
+ * fallback, so adding a member here fails every adapter's build until someone
114832
+ * decides its glyph, which is the only place that decision can be made
114833
+ * honestly.
114834
+ *
114835
+ * This paragraph is the bug. Zentik declared `actionIcons: true` and passed
114836
+ * `disarm` straight through; iOS feeds that string to
114837
+ * `UNNotificationActionIcon(systemImageName:)`, `disarm` is not an SF Symbol,
114838
+ * and every snooze and alarm button arrived BLANK. A pass-through is not a
114839
+ * mapping, and "the field is documented" is not "the value renders".
114840
+ *
114841
+ * Adding a member is TRAIN-BOUND. The enum lives in the published
114842
+ * `@camstack/server` closure and the cap seam validates against the HUB's copy,
114843
+ * so an addon that emits a token the running hub does not know does not lose an
114844
+ * icon — its whole `send` fails Zod validation and the notification never
114845
+ * arrives. Never emit a new token from an addon before the train carrying it.
114846
+ */
114847
+ var NotificationActionIconSchema = _enum([
114848
+ "acknowledge",
114849
+ "dismiss",
114850
+ "silence",
114851
+ "snooze",
114852
+ "view",
114853
+ "play",
114854
+ "open",
114855
+ "close",
114856
+ "lock",
114857
+ "unlock",
114858
+ "arm",
114859
+ "arm-home",
114860
+ "arm-away",
114861
+ "arm-night",
114862
+ "disarm",
114863
+ "light",
114864
+ "alert",
114865
+ "camera"
114866
+ ]);
114867
+ /** A single tap-through action button. */
114868
+ var NotificationActionSchema = object({
114869
+ id: string(),
114870
+ label: string(),
114871
+ url: string().optional(),
114872
+ /** Dropped by the degrade engine for a kind with `caps.actionIcons: false`. */
114873
+ icon: NotificationActionIconSchema.optional(),
114874
+ /**
114875
+ * Renders in a warning style where the notifier supports it.
114876
+ *
114877
+ * A HINT, never a gate. The callback's authority is its token and nothing
114878
+ * else — see `notification-center/action-token.ts` for what that does and
114879
+ * does not buy.
114880
+ */
114881
+ destructive: boolean().optional(),
114882
+ /**
114883
+ * How the tap should REACH the url.
114884
+ *
114885
+ * `navigate` (absent, and every button authored before this field) opens it:
114886
+ * the phone leaves the notification and shows whatever the callback returns.
114887
+ * That is right for a button whose answer the operator wants to read.
114888
+ *
114889
+ * `background` fires it as a POST and stays put. It exists for the buttons
114890
+ * whose whole point is not to interrupt — "silence this for 30 minutes" is
114891
+ * an answer to the notification, and being thrown into a browser tab to
114892
+ * confirm it costs more attention than the notification did. A backend that
114893
+ * cannot do a background call renders it as an ordinary link (the adapters
114894
+ * fall back rather than dropping the button), so this is a preference, never
114895
+ * a requirement.
114896
+ */
114897
+ mode: _enum(["navigate", "background"]).optional()
114898
+ });
114899
+ /** A delivery parameter value: what a notifier declared it takes. */
114900
+ var DeliveryParamValueSchema = union([
114901
+ string(),
114902
+ number(),
114903
+ boolean()
114904
+ ]);
114905
+ /**
114906
+ * One extra delivery parameter a notifier KIND declares (D938). A rule that
114907
+ * addresses a target of that kind may set it; a kind that declares nothing is
114908
+ * never handed one. The admin UI derives its control from this descriptor —
114909
+ * no editor knows a service by name.
114910
+ *
114911
+ * Optional fields are `.optional()`, never `.default()` (a Zod default does not
114912
+ * run on the addon cap path).
114913
+ */
114914
+ var DeliveryParamSchema = object({
114915
+ key: string().min(1),
114916
+ label: string(),
114917
+ /** i18n key of the label, resolved by the declaring addon's namespace. */
114918
+ labelKey: string().optional(),
114919
+ type: _enum([
114920
+ "enum",
114921
+ "number",
114922
+ "boolean",
114923
+ "string"
114924
+ ]),
114925
+ /** `enum` only: the closed set of accepted values. */
114926
+ options: array(object({
114927
+ value: string(),
114928
+ label: string()
114929
+ })).optional(),
114930
+ /** `number` only. */
114931
+ min: number().optional(),
114932
+ max: number().optional(),
114933
+ /** What the notifier does when the rule sets nothing; shown as the placeholder. */
114934
+ default: DeliveryParamValueSchema.optional()
114935
+ });
114936
+ /**
114937
+ * The canonical notification. `body` is the only hard field (Apprise model).
114938
+ * `priority` is a 5-level ORDINAL (1=lowest … 3=normal(default) … 5=urgent),
114939
+ * NOT a fixed severity enum — each kind declares its own `caps.levels` and
114940
+ * the adapter maps this ordinal onto its native level. `level?` is an
114941
+ * optional kind-native level id (`emergency`, `silent`, …) that overrides
114942
+ * `priority` for that one target.
114943
+ */
114944
+ var NotificationSchema = object({
114945
+ body: string(),
114946
+ title: string().optional(),
114947
+ format: NotificationFormatSchema.default("text"),
114948
+ priority: number().int().min(1).max(5).default(3),
114949
+ level: string().optional(),
114950
+ attachments: array(AttachmentSchema).optional(),
114951
+ clickUrl: string().optional(),
114952
+ actions: array(NotificationActionSchema).optional(),
114953
+ sound: string().optional(),
114954
+ ttl: number().optional(),
114955
+ tag: string().optional(),
114956
+ deviceId: number().optional(),
114957
+ eventId: string().optional(),
114958
+ metadata: record(string(), unknown()).optional(),
114959
+ /**
114960
+ * Values for the parameters the target's kind DECLARES in
114961
+ * {@link TargetKindSchema} `deliveryParams`. Already validated against the
114962
+ * declaration by the sender; a notifier reads only the keys it declared.
114963
+ */
114964
+ delivery: record(string(), DeliveryParamValueSchema).optional()
114965
+ });
114966
+ /** One declared native severity/priority level for a kind. */
114967
+ var TargetKindLevelSchema = object({
114968
+ id: string(),
114969
+ label: string(),
114970
+ /** Which canonical priority (1..5) this level maps to. `null` = qualitative-only. */
114971
+ ordinal: number().int().min(1).max(5).nullable(),
114972
+ flags: object({
114973
+ critical: boolean().optional(),
114974
+ silent: boolean().optional(),
114975
+ noPush: boolean().optional()
114976
+ }).optional(),
114977
+ /** e.g. Pushover `emergency` requires `retry` / `expire`. */
114978
+ requires: array(string()).optional(),
114979
+ description: string().optional()
114980
+ });
114981
+ /** The full capability block consulted before dispatch. */
114982
+ var TargetKindCapsSchema = object({
114983
+ attachments: object({
114984
+ mediaTypes: array(AttachmentMediaTypeSchema),
114985
+ mode: _enum([
114986
+ "url",
114987
+ "bytes",
114988
+ "both"
114989
+ ]),
114990
+ max: number().int().nonnegative(),
114991
+ maxBytes: number().int().positive().optional()
114992
+ }),
114993
+ /** Max action buttons (0 = none). */
114994
+ actions: number().int().nonnegative(),
114995
+ /**
114996
+ * Whether this kind renders a per-action ICON.
114997
+ *
114998
+ * `.optional()`, deliberately NOT `.default(false)`: a Zod default does not
114999
+ * run on the addon cap path — three production failures in one day taught
115000
+ * this repo that once. Absent is read as false by the degrade engine, which
115001
+ * is the safe direction: an icon that is not rendered costs nothing, an icon
115002
+ * assumed and dropped costs the operator's trust in the field.
115003
+ */
115004
+ actionIcons: boolean().optional(),
115005
+ levels: array(TargetKindLevelSchema),
115006
+ format: array(NotificationFormatSchema),
115007
+ clickUrl: boolean(),
115008
+ sound: boolean(),
115009
+ ttl: boolean(),
115010
+ bodyMaxLen: number().int().positive()
115011
+ });
115012
+ /**
115013
+ * `configSchema` is a `ConfigUISchema` tree passed through to the admin
115014
+ * FormBuilder. Stored as `z.unknown()` at the cap seam (mirrors
115015
+ * `device-provider.getChildCreationSchema` `CreationSchemaOutputSchema`) —
115016
+ * the union is large and not meant for runtime validation here; the exported
115017
+ * `TargetKind` type re-tightens `configSchema` to `ConfigUISchema`.
114089
115018
  */
114090
- var SmtpInboundConfigSchema = object({
114091
- host: string().min(1).nullable(),
114092
- hostReason: string().nullable(),
114093
- port: PortSchema,
114094
- domain: string().min(1),
114095
- requireAuth: boolean(),
114096
- username: string(),
114097
- password: string(),
114098
- starttls: boolean()
114099
- });
114100
- object({
114101
- recipients: array(SmtpRecipientSchema).min(1),
115019
+ var ConfigSchemaPassthrough$4 = unknown();
115020
+ var TargetKindSchema = object({
115021
+ kind: string(),
115022
+ label: string(),
115023
+ icon: string(),
115024
+ /** Stamped by each provider so the concat-fanned catalog stays routable. */
115025
+ addonId: string(),
114102
115026
  /**
114103
- * Who is subscribing. A second `subscribe` with the same id REPLACES that subscriber's
114104
- * recipients (the way a consumer that restarted, or lost a device, declares its set again);
114105
- * a recipient held by another subscriber is refused with `smtp-inbound/recipient-claimed`.
114106
- * Absent, the subscriber is anonymous and unique.
115027
+ * URL of the kind's bundled BRAND icon, served by the providing addon over
115028
+ * its own `addon-routes` surface (`/addon/<addonId>/icons/<kind>`). Absent
115029
+ * when the addon bundles no icon for that kind — the client then falls back
115030
+ * to a neutral glyph rather than rendering the raw `icon` NAME as text.
115031
+ *
115032
+ * Root-relative on purpose: it resolves against whatever origin serves a web
115033
+ * client, and a native client joins it onto its own hub base.
115034
+ *
115035
+ * DECLARED here deliberately. It used to travel as an undeclared passthrough
115036
+ * field that survived only because the runtime cap-router forwards provider
115037
+ * output verbatim — so every consumer had to re-declare it by hand to stop
115038
+ * its own Zod parse from stripping it, and the whole arrangement would have
115039
+ * broken silently the moment output validation was tightened anywhere.
114107
115040
  */
114108
- subscriberId: string().min(1).max(64).optional()
114109
- });
114110
- var SmtpInboundAttachmentSchema = object({
114111
- filename: string(),
114112
- contentType: string(),
114113
- bytes: number().int().nonnegative()
114114
- });
114115
- /** The payload of one `broker.message` (the key is the recipient local-part). */
114116
- var SmtpInboundMessageSchema = object({
114117
- /** Monotonic per mailbox; a gap tells a consumer it missed an event. */
114118
- seq: number().int().positive(),
114119
- messageId: string(),
114120
- receivedAt: number().int().nonnegative(),
114121
- from: string(),
114122
- to: string(),
114123
- subject: string(),
114124
- text: string().max(SMTP_INBOUND_TEXT_MAX_CHARS),
114125
- attachments: array(SmtpInboundAttachmentSchema)
114126
- });
114127
- /** What `getState('since:<seq>')` answers: every retained message after `seq`. */
114128
- var SmtpInboundSinceSchema = object({
114129
- /** The newest seq issued so far (0 before any mail). */
114130
- lastSeq: number().int().nonnegative(),
114131
- /** The oldest seq still retained; messages below it are gone. */
114132
- oldestSeq: number().int().nonnegative(),
114133
- messages: array(object({
114134
- key: string(),
114135
- message: SmtpInboundMessageSchema
114136
- }))
115041
+ iconUrl: string().optional(),
115042
+ /**
115043
+ * Media type of {@link iconUrl} (`image/svg+xml`, `image/png`, …).
115044
+ *
115045
+ * The server knows this and therefore says it, because the client cannot
115046
+ * safely guess: a React-Native client renders SVG and raster through two
115047
+ * DIFFERENT components (`react-native-svg` vs `expo-image` — expo-image does
115048
+ * not decode SVG on iOS/Android), so without this it silently fell back to a
115049
+ * placeholder glyph for every vector icon while the web build looked fine.
115050
+ *
115051
+ * Absent when {@link iconUrl} is absent, or for a legacy provider that has
115052
+ * not been updated — a client that cannot determine the type should prefer
115053
+ * its raster path, which is the safe default for an unknown image.
115054
+ */
115055
+ iconMediaType: string().optional(),
115056
+ configSchema: ConfigSchemaPassthrough$4,
115057
+ /**
115058
+ * The config keys that decide WHERE this kind's secrets are sent (server,
115059
+ * base URL, instance, chat, recipient). A save that changes any of them
115060
+ * while leaving a secret redacted is refused by the provider (D634), so an
115061
+ * editor uses this to ask for the secret on exactly those edits instead of
115062
+ * on every edit.
115063
+ *
115064
+ * Optional: absent from a provider that holds no secret (the Home Assistant
115065
+ * kinds) and from a provider older than this field — an editor that finds
115066
+ * it absent must assume ANY edit may need the secret.
115067
+ */
115068
+ destinationKeys: array(string()).optional(),
115069
+ supportsDiscovery: boolean(),
115070
+ /**
115071
+ * Extra delivery parameters a rule may set for a target of this kind (D938).
115072
+ * Absent = none; the rule editor then offers nothing.
115073
+ */
115074
+ deliveryParams: array(DeliveryParamSchema).optional(),
115075
+ caps: TargetKindCapsSchema
114137
115076
  });
114138
- /** The key a consumer passes to `getState` to replay the ring, and its parser. */
114139
- function smtpSinceKey(seq) {
114140
- return `since:${seq}`;
114141
- }
114142
- new Set([
114143
- "track",
114144
- "face",
114145
- "identity",
114146
- "plate",
114147
- "vehicle",
114148
- "scene",
114149
- "motion",
114150
- "object",
114151
- "audio",
114152
- "mosaic"
114153
- ]);
114154
- /**
114155
- * The owner types that are event tables, in the order the event-media resolver
114156
- * should consider them. Exported so a consumer asking "is this key an event?"
114157
- * does not re-spell the list and drift from it.
114158
- */
114159
- var EVENT_OWNER_TYPES = [
114160
- "motion",
114161
- "object",
114162
- "audio"
114163
- ];
114164
- /**
114165
- * The same list as a Zod enum, for the cap inputs that must NAME the table
114166
- * (D482: `getEventMedia` / `listEventMedia` take an owner, and an owner is
114167
- * `(table, id)`).
114168
- *
114169
- * Built FROM {@link EVENT_OWNER_TYPES} rather than re-spelled: a fourth event
114170
- * table would otherwise be accepted by the codec and refused at the door, with
114171
- * nothing failing until a caller asked.
114172
- */
114173
- var EventOwnerTypeSchema = _enum(EVENT_OWNER_TYPES);
114174
- /** The same list as a Zod enum, for the cap input that carries it. */
114175
- var MediaPresenceOwnerKindSchema = _enum([...EVENT_OWNER_TYPES, "track"]);
114176
- new Set(EVENT_OWNER_TYPES);
114177
115077
  /**
114178
- * What a published package needs from the rest of the install (D989).
114179
- *
114180
- * One published framework package (`@camstack/server`) carries the kernel, the
114181
- * builtins and the capability contracts, so "which addon runs on which
114182
- * framework" is a question of version, and the answer is DECLARED by the
114183
- * package that knows it:
114184
- *
114185
- * - an addon says the oldest server it runs on (`requires.server: ">=X"`);
114186
- * - the server says the oldest addon it works with
114187
- * (`requires.addons: { "@camstack/addon-x": ">=Y" }`) and the oldest shell
114188
- * around it (`requires.wrapper: { desktop, image }`);
114189
- * - a wrapper (the desktop app, the container starter) says which server
114190
- * range it can host, and reports its own kind and version.
114191
- *
114192
- * The publish workflow STAMPS these after the version bump
114193
- * (`scripts/ci/stamp-requires.mjs`); nobody types a number by hand.
114194
- *
114195
- * A requirement that cannot be checked is NOT met: a shell that reports no
114196
- * version counts as below the minimum, and an unreadable running version is
114197
- * named in the result (a failed read is never a pass).
115078
+ * A persisted target. `config` holds secrets; providers REDACT secret fields
115079
+ * (return a presence marker only) when serving `listTargets` — never
115080
+ * round-trip a stored secret to the UI.
114198
115081
  */
114199
- /** `>=MAJOR.MINOR.PATCH[-prerelease]` — the only range shape a requirement uses. */
114200
- var MinVersionSchema = string().regex(/^>=\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/, "a minimum is written \">=X.Y.Z\"");
114201
- object({
114202
- /** The oldest `@camstack/server` this package runs on. */
114203
- server: MinVersionSchema.optional(),
114204
- /** The oldest installed version of each named addon package. */
114205
- addons: record(string(), MinVersionSchema).optional(),
114206
- /** The oldest shell around the server, per shell kind. */
114207
- wrapper: object({
114208
- desktop: MinVersionSchema.optional(),
114209
- image: MinVersionSchema.optional()
114210
- }).optional()
115082
+ var TargetSchema = object({
115083
+ id: string(),
115084
+ name: string(),
115085
+ kind: string(),
115086
+ addonId: string(),
115087
+ enabled: boolean(),
115088
+ config: record(string(), unknown())
114211
115089
  });
114212
- /** One unmet requirement; each names the versions on both sides. */
114213
- var UnmetRequirementSchema = discriminatedUnion("kind", [
114214
- object({
114215
- kind: literal("server-too-old"),
114216
- required: string(),
114217
- /** `null` — the running server version could not be read. */
114218
- running: string().nullable()
114219
- }),
114220
- object({
114221
- kind: literal("addon-too-old"),
114222
- packageName: string(),
114223
- required: string(),
114224
- /** `null` — the addon is not installed (or its version is unreadable). */
114225
- running: string().nullable()
114226
- }),
114227
- object({
114228
- kind: literal("wrapper-too-old"),
114229
- wrapper: _enum(["desktop", "image"]),
114230
- required: string(),
114231
- /** `null` — the wrapper reported no version. */
114232
- running: string().nullable()
114233
- })
114234
- ]);
114235
- var RequiredAddonUpdateSchema = object({
114236
- packageName: string(),
114237
- /** The minimum the target server declares. */
114238
- required: string(),
114239
- /** What this node has; `null` when the addon is not installed. */
114240
- installed: string().nullable()
115090
+ /** A discovery-surfaced candidate (config is partial + non-secret). */
115091
+ var DiscoveredTargetSchema = object({
115092
+ kind: string(),
115093
+ suggestedName: string(),
115094
+ config: record(string(), unknown())
114241
115095
  });
114242
- /**
114243
- * Which integration instance a settings form is for. An addon that serves several instances
114244
- * (`instanceMode: multiple`) can show a different form per instance — an NVR integration
114245
- * needs its connection, the default integration needs the addon's own sections.
114246
- *
114247
- * - `integrationId` is `null` in the create wizard: nothing exists yet, the operator is
114248
- * setting up a NEW instance.
114249
- * - `mode` is the wizard mode of the integration type (`getAvailableTypes`).
114250
- * - `candidateStableId` is the discovery candidate a wizard was seeded from, if any.
114251
- */
114252
- var IntegrationInstanceRefSchema = object({
114253
- integrationId: string().nullable(),
114254
- mode: _enum([
114255
- "standalone",
114256
- "account",
114257
- "broker"
114258
- ]),
114259
- candidateStableId: string().optional()
115096
+ /** The degrade engine's report — what was resolved / dropped / degraded. */
115097
+ var RenderedAsSchema = object({
115098
+ level: string(),
115099
+ format: NotificationFormatSchema,
115100
+ attachmentsSent: number().int().nonnegative(),
115101
+ actionsSent: number().int().nonnegative(),
115102
+ truncated: boolean(),
115103
+ dropped: array(string())
114260
115104
  });
115105
+ var SendResultSchema = object({
115106
+ success: boolean(),
115107
+ error: string().optional(),
115108
+ renderedAs: RenderedAsSchema.optional()
115109
+ });
115110
+ /** Same shape as SendResult — kept as a distinct name for the test panel. */
115111
+ var TestResultSchema = SendResultSchema;
114261
115112
  /**
114262
- * `RecordIntegrationInstances` - the `integration-instances` provider over ONE
114263
- * entry kind, so an addon that holds a connection serves it in ~30 lines.
114264
- *
114265
- * Every instance is one record of the addon's own kind, keyed by the
114266
- * `integrations` registry id. The records door does the secret work: a field the
114267
- * kind marks `.meta({ secret: true })` is a keychain marker bound to the row, so
114268
- * deleting the row deletes the secret, and one row's value is never another's.
114269
- *
114270
- * Patch rules for a secret (`updateInstance`): omitted, `''`, the redaction
114271
- * token or the view the form was given KEEP the stored secret;
114272
- * `{ $secretClear: true }` clears it; any other string replaces it.
114273
- */
114274
- /** The most instances one addon lists (an integrations page, not a table). */
114275
- var INSTANCES_LIST_MAX = 1e3;
114276
- /** The keys of the kind's secret fields that sit at the top level of the body. */
114277
- function topLevelSecretKeys(paths) {
114278
- return new Set(paths.filter((p) => !p.includes(".") && !p.includes("[") && !p.includes("{")));
114279
- }
114280
- /** The keys of the kind's top-level MAPS whose values are secrets (`applianceSecrets{}`). */
114281
- function secretMapKeys(paths) {
114282
- return new Set(paths.filter((p) => p.endsWith("{}") && !p.slice(0, -2).match(/[.[{]/)).map((p) => p.slice(0, -2)));
114283
- }
114284
- /**
114285
- * A patch value for a map of secrets: an entry that is omitted, `''`, the redaction token or the
114286
- * view the form was given KEEPS its stored secret (it is left out of the merge); `{ $secretClear }`
114287
- * or `null` removes the entry; any other string replaces it. Null when nothing is left to merge.
115113
+ * Pre-save credential probe against a partial (unsaved) target config.
115114
+ * `resolvedUrl` never includes secrets (token stripped from path).
114288
115115
  */
114289
- function secretMapPatch(value) {
114290
- if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
114291
- const out = {};
114292
- for (const [key, entry] of Object.entries(value)) if (entry === null || isSecretClear(entry)) out[key] = null;
114293
- else if (typeof entry === "string" && entry !== "" && entry !== "__camstack_redacted__" && !isSecretFieldView(entry)) out[key] = entry;
114294
- return Object.keys(out).length > 0 ? out : null;
114295
- }
114296
- /** Does the kind's body schema carry an `enabled` field? */
114297
- function declaresEnabled(kind) {
114298
- const json = toJSONSchema(kind.schema, {
114299
- unrepresentable: "any",
114300
- io: "input"
114301
- });
114302
- const properties = Reflect.get(json, "properties");
114303
- return typeof properties === "object" && properties !== null && "enabled" in properties;
114304
- }
114305
- var RecordIntegrationInstances = class {
114306
- records;
114307
- kind;
114308
- hooks;
114309
- handle;
114310
- secretKeys;
114311
- secretMaps;
114312
- nameField;
114313
- /** The `integrations` registry owns the on/off switch (`role: devices`); the body has none. */
114314
- registryOwnsEnabled;
114315
- constructor(records, kind, hooks) {
114316
- this.records = records;
114317
- this.kind = kind;
114318
- this.hooks = hooks;
114319
- this.handle = records.kind(kind);
114320
- this.secretKeys = topLevelSecretKeys(kind.declaration.secretPaths);
114321
- this.secretMaps = secretMapKeys(kind.declaration.secretPaths);
114322
- this.nameField = kind.declaration.entry?.nameField ?? "name";
114323
- this.registryOwnsEnabled = hooks.description.role === "devices";
114324
- 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"`);
114325
- }
115116
+ var ProbeTargetConfigResultSchema = object({
115117
+ ok: boolean(),
115118
+ resolvedUrl: string(),
115119
+ httpStatus: number().int().optional(),
115120
+ stateInstance: string().optional(),
115121
+ error: string().optional()
115122
+ });
115123
+ method(object({}), array(TargetKindSchema)), method(object({}), array(TargetSchema), { auth: "admin" }), method(object({ targetId: string() }), TargetSchema, { auth: "admin" }), method(object({
115124
+ kind: string(),
115125
+ config: record(string(), unknown()).optional(),
114326
115126
  /**
114327
- * One instance read for the addon's own runtime; null when absent. When the keychain is
114328
- * locked the row is served WITHOUT its secrets and says so (`secrets: 'unavailable'`), so the
114329
- * caller can keep what it had instead of reconfiguring with an empty secret (D49).
115127
+ * When editing / duplicating, the blank password field never round-trips
115128
+ * the stored token. Pass the source target id so the provider can restore
115129
+ * secrets server-side before dialling (same merge as upsert).
114330
115130
  */
114331
- async readResolved(id) {
114332
- try {
114333
- const record = await this.handle.getResolved(id);
114334
- return record === null ? null : {
114335
- id,
114336
- body: record.data,
114337
- enabled: record.data.enabled !== false,
114338
- secrets: "resolved"
114339
- };
114340
- } catch (err) {
114341
- if (!(err instanceof RecordSecretUnavailableError)) throw err;
114342
- const stored = await this.handle.get(id);
114343
- if (stored === null) return null;
114344
- return {
114345
- id,
114346
- body: Object.fromEntries(Object.entries(stored.data).filter(([key]) => !this.secretKeys.has(key))),
114347
- enabled: stored.data.enabled !== false,
114348
- secrets: "unavailable"
114349
- };
114350
- }
114351
- }
114352
- /** The body of {@link readResolved} alone; a locked keychain yields the row without secrets. */
114353
- async getResolved(id) {
114354
- return (await this.readResolved(id))?.body ?? null;
114355
- }
114356
- /** Every instance, secrets resolved where the keychain allows; an absent one is skipped. */
114357
- async listResolved() {
114358
- const page = await this.handle.query({ limit: INSTANCES_LIST_MAX });
114359
- const out = [];
114360
- for (const record of page.records) {
114361
- const read = await this.readResolved(record.id);
114362
- if (read !== null) out.push(read);
114363
- }
114364
- return out;
114365
- }
114366
- viewOf(record) {
114367
- const shown = secretViewsOf(this.records.owner, this.kind.name, record.id, this.kind.declaration, record.data);
114368
- const rawName = record.data[this.nameField];
114369
- const kind = this.hooks.kindOf?.(record.data);
114370
- const health = this.hooks.health?.(record.data, record.id);
114371
- return {
114372
- id: record.id,
114373
- name: typeof rawName === "string" ? rawName : record.id,
114374
- configured: this.hooks.configured(record.data),
114375
- ...this.registryOwnsEnabled ? {} : { enabled: record.data.enabled !== false },
114376
- formValues: shown,
114377
- ...kind !== void 0 ? { kind } : {},
114378
- ...health?.status !== void 0 ? { status: health.status } : {},
114379
- ...health?.lastCheckedAt !== void 0 ? { lastCheckedAt: health.lastCheckedAt } : {}
114380
- };
114381
- }
114382
- describe = async () => this.hooks.mintId === void 0 ? this.hooks.description : {
114383
- ...this.hooks.description,
114384
- mintsId: true
114385
- };
114386
- instanceFormSchema = async ({ id }) => this.hooks.formSchema(id);
114387
- listInstances = async () => {
114388
- return (await this.handle.query({ limit: INSTANCES_LIST_MAX })).records.map((record) => this.viewOf(record));
114389
- };
114390
- getInstance = async ({ id }) => {
114391
- const record = await this.handle.get(id);
114392
- return record === null ? null : this.viewOf(record);
114393
- };
114394
- /** Insert ONE row (`ifRev: 0`: an existing id is refused, never overwritten). */
114395
- createInstance = async ({ id, name, kind, values }) => {
114396
- const minted = id ?? this.hooks.mintId?.({
114397
- name,
114398
- ...kind !== void 0 ? { kind } : {}
114399
- });
114400
- if (minted === void 0) throw new Error("createInstance needs an id: this provider does not mint one");
114401
- await this.handle.put({
114402
- id: minted,
114403
- data: this.hooks.initialBody(name, kind)
114404
- }, { ifRev: 0 });
114405
- const patch = this.patchOf(values ?? {});
114406
- if (Object.keys(patch).length > 0) await this.handle.patch(minted, patch);
114407
- await this.hooks.onChanged?.(minted, "created");
114408
- return { id: minted };
114409
- };
114410
- updateInstance = async ({ id, name, values }) => {
114411
- const patch = this.patchOf(values);
114412
- if (name !== void 0) patch[this.nameField] = name;
114413
- await this.handle.patch(id, patch);
114414
- await this.hooks.onChanged?.(id, "updated");
114415
- return { ok: true };
114416
- };
114417
- /** The record patch a form `values` object means: secrets kept, cleared or replaced. */
114418
- patchOf(values) {
114419
- const patch = {};
114420
- for (const [key, value] of Object.entries(values)) {
114421
- if (value === void 0) continue;
114422
- if (this.secretMaps.has(key)) {
114423
- const entries = secretMapPatch(value);
114424
- if (entries !== null) patch[key] = entries;
114425
- } else if (!this.secretKeys.has(key)) patch[key] = value;
114426
- else if (isSecretClear(value)) patch[key] = null;
114427
- else if (typeof value === "string" && value !== "" && value !== "__camstack_redacted__" && !isSecretFieldView(value)) patch[key] = value;
114428
- }
114429
- return patch;
114430
- }
114431
- /** The switch lives in the record body; the addon is told so it applies it (D996). */
114432
- setInstanceEnabled = async ({ id, enabled }) => {
114433
- if (this.registryOwnsEnabled) throw new Error(`instance "${id}": the integrations registry owns the on/off switch of this addon; set it with integrations.update`);
114434
- await this.handle.patch(id, { enabled });
114435
- await this.hooks.onChanged?.(id, "enabled");
114436
- return { ok: true };
114437
- };
114438
- /** The row and its keychain refs go together (the records door). */
114439
- deleteInstance = async ({ id }) => {
114440
- await this.handle.delete(id);
114441
- await this.hooks.onChanged?.(id, "deleted");
114442
- return { ok: true };
114443
- };
114444
- testInstance = async (input) => {
114445
- if (this.hooks.test === void 0) return {
114446
- success: false,
114447
- status: "unsupported",
114448
- error: "This integration declares no connection test"
114449
- };
114450
- return this.hooks.test(input);
114451
- };
114452
- /** The flat provider object to hand to `registerProvider`. */
114453
- toProvider() {
114454
- return {
114455
- describe: this.describe,
114456
- instanceFormSchema: this.instanceFormSchema,
114457
- listInstances: this.listInstances,
114458
- getInstance: this.getInstance,
114459
- createInstance: this.createInstance,
114460
- updateInstance: this.updateInstance,
114461
- setInstanceEnabled: this.setInstanceEnabled,
114462
- deleteInstance: this.deleteInstance,
114463
- testInstance: this.testInstance
114464
- };
114465
- }
114466
- };
115131
+ targetId: string().optional()
115132
+ }), array(DiscoveredTargetSchema), { auth: "admin" }), method(object({
115133
+ kind: string(),
115134
+ config: record(string(), unknown()),
115135
+ /** See `discoverTargets.targetId` — restore stored secrets for a blank password. */
115136
+ targetId: string().optional()
115137
+ }), ProbeTargetConfigResultSchema, {
115138
+ kind: "mutation",
115139
+ auth: "admin"
115140
+ }), method(object({
115141
+ targetId: string(),
115142
+ notification: NotificationSchema
115143
+ }), SendResultSchema, {
115144
+ kind: "mutation",
115145
+ auth: "admin"
115146
+ }), method(object({
115147
+ targetId: string(),
115148
+ sample: NotificationSchema.optional()
115149
+ }), TestResultSchema, {
115150
+ kind: "mutation",
115151
+ auth: "admin"
115152
+ }), method(object({
115153
+ target: TargetSchema,
115154
+ /**
115155
+ * Duplicate flow: create a NEW target id while copying secrets from an
115156
+ * existing row. The UI never holds the stored token; blank / redacted
115157
+ * password fields are restored from this source (D634 still applies if
115158
+ * destinations diverge without a re-typed secret).
115159
+ */
115160
+ cloneSecretsFrom: string().optional()
115161
+ }), TargetSchema, {
115162
+ kind: "mutation",
115163
+ auth: "admin"
115164
+ }), method(object({ targetId: string() }), _void(), {
115165
+ kind: "mutation",
115166
+ auth: "admin"
115167
+ }), method(object({
115168
+ targetId: string(),
115169
+ enabled: boolean()
115170
+ }), _void(), {
115171
+ kind: "mutation",
115172
+ auth: "admin"
115173
+ });
115174
+ looseObject({
115175
+ name: string().min(1),
115176
+ enabled: boolean().optional()
115177
+ });
115178
+ TargetSchema.omit({ id: true });
114467
115179
  var EncodeProfileSchema = object({
114468
115180
  video: object({
114469
115181
  codec: _enum([
@@ -121528,31 +122240,21 @@ var APPLIANCE_CAP_VOCABULARY = {
121528
122240
  "pet-fountain": {
121529
122241
  scope: "device",
121530
122242
  noun: t("Pet fountain", "Fontana per animali"),
121531
- actions: [
121532
- {
121533
- id: "petFountain.pumpOn",
121534
- method: "setPump",
121535
- label: t("Pump on", "Pompa accesa"),
121536
- phrase: t("Start the pump of {device}", "Avvia la pompa di {device}"),
121537
- icon: "play",
121538
- args: { on: true }
121539
- },
121540
- {
121541
- id: "petFountain.pumpOff",
121542
- method: "setPump",
121543
- label: t("Pump off", "Pompa spenta"),
121544
- phrase: t("Stop the pump of {device}", "Ferma la pompa di {device}"),
121545
- icon: "square",
121546
- args: { on: false }
121547
- },
121548
- {
121549
- id: "petFountain.resetDailyConsumption",
121550
- method: "resetDailyConsumption",
121551
- label: t("Clear daily consumption", "Azzera il consumo giornaliero"),
121552
- phrase: t("Clear the daily water consumption of {device}", "Azzera il consumo giornaliero di acqua di {device}"),
121553
- icon: "rotate-ccw"
121554
- }
121555
- ],
122243
+ actions: [{
122244
+ id: "petFountain.pumpOn",
122245
+ method: "setPump",
122246
+ label: t("Pump on", "Pompa accesa"),
122247
+ phrase: t("Start the pump of {device}", "Avvia la pompa di {device}"),
122248
+ icon: "play",
122249
+ args: { on: true }
122250
+ }, {
122251
+ id: "petFountain.pumpOff",
122252
+ method: "setPump",
122253
+ label: t("Pump off", "Pompa spenta"),
122254
+ phrase: t("Stop the pump of {device}", "Ferma la pompa di {device}"),
122255
+ icon: "square",
122256
+ args: { on: false }
122257
+ }],
121556
122258
  state: [{
121557
122259
  kind: "boolean",
121558
122260
  field: "empty",
@@ -123571,7 +124273,6 @@ var SYSTEM_CAP_VOCABULARY = {
123571
124273
  "calendar-source": system(INTERNAL),
123572
124274
  calendars: system("calendars feed schedules and conditions, not device actions"),
123573
124275
  composer: system("device composition — an authoring tool, not an action"),
123574
- "connection-test": system(INTERNAL),
123575
124276
  "core-blocks": system(INTERNAL),
123576
124277
  "custom-model-registry": system(ML),
123577
124278
  "data-store-provider": system(INTERNAL),
@@ -145330,637 +146031,223 @@ var AutomationStepTraceSchema = object({
145330
146031
  kind: string().min(1),
145331
146032
  cap: string().optional(),
145332
146033
  method: string().optional(),
145333
- /** The vocabulary action the step performs (`cover.open`), when it names one. */
145334
- actionId: string().optional(),
145335
- deviceId: number().int().optional(),
145336
- /** What happened per device, when the step drove several (or a domain). */
145337
- devices: array(StepDeviceTraceSchema).optional(),
145338
- startedAt: number().optional(),
145339
- endedAt: number().optional(),
145340
- /**
145341
- * The parameters the step SENT, after `{{vars.x}}` substitution — what the
145342
- * device was actually asked. Bounded like trigger `vars`; a secret parameter
145343
- * is shown as {@link REDACTED_ARG}. Absent on traces written before it existed.
145344
- */
145345
- args: record(string(), TraceValueSchema).optional(),
145346
- /** `empty`: the target resolved to no device, so nothing was done — never silently `ok`. */
145347
- outcome: _enum([
145348
- "ok",
145349
- "error",
145350
- "not-run",
145351
- "empty"
145352
- ]),
145353
- message: string().optional()
145354
- });
145355
- var AutomationRunTraceSchema = object({
145356
- runId: string().min(1),
145357
- startedAt: number(),
145358
- endedAt: number(),
145359
- trigger: AutomationTriggerTraceSchema,
145360
- conditions: array(AutomationConditionTraceNodeSchema),
145361
- verdict: AutomationRunVerdictSchema.optional(),
145362
- steps: array(AutomationStepTraceSchema),
145363
- outcome: AutomationRunOutcomeSchema,
145364
- /** How many identical consecutive skips this trace stands for (>= 1). */
145365
- repeat: number().int().min(1),
145366
- /** When the latest of those repeats happened. */
145367
- lastAt: number(),
145368
- /**
145369
- * A scheduler point's own outcome (D983). `outcome` carries the closest
145370
- * automation outcome so a reader that does not know schedulers still reads
145371
- * the trace; this field says exactly what happened.
145372
- */
145373
- scheduler: SchedulerOutcomeSchema.optional()
145374
- });
145375
- /**
145376
- * What the hub's `runs` ledger holds for one owner (`automation:<blockId>` or
145377
- * `action:<actionId>`): the cooldown stamp and the trace ring.
145378
- */
145379
- var AutomationStateDocSchema = object({
145380
- version: literal(1),
145381
- lastRunStartedAt: number().nullable(),
145382
- traces: array(AutomationRunTraceSchema)
145383
- });
145384
- /**
145385
- * Actions — named, runnable things an operator (or an automation) can start,
145386
- * declared as LIST ENTRIES, never as devices.
145387
- *
145388
- * An entry is either **internal** (a short list of cap/wait steps kept in the
145389
- * hub's `actions` record kind) or declared by an addon through the
145390
- * `action-source` collection (a Home Assistant script, a scene …). The one
145391
- * surface the UI and automations talk to is the `actions` cap; it keeps no
145392
- * catalog of its own (D3) — every `list` asks the providers live.
145393
- *
145394
- * This file is the data half: the entry schema, the variables an entry may
145395
- * declare, and the pure resolution of the values a run was given. It holds no
145396
- * runtime.
145397
- */
145398
- /** What a variable's value is. `select` takes one of `options`. */
145399
- var ActionVariableTypeSchema = _enum([
145400
- "string",
145401
- "number",
145402
- "boolean",
145403
- "select"
145404
- ]);
145405
- var ACTION_VARIABLE_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
145406
- var ActionVariableValueSchema = union([
145407
- string(),
145408
- number(),
145409
- boolean()
145410
- ]);
145411
- /**
145412
- * One declared variable. Steps reference it as `{ $var: 'name' }` (the whole
145413
- * value) or `{{vars.name}}` (inside a string) in their args.
145414
- */
145415
- var ActionVariableSchema = object({
145416
- name: string().regex(ACTION_VARIABLE_NAME_RE),
145417
- label: string().min(1).max(120).optional(),
145418
- type: ActionVariableTypeSchema,
145419
- required: boolean().optional(),
145420
- default: ActionVariableValueSchema.optional(),
145421
- /** The allowed values of a `select`. */
145422
- options: array(string().min(1)).min(1).optional()
145423
- }).superRefine((v, ctx) => {
145424
- if (v.type === "select" && v.options === void 0) ctx.addIssue({
145425
- code: "custom",
145426
- message: "a select variable needs options",
145427
- path: ["options"]
145428
- });
145429
- if (v.default !== void 0 && variableValueError(v, v.default) !== null) ctx.addIssue({
145430
- code: "custom",
145431
- message: variableValueError(v, v.default) ?? "invalid default",
145432
- path: ["default"]
145433
- });
145434
- });
145435
- /** Why `value` is not a legal value for the variable, or null when it is. */
145436
- function variableValueError(variable, value) {
145437
- switch (variable.type) {
145438
- case "string": return typeof value === "string" ? null : `variable "${variable.name}" must be a string`;
145439
- case "number": return typeof value === "number" && Number.isFinite(value) ? null : `variable "${variable.name}" must be a number`;
145440
- case "boolean": return typeof value === "boolean" ? null : `variable "${variable.name}" must be true or false`;
145441
- case "select": return typeof value === "string" && (variable.options ?? []).includes(value) ? null : `variable "${variable.name}" must be one of ${(variable.options ?? []).join(", ")}`;
145442
- }
145443
- }
145444
- var ActionSourceKindSchema = _enum(["internal", "addon"]);
145445
- function isInternalActionId(actionId) {
145446
- return actionId.startsWith("internal:") && actionId.length > 9;
145447
- }
145448
- /** The addon behind a `<addonId>:<localId>` id, or null for anything else (internal included). */
145449
- function addonIdOfActionId(actionId) {
145450
- if (isInternalActionId(actionId)) return null;
145451
- const at = actionId.indexOf(":");
145452
- return at > 0 && at < actionId.length - 1 ? actionId.slice(0, at) : null;
145453
- }
145454
- var ActionStatusSchema = object({
145455
- isRunning: boolean(),
145456
- /** Ms epoch the latest run STARTED; null when it never ran. */
145457
- lastRunAt: number().nullable(),
145458
- /** The latest run's failure; null on success or when it never ran. */
145459
- lastError: string().nullable()
145460
- });
145461
- var ActionEntrySchema = object({
145462
- /** `internal:<uuid>` or `<addonId>:<localId>`. */
145463
- id: string().min(3),
145464
- name: string().min(1).max(120),
145465
- /** The addon that declared it; `core-blocks` for an internal one. */
145466
- addonId: string().min(1),
145467
- source: ActionSourceKindSchema,
145468
- /** An addon-declared entry is edited where it was declared. */
145469
- readOnly: boolean(),
145470
- /** Internal only: cap and wait steps. No action-in-action, so no cycles. */
145471
- steps: array(ActionStepSchema).min(1).max(50).optional(),
145472
- variables: array(ActionVariableSchema).max(20).optional(),
145473
- status: ActionStatusSchema
145474
- }).superRefine((entry, ctx) => {
145475
- if (entry.source === "internal") {
145476
- if (!isInternalActionId(entry.id)) ctx.addIssue({
145477
- code: "custom",
145478
- message: "an internal action id is internal:<uuid>",
145479
- path: ["id"]
145480
- });
145481
- return;
145482
- }
145483
- if (entry.steps !== void 0) ctx.addIssue({
145484
- code: "custom",
145485
- message: "only an internal action carries steps",
145486
- path: ["steps"]
145487
- });
145488
- if (!entry.readOnly) ctx.addIssue({
145489
- code: "custom",
145490
- message: "an addon action is read-only here",
145491
- path: ["readOnly"]
145492
- });
145493
- if (addonIdOfActionId(entry.id) === null) ctx.addIssue({
145494
- code: "custom",
145495
- message: "an addon action id is <addonId>:<localId>",
145496
- path: ["id"]
145497
- });
145498
- });
145499
- /** What an operator writes for an internal action. */
145500
- var ActionInputSchema = object({
145501
- name: string().min(1).max(120),
145502
- steps: array(ActionStepSchema).min(1).max(50),
145503
- variables: array(ActionVariableSchema).max(20).optional()
145504
- });
145505
- /** Who started a run. Absent = the operator pressed it. */
145506
- var ActionRunOriginSchema = object({
145507
- /** The automation block whose step started it. */
145508
- blockId: string().min(1).optional() });
145509
- /** `started` = the caller did not ask to wait. */
145510
- var ActionRunOutcomeSchema = union([AutomationRunOutcomeSchema, literal("started")]);
145511
- var ActionRunResultSchema = object({
145512
- runId: string().min(1),
145513
- outcome: ActionRunOutcomeSchema,
145514
- /** Why it did not run, or what failed. */
145515
- message: string().optional()
145516
- });
145517
- _enum([
145518
- "not-found",
145519
- "read-only",
145520
- "invalid-variables",
145521
- "invalid-steps",
145522
- "not-linked",
145523
- "busy"
145524
- ]);
145525
- object({
145526
- actionId: string(),
145527
- runId: string(),
145528
- isRunning: boolean(),
145529
- /** Set when the run ended. */
145530
- outcome: AutomationRunOutcomeSchema.optional(),
145531
- lastRunAt: number().nullable(),
145532
- lastError: string().nullable()
145533
- });
145534
- /** A bare number accepted as a base unit — the save succeeded, say so. */
145535
- var UnitWarningSchema = object({
145536
- /** Where in the saved record, e.g. `conditions.children.0` or `steps.2.args.grams`. */
145537
- path: string(),
145538
- deviceId: number().int().optional(),
145539
- field: string(),
145540
- value: number(),
145541
- assumedUnit: string(),
145542
- message: string()
145543
- });
145544
- /**
145545
- * notification-output — canonical, capability-gated notification delivery.
145546
- *
145547
- * Apprise-derived model (see
145548
- * `docs/superpowers/specs/2026-07-03-notification-output-notifier-matrix.md`):
145549
- * callers emit ONE canonical `Notification`; each provider declares a
145550
- * per-kind capability descriptor (`TargetKind`), and the pure degrade
145551
- * engine (`@camstack/types` `prepareNotification`) transcodes / degrades the
145552
- * message to what the kind supports — callers never special-case a service.
145553
- *
145554
- * DESIGN DECISIONS (locked):
145555
- * - Target CRUD lives on THIS cap (`upsertTarget` / `deleteTarget` /
145556
- * `setTargetEnabled`), each provider persisting via the `settings-store`
145557
- * cap. Rationale: the admin UI needs one uniform surface across the
145558
- * notifiers addon AND the HA addon; the addon-`globalSettingsSchema`-array
145559
- * alternative would fork the UI per addon and cannot host the
145560
- * discovery→adopt flow.
145561
- * - `listTargetKinds` / `listTargets` / `discoverTargets` return arrays →
145562
- * the generated cap-mount auto-`concatCollection`-fans them across every
145563
- * registered provider (notifiers addon + HA addon) so one catalog is
145564
- * routable. `send` / `testTarget` / CRUD route to ONE provider by the
145565
- * `addonId` the generated collection router extracts from the call input.
145566
- * - `Attachment.bytes` is `Uint8Array`. Transport-safe: superjson (the tRPC
145567
- * transformer) + UDS MsgPack both round-trip typed arrays — already used by
145568
- * `storage` / `storage-provider` / `recording` caps over the same path. No
145569
- * base64 fallback needed.
145570
- *
145571
- * TODO (deferred, closed-set change — separate decision): add
145572
- * `providerKind: 'notify'` so notification providers surface on the unified
145573
- * admin "Integrations" page.
145574
- */
145575
- /**
145576
- * Zentik-derived typed-media enum — the superset across every kind. Each
145577
- * adapter picks what it supports and the degrade engine filters the rest.
145578
- */
145579
- var AttachmentMediaTypeSchema = _enum([
145580
- "image",
145581
- "video",
145582
- "gif",
145583
- "audio",
145584
- "icon"
145585
- ]);
145586
- /**
145587
- * A single attachment. Exactly one of `url` (remote source, most adapters
145588
- * prefer this) or `bytes` (inline source; required for Pushover-style
145589
- * bytes-only kinds) MUST be present — the degrade engine expresses a
145590
- * url→bytes fetch as a `needsFetch` directive the adapter executes.
145591
- */
145592
- var AttachmentSchema = object({
145593
- mediaType: AttachmentMediaTypeSchema,
145594
- url: string().optional(),
145595
- bytes: _instanceof(Uint8Array).optional(),
145596
- mime: string().optional(),
145597
- name: string().optional()
145598
- }).refine((a) => a.url !== void 0 || a.bytes !== void 0, { message: "Attachment requires either `url` or `bytes`" });
145599
- var NotificationFormatSchema = _enum([
145600
- "text",
145601
- "markdown",
145602
- "html"
145603
- ]);
145604
- /**
145605
- * The CLOSED icon vocabulary an action button may use.
145606
- *
145607
- * A closed set, not a free string, and that is the whole point: an arbitrary
145608
- * icon name is one that ntfy renders, zentik silently drops, and nobody
145609
- * notices — the same class of gap as a zone vocabulary nothing produced
145610
- * ([D35](../../../docs/decisions/adr-0035.md)). Every adapter maps this set or
145611
- * declares `actionIcons: false` and the degrade engine strips the field.
145612
- *
145613
- * Named by INTENT, never by glyph. "check" would tie the vocabulary to one
145614
- * renderer's icon set; "acknowledge" survives an adapter that draws it
145615
- * differently.
145616
- *
145617
- * ── A TOKEN IS NOT A WIRE VALUE ─────────────────────────────────────
145618
- *
145619
- * These names are for US. **No adapter may forward one verbatim.** Each maps
145620
- * the whole set onto its own renderer's vocabulary through a
145621
- * `Record<NotificationActionIcon, string>` — a Record, never a lookup with a
145622
- * fallback, so adding a member here fails every adapter's build until someone
145623
- * decides its glyph, which is the only place that decision can be made
145624
- * honestly.
145625
- *
145626
- * This paragraph is the bug. Zentik declared `actionIcons: true` and passed
145627
- * `disarm` straight through; iOS feeds that string to
145628
- * `UNNotificationActionIcon(systemImageName:)`, `disarm` is not an SF Symbol,
145629
- * and every snooze and alarm button arrived BLANK. A pass-through is not a
145630
- * mapping, and "the field is documented" is not "the value renders".
145631
- *
145632
- * Adding a member is TRAIN-BOUND. The enum lives in the published
145633
- * `@camstack/server` closure and the cap seam validates against the HUB's copy,
145634
- * so an addon that emits a token the running hub does not know does not lose an
145635
- * icon — its whole `send` fails Zod validation and the notification never
145636
- * arrives. Never emit a new token from an addon before the train carrying it.
145637
- */
145638
- var NotificationActionIconSchema = _enum([
145639
- "acknowledge",
145640
- "dismiss",
145641
- "silence",
145642
- "snooze",
145643
- "view",
145644
- "play",
145645
- "open",
145646
- "close",
145647
- "lock",
145648
- "unlock",
145649
- "arm",
145650
- "arm-home",
145651
- "arm-away",
145652
- "arm-night",
145653
- "disarm",
145654
- "light",
145655
- "alert",
145656
- "camera"
145657
- ]);
145658
- /** A single tap-through action button. */
145659
- var NotificationActionSchema = object({
145660
- id: string(),
145661
- label: string(),
145662
- url: string().optional(),
145663
- /** Dropped by the degrade engine for a kind with `caps.actionIcons: false`. */
145664
- icon: NotificationActionIconSchema.optional(),
145665
- /**
145666
- * Renders in a warning style where the notifier supports it.
145667
- *
145668
- * A HINT, never a gate. The callback's authority is its token and nothing
145669
- * else — see `notification-center/action-token.ts` for what that does and
145670
- * does not buy.
145671
- */
145672
- destructive: boolean().optional(),
145673
- /**
145674
- * How the tap should REACH the url.
145675
- *
145676
- * `navigate` (absent, and every button authored before this field) opens it:
145677
- * the phone leaves the notification and shows whatever the callback returns.
145678
- * That is right for a button whose answer the operator wants to read.
145679
- *
145680
- * `background` fires it as a POST and stays put. It exists for the buttons
145681
- * whose whole point is not to interrupt — "silence this for 30 minutes" is
145682
- * an answer to the notification, and being thrown into a browser tab to
145683
- * confirm it costs more attention than the notification did. A backend that
145684
- * cannot do a background call renders it as an ordinary link (the adapters
145685
- * fall back rather than dropping the button), so this is a preference, never
145686
- * a requirement.
145687
- */
145688
- mode: _enum(["navigate", "background"]).optional()
145689
- });
145690
- /** A delivery parameter value: what a notifier declared it takes. */
145691
- var DeliveryParamValueSchema = union([
145692
- string(),
145693
- number(),
145694
- boolean()
145695
- ]);
145696
- /**
145697
- * One extra delivery parameter a notifier KIND declares (D938). A rule that
145698
- * addresses a target of that kind may set it; a kind that declares nothing is
145699
- * never handed one. The admin UI derives its control from this descriptor —
145700
- * no editor knows a service by name.
145701
- *
145702
- * Optional fields are `.optional()`, never `.default()` (a Zod default does not
145703
- * run on the addon cap path).
145704
- */
145705
- var DeliveryParamSchema = object({
145706
- key: string().min(1),
145707
- label: string(),
145708
- /** i18n key of the label, resolved by the declaring addon's namespace. */
145709
- labelKey: string().optional(),
145710
- type: _enum([
145711
- "enum",
145712
- "number",
145713
- "boolean",
145714
- "string"
145715
- ]),
145716
- /** `enum` only: the closed set of accepted values. */
145717
- options: array(object({
145718
- value: string(),
145719
- label: string()
145720
- })).optional(),
145721
- /** `number` only. */
145722
- min: number().optional(),
145723
- max: number().optional(),
145724
- /** What the notifier does when the rule sets nothing; shown as the placeholder. */
145725
- default: DeliveryParamValueSchema.optional()
145726
- });
145727
- /**
145728
- * The canonical notification. `body` is the only hard field (Apprise model).
145729
- * `priority` is a 5-level ORDINAL (1=lowest … 3=normal(default) … 5=urgent),
145730
- * NOT a fixed severity enum — each kind declares its own `caps.levels` and
145731
- * the adapter maps this ordinal onto its native level. `level?` is an
145732
- * optional kind-native level id (`emergency`, `silent`, …) that overrides
145733
- * `priority` for that one target.
145734
- */
145735
- var NotificationSchema = object({
145736
- body: string(),
145737
- title: string().optional(),
145738
- format: NotificationFormatSchema.default("text"),
145739
- priority: number().int().min(1).max(5).default(3),
145740
- level: string().optional(),
145741
- attachments: array(AttachmentSchema).optional(),
145742
- clickUrl: string().optional(),
145743
- actions: array(NotificationActionSchema).optional(),
145744
- sound: string().optional(),
145745
- ttl: number().optional(),
145746
- tag: string().optional(),
145747
- deviceId: number().optional(),
145748
- eventId: string().optional(),
145749
- metadata: record(string(), unknown()).optional(),
146034
+ /** The vocabulary action the step performs (`cover.open`), when it names one. */
146035
+ actionId: string().optional(),
146036
+ deviceId: number().int().optional(),
146037
+ /** What happened per device, when the step drove several (or a domain). */
146038
+ devices: array(StepDeviceTraceSchema).optional(),
146039
+ startedAt: number().optional(),
146040
+ endedAt: number().optional(),
145750
146041
  /**
145751
- * Values for the parameters the target's kind DECLARES in
145752
- * {@link TargetKindSchema} `deliveryParams`. Already validated against the
145753
- * declaration by the sender; a notifier reads only the keys it declared.
146042
+ * The parameters the step SENT, after `{{vars.x}}` substitution — what the
146043
+ * device was actually asked. Bounded like trigger `vars`; a secret parameter
146044
+ * is shown as {@link REDACTED_ARG}. Absent on traces written before it existed.
145754
146045
  */
145755
- delivery: record(string(), DeliveryParamValueSchema).optional()
145756
- });
145757
- /** One declared native severity/priority level for a kind. */
145758
- var TargetKindLevelSchema = object({
145759
- id: string(),
145760
- label: string(),
145761
- /** Which canonical priority (1..5) this level maps to. `null` = qualitative-only. */
145762
- ordinal: number().int().min(1).max(5).nullable(),
145763
- flags: object({
145764
- critical: boolean().optional(),
145765
- silent: boolean().optional(),
145766
- noPush: boolean().optional()
145767
- }).optional(),
145768
- /** e.g. Pushover `emergency` requires `retry` / `expire`. */
145769
- requires: array(string()).optional(),
145770
- description: string().optional()
146046
+ args: record(string(), TraceValueSchema).optional(),
146047
+ /** `empty`: the target resolved to no device, so nothing was done — never silently `ok`. */
146048
+ outcome: _enum([
146049
+ "ok",
146050
+ "error",
146051
+ "not-run",
146052
+ "empty"
146053
+ ]),
146054
+ message: string().optional()
145771
146055
  });
145772
- /** The full capability block consulted before dispatch. */
145773
- var TargetKindCapsSchema = object({
145774
- attachments: object({
145775
- mediaTypes: array(AttachmentMediaTypeSchema),
145776
- mode: _enum([
145777
- "url",
145778
- "bytes",
145779
- "both"
145780
- ]),
145781
- max: number().int().nonnegative(),
145782
- maxBytes: number().int().positive().optional()
145783
- }),
145784
- /** Max action buttons (0 = none). */
145785
- actions: number().int().nonnegative(),
146056
+ var AutomationRunTraceSchema = object({
146057
+ runId: string().min(1),
146058
+ startedAt: number(),
146059
+ endedAt: number(),
146060
+ trigger: AutomationTriggerTraceSchema,
146061
+ conditions: array(AutomationConditionTraceNodeSchema),
146062
+ verdict: AutomationRunVerdictSchema.optional(),
146063
+ steps: array(AutomationStepTraceSchema),
146064
+ outcome: AutomationRunOutcomeSchema,
146065
+ /** How many identical consecutive skips this trace stands for (>= 1). */
146066
+ repeat: number().int().min(1),
146067
+ /** When the latest of those repeats happened. */
146068
+ lastAt: number(),
145786
146069
  /**
145787
- * Whether this kind renders a per-action ICON.
145788
- *
145789
- * `.optional()`, deliberately NOT `.default(false)`: a Zod default does not
145790
- * run on the addon cap path — three production failures in one day taught
145791
- * this repo that once. Absent is read as false by the degrade engine, which
145792
- * is the safe direction: an icon that is not rendered costs nothing, an icon
145793
- * assumed and dropped costs the operator's trust in the field.
146070
+ * A scheduler point's own outcome (D983). `outcome` carries the closest
146071
+ * automation outcome so a reader that does not know schedulers still reads
146072
+ * the trace; this field says exactly what happened.
145794
146073
  */
145795
- actionIcons: boolean().optional(),
145796
- levels: array(TargetKindLevelSchema),
145797
- format: array(NotificationFormatSchema),
145798
- clickUrl: boolean(),
145799
- sound: boolean(),
145800
- ttl: boolean(),
145801
- bodyMaxLen: number().int().positive()
146074
+ scheduler: SchedulerOutcomeSchema.optional()
145802
146075
  });
145803
146076
  /**
145804
- * `configSchema` is a `ConfigUISchema` tree passed through to the admin
145805
- * FormBuilder. Stored as `z.unknown()` at the cap seam (mirrors
145806
- * `device-provider.getChildCreationSchema` `CreationSchemaOutputSchema`) —
145807
- * the union is large and not meant for runtime validation here; the exported
145808
- * `TargetKind` type re-tightens `configSchema` to `ConfigUISchema`.
146077
+ * What the hub's `runs` ledger holds for one owner (`automation:<blockId>` or
146078
+ * `action:<actionId>`): the cooldown stamp and the trace ring.
145809
146079
  */
145810
- var ConfigSchemaPassthrough$4 = unknown();
145811
- var TargetKindSchema = object({
145812
- kind: string(),
145813
- label: string(),
145814
- icon: string(),
145815
- /** Stamped by each provider so the concat-fanned catalog stays routable. */
145816
- addonId: string(),
145817
- /**
145818
- * URL of the kind's bundled BRAND icon, served by the providing addon over
145819
- * its own `addon-routes` surface (`/addon/<addonId>/icons/<kind>`). Absent
145820
- * when the addon bundles no icon for that kind — the client then falls back
145821
- * to a neutral glyph rather than rendering the raw `icon` NAME as text.
145822
- *
145823
- * Root-relative on purpose: it resolves against whatever origin serves a web
145824
- * client, and a native client joins it onto its own hub base.
145825
- *
145826
- * DECLARED here deliberately. It used to travel as an undeclared passthrough
145827
- * field that survived only because the runtime cap-router forwards provider
145828
- * output verbatim — so every consumer had to re-declare it by hand to stop
145829
- * its own Zod parse from stripping it, and the whole arrangement would have
145830
- * broken silently the moment output validation was tightened anywhere.
145831
- */
145832
- iconUrl: string().optional(),
145833
- /**
145834
- * Media type of {@link iconUrl} (`image/svg+xml`, `image/png`, …).
145835
- *
145836
- * The server knows this and therefore says it, because the client cannot
145837
- * safely guess: a React-Native client renders SVG and raster through two
145838
- * DIFFERENT components (`react-native-svg` vs `expo-image` — expo-image does
145839
- * not decode SVG on iOS/Android), so without this it silently fell back to a
145840
- * placeholder glyph for every vector icon while the web build looked fine.
145841
- *
145842
- * Absent when {@link iconUrl} is absent, or for a legacy provider that has
145843
- * not been updated — a client that cannot determine the type should prefer
145844
- * its raster path, which is the safe default for an unknown image.
145845
- */
145846
- iconMediaType: string().optional(),
145847
- configSchema: ConfigSchemaPassthrough$4,
145848
- /**
145849
- * The config keys that decide WHERE this kind's secrets are sent (server,
145850
- * base URL, instance, chat, recipient). A save that changes any of them
145851
- * while leaving a secret redacted is refused by the provider (D634), so an
145852
- * editor uses this to ask for the secret on exactly those edits instead of
145853
- * on every edit.
145854
- *
145855
- * Optional: absent from a provider that holds no secret (the Home Assistant
145856
- * kinds) and from a provider older than this field — an editor that finds
145857
- * it absent must assume ANY edit may need the secret.
145858
- */
145859
- destinationKeys: array(string()).optional(),
145860
- supportsDiscovery: boolean(),
145861
- /**
145862
- * Extra delivery parameters a rule may set for a target of this kind (D938).
145863
- * Absent = none; the rule editor then offers nothing.
145864
- */
145865
- deliveryParams: array(DeliveryParamSchema).optional(),
145866
- caps: TargetKindCapsSchema
146080
+ var AutomationStateDocSchema = object({
146081
+ version: literal(1),
146082
+ lastRunStartedAt: number().nullable(),
146083
+ traces: array(AutomationRunTraceSchema)
145867
146084
  });
145868
146085
  /**
145869
- * A persisted target. `config` holds secrets; providers REDACT secret fields
145870
- * (return a presence marker only) when serving `listTargets` — never
145871
- * round-trip a stored secret to the UI.
146086
+ * Actions — named, runnable things an operator (or an automation) can start,
146087
+ * declared as LIST ENTRIES, never as devices.
146088
+ *
146089
+ * An entry is either **internal** (a short list of cap/wait steps kept in the
146090
+ * hub's `actions` record kind) or declared by an addon through the
146091
+ * `action-source` collection (a Home Assistant script, a scene …). The one
146092
+ * surface the UI and automations talk to is the `actions` cap; it keeps no
146093
+ * catalog of its own (D3) — every `list` asks the providers live.
146094
+ *
146095
+ * This file is the data half: the entry schema, the variables an entry may
146096
+ * declare, and the pure resolution of the values a run was given. It holds no
146097
+ * runtime.
145872
146098
  */
145873
- var TargetSchema = object({
145874
- id: string(),
145875
- name: string(),
145876
- kind: string(),
145877
- addonId: string(),
145878
- enabled: boolean(),
145879
- config: record(string(), unknown())
146099
+ /** What a variable's value is. `select` takes one of `options`. */
146100
+ var ActionVariableTypeSchema = _enum([
146101
+ "string",
146102
+ "number",
146103
+ "boolean",
146104
+ "select"
146105
+ ]);
146106
+ var ACTION_VARIABLE_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
146107
+ var ActionVariableValueSchema = union([
146108
+ string(),
146109
+ number(),
146110
+ boolean()
146111
+ ]);
146112
+ /**
146113
+ * One declared variable. Steps reference it as `{ $var: 'name' }` (the whole
146114
+ * value) or `{{vars.name}}` (inside a string) in their args.
146115
+ */
146116
+ var ActionVariableSchema = object({
146117
+ name: string().regex(ACTION_VARIABLE_NAME_RE),
146118
+ label: string().min(1).max(120).optional(),
146119
+ type: ActionVariableTypeSchema,
146120
+ required: boolean().optional(),
146121
+ default: ActionVariableValueSchema.optional(),
146122
+ /** The allowed values of a `select`. */
146123
+ options: array(string().min(1)).min(1).optional()
146124
+ }).superRefine((v, ctx) => {
146125
+ if (v.type === "select" && v.options === void 0) ctx.addIssue({
146126
+ code: "custom",
146127
+ message: "a select variable needs options",
146128
+ path: ["options"]
146129
+ });
146130
+ if (v.default !== void 0 && variableValueError(v, v.default) !== null) ctx.addIssue({
146131
+ code: "custom",
146132
+ message: variableValueError(v, v.default) ?? "invalid default",
146133
+ path: ["default"]
146134
+ });
145880
146135
  });
145881
- /** A discovery-surfaced candidate (config is partial + non-secret). */
145882
- var DiscoveredTargetSchema = object({
145883
- kind: string(),
145884
- suggestedName: string(),
145885
- config: record(string(), unknown())
146136
+ /** Why `value` is not a legal value for the variable, or null when it is. */
146137
+ function variableValueError(variable, value) {
146138
+ switch (variable.type) {
146139
+ case "string": return typeof value === "string" ? null : `variable "${variable.name}" must be a string`;
146140
+ case "number": return typeof value === "number" && Number.isFinite(value) ? null : `variable "${variable.name}" must be a number`;
146141
+ case "boolean": return typeof value === "boolean" ? null : `variable "${variable.name}" must be true or false`;
146142
+ case "select": return typeof value === "string" && (variable.options ?? []).includes(value) ? null : `variable "${variable.name}" must be one of ${(variable.options ?? []).join(", ")}`;
146143
+ }
146144
+ }
146145
+ var ActionSourceKindSchema = _enum(["internal", "addon"]);
146146
+ function isInternalActionId(actionId) {
146147
+ return actionId.startsWith("internal:") && actionId.length > 9;
146148
+ }
146149
+ /** The addon behind a `<addonId>:<localId>` id, or null for anything else (internal included). */
146150
+ function addonIdOfActionId(actionId) {
146151
+ if (isInternalActionId(actionId)) return null;
146152
+ const at = actionId.indexOf(":");
146153
+ return at > 0 && at < actionId.length - 1 ? actionId.slice(0, at) : null;
146154
+ }
146155
+ var ActionStatusSchema = object({
146156
+ isRunning: boolean(),
146157
+ /** Ms epoch the latest run STARTED; null when it never ran. */
146158
+ lastRunAt: number().nullable(),
146159
+ /** The latest run's failure; null on success or when it never ran. */
146160
+ lastError: string().nullable()
145886
146161
  });
145887
- /** The degrade engine's report — what was resolved / dropped / degraded. */
145888
- var RenderedAsSchema = object({
145889
- level: string(),
145890
- format: NotificationFormatSchema,
145891
- attachmentsSent: number().int().nonnegative(),
145892
- actionsSent: number().int().nonnegative(),
145893
- truncated: boolean(),
145894
- dropped: array(string())
146162
+ var ActionEntrySchema = object({
146163
+ /** `internal:<uuid>` or `<addonId>:<localId>`. */
146164
+ id: string().min(3),
146165
+ name: string().min(1).max(120),
146166
+ /** The addon that declared it; `core-blocks` for an internal one. */
146167
+ addonId: string().min(1),
146168
+ source: ActionSourceKindSchema,
146169
+ /** An addon-declared entry is edited where it was declared. */
146170
+ readOnly: boolean(),
146171
+ /** Internal only: cap and wait steps. No action-in-action, so no cycles. */
146172
+ steps: array(ActionStepSchema).min(1).max(50).optional(),
146173
+ variables: array(ActionVariableSchema).max(20).optional(),
146174
+ status: ActionStatusSchema
146175
+ }).superRefine((entry, ctx) => {
146176
+ if (entry.source === "internal") {
146177
+ if (!isInternalActionId(entry.id)) ctx.addIssue({
146178
+ code: "custom",
146179
+ message: "an internal action id is internal:<uuid>",
146180
+ path: ["id"]
146181
+ });
146182
+ return;
146183
+ }
146184
+ if (entry.steps !== void 0) ctx.addIssue({
146185
+ code: "custom",
146186
+ message: "only an internal action carries steps",
146187
+ path: ["steps"]
146188
+ });
146189
+ if (!entry.readOnly) ctx.addIssue({
146190
+ code: "custom",
146191
+ message: "an addon action is read-only here",
146192
+ path: ["readOnly"]
146193
+ });
146194
+ if (addonIdOfActionId(entry.id) === null) ctx.addIssue({
146195
+ code: "custom",
146196
+ message: "an addon action id is <addonId>:<localId>",
146197
+ path: ["id"]
146198
+ });
145895
146199
  });
145896
- var SendResultSchema = object({
145897
- success: boolean(),
145898
- error: string().optional(),
145899
- renderedAs: RenderedAsSchema.optional()
146200
+ /** What an operator writes for an internal action. */
146201
+ var ActionInputSchema = object({
146202
+ name: string().min(1).max(120),
146203
+ steps: array(ActionStepSchema).min(1).max(50),
146204
+ variables: array(ActionVariableSchema).max(20).optional()
145900
146205
  });
145901
- /** Same shape as SendResult — kept as a distinct name for the test panel. */
145902
- var TestResultSchema = SendResultSchema;
146206
+ /** Who started a run. Absent = the operator pressed it. */
146207
+ var ActionRunOriginSchema = object({
146208
+ /** The automation block whose step started it. */
146209
+ blockId: string().min(1).optional() });
145903
146210
  /**
145904
- * Pre-save credential probe against a partial (unsaved) target config.
145905
- * `resolvedUrl` never includes secrets (token stripped from path).
146211
+ * `started` = the caller did not ask to wait. `timed-out` = the run reached the
146212
+ * ceiling (`ACTION_RUN_MAX_MS`) and was stopped; it is never a `ran`.
145906
146213
  */
145907
- var ProbeTargetConfigResultSchema = object({
145908
- ok: boolean(),
145909
- resolvedUrl: string(),
145910
- httpStatus: number().int().optional(),
145911
- stateInstance: string().optional(),
145912
- error: string().optional()
146214
+ var ActionRunOutcomeSchema = union([
146215
+ AutomationRunOutcomeSchema,
146216
+ literal("started"),
146217
+ literal("timed-out")
146218
+ ]);
146219
+ var ActionRunResultSchema = object({
146220
+ runId: string().min(1),
146221
+ outcome: ActionRunOutcomeSchema,
146222
+ /** Why it did not run, or what failed. */
146223
+ message: string().optional()
145913
146224
  });
145914
- method(object({}), array(TargetKindSchema)), method(object({}), array(TargetSchema), { auth: "admin" }), method(object({ targetId: string() }), TargetSchema, { auth: "admin" }), method(object({
145915
- kind: string(),
145916
- config: record(string(), unknown()).optional(),
145917
- /**
145918
- * When editing / duplicating, the blank password field never round-trips
145919
- * the stored token. Pass the source target id so the provider can restore
145920
- * secrets server-side before dialling (same merge as upsert).
145921
- */
145922
- targetId: string().optional()
145923
- }), array(DiscoveredTargetSchema), { auth: "admin" }), method(object({
145924
- kind: string(),
145925
- config: record(string(), unknown()),
145926
- /** See `discoverTargets.targetId` — restore stored secrets for a blank password. */
145927
- targetId: string().optional()
145928
- }), ProbeTargetConfigResultSchema, {
145929
- kind: "mutation",
145930
- auth: "admin"
145931
- }), method(object({
145932
- targetId: string(),
145933
- notification: NotificationSchema
145934
- }), SendResultSchema, {
145935
- kind: "mutation",
145936
- auth: "admin"
145937
- }), method(object({
145938
- targetId: string(),
145939
- sample: NotificationSchema.optional()
145940
- }), TestResultSchema, {
145941
- kind: "mutation",
145942
- auth: "admin"
145943
- }), method(object({
145944
- target: TargetSchema,
145945
- /**
145946
- * Duplicate flow: create a NEW target id while copying secrets from an
145947
- * existing row. The UI never holds the stored token; blank / redacted
145948
- * password fields are restored from this source (D634 still applies if
145949
- * destinations diverge without a re-typed secret).
145950
- */
145951
- cloneSecretsFrom: string().optional()
145952
- }), TargetSchema, {
145953
- kind: "mutation",
145954
- auth: "admin"
145955
- }), method(object({ targetId: string() }), _void(), {
145956
- kind: "mutation",
145957
- auth: "admin"
145958
- }), method(object({
145959
- targetId: string(),
145960
- enabled: boolean()
145961
- }), _void(), {
145962
- kind: "mutation",
145963
- auth: "admin"
146225
+ _enum([
146226
+ "not-found",
146227
+ "read-only",
146228
+ "invalid-variables",
146229
+ "invalid-steps",
146230
+ "not-linked",
146231
+ "busy"
146232
+ ]);
146233
+ object({
146234
+ actionId: string(),
146235
+ runId: string(),
146236
+ isRunning: boolean(),
146237
+ /** Set when the run ended. */
146238
+ outcome: AutomationRunOutcomeSchema.optional(),
146239
+ lastRunAt: number().nullable(),
146240
+ lastError: string().nullable()
146241
+ });
146242
+ /** A bare number accepted as a base unit — the save succeeded, say so. */
146243
+ var UnitWarningSchema = object({
146244
+ /** Where in the saved record, e.g. `conditions.children.0` or `steps.2.args.grams`. */
146245
+ path: string(),
146246
+ deviceId: number().int().optional(),
146247
+ field: string(),
146248
+ value: number(),
146249
+ assumedUnit: string(),
146250
+ message: string()
145964
146251
  });
145965
146252
  _enum([
145966
146253
  "automation",
@@ -146029,6 +146316,8 @@ method(object({}), array(ActionEntrySchema), { auth: "admin" }), method(object({
146029
146316
  kind: "mutation",
146030
146317
  auth: "admin"
146031
146318
  });
146319
+ /** `timeoutMs` of `actions.run`: a waited call outlives any legal run. */
146320
+ var ACTION_RUN_TIMEOUT_MS = 363e4;
146032
146321
  /**
146033
146322
  * actions — the ONE surface for runnable actions, for the UI and for
146034
146323
  * automations. Provided by the core-blocks builtin on the hub.
@@ -146047,6 +146336,12 @@ method(object({}), array(ActionEntrySchema), { auth: "admin" }), method(object({
146047
146336
  * An admin, and an in-process caller (an automation block), may run any action.
146048
146337
  * Every refusal is typed (`[not-linked] …`) and logged.
146049
146338
  *
146339
+ * **A run lasts at most `ACTION_RUN_MAX_MS` (60 min).** The provider stops a
146340
+ * run that reaches it and answers `timed-out` (never `ran`); an action whose
146341
+ * `wait` steps alone add up to more is refused at create/update
146342
+ * (`[invalid-steps]`). `run` declares a `timeoutMs` above that ceiling, so a
146343
+ * waited call (an automation step) is never cut by the 60 s transport default.
146344
+ *
146050
146345
  * A second `run` of an action that is already running is REFUSED — traced and
146051
146346
  * logged — never queued.
146052
146347
  */
@@ -146073,7 +146368,8 @@ method(object({}), array(ActionEntrySchema), { auth: "admin" }), method(object({
146073
146368
  role: "viewer",
146074
146369
  auth: "protected",
146075
146370
  kind: "mutation",
146076
- caller: "required"
146371
+ caller: "required",
146372
+ timeoutMs: ACTION_RUN_TIMEOUT_MS
146077
146373
  }), method(ActionIdInput, _void(), {
146078
146374
  kind: "mutation",
146079
146375
  auth: "admin"
@@ -150492,37 +150788,6 @@ method(object({
150492
150788
  kind: "mutation",
150493
150789
  auth: "admin"
150494
150790
  }), method(object({ blockIds: array(string()) }), object({ states: array(CompositionBlockStateSchema) }), { auth: "admin" });
150495
- var ConnectionTestOutcomeSchema = discriminatedUnion("outcome", [
150496
- object({
150497
- outcome: literal("validated"),
150498
- /** Round-trip of the sign-in, when the provider measured it. */
150499
- latencyMs: number().nonnegative().optional(),
150500
- /** Optional human detail worth showing next to the tick
150501
- * ("3 devices visible on this account"). */
150502
- detail: string().optional()
150503
- }).strict(),
150504
- object({
150505
- outcome: literal("rejected"),
150506
- error: string()
150507
- }).strict(),
150508
- object({
150509
- outcome: literal("inconclusive"),
150510
- error: string()
150511
- }).strict()
150512
- ]);
150513
- var ConnectionTestInputSchema = object({
150514
- /** Candidate integration settings, exactly as the create form collected them. */
150515
- settings: record(string(), unknown()) });
150516
- /**
150517
- * What the provider's test actually DOES, so the UI can say it in words before
150518
- * the operator presses the button ("Signs in to the Dreo cloud"). Purely
150519
- * descriptive — it never changes routing.
150520
- */
150521
- var ConnectionTestDescriptorSchema = object({ label: string() });
150522
- method(ConnectionTestInputSchema, ConnectionTestOutcomeSchema, {
150523
- kind: "mutation",
150524
- auth: "admin"
150525
- }), method(_void(), ConnectionTestDescriptorSchema, { auth: "admin" });
150526
150791
  /**
150527
150792
  * Upstream-system connectivity sensor — distinct from `device-status`,
150528
150793
  * which is the kernel-managed online/offline flag for the device's
@@ -151100,6 +151365,9 @@ var MediaPlayerStatusSchema = object({
151100
151365
  /** Repeat mode. Null when no repeat surface.
151101
151366
  * Pair with `DeviceFeature.MediaPlayerRepeat`. */
151102
151367
  repeat: MediaPlayerRepeatSchema.nullable(),
151368
+ /** Ms epoch when `position` was read from the device. Null when the driver
151369
+ * does not say; a UI that advances the position while playing counts from it. */
151370
+ positionUpdatedAt: number().nullable().default(null),
151103
151371
  /** Ms epoch when the slice was last updated. */
151104
151372
  lastChangedAt: number()
151105
151373
  });
@@ -151735,7 +152003,9 @@ var ThresholdTransformDraftSchema = object({
151735
152003
  comparison: _enum(["gte", "lte"]),
151736
152004
  threshold: number(),
151737
152005
  startDwellMs: number().nonnegative(),
151738
- stopDwellMs: number().nonnegative()
152006
+ stopDwellMs: number().nonnegative(),
152007
+ /** Samples a start needs; absent = the compiler's default for the source (2 for running power, else 1). */
152008
+ minSamples: number().int().min(1).optional()
151739
152009
  });
151740
152010
  var CustomizeTransformDraftSchema = discriminatedUnion("kind", [
151741
152011
  IdentityTransformDraftSchema,
@@ -157665,6 +157935,7 @@ var IntegrationWithStateSchema = object({
157665
157935
  id: string(),
157666
157936
  addonId: string(),
157667
157937
  name: string(),
157938
+ /** A projection of the instance body's switch (`setInstanceEnabled` is the only writer). */
157668
157939
  enabled: boolean(),
157669
157940
  info: record(string(), unknown()).readonly(),
157670
157941
  /** The discovery candidate this integration was set up from (D984). */
@@ -157677,6 +157948,7 @@ var IntegrationLiteSchema = object({
157677
157948
  id: string(),
157678
157949
  addonId: string(),
157679
157950
  name: string(),
157951
+ /** A projection of the instance body's switch (`setInstanceEnabled` is the only writer). */
157680
157952
  enabled: boolean(),
157681
157953
  info: record(string(), unknown()).readonly(),
157682
157954
  /** The discovery candidate this integration was set up from (D984). */
@@ -157722,10 +157994,9 @@ var AvailableIntegrationTypeSchema = object({
157722
157994
  * locations" checkbox. Provider-declared in the addon manifest. */
157723
157995
  supportsLocationImport: boolean(),
157724
157996
  /**
157725
- * True when this integration DECLARES a pre-creation test (the
157726
- * `connection-test` cap, or a broker whose settings it stores). Drives the
157727
- * Test button: an integration that cannot be tested must say so up front
157728
- * rather than offering a button that always answers the same nonsense.
157997
+ * True when this integration's instances declare a Test (`integration-instances.describe().canTest`,
157998
+ * D1016). An integration that cannot be tested must say so up front rather than offering a
157999
+ * button that always answers the same nonsense.
157729
158000
  */
157730
158001
  canTest: boolean(),
157731
158002
  existingInstances: array(object({
@@ -157776,15 +158047,21 @@ var TestConnectionResultSchema = object({
157776
158047
  var CreateIntegrationInputSchema = object({
157777
158048
  addonId: string(),
157778
158049
  name: string(),
157779
- enabled: boolean().optional(),
157780
158050
  info: record(string(), unknown()).optional(),
157781
158051
  /** `stableId` of the discovery candidate the form was seeded from (D984). */
157782
158052
  originStableId: string().optional(),
157783
- settings: record(string(), unknown()).optional()
158053
+ settings: record(string(), unknown()).optional(),
158054
+ /** The instance kind being created, for a provider with several; omitted = its only testable kind. */
158055
+ kind: string().min(1).optional()
157784
158056
  });
157785
158057
  var UpdateIntegrationInputSchema = object({
157786
158058
  id: string(),
157787
158059
  name: string().optional(),
158060
+ /**
158061
+ * Accepted for a FIXED builtin only (`info.fixed`: alarm panel, camera grid, core blocks,
158062
+ * terminal), which keeps no instance record: the registry flag is its one store. Any other
158063
+ * integration is switched through `integration-instances.setInstanceEnabled`.
158064
+ */
157788
158065
  enabled: boolean().optional(),
157789
158066
  info: record(string(), unknown()).optional()
157790
158067
  });
@@ -157801,13 +158078,7 @@ method(_void(), array(IntegrationWithStateSchema)), method(object({ id: string()
157801
158078
  }), method(object({ id: string() }), DeleteIntegrationResultSchema, {
157802
158079
  kind: "mutation",
157803
158080
  auth: "admin"
157804
- }), method(_void(), array(AvailableIntegrationTypeSchema), { auth: "admin" }), method(object({
157805
- addonId: string(),
157806
- settings: record(string(), unknown())
157807
- }), TestConnectionResultSchema, {
157808
- kind: "mutation",
157809
- auth: "admin"
157810
- });
158081
+ }), method(_void(), array(AvailableIntegrationTypeSchema), { auth: "admin" });
157811
158082
  /**
157812
158083
  * `integration-instances` - the connection of an addon that holds ONE or SEVERAL
157813
158084
  * (an account, a relay, a destination) as typed records (D985, D986). The addon's
@@ -157832,7 +158103,7 @@ var IntegrationInstanceIdSchema = string().min(1);
157832
158103
  var IntegrationInstanceModeSchema = _enum(["single", "multiple"]);
157833
158104
  /**
157834
158105
  * What the addon's instances ARE for the Integrations page (planning#416). `devices`: each
157835
- * instance is an integration that brings devices (the registry owns its on/off switch);
158106
+ * instance is an integration that brings devices (its record body owns the on/off switch);
157836
158107
  * `services`: a connection configured from the addon's own function page, never listed on
157837
158108
  * Integrations.
157838
158109
  * It is the same vocabulary as the manifest's `integrationRole`, which stays as an override.
@@ -157875,18 +158146,38 @@ var IntegrationInstanceKindSchema = object({
157875
158146
  /** Relative hub path to disconnect that account. */
157876
158147
  disconnectPath: string().min(1).optional()
157877
158148
  });
158149
+ /**
158150
+ * How devices of an instance are found. `none`: the operator adds them by hand; `lan`: the addon
158151
+ * scans the network before any instance exists (the wizard offers the candidates); `account`: the
158152
+ * devices appear after the instance signs in. `scopedToInstance`: a discovery run belongs to ONE
158153
+ * instance and its candidates are claimed by it.
158154
+ */
158155
+ var IntegrationInstanceDiscoverySchema = object({
158156
+ mode: _enum([
158157
+ "none",
158158
+ "lan",
158159
+ "account"
158160
+ ]),
158161
+ scopedToInstance: boolean()
158162
+ });
158163
+ /**
158164
+ * One link a kind of this provider declares (D1013 rule 5): the body `field` of an instance of
158165
+ * `kind` holds the id of an instance of the function cap `to.cap` (of kind `to.kind`, when set).
158166
+ * The hub indexes these so the target's delete is refused while a link names it.
158167
+ */
158168
+ var IntegrationInstanceLinkSchema = object({
158169
+ kind: string().min(1),
158170
+ field: string().min(1),
158171
+ to: object({
158172
+ cap: string().min(1),
158173
+ kind: string().min(1).optional()
158174
+ })
158175
+ });
157878
158176
  var IntegrationInstanceDescriptionSchema = object({
157879
158177
  /** What the instances are for the Integrations page; see {@link IntegrationInstanceRoleSchema}. */
157880
158178
  role: IntegrationInstanceRoleSchema,
157881
158179
  /** How the devices of an instance are found; absent means `{ mode: 'none' }`. */
157882
- discovery: object({
157883
- mode: _enum([
157884
- "none",
157885
- "lan",
157886
- "account"
157887
- ]),
157888
- scopedToInstance: boolean()
157889
- }).optional(),
158180
+ discovery: IntegrationInstanceDiscoverySchema.optional(),
157890
158181
  /** `single`: at most one instance can exist (Loki). `multiple`: an account each. */
157891
158182
  instanceMode: IntegrationInstanceModeSchema,
157892
158183
  /** What the instance is, for the UI (`destination`, `relay`, `account`). */
@@ -157907,7 +158198,9 @@ var IntegrationInstanceDescriptionSchema = object({
157907
158198
  * `createInstance` without an `id` works: the provider mints it. Absent means the caller must
157908
158199
  * send an id (the UI then mints an opaque one).
157909
158200
  */
157910
- mintsId: boolean().optional()
158201
+ mintsId: boolean().optional(),
158202
+ /** The links to other instances the provider's kinds declare; absent means none. */
158203
+ links: array(IntegrationInstanceLinkSchema).optional()
157911
158204
  });
157912
158205
  var IntegrationInstanceStatusSchema = object({
157913
158206
  state: _enum([
@@ -157927,8 +158220,8 @@ var IntegrationInstanceSchema = object({
157927
158220
  configured: boolean(),
157928
158221
  /**
157929
158222
  * The instance's own on/off switch (D996), derived from the record body (`enabled !== false`,
157930
- * so a row written before the field existed is on). Absent when the `integrations` registry
157931
- * owns the switch (`describe().role` is `devices`): read it from the registry row.
158223
+ * so a row written before the field existed is on). The same for every role, `devices` included:
158224
+ * the body is the one store, `setInstanceEnabled` the one writer (epic #440, step 3).
157932
158225
  */
157933
158226
  enabled: boolean().optional(),
157934
158227
  /** The kind of this instance (one of `describe().kinds[].id`), when the provider has kinds. */
@@ -157978,7 +158271,8 @@ var integrationInstancesCapability = {
157978
158271
  auth: "admin"
157979
158272
  }),
157980
158273
  /**
157981
- * Switch ONE instance on or off. A row control, not a form field: `updateInstance.values` is the
158274
+ * Switch ONE instance on or off, for every role; a missing record is created from the addon's
158275
+ * initial body. A row control, not a form field: `updateInstance.values` is the
157982
158276
  * form patch (D62, D996). An off instance keeps its record and secrets and does no work.
157983
158277
  */
157984
158278
  setInstanceEnabled: method(object({
@@ -161062,6 +161356,8 @@ var MigrationIntegrationSchema = object({
161062
161356
  addonId: string(),
161063
161357
  name: string(),
161064
161358
  info: Rows,
161359
+ /** The registry's stored switch: read by the one-switch migration, nothing else. */
161360
+ enabled: boolean().optional(),
161065
161361
  originStableId: string().optional()
161066
161362
  });
161067
161363
  var MigrationDeviceSchema = object({
@@ -166546,13 +166842,6 @@ var AddBrokerInputSchema = object({
166546
166842
  });
166547
166843
  var AddBrokerResultSchema = object({ id: string() });
166548
166844
  var IdInputSchema = object({ id: string() });
166549
- var TestResultSchema$1 = discriminatedUnion("ok", [object({
166550
- ok: literal(true),
166551
- latencyMs: number()
166552
- }), object({
166553
- ok: literal(false),
166554
- error: string()
166555
- })]);
166556
166845
  var StartEmbeddedInputSchema = object({
166557
166846
  port: number().int().min(1).max(65535).default(1883),
166558
166847
  /** Allow anonymous connect (no username/password). Default: false. */
@@ -166575,9 +166864,6 @@ method(_void(), array(BrokerInfoSchema)), method(IdInputSchema, BrokerConnection
166575
166864
  }), method(IdInputSchema, _void(), {
166576
166865
  kind: "mutation",
166577
166866
  auth: "admin"
166578
- }), method(IdInputSchema, TestResultSchema$1, {
166579
- kind: "mutation",
166580
- auth: "admin"
166581
166867
  }), method(StartEmbeddedInputSchema, StartEmbeddedResultSchema, {
166582
166868
  kind: "mutation",
166583
166869
  auth: "admin"
@@ -171257,14 +171543,6 @@ var PetFountainStatusSchema = object({
171257
171543
  empty: boolean().nullable(),
171258
171544
  /** True while the pump is running. Null while unknown. */
171259
171545
  pumpRunning: boolean().nullable(),
171260
- /** Water drunk in the last drink, in litres. */
171261
- lastDrink: number().min(0).nullable().meta(readingMeta("volume")),
171262
- /** Water drunk in the current hour, in litres. */
171263
- currentHourDrink: number().min(0).nullable().meta(readingMeta("volume")),
171264
- /** Water drunk over the last 24 hours (rolling), in litres. */
171265
- last24hDrink: number().min(0).nullable().meta(readingMeta("volume")),
171266
- /** Water drunk since local midnight, in litres. Null when the fountain has no such sensor. */
171267
- todayDrink: number().min(0).nullable().meta(readingMeta("volume")),
171268
171546
  /** Decoded fault message. Null means healthy; a non-null string is an active fault. */
171269
171547
  error: string().nullable(),
171270
171548
  /** Ms epoch when the slice was last refreshed. */
@@ -171277,21 +171555,15 @@ var petFountainCapability = {
171277
171555
  deviceNative: true,
171278
171556
  mode: "singleton",
171279
171557
  deviceTypes: [DeviceType.PetFountain],
171280
- methods: {
171281
- /** Start or stop the pump. */
171282
- setPump: method(object({
171283
- deviceId: DeviceIdSchema$1,
171284
- on: boolean()
171285
- }), _void(), {
171286
- kind: "mutation",
171287
- auth: "protected"
171288
- }),
171289
- /** Clear the rolling daily consumption counters on the device. */
171290
- resetDailyConsumption: method(object({ deviceId: DeviceIdSchema$1 }), _void(), {
171291
- kind: "mutation",
171292
- auth: "protected"
171293
- })
171294
- },
171558
+ methods: {
171559
+ /** Start or stop the pump. */
171560
+ setPump: method(object({
171561
+ deviceId: DeviceIdSchema$1,
171562
+ on: boolean()
171563
+ }), _void(), {
171564
+ kind: "mutation",
171565
+ auth: "protected"
171566
+ }) },
171295
171567
  status: {
171296
171568
  schema: PetFountainStatusSchema,
171297
171569
  kind: "push"
@@ -171315,14 +171587,6 @@ var petFountainCapability = {
171315
171587
  waterVolume: {
171316
171588
  kind: "gauge",
171317
171589
  unit: "L"
171318
- },
171319
- todayDrink: {
171320
- kind: "gauge",
171321
- unit: "L"
171322
- },
171323
- last24hDrink: {
171324
- kind: "gauge",
171325
- unit: "L"
171326
171590
  }
171327
171591
  } }
171328
171592
  };
@@ -180436,7 +180700,7 @@ var TrainingProviderTypeSchema = object({
180436
180700
  label: string(),
180437
180701
  /** Path under the addon package (e.g. `assets/training-modal/icon.svg`). */
180438
180702
  iconAsset: string(),
180439
- /** Owning `training-provider` addon — collection selector for createEntry. */
180703
+ /** Owning `training-provider` addon. */
180440
180704
  addonId: string(),
180441
180705
  /**
180442
180706
  * Fields for one entry of this type (credentials + defaults). Absent on a
@@ -180481,36 +180745,6 @@ var TrainingProviderDescriptorSchema = object({
180481
180745
  */
180482
180746
  formValues: record(string(), unknown()).optional()
180483
180747
  });
180484
- /**
180485
- * Patch one entry's name, credentials and defaults. Pin with owning `{ addonId }`.
180486
- * An omitted or empty `tokenSecret` means KEEP the stored secret (D787).
180487
- * `{ $secretClear: true }` clears it.
180488
- */
180489
- var TrainingProviderUpdateEntryInputSchema = object({
180490
- entryId: string().min(1),
180491
- name: string().min(1),
180492
- tokenId: string().optional(),
180493
- tokenSecret: union([string(), object({ $secretClear: literal(true) })]).optional(),
180494
- environment: string().optional(),
180495
- gpuType: string().optional(),
180496
- region: string().optional(),
180497
- costCapUsd: number().nonnegative().optional(),
180498
- maxRuntimeSec: number().int().positive().optional(),
180499
- failedDatasetGraceHours: number().nonnegative().optional()
180500
- });
180501
- var TrainingCredentialCheckSchema = object({
180502
- ok: boolean(),
180503
- /** Workspace / account name, when the provider says. */
180504
- account: string().optional(),
180505
- reason: _enum([
180506
- "missing",
180507
- "invalid",
180508
- "forbidden",
180509
- "network",
180510
- "quota"
180511
- ]).optional(),
180512
- detail: string().optional()
180513
- });
180514
180748
  var ProviderJobStateSchema = _enum([
180515
180749
  "pending",
180516
180750
  "starting",
@@ -180558,22 +180792,6 @@ var TrainingLogLineSchema = object({
180558
180792
  text: string()
180559
180793
  });
180560
180794
  method(object({}), array(TrainingProviderDescriptorSchema).readonly(), { auth: "admin" }), method(object({}), array(TrainingProviderTypeSchema).readonly(), { auth: "admin" }), method(object({}), array(TrainingProviderEntrySchema).readonly(), { auth: "admin" }), method(object({
180561
- typeId: string().min(1),
180562
- name: string().min(1)
180563
- }), object({ entryId: string() }), {
180564
- kind: "mutation",
180565
- auth: "admin"
180566
- }), method(object({ entryId: string().min(1) }), object({ ok: literal(true) }), {
180567
- kind: "mutation",
180568
- auth: "admin"
180569
- }), method(TrainingProviderUpdateEntryInputSchema, object({ ok: literal(true) }), {
180570
- kind: "mutation",
180571
- auth: "admin"
180572
- }), method(object({ entryId: string().min(1) }), TrainingCredentialCheckSchema, {
180573
- kind: "mutation",
180574
- auth: "admin",
180575
- timeoutMs: 3e4
180576
- }), method(object({
180577
180795
  entryId: string().min(1),
180578
180796
  gpuType: string(),
180579
180797
  region: string(),
@@ -186537,20 +186755,6 @@ Object.freeze({
186537
186755
  access: "view",
186538
186756
  role: "admin"
186539
186757
  },
186540
- "connectionTest.describeTest": {
186541
- capName: "connection-test",
186542
- capScope: "system",
186543
- addonId: null,
186544
- access: "view",
186545
- role: "admin"
186546
- },
186547
- "connectionTest.testSettings": {
186548
- capName: "connection-test",
186549
- capScope: "system",
186550
- addonId: null,
186551
- access: "create",
186552
- role: "admin"
186553
- },
186554
186758
  "connectivity.getStatus": {
186555
186759
  capName: "connectivity",
186556
186760
  capScope: "device",
@@ -188917,13 +189121,6 @@ Object.freeze({
188917
189121
  access: "view",
188918
189122
  role: "admin"
188919
189123
  },
188920
- "integrations.testConnection": {
188921
- capName: "integrations",
188922
- capScope: "system",
188923
- addonId: null,
188924
- access: "create",
188925
- role: "admin"
188926
- },
188927
189124
  "integrations.update": {
188928
189125
  capName: "integrations",
188929
189126
  capScope: "system",
@@ -190156,13 +190353,6 @@ Object.freeze({
190156
190353
  access: "create",
190157
190354
  role: "admin"
190158
190355
  },
190159
- "mqttBroker.testConnection": {
190160
- capName: "mqtt-broker",
190161
- capScope: "system",
190162
- addonId: null,
190163
- access: "create",
190164
- role: "admin"
190165
- },
190166
190356
  "nativeObjectDetection.getOptions": {
190167
190357
  capName: "native-object-detection",
190168
190358
  capScope: "device",
@@ -191038,13 +191228,6 @@ Object.freeze({
191038
191228
  access: "view",
191039
191229
  role: "viewer"
191040
191230
  },
191041
- "petFountain.resetDailyConsumption": {
191042
- capName: "pet-fountain",
191043
- capScope: "device",
191044
- addonId: null,
191045
- access: "delete",
191046
- role: "viewer"
191047
- },
191048
191231
  "petFountain.setPump": {
191049
191232
  capName: "pet-fountain",
191050
191233
  capScope: "device",
@@ -195000,20 +195183,6 @@ Object.freeze({
195000
195183
  access: "create",
195001
195184
  role: "admin"
195002
195185
  },
195003
- "trainingProvider.createEntry": {
195004
- capName: "training-provider",
195005
- capScope: "system",
195006
- addonId: null,
195007
- access: "create",
195008
- role: "admin"
195009
- },
195010
- "trainingProvider.deleteEntry": {
195011
- capName: "training-provider",
195012
- capScope: "system",
195013
- addonId: null,
195014
- access: "delete",
195015
- role: "admin"
195016
- },
195017
195186
  "trainingProvider.describe": {
195018
195187
  capName: "training-provider",
195019
195188
  capScope: "system",
@@ -195084,13 +195253,6 @@ Object.freeze({
195084
195253
  access: "create",
195085
195254
  role: "admin"
195086
195255
  },
195087
- "trainingProvider.updateEntry": {
195088
- capName: "training-provider",
195089
- capScope: "system",
195090
- addonId: null,
195091
- access: "create",
195092
- role: "admin"
195093
- },
195094
195256
  "trainingProvider.uploadDataset": {
195095
195257
  capName: "training-provider",
195096
195258
  capScope: "system",
@@ -195098,13 +195260,6 @@ Object.freeze({
195098
195260
  access: "create",
195099
195261
  role: "admin"
195100
195262
  },
195101
- "trainingProvider.validateCredentials": {
195102
- capName: "training-provider",
195103
- capScope: "system",
195104
- addonId: null,
195105
- access: "create",
195106
- role: "admin"
195107
- },
195108
195263
  "turnProvider.getTurnServers": {
195109
195264
  capName: "turn-provider",
195110
195265
  capScope: "system",
@@ -197593,11 +197748,6 @@ Object.freeze({
197593
197748
  form: "single",
197594
197749
  optional: false
197595
197750
  }],
197596
- "petFountain.resetDailyConsumption": [{
197597
- name: "deviceId",
197598
- form: "single",
197599
- optional: false
197600
- }],
197601
197751
  "petFountain.setPump": [{
197602
197752
  name: "deviceId",
197603
197753
  form: "single",
@@ -200392,7 +200542,6 @@ object({
200392
200542
  delay: number().nonnegative().optional(),
200393
200543
  commands: record(string(), unknown())
200394
200544
  });
200395
- entryBody({ brokerId: string() });
200396
200545
  //#endregion
200397
200546
  //#region src/clips/clip-prefetch.ts
200398
200547
  /** The longest a device may stay quiet after refusals, whatever its interval. */
@@ -212895,6 +213044,10 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
212895
213044
  const host = this.config.get("host");
212896
213045
  return typeof host === "string" && host.length > 0 ? host : null;
212897
213046
  }
213047
+ /** The integration this camera belongs to, or `null` when it names none. */
213048
+ get integrationId() {
213049
+ return this.hubIntegrationId();
213050
+ }
212898
213051
  /** The integration (one NVR / Home Hub, D985) this camera was adopted from, or `null`. */
212899
213052
  hubIntegrationId() {
212900
213053
  const id = this.config.get("integrationId");
@@ -220869,6 +221022,20 @@ var SMTP_BROKER_ADDON_ID = "smtp-nodemailer";
220869
221022
  /** Who this addon is, among the subscribers of a mailbox. */
220870
221023
  var REOLINK_SUBSCRIBER_ID = "provider-reolink";
220871
221024
  var MAILBOX_NAME = "Camera mailbox";
221025
+ /** What an integration's `mailboxId` points at: an `smtp-inbound` instance of the `broker` cap (D1013). */
221026
+ var SMTP_MAILBOX_LINK = {
221027
+ cap: "broker",
221028
+ kind: SMTP_INBOUND_KIND
221029
+ };
221030
+ /** The body field of an integration record that names its camera mailbox; empty or absent when none. */
221031
+ var MAILBOX_LINK_FIELD = "mailboxId";
221032
+ /**
221033
+ * The link field of the integration record. The bridge fills it (an integration whose standalone
221034
+ * cameras mail the mailbox links to it), so the hub refuses to delete a mailbox that is in use.
221035
+ */
221036
+ function mailboxLinkField() {
221037
+ return optionalLinkField(SMTP_MAILBOX_LINK);
221038
+ }
220872
221039
  var RECIPIENT_PREFIX = "cam-";
220873
221040
  /**
220874
221041
  * The real port: the mailboxes are `integration-instances` of the SMTP addon (the kind of its
@@ -221022,20 +221189,54 @@ var EmailPushBridge = class {
221022
221189
  const recipients = this.recipients();
221023
221190
  if (recipients.length === 0) {
221024
221191
  if (this.brokerId !== null && this.subscriptionId !== null) await this.deps.port.unsubscribe(this.brokerId, this.subscriptionId);
221192
+ if (this.brokerId !== null) await this.syncLinks(this.brokerId, /* @__PURE__ */ new Set());
221025
221193
  this.subscriptionId = null;
221026
221194
  this.declared = null;
221027
221195
  return;
221028
221196
  }
221029
- const key = recipients.join(",");
221197
+ const owners = this.linkOwners();
221198
+ const key = `${recipients.join(",")}|${[...owners].sort().join(",")}`;
221030
221199
  if (!force && this.declared === key && this.subscriptionId !== null) return;
221031
221200
  const brokerId = await this.ensureMailbox();
221032
221201
  await this.seedBaseline(brokerId);
221033
221202
  const { subscriptionId } = await this.deps.port.subscribe(brokerId, recipients);
221034
221203
  this.brokerId = brokerId;
221035
221204
  this.subscriptionId = subscriptionId;
221036
- this.declared = key;
221205
+ this.declared = await this.syncLinks(brokerId, owners) ? key : null;
221037
221206
  await this.reconcile();
221038
221207
  }
221208
+ /** The integrations whose standalone cameras mail the mailbox: they link to it. */
221209
+ linkOwners() {
221210
+ const owners = /* @__PURE__ */ new Set();
221211
+ for (const cam of this.deps.listCameras()) if (cam.isEmailPushEligible && cam.integrationId !== null) owners.add(cam.integrationId);
221212
+ return owners;
221213
+ }
221214
+ /**
221215
+ * Make the `mailboxId` links say who uses the mailbox: `owners` link to it, no other
221216
+ * integration does. Idempotent, so an install whose mailbox already exists is filled from it
221217
+ * (the mailbox is re-adopted by `ensureMailbox`) with nothing stored beforehand. False when the
221218
+ * links could not be written: the caller retries at the next sync.
221219
+ */
221220
+ async syncLinks(brokerId, owners) {
221221
+ try {
221222
+ const rows = await this.deps.links.list();
221223
+ for (const row of rows) {
221224
+ const wanted = owners.has(row.id) ? brokerId : "";
221225
+ if (row.mailboxId !== wanted) await this.deps.links.set(row.id, wanted);
221226
+ }
221227
+ for (const owner of owners) if (!rows.some((row) => row.id === owner)) this.deps.logger.warn("email-push: an integration with email-push cameras has no record to link the mailbox from", { meta: {
221228
+ integrationId: owner,
221229
+ brokerId
221230
+ } });
221231
+ return true;
221232
+ } catch (err) {
221233
+ this.deps.logger.warn("email-push: the camera mailbox links could not be written", { meta: {
221234
+ brokerId,
221235
+ error: errMsg(err)
221236
+ } });
221237
+ return false;
221238
+ }
221239
+ }
221039
221240
  /**
221040
221241
  * What the mailbox retains from BEFORE this subscription is old news (a restart of this addon
221041
221242
  * must not re-fire a quarter hour of alarms). Nothing for our recipients is accepted before the
@@ -221184,6 +221385,126 @@ var EmailPushBridge = class {
221184
221385
  function pickMailbox(list) {
221185
221386
  return list.find((b) => b.id === "smtp-inbound-default")?.id ?? list[0]?.id ?? null;
221186
221387
  }
221388
+ var reolinkConnectionsEntryKind = defineEntryKind("connections", {
221389
+ title: "Reolink integrations",
221390
+ schema: entryBody({
221391
+ host: string().nullish(),
221392
+ port: number().int().min(1).max(65535).nullish(),
221393
+ rtspPort: number().int().min(1).max(65535).nullish(),
221394
+ username: string().nullish(),
221395
+ password: string().optional().meta({ secret: true }),
221396
+ transport: _enum(["tcp", "udp"]).nullish(),
221397
+ uid: string().nullish(),
221398
+ debugGeneral: boolean().nullish(),
221399
+ debugSocketLogs: array(ReolinkSocketDebugFlagSchema).nullish(),
221400
+ mailboxId: mailboxLinkField()
221401
+ }),
221402
+ writeTrigger: "an operator adds, edits or removes a Reolink integration, or a Hub device is migrated into one"
221403
+ });
221404
+ /** Every kind this addon declares, keyed by its name. */
221405
+ var reolinkRecordKinds = { connections: reolinkConnectionsEntryKind };
221406
+ /** The record body as the connection form's flat values: no name, no unset keys. */
221407
+ function hubSettingsOf(body) {
221408
+ const out = {};
221409
+ for (const [key, value] of Object.entries(body)) {
221410
+ if (key === "name" || value === null || value === void 0) continue;
221411
+ out[key] = value;
221412
+ }
221413
+ return out;
221414
+ }
221415
+ /**
221416
+ * What a resolved record says about its hub. A keychain that is locked yields a record WITHOUT
221417
+ * its password: that is `password-locked`, never an empty password (D49).
221418
+ */
221419
+ function hubConnectionOf(resolved) {
221420
+ const read = readHubConnection(hubSettingsOf(resolved.body));
221421
+ return read.kind === "no-password" && resolved.secrets === "unavailable" ? { kind: "password-locked" } : read;
221422
+ }
221423
+ /**
221424
+ * What each enabled integration's RECORD says about its hub: the one reader of the connection.
221425
+ * A record that is absent reads as `no-host` (no session), exactly as an empty settings blob did.
221426
+ */
221427
+ async function readHubConnections(instances, integrations) {
221428
+ const out = [];
221429
+ for (const integration of integrations) {
221430
+ const resolved = await instances.readResolved(integration.id);
221431
+ out.push({
221432
+ id: integration.id,
221433
+ name: integration.name,
221434
+ read: resolved === null ? { kind: "no-host" } : hubConnectionOf(resolved)
221435
+ });
221436
+ }
221437
+ return out;
221438
+ }
221439
+ function buildReolinkInstances(records, deps) {
221440
+ return new RecordIntegrationInstances(records, reolinkConnectionsEntryKind, {
221441
+ description: {
221442
+ role: "devices",
221443
+ discovery: {
221444
+ mode: "lan",
221445
+ scopedToInstance: false
221446
+ },
221447
+ instanceMode: "multiple",
221448
+ kind: "connection",
221449
+ canTest: false
221450
+ },
221451
+ formSchema: () => buildHubInstanceSchema(),
221452
+ initialBody: (name) => ({ name }),
221453
+ configured: (body) => (body.host ?? "").length === 0 || (body.password ?? "").length > 0,
221454
+ onChanged: () => deps.onChanged()
221455
+ });
221456
+ }
221457
+ /**
221458
+ * The provider handed to the hub: the default integration (no connection) shows no hub form, an
221459
+ * NVR / Home Hub one does, and a create wizard (no id yet) sets up a hub.
221460
+ */
221461
+ function reolinkInstancesProvider(instances, deps) {
221462
+ return {
221463
+ ...instances.toProvider(),
221464
+ instanceFormSchema: async ({ id }) => {
221465
+ if (id === null) return buildHubInstanceSchema();
221466
+ const [evidence, body] = await Promise.all([deps.registryEvidenceOf(id), instances.getResolved(id)]);
221467
+ return evidence !== null && isHubIntegration({
221468
+ originStableId: evidence.originStableId,
221469
+ info: evidence.info,
221470
+ settings: body === null ? {} : hubSettingsOf(body)
221471
+ }) || body === null ? buildHubInstanceSchema() : { sections: [] };
221472
+ }
221473
+ };
221474
+ }
221475
+ /**
221476
+ * Whether an integration IS one NVR / Home Hub (its devices come from the hub, so there is no
221477
+ * manual add by IP). An integration the registry cannot name is not a hub for this question.
221478
+ */
221479
+ async function integrationIsHub(instances, deps, id) {
221480
+ const [evidence, body] = await Promise.all([deps.registryEvidenceOf(id), instances.getResolved(id)]);
221481
+ if (evidence === null) return false;
221482
+ return isHubIntegration({
221483
+ originStableId: evidence.originStableId,
221484
+ info: evidence.info,
221485
+ settings: body === null ? {} : hubSettingsOf(body)
221486
+ });
221487
+ }
221488
+ //#endregion
221489
+ //#region src/mailbox-link-store.ts
221490
+ var INTEGRATIONS_MAX = 1e3;
221491
+ function mailboxLinkStoreOver(records) {
221492
+ const handle = records.kind(reolinkConnectionsEntryKind);
221493
+ return {
221494
+ list: async () => {
221495
+ return (await handle.query({ limit: INTEGRATIONS_MAX })).records.map((row) => {
221496
+ const linked = row.data[MAILBOX_LINK_FIELD];
221497
+ return {
221498
+ id: row.id,
221499
+ mailboxId: typeof linked === "string" ? linked : ""
221500
+ };
221501
+ });
221502
+ },
221503
+ set: async (integrationId, mailboxId) => {
221504
+ await handle.patch(integrationId, { [MAILBOX_LINK_FIELD]: mailboxId === "" ? null : mailboxId });
221505
+ }
221506
+ };
221507
+ }
221187
221508
  //#endregion
221188
221509
  //#region src/email-push-removal-hook.ts
221189
221510
  /**
@@ -221610,105 +221931,6 @@ async function moveEmailPushToMailbox(ports) {
221610
221931
  summary: { moved: true }
221611
221932
  };
221612
221933
  }
221613
- var reolinkConnectionsEntryKind = defineEntryKind("connections", {
221614
- title: "Reolink integrations",
221615
- schema: entryBody({
221616
- host: string().nullish(),
221617
- port: number().int().min(1).max(65535).nullish(),
221618
- rtspPort: number().int().min(1).max(65535).nullish(),
221619
- username: string().nullish(),
221620
- password: string().optional().meta({ secret: true }),
221621
- transport: _enum(["tcp", "udp"]).nullish(),
221622
- uid: string().nullish(),
221623
- debugGeneral: boolean().nullish(),
221624
- debugSocketLogs: array(ReolinkSocketDebugFlagSchema).nullish()
221625
- }),
221626
- writeTrigger: "an operator adds, edits or removes a Reolink integration, or a Hub device is migrated into one"
221627
- });
221628
- /** Every kind this addon declares, keyed by its name. */
221629
- var reolinkRecordKinds = { connections: reolinkConnectionsEntryKind };
221630
- /** The record body as the connection form's flat values: no name, no unset keys. */
221631
- function hubSettingsOf(body) {
221632
- const out = {};
221633
- for (const [key, value] of Object.entries(body)) {
221634
- if (key === "name" || value === null || value === void 0) continue;
221635
- out[key] = value;
221636
- }
221637
- return out;
221638
- }
221639
- /**
221640
- * What a resolved record says about its hub. A keychain that is locked yields a record WITHOUT
221641
- * its password: that is `password-locked`, never an empty password (D49).
221642
- */
221643
- function hubConnectionOf(resolved) {
221644
- const read = readHubConnection(hubSettingsOf(resolved.body));
221645
- return read.kind === "no-password" && resolved.secrets === "unavailable" ? { kind: "password-locked" } : read;
221646
- }
221647
- /**
221648
- * What each enabled integration's RECORD says about its hub: the one reader of the connection.
221649
- * A record that is absent reads as `no-host` (no session), exactly as an empty settings blob did.
221650
- */
221651
- async function readHubConnections(instances, integrations) {
221652
- const out = [];
221653
- for (const integration of integrations) {
221654
- const resolved = await instances.readResolved(integration.id);
221655
- out.push({
221656
- id: integration.id,
221657
- name: integration.name,
221658
- read: resolved === null ? { kind: "no-host" } : hubConnectionOf(resolved)
221659
- });
221660
- }
221661
- return out;
221662
- }
221663
- function buildReolinkInstances(records, deps) {
221664
- return new RecordIntegrationInstances(records, reolinkConnectionsEntryKind, {
221665
- description: {
221666
- role: "devices",
221667
- discovery: {
221668
- mode: "lan",
221669
- scopedToInstance: false
221670
- },
221671
- instanceMode: "multiple",
221672
- kind: "connection",
221673
- canTest: false
221674
- },
221675
- formSchema: () => buildHubInstanceSchema(),
221676
- initialBody: (name) => ({ name }),
221677
- configured: (body) => (body.host ?? "").length === 0 || (body.password ?? "").length > 0,
221678
- onChanged: () => deps.onChanged()
221679
- });
221680
- }
221681
- /**
221682
- * The provider handed to the hub: the default integration (no connection) shows no hub form, an
221683
- * NVR / Home Hub one does, and a create wizard (no id yet) sets up a hub.
221684
- */
221685
- function reolinkInstancesProvider(instances, deps) {
221686
- return {
221687
- ...instances.toProvider(),
221688
- instanceFormSchema: async ({ id }) => {
221689
- if (id === null) return buildHubInstanceSchema();
221690
- const [evidence, body] = await Promise.all([deps.registryEvidenceOf(id), instances.getResolved(id)]);
221691
- return evidence !== null && isHubIntegration({
221692
- originStableId: evidence.originStableId,
221693
- info: evidence.info,
221694
- settings: body === null ? {} : hubSettingsOf(body)
221695
- }) || body === null ? buildHubInstanceSchema() : { sections: [] };
221696
- }
221697
- };
221698
- }
221699
- /**
221700
- * Whether an integration IS one NVR / Home Hub (its devices come from the hub, so there is no
221701
- * manual add by IP). An integration the registry cannot name is not a hub for this question.
221702
- */
221703
- async function integrationIsHub(instances, deps, id) {
221704
- const [evidence, body] = await Promise.all([deps.registryEvidenceOf(id), instances.getResolved(id)]);
221705
- if (evidence === null) return false;
221706
- return isHubIntegration({
221707
- originStableId: evidence.originStableId,
221708
- info: evidence.info,
221709
- settings: body === null ? {} : hubSettingsOf(body)
221710
- });
221711
- }
221712
221934
  //#endregion
221713
221935
  //#region src/migrations/integration-rows-to-record.ts
221714
221936
  /**
@@ -222585,10 +222807,16 @@ var ReolinkProviderAddon = class extends BaseDeviceProvider {
222585
222807
  await this.mailboxPendingState.set(null);
222586
222808
  await this.mailboxPendingPasswordState.set("");
222587
222809
  }
222810
+ requireRecords() {
222811
+ const records = this.ctx.records;
222812
+ if (records === void 0) throw new Error("provider-reolink: ctx.records is required (hub-only addon)");
222813
+ return records;
222814
+ }
222588
222815
  /** The camera mailbox bridge, built once. */
222589
222816
  ensureEmailBridge() {
222590
222817
  this.emailBridge ??= new EmailPushBridge({
222591
222818
  port: createBrokerPort(this.ctx.api),
222819
+ links: mailboxLinkStoreOver(this.requireRecords()),
222592
222820
  listCameras: () => this.listReolinkCameras(),
222593
222821
  logger: this.ctx.logger.child("email-push"),
222594
222822
  pending: {
@@ -222754,8 +222982,9 @@ var ReolinkProviderAddon = class extends BaseDeviceProvider {
222754
222982
  if (typeof addonId === "string" && addonId !== this.ctx.id) return;
222755
222983
  this.reconcileIntegrations();
222756
222984
  };
222757
- this.ctx.eventBus.subscribe({ category: EventCategory.IntegrationEnabled }, handler);
222758
- this.ctx.eventBus.subscribe({ category: EventCategory.IntegrationDisabled }, handler);
222985
+ this.instances?.onSwitched(() => {
222986
+ this.reconcileIntegrations();
222987
+ });
222759
222988
  this.ctx.eventBus.subscribe({ category: EventCategory.IntegrationDeleted }, handler);
222760
222989
  }
222761
222990
  /** The hub box follows its integration's socket. */
@@ -222999,6 +223228,10 @@ var ReolinkProviderAddon = class extends BaseDeviceProvider {
222999
223228
  });
223000
223229
  this.instances = instances;
223001
223230
  this.hubIntegrationProbe = (id) => integrationIsHub(instances, { registryEvidenceOf }, id);
223231
+ this.declareRegistrySwitch({
223232
+ kind: reolinkConnectionsEntryKind,
223233
+ initialBody: (name) => ({ name })
223234
+ });
223002
223235
  await this.runMigrations([...defineAddonMigrations(REOLINK_MIGRATIONS, this.migrationPorts()), ...defineAddonMigrations(REOLINK_INTEGRATION_MIGRATIONS, integrationPorts)]);
223003
223236
  this.wireEmailBridge();
223004
223237
  const wireSleepPushResolvers = (event, via) => {