@camstack/addon-google-services 0.2.40 → 0.2.42

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.
@@ -5985,7 +5985,7 @@ var ZodIssueCode = {
5985
5985
  var ZodFirstPartyTypeKind;
5986
5986
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
5987
5987
  //#endregion
5988
- //#region ../types/dist/sleep-BX_MqzUe.mjs
5988
+ //#region ../types/dist/sleep-D7ZKm4nb.mjs
5989
5989
  /**
5990
5990
  * The audio chunk plane's byte format, and the ONE expansion from a coded
5991
5991
  * window to float samples (D455).
@@ -6669,137 +6669,121 @@ async function runAddonMigrations(host, migrations, logger, options = {}) {
6669
6669
  blockOwner
6670
6670
  };
6671
6671
  }
6672
- /**
6673
- * Build a {@link DurableState} over a single store key. Transport-agnostic:
6674
- * `read`/`write` are the addon-store or device-store accessors. The whole
6675
- * validated value round-trips on every read/write — the schema is the
6676
- * single source of truth for what is persisted, so no hand-listed field
6677
- * set can drop a key on save.
6678
- */
6679
- function createDurableState(deps) {
6680
- const get = async () => {
6681
- const raw = (await deps.read())[deps.key];
6682
- if (raw === void 0) return deps.fallback;
6683
- const parsed = deps.schema.safeParse(raw);
6684
- if (!parsed.success) {
6685
- deps.onParseError?.(deps.key, parsed.error);
6686
- return deps.fallback;
6687
- }
6688
- return parsed.data;
6689
- };
6690
- const set = async (next) => {
6691
- const validated = deps.schema.parse(next);
6692
- await deps.write({ [deps.key]: validated });
6693
- };
6694
- const update = async (fn) => {
6695
- await set(fn(await get()));
6696
- };
6672
+ /** The record calls the one-switch migration makes, over the migration API. */
6673
+ function switchRecordsOverMigrationApi(api) {
6674
+ return { kind: (definition) => {
6675
+ const handle = api.records.kind(definition);
6676
+ return {
6677
+ get: (id) => handle.get({ id }),
6678
+ put: (input, opts) => handle.put({
6679
+ ...input,
6680
+ ...opts?.ifRev === void 0 ? {} : { ifRev: opts.ifRev }
6681
+ }),
6682
+ patch: (id, partial) => handle.patch({
6683
+ id,
6684
+ partial
6685
+ })
6686
+ };
6687
+ } };
6688
+ }
6689
+ function integrationRowsApiOver(api) {
6697
6690
  return {
6698
- get,
6699
- set,
6700
- update
6691
+ list: async () => (await api.integrations.list({})).integrations,
6692
+ readLegacyIntegrationRows: (input) => api.legacyRows.read(input),
6693
+ clearLegacyIntegrationRows: (input) => api.legacyRows.clear(input)
6701
6694
  };
6702
6695
  }
6696
+ var PREFIX = "records/";
6703
6697
  /**
6704
- * Per-node scoping for the shared addon-settings blob.
6705
- *
6706
- * An addon's settings store is hub-central (the `addon-settings` cap is
6707
- * hub-routed — the hub instance answers for every node), so fields whose
6708
- * value is a NODE fact (decoder backend, engine pick, probed hardware
6709
- * capabilities) persist under the node-scoped key `<key>@<nodeId>` inside
6710
- * the single shared blob. The SCHEMA field key stays bare: the write path
6711
- * ({@link scopePatch}) maps the bare field onto the target node's scoped
6712
- * key; the read/hydrate path ({@link projectStore}) maps THIS node's value
6713
- * back, so UI forms and `resolveConfig` only ever see the bare key.
6714
- *
6715
- * Fields opt in via the `perNode: true` schema marker on `ConfigFieldBase`
6716
- * (`interfaces/config-ui.ts`); `BaseAddon` derives the key set from the
6717
- * schema and routes reads/writes through these helpers.
6718
- *
6719
- * ## No bare-key fallback — deliberate
6720
- *
6721
- * {@link readNodeValue} reads the node-scoped key ONLY. A node with no
6722
- * scoped key resolves to `undefined` so the field's schema `default` wins —
6723
- * NEVER `store[base]` and never another node's value. A bare legacy key in
6724
- * the store is invisible to every node, hub included, so one node's
6725
- * selection can never leak onto another. (This generalizes the
6726
- * `decoder-backend-keys.ts` semantics — the no-fallback variant — over an
6727
- * arbitrary set of per-node field keys.)
6728
- *
6729
- * Pure functions only — no I/O, no imports beyond the language. This is a
6730
- * LEAF module: import it via its deep path, never from the root barrel.
6731
- */
6732
- /**
6733
- * Normalize a raw kernel node id to the bare node id used for scoping.
6734
- * `localNodeId` can carry a `<node>/<addon>` suffix on forked child
6735
- * processes; per-node settings are per-NODE, so strip the addon segment.
6736
- * `undefined` / `null` / empty falls back to `'hub'`.
6698
+ * Cross-realm brand. An addon bundles its own copy of this module (D15) while
6699
+ * `ctx.records` is the HOST's door, so an error thrown by the host is an
6700
+ * instance of the host's classes, not of the addon's. The brand plus the code
6701
+ * make `instanceof` answer by identity of the failure, not of the copy.
6737
6702
  */
6738
- function normalizeNodeId(raw) {
6739
- if (raw === void 0 || raw === null || raw === "") return "hub";
6740
- const slashIdx = raw.indexOf("/");
6741
- if (slashIdx < 0) return raw;
6742
- const bare = raw.slice(0, slashIdx);
6743
- return bare === "" ? "hub" : bare;
6744
- }
6745
- /** The node-scoped store key for a per-node field: `<base>@<nodeId>`. */
6746
- function nodeScopedKey(base, nodeId) {
6747
- return `${base}@${normalizeNodeId(nodeId)}`;
6703
+ var RECORDS_ERROR_BRAND = Symbol.for("camstack.records-error");
6704
+ function carriesBrand(value) {
6705
+ return typeof value === "object" && value !== null && Reflect.get(value, RECORDS_ERROR_BRAND) === true;
6748
6706
  }
6707
+ /** The base of every records failure. `detail` is the human part of the message. */
6708
+ var RecordsError = class extends Error {
6709
+ /** The code a subclass stands for; the base stands for every code. */
6710
+ static code = void 0;
6711
+ /**
6712
+ * `instanceof` across copies of this module: any branded error is a
6713
+ * `RecordsError`, and is an instance of a subclass only when its code is the
6714
+ * subclass's code. Same-copy answers are unchanged.
6715
+ */
6716
+ static [Symbol.hasInstance](value) {
6717
+ if (Function.prototype[Symbol.hasInstance].call(this, value)) return true;
6718
+ if (!carriesBrand(value)) return false;
6719
+ return this.code === void 0 || value.code === this.code;
6720
+ }
6721
+ code;
6722
+ detail;
6723
+ [RECORDS_ERROR_BRAND] = true;
6724
+ constructor(code, detail) {
6725
+ super(`${PREFIX}${code}: ${detail}`);
6726
+ this.name = "RecordsError";
6727
+ this.code = code;
6728
+ this.detail = detail;
6729
+ }
6730
+ };
6731
+ /** The keychain could not store or serve a value: explicit, never an empty string. */
6732
+ var RecordSecretUnavailableError = class RecordSecretUnavailableError extends RecordsError {
6733
+ static code = "secret-unavailable";
6734
+ constructor(detail) {
6735
+ super(RecordSecretUnavailableError.code, detail);
6736
+ this.name = "RecordSecretUnavailableError";
6737
+ }
6738
+ };
6739
+ var InvalidRecordError = class InvalidRecordError extends RecordsError {
6740
+ static code = "invalid-record";
6741
+ constructor(detail) {
6742
+ super(InvalidRecordError.code, detail);
6743
+ this.name = "InvalidRecordError";
6744
+ }
6745
+ };
6746
+ /** A kind declaration the engine refuses (non-additive change, bad shape, wrong file). */
6747
+ var DeclarationRefusedError = class DeclarationRefusedError extends RecordsError {
6748
+ static code = "declaration-refused";
6749
+ constructor(detail) {
6750
+ super(DeclarationRefusedError.code, detail);
6751
+ this.name = "DeclarationRefusedError";
6752
+ }
6753
+ };
6749
6754
  /**
6750
- * Read a node's value for a per-node field from the raw shared store:
6751
- * the node-scoped key when present, otherwise `undefined`.
6752
- * Deliberately NO bare-key fallback (see module doc) — the caller lets the
6753
- * schema `default` win on `undefined`.
6755
+ * The link primitive's declaration half (D1013 rule 5): what a link field names and how a kind
6756
+ * records it. Split from `instance-link.ts` so `RecordIntegrationInstances` can read the links of
6757
+ * its kind without importing the builders that import it.
6754
6758
  */
6755
- function readNodeValue(store, base, nodeId) {
6756
- return store[nodeScopedKey(base, nodeId)];
6759
+ /** The body field of a link: the id of the instance it names; the target rides in the field meta. */
6760
+ function linkField(target) {
6761
+ return string().meta({ link: target });
6757
6762
  }
6758
- /**
6759
- * Re-map a UI/settings patch so every bare perNode field persists under the
6760
- * TARGET node's scoped key; all other keys pass through unchanged. Used on
6761
- * the write path so a save for one node never clobbers another node's value
6762
- * (and the bare key is never written). Returns a new object — the input
6763
- * patch is not mutated.
6764
- */
6765
- function scopePatch(patch, perNodeKeys, nodeId) {
6766
- const out = {};
6767
- for (const [key, value] of Object.entries(patch)) out[perNodeKeys.has(key) ? nodeScopedKey(key, nodeId) : key] = value;
6768
- return out;
6763
+ function linkTargetOf(meta) {
6764
+ if (typeof meta !== "object" || meta === null) return void 0;
6765
+ const link = Reflect.get(meta, "link");
6766
+ const parsed = LinkTargetSchema.safeParse(link);
6767
+ return parsed.success ? parsed.data : void 0;
6769
6768
  }
6770
- /**
6771
- * Project the raw shared store onto the bare schema keys for ONE node so a
6772
- * UI schema (whose field keys are bare) hydrates from that node's own
6773
- * values:
6774
- *
6775
- * - EVERY `@`-scoped key (any node's) is dropped from the pass-through.
6776
- * - Every bare perNode key is dropped from the pass-through (a stray bare
6777
- * legacy key must never hydrate any node — no bare fallback).
6778
- * - THIS node's effective value ({@link readNodeValue}) is then laid onto
6779
- * each bare perNode key; when the node has no scoped key the bare key is
6780
- * left ABSENT so the field's schema `default` wins.
6781
- *
6782
- * Returns a new object — the input store is not mutated.
6783
- */
6784
- function projectStore(store, perNodeKeys, nodeId) {
6785
- const out = {};
6786
- for (const [key, value] of Object.entries(store)) {
6787
- if (key.includes("@")) continue;
6788
- if (perNodeKeys.has(key)) continue;
6789
- out[key] = value;
6790
- }
6791
- for (const base of perNodeKeys) {
6792
- const value = readNodeValue(store, base, nodeId);
6793
- if (value !== void 0) out[base] = value;
6769
+ var LinkTargetSchema = object({
6770
+ cap: string().min(1),
6771
+ kind: string().min(1).optional()
6772
+ });
6773
+ /** The links a kind declares, read from the meta of its body fields. */
6774
+ function linksOfKind(kind) {
6775
+ const schema = kind.schema;
6776
+ if (!(schema instanceof ZodObject)) return [];
6777
+ const links = [];
6778
+ for (const [field, fieldSchema] of Object.entries(schema.shape)) {
6779
+ const to = linkTargetOf(globalRegistry.get(fieldSchema));
6780
+ if (to !== void 0) links.push({
6781
+ field,
6782
+ to
6783
+ });
6794
6784
  }
6795
- return out;
6785
+ return links;
6796
6786
  }
6797
- /** Every scope, in the order the guard and the docs list them. */
6798
- var SCOPED_SETTINGS_SCOPES = [
6799
- "cluster",
6800
- "device-defaults",
6801
- "node"
6802
- ];
6803
6787
  /**
6804
6788
  * The address of one keychain value: `secret://<owner>/<scope>/<fieldPath>`.
6805
6789
  *
@@ -6934,6 +6918,643 @@ function parseSecretRef(ref) {
6934
6918
  fieldPath
6935
6919
  };
6936
6920
  }
6921
+ /** Limits and names of `ctx.records` (D881). One authority; the engine and the facade read it. */
6922
+ /** The files a kind may live in. `history` is device-history's (D850), never records. */
6923
+ var RECORD_DATABASES = ["settings", "events"];
6924
+ /** The classes of a kind: the `@durable` vocabulary, one authority (replaces the annotation). */
6925
+ var RECORD_CLASSES = [
6926
+ "config",
6927
+ "ledger",
6928
+ "audit",
6929
+ "mirror",
6930
+ "ephemeral"
6931
+ ];
6932
+ var RECORD_DEFAULT_MAX_DATA_BYTES = 64 * 1024;
6933
+ var RECORD_MAX_DATA_BYTES = 1024 * 1024;
6934
+ var RECORD_BATCH_MAX = 1e3;
6935
+ var RECORD_QUERY_MAX = 1e3;
6936
+ /** A kind in the `settings` file may not bound itself above this (D447: high volume is `events`). */
6937
+ var RECORD_SETTINGS_MAX_ROWS = 5e4;
6938
+ /** The `Column`-free proof prefix: a ref collection for a kind's secret fields. */
6939
+ var RECORD_SECRET_COLLECTION_PREFIX = "records:";
6940
+ /**
6941
+ * Secret fields of a record, addressed the way a Zod schema declares them
6942
+ * (`collectZodSecretPaths`): dotted keys, `[]` for "each element of this array"
6943
+ * (`auth.accessToken`, `headers[].value`).
6944
+ *
6945
+ * `{}` after a key means "each value of this map" (`applianceSecrets{}`): the map's own key
6946
+ * names the value (`applianceSecrets{fridge}`), so no id key is declared and a body that drops a
6947
+ * key releases exactly that key's secret.
6948
+ *
6949
+ * Array elements are matched by a DECLARED id key (`secretArrayKeys`:
6950
+ * `{ headers: 'name' }`), never by index, so reordering a list keeps every
6951
+ * keychain ref (the same rule as `arrayItemFieldPath`). The concrete path of a
6952
+ * leaf names its element: `headers[X-Api].value`.
6953
+ *
6954
+ * Pure and browser-safe. Nothing here mutates: every transform returns a new value.
6955
+ */
6956
+ /** The array prefixes (declared form, e.g. `headers` or `a.headers`) of a path. */
6957
+ function parseSecretPath(path) {
6958
+ if (path.length === 0) throw new InvalidRecordError("an empty secret path");
6959
+ return path.split(".").map((raw) => {
6960
+ const each = raw.endsWith("[]");
6961
+ const map = raw.endsWith("{}");
6962
+ const key = each || map ? raw.slice(0, -2) : raw;
6963
+ if (key.length === 0) throw new InvalidRecordError(`secret path "${path}" has an empty segment`);
6964
+ return {
6965
+ key,
6966
+ each,
6967
+ map
6968
+ };
6969
+ });
6970
+ }
6971
+ /** The declared array prefixes of `path` that need an id key (`headers`, `a.rows`). */
6972
+ function secretArrayPrefixes(path) {
6973
+ const segments = parseSecretPath(path);
6974
+ const prefixes = [];
6975
+ const walked = [];
6976
+ for (const segment of segments) {
6977
+ walked.push(segment.key);
6978
+ if (segment.each) prefixes.push(walked.join("."));
6979
+ }
6980
+ return prefixes;
6981
+ }
6982
+ function isRecord$6(value) {
6983
+ return typeof value === "object" && value !== null && !Array.isArray(value);
6984
+ }
6985
+ function elementId(element, idKey, declared, prefix) {
6986
+ const id = isRecord$6(element) ? element[idKey] : void 0;
6987
+ 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`);
6988
+ return id;
6989
+ }
6990
+ /**
6991
+ * Visit every secret leaf PRESENT in `data` (an absent branch has nothing to
6992
+ * visit). `replace` returns the new leaf value, or {@link REMOVE_LEAF}; the
6993
+ * result is a new body, `data` is untouched.
6994
+ */
6995
+ var REMOVE_LEAF = Symbol("remove-leaf");
6996
+ function mapAt(node, segments, index, walkedKeys, concretePrefix, declared, arrayKeys, visit) {
6997
+ if (!isRecord$6(node)) return node;
6998
+ const segment = segments[index];
6999
+ if (segment === void 0) return node;
7000
+ if (!Object.prototype.hasOwnProperty.call(node, segment.key)) return node;
7001
+ const child = node[segment.key];
7002
+ const keys = [...walkedKeys, segment.key];
7003
+ const last = index === segments.length - 1;
7004
+ if (segment.each) {
7005
+ if (!Array.isArray(child)) return node;
7006
+ const prefix = keys.join(".");
7007
+ const idKey = arrayKeys[prefix];
7008
+ if (idKey === void 0) throw new InvalidRecordError(`"${declared}": no id key declared for the array "${prefix}"`);
7009
+ const mapped = child.map((element) => {
7010
+ const id = elementId(element, idKey, declared, prefix);
7011
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}[${encodeURIComponent(id)}]`;
7012
+ return last ? element : mapAt(element, segments, index + 1, keys, concrete, declared, arrayKeys, visit);
7013
+ });
7014
+ return {
7015
+ ...node,
7016
+ [segment.key]: mapped
7017
+ };
7018
+ }
7019
+ if (segment.map) {
7020
+ if (!isRecord$6(child)) return node;
7021
+ const kept = Object.entries(child).map(([mapKey, value]) => {
7022
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}{${encodeURIComponent(mapKey)}}`;
7023
+ if (!last) return [mapKey, mapAt(value, segments, index + 1, keys, concrete, declared, arrayKeys, visit)];
7024
+ return [mapKey, visit({
7025
+ declared,
7026
+ concrete,
7027
+ value
7028
+ })];
7029
+ }).filter(([, value]) => value !== REMOVE_LEAF);
7030
+ return {
7031
+ ...node,
7032
+ [segment.key]: Object.fromEntries(kept)
7033
+ };
7034
+ }
7035
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}`;
7036
+ if (last) {
7037
+ const replacement = visit({
7038
+ declared,
7039
+ concrete,
7040
+ value: child
7041
+ });
7042
+ if (replacement === REMOVE_LEAF) return Object.fromEntries(Object.entries(node).filter(([key]) => key !== segment.key));
7043
+ return {
7044
+ ...node,
7045
+ [segment.key]: replacement
7046
+ };
7047
+ }
7048
+ return {
7049
+ ...node,
7050
+ [segment.key]: mapAt(child, segments, index + 1, keys, concrete, declared, arrayKeys, visit)
7051
+ };
7052
+ }
7053
+ /** Replace/remove every present secret leaf; returns a NEW body. */
7054
+ function mapSecretLeaves(data, paths, arrayKeys, visit) {
7055
+ let current = data;
7056
+ for (const declared of paths) current = mapAt(current, parseSecretPath(declared), 0, [], "", declared, arrayKeys, visit);
7057
+ return current;
7058
+ }
7059
+ /**
7060
+ * The keychain collection name a kind's secrets live under. Prefixed so a
7061
+ * record's refs never collide with the refs a legacy collection of the same name
7062
+ * already holds during an adoption.
7063
+ */
7064
+ function recordSecretCollection(kind) {
7065
+ return `${RECORD_SECRET_COLLECTION_PREFIX}${kind}`;
7066
+ }
7067
+ /** The ONE ref a row's secret field may carry: the engine and the facade both build it here. */
7068
+ function recordSecretRef(owner, kind, rowId, concretePath) {
7069
+ return buildSecretRef({
7070
+ owner,
7071
+ scope: {
7072
+ kind: "row",
7073
+ collection: recordSecretCollection(kind),
7074
+ rowId
7075
+ },
7076
+ fieldPath: concretePath
7077
+ });
7078
+ }
7079
+ /**
7080
+ * A stored secret, as an admin read shows it: a VIEW naming the row's own
7081
+ * keychain ref (`set: true`), never the value and no longer the bare redaction
7082
+ * token. The form hands it to the secret field, which reveals the value by ref
7083
+ * through the audited `keychain-admin.reveal`; sent back untouched it keeps the
7084
+ * stored secret (the records door reads a view as KEEP).
7085
+ *
7086
+ * ONE implementation for the entries service and for every addon that serves
7087
+ * its own instances (`RecordIntegrationInstances`).
7088
+ */
7089
+ function isRecord$5(value) {
7090
+ return typeof value === "object" && value !== null && !Array.isArray(value);
7091
+ }
7092
+ function secretViewsOf(owner, kind, id, decl, data) {
7093
+ if (decl.secretPaths.length === 0) return data;
7094
+ const shown = mapSecretLeaves(data, decl.secretPaths, decl.secretArrayKeys, (leaf) => {
7095
+ if (leaf.value !== "__camstack_redacted__") return leaf.value;
7096
+ return {
7097
+ $secret: recordSecretRef(owner, kind, id, leaf.concrete),
7098
+ v: 1,
7099
+ set: true
7100
+ };
7101
+ });
7102
+ return isRecord$5(shown) ? shown : data;
7103
+ }
7104
+ /** The most instances one addon lists (an integrations page, not a table). */
7105
+ var INSTANCES_LIST_MAX = 1e3;
7106
+ /**
7107
+ * The ONE reader of an instance's switch (D996): an absent field means on, so a row written
7108
+ * before the field existed needs no migration. Every consumer of an instance body asks this.
7109
+ */
7110
+ function isInstanceEnabled(body) {
7111
+ return body.enabled !== false;
7112
+ }
7113
+ /** The body key of the switch; only {@link RecordIntegrationInstances.setInstanceEnabled} writes it. */
7114
+ var SWITCH_KEY = "enabled";
7115
+ /** The keys of the kind's secret fields that sit at the top level of the body. */
7116
+ function topLevelSecretKeys(paths) {
7117
+ return new Set(paths.filter((p) => !p.includes(".") && !p.includes("[") && !p.includes("{")));
7118
+ }
7119
+ /** The keys of the kind's top-level MAPS whose values are secrets (`applianceSecrets{}`). */
7120
+ function secretMapKeys(paths) {
7121
+ return new Set(paths.filter((p) => p.endsWith("{}") && !p.slice(0, -2).match(/[.[{]/)).map((p) => p.slice(0, -2)));
7122
+ }
7123
+ /**
7124
+ * A patch value for a map of secrets: an entry that is omitted, `''`, the redaction token or the
7125
+ * view the form was given KEEPS its stored secret (it is left out of the merge); `{ $secretClear }`
7126
+ * or `null` removes the entry; any other string replaces it. Null when nothing is left to merge.
7127
+ */
7128
+ function secretMapPatch(value) {
7129
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
7130
+ const out = {};
7131
+ for (const [key, entry] of Object.entries(value)) if (entry === null || isSecretClear(entry)) out[key] = null;
7132
+ else if (typeof entry === "string" && entry !== "" && entry !== "__camstack_redacted__" && !isSecretFieldView(entry)) out[key] = entry;
7133
+ return Object.keys(out).length > 0 ? out : null;
7134
+ }
7135
+ var RecordIntegrationInstances = class {
7136
+ records;
7137
+ kind;
7138
+ hooks;
7139
+ handle;
7140
+ secretKeys;
7141
+ secretMaps;
7142
+ nameField;
7143
+ switchListeners = /* @__PURE__ */ new Set();
7144
+ constructor(records, kind, hooks) {
7145
+ this.records = records;
7146
+ this.kind = kind;
7147
+ this.hooks = hooks;
7148
+ this.handle = records.kind(kind);
7149
+ this.secretKeys = topLevelSecretKeys(kind.declaration.secretPaths);
7150
+ this.secretMaps = secretMapKeys(kind.declaration.secretPaths);
7151
+ this.nameField = kind.declaration.entry?.nameField ?? "name";
7152
+ }
7153
+ /**
7154
+ * One instance read for the addon's own runtime; null when absent. When the keychain is
7155
+ * locked the row is served WITHOUT its secrets and says so (`secrets: 'unavailable'`), so the
7156
+ * caller can keep what it had instead of reconfiguring with an empty secret (D49).
7157
+ */
7158
+ async readResolved(id) {
7159
+ try {
7160
+ const record = await this.handle.getResolved(id);
7161
+ return record === null ? null : {
7162
+ id,
7163
+ body: record.data,
7164
+ enabled: isInstanceEnabled(record.data),
7165
+ secrets: "resolved"
7166
+ };
7167
+ } catch (err) {
7168
+ if (!(err instanceof RecordSecretUnavailableError)) throw err;
7169
+ const stored = await this.handle.get(id);
7170
+ if (stored === null) return null;
7171
+ return {
7172
+ id,
7173
+ body: Object.fromEntries(Object.entries(stored.data).filter(([key]) => !this.secretKeys.has(key))),
7174
+ enabled: isInstanceEnabled(stored.data),
7175
+ secrets: "unavailable"
7176
+ };
7177
+ }
7178
+ }
7179
+ /** The body of {@link readResolved} alone; a locked keychain yields the row without secrets. */
7180
+ async getResolved(id) {
7181
+ return (await this.readResolved(id))?.body ?? null;
7182
+ }
7183
+ /** Every instance, secrets resolved where the keychain allows; an absent one is skipped. */
7184
+ async listResolved() {
7185
+ const page = await this.handle.query({ limit: INSTANCES_LIST_MAX });
7186
+ const out = [];
7187
+ for (const record of page.records) {
7188
+ const read = await this.readResolved(record.id);
7189
+ if (read !== null) out.push(read);
7190
+ }
7191
+ return out;
7192
+ }
7193
+ viewOf(record) {
7194
+ const shown = secretViewsOf(this.records.owner, this.kind.name, record.id, this.kind.declaration, record.data);
7195
+ const rawName = record.data[this.nameField];
7196
+ const kind = this.hooks.kindOf?.(record.data);
7197
+ const health = this.hooks.health?.(record.data, record.id);
7198
+ return {
7199
+ id: record.id,
7200
+ name: typeof rawName === "string" ? rawName : record.id,
7201
+ configured: this.hooks.configured(record.data),
7202
+ enabled: isInstanceEnabled(record.data),
7203
+ formValues: shown,
7204
+ ...kind !== void 0 ? { kind } : {},
7205
+ ...health?.status !== void 0 ? { status: health.status } : {},
7206
+ ...health?.lastCheckedAt !== void 0 ? { lastCheckedAt: health.lastCheckedAt } : {}
7207
+ };
7208
+ }
7209
+ describe = async () => {
7210
+ const declared = linksOfKind(this.kind);
7211
+ const links = this.hooks.description.links !== void 0 || declared.length === 0 ? {} : { links: declared.map((link) => ({
7212
+ kind: this.kind.name,
7213
+ field: link.field,
7214
+ to: link.to
7215
+ })) };
7216
+ return {
7217
+ ...this.hooks.description,
7218
+ ...links,
7219
+ ...this.hooks.mintId === void 0 ? {} : { mintsId: true }
7220
+ };
7221
+ };
7222
+ instanceFormSchema = async ({ id }) => this.hooks.formSchema(id);
7223
+ listInstances = async () => {
7224
+ return (await this.handle.query({ limit: INSTANCES_LIST_MAX })).records.map((record) => this.viewOf(record));
7225
+ };
7226
+ getInstance = async ({ id }) => {
7227
+ const record = await this.handle.get(id);
7228
+ return record === null ? null : this.viewOf(record);
7229
+ };
7230
+ /** Insert ONE row (`ifRev: 0`: an existing id is refused, never overwritten). */
7231
+ createInstance = async ({ id, name, kind, values }) => {
7232
+ const minted = id ?? this.hooks.mintId?.({
7233
+ name,
7234
+ ...kind !== void 0 ? { kind } : {}
7235
+ });
7236
+ if (minted === void 0) throw new Error("createInstance needs an id: this provider does not mint one");
7237
+ await this.handle.put({
7238
+ id: minted,
7239
+ data: this.hooks.initialBody(name, kind)
7240
+ }, { ifRev: 0 });
7241
+ const patch = this.patchOf(values ?? {});
7242
+ if (Object.keys(patch).length > 0) await this.handle.patch(minted, patch);
7243
+ await this.hooks.onChanged?.(minted, "created");
7244
+ return { id: minted };
7245
+ };
7246
+ updateInstance = async ({ id, name, values }) => {
7247
+ const patch = this.patchOf(values);
7248
+ if (name !== void 0) patch[this.nameField] = name;
7249
+ await this.handle.patch(id, patch);
7250
+ await this.hooks.onChanged?.(id, "updated");
7251
+ return { ok: true };
7252
+ };
7253
+ /** The record patch a form `values` object means: secrets kept, cleared or replaced. */
7254
+ patchOf(values) {
7255
+ const patch = {};
7256
+ for (const [key, value] of Object.entries(values)) {
7257
+ if (value === void 0) continue;
7258
+ if (key === "enabled") continue;
7259
+ if (this.secretMaps.has(key)) {
7260
+ const entries = secretMapPatch(value);
7261
+ if (entries !== null) patch[key] = entries;
7262
+ } else if (!this.secretKeys.has(key)) patch[key] = value;
7263
+ else if (isSecretClear(value)) patch[key] = null;
7264
+ else if (typeof value === "string" && value !== "" && value !== "__camstack_redacted__" && !isSecretFieldView(value)) patch[key] = value;
7265
+ }
7266
+ return patch;
7267
+ }
7268
+ /**
7269
+ * Listen to the switch of ANY instance of this helper (in the process that serves it). The
7270
+ * durable replacement of the `integration.enabled` / `integration.disabled` events (D8): the
7271
+ * addon reconciles from the record, whichever way it flipped.
7272
+ */
7273
+ onSwitched(listener) {
7274
+ this.switchListeners.add(listener);
7275
+ }
7276
+ /**
7277
+ * The ONE writer of the switch (D996, D1014): the record body's `enabled`, for every role. A
7278
+ * configured thing is an instance, so an id with no record yet (a default integration that was
7279
+ * never configured) gets its record from `initialBody` before the switch is written.
7280
+ */
7281
+ setInstanceEnabled = async ({ id, enabled }) => {
7282
+ if (await this.handle.get(id) === null) await this.handle.put({
7283
+ id,
7284
+ data: this.hooks.initialBody(id)
7285
+ }, { ifRev: 0 });
7286
+ await this.handle.patch(id, { [SWITCH_KEY]: enabled });
7287
+ await this.hooks.onChanged?.(id, "enabled");
7288
+ for (const listener of this.switchListeners) await listener(id, enabled);
7289
+ return { ok: true };
7290
+ };
7291
+ /** The row and its keychain refs go together (the records door). */
7292
+ deleteInstance = async ({ id }) => {
7293
+ await this.handle.delete(id);
7294
+ await this.hooks.onChanged?.(id, "deleted");
7295
+ return { ok: true };
7296
+ };
7297
+ testInstance = async (input) => {
7298
+ if (this.hooks.test === void 0) return {
7299
+ success: false,
7300
+ status: "unsupported",
7301
+ error: "This integration declares no connection test"
7302
+ };
7303
+ return this.hooks.test(input);
7304
+ };
7305
+ /** The flat provider object to hand to `registerProvider`. */
7306
+ toProvider() {
7307
+ return {
7308
+ describe: this.describe,
7309
+ instanceFormSchema: this.instanceFormSchema,
7310
+ listInstances: this.listInstances,
7311
+ getInstance: this.getInstance,
7312
+ createInstance: this.createInstance,
7313
+ updateInstance: this.updateInstance,
7314
+ setInstanceEnabled: this.setInstanceEnabled,
7315
+ deleteInstance: this.deleteInstance,
7316
+ testInstance: this.testInstance
7317
+ };
7318
+ }
7319
+ };
7320
+ /**
7321
+ * The one-switch migration (epic #440, step 3). An integration's on/off state used to live in the
7322
+ * registry's `enabled` column for a device addon; it now lives only in the instance record's
7323
+ * body (`enabled`, D1007 superseded). This moves a registry `enabled = false` into the body, once.
7324
+ *
7325
+ * For every registry row of the addon that is OFF:
7326
+ * - no record under its id: the record is created from `initialBody(name)` with `enabled: false`
7327
+ * (a default integration that never had settings, Reolink's among them);
7328
+ * - a record whose body states no `enabled`: `enabled: false` is written into it;
7329
+ * - a record that already states `enabled` (either way) is the newer truth and is left alone.
7330
+ * A row that is ON writes nothing: an absent field reads as on. A rerun finds every off row with
7331
+ * a stated switch and does nothing, so nothing switched off comes back on and nothing switched on
7332
+ * goes off. The registry column itself is neither read afterwards nor written; its drop is step 5.
7333
+ *
7334
+ * It runs in the addon process, BEFORE the addon registers its `integration-instances` provider,
7335
+ * which is also why `integrations.list` still answers the stored column at that point.
7336
+ */
7337
+ function registrySwitchToBodyId(addonId, date) {
7338
+ return `${addonId}/${date}-registry-switch-to-body`;
7339
+ }
7340
+ async function moveRegistrySwitchToBody(ports, spec) {
7341
+ const rows = await ports.listIntegrations(spec.addonId);
7342
+ let created = 0;
7343
+ let switched = 0;
7344
+ let kept = 0;
7345
+ for (const row of rows) {
7346
+ if (row.enabled) continue;
7347
+ const body = await ports.readBody(row.id);
7348
+ if (body === null) {
7349
+ if (await ports.createRecord(row.id, {
7350
+ ...spec.initialBody(row.name),
7351
+ ["enabled"]: false
7352
+ }) === "created") created += 1;
7353
+ else kept += 1;
7354
+ continue;
7355
+ }
7356
+ if ("enabled" in body) {
7357
+ kept += 1;
7358
+ continue;
7359
+ }
7360
+ await ports.switchOff(row.id);
7361
+ switched += 1;
7362
+ }
7363
+ const summary = {
7364
+ integrations: rows.length,
7365
+ off: rows.filter((r) => !r.enabled).length,
7366
+ created,
7367
+ switched,
7368
+ kept
7369
+ };
7370
+ return created === 0 && switched === 0 ? {
7371
+ outcome: "already-done",
7372
+ summary
7373
+ } : {
7374
+ outcome: "done",
7375
+ summary
7376
+ };
7377
+ }
7378
+ /** A migration entry: an addon states its kind and how a new body starts, nothing else. */
7379
+ function registrySwitchToBodyMigration(spec) {
7380
+ return {
7381
+ meta: {
7382
+ id: registrySwitchToBodyId(spec.addonId, spec.date),
7383
+ owner: spec.addonId,
7384
+ level: "addon-state",
7385
+ seq: spec.seq,
7386
+ dependsOn: [],
7387
+ store: "settings",
7388
+ scope: "cluster",
7389
+ onFailure: "block-owner",
7390
+ bodyKind: "procedure",
7391
+ description: "Move the registry enabled flag of every switched-off integration into its instance record body, creating the record when there is none",
7392
+ fixtureMark: "enabled"
7393
+ },
7394
+ procedure: (ports) => moveRegistrySwitchToBody(ports, {
7395
+ addonId: spec.addonId,
7396
+ initialBody: spec.initialBody
7397
+ })
7398
+ };
7399
+ }
7400
+ /** The hub and records sides of {@link registrySwitchToBodyMigration}. */
7401
+ function registrySwitchPortsOver(deps) {
7402
+ const handle = deps.records.kind({
7403
+ name: deps.kind.name,
7404
+ declaration: deps.kind.declaration,
7405
+ schema: record(string(), unknown())
7406
+ });
7407
+ return {
7408
+ listIntegrations: async (addonId) => (await deps.api.list()).filter((i) => i.addonId === addonId).map((i) => ({
7409
+ id: i.id,
7410
+ name: i.name,
7411
+ enabled: i.enabled !== false
7412
+ })),
7413
+ readBody: async (id) => (await handle.get(id))?.data ?? null,
7414
+ createRecord: async (id, body) => {
7415
+ if (await handle.get(id) !== null) return "exists";
7416
+ await handle.put({
7417
+ id,
7418
+ data: body
7419
+ }, { ifRev: 0 });
7420
+ return "created";
7421
+ },
7422
+ switchOff: async (id) => {
7423
+ await handle.patch(id, { [SWITCH_KEY]: false });
7424
+ }
7425
+ };
7426
+ }
7427
+ /**
7428
+ * Build a {@link DurableState} over a single store key. Transport-agnostic:
7429
+ * `read`/`write` are the addon-store or device-store accessors. The whole
7430
+ * validated value round-trips on every read/write — the schema is the
7431
+ * single source of truth for what is persisted, so no hand-listed field
7432
+ * set can drop a key on save.
7433
+ */
7434
+ function createDurableState(deps) {
7435
+ const get = async () => {
7436
+ const raw = (await deps.read())[deps.key];
7437
+ if (raw === void 0) return deps.fallback;
7438
+ const parsed = deps.schema.safeParse(raw);
7439
+ if (!parsed.success) {
7440
+ deps.onParseError?.(deps.key, parsed.error);
7441
+ return deps.fallback;
7442
+ }
7443
+ return parsed.data;
7444
+ };
7445
+ const set = async (next) => {
7446
+ const validated = deps.schema.parse(next);
7447
+ await deps.write({ [deps.key]: validated });
7448
+ };
7449
+ const update = async (fn) => {
7450
+ await set(fn(await get()));
7451
+ };
7452
+ return {
7453
+ get,
7454
+ set,
7455
+ update
7456
+ };
7457
+ }
7458
+ /**
7459
+ * Per-node scoping for the shared addon-settings blob.
7460
+ *
7461
+ * An addon's settings store is hub-central (the `addon-settings` cap is
7462
+ * hub-routed — the hub instance answers for every node), so fields whose
7463
+ * value is a NODE fact (decoder backend, engine pick, probed hardware
7464
+ * capabilities) persist under the node-scoped key `<key>@<nodeId>` inside
7465
+ * the single shared blob. The SCHEMA field key stays bare: the write path
7466
+ * ({@link scopePatch}) maps the bare field onto the target node's scoped
7467
+ * key; the read/hydrate path ({@link projectStore}) maps THIS node's value
7468
+ * back, so UI forms and `resolveConfig` only ever see the bare key.
7469
+ *
7470
+ * Fields opt in via the `perNode: true` schema marker on `ConfigFieldBase`
7471
+ * (`interfaces/config-ui.ts`); `BaseAddon` derives the key set from the
7472
+ * schema and routes reads/writes through these helpers.
7473
+ *
7474
+ * ## No bare-key fallback — deliberate
7475
+ *
7476
+ * {@link readNodeValue} reads the node-scoped key ONLY. A node with no
7477
+ * scoped key resolves to `undefined` so the field's schema `default` wins —
7478
+ * NEVER `store[base]` and never another node's value. A bare legacy key in
7479
+ * the store is invisible to every node, hub included, so one node's
7480
+ * selection can never leak onto another. (This generalizes the
7481
+ * `decoder-backend-keys.ts` semantics — the no-fallback variant — over an
7482
+ * arbitrary set of per-node field keys.)
7483
+ *
7484
+ * Pure functions only — no I/O, no imports beyond the language. This is a
7485
+ * LEAF module: import it via its deep path, never from the root barrel.
7486
+ */
7487
+ /**
7488
+ * Normalize a raw kernel node id to the bare node id used for scoping.
7489
+ * `localNodeId` can carry a `<node>/<addon>` suffix on forked child
7490
+ * processes; per-node settings are per-NODE, so strip the addon segment.
7491
+ * `undefined` / `null` / empty falls back to `'hub'`.
7492
+ */
7493
+ function normalizeNodeId(raw) {
7494
+ if (raw === void 0 || raw === null || raw === "") return "hub";
7495
+ const slashIdx = raw.indexOf("/");
7496
+ if (slashIdx < 0) return raw;
7497
+ const bare = raw.slice(0, slashIdx);
7498
+ return bare === "" ? "hub" : bare;
7499
+ }
7500
+ /** The node-scoped store key for a per-node field: `<base>@<nodeId>`. */
7501
+ function nodeScopedKey(base, nodeId) {
7502
+ return `${base}@${normalizeNodeId(nodeId)}`;
7503
+ }
7504
+ /**
7505
+ * Read a node's value for a per-node field from the raw shared store:
7506
+ * the node-scoped key when present, otherwise `undefined`.
7507
+ * Deliberately NO bare-key fallback (see module doc) — the caller lets the
7508
+ * schema `default` win on `undefined`.
7509
+ */
7510
+ function readNodeValue(store, base, nodeId) {
7511
+ return store[nodeScopedKey(base, nodeId)];
7512
+ }
7513
+ /**
7514
+ * Re-map a UI/settings patch so every bare perNode field persists under the
7515
+ * TARGET node's scoped key; all other keys pass through unchanged. Used on
7516
+ * the write path so a save for one node never clobbers another node's value
7517
+ * (and the bare key is never written). Returns a new object — the input
7518
+ * patch is not mutated.
7519
+ */
7520
+ function scopePatch(patch, perNodeKeys, nodeId) {
7521
+ const out = {};
7522
+ for (const [key, value] of Object.entries(patch)) out[perNodeKeys.has(key) ? nodeScopedKey(key, nodeId) : key] = value;
7523
+ return out;
7524
+ }
7525
+ /**
7526
+ * Project the raw shared store onto the bare schema keys for ONE node so a
7527
+ * UI schema (whose field keys are bare) hydrates from that node's own
7528
+ * values:
7529
+ *
7530
+ * - EVERY `@`-scoped key (any node's) is dropped from the pass-through.
7531
+ * - Every bare perNode key is dropped from the pass-through (a stray bare
7532
+ * legacy key must never hydrate any node — no bare fallback).
7533
+ * - THIS node's effective value ({@link readNodeValue}) is then laid onto
7534
+ * each bare perNode key; when the node has no scoped key the bare key is
7535
+ * left ABSENT so the field's schema `default` wins.
7536
+ *
7537
+ * Returns a new object — the input store is not mutated.
7538
+ */
7539
+ function projectStore(store, perNodeKeys, nodeId) {
7540
+ const out = {};
7541
+ for (const [key, value] of Object.entries(store)) {
7542
+ if (key.includes("@")) continue;
7543
+ if (perNodeKeys.has(key)) continue;
7544
+ out[key] = value;
7545
+ }
7546
+ for (const base of perNodeKeys) {
7547
+ const value = readNodeValue(store, base, nodeId);
7548
+ if (value !== void 0) out[base] = value;
7549
+ }
7550
+ return out;
7551
+ }
7552
+ /** Every scope, in the order the guard and the docs list them. */
7553
+ var SCOPED_SETTINGS_SCOPES = [
7554
+ "cluster",
7555
+ "device-defaults",
7556
+ "node"
7557
+ ];
6937
7558
  /** A write to a secret path could not be stored in the keychain, so it was refused. */
6938
7559
  var KeychainWriteRefusedError = class extends Error {
6939
7560
  fieldPath;
@@ -6944,7 +7565,7 @@ var KeychainWriteRefusedError = class extends Error {
6944
7565
  }
6945
7566
  };
6946
7567
  var KEEP = { kind: "keep" };
6947
- function isRecord$6(value) {
7568
+ function isRecord$4(value) {
6948
7569
  return typeof value === "object" && value !== null && !Array.isArray(value);
6949
7570
  }
6950
7571
  function defaultMintId() {
@@ -6957,7 +7578,7 @@ function collectSecretMarkerRefs(value, out = []) {
6957
7578
  return out;
6958
7579
  }
6959
7580
  if (Array.isArray(value)) for (const item of value) collectSecretMarkerRefs(item, out);
6960
- else if (isRecord$6(value)) for (const child of Object.values(value)) collectSecretMarkerRefs(child, out);
7581
+ else if (isRecord$4(value)) for (const child of Object.values(value)) collectSecretMarkerRefs(child, out);
6961
7582
  return out;
6962
7583
  }
6963
7584
  async function storedValueEquals(secrets, marker, candidate) {
@@ -7012,7 +7633,7 @@ function rowId(row, idKey) {
7012
7633
  return null;
7013
7634
  }
7014
7635
  async function writeArray(ctx, node, incoming, stored, fieldPath) {
7015
- const storedRows = Array.isArray(stored) ? stored.filter(isRecord$6) : [];
7636
+ const storedRows = Array.isArray(stored) ? stored.filter(isRecord$4) : [];
7016
7637
  if (!Array.isArray(incoming)) {
7017
7638
  ctx.deletes.push(...collectSecretMarkerRefs(storedRows));
7018
7639
  return {
@@ -7028,7 +7649,7 @@ async function writeArray(ctx, node, incoming, stored, fieldPath) {
7028
7649
  const kept = /* @__PURE__ */ new Set();
7029
7650
  const rows = [];
7030
7651
  for (const row of incoming) {
7031
- if (!isRecord$6(row)) {
7652
+ if (!isRecord$4(row)) {
7032
7653
  rows.push(row);
7033
7654
  continue;
7034
7655
  }
@@ -7053,7 +7674,7 @@ async function writeNode(ctx, node, incoming, stored, fieldPath) {
7053
7674
  case "leaf": return writeLeaf(ctx, incoming, stored, fieldPath);
7054
7675
  case "array": return writeArray(ctx, node, incoming, stored, fieldPath);
7055
7676
  case "object": {
7056
- if (!isRecord$6(incoming)) {
7677
+ if (!isRecord$4(incoming)) {
7057
7678
  if (incoming === void 0) return KEEP;
7058
7679
  ctx.deletes.push(...collectSecretMarkerRefs(stored));
7059
7680
  return {
@@ -7061,7 +7682,7 @@ async function writeNode(ctx, node, incoming, stored, fieldPath) {
7061
7682
  value: incoming
7062
7683
  };
7063
7684
  }
7064
- const storedObj = isRecord$6(stored) ? stored : {};
7685
+ const storedObj = isRecord$4(stored) ? stored : {};
7065
7686
  return {
7066
7687
  kind: "value",
7067
7688
  value: await writeMembers(ctx, node.children, incoming, storedObj, (m) => `${fieldPath}.${m}`)
@@ -7184,7 +7805,7 @@ async function resolveSecretMarkers(value, secrets, options = {}) {
7184
7805
  value: items
7185
7806
  };
7186
7807
  }
7187
- if (isRecord$6(v)) {
7808
+ if (isRecord$4(v)) {
7188
7809
  const out = {};
7189
7810
  for (const [k, child] of Object.entries(v)) {
7190
7811
  const s = substitute(child);
@@ -7216,7 +7837,7 @@ var SecretOverwriteRefusedError = class extends Error {
7216
7837
  this.name = "SecretOverwriteRefusedError";
7217
7838
  }
7218
7839
  };
7219
- function isRecord$5(value) {
7840
+ function isRecord$3(value) {
7220
7841
  return typeof value === "object" && value !== null && !Array.isArray(value);
7221
7842
  }
7222
7843
  function resolvedValue(pass, marker) {
@@ -7245,7 +7866,7 @@ function inArray(pass, incoming, stored) {
7245
7866
  return incoming.map((item, index) => {
7246
7867
  const twin = stored[index];
7247
7868
  if (isSecretMarker(twin)) return typeof item === "string" && item === resolvedValue(pass, twin) ? twin : item;
7248
- if (isRecord$5(item) && isRecord$5(twin)) return inArrayRow(pass, item, twin);
7869
+ if (isRecord$3(item) && isRecord$3(twin)) return inArrayRow(pass, item, twin);
7249
7870
  if (Array.isArray(item) && Array.isArray(twin)) return inArray(pass, item, twin);
7250
7871
  return item;
7251
7872
  });
@@ -7256,7 +7877,7 @@ function inArrayRow(pass, incoming, stored) {
7256
7877
  const twin = stored[key];
7257
7878
  if (isSecretMarker(twin)) {
7258
7879
  if (typeof value === "string" && value === resolvedValue(pass, twin)) out[key] = twin;
7259
- } else if (isRecord$5(value) && isRecord$5(twin)) out[key] = inArrayRow(pass, value, twin);
7880
+ } else if (isRecord$3(value) && isRecord$3(twin)) out[key] = inArrayRow(pass, value, twin);
7260
7881
  else if (Array.isArray(value) && Array.isArray(twin)) out[key] = inArray(pass, value, twin);
7261
7882
  }
7262
7883
  return out;
@@ -7264,7 +7885,7 @@ function inArrayRow(pass, incoming, stored) {
7264
7885
  async function walk(pass, incoming, stored) {
7265
7886
  if (isSecretMarker(stored)) return atMarker(pass, incoming, stored);
7266
7887
  if (Array.isArray(incoming) && Array.isArray(stored)) return inArray(pass, incoming, stored);
7267
- if (!isRecord$5(incoming) || !isRecord$5(stored)) return incoming;
7888
+ if (!isRecord$3(incoming) || !isRecord$3(stored)) return incoming;
7268
7889
  const out = { ...incoming };
7269
7890
  for (const [key, value] of Object.entries(incoming)) out[key] = await walk(pass, value, stored[key]);
7270
7891
  return out;
@@ -7295,7 +7916,7 @@ async function restoreUnchangedSecrets(input) {
7295
7916
  function isJsonEqual(a, b) {
7296
7917
  if (Object.is(a, b)) return true;
7297
7918
  if (Array.isArray(a)) return Array.isArray(b) && a.length === b.length && a.every((v, i) => isJsonEqual(v, b[i]));
7298
- if (isRecord$5(a) && isRecord$5(b)) {
7919
+ if (isRecord$3(a) && isRecord$3(b)) {
7299
7920
  const keys = Object.keys(a);
7300
7921
  if (keys.length !== Object.keys(b).length) return false;
7301
7922
  return keys.every((k) => Object.prototype.hasOwnProperty.call(b, k) && isJsonEqual(a[k], b[k]));
@@ -7319,7 +7940,7 @@ function markerKeysOf(blob, owner) {
7319
7940
  }
7320
7941
  function nodeFromStored(value, owner) {
7321
7942
  if (isSecretMarker(value)) return isSecretRefOwnedBy(value.$secret, owner) ? { kind: "leaf" } : null;
7322
- if (!isRecord$5(value)) return null;
7943
+ if (!isRecord$3(value)) return null;
7323
7944
  const children = /* @__PURE__ */ new Map();
7324
7945
  for (const [key, child] of Object.entries(value)) {
7325
7946
  const node = nodeFromStored(child, owner);
@@ -7816,13 +8437,48 @@ var BaseAddon = class {
7816
8437
  if (api === void 0) throw new Error(`${this.ctx.id}: the migration API is not available on this context`);
7817
8438
  return this.runBound(sets.flatMap((set) => set.bind(api)), options);
7818
8439
  }
7819
- async runBound(migrations, options) {
8440
+ /**
8441
+ * A device addon states its instance kind once, before its migrations run, and the one-switch
8442
+ * migration (registry `enabled` to the instance body, epic #440 step 3) joins whatever
8443
+ * catalogue the addon runs, in the SAME declaration (the engine replaces an owner's catalogue
8444
+ * on every declare).
8445
+ */
8446
+ declareRegistrySwitch(spec) {
8447
+ this.registrySwitchSpec = spec;
8448
+ }
8449
+ registrySwitchSpec = null;
8450
+ registrySwitchBound() {
8451
+ const spec = this.registrySwitchSpec;
8452
+ if (spec === null) return [];
8453
+ const api = this.ctx.migrationApi;
8454
+ if (api === void 0) {
8455
+ this.ctx.logger.warn("the registry switch migration is skipped: the migration API is not available on this context");
8456
+ return [];
8457
+ }
8458
+ return migrationSet([registrySwitchToBodyMigration({
8459
+ addonId: this.ctx.id,
8460
+ date: "2026-11-06",
8461
+ seq: 1e3,
8462
+ initialBody: spec.initialBody
8463
+ })], (a) => registrySwitchPortsOver({
8464
+ api: integrationRowsApiOver(a),
8465
+ records: switchRecordsOverMigrationApi(a),
8466
+ kind: spec.kind
8467
+ })).bind(api);
8468
+ }
8469
+ async runBound(declared, options) {
8470
+ const added = this.registrySwitchBound();
8471
+ const migrations = [...declared, ...added];
8472
+ const phased = options?.only === void 0 || added.length === 0 ? options : {
8473
+ ...options,
8474
+ only: [...options.only, ...added.map((m) => m.meta.id)]
8475
+ };
7820
8476
  const api = this.ctx.api.migrations;
7821
8477
  const report = await runAddonMigrations({
7822
8478
  declareOwner: (input) => api.declareOwner.mutate(input),
7823
8479
  startMigration: (input) => api.startMigration.mutate(input),
7824
8480
  finishMigration: (input) => api.finishMigration.mutate(input)
7825
- }, migrations, this.ctx.logger, options);
8481
+ }, migrations, this.ctx.logger, phased);
7826
8482
  if (report.blockOwner.length > 0) throw new AddonMigrationsBlockedError(report.blockOwner);
7827
8483
  return report;
7828
8484
  }
@@ -8895,245 +9551,94 @@ function normalizeAddonInitResult(result) {
8895
9551
  if (Array.isArray(result)) return { providers: result };
8896
9552
  return result;
8897
9553
  }
8898
- var PREFIX = "records/";
8899
- /** The base of every records failure. `detail` is the human part of the message. */
8900
- var RecordsError = class extends Error {
8901
- code;
8902
- detail;
8903
- constructor(code, detail) {
8904
- super(`${PREFIX}${code}: ${detail}`);
8905
- this.name = "RecordsError";
8906
- this.code = code;
8907
- this.detail = detail;
8908
- }
8909
- };
8910
- /** The keychain could not store or serve a value: explicit, never an empty string. */
8911
- var RecordSecretUnavailableError = class extends RecordsError {
8912
- constructor(detail) {
8913
- super("secret-unavailable", detail);
8914
- this.name = "RecordSecretUnavailableError";
8915
- }
8916
- };
8917
- var InvalidRecordError = class extends RecordsError {
8918
- constructor(detail) {
8919
- super("invalid-record", detail);
8920
- this.name = "InvalidRecordError";
8921
- }
8922
- };
8923
- /** A kind declaration the engine refuses (non-additive change, bad shape, wrong file). */
8924
- var DeclarationRefusedError = class extends RecordsError {
8925
- constructor(detail) {
8926
- super("declaration-refused", detail);
8927
- this.name = "DeclarationRefusedError";
8928
- }
8929
- };
8930
- /** Limits and names of `ctx.records` (D881). One authority; the engine and the facade read it. */
8931
- /** The files a kind may live in. `history` is device-history's (D850), never records. */
8932
- var RECORD_DATABASES = ["settings", "events"];
8933
- /** The classes of a kind: the `@durable` vocabulary, one authority (replaces the annotation). */
8934
- var RECORD_CLASSES = [
8935
- "config",
8936
- "ledger",
8937
- "audit",
8938
- "mirror",
8939
- "ephemeral"
8940
- ];
8941
- var RECORD_DEFAULT_MAX_DATA_BYTES = 64 * 1024;
8942
- var RECORD_MAX_DATA_BYTES = 1024 * 1024;
8943
- var RECORD_BATCH_MAX = 1e3;
8944
- var RECORD_QUERY_MAX = 1e3;
8945
- /** A kind in the `settings` file may not bound itself above this (D447: high volume is `events`). */
8946
- var RECORD_SETTINGS_MAX_ROWS = 5e4;
8947
- /** The `Column`-free proof prefix: a ref collection for a kind's secret fields. */
8948
- var RECORD_SECRET_COLLECTION_PREFIX = "records:";
9554
+ object({
9555
+ field: string().min(1),
9556
+ on: literal("advance")
9557
+ });
8949
9558
  /**
8950
- * Secret fields of a record, addressed the way a Zod schema declares them
8951
- * (`collectZodSecretPaths`): dotted keys, `[]` for "each element of this array"
8952
- * (`auth.accessToken`, `headers[].value`).
8953
- *
8954
- * `{}` after a key means "each value of this map" (`applianceSecrets{}`): the map's own key
8955
- * names the value (`applianceSecrets{fridge}`), so no id key is declared and a body that drops a
8956
- * key releases exactly that key's secret.
9559
+ * Output schema shared by the contribution + live methods.
8957
9560
  *
8958
- * Array elements are matched by a DECLARED id key (`secretArrayKeys`:
8959
- * `{ headers: 'name' }`), never by index, so reordering a list keeps every
8960
- * keychain ref (the same rule as `arrayItemFieldPath`). The concrete path of a
8961
- * leaf names its element: `headers[X-Api].value`.
9561
+ * Mirrors the `ConfigUISchemaWithValues` shape (sections[] + optional
9562
+ * tabs[]) without importing from `../interfaces/config-ui.js` — a
9563
+ * concrete-but-lenient Zod object keeps tRPC output inference happy
9564
+ * (using `z.unknown()` here collapses unrelated router branches to
9565
+ * `unknown` when the generator re-inlines the huge AppRouter type).
8962
9566
  *
8963
- * Pure and browser-safe. Nothing here mutates: every transform returns a new value.
8964
- */
8965
- /** The array prefixes (declared form, e.g. `headers` or `a.headers`) of a path. */
8966
- function parseSecretPath(path) {
8967
- if (path.length === 0) throw new InvalidRecordError("an empty secret path");
8968
- return path.split(".").map((raw) => {
8969
- const each = raw.endsWith("[]");
8970
- const map = raw.endsWith("{}");
8971
- const key = each || map ? raw.slice(0, -2) : raw;
8972
- if (key.length === 0) throw new InvalidRecordError(`secret path "${path}" has an empty segment`);
8973
- return {
8974
- key,
8975
- each,
8976
- map
8977
- };
8978
- });
8979
- }
8980
- /** The declared array prefixes of `path` that need an id key (`headers`, `a.rows`). */
8981
- function secretArrayPrefixes(path) {
8982
- const segments = parseSecretPath(path);
8983
- const prefixes = [];
8984
- const walked = [];
8985
- for (const segment of segments) {
8986
- walked.push(segment.key);
8987
- if (segment.each) prefixes.push(walked.join("."));
8988
- }
8989
- return prefixes;
8990
- }
8991
- function isRecord$4(value) {
8992
- return typeof value === "object" && value !== null && !Array.isArray(value);
8993
- }
8994
- function elementId(element, idKey, declared, prefix) {
8995
- const id = isRecord$4(element) ? element[idKey] : void 0;
8996
- 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`);
8997
- return id;
8998
- }
8999
- /**
9000
- * Visit every secret leaf PRESENT in `data` (an absent branch has nothing to
9001
- * visit). `replace` returns the new leaf value, or {@link REMOVE_LEAF}; the
9002
- * result is a new body, `data` is untouched.
9567
+ * `.passthrough()` on sections/fields accepts whatever FormBuilder
9568
+ * extensions the caller adds (showWhen, displayScale, …) without
9569
+ * rebuilding every time a new field kind is introduced.
9003
9570
  */
9004
- var REMOVE_LEAF = Symbol("remove-leaf");
9005
- function mapAt(node, segments, index, walkedKeys, concretePrefix, declared, arrayKeys, visit) {
9006
- if (!isRecord$4(node)) return node;
9007
- const segment = segments[index];
9008
- if (segment === void 0) return node;
9009
- if (!Object.prototype.hasOwnProperty.call(node, segment.key)) return node;
9010
- const child = node[segment.key];
9011
- const keys = [...walkedKeys, segment.key];
9012
- const last = index === segments.length - 1;
9013
- if (segment.each) {
9014
- if (!Array.isArray(child)) return node;
9015
- const prefix = keys.join(".");
9016
- const idKey = arrayKeys[prefix];
9017
- if (idKey === void 0) throw new InvalidRecordError(`"${declared}": no id key declared for the array "${prefix}"`);
9018
- const mapped = child.map((element) => {
9019
- const id = elementId(element, idKey, declared, prefix);
9020
- const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}[${encodeURIComponent(id)}]`;
9021
- return last ? element : mapAt(element, segments, index + 1, keys, concrete, declared, arrayKeys, visit);
9022
- });
9023
- return {
9024
- ...node,
9025
- [segment.key]: mapped
9026
- };
9027
- }
9028
- if (segment.map) {
9029
- if (!isRecord$4(child)) return node;
9030
- const kept = Object.entries(child).map(([mapKey, value]) => {
9031
- const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}{${encodeURIComponent(mapKey)}}`;
9032
- if (!last) return [mapKey, mapAt(value, segments, index + 1, keys, concrete, declared, arrayKeys, visit)];
9033
- return [mapKey, visit({
9034
- declared,
9035
- concrete,
9036
- value
9037
- })];
9038
- }).filter(([, value]) => value !== REMOVE_LEAF);
9039
- return {
9040
- ...node,
9041
- [segment.key]: Object.fromEntries(kept)
9042
- };
9043
- }
9044
- const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}`;
9045
- if (last) {
9046
- const replacement = visit({
9047
- declared,
9048
- concrete,
9049
- value: child
9050
- });
9051
- if (replacement === REMOVE_LEAF) return Object.fromEntries(Object.entries(node).filter(([key]) => key !== segment.key));
9052
- return {
9053
- ...node,
9054
- [segment.key]: replacement
9055
- };
9056
- }
9571
+ var ContributionSectionSchema = object({
9572
+ id: string(),
9573
+ title: string(),
9574
+ description: string().optional(),
9575
+ style: _enum(["card", "accordion"]).optional(),
9576
+ defaultCollapsed: boolean().optional(),
9577
+ columns: union([
9578
+ literal(1),
9579
+ literal(2),
9580
+ literal(3),
9581
+ literal(4)
9582
+ ]).optional(),
9583
+ tab: string().optional(),
9584
+ location: _enum([
9585
+ "settings",
9586
+ "top-tab",
9587
+ "hero"
9588
+ ]).optional(),
9589
+ order: number().optional(),
9590
+ fields: array(any())
9591
+ });
9592
+ object({
9593
+ tabs: array(object({
9594
+ id: string(),
9595
+ label: string(),
9596
+ icon: string(),
9597
+ order: number().optional()
9598
+ })).optional(),
9599
+ sections: array(ContributionSectionSchema)
9600
+ }).nullable();
9601
+ object({ deviceId: number() }), object({ deviceId: number() }), object({
9602
+ deviceId: number(),
9603
+ patch: record(string(), unknown())
9604
+ }), object({ success: literal(true) });
9605
+ object({ deviceId: number() }), unknown().nullable();
9606
+ function method(input, output, options) {
9057
9607
  return {
9058
- ...node,
9059
- [segment.key]: mapAt(child, segments, index + 1, keys, concrete, declared, arrayKeys, visit)
9608
+ input,
9609
+ output,
9610
+ kind: options?.kind ?? "query",
9611
+ ...options?.auth !== void 0 ? { auth: options.auth } : {},
9612
+ ...options?.access !== void 0 ? { access: options.access } : {},
9613
+ ...options?.role !== void 0 ? { role: options.role } : {},
9614
+ ...options?.caller !== void 0 ? { caller: options.caller } : {},
9615
+ timeoutMs: options?.timeoutMs
9060
9616
  };
9061
9617
  }
9062
- /** Replace/remove every present secret leaf; returns a NEW body. */
9063
- function mapSecretLeaves(data, paths, arrayKeys, visit) {
9064
- let current = data;
9065
- for (const declared of paths) current = mapAt(current, parseSecretPath(declared), 0, [], "", declared, arrayKeys, visit);
9066
- return current;
9067
- }
9068
9618
  /**
9069
- * The keychain collection name a kind's secrets live under. Prefixed so a
9070
- * record's refs never collide with the refs a legacy collection of the same name
9071
- * already holds during an adoption.
9619
+ * A wrapper/system-only method: served exclusively by the cap's system-level
9620
+ * provider (`InferProvider`), and OPTIONAL on `InferNativeProvider` so per-device
9621
+ * driver natives don't stub out a wrapper concern (e.g. a cross-device cache
9622
+ * overview). The `systemOnly: true` literal is what `InferNativeProvider` keys on.
9072
9623
  */
9073
- function recordSecretCollection(kind) {
9074
- return `${RECORD_SECRET_COLLECTION_PREFIX}${kind}`;
9075
- }
9076
- /** The ONE ref a row's secret field may carry: the engine and the facade both build it here. */
9077
- function recordSecretRef(owner, kind, rowId, concretePath) {
9078
- return buildSecretRef({
9079
- owner,
9080
- scope: {
9081
- kind: "row",
9082
- collection: recordSecretCollection(kind),
9083
- rowId
9084
- },
9085
- fieldPath: concretePath
9086
- });
9624
+ function systemMethod(input, output, options) {
9625
+ return {
9626
+ ...method(input, output, options),
9627
+ systemOnly: true
9628
+ };
9087
9629
  }
9088
9630
  /**
9089
- * A stored secret, as an admin read shows it: a VIEW naming the row's own
9090
- * keychain ref (`set: true`), never the value and no longer the bare redaction
9091
- * token. The form hands it to the secret field, which reveals the value by ref
9092
- * through the audited `keychain-admin.reveal`; sent back untouched it keeps the
9093
- * stored secret (the records door reads a view as KEEP).
9094
- *
9095
- * ONE implementation for the entries service and for every addon that serves
9096
- * its own instances (`RecordIntegrationInstances`).
9631
+ * A method a SOURCE of a collection cap may legitimately not serve — OPTIONAL
9632
+ * on `InferProvider`. The `providerOptional: true` literal is what
9633
+ * `InferProvider` keys on; see {@link CapabilityMethodSchema.providerOptional}
9634
+ * for when this is the honest answer and when it is a soft stub.
9097
9635
  */
9098
- function isRecord$3(value) {
9099
- return typeof value === "object" && value !== null && !Array.isArray(value);
9100
- }
9101
- function secretViewsOf(owner, kind, id, decl, data) {
9102
- if (decl.secretPaths.length === 0) return data;
9103
- const shown = mapSecretLeaves(data, decl.secretPaths, decl.secretArrayKeys, (leaf) => {
9104
- if (leaf.value !== "__camstack_redacted__") return leaf.value;
9105
- return {
9106
- $secret: recordSecretRef(owner, kind, id, leaf.concrete),
9107
- v: 1,
9108
- set: true
9109
- };
9110
- });
9111
- return isRecord$3(shown) ? shown : data;
9636
+ function optionalMethod(input, output, options) {
9637
+ return {
9638
+ ...method(input, output, options),
9639
+ providerOptional: true
9640
+ };
9112
9641
  }
9113
- /**
9114
- * The share-view scope kinds a share-link token can carry. The hub mints
9115
- * and validates them (`ShareViewGrantSchema` builds its
9116
- * enum from this list); a data plane names the kinds it ACCEPTS in `share`.
9117
- */
9118
- var SHARE_VIEW_KINDS = ["grid-view", "events-view"];
9119
- /** The wire shape of {@link PeerBytesTicket} — see the type for what it is. */
9120
- var PeerBytesTicketSchema = object({
9121
- /** `http://127.0.0.1:<port>/<token>`. One `GET` takes it. */
9122
- url: string().min(1),
9123
- /**
9124
- * The HOST node this URL means something on — the hub or a named agent,
9125
- * never a runner. {@link AddonPeerBytes.open} compares it to its own and
9126
- * refuses `cross-node` by name when they differ, without dialling.
9127
- */
9128
- hostNodeId: string().min(1),
9129
- expiresAtMs: number().int().nonnegative(),
9130
- /**
9131
- * What the producer DECLARED the body to be, when it knows — `null` when it
9132
- * does not. Never `0` for unknown (D393): a consumer sizing a bound off this
9133
- * must be able to tell "the producer did not say" from "the body is empty".
9134
- */
9135
- declaredBytes: number().int().nonnegative().nullable()
9136
- });
9137
9642
  function defOf(schema) {
9138
9643
  const zodBag = Reflect.get(schema, "_zod");
9139
9644
  if (typeof zodBag !== "object" || zodBag === null) return {};
@@ -9363,6 +9868,7 @@ function defineRecordKinds(specs) {
9363
9868
  function entryBody(shape) {
9364
9869
  return object({
9365
9870
  name: string().min(1),
9871
+ enabled: boolean().optional(),
9366
9872
  ...shape
9367
9873
  });
9368
9874
  }
@@ -9389,94 +9895,30 @@ function defineEntryKind(name, spec) {
9389
9895
  if (defined === void 0) throw new DeclarationRefusedError(`entry kind "${name}" was not built`);
9390
9896
  return defined;
9391
9897
  }
9392
- object({
9393
- field: string().min(1),
9394
- on: literal("advance")
9395
- });
9396
9898
  /**
9397
- * Output schema shared by the contribution + live methods.
9398
- *
9399
- * Mirrors the `ConfigUISchemaWithValues` shape (sections[] + optional
9400
- * tabs[]) without importing from `../interfaces/config-ui.js` — a
9401
- * concrete-but-lenient Zod object keeps tRPC output inference happy
9402
- * (using `z.unknown()` here collapses unrelated router branches to
9403
- * `unknown` when the generator re-inlines the huge AppRouter type).
9404
- *
9405
- * `.passthrough()` on sections/fields accepts whatever FormBuilder
9406
- * extensions the caller adds (showWhen, displayScale, …) without
9407
- * rebuilding every time a new field kind is introduced.
9899
+ * The share-view scope kinds a share-link token can carry. The hub mints
9900
+ * and validates them (`ShareViewGrantSchema` builds its
9901
+ * enum from this list); a data plane names the kinds it ACCEPTS in `share`.
9408
9902
  */
9409
- var ContributionSectionSchema = object({
9410
- id: string(),
9411
- title: string(),
9412
- description: string().optional(),
9413
- style: _enum(["card", "accordion"]).optional(),
9414
- defaultCollapsed: boolean().optional(),
9415
- columns: union([
9416
- literal(1),
9417
- literal(2),
9418
- literal(3),
9419
- literal(4)
9420
- ]).optional(),
9421
- tab: string().optional(),
9422
- location: _enum([
9423
- "settings",
9424
- "top-tab",
9425
- "hero"
9426
- ]).optional(),
9427
- order: number().optional(),
9428
- fields: array(any())
9903
+ var SHARE_VIEW_KINDS = ["grid-view", "events-view"];
9904
+ /** The wire shape of {@link PeerBytesTicket} — see the type for what it is. */
9905
+ var PeerBytesTicketSchema = object({
9906
+ /** `http://127.0.0.1:<port>/<token>`. One `GET` takes it. */
9907
+ url: string().min(1),
9908
+ /**
9909
+ * The HOST node this URL means something on — the hub or a named agent,
9910
+ * never a runner. {@link AddonPeerBytes.open} compares it to its own and
9911
+ * refuses `cross-node` by name when they differ, without dialling.
9912
+ */
9913
+ hostNodeId: string().min(1),
9914
+ expiresAtMs: number().int().nonnegative(),
9915
+ /**
9916
+ * What the producer DECLARED the body to be, when it knows — `null` when it
9917
+ * does not. Never `0` for unknown (D393): a consumer sizing a bound off this
9918
+ * must be able to tell "the producer did not say" from "the body is empty".
9919
+ */
9920
+ declaredBytes: number().int().nonnegative().nullable()
9429
9921
  });
9430
- object({
9431
- tabs: array(object({
9432
- id: string(),
9433
- label: string(),
9434
- icon: string(),
9435
- order: number().optional()
9436
- })).optional(),
9437
- sections: array(ContributionSectionSchema)
9438
- }).nullable();
9439
- object({ deviceId: number() }), object({ deviceId: number() }), object({
9440
- deviceId: number(),
9441
- patch: record(string(), unknown())
9442
- }), object({ success: literal(true) });
9443
- object({ deviceId: number() }), unknown().nullable();
9444
- function method(input, output, options) {
9445
- return {
9446
- input,
9447
- output,
9448
- kind: options?.kind ?? "query",
9449
- ...options?.auth !== void 0 ? { auth: options.auth } : {},
9450
- ...options?.access !== void 0 ? { access: options.access } : {},
9451
- ...options?.role !== void 0 ? { role: options.role } : {},
9452
- ...options?.caller !== void 0 ? { caller: options.caller } : {},
9453
- timeoutMs: options?.timeoutMs
9454
- };
9455
- }
9456
- /**
9457
- * A wrapper/system-only method: served exclusively by the cap's system-level
9458
- * provider (`InferProvider`), and OPTIONAL on `InferNativeProvider` so per-device
9459
- * driver natives don't stub out a wrapper concern (e.g. a cross-device cache
9460
- * overview). The `systemOnly: true` literal is what `InferNativeProvider` keys on.
9461
- */
9462
- function systemMethod(input, output, options) {
9463
- return {
9464
- ...method(input, output, options),
9465
- systemOnly: true
9466
- };
9467
- }
9468
- /**
9469
- * A method a SOURCE of a collection cap may legitimately not serve — OPTIONAL
9470
- * on `InferProvider`. The `providerOptional: true` literal is what
9471
- * `InferProvider` keys on; see {@link CapabilityMethodSchema.providerOptional}
9472
- * for when this is the honest answer and when it is a soft stub.
9473
- */
9474
- function optionalMethod(input, output, options) {
9475
- return {
9476
- ...method(input, output, options),
9477
- providerOptional: true
9478
- };
9479
- }
9480
9922
  var READING_QUANTITIES = [
9481
9923
  "temperature",
9482
9924
  "pressure",
@@ -10055,7 +10497,6 @@ var CAP_NAMES = Object.freeze([
10055
10497
  "climate-control",
10056
10498
  "color",
10057
10499
  "composer",
10058
- "connection-test",
10059
10500
  "connectivity",
10060
10501
  "consumables",
10061
10502
  "contact",
@@ -11202,6 +11643,10 @@ Object.freeze({
11202
11643
  "all",
11203
11644
  "one"
11204
11645
  ]
11646
+ },
11647
+ {
11648
+ "path": "positionUpdatedAt",
11649
+ "valueType": "number"
11205
11650
  }
11206
11651
  ],
11207
11652
  "meter": [{
@@ -11456,22 +11901,6 @@ Object.freeze({
11456
11901
  "path": "pumpRunning",
11457
11902
  "valueType": "boolean"
11458
11903
  },
11459
- {
11460
- "path": "lastDrink",
11461
- "valueType": "number"
11462
- },
11463
- {
11464
- "path": "currentHourDrink",
11465
- "valueType": "number"
11466
- },
11467
- {
11468
- "path": "last24hDrink",
11469
- "valueType": "number"
11470
- },
11471
- {
11472
- "path": "todayDrink",
11473
- "valueType": "number"
11474
- },
11475
11904
  {
11476
11905
  "path": "error",
11477
11906
  "valueType": "string"
@@ -12037,6 +12466,59 @@ Object.freeze({
12037
12466
  }
12038
12467
  ]
12039
12468
  });
12469
+ Object.freeze({
12470
+ "actions": { "run": 363e4 },
12471
+ "audio-analyzer": { "classify": 3e4 },
12472
+ "custom-model-registry": { "importModelBundle": 18e5 },
12473
+ "database-snapshot": { "writeSnapshot": 18e5 },
12474
+ "device-manager": {
12475
+ "migrateDevice": 72e4,
12476
+ "runDiscoverySweep": 12e4
12477
+ },
12478
+ "device-provider": { "reloadDevice": 18e4 },
12479
+ "llm": {
12480
+ "generate": 6e5,
12481
+ "generateVision": 6e5,
12482
+ "testProfile": 6e5
12483
+ },
12484
+ "llm-runtime": {
12485
+ "complete": 6e5,
12486
+ "completeApple": 6e5,
12487
+ "ensureStarted": 6e5,
12488
+ "installModel": 36e5
12489
+ },
12490
+ "local-network": { "scanNetwork": 9e4 },
12491
+ "model-convert": { "convert": 6e5 },
12492
+ "pipeline-analytics": {
12493
+ "addRetrainFrameFromRecording": 6e4,
12494
+ "offerRetrainArchive": 12e4,
12495
+ "proposeRetrainAnnotationsWithLlm": 18e4,
12496
+ "resolveRetrainTrainingCorpus": 6e4,
12497
+ "writeRetrainArchive": 36e5
12498
+ },
12499
+ "server-management": { "applyServerUpdate": 96e4 },
12500
+ "terminal-session": { "pullOutput": 15e3 },
12501
+ "training": {
12502
+ "canaryResult": 12e4,
12503
+ "cancelJob": 12e4,
12504
+ "planJob": 6e4,
12505
+ "registerResult": 18e5,
12506
+ "rollbackCanary": 12e4,
12507
+ "startJob": 12e4,
12508
+ "startJobBatch": 12e4
12509
+ },
12510
+ "training-provider": {
12511
+ "cancelJob": 6e4,
12512
+ "cleanupJob": 3e5,
12513
+ "getJob": 6e4,
12514
+ "listJobEvents": 6e4,
12515
+ "listJobs": 12e4,
12516
+ "offerArtifact": 3e5,
12517
+ "readResult": 3e5,
12518
+ "submitJob": 18e5,
12519
+ "uploadDataset": 72e5
12520
+ }
12521
+ });
12040
12522
  object({
12041
12523
  code: string().regex(/^[a-z][a-z0-9-]*(\.[a-z0-9-]+)+$/),
12042
12524
  params: record(string(), union([string(), number()])).optional()
@@ -12056,7 +12538,7 @@ function userError(code, params, englishFallback) {
12056
12538
  return new CamstackError(code, params, englishFallback);
12057
12539
  }
12058
12540
  //#endregion
12059
- //#region ../types/dist/composition-pOHbTzRB.mjs
12541
+ //#region ../types/dist/composition-BmBHuDTQ.mjs
12060
12542
  /**
12061
12543
  * The ffmpeg build every CamStack node downloads, per platform and arch.
12062
12544
  *
@@ -12360,7 +12842,7 @@ var table = {
12360
12842
  },
12361
12843
  dwell: {
12362
12844
  minArgs: 3,
12363
- maxArgs: 3,
12845
+ maxArgs: 4,
12364
12846
  apply: () => {
12365
12847
  throw new ExpressionEvalError("dwell: stateful evaluation context is required");
12366
12848
  }
@@ -13520,254 +14002,6 @@ function buildCapturingReply(envelope) {
13520
14002
  };
13521
14003
  return wrapper;
13522
14004
  }
13523
- /**
13524
- * The link primitive's declaration half (D1013 rule 5): what a link field names and how a kind
13525
- * records it. Split from `instance-link.ts` so `RecordIntegrationInstances` can read the links of
13526
- * its kind without importing the builders that import it.
13527
- */
13528
- /** The body field of a link: the id of the instance it names; the target rides in the field meta. */
13529
- function linkField(target) {
13530
- return string().meta({ link: target });
13531
- }
13532
- function linkTargetOf(meta) {
13533
- if (typeof meta !== "object" || meta === null) return void 0;
13534
- const link = Reflect.get(meta, "link");
13535
- const parsed = LinkTargetSchema.safeParse(link);
13536
- return parsed.success ? parsed.data : void 0;
13537
- }
13538
- var LinkTargetSchema = object({
13539
- cap: string().min(1),
13540
- kind: string().min(1).optional()
13541
- });
13542
- /** The links a kind declares, read from the meta of its body fields. */
13543
- function linksOfKind(kind) {
13544
- const schema = kind.schema;
13545
- if (!(schema instanceof ZodObject)) return [];
13546
- const links = [];
13547
- for (const [field, fieldSchema] of Object.entries(schema.shape)) {
13548
- const to = linkTargetOf(globalRegistry.get(fieldSchema));
13549
- if (to !== void 0) links.push({
13550
- field,
13551
- to
13552
- });
13553
- }
13554
- return links;
13555
- }
13556
- /**
13557
- * `RecordIntegrationInstances` - the `integration-instances` provider over ONE
13558
- * entry kind, so an addon that holds a connection serves it in ~30 lines.
13559
- *
13560
- * Every instance is one record of the addon's own kind, keyed by the
13561
- * `integrations` registry id. The records door does the secret work: a field the
13562
- * kind marks `.meta({ secret: true })` is a keychain marker bound to the row, so
13563
- * deleting the row deletes the secret, and one row's value is never another's.
13564
- *
13565
- * Patch rules for a secret (`updateInstance`): omitted, `''`, the redaction
13566
- * token or the view the form was given KEEP the stored secret;
13567
- * `{ $secretClear: true }` clears it; any other string replaces it.
13568
- */
13569
- /** The most instances one addon lists (an integrations page, not a table). */
13570
- var INSTANCES_LIST_MAX = 1e3;
13571
- /** The keys of the kind's secret fields that sit at the top level of the body. */
13572
- function topLevelSecretKeys(paths) {
13573
- return new Set(paths.filter((p) => !p.includes(".") && !p.includes("[") && !p.includes("{")));
13574
- }
13575
- /** The keys of the kind's top-level MAPS whose values are secrets (`applianceSecrets{}`). */
13576
- function secretMapKeys(paths) {
13577
- return new Set(paths.filter((p) => p.endsWith("{}") && !p.slice(0, -2).match(/[.[{]/)).map((p) => p.slice(0, -2)));
13578
- }
13579
- /**
13580
- * A patch value for a map of secrets: an entry that is omitted, `''`, the redaction token or the
13581
- * view the form was given KEEPS its stored secret (it is left out of the merge); `{ $secretClear }`
13582
- * or `null` removes the entry; any other string replaces it. Null when nothing is left to merge.
13583
- */
13584
- function secretMapPatch(value) {
13585
- if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
13586
- const out = {};
13587
- for (const [key, entry] of Object.entries(value)) if (entry === null || isSecretClear(entry)) out[key] = null;
13588
- else if (typeof entry === "string" && entry !== "" && entry !== "__camstack_redacted__" && !isSecretFieldView(entry)) out[key] = entry;
13589
- return Object.keys(out).length > 0 ? out : null;
13590
- }
13591
- /** Does the kind's body schema carry an `enabled` field? */
13592
- function declaresEnabled(kind) {
13593
- const json = toJSONSchema(kind.schema, {
13594
- unrepresentable: "any",
13595
- io: "input"
13596
- });
13597
- const properties = Reflect.get(json, "properties");
13598
- return typeof properties === "object" && properties !== null && "enabled" in properties;
13599
- }
13600
- var RecordIntegrationInstances = class {
13601
- records;
13602
- kind;
13603
- hooks;
13604
- handle;
13605
- secretKeys;
13606
- secretMaps;
13607
- nameField;
13608
- /** The `integrations` registry owns the on/off switch (`role: devices`); the body has none. */
13609
- registryOwnsEnabled;
13610
- constructor(records, kind, hooks) {
13611
- this.records = records;
13612
- this.kind = kind;
13613
- this.hooks = hooks;
13614
- this.handle = records.kind(kind);
13615
- this.secretKeys = topLevelSecretKeys(kind.declaration.secretPaths);
13616
- this.secretMaps = secretMapKeys(kind.declaration.secretPaths);
13617
- this.nameField = kind.declaration.entry?.nameField ?? "name";
13618
- this.registryOwnsEnabled = hooks.description.role === "devices";
13619
- 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"`);
13620
- }
13621
- /**
13622
- * One instance read for the addon's own runtime; null when absent. When the keychain is
13623
- * locked the row is served WITHOUT its secrets and says so (`secrets: 'unavailable'`), so the
13624
- * caller can keep what it had instead of reconfiguring with an empty secret (D49).
13625
- */
13626
- async readResolved(id) {
13627
- try {
13628
- const record = await this.handle.getResolved(id);
13629
- return record === null ? null : {
13630
- id,
13631
- body: record.data,
13632
- enabled: record.data.enabled !== false,
13633
- secrets: "resolved"
13634
- };
13635
- } catch (err) {
13636
- if (!(err instanceof RecordSecretUnavailableError)) throw err;
13637
- const stored = await this.handle.get(id);
13638
- if (stored === null) return null;
13639
- return {
13640
- id,
13641
- body: Object.fromEntries(Object.entries(stored.data).filter(([key]) => !this.secretKeys.has(key))),
13642
- enabled: stored.data.enabled !== false,
13643
- secrets: "unavailable"
13644
- };
13645
- }
13646
- }
13647
- /** The body of {@link readResolved} alone; a locked keychain yields the row without secrets. */
13648
- async getResolved(id) {
13649
- return (await this.readResolved(id))?.body ?? null;
13650
- }
13651
- /** Every instance, secrets resolved where the keychain allows; an absent one is skipped. */
13652
- async listResolved() {
13653
- const page = await this.handle.query({ limit: INSTANCES_LIST_MAX });
13654
- const out = [];
13655
- for (const record of page.records) {
13656
- const read = await this.readResolved(record.id);
13657
- if (read !== null) out.push(read);
13658
- }
13659
- return out;
13660
- }
13661
- viewOf(record) {
13662
- const shown = secretViewsOf(this.records.owner, this.kind.name, record.id, this.kind.declaration, record.data);
13663
- const rawName = record.data[this.nameField];
13664
- const kind = this.hooks.kindOf?.(record.data);
13665
- const health = this.hooks.health?.(record.data, record.id);
13666
- return {
13667
- id: record.id,
13668
- name: typeof rawName === "string" ? rawName : record.id,
13669
- configured: this.hooks.configured(record.data),
13670
- ...this.registryOwnsEnabled ? {} : { enabled: record.data.enabled !== false },
13671
- formValues: shown,
13672
- ...kind !== void 0 ? { kind } : {},
13673
- ...health?.status !== void 0 ? { status: health.status } : {},
13674
- ...health?.lastCheckedAt !== void 0 ? { lastCheckedAt: health.lastCheckedAt } : {}
13675
- };
13676
- }
13677
- describe = async () => {
13678
- const declared = linksOfKind(this.kind);
13679
- const links = this.hooks.description.links !== void 0 || declared.length === 0 ? {} : { links: declared.map((link) => ({
13680
- kind: this.kind.name,
13681
- field: link.field,
13682
- to: link.to
13683
- })) };
13684
- return {
13685
- ...this.hooks.description,
13686
- ...links,
13687
- ...this.hooks.mintId === void 0 ? {} : { mintsId: true }
13688
- };
13689
- };
13690
- instanceFormSchema = async ({ id }) => this.hooks.formSchema(id);
13691
- listInstances = async () => {
13692
- return (await this.handle.query({ limit: INSTANCES_LIST_MAX })).records.map((record) => this.viewOf(record));
13693
- };
13694
- getInstance = async ({ id }) => {
13695
- const record = await this.handle.get(id);
13696
- return record === null ? null : this.viewOf(record);
13697
- };
13698
- /** Insert ONE row (`ifRev: 0`: an existing id is refused, never overwritten). */
13699
- createInstance = async ({ id, name, kind, values }) => {
13700
- const minted = id ?? this.hooks.mintId?.({
13701
- name,
13702
- ...kind !== void 0 ? { kind } : {}
13703
- });
13704
- if (minted === void 0) throw new Error("createInstance needs an id: this provider does not mint one");
13705
- await this.handle.put({
13706
- id: minted,
13707
- data: this.hooks.initialBody(name, kind)
13708
- }, { ifRev: 0 });
13709
- const patch = this.patchOf(values ?? {});
13710
- if (Object.keys(patch).length > 0) await this.handle.patch(minted, patch);
13711
- await this.hooks.onChanged?.(minted, "created");
13712
- return { id: minted };
13713
- };
13714
- updateInstance = async ({ id, name, values }) => {
13715
- const patch = this.patchOf(values);
13716
- if (name !== void 0) patch[this.nameField] = name;
13717
- await this.handle.patch(id, patch);
13718
- await this.hooks.onChanged?.(id, "updated");
13719
- return { ok: true };
13720
- };
13721
- /** The record patch a form `values` object means: secrets kept, cleared or replaced. */
13722
- patchOf(values) {
13723
- const patch = {};
13724
- for (const [key, value] of Object.entries(values)) {
13725
- if (value === void 0) continue;
13726
- if (this.secretMaps.has(key)) {
13727
- const entries = secretMapPatch(value);
13728
- if (entries !== null) patch[key] = entries;
13729
- } else if (!this.secretKeys.has(key)) patch[key] = value;
13730
- else if (isSecretClear(value)) patch[key] = null;
13731
- else if (typeof value === "string" && value !== "" && value !== "__camstack_redacted__" && !isSecretFieldView(value)) patch[key] = value;
13732
- }
13733
- return patch;
13734
- }
13735
- /** The switch lives in the record body; the addon is told so it applies it (D996). */
13736
- setInstanceEnabled = async ({ id, enabled }) => {
13737
- if (this.registryOwnsEnabled) throw new Error(`instance "${id}": the integrations registry owns the on/off switch of this addon; set it with integrations.update`);
13738
- await this.handle.patch(id, { enabled });
13739
- await this.hooks.onChanged?.(id, "enabled");
13740
- return { ok: true };
13741
- };
13742
- /** The row and its keychain refs go together (the records door). */
13743
- deleteInstance = async ({ id }) => {
13744
- await this.handle.delete(id);
13745
- await this.hooks.onChanged?.(id, "deleted");
13746
- return { ok: true };
13747
- };
13748
- testInstance = async (input) => {
13749
- if (this.hooks.test === void 0) return {
13750
- success: false,
13751
- status: "unsupported",
13752
- error: "This integration declares no connection test"
13753
- };
13754
- return this.hooks.test(input);
13755
- };
13756
- /** The flat provider object to hand to `registerProvider`. */
13757
- toProvider() {
13758
- return {
13759
- describe: this.describe,
13760
- instanceFormSchema: this.instanceFormSchema,
13761
- listInstances: this.listInstances,
13762
- getInstance: this.getInstance,
13763
- createInstance: this.createInstance,
13764
- updateInstance: this.updateInstance,
13765
- setInstanceEnabled: this.setInstanceEnabled,
13766
- deleteInstance: this.deleteInstance,
13767
- testInstance: this.testInstance
13768
- };
13769
- }
13770
- };
13771
14005
  /** No part holds the id a call named. */
13772
14006
  var UnknownInstanceError = class extends Error {
13773
14007
  instanceId;
@@ -13797,6 +14031,17 @@ function composeInstanceKinds(parts, base) {
13797
14031
  if (part === void 0) throw new UnknownInstanceKindError(kindId);
13798
14032
  return part;
13799
14033
  };
14034
+ /**
14035
+ * The part a DRAFT test runs on. A named kind is that kind; an unnamed one is the provider's only
14036
+ * testable kind. Several testable kinds and none named is a typed refusal that lists them, never a throw.
14037
+ */
14038
+ const draftPart = (kindId) => {
14039
+ if (kindId !== void 0) return parts.find((candidate) => candidate.kind.id === kindId) ?? { error: `Unknown instance kind '${kindId}'` };
14040
+ const testable = parts.filter((part) => part.kind.canTest !== false);
14041
+ const only = testable.length === 1 ? testable[0] : parts.length === 1 ? parts[0] : void 0;
14042
+ if (only !== void 0) return only;
14043
+ return { error: `This provider has several kinds: name one of ${(testable.length > 0 ? testable : parts).map((part) => part.kind.id).join(", ")}` };
14044
+ };
13800
14045
  const holderOf = async (id) => {
13801
14046
  for (const part of parts) if (await part.provider.getInstance({ id }) !== null) return part;
13802
14047
  throw new UnknownInstanceError(id);
@@ -13832,7 +14077,13 @@ function composeInstanceKinds(parts, base) {
13832
14077
  setInstanceEnabled: async (input) => (await holderOf(input.id)).provider.setInstanceEnabled(input),
13833
14078
  deleteInstance: async (input) => (await holderOf(input.id)).provider.deleteInstance(input),
13834
14079
  testInstance: async (input) => {
13835
- const test = (input.id === null ? byKind(input.kind) : await holderOf(input.id)).provider.testInstance;
14080
+ const resolved = input.id === null ? draftPart(input.kind) : await holderOf(input.id);
14081
+ if ("error" in resolved) return {
14082
+ success: false,
14083
+ status: "inconclusive",
14084
+ error: resolved.error
14085
+ };
14086
+ const test = resolved.provider.testInstance;
13836
14087
  if (test === void 0) return {
13837
14088
  success: false,
13838
14089
  status: "inconclusive",
@@ -13842,6 +14093,432 @@ function composeInstanceKinds(parts, base) {
13842
14093
  }
13843
14094
  };
13844
14095
  }
14096
+ /**
14097
+ * notification-output — canonical, capability-gated notification delivery.
14098
+ *
14099
+ * Apprise-derived model (see
14100
+ * `docs/superpowers/specs/2026-07-03-notification-output-notifier-matrix.md`):
14101
+ * callers emit ONE canonical `Notification`; each provider declares a
14102
+ * per-kind capability descriptor (`TargetKind`), and the pure degrade
14103
+ * engine (`@camstack/types` `prepareNotification`) transcodes / degrades the
14104
+ * message to what the kind supports — callers never special-case a service.
14105
+ *
14106
+ * DESIGN DECISIONS (locked):
14107
+ * - Target CRUD lives on THIS cap (`upsertTarget` / `deleteTarget` /
14108
+ * `setTargetEnabled`), each provider persisting via the `settings-store`
14109
+ * cap. Rationale: the admin UI needs one uniform surface across the
14110
+ * notifiers addon AND the HA addon; the addon-`globalSettingsSchema`-array
14111
+ * alternative would fork the UI per addon and cannot host the
14112
+ * discovery→adopt flow.
14113
+ * - `listTargetKinds` / `listTargets` / `discoverTargets` return arrays →
14114
+ * the generated cap-mount auto-`concatCollection`-fans them across every
14115
+ * registered provider (notifiers addon + HA addon) so one catalog is
14116
+ * routable. `send` / `testTarget` / CRUD route to ONE provider by the
14117
+ * `addonId` the generated collection router extracts from the call input.
14118
+ * - `Attachment.bytes` is `Uint8Array`. Transport-safe: superjson (the tRPC
14119
+ * transformer) + UDS MsgPack both round-trip typed arrays — already used by
14120
+ * `storage` / `storage-provider` / `recording` caps over the same path. No
14121
+ * base64 fallback needed.
14122
+ *
14123
+ * TODO (deferred, closed-set change — separate decision): add
14124
+ * `providerKind: 'notify'` so notification providers surface on the unified
14125
+ * admin "Integrations" page.
14126
+ */
14127
+ /**
14128
+ * Zentik-derived typed-media enum — the superset across every kind. Each
14129
+ * adapter picks what it supports and the degrade engine filters the rest.
14130
+ */
14131
+ var AttachmentMediaTypeSchema = _enum([
14132
+ "image",
14133
+ "video",
14134
+ "gif",
14135
+ "audio",
14136
+ "icon"
14137
+ ]);
14138
+ /**
14139
+ * A single attachment. Exactly one of `url` (remote source, most adapters
14140
+ * prefer this) or `bytes` (inline source; required for Pushover-style
14141
+ * bytes-only kinds) MUST be present — the degrade engine expresses a
14142
+ * url→bytes fetch as a `needsFetch` directive the adapter executes.
14143
+ */
14144
+ var AttachmentSchema = object({
14145
+ mediaType: AttachmentMediaTypeSchema,
14146
+ url: string().optional(),
14147
+ bytes: _instanceof(Uint8Array).optional(),
14148
+ mime: string().optional(),
14149
+ name: string().optional()
14150
+ }).refine((a) => a.url !== void 0 || a.bytes !== void 0, { message: "Attachment requires either `url` or `bytes`" });
14151
+ var NotificationFormatSchema = _enum([
14152
+ "text",
14153
+ "markdown",
14154
+ "html"
14155
+ ]);
14156
+ /**
14157
+ * The CLOSED icon vocabulary an action button may use.
14158
+ *
14159
+ * A closed set, not a free string, and that is the whole point: an arbitrary
14160
+ * icon name is one that ntfy renders, zentik silently drops, and nobody
14161
+ * notices — the same class of gap as a zone vocabulary nothing produced
14162
+ * ([D35](../../../docs/decisions/adr-0035.md)). Every adapter maps this set or
14163
+ * declares `actionIcons: false` and the degrade engine strips the field.
14164
+ *
14165
+ * Named by INTENT, never by glyph. "check" would tie the vocabulary to one
14166
+ * renderer's icon set; "acknowledge" survives an adapter that draws it
14167
+ * differently.
14168
+ *
14169
+ * ── A TOKEN IS NOT A WIRE VALUE ─────────────────────────────────────
14170
+ *
14171
+ * These names are for US. **No adapter may forward one verbatim.** Each maps
14172
+ * the whole set onto its own renderer's vocabulary through a
14173
+ * `Record<NotificationActionIcon, string>` — a Record, never a lookup with a
14174
+ * fallback, so adding a member here fails every adapter's build until someone
14175
+ * decides its glyph, which is the only place that decision can be made
14176
+ * honestly.
14177
+ *
14178
+ * This paragraph is the bug. Zentik declared `actionIcons: true` and passed
14179
+ * `disarm` straight through; iOS feeds that string to
14180
+ * `UNNotificationActionIcon(systemImageName:)`, `disarm` is not an SF Symbol,
14181
+ * and every snooze and alarm button arrived BLANK. A pass-through is not a
14182
+ * mapping, and "the field is documented" is not "the value renders".
14183
+ *
14184
+ * Adding a member is TRAIN-BOUND. The enum lives in the published
14185
+ * `@camstack/server` closure and the cap seam validates against the HUB's copy,
14186
+ * so an addon that emits a token the running hub does not know does not lose an
14187
+ * icon — its whole `send` fails Zod validation and the notification never
14188
+ * arrives. Never emit a new token from an addon before the train carrying it.
14189
+ */
14190
+ var NotificationActionIconSchema = _enum([
14191
+ "acknowledge",
14192
+ "dismiss",
14193
+ "silence",
14194
+ "snooze",
14195
+ "view",
14196
+ "play",
14197
+ "open",
14198
+ "close",
14199
+ "lock",
14200
+ "unlock",
14201
+ "arm",
14202
+ "arm-home",
14203
+ "arm-away",
14204
+ "arm-night",
14205
+ "disarm",
14206
+ "light",
14207
+ "alert",
14208
+ "camera"
14209
+ ]);
14210
+ /** A single tap-through action button. */
14211
+ var NotificationActionSchema = object({
14212
+ id: string(),
14213
+ label: string(),
14214
+ url: string().optional(),
14215
+ /** Dropped by the degrade engine for a kind with `caps.actionIcons: false`. */
14216
+ icon: NotificationActionIconSchema.optional(),
14217
+ /**
14218
+ * Renders in a warning style where the notifier supports it.
14219
+ *
14220
+ * A HINT, never a gate. The callback's authority is its token and nothing
14221
+ * else — see `notification-center/action-token.ts` for what that does and
14222
+ * does not buy.
14223
+ */
14224
+ destructive: boolean().optional(),
14225
+ /**
14226
+ * How the tap should REACH the url.
14227
+ *
14228
+ * `navigate` (absent, and every button authored before this field) opens it:
14229
+ * the phone leaves the notification and shows whatever the callback returns.
14230
+ * That is right for a button whose answer the operator wants to read.
14231
+ *
14232
+ * `background` fires it as a POST and stays put. It exists for the buttons
14233
+ * whose whole point is not to interrupt — "silence this for 30 minutes" is
14234
+ * an answer to the notification, and being thrown into a browser tab to
14235
+ * confirm it costs more attention than the notification did. A backend that
14236
+ * cannot do a background call renders it as an ordinary link (the adapters
14237
+ * fall back rather than dropping the button), so this is a preference, never
14238
+ * a requirement.
14239
+ */
14240
+ mode: _enum(["navigate", "background"]).optional()
14241
+ });
14242
+ /** A delivery parameter value: what a notifier declared it takes. */
14243
+ var DeliveryParamValueSchema = union([
14244
+ string(),
14245
+ number(),
14246
+ boolean()
14247
+ ]);
14248
+ /**
14249
+ * One extra delivery parameter a notifier KIND declares (D938). A rule that
14250
+ * addresses a target of that kind may set it; a kind that declares nothing is
14251
+ * never handed one. The admin UI derives its control from this descriptor —
14252
+ * no editor knows a service by name.
14253
+ *
14254
+ * Optional fields are `.optional()`, never `.default()` (a Zod default does not
14255
+ * run on the addon cap path).
14256
+ */
14257
+ var DeliveryParamSchema = object({
14258
+ key: string().min(1),
14259
+ label: string(),
14260
+ /** i18n key of the label, resolved by the declaring addon's namespace. */
14261
+ labelKey: string().optional(),
14262
+ type: _enum([
14263
+ "enum",
14264
+ "number",
14265
+ "boolean",
14266
+ "string"
14267
+ ]),
14268
+ /** `enum` only: the closed set of accepted values. */
14269
+ options: array(object({
14270
+ value: string(),
14271
+ label: string()
14272
+ })).optional(),
14273
+ /** `number` only. */
14274
+ min: number().optional(),
14275
+ max: number().optional(),
14276
+ /** What the notifier does when the rule sets nothing; shown as the placeholder. */
14277
+ default: DeliveryParamValueSchema.optional()
14278
+ });
14279
+ /**
14280
+ * The canonical notification. `body` is the only hard field (Apprise model).
14281
+ * `priority` is a 5-level ORDINAL (1=lowest … 3=normal(default) … 5=urgent),
14282
+ * NOT a fixed severity enum — each kind declares its own `caps.levels` and
14283
+ * the adapter maps this ordinal onto its native level. `level?` is an
14284
+ * optional kind-native level id (`emergency`, `silent`, …) that overrides
14285
+ * `priority` for that one target.
14286
+ */
14287
+ var NotificationSchema = object({
14288
+ body: string(),
14289
+ title: string().optional(),
14290
+ format: NotificationFormatSchema.default("text"),
14291
+ priority: number().int().min(1).max(5).default(3),
14292
+ level: string().optional(),
14293
+ attachments: array(AttachmentSchema).optional(),
14294
+ clickUrl: string().optional(),
14295
+ actions: array(NotificationActionSchema).optional(),
14296
+ sound: string().optional(),
14297
+ ttl: number().optional(),
14298
+ tag: string().optional(),
14299
+ deviceId: number().optional(),
14300
+ eventId: string().optional(),
14301
+ metadata: record(string(), unknown()).optional(),
14302
+ /**
14303
+ * Values for the parameters the target's kind DECLARES in
14304
+ * {@link TargetKindSchema} `deliveryParams`. Already validated against the
14305
+ * declaration by the sender; a notifier reads only the keys it declared.
14306
+ */
14307
+ delivery: record(string(), DeliveryParamValueSchema).optional()
14308
+ });
14309
+ /** One declared native severity/priority level for a kind. */
14310
+ var TargetKindLevelSchema = object({
14311
+ id: string(),
14312
+ label: string(),
14313
+ /** Which canonical priority (1..5) this level maps to. `null` = qualitative-only. */
14314
+ ordinal: number().int().min(1).max(5).nullable(),
14315
+ flags: object({
14316
+ critical: boolean().optional(),
14317
+ silent: boolean().optional(),
14318
+ noPush: boolean().optional()
14319
+ }).optional(),
14320
+ /** e.g. Pushover `emergency` requires `retry` / `expire`. */
14321
+ requires: array(string()).optional(),
14322
+ description: string().optional()
14323
+ });
14324
+ /** The full capability block consulted before dispatch. */
14325
+ var TargetKindCapsSchema = object({
14326
+ attachments: object({
14327
+ mediaTypes: array(AttachmentMediaTypeSchema),
14328
+ mode: _enum([
14329
+ "url",
14330
+ "bytes",
14331
+ "both"
14332
+ ]),
14333
+ max: number().int().nonnegative(),
14334
+ maxBytes: number().int().positive().optional()
14335
+ }),
14336
+ /** Max action buttons (0 = none). */
14337
+ actions: number().int().nonnegative(),
14338
+ /**
14339
+ * Whether this kind renders a per-action ICON.
14340
+ *
14341
+ * `.optional()`, deliberately NOT `.default(false)`: a Zod default does not
14342
+ * run on the addon cap path — three production failures in one day taught
14343
+ * this repo that once. Absent is read as false by the degrade engine, which
14344
+ * is the safe direction: an icon that is not rendered costs nothing, an icon
14345
+ * assumed and dropped costs the operator's trust in the field.
14346
+ */
14347
+ actionIcons: boolean().optional(),
14348
+ levels: array(TargetKindLevelSchema),
14349
+ format: array(NotificationFormatSchema),
14350
+ clickUrl: boolean(),
14351
+ sound: boolean(),
14352
+ ttl: boolean(),
14353
+ bodyMaxLen: number().int().positive()
14354
+ });
14355
+ /**
14356
+ * `configSchema` is a `ConfigUISchema` tree passed through to the admin
14357
+ * FormBuilder. Stored as `z.unknown()` at the cap seam (mirrors
14358
+ * `device-provider.getChildCreationSchema` `CreationSchemaOutputSchema`) —
14359
+ * the union is large and not meant for runtime validation here; the exported
14360
+ * `TargetKind` type re-tightens `configSchema` to `ConfigUISchema`.
14361
+ */
14362
+ var ConfigSchemaPassthrough$4 = unknown();
14363
+ var TargetKindSchema = object({
14364
+ kind: string(),
14365
+ label: string(),
14366
+ icon: string(),
14367
+ /** Stamped by each provider so the concat-fanned catalog stays routable. */
14368
+ addonId: string(),
14369
+ /**
14370
+ * URL of the kind's bundled BRAND icon, served by the providing addon over
14371
+ * its own `addon-routes` surface (`/addon/<addonId>/icons/<kind>`). Absent
14372
+ * when the addon bundles no icon for that kind — the client then falls back
14373
+ * to a neutral glyph rather than rendering the raw `icon` NAME as text.
14374
+ *
14375
+ * Root-relative on purpose: it resolves against whatever origin serves a web
14376
+ * client, and a native client joins it onto its own hub base.
14377
+ *
14378
+ * DECLARED here deliberately. It used to travel as an undeclared passthrough
14379
+ * field that survived only because the runtime cap-router forwards provider
14380
+ * output verbatim — so every consumer had to re-declare it by hand to stop
14381
+ * its own Zod parse from stripping it, and the whole arrangement would have
14382
+ * broken silently the moment output validation was tightened anywhere.
14383
+ */
14384
+ iconUrl: string().optional(),
14385
+ /**
14386
+ * Media type of {@link iconUrl} (`image/svg+xml`, `image/png`, …).
14387
+ *
14388
+ * The server knows this and therefore says it, because the client cannot
14389
+ * safely guess: a React-Native client renders SVG and raster through two
14390
+ * DIFFERENT components (`react-native-svg` vs `expo-image` — expo-image does
14391
+ * not decode SVG on iOS/Android), so without this it silently fell back to a
14392
+ * placeholder glyph for every vector icon while the web build looked fine.
14393
+ *
14394
+ * Absent when {@link iconUrl} is absent, or for a legacy provider that has
14395
+ * not been updated — a client that cannot determine the type should prefer
14396
+ * its raster path, which is the safe default for an unknown image.
14397
+ */
14398
+ iconMediaType: string().optional(),
14399
+ configSchema: ConfigSchemaPassthrough$4,
14400
+ /**
14401
+ * The config keys that decide WHERE this kind's secrets are sent (server,
14402
+ * base URL, instance, chat, recipient). A save that changes any of them
14403
+ * while leaving a secret redacted is refused by the provider (D634), so an
14404
+ * editor uses this to ask for the secret on exactly those edits instead of
14405
+ * on every edit.
14406
+ *
14407
+ * Optional: absent from a provider that holds no secret (the Home Assistant
14408
+ * kinds) and from a provider older than this field — an editor that finds
14409
+ * it absent must assume ANY edit may need the secret.
14410
+ */
14411
+ destinationKeys: array(string()).optional(),
14412
+ supportsDiscovery: boolean(),
14413
+ /**
14414
+ * Extra delivery parameters a rule may set for a target of this kind (D938).
14415
+ * Absent = none; the rule editor then offers nothing.
14416
+ */
14417
+ deliveryParams: array(DeliveryParamSchema).optional(),
14418
+ caps: TargetKindCapsSchema
14419
+ });
14420
+ /**
14421
+ * A persisted target. `config` holds secrets; providers REDACT secret fields
14422
+ * (return a presence marker only) when serving `listTargets` — never
14423
+ * round-trip a stored secret to the UI.
14424
+ */
14425
+ var TargetSchema = object({
14426
+ id: string(),
14427
+ name: string(),
14428
+ kind: string(),
14429
+ addonId: string(),
14430
+ enabled: boolean(),
14431
+ config: record(string(), unknown())
14432
+ });
14433
+ /** A discovery-surfaced candidate (config is partial + non-secret). */
14434
+ var DiscoveredTargetSchema = object({
14435
+ kind: string(),
14436
+ suggestedName: string(),
14437
+ config: record(string(), unknown())
14438
+ });
14439
+ /** The degrade engine's report — what was resolved / dropped / degraded. */
14440
+ var RenderedAsSchema = object({
14441
+ level: string(),
14442
+ format: NotificationFormatSchema,
14443
+ attachmentsSent: number().int().nonnegative(),
14444
+ actionsSent: number().int().nonnegative(),
14445
+ truncated: boolean(),
14446
+ dropped: array(string())
14447
+ });
14448
+ var SendResultSchema = object({
14449
+ success: boolean(),
14450
+ error: string().optional(),
14451
+ renderedAs: RenderedAsSchema.optional()
14452
+ });
14453
+ /** Same shape as SendResult — kept as a distinct name for the test panel. */
14454
+ var TestResultSchema = SendResultSchema;
14455
+ /**
14456
+ * Pre-save credential probe against a partial (unsaved) target config.
14457
+ * `resolvedUrl` never includes secrets (token stripped from path).
14458
+ */
14459
+ var ProbeTargetConfigResultSchema = object({
14460
+ ok: boolean(),
14461
+ resolvedUrl: string(),
14462
+ httpStatus: number().int().optional(),
14463
+ stateInstance: string().optional(),
14464
+ error: string().optional()
14465
+ });
14466
+ method(object({}), array(TargetKindSchema)), method(object({}), array(TargetSchema), { auth: "admin" }), method(object({ targetId: string() }), TargetSchema, { auth: "admin" }), method(object({
14467
+ kind: string(),
14468
+ config: record(string(), unknown()).optional(),
14469
+ /**
14470
+ * When editing / duplicating, the blank password field never round-trips
14471
+ * the stored token. Pass the source target id so the provider can restore
14472
+ * secrets server-side before dialling (same merge as upsert).
14473
+ */
14474
+ targetId: string().optional()
14475
+ }), array(DiscoveredTargetSchema), { auth: "admin" }), method(object({
14476
+ kind: string(),
14477
+ config: record(string(), unknown()),
14478
+ /** See `discoverTargets.targetId` — restore stored secrets for a blank password. */
14479
+ targetId: string().optional()
14480
+ }), ProbeTargetConfigResultSchema, {
14481
+ kind: "mutation",
14482
+ auth: "admin"
14483
+ }), method(object({
14484
+ targetId: string(),
14485
+ notification: NotificationSchema
14486
+ }), SendResultSchema, {
14487
+ kind: "mutation",
14488
+ auth: "admin"
14489
+ }), method(object({
14490
+ targetId: string(),
14491
+ sample: NotificationSchema.optional()
14492
+ }), TestResultSchema, {
14493
+ kind: "mutation",
14494
+ auth: "admin"
14495
+ }), method(object({
14496
+ target: TargetSchema,
14497
+ /**
14498
+ * Duplicate flow: create a NEW target id while copying secrets from an
14499
+ * existing row. The UI never holds the stored token; blank / redacted
14500
+ * password fields are restored from this source (D634 still applies if
14501
+ * destinations diverge without a re-typed secret).
14502
+ */
14503
+ cloneSecretsFrom: string().optional()
14504
+ }), TargetSchema, {
14505
+ kind: "mutation",
14506
+ auth: "admin"
14507
+ }), method(object({ targetId: string() }), _void(), {
14508
+ kind: "mutation",
14509
+ auth: "admin"
14510
+ }), method(object({
14511
+ targetId: string(),
14512
+ enabled: boolean()
14513
+ }), _void(), {
14514
+ kind: "mutation",
14515
+ auth: "admin"
14516
+ });
14517
+ looseObject({
14518
+ name: string().min(1),
14519
+ enabled: boolean().optional()
14520
+ });
14521
+ TargetSchema.omit({ id: true });
13845
14522
  var EncodeProfileSchema = object({
13846
14523
  video: object({
13847
14524
  codec: _enum([
@@ -20026,31 +20703,21 @@ var APPLIANCE_CAP_VOCABULARY = {
20026
20703
  "pet-fountain": {
20027
20704
  scope: "device",
20028
20705
  noun: t("Pet fountain", "Fontana per animali"),
20029
- actions: [
20030
- {
20031
- id: "petFountain.pumpOn",
20032
- method: "setPump",
20033
- label: t("Pump on", "Pompa accesa"),
20034
- phrase: t("Start the pump of {device}", "Avvia la pompa di {device}"),
20035
- icon: "play",
20036
- args: { on: true }
20037
- },
20038
- {
20039
- id: "petFountain.pumpOff",
20040
- method: "setPump",
20041
- label: t("Pump off", "Pompa spenta"),
20042
- phrase: t("Stop the pump of {device}", "Ferma la pompa di {device}"),
20043
- icon: "square",
20044
- args: { on: false }
20045
- },
20046
- {
20047
- id: "petFountain.resetDailyConsumption",
20048
- method: "resetDailyConsumption",
20049
- label: t("Clear daily consumption", "Azzera il consumo giornaliero"),
20050
- phrase: t("Clear the daily water consumption of {device}", "Azzera il consumo giornaliero di acqua di {device}"),
20051
- icon: "rotate-ccw"
20052
- }
20053
- ],
20706
+ actions: [{
20707
+ id: "petFountain.pumpOn",
20708
+ method: "setPump",
20709
+ label: t("Pump on", "Pompa accesa"),
20710
+ phrase: t("Start the pump of {device}", "Avvia la pompa di {device}"),
20711
+ icon: "play",
20712
+ args: { on: true }
20713
+ }, {
20714
+ id: "petFountain.pumpOff",
20715
+ method: "setPump",
20716
+ label: t("Pump off", "Pompa spenta"),
20717
+ phrase: t("Stop the pump of {device}", "Ferma la pompa di {device}"),
20718
+ icon: "square",
20719
+ args: { on: false }
20720
+ }],
20054
20721
  state: [{
20055
20722
  kind: "boolean",
20056
20723
  field: "empty",
@@ -22069,7 +22736,6 @@ var SYSTEM_CAP_VOCABULARY = {
22069
22736
  "calendar-source": system(INTERNAL),
22070
22737
  calendars: system("calendars feed schedules and conditions, not device actions"),
22071
22738
  composer: system("device composition — an authoring tool, not an action"),
22072
- "connection-test": system(INTERNAL),
22073
22739
  "core-blocks": system(INTERNAL),
22074
22740
  "custom-model-registry": system(ML),
22075
22741
  "data-store-provider": system(INTERNAL),
@@ -43795,610 +44461,196 @@ var AutomationRunTraceSchema = object({
43795
44461
  startedAt: number(),
43796
44462
  endedAt: number(),
43797
44463
  trigger: AutomationTriggerTraceSchema,
43798
- conditions: array(AutomationConditionTraceNodeSchema),
43799
- verdict: AutomationRunVerdictSchema.optional(),
43800
- steps: array(AutomationStepTraceSchema),
43801
- outcome: AutomationRunOutcomeSchema,
43802
- /** How many identical consecutive skips this trace stands for (>= 1). */
43803
- repeat: number().int().min(1),
43804
- /** When the latest of those repeats happened. */
43805
- lastAt: number(),
43806
- /**
43807
- * A scheduler point's own outcome (D983). `outcome` carries the closest
43808
- * automation outcome so a reader that does not know schedulers still reads
43809
- * the trace; this field says exactly what happened.
43810
- */
43811
- scheduler: SchedulerOutcomeSchema.optional()
43812
- });
43813
- /**
43814
- * What the hub's `runs` ledger holds for one owner (`automation:<blockId>` or
43815
- * `action:<actionId>`): the cooldown stamp and the trace ring.
43816
- */
43817
- var AutomationStateDocSchema = object({
43818
- version: literal(1),
43819
- lastRunStartedAt: number().nullable(),
43820
- traces: array(AutomationRunTraceSchema)
43821
- });
43822
- /**
43823
- * Actions — named, runnable things an operator (or an automation) can start,
43824
- * declared as LIST ENTRIES, never as devices.
43825
- *
43826
- * An entry is either **internal** (a short list of cap/wait steps kept in the
43827
- * hub's `actions` record kind) or declared by an addon through the
43828
- * `action-source` collection (a Home Assistant script, a scene …). The one
43829
- * surface the UI and automations talk to is the `actions` cap; it keeps no
43830
- * catalog of its own (D3) — every `list` asks the providers live.
43831
- *
43832
- * This file is the data half: the entry schema, the variables an entry may
43833
- * declare, and the pure resolution of the values a run was given. It holds no
43834
- * runtime.
43835
- */
43836
- /** What a variable's value is. `select` takes one of `options`. */
43837
- var ActionVariableTypeSchema = _enum([
43838
- "string",
43839
- "number",
43840
- "boolean",
43841
- "select"
43842
- ]);
43843
- var ACTION_VARIABLE_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
43844
- var ActionVariableValueSchema = union([
43845
- string(),
43846
- number(),
43847
- boolean()
43848
- ]);
43849
- /**
43850
- * One declared variable. Steps reference it as `{ $var: 'name' }` (the whole
43851
- * value) or `{{vars.name}}` (inside a string) in their args.
43852
- */
43853
- var ActionVariableSchema = object({
43854
- name: string().regex(ACTION_VARIABLE_NAME_RE),
43855
- label: string().min(1).max(120).optional(),
43856
- type: ActionVariableTypeSchema,
43857
- required: boolean().optional(),
43858
- default: ActionVariableValueSchema.optional(),
43859
- /** The allowed values of a `select`. */
43860
- options: array(string().min(1)).min(1).optional()
43861
- }).superRefine((v, ctx) => {
43862
- if (v.type === "select" && v.options === void 0) ctx.addIssue({
43863
- code: "custom",
43864
- message: "a select variable needs options",
43865
- path: ["options"]
43866
- });
43867
- if (v.default !== void 0 && variableValueError(v, v.default) !== null) ctx.addIssue({
43868
- code: "custom",
43869
- message: variableValueError(v, v.default) ?? "invalid default",
43870
- path: ["default"]
43871
- });
43872
- });
43873
- /** Why `value` is not a legal value for the variable, or null when it is. */
43874
- function variableValueError(variable, value) {
43875
- switch (variable.type) {
43876
- case "string": return typeof value === "string" ? null : `variable "${variable.name}" must be a string`;
43877
- case "number": return typeof value === "number" && Number.isFinite(value) ? null : `variable "${variable.name}" must be a number`;
43878
- case "boolean": return typeof value === "boolean" ? null : `variable "${variable.name}" must be true or false`;
43879
- case "select": return typeof value === "string" && (variable.options ?? []).includes(value) ? null : `variable "${variable.name}" must be one of ${(variable.options ?? []).join(", ")}`;
43880
- }
43881
- }
43882
- var ActionSourceKindSchema = _enum(["internal", "addon"]);
43883
- function isInternalActionId(actionId) {
43884
- return actionId.startsWith("internal:") && actionId.length > 9;
43885
- }
43886
- /** The addon behind a `<addonId>:<localId>` id, or null for anything else (internal included). */
43887
- function addonIdOfActionId(actionId) {
43888
- if (isInternalActionId(actionId)) return null;
43889
- const at = actionId.indexOf(":");
43890
- return at > 0 && at < actionId.length - 1 ? actionId.slice(0, at) : null;
43891
- }
43892
- var ActionStatusSchema = object({
43893
- isRunning: boolean(),
43894
- /** Ms epoch the latest run STARTED; null when it never ran. */
43895
- lastRunAt: number().nullable(),
43896
- /** The latest run's failure; null on success or when it never ran. */
43897
- lastError: string().nullable()
43898
- });
43899
- var ActionEntrySchema = object({
43900
- /** `internal:<uuid>` or `<addonId>:<localId>`. */
43901
- id: string().min(3),
43902
- name: string().min(1).max(120),
43903
- /** The addon that declared it; `core-blocks` for an internal one. */
43904
- addonId: string().min(1),
43905
- source: ActionSourceKindSchema,
43906
- /** An addon-declared entry is edited where it was declared. */
43907
- readOnly: boolean(),
43908
- /** Internal only: cap and wait steps. No action-in-action, so no cycles. */
43909
- steps: array(ActionStepSchema).min(1).max(50).optional(),
43910
- variables: array(ActionVariableSchema).max(20).optional(),
43911
- status: ActionStatusSchema
43912
- }).superRefine((entry, ctx) => {
43913
- if (entry.source === "internal") {
43914
- if (!isInternalActionId(entry.id)) ctx.addIssue({
43915
- code: "custom",
43916
- message: "an internal action id is internal:<uuid>",
43917
- path: ["id"]
43918
- });
43919
- return;
43920
- }
43921
- if (entry.steps !== void 0) ctx.addIssue({
43922
- code: "custom",
43923
- message: "only an internal action carries steps",
43924
- path: ["steps"]
43925
- });
43926
- if (!entry.readOnly) ctx.addIssue({
43927
- code: "custom",
43928
- message: "an addon action is read-only here",
43929
- path: ["readOnly"]
43930
- });
43931
- if (addonIdOfActionId(entry.id) === null) ctx.addIssue({
43932
- code: "custom",
43933
- message: "an addon action id is <addonId>:<localId>",
43934
- path: ["id"]
43935
- });
43936
- });
43937
- /** What an operator writes for an internal action. */
43938
- var ActionInputSchema = object({
43939
- name: string().min(1).max(120),
43940
- steps: array(ActionStepSchema).min(1).max(50),
43941
- variables: array(ActionVariableSchema).max(20).optional()
43942
- });
43943
- /** Who started a run. Absent = the operator pressed it. */
43944
- var ActionRunOriginSchema = object({
43945
- /** The automation block whose step started it. */
43946
- blockId: string().min(1).optional() });
43947
- /** `started` = the caller did not ask to wait. */
43948
- var ActionRunOutcomeSchema = union([AutomationRunOutcomeSchema, literal("started")]);
43949
- var ActionRunResultSchema = object({
43950
- runId: string().min(1),
43951
- outcome: ActionRunOutcomeSchema,
43952
- /** Why it did not run, or what failed. */
43953
- message: string().optional()
43954
- });
43955
- _enum([
43956
- "not-found",
43957
- "read-only",
43958
- "invalid-variables",
43959
- "invalid-steps",
43960
- "not-linked",
43961
- "busy"
43962
- ]);
43963
- object({
43964
- actionId: string(),
43965
- runId: string(),
43966
- isRunning: boolean(),
43967
- /** Set when the run ended. */
43968
- outcome: AutomationRunOutcomeSchema.optional(),
43969
- lastRunAt: number().nullable(),
43970
- lastError: string().nullable()
43971
- });
43972
- /** A bare number accepted as a base unit — the save succeeded, say so. */
43973
- var UnitWarningSchema = object({
43974
- /** Where in the saved record, e.g. `conditions.children.0` or `steps.2.args.grams`. */
43975
- path: string(),
43976
- deviceId: number().int().optional(),
43977
- field: string(),
43978
- value: number(),
43979
- assumedUnit: string(),
43980
- message: string()
43981
- });
43982
- /**
43983
- * notification-output — canonical, capability-gated notification delivery.
43984
- *
43985
- * Apprise-derived model (see
43986
- * `docs/superpowers/specs/2026-07-03-notification-output-notifier-matrix.md`):
43987
- * callers emit ONE canonical `Notification`; each provider declares a
43988
- * per-kind capability descriptor (`TargetKind`), and the pure degrade
43989
- * engine (`@camstack/types` `prepareNotification`) transcodes / degrades the
43990
- * message to what the kind supports — callers never special-case a service.
43991
- *
43992
- * DESIGN DECISIONS (locked):
43993
- * - Target CRUD lives on THIS cap (`upsertTarget` / `deleteTarget` /
43994
- * `setTargetEnabled`), each provider persisting via the `settings-store`
43995
- * cap. Rationale: the admin UI needs one uniform surface across the
43996
- * notifiers addon AND the HA addon; the addon-`globalSettingsSchema`-array
43997
- * alternative would fork the UI per addon and cannot host the
43998
- * discovery→adopt flow.
43999
- * - `listTargetKinds` / `listTargets` / `discoverTargets` return arrays →
44000
- * the generated cap-mount auto-`concatCollection`-fans them across every
44001
- * registered provider (notifiers addon + HA addon) so one catalog is
44002
- * routable. `send` / `testTarget` / CRUD route to ONE provider by the
44003
- * `addonId` the generated collection router extracts from the call input.
44004
- * - `Attachment.bytes` is `Uint8Array`. Transport-safe: superjson (the tRPC
44005
- * transformer) + UDS MsgPack both round-trip typed arrays — already used by
44006
- * `storage` / `storage-provider` / `recording` caps over the same path. No
44007
- * base64 fallback needed.
44008
- *
44009
- * TODO (deferred, closed-set change — separate decision): add
44010
- * `providerKind: 'notify'` so notification providers surface on the unified
44011
- * admin "Integrations" page.
44012
- */
44013
- /**
44014
- * Zentik-derived typed-media enum — the superset across every kind. Each
44015
- * adapter picks what it supports and the degrade engine filters the rest.
44016
- */
44017
- var AttachmentMediaTypeSchema = _enum([
44018
- "image",
44019
- "video",
44020
- "gif",
44021
- "audio",
44022
- "icon"
44023
- ]);
44024
- /**
44025
- * A single attachment. Exactly one of `url` (remote source, most adapters
44026
- * prefer this) or `bytes` (inline source; required for Pushover-style
44027
- * bytes-only kinds) MUST be present — the degrade engine expresses a
44028
- * url→bytes fetch as a `needsFetch` directive the adapter executes.
44029
- */
44030
- var AttachmentSchema = object({
44031
- mediaType: AttachmentMediaTypeSchema,
44032
- url: string().optional(),
44033
- bytes: _instanceof(Uint8Array).optional(),
44034
- mime: string().optional(),
44035
- name: string().optional()
44036
- }).refine((a) => a.url !== void 0 || a.bytes !== void 0, { message: "Attachment requires either `url` or `bytes`" });
44037
- var NotificationFormatSchema = _enum([
44038
- "text",
44039
- "markdown",
44040
- "html"
44041
- ]);
44042
- /**
44043
- * The CLOSED icon vocabulary an action button may use.
44044
- *
44045
- * A closed set, not a free string, and that is the whole point: an arbitrary
44046
- * icon name is one that ntfy renders, zentik silently drops, and nobody
44047
- * notices — the same class of gap as a zone vocabulary nothing produced
44048
- * ([D35](../../../docs/decisions/adr-0035.md)). Every adapter maps this set or
44049
- * declares `actionIcons: false` and the degrade engine strips the field.
44050
- *
44051
- * Named by INTENT, never by glyph. "check" would tie the vocabulary to one
44052
- * renderer's icon set; "acknowledge" survives an adapter that draws it
44053
- * differently.
44054
- *
44055
- * ── A TOKEN IS NOT A WIRE VALUE ─────────────────────────────────────
44056
- *
44057
- * These names are for US. **No adapter may forward one verbatim.** Each maps
44058
- * the whole set onto its own renderer's vocabulary through a
44059
- * `Record<NotificationActionIcon, string>` — a Record, never a lookup with a
44060
- * fallback, so adding a member here fails every adapter's build until someone
44061
- * decides its glyph, which is the only place that decision can be made
44062
- * honestly.
44063
- *
44064
- * This paragraph is the bug. Zentik declared `actionIcons: true` and passed
44065
- * `disarm` straight through; iOS feeds that string to
44066
- * `UNNotificationActionIcon(systemImageName:)`, `disarm` is not an SF Symbol,
44067
- * and every snooze and alarm button arrived BLANK. A pass-through is not a
44068
- * mapping, and "the field is documented" is not "the value renders".
44069
- *
44070
- * Adding a member is TRAIN-BOUND. The enum lives in the published
44071
- * `@camstack/server` closure and the cap seam validates against the HUB's copy,
44072
- * so an addon that emits a token the running hub does not know does not lose an
44073
- * icon — its whole `send` fails Zod validation and the notification never
44074
- * arrives. Never emit a new token from an addon before the train carrying it.
44075
- */
44076
- var NotificationActionIconSchema = _enum([
44077
- "acknowledge",
44078
- "dismiss",
44079
- "silence",
44080
- "snooze",
44081
- "view",
44082
- "play",
44083
- "open",
44084
- "close",
44085
- "lock",
44086
- "unlock",
44087
- "arm",
44088
- "arm-home",
44089
- "arm-away",
44090
- "arm-night",
44091
- "disarm",
44092
- "light",
44093
- "alert",
44094
- "camera"
44095
- ]);
44096
- /** A single tap-through action button. */
44097
- var NotificationActionSchema = object({
44098
- id: string(),
44099
- label: string(),
44100
- url: string().optional(),
44101
- /** Dropped by the degrade engine for a kind with `caps.actionIcons: false`. */
44102
- icon: NotificationActionIconSchema.optional(),
44103
- /**
44104
- * Renders in a warning style where the notifier supports it.
44105
- *
44106
- * A HINT, never a gate. The callback's authority is its token and nothing
44107
- * else — see `notification-center/action-token.ts` for what that does and
44108
- * does not buy.
44109
- */
44110
- destructive: boolean().optional(),
44111
- /**
44112
- * How the tap should REACH the url.
44113
- *
44114
- * `navigate` (absent, and every button authored before this field) opens it:
44115
- * the phone leaves the notification and shows whatever the callback returns.
44116
- * That is right for a button whose answer the operator wants to read.
44117
- *
44118
- * `background` fires it as a POST and stays put. It exists for the buttons
44119
- * whose whole point is not to interrupt — "silence this for 30 minutes" is
44120
- * an answer to the notification, and being thrown into a browser tab to
44121
- * confirm it costs more attention than the notification did. A backend that
44122
- * cannot do a background call renders it as an ordinary link (the adapters
44123
- * fall back rather than dropping the button), so this is a preference, never
44124
- * a requirement.
44125
- */
44126
- mode: _enum(["navigate", "background"]).optional()
44127
- });
44128
- /** A delivery parameter value: what a notifier declared it takes. */
44129
- var DeliveryParamValueSchema = union([
44130
- string(),
44131
- number(),
44132
- boolean()
44133
- ]);
44134
- /**
44135
- * One extra delivery parameter a notifier KIND declares (D938). A rule that
44136
- * addresses a target of that kind may set it; a kind that declares nothing is
44137
- * never handed one. The admin UI derives its control from this descriptor —
44138
- * no editor knows a service by name.
44139
- *
44140
- * Optional fields are `.optional()`, never `.default()` (a Zod default does not
44141
- * run on the addon cap path).
44142
- */
44143
- var DeliveryParamSchema = object({
44144
- key: string().min(1),
44145
- label: string(),
44146
- /** i18n key of the label, resolved by the declaring addon's namespace. */
44147
- labelKey: string().optional(),
44148
- type: _enum([
44149
- "enum",
44150
- "number",
44151
- "boolean",
44152
- "string"
44153
- ]),
44154
- /** `enum` only: the closed set of accepted values. */
44155
- options: array(object({
44156
- value: string(),
44157
- label: string()
44158
- })).optional(),
44159
- /** `number` only. */
44160
- min: number().optional(),
44161
- max: number().optional(),
44162
- /** What the notifier does when the rule sets nothing; shown as the placeholder. */
44163
- default: DeliveryParamValueSchema.optional()
44164
- });
44165
- /**
44166
- * The canonical notification. `body` is the only hard field (Apprise model).
44167
- * `priority` is a 5-level ORDINAL (1=lowest … 3=normal(default) … 5=urgent),
44168
- * NOT a fixed severity enum — each kind declares its own `caps.levels` and
44169
- * the adapter maps this ordinal onto its native level. `level?` is an
44170
- * optional kind-native level id (`emergency`, `silent`, …) that overrides
44171
- * `priority` for that one target.
44172
- */
44173
- var NotificationSchema = object({
44174
- body: string(),
44175
- title: string().optional(),
44176
- format: NotificationFormatSchema.default("text"),
44177
- priority: number().int().min(1).max(5).default(3),
44178
- level: string().optional(),
44179
- attachments: array(AttachmentSchema).optional(),
44180
- clickUrl: string().optional(),
44181
- actions: array(NotificationActionSchema).optional(),
44182
- sound: string().optional(),
44183
- ttl: number().optional(),
44184
- tag: string().optional(),
44185
- deviceId: number().optional(),
44186
- eventId: string().optional(),
44187
- metadata: record(string(), unknown()).optional(),
44188
- /**
44189
- * Values for the parameters the target's kind DECLARES in
44190
- * {@link TargetKindSchema} `deliveryParams`. Already validated against the
44191
- * declaration by the sender; a notifier reads only the keys it declared.
44192
- */
44193
- delivery: record(string(), DeliveryParamValueSchema).optional()
44194
- });
44195
- /** One declared native severity/priority level for a kind. */
44196
- var TargetKindLevelSchema = object({
44197
- id: string(),
44198
- label: string(),
44199
- /** Which canonical priority (1..5) this level maps to. `null` = qualitative-only. */
44200
- ordinal: number().int().min(1).max(5).nullable(),
44201
- flags: object({
44202
- critical: boolean().optional(),
44203
- silent: boolean().optional(),
44204
- noPush: boolean().optional()
44205
- }).optional(),
44206
- /** e.g. Pushover `emergency` requires `retry` / `expire`. */
44207
- requires: array(string()).optional(),
44208
- description: string().optional()
44209
- });
44210
- /** The full capability block consulted before dispatch. */
44211
- var TargetKindCapsSchema = object({
44212
- attachments: object({
44213
- mediaTypes: array(AttachmentMediaTypeSchema),
44214
- mode: _enum([
44215
- "url",
44216
- "bytes",
44217
- "both"
44218
- ]),
44219
- max: number().int().nonnegative(),
44220
- maxBytes: number().int().positive().optional()
44221
- }),
44222
- /** Max action buttons (0 = none). */
44223
- actions: number().int().nonnegative(),
44224
- /**
44225
- * Whether this kind renders a per-action ICON.
44226
- *
44227
- * `.optional()`, deliberately NOT `.default(false)`: a Zod default does not
44228
- * run on the addon cap path — three production failures in one day taught
44229
- * this repo that once. Absent is read as false by the degrade engine, which
44230
- * is the safe direction: an icon that is not rendered costs nothing, an icon
44231
- * assumed and dropped costs the operator's trust in the field.
44232
- */
44233
- actionIcons: boolean().optional(),
44234
- levels: array(TargetKindLevelSchema),
44235
- format: array(NotificationFormatSchema),
44236
- clickUrl: boolean(),
44237
- sound: boolean(),
44238
- ttl: boolean(),
44239
- bodyMaxLen: number().int().positive()
44240
- });
44241
- /**
44242
- * `configSchema` is a `ConfigUISchema` tree passed through to the admin
44243
- * FormBuilder. Stored as `z.unknown()` at the cap seam (mirrors
44244
- * `device-provider.getChildCreationSchema` `CreationSchemaOutputSchema`) —
44245
- * the union is large and not meant for runtime validation here; the exported
44246
- * `TargetKind` type re-tightens `configSchema` to `ConfigUISchema`.
44247
- */
44248
- var ConfigSchemaPassthrough$4 = unknown();
44249
- var TargetKindSchema = object({
44250
- kind: string(),
44251
- label: string(),
44252
- icon: string(),
44253
- /** Stamped by each provider so the concat-fanned catalog stays routable. */
44254
- addonId: string(),
44255
- /**
44256
- * URL of the kind's bundled BRAND icon, served by the providing addon over
44257
- * its own `addon-routes` surface (`/addon/<addonId>/icons/<kind>`). Absent
44258
- * when the addon bundles no icon for that kind — the client then falls back
44259
- * to a neutral glyph rather than rendering the raw `icon` NAME as text.
44260
- *
44261
- * Root-relative on purpose: it resolves against whatever origin serves a web
44262
- * client, and a native client joins it onto its own hub base.
44263
- *
44264
- * DECLARED here deliberately. It used to travel as an undeclared passthrough
44265
- * field that survived only because the runtime cap-router forwards provider
44266
- * output verbatim — so every consumer had to re-declare it by hand to stop
44267
- * its own Zod parse from stripping it, and the whole arrangement would have
44268
- * broken silently the moment output validation was tightened anywhere.
44269
- */
44270
- iconUrl: string().optional(),
44271
- /**
44272
- * Media type of {@link iconUrl} (`image/svg+xml`, `image/png`, …).
44273
- *
44274
- * The server knows this and therefore says it, because the client cannot
44275
- * safely guess: a React-Native client renders SVG and raster through two
44276
- * DIFFERENT components (`react-native-svg` vs `expo-image` — expo-image does
44277
- * not decode SVG on iOS/Android), so without this it silently fell back to a
44278
- * placeholder glyph for every vector icon while the web build looked fine.
44279
- *
44280
- * Absent when {@link iconUrl} is absent, or for a legacy provider that has
44281
- * not been updated — a client that cannot determine the type should prefer
44282
- * its raster path, which is the safe default for an unknown image.
44283
- */
44284
- iconMediaType: string().optional(),
44285
- configSchema: ConfigSchemaPassthrough$4,
44286
- /**
44287
- * The config keys that decide WHERE this kind's secrets are sent (server,
44288
- * base URL, instance, chat, recipient). A save that changes any of them
44289
- * while leaving a secret redacted is refused by the provider (D634), so an
44290
- * editor uses this to ask for the secret on exactly those edits instead of
44291
- * on every edit.
44292
- *
44293
- * Optional: absent from a provider that holds no secret (the Home Assistant
44294
- * kinds) and from a provider older than this field — an editor that finds
44295
- * it absent must assume ANY edit may need the secret.
44296
- */
44297
- destinationKeys: array(string()).optional(),
44298
- supportsDiscovery: boolean(),
44464
+ conditions: array(AutomationConditionTraceNodeSchema),
44465
+ verdict: AutomationRunVerdictSchema.optional(),
44466
+ steps: array(AutomationStepTraceSchema),
44467
+ outcome: AutomationRunOutcomeSchema,
44468
+ /** How many identical consecutive skips this trace stands for (>= 1). */
44469
+ repeat: number().int().min(1),
44470
+ /** When the latest of those repeats happened. */
44471
+ lastAt: number(),
44299
44472
  /**
44300
- * Extra delivery parameters a rule may set for a target of this kind (D938).
44301
- * Absent = none; the rule editor then offers nothing.
44473
+ * A scheduler point's own outcome (D983). `outcome` carries the closest
44474
+ * automation outcome so a reader that does not know schedulers still reads
44475
+ * the trace; this field says exactly what happened.
44302
44476
  */
44303
- deliveryParams: array(DeliveryParamSchema).optional(),
44304
- caps: TargetKindCapsSchema
44477
+ scheduler: SchedulerOutcomeSchema.optional()
44305
44478
  });
44306
44479
  /**
44307
- * A persisted target. `config` holds secrets; providers REDACT secret fields
44308
- * (return a presence marker only) when serving `listTargets` — never
44309
- * round-trip a stored secret to the UI.
44480
+ * What the hub's `runs` ledger holds for one owner (`automation:<blockId>` or
44481
+ * `action:<actionId>`): the cooldown stamp and the trace ring.
44310
44482
  */
44311
- var TargetSchema = object({
44312
- id: string(),
44313
- name: string(),
44314
- kind: string(),
44315
- addonId: string(),
44316
- enabled: boolean(),
44317
- config: record(string(), unknown())
44483
+ var AutomationStateDocSchema = object({
44484
+ version: literal(1),
44485
+ lastRunStartedAt: number().nullable(),
44486
+ traces: array(AutomationRunTraceSchema)
44318
44487
  });
44319
- /** A discovery-surfaced candidate (config is partial + non-secret). */
44320
- var DiscoveredTargetSchema = object({
44321
- kind: string(),
44322
- suggestedName: string(),
44323
- config: record(string(), unknown())
44488
+ /**
44489
+ * Actions — named, runnable things an operator (or an automation) can start,
44490
+ * declared as LIST ENTRIES, never as devices.
44491
+ *
44492
+ * An entry is either **internal** (a short list of cap/wait steps kept in the
44493
+ * hub's `actions` record kind) or declared by an addon through the
44494
+ * `action-source` collection (a Home Assistant script, a scene …). The one
44495
+ * surface the UI and automations talk to is the `actions` cap; it keeps no
44496
+ * catalog of its own (D3) — every `list` asks the providers live.
44497
+ *
44498
+ * This file is the data half: the entry schema, the variables an entry may
44499
+ * declare, and the pure resolution of the values a run was given. It holds no
44500
+ * runtime.
44501
+ */
44502
+ /** What a variable's value is. `select` takes one of `options`. */
44503
+ var ActionVariableTypeSchema = _enum([
44504
+ "string",
44505
+ "number",
44506
+ "boolean",
44507
+ "select"
44508
+ ]);
44509
+ var ACTION_VARIABLE_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
44510
+ var ActionVariableValueSchema = union([
44511
+ string(),
44512
+ number(),
44513
+ boolean()
44514
+ ]);
44515
+ /**
44516
+ * One declared variable. Steps reference it as `{ $var: 'name' }` (the whole
44517
+ * value) or `{{vars.name}}` (inside a string) in their args.
44518
+ */
44519
+ var ActionVariableSchema = object({
44520
+ name: string().regex(ACTION_VARIABLE_NAME_RE),
44521
+ label: string().min(1).max(120).optional(),
44522
+ type: ActionVariableTypeSchema,
44523
+ required: boolean().optional(),
44524
+ default: ActionVariableValueSchema.optional(),
44525
+ /** The allowed values of a `select`. */
44526
+ options: array(string().min(1)).min(1).optional()
44527
+ }).superRefine((v, ctx) => {
44528
+ if (v.type === "select" && v.options === void 0) ctx.addIssue({
44529
+ code: "custom",
44530
+ message: "a select variable needs options",
44531
+ path: ["options"]
44532
+ });
44533
+ if (v.default !== void 0 && variableValueError(v, v.default) !== null) ctx.addIssue({
44534
+ code: "custom",
44535
+ message: variableValueError(v, v.default) ?? "invalid default",
44536
+ path: ["default"]
44537
+ });
44324
44538
  });
44325
- /** The degrade engine's report — what was resolved / dropped / degraded. */
44326
- var RenderedAsSchema = object({
44327
- level: string(),
44328
- format: NotificationFormatSchema,
44329
- attachmentsSent: number().int().nonnegative(),
44330
- actionsSent: number().int().nonnegative(),
44331
- truncated: boolean(),
44332
- dropped: array(string())
44539
+ /** Why `value` is not a legal value for the variable, or null when it is. */
44540
+ function variableValueError(variable, value) {
44541
+ switch (variable.type) {
44542
+ case "string": return typeof value === "string" ? null : `variable "${variable.name}" must be a string`;
44543
+ case "number": return typeof value === "number" && Number.isFinite(value) ? null : `variable "${variable.name}" must be a number`;
44544
+ case "boolean": return typeof value === "boolean" ? null : `variable "${variable.name}" must be true or false`;
44545
+ case "select": return typeof value === "string" && (variable.options ?? []).includes(value) ? null : `variable "${variable.name}" must be one of ${(variable.options ?? []).join(", ")}`;
44546
+ }
44547
+ }
44548
+ var ActionSourceKindSchema = _enum(["internal", "addon"]);
44549
+ function isInternalActionId(actionId) {
44550
+ return actionId.startsWith("internal:") && actionId.length > 9;
44551
+ }
44552
+ /** The addon behind a `<addonId>:<localId>` id, or null for anything else (internal included). */
44553
+ function addonIdOfActionId(actionId) {
44554
+ if (isInternalActionId(actionId)) return null;
44555
+ const at = actionId.indexOf(":");
44556
+ return at > 0 && at < actionId.length - 1 ? actionId.slice(0, at) : null;
44557
+ }
44558
+ var ActionStatusSchema = object({
44559
+ isRunning: boolean(),
44560
+ /** Ms epoch the latest run STARTED; null when it never ran. */
44561
+ lastRunAt: number().nullable(),
44562
+ /** The latest run's failure; null on success or when it never ran. */
44563
+ lastError: string().nullable()
44333
44564
  });
44334
- var SendResultSchema = object({
44335
- success: boolean(),
44336
- error: string().optional(),
44337
- renderedAs: RenderedAsSchema.optional()
44565
+ var ActionEntrySchema = object({
44566
+ /** `internal:<uuid>` or `<addonId>:<localId>`. */
44567
+ id: string().min(3),
44568
+ name: string().min(1).max(120),
44569
+ /** The addon that declared it; `core-blocks` for an internal one. */
44570
+ addonId: string().min(1),
44571
+ source: ActionSourceKindSchema,
44572
+ /** An addon-declared entry is edited where it was declared. */
44573
+ readOnly: boolean(),
44574
+ /** Internal only: cap and wait steps. No action-in-action, so no cycles. */
44575
+ steps: array(ActionStepSchema).min(1).max(50).optional(),
44576
+ variables: array(ActionVariableSchema).max(20).optional(),
44577
+ status: ActionStatusSchema
44578
+ }).superRefine((entry, ctx) => {
44579
+ if (entry.source === "internal") {
44580
+ if (!isInternalActionId(entry.id)) ctx.addIssue({
44581
+ code: "custom",
44582
+ message: "an internal action id is internal:<uuid>",
44583
+ path: ["id"]
44584
+ });
44585
+ return;
44586
+ }
44587
+ if (entry.steps !== void 0) ctx.addIssue({
44588
+ code: "custom",
44589
+ message: "only an internal action carries steps",
44590
+ path: ["steps"]
44591
+ });
44592
+ if (!entry.readOnly) ctx.addIssue({
44593
+ code: "custom",
44594
+ message: "an addon action is read-only here",
44595
+ path: ["readOnly"]
44596
+ });
44597
+ if (addonIdOfActionId(entry.id) === null) ctx.addIssue({
44598
+ code: "custom",
44599
+ message: "an addon action id is <addonId>:<localId>",
44600
+ path: ["id"]
44601
+ });
44338
44602
  });
44339
- /** Same shape as SendResult — kept as a distinct name for the test panel. */
44340
- var TestResultSchema = SendResultSchema;
44603
+ /** What an operator writes for an internal action. */
44604
+ var ActionInputSchema = object({
44605
+ name: string().min(1).max(120),
44606
+ steps: array(ActionStepSchema).min(1).max(50),
44607
+ variables: array(ActionVariableSchema).max(20).optional()
44608
+ });
44609
+ /** Who started a run. Absent = the operator pressed it. */
44610
+ var ActionRunOriginSchema = object({
44611
+ /** The automation block whose step started it. */
44612
+ blockId: string().min(1).optional() });
44341
44613
  /**
44342
- * Pre-save credential probe against a partial (unsaved) target config.
44343
- * `resolvedUrl` never includes secrets (token stripped from path).
44614
+ * `started` = the caller did not ask to wait. `timed-out` = the run reached the
44615
+ * ceiling (`ACTION_RUN_MAX_MS`) and was stopped; it is never a `ran`.
44344
44616
  */
44345
- var ProbeTargetConfigResultSchema = object({
44346
- ok: boolean(),
44347
- resolvedUrl: string(),
44348
- httpStatus: number().int().optional(),
44349
- stateInstance: string().optional(),
44350
- error: string().optional()
44617
+ var ActionRunOutcomeSchema = union([
44618
+ AutomationRunOutcomeSchema,
44619
+ literal("started"),
44620
+ literal("timed-out")
44621
+ ]);
44622
+ var ActionRunResultSchema = object({
44623
+ runId: string().min(1),
44624
+ outcome: ActionRunOutcomeSchema,
44625
+ /** Why it did not run, or what failed. */
44626
+ message: string().optional()
44351
44627
  });
44352
- method(object({}), array(TargetKindSchema)), method(object({}), array(TargetSchema), { auth: "admin" }), method(object({ targetId: string() }), TargetSchema, { auth: "admin" }), method(object({
44353
- kind: string(),
44354
- config: record(string(), unknown()).optional(),
44355
- /**
44356
- * When editing / duplicating, the blank password field never round-trips
44357
- * the stored token. Pass the source target id so the provider can restore
44358
- * secrets server-side before dialling (same merge as upsert).
44359
- */
44360
- targetId: string().optional()
44361
- }), array(DiscoveredTargetSchema), { auth: "admin" }), method(object({
44362
- kind: string(),
44363
- config: record(string(), unknown()),
44364
- /** See `discoverTargets.targetId` — restore stored secrets for a blank password. */
44365
- targetId: string().optional()
44366
- }), ProbeTargetConfigResultSchema, {
44367
- kind: "mutation",
44368
- auth: "admin"
44369
- }), method(object({
44370
- targetId: string(),
44371
- notification: NotificationSchema
44372
- }), SendResultSchema, {
44373
- kind: "mutation",
44374
- auth: "admin"
44375
- }), method(object({
44376
- targetId: string(),
44377
- sample: NotificationSchema.optional()
44378
- }), TestResultSchema, {
44379
- kind: "mutation",
44380
- auth: "admin"
44381
- }), method(object({
44382
- target: TargetSchema,
44383
- /**
44384
- * Duplicate flow: create a NEW target id while copying secrets from an
44385
- * existing row. The UI never holds the stored token; blank / redacted
44386
- * password fields are restored from this source (D634 still applies if
44387
- * destinations diverge without a re-typed secret).
44388
- */
44389
- cloneSecretsFrom: string().optional()
44390
- }), TargetSchema, {
44391
- kind: "mutation",
44392
- auth: "admin"
44393
- }), method(object({ targetId: string() }), _void(), {
44394
- kind: "mutation",
44395
- auth: "admin"
44396
- }), method(object({
44397
- targetId: string(),
44398
- enabled: boolean()
44399
- }), _void(), {
44400
- kind: "mutation",
44401
- auth: "admin"
44628
+ _enum([
44629
+ "not-found",
44630
+ "read-only",
44631
+ "invalid-variables",
44632
+ "invalid-steps",
44633
+ "not-linked",
44634
+ "busy"
44635
+ ]);
44636
+ object({
44637
+ actionId: string(),
44638
+ runId: string(),
44639
+ isRunning: boolean(),
44640
+ /** Set when the run ended. */
44641
+ outcome: AutomationRunOutcomeSchema.optional(),
44642
+ lastRunAt: number().nullable(),
44643
+ lastError: string().nullable()
44644
+ });
44645
+ /** A bare number accepted as a base unit — the save succeeded, say so. */
44646
+ var UnitWarningSchema = object({
44647
+ /** Where in the saved record, e.g. `conditions.children.0` or `steps.2.args.grams`. */
44648
+ path: string(),
44649
+ deviceId: number().int().optional(),
44650
+ field: string(),
44651
+ value: number(),
44652
+ assumedUnit: string(),
44653
+ message: string()
44402
44654
  });
44403
44655
  _enum([
44404
44656
  "automation",
@@ -44467,6 +44719,8 @@ method(object({}), array(ActionEntrySchema), { auth: "admin" }), method(object({
44467
44719
  kind: "mutation",
44468
44720
  auth: "admin"
44469
44721
  });
44722
+ /** `timeoutMs` of `actions.run`: a waited call outlives any legal run. */
44723
+ var ACTION_RUN_TIMEOUT_MS = 363e4;
44470
44724
  /**
44471
44725
  * actions — the ONE surface for runnable actions, for the UI and for
44472
44726
  * automations. Provided by the core-blocks builtin on the hub.
@@ -44485,6 +44739,12 @@ method(object({}), array(ActionEntrySchema), { auth: "admin" }), method(object({
44485
44739
  * An admin, and an in-process caller (an automation block), may run any action.
44486
44740
  * Every refusal is typed (`[not-linked] …`) and logged.
44487
44741
  *
44742
+ * **A run lasts at most `ACTION_RUN_MAX_MS` (60 min).** The provider stops a
44743
+ * run that reaches it and answers `timed-out` (never `ran`); an action whose
44744
+ * `wait` steps alone add up to more is refused at create/update
44745
+ * (`[invalid-steps]`). `run` declares a `timeoutMs` above that ceiling, so a
44746
+ * waited call (an automation step) is never cut by the 60 s transport default.
44747
+ *
44488
44748
  * A second `run` of an action that is already running is REFUSED — traced and
44489
44749
  * logged — never queued.
44490
44750
  */
@@ -44511,7 +44771,8 @@ method(object({}), array(ActionEntrySchema), { auth: "admin" }), method(object({
44511
44771
  role: "viewer",
44512
44772
  auth: "protected",
44513
44773
  kind: "mutation",
44514
- caller: "required"
44774
+ caller: "required",
44775
+ timeoutMs: ACTION_RUN_TIMEOUT_MS
44515
44776
  }), method(ActionIdInput, _void(), {
44516
44777
  kind: "mutation",
44517
44778
  auth: "admin"
@@ -48297,37 +48558,6 @@ method(object({
48297
48558
  kind: "mutation",
48298
48559
  auth: "admin"
48299
48560
  }), method(object({ blockIds: array(string()) }), object({ states: array(CompositionBlockStateSchema) }), { auth: "admin" });
48300
- var ConnectionTestOutcomeSchema = discriminatedUnion("outcome", [
48301
- object({
48302
- outcome: literal("validated"),
48303
- /** Round-trip of the sign-in, when the provider measured it. */
48304
- latencyMs: number().nonnegative().optional(),
48305
- /** Optional human detail worth showing next to the tick
48306
- * ("3 devices visible on this account"). */
48307
- detail: string().optional()
48308
- }).strict(),
48309
- object({
48310
- outcome: literal("rejected"),
48311
- error: string()
48312
- }).strict(),
48313
- object({
48314
- outcome: literal("inconclusive"),
48315
- error: string()
48316
- }).strict()
48317
- ]);
48318
- var ConnectionTestInputSchema = object({
48319
- /** Candidate integration settings, exactly as the create form collected them. */
48320
- settings: record(string(), unknown()) });
48321
- /**
48322
- * What the provider's test actually DOES, so the UI can say it in words before
48323
- * the operator presses the button ("Signs in to the Dreo cloud"). Purely
48324
- * descriptive — it never changes routing.
48325
- */
48326
- var ConnectionTestDescriptorSchema = object({ label: string() });
48327
- method(ConnectionTestInputSchema, ConnectionTestOutcomeSchema, {
48328
- kind: "mutation",
48329
- auth: "admin"
48330
- }), method(_void(), ConnectionTestDescriptorSchema, { auth: "admin" });
48331
48561
  object({
48332
48562
  /** True when the upstream system considers the entity connected. */
48333
48563
  connected: boolean(),
@@ -48585,6 +48815,9 @@ var MediaPlayerStatusSchema = object({
48585
48815
  /** Repeat mode. Null when no repeat surface.
48586
48816
  * Pair with `DeviceFeature.MediaPlayerRepeat`. */
48587
48817
  repeat: MediaPlayerRepeatSchema.nullable(),
48818
+ /** Ms epoch when `position` was read from the device. Null when the driver
48819
+ * does not say; a UI that advances the position while playing counts from it. */
48820
+ positionUpdatedAt: number().nullable().default(null),
48588
48821
  /** Ms epoch when the slice was last updated. */
48589
48822
  lastChangedAt: number()
48590
48823
  });
@@ -49164,7 +49397,9 @@ var ThresholdTransformDraftSchema = object({
49164
49397
  comparison: _enum(["gte", "lte"]),
49165
49398
  threshold: number(),
49166
49399
  startDwellMs: number().nonnegative(),
49167
- stopDwellMs: number().nonnegative()
49400
+ stopDwellMs: number().nonnegative(),
49401
+ /** Samples a start needs; absent = the compiler's default for the source (2 for running power, else 1). */
49402
+ minSamples: number().int().min(1).optional()
49168
49403
  });
49169
49404
  var CustomizeTransformDraftSchema = discriminatedUnion("kind", [
49170
49405
  IdentityTransformDraftSchema,
@@ -54117,6 +54352,7 @@ var IntegrationWithStateSchema = object({
54117
54352
  id: string(),
54118
54353
  addonId: string(),
54119
54354
  name: string(),
54355
+ /** A projection of the instance body's switch (`setInstanceEnabled` is the only writer). */
54120
54356
  enabled: boolean(),
54121
54357
  info: record(string(), unknown()).readonly(),
54122
54358
  /** The discovery candidate this integration was set up from (D984). */
@@ -54129,6 +54365,7 @@ var IntegrationLiteSchema = object({
54129
54365
  id: string(),
54130
54366
  addonId: string(),
54131
54367
  name: string(),
54368
+ /** A projection of the instance body's switch (`setInstanceEnabled` is the only writer). */
54132
54369
  enabled: boolean(),
54133
54370
  info: record(string(), unknown()).readonly(),
54134
54371
  /** The discovery candidate this integration was set up from (D984). */
@@ -54174,10 +54411,9 @@ var AvailableIntegrationTypeSchema = object({
54174
54411
  * locations" checkbox. Provider-declared in the addon manifest. */
54175
54412
  supportsLocationImport: boolean(),
54176
54413
  /**
54177
- * True when this integration DECLARES a pre-creation test (the
54178
- * `connection-test` cap, or a broker whose settings it stores). Drives the
54179
- * Test button: an integration that cannot be tested must say so up front
54180
- * rather than offering a button that always answers the same nonsense.
54414
+ * True when this integration's instances declare a Test (`integration-instances.describe().canTest`,
54415
+ * D1016). An integration that cannot be tested must say so up front rather than offering a
54416
+ * button that always answers the same nonsense.
54181
54417
  */
54182
54418
  canTest: boolean(),
54183
54419
  existingInstances: array(object({
@@ -54228,15 +54464,21 @@ var TestConnectionResultSchema = object({
54228
54464
  var CreateIntegrationInputSchema = object({
54229
54465
  addonId: string(),
54230
54466
  name: string(),
54231
- enabled: boolean().optional(),
54232
54467
  info: record(string(), unknown()).optional(),
54233
54468
  /** `stableId` of the discovery candidate the form was seeded from (D984). */
54234
54469
  originStableId: string().optional(),
54235
- settings: record(string(), unknown()).optional()
54470
+ settings: record(string(), unknown()).optional(),
54471
+ /** The instance kind being created, for a provider with several; omitted = its only testable kind. */
54472
+ kind: string().min(1).optional()
54236
54473
  });
54237
54474
  var UpdateIntegrationInputSchema = object({
54238
54475
  id: string(),
54239
54476
  name: string().optional(),
54477
+ /**
54478
+ * Accepted for a FIXED builtin only (`info.fixed`: alarm panel, camera grid, core blocks,
54479
+ * terminal), which keeps no instance record: the registry flag is its one store. Any other
54480
+ * integration is switched through `integration-instances.setInstanceEnabled`.
54481
+ */
54240
54482
  enabled: boolean().optional(),
54241
54483
  info: record(string(), unknown()).optional()
54242
54484
  });
@@ -54253,13 +54495,7 @@ method(_void(), array(IntegrationWithStateSchema)), method(object({ id: string()
54253
54495
  }), method(object({ id: string() }), DeleteIntegrationResultSchema, {
54254
54496
  kind: "mutation",
54255
54497
  auth: "admin"
54256
- }), method(_void(), array(AvailableIntegrationTypeSchema), { auth: "admin" }), method(object({
54257
- addonId: string(),
54258
- settings: record(string(), unknown())
54259
- }), TestConnectionResultSchema, {
54260
- kind: "mutation",
54261
- auth: "admin"
54262
- });
54498
+ }), method(_void(), array(AvailableIntegrationTypeSchema), { auth: "admin" });
54263
54499
  /**
54264
54500
  * `integration-instances` - the connection of an addon that holds ONE or SEVERAL
54265
54501
  * (an account, a relay, a destination) as typed records (D985, D986). The addon's
@@ -54284,7 +54520,7 @@ var IntegrationInstanceIdSchema = string().min(1);
54284
54520
  var IntegrationInstanceModeSchema = _enum(["single", "multiple"]);
54285
54521
  /**
54286
54522
  * What the addon's instances ARE for the Integrations page (planning#416). `devices`: each
54287
- * instance is an integration that brings devices (the registry owns its on/off switch);
54523
+ * instance is an integration that brings devices (its record body owns the on/off switch);
54288
54524
  * `services`: a connection configured from the addon's own function page, never listed on
54289
54525
  * Integrations.
54290
54526
  * It is the same vocabulary as the manifest's `integrationRole`, which stays as an override.
@@ -54401,8 +54637,8 @@ var IntegrationInstanceSchema = object({
54401
54637
  configured: boolean(),
54402
54638
  /**
54403
54639
  * The instance's own on/off switch (D996), derived from the record body (`enabled !== false`,
54404
- * so a row written before the field existed is on). Absent when the `integrations` registry
54405
- * owns the switch (`describe().role` is `devices`): read it from the registry row.
54640
+ * so a row written before the field existed is on). The same for every role, `devices` included:
54641
+ * the body is the one store, `setInstanceEnabled` the one writer (epic #440, step 3).
54406
54642
  */
54407
54643
  enabled: boolean().optional(),
54408
54644
  /** The kind of this instance (one of `describe().kinds[].id`), when the provider has kinds. */
@@ -54452,7 +54688,8 @@ var integrationInstancesCapability = {
54452
54688
  auth: "admin"
54453
54689
  }),
54454
54690
  /**
54455
- * Switch ONE instance on or off. A row control, not a form field: `updateInstance.values` is the
54691
+ * Switch ONE instance on or off, for every role; a missing record is created from the addon's
54692
+ * initial body. A row control, not a form field: `updateInstance.values` is the
54456
54693
  * form patch (D62, D996). An off instance keeps its record and secrets and does no work.
54457
54694
  */
54458
54695
  setInstanceEnabled: method(object({
@@ -57263,6 +57500,8 @@ var MigrationIntegrationSchema = object({
57263
57500
  addonId: string(),
57264
57501
  name: string(),
57265
57502
  info: Rows,
57503
+ /** The registry's stored switch: read by the one-switch migration, nothing else. */
57504
+ enabled: boolean().optional(),
57266
57505
  originStableId: string().optional()
57267
57506
  });
57268
57507
  var MigrationDeviceSchema = object({
@@ -62499,13 +62738,6 @@ var AddBrokerInputSchema = object({
62499
62738
  });
62500
62739
  var AddBrokerResultSchema = object({ id: string() });
62501
62740
  var IdInputSchema = object({ id: string() });
62502
- var TestResultSchema$1 = discriminatedUnion("ok", [object({
62503
- ok: literal(true),
62504
- latencyMs: number()
62505
- }), object({
62506
- ok: literal(false),
62507
- error: string()
62508
- })]);
62509
62741
  var StartEmbeddedInputSchema = object({
62510
62742
  port: number().int().min(1).max(65535).default(1883),
62511
62743
  /** Allow anonymous connect (no username/password). Default: false. */
@@ -62528,9 +62760,6 @@ method(_void(), array(BrokerInfoSchema)), method(IdInputSchema, BrokerConnection
62528
62760
  }), method(IdInputSchema, _void(), {
62529
62761
  kind: "mutation",
62530
62762
  auth: "admin"
62531
- }), method(IdInputSchema, TestResultSchema$1, {
62532
- kind: "mutation",
62533
- auth: "admin"
62534
62763
  }), method(StartEmbeddedInputSchema, StartEmbeddedResultSchema, {
62535
62764
  kind: "mutation",
62536
62765
  auth: "admin"
@@ -66781,14 +67010,6 @@ object({
66781
67010
  empty: boolean().nullable(),
66782
67011
  /** True while the pump is running. Null while unknown. */
66783
67012
  pumpRunning: boolean().nullable(),
66784
- /** Water drunk in the last drink, in litres. */
66785
- lastDrink: number().min(0).nullable().meta(readingMeta("volume")),
66786
- /** Water drunk in the current hour, in litres. */
66787
- currentHourDrink: number().min(0).nullable().meta(readingMeta("volume")),
66788
- /** Water drunk over the last 24 hours (rolling), in litres. */
66789
- last24hDrink: number().min(0).nullable().meta(readingMeta("volume")),
66790
- /** Water drunk since local midnight, in litres. Null when the fountain has no such sensor. */
66791
- todayDrink: number().min(0).nullable().meta(readingMeta("volume")),
66792
67013
  /** Decoded fault message. Null means healthy; a non-null string is an active fault. */
66793
67014
  error: string().nullable(),
66794
67015
  /** Ms epoch when the slice was last refreshed. */
@@ -66801,9 +67022,6 @@ DeviceType.PetFountain, method(object({
66801
67022
  }), _void(), {
66802
67023
  kind: "mutation",
66803
67024
  auth: "protected"
66804
- }), method(object({ deviceId: DeviceIdSchema$1 }), _void(), {
66805
- kind: "mutation",
66806
- auth: "protected"
66807
67025
  });
66808
67026
  /**
66809
67027
  * The wire shapes of the Auto tune plan and apply (D745), used by the
@@ -74166,7 +74384,7 @@ var TrainingProviderTypeSchema = object({
74166
74384
  label: string(),
74167
74385
  /** Path under the addon package (e.g. `assets/training-modal/icon.svg`). */
74168
74386
  iconAsset: string(),
74169
- /** Owning `training-provider` addon — collection selector for createEntry. */
74387
+ /** Owning `training-provider` addon. */
74170
74388
  addonId: string(),
74171
74389
  /**
74172
74390
  * Fields for one entry of this type (credentials + defaults). Absent on a
@@ -74211,36 +74429,6 @@ var TrainingProviderDescriptorSchema = object({
74211
74429
  */
74212
74430
  formValues: record(string(), unknown()).optional()
74213
74431
  });
74214
- /**
74215
- * Patch one entry's name, credentials and defaults. Pin with owning `{ addonId }`.
74216
- * An omitted or empty `tokenSecret` means KEEP the stored secret (D787).
74217
- * `{ $secretClear: true }` clears it.
74218
- */
74219
- var TrainingProviderUpdateEntryInputSchema = object({
74220
- entryId: string().min(1),
74221
- name: string().min(1),
74222
- tokenId: string().optional(),
74223
- tokenSecret: union([string(), object({ $secretClear: literal(true) })]).optional(),
74224
- environment: string().optional(),
74225
- gpuType: string().optional(),
74226
- region: string().optional(),
74227
- costCapUsd: number().nonnegative().optional(),
74228
- maxRuntimeSec: number().int().positive().optional(),
74229
- failedDatasetGraceHours: number().nonnegative().optional()
74230
- });
74231
- var TrainingCredentialCheckSchema = object({
74232
- ok: boolean(),
74233
- /** Workspace / account name, when the provider says. */
74234
- account: string().optional(),
74235
- reason: _enum([
74236
- "missing",
74237
- "invalid",
74238
- "forbidden",
74239
- "network",
74240
- "quota"
74241
- ]).optional(),
74242
- detail: string().optional()
74243
- });
74244
74432
  var ProviderJobStateSchema = _enum([
74245
74433
  "pending",
74246
74434
  "starting",
@@ -74288,22 +74476,6 @@ var TrainingLogLineSchema = object({
74288
74476
  text: string()
74289
74477
  });
74290
74478
  method(object({}), array(TrainingProviderDescriptorSchema).readonly(), { auth: "admin" }), method(object({}), array(TrainingProviderTypeSchema).readonly(), { auth: "admin" }), method(object({}), array(TrainingProviderEntrySchema).readonly(), { auth: "admin" }), method(object({
74291
- typeId: string().min(1),
74292
- name: string().min(1)
74293
- }), object({ entryId: string() }), {
74294
- kind: "mutation",
74295
- auth: "admin"
74296
- }), method(object({ entryId: string().min(1) }), object({ ok: literal(true) }), {
74297
- kind: "mutation",
74298
- auth: "admin"
74299
- }), method(TrainingProviderUpdateEntryInputSchema, object({ ok: literal(true) }), {
74300
- kind: "mutation",
74301
- auth: "admin"
74302
- }), method(object({ entryId: string().min(1) }), TrainingCredentialCheckSchema, {
74303
- kind: "mutation",
74304
- auth: "admin",
74305
- timeoutMs: 3e4
74306
- }), method(object({
74307
74479
  entryId: string().min(1),
74308
74480
  gpuType: string(),
74309
74481
  region: string(),
@@ -77689,20 +77861,6 @@ Object.freeze({
77689
77861
  access: "view",
77690
77862
  role: "admin"
77691
77863
  },
77692
- "connectionTest.describeTest": {
77693
- capName: "connection-test",
77694
- capScope: "system",
77695
- addonId: null,
77696
- access: "view",
77697
- role: "admin"
77698
- },
77699
- "connectionTest.testSettings": {
77700
- capName: "connection-test",
77701
- capScope: "system",
77702
- addonId: null,
77703
- access: "create",
77704
- role: "admin"
77705
- },
77706
77864
  "connectivity.getStatus": {
77707
77865
  capName: "connectivity",
77708
77866
  capScope: "device",
@@ -80069,13 +80227,6 @@ Object.freeze({
80069
80227
  access: "view",
80070
80228
  role: "admin"
80071
80229
  },
80072
- "integrations.testConnection": {
80073
- capName: "integrations",
80074
- capScope: "system",
80075
- addonId: null,
80076
- access: "create",
80077
- role: "admin"
80078
- },
80079
80230
  "integrations.update": {
80080
80231
  capName: "integrations",
80081
80232
  capScope: "system",
@@ -81308,13 +81459,6 @@ Object.freeze({
81308
81459
  access: "create",
81309
81460
  role: "admin"
81310
81461
  },
81311
- "mqttBroker.testConnection": {
81312
- capName: "mqtt-broker",
81313
- capScope: "system",
81314
- addonId: null,
81315
- access: "create",
81316
- role: "admin"
81317
- },
81318
81462
  "nativeObjectDetection.getOptions": {
81319
81463
  capName: "native-object-detection",
81320
81464
  capScope: "device",
@@ -82190,13 +82334,6 @@ Object.freeze({
82190
82334
  access: "view",
82191
82335
  role: "viewer"
82192
82336
  },
82193
- "petFountain.resetDailyConsumption": {
82194
- capName: "pet-fountain",
82195
- capScope: "device",
82196
- addonId: null,
82197
- access: "delete",
82198
- role: "viewer"
82199
- },
82200
82337
  "petFountain.setPump": {
82201
82338
  capName: "pet-fountain",
82202
82339
  capScope: "device",
@@ -86152,20 +86289,6 @@ Object.freeze({
86152
86289
  access: "create",
86153
86290
  role: "admin"
86154
86291
  },
86155
- "trainingProvider.createEntry": {
86156
- capName: "training-provider",
86157
- capScope: "system",
86158
- addonId: null,
86159
- access: "create",
86160
- role: "admin"
86161
- },
86162
- "trainingProvider.deleteEntry": {
86163
- capName: "training-provider",
86164
- capScope: "system",
86165
- addonId: null,
86166
- access: "delete",
86167
- role: "admin"
86168
- },
86169
86292
  "trainingProvider.describe": {
86170
86293
  capName: "training-provider",
86171
86294
  capScope: "system",
@@ -86236,13 +86359,6 @@ Object.freeze({
86236
86359
  access: "create",
86237
86360
  role: "admin"
86238
86361
  },
86239
- "trainingProvider.updateEntry": {
86240
- capName: "training-provider",
86241
- capScope: "system",
86242
- addonId: null,
86243
- access: "create",
86244
- role: "admin"
86245
- },
86246
86362
  "trainingProvider.uploadDataset": {
86247
86363
  capName: "training-provider",
86248
86364
  capScope: "system",
@@ -86250,13 +86366,6 @@ Object.freeze({
86250
86366
  access: "create",
86251
86367
  role: "admin"
86252
86368
  },
86253
- "trainingProvider.validateCredentials": {
86254
- capName: "training-provider",
86255
- capScope: "system",
86256
- addonId: null,
86257
- access: "create",
86258
- role: "admin"
86259
- },
86260
86369
  "turnProvider.getTurnServers": {
86261
86370
  capName: "turn-provider",
86262
86371
  capScope: "system",
@@ -88593,11 +88702,6 @@ Object.freeze({
88593
88702
  form: "single",
88594
88703
  optional: false
88595
88704
  }],
88596
- "petFountain.resetDailyConsumption": [{
88597
- name: "deviceId",
88598
- form: "single",
88599
- optional: false
88600
- }],
88601
88705
  "petFountain.setPump": [{
88602
88706
  name: "deviceId",
88603
88707
  form: "single",
@@ -91385,11 +91489,6 @@ function linkFieldDescriptor(key, target, labels) {
91385
91489
  ...target.kind !== void 0 ? { kind: target.kind } : {}
91386
91490
  };
91387
91491
  }
91388
- /**
91389
- * Declare the record kind of a service that links to other instances. The body is
91390
- * `{ name, ...links, ...fields }`; the links are recorded in the kind (read back by
91391
- * {@link linksOfKind}) so the hub can index who points at what.
91392
- */
91393
91492
  function declareLinkKind(spec) {
91394
91493
  const linkShape = {};
91395
91494
  for (const [field, target] of Object.entries(spec.links)) linkShape[field] = linkField(target);
@@ -91446,7 +91545,6 @@ function buildLinkedInstances(records, spec) {
91446
91545
  });
91447
91546
  return instances;
91448
91547
  }
91449
- entryBody({ brokerId: string() });
91450
91548
  /**
91451
91549
  * The calendars an account imports leave the account (D1013). An account record used to carry a
91452
91550
  * `calendarIds` array; each calendar is now a record of its own that LINKS to the account
@@ -91549,22 +91647,12 @@ var GoogleBrokerEntrySchema = object({
91549
91647
  fromAddress: string().default(""),
91550
91648
  fromName: string().default("")
91551
91649
  });
91552
- var GoogleServicesConfigSchema = object({
91553
- brokers: array(GoogleBrokerEntrySchema).default([]),
91554
- /** @deprecated Pre-broker singleton — cleared after migrateLegacyToBrokers. */
91555
- clientId: string().optional(),
91556
- /** @deprecated Pre-broker singleton — cleared after migrateLegacyToBrokers. */
91557
- clientSecret: string().optional().meta({ secret: true }),
91558
- /** @deprecated Pre-broker singleton — cleared after migrateLegacyToBrokers. */
91559
- calendarFilter: string().optional(),
91560
- /** @deprecated Pre-broker singleton — cleared after migrateLegacyToBrokers. */
91561
- fromAddress: string().optional(),
91562
- /** @deprecated Pre-broker singleton — cleared after migrateLegacyToBrokers. */
91563
- fromName: string().optional()
91564
- });
91650
+ /**
91651
+ * The addon keeps no addon-level settings: every account is a `brokers` record and its tokens
91652
+ * live in the durable `oauthAccounts` state.
91653
+ */
91654
+ var GoogleServicesConfigSchema = object({});
91565
91655
  var DEFAULT_GOOGLE_CONFIG = GoogleServicesConfigSchema.parse({});
91566
- /** Flat pre-broker config (singleton). Parsed only for one-shot migration. */
91567
- var LegacyGoogleFlatConfigSchema = GoogleServicesConfigSchema;
91568
91656
  var DEFAULT_OAUTH_STATE = {
91569
91657
  refreshToken: "",
91570
91658
  accessToken: "",
@@ -91634,52 +91722,6 @@ function brokerEntryToSettings(entry) {
91634
91722
  fromName: entry.fromName
91635
91723
  };
91636
91724
  }
91637
- /**
91638
- * One-shot: flat singleton config + legacy `oauth` state → `google_001`.
91639
- * Idempotent when `brokers` already present.
91640
- */
91641
- function migrateLegacyToBrokers(rawConfig, legacyOauth) {
91642
- const loose = LegacyGoogleFlatConfigSchema.safeParse(rawConfig);
91643
- const flat = loose.success ? loose.data : {};
91644
- const existingBrokers = flat.brokers ?? [];
91645
- if (existingBrokers.length > 0) return {
91646
- brokers: existingBrokers.map((b) => GoogleBrokerEntrySchema.parse(b)),
91647
- oauthAccounts: [],
91648
- didMigrate: false
91649
- };
91650
- const hasClient = (flat.clientId ?? "").length > 0 || (flat.clientSecret ?? "").length > 0;
91651
- const hasOauth = legacyOauth !== null && legacyOauth.refreshToken.length > 0;
91652
- if (!hasClient && !hasOauth) return {
91653
- brokers: [],
91654
- oauthAccounts: [],
91655
- didMigrate: false
91656
- };
91657
- const id = "google_001";
91658
- const email = legacyOauth?.accountEmail?.trim() ?? "";
91659
- const name = email.length > 0 ? email : "Google account";
91660
- const entry = GoogleBrokerEntrySchema.parse({
91661
- id,
91662
- name,
91663
- clientId: flat.clientId ?? "",
91664
- clientSecret: flat.clientSecret ?? "",
91665
- calendarFilter: flat.calendarFilter ?? "",
91666
- fromAddress: flat.fromAddress ?? "",
91667
- fromName: flat.fromName ?? ""
91668
- });
91669
- const oauthAccounts = legacyOauth !== null && (legacyOauth.refreshToken.length > 0 || legacyOauth.accessToken.length > 0) ? [{
91670
- id,
91671
- refreshToken: legacyOauth.refreshToken,
91672
- accessToken: legacyOauth.accessToken,
91673
- accessExpiresAt: legacyOauth.accessExpiresAt,
91674
- accountEmail: legacyOauth.accountEmail,
91675
- needsReauth: false
91676
- }] : [];
91677
- return {
91678
- brokers: [entry],
91679
- oauthAccounts,
91680
- didMigrate: true
91681
- };
91682
- }
91683
91725
  /** Local calendar id stamped as `brokerId:googleCalendarId`. */
91684
91726
  function stampCalendarId(brokerId, googleCalendarId) {
91685
91727
  return `${brokerId}:${googleCalendarId}`;
@@ -91795,9 +91837,6 @@ var GoogleBrokerRegistry = class {
91795
91837
  connectedSize() {
91796
91838
  return this.entries.filter((e) => this.isConnected(e.id)).length;
91797
91839
  }
91798
- toConfig() {
91799
- return { brokers: [...this.entries] };
91800
- }
91801
91840
  seedCounterFromEntries(entries) {
91802
91841
  let maxSeen = 0;
91803
91842
  for (const e of entries) {
@@ -92708,6 +92747,245 @@ async function planDropSharedCalendarIds(ports) {
92708
92747
  } })
92709
92748
  }] };
92710
92749
  }
92750
+ //#endregion
92751
+ //#region src/migrations/drop-config-brokers-and-legacy-oauth.ts
92752
+ /**
92753
+ * The addon-level `brokers` setting and the singleton `oauth` state are gone (planning#440 step 5):
92754
+ * every account is a `brokers` record and its tokens live in `oauthAccounts`. This deletes the two
92755
+ * leftover keys, each only when nothing in them is still the only copy:
92756
+ *
92757
+ * - `brokers` goes when the `brokers` kind holds records, or when the setting itself is empty. A
92758
+ * non-empty setting with an empty kind was never copied: it stays.
92759
+ * - `oauth` goes when it carries no token (the empty state the old boot migration left behind), or
92760
+ * when `oauthAccounts` already holds accounts. A token with no account to hold it stays.
92761
+ *
92762
+ * Each edit carries a precondition read, so a row that changed since the plan was made is not
92763
+ * deleted; a second run finds nothing to plan.
92764
+ */
92765
+ var BROKERS_KEY = "brokers";
92766
+ var LEGACY_OAUTH_KEY = "oauth";
92767
+ /** The flat singleton client the boot migration used to clear. */
92768
+ var FLAT_KEYS = [
92769
+ "clientId",
92770
+ "clientSecret",
92771
+ "calendarFilter",
92772
+ "fromAddress",
92773
+ "fromName"
92774
+ ];
92775
+ var OAUTH_ACCOUNTS_KEY = "oauthAccounts";
92776
+ function present$1(answer, key) {
92777
+ if (answer.kind === "unreadable") throw new Error(`google-services: the stored '${key}' cannot be read (${answer.reason})`);
92778
+ return answer.kind === "absent" ? null : { value: answer.value };
92779
+ }
92780
+ function field(value, key) {
92781
+ return typeof value === "object" && value !== null ? Reflect.get(value, key) : void 0;
92782
+ }
92783
+ /** A token field that holds nothing: absent or the empty string. A secret marker is something. */
92784
+ function isBlank(value) {
92785
+ return value === void 0 || value === null || value === "";
92786
+ }
92787
+ function stringList(value) {
92788
+ if (!Array.isArray(value)) return null;
92789
+ const out = [];
92790
+ for (const item of value) {
92791
+ if (typeof item !== "string") return null;
92792
+ out.push(item);
92793
+ }
92794
+ return out;
92795
+ }
92796
+ function holdsAccounts(value) {
92797
+ const accounts = field(value, "accounts");
92798
+ return Array.isArray(accounts) && accounts.length > 0;
92799
+ }
92800
+ async function planDropConfigBrokersAndLegacyOauth(ports) {
92801
+ const rows = {};
92802
+ const keys = [];
92803
+ const take = (key, value) => {
92804
+ const id = `${GOOGLE_ADDON_ID}.${key}`;
92805
+ keys.push(id);
92806
+ rows[id] = {
92807
+ addonId: GOOGLE_ADDON_ID,
92808
+ key,
92809
+ value
92810
+ };
92811
+ };
92812
+ const brokers = present$1(await ports.readStored(BROKERS_KEY), BROKERS_KEY);
92813
+ if (brokers !== null) {
92814
+ if (!(Array.isArray(brokers.value) && brokers.value.length > 0) || (await ports.listBrokers()).length > 0) take(BROKERS_KEY, brokers.value);
92815
+ }
92816
+ for (const key of FLAT_KEYS) {
92817
+ const flat = present$1(await ports.readStored(key), key);
92818
+ if (flat !== null && (await ports.listBrokers()).length > 0) take(key, flat.value);
92819
+ }
92820
+ const shared = present$1(await ports.readStored(SHARED_CALENDAR_IDS_KEY), SHARED_CALENDAR_IDS_KEY);
92821
+ if (shared !== null) {
92822
+ const sharedIds = stringList(shared.value);
92823
+ if (sharedIds === null) throw new Error(`google-services: the stored '${SHARED_CALENDAR_IDS_KEY}' is not a list of ids — nothing dropped`);
92824
+ else {
92825
+ const brokers = await ports.listBrokers();
92826
+ const same = (ids) => ids === void 0 || ids.length === sharedIds.length && ids.every((id) => sharedIds.includes(id));
92827
+ if (brokers.length > 0 && brokers.every((b) => same(b.calendarIds))) take(SHARED_CALENDAR_IDS_KEY, shared.value);
92828
+ }
92829
+ }
92830
+ const oauth = present$1(await ports.readStored(LEGACY_OAUTH_KEY), LEGACY_OAUTH_KEY);
92831
+ if (oauth !== null) {
92832
+ const tokenless = isBlank(field(oauth.value, "refreshToken")) && isBlank(field(oauth.value, "accessToken"));
92833
+ const accounts = present$1(await ports.readStored(OAUTH_ACCOUNTS_KEY), OAUTH_ACCOUNTS_KEY);
92834
+ if (tokenless || accounts !== null && holdsAccounts(accounts.value)) take(LEGACY_OAUTH_KEY, oauth.value);
92835
+ }
92836
+ if (keys.length === 0) return { edits: [] };
92837
+ return { edits: [{
92838
+ op: "deleteKeys",
92839
+ scope: ADDON_SETTINGS_TABLE,
92840
+ keys,
92841
+ precondition: preconditionOf(rows)
92842
+ }] };
92843
+ }
92844
+ //#endregion
92845
+ //#region src/migrations/legacy-brokers-to-records.ts
92846
+ /**
92847
+ * The accounts a pre-record install kept in the addon settings become `brokers` records and
92848
+ * `oauthAccounts` entries (planning#440 step 5). Three legacy shapes feed it, the ones the boot
92849
+ * migration used to read:
92850
+ *
92851
+ * - the `brokers` setting (a list of entries);
92852
+ * - the flat singleton (`clientId`, `clientSecret`, `calendarFilter`, `fromAddress`, `fromName`),
92853
+ * which becomes `google_001`;
92854
+ * - the singleton `oauth` state, whose token follows its account (`google_001`, or the first
92855
+ * broker when brokers already existed).
92856
+ *
92857
+ * Reads come RESOLVED (the settings view answers values, not keychain markers); a value the
92858
+ * keychain could not serve is not a string and REFUSES the step, so nothing is written from a
92859
+ * guess. Each record is read back with its secret before the step reports done, and an account
92860
+ * that already has a record is never overwritten. The shared `calendarIds` set goes onto every
92861
+ * broker this step creates (the calendar migrations before it found no broker to give it to),
92862
+ * then becomes calendar records, so the selection is not lost whichever order the steps ran in. The legacy keys stay where they are: the drop
92863
+ * migration deletes them only after this one landed.
92864
+ */
92865
+ var LEGACY_BROKER_ID = "google_001";
92866
+ var LEGACY_FLAT_KEYS = [
92867
+ "clientId",
92868
+ "clientSecret",
92869
+ "calendarFilter",
92870
+ "fromAddress",
92871
+ "fromName"
92872
+ ];
92873
+ function present(answer, key) {
92874
+ if (answer.kind === "unreadable") throw new Error(`google-services: the stored '${key}' cannot be read (${answer.reason})`);
92875
+ return answer.kind === "absent" ? void 0 : answer.value;
92876
+ }
92877
+ function text(value, what) {
92878
+ if (value === void 0 || value === null) return "";
92879
+ if (typeof value === "string") return value;
92880
+ throw new Error(`google-services: ${what} is not a plain value (is the keychain available?)`);
92881
+ }
92882
+ function legacyOauthOf(value) {
92883
+ if (typeof value !== "object" || value === null) return null;
92884
+ const refreshToken = text(Reflect.get(value, "refreshToken"), "the legacy oauth refreshToken");
92885
+ if (refreshToken.length === 0) return null;
92886
+ const expires = Reflect.get(value, "accessExpiresAt");
92887
+ return {
92888
+ refreshToken,
92889
+ accessToken: text(Reflect.get(value, "accessToken"), "the legacy oauth accessToken"),
92890
+ accessExpiresAt: typeof expires === "number" ? expires : 0,
92891
+ accountEmail: text(Reflect.get(value, "accountEmail"), "the legacy oauth accountEmail").trim()
92892
+ };
92893
+ }
92894
+ async function flatFields(ports) {
92895
+ const out = {};
92896
+ for (const key of LEGACY_FLAT_KEYS) out[key] = text(present(await ports.readStored(key), key), `the stored '${key}'`);
92897
+ return out;
92898
+ }
92899
+ async function legacyEntries(ports, oauth) {
92900
+ const listed = present(await ports.readStored("brokers"), "brokers");
92901
+ if (Array.isArray(listed) && listed.length > 0) return listed.map((item) => {
92902
+ const parsed = GoogleBrokerEntrySchema.safeParse(item);
92903
+ if (!parsed.success) throw new Error(`google-services: a stored broker is invalid — ${parsed.error.message}`);
92904
+ return parsed.data;
92905
+ });
92906
+ const flat = await flatFields(ports);
92907
+ if (!flat["clientId"] && !flat["clientSecret"] && oauth === null) return [];
92908
+ const email = oauth?.accountEmail ?? "";
92909
+ return [GoogleBrokerEntrySchema.parse({
92910
+ id: LEGACY_BROKER_ID,
92911
+ name: email.length > 0 ? email : "Google account",
92912
+ ...flat
92913
+ })];
92914
+ }
92915
+ async function sharedCalendarIds(ports) {
92916
+ const value = present(await ports.readStored("calendarIds"), "calendarIds");
92917
+ if (value === void 0) return null;
92918
+ if (!Array.isArray(value) || !value.every((item) => typeof item === "string")) throw new Error("google-services: the shared calendarIds is not a list of ids — nothing copied");
92919
+ return value;
92920
+ }
92921
+ /** The keys a legacy install left that no record holds yet, for the init warning. */
92922
+ async function leftoverLegacyKeys(ports) {
92923
+ const left = [];
92924
+ const listed = await ports.readStored("brokers");
92925
+ if (listed.kind === "present" && Array.isArray(listed.value) && listed.value.length > 0) left.push("brokers");
92926
+ for (const key of ["clientId", "clientSecret"]) {
92927
+ const answer = await ports.readStored(key);
92928
+ if (answer.kind === "present" && answer.value !== "" && answer.value !== null) left.push(key);
92929
+ }
92930
+ const oauth = await ports.readStored("oauth");
92931
+ if (oauth.kind === "present") {
92932
+ const token = typeof oauth.value === "object" && oauth.value !== null ? Reflect.get(oauth.value, "refreshToken") : void 0;
92933
+ if (token !== void 0 && token !== "" && token !== null) left.push("oauth");
92934
+ }
92935
+ return left;
92936
+ }
92937
+ async function copyLegacyBrokersToRecords(ports) {
92938
+ const oauth = legacyOauthOf(present(await ports.readStored("oauth"), "oauth"));
92939
+ const entries = await legacyEntries(ports, oauth);
92940
+ if (entries.length === 0) return {
92941
+ outcome: "already-done",
92942
+ summary: { reason: "no-legacy-data" }
92943
+ };
92944
+ const have = new Set((await ports.listBrokers()).map((b) => b.id));
92945
+ const shared = await sharedCalendarIds(ports);
92946
+ let created = 0;
92947
+ let selections = 0;
92948
+ for (const entry of entries) {
92949
+ if (have.has(entry.id)) continue;
92950
+ await ports.putBroker(entry);
92951
+ const back = await ports.readBroker(entry.id);
92952
+ if (back === null || back.clientId !== entry.clientId || back.clientSecret !== entry.clientSecret) throw new Error(`google-services: broker '${entry.id}' did not read back as written`);
92953
+ created += 1;
92954
+ if (shared !== null && await ports.setBrokerCalendarIds(entry.id, shared)) selections += 1;
92955
+ }
92956
+ if (selections > 0) await moveCalendarIdsToRecords(ports, { calendarIdOf: (accountId, stamped) => {
92957
+ const parsed = parseStampedCalendarId(stamped);
92958
+ return parsed?.brokerId === accountId ? parsed.googleCalendarId : null;
92959
+ } });
92960
+ let account = 0;
92961
+ const primary = entries[0];
92962
+ if (oauth !== null && primary !== void 0) {
92963
+ if ((await ports.listOauthAccountIds()).length === 0) {
92964
+ await ports.putOauthAccount({
92965
+ id: primary.id,
92966
+ refreshToken: oauth.refreshToken,
92967
+ accessToken: oauth.accessToken,
92968
+ accessExpiresAt: oauth.accessExpiresAt,
92969
+ accountEmail: oauth.accountEmail,
92970
+ needsReauth: false
92971
+ });
92972
+ const back = await ports.readOauthAccount(primary.id);
92973
+ if (back === null || back.refreshToken !== oauth.refreshToken) throw new Error(`google-services: the oauth account of '${primary.id}' did not read back`);
92974
+ account = 1;
92975
+ }
92976
+ }
92977
+ return {
92978
+ outcome: created + account === 0 ? "already-done" : "done",
92979
+ summary: {
92980
+ brokers: created,
92981
+ oauthAccounts: account
92982
+ }
92983
+ };
92984
+ }
92985
+ //#endregion
92986
+ //#region src/migrations/index.ts
92987
+ var CALENDAR_IDS_TO_RECORDS_ID = "google-services/2026-11-07-calendar-ids-to-calendar-records";
92988
+ var LEGACY_BROKERS_TO_RECORDS_ID = "google-services/2026-11-06-legacy-brokers-to-records";
92711
92989
  /** The `google-services` catalogue (D987): offered to the engine when the addon initialises. */
92712
92990
  var ADDON_MIGRATIONS = [
92713
92991
  {
@@ -92744,7 +93022,7 @@ var ADDON_MIGRATIONS = [
92744
93022
  },
92745
93023
  {
92746
93024
  meta: {
92747
- id: "google-services/2026-11-07-calendar-ids-to-calendar-records",
93025
+ id: CALENDAR_IDS_TO_RECORDS_ID,
92748
93026
  owner: "google-services",
92749
93027
  level: "addon-state",
92750
93028
  seq: 3,
@@ -92760,6 +93038,38 @@ var ADDON_MIGRATIONS = [
92760
93038
  const parsed = parseStampedCalendarId(entry);
92761
93039
  return parsed?.brokerId === accountId ? parsed.googleCalendarId : null;
92762
93040
  } })
93041
+ },
93042
+ {
93043
+ meta: {
93044
+ id: LEGACY_BROKERS_TO_RECORDS_ID,
93045
+ owner: "google-services",
93046
+ level: "addon-state",
93047
+ seq: 4,
93048
+ dependsOn: [CALENDAR_IDS_TO_RECORDS_ID],
93049
+ store: "settings",
93050
+ scope: "cluster",
93051
+ onFailure: "tolerate",
93052
+ bodyKind: "procedure",
93053
+ description: "Copy the addon-level brokers setting or the flat singleton client, and the legacy oauth token, into broker records and oauthAccounts, each read back",
93054
+ fixtureMark: "the client secret of a flat singleton, read back from its record"
93055
+ },
93056
+ procedure: copyLegacyBrokersToRecords
93057
+ },
93058
+ {
93059
+ meta: {
93060
+ id: "google-services/2026-11-06-drop-config-brokers-and-legacy-oauth",
93061
+ owner: "google-services",
93062
+ level: "addon-state",
93063
+ seq: 5,
93064
+ dependsOn: [LEGACY_BROKERS_TO_RECORDS_ID],
93065
+ store: "settings",
93066
+ scope: "cluster",
93067
+ onFailure: "tolerate",
93068
+ bodyKind: "plan",
93069
+ description: "Delete the addon-level brokers setting once the brokers records exist, and the singleton oauth state once it holds no token",
93070
+ fixtureMark: "the brokers setting kept when its records are missing"
93071
+ },
93072
+ plan: planDropConfigBrokersAndLegacyOauth
92763
93073
  }
92764
93074
  ];
92765
93075
  //#endregion
@@ -92845,6 +93155,22 @@ var GoogleBrokerStore = class GoogleBrokerStore {
92845
93155
  }
92846
93156
  return out;
92847
93157
  }
93158
+ async putOne(entry) {
93159
+ const { id, name, clientId, clientSecret, calendarFilter, fromAddress, fromName } = entry;
93160
+ const parsed = googleBrokersEntryKind.schema.safeParse({
93161
+ name,
93162
+ clientId,
93163
+ clientSecret,
93164
+ calendarFilter,
93165
+ fromAddress,
93166
+ fromName
93167
+ });
93168
+ if (!parsed.success) throw new Error(`invalid Google broker '${id}': ${parsed.error.message}`);
93169
+ await this.kind.put({
93170
+ id,
93171
+ data: parsed.data
93172
+ });
93173
+ }
92848
93174
  async replaceAll(entries) {
92849
93175
  const page = await this.kind.query({ limit: 1e3 });
92850
93176
  const nextIds = new Set(entries.map((e) => e.id));
@@ -92886,19 +93212,8 @@ var GoogleCallbackError = class extends Error {
92886
93212
  var CALLBACK_PATH = "/oauth/callback";
92887
93213
  var START_PATH = "/oauth/start";
92888
93214
  var DISCONNECT_PATH = "/oauth/disconnect";
92889
- var LegacyOauthStateSchema = object({
92890
- refreshToken: string().default("").meta({ secret: true }),
92891
- accessToken: string().default("").meta({ secret: true }),
92892
- accessExpiresAt: number().default(0),
92893
- accountEmail: string().default("")
92894
- });
92895
93215
  var GoogleServicesAddon = class extends BaseAddon {
92896
- secretStatePaths = [
92897
- "oauthAccounts.accounts[id].refreshToken",
92898
- "oauthAccounts.accounts[id].accessToken",
92899
- "oauth.refreshToken",
92900
- "oauth.accessToken"
92901
- ];
93216
+ secretStatePaths = ["oauthAccounts.accounts[id].refreshToken", "oauthAccounts.accounts[id].accessToken"];
92902
93217
  oauthAccountsHandle = null;
92903
93218
  registry = new GoogleBrokerRegistry();
92904
93219
  brokerStore = null;
@@ -92915,40 +93230,6 @@ var GoogleServicesAddon = class extends BaseAddon {
92915
93230
  }
92916
93231
  async onInitialize() {
92917
93232
  this.oauthAccountsHandle = this.state("oauthAccounts", GoogleOauthAccountsStateSchema, { accounts: [] });
92918
- let oauthAccounts = await this.oauthAccountsHandle.get();
92919
- const legacyHandle = this.state("oauth", LegacyOauthStateSchema, { ...DEFAULT_OAUTH_STATE });
92920
- const legacyOauth = await legacyHandle.get();
92921
- const migrated = migrateLegacyToBrokers(this.config, legacyOauth);
92922
- if (migrated.didMigrate) {
92923
- await this.updateGlobalSettings({
92924
- brokers: [...migrated.brokers],
92925
- clientId: void 0,
92926
- clientSecret: void 0,
92927
- calendarFilter: void 0,
92928
- fromAddress: void 0,
92929
- fromName: void 0
92930
- });
92931
- if (migrated.oauthAccounts.length > 0) {
92932
- oauthAccounts = { accounts: [...migrated.oauthAccounts] };
92933
- await this.oauthAccountsHandle.set(oauthAccounts);
92934
- }
92935
- await legacyHandle.set({ ...DEFAULT_OAUTH_STATE });
92936
- this.ctx.logger.info("google-services: migrated singleton OAuth to broker google_001", { meta: {
92937
- brokerId: "google_001",
92938
- accountEmail: legacyOauth.accountEmail || void 0
92939
- } });
92940
- } else if (oauthAccounts.accounts.length === 0 && legacyOauth.refreshToken.length > 0 && this.config.brokers.length > 0) {
92941
- oauthAccounts = { accounts: [{
92942
- id: this.config.brokers[0].id,
92943
- refreshToken: legacyOauth.refreshToken,
92944
- accessToken: legacyOauth.accessToken,
92945
- accessExpiresAt: legacyOauth.accessExpiresAt,
92946
- accountEmail: legacyOauth.accountEmail,
92947
- needsReauth: false
92948
- }] };
92949
- await this.oauthAccountsHandle.set(oauthAccounts);
92950
- await legacyHandle.set({ ...DEFAULT_OAUTH_STATE });
92951
- }
92952
93233
  const records = this.ctx.records;
92953
93234
  if (records === void 0) throw new Error("google-services: ctx.records is required (hub-only addon)");
92954
93235
  await records.declare({
@@ -92962,12 +93243,9 @@ var GoogleServicesAddon = class extends BaseAddon {
92962
93243
  onChanged: () => this.refreshCalendarSelection()
92963
93244
  });
92964
93245
  this.activeBrokers = await this.loadPersistedBrokers();
92965
- if ((await this.brokerStore.listResolved()).length === 0 && this.config.brokers.length > 0) {
92966
- await this.brokerStore.replaceAll(this.config.brokers);
92967
- this.activeBrokers = await this.loadPersistedBrokers();
92968
- }
92969
93246
  await this.migrateCalendarIds(records);
92970
93247
  await this.refreshCalendarSelection();
93248
+ const oauthAccounts = await this.oauthAccountsHandle.get();
92971
93249
  this.registry.seedFrom(this.activeBrokers, oauthAccounts.accounts);
92972
93250
  await this.refreshPublicOrigin();
92973
93251
  const calendarProvider = createGoogleCalendarSource({
@@ -93403,27 +93681,61 @@ var GoogleServicesAddon = class extends BaseAddon {
93403
93681
  brokers,
93404
93682
  calendars: records.kind(googleCalendarsEntryKind),
93405
93683
  warn: (message) => this.ctx.logger.warn(message)
93406
- })
93684
+ }),
93685
+ ...this.legacyBrokerPorts()
93686
+ };
93687
+ const report = await this.runMigrations(defineAddonMigrations(ADDON_MIGRATIONS, ports));
93688
+ if (report.applied.length > 0) this.activeBrokers = await this.loadPersistedBrokers();
93689
+ if (this.activeBrokers.length === 0) {
93690
+ const left = await leftoverLegacyKeys(ports);
93691
+ if (left.length > 0) this.ctx.logger.error("google-services: legacy account data was NOT copied into broker records — Google stays unavailable until it is", { meta: {
93692
+ leftoverKeys: left,
93693
+ failed: report.failed
93694
+ } });
93695
+ }
93696
+ }
93697
+ /** The legacy-broker migration's writes: a broker record and an `oauthAccounts` entry, each read back. */
93698
+ legacyBrokerPorts() {
93699
+ return {
93700
+ putBroker: async (entry) => {
93701
+ const store = this.brokerStore;
93702
+ if (store === null) throw new Error("google-services: the brokers store is not ready");
93703
+ await store.putOne(entry);
93704
+ },
93705
+ readBroker: async (id) => {
93706
+ const store = this.brokerStore;
93707
+ if (store === null) throw new Error("google-services: the brokers store is not ready");
93708
+ const found = (await store.listResolved()).find((b) => b.id === id);
93709
+ return found === void 0 ? null : found;
93710
+ },
93711
+ listOauthAccountIds: async () => {
93712
+ const handle = this.oauthAccountsHandle;
93713
+ if (handle === null) return [];
93714
+ return (await handle.get()).accounts.map((a) => a.id);
93715
+ },
93716
+ putOauthAccount: async (account) => {
93717
+ const handle = this.oauthAccountsHandle;
93718
+ if (handle === null) throw new Error("google-services: oauthAccounts is not ready");
93719
+ const current = await handle.get();
93720
+ await handle.set({ accounts: [...current.accounts, account] });
93721
+ },
93722
+ readOauthAccount: async (id) => {
93723
+ const handle = this.oauthAccountsHandle;
93724
+ if (handle === null) return null;
93725
+ return (await handle.get()).accounts.find((a) => a.id === id) ?? null;
93726
+ }
93407
93727
  };
93408
- if ((await this.runMigrations(defineAddonMigrations(ADDON_MIGRATIONS, ports))).applied.length > 0) this.activeBrokers = await this.loadPersistedBrokers();
93409
93728
  }
93410
93729
  async loadPersistedBrokers() {
93411
93730
  const store = this.brokerStore;
93412
- if (store !== null) {
93413
- const fromRecords = await store.listResolved();
93414
- if (fromRecords.length > 0) return fromRecords;
93415
- }
93416
- return this.config.brokers;
93731
+ return store === null ? [] : store.listResolved();
93417
93732
  }
93418
93733
  async persistBrokers() {
93419
93734
  const entries = [...this.registry.listEntries()];
93420
93735
  this.activeBrokers = entries;
93421
93736
  const store = this.brokerStore;
93422
- if (store !== null) {
93423
- await store.replaceAll(entries);
93424
- return;
93425
- }
93426
- await this.updateGlobalSettings({ brokers: entries });
93737
+ if (store === null) throw new Error("google-services: the brokers store is not ready");
93738
+ await store.replaceAll(entries);
93427
93739
  }
93428
93740
  async persistOauthAccounts() {
93429
93741
  if (!this.oauthAccountsHandle) return;
@@ -93595,7 +93907,6 @@ exports.createGoogleCalendarSource = createGoogleCalendarSource;
93595
93907
  exports.exchangeCode = exchangeCode;
93596
93908
  exports.introHtml = introHtml;
93597
93909
  exports.mapGoogleEvent = mapGoogleEvent;
93598
- exports.migrateLegacyToBrokers = migrateLegacyToBrokers;
93599
93910
  exports.needsRefresh = needsRefresh;
93600
93911
  exports.parseStampedCalendarId = parseStampedCalendarId;
93601
93912
  exports.redirectUriDisplay = redirectUriDisplay;