@camstack/addon-google-services 0.2.40 → 0.2.41

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.
@@ -5981,7 +5981,7 @@ var ZodIssueCode = {
5981
5981
  var ZodFirstPartyTypeKind;
5982
5982
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
5983
5983
  //#endregion
5984
- //#region ../types/dist/sleep-BX_MqzUe.mjs
5984
+ //#region ../types/dist/sleep-CdKka2ri.mjs
5985
5985
  /**
5986
5986
  * The audio chunk plane's byte format, and the ONE expansion from a coded
5987
5987
  * window to float samples (D455).
@@ -6665,137 +6665,95 @@ async function runAddonMigrations(host, migrations, logger, options = {}) {
6665
6665
  blockOwner
6666
6666
  };
6667
6667
  }
6668
- /**
6669
- * Build a {@link DurableState} over a single store key. Transport-agnostic:
6670
- * `read`/`write` are the addon-store or device-store accessors. The whole
6671
- * validated value round-trips on every read/write — the schema is the
6672
- * single source of truth for what is persisted, so no hand-listed field
6673
- * set can drop a key on save.
6674
- */
6675
- function createDurableState(deps) {
6676
- const get = async () => {
6677
- const raw = (await deps.read())[deps.key];
6678
- if (raw === void 0) return deps.fallback;
6679
- const parsed = deps.schema.safeParse(raw);
6680
- if (!parsed.success) {
6681
- deps.onParseError?.(deps.key, parsed.error);
6682
- return deps.fallback;
6683
- }
6684
- return parsed.data;
6685
- };
6686
- const set = async (next) => {
6687
- const validated = deps.schema.parse(next);
6688
- await deps.write({ [deps.key]: validated });
6689
- };
6690
- const update = async (fn) => {
6691
- await set(fn(await get()));
6692
- };
6668
+ /** The record calls the one-switch migration makes, over the migration API. */
6669
+ function switchRecordsOverMigrationApi(api) {
6670
+ return { kind: (definition) => {
6671
+ const handle = api.records.kind(definition);
6672
+ return {
6673
+ get: (id) => handle.get({ id }),
6674
+ put: (input, opts) => handle.put({
6675
+ ...input,
6676
+ ...opts?.ifRev === void 0 ? {} : { ifRev: opts.ifRev }
6677
+ }),
6678
+ patch: (id, partial) => handle.patch({
6679
+ id,
6680
+ partial
6681
+ })
6682
+ };
6683
+ } };
6684
+ }
6685
+ function integrationRowsApiOver(api) {
6693
6686
  return {
6694
- get,
6695
- set,
6696
- update
6687
+ list: async () => (await api.integrations.list({})).integrations,
6688
+ readLegacyIntegrationRows: (input) => api.legacyRows.read(input),
6689
+ clearLegacyIntegrationRows: (input) => api.legacyRows.clear(input)
6697
6690
  };
6698
6691
  }
6692
+ var PREFIX = "records/";
6693
+ /** The base of every records failure. `detail` is the human part of the message. */
6694
+ var RecordsError = class extends Error {
6695
+ code;
6696
+ detail;
6697
+ constructor(code, detail) {
6698
+ super(`${PREFIX}${code}: ${detail}`);
6699
+ this.name = "RecordsError";
6700
+ this.code = code;
6701
+ this.detail = detail;
6702
+ }
6703
+ };
6704
+ /** The keychain could not store or serve a value: explicit, never an empty string. */
6705
+ var RecordSecretUnavailableError = class extends RecordsError {
6706
+ constructor(detail) {
6707
+ super("secret-unavailable", detail);
6708
+ this.name = "RecordSecretUnavailableError";
6709
+ }
6710
+ };
6711
+ var InvalidRecordError = class extends RecordsError {
6712
+ constructor(detail) {
6713
+ super("invalid-record", detail);
6714
+ this.name = "InvalidRecordError";
6715
+ }
6716
+ };
6717
+ /** A kind declaration the engine refuses (non-additive change, bad shape, wrong file). */
6718
+ var DeclarationRefusedError = class extends RecordsError {
6719
+ constructor(detail) {
6720
+ super("declaration-refused", detail);
6721
+ this.name = "DeclarationRefusedError";
6722
+ }
6723
+ };
6699
6724
  /**
6700
- * Per-node scoping for the shared addon-settings blob.
6701
- *
6702
- * An addon's settings store is hub-central (the `addon-settings` cap is
6703
- * hub-routed — the hub instance answers for every node), so fields whose
6704
- * value is a NODE fact (decoder backend, engine pick, probed hardware
6705
- * capabilities) persist under the node-scoped key `<key>@<nodeId>` inside
6706
- * the single shared blob. The SCHEMA field key stays bare: the write path
6707
- * ({@link scopePatch}) maps the bare field onto the target node's scoped
6708
- * key; the read/hydrate path ({@link projectStore}) maps THIS node's value
6709
- * back, so UI forms and `resolveConfig` only ever see the bare key.
6710
- *
6711
- * Fields opt in via the `perNode: true` schema marker on `ConfigFieldBase`
6712
- * (`interfaces/config-ui.ts`); `BaseAddon` derives the key set from the
6713
- * schema and routes reads/writes through these helpers.
6714
- *
6715
- * ## No bare-key fallback — deliberate
6716
- *
6717
- * {@link readNodeValue} reads the node-scoped key ONLY. A node with no
6718
- * scoped key resolves to `undefined` so the field's schema `default` wins —
6719
- * NEVER `store[base]` and never another node's value. A bare legacy key in
6720
- * the store is invisible to every node, hub included, so one node's
6721
- * selection can never leak onto another. (This generalizes the
6722
- * `decoder-backend-keys.ts` semantics — the no-fallback variant — over an
6723
- * arbitrary set of per-node field keys.)
6724
- *
6725
- * Pure functions only — no I/O, no imports beyond the language. This is a
6726
- * LEAF module: import it via its deep path, never from the root barrel.
6727
- */
6728
- /**
6729
- * Normalize a raw kernel node id to the bare node id used for scoping.
6730
- * `localNodeId` can carry a `<node>/<addon>` suffix on forked child
6731
- * processes; per-node settings are per-NODE, so strip the addon segment.
6732
- * `undefined` / `null` / empty falls back to `'hub'`.
6733
- */
6734
- function normalizeNodeId(raw) {
6735
- if (raw === void 0 || raw === null || raw === "") return "hub";
6736
- const slashIdx = raw.indexOf("/");
6737
- if (slashIdx < 0) return raw;
6738
- const bare = raw.slice(0, slashIdx);
6739
- return bare === "" ? "hub" : bare;
6740
- }
6741
- /** The node-scoped store key for a per-node field: `<base>@<nodeId>`. */
6742
- function nodeScopedKey(base, nodeId) {
6743
- return `${base}@${normalizeNodeId(nodeId)}`;
6744
- }
6745
- /**
6746
- * Read a node's value for a per-node field from the raw shared store:
6747
- * the node-scoped key when present, otherwise `undefined`.
6748
- * Deliberately NO bare-key fallback (see module doc) — the caller lets the
6749
- * schema `default` win on `undefined`.
6725
+ * The link primitive's declaration half (D1013 rule 5): what a link field names and how a kind
6726
+ * records it. Split from `instance-link.ts` so `RecordIntegrationInstances` can read the links of
6727
+ * its kind without importing the builders that import it.
6750
6728
  */
6751
- function readNodeValue(store, base, nodeId) {
6752
- return store[nodeScopedKey(base, nodeId)];
6729
+ /** The body field of a link: the id of the instance it names; the target rides in the field meta. */
6730
+ function linkField(target) {
6731
+ return string().meta({ link: target });
6753
6732
  }
6754
- /**
6755
- * Re-map a UI/settings patch so every bare perNode field persists under the
6756
- * TARGET node's scoped key; all other keys pass through unchanged. Used on
6757
- * the write path so a save for one node never clobbers another node's value
6758
- * (and the bare key is never written). Returns a new object — the input
6759
- * patch is not mutated.
6760
- */
6761
- function scopePatch(patch, perNodeKeys, nodeId) {
6762
- const out = {};
6763
- for (const [key, value] of Object.entries(patch)) out[perNodeKeys.has(key) ? nodeScopedKey(key, nodeId) : key] = value;
6764
- return out;
6733
+ function linkTargetOf(meta) {
6734
+ if (typeof meta !== "object" || meta === null) return void 0;
6735
+ const link = Reflect.get(meta, "link");
6736
+ const parsed = LinkTargetSchema.safeParse(link);
6737
+ return parsed.success ? parsed.data : void 0;
6765
6738
  }
6766
- /**
6767
- * Project the raw shared store onto the bare schema keys for ONE node so a
6768
- * UI schema (whose field keys are bare) hydrates from that node's own
6769
- * values:
6770
- *
6771
- * - EVERY `@`-scoped key (any node's) is dropped from the pass-through.
6772
- * - Every bare perNode key is dropped from the pass-through (a stray bare
6773
- * legacy key must never hydrate any node — no bare fallback).
6774
- * - THIS node's effective value ({@link readNodeValue}) is then laid onto
6775
- * each bare perNode key; when the node has no scoped key the bare key is
6776
- * left ABSENT so the field's schema `default` wins.
6777
- *
6778
- * Returns a new object — the input store is not mutated.
6779
- */
6780
- function projectStore(store, perNodeKeys, nodeId) {
6781
- const out = {};
6782
- for (const [key, value] of Object.entries(store)) {
6783
- if (key.includes("@")) continue;
6784
- if (perNodeKeys.has(key)) continue;
6785
- out[key] = value;
6786
- }
6787
- for (const base of perNodeKeys) {
6788
- const value = readNodeValue(store, base, nodeId);
6789
- if (value !== void 0) out[base] = value;
6739
+ var LinkTargetSchema = object({
6740
+ cap: string().min(1),
6741
+ kind: string().min(1).optional()
6742
+ });
6743
+ /** The links a kind declares, read from the meta of its body fields. */
6744
+ function linksOfKind(kind) {
6745
+ const schema = kind.schema;
6746
+ if (!(schema instanceof ZodObject)) return [];
6747
+ const links = [];
6748
+ for (const [field, fieldSchema] of Object.entries(schema.shape)) {
6749
+ const to = linkTargetOf(globalRegistry.get(fieldSchema));
6750
+ if (to !== void 0) links.push({
6751
+ field,
6752
+ to
6753
+ });
6790
6754
  }
6791
- return out;
6755
+ return links;
6792
6756
  }
6793
- /** Every scope, in the order the guard and the docs list them. */
6794
- var SCOPED_SETTINGS_SCOPES = [
6795
- "cluster",
6796
- "device-defaults",
6797
- "node"
6798
- ];
6799
6757
  /**
6800
6758
  * The address of one keychain value: `secret://<owner>/<scope>/<fieldPath>`.
6801
6759
  *
@@ -6930,6 +6888,643 @@ function parseSecretRef(ref) {
6930
6888
  fieldPath
6931
6889
  };
6932
6890
  }
6891
+ /** Limits and names of `ctx.records` (D881). One authority; the engine and the facade read it. */
6892
+ /** The files a kind may live in. `history` is device-history's (D850), never records. */
6893
+ var RECORD_DATABASES = ["settings", "events"];
6894
+ /** The classes of a kind: the `@durable` vocabulary, one authority (replaces the annotation). */
6895
+ var RECORD_CLASSES = [
6896
+ "config",
6897
+ "ledger",
6898
+ "audit",
6899
+ "mirror",
6900
+ "ephemeral"
6901
+ ];
6902
+ var RECORD_DEFAULT_MAX_DATA_BYTES = 64 * 1024;
6903
+ var RECORD_MAX_DATA_BYTES = 1024 * 1024;
6904
+ var RECORD_BATCH_MAX = 1e3;
6905
+ var RECORD_QUERY_MAX = 1e3;
6906
+ /** A kind in the `settings` file may not bound itself above this (D447: high volume is `events`). */
6907
+ var RECORD_SETTINGS_MAX_ROWS = 5e4;
6908
+ /** The `Column`-free proof prefix: a ref collection for a kind's secret fields. */
6909
+ var RECORD_SECRET_COLLECTION_PREFIX = "records:";
6910
+ /**
6911
+ * Secret fields of a record, addressed the way a Zod schema declares them
6912
+ * (`collectZodSecretPaths`): dotted keys, `[]` for "each element of this array"
6913
+ * (`auth.accessToken`, `headers[].value`).
6914
+ *
6915
+ * `{}` after a key means "each value of this map" (`applianceSecrets{}`): the map's own key
6916
+ * names the value (`applianceSecrets{fridge}`), so no id key is declared and a body that drops a
6917
+ * key releases exactly that key's secret.
6918
+ *
6919
+ * Array elements are matched by a DECLARED id key (`secretArrayKeys`:
6920
+ * `{ headers: 'name' }`), never by index, so reordering a list keeps every
6921
+ * keychain ref (the same rule as `arrayItemFieldPath`). The concrete path of a
6922
+ * leaf names its element: `headers[X-Api].value`.
6923
+ *
6924
+ * Pure and browser-safe. Nothing here mutates: every transform returns a new value.
6925
+ */
6926
+ /** The array prefixes (declared form, e.g. `headers` or `a.headers`) of a path. */
6927
+ function parseSecretPath(path) {
6928
+ if (path.length === 0) throw new InvalidRecordError("an empty secret path");
6929
+ return path.split(".").map((raw) => {
6930
+ const each = raw.endsWith("[]");
6931
+ const map = raw.endsWith("{}");
6932
+ const key = each || map ? raw.slice(0, -2) : raw;
6933
+ if (key.length === 0) throw new InvalidRecordError(`secret path "${path}" has an empty segment`);
6934
+ return {
6935
+ key,
6936
+ each,
6937
+ map
6938
+ };
6939
+ });
6940
+ }
6941
+ /** The declared array prefixes of `path` that need an id key (`headers`, `a.rows`). */
6942
+ function secretArrayPrefixes(path) {
6943
+ const segments = parseSecretPath(path);
6944
+ const prefixes = [];
6945
+ const walked = [];
6946
+ for (const segment of segments) {
6947
+ walked.push(segment.key);
6948
+ if (segment.each) prefixes.push(walked.join("."));
6949
+ }
6950
+ return prefixes;
6951
+ }
6952
+ function isRecord$6(value) {
6953
+ return typeof value === "object" && value !== null && !Array.isArray(value);
6954
+ }
6955
+ function elementId(element, idKey, declared, prefix) {
6956
+ const id = isRecord$6(element) ? element[idKey] : void 0;
6957
+ 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`);
6958
+ return id;
6959
+ }
6960
+ /**
6961
+ * Visit every secret leaf PRESENT in `data` (an absent branch has nothing to
6962
+ * visit). `replace` returns the new leaf value, or {@link REMOVE_LEAF}; the
6963
+ * result is a new body, `data` is untouched.
6964
+ */
6965
+ var REMOVE_LEAF = Symbol("remove-leaf");
6966
+ function mapAt(node, segments, index, walkedKeys, concretePrefix, declared, arrayKeys, visit) {
6967
+ if (!isRecord$6(node)) return node;
6968
+ const segment = segments[index];
6969
+ if (segment === void 0) return node;
6970
+ if (!Object.prototype.hasOwnProperty.call(node, segment.key)) return node;
6971
+ const child = node[segment.key];
6972
+ const keys = [...walkedKeys, segment.key];
6973
+ const last = index === segments.length - 1;
6974
+ if (segment.each) {
6975
+ if (!Array.isArray(child)) return node;
6976
+ const prefix = keys.join(".");
6977
+ const idKey = arrayKeys[prefix];
6978
+ if (idKey === void 0) throw new InvalidRecordError(`"${declared}": no id key declared for the array "${prefix}"`);
6979
+ const mapped = child.map((element) => {
6980
+ const id = elementId(element, idKey, declared, prefix);
6981
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}[${encodeURIComponent(id)}]`;
6982
+ return last ? element : mapAt(element, segments, index + 1, keys, concrete, declared, arrayKeys, visit);
6983
+ });
6984
+ return {
6985
+ ...node,
6986
+ [segment.key]: mapped
6987
+ };
6988
+ }
6989
+ if (segment.map) {
6990
+ if (!isRecord$6(child)) return node;
6991
+ const kept = Object.entries(child).map(([mapKey, value]) => {
6992
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}{${encodeURIComponent(mapKey)}}`;
6993
+ if (!last) return [mapKey, mapAt(value, segments, index + 1, keys, concrete, declared, arrayKeys, visit)];
6994
+ return [mapKey, visit({
6995
+ declared,
6996
+ concrete,
6997
+ value
6998
+ })];
6999
+ }).filter(([, value]) => value !== REMOVE_LEAF);
7000
+ return {
7001
+ ...node,
7002
+ [segment.key]: Object.fromEntries(kept)
7003
+ };
7004
+ }
7005
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}`;
7006
+ if (last) {
7007
+ const replacement = visit({
7008
+ declared,
7009
+ concrete,
7010
+ value: child
7011
+ });
7012
+ if (replacement === REMOVE_LEAF) return Object.fromEntries(Object.entries(node).filter(([key]) => key !== segment.key));
7013
+ return {
7014
+ ...node,
7015
+ [segment.key]: replacement
7016
+ };
7017
+ }
7018
+ return {
7019
+ ...node,
7020
+ [segment.key]: mapAt(child, segments, index + 1, keys, concrete, declared, arrayKeys, visit)
7021
+ };
7022
+ }
7023
+ /** Replace/remove every present secret leaf; returns a NEW body. */
7024
+ function mapSecretLeaves(data, paths, arrayKeys, visit) {
7025
+ let current = data;
7026
+ for (const declared of paths) current = mapAt(current, parseSecretPath(declared), 0, [], "", declared, arrayKeys, visit);
7027
+ return current;
7028
+ }
7029
+ /**
7030
+ * The keychain collection name a kind's secrets live under. Prefixed so a
7031
+ * record's refs never collide with the refs a legacy collection of the same name
7032
+ * already holds during an adoption.
7033
+ */
7034
+ function recordSecretCollection(kind) {
7035
+ return `${RECORD_SECRET_COLLECTION_PREFIX}${kind}`;
7036
+ }
7037
+ /** The ONE ref a row's secret field may carry: the engine and the facade both build it here. */
7038
+ function recordSecretRef(owner, kind, rowId, concretePath) {
7039
+ return buildSecretRef({
7040
+ owner,
7041
+ scope: {
7042
+ kind: "row",
7043
+ collection: recordSecretCollection(kind),
7044
+ rowId
7045
+ },
7046
+ fieldPath: concretePath
7047
+ });
7048
+ }
7049
+ /**
7050
+ * A stored secret, as an admin read shows it: a VIEW naming the row's own
7051
+ * keychain ref (`set: true`), never the value and no longer the bare redaction
7052
+ * token. The form hands it to the secret field, which reveals the value by ref
7053
+ * through the audited `keychain-admin.reveal`; sent back untouched it keeps the
7054
+ * stored secret (the records door reads a view as KEEP).
7055
+ *
7056
+ * ONE implementation for the entries service and for every addon that serves
7057
+ * its own instances (`RecordIntegrationInstances`).
7058
+ */
7059
+ function isRecord$5(value) {
7060
+ return typeof value === "object" && value !== null && !Array.isArray(value);
7061
+ }
7062
+ function secretViewsOf(owner, kind, id, decl, data) {
7063
+ if (decl.secretPaths.length === 0) return data;
7064
+ const shown = mapSecretLeaves(data, decl.secretPaths, decl.secretArrayKeys, (leaf) => {
7065
+ if (leaf.value !== "__camstack_redacted__") return leaf.value;
7066
+ return {
7067
+ $secret: recordSecretRef(owner, kind, id, leaf.concrete),
7068
+ v: 1,
7069
+ set: true
7070
+ };
7071
+ });
7072
+ return isRecord$5(shown) ? shown : data;
7073
+ }
7074
+ /** The most instances one addon lists (an integrations page, not a table). */
7075
+ var INSTANCES_LIST_MAX = 1e3;
7076
+ /**
7077
+ * The ONE reader of an instance's switch (D996): an absent field means on, so a row written
7078
+ * before the field existed needs no migration. Every consumer of an instance body asks this.
7079
+ */
7080
+ function isInstanceEnabled(body) {
7081
+ return body.enabled !== false;
7082
+ }
7083
+ /** The body key of the switch; only {@link RecordIntegrationInstances.setInstanceEnabled} writes it. */
7084
+ var SWITCH_KEY = "enabled";
7085
+ /** The keys of the kind's secret fields that sit at the top level of the body. */
7086
+ function topLevelSecretKeys(paths) {
7087
+ return new Set(paths.filter((p) => !p.includes(".") && !p.includes("[") && !p.includes("{")));
7088
+ }
7089
+ /** The keys of the kind's top-level MAPS whose values are secrets (`applianceSecrets{}`). */
7090
+ function secretMapKeys(paths) {
7091
+ return new Set(paths.filter((p) => p.endsWith("{}") && !p.slice(0, -2).match(/[.[{]/)).map((p) => p.slice(0, -2)));
7092
+ }
7093
+ /**
7094
+ * A patch value for a map of secrets: an entry that is omitted, `''`, the redaction token or the
7095
+ * view the form was given KEEPS its stored secret (it is left out of the merge); `{ $secretClear }`
7096
+ * or `null` removes the entry; any other string replaces it. Null when nothing is left to merge.
7097
+ */
7098
+ function secretMapPatch(value) {
7099
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
7100
+ const out = {};
7101
+ for (const [key, entry] of Object.entries(value)) if (entry === null || isSecretClear(entry)) out[key] = null;
7102
+ else if (typeof entry === "string" && entry !== "" && entry !== "__camstack_redacted__" && !isSecretFieldView(entry)) out[key] = entry;
7103
+ return Object.keys(out).length > 0 ? out : null;
7104
+ }
7105
+ var RecordIntegrationInstances = class {
7106
+ records;
7107
+ kind;
7108
+ hooks;
7109
+ handle;
7110
+ secretKeys;
7111
+ secretMaps;
7112
+ nameField;
7113
+ switchListeners = /* @__PURE__ */ new Set();
7114
+ constructor(records, kind, hooks) {
7115
+ this.records = records;
7116
+ this.kind = kind;
7117
+ this.hooks = hooks;
7118
+ this.handle = records.kind(kind);
7119
+ this.secretKeys = topLevelSecretKeys(kind.declaration.secretPaths);
7120
+ this.secretMaps = secretMapKeys(kind.declaration.secretPaths);
7121
+ this.nameField = kind.declaration.entry?.nameField ?? "name";
7122
+ }
7123
+ /**
7124
+ * One instance read for the addon's own runtime; null when absent. When the keychain is
7125
+ * locked the row is served WITHOUT its secrets and says so (`secrets: 'unavailable'`), so the
7126
+ * caller can keep what it had instead of reconfiguring with an empty secret (D49).
7127
+ */
7128
+ async readResolved(id) {
7129
+ try {
7130
+ const record = await this.handle.getResolved(id);
7131
+ return record === null ? null : {
7132
+ id,
7133
+ body: record.data,
7134
+ enabled: isInstanceEnabled(record.data),
7135
+ secrets: "resolved"
7136
+ };
7137
+ } catch (err) {
7138
+ if (!(err instanceof RecordSecretUnavailableError)) throw err;
7139
+ const stored = await this.handle.get(id);
7140
+ if (stored === null) return null;
7141
+ return {
7142
+ id,
7143
+ body: Object.fromEntries(Object.entries(stored.data).filter(([key]) => !this.secretKeys.has(key))),
7144
+ enabled: isInstanceEnabled(stored.data),
7145
+ secrets: "unavailable"
7146
+ };
7147
+ }
7148
+ }
7149
+ /** The body of {@link readResolved} alone; a locked keychain yields the row without secrets. */
7150
+ async getResolved(id) {
7151
+ return (await this.readResolved(id))?.body ?? null;
7152
+ }
7153
+ /** Every instance, secrets resolved where the keychain allows; an absent one is skipped. */
7154
+ async listResolved() {
7155
+ const page = await this.handle.query({ limit: INSTANCES_LIST_MAX });
7156
+ const out = [];
7157
+ for (const record of page.records) {
7158
+ const read = await this.readResolved(record.id);
7159
+ if (read !== null) out.push(read);
7160
+ }
7161
+ return out;
7162
+ }
7163
+ viewOf(record) {
7164
+ const shown = secretViewsOf(this.records.owner, this.kind.name, record.id, this.kind.declaration, record.data);
7165
+ const rawName = record.data[this.nameField];
7166
+ const kind = this.hooks.kindOf?.(record.data);
7167
+ const health = this.hooks.health?.(record.data, record.id);
7168
+ return {
7169
+ id: record.id,
7170
+ name: typeof rawName === "string" ? rawName : record.id,
7171
+ configured: this.hooks.configured(record.data),
7172
+ enabled: isInstanceEnabled(record.data),
7173
+ formValues: shown,
7174
+ ...kind !== void 0 ? { kind } : {},
7175
+ ...health?.status !== void 0 ? { status: health.status } : {},
7176
+ ...health?.lastCheckedAt !== void 0 ? { lastCheckedAt: health.lastCheckedAt } : {}
7177
+ };
7178
+ }
7179
+ describe = async () => {
7180
+ const declared = linksOfKind(this.kind);
7181
+ const links = this.hooks.description.links !== void 0 || declared.length === 0 ? {} : { links: declared.map((link) => ({
7182
+ kind: this.kind.name,
7183
+ field: link.field,
7184
+ to: link.to
7185
+ })) };
7186
+ return {
7187
+ ...this.hooks.description,
7188
+ ...links,
7189
+ ...this.hooks.mintId === void 0 ? {} : { mintsId: true }
7190
+ };
7191
+ };
7192
+ instanceFormSchema = async ({ id }) => this.hooks.formSchema(id);
7193
+ listInstances = async () => {
7194
+ return (await this.handle.query({ limit: INSTANCES_LIST_MAX })).records.map((record) => this.viewOf(record));
7195
+ };
7196
+ getInstance = async ({ id }) => {
7197
+ const record = await this.handle.get(id);
7198
+ return record === null ? null : this.viewOf(record);
7199
+ };
7200
+ /** Insert ONE row (`ifRev: 0`: an existing id is refused, never overwritten). */
7201
+ createInstance = async ({ id, name, kind, values }) => {
7202
+ const minted = id ?? this.hooks.mintId?.({
7203
+ name,
7204
+ ...kind !== void 0 ? { kind } : {}
7205
+ });
7206
+ if (minted === void 0) throw new Error("createInstance needs an id: this provider does not mint one");
7207
+ await this.handle.put({
7208
+ id: minted,
7209
+ data: this.hooks.initialBody(name, kind)
7210
+ }, { ifRev: 0 });
7211
+ const patch = this.patchOf(values ?? {});
7212
+ if (Object.keys(patch).length > 0) await this.handle.patch(minted, patch);
7213
+ await this.hooks.onChanged?.(minted, "created");
7214
+ return { id: minted };
7215
+ };
7216
+ updateInstance = async ({ id, name, values }) => {
7217
+ const patch = this.patchOf(values);
7218
+ if (name !== void 0) patch[this.nameField] = name;
7219
+ await this.handle.patch(id, patch);
7220
+ await this.hooks.onChanged?.(id, "updated");
7221
+ return { ok: true };
7222
+ };
7223
+ /** The record patch a form `values` object means: secrets kept, cleared or replaced. */
7224
+ patchOf(values) {
7225
+ const patch = {};
7226
+ for (const [key, value] of Object.entries(values)) {
7227
+ if (value === void 0) continue;
7228
+ if (key === "enabled") continue;
7229
+ if (this.secretMaps.has(key)) {
7230
+ const entries = secretMapPatch(value);
7231
+ if (entries !== null) patch[key] = entries;
7232
+ } else if (!this.secretKeys.has(key)) patch[key] = value;
7233
+ else if (isSecretClear(value)) patch[key] = null;
7234
+ else if (typeof value === "string" && value !== "" && value !== "__camstack_redacted__" && !isSecretFieldView(value)) patch[key] = value;
7235
+ }
7236
+ return patch;
7237
+ }
7238
+ /**
7239
+ * Listen to the switch of ANY instance of this helper (in the process that serves it). The
7240
+ * durable replacement of the `integration.enabled` / `integration.disabled` events (D8): the
7241
+ * addon reconciles from the record, whichever way it flipped.
7242
+ */
7243
+ onSwitched(listener) {
7244
+ this.switchListeners.add(listener);
7245
+ }
7246
+ /**
7247
+ * The ONE writer of the switch (D996, D1014): the record body's `enabled`, for every role. A
7248
+ * configured thing is an instance, so an id with no record yet (a default integration that was
7249
+ * never configured) gets its record from `initialBody` before the switch is written.
7250
+ */
7251
+ setInstanceEnabled = async ({ id, enabled }) => {
7252
+ if (await this.handle.get(id) === null) await this.handle.put({
7253
+ id,
7254
+ data: this.hooks.initialBody(id)
7255
+ }, { ifRev: 0 });
7256
+ await this.handle.patch(id, { [SWITCH_KEY]: enabled });
7257
+ await this.hooks.onChanged?.(id, "enabled");
7258
+ for (const listener of this.switchListeners) await listener(id, enabled);
7259
+ return { ok: true };
7260
+ };
7261
+ /** The row and its keychain refs go together (the records door). */
7262
+ deleteInstance = async ({ id }) => {
7263
+ await this.handle.delete(id);
7264
+ await this.hooks.onChanged?.(id, "deleted");
7265
+ return { ok: true };
7266
+ };
7267
+ testInstance = async (input) => {
7268
+ if (this.hooks.test === void 0) return {
7269
+ success: false,
7270
+ status: "unsupported",
7271
+ error: "This integration declares no connection test"
7272
+ };
7273
+ return this.hooks.test(input);
7274
+ };
7275
+ /** The flat provider object to hand to `registerProvider`. */
7276
+ toProvider() {
7277
+ return {
7278
+ describe: this.describe,
7279
+ instanceFormSchema: this.instanceFormSchema,
7280
+ listInstances: this.listInstances,
7281
+ getInstance: this.getInstance,
7282
+ createInstance: this.createInstance,
7283
+ updateInstance: this.updateInstance,
7284
+ setInstanceEnabled: this.setInstanceEnabled,
7285
+ deleteInstance: this.deleteInstance,
7286
+ testInstance: this.testInstance
7287
+ };
7288
+ }
7289
+ };
7290
+ /**
7291
+ * The one-switch migration (epic #440, step 3). An integration's on/off state used to live in the
7292
+ * registry's `enabled` column for a device addon; it now lives only in the instance record's
7293
+ * body (`enabled`, D1007 superseded). This moves a registry `enabled = false` into the body, once.
7294
+ *
7295
+ * For every registry row of the addon that is OFF:
7296
+ * - no record under its id: the record is created from `initialBody(name)` with `enabled: false`
7297
+ * (a default integration that never had settings, Reolink's among them);
7298
+ * - a record whose body states no `enabled`: `enabled: false` is written into it;
7299
+ * - a record that already states `enabled` (either way) is the newer truth and is left alone.
7300
+ * A row that is ON writes nothing: an absent field reads as on. A rerun finds every off row with
7301
+ * a stated switch and does nothing, so nothing switched off comes back on and nothing switched on
7302
+ * goes off. The registry column itself is neither read afterwards nor written; its drop is step 5.
7303
+ *
7304
+ * It runs in the addon process, BEFORE the addon registers its `integration-instances` provider,
7305
+ * which is also why `integrations.list` still answers the stored column at that point.
7306
+ */
7307
+ function registrySwitchToBodyId(addonId, date) {
7308
+ return `${addonId}/${date}-registry-switch-to-body`;
7309
+ }
7310
+ async function moveRegistrySwitchToBody(ports, spec) {
7311
+ const rows = await ports.listIntegrations(spec.addonId);
7312
+ let created = 0;
7313
+ let switched = 0;
7314
+ let kept = 0;
7315
+ for (const row of rows) {
7316
+ if (row.enabled) continue;
7317
+ const body = await ports.readBody(row.id);
7318
+ if (body === null) {
7319
+ if (await ports.createRecord(row.id, {
7320
+ ...spec.initialBody(row.name),
7321
+ ["enabled"]: false
7322
+ }) === "created") created += 1;
7323
+ else kept += 1;
7324
+ continue;
7325
+ }
7326
+ if ("enabled" in body) {
7327
+ kept += 1;
7328
+ continue;
7329
+ }
7330
+ await ports.switchOff(row.id);
7331
+ switched += 1;
7332
+ }
7333
+ const summary = {
7334
+ integrations: rows.length,
7335
+ off: rows.filter((r) => !r.enabled).length,
7336
+ created,
7337
+ switched,
7338
+ kept
7339
+ };
7340
+ return created === 0 && switched === 0 ? {
7341
+ outcome: "already-done",
7342
+ summary
7343
+ } : {
7344
+ outcome: "done",
7345
+ summary
7346
+ };
7347
+ }
7348
+ /** A migration entry: an addon states its kind and how a new body starts, nothing else. */
7349
+ function registrySwitchToBodyMigration(spec) {
7350
+ return {
7351
+ meta: {
7352
+ id: registrySwitchToBodyId(spec.addonId, spec.date),
7353
+ owner: spec.addonId,
7354
+ level: "addon-state",
7355
+ seq: spec.seq,
7356
+ dependsOn: [],
7357
+ store: "settings",
7358
+ scope: "cluster",
7359
+ onFailure: "block-owner",
7360
+ bodyKind: "procedure",
7361
+ description: "Move the registry enabled flag of every switched-off integration into its instance record body, creating the record when there is none",
7362
+ fixtureMark: "enabled"
7363
+ },
7364
+ procedure: (ports) => moveRegistrySwitchToBody(ports, {
7365
+ addonId: spec.addonId,
7366
+ initialBody: spec.initialBody
7367
+ })
7368
+ };
7369
+ }
7370
+ /** The hub and records sides of {@link registrySwitchToBodyMigration}. */
7371
+ function registrySwitchPortsOver(deps) {
7372
+ const handle = deps.records.kind({
7373
+ name: deps.kind.name,
7374
+ declaration: deps.kind.declaration,
7375
+ schema: record(string(), unknown())
7376
+ });
7377
+ return {
7378
+ listIntegrations: async (addonId) => (await deps.api.list()).filter((i) => i.addonId === addonId).map((i) => ({
7379
+ id: i.id,
7380
+ name: i.name,
7381
+ enabled: i.enabled !== false
7382
+ })),
7383
+ readBody: async (id) => (await handle.get(id))?.data ?? null,
7384
+ createRecord: async (id, body) => {
7385
+ if (await handle.get(id) !== null) return "exists";
7386
+ await handle.put({
7387
+ id,
7388
+ data: body
7389
+ }, { ifRev: 0 });
7390
+ return "created";
7391
+ },
7392
+ switchOff: async (id) => {
7393
+ await handle.patch(id, { [SWITCH_KEY]: false });
7394
+ }
7395
+ };
7396
+ }
7397
+ /**
7398
+ * Build a {@link DurableState} over a single store key. Transport-agnostic:
7399
+ * `read`/`write` are the addon-store or device-store accessors. The whole
7400
+ * validated value round-trips on every read/write — the schema is the
7401
+ * single source of truth for what is persisted, so no hand-listed field
7402
+ * set can drop a key on save.
7403
+ */
7404
+ function createDurableState(deps) {
7405
+ const get = async () => {
7406
+ const raw = (await deps.read())[deps.key];
7407
+ if (raw === void 0) return deps.fallback;
7408
+ const parsed = deps.schema.safeParse(raw);
7409
+ if (!parsed.success) {
7410
+ deps.onParseError?.(deps.key, parsed.error);
7411
+ return deps.fallback;
7412
+ }
7413
+ return parsed.data;
7414
+ };
7415
+ const set = async (next) => {
7416
+ const validated = deps.schema.parse(next);
7417
+ await deps.write({ [deps.key]: validated });
7418
+ };
7419
+ const update = async (fn) => {
7420
+ await set(fn(await get()));
7421
+ };
7422
+ return {
7423
+ get,
7424
+ set,
7425
+ update
7426
+ };
7427
+ }
7428
+ /**
7429
+ * Per-node scoping for the shared addon-settings blob.
7430
+ *
7431
+ * An addon's settings store is hub-central (the `addon-settings` cap is
7432
+ * hub-routed — the hub instance answers for every node), so fields whose
7433
+ * value is a NODE fact (decoder backend, engine pick, probed hardware
7434
+ * capabilities) persist under the node-scoped key `<key>@<nodeId>` inside
7435
+ * the single shared blob. The SCHEMA field key stays bare: the write path
7436
+ * ({@link scopePatch}) maps the bare field onto the target node's scoped
7437
+ * key; the read/hydrate path ({@link projectStore}) maps THIS node's value
7438
+ * back, so UI forms and `resolveConfig` only ever see the bare key.
7439
+ *
7440
+ * Fields opt in via the `perNode: true` schema marker on `ConfigFieldBase`
7441
+ * (`interfaces/config-ui.ts`); `BaseAddon` derives the key set from the
7442
+ * schema and routes reads/writes through these helpers.
7443
+ *
7444
+ * ## No bare-key fallback — deliberate
7445
+ *
7446
+ * {@link readNodeValue} reads the node-scoped key ONLY. A node with no
7447
+ * scoped key resolves to `undefined` so the field's schema `default` wins —
7448
+ * NEVER `store[base]` and never another node's value. A bare legacy key in
7449
+ * the store is invisible to every node, hub included, so one node's
7450
+ * selection can never leak onto another. (This generalizes the
7451
+ * `decoder-backend-keys.ts` semantics — the no-fallback variant — over an
7452
+ * arbitrary set of per-node field keys.)
7453
+ *
7454
+ * Pure functions only — no I/O, no imports beyond the language. This is a
7455
+ * LEAF module: import it via its deep path, never from the root barrel.
7456
+ */
7457
+ /**
7458
+ * Normalize a raw kernel node id to the bare node id used for scoping.
7459
+ * `localNodeId` can carry a `<node>/<addon>` suffix on forked child
7460
+ * processes; per-node settings are per-NODE, so strip the addon segment.
7461
+ * `undefined` / `null` / empty falls back to `'hub'`.
7462
+ */
7463
+ function normalizeNodeId(raw) {
7464
+ if (raw === void 0 || raw === null || raw === "") return "hub";
7465
+ const slashIdx = raw.indexOf("/");
7466
+ if (slashIdx < 0) return raw;
7467
+ const bare = raw.slice(0, slashIdx);
7468
+ return bare === "" ? "hub" : bare;
7469
+ }
7470
+ /** The node-scoped store key for a per-node field: `<base>@<nodeId>`. */
7471
+ function nodeScopedKey(base, nodeId) {
7472
+ return `${base}@${normalizeNodeId(nodeId)}`;
7473
+ }
7474
+ /**
7475
+ * Read a node's value for a per-node field from the raw shared store:
7476
+ * the node-scoped key when present, otherwise `undefined`.
7477
+ * Deliberately NO bare-key fallback (see module doc) — the caller lets the
7478
+ * schema `default` win on `undefined`.
7479
+ */
7480
+ function readNodeValue(store, base, nodeId) {
7481
+ return store[nodeScopedKey(base, nodeId)];
7482
+ }
7483
+ /**
7484
+ * Re-map a UI/settings patch so every bare perNode field persists under the
7485
+ * TARGET node's scoped key; all other keys pass through unchanged. Used on
7486
+ * the write path so a save for one node never clobbers another node's value
7487
+ * (and the bare key is never written). Returns a new object — the input
7488
+ * patch is not mutated.
7489
+ */
7490
+ function scopePatch(patch, perNodeKeys, nodeId) {
7491
+ const out = {};
7492
+ for (const [key, value] of Object.entries(patch)) out[perNodeKeys.has(key) ? nodeScopedKey(key, nodeId) : key] = value;
7493
+ return out;
7494
+ }
7495
+ /**
7496
+ * Project the raw shared store onto the bare schema keys for ONE node so a
7497
+ * UI schema (whose field keys are bare) hydrates from that node's own
7498
+ * values:
7499
+ *
7500
+ * - EVERY `@`-scoped key (any node's) is dropped from the pass-through.
7501
+ * - Every bare perNode key is dropped from the pass-through (a stray bare
7502
+ * legacy key must never hydrate any node — no bare fallback).
7503
+ * - THIS node's effective value ({@link readNodeValue}) is then laid onto
7504
+ * each bare perNode key; when the node has no scoped key the bare key is
7505
+ * left ABSENT so the field's schema `default` wins.
7506
+ *
7507
+ * Returns a new object — the input store is not mutated.
7508
+ */
7509
+ function projectStore(store, perNodeKeys, nodeId) {
7510
+ const out = {};
7511
+ for (const [key, value] of Object.entries(store)) {
7512
+ if (key.includes("@")) continue;
7513
+ if (perNodeKeys.has(key)) continue;
7514
+ out[key] = value;
7515
+ }
7516
+ for (const base of perNodeKeys) {
7517
+ const value = readNodeValue(store, base, nodeId);
7518
+ if (value !== void 0) out[base] = value;
7519
+ }
7520
+ return out;
7521
+ }
7522
+ /** Every scope, in the order the guard and the docs list them. */
7523
+ var SCOPED_SETTINGS_SCOPES = [
7524
+ "cluster",
7525
+ "device-defaults",
7526
+ "node"
7527
+ ];
6933
7528
  /** A write to a secret path could not be stored in the keychain, so it was refused. */
6934
7529
  var KeychainWriteRefusedError = class extends Error {
6935
7530
  fieldPath;
@@ -6940,7 +7535,7 @@ var KeychainWriteRefusedError = class extends Error {
6940
7535
  }
6941
7536
  };
6942
7537
  var KEEP = { kind: "keep" };
6943
- function isRecord$6(value) {
7538
+ function isRecord$4(value) {
6944
7539
  return typeof value === "object" && value !== null && !Array.isArray(value);
6945
7540
  }
6946
7541
  function defaultMintId() {
@@ -6953,7 +7548,7 @@ function collectSecretMarkerRefs(value, out = []) {
6953
7548
  return out;
6954
7549
  }
6955
7550
  if (Array.isArray(value)) for (const item of value) collectSecretMarkerRefs(item, out);
6956
- else if (isRecord$6(value)) for (const child of Object.values(value)) collectSecretMarkerRefs(child, out);
7551
+ else if (isRecord$4(value)) for (const child of Object.values(value)) collectSecretMarkerRefs(child, out);
6957
7552
  return out;
6958
7553
  }
6959
7554
  async function storedValueEquals(secrets, marker, candidate) {
@@ -7008,7 +7603,7 @@ function rowId(row, idKey) {
7008
7603
  return null;
7009
7604
  }
7010
7605
  async function writeArray(ctx, node, incoming, stored, fieldPath) {
7011
- const storedRows = Array.isArray(stored) ? stored.filter(isRecord$6) : [];
7606
+ const storedRows = Array.isArray(stored) ? stored.filter(isRecord$4) : [];
7012
7607
  if (!Array.isArray(incoming)) {
7013
7608
  ctx.deletes.push(...collectSecretMarkerRefs(storedRows));
7014
7609
  return {
@@ -7024,7 +7619,7 @@ async function writeArray(ctx, node, incoming, stored, fieldPath) {
7024
7619
  const kept = /* @__PURE__ */ new Set();
7025
7620
  const rows = [];
7026
7621
  for (const row of incoming) {
7027
- if (!isRecord$6(row)) {
7622
+ if (!isRecord$4(row)) {
7028
7623
  rows.push(row);
7029
7624
  continue;
7030
7625
  }
@@ -7049,7 +7644,7 @@ async function writeNode(ctx, node, incoming, stored, fieldPath) {
7049
7644
  case "leaf": return writeLeaf(ctx, incoming, stored, fieldPath);
7050
7645
  case "array": return writeArray(ctx, node, incoming, stored, fieldPath);
7051
7646
  case "object": {
7052
- if (!isRecord$6(incoming)) {
7647
+ if (!isRecord$4(incoming)) {
7053
7648
  if (incoming === void 0) return KEEP;
7054
7649
  ctx.deletes.push(...collectSecretMarkerRefs(stored));
7055
7650
  return {
@@ -7057,7 +7652,7 @@ async function writeNode(ctx, node, incoming, stored, fieldPath) {
7057
7652
  value: incoming
7058
7653
  };
7059
7654
  }
7060
- const storedObj = isRecord$6(stored) ? stored : {};
7655
+ const storedObj = isRecord$4(stored) ? stored : {};
7061
7656
  return {
7062
7657
  kind: "value",
7063
7658
  value: await writeMembers(ctx, node.children, incoming, storedObj, (m) => `${fieldPath}.${m}`)
@@ -7180,7 +7775,7 @@ async function resolveSecretMarkers(value, secrets, options = {}) {
7180
7775
  value: items
7181
7776
  };
7182
7777
  }
7183
- if (isRecord$6(v)) {
7778
+ if (isRecord$4(v)) {
7184
7779
  const out = {};
7185
7780
  for (const [k, child] of Object.entries(v)) {
7186
7781
  const s = substitute(child);
@@ -7212,7 +7807,7 @@ var SecretOverwriteRefusedError = class extends Error {
7212
7807
  this.name = "SecretOverwriteRefusedError";
7213
7808
  }
7214
7809
  };
7215
- function isRecord$5(value) {
7810
+ function isRecord$3(value) {
7216
7811
  return typeof value === "object" && value !== null && !Array.isArray(value);
7217
7812
  }
7218
7813
  function resolvedValue(pass, marker) {
@@ -7241,7 +7836,7 @@ function inArray(pass, incoming, stored) {
7241
7836
  return incoming.map((item, index) => {
7242
7837
  const twin = stored[index];
7243
7838
  if (isSecretMarker(twin)) return typeof item === "string" && item === resolvedValue(pass, twin) ? twin : item;
7244
- if (isRecord$5(item) && isRecord$5(twin)) return inArrayRow(pass, item, twin);
7839
+ if (isRecord$3(item) && isRecord$3(twin)) return inArrayRow(pass, item, twin);
7245
7840
  if (Array.isArray(item) && Array.isArray(twin)) return inArray(pass, item, twin);
7246
7841
  return item;
7247
7842
  });
@@ -7252,7 +7847,7 @@ function inArrayRow(pass, incoming, stored) {
7252
7847
  const twin = stored[key];
7253
7848
  if (isSecretMarker(twin)) {
7254
7849
  if (typeof value === "string" && value === resolvedValue(pass, twin)) out[key] = twin;
7255
- } else if (isRecord$5(value) && isRecord$5(twin)) out[key] = inArrayRow(pass, value, twin);
7850
+ } else if (isRecord$3(value) && isRecord$3(twin)) out[key] = inArrayRow(pass, value, twin);
7256
7851
  else if (Array.isArray(value) && Array.isArray(twin)) out[key] = inArray(pass, value, twin);
7257
7852
  }
7258
7853
  return out;
@@ -7260,7 +7855,7 @@ function inArrayRow(pass, incoming, stored) {
7260
7855
  async function walk(pass, incoming, stored) {
7261
7856
  if (isSecretMarker(stored)) return atMarker(pass, incoming, stored);
7262
7857
  if (Array.isArray(incoming) && Array.isArray(stored)) return inArray(pass, incoming, stored);
7263
- if (!isRecord$5(incoming) || !isRecord$5(stored)) return incoming;
7858
+ if (!isRecord$3(incoming) || !isRecord$3(stored)) return incoming;
7264
7859
  const out = { ...incoming };
7265
7860
  for (const [key, value] of Object.entries(incoming)) out[key] = await walk(pass, value, stored[key]);
7266
7861
  return out;
@@ -7291,7 +7886,7 @@ async function restoreUnchangedSecrets(input) {
7291
7886
  function isJsonEqual(a, b) {
7292
7887
  if (Object.is(a, b)) return true;
7293
7888
  if (Array.isArray(a)) return Array.isArray(b) && a.length === b.length && a.every((v, i) => isJsonEqual(v, b[i]));
7294
- if (isRecord$5(a) && isRecord$5(b)) {
7889
+ if (isRecord$3(a) && isRecord$3(b)) {
7295
7890
  const keys = Object.keys(a);
7296
7891
  if (keys.length !== Object.keys(b).length) return false;
7297
7892
  return keys.every((k) => Object.prototype.hasOwnProperty.call(b, k) && isJsonEqual(a[k], b[k]));
@@ -7315,7 +7910,7 @@ function markerKeysOf(blob, owner) {
7315
7910
  }
7316
7911
  function nodeFromStored(value, owner) {
7317
7912
  if (isSecretMarker(value)) return isSecretRefOwnedBy(value.$secret, owner) ? { kind: "leaf" } : null;
7318
- if (!isRecord$5(value)) return null;
7913
+ if (!isRecord$3(value)) return null;
7319
7914
  const children = /* @__PURE__ */ new Map();
7320
7915
  for (const [key, child] of Object.entries(value)) {
7321
7916
  const node = nodeFromStored(child, owner);
@@ -7812,13 +8407,48 @@ var BaseAddon = class {
7812
8407
  if (api === void 0) throw new Error(`${this.ctx.id}: the migration API is not available on this context`);
7813
8408
  return this.runBound(sets.flatMap((set) => set.bind(api)), options);
7814
8409
  }
7815
- async runBound(migrations, options) {
8410
+ /**
8411
+ * A device addon states its instance kind once, before its migrations run, and the one-switch
8412
+ * migration (registry `enabled` to the instance body, epic #440 step 3) joins whatever
8413
+ * catalogue the addon runs, in the SAME declaration (the engine replaces an owner's catalogue
8414
+ * on every declare).
8415
+ */
8416
+ declareRegistrySwitch(spec) {
8417
+ this.registrySwitchSpec = spec;
8418
+ }
8419
+ registrySwitchSpec = null;
8420
+ registrySwitchBound() {
8421
+ const spec = this.registrySwitchSpec;
8422
+ if (spec === null) return [];
8423
+ const api = this.ctx.migrationApi;
8424
+ if (api === void 0) {
8425
+ this.ctx.logger.warn("the registry switch migration is skipped: the migration API is not available on this context");
8426
+ return [];
8427
+ }
8428
+ return migrationSet([registrySwitchToBodyMigration({
8429
+ addonId: this.ctx.id,
8430
+ date: "2026-11-06",
8431
+ seq: 1e3,
8432
+ initialBody: spec.initialBody
8433
+ })], (a) => registrySwitchPortsOver({
8434
+ api: integrationRowsApiOver(a),
8435
+ records: switchRecordsOverMigrationApi(a),
8436
+ kind: spec.kind
8437
+ })).bind(api);
8438
+ }
8439
+ async runBound(declared, options) {
8440
+ const added = this.registrySwitchBound();
8441
+ const migrations = [...declared, ...added];
8442
+ const phased = options?.only === void 0 || added.length === 0 ? options : {
8443
+ ...options,
8444
+ only: [...options.only, ...added.map((m) => m.meta.id)]
8445
+ };
7816
8446
  const api = this.ctx.api.migrations;
7817
8447
  const report = await runAddonMigrations({
7818
8448
  declareOwner: (input) => api.declareOwner.mutate(input),
7819
8449
  startMigration: (input) => api.startMigration.mutate(input),
7820
8450
  finishMigration: (input) => api.finishMigration.mutate(input)
7821
- }, migrations, this.ctx.logger, options);
8451
+ }, migrations, this.ctx.logger, phased);
7822
8452
  if (report.blockOwner.length > 0) throw new AddonMigrationsBlockedError(report.blockOwner);
7823
8453
  return report;
7824
8454
  }
@@ -8891,245 +9521,94 @@ function normalizeAddonInitResult(result) {
8891
9521
  if (Array.isArray(result)) return { providers: result };
8892
9522
  return result;
8893
9523
  }
8894
- var PREFIX = "records/";
8895
- /** The base of every records failure. `detail` is the human part of the message. */
8896
- var RecordsError = class extends Error {
8897
- code;
8898
- detail;
8899
- constructor(code, detail) {
8900
- super(`${PREFIX}${code}: ${detail}`);
8901
- this.name = "RecordsError";
8902
- this.code = code;
8903
- this.detail = detail;
8904
- }
8905
- };
8906
- /** The keychain could not store or serve a value: explicit, never an empty string. */
8907
- var RecordSecretUnavailableError = class extends RecordsError {
8908
- constructor(detail) {
8909
- super("secret-unavailable", detail);
8910
- this.name = "RecordSecretUnavailableError";
8911
- }
8912
- };
8913
- var InvalidRecordError = class extends RecordsError {
8914
- constructor(detail) {
8915
- super("invalid-record", detail);
8916
- this.name = "InvalidRecordError";
8917
- }
8918
- };
8919
- /** A kind declaration the engine refuses (non-additive change, bad shape, wrong file). */
8920
- var DeclarationRefusedError = class extends RecordsError {
8921
- constructor(detail) {
8922
- super("declaration-refused", detail);
8923
- this.name = "DeclarationRefusedError";
8924
- }
8925
- };
8926
- /** Limits and names of `ctx.records` (D881). One authority; the engine and the facade read it. */
8927
- /** The files a kind may live in. `history` is device-history's (D850), never records. */
8928
- var RECORD_DATABASES = ["settings", "events"];
8929
- /** The classes of a kind: the `@durable` vocabulary, one authority (replaces the annotation). */
8930
- var RECORD_CLASSES = [
8931
- "config",
8932
- "ledger",
8933
- "audit",
8934
- "mirror",
8935
- "ephemeral"
8936
- ];
8937
- var RECORD_DEFAULT_MAX_DATA_BYTES = 64 * 1024;
8938
- var RECORD_MAX_DATA_BYTES = 1024 * 1024;
8939
- var RECORD_BATCH_MAX = 1e3;
8940
- var RECORD_QUERY_MAX = 1e3;
8941
- /** A kind in the `settings` file may not bound itself above this (D447: high volume is `events`). */
8942
- var RECORD_SETTINGS_MAX_ROWS = 5e4;
8943
- /** The `Column`-free proof prefix: a ref collection for a kind's secret fields. */
8944
- var RECORD_SECRET_COLLECTION_PREFIX = "records:";
9524
+ object({
9525
+ field: string().min(1),
9526
+ on: literal("advance")
9527
+ });
8945
9528
  /**
8946
- * Secret fields of a record, addressed the way a Zod schema declares them
8947
- * (`collectZodSecretPaths`): dotted keys, `[]` for "each element of this array"
8948
- * (`auth.accessToken`, `headers[].value`).
8949
- *
8950
- * `{}` after a key means "each value of this map" (`applianceSecrets{}`): the map's own key
8951
- * names the value (`applianceSecrets{fridge}`), so no id key is declared and a body that drops a
8952
- * key releases exactly that key's secret.
9529
+ * Output schema shared by the contribution + live methods.
8953
9530
  *
8954
- * Array elements are matched by a DECLARED id key (`secretArrayKeys`:
8955
- * `{ headers: 'name' }`), never by index, so reordering a list keeps every
8956
- * keychain ref (the same rule as `arrayItemFieldPath`). The concrete path of a
8957
- * leaf names its element: `headers[X-Api].value`.
9531
+ * Mirrors the `ConfigUISchemaWithValues` shape (sections[] + optional
9532
+ * tabs[]) without importing from `../interfaces/config-ui.js` — a
9533
+ * concrete-but-lenient Zod object keeps tRPC output inference happy
9534
+ * (using `z.unknown()` here collapses unrelated router branches to
9535
+ * `unknown` when the generator re-inlines the huge AppRouter type).
8958
9536
  *
8959
- * Pure and browser-safe. Nothing here mutates: every transform returns a new value.
8960
- */
8961
- /** The array prefixes (declared form, e.g. `headers` or `a.headers`) of a path. */
8962
- function parseSecretPath(path) {
8963
- if (path.length === 0) throw new InvalidRecordError("an empty secret path");
8964
- return path.split(".").map((raw) => {
8965
- const each = raw.endsWith("[]");
8966
- const map = raw.endsWith("{}");
8967
- const key = each || map ? raw.slice(0, -2) : raw;
8968
- if (key.length === 0) throw new InvalidRecordError(`secret path "${path}" has an empty segment`);
8969
- return {
8970
- key,
8971
- each,
8972
- map
8973
- };
8974
- });
8975
- }
8976
- /** The declared array prefixes of `path` that need an id key (`headers`, `a.rows`). */
8977
- function secretArrayPrefixes(path) {
8978
- const segments = parseSecretPath(path);
8979
- const prefixes = [];
8980
- const walked = [];
8981
- for (const segment of segments) {
8982
- walked.push(segment.key);
8983
- if (segment.each) prefixes.push(walked.join("."));
8984
- }
8985
- return prefixes;
8986
- }
8987
- function isRecord$4(value) {
8988
- return typeof value === "object" && value !== null && !Array.isArray(value);
8989
- }
8990
- function elementId(element, idKey, declared, prefix) {
8991
- const id = isRecord$4(element) ? element[idKey] : void 0;
8992
- 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`);
8993
- return id;
8994
- }
8995
- /**
8996
- * Visit every secret leaf PRESENT in `data` (an absent branch has nothing to
8997
- * visit). `replace` returns the new leaf value, or {@link REMOVE_LEAF}; the
8998
- * result is a new body, `data` is untouched.
9537
+ * `.passthrough()` on sections/fields accepts whatever FormBuilder
9538
+ * extensions the caller adds (showWhen, displayScale, …) without
9539
+ * rebuilding every time a new field kind is introduced.
8999
9540
  */
9000
- var REMOVE_LEAF = Symbol("remove-leaf");
9001
- function mapAt(node, segments, index, walkedKeys, concretePrefix, declared, arrayKeys, visit) {
9002
- if (!isRecord$4(node)) return node;
9003
- const segment = segments[index];
9004
- if (segment === void 0) return node;
9005
- if (!Object.prototype.hasOwnProperty.call(node, segment.key)) return node;
9006
- const child = node[segment.key];
9007
- const keys = [...walkedKeys, segment.key];
9008
- const last = index === segments.length - 1;
9009
- if (segment.each) {
9010
- if (!Array.isArray(child)) return node;
9011
- const prefix = keys.join(".");
9012
- const idKey = arrayKeys[prefix];
9013
- if (idKey === void 0) throw new InvalidRecordError(`"${declared}": no id key declared for the array "${prefix}"`);
9014
- const mapped = child.map((element) => {
9015
- const id = elementId(element, idKey, declared, prefix);
9016
- const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}[${encodeURIComponent(id)}]`;
9017
- return last ? element : mapAt(element, segments, index + 1, keys, concrete, declared, arrayKeys, visit);
9018
- });
9019
- return {
9020
- ...node,
9021
- [segment.key]: mapped
9022
- };
9023
- }
9024
- if (segment.map) {
9025
- if (!isRecord$4(child)) return node;
9026
- const kept = Object.entries(child).map(([mapKey, value]) => {
9027
- const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}{${encodeURIComponent(mapKey)}}`;
9028
- if (!last) return [mapKey, mapAt(value, segments, index + 1, keys, concrete, declared, arrayKeys, visit)];
9029
- return [mapKey, visit({
9030
- declared,
9031
- concrete,
9032
- value
9033
- })];
9034
- }).filter(([, value]) => value !== REMOVE_LEAF);
9035
- return {
9036
- ...node,
9037
- [segment.key]: Object.fromEntries(kept)
9038
- };
9039
- }
9040
- const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}`;
9041
- if (last) {
9042
- const replacement = visit({
9043
- declared,
9044
- concrete,
9045
- value: child
9046
- });
9047
- if (replacement === REMOVE_LEAF) return Object.fromEntries(Object.entries(node).filter(([key]) => key !== segment.key));
9048
- return {
9049
- ...node,
9050
- [segment.key]: replacement
9051
- };
9052
- }
9541
+ var ContributionSectionSchema = object({
9542
+ id: string(),
9543
+ title: string(),
9544
+ description: string().optional(),
9545
+ style: _enum(["card", "accordion"]).optional(),
9546
+ defaultCollapsed: boolean().optional(),
9547
+ columns: union([
9548
+ literal(1),
9549
+ literal(2),
9550
+ literal(3),
9551
+ literal(4)
9552
+ ]).optional(),
9553
+ tab: string().optional(),
9554
+ location: _enum([
9555
+ "settings",
9556
+ "top-tab",
9557
+ "hero"
9558
+ ]).optional(),
9559
+ order: number().optional(),
9560
+ fields: array(any())
9561
+ });
9562
+ object({
9563
+ tabs: array(object({
9564
+ id: string(),
9565
+ label: string(),
9566
+ icon: string(),
9567
+ order: number().optional()
9568
+ })).optional(),
9569
+ sections: array(ContributionSectionSchema)
9570
+ }).nullable();
9571
+ object({ deviceId: number() }), object({ deviceId: number() }), object({
9572
+ deviceId: number(),
9573
+ patch: record(string(), unknown())
9574
+ }), object({ success: literal(true) });
9575
+ object({ deviceId: number() }), unknown().nullable();
9576
+ function method(input, output, options) {
9053
9577
  return {
9054
- ...node,
9055
- [segment.key]: mapAt(child, segments, index + 1, keys, concrete, declared, arrayKeys, visit)
9578
+ input,
9579
+ output,
9580
+ kind: options?.kind ?? "query",
9581
+ ...options?.auth !== void 0 ? { auth: options.auth } : {},
9582
+ ...options?.access !== void 0 ? { access: options.access } : {},
9583
+ ...options?.role !== void 0 ? { role: options.role } : {},
9584
+ ...options?.caller !== void 0 ? { caller: options.caller } : {},
9585
+ timeoutMs: options?.timeoutMs
9056
9586
  };
9057
9587
  }
9058
- /** Replace/remove every present secret leaf; returns a NEW body. */
9059
- function mapSecretLeaves(data, paths, arrayKeys, visit) {
9060
- let current = data;
9061
- for (const declared of paths) current = mapAt(current, parseSecretPath(declared), 0, [], "", declared, arrayKeys, visit);
9062
- return current;
9063
- }
9064
9588
  /**
9065
- * The keychain collection name a kind's secrets live under. Prefixed so a
9066
- * record's refs never collide with the refs a legacy collection of the same name
9067
- * already holds during an adoption.
9589
+ * A wrapper/system-only method: served exclusively by the cap's system-level
9590
+ * provider (`InferProvider`), and OPTIONAL on `InferNativeProvider` so per-device
9591
+ * driver natives don't stub out a wrapper concern (e.g. a cross-device cache
9592
+ * overview). The `systemOnly: true` literal is what `InferNativeProvider` keys on.
9068
9593
  */
9069
- function recordSecretCollection(kind) {
9070
- return `${RECORD_SECRET_COLLECTION_PREFIX}${kind}`;
9071
- }
9072
- /** The ONE ref a row's secret field may carry: the engine and the facade both build it here. */
9073
- function recordSecretRef(owner, kind, rowId, concretePath) {
9074
- return buildSecretRef({
9075
- owner,
9076
- scope: {
9077
- kind: "row",
9078
- collection: recordSecretCollection(kind),
9079
- rowId
9080
- },
9081
- fieldPath: concretePath
9082
- });
9594
+ function systemMethod(input, output, options) {
9595
+ return {
9596
+ ...method(input, output, options),
9597
+ systemOnly: true
9598
+ };
9083
9599
  }
9084
9600
  /**
9085
- * A stored secret, as an admin read shows it: a VIEW naming the row's own
9086
- * keychain ref (`set: true`), never the value and no longer the bare redaction
9087
- * token. The form hands it to the secret field, which reveals the value by ref
9088
- * through the audited `keychain-admin.reveal`; sent back untouched it keeps the
9089
- * stored secret (the records door reads a view as KEEP).
9090
- *
9091
- * ONE implementation for the entries service and for every addon that serves
9092
- * its own instances (`RecordIntegrationInstances`).
9601
+ * A method a SOURCE of a collection cap may legitimately not serve — OPTIONAL
9602
+ * on `InferProvider`. The `providerOptional: true` literal is what
9603
+ * `InferProvider` keys on; see {@link CapabilityMethodSchema.providerOptional}
9604
+ * for when this is the honest answer and when it is a soft stub.
9093
9605
  */
9094
- function isRecord$3(value) {
9095
- return typeof value === "object" && value !== null && !Array.isArray(value);
9096
- }
9097
- function secretViewsOf(owner, kind, id, decl, data) {
9098
- if (decl.secretPaths.length === 0) return data;
9099
- const shown = mapSecretLeaves(data, decl.secretPaths, decl.secretArrayKeys, (leaf) => {
9100
- if (leaf.value !== "__camstack_redacted__") return leaf.value;
9101
- return {
9102
- $secret: recordSecretRef(owner, kind, id, leaf.concrete),
9103
- v: 1,
9104
- set: true
9105
- };
9106
- });
9107
- return isRecord$3(shown) ? shown : data;
9606
+ function optionalMethod(input, output, options) {
9607
+ return {
9608
+ ...method(input, output, options),
9609
+ providerOptional: true
9610
+ };
9108
9611
  }
9109
- /**
9110
- * The share-view scope kinds a share-link token can carry. The hub mints
9111
- * and validates them (`ShareViewGrantSchema` builds its
9112
- * enum from this list); a data plane names the kinds it ACCEPTS in `share`.
9113
- */
9114
- var SHARE_VIEW_KINDS = ["grid-view", "events-view"];
9115
- /** The wire shape of {@link PeerBytesTicket} — see the type for what it is. */
9116
- var PeerBytesTicketSchema = object({
9117
- /** `http://127.0.0.1:<port>/<token>`. One `GET` takes it. */
9118
- url: string().min(1),
9119
- /**
9120
- * The HOST node this URL means something on — the hub or a named agent,
9121
- * never a runner. {@link AddonPeerBytes.open} compares it to its own and
9122
- * refuses `cross-node` by name when they differ, without dialling.
9123
- */
9124
- hostNodeId: string().min(1),
9125
- expiresAtMs: number().int().nonnegative(),
9126
- /**
9127
- * What the producer DECLARED the body to be, when it knows — `null` when it
9128
- * does not. Never `0` for unknown (D393): a consumer sizing a bound off this
9129
- * must be able to tell "the producer did not say" from "the body is empty".
9130
- */
9131
- declaredBytes: number().int().nonnegative().nullable()
9132
- });
9133
9612
  function defOf(schema) {
9134
9613
  const zodBag = Reflect.get(schema, "_zod");
9135
9614
  if (typeof zodBag !== "object" || zodBag === null) return {};
@@ -9359,6 +9838,7 @@ function defineRecordKinds(specs) {
9359
9838
  function entryBody(shape) {
9360
9839
  return object({
9361
9840
  name: string().min(1),
9841
+ enabled: boolean().optional(),
9362
9842
  ...shape
9363
9843
  });
9364
9844
  }
@@ -9385,94 +9865,30 @@ function defineEntryKind(name, spec) {
9385
9865
  if (defined === void 0) throw new DeclarationRefusedError(`entry kind "${name}" was not built`);
9386
9866
  return defined;
9387
9867
  }
9388
- object({
9389
- field: string().min(1),
9390
- on: literal("advance")
9391
- });
9392
9868
  /**
9393
- * Output schema shared by the contribution + live methods.
9394
- *
9395
- * Mirrors the `ConfigUISchemaWithValues` shape (sections[] + optional
9396
- * tabs[]) without importing from `../interfaces/config-ui.js` — a
9397
- * concrete-but-lenient Zod object keeps tRPC output inference happy
9398
- * (using `z.unknown()` here collapses unrelated router branches to
9399
- * `unknown` when the generator re-inlines the huge AppRouter type).
9400
- *
9401
- * `.passthrough()` on sections/fields accepts whatever FormBuilder
9402
- * extensions the caller adds (showWhen, displayScale, …) without
9403
- * rebuilding every time a new field kind is introduced.
9869
+ * The share-view scope kinds a share-link token can carry. The hub mints
9870
+ * and validates them (`ShareViewGrantSchema` builds its
9871
+ * enum from this list); a data plane names the kinds it ACCEPTS in `share`.
9404
9872
  */
9405
- var ContributionSectionSchema = object({
9406
- id: string(),
9407
- title: string(),
9408
- description: string().optional(),
9409
- style: _enum(["card", "accordion"]).optional(),
9410
- defaultCollapsed: boolean().optional(),
9411
- columns: union([
9412
- literal(1),
9413
- literal(2),
9414
- literal(3),
9415
- literal(4)
9416
- ]).optional(),
9417
- tab: string().optional(),
9418
- location: _enum([
9419
- "settings",
9420
- "top-tab",
9421
- "hero"
9422
- ]).optional(),
9423
- order: number().optional(),
9424
- fields: array(any())
9873
+ var SHARE_VIEW_KINDS = ["grid-view", "events-view"];
9874
+ /** The wire shape of {@link PeerBytesTicket} — see the type for what it is. */
9875
+ var PeerBytesTicketSchema = object({
9876
+ /** `http://127.0.0.1:<port>/<token>`. One `GET` takes it. */
9877
+ url: string().min(1),
9878
+ /**
9879
+ * The HOST node this URL means something on — the hub or a named agent,
9880
+ * never a runner. {@link AddonPeerBytes.open} compares it to its own and
9881
+ * refuses `cross-node` by name when they differ, without dialling.
9882
+ */
9883
+ hostNodeId: string().min(1),
9884
+ expiresAtMs: number().int().nonnegative(),
9885
+ /**
9886
+ * What the producer DECLARED the body to be, when it knows — `null` when it
9887
+ * does not. Never `0` for unknown (D393): a consumer sizing a bound off this
9888
+ * must be able to tell "the producer did not say" from "the body is empty".
9889
+ */
9890
+ declaredBytes: number().int().nonnegative().nullable()
9425
9891
  });
9426
- object({
9427
- tabs: array(object({
9428
- id: string(),
9429
- label: string(),
9430
- icon: string(),
9431
- order: number().optional()
9432
- })).optional(),
9433
- sections: array(ContributionSectionSchema)
9434
- }).nullable();
9435
- object({ deviceId: number() }), object({ deviceId: number() }), object({
9436
- deviceId: number(),
9437
- patch: record(string(), unknown())
9438
- }), object({ success: literal(true) });
9439
- object({ deviceId: number() }), unknown().nullable();
9440
- function method(input, output, options) {
9441
- return {
9442
- input,
9443
- output,
9444
- kind: options?.kind ?? "query",
9445
- ...options?.auth !== void 0 ? { auth: options.auth } : {},
9446
- ...options?.access !== void 0 ? { access: options.access } : {},
9447
- ...options?.role !== void 0 ? { role: options.role } : {},
9448
- ...options?.caller !== void 0 ? { caller: options.caller } : {},
9449
- timeoutMs: options?.timeoutMs
9450
- };
9451
- }
9452
- /**
9453
- * A wrapper/system-only method: served exclusively by the cap's system-level
9454
- * provider (`InferProvider`), and OPTIONAL on `InferNativeProvider` so per-device
9455
- * driver natives don't stub out a wrapper concern (e.g. a cross-device cache
9456
- * overview). The `systemOnly: true` literal is what `InferNativeProvider` keys on.
9457
- */
9458
- function systemMethod(input, output, options) {
9459
- return {
9460
- ...method(input, output, options),
9461
- systemOnly: true
9462
- };
9463
- }
9464
- /**
9465
- * A method a SOURCE of a collection cap may legitimately not serve — OPTIONAL
9466
- * on `InferProvider`. The `providerOptional: true` literal is what
9467
- * `InferProvider` keys on; see {@link CapabilityMethodSchema.providerOptional}
9468
- * for when this is the honest answer and when it is a soft stub.
9469
- */
9470
- function optionalMethod(input, output, options) {
9471
- return {
9472
- ...method(input, output, options),
9473
- providerOptional: true
9474
- };
9475
- }
9476
9892
  var READING_QUANTITIES = [
9477
9893
  "temperature",
9478
9894
  "pressure",
@@ -10051,7 +10467,6 @@ var CAP_NAMES = Object.freeze([
10051
10467
  "climate-control",
10052
10468
  "color",
10053
10469
  "composer",
10054
- "connection-test",
10055
10470
  "connectivity",
10056
10471
  "consumables",
10057
10472
  "contact",
@@ -11198,6 +11613,10 @@ Object.freeze({
11198
11613
  "all",
11199
11614
  "one"
11200
11615
  ]
11616
+ },
11617
+ {
11618
+ "path": "positionUpdatedAt",
11619
+ "valueType": "number"
11201
11620
  }
11202
11621
  ],
11203
11622
  "meter": [{
@@ -11452,22 +11871,6 @@ Object.freeze({
11452
11871
  "path": "pumpRunning",
11453
11872
  "valueType": "boolean"
11454
11873
  },
11455
- {
11456
- "path": "lastDrink",
11457
- "valueType": "number"
11458
- },
11459
- {
11460
- "path": "currentHourDrink",
11461
- "valueType": "number"
11462
- },
11463
- {
11464
- "path": "last24hDrink",
11465
- "valueType": "number"
11466
- },
11467
- {
11468
- "path": "todayDrink",
11469
- "valueType": "number"
11470
- },
11471
11874
  {
11472
11875
  "path": "error",
11473
11876
  "valueType": "string"
@@ -12033,6 +12436,59 @@ Object.freeze({
12033
12436
  }
12034
12437
  ]
12035
12438
  });
12439
+ Object.freeze({
12440
+ "actions": { "run": 363e4 },
12441
+ "audio-analyzer": { "classify": 3e4 },
12442
+ "custom-model-registry": { "importModelBundle": 18e5 },
12443
+ "database-snapshot": { "writeSnapshot": 18e5 },
12444
+ "device-manager": {
12445
+ "migrateDevice": 72e4,
12446
+ "runDiscoverySweep": 12e4
12447
+ },
12448
+ "device-provider": { "reloadDevice": 18e4 },
12449
+ "llm": {
12450
+ "generate": 6e5,
12451
+ "generateVision": 6e5,
12452
+ "testProfile": 6e5
12453
+ },
12454
+ "llm-runtime": {
12455
+ "complete": 6e5,
12456
+ "completeApple": 6e5,
12457
+ "ensureStarted": 6e5,
12458
+ "installModel": 36e5
12459
+ },
12460
+ "local-network": { "scanNetwork": 9e4 },
12461
+ "model-convert": { "convert": 6e5 },
12462
+ "pipeline-analytics": {
12463
+ "addRetrainFrameFromRecording": 6e4,
12464
+ "offerRetrainArchive": 12e4,
12465
+ "proposeRetrainAnnotationsWithLlm": 18e4,
12466
+ "resolveRetrainTrainingCorpus": 6e4,
12467
+ "writeRetrainArchive": 36e5
12468
+ },
12469
+ "server-management": { "applyServerUpdate": 96e4 },
12470
+ "terminal-session": { "pullOutput": 15e3 },
12471
+ "training": {
12472
+ "canaryResult": 12e4,
12473
+ "cancelJob": 12e4,
12474
+ "planJob": 6e4,
12475
+ "registerResult": 18e5,
12476
+ "rollbackCanary": 12e4,
12477
+ "startJob": 12e4,
12478
+ "startJobBatch": 12e4
12479
+ },
12480
+ "training-provider": {
12481
+ "cancelJob": 6e4,
12482
+ "cleanupJob": 3e5,
12483
+ "getJob": 6e4,
12484
+ "listJobEvents": 6e4,
12485
+ "listJobs": 12e4,
12486
+ "offerArtifact": 3e5,
12487
+ "readResult": 3e5,
12488
+ "submitJob": 18e5,
12489
+ "uploadDataset": 72e5
12490
+ }
12491
+ });
12036
12492
  object({
12037
12493
  code: string().regex(/^[a-z][a-z0-9-]*(\.[a-z0-9-]+)+$/),
12038
12494
  params: record(string(), union([string(), number()])).optional()
@@ -12052,7 +12508,7 @@ function userError(code, params, englishFallback) {
12052
12508
  return new CamstackError(code, params, englishFallback);
12053
12509
  }
12054
12510
  //#endregion
12055
- //#region ../types/dist/composition-pOHbTzRB.mjs
12511
+ //#region ../types/dist/composition-BmBHuDTQ.mjs
12056
12512
  /**
12057
12513
  * The ffmpeg build every CamStack node downloads, per platform and arch.
12058
12514
  *
@@ -12356,7 +12812,7 @@ var table = {
12356
12812
  },
12357
12813
  dwell: {
12358
12814
  minArgs: 3,
12359
- maxArgs: 3,
12815
+ maxArgs: 4,
12360
12816
  apply: () => {
12361
12817
  throw new ExpressionEvalError("dwell: stateful evaluation context is required");
12362
12818
  }
@@ -13516,254 +13972,6 @@ function buildCapturingReply(envelope) {
13516
13972
  };
13517
13973
  return wrapper;
13518
13974
  }
13519
- /**
13520
- * The link primitive's declaration half (D1013 rule 5): what a link field names and how a kind
13521
- * records it. Split from `instance-link.ts` so `RecordIntegrationInstances` can read the links of
13522
- * its kind without importing the builders that import it.
13523
- */
13524
- /** The body field of a link: the id of the instance it names; the target rides in the field meta. */
13525
- function linkField(target) {
13526
- return string().meta({ link: target });
13527
- }
13528
- function linkTargetOf(meta) {
13529
- if (typeof meta !== "object" || meta === null) return void 0;
13530
- const link = Reflect.get(meta, "link");
13531
- const parsed = LinkTargetSchema.safeParse(link);
13532
- return parsed.success ? parsed.data : void 0;
13533
- }
13534
- var LinkTargetSchema = object({
13535
- cap: string().min(1),
13536
- kind: string().min(1).optional()
13537
- });
13538
- /** The links a kind declares, read from the meta of its body fields. */
13539
- function linksOfKind(kind) {
13540
- const schema = kind.schema;
13541
- if (!(schema instanceof ZodObject)) return [];
13542
- const links = [];
13543
- for (const [field, fieldSchema] of Object.entries(schema.shape)) {
13544
- const to = linkTargetOf(globalRegistry.get(fieldSchema));
13545
- if (to !== void 0) links.push({
13546
- field,
13547
- to
13548
- });
13549
- }
13550
- return links;
13551
- }
13552
- /**
13553
- * `RecordIntegrationInstances` - the `integration-instances` provider over ONE
13554
- * entry kind, so an addon that holds a connection serves it in ~30 lines.
13555
- *
13556
- * Every instance is one record of the addon's own kind, keyed by the
13557
- * `integrations` registry id. The records door does the secret work: a field the
13558
- * kind marks `.meta({ secret: true })` is a keychain marker bound to the row, so
13559
- * deleting the row deletes the secret, and one row's value is never another's.
13560
- *
13561
- * Patch rules for a secret (`updateInstance`): omitted, `''`, the redaction
13562
- * token or the view the form was given KEEP the stored secret;
13563
- * `{ $secretClear: true }` clears it; any other string replaces it.
13564
- */
13565
- /** The most instances one addon lists (an integrations page, not a table). */
13566
- var INSTANCES_LIST_MAX = 1e3;
13567
- /** The keys of the kind's secret fields that sit at the top level of the body. */
13568
- function topLevelSecretKeys(paths) {
13569
- return new Set(paths.filter((p) => !p.includes(".") && !p.includes("[") && !p.includes("{")));
13570
- }
13571
- /** The keys of the kind's top-level MAPS whose values are secrets (`applianceSecrets{}`). */
13572
- function secretMapKeys(paths) {
13573
- return new Set(paths.filter((p) => p.endsWith("{}") && !p.slice(0, -2).match(/[.[{]/)).map((p) => p.slice(0, -2)));
13574
- }
13575
- /**
13576
- * A patch value for a map of secrets: an entry that is omitted, `''`, the redaction token or the
13577
- * view the form was given KEEPS its stored secret (it is left out of the merge); `{ $secretClear }`
13578
- * or `null` removes the entry; any other string replaces it. Null when nothing is left to merge.
13579
- */
13580
- function secretMapPatch(value) {
13581
- if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
13582
- const out = {};
13583
- for (const [key, entry] of Object.entries(value)) if (entry === null || isSecretClear(entry)) out[key] = null;
13584
- else if (typeof entry === "string" && entry !== "" && entry !== "__camstack_redacted__" && !isSecretFieldView(entry)) out[key] = entry;
13585
- return Object.keys(out).length > 0 ? out : null;
13586
- }
13587
- /** Does the kind's body schema carry an `enabled` field? */
13588
- function declaresEnabled(kind) {
13589
- const json = toJSONSchema(kind.schema, {
13590
- unrepresentable: "any",
13591
- io: "input"
13592
- });
13593
- const properties = Reflect.get(json, "properties");
13594
- return typeof properties === "object" && properties !== null && "enabled" in properties;
13595
- }
13596
- var RecordIntegrationInstances = class {
13597
- records;
13598
- kind;
13599
- hooks;
13600
- handle;
13601
- secretKeys;
13602
- secretMaps;
13603
- nameField;
13604
- /** The `integrations` registry owns the on/off switch (`role: devices`); the body has none. */
13605
- registryOwnsEnabled;
13606
- constructor(records, kind, hooks) {
13607
- this.records = records;
13608
- this.kind = kind;
13609
- this.hooks = hooks;
13610
- this.handle = records.kind(kind);
13611
- this.secretKeys = topLevelSecretKeys(kind.declaration.secretPaths);
13612
- this.secretMaps = secretMapKeys(kind.declaration.secretPaths);
13613
- this.nameField = kind.declaration.entry?.nameField ?? "name";
13614
- this.registryOwnsEnabled = hooks.description.role === "devices";
13615
- 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"`);
13616
- }
13617
- /**
13618
- * One instance read for the addon's own runtime; null when absent. When the keychain is
13619
- * locked the row is served WITHOUT its secrets and says so (`secrets: 'unavailable'`), so the
13620
- * caller can keep what it had instead of reconfiguring with an empty secret (D49).
13621
- */
13622
- async readResolved(id) {
13623
- try {
13624
- const record = await this.handle.getResolved(id);
13625
- return record === null ? null : {
13626
- id,
13627
- body: record.data,
13628
- enabled: record.data.enabled !== false,
13629
- secrets: "resolved"
13630
- };
13631
- } catch (err) {
13632
- if (!(err instanceof RecordSecretUnavailableError)) throw err;
13633
- const stored = await this.handle.get(id);
13634
- if (stored === null) return null;
13635
- return {
13636
- id,
13637
- body: Object.fromEntries(Object.entries(stored.data).filter(([key]) => !this.secretKeys.has(key))),
13638
- enabled: stored.data.enabled !== false,
13639
- secrets: "unavailable"
13640
- };
13641
- }
13642
- }
13643
- /** The body of {@link readResolved} alone; a locked keychain yields the row without secrets. */
13644
- async getResolved(id) {
13645
- return (await this.readResolved(id))?.body ?? null;
13646
- }
13647
- /** Every instance, secrets resolved where the keychain allows; an absent one is skipped. */
13648
- async listResolved() {
13649
- const page = await this.handle.query({ limit: INSTANCES_LIST_MAX });
13650
- const out = [];
13651
- for (const record of page.records) {
13652
- const read = await this.readResolved(record.id);
13653
- if (read !== null) out.push(read);
13654
- }
13655
- return out;
13656
- }
13657
- viewOf(record) {
13658
- const shown = secretViewsOf(this.records.owner, this.kind.name, record.id, this.kind.declaration, record.data);
13659
- const rawName = record.data[this.nameField];
13660
- const kind = this.hooks.kindOf?.(record.data);
13661
- const health = this.hooks.health?.(record.data, record.id);
13662
- return {
13663
- id: record.id,
13664
- name: typeof rawName === "string" ? rawName : record.id,
13665
- configured: this.hooks.configured(record.data),
13666
- ...this.registryOwnsEnabled ? {} : { enabled: record.data.enabled !== false },
13667
- formValues: shown,
13668
- ...kind !== void 0 ? { kind } : {},
13669
- ...health?.status !== void 0 ? { status: health.status } : {},
13670
- ...health?.lastCheckedAt !== void 0 ? { lastCheckedAt: health.lastCheckedAt } : {}
13671
- };
13672
- }
13673
- describe = async () => {
13674
- const declared = linksOfKind(this.kind);
13675
- const links = this.hooks.description.links !== void 0 || declared.length === 0 ? {} : { links: declared.map((link) => ({
13676
- kind: this.kind.name,
13677
- field: link.field,
13678
- to: link.to
13679
- })) };
13680
- return {
13681
- ...this.hooks.description,
13682
- ...links,
13683
- ...this.hooks.mintId === void 0 ? {} : { mintsId: true }
13684
- };
13685
- };
13686
- instanceFormSchema = async ({ id }) => this.hooks.formSchema(id);
13687
- listInstances = async () => {
13688
- return (await this.handle.query({ limit: INSTANCES_LIST_MAX })).records.map((record) => this.viewOf(record));
13689
- };
13690
- getInstance = async ({ id }) => {
13691
- const record = await this.handle.get(id);
13692
- return record === null ? null : this.viewOf(record);
13693
- };
13694
- /** Insert ONE row (`ifRev: 0`: an existing id is refused, never overwritten). */
13695
- createInstance = async ({ id, name, kind, values }) => {
13696
- const minted = id ?? this.hooks.mintId?.({
13697
- name,
13698
- ...kind !== void 0 ? { kind } : {}
13699
- });
13700
- if (minted === void 0) throw new Error("createInstance needs an id: this provider does not mint one");
13701
- await this.handle.put({
13702
- id: minted,
13703
- data: this.hooks.initialBody(name, kind)
13704
- }, { ifRev: 0 });
13705
- const patch = this.patchOf(values ?? {});
13706
- if (Object.keys(patch).length > 0) await this.handle.patch(minted, patch);
13707
- await this.hooks.onChanged?.(minted, "created");
13708
- return { id: minted };
13709
- };
13710
- updateInstance = async ({ id, name, values }) => {
13711
- const patch = this.patchOf(values);
13712
- if (name !== void 0) patch[this.nameField] = name;
13713
- await this.handle.patch(id, patch);
13714
- await this.hooks.onChanged?.(id, "updated");
13715
- return { ok: true };
13716
- };
13717
- /** The record patch a form `values` object means: secrets kept, cleared or replaced. */
13718
- patchOf(values) {
13719
- const patch = {};
13720
- for (const [key, value] of Object.entries(values)) {
13721
- if (value === void 0) continue;
13722
- if (this.secretMaps.has(key)) {
13723
- const entries = secretMapPatch(value);
13724
- if (entries !== null) patch[key] = entries;
13725
- } else if (!this.secretKeys.has(key)) patch[key] = value;
13726
- else if (isSecretClear(value)) patch[key] = null;
13727
- else if (typeof value === "string" && value !== "" && value !== "__camstack_redacted__" && !isSecretFieldView(value)) patch[key] = value;
13728
- }
13729
- return patch;
13730
- }
13731
- /** The switch lives in the record body; the addon is told so it applies it (D996). */
13732
- setInstanceEnabled = async ({ id, enabled }) => {
13733
- if (this.registryOwnsEnabled) throw new Error(`instance "${id}": the integrations registry owns the on/off switch of this addon; set it with integrations.update`);
13734
- await this.handle.patch(id, { enabled });
13735
- await this.hooks.onChanged?.(id, "enabled");
13736
- return { ok: true };
13737
- };
13738
- /** The row and its keychain refs go together (the records door). */
13739
- deleteInstance = async ({ id }) => {
13740
- await this.handle.delete(id);
13741
- await this.hooks.onChanged?.(id, "deleted");
13742
- return { ok: true };
13743
- };
13744
- testInstance = async (input) => {
13745
- if (this.hooks.test === void 0) return {
13746
- success: false,
13747
- status: "unsupported",
13748
- error: "This integration declares no connection test"
13749
- };
13750
- return this.hooks.test(input);
13751
- };
13752
- /** The flat provider object to hand to `registerProvider`. */
13753
- toProvider() {
13754
- return {
13755
- describe: this.describe,
13756
- instanceFormSchema: this.instanceFormSchema,
13757
- listInstances: this.listInstances,
13758
- getInstance: this.getInstance,
13759
- createInstance: this.createInstance,
13760
- updateInstance: this.updateInstance,
13761
- setInstanceEnabled: this.setInstanceEnabled,
13762
- deleteInstance: this.deleteInstance,
13763
- testInstance: this.testInstance
13764
- };
13765
- }
13766
- };
13767
13975
  /** No part holds the id a call named. */
13768
13976
  var UnknownInstanceError = class extends Error {
13769
13977
  instanceId;
@@ -13793,6 +14001,17 @@ function composeInstanceKinds(parts, base) {
13793
14001
  if (part === void 0) throw new UnknownInstanceKindError(kindId);
13794
14002
  return part;
13795
14003
  };
14004
+ /**
14005
+ * The part a DRAFT test runs on. A named kind is that kind; an unnamed one is the provider's only
14006
+ * testable kind. Several testable kinds and none named is a typed refusal that lists them, never a throw.
14007
+ */
14008
+ const draftPart = (kindId) => {
14009
+ if (kindId !== void 0) return parts.find((candidate) => candidate.kind.id === kindId) ?? { error: `Unknown instance kind '${kindId}'` };
14010
+ const testable = parts.filter((part) => part.kind.canTest !== false);
14011
+ const only = testable.length === 1 ? testable[0] : parts.length === 1 ? parts[0] : void 0;
14012
+ if (only !== void 0) return only;
14013
+ return { error: `This provider has several kinds: name one of ${(testable.length > 0 ? testable : parts).map((part) => part.kind.id).join(", ")}` };
14014
+ };
13796
14015
  const holderOf = async (id) => {
13797
14016
  for (const part of parts) if (await part.provider.getInstance({ id }) !== null) return part;
13798
14017
  throw new UnknownInstanceError(id);
@@ -13828,7 +14047,13 @@ function composeInstanceKinds(parts, base) {
13828
14047
  setInstanceEnabled: async (input) => (await holderOf(input.id)).provider.setInstanceEnabled(input),
13829
14048
  deleteInstance: async (input) => (await holderOf(input.id)).provider.deleteInstance(input),
13830
14049
  testInstance: async (input) => {
13831
- const test = (input.id === null ? byKind(input.kind) : await holderOf(input.id)).provider.testInstance;
14050
+ const resolved = input.id === null ? draftPart(input.kind) : await holderOf(input.id);
14051
+ if ("error" in resolved) return {
14052
+ success: false,
14053
+ status: "inconclusive",
14054
+ error: resolved.error
14055
+ };
14056
+ const test = resolved.provider.testInstance;
13832
14057
  if (test === void 0) return {
13833
14058
  success: false,
13834
14059
  status: "inconclusive",
@@ -13838,6 +14063,432 @@ function composeInstanceKinds(parts, base) {
13838
14063
  }
13839
14064
  };
13840
14065
  }
14066
+ /**
14067
+ * notification-output — canonical, capability-gated notification delivery.
14068
+ *
14069
+ * Apprise-derived model (see
14070
+ * `docs/superpowers/specs/2026-07-03-notification-output-notifier-matrix.md`):
14071
+ * callers emit ONE canonical `Notification`; each provider declares a
14072
+ * per-kind capability descriptor (`TargetKind`), and the pure degrade
14073
+ * engine (`@camstack/types` `prepareNotification`) transcodes / degrades the
14074
+ * message to what the kind supports — callers never special-case a service.
14075
+ *
14076
+ * DESIGN DECISIONS (locked):
14077
+ * - Target CRUD lives on THIS cap (`upsertTarget` / `deleteTarget` /
14078
+ * `setTargetEnabled`), each provider persisting via the `settings-store`
14079
+ * cap. Rationale: the admin UI needs one uniform surface across the
14080
+ * notifiers addon AND the HA addon; the addon-`globalSettingsSchema`-array
14081
+ * alternative would fork the UI per addon and cannot host the
14082
+ * discovery→adopt flow.
14083
+ * - `listTargetKinds` / `listTargets` / `discoverTargets` return arrays →
14084
+ * the generated cap-mount auto-`concatCollection`-fans them across every
14085
+ * registered provider (notifiers addon + HA addon) so one catalog is
14086
+ * routable. `send` / `testTarget` / CRUD route to ONE provider by the
14087
+ * `addonId` the generated collection router extracts from the call input.
14088
+ * - `Attachment.bytes` is `Uint8Array`. Transport-safe: superjson (the tRPC
14089
+ * transformer) + UDS MsgPack both round-trip typed arrays — already used by
14090
+ * `storage` / `storage-provider` / `recording` caps over the same path. No
14091
+ * base64 fallback needed.
14092
+ *
14093
+ * TODO (deferred, closed-set change — separate decision): add
14094
+ * `providerKind: 'notify'` so notification providers surface on the unified
14095
+ * admin "Integrations" page.
14096
+ */
14097
+ /**
14098
+ * Zentik-derived typed-media enum — the superset across every kind. Each
14099
+ * adapter picks what it supports and the degrade engine filters the rest.
14100
+ */
14101
+ var AttachmentMediaTypeSchema = _enum([
14102
+ "image",
14103
+ "video",
14104
+ "gif",
14105
+ "audio",
14106
+ "icon"
14107
+ ]);
14108
+ /**
14109
+ * A single attachment. Exactly one of `url` (remote source, most adapters
14110
+ * prefer this) or `bytes` (inline source; required for Pushover-style
14111
+ * bytes-only kinds) MUST be present — the degrade engine expresses a
14112
+ * url→bytes fetch as a `needsFetch` directive the adapter executes.
14113
+ */
14114
+ var AttachmentSchema = object({
14115
+ mediaType: AttachmentMediaTypeSchema,
14116
+ url: string().optional(),
14117
+ bytes: _instanceof(Uint8Array).optional(),
14118
+ mime: string().optional(),
14119
+ name: string().optional()
14120
+ }).refine((a) => a.url !== void 0 || a.bytes !== void 0, { message: "Attachment requires either `url` or `bytes`" });
14121
+ var NotificationFormatSchema = _enum([
14122
+ "text",
14123
+ "markdown",
14124
+ "html"
14125
+ ]);
14126
+ /**
14127
+ * The CLOSED icon vocabulary an action button may use.
14128
+ *
14129
+ * A closed set, not a free string, and that is the whole point: an arbitrary
14130
+ * icon name is one that ntfy renders, zentik silently drops, and nobody
14131
+ * notices — the same class of gap as a zone vocabulary nothing produced
14132
+ * ([D35](../../../docs/decisions/adr-0035.md)). Every adapter maps this set or
14133
+ * declares `actionIcons: false` and the degrade engine strips the field.
14134
+ *
14135
+ * Named by INTENT, never by glyph. "check" would tie the vocabulary to one
14136
+ * renderer's icon set; "acknowledge" survives an adapter that draws it
14137
+ * differently.
14138
+ *
14139
+ * ── A TOKEN IS NOT A WIRE VALUE ─────────────────────────────────────
14140
+ *
14141
+ * These names are for US. **No adapter may forward one verbatim.** Each maps
14142
+ * the whole set onto its own renderer's vocabulary through a
14143
+ * `Record<NotificationActionIcon, string>` — a Record, never a lookup with a
14144
+ * fallback, so adding a member here fails every adapter's build until someone
14145
+ * decides its glyph, which is the only place that decision can be made
14146
+ * honestly.
14147
+ *
14148
+ * This paragraph is the bug. Zentik declared `actionIcons: true` and passed
14149
+ * `disarm` straight through; iOS feeds that string to
14150
+ * `UNNotificationActionIcon(systemImageName:)`, `disarm` is not an SF Symbol,
14151
+ * and every snooze and alarm button arrived BLANK. A pass-through is not a
14152
+ * mapping, and "the field is documented" is not "the value renders".
14153
+ *
14154
+ * Adding a member is TRAIN-BOUND. The enum lives in the published
14155
+ * `@camstack/server` closure and the cap seam validates against the HUB's copy,
14156
+ * so an addon that emits a token the running hub does not know does not lose an
14157
+ * icon — its whole `send` fails Zod validation and the notification never
14158
+ * arrives. Never emit a new token from an addon before the train carrying it.
14159
+ */
14160
+ var NotificationActionIconSchema = _enum([
14161
+ "acknowledge",
14162
+ "dismiss",
14163
+ "silence",
14164
+ "snooze",
14165
+ "view",
14166
+ "play",
14167
+ "open",
14168
+ "close",
14169
+ "lock",
14170
+ "unlock",
14171
+ "arm",
14172
+ "arm-home",
14173
+ "arm-away",
14174
+ "arm-night",
14175
+ "disarm",
14176
+ "light",
14177
+ "alert",
14178
+ "camera"
14179
+ ]);
14180
+ /** A single tap-through action button. */
14181
+ var NotificationActionSchema = object({
14182
+ id: string(),
14183
+ label: string(),
14184
+ url: string().optional(),
14185
+ /** Dropped by the degrade engine for a kind with `caps.actionIcons: false`. */
14186
+ icon: NotificationActionIconSchema.optional(),
14187
+ /**
14188
+ * Renders in a warning style where the notifier supports it.
14189
+ *
14190
+ * A HINT, never a gate. The callback's authority is its token and nothing
14191
+ * else — see `notification-center/action-token.ts` for what that does and
14192
+ * does not buy.
14193
+ */
14194
+ destructive: boolean().optional(),
14195
+ /**
14196
+ * How the tap should REACH the url.
14197
+ *
14198
+ * `navigate` (absent, and every button authored before this field) opens it:
14199
+ * the phone leaves the notification and shows whatever the callback returns.
14200
+ * That is right for a button whose answer the operator wants to read.
14201
+ *
14202
+ * `background` fires it as a POST and stays put. It exists for the buttons
14203
+ * whose whole point is not to interrupt — "silence this for 30 minutes" is
14204
+ * an answer to the notification, and being thrown into a browser tab to
14205
+ * confirm it costs more attention than the notification did. A backend that
14206
+ * cannot do a background call renders it as an ordinary link (the adapters
14207
+ * fall back rather than dropping the button), so this is a preference, never
14208
+ * a requirement.
14209
+ */
14210
+ mode: _enum(["navigate", "background"]).optional()
14211
+ });
14212
+ /** A delivery parameter value: what a notifier declared it takes. */
14213
+ var DeliveryParamValueSchema = union([
14214
+ string(),
14215
+ number(),
14216
+ boolean()
14217
+ ]);
14218
+ /**
14219
+ * One extra delivery parameter a notifier KIND declares (D938). A rule that
14220
+ * addresses a target of that kind may set it; a kind that declares nothing is
14221
+ * never handed one. The admin UI derives its control from this descriptor —
14222
+ * no editor knows a service by name.
14223
+ *
14224
+ * Optional fields are `.optional()`, never `.default()` (a Zod default does not
14225
+ * run on the addon cap path).
14226
+ */
14227
+ var DeliveryParamSchema = object({
14228
+ key: string().min(1),
14229
+ label: string(),
14230
+ /** i18n key of the label, resolved by the declaring addon's namespace. */
14231
+ labelKey: string().optional(),
14232
+ type: _enum([
14233
+ "enum",
14234
+ "number",
14235
+ "boolean",
14236
+ "string"
14237
+ ]),
14238
+ /** `enum` only: the closed set of accepted values. */
14239
+ options: array(object({
14240
+ value: string(),
14241
+ label: string()
14242
+ })).optional(),
14243
+ /** `number` only. */
14244
+ min: number().optional(),
14245
+ max: number().optional(),
14246
+ /** What the notifier does when the rule sets nothing; shown as the placeholder. */
14247
+ default: DeliveryParamValueSchema.optional()
14248
+ });
14249
+ /**
14250
+ * The canonical notification. `body` is the only hard field (Apprise model).
14251
+ * `priority` is a 5-level ORDINAL (1=lowest … 3=normal(default) … 5=urgent),
14252
+ * NOT a fixed severity enum — each kind declares its own `caps.levels` and
14253
+ * the adapter maps this ordinal onto its native level. `level?` is an
14254
+ * optional kind-native level id (`emergency`, `silent`, …) that overrides
14255
+ * `priority` for that one target.
14256
+ */
14257
+ var NotificationSchema = object({
14258
+ body: string(),
14259
+ title: string().optional(),
14260
+ format: NotificationFormatSchema.default("text"),
14261
+ priority: number().int().min(1).max(5).default(3),
14262
+ level: string().optional(),
14263
+ attachments: array(AttachmentSchema).optional(),
14264
+ clickUrl: string().optional(),
14265
+ actions: array(NotificationActionSchema).optional(),
14266
+ sound: string().optional(),
14267
+ ttl: number().optional(),
14268
+ tag: string().optional(),
14269
+ deviceId: number().optional(),
14270
+ eventId: string().optional(),
14271
+ metadata: record(string(), unknown()).optional(),
14272
+ /**
14273
+ * Values for the parameters the target's kind DECLARES in
14274
+ * {@link TargetKindSchema} `deliveryParams`. Already validated against the
14275
+ * declaration by the sender; a notifier reads only the keys it declared.
14276
+ */
14277
+ delivery: record(string(), DeliveryParamValueSchema).optional()
14278
+ });
14279
+ /** One declared native severity/priority level for a kind. */
14280
+ var TargetKindLevelSchema = object({
14281
+ id: string(),
14282
+ label: string(),
14283
+ /** Which canonical priority (1..5) this level maps to. `null` = qualitative-only. */
14284
+ ordinal: number().int().min(1).max(5).nullable(),
14285
+ flags: object({
14286
+ critical: boolean().optional(),
14287
+ silent: boolean().optional(),
14288
+ noPush: boolean().optional()
14289
+ }).optional(),
14290
+ /** e.g. Pushover `emergency` requires `retry` / `expire`. */
14291
+ requires: array(string()).optional(),
14292
+ description: string().optional()
14293
+ });
14294
+ /** The full capability block consulted before dispatch. */
14295
+ var TargetKindCapsSchema = object({
14296
+ attachments: object({
14297
+ mediaTypes: array(AttachmentMediaTypeSchema),
14298
+ mode: _enum([
14299
+ "url",
14300
+ "bytes",
14301
+ "both"
14302
+ ]),
14303
+ max: number().int().nonnegative(),
14304
+ maxBytes: number().int().positive().optional()
14305
+ }),
14306
+ /** Max action buttons (0 = none). */
14307
+ actions: number().int().nonnegative(),
14308
+ /**
14309
+ * Whether this kind renders a per-action ICON.
14310
+ *
14311
+ * `.optional()`, deliberately NOT `.default(false)`: a Zod default does not
14312
+ * run on the addon cap path — three production failures in one day taught
14313
+ * this repo that once. Absent is read as false by the degrade engine, which
14314
+ * is the safe direction: an icon that is not rendered costs nothing, an icon
14315
+ * assumed and dropped costs the operator's trust in the field.
14316
+ */
14317
+ actionIcons: boolean().optional(),
14318
+ levels: array(TargetKindLevelSchema),
14319
+ format: array(NotificationFormatSchema),
14320
+ clickUrl: boolean(),
14321
+ sound: boolean(),
14322
+ ttl: boolean(),
14323
+ bodyMaxLen: number().int().positive()
14324
+ });
14325
+ /**
14326
+ * `configSchema` is a `ConfigUISchema` tree passed through to the admin
14327
+ * FormBuilder. Stored as `z.unknown()` at the cap seam (mirrors
14328
+ * `device-provider.getChildCreationSchema` `CreationSchemaOutputSchema`) —
14329
+ * the union is large and not meant for runtime validation here; the exported
14330
+ * `TargetKind` type re-tightens `configSchema` to `ConfigUISchema`.
14331
+ */
14332
+ var ConfigSchemaPassthrough$4 = unknown();
14333
+ var TargetKindSchema = object({
14334
+ kind: string(),
14335
+ label: string(),
14336
+ icon: string(),
14337
+ /** Stamped by each provider so the concat-fanned catalog stays routable. */
14338
+ addonId: string(),
14339
+ /**
14340
+ * URL of the kind's bundled BRAND icon, served by the providing addon over
14341
+ * its own `addon-routes` surface (`/addon/<addonId>/icons/<kind>`). Absent
14342
+ * when the addon bundles no icon for that kind — the client then falls back
14343
+ * to a neutral glyph rather than rendering the raw `icon` NAME as text.
14344
+ *
14345
+ * Root-relative on purpose: it resolves against whatever origin serves a web
14346
+ * client, and a native client joins it onto its own hub base.
14347
+ *
14348
+ * DECLARED here deliberately. It used to travel as an undeclared passthrough
14349
+ * field that survived only because the runtime cap-router forwards provider
14350
+ * output verbatim — so every consumer had to re-declare it by hand to stop
14351
+ * its own Zod parse from stripping it, and the whole arrangement would have
14352
+ * broken silently the moment output validation was tightened anywhere.
14353
+ */
14354
+ iconUrl: string().optional(),
14355
+ /**
14356
+ * Media type of {@link iconUrl} (`image/svg+xml`, `image/png`, …).
14357
+ *
14358
+ * The server knows this and therefore says it, because the client cannot
14359
+ * safely guess: a React-Native client renders SVG and raster through two
14360
+ * DIFFERENT components (`react-native-svg` vs `expo-image` — expo-image does
14361
+ * not decode SVG on iOS/Android), so without this it silently fell back to a
14362
+ * placeholder glyph for every vector icon while the web build looked fine.
14363
+ *
14364
+ * Absent when {@link iconUrl} is absent, or for a legacy provider that has
14365
+ * not been updated — a client that cannot determine the type should prefer
14366
+ * its raster path, which is the safe default for an unknown image.
14367
+ */
14368
+ iconMediaType: string().optional(),
14369
+ configSchema: ConfigSchemaPassthrough$4,
14370
+ /**
14371
+ * The config keys that decide WHERE this kind's secrets are sent (server,
14372
+ * base URL, instance, chat, recipient). A save that changes any of them
14373
+ * while leaving a secret redacted is refused by the provider (D634), so an
14374
+ * editor uses this to ask for the secret on exactly those edits instead of
14375
+ * on every edit.
14376
+ *
14377
+ * Optional: absent from a provider that holds no secret (the Home Assistant
14378
+ * kinds) and from a provider older than this field — an editor that finds
14379
+ * it absent must assume ANY edit may need the secret.
14380
+ */
14381
+ destinationKeys: array(string()).optional(),
14382
+ supportsDiscovery: boolean(),
14383
+ /**
14384
+ * Extra delivery parameters a rule may set for a target of this kind (D938).
14385
+ * Absent = none; the rule editor then offers nothing.
14386
+ */
14387
+ deliveryParams: array(DeliveryParamSchema).optional(),
14388
+ caps: TargetKindCapsSchema
14389
+ });
14390
+ /**
14391
+ * A persisted target. `config` holds secrets; providers REDACT secret fields
14392
+ * (return a presence marker only) when serving `listTargets` — never
14393
+ * round-trip a stored secret to the UI.
14394
+ */
14395
+ var TargetSchema = object({
14396
+ id: string(),
14397
+ name: string(),
14398
+ kind: string(),
14399
+ addonId: string(),
14400
+ enabled: boolean(),
14401
+ config: record(string(), unknown())
14402
+ });
14403
+ /** A discovery-surfaced candidate (config is partial + non-secret). */
14404
+ var DiscoveredTargetSchema = object({
14405
+ kind: string(),
14406
+ suggestedName: string(),
14407
+ config: record(string(), unknown())
14408
+ });
14409
+ /** The degrade engine's report — what was resolved / dropped / degraded. */
14410
+ var RenderedAsSchema = object({
14411
+ level: string(),
14412
+ format: NotificationFormatSchema,
14413
+ attachmentsSent: number().int().nonnegative(),
14414
+ actionsSent: number().int().nonnegative(),
14415
+ truncated: boolean(),
14416
+ dropped: array(string())
14417
+ });
14418
+ var SendResultSchema = object({
14419
+ success: boolean(),
14420
+ error: string().optional(),
14421
+ renderedAs: RenderedAsSchema.optional()
14422
+ });
14423
+ /** Same shape as SendResult — kept as a distinct name for the test panel. */
14424
+ var TestResultSchema = SendResultSchema;
14425
+ /**
14426
+ * Pre-save credential probe against a partial (unsaved) target config.
14427
+ * `resolvedUrl` never includes secrets (token stripped from path).
14428
+ */
14429
+ var ProbeTargetConfigResultSchema = object({
14430
+ ok: boolean(),
14431
+ resolvedUrl: string(),
14432
+ httpStatus: number().int().optional(),
14433
+ stateInstance: string().optional(),
14434
+ error: string().optional()
14435
+ });
14436
+ method(object({}), array(TargetKindSchema)), method(object({}), array(TargetSchema), { auth: "admin" }), method(object({ targetId: string() }), TargetSchema, { auth: "admin" }), method(object({
14437
+ kind: string(),
14438
+ config: record(string(), unknown()).optional(),
14439
+ /**
14440
+ * When editing / duplicating, the blank password field never round-trips
14441
+ * the stored token. Pass the source target id so the provider can restore
14442
+ * secrets server-side before dialling (same merge as upsert).
14443
+ */
14444
+ targetId: string().optional()
14445
+ }), array(DiscoveredTargetSchema), { auth: "admin" }), method(object({
14446
+ kind: string(),
14447
+ config: record(string(), unknown()),
14448
+ /** See `discoverTargets.targetId` — restore stored secrets for a blank password. */
14449
+ targetId: string().optional()
14450
+ }), ProbeTargetConfigResultSchema, {
14451
+ kind: "mutation",
14452
+ auth: "admin"
14453
+ }), method(object({
14454
+ targetId: string(),
14455
+ notification: NotificationSchema
14456
+ }), SendResultSchema, {
14457
+ kind: "mutation",
14458
+ auth: "admin"
14459
+ }), method(object({
14460
+ targetId: string(),
14461
+ sample: NotificationSchema.optional()
14462
+ }), TestResultSchema, {
14463
+ kind: "mutation",
14464
+ auth: "admin"
14465
+ }), method(object({
14466
+ target: TargetSchema,
14467
+ /**
14468
+ * Duplicate flow: create a NEW target id while copying secrets from an
14469
+ * existing row. The UI never holds the stored token; blank / redacted
14470
+ * password fields are restored from this source (D634 still applies if
14471
+ * destinations diverge without a re-typed secret).
14472
+ */
14473
+ cloneSecretsFrom: string().optional()
14474
+ }), TargetSchema, {
14475
+ kind: "mutation",
14476
+ auth: "admin"
14477
+ }), method(object({ targetId: string() }), _void(), {
14478
+ kind: "mutation",
14479
+ auth: "admin"
14480
+ }), method(object({
14481
+ targetId: string(),
14482
+ enabled: boolean()
14483
+ }), _void(), {
14484
+ kind: "mutation",
14485
+ auth: "admin"
14486
+ });
14487
+ looseObject({
14488
+ name: string().min(1),
14489
+ enabled: boolean().optional()
14490
+ });
14491
+ TargetSchema.omit({ id: true });
13841
14492
  var EncodeProfileSchema = object({
13842
14493
  video: object({
13843
14494
  codec: _enum([
@@ -20022,31 +20673,21 @@ var APPLIANCE_CAP_VOCABULARY = {
20022
20673
  "pet-fountain": {
20023
20674
  scope: "device",
20024
20675
  noun: t("Pet fountain", "Fontana per animali"),
20025
- actions: [
20026
- {
20027
- id: "petFountain.pumpOn",
20028
- method: "setPump",
20029
- label: t("Pump on", "Pompa accesa"),
20030
- phrase: t("Start the pump of {device}", "Avvia la pompa di {device}"),
20031
- icon: "play",
20032
- args: { on: true }
20033
- },
20034
- {
20035
- id: "petFountain.pumpOff",
20036
- method: "setPump",
20037
- label: t("Pump off", "Pompa spenta"),
20038
- phrase: t("Stop the pump of {device}", "Ferma la pompa di {device}"),
20039
- icon: "square",
20040
- args: { on: false }
20041
- },
20042
- {
20043
- id: "petFountain.resetDailyConsumption",
20044
- method: "resetDailyConsumption",
20045
- label: t("Clear daily consumption", "Azzera il consumo giornaliero"),
20046
- phrase: t("Clear the daily water consumption of {device}", "Azzera il consumo giornaliero di acqua di {device}"),
20047
- icon: "rotate-ccw"
20048
- }
20049
- ],
20676
+ actions: [{
20677
+ id: "petFountain.pumpOn",
20678
+ method: "setPump",
20679
+ label: t("Pump on", "Pompa accesa"),
20680
+ phrase: t("Start the pump of {device}", "Avvia la pompa di {device}"),
20681
+ icon: "play",
20682
+ args: { on: true }
20683
+ }, {
20684
+ id: "petFountain.pumpOff",
20685
+ method: "setPump",
20686
+ label: t("Pump off", "Pompa spenta"),
20687
+ phrase: t("Stop the pump of {device}", "Ferma la pompa di {device}"),
20688
+ icon: "square",
20689
+ args: { on: false }
20690
+ }],
20050
20691
  state: [{
20051
20692
  kind: "boolean",
20052
20693
  field: "empty",
@@ -22065,7 +22706,6 @@ var SYSTEM_CAP_VOCABULARY = {
22065
22706
  "calendar-source": system(INTERNAL),
22066
22707
  calendars: system("calendars feed schedules and conditions, not device actions"),
22067
22708
  composer: system("device composition — an authoring tool, not an action"),
22068
- "connection-test": system(INTERNAL),
22069
22709
  "core-blocks": system(INTERNAL),
22070
22710
  "custom-model-registry": system(ML),
22071
22711
  "data-store-provider": system(INTERNAL),
@@ -43791,610 +44431,196 @@ var AutomationRunTraceSchema = object({
43791
44431
  startedAt: number(),
43792
44432
  endedAt: number(),
43793
44433
  trigger: AutomationTriggerTraceSchema,
43794
- conditions: array(AutomationConditionTraceNodeSchema),
43795
- verdict: AutomationRunVerdictSchema.optional(),
43796
- steps: array(AutomationStepTraceSchema),
43797
- outcome: AutomationRunOutcomeSchema,
43798
- /** How many identical consecutive skips this trace stands for (>= 1). */
43799
- repeat: number().int().min(1),
43800
- /** When the latest of those repeats happened. */
43801
- lastAt: number(),
43802
- /**
43803
- * A scheduler point's own outcome (D983). `outcome` carries the closest
43804
- * automation outcome so a reader that does not know schedulers still reads
43805
- * the trace; this field says exactly what happened.
43806
- */
43807
- scheduler: SchedulerOutcomeSchema.optional()
43808
- });
43809
- /**
43810
- * What the hub's `runs` ledger holds for one owner (`automation:<blockId>` or
43811
- * `action:<actionId>`): the cooldown stamp and the trace ring.
43812
- */
43813
- var AutomationStateDocSchema = object({
43814
- version: literal(1),
43815
- lastRunStartedAt: number().nullable(),
43816
- traces: array(AutomationRunTraceSchema)
43817
- });
43818
- /**
43819
- * Actions — named, runnable things an operator (or an automation) can start,
43820
- * declared as LIST ENTRIES, never as devices.
43821
- *
43822
- * An entry is either **internal** (a short list of cap/wait steps kept in the
43823
- * hub's `actions` record kind) or declared by an addon through the
43824
- * `action-source` collection (a Home Assistant script, a scene …). The one
43825
- * surface the UI and automations talk to is the `actions` cap; it keeps no
43826
- * catalog of its own (D3) — every `list` asks the providers live.
43827
- *
43828
- * This file is the data half: the entry schema, the variables an entry may
43829
- * declare, and the pure resolution of the values a run was given. It holds no
43830
- * runtime.
43831
- */
43832
- /** What a variable's value is. `select` takes one of `options`. */
43833
- var ActionVariableTypeSchema = _enum([
43834
- "string",
43835
- "number",
43836
- "boolean",
43837
- "select"
43838
- ]);
43839
- var ACTION_VARIABLE_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
43840
- var ActionVariableValueSchema = union([
43841
- string(),
43842
- number(),
43843
- boolean()
43844
- ]);
43845
- /**
43846
- * One declared variable. Steps reference it as `{ $var: 'name' }` (the whole
43847
- * value) or `{{vars.name}}` (inside a string) in their args.
43848
- */
43849
- var ActionVariableSchema = object({
43850
- name: string().regex(ACTION_VARIABLE_NAME_RE),
43851
- label: string().min(1).max(120).optional(),
43852
- type: ActionVariableTypeSchema,
43853
- required: boolean().optional(),
43854
- default: ActionVariableValueSchema.optional(),
43855
- /** The allowed values of a `select`. */
43856
- options: array(string().min(1)).min(1).optional()
43857
- }).superRefine((v, ctx) => {
43858
- if (v.type === "select" && v.options === void 0) ctx.addIssue({
43859
- code: "custom",
43860
- message: "a select variable needs options",
43861
- path: ["options"]
43862
- });
43863
- if (v.default !== void 0 && variableValueError(v, v.default) !== null) ctx.addIssue({
43864
- code: "custom",
43865
- message: variableValueError(v, v.default) ?? "invalid default",
43866
- path: ["default"]
43867
- });
43868
- });
43869
- /** Why `value` is not a legal value for the variable, or null when it is. */
43870
- function variableValueError(variable, value) {
43871
- switch (variable.type) {
43872
- case "string": return typeof value === "string" ? null : `variable "${variable.name}" must be a string`;
43873
- case "number": return typeof value === "number" && Number.isFinite(value) ? null : `variable "${variable.name}" must be a number`;
43874
- case "boolean": return typeof value === "boolean" ? null : `variable "${variable.name}" must be true or false`;
43875
- case "select": return typeof value === "string" && (variable.options ?? []).includes(value) ? null : `variable "${variable.name}" must be one of ${(variable.options ?? []).join(", ")}`;
43876
- }
43877
- }
43878
- var ActionSourceKindSchema = _enum(["internal", "addon"]);
43879
- function isInternalActionId(actionId) {
43880
- return actionId.startsWith("internal:") && actionId.length > 9;
43881
- }
43882
- /** The addon behind a `<addonId>:<localId>` id, or null for anything else (internal included). */
43883
- function addonIdOfActionId(actionId) {
43884
- if (isInternalActionId(actionId)) return null;
43885
- const at = actionId.indexOf(":");
43886
- return at > 0 && at < actionId.length - 1 ? actionId.slice(0, at) : null;
43887
- }
43888
- var ActionStatusSchema = object({
43889
- isRunning: boolean(),
43890
- /** Ms epoch the latest run STARTED; null when it never ran. */
43891
- lastRunAt: number().nullable(),
43892
- /** The latest run's failure; null on success or when it never ran. */
43893
- lastError: string().nullable()
43894
- });
43895
- var ActionEntrySchema = object({
43896
- /** `internal:<uuid>` or `<addonId>:<localId>`. */
43897
- id: string().min(3),
43898
- name: string().min(1).max(120),
43899
- /** The addon that declared it; `core-blocks` for an internal one. */
43900
- addonId: string().min(1),
43901
- source: ActionSourceKindSchema,
43902
- /** An addon-declared entry is edited where it was declared. */
43903
- readOnly: boolean(),
43904
- /** Internal only: cap and wait steps. No action-in-action, so no cycles. */
43905
- steps: array(ActionStepSchema).min(1).max(50).optional(),
43906
- variables: array(ActionVariableSchema).max(20).optional(),
43907
- status: ActionStatusSchema
43908
- }).superRefine((entry, ctx) => {
43909
- if (entry.source === "internal") {
43910
- if (!isInternalActionId(entry.id)) ctx.addIssue({
43911
- code: "custom",
43912
- message: "an internal action id is internal:<uuid>",
43913
- path: ["id"]
43914
- });
43915
- return;
43916
- }
43917
- if (entry.steps !== void 0) ctx.addIssue({
43918
- code: "custom",
43919
- message: "only an internal action carries steps",
43920
- path: ["steps"]
43921
- });
43922
- if (!entry.readOnly) ctx.addIssue({
43923
- code: "custom",
43924
- message: "an addon action is read-only here",
43925
- path: ["readOnly"]
43926
- });
43927
- if (addonIdOfActionId(entry.id) === null) ctx.addIssue({
43928
- code: "custom",
43929
- message: "an addon action id is <addonId>:<localId>",
43930
- path: ["id"]
43931
- });
43932
- });
43933
- /** What an operator writes for an internal action. */
43934
- var ActionInputSchema = object({
43935
- name: string().min(1).max(120),
43936
- steps: array(ActionStepSchema).min(1).max(50),
43937
- variables: array(ActionVariableSchema).max(20).optional()
43938
- });
43939
- /** Who started a run. Absent = the operator pressed it. */
43940
- var ActionRunOriginSchema = object({
43941
- /** The automation block whose step started it. */
43942
- blockId: string().min(1).optional() });
43943
- /** `started` = the caller did not ask to wait. */
43944
- var ActionRunOutcomeSchema = union([AutomationRunOutcomeSchema, literal("started")]);
43945
- var ActionRunResultSchema = object({
43946
- runId: string().min(1),
43947
- outcome: ActionRunOutcomeSchema,
43948
- /** Why it did not run, or what failed. */
43949
- message: string().optional()
43950
- });
43951
- _enum([
43952
- "not-found",
43953
- "read-only",
43954
- "invalid-variables",
43955
- "invalid-steps",
43956
- "not-linked",
43957
- "busy"
43958
- ]);
43959
- object({
43960
- actionId: string(),
43961
- runId: string(),
43962
- isRunning: boolean(),
43963
- /** Set when the run ended. */
43964
- outcome: AutomationRunOutcomeSchema.optional(),
43965
- lastRunAt: number().nullable(),
43966
- lastError: string().nullable()
43967
- });
43968
- /** A bare number accepted as a base unit — the save succeeded, say so. */
43969
- var UnitWarningSchema = object({
43970
- /** Where in the saved record, e.g. `conditions.children.0` or `steps.2.args.grams`. */
43971
- path: string(),
43972
- deviceId: number().int().optional(),
43973
- field: string(),
43974
- value: number(),
43975
- assumedUnit: string(),
43976
- message: string()
43977
- });
43978
- /**
43979
- * notification-output — canonical, capability-gated notification delivery.
43980
- *
43981
- * Apprise-derived model (see
43982
- * `docs/superpowers/specs/2026-07-03-notification-output-notifier-matrix.md`):
43983
- * callers emit ONE canonical `Notification`; each provider declares a
43984
- * per-kind capability descriptor (`TargetKind`), and the pure degrade
43985
- * engine (`@camstack/types` `prepareNotification`) transcodes / degrades the
43986
- * message to what the kind supports — callers never special-case a service.
43987
- *
43988
- * DESIGN DECISIONS (locked):
43989
- * - Target CRUD lives on THIS cap (`upsertTarget` / `deleteTarget` /
43990
- * `setTargetEnabled`), each provider persisting via the `settings-store`
43991
- * cap. Rationale: the admin UI needs one uniform surface across the
43992
- * notifiers addon AND the HA addon; the addon-`globalSettingsSchema`-array
43993
- * alternative would fork the UI per addon and cannot host the
43994
- * discovery→adopt flow.
43995
- * - `listTargetKinds` / `listTargets` / `discoverTargets` return arrays →
43996
- * the generated cap-mount auto-`concatCollection`-fans them across every
43997
- * registered provider (notifiers addon + HA addon) so one catalog is
43998
- * routable. `send` / `testTarget` / CRUD route to ONE provider by the
43999
- * `addonId` the generated collection router extracts from the call input.
44000
- * - `Attachment.bytes` is `Uint8Array`. Transport-safe: superjson (the tRPC
44001
- * transformer) + UDS MsgPack both round-trip typed arrays — already used by
44002
- * `storage` / `storage-provider` / `recording` caps over the same path. No
44003
- * base64 fallback needed.
44004
- *
44005
- * TODO (deferred, closed-set change — separate decision): add
44006
- * `providerKind: 'notify'` so notification providers surface on the unified
44007
- * admin "Integrations" page.
44008
- */
44009
- /**
44010
- * Zentik-derived typed-media enum — the superset across every kind. Each
44011
- * adapter picks what it supports and the degrade engine filters the rest.
44012
- */
44013
- var AttachmentMediaTypeSchema = _enum([
44014
- "image",
44015
- "video",
44016
- "gif",
44017
- "audio",
44018
- "icon"
44019
- ]);
44020
- /**
44021
- * A single attachment. Exactly one of `url` (remote source, most adapters
44022
- * prefer this) or `bytes` (inline source; required for Pushover-style
44023
- * bytes-only kinds) MUST be present — the degrade engine expresses a
44024
- * url→bytes fetch as a `needsFetch` directive the adapter executes.
44025
- */
44026
- var AttachmentSchema = object({
44027
- mediaType: AttachmentMediaTypeSchema,
44028
- url: string().optional(),
44029
- bytes: _instanceof(Uint8Array).optional(),
44030
- mime: string().optional(),
44031
- name: string().optional()
44032
- }).refine((a) => a.url !== void 0 || a.bytes !== void 0, { message: "Attachment requires either `url` or `bytes`" });
44033
- var NotificationFormatSchema = _enum([
44034
- "text",
44035
- "markdown",
44036
- "html"
44037
- ]);
44038
- /**
44039
- * The CLOSED icon vocabulary an action button may use.
44040
- *
44041
- * A closed set, not a free string, and that is the whole point: an arbitrary
44042
- * icon name is one that ntfy renders, zentik silently drops, and nobody
44043
- * notices — the same class of gap as a zone vocabulary nothing produced
44044
- * ([D35](../../../docs/decisions/adr-0035.md)). Every adapter maps this set or
44045
- * declares `actionIcons: false` and the degrade engine strips the field.
44046
- *
44047
- * Named by INTENT, never by glyph. "check" would tie the vocabulary to one
44048
- * renderer's icon set; "acknowledge" survives an adapter that draws it
44049
- * differently.
44050
- *
44051
- * ── A TOKEN IS NOT A WIRE VALUE ─────────────────────────────────────
44052
- *
44053
- * These names are for US. **No adapter may forward one verbatim.** Each maps
44054
- * the whole set onto its own renderer's vocabulary through a
44055
- * `Record<NotificationActionIcon, string>` — a Record, never a lookup with a
44056
- * fallback, so adding a member here fails every adapter's build until someone
44057
- * decides its glyph, which is the only place that decision can be made
44058
- * honestly.
44059
- *
44060
- * This paragraph is the bug. Zentik declared `actionIcons: true` and passed
44061
- * `disarm` straight through; iOS feeds that string to
44062
- * `UNNotificationActionIcon(systemImageName:)`, `disarm` is not an SF Symbol,
44063
- * and every snooze and alarm button arrived BLANK. A pass-through is not a
44064
- * mapping, and "the field is documented" is not "the value renders".
44065
- *
44066
- * Adding a member is TRAIN-BOUND. The enum lives in the published
44067
- * `@camstack/server` closure and the cap seam validates against the HUB's copy,
44068
- * so an addon that emits a token the running hub does not know does not lose an
44069
- * icon — its whole `send` fails Zod validation and the notification never
44070
- * arrives. Never emit a new token from an addon before the train carrying it.
44071
- */
44072
- var NotificationActionIconSchema = _enum([
44073
- "acknowledge",
44074
- "dismiss",
44075
- "silence",
44076
- "snooze",
44077
- "view",
44078
- "play",
44079
- "open",
44080
- "close",
44081
- "lock",
44082
- "unlock",
44083
- "arm",
44084
- "arm-home",
44085
- "arm-away",
44086
- "arm-night",
44087
- "disarm",
44088
- "light",
44089
- "alert",
44090
- "camera"
44091
- ]);
44092
- /** A single tap-through action button. */
44093
- var NotificationActionSchema = object({
44094
- id: string(),
44095
- label: string(),
44096
- url: string().optional(),
44097
- /** Dropped by the degrade engine for a kind with `caps.actionIcons: false`. */
44098
- icon: NotificationActionIconSchema.optional(),
44099
- /**
44100
- * Renders in a warning style where the notifier supports it.
44101
- *
44102
- * A HINT, never a gate. The callback's authority is its token and nothing
44103
- * else — see `notification-center/action-token.ts` for what that does and
44104
- * does not buy.
44105
- */
44106
- destructive: boolean().optional(),
44107
- /**
44108
- * How the tap should REACH the url.
44109
- *
44110
- * `navigate` (absent, and every button authored before this field) opens it:
44111
- * the phone leaves the notification and shows whatever the callback returns.
44112
- * That is right for a button whose answer the operator wants to read.
44113
- *
44114
- * `background` fires it as a POST and stays put. It exists for the buttons
44115
- * whose whole point is not to interrupt — "silence this for 30 minutes" is
44116
- * an answer to the notification, and being thrown into a browser tab to
44117
- * confirm it costs more attention than the notification did. A backend that
44118
- * cannot do a background call renders it as an ordinary link (the adapters
44119
- * fall back rather than dropping the button), so this is a preference, never
44120
- * a requirement.
44121
- */
44122
- mode: _enum(["navigate", "background"]).optional()
44123
- });
44124
- /** A delivery parameter value: what a notifier declared it takes. */
44125
- var DeliveryParamValueSchema = union([
44126
- string(),
44127
- number(),
44128
- boolean()
44129
- ]);
44130
- /**
44131
- * One extra delivery parameter a notifier KIND declares (D938). A rule that
44132
- * addresses a target of that kind may set it; a kind that declares nothing is
44133
- * never handed one. The admin UI derives its control from this descriptor —
44134
- * no editor knows a service by name.
44135
- *
44136
- * Optional fields are `.optional()`, never `.default()` (a Zod default does not
44137
- * run on the addon cap path).
44138
- */
44139
- var DeliveryParamSchema = object({
44140
- key: string().min(1),
44141
- label: string(),
44142
- /** i18n key of the label, resolved by the declaring addon's namespace. */
44143
- labelKey: string().optional(),
44144
- type: _enum([
44145
- "enum",
44146
- "number",
44147
- "boolean",
44148
- "string"
44149
- ]),
44150
- /** `enum` only: the closed set of accepted values. */
44151
- options: array(object({
44152
- value: string(),
44153
- label: string()
44154
- })).optional(),
44155
- /** `number` only. */
44156
- min: number().optional(),
44157
- max: number().optional(),
44158
- /** What the notifier does when the rule sets nothing; shown as the placeholder. */
44159
- default: DeliveryParamValueSchema.optional()
44160
- });
44161
- /**
44162
- * The canonical notification. `body` is the only hard field (Apprise model).
44163
- * `priority` is a 5-level ORDINAL (1=lowest … 3=normal(default) … 5=urgent),
44164
- * NOT a fixed severity enum — each kind declares its own `caps.levels` and
44165
- * the adapter maps this ordinal onto its native level. `level?` is an
44166
- * optional kind-native level id (`emergency`, `silent`, …) that overrides
44167
- * `priority` for that one target.
44168
- */
44169
- var NotificationSchema = object({
44170
- body: string(),
44171
- title: string().optional(),
44172
- format: NotificationFormatSchema.default("text"),
44173
- priority: number().int().min(1).max(5).default(3),
44174
- level: string().optional(),
44175
- attachments: array(AttachmentSchema).optional(),
44176
- clickUrl: string().optional(),
44177
- actions: array(NotificationActionSchema).optional(),
44178
- sound: string().optional(),
44179
- ttl: number().optional(),
44180
- tag: string().optional(),
44181
- deviceId: number().optional(),
44182
- eventId: string().optional(),
44183
- metadata: record(string(), unknown()).optional(),
44184
- /**
44185
- * Values for the parameters the target's kind DECLARES in
44186
- * {@link TargetKindSchema} `deliveryParams`. Already validated against the
44187
- * declaration by the sender; a notifier reads only the keys it declared.
44188
- */
44189
- delivery: record(string(), DeliveryParamValueSchema).optional()
44190
- });
44191
- /** One declared native severity/priority level for a kind. */
44192
- var TargetKindLevelSchema = object({
44193
- id: string(),
44194
- label: string(),
44195
- /** Which canonical priority (1..5) this level maps to. `null` = qualitative-only. */
44196
- ordinal: number().int().min(1).max(5).nullable(),
44197
- flags: object({
44198
- critical: boolean().optional(),
44199
- silent: boolean().optional(),
44200
- noPush: boolean().optional()
44201
- }).optional(),
44202
- /** e.g. Pushover `emergency` requires `retry` / `expire`. */
44203
- requires: array(string()).optional(),
44204
- description: string().optional()
44205
- });
44206
- /** The full capability block consulted before dispatch. */
44207
- var TargetKindCapsSchema = object({
44208
- attachments: object({
44209
- mediaTypes: array(AttachmentMediaTypeSchema),
44210
- mode: _enum([
44211
- "url",
44212
- "bytes",
44213
- "both"
44214
- ]),
44215
- max: number().int().nonnegative(),
44216
- maxBytes: number().int().positive().optional()
44217
- }),
44218
- /** Max action buttons (0 = none). */
44219
- actions: number().int().nonnegative(),
44220
- /**
44221
- * Whether this kind renders a per-action ICON.
44222
- *
44223
- * `.optional()`, deliberately NOT `.default(false)`: a Zod default does not
44224
- * run on the addon cap path — three production failures in one day taught
44225
- * this repo that once. Absent is read as false by the degrade engine, which
44226
- * is the safe direction: an icon that is not rendered costs nothing, an icon
44227
- * assumed and dropped costs the operator's trust in the field.
44228
- */
44229
- actionIcons: boolean().optional(),
44230
- levels: array(TargetKindLevelSchema),
44231
- format: array(NotificationFormatSchema),
44232
- clickUrl: boolean(),
44233
- sound: boolean(),
44234
- ttl: boolean(),
44235
- bodyMaxLen: number().int().positive()
44236
- });
44237
- /**
44238
- * `configSchema` is a `ConfigUISchema` tree passed through to the admin
44239
- * FormBuilder. Stored as `z.unknown()` at the cap seam (mirrors
44240
- * `device-provider.getChildCreationSchema` `CreationSchemaOutputSchema`) —
44241
- * the union is large and not meant for runtime validation here; the exported
44242
- * `TargetKind` type re-tightens `configSchema` to `ConfigUISchema`.
44243
- */
44244
- var ConfigSchemaPassthrough$4 = unknown();
44245
- var TargetKindSchema = object({
44246
- kind: string(),
44247
- label: string(),
44248
- icon: string(),
44249
- /** Stamped by each provider so the concat-fanned catalog stays routable. */
44250
- addonId: string(),
44251
- /**
44252
- * URL of the kind's bundled BRAND icon, served by the providing addon over
44253
- * its own `addon-routes` surface (`/addon/<addonId>/icons/<kind>`). Absent
44254
- * when the addon bundles no icon for that kind — the client then falls back
44255
- * to a neutral glyph rather than rendering the raw `icon` NAME as text.
44256
- *
44257
- * Root-relative on purpose: it resolves against whatever origin serves a web
44258
- * client, and a native client joins it onto its own hub base.
44259
- *
44260
- * DECLARED here deliberately. It used to travel as an undeclared passthrough
44261
- * field that survived only because the runtime cap-router forwards provider
44262
- * output verbatim — so every consumer had to re-declare it by hand to stop
44263
- * its own Zod parse from stripping it, and the whole arrangement would have
44264
- * broken silently the moment output validation was tightened anywhere.
44265
- */
44266
- iconUrl: string().optional(),
44267
- /**
44268
- * Media type of {@link iconUrl} (`image/svg+xml`, `image/png`, …).
44269
- *
44270
- * The server knows this and therefore says it, because the client cannot
44271
- * safely guess: a React-Native client renders SVG and raster through two
44272
- * DIFFERENT components (`react-native-svg` vs `expo-image` — expo-image does
44273
- * not decode SVG on iOS/Android), so without this it silently fell back to a
44274
- * placeholder glyph for every vector icon while the web build looked fine.
44275
- *
44276
- * Absent when {@link iconUrl} is absent, or for a legacy provider that has
44277
- * not been updated — a client that cannot determine the type should prefer
44278
- * its raster path, which is the safe default for an unknown image.
44279
- */
44280
- iconMediaType: string().optional(),
44281
- configSchema: ConfigSchemaPassthrough$4,
44282
- /**
44283
- * The config keys that decide WHERE this kind's secrets are sent (server,
44284
- * base URL, instance, chat, recipient). A save that changes any of them
44285
- * while leaving a secret redacted is refused by the provider (D634), so an
44286
- * editor uses this to ask for the secret on exactly those edits instead of
44287
- * on every edit.
44288
- *
44289
- * Optional: absent from a provider that holds no secret (the Home Assistant
44290
- * kinds) and from a provider older than this field — an editor that finds
44291
- * it absent must assume ANY edit may need the secret.
44292
- */
44293
- destinationKeys: array(string()).optional(),
44294
- supportsDiscovery: boolean(),
44434
+ conditions: array(AutomationConditionTraceNodeSchema),
44435
+ verdict: AutomationRunVerdictSchema.optional(),
44436
+ steps: array(AutomationStepTraceSchema),
44437
+ outcome: AutomationRunOutcomeSchema,
44438
+ /** How many identical consecutive skips this trace stands for (>= 1). */
44439
+ repeat: number().int().min(1),
44440
+ /** When the latest of those repeats happened. */
44441
+ lastAt: number(),
44295
44442
  /**
44296
- * Extra delivery parameters a rule may set for a target of this kind (D938).
44297
- * Absent = none; the rule editor then offers nothing.
44443
+ * A scheduler point's own outcome (D983). `outcome` carries the closest
44444
+ * automation outcome so a reader that does not know schedulers still reads
44445
+ * the trace; this field says exactly what happened.
44298
44446
  */
44299
- deliveryParams: array(DeliveryParamSchema).optional(),
44300
- caps: TargetKindCapsSchema
44447
+ scheduler: SchedulerOutcomeSchema.optional()
44301
44448
  });
44302
44449
  /**
44303
- * A persisted target. `config` holds secrets; providers REDACT secret fields
44304
- * (return a presence marker only) when serving `listTargets` — never
44305
- * round-trip a stored secret to the UI.
44450
+ * What the hub's `runs` ledger holds for one owner (`automation:<blockId>` or
44451
+ * `action:<actionId>`): the cooldown stamp and the trace ring.
44306
44452
  */
44307
- var TargetSchema = object({
44308
- id: string(),
44309
- name: string(),
44310
- kind: string(),
44311
- addonId: string(),
44312
- enabled: boolean(),
44313
- config: record(string(), unknown())
44453
+ var AutomationStateDocSchema = object({
44454
+ version: literal(1),
44455
+ lastRunStartedAt: number().nullable(),
44456
+ traces: array(AutomationRunTraceSchema)
44314
44457
  });
44315
- /** A discovery-surfaced candidate (config is partial + non-secret). */
44316
- var DiscoveredTargetSchema = object({
44317
- kind: string(),
44318
- suggestedName: string(),
44319
- config: record(string(), unknown())
44458
+ /**
44459
+ * Actions — named, runnable things an operator (or an automation) can start,
44460
+ * declared as LIST ENTRIES, never as devices.
44461
+ *
44462
+ * An entry is either **internal** (a short list of cap/wait steps kept in the
44463
+ * hub's `actions` record kind) or declared by an addon through the
44464
+ * `action-source` collection (a Home Assistant script, a scene …). The one
44465
+ * surface the UI and automations talk to is the `actions` cap; it keeps no
44466
+ * catalog of its own (D3) — every `list` asks the providers live.
44467
+ *
44468
+ * This file is the data half: the entry schema, the variables an entry may
44469
+ * declare, and the pure resolution of the values a run was given. It holds no
44470
+ * runtime.
44471
+ */
44472
+ /** What a variable's value is. `select` takes one of `options`. */
44473
+ var ActionVariableTypeSchema = _enum([
44474
+ "string",
44475
+ "number",
44476
+ "boolean",
44477
+ "select"
44478
+ ]);
44479
+ var ACTION_VARIABLE_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
44480
+ var ActionVariableValueSchema = union([
44481
+ string(),
44482
+ number(),
44483
+ boolean()
44484
+ ]);
44485
+ /**
44486
+ * One declared variable. Steps reference it as `{ $var: 'name' }` (the whole
44487
+ * value) or `{{vars.name}}` (inside a string) in their args.
44488
+ */
44489
+ var ActionVariableSchema = object({
44490
+ name: string().regex(ACTION_VARIABLE_NAME_RE),
44491
+ label: string().min(1).max(120).optional(),
44492
+ type: ActionVariableTypeSchema,
44493
+ required: boolean().optional(),
44494
+ default: ActionVariableValueSchema.optional(),
44495
+ /** The allowed values of a `select`. */
44496
+ options: array(string().min(1)).min(1).optional()
44497
+ }).superRefine((v, ctx) => {
44498
+ if (v.type === "select" && v.options === void 0) ctx.addIssue({
44499
+ code: "custom",
44500
+ message: "a select variable needs options",
44501
+ path: ["options"]
44502
+ });
44503
+ if (v.default !== void 0 && variableValueError(v, v.default) !== null) ctx.addIssue({
44504
+ code: "custom",
44505
+ message: variableValueError(v, v.default) ?? "invalid default",
44506
+ path: ["default"]
44507
+ });
44320
44508
  });
44321
- /** The degrade engine's report — what was resolved / dropped / degraded. */
44322
- var RenderedAsSchema = object({
44323
- level: string(),
44324
- format: NotificationFormatSchema,
44325
- attachmentsSent: number().int().nonnegative(),
44326
- actionsSent: number().int().nonnegative(),
44327
- truncated: boolean(),
44328
- dropped: array(string())
44509
+ /** Why `value` is not a legal value for the variable, or null when it is. */
44510
+ function variableValueError(variable, value) {
44511
+ switch (variable.type) {
44512
+ case "string": return typeof value === "string" ? null : `variable "${variable.name}" must be a string`;
44513
+ case "number": return typeof value === "number" && Number.isFinite(value) ? null : `variable "${variable.name}" must be a number`;
44514
+ case "boolean": return typeof value === "boolean" ? null : `variable "${variable.name}" must be true or false`;
44515
+ case "select": return typeof value === "string" && (variable.options ?? []).includes(value) ? null : `variable "${variable.name}" must be one of ${(variable.options ?? []).join(", ")}`;
44516
+ }
44517
+ }
44518
+ var ActionSourceKindSchema = _enum(["internal", "addon"]);
44519
+ function isInternalActionId(actionId) {
44520
+ return actionId.startsWith("internal:") && actionId.length > 9;
44521
+ }
44522
+ /** The addon behind a `<addonId>:<localId>` id, or null for anything else (internal included). */
44523
+ function addonIdOfActionId(actionId) {
44524
+ if (isInternalActionId(actionId)) return null;
44525
+ const at = actionId.indexOf(":");
44526
+ return at > 0 && at < actionId.length - 1 ? actionId.slice(0, at) : null;
44527
+ }
44528
+ var ActionStatusSchema = object({
44529
+ isRunning: boolean(),
44530
+ /** Ms epoch the latest run STARTED; null when it never ran. */
44531
+ lastRunAt: number().nullable(),
44532
+ /** The latest run's failure; null on success or when it never ran. */
44533
+ lastError: string().nullable()
44329
44534
  });
44330
- var SendResultSchema = object({
44331
- success: boolean(),
44332
- error: string().optional(),
44333
- renderedAs: RenderedAsSchema.optional()
44535
+ var ActionEntrySchema = object({
44536
+ /** `internal:<uuid>` or `<addonId>:<localId>`. */
44537
+ id: string().min(3),
44538
+ name: string().min(1).max(120),
44539
+ /** The addon that declared it; `core-blocks` for an internal one. */
44540
+ addonId: string().min(1),
44541
+ source: ActionSourceKindSchema,
44542
+ /** An addon-declared entry is edited where it was declared. */
44543
+ readOnly: boolean(),
44544
+ /** Internal only: cap and wait steps. No action-in-action, so no cycles. */
44545
+ steps: array(ActionStepSchema).min(1).max(50).optional(),
44546
+ variables: array(ActionVariableSchema).max(20).optional(),
44547
+ status: ActionStatusSchema
44548
+ }).superRefine((entry, ctx) => {
44549
+ if (entry.source === "internal") {
44550
+ if (!isInternalActionId(entry.id)) ctx.addIssue({
44551
+ code: "custom",
44552
+ message: "an internal action id is internal:<uuid>",
44553
+ path: ["id"]
44554
+ });
44555
+ return;
44556
+ }
44557
+ if (entry.steps !== void 0) ctx.addIssue({
44558
+ code: "custom",
44559
+ message: "only an internal action carries steps",
44560
+ path: ["steps"]
44561
+ });
44562
+ if (!entry.readOnly) ctx.addIssue({
44563
+ code: "custom",
44564
+ message: "an addon action is read-only here",
44565
+ path: ["readOnly"]
44566
+ });
44567
+ if (addonIdOfActionId(entry.id) === null) ctx.addIssue({
44568
+ code: "custom",
44569
+ message: "an addon action id is <addonId>:<localId>",
44570
+ path: ["id"]
44571
+ });
44334
44572
  });
44335
- /** Same shape as SendResult — kept as a distinct name for the test panel. */
44336
- var TestResultSchema = SendResultSchema;
44573
+ /** What an operator writes for an internal action. */
44574
+ var ActionInputSchema = object({
44575
+ name: string().min(1).max(120),
44576
+ steps: array(ActionStepSchema).min(1).max(50),
44577
+ variables: array(ActionVariableSchema).max(20).optional()
44578
+ });
44579
+ /** Who started a run. Absent = the operator pressed it. */
44580
+ var ActionRunOriginSchema = object({
44581
+ /** The automation block whose step started it. */
44582
+ blockId: string().min(1).optional() });
44337
44583
  /**
44338
- * Pre-save credential probe against a partial (unsaved) target config.
44339
- * `resolvedUrl` never includes secrets (token stripped from path).
44584
+ * `started` = the caller did not ask to wait. `timed-out` = the run reached the
44585
+ * ceiling (`ACTION_RUN_MAX_MS`) and was stopped; it is never a `ran`.
44340
44586
  */
44341
- var ProbeTargetConfigResultSchema = object({
44342
- ok: boolean(),
44343
- resolvedUrl: string(),
44344
- httpStatus: number().int().optional(),
44345
- stateInstance: string().optional(),
44346
- error: string().optional()
44587
+ var ActionRunOutcomeSchema = union([
44588
+ AutomationRunOutcomeSchema,
44589
+ literal("started"),
44590
+ literal("timed-out")
44591
+ ]);
44592
+ var ActionRunResultSchema = object({
44593
+ runId: string().min(1),
44594
+ outcome: ActionRunOutcomeSchema,
44595
+ /** Why it did not run, or what failed. */
44596
+ message: string().optional()
44347
44597
  });
44348
- method(object({}), array(TargetKindSchema)), method(object({}), array(TargetSchema), { auth: "admin" }), method(object({ targetId: string() }), TargetSchema, { auth: "admin" }), method(object({
44349
- kind: string(),
44350
- config: record(string(), unknown()).optional(),
44351
- /**
44352
- * When editing / duplicating, the blank password field never round-trips
44353
- * the stored token. Pass the source target id so the provider can restore
44354
- * secrets server-side before dialling (same merge as upsert).
44355
- */
44356
- targetId: string().optional()
44357
- }), array(DiscoveredTargetSchema), { auth: "admin" }), method(object({
44358
- kind: string(),
44359
- config: record(string(), unknown()),
44360
- /** See `discoverTargets.targetId` — restore stored secrets for a blank password. */
44361
- targetId: string().optional()
44362
- }), ProbeTargetConfigResultSchema, {
44363
- kind: "mutation",
44364
- auth: "admin"
44365
- }), method(object({
44366
- targetId: string(),
44367
- notification: NotificationSchema
44368
- }), SendResultSchema, {
44369
- kind: "mutation",
44370
- auth: "admin"
44371
- }), method(object({
44372
- targetId: string(),
44373
- sample: NotificationSchema.optional()
44374
- }), TestResultSchema, {
44375
- kind: "mutation",
44376
- auth: "admin"
44377
- }), method(object({
44378
- target: TargetSchema,
44379
- /**
44380
- * Duplicate flow: create a NEW target id while copying secrets from an
44381
- * existing row. The UI never holds the stored token; blank / redacted
44382
- * password fields are restored from this source (D634 still applies if
44383
- * destinations diverge without a re-typed secret).
44384
- */
44385
- cloneSecretsFrom: string().optional()
44386
- }), TargetSchema, {
44387
- kind: "mutation",
44388
- auth: "admin"
44389
- }), method(object({ targetId: string() }), _void(), {
44390
- kind: "mutation",
44391
- auth: "admin"
44392
- }), method(object({
44393
- targetId: string(),
44394
- enabled: boolean()
44395
- }), _void(), {
44396
- kind: "mutation",
44397
- auth: "admin"
44598
+ _enum([
44599
+ "not-found",
44600
+ "read-only",
44601
+ "invalid-variables",
44602
+ "invalid-steps",
44603
+ "not-linked",
44604
+ "busy"
44605
+ ]);
44606
+ object({
44607
+ actionId: string(),
44608
+ runId: string(),
44609
+ isRunning: boolean(),
44610
+ /** Set when the run ended. */
44611
+ outcome: AutomationRunOutcomeSchema.optional(),
44612
+ lastRunAt: number().nullable(),
44613
+ lastError: string().nullable()
44614
+ });
44615
+ /** A bare number accepted as a base unit — the save succeeded, say so. */
44616
+ var UnitWarningSchema = object({
44617
+ /** Where in the saved record, e.g. `conditions.children.0` or `steps.2.args.grams`. */
44618
+ path: string(),
44619
+ deviceId: number().int().optional(),
44620
+ field: string(),
44621
+ value: number(),
44622
+ assumedUnit: string(),
44623
+ message: string()
44398
44624
  });
44399
44625
  _enum([
44400
44626
  "automation",
@@ -44463,6 +44689,8 @@ method(object({}), array(ActionEntrySchema), { auth: "admin" }), method(object({
44463
44689
  kind: "mutation",
44464
44690
  auth: "admin"
44465
44691
  });
44692
+ /** `timeoutMs` of `actions.run`: a waited call outlives any legal run. */
44693
+ var ACTION_RUN_TIMEOUT_MS = 363e4;
44466
44694
  /**
44467
44695
  * actions — the ONE surface for runnable actions, for the UI and for
44468
44696
  * automations. Provided by the core-blocks builtin on the hub.
@@ -44481,6 +44709,12 @@ method(object({}), array(ActionEntrySchema), { auth: "admin" }), method(object({
44481
44709
  * An admin, and an in-process caller (an automation block), may run any action.
44482
44710
  * Every refusal is typed (`[not-linked] …`) and logged.
44483
44711
  *
44712
+ * **A run lasts at most `ACTION_RUN_MAX_MS` (60 min).** The provider stops a
44713
+ * run that reaches it and answers `timed-out` (never `ran`); an action whose
44714
+ * `wait` steps alone add up to more is refused at create/update
44715
+ * (`[invalid-steps]`). `run` declares a `timeoutMs` above that ceiling, so a
44716
+ * waited call (an automation step) is never cut by the 60 s transport default.
44717
+ *
44484
44718
  * A second `run` of an action that is already running is REFUSED — traced and
44485
44719
  * logged — never queued.
44486
44720
  */
@@ -44507,7 +44741,8 @@ method(object({}), array(ActionEntrySchema), { auth: "admin" }), method(object({
44507
44741
  role: "viewer",
44508
44742
  auth: "protected",
44509
44743
  kind: "mutation",
44510
- caller: "required"
44744
+ caller: "required",
44745
+ timeoutMs: ACTION_RUN_TIMEOUT_MS
44511
44746
  }), method(ActionIdInput, _void(), {
44512
44747
  kind: "mutation",
44513
44748
  auth: "admin"
@@ -48293,37 +48528,6 @@ method(object({
48293
48528
  kind: "mutation",
48294
48529
  auth: "admin"
48295
48530
  }), method(object({ blockIds: array(string()) }), object({ states: array(CompositionBlockStateSchema) }), { auth: "admin" });
48296
- var ConnectionTestOutcomeSchema = discriminatedUnion("outcome", [
48297
- object({
48298
- outcome: literal("validated"),
48299
- /** Round-trip of the sign-in, when the provider measured it. */
48300
- latencyMs: number().nonnegative().optional(),
48301
- /** Optional human detail worth showing next to the tick
48302
- * ("3 devices visible on this account"). */
48303
- detail: string().optional()
48304
- }).strict(),
48305
- object({
48306
- outcome: literal("rejected"),
48307
- error: string()
48308
- }).strict(),
48309
- object({
48310
- outcome: literal("inconclusive"),
48311
- error: string()
48312
- }).strict()
48313
- ]);
48314
- var ConnectionTestInputSchema = object({
48315
- /** Candidate integration settings, exactly as the create form collected them. */
48316
- settings: record(string(), unknown()) });
48317
- /**
48318
- * What the provider's test actually DOES, so the UI can say it in words before
48319
- * the operator presses the button ("Signs in to the Dreo cloud"). Purely
48320
- * descriptive — it never changes routing.
48321
- */
48322
- var ConnectionTestDescriptorSchema = object({ label: string() });
48323
- method(ConnectionTestInputSchema, ConnectionTestOutcomeSchema, {
48324
- kind: "mutation",
48325
- auth: "admin"
48326
- }), method(_void(), ConnectionTestDescriptorSchema, { auth: "admin" });
48327
48531
  object({
48328
48532
  /** True when the upstream system considers the entity connected. */
48329
48533
  connected: boolean(),
@@ -48581,6 +48785,9 @@ var MediaPlayerStatusSchema = object({
48581
48785
  /** Repeat mode. Null when no repeat surface.
48582
48786
  * Pair with `DeviceFeature.MediaPlayerRepeat`. */
48583
48787
  repeat: MediaPlayerRepeatSchema.nullable(),
48788
+ /** Ms epoch when `position` was read from the device. Null when the driver
48789
+ * does not say; a UI that advances the position while playing counts from it. */
48790
+ positionUpdatedAt: number().nullable().default(null),
48584
48791
  /** Ms epoch when the slice was last updated. */
48585
48792
  lastChangedAt: number()
48586
48793
  });
@@ -49160,7 +49367,9 @@ var ThresholdTransformDraftSchema = object({
49160
49367
  comparison: _enum(["gte", "lte"]),
49161
49368
  threshold: number(),
49162
49369
  startDwellMs: number().nonnegative(),
49163
- stopDwellMs: number().nonnegative()
49370
+ stopDwellMs: number().nonnegative(),
49371
+ /** Samples a start needs; absent = the compiler's default for the source (2 for running power, else 1). */
49372
+ minSamples: number().int().min(1).optional()
49164
49373
  });
49165
49374
  var CustomizeTransformDraftSchema = discriminatedUnion("kind", [
49166
49375
  IdentityTransformDraftSchema,
@@ -54113,6 +54322,7 @@ var IntegrationWithStateSchema = object({
54113
54322
  id: string(),
54114
54323
  addonId: string(),
54115
54324
  name: string(),
54325
+ /** A projection of the instance body's switch (`setInstanceEnabled` is the only writer). */
54116
54326
  enabled: boolean(),
54117
54327
  info: record(string(), unknown()).readonly(),
54118
54328
  /** The discovery candidate this integration was set up from (D984). */
@@ -54125,6 +54335,7 @@ var IntegrationLiteSchema = object({
54125
54335
  id: string(),
54126
54336
  addonId: string(),
54127
54337
  name: string(),
54338
+ /** A projection of the instance body's switch (`setInstanceEnabled` is the only writer). */
54128
54339
  enabled: boolean(),
54129
54340
  info: record(string(), unknown()).readonly(),
54130
54341
  /** The discovery candidate this integration was set up from (D984). */
@@ -54170,10 +54381,9 @@ var AvailableIntegrationTypeSchema = object({
54170
54381
  * locations" checkbox. Provider-declared in the addon manifest. */
54171
54382
  supportsLocationImport: boolean(),
54172
54383
  /**
54173
- * True when this integration DECLARES a pre-creation test (the
54174
- * `connection-test` cap, or a broker whose settings it stores). Drives the
54175
- * Test button: an integration that cannot be tested must say so up front
54176
- * rather than offering a button that always answers the same nonsense.
54384
+ * True when this integration's instances declare a Test (`integration-instances.describe().canTest`,
54385
+ * D1016). An integration that cannot be tested must say so up front rather than offering a
54386
+ * button that always answers the same nonsense.
54177
54387
  */
54178
54388
  canTest: boolean(),
54179
54389
  existingInstances: array(object({
@@ -54224,15 +54434,21 @@ var TestConnectionResultSchema = object({
54224
54434
  var CreateIntegrationInputSchema = object({
54225
54435
  addonId: string(),
54226
54436
  name: string(),
54227
- enabled: boolean().optional(),
54228
54437
  info: record(string(), unknown()).optional(),
54229
54438
  /** `stableId` of the discovery candidate the form was seeded from (D984). */
54230
54439
  originStableId: string().optional(),
54231
- settings: record(string(), unknown()).optional()
54440
+ settings: record(string(), unknown()).optional(),
54441
+ /** The instance kind being created, for a provider with several; omitted = its only testable kind. */
54442
+ kind: string().min(1).optional()
54232
54443
  });
54233
54444
  var UpdateIntegrationInputSchema = object({
54234
54445
  id: string(),
54235
54446
  name: string().optional(),
54447
+ /**
54448
+ * Accepted for a FIXED builtin only (`info.fixed`: alarm panel, camera grid, core blocks,
54449
+ * terminal), which keeps no instance record: the registry flag is its one store. Any other
54450
+ * integration is switched through `integration-instances.setInstanceEnabled`.
54451
+ */
54236
54452
  enabled: boolean().optional(),
54237
54453
  info: record(string(), unknown()).optional()
54238
54454
  });
@@ -54249,13 +54465,7 @@ method(_void(), array(IntegrationWithStateSchema)), method(object({ id: string()
54249
54465
  }), method(object({ id: string() }), DeleteIntegrationResultSchema, {
54250
54466
  kind: "mutation",
54251
54467
  auth: "admin"
54252
- }), method(_void(), array(AvailableIntegrationTypeSchema), { auth: "admin" }), method(object({
54253
- addonId: string(),
54254
- settings: record(string(), unknown())
54255
- }), TestConnectionResultSchema, {
54256
- kind: "mutation",
54257
- auth: "admin"
54258
- });
54468
+ }), method(_void(), array(AvailableIntegrationTypeSchema), { auth: "admin" });
54259
54469
  /**
54260
54470
  * `integration-instances` - the connection of an addon that holds ONE or SEVERAL
54261
54471
  * (an account, a relay, a destination) as typed records (D985, D986). The addon's
@@ -54280,7 +54490,7 @@ var IntegrationInstanceIdSchema = string().min(1);
54280
54490
  var IntegrationInstanceModeSchema = _enum(["single", "multiple"]);
54281
54491
  /**
54282
54492
  * What the addon's instances ARE for the Integrations page (planning#416). `devices`: each
54283
- * instance is an integration that brings devices (the registry owns its on/off switch);
54493
+ * instance is an integration that brings devices (its record body owns the on/off switch);
54284
54494
  * `services`: a connection configured from the addon's own function page, never listed on
54285
54495
  * Integrations.
54286
54496
  * It is the same vocabulary as the manifest's `integrationRole`, which stays as an override.
@@ -54397,8 +54607,8 @@ var IntegrationInstanceSchema = object({
54397
54607
  configured: boolean(),
54398
54608
  /**
54399
54609
  * The instance's own on/off switch (D996), derived from the record body (`enabled !== false`,
54400
- * so a row written before the field existed is on). Absent when the `integrations` registry
54401
- * owns the switch (`describe().role` is `devices`): read it from the registry row.
54610
+ * so a row written before the field existed is on). The same for every role, `devices` included:
54611
+ * the body is the one store, `setInstanceEnabled` the one writer (epic #440, step 3).
54402
54612
  */
54403
54613
  enabled: boolean().optional(),
54404
54614
  /** The kind of this instance (one of `describe().kinds[].id`), when the provider has kinds. */
@@ -54448,7 +54658,8 @@ var integrationInstancesCapability = {
54448
54658
  auth: "admin"
54449
54659
  }),
54450
54660
  /**
54451
- * Switch ONE instance on or off. A row control, not a form field: `updateInstance.values` is the
54661
+ * Switch ONE instance on or off, for every role; a missing record is created from the addon's
54662
+ * initial body. A row control, not a form field: `updateInstance.values` is the
54452
54663
  * form patch (D62, D996). An off instance keeps its record and secrets and does no work.
54453
54664
  */
54454
54665
  setInstanceEnabled: method(object({
@@ -57259,6 +57470,8 @@ var MigrationIntegrationSchema = object({
57259
57470
  addonId: string(),
57260
57471
  name: string(),
57261
57472
  info: Rows,
57473
+ /** The registry's stored switch: read by the one-switch migration, nothing else. */
57474
+ enabled: boolean().optional(),
57262
57475
  originStableId: string().optional()
57263
57476
  });
57264
57477
  var MigrationDeviceSchema = object({
@@ -62495,13 +62708,6 @@ var AddBrokerInputSchema = object({
62495
62708
  });
62496
62709
  var AddBrokerResultSchema = object({ id: string() });
62497
62710
  var IdInputSchema = object({ id: string() });
62498
- var TestResultSchema$1 = discriminatedUnion("ok", [object({
62499
- ok: literal(true),
62500
- latencyMs: number()
62501
- }), object({
62502
- ok: literal(false),
62503
- error: string()
62504
- })]);
62505
62711
  var StartEmbeddedInputSchema = object({
62506
62712
  port: number().int().min(1).max(65535).default(1883),
62507
62713
  /** Allow anonymous connect (no username/password). Default: false. */
@@ -62524,9 +62730,6 @@ method(_void(), array(BrokerInfoSchema)), method(IdInputSchema, BrokerConnection
62524
62730
  }), method(IdInputSchema, _void(), {
62525
62731
  kind: "mutation",
62526
62732
  auth: "admin"
62527
- }), method(IdInputSchema, TestResultSchema$1, {
62528
- kind: "mutation",
62529
- auth: "admin"
62530
62733
  }), method(StartEmbeddedInputSchema, StartEmbeddedResultSchema, {
62531
62734
  kind: "mutation",
62532
62735
  auth: "admin"
@@ -66777,14 +66980,6 @@ object({
66777
66980
  empty: boolean().nullable(),
66778
66981
  /** True while the pump is running. Null while unknown. */
66779
66982
  pumpRunning: boolean().nullable(),
66780
- /** Water drunk in the last drink, in litres. */
66781
- lastDrink: number().min(0).nullable().meta(readingMeta("volume")),
66782
- /** Water drunk in the current hour, in litres. */
66783
- currentHourDrink: number().min(0).nullable().meta(readingMeta("volume")),
66784
- /** Water drunk over the last 24 hours (rolling), in litres. */
66785
- last24hDrink: number().min(0).nullable().meta(readingMeta("volume")),
66786
- /** Water drunk since local midnight, in litres. Null when the fountain has no such sensor. */
66787
- todayDrink: number().min(0).nullable().meta(readingMeta("volume")),
66788
66983
  /** Decoded fault message. Null means healthy; a non-null string is an active fault. */
66789
66984
  error: string().nullable(),
66790
66985
  /** Ms epoch when the slice was last refreshed. */
@@ -66797,9 +66992,6 @@ DeviceType.PetFountain, method(object({
66797
66992
  }), _void(), {
66798
66993
  kind: "mutation",
66799
66994
  auth: "protected"
66800
- }), method(object({ deviceId: DeviceIdSchema$1 }), _void(), {
66801
- kind: "mutation",
66802
- auth: "protected"
66803
66995
  });
66804
66996
  /**
66805
66997
  * The wire shapes of the Auto tune plan and apply (D745), used by the
@@ -74162,7 +74354,7 @@ var TrainingProviderTypeSchema = object({
74162
74354
  label: string(),
74163
74355
  /** Path under the addon package (e.g. `assets/training-modal/icon.svg`). */
74164
74356
  iconAsset: string(),
74165
- /** Owning `training-provider` addon — collection selector for createEntry. */
74357
+ /** Owning `training-provider` addon. */
74166
74358
  addonId: string(),
74167
74359
  /**
74168
74360
  * Fields for one entry of this type (credentials + defaults). Absent on a
@@ -74207,36 +74399,6 @@ var TrainingProviderDescriptorSchema = object({
74207
74399
  */
74208
74400
  formValues: record(string(), unknown()).optional()
74209
74401
  });
74210
- /**
74211
- * Patch one entry's name, credentials and defaults. Pin with owning `{ addonId }`.
74212
- * An omitted or empty `tokenSecret` means KEEP the stored secret (D787).
74213
- * `{ $secretClear: true }` clears it.
74214
- */
74215
- var TrainingProviderUpdateEntryInputSchema = object({
74216
- entryId: string().min(1),
74217
- name: string().min(1),
74218
- tokenId: string().optional(),
74219
- tokenSecret: union([string(), object({ $secretClear: literal(true) })]).optional(),
74220
- environment: string().optional(),
74221
- gpuType: string().optional(),
74222
- region: string().optional(),
74223
- costCapUsd: number().nonnegative().optional(),
74224
- maxRuntimeSec: number().int().positive().optional(),
74225
- failedDatasetGraceHours: number().nonnegative().optional()
74226
- });
74227
- var TrainingCredentialCheckSchema = object({
74228
- ok: boolean(),
74229
- /** Workspace / account name, when the provider says. */
74230
- account: string().optional(),
74231
- reason: _enum([
74232
- "missing",
74233
- "invalid",
74234
- "forbidden",
74235
- "network",
74236
- "quota"
74237
- ]).optional(),
74238
- detail: string().optional()
74239
- });
74240
74402
  var ProviderJobStateSchema = _enum([
74241
74403
  "pending",
74242
74404
  "starting",
@@ -74284,22 +74446,6 @@ var TrainingLogLineSchema = object({
74284
74446
  text: string()
74285
74447
  });
74286
74448
  method(object({}), array(TrainingProviderDescriptorSchema).readonly(), { auth: "admin" }), method(object({}), array(TrainingProviderTypeSchema).readonly(), { auth: "admin" }), method(object({}), array(TrainingProviderEntrySchema).readonly(), { auth: "admin" }), method(object({
74287
- typeId: string().min(1),
74288
- name: string().min(1)
74289
- }), object({ entryId: string() }), {
74290
- kind: "mutation",
74291
- auth: "admin"
74292
- }), method(object({ entryId: string().min(1) }), object({ ok: literal(true) }), {
74293
- kind: "mutation",
74294
- auth: "admin"
74295
- }), method(TrainingProviderUpdateEntryInputSchema, object({ ok: literal(true) }), {
74296
- kind: "mutation",
74297
- auth: "admin"
74298
- }), method(object({ entryId: string().min(1) }), TrainingCredentialCheckSchema, {
74299
- kind: "mutation",
74300
- auth: "admin",
74301
- timeoutMs: 3e4
74302
- }), method(object({
74303
74449
  entryId: string().min(1),
74304
74450
  gpuType: string(),
74305
74451
  region: string(),
@@ -77685,20 +77831,6 @@ Object.freeze({
77685
77831
  access: "view",
77686
77832
  role: "admin"
77687
77833
  },
77688
- "connectionTest.describeTest": {
77689
- capName: "connection-test",
77690
- capScope: "system",
77691
- addonId: null,
77692
- access: "view",
77693
- role: "admin"
77694
- },
77695
- "connectionTest.testSettings": {
77696
- capName: "connection-test",
77697
- capScope: "system",
77698
- addonId: null,
77699
- access: "create",
77700
- role: "admin"
77701
- },
77702
77834
  "connectivity.getStatus": {
77703
77835
  capName: "connectivity",
77704
77836
  capScope: "device",
@@ -80065,13 +80197,6 @@ Object.freeze({
80065
80197
  access: "view",
80066
80198
  role: "admin"
80067
80199
  },
80068
- "integrations.testConnection": {
80069
- capName: "integrations",
80070
- capScope: "system",
80071
- addonId: null,
80072
- access: "create",
80073
- role: "admin"
80074
- },
80075
80200
  "integrations.update": {
80076
80201
  capName: "integrations",
80077
80202
  capScope: "system",
@@ -81304,13 +81429,6 @@ Object.freeze({
81304
81429
  access: "create",
81305
81430
  role: "admin"
81306
81431
  },
81307
- "mqttBroker.testConnection": {
81308
- capName: "mqtt-broker",
81309
- capScope: "system",
81310
- addonId: null,
81311
- access: "create",
81312
- role: "admin"
81313
- },
81314
81432
  "nativeObjectDetection.getOptions": {
81315
81433
  capName: "native-object-detection",
81316
81434
  capScope: "device",
@@ -82186,13 +82304,6 @@ Object.freeze({
82186
82304
  access: "view",
82187
82305
  role: "viewer"
82188
82306
  },
82189
- "petFountain.resetDailyConsumption": {
82190
- capName: "pet-fountain",
82191
- capScope: "device",
82192
- addonId: null,
82193
- access: "delete",
82194
- role: "viewer"
82195
- },
82196
82307
  "petFountain.setPump": {
82197
82308
  capName: "pet-fountain",
82198
82309
  capScope: "device",
@@ -86148,20 +86259,6 @@ Object.freeze({
86148
86259
  access: "create",
86149
86260
  role: "admin"
86150
86261
  },
86151
- "trainingProvider.createEntry": {
86152
- capName: "training-provider",
86153
- capScope: "system",
86154
- addonId: null,
86155
- access: "create",
86156
- role: "admin"
86157
- },
86158
- "trainingProvider.deleteEntry": {
86159
- capName: "training-provider",
86160
- capScope: "system",
86161
- addonId: null,
86162
- access: "delete",
86163
- role: "admin"
86164
- },
86165
86262
  "trainingProvider.describe": {
86166
86263
  capName: "training-provider",
86167
86264
  capScope: "system",
@@ -86232,13 +86329,6 @@ Object.freeze({
86232
86329
  access: "create",
86233
86330
  role: "admin"
86234
86331
  },
86235
- "trainingProvider.updateEntry": {
86236
- capName: "training-provider",
86237
- capScope: "system",
86238
- addonId: null,
86239
- access: "create",
86240
- role: "admin"
86241
- },
86242
86332
  "trainingProvider.uploadDataset": {
86243
86333
  capName: "training-provider",
86244
86334
  capScope: "system",
@@ -86246,13 +86336,6 @@ Object.freeze({
86246
86336
  access: "create",
86247
86337
  role: "admin"
86248
86338
  },
86249
- "trainingProvider.validateCredentials": {
86250
- capName: "training-provider",
86251
- capScope: "system",
86252
- addonId: null,
86253
- access: "create",
86254
- role: "admin"
86255
- },
86256
86339
  "turnProvider.getTurnServers": {
86257
86340
  capName: "turn-provider",
86258
86341
  capScope: "system",
@@ -88589,11 +88672,6 @@ Object.freeze({
88589
88672
  form: "single",
88590
88673
  optional: false
88591
88674
  }],
88592
- "petFountain.resetDailyConsumption": [{
88593
- name: "deviceId",
88594
- form: "single",
88595
- optional: false
88596
- }],
88597
88675
  "petFountain.setPump": [{
88598
88676
  name: "deviceId",
88599
88677
  form: "single",
@@ -91381,11 +91459,6 @@ function linkFieldDescriptor(key, target, labels) {
91381
91459
  ...target.kind !== void 0 ? { kind: target.kind } : {}
91382
91460
  };
91383
91461
  }
91384
- /**
91385
- * Declare the record kind of a service that links to other instances. The body is
91386
- * `{ name, ...links, ...fields }`; the links are recorded in the kind (read back by
91387
- * {@link linksOfKind}) so the hub can index who points at what.
91388
- */
91389
91462
  function declareLinkKind(spec) {
91390
91463
  const linkShape = {};
91391
91464
  for (const [field, target] of Object.entries(spec.links)) linkShape[field] = linkField(target);
@@ -91442,7 +91515,6 @@ function buildLinkedInstances(records, spec) {
91442
91515
  });
91443
91516
  return instances;
91444
91517
  }
91445
- entryBody({ brokerId: string() });
91446
91518
  /**
91447
91519
  * The calendars an account imports leave the account (D1013). An account record used to carry a
91448
91520
  * `calendarIds` array; each calendar is now a record of its own that LINKS to the account
@@ -91545,22 +91617,12 @@ var GoogleBrokerEntrySchema = object({
91545
91617
  fromAddress: string().default(""),
91546
91618
  fromName: string().default("")
91547
91619
  });
91548
- var GoogleServicesConfigSchema = object({
91549
- brokers: array(GoogleBrokerEntrySchema).default([]),
91550
- /** @deprecated Pre-broker singleton — cleared after migrateLegacyToBrokers. */
91551
- clientId: string().optional(),
91552
- /** @deprecated Pre-broker singleton — cleared after migrateLegacyToBrokers. */
91553
- clientSecret: string().optional().meta({ secret: true }),
91554
- /** @deprecated Pre-broker singleton — cleared after migrateLegacyToBrokers. */
91555
- calendarFilter: string().optional(),
91556
- /** @deprecated Pre-broker singleton — cleared after migrateLegacyToBrokers. */
91557
- fromAddress: string().optional(),
91558
- /** @deprecated Pre-broker singleton — cleared after migrateLegacyToBrokers. */
91559
- fromName: string().optional()
91560
- });
91620
+ /**
91621
+ * The addon keeps no addon-level settings: every account is a `brokers` record and its tokens
91622
+ * live in the durable `oauthAccounts` state.
91623
+ */
91624
+ var GoogleServicesConfigSchema = object({});
91561
91625
  var DEFAULT_GOOGLE_CONFIG = GoogleServicesConfigSchema.parse({});
91562
- /** Flat pre-broker config (singleton). Parsed only for one-shot migration. */
91563
- var LegacyGoogleFlatConfigSchema = GoogleServicesConfigSchema;
91564
91626
  var DEFAULT_OAUTH_STATE = {
91565
91627
  refreshToken: "",
91566
91628
  accessToken: "",
@@ -91630,52 +91692,6 @@ function brokerEntryToSettings(entry) {
91630
91692
  fromName: entry.fromName
91631
91693
  };
91632
91694
  }
91633
- /**
91634
- * One-shot: flat singleton config + legacy `oauth` state → `google_001`.
91635
- * Idempotent when `brokers` already present.
91636
- */
91637
- function migrateLegacyToBrokers(rawConfig, legacyOauth) {
91638
- const loose = LegacyGoogleFlatConfigSchema.safeParse(rawConfig);
91639
- const flat = loose.success ? loose.data : {};
91640
- const existingBrokers = flat.brokers ?? [];
91641
- if (existingBrokers.length > 0) return {
91642
- brokers: existingBrokers.map((b) => GoogleBrokerEntrySchema.parse(b)),
91643
- oauthAccounts: [],
91644
- didMigrate: false
91645
- };
91646
- const hasClient = (flat.clientId ?? "").length > 0 || (flat.clientSecret ?? "").length > 0;
91647
- const hasOauth = legacyOauth !== null && legacyOauth.refreshToken.length > 0;
91648
- if (!hasClient && !hasOauth) return {
91649
- brokers: [],
91650
- oauthAccounts: [],
91651
- didMigrate: false
91652
- };
91653
- const id = "google_001";
91654
- const email = legacyOauth?.accountEmail?.trim() ?? "";
91655
- const name = email.length > 0 ? email : "Google account";
91656
- const entry = GoogleBrokerEntrySchema.parse({
91657
- id,
91658
- name,
91659
- clientId: flat.clientId ?? "",
91660
- clientSecret: flat.clientSecret ?? "",
91661
- calendarFilter: flat.calendarFilter ?? "",
91662
- fromAddress: flat.fromAddress ?? "",
91663
- fromName: flat.fromName ?? ""
91664
- });
91665
- const oauthAccounts = legacyOauth !== null && (legacyOauth.refreshToken.length > 0 || legacyOauth.accessToken.length > 0) ? [{
91666
- id,
91667
- refreshToken: legacyOauth.refreshToken,
91668
- accessToken: legacyOauth.accessToken,
91669
- accessExpiresAt: legacyOauth.accessExpiresAt,
91670
- accountEmail: legacyOauth.accountEmail,
91671
- needsReauth: false
91672
- }] : [];
91673
- return {
91674
- brokers: [entry],
91675
- oauthAccounts,
91676
- didMigrate: true
91677
- };
91678
- }
91679
91695
  /** Local calendar id stamped as `brokerId:googleCalendarId`. */
91680
91696
  function stampCalendarId(brokerId, googleCalendarId) {
91681
91697
  return `${brokerId}:${googleCalendarId}`;
@@ -91791,9 +91807,6 @@ var GoogleBrokerRegistry = class {
91791
91807
  connectedSize() {
91792
91808
  return this.entries.filter((e) => this.isConnected(e.id)).length;
91793
91809
  }
91794
- toConfig() {
91795
- return { brokers: [...this.entries] };
91796
- }
91797
91810
  seedCounterFromEntries(entries) {
91798
91811
  let maxSeen = 0;
91799
91812
  for (const e of entries) {
@@ -92704,6 +92717,245 @@ async function planDropSharedCalendarIds(ports) {
92704
92717
  } })
92705
92718
  }] };
92706
92719
  }
92720
+ //#endregion
92721
+ //#region src/migrations/drop-config-brokers-and-legacy-oauth.ts
92722
+ /**
92723
+ * The addon-level `brokers` setting and the singleton `oauth` state are gone (planning#440 step 5):
92724
+ * every account is a `brokers` record and its tokens live in `oauthAccounts`. This deletes the two
92725
+ * leftover keys, each only when nothing in them is still the only copy:
92726
+ *
92727
+ * - `brokers` goes when the `brokers` kind holds records, or when the setting itself is empty. A
92728
+ * non-empty setting with an empty kind was never copied: it stays.
92729
+ * - `oauth` goes when it carries no token (the empty state the old boot migration left behind), or
92730
+ * when `oauthAccounts` already holds accounts. A token with no account to hold it stays.
92731
+ *
92732
+ * Each edit carries a precondition read, so a row that changed since the plan was made is not
92733
+ * deleted; a second run finds nothing to plan.
92734
+ */
92735
+ var BROKERS_KEY = "brokers";
92736
+ var LEGACY_OAUTH_KEY = "oauth";
92737
+ /** The flat singleton client the boot migration used to clear. */
92738
+ var FLAT_KEYS = [
92739
+ "clientId",
92740
+ "clientSecret",
92741
+ "calendarFilter",
92742
+ "fromAddress",
92743
+ "fromName"
92744
+ ];
92745
+ var OAUTH_ACCOUNTS_KEY = "oauthAccounts";
92746
+ function present$1(answer, key) {
92747
+ if (answer.kind === "unreadable") throw new Error(`google-services: the stored '${key}' cannot be read (${answer.reason})`);
92748
+ return answer.kind === "absent" ? null : { value: answer.value };
92749
+ }
92750
+ function field(value, key) {
92751
+ return typeof value === "object" && value !== null ? Reflect.get(value, key) : void 0;
92752
+ }
92753
+ /** A token field that holds nothing: absent or the empty string. A secret marker is something. */
92754
+ function isBlank(value) {
92755
+ return value === void 0 || value === null || value === "";
92756
+ }
92757
+ function stringList(value) {
92758
+ if (!Array.isArray(value)) return null;
92759
+ const out = [];
92760
+ for (const item of value) {
92761
+ if (typeof item !== "string") return null;
92762
+ out.push(item);
92763
+ }
92764
+ return out;
92765
+ }
92766
+ function holdsAccounts(value) {
92767
+ const accounts = field(value, "accounts");
92768
+ return Array.isArray(accounts) && accounts.length > 0;
92769
+ }
92770
+ async function planDropConfigBrokersAndLegacyOauth(ports) {
92771
+ const rows = {};
92772
+ const keys = [];
92773
+ const take = (key, value) => {
92774
+ const id = `${GOOGLE_ADDON_ID}.${key}`;
92775
+ keys.push(id);
92776
+ rows[id] = {
92777
+ addonId: GOOGLE_ADDON_ID,
92778
+ key,
92779
+ value
92780
+ };
92781
+ };
92782
+ const brokers = present$1(await ports.readStored(BROKERS_KEY), BROKERS_KEY);
92783
+ if (brokers !== null) {
92784
+ if (!(Array.isArray(brokers.value) && brokers.value.length > 0) || (await ports.listBrokers()).length > 0) take(BROKERS_KEY, brokers.value);
92785
+ }
92786
+ for (const key of FLAT_KEYS) {
92787
+ const flat = present$1(await ports.readStored(key), key);
92788
+ if (flat !== null && (await ports.listBrokers()).length > 0) take(key, flat.value);
92789
+ }
92790
+ const shared = present$1(await ports.readStored(SHARED_CALENDAR_IDS_KEY), SHARED_CALENDAR_IDS_KEY);
92791
+ if (shared !== null) {
92792
+ const sharedIds = stringList(shared.value);
92793
+ if (sharedIds === null) throw new Error(`google-services: the stored '${SHARED_CALENDAR_IDS_KEY}' is not a list of ids — nothing dropped`);
92794
+ else {
92795
+ const brokers = await ports.listBrokers();
92796
+ const same = (ids) => ids === void 0 || ids.length === sharedIds.length && ids.every((id) => sharedIds.includes(id));
92797
+ if (brokers.length > 0 && brokers.every((b) => same(b.calendarIds))) take(SHARED_CALENDAR_IDS_KEY, shared.value);
92798
+ }
92799
+ }
92800
+ const oauth = present$1(await ports.readStored(LEGACY_OAUTH_KEY), LEGACY_OAUTH_KEY);
92801
+ if (oauth !== null) {
92802
+ const tokenless = isBlank(field(oauth.value, "refreshToken")) && isBlank(field(oauth.value, "accessToken"));
92803
+ const accounts = present$1(await ports.readStored(OAUTH_ACCOUNTS_KEY), OAUTH_ACCOUNTS_KEY);
92804
+ if (tokenless || accounts !== null && holdsAccounts(accounts.value)) take(LEGACY_OAUTH_KEY, oauth.value);
92805
+ }
92806
+ if (keys.length === 0) return { edits: [] };
92807
+ return { edits: [{
92808
+ op: "deleteKeys",
92809
+ scope: ADDON_SETTINGS_TABLE,
92810
+ keys,
92811
+ precondition: preconditionOf(rows)
92812
+ }] };
92813
+ }
92814
+ //#endregion
92815
+ //#region src/migrations/legacy-brokers-to-records.ts
92816
+ /**
92817
+ * The accounts a pre-record install kept in the addon settings become `brokers` records and
92818
+ * `oauthAccounts` entries (planning#440 step 5). Three legacy shapes feed it, the ones the boot
92819
+ * migration used to read:
92820
+ *
92821
+ * - the `brokers` setting (a list of entries);
92822
+ * - the flat singleton (`clientId`, `clientSecret`, `calendarFilter`, `fromAddress`, `fromName`),
92823
+ * which becomes `google_001`;
92824
+ * - the singleton `oauth` state, whose token follows its account (`google_001`, or the first
92825
+ * broker when brokers already existed).
92826
+ *
92827
+ * Reads come RESOLVED (the settings view answers values, not keychain markers); a value the
92828
+ * keychain could not serve is not a string and REFUSES the step, so nothing is written from a
92829
+ * guess. Each record is read back with its secret before the step reports done, and an account
92830
+ * that already has a record is never overwritten. The shared `calendarIds` set goes onto every
92831
+ * broker this step creates (the calendar migrations before it found no broker to give it to),
92832
+ * 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
92833
+ * migration deletes them only after this one landed.
92834
+ */
92835
+ var LEGACY_BROKER_ID = "google_001";
92836
+ var LEGACY_FLAT_KEYS = [
92837
+ "clientId",
92838
+ "clientSecret",
92839
+ "calendarFilter",
92840
+ "fromAddress",
92841
+ "fromName"
92842
+ ];
92843
+ function present(answer, key) {
92844
+ if (answer.kind === "unreadable") throw new Error(`google-services: the stored '${key}' cannot be read (${answer.reason})`);
92845
+ return answer.kind === "absent" ? void 0 : answer.value;
92846
+ }
92847
+ function text(value, what) {
92848
+ if (value === void 0 || value === null) return "";
92849
+ if (typeof value === "string") return value;
92850
+ throw new Error(`google-services: ${what} is not a plain value (is the keychain available?)`);
92851
+ }
92852
+ function legacyOauthOf(value) {
92853
+ if (typeof value !== "object" || value === null) return null;
92854
+ const refreshToken = text(Reflect.get(value, "refreshToken"), "the legacy oauth refreshToken");
92855
+ if (refreshToken.length === 0) return null;
92856
+ const expires = Reflect.get(value, "accessExpiresAt");
92857
+ return {
92858
+ refreshToken,
92859
+ accessToken: text(Reflect.get(value, "accessToken"), "the legacy oauth accessToken"),
92860
+ accessExpiresAt: typeof expires === "number" ? expires : 0,
92861
+ accountEmail: text(Reflect.get(value, "accountEmail"), "the legacy oauth accountEmail").trim()
92862
+ };
92863
+ }
92864
+ async function flatFields(ports) {
92865
+ const out = {};
92866
+ for (const key of LEGACY_FLAT_KEYS) out[key] = text(present(await ports.readStored(key), key), `the stored '${key}'`);
92867
+ return out;
92868
+ }
92869
+ async function legacyEntries(ports, oauth) {
92870
+ const listed = present(await ports.readStored("brokers"), "brokers");
92871
+ if (Array.isArray(listed) && listed.length > 0) return listed.map((item) => {
92872
+ const parsed = GoogleBrokerEntrySchema.safeParse(item);
92873
+ if (!parsed.success) throw new Error(`google-services: a stored broker is invalid — ${parsed.error.message}`);
92874
+ return parsed.data;
92875
+ });
92876
+ const flat = await flatFields(ports);
92877
+ if (!flat["clientId"] && !flat["clientSecret"] && oauth === null) return [];
92878
+ const email = oauth?.accountEmail ?? "";
92879
+ return [GoogleBrokerEntrySchema.parse({
92880
+ id: LEGACY_BROKER_ID,
92881
+ name: email.length > 0 ? email : "Google account",
92882
+ ...flat
92883
+ })];
92884
+ }
92885
+ async function sharedCalendarIds(ports) {
92886
+ const value = present(await ports.readStored("calendarIds"), "calendarIds");
92887
+ if (value === void 0) return null;
92888
+ 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");
92889
+ return value;
92890
+ }
92891
+ /** The keys a legacy install left that no record holds yet, for the init warning. */
92892
+ async function leftoverLegacyKeys(ports) {
92893
+ const left = [];
92894
+ const listed = await ports.readStored("brokers");
92895
+ if (listed.kind === "present" && Array.isArray(listed.value) && listed.value.length > 0) left.push("brokers");
92896
+ for (const key of ["clientId", "clientSecret"]) {
92897
+ const answer = await ports.readStored(key);
92898
+ if (answer.kind === "present" && answer.value !== "" && answer.value !== null) left.push(key);
92899
+ }
92900
+ const oauth = await ports.readStored("oauth");
92901
+ if (oauth.kind === "present") {
92902
+ const token = typeof oauth.value === "object" && oauth.value !== null ? Reflect.get(oauth.value, "refreshToken") : void 0;
92903
+ if (token !== void 0 && token !== "" && token !== null) left.push("oauth");
92904
+ }
92905
+ return left;
92906
+ }
92907
+ async function copyLegacyBrokersToRecords(ports) {
92908
+ const oauth = legacyOauthOf(present(await ports.readStored("oauth"), "oauth"));
92909
+ const entries = await legacyEntries(ports, oauth);
92910
+ if (entries.length === 0) return {
92911
+ outcome: "already-done",
92912
+ summary: { reason: "no-legacy-data" }
92913
+ };
92914
+ const have = new Set((await ports.listBrokers()).map((b) => b.id));
92915
+ const shared = await sharedCalendarIds(ports);
92916
+ let created = 0;
92917
+ let selections = 0;
92918
+ for (const entry of entries) {
92919
+ if (have.has(entry.id)) continue;
92920
+ await ports.putBroker(entry);
92921
+ const back = await ports.readBroker(entry.id);
92922
+ 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`);
92923
+ created += 1;
92924
+ if (shared !== null && await ports.setBrokerCalendarIds(entry.id, shared)) selections += 1;
92925
+ }
92926
+ if (selections > 0) await moveCalendarIdsToRecords(ports, { calendarIdOf: (accountId, stamped) => {
92927
+ const parsed = parseStampedCalendarId(stamped);
92928
+ return parsed?.brokerId === accountId ? parsed.googleCalendarId : null;
92929
+ } });
92930
+ let account = 0;
92931
+ const primary = entries[0];
92932
+ if (oauth !== null && primary !== void 0) {
92933
+ if ((await ports.listOauthAccountIds()).length === 0) {
92934
+ await ports.putOauthAccount({
92935
+ id: primary.id,
92936
+ refreshToken: oauth.refreshToken,
92937
+ accessToken: oauth.accessToken,
92938
+ accessExpiresAt: oauth.accessExpiresAt,
92939
+ accountEmail: oauth.accountEmail,
92940
+ needsReauth: false
92941
+ });
92942
+ const back = await ports.readOauthAccount(primary.id);
92943
+ if (back === null || back.refreshToken !== oauth.refreshToken) throw new Error(`google-services: the oauth account of '${primary.id}' did not read back`);
92944
+ account = 1;
92945
+ }
92946
+ }
92947
+ return {
92948
+ outcome: created + account === 0 ? "already-done" : "done",
92949
+ summary: {
92950
+ brokers: created,
92951
+ oauthAccounts: account
92952
+ }
92953
+ };
92954
+ }
92955
+ //#endregion
92956
+ //#region src/migrations/index.ts
92957
+ var CALENDAR_IDS_TO_RECORDS_ID = "google-services/2026-11-07-calendar-ids-to-calendar-records";
92958
+ var LEGACY_BROKERS_TO_RECORDS_ID = "google-services/2026-11-06-legacy-brokers-to-records";
92707
92959
  /** The `google-services` catalogue (D987): offered to the engine when the addon initialises. */
92708
92960
  var ADDON_MIGRATIONS = [
92709
92961
  {
@@ -92740,7 +92992,7 @@ var ADDON_MIGRATIONS = [
92740
92992
  },
92741
92993
  {
92742
92994
  meta: {
92743
- id: "google-services/2026-11-07-calendar-ids-to-calendar-records",
92995
+ id: CALENDAR_IDS_TO_RECORDS_ID,
92744
92996
  owner: "google-services",
92745
92997
  level: "addon-state",
92746
92998
  seq: 3,
@@ -92756,6 +93008,38 @@ var ADDON_MIGRATIONS = [
92756
93008
  const parsed = parseStampedCalendarId(entry);
92757
93009
  return parsed?.brokerId === accountId ? parsed.googleCalendarId : null;
92758
93010
  } })
93011
+ },
93012
+ {
93013
+ meta: {
93014
+ id: LEGACY_BROKERS_TO_RECORDS_ID,
93015
+ owner: "google-services",
93016
+ level: "addon-state",
93017
+ seq: 4,
93018
+ dependsOn: [CALENDAR_IDS_TO_RECORDS_ID],
93019
+ store: "settings",
93020
+ scope: "cluster",
93021
+ onFailure: "tolerate",
93022
+ bodyKind: "procedure",
93023
+ 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",
93024
+ fixtureMark: "the client secret of a flat singleton, read back from its record"
93025
+ },
93026
+ procedure: copyLegacyBrokersToRecords
93027
+ },
93028
+ {
93029
+ meta: {
93030
+ id: "google-services/2026-11-06-drop-config-brokers-and-legacy-oauth",
93031
+ owner: "google-services",
93032
+ level: "addon-state",
93033
+ seq: 5,
93034
+ dependsOn: [LEGACY_BROKERS_TO_RECORDS_ID],
93035
+ store: "settings",
93036
+ scope: "cluster",
93037
+ onFailure: "tolerate",
93038
+ bodyKind: "plan",
93039
+ description: "Delete the addon-level brokers setting once the brokers records exist, and the singleton oauth state once it holds no token",
93040
+ fixtureMark: "the brokers setting kept when its records are missing"
93041
+ },
93042
+ plan: planDropConfigBrokersAndLegacyOauth
92759
93043
  }
92760
93044
  ];
92761
93045
  //#endregion
@@ -92841,6 +93125,22 @@ var GoogleBrokerStore = class GoogleBrokerStore {
92841
93125
  }
92842
93126
  return out;
92843
93127
  }
93128
+ async putOne(entry) {
93129
+ const { id, name, clientId, clientSecret, calendarFilter, fromAddress, fromName } = entry;
93130
+ const parsed = googleBrokersEntryKind.schema.safeParse({
93131
+ name,
93132
+ clientId,
93133
+ clientSecret,
93134
+ calendarFilter,
93135
+ fromAddress,
93136
+ fromName
93137
+ });
93138
+ if (!parsed.success) throw new Error(`invalid Google broker '${id}': ${parsed.error.message}`);
93139
+ await this.kind.put({
93140
+ id,
93141
+ data: parsed.data
93142
+ });
93143
+ }
92844
93144
  async replaceAll(entries) {
92845
93145
  const page = await this.kind.query({ limit: 1e3 });
92846
93146
  const nextIds = new Set(entries.map((e) => e.id));
@@ -92882,19 +93182,8 @@ var GoogleCallbackError = class extends Error {
92882
93182
  var CALLBACK_PATH = "/oauth/callback";
92883
93183
  var START_PATH = "/oauth/start";
92884
93184
  var DISCONNECT_PATH = "/oauth/disconnect";
92885
- var LegacyOauthStateSchema = object({
92886
- refreshToken: string().default("").meta({ secret: true }),
92887
- accessToken: string().default("").meta({ secret: true }),
92888
- accessExpiresAt: number().default(0),
92889
- accountEmail: string().default("")
92890
- });
92891
93185
  var GoogleServicesAddon = class extends BaseAddon {
92892
- secretStatePaths = [
92893
- "oauthAccounts.accounts[id].refreshToken",
92894
- "oauthAccounts.accounts[id].accessToken",
92895
- "oauth.refreshToken",
92896
- "oauth.accessToken"
92897
- ];
93186
+ secretStatePaths = ["oauthAccounts.accounts[id].refreshToken", "oauthAccounts.accounts[id].accessToken"];
92898
93187
  oauthAccountsHandle = null;
92899
93188
  registry = new GoogleBrokerRegistry();
92900
93189
  brokerStore = null;
@@ -92911,40 +93200,6 @@ var GoogleServicesAddon = class extends BaseAddon {
92911
93200
  }
92912
93201
  async onInitialize() {
92913
93202
  this.oauthAccountsHandle = this.state("oauthAccounts", GoogleOauthAccountsStateSchema, { accounts: [] });
92914
- let oauthAccounts = await this.oauthAccountsHandle.get();
92915
- const legacyHandle = this.state("oauth", LegacyOauthStateSchema, { ...DEFAULT_OAUTH_STATE });
92916
- const legacyOauth = await legacyHandle.get();
92917
- const migrated = migrateLegacyToBrokers(this.config, legacyOauth);
92918
- if (migrated.didMigrate) {
92919
- await this.updateGlobalSettings({
92920
- brokers: [...migrated.brokers],
92921
- clientId: void 0,
92922
- clientSecret: void 0,
92923
- calendarFilter: void 0,
92924
- fromAddress: void 0,
92925
- fromName: void 0
92926
- });
92927
- if (migrated.oauthAccounts.length > 0) {
92928
- oauthAccounts = { accounts: [...migrated.oauthAccounts] };
92929
- await this.oauthAccountsHandle.set(oauthAccounts);
92930
- }
92931
- await legacyHandle.set({ ...DEFAULT_OAUTH_STATE });
92932
- this.ctx.logger.info("google-services: migrated singleton OAuth to broker google_001", { meta: {
92933
- brokerId: "google_001",
92934
- accountEmail: legacyOauth.accountEmail || void 0
92935
- } });
92936
- } else if (oauthAccounts.accounts.length === 0 && legacyOauth.refreshToken.length > 0 && this.config.brokers.length > 0) {
92937
- oauthAccounts = { accounts: [{
92938
- id: this.config.brokers[0].id,
92939
- refreshToken: legacyOauth.refreshToken,
92940
- accessToken: legacyOauth.accessToken,
92941
- accessExpiresAt: legacyOauth.accessExpiresAt,
92942
- accountEmail: legacyOauth.accountEmail,
92943
- needsReauth: false
92944
- }] };
92945
- await this.oauthAccountsHandle.set(oauthAccounts);
92946
- await legacyHandle.set({ ...DEFAULT_OAUTH_STATE });
92947
- }
92948
93203
  const records = this.ctx.records;
92949
93204
  if (records === void 0) throw new Error("google-services: ctx.records is required (hub-only addon)");
92950
93205
  await records.declare({
@@ -92958,12 +93213,9 @@ var GoogleServicesAddon = class extends BaseAddon {
92958
93213
  onChanged: () => this.refreshCalendarSelection()
92959
93214
  });
92960
93215
  this.activeBrokers = await this.loadPersistedBrokers();
92961
- if ((await this.brokerStore.listResolved()).length === 0 && this.config.brokers.length > 0) {
92962
- await this.brokerStore.replaceAll(this.config.brokers);
92963
- this.activeBrokers = await this.loadPersistedBrokers();
92964
- }
92965
93216
  await this.migrateCalendarIds(records);
92966
93217
  await this.refreshCalendarSelection();
93218
+ const oauthAccounts = await this.oauthAccountsHandle.get();
92967
93219
  this.registry.seedFrom(this.activeBrokers, oauthAccounts.accounts);
92968
93220
  await this.refreshPublicOrigin();
92969
93221
  const calendarProvider = createGoogleCalendarSource({
@@ -93399,27 +93651,61 @@ var GoogleServicesAddon = class extends BaseAddon {
93399
93651
  brokers,
93400
93652
  calendars: records.kind(googleCalendarsEntryKind),
93401
93653
  warn: (message) => this.ctx.logger.warn(message)
93402
- })
93654
+ }),
93655
+ ...this.legacyBrokerPorts()
93656
+ };
93657
+ const report = await this.runMigrations(defineAddonMigrations(ADDON_MIGRATIONS, ports));
93658
+ if (report.applied.length > 0) this.activeBrokers = await this.loadPersistedBrokers();
93659
+ if (this.activeBrokers.length === 0) {
93660
+ const left = await leftoverLegacyKeys(ports);
93661
+ 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: {
93662
+ leftoverKeys: left,
93663
+ failed: report.failed
93664
+ } });
93665
+ }
93666
+ }
93667
+ /** The legacy-broker migration's writes: a broker record and an `oauthAccounts` entry, each read back. */
93668
+ legacyBrokerPorts() {
93669
+ return {
93670
+ putBroker: async (entry) => {
93671
+ const store = this.brokerStore;
93672
+ if (store === null) throw new Error("google-services: the brokers store is not ready");
93673
+ await store.putOne(entry);
93674
+ },
93675
+ readBroker: async (id) => {
93676
+ const store = this.brokerStore;
93677
+ if (store === null) throw new Error("google-services: the brokers store is not ready");
93678
+ const found = (await store.listResolved()).find((b) => b.id === id);
93679
+ return found === void 0 ? null : found;
93680
+ },
93681
+ listOauthAccountIds: async () => {
93682
+ const handle = this.oauthAccountsHandle;
93683
+ if (handle === null) return [];
93684
+ return (await handle.get()).accounts.map((a) => a.id);
93685
+ },
93686
+ putOauthAccount: async (account) => {
93687
+ const handle = this.oauthAccountsHandle;
93688
+ if (handle === null) throw new Error("google-services: oauthAccounts is not ready");
93689
+ const current = await handle.get();
93690
+ await handle.set({ accounts: [...current.accounts, account] });
93691
+ },
93692
+ readOauthAccount: async (id) => {
93693
+ const handle = this.oauthAccountsHandle;
93694
+ if (handle === null) return null;
93695
+ return (await handle.get()).accounts.find((a) => a.id === id) ?? null;
93696
+ }
93403
93697
  };
93404
- if ((await this.runMigrations(defineAddonMigrations(ADDON_MIGRATIONS, ports))).applied.length > 0) this.activeBrokers = await this.loadPersistedBrokers();
93405
93698
  }
93406
93699
  async loadPersistedBrokers() {
93407
93700
  const store = this.brokerStore;
93408
- if (store !== null) {
93409
- const fromRecords = await store.listResolved();
93410
- if (fromRecords.length > 0) return fromRecords;
93411
- }
93412
- return this.config.brokers;
93701
+ return store === null ? [] : store.listResolved();
93413
93702
  }
93414
93703
  async persistBrokers() {
93415
93704
  const entries = [...this.registry.listEntries()];
93416
93705
  this.activeBrokers = entries;
93417
93706
  const store = this.brokerStore;
93418
- if (store !== null) {
93419
- await store.replaceAll(entries);
93420
- return;
93421
- }
93422
- await this.updateGlobalSettings({ brokers: entries });
93707
+ if (store === null) throw new Error("google-services: the brokers store is not ready");
93708
+ await store.replaceAll(entries);
93423
93709
  }
93424
93710
  async persistOauthAccounts() {
93425
93711
  if (!this.oauthAccountsHandle) return;
@@ -93570,4 +93856,4 @@ function asSettingsCap(cap) {
93570
93856
  if (cap === "calendar-source" || cap === "smtp-provider") return cap;
93571
93857
  }
93572
93858
  //#endregion
93573
- export { GOOGLE_GMAIL_SEND_SCOPE as C, OAUTH_START_PATH as E, GoogleServicesAddon, GoogleServicesAddon as default, GOOGLE_BROKER_KIND as S, GoogleServicesConfigSchema as T, GoogleBrokerRegistry as _, refreshAccessToken as a, stampCalendarId as b, selectGmailAccount as c, mapGoogleEvent as d, GOOGLE_CONSOLE_APIS_URL as f, redirectUriDisplay as g, introHtml as h, needsRefresh as i, createGoogleCalendarApi as l, connectHtml as m, buildAuthorizeUrl as n, buildRawMime as o, GOOGLE_CONSOLE_CREDENTIALS_URL as p, exchangeCode as r, createGmailSmtpProvider as s, applyTokenResponse as t, createGoogleCalendarSource as u, migrateLegacyToBrokers as v, GOOGLE_OAUTH_SCOPES as w, DEFAULT_GOOGLE_CONFIG as x, parseStampedCalendarId as y };
93859
+ export { GOOGLE_OAUTH_SCOPES as C, GoogleServicesAddon, GoogleServicesAddon as default, GOOGLE_GMAIL_SEND_SCOPE as S, OAUTH_START_PATH as T, GoogleBrokerRegistry as _, refreshAccessToken as a, DEFAULT_GOOGLE_CONFIG as b, selectGmailAccount as c, mapGoogleEvent as d, GOOGLE_CONSOLE_APIS_URL as f, redirectUriDisplay as g, introHtml as h, needsRefresh as i, createGoogleCalendarApi as l, connectHtml as m, buildAuthorizeUrl as n, buildRawMime as o, GOOGLE_CONSOLE_CREDENTIALS_URL as p, exchangeCode as r, createGmailSmtpProvider as s, applyTokenResponse as t, createGoogleCalendarSource as u, parseStampedCalendarId as v, GoogleServicesConfigSchema as w, GOOGLE_BROKER_KIND as x, stampCalendarId as y };