@camstack/addon-export-google 0.1.127 → 0.1.128

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.
@@ -6056,7 +6056,7 @@ var ZodIssueCode = {
6056
6056
  var ZodFirstPartyTypeKind;
6057
6057
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
6058
6058
  //#endregion
6059
- //#region ../types/dist/sleep-9TIHFj1w.mjs
6059
+ //#region ../types/dist/sleep-CmjWurK5.mjs
6060
6060
  /**
6061
6061
  * The audio chunk plane's byte format, and the ONE expansion from a coded
6062
6062
  * window to float samples (D455).
@@ -6740,130 +6740,92 @@ async function runAddonMigrations(host, migrations, logger, options = {}) {
6740
6740
  blockOwner
6741
6741
  };
6742
6742
  }
6743
- /**
6744
- * Build a {@link DurableState} over a single store key. Transport-agnostic:
6745
- * `read`/`write` are the addon-store or device-store accessors. The whole
6746
- * validated value round-trips on every read/write — the schema is the
6747
- * single source of truth for what is persisted, so no hand-listed field
6748
- * set can drop a key on save.
6749
- */
6750
- function createDurableState(deps) {
6751
- const get = async () => {
6752
- const raw = (await deps.read())[deps.key];
6753
- if (raw === void 0) return deps.fallback;
6754
- const parsed = deps.schema.safeParse(raw);
6755
- if (!parsed.success) {
6756
- deps.onParseError?.(deps.key, parsed.error);
6757
- return deps.fallback;
6758
- }
6759
- return parsed.data;
6760
- };
6761
- const set = async (next) => {
6762
- const validated = deps.schema.parse(next);
6763
- await deps.write({ [deps.key]: validated });
6764
- };
6765
- const update = async (fn) => {
6766
- await set(fn(await get()));
6767
- };
6743
+ /** The record calls the one-switch migration makes, over the migration API. */
6744
+ function switchRecordsOverMigrationApi(api) {
6745
+ return { kind: (definition) => {
6746
+ const handle = api.records.kind(definition);
6747
+ return {
6748
+ get: (id) => handle.get({ id }),
6749
+ put: (input, opts) => handle.put({
6750
+ ...input,
6751
+ ...opts?.ifRev === void 0 ? {} : { ifRev: opts.ifRev }
6752
+ }),
6753
+ patch: (id, partial) => handle.patch({
6754
+ id,
6755
+ partial
6756
+ })
6757
+ };
6758
+ } };
6759
+ }
6760
+ function integrationRowsApiOver(api) {
6768
6761
  return {
6769
- get,
6770
- set,
6771
- update
6762
+ list: async () => (await api.integrations.list({})).integrations,
6763
+ readLegacyIntegrationRows: (input) => api.legacyRows.read(input),
6764
+ clearLegacyIntegrationRows: (input) => api.legacyRows.clear(input)
6772
6765
  };
6773
6766
  }
6774
- /**
6775
- * Per-node scoping for the shared addon-settings blob.
6776
- *
6777
- * An addon's settings store is hub-central (the `addon-settings` cap is
6778
- * hub-routed — the hub instance answers for every node), so fields whose
6779
- * value is a NODE fact (decoder backend, engine pick, probed hardware
6780
- * capabilities) persist under the node-scoped key `<key>@<nodeId>` inside
6781
- * the single shared blob. The SCHEMA field key stays bare: the write path
6782
- * ({@link scopePatch}) maps the bare field onto the target node's scoped
6783
- * key; the read/hydrate path ({@link projectStore}) maps THIS node's value
6784
- * back, so UI forms and `resolveConfig` only ever see the bare key.
6785
- *
6786
- * Fields opt in via the `perNode: true` schema marker on `ConfigFieldBase`
6787
- * (`interfaces/config-ui.ts`); `BaseAddon` derives the key set from the
6788
- * schema and routes reads/writes through these helpers.
6789
- *
6790
- * ## No bare-key fallback — deliberate
6791
- *
6792
- * {@link readNodeValue} reads the node-scoped key ONLY. A node with no
6793
- * scoped key resolves to `undefined` so the field's schema `default` wins —
6794
- * NEVER `store[base]` and never another node's value. A bare legacy key in
6795
- * the store is invisible to every node, hub included, so one node's
6796
- * selection can never leak onto another. (This generalizes the
6797
- * `decoder-backend-keys.ts` semantics — the no-fallback variant — over an
6798
- * arbitrary set of per-node field keys.)
6799
- *
6800
- * Pure functions only — no I/O, no imports beyond the language. This is a
6801
- * LEAF module: import it via its deep path, never from the root barrel.
6802
- */
6803
- /**
6804
- * Normalize a raw kernel node id to the bare node id used for scoping.
6805
- * `localNodeId` can carry a `<node>/<addon>` suffix on forked child
6806
- * processes; per-node settings are per-NODE, so strip the addon segment.
6807
- * `undefined` / `null` / empty falls back to `'hub'`.
6808
- */
6809
- function normalizeNodeId(raw) {
6810
- if (raw === void 0 || raw === null || raw === "") return "hub";
6811
- const slashIdx = raw.indexOf("/");
6812
- if (slashIdx < 0) return raw;
6813
- const bare = raw.slice(0, slashIdx);
6814
- return bare === "" ? "hub" : bare;
6815
- }
6816
- /** The node-scoped store key for a per-node field: `<base>@<nodeId>`. */
6817
- function nodeScopedKey(base, nodeId) {
6818
- return `${base}@${normalizeNodeId(nodeId)}`;
6819
- }
6820
- /**
6821
- * Read a node's value for a per-node field from the raw shared store:
6822
- * the node-scoped key when present, otherwise `undefined`.
6823
- * Deliberately NO bare-key fallback (see module doc) — the caller lets the
6824
- * schema `default` win on `undefined`.
6825
- */
6826
- function readNodeValue(store, base, nodeId) {
6827
- return store[nodeScopedKey(base, nodeId)];
6828
- }
6829
- /**
6830
- * Re-map a UI/settings patch so every bare perNode field persists under the
6831
- * TARGET node's scoped key; all other keys pass through unchanged. Used on
6832
- * the write path so a save for one node never clobbers another node's value
6833
- * (and the bare key is never written). Returns a new object — the input
6834
- * patch is not mutated.
6835
- */
6836
- function scopePatch(patch, perNodeKeys, nodeId) {
6837
- const out = {};
6838
- for (const [key, value] of Object.entries(patch)) out[perNodeKeys.has(key) ? nodeScopedKey(key, nodeId) : key] = value;
6839
- return out;
6840
- }
6841
- /**
6842
- * Project the raw shared store onto the bare schema keys for ONE node so a
6843
- * UI schema (whose field keys are bare) hydrates from that node's own
6844
- * values:
6845
- *
6846
- * - EVERY `@`-scoped key (any node's) is dropped from the pass-through.
6847
- * - Every bare perNode key is dropped from the pass-through (a stray bare
6848
- * legacy key must never hydrate any node — no bare fallback).
6849
- * - THIS node's effective value ({@link readNodeValue}) is then laid onto
6850
- * each bare perNode key; when the node has no scoped key the bare key is
6851
- * left ABSENT so the field's schema `default` wins.
6852
- *
6853
- * Returns a new object — the input store is not mutated.
6854
- */
6855
- function projectStore(store, perNodeKeys, nodeId) {
6856
- const out = {};
6857
- for (const [key, value] of Object.entries(store)) {
6858
- if (key.includes("@")) continue;
6859
- if (perNodeKeys.has(key)) continue;
6860
- out[key] = value;
6767
+ var PREFIX$1 = "records/";
6768
+ /** The base of every records failure. `detail` is the human part of the message. */
6769
+ var RecordsError = class extends Error {
6770
+ code;
6771
+ detail;
6772
+ constructor(code, detail) {
6773
+ super(`${PREFIX$1}${code}: ${detail}`);
6774
+ this.name = "RecordsError";
6775
+ this.code = code;
6776
+ this.detail = detail;
6861
6777
  }
6862
- for (const base of perNodeKeys) {
6863
- const value = readNodeValue(store, base, nodeId);
6864
- if (value !== void 0) out[base] = value;
6778
+ };
6779
+ /** A write guarded by `ifRev` found another revision (or an existing row for `ifRev: 0`). */
6780
+ var RevConflictError = class extends RecordsError {
6781
+ constructor(detail) {
6782
+ super("rev-conflict", detail);
6783
+ this.name = "RevConflictError";
6865
6784
  }
6866
- return out;
6785
+ };
6786
+ /** The keychain could not store or serve a value: explicit, never an empty string. */
6787
+ var RecordSecretUnavailableError = class extends RecordsError {
6788
+ constructor(detail) {
6789
+ super("secret-unavailable", detail);
6790
+ this.name = "RecordSecretUnavailableError";
6791
+ }
6792
+ };
6793
+ var InvalidRecordError = class extends RecordsError {
6794
+ constructor(detail) {
6795
+ super("invalid-record", detail);
6796
+ this.name = "InvalidRecordError";
6797
+ }
6798
+ };
6799
+ /** A kind declaration the engine refuses (non-additive change, bad shape, wrong file). */
6800
+ var DeclarationRefusedError = class extends RecordsError {
6801
+ constructor(detail) {
6802
+ super("declaration-refused", detail);
6803
+ this.name = "DeclarationRefusedError";
6804
+ }
6805
+ };
6806
+ function linkTargetOf(meta) {
6807
+ if (typeof meta !== "object" || meta === null) return void 0;
6808
+ const link = Reflect.get(meta, "link");
6809
+ const parsed = LinkTargetSchema.safeParse(link);
6810
+ return parsed.success ? parsed.data : void 0;
6811
+ }
6812
+ var LinkTargetSchema = object({
6813
+ cap: string().min(1),
6814
+ kind: string().min(1).optional()
6815
+ });
6816
+ /** The links a kind declares, read from the meta of its body fields. */
6817
+ function linksOfKind(kind) {
6818
+ const schema = kind.schema;
6819
+ if (!(schema instanceof ZodObject)) return [];
6820
+ const links = [];
6821
+ for (const [field, fieldSchema] of Object.entries(schema.shape)) {
6822
+ const to = linkTargetOf(globalRegistry.get(fieldSchema));
6823
+ if (to !== void 0) links.push({
6824
+ field,
6825
+ to
6826
+ });
6827
+ }
6828
+ return links;
6867
6829
  }
6868
6830
  /**
6869
6831
  * The address of one keychain value: `secret://<owner>/<scope>/<fieldPath>`.
@@ -6999,6 +6961,643 @@ function parseSecretRef(ref) {
6999
6961
  fieldPath
7000
6962
  };
7001
6963
  }
6964
+ /** Limits and names of `ctx.records` (D881). One authority; the engine and the facade read it. */
6965
+ /** The files a kind may live in. `history` is device-history's (D850), never records. */
6966
+ var RECORD_DATABASES = ["settings", "events"];
6967
+ /** The classes of a kind: the `@durable` vocabulary, one authority (replaces the annotation). */
6968
+ var RECORD_CLASSES = [
6969
+ "config",
6970
+ "ledger",
6971
+ "audit",
6972
+ "mirror",
6973
+ "ephemeral"
6974
+ ];
6975
+ var RECORD_DEFAULT_MAX_DATA_BYTES = 64 * 1024;
6976
+ var RECORD_MAX_DATA_BYTES = 1024 * 1024;
6977
+ var RECORD_BATCH_MAX = 1e3;
6978
+ var RECORD_QUERY_MAX = 1e3;
6979
+ /** A kind in the `settings` file may not bound itself above this (D447: high volume is `events`). */
6980
+ var RECORD_SETTINGS_MAX_ROWS = 5e4;
6981
+ /** The `Column`-free proof prefix: a ref collection for a kind's secret fields. */
6982
+ var RECORD_SECRET_COLLECTION_PREFIX = "records:";
6983
+ /**
6984
+ * Secret fields of a record, addressed the way a Zod schema declares them
6985
+ * (`collectZodSecretPaths`): dotted keys, `[]` for "each element of this array"
6986
+ * (`auth.accessToken`, `headers[].value`).
6987
+ *
6988
+ * `{}` after a key means "each value of this map" (`applianceSecrets{}`): the map's own key
6989
+ * names the value (`applianceSecrets{fridge}`), so no id key is declared and a body that drops a
6990
+ * key releases exactly that key's secret.
6991
+ *
6992
+ * Array elements are matched by a DECLARED id key (`secretArrayKeys`:
6993
+ * `{ headers: 'name' }`), never by index, so reordering a list keeps every
6994
+ * keychain ref (the same rule as `arrayItemFieldPath`). The concrete path of a
6995
+ * leaf names its element: `headers[X-Api].value`.
6996
+ *
6997
+ * Pure and browser-safe. Nothing here mutates: every transform returns a new value.
6998
+ */
6999
+ /** The array prefixes (declared form, e.g. `headers` or `a.headers`) of a path. */
7000
+ function parseSecretPath(path) {
7001
+ if (path.length === 0) throw new InvalidRecordError("an empty secret path");
7002
+ return path.split(".").map((raw) => {
7003
+ const each = raw.endsWith("[]");
7004
+ const map = raw.endsWith("{}");
7005
+ const key = each || map ? raw.slice(0, -2) : raw;
7006
+ if (key.length === 0) throw new InvalidRecordError(`secret path "${path}" has an empty segment`);
7007
+ return {
7008
+ key,
7009
+ each,
7010
+ map
7011
+ };
7012
+ });
7013
+ }
7014
+ /** The declared array prefixes of `path` that need an id key (`headers`, `a.rows`). */
7015
+ function secretArrayPrefixes(path) {
7016
+ const segments = parseSecretPath(path);
7017
+ const prefixes = [];
7018
+ const walked = [];
7019
+ for (const segment of segments) {
7020
+ walked.push(segment.key);
7021
+ if (segment.each) prefixes.push(walked.join("."));
7022
+ }
7023
+ return prefixes;
7024
+ }
7025
+ function isRecord$6(value) {
7026
+ return typeof value === "object" && value !== null && !Array.isArray(value);
7027
+ }
7028
+ function elementId(element, idKey, declared, prefix) {
7029
+ const id = isRecord$6(element) ? element[idKey] : void 0;
7030
+ 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`);
7031
+ return id;
7032
+ }
7033
+ /**
7034
+ * Visit every secret leaf PRESENT in `data` (an absent branch has nothing to
7035
+ * visit). `replace` returns the new leaf value, or {@link REMOVE_LEAF}; the
7036
+ * result is a new body, `data` is untouched.
7037
+ */
7038
+ var REMOVE_LEAF = Symbol("remove-leaf");
7039
+ function mapAt(node, segments, index, walkedKeys, concretePrefix, declared, arrayKeys, visit) {
7040
+ if (!isRecord$6(node)) return node;
7041
+ const segment = segments[index];
7042
+ if (segment === void 0) return node;
7043
+ if (!Object.prototype.hasOwnProperty.call(node, segment.key)) return node;
7044
+ const child = node[segment.key];
7045
+ const keys = [...walkedKeys, segment.key];
7046
+ const last = index === segments.length - 1;
7047
+ if (segment.each) {
7048
+ if (!Array.isArray(child)) return node;
7049
+ const prefix = keys.join(".");
7050
+ const idKey = arrayKeys[prefix];
7051
+ if (idKey === void 0) throw new InvalidRecordError(`"${declared}": no id key declared for the array "${prefix}"`);
7052
+ const mapped = child.map((element) => {
7053
+ const id = elementId(element, idKey, declared, prefix);
7054
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}[${encodeURIComponent(id)}]`;
7055
+ return last ? element : mapAt(element, segments, index + 1, keys, concrete, declared, arrayKeys, visit);
7056
+ });
7057
+ return {
7058
+ ...node,
7059
+ [segment.key]: mapped
7060
+ };
7061
+ }
7062
+ if (segment.map) {
7063
+ if (!isRecord$6(child)) return node;
7064
+ const kept = Object.entries(child).map(([mapKey, value]) => {
7065
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}{${encodeURIComponent(mapKey)}}`;
7066
+ if (!last) return [mapKey, mapAt(value, segments, index + 1, keys, concrete, declared, arrayKeys, visit)];
7067
+ return [mapKey, visit({
7068
+ declared,
7069
+ concrete,
7070
+ value
7071
+ })];
7072
+ }).filter(([, value]) => value !== REMOVE_LEAF);
7073
+ return {
7074
+ ...node,
7075
+ [segment.key]: Object.fromEntries(kept)
7076
+ };
7077
+ }
7078
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}`;
7079
+ if (last) {
7080
+ const replacement = visit({
7081
+ declared,
7082
+ concrete,
7083
+ value: child
7084
+ });
7085
+ if (replacement === REMOVE_LEAF) return Object.fromEntries(Object.entries(node).filter(([key]) => key !== segment.key));
7086
+ return {
7087
+ ...node,
7088
+ [segment.key]: replacement
7089
+ };
7090
+ }
7091
+ return {
7092
+ ...node,
7093
+ [segment.key]: mapAt(child, segments, index + 1, keys, concrete, declared, arrayKeys, visit)
7094
+ };
7095
+ }
7096
+ /** Replace/remove every present secret leaf; returns a NEW body. */
7097
+ function mapSecretLeaves(data, paths, arrayKeys, visit) {
7098
+ let current = data;
7099
+ for (const declared of paths) current = mapAt(current, parseSecretPath(declared), 0, [], "", declared, arrayKeys, visit);
7100
+ return current;
7101
+ }
7102
+ /**
7103
+ * The keychain collection name a kind's secrets live under. Prefixed so a
7104
+ * record's refs never collide with the refs a legacy collection of the same name
7105
+ * already holds during an adoption.
7106
+ */
7107
+ function recordSecretCollection(kind) {
7108
+ return `${RECORD_SECRET_COLLECTION_PREFIX}${kind}`;
7109
+ }
7110
+ /** The ONE ref a row's secret field may carry: the engine and the facade both build it here. */
7111
+ function recordSecretRef(owner, kind, rowId, concretePath) {
7112
+ return buildSecretRef({
7113
+ owner,
7114
+ scope: {
7115
+ kind: "row",
7116
+ collection: recordSecretCollection(kind),
7117
+ rowId
7118
+ },
7119
+ fieldPath: concretePath
7120
+ });
7121
+ }
7122
+ /**
7123
+ * A stored secret, as an admin read shows it: a VIEW naming the row's own
7124
+ * keychain ref (`set: true`), never the value and no longer the bare redaction
7125
+ * token. The form hands it to the secret field, which reveals the value by ref
7126
+ * through the audited `keychain-admin.reveal`; sent back untouched it keeps the
7127
+ * stored secret (the records door reads a view as KEEP).
7128
+ *
7129
+ * ONE implementation for the entries service and for every addon that serves
7130
+ * its own instances (`RecordIntegrationInstances`).
7131
+ */
7132
+ function isRecord$5(value) {
7133
+ return typeof value === "object" && value !== null && !Array.isArray(value);
7134
+ }
7135
+ function secretViewsOf(owner, kind, id, decl, data) {
7136
+ if (decl.secretPaths.length === 0) return data;
7137
+ const shown = mapSecretLeaves(data, decl.secretPaths, decl.secretArrayKeys, (leaf) => {
7138
+ if (leaf.value !== "__camstack_redacted__") return leaf.value;
7139
+ return {
7140
+ $secret: recordSecretRef(owner, kind, id, leaf.concrete),
7141
+ v: 1,
7142
+ set: true
7143
+ };
7144
+ });
7145
+ return isRecord$5(shown) ? shown : data;
7146
+ }
7147
+ /** The most instances one addon lists (an integrations page, not a table). */
7148
+ var INSTANCES_LIST_MAX = 1e3;
7149
+ /**
7150
+ * The ONE reader of an instance's switch (D996): an absent field means on, so a row written
7151
+ * before the field existed needs no migration. Every consumer of an instance body asks this.
7152
+ */
7153
+ function isInstanceEnabled(body) {
7154
+ return body.enabled !== false;
7155
+ }
7156
+ /** The body key of the switch; only {@link RecordIntegrationInstances.setInstanceEnabled} writes it. */
7157
+ var SWITCH_KEY = "enabled";
7158
+ /** The keys of the kind's secret fields that sit at the top level of the body. */
7159
+ function topLevelSecretKeys(paths) {
7160
+ return new Set(paths.filter((p) => !p.includes(".") && !p.includes("[") && !p.includes("{")));
7161
+ }
7162
+ /** The keys of the kind's top-level MAPS whose values are secrets (`applianceSecrets{}`). */
7163
+ function secretMapKeys(paths) {
7164
+ return new Set(paths.filter((p) => p.endsWith("{}") && !p.slice(0, -2).match(/[.[{]/)).map((p) => p.slice(0, -2)));
7165
+ }
7166
+ /**
7167
+ * A patch value for a map of secrets: an entry that is omitted, `''`, the redaction token or the
7168
+ * view the form was given KEEPS its stored secret (it is left out of the merge); `{ $secretClear }`
7169
+ * or `null` removes the entry; any other string replaces it. Null when nothing is left to merge.
7170
+ */
7171
+ function secretMapPatch(value) {
7172
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
7173
+ const out = {};
7174
+ for (const [key, entry] of Object.entries(value)) if (entry === null || isSecretClear(entry)) out[key] = null;
7175
+ else if (typeof entry === "string" && entry !== "" && entry !== "__camstack_redacted__" && !isSecretFieldView(entry)) out[key] = entry;
7176
+ return Object.keys(out).length > 0 ? out : null;
7177
+ }
7178
+ var RecordIntegrationInstances = class {
7179
+ records;
7180
+ kind;
7181
+ hooks;
7182
+ handle;
7183
+ secretKeys;
7184
+ secretMaps;
7185
+ nameField;
7186
+ switchListeners = /* @__PURE__ */ new Set();
7187
+ constructor(records, kind, hooks) {
7188
+ this.records = records;
7189
+ this.kind = kind;
7190
+ this.hooks = hooks;
7191
+ this.handle = records.kind(kind);
7192
+ this.secretKeys = topLevelSecretKeys(kind.declaration.secretPaths);
7193
+ this.secretMaps = secretMapKeys(kind.declaration.secretPaths);
7194
+ this.nameField = kind.declaration.entry?.nameField ?? "name";
7195
+ }
7196
+ /**
7197
+ * One instance read for the addon's own runtime; null when absent. When the keychain is
7198
+ * locked the row is served WITHOUT its secrets and says so (`secrets: 'unavailable'`), so the
7199
+ * caller can keep what it had instead of reconfiguring with an empty secret (D49).
7200
+ */
7201
+ async readResolved(id) {
7202
+ try {
7203
+ const record = await this.handle.getResolved(id);
7204
+ return record === null ? null : {
7205
+ id,
7206
+ body: record.data,
7207
+ enabled: isInstanceEnabled(record.data),
7208
+ secrets: "resolved"
7209
+ };
7210
+ } catch (err) {
7211
+ if (!(err instanceof RecordSecretUnavailableError)) throw err;
7212
+ const stored = await this.handle.get(id);
7213
+ if (stored === null) return null;
7214
+ return {
7215
+ id,
7216
+ body: Object.fromEntries(Object.entries(stored.data).filter(([key]) => !this.secretKeys.has(key))),
7217
+ enabled: isInstanceEnabled(stored.data),
7218
+ secrets: "unavailable"
7219
+ };
7220
+ }
7221
+ }
7222
+ /** The body of {@link readResolved} alone; a locked keychain yields the row without secrets. */
7223
+ async getResolved(id) {
7224
+ return (await this.readResolved(id))?.body ?? null;
7225
+ }
7226
+ /** Every instance, secrets resolved where the keychain allows; an absent one is skipped. */
7227
+ async listResolved() {
7228
+ const page = await this.handle.query({ limit: INSTANCES_LIST_MAX });
7229
+ const out = [];
7230
+ for (const record of page.records) {
7231
+ const read = await this.readResolved(record.id);
7232
+ if (read !== null) out.push(read);
7233
+ }
7234
+ return out;
7235
+ }
7236
+ viewOf(record) {
7237
+ const shown = secretViewsOf(this.records.owner, this.kind.name, record.id, this.kind.declaration, record.data);
7238
+ const rawName = record.data[this.nameField];
7239
+ const kind = this.hooks.kindOf?.(record.data);
7240
+ const health = this.hooks.health?.(record.data, record.id);
7241
+ return {
7242
+ id: record.id,
7243
+ name: typeof rawName === "string" ? rawName : record.id,
7244
+ configured: this.hooks.configured(record.data),
7245
+ enabled: isInstanceEnabled(record.data),
7246
+ formValues: shown,
7247
+ ...kind !== void 0 ? { kind } : {},
7248
+ ...health?.status !== void 0 ? { status: health.status } : {},
7249
+ ...health?.lastCheckedAt !== void 0 ? { lastCheckedAt: health.lastCheckedAt } : {}
7250
+ };
7251
+ }
7252
+ describe = async () => {
7253
+ const declared = linksOfKind(this.kind);
7254
+ const links = this.hooks.description.links !== void 0 || declared.length === 0 ? {} : { links: declared.map((link) => ({
7255
+ kind: this.kind.name,
7256
+ field: link.field,
7257
+ to: link.to
7258
+ })) };
7259
+ return {
7260
+ ...this.hooks.description,
7261
+ ...links,
7262
+ ...this.hooks.mintId === void 0 ? {} : { mintsId: true }
7263
+ };
7264
+ };
7265
+ instanceFormSchema = async ({ id }) => this.hooks.formSchema(id);
7266
+ listInstances = async () => {
7267
+ return (await this.handle.query({ limit: INSTANCES_LIST_MAX })).records.map((record) => this.viewOf(record));
7268
+ };
7269
+ getInstance = async ({ id }) => {
7270
+ const record = await this.handle.get(id);
7271
+ return record === null ? null : this.viewOf(record);
7272
+ };
7273
+ /** Insert ONE row (`ifRev: 0`: an existing id is refused, never overwritten). */
7274
+ createInstance = async ({ id, name, kind, values }) => {
7275
+ const minted = id ?? this.hooks.mintId?.({
7276
+ name,
7277
+ ...kind !== void 0 ? { kind } : {}
7278
+ });
7279
+ if (minted === void 0) throw new Error("createInstance needs an id: this provider does not mint one");
7280
+ await this.handle.put({
7281
+ id: minted,
7282
+ data: this.hooks.initialBody(name, kind)
7283
+ }, { ifRev: 0 });
7284
+ const patch = this.patchOf(values ?? {});
7285
+ if (Object.keys(patch).length > 0) await this.handle.patch(minted, patch);
7286
+ await this.hooks.onChanged?.(minted, "created");
7287
+ return { id: minted };
7288
+ };
7289
+ updateInstance = async ({ id, name, values }) => {
7290
+ const patch = this.patchOf(values);
7291
+ if (name !== void 0) patch[this.nameField] = name;
7292
+ await this.handle.patch(id, patch);
7293
+ await this.hooks.onChanged?.(id, "updated");
7294
+ return { ok: true };
7295
+ };
7296
+ /** The record patch a form `values` object means: secrets kept, cleared or replaced. */
7297
+ patchOf(values) {
7298
+ const patch = {};
7299
+ for (const [key, value] of Object.entries(values)) {
7300
+ if (value === void 0) continue;
7301
+ if (key === "enabled") continue;
7302
+ if (this.secretMaps.has(key)) {
7303
+ const entries = secretMapPatch(value);
7304
+ if (entries !== null) patch[key] = entries;
7305
+ } else if (!this.secretKeys.has(key)) patch[key] = value;
7306
+ else if (isSecretClear(value)) patch[key] = null;
7307
+ else if (typeof value === "string" && value !== "" && value !== "__camstack_redacted__" && !isSecretFieldView(value)) patch[key] = value;
7308
+ }
7309
+ return patch;
7310
+ }
7311
+ /**
7312
+ * Listen to the switch of ANY instance of this helper (in the process that serves it). The
7313
+ * durable replacement of the `integration.enabled` / `integration.disabled` events (D8): the
7314
+ * addon reconciles from the record, whichever way it flipped.
7315
+ */
7316
+ onSwitched(listener) {
7317
+ this.switchListeners.add(listener);
7318
+ }
7319
+ /**
7320
+ * The ONE writer of the switch (D996, D1014): the record body's `enabled`, for every role. A
7321
+ * configured thing is an instance, so an id with no record yet (a default integration that was
7322
+ * never configured) gets its record from `initialBody` before the switch is written.
7323
+ */
7324
+ setInstanceEnabled = async ({ id, enabled }) => {
7325
+ if (await this.handle.get(id) === null) await this.handle.put({
7326
+ id,
7327
+ data: this.hooks.initialBody(id)
7328
+ }, { ifRev: 0 });
7329
+ await this.handle.patch(id, { [SWITCH_KEY]: enabled });
7330
+ await this.hooks.onChanged?.(id, "enabled");
7331
+ for (const listener of this.switchListeners) await listener(id, enabled);
7332
+ return { ok: true };
7333
+ };
7334
+ /** The row and its keychain refs go together (the records door). */
7335
+ deleteInstance = async ({ id }) => {
7336
+ await this.handle.delete(id);
7337
+ await this.hooks.onChanged?.(id, "deleted");
7338
+ return { ok: true };
7339
+ };
7340
+ testInstance = async (input) => {
7341
+ if (this.hooks.test === void 0) return {
7342
+ success: false,
7343
+ status: "unsupported",
7344
+ error: "This integration declares no connection test"
7345
+ };
7346
+ return this.hooks.test(input);
7347
+ };
7348
+ /** The flat provider object to hand to `registerProvider`. */
7349
+ toProvider() {
7350
+ return {
7351
+ describe: this.describe,
7352
+ instanceFormSchema: this.instanceFormSchema,
7353
+ listInstances: this.listInstances,
7354
+ getInstance: this.getInstance,
7355
+ createInstance: this.createInstance,
7356
+ updateInstance: this.updateInstance,
7357
+ setInstanceEnabled: this.setInstanceEnabled,
7358
+ deleteInstance: this.deleteInstance,
7359
+ testInstance: this.testInstance
7360
+ };
7361
+ }
7362
+ };
7363
+ /**
7364
+ * The one-switch migration (epic #440, step 3). An integration's on/off state used to live in the
7365
+ * registry's `enabled` column for a device addon; it now lives only in the instance record's
7366
+ * body (`enabled`, D1007 superseded). This moves a registry `enabled = false` into the body, once.
7367
+ *
7368
+ * For every registry row of the addon that is OFF:
7369
+ * - no record under its id: the record is created from `initialBody(name)` with `enabled: false`
7370
+ * (a default integration that never had settings, Reolink's among them);
7371
+ * - a record whose body states no `enabled`: `enabled: false` is written into it;
7372
+ * - a record that already states `enabled` (either way) is the newer truth and is left alone.
7373
+ * A row that is ON writes nothing: an absent field reads as on. A rerun finds every off row with
7374
+ * a stated switch and does nothing, so nothing switched off comes back on and nothing switched on
7375
+ * goes off. The registry column itself is neither read afterwards nor written; its drop is step 5.
7376
+ *
7377
+ * It runs in the addon process, BEFORE the addon registers its `integration-instances` provider,
7378
+ * which is also why `integrations.list` still answers the stored column at that point.
7379
+ */
7380
+ function registrySwitchToBodyId(addonId, date) {
7381
+ return `${addonId}/${date}-registry-switch-to-body`;
7382
+ }
7383
+ async function moveRegistrySwitchToBody(ports, spec) {
7384
+ const rows = await ports.listIntegrations(spec.addonId);
7385
+ let created = 0;
7386
+ let switched = 0;
7387
+ let kept = 0;
7388
+ for (const row of rows) {
7389
+ if (row.enabled) continue;
7390
+ const body = await ports.readBody(row.id);
7391
+ if (body === null) {
7392
+ if (await ports.createRecord(row.id, {
7393
+ ...spec.initialBody(row.name),
7394
+ ["enabled"]: false
7395
+ }) === "created") created += 1;
7396
+ else kept += 1;
7397
+ continue;
7398
+ }
7399
+ if ("enabled" in body) {
7400
+ kept += 1;
7401
+ continue;
7402
+ }
7403
+ await ports.switchOff(row.id);
7404
+ switched += 1;
7405
+ }
7406
+ const summary = {
7407
+ integrations: rows.length,
7408
+ off: rows.filter((r) => !r.enabled).length,
7409
+ created,
7410
+ switched,
7411
+ kept
7412
+ };
7413
+ return created === 0 && switched === 0 ? {
7414
+ outcome: "already-done",
7415
+ summary
7416
+ } : {
7417
+ outcome: "done",
7418
+ summary
7419
+ };
7420
+ }
7421
+ /** A migration entry: an addon states its kind and how a new body starts, nothing else. */
7422
+ function registrySwitchToBodyMigration(spec) {
7423
+ return {
7424
+ meta: {
7425
+ id: registrySwitchToBodyId(spec.addonId, spec.date),
7426
+ owner: spec.addonId,
7427
+ level: "addon-state",
7428
+ seq: spec.seq,
7429
+ dependsOn: [],
7430
+ store: "settings",
7431
+ scope: "cluster",
7432
+ onFailure: "block-owner",
7433
+ bodyKind: "procedure",
7434
+ description: "Move the registry enabled flag of every switched-off integration into its instance record body, creating the record when there is none",
7435
+ fixtureMark: "enabled"
7436
+ },
7437
+ procedure: (ports) => moveRegistrySwitchToBody(ports, {
7438
+ addonId: spec.addonId,
7439
+ initialBody: spec.initialBody
7440
+ })
7441
+ };
7442
+ }
7443
+ /** The hub and records sides of {@link registrySwitchToBodyMigration}. */
7444
+ function registrySwitchPortsOver(deps) {
7445
+ const handle = deps.records.kind({
7446
+ name: deps.kind.name,
7447
+ declaration: deps.kind.declaration,
7448
+ schema: record(string(), unknown())
7449
+ });
7450
+ return {
7451
+ listIntegrations: async (addonId) => (await deps.api.list()).filter((i) => i.addonId === addonId).map((i) => ({
7452
+ id: i.id,
7453
+ name: i.name,
7454
+ enabled: i.enabled !== false
7455
+ })),
7456
+ readBody: async (id) => (await handle.get(id))?.data ?? null,
7457
+ createRecord: async (id, body) => {
7458
+ if (await handle.get(id) !== null) return "exists";
7459
+ await handle.put({
7460
+ id,
7461
+ data: body
7462
+ }, { ifRev: 0 });
7463
+ return "created";
7464
+ },
7465
+ switchOff: async (id) => {
7466
+ await handle.patch(id, { [SWITCH_KEY]: false });
7467
+ }
7468
+ };
7469
+ }
7470
+ /**
7471
+ * Build a {@link DurableState} over a single store key. Transport-agnostic:
7472
+ * `read`/`write` are the addon-store or device-store accessors. The whole
7473
+ * validated value round-trips on every read/write — the schema is the
7474
+ * single source of truth for what is persisted, so no hand-listed field
7475
+ * set can drop a key on save.
7476
+ */
7477
+ function createDurableState(deps) {
7478
+ const get = async () => {
7479
+ const raw = (await deps.read())[deps.key];
7480
+ if (raw === void 0) return deps.fallback;
7481
+ const parsed = deps.schema.safeParse(raw);
7482
+ if (!parsed.success) {
7483
+ deps.onParseError?.(deps.key, parsed.error);
7484
+ return deps.fallback;
7485
+ }
7486
+ return parsed.data;
7487
+ };
7488
+ const set = async (next) => {
7489
+ const validated = deps.schema.parse(next);
7490
+ await deps.write({ [deps.key]: validated });
7491
+ };
7492
+ const update = async (fn) => {
7493
+ await set(fn(await get()));
7494
+ };
7495
+ return {
7496
+ get,
7497
+ set,
7498
+ update
7499
+ };
7500
+ }
7501
+ /**
7502
+ * Per-node scoping for the shared addon-settings blob.
7503
+ *
7504
+ * An addon's settings store is hub-central (the `addon-settings` cap is
7505
+ * hub-routed — the hub instance answers for every node), so fields whose
7506
+ * value is a NODE fact (decoder backend, engine pick, probed hardware
7507
+ * capabilities) persist under the node-scoped key `<key>@<nodeId>` inside
7508
+ * the single shared blob. The SCHEMA field key stays bare: the write path
7509
+ * ({@link scopePatch}) maps the bare field onto the target node's scoped
7510
+ * key; the read/hydrate path ({@link projectStore}) maps THIS node's value
7511
+ * back, so UI forms and `resolveConfig` only ever see the bare key.
7512
+ *
7513
+ * Fields opt in via the `perNode: true` schema marker on `ConfigFieldBase`
7514
+ * (`interfaces/config-ui.ts`); `BaseAddon` derives the key set from the
7515
+ * schema and routes reads/writes through these helpers.
7516
+ *
7517
+ * ## No bare-key fallback — deliberate
7518
+ *
7519
+ * {@link readNodeValue} reads the node-scoped key ONLY. A node with no
7520
+ * scoped key resolves to `undefined` so the field's schema `default` wins —
7521
+ * NEVER `store[base]` and never another node's value. A bare legacy key in
7522
+ * the store is invisible to every node, hub included, so one node's
7523
+ * selection can never leak onto another. (This generalizes the
7524
+ * `decoder-backend-keys.ts` semantics — the no-fallback variant — over an
7525
+ * arbitrary set of per-node field keys.)
7526
+ *
7527
+ * Pure functions only — no I/O, no imports beyond the language. This is a
7528
+ * LEAF module: import it via its deep path, never from the root barrel.
7529
+ */
7530
+ /**
7531
+ * Normalize a raw kernel node id to the bare node id used for scoping.
7532
+ * `localNodeId` can carry a `<node>/<addon>` suffix on forked child
7533
+ * processes; per-node settings are per-NODE, so strip the addon segment.
7534
+ * `undefined` / `null` / empty falls back to `'hub'`.
7535
+ */
7536
+ function normalizeNodeId(raw) {
7537
+ if (raw === void 0 || raw === null || raw === "") return "hub";
7538
+ const slashIdx = raw.indexOf("/");
7539
+ if (slashIdx < 0) return raw;
7540
+ const bare = raw.slice(0, slashIdx);
7541
+ return bare === "" ? "hub" : bare;
7542
+ }
7543
+ /** The node-scoped store key for a per-node field: `<base>@<nodeId>`. */
7544
+ function nodeScopedKey(base, nodeId) {
7545
+ return `${base}@${normalizeNodeId(nodeId)}`;
7546
+ }
7547
+ /**
7548
+ * Read a node's value for a per-node field from the raw shared store:
7549
+ * the node-scoped key when present, otherwise `undefined`.
7550
+ * Deliberately NO bare-key fallback (see module doc) — the caller lets the
7551
+ * schema `default` win on `undefined`.
7552
+ */
7553
+ function readNodeValue(store, base, nodeId) {
7554
+ return store[nodeScopedKey(base, nodeId)];
7555
+ }
7556
+ /**
7557
+ * Re-map a UI/settings patch so every bare perNode field persists under the
7558
+ * TARGET node's scoped key; all other keys pass through unchanged. Used on
7559
+ * the write path so a save for one node never clobbers another node's value
7560
+ * (and the bare key is never written). Returns a new object — the input
7561
+ * patch is not mutated.
7562
+ */
7563
+ function scopePatch(patch, perNodeKeys, nodeId) {
7564
+ const out = {};
7565
+ for (const [key, value] of Object.entries(patch)) out[perNodeKeys.has(key) ? nodeScopedKey(key, nodeId) : key] = value;
7566
+ return out;
7567
+ }
7568
+ /**
7569
+ * Project the raw shared store onto the bare schema keys for ONE node so a
7570
+ * UI schema (whose field keys are bare) hydrates from that node's own
7571
+ * values:
7572
+ *
7573
+ * - EVERY `@`-scoped key (any node's) is dropped from the pass-through.
7574
+ * - Every bare perNode key is dropped from the pass-through (a stray bare
7575
+ * legacy key must never hydrate any node — no bare fallback).
7576
+ * - THIS node's effective value ({@link readNodeValue}) is then laid onto
7577
+ * each bare perNode key; when the node has no scoped key the bare key is
7578
+ * left ABSENT so the field's schema `default` wins.
7579
+ *
7580
+ * Returns a new object — the input store is not mutated.
7581
+ */
7582
+ function projectStore(store, perNodeKeys, nodeId) {
7583
+ const out = {};
7584
+ for (const [key, value] of Object.entries(store)) {
7585
+ if (key.includes("@")) continue;
7586
+ if (perNodeKeys.has(key)) continue;
7587
+ out[key] = value;
7588
+ }
7589
+ for (const base of perNodeKeys) {
7590
+ const value = readNodeValue(store, base, nodeId);
7591
+ if (value !== void 0) out[base] = value;
7592
+ }
7593
+ return out;
7594
+ }
7595
+ /** Every scope, in the order the guard and the docs list them. */
7596
+ var SCOPED_SETTINGS_SCOPES = [
7597
+ "cluster",
7598
+ "device-defaults",
7599
+ "node"
7600
+ ];
7002
7601
  /** A write to a secret path could not be stored in the keychain, so it was refused. */
7003
7602
  var KeychainWriteRefusedError = class extends Error {
7004
7603
  fieldPath;
@@ -7009,7 +7608,7 @@ var KeychainWriteRefusedError = class extends Error {
7009
7608
  }
7010
7609
  };
7011
7610
  var KEEP = { kind: "keep" };
7012
- function isRecord$6(value) {
7611
+ function isRecord$4(value) {
7013
7612
  return typeof value === "object" && value !== null && !Array.isArray(value);
7014
7613
  }
7015
7614
  function defaultMintId() {
@@ -7022,7 +7621,7 @@ function collectSecretMarkerRefs(value, out = []) {
7022
7621
  return out;
7023
7622
  }
7024
7623
  if (Array.isArray(value)) for (const item of value) collectSecretMarkerRefs(item, out);
7025
- else if (isRecord$6(value)) for (const child of Object.values(value)) collectSecretMarkerRefs(child, out);
7624
+ else if (isRecord$4(value)) for (const child of Object.values(value)) collectSecretMarkerRefs(child, out);
7026
7625
  return out;
7027
7626
  }
7028
7627
  async function storedValueEquals(secrets, marker, candidate) {
@@ -7077,7 +7676,7 @@ function rowId$1(row, idKey) {
7077
7676
  return null;
7078
7677
  }
7079
7678
  async function writeArray(ctx, node, incoming, stored, fieldPath) {
7080
- const storedRows = Array.isArray(stored) ? stored.filter(isRecord$6) : [];
7679
+ const storedRows = Array.isArray(stored) ? stored.filter(isRecord$4) : [];
7081
7680
  if (!Array.isArray(incoming)) {
7082
7681
  ctx.deletes.push(...collectSecretMarkerRefs(storedRows));
7083
7682
  return {
@@ -7093,7 +7692,7 @@ async function writeArray(ctx, node, incoming, stored, fieldPath) {
7093
7692
  const kept = /* @__PURE__ */ new Set();
7094
7693
  const rows = [];
7095
7694
  for (const row of incoming) {
7096
- if (!isRecord$6(row)) {
7695
+ if (!isRecord$4(row)) {
7097
7696
  rows.push(row);
7098
7697
  continue;
7099
7698
  }
@@ -7118,7 +7717,7 @@ async function writeNode(ctx, node, incoming, stored, fieldPath) {
7118
7717
  case "leaf": return writeLeaf(ctx, incoming, stored, fieldPath);
7119
7718
  case "array": return writeArray(ctx, node, incoming, stored, fieldPath);
7120
7719
  case "object": {
7121
- if (!isRecord$6(incoming)) {
7720
+ if (!isRecord$4(incoming)) {
7122
7721
  if (incoming === void 0) return KEEP;
7123
7722
  ctx.deletes.push(...collectSecretMarkerRefs(stored));
7124
7723
  return {
@@ -7126,7 +7725,7 @@ async function writeNode(ctx, node, incoming, stored, fieldPath) {
7126
7725
  value: incoming
7127
7726
  };
7128
7727
  }
7129
- const storedObj = isRecord$6(stored) ? stored : {};
7728
+ const storedObj = isRecord$4(stored) ? stored : {};
7130
7729
  return {
7131
7730
  kind: "value",
7132
7731
  value: await writeMembers(ctx, node.children, incoming, storedObj, (m) => `${fieldPath}.${m}`)
@@ -7249,7 +7848,7 @@ async function resolveSecretMarkers(value, secrets, options = {}) {
7249
7848
  value: items
7250
7849
  };
7251
7850
  }
7252
- if (isRecord$6(v)) {
7851
+ if (isRecord$4(v)) {
7253
7852
  const out = {};
7254
7853
  for (const [k, child] of Object.entries(v)) {
7255
7854
  const s = substitute(child);
@@ -7281,7 +7880,7 @@ var SecretOverwriteRefusedError = class extends Error {
7281
7880
  this.name = "SecretOverwriteRefusedError";
7282
7881
  }
7283
7882
  };
7284
- function isRecord$5(value) {
7883
+ function isRecord$3(value) {
7285
7884
  return typeof value === "object" && value !== null && !Array.isArray(value);
7286
7885
  }
7287
7886
  function resolvedValue(pass, marker) {
@@ -7310,7 +7909,7 @@ function inArray(pass, incoming, stored) {
7310
7909
  return incoming.map((item, index) => {
7311
7910
  const twin = stored[index];
7312
7911
  if (isSecretMarker(twin)) return typeof item === "string" && item === resolvedValue(pass, twin) ? twin : item;
7313
- if (isRecord$5(item) && isRecord$5(twin)) return inArrayRow(pass, item, twin);
7912
+ if (isRecord$3(item) && isRecord$3(twin)) return inArrayRow(pass, item, twin);
7314
7913
  if (Array.isArray(item) && Array.isArray(twin)) return inArray(pass, item, twin);
7315
7914
  return item;
7316
7915
  });
@@ -7321,7 +7920,7 @@ function inArrayRow(pass, incoming, stored) {
7321
7920
  const twin = stored[key];
7322
7921
  if (isSecretMarker(twin)) {
7323
7922
  if (typeof value === "string" && value === resolvedValue(pass, twin)) out[key] = twin;
7324
- } else if (isRecord$5(value) && isRecord$5(twin)) out[key] = inArrayRow(pass, value, twin);
7923
+ } else if (isRecord$3(value) && isRecord$3(twin)) out[key] = inArrayRow(pass, value, twin);
7325
7924
  else if (Array.isArray(value) && Array.isArray(twin)) out[key] = inArray(pass, value, twin);
7326
7925
  }
7327
7926
  return out;
@@ -7329,7 +7928,7 @@ function inArrayRow(pass, incoming, stored) {
7329
7928
  async function walk(pass, incoming, stored) {
7330
7929
  if (isSecretMarker(stored)) return atMarker(pass, incoming, stored);
7331
7930
  if (Array.isArray(incoming) && Array.isArray(stored)) return inArray(pass, incoming, stored);
7332
- if (!isRecord$5(incoming) || !isRecord$5(stored)) return incoming;
7931
+ if (!isRecord$3(incoming) || !isRecord$3(stored)) return incoming;
7333
7932
  const out = { ...incoming };
7334
7933
  for (const [key, value] of Object.entries(incoming)) out[key] = await walk(pass, value, stored[key]);
7335
7934
  return out;
@@ -7360,7 +7959,7 @@ async function restoreUnchangedSecrets(input) {
7360
7959
  function isJsonEqual(a, b) {
7361
7960
  if (Object.is(a, b)) return true;
7362
7961
  if (Array.isArray(a)) return Array.isArray(b) && a.length === b.length && a.every((v, i) => isJsonEqual(v, b[i]));
7363
- if (isRecord$5(a) && isRecord$5(b)) {
7962
+ if (isRecord$3(a) && isRecord$3(b)) {
7364
7963
  const keys = Object.keys(a);
7365
7964
  if (keys.length !== Object.keys(b).length) return false;
7366
7965
  return keys.every((k) => Object.prototype.hasOwnProperty.call(b, k) && isJsonEqual(a[k], b[k]));
@@ -7384,7 +7983,7 @@ function markerKeysOf(blob, owner) {
7384
7983
  }
7385
7984
  function nodeFromStored(value, owner) {
7386
7985
  if (isSecretMarker(value)) return isSecretRefOwnedBy(value.$secret, owner) ? { kind: "leaf" } : null;
7387
- if (!isRecord$5(value)) return null;
7986
+ if (!isRecord$3(value)) return null;
7388
7987
  const children = /* @__PURE__ */ new Map();
7389
7988
  for (const [key, child] of Object.entries(value)) {
7390
7989
  const node = nodeFromStored(child, owner);
@@ -7679,6 +8278,28 @@ var SECRET_RETRY_MAX_MS = 5 * 6e4;
7679
8278
  /** Coalesces a burst of `keychain.changed` events into one re-resolve. */
7680
8279
  var SECRET_CHANGE_DEBOUNCE_MS = 250;
7681
8280
  /**
8281
+ * Pair a catalogue with the function that builds its ports FROM THE MIGRATION API. The one
8282
+ * place a catalogue is bound: a migration reaches nothing a ports binder cannot reach
8283
+ * through `api` (guard `check-migration-ports-surface`).
8284
+ */
8285
+ function migrationSet(catalogue, bindPorts) {
8286
+ return { bind: (api) => defineAddonMigrations(catalogue, bindPorts(api)) };
8287
+ }
8288
+ /** A mixed array is a mistake: the other kind would be dropped without a word. */
8289
+ function refuseMixed(form, kept, dropped) {
8290
+ if (dropped > 0) throw new Error(`runMigrations(${form}): ${dropped} of ${kept + dropped} entries are of the other kind and would be dropped; pass one kind per call`);
8291
+ }
8292
+ function catalogueOf(list) {
8293
+ const kept = list.filter((entry) => !("execute" in entry));
8294
+ refuseMixed("catalogue, (api) => ports", kept.length, list.length - kept.length);
8295
+ return kept;
8296
+ }
8297
+ function boundOf(list) {
8298
+ const kept = list.filter((entry) => "execute" in entry);
8299
+ refuseMixed("bound migrations", kept.length, list.length - kept.length);
8300
+ return kept;
8301
+ }
8302
+ /**
7682
8303
  * Base class for CamStack addons. Eliminates settings boilerplate:
7683
8304
  *
7684
8305
  * - Typed `config` property with automatic resolution from store + defaults
@@ -7756,6 +8377,13 @@ var BaseAddon = class {
7756
8377
  */
7757
8378
  secretStatePaths = [];
7758
8379
  _addonSecretTree = null;
8380
+ /**
8381
+ * D986 M4: the scoped schemas this addon declared, resolved once per capability
8382
+ * (`loadScopedSchemas`) so the sync readers (`perNodeKeys`, the secret tree, the restart check)
8383
+ * see them. Empty until loaded: the readers then fall back to {@link globalSettingsSchema}.
8384
+ */
8385
+ _scopedByCap = /* @__PURE__ */ new Map();
8386
+ _nodeKeysByCap = /* @__PURE__ */ new Map();
7759
8387
  _deviceSecretTree = null;
7760
8388
  /** Refs the last resolved config pointed at — a change to one re-resolves. */
7761
8389
  _configSecretRefs = /* @__PURE__ */ new Set();
@@ -7825,6 +8453,7 @@ var BaseAddon = class {
7825
8453
  this._ctx = context;
7826
8454
  this._secretSettings = null;
7827
8455
  }
8456
+ await this.loadScopedSchemas();
7828
8457
  await this.resolveConfig();
7829
8458
  if (secrets !== void 0) this._secretChangeUnsub = secrets.onChange((ref) => {
7830
8459
  if (this._configSecretRefs.has(ref)) this.scheduleSecretReresolve(SECRET_CHANGE_DEBOUNCE_MS);
@@ -7834,31 +8463,65 @@ var BaseAddon = class {
7834
8463
  const normalized = normalizeAddonInitResult(result);
7835
8464
  const providers = normalized && "providers" in normalized && normalized.providers ? normalized.providers : [];
7836
8465
  this._registeredCapNames = providers.map((p) => p.capability.name);
8466
+ await this.loadScopedSchemas();
7837
8467
  return normalized;
7838
8468
  }
8469
+ async runMigrations(first, second, third) {
8470
+ if (typeof second === "function") return this.runMigrationSets([migrationSet(catalogueOf(first), second)], third);
8471
+ return this.runBound(boundOf(first), second);
8472
+ }
7839
8473
  /**
7840
- * Run this addon's migration catalogue (D987 M3) through the hub's `migrations`
7841
- * engine. Call it at the point of the boot where the data must already have the new
7842
- * shape — `onInitialize`, or `onRestoreDevices` for a migration that needs the
7843
- * restored devices — with the catalogue bound to the addon's ports
7844
- * (`defineAddonMigrations(ADDON_MIGRATIONS, ports)`).
7845
- *
7846
- * An engine that cannot be reached or refuses the catalogue is logged and runs
7847
- * nothing; the boot continues. A migration that FAILED (or was blocked by one)
7848
- * and declares `onFailure: 'block-owner'` makes this throw, so the addon does not
7849
- * serve data whose shape it cannot trust; `tolerate` migrations never do.
7850
- *
7851
- * ALWAYS pass the whole catalogue; a phase that must run only some of it passes
7852
- * `{ only: [ids] }` — never a filtered catalogue (the engine would judge the
7853
- * omitted applied ids "newer").
8474
+ * Several catalogues of ONE owner in one declaration (the engine replaces an owner's
8475
+ * catalogue on every declare, so two calls would each judge the other's ids "newer").
8476
+ * Build each entry with `migrationSet(catalogue, (api) => ports)`.
7854
8477
  */
7855
- async runMigrations(migrations, options) {
8478
+ async runMigrationSets(sets, options) {
8479
+ const api = this.ctx.migrationApi;
8480
+ if (api === void 0) throw new Error(`${this.ctx.id}: the migration API is not available on this context`);
8481
+ return this.runBound(sets.flatMap((set) => set.bind(api)), options);
8482
+ }
8483
+ /**
8484
+ * A device addon states its instance kind once, before its migrations run, and the one-switch
8485
+ * migration (registry `enabled` to the instance body, epic #440 step 3) joins whatever
8486
+ * catalogue the addon runs, in the SAME declaration (the engine replaces an owner's catalogue
8487
+ * on every declare).
8488
+ */
8489
+ declareRegistrySwitch(spec) {
8490
+ this.registrySwitchSpec = spec;
8491
+ }
8492
+ registrySwitchSpec = null;
8493
+ registrySwitchBound() {
8494
+ const spec = this.registrySwitchSpec;
8495
+ if (spec === null) return [];
8496
+ const api = this.ctx.migrationApi;
8497
+ if (api === void 0) {
8498
+ this.ctx.logger.warn("the registry switch migration is skipped: the migration API is not available on this context");
8499
+ return [];
8500
+ }
8501
+ return migrationSet([registrySwitchToBodyMigration({
8502
+ addonId: this.ctx.id,
8503
+ date: "2026-11-06",
8504
+ seq: 1e3,
8505
+ initialBody: spec.initialBody
8506
+ })], (a) => registrySwitchPortsOver({
8507
+ api: integrationRowsApiOver(a),
8508
+ records: switchRecordsOverMigrationApi(a),
8509
+ kind: spec.kind
8510
+ })).bind(api);
8511
+ }
8512
+ async runBound(declared, options) {
8513
+ const added = this.registrySwitchBound();
8514
+ const migrations = [...declared, ...added];
8515
+ const phased = options?.only === void 0 || added.length === 0 ? options : {
8516
+ ...options,
8517
+ only: [...options.only, ...added.map((m) => m.meta.id)]
8518
+ };
7856
8519
  const api = this.ctx.api.migrations;
7857
8520
  const report = await runAddonMigrations({
7858
8521
  declareOwner: (input) => api.declareOwner.mutate(input),
7859
8522
  startMigration: (input) => api.startMigration.mutate(input),
7860
8523
  finishMigration: (input) => api.finishMigration.mutate(input)
7861
- }, migrations, this.ctx.logger, options);
8524
+ }, migrations, this.ctx.logger, phased);
7862
8525
  if (report.blockOwner.length > 0) throw new AddonMigrationsBlockedError(report.blockOwner);
7863
8526
  return report;
7864
8527
  }
@@ -7922,6 +8585,16 @@ var BaseAddon = class {
7922
8585
  schema(schema) {
7923
8586
  return schema;
7924
8587
  }
8588
+ /**
8589
+ * The capability names whose scoped settings schemas ({@link clusterSettingsSchema},
8590
+ * {@link nodeSettingsSchema}, {@link deviceDefaultsSchema}) this addon declares. Read BEFORE
8591
+ * `onInitialize`, when the providers it registers are not known yet: the first config resolve
8592
+ * must already know which keys are per node. Names the providers register at init are added
8593
+ * once known.
8594
+ */
8595
+ scopedSettingsCapabilities() {
8596
+ return [];
8597
+ }
7925
8598
  /** Override to provide global-level settings UI schema. */
7926
8599
  globalSettingsSchema(_cap) {
7927
8600
  return null;
@@ -7965,7 +8638,8 @@ var BaseAddon = class {
7965
8638
  return [];
7966
8639
  }
7967
8640
  async getGlobalSettings(overlay, cap, nodeId) {
7968
- const schema = this.globalSettingsSchema(cap);
8641
+ await this.loadScopedSchemas(cap);
8642
+ const schema = this.globalSettingsSchema(cap) ?? this.scopedFormSchema(cap);
7969
8643
  if (!schema) return { sections: [] };
7970
8644
  const projected = await this.readRawProjectedStore(nodeId, cap);
7971
8645
  return hydrateSchema(schema, overlay ? await this.overlayKeepingMarkers(projected, overlay) : projected, { inlineSecretsAsViews: true });
@@ -8096,6 +8770,7 @@ var BaseAddon = class {
8096
8770
  * resolved blob back is a no-op for every unchanged secret.
8097
8771
  */
8098
8772
  async resolveGlobalStore(nodeId, cap) {
8773
+ await this.loadScopedSchemas(cap);
8099
8774
  const raw = await this._ctx?.settings?.readAddonStore() ?? {};
8100
8775
  return this.projectForNode(raw, nodeId, cap);
8101
8776
  }
@@ -8106,6 +8781,7 @@ var BaseAddon = class {
8106
8781
  }
8107
8782
  /** The PROJECTED store with its markers — the form hydrate only (D798). */
8108
8783
  async readRawProjectedStore(nodeId, cap) {
8784
+ await this.loadScopedSchemas(cap);
8109
8785
  const raw = await this.rawSettings()?.readAddonStore() ?? {};
8110
8786
  return this.projectForNode(raw, nodeId, cap);
8111
8787
  }
@@ -8208,6 +8884,7 @@ var BaseAddon = class {
8208
8884
  await this.applyGlobalPatch(patch, nodeId);
8209
8885
  }
8210
8886
  async applyGlobalPatch(barePatch, nodeId) {
8887
+ await this.loadScopedSchemas();
8211
8888
  const keys = this.perNodeKeys();
8212
8889
  const localNode = normalizeNodeId(this._ctx?.kernel?.localNodeId);
8213
8890
  const target = normalizeNodeId(nodeId ?? this._ctx?.kernel?.localNodeId);
@@ -8221,7 +8898,8 @@ var BaseAddon = class {
8221
8898
  await this.resolveConfig();
8222
8899
  await this.onConfigChanged();
8223
8900
  this.emitLifecycle(EventCategory.AddonUpdated, { level: "global" });
8224
- this.maybeAutoRestart(Object.keys(barePatch), this.globalSettingsSchema());
8901
+ const legacy = this.globalSettingsSchema();
8902
+ this.maybeAutoRestart(Object.keys(barePatch), [...legacy === null ? [] : [legacy], ...this.loadedScopedSchemas().map((entry) => entry.schema)]);
8225
8903
  }
8226
8904
  /**
8227
8905
  * The set of field keys the global settings schema declares `perNode: true`
@@ -8229,14 +8907,67 @@ var BaseAddon = class {
8229
8907
  * declarations). Empty set ⇒ every per-node code path is bypassed and the
8230
8908
  * settings API behaves exactly like the legacy node-agnostic one.
8231
8909
  */
8232
- _perNodeKeysCache = /* @__PURE__ */ new Map();
8910
+ /**
8911
+ * Load the scoped schemas of every capability this addon declares (the override and the
8912
+ * providers registered at init, plus `extraCap`) that is not loaded yet, then drop what was
8913
+ * derived from the previous set. Idempotent.
8914
+ */
8915
+ async loadScopedSchemas(extraCap) {
8916
+ const caps = new Set([
8917
+ ...this.scopedSettingsCapabilities(),
8918
+ ...this._registeredCapNames,
8919
+ ...extraCap === void 0 ? [] : [extraCap]
8920
+ ]);
8921
+ let added = false;
8922
+ for (const cap of caps) {
8923
+ if (this._scopedByCap.has(cap)) continue;
8924
+ const loaded = [];
8925
+ for (const scope of SCOPED_SETTINGS_SCOPES) {
8926
+ const schema = await this.getScopedSettingsSchema(scope, cap);
8927
+ if (schema !== null) loaded.push({
8928
+ scope,
8929
+ schema
8930
+ });
8931
+ }
8932
+ this._scopedByCap.set(cap, loaded);
8933
+ added = true;
8934
+ }
8935
+ if (!added) return;
8936
+ this._nodeKeysByCap = /* @__PURE__ */ new Map();
8937
+ this._addonSecretTree = null;
8938
+ }
8939
+ /**
8940
+ * The form the settings API serves while an addon declares no {@link globalSettingsSchema}: the
8941
+ * sections of its scoped schemas, so dropping the old hook does not blank the form.
8942
+ */
8943
+ scopedFormSchema(cap) {
8944
+ const byId = /* @__PURE__ */ new Map();
8945
+ for (const entry of this.loadedScopedSchemas(cap)) for (const section of entry.schema.sections) if (!byId.has(section.id)) byId.set(section.id, section);
8946
+ return byId.size === 0 ? null : { sections: [...byId.values()] };
8947
+ }
8948
+ /** Every loaded scoped schema of `cap`, or of every loaded capability. */
8949
+ loadedScopedSchemas(cap) {
8950
+ if (cap !== void 0) return this._scopedByCap.get(cap) ?? [];
8951
+ return [...this._scopedByCap.values()].flat();
8952
+ }
8953
+ /**
8954
+ * The field keys that are stored per node: every field of a {@link nodeSettingsSchema}, plus
8955
+ * the fields the legacy {@link globalSettingsSchema} still marks `perNode: true`. Derived once
8956
+ * per `cap` argument and memoized (schemas are static declarations). Empty set ⇒ every
8957
+ * per-node code path is bypassed and the settings API behaves like the node-agnostic one.
8958
+ * Call {@link loadScopedSchemas} first (the async seams do).
8959
+ */
8233
8960
  perNodeKeys(cap) {
8234
8961
  const cacheKey = cap ?? "";
8235
- const cached = this._perNodeKeysCache.get(cacheKey);
8962
+ const cached = this._nodeKeysByCap.get(cacheKey);
8236
8963
  if (cached) return cached;
8237
- const schema = this.globalSettingsSchema(cap);
8238
- const keys = new Set(schema ? schema.sections.flatMap((section) => collectPerNodeFieldKeys(section.fields)) : []);
8239
- this._perNodeKeysCache.set(cacheKey, keys);
8964
+ const legacy = this.globalSettingsSchema(cap);
8965
+ const keys = new Set(legacy ? legacy.sections.flatMap((section) => collectPerNodeFieldKeys(section.fields)) : []);
8966
+ for (const { scope, schema } of this.loadedScopedSchemas(cap)) {
8967
+ if (scope !== "node") continue;
8968
+ for (const section of schema.sections) for (const key of collectValueFieldKeys(section.fields)) keys.add(key);
8969
+ }
8970
+ this._nodeKeysByCap.set(cacheKey, keys);
8240
8971
  return keys;
8241
8972
  }
8242
8973
  /**
@@ -8246,10 +8977,9 @@ var BaseAddon = class {
8246
8977
  * time to return its response before the addon is torn down and
8247
8978
  * re-initialised by `AddonRegistryService.restartAddon`.
8248
8979
  */
8249
- maybeAutoRestart(patchKeys, schema) {
8250
- if (!schema) return;
8980
+ maybeAutoRestart(patchKeys, schemas) {
8251
8981
  const restartKeys = /* @__PURE__ */ new Set();
8252
- for (const section of schema.sections) for (const field of section.fields) {
8982
+ for (const schema of schemas) for (const section of schema.sections) for (const field of section.fields) {
8253
8983
  if (field.type === "separator" || field.type === "info") continue;
8254
8984
  if (field.requiresRestart) restartKeys.add(field.key);
8255
8985
  }
@@ -8445,12 +9175,14 @@ var BaseAddon = class {
8445
9175
  * here, in the addon's own process, so the hub keeps no copy of it.
8446
9176
  */
8447
9177
  async getDeclaredSettingsKeys() {
9178
+ await this.loadScopedSchemas();
8448
9179
  return { keys: [...this.declaredKeySet()].toSorted() };
8449
9180
  }
8450
9181
  declaredKeySet() {
8451
9182
  const keys = new Set(Object.keys(this.defaults));
8452
9183
  const schema = this.globalSettingsSchema();
8453
9184
  if (schema) for (const section of schema.sections) for (const key of collectFieldKeys(section.fields)) keys.add(key);
9185
+ for (const { schema: scoped } of this.loadedScopedSchemas()) for (const section of scoped.sections) for (const key of collectFieldKeys(section.fields)) keys.add(key);
8454
9186
  for (const key of this._declaredStateKeys) keys.add(key);
8455
9187
  for (const path of this.secretStatePaths) {
8456
9188
  const root = path.split(/[.[]/, 1)[0];
@@ -8546,7 +9278,11 @@ var BaseAddon = class {
8546
9278
  }
8547
9279
  /** The addon store's secret tree: schema fields by TYPE, plus `secretStatePaths`. */
8548
9280
  addonSecretTree() {
8549
- this._addonSecretTree ??= mergeSecretStatePaths(secretTreeFromSchema(this.globalSettingsSchema()), this.secretStatePaths);
9281
+ if (this._addonSecretTree === null) {
9282
+ const tree = new Map(secretTreeFromSchema(this.globalSettingsSchema()));
9283
+ for (const { schema } of this.loadedScopedSchemas()) for (const [key, node] of secretTreeFromSchema(schema)) tree.set(key, node);
9284
+ this._addonSecretTree = mergeSecretStatePaths(tree, this.secretStatePaths);
9285
+ }
8550
9286
  return this._addonSecretTree;
8551
9287
  }
8552
9288
  deviceSecretTree() {
@@ -8796,6 +9532,23 @@ function dropPerNodeFields(fields) {
8796
9532
  }
8797
9533
  return kept;
8798
9534
  }
9535
+ /** The keys of the value-holding fields, recursing into layout containers. */
9536
+ function collectValueFieldKeys(fields) {
9537
+ const collected = [];
9538
+ for (const field of fields) {
9539
+ if (field.type === "group") {
9540
+ collected.push(...collectValueFieldKeys(field.fields));
9541
+ continue;
9542
+ }
9543
+ if (field.type === "sub-tabs") {
9544
+ for (const tab of field.tabs) collected.push(...collectValueFieldKeys(tab.fields));
9545
+ continue;
9546
+ }
9547
+ if (field.type === "separator" || field.type === "info") continue;
9548
+ if ("key" in field && typeof field.key === "string") collected.push(field.key);
9549
+ }
9550
+ return collected;
9551
+ }
8799
9552
  function collectFieldKeys(fields) {
8800
9553
  const collected = [];
8801
9554
  for (const field of fields) {
@@ -8841,228 +9594,6 @@ function normalizeAddonInitResult(result) {
8841
9594
  if (Array.isArray(result)) return { providers: result };
8842
9595
  return result;
8843
9596
  }
8844
- var PREFIX$1 = "records/";
8845
- /** The base of every records failure. `detail` is the human part of the message. */
8846
- var RecordsError = class extends Error {
8847
- code;
8848
- detail;
8849
- constructor(code, detail) {
8850
- super(`${PREFIX$1}${code}: ${detail}`);
8851
- this.name = "RecordsError";
8852
- this.code = code;
8853
- this.detail = detail;
8854
- }
8855
- };
8856
- /** A write guarded by `ifRev` found another revision (or an existing row for `ifRev: 0`). */
8857
- var RevConflictError = class extends RecordsError {
8858
- constructor(detail) {
8859
- super("rev-conflict", detail);
8860
- this.name = "RevConflictError";
8861
- }
8862
- };
8863
- /** The keychain could not store or serve a value: explicit, never an empty string. */
8864
- var RecordSecretUnavailableError = class extends RecordsError {
8865
- constructor(detail) {
8866
- super("secret-unavailable", detail);
8867
- this.name = "RecordSecretUnavailableError";
8868
- }
8869
- };
8870
- var InvalidRecordError = class extends RecordsError {
8871
- constructor(detail) {
8872
- super("invalid-record", detail);
8873
- this.name = "InvalidRecordError";
8874
- }
8875
- };
8876
- /** A kind declaration the engine refuses (non-additive change, bad shape, wrong file). */
8877
- var DeclarationRefusedError = class extends RecordsError {
8878
- constructor(detail) {
8879
- super("declaration-refused", detail);
8880
- this.name = "DeclarationRefusedError";
8881
- }
8882
- };
8883
- /** Limits and names of `ctx.records` (D881). One authority; the engine and the facade read it. */
8884
- /** The files a kind may live in. `history` is device-history's (D850), never records. */
8885
- var RECORD_DATABASES = ["settings", "events"];
8886
- /** The classes of a kind: the `@durable` vocabulary, one authority (replaces the annotation). */
8887
- var RECORD_CLASSES = [
8888
- "config",
8889
- "ledger",
8890
- "audit",
8891
- "mirror",
8892
- "ephemeral"
8893
- ];
8894
- var RECORD_DEFAULT_MAX_DATA_BYTES = 64 * 1024;
8895
- var RECORD_MAX_DATA_BYTES = 1024 * 1024;
8896
- var RECORD_BATCH_MAX = 1e3;
8897
- var RECORD_QUERY_MAX = 1e3;
8898
- /** A kind in the `settings` file may not bound itself above this (D447: high volume is `events`). */
8899
- var RECORD_SETTINGS_MAX_ROWS = 5e4;
8900
- /** The `Column`-free proof prefix: a ref collection for a kind's secret fields. */
8901
- var RECORD_SECRET_COLLECTION_PREFIX = "records:";
8902
- /**
8903
- * Secret fields of a record, addressed the way a Zod schema declares them
8904
- * (`collectZodSecretPaths`): dotted keys, `[]` for "each element of this array"
8905
- * (`auth.accessToken`, `headers[].value`).
8906
- *
8907
- * `{}` after a key means "each value of this map" (`applianceSecrets{}`): the map's own key
8908
- * names the value (`applianceSecrets{fridge}`), so no id key is declared and a body that drops a
8909
- * key releases exactly that key's secret.
8910
- *
8911
- * Array elements are matched by a DECLARED id key (`secretArrayKeys`:
8912
- * `{ headers: 'name' }`), never by index, so reordering a list keeps every
8913
- * keychain ref (the same rule as `arrayItemFieldPath`). The concrete path of a
8914
- * leaf names its element: `headers[X-Api].value`.
8915
- *
8916
- * Pure and browser-safe. Nothing here mutates: every transform returns a new value.
8917
- */
8918
- /** The array prefixes (declared form, e.g. `headers` or `a.headers`) of a path. */
8919
- function parseSecretPath(path) {
8920
- if (path.length === 0) throw new InvalidRecordError("an empty secret path");
8921
- return path.split(".").map((raw) => {
8922
- const each = raw.endsWith("[]");
8923
- const map = raw.endsWith("{}");
8924
- const key = each || map ? raw.slice(0, -2) : raw;
8925
- if (key.length === 0) throw new InvalidRecordError(`secret path "${path}" has an empty segment`);
8926
- return {
8927
- key,
8928
- each,
8929
- map
8930
- };
8931
- });
8932
- }
8933
- /** The declared array prefixes of `path` that need an id key (`headers`, `a.rows`). */
8934
- function secretArrayPrefixes(path) {
8935
- const segments = parseSecretPath(path);
8936
- const prefixes = [];
8937
- const walked = [];
8938
- for (const segment of segments) {
8939
- walked.push(segment.key);
8940
- if (segment.each) prefixes.push(walked.join("."));
8941
- }
8942
- return prefixes;
8943
- }
8944
- function isRecord$4(value) {
8945
- return typeof value === "object" && value !== null && !Array.isArray(value);
8946
- }
8947
- function elementId(element, idKey, declared, prefix) {
8948
- const id = isRecord$4(element) ? element[idKey] : void 0;
8949
- 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`);
8950
- return id;
8951
- }
8952
- /**
8953
- * Visit every secret leaf PRESENT in `data` (an absent branch has nothing to
8954
- * visit). `replace` returns the new leaf value, or {@link REMOVE_LEAF}; the
8955
- * result is a new body, `data` is untouched.
8956
- */
8957
- var REMOVE_LEAF = Symbol("remove-leaf");
8958
- function mapAt(node, segments, index, walkedKeys, concretePrefix, declared, arrayKeys, visit) {
8959
- if (!isRecord$4(node)) return node;
8960
- const segment = segments[index];
8961
- if (segment === void 0) return node;
8962
- if (!Object.prototype.hasOwnProperty.call(node, segment.key)) return node;
8963
- const child = node[segment.key];
8964
- const keys = [...walkedKeys, segment.key];
8965
- const last = index === segments.length - 1;
8966
- if (segment.each) {
8967
- if (!Array.isArray(child)) return node;
8968
- const prefix = keys.join(".");
8969
- const idKey = arrayKeys[prefix];
8970
- if (idKey === void 0) throw new InvalidRecordError(`"${declared}": no id key declared for the array "${prefix}"`);
8971
- const mapped = child.map((element) => {
8972
- const id = elementId(element, idKey, declared, prefix);
8973
- const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}[${encodeURIComponent(id)}]`;
8974
- return last ? element : mapAt(element, segments, index + 1, keys, concrete, declared, arrayKeys, visit);
8975
- });
8976
- return {
8977
- ...node,
8978
- [segment.key]: mapped
8979
- };
8980
- }
8981
- if (segment.map) {
8982
- if (!isRecord$4(child)) return node;
8983
- const kept = Object.entries(child).map(([mapKey, value]) => {
8984
- const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}{${encodeURIComponent(mapKey)}}`;
8985
- if (!last) return [mapKey, mapAt(value, segments, index + 1, keys, concrete, declared, arrayKeys, visit)];
8986
- return [mapKey, visit({
8987
- declared,
8988
- concrete,
8989
- value
8990
- })];
8991
- }).filter(([, value]) => value !== REMOVE_LEAF);
8992
- return {
8993
- ...node,
8994
- [segment.key]: Object.fromEntries(kept)
8995
- };
8996
- }
8997
- const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}`;
8998
- if (last) {
8999
- const replacement = visit({
9000
- declared,
9001
- concrete,
9002
- value: child
9003
- });
9004
- if (replacement === REMOVE_LEAF) return Object.fromEntries(Object.entries(node).filter(([key]) => key !== segment.key));
9005
- return {
9006
- ...node,
9007
- [segment.key]: replacement
9008
- };
9009
- }
9010
- return {
9011
- ...node,
9012
- [segment.key]: mapAt(child, segments, index + 1, keys, concrete, declared, arrayKeys, visit)
9013
- };
9014
- }
9015
- /** Replace/remove every present secret leaf; returns a NEW body. */
9016
- function mapSecretLeaves(data, paths, arrayKeys, visit) {
9017
- let current = data;
9018
- for (const declared of paths) current = mapAt(current, parseSecretPath(declared), 0, [], "", declared, arrayKeys, visit);
9019
- return current;
9020
- }
9021
- /**
9022
- * The keychain collection name a kind's secrets live under. Prefixed so a
9023
- * record's refs never collide with the refs a legacy collection of the same name
9024
- * already holds during an adoption.
9025
- */
9026
- function recordSecretCollection(kind) {
9027
- return `${RECORD_SECRET_COLLECTION_PREFIX}${kind}`;
9028
- }
9029
- /** The ONE ref a row's secret field may carry: the engine and the facade both build it here. */
9030
- function recordSecretRef(owner, kind, rowId, concretePath) {
9031
- return buildSecretRef({
9032
- owner,
9033
- scope: {
9034
- kind: "row",
9035
- collection: recordSecretCollection(kind),
9036
- rowId
9037
- },
9038
- fieldPath: concretePath
9039
- });
9040
- }
9041
- /**
9042
- * A stored secret, as an admin read shows it: a VIEW naming the row's own
9043
- * keychain ref (`set: true`), never the value and no longer the bare redaction
9044
- * token. The form hands it to the secret field, which reveals the value by ref
9045
- * through the audited `keychain-admin.reveal`; sent back untouched it keeps the
9046
- * stored secret (the records door reads a view as KEEP).
9047
- *
9048
- * ONE implementation for the entries service and for every addon that serves
9049
- * its own instances (`RecordIntegrationInstances`).
9050
- */
9051
- function isRecord$3(value) {
9052
- return typeof value === "object" && value !== null && !Array.isArray(value);
9053
- }
9054
- function secretViewsOf(owner, kind, id, decl, data) {
9055
- if (decl.secretPaths.length === 0) return data;
9056
- const shown = mapSecretLeaves(data, decl.secretPaths, decl.secretArrayKeys, (leaf) => {
9057
- if (leaf.value !== "__camstack_redacted__") return leaf.value;
9058
- return {
9059
- $secret: recordSecretRef(owner, kind, id, leaf.concrete),
9060
- v: 1,
9061
- set: true
9062
- };
9063
- });
9064
- return isRecord$3(shown) ? shown : data;
9065
- }
9066
9597
  /**
9067
9598
  * The share-view scope kinds a share-link token can carry. The hub mints
9068
9599
  * and validates them (`ShareViewGrantSchema` builds its
@@ -11141,6 +11672,10 @@ Object.freeze({
11141
11672
  "all",
11142
11673
  "one"
11143
11674
  ]
11675
+ },
11676
+ {
11677
+ "path": "positionUpdatedAt",
11678
+ "valueType": "number"
11144
11679
  }
11145
11680
  ],
11146
11681
  "meter": [{
@@ -11395,22 +11930,6 @@ Object.freeze({
11395
11930
  "path": "pumpRunning",
11396
11931
  "valueType": "boolean"
11397
11932
  },
11398
- {
11399
- "path": "lastDrink",
11400
- "valueType": "number"
11401
- },
11402
- {
11403
- "path": "currentHourDrink",
11404
- "valueType": "number"
11405
- },
11406
- {
11407
- "path": "last24hDrink",
11408
- "valueType": "number"
11409
- },
11410
- {
11411
- "path": "todayDrink",
11412
- "valueType": "number"
11413
- },
11414
11933
  {
11415
11934
  "path": "error",
11416
11935
  "valueType": "string"
@@ -11976,12 +12495,66 @@ Object.freeze({
11976
12495
  }
11977
12496
  ]
11978
12497
  });
12498
+ Object.freeze({
12499
+ "actions": { "run": 363e4 },
12500
+ "audio-analyzer": { "classify": 3e4 },
12501
+ "custom-model-registry": { "importModelBundle": 18e5 },
12502
+ "database-snapshot": { "writeSnapshot": 18e5 },
12503
+ "device-manager": {
12504
+ "migrateDevice": 72e4,
12505
+ "runDiscoverySweep": 12e4
12506
+ },
12507
+ "device-provider": { "reloadDevice": 18e4 },
12508
+ "llm": {
12509
+ "generate": 6e5,
12510
+ "generateVision": 6e5,
12511
+ "testProfile": 6e5
12512
+ },
12513
+ "llm-runtime": {
12514
+ "complete": 6e5,
12515
+ "completeApple": 6e5,
12516
+ "ensureStarted": 6e5,
12517
+ "installModel": 36e5
12518
+ },
12519
+ "local-network": { "scanNetwork": 9e4 },
12520
+ "model-convert": { "convert": 6e5 },
12521
+ "pipeline-analytics": {
12522
+ "addRetrainFrameFromRecording": 6e4,
12523
+ "offerRetrainArchive": 12e4,
12524
+ "proposeRetrainAnnotationsWithLlm": 18e4,
12525
+ "resolveRetrainTrainingCorpus": 6e4,
12526
+ "writeRetrainArchive": 36e5
12527
+ },
12528
+ "server-management": { "applyServerUpdate": 96e4 },
12529
+ "terminal-session": { "pullOutput": 15e3 },
12530
+ "training": {
12531
+ "canaryResult": 12e4,
12532
+ "cancelJob": 12e4,
12533
+ "planJob": 6e4,
12534
+ "registerResult": 18e5,
12535
+ "rollbackCanary": 12e4,
12536
+ "startJob": 12e4,
12537
+ "startJobBatch": 12e4
12538
+ },
12539
+ "training-provider": {
12540
+ "cancelJob": 6e4,
12541
+ "cleanupJob": 3e5,
12542
+ "getJob": 6e4,
12543
+ "listJobEvents": 6e4,
12544
+ "listJobs": 12e4,
12545
+ "offerArtifact": 3e5,
12546
+ "readResult": 3e5,
12547
+ "submitJob": 18e5,
12548
+ "uploadDataset": 72e5,
12549
+ "validateCredentials": 3e4
12550
+ }
12551
+ });
11979
12552
  object({
11980
12553
  code: string().regex(/^[a-z][a-z0-9-]*(\.[a-z0-9-]+)+$/),
11981
12554
  params: record(string(), union([string(), number()])).optional()
11982
12555
  });
11983
12556
  //#endregion
11984
- //#region ../types/dist/composition-pOHbTzRB.mjs
12557
+ //#region ../types/dist/composition-BmBHuDTQ.mjs
11985
12558
  /**
11986
12559
  * The ffmpeg build every CamStack node downloads, per platform and arch.
11987
12560
  *
@@ -12285,7 +12858,7 @@ var table = {
12285
12858
  },
12286
12859
  dwell: {
12287
12860
  minArgs: 3,
12288
- maxArgs: 3,
12861
+ maxArgs: 4,
12289
12862
  apply: () => {
12290
12863
  throw new ExpressionEvalError("dwell: stateful evaluation context is required");
12291
12864
  }
@@ -13445,205 +14018,6 @@ function buildCapturingReply(envelope) {
13445
14018
  };
13446
14019
  return wrapper;
13447
14020
  }
13448
- /**
13449
- * `RecordIntegrationInstances` - the `integration-instances` provider over ONE
13450
- * entry kind, so an addon that holds a connection serves it in ~30 lines.
13451
- *
13452
- * Every instance is one record of the addon's own kind, keyed by the
13453
- * `integrations` registry id. The records door does the secret work: a field the
13454
- * kind marks `.meta({ secret: true })` is a keychain marker bound to the row, so
13455
- * deleting the row deletes the secret, and one row's value is never another's.
13456
- *
13457
- * Patch rules for a secret (`updateInstance`): omitted, `''`, the redaction
13458
- * token or the view the form was given KEEP the stored secret;
13459
- * `{ $secretClear: true }` clears it; any other string replaces it.
13460
- */
13461
- /** The most instances one addon lists (an integrations page, not a table). */
13462
- var INSTANCES_LIST_MAX = 1e3;
13463
- /** The keys of the kind's secret fields that sit at the top level of the body. */
13464
- function topLevelSecretKeys(paths) {
13465
- return new Set(paths.filter((p) => !p.includes(".") && !p.includes("[") && !p.includes("{")));
13466
- }
13467
- /** The keys of the kind's top-level MAPS whose values are secrets (`applianceSecrets{}`). */
13468
- function secretMapKeys(paths) {
13469
- return new Set(paths.filter((p) => p.endsWith("{}") && !p.slice(0, -2).match(/[.[{]/)).map((p) => p.slice(0, -2)));
13470
- }
13471
- /**
13472
- * A patch value for a map of secrets: an entry that is omitted, `''`, the redaction token or the
13473
- * view the form was given KEEPS its stored secret (it is left out of the merge); `{ $secretClear }`
13474
- * or `null` removes the entry; any other string replaces it. Null when nothing is left to merge.
13475
- */
13476
- function secretMapPatch(value) {
13477
- if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
13478
- const out = {};
13479
- for (const [key, entry] of Object.entries(value)) if (entry === null || isSecretClear(entry)) out[key] = null;
13480
- else if (typeof entry === "string" && entry !== "" && entry !== "__camstack_redacted__" && !isSecretFieldView(entry)) out[key] = entry;
13481
- return Object.keys(out).length > 0 ? out : null;
13482
- }
13483
- /** Does the kind's body schema carry an `enabled` field? */
13484
- function declaresEnabled(kind) {
13485
- const json = toJSONSchema(kind.schema, {
13486
- unrepresentable: "any",
13487
- io: "input"
13488
- });
13489
- const properties = Reflect.get(json, "properties");
13490
- return typeof properties === "object" && properties !== null && "enabled" in properties;
13491
- }
13492
- var RecordIntegrationInstances = class {
13493
- records;
13494
- kind;
13495
- hooks;
13496
- handle;
13497
- secretKeys;
13498
- secretMaps;
13499
- nameField;
13500
- /** The `integrations` registry owns the on/off switch (`role: devices`); the body has none. */
13501
- registryOwnsEnabled;
13502
- constructor(records, kind, hooks) {
13503
- this.records = records;
13504
- this.kind = kind;
13505
- this.hooks = hooks;
13506
- this.handle = records.kind(kind);
13507
- this.secretKeys = topLevelSecretKeys(kind.declaration.secretPaths);
13508
- this.secretMaps = secretMapKeys(kind.declaration.secretPaths);
13509
- this.nameField = kind.declaration.entry?.nameField ?? "name";
13510
- this.registryOwnsEnabled = hooks.description.role === "devices";
13511
- 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"`);
13512
- }
13513
- /**
13514
- * One instance read for the addon's own runtime; null when absent. When the keychain is
13515
- * locked the row is served WITHOUT its secrets and says so (`secrets: 'unavailable'`), so the
13516
- * caller can keep what it had instead of reconfiguring with an empty secret (D49).
13517
- */
13518
- async readResolved(id) {
13519
- try {
13520
- const record = await this.handle.getResolved(id);
13521
- return record === null ? null : {
13522
- id,
13523
- body: record.data,
13524
- enabled: record.data.enabled !== false,
13525
- secrets: "resolved"
13526
- };
13527
- } catch (err) {
13528
- if (!(err instanceof RecordSecretUnavailableError)) throw err;
13529
- const stored = await this.handle.get(id);
13530
- if (stored === null) return null;
13531
- return {
13532
- id,
13533
- body: Object.fromEntries(Object.entries(stored.data).filter(([key]) => !this.secretKeys.has(key))),
13534
- enabled: stored.data.enabled !== false,
13535
- secrets: "unavailable"
13536
- };
13537
- }
13538
- }
13539
- /** The body of {@link readResolved} alone; a locked keychain yields the row without secrets. */
13540
- async getResolved(id) {
13541
- return (await this.readResolved(id))?.body ?? null;
13542
- }
13543
- /** Every instance, secrets resolved where the keychain allows; an absent one is skipped. */
13544
- async listResolved() {
13545
- const page = await this.handle.query({ limit: INSTANCES_LIST_MAX });
13546
- const out = [];
13547
- for (const record of page.records) {
13548
- const read = await this.readResolved(record.id);
13549
- if (read !== null) out.push(read);
13550
- }
13551
- return out;
13552
- }
13553
- viewOf(record) {
13554
- const shown = secretViewsOf(this.records.owner, this.kind.name, record.id, this.kind.declaration, record.data);
13555
- const rawName = record.data[this.nameField];
13556
- const kind = this.hooks.kindOf?.(record.data);
13557
- const health = this.hooks.health?.(record.data, record.id);
13558
- return {
13559
- id: record.id,
13560
- name: typeof rawName === "string" ? rawName : record.id,
13561
- configured: this.hooks.configured(record.data),
13562
- ...this.registryOwnsEnabled ? {} : { enabled: record.data.enabled !== false },
13563
- formValues: shown,
13564
- ...kind !== void 0 ? { kind } : {},
13565
- ...health?.status !== void 0 ? { status: health.status } : {},
13566
- ...health?.lastCheckedAt !== void 0 ? { lastCheckedAt: health.lastCheckedAt } : {}
13567
- };
13568
- }
13569
- describe = async () => this.hooks.mintId === void 0 ? this.hooks.description : {
13570
- ...this.hooks.description,
13571
- mintsId: true
13572
- };
13573
- instanceFormSchema = async ({ id }) => this.hooks.formSchema(id);
13574
- listInstances = async () => {
13575
- return (await this.handle.query({ limit: INSTANCES_LIST_MAX })).records.map((record) => this.viewOf(record));
13576
- };
13577
- getInstance = async ({ id }) => {
13578
- const record = await this.handle.get(id);
13579
- return record === null ? null : this.viewOf(record);
13580
- };
13581
- /** Insert ONE row (`ifRev: 0`: an existing id is refused, never overwritten). */
13582
- createInstance = async ({ id, name, kind }) => {
13583
- const minted = id ?? this.hooks.mintId?.({
13584
- name,
13585
- ...kind !== void 0 ? { kind } : {}
13586
- });
13587
- if (minted === void 0) throw new Error("createInstance needs an id: this provider does not mint one");
13588
- await this.handle.put({
13589
- id: minted,
13590
- data: this.hooks.initialBody(name, kind)
13591
- }, { ifRev: 0 });
13592
- await this.hooks.onChanged?.(minted, "created");
13593
- return { id: minted };
13594
- };
13595
- updateInstance = async ({ id, name, values }) => {
13596
- const patch = {};
13597
- for (const [key, value] of Object.entries(values)) {
13598
- if (value === void 0) continue;
13599
- if (this.secretMaps.has(key)) {
13600
- const entries = secretMapPatch(value);
13601
- if (entries !== null) patch[key] = entries;
13602
- } else if (!this.secretKeys.has(key)) patch[key] = value;
13603
- else if (isSecretClear(value)) patch[key] = null;
13604
- else if (typeof value === "string" && value !== "" && value !== "__camstack_redacted__" && !isSecretFieldView(value)) patch[key] = value;
13605
- }
13606
- if (name !== void 0) patch[this.nameField] = name;
13607
- await this.handle.patch(id, patch);
13608
- await this.hooks.onChanged?.(id, "updated");
13609
- return { ok: true };
13610
- };
13611
- /** The switch lives in the record body; the addon is told so it applies it (D996). */
13612
- setInstanceEnabled = async ({ id, enabled }) => {
13613
- if (this.registryOwnsEnabled) throw new Error(`instance "${id}": the integrations registry owns the on/off switch of this addon; set it with integrations.update`);
13614
- await this.handle.patch(id, { enabled });
13615
- await this.hooks.onChanged?.(id, "enabled");
13616
- return { ok: true };
13617
- };
13618
- /** The row and its keychain refs go together (the records door). */
13619
- deleteInstance = async ({ id }) => {
13620
- await this.handle.delete(id);
13621
- await this.hooks.onChanged?.(id, "deleted");
13622
- return { ok: true };
13623
- };
13624
- testInstance = async (input) => {
13625
- if (this.hooks.test === void 0) return {
13626
- success: false,
13627
- status: "unsupported",
13628
- error: "This integration declares no connection test"
13629
- };
13630
- return this.hooks.test(input);
13631
- };
13632
- /** The flat provider object to hand to `registerProvider`. */
13633
- toProvider() {
13634
- return {
13635
- describe: this.describe,
13636
- instanceFormSchema: this.instanceFormSchema,
13637
- listInstances: this.listInstances,
13638
- getInstance: this.getInstance,
13639
- createInstance: this.createInstance,
13640
- updateInstance: this.updateInstance,
13641
- setInstanceEnabled: this.setInstanceEnabled,
13642
- deleteInstance: this.deleteInstance,
13643
- testInstance: this.testInstance
13644
- };
13645
- }
13646
- };
13647
14021
  var EncodeProfileSchema = object({
13648
14022
  video: object({
13649
14023
  codec: _enum([
@@ -15816,6 +16190,39 @@ var UnstampedEventMediaCountSchema = object({
15816
16190
  /** Sum across both, or `null` when either lane could not be counted. */
15817
16191
  total: number().int().nonnegative().nullable()
15818
16192
  }).nullable();
16193
+ /**
16194
+ * Where the stored event media sits, per storage location: how many media rows
16195
+ * and how many bytes carry each location id, how many carry none (legacy,
16196
+ * resolved to the default `eventMedia` location), and how many name a location
16197
+ * that was not asked about (a deleted or never-listed one).
16198
+ *
16199
+ * One covering-index aggregate per asked location plus the NULL one, and one
16200
+ * unfiltered total that scans the covering index: O(rows), not a walk of the
16201
+ * rows themselves. `unlisted` is total minus the ASKED locations minus NULL, so
16202
+ * it is a deleted location only when every location id was asked.
16203
+ * `null` is "could not be measured", never zero.
16204
+ */
16205
+ var MediaLocationCensusInputSchema = object({ locationIds: array(string().min(1)).max(50).readonly() });
16206
+ var MediaLocationCensusSchema = object({
16207
+ locations: array(object({
16208
+ locationId: string(),
16209
+ rows: number().int().nonnegative(),
16210
+ bytes: number().nonnegative()
16211
+ })).readonly(),
16212
+ unstamped: object({
16213
+ rows: number().int().nonnegative(),
16214
+ bytes: number().nonnegative()
16215
+ }),
16216
+ /** Rows stamped with a location id that was not in the asked list. */
16217
+ unlisted: object({
16218
+ rows: number().int().nonnegative(),
16219
+ bytes: number().nonnegative()
16220
+ }),
16221
+ total: object({
16222
+ rows: number().int().nonnegative(),
16223
+ bytes: number().nonnegative()
16224
+ })
16225
+ });
15819
16226
  var StorageMigrationMediaMoveInputSchema = RelocateMediaInputSchema.extend({ leaseId: string().min(1) });
15820
16227
  /** The independently selectable logical storage classes — every class
15821
16228
  * `storage.listLocationDeclarations` reports, so an operator never meets a
@@ -19802,31 +20209,21 @@ var APPLIANCE_CAP_VOCABULARY = {
19802
20209
  "pet-fountain": {
19803
20210
  scope: "device",
19804
20211
  noun: t("Pet fountain", "Fontana per animali"),
19805
- actions: [
19806
- {
19807
- id: "petFountain.pumpOn",
19808
- method: "setPump",
19809
- label: t("Pump on", "Pompa accesa"),
19810
- phrase: t("Start the pump of {device}", "Avvia la pompa di {device}"),
19811
- icon: "play",
19812
- args: { on: true }
19813
- },
19814
- {
19815
- id: "petFountain.pumpOff",
19816
- method: "setPump",
19817
- label: t("Pump off", "Pompa spenta"),
19818
- phrase: t("Stop the pump of {device}", "Ferma la pompa di {device}"),
19819
- icon: "square",
19820
- args: { on: false }
19821
- },
19822
- {
19823
- id: "petFountain.resetDailyConsumption",
19824
- method: "resetDailyConsumption",
19825
- label: t("Clear daily consumption", "Azzera il consumo giornaliero"),
19826
- phrase: t("Clear the daily water consumption of {device}", "Azzera il consumo giornaliero di acqua di {device}"),
19827
- icon: "rotate-ccw"
19828
- }
19829
- ],
20212
+ actions: [{
20213
+ id: "petFountain.pumpOn",
20214
+ method: "setPump",
20215
+ label: t("Pump on", "Pompa accesa"),
20216
+ phrase: t("Start the pump of {device}", "Avvia la pompa di {device}"),
20217
+ icon: "play",
20218
+ args: { on: true }
20219
+ }, {
20220
+ id: "petFountain.pumpOff",
20221
+ method: "setPump",
20222
+ label: t("Pump off", "Pompa spenta"),
20223
+ phrase: t("Stop the pump of {device}", "Ferma la pompa di {device}"),
20224
+ icon: "square",
20225
+ args: { on: false }
20226
+ }],
19830
20227
  state: [{
19831
20228
  kind: "boolean",
19832
20229
  field: "empty",
@@ -43720,8 +44117,15 @@ var ActionInputSchema = object({
43720
44117
  var ActionRunOriginSchema = object({
43721
44118
  /** The automation block whose step started it. */
43722
44119
  blockId: string().min(1).optional() });
43723
- /** `started` = the caller did not ask to wait. */
43724
- var ActionRunOutcomeSchema = union([AutomationRunOutcomeSchema, literal("started")]);
44120
+ /**
44121
+ * `started` = the caller did not ask to wait. `timed-out` = the run reached the
44122
+ * ceiling (`ACTION_RUN_MAX_MS`) and was stopped; it is never a `ran`.
44123
+ */
44124
+ var ActionRunOutcomeSchema = union([
44125
+ AutomationRunOutcomeSchema,
44126
+ literal("started"),
44127
+ literal("timed-out")
44128
+ ]);
43725
44129
  var ActionRunResultSchema = object({
43726
44130
  runId: string().min(1),
43727
44131
  outcome: ActionRunOutcomeSchema,
@@ -44205,7 +44609,7 @@ async function runExportedAction(api, log, input) {
44205
44609
  const result = await api.actions.run.mutate({ actionId });
44206
44610
  if (result.outcome === "skipped-overlap") return refuse("already-running", result.message);
44207
44611
  if (result.outcome === "skipped-cooldown") return refuse("cooldown", result.message);
44208
- if (result.outcome === "failed" || result.outcome === "aborted") {
44612
+ if (result.outcome === "failed" || result.outcome === "aborted" || result.outcome === "timed-out") {
44209
44613
  const message = result.message ?? result.outcome;
44210
44614
  log.warn(`${exporter}: exported action failed`, {
44211
44615
  tags,
@@ -44326,6 +44730,8 @@ method(object({}), array(ActionEntrySchema), { auth: "admin" }), method(object({
44326
44730
  kind: "mutation",
44327
44731
  auth: "admin"
44328
44732
  });
44733
+ /** `timeoutMs` of `actions.run`: a waited call outlives any legal run. */
44734
+ var ACTION_RUN_TIMEOUT_MS = 363e4;
44329
44735
  /**
44330
44736
  * actions — the ONE surface for runnable actions, for the UI and for
44331
44737
  * automations. Provided by the core-blocks builtin on the hub.
@@ -44344,6 +44750,12 @@ method(object({}), array(ActionEntrySchema), { auth: "admin" }), method(object({
44344
44750
  * An admin, and an in-process caller (an automation block), may run any action.
44345
44751
  * Every refusal is typed (`[not-linked] …`) and logged.
44346
44752
  *
44753
+ * **A run lasts at most `ACTION_RUN_MAX_MS` (60 min).** The provider stops a
44754
+ * run that reaches it and answers `timed-out` (never `ran`); an action whose
44755
+ * `wait` steps alone add up to more is refused at create/update
44756
+ * (`[invalid-steps]`). `run` declares a `timeoutMs` above that ceiling, so a
44757
+ * waited call (an automation step) is never cut by the 60 s transport default.
44758
+ *
44347
44759
  * A second `run` of an action that is already running is REFUSED — traced and
44348
44760
  * logged — never queued.
44349
44761
  */
@@ -44370,7 +44782,8 @@ method(object({}), array(ActionEntrySchema), { auth: "admin" }), method(object({
44370
44782
  role: "viewer",
44371
44783
  auth: "protected",
44372
44784
  kind: "mutation",
44373
- caller: "required"
44785
+ caller: "required",
44786
+ timeoutMs: ACTION_RUN_TIMEOUT_MS
44374
44787
  }), method(ActionIdInput, _void(), {
44375
44788
  kind: "mutation",
44376
44789
  auth: "admin"
@@ -46457,52 +46870,7 @@ DeviceType.Light, method(object({
46457
46870
  level: number().min(0).max(100),
46458
46871
  lastChangedAt: number()
46459
46872
  });
46460
- /**
46461
- * `broker` — unified pub/sub broker registry, system-scoped collection.
46462
- *
46463
- * The cap models any kind-tagged message broker the user wants to
46464
- * register and that other addons might consume. The first two kinds
46465
- * are MQTT (mosquitto / aedes embedded / cloud bridge) and
46466
- * Home Assistant (HA WebSocket — subscribe_entities + call_service).
46467
- * Future kinds (Zigbee2MQTT bridge, ZHA, KNX, Telegram, …) plug in
46468
- * the same surface.
46469
- *
46470
- * Why one cap, not one cap per kind:
46471
- * - The integrations page wants a single table of "every broker"
46472
- * across kinds; a unified cap drives it without join logic.
46473
- * - Generic admin operations (add / remove / test / status) are
46474
- * identical across kinds — duplicating them per cap was busywork.
46475
- * - The `network-access` cap precedent: same interface, many
46476
- * `providerKind: 'ingress'` implementations (Tailscale, ngrok, …).
46477
- *
46478
- * What stays kind-specific:
46479
- * - `getBrokerConfig` payload (kind decides whether it returns
46480
- * mqtt URL+creds, HA baseUrl+token, …) — typed as
46481
- * `Record<string, unknown>` at the wire; consumers narrow.
46482
- * - `publish` / `subscribe` / `getState` arguments (target / filter /
46483
- * key) — also typed as `Record<string, unknown>` so each kind can
46484
- * evolve its surface (MQTT topic+qos vs HA entity_id+domain)
46485
- * without rebreaking the cap signature.
46486
- * - `add` `settings` payload (different fields per kind, validated by
46487
- * the kind-specific provider).
46488
- *
46489
- * Bidirectionality:
46490
- * - `publish` is RPC — synchronous result (provider-defined).
46491
- * - `subscribe` returns a subscription handle; the actual message
46492
- * stream flows over the typed event-bus as `broker.message` events
46493
- * keyed by `(brokerId, subscriptionId)`. Consumers filter in their
46494
- * event handler. Subscriptions persist across reconnects — the
46495
- * provider re-subscribes upstream after a transport drop.
46496
- *
46497
- * Why event-bus push (not a subscription RPC stream):
46498
- * - Matches the rest of CamStack's D8 contract — events for telemetry,
46499
- * RPC for loss-is-a-bug. Broker messages are telemetry (a single
46500
- * drop is recoverable via `getState({key})`).
46501
- * - Frees `broker.subscribe` from holding a long-lived RPC channel.
46502
- * - Cross-process: events already route through `$event-bus`; no
46503
- * per-broker wire-shaping needed.
46504
- */
46505
- var BrokerStatusEnum = _enum([
46873
+ _enum([
46506
46874
  "connected",
46507
46875
  "disconnected",
46508
46876
  "connecting",
@@ -46510,141 +46878,12 @@ var BrokerStatusEnum = _enum([
46510
46878
  "unreachable",
46511
46879
  "error"
46512
46880
  ]);
46513
- var BrokerInfoSchema = object({
46514
- /** Stable broker id. Persisted; survives addon restarts. */
46515
- id: string(),
46516
- /** Addon id of the provider that OWNS this broker.
46517
- *
46518
- * The `broker` cap is a system-scoped collection: several addons
46519
- * register a `broker` provider, each owning a DISJOINT set of
46520
- * brokers (mqtt-broker owns `mqtt_*`, provider-homeassistant owns
46521
- * `ha_*`). A broker therefore belongs to exactly one addon — like a
46522
- * device belongs to one integration. The admin UI threads this id
46523
- * back as the `{ addonId }` system-collection selector on every
46524
- * id-keyed call (`get` / `getSettings` / `setSettings` / `remove` /
46525
- * `testConnection`), so the call routes to the OWNING provider
46526
- * instead of defaulting to the first-registered one. */
46527
- addonId: string(),
46528
- /** Human-readable name (operator-chosen at add-time). */
46529
- name: string(),
46530
- /** Provider-defined kind tag — `mqtt` / `home-assistant` / future. */
46531
- kind: string(),
46532
- status: BrokerStatusEnum,
46533
- /** Free-form provider-specific info (HA version, MQTT broker
46534
- * flavour, latency, mTLS active, …). */
46535
- info: record(string(), unknown()),
46536
- /** Ms epoch of the last connection probe / status update. */
46537
- lastCheckedAt: number().nullable(),
46538
- /** Last error message, when `status` indicates failure. */
46539
- error: string().nullable()
46540
- });
46541
46881
  var RegistryStatusSchema = object({
46542
46882
  brokerCount: number().int().nonnegative(),
46543
46883
  connectedCount: number().int().nonnegative()
46544
46884
  });
46545
- /**
46546
- * One entry per `broker` provider — which addon provides which broker
46547
- * kind(s). The unified create picker reads this to know, for each
46548
- * (addonId, kind) pair the operator can pick, where to route the
46549
- * follow-up `getSettingsSchema` / `testSettings` / `add` calls (via the
46550
- * `{ addonId }` selector). A provider only advertises a kind here when
46551
- * it implements `getSettingsSchema` for that kind (so the picker never
46552
- * offers a kind whose creation form can't be rendered).
46553
- */
46554
- var BrokerProviderInfoSchema = object({
46555
- /** Addon id of the `broker` provider this entry describes. */
46556
- addonId: string(),
46557
- /** Broker kinds this provider can create, with a display label. */
46558
- kinds: array(object({
46559
- kind: string(),
46560
- label: string(),
46561
- /**
46562
- * Relative hub path to start an interactive account link (OAuth popup).
46563
- * May include `{{brokerId}}`; admin-ui substitutes and appends `?popup=1`.
46564
- */
46565
- interactiveConnectPath: string().min(1).optional(),
46566
- /** Relative hub path to disconnect the linked account (same popup pattern). */
46567
- interactiveDisconnectPath: string().min(1).optional(),
46568
- /**
46569
- * The kind signs in through a server-held interactive session instead of
46570
- * (or before) typed credentials. `basePath` is a hub-relative route set
46571
- * served by the owning addon (`/addon/<id>/...`) speaking the sign-in
46572
- * contract: `POST {basePath}/start` (body: the form's settings) answers
46573
- * `{ sessionId, loginUrl }`; `GET {basePath}/status?sessionId=` answers
46574
- * `{ phase: 'starting' | 'awaiting-login' | 'captured' | 'error' |
46575
- * 'cancelled', loginUrl, error }`; `POST {basePath}/commit`
46576
- * (`{ sessionId, name, brokerId? }`) stores the credentials on a new or
46577
- * existing broker and answers `{ brokerId }`; `POST {basePath}/cancel`
46578
- * (`{ sessionId }`) drops the session. The dialog that edits a broker
46579
- * offers it as the default path; the fields the session fills are
46580
- * marked `filledBySignIn` in the kind's settings schema.
46581
- *
46582
- * `methods` lists the ways the session can sign in, recommended first:
46583
- * `'device-code'` adds `POST {basePath}/code/start` (body: the form's
46584
- * settings) answering `{ sessionId, userCode, verificationUrl,
46585
- * expiresAt }` — the operator types `userCode` at `verificationUrl` on
46586
- * any device, and the same `status` / `commit` / `cancel` routes follow
46587
- * (status then carries `method`, `userCode`, `verificationUrl`,
46588
- * `expiresAt` and the phases `'awaiting-code'` / `'expired'`);
46589
- * `'proxy'` is the `{basePath}/start` flow above. Absent means
46590
- * `['proxy']`.
46591
- */
46592
- signIn: object({
46593
- basePath: string().min(1),
46594
- methods: array(_enum(["device-code", "proxy"])).optional()
46595
- }).optional()
46596
- }))
46597
- });
46598
- var ListInputSchema = object({
46599
- /** Optional kind filter — `list({kind:'home-assistant'})` returns
46600
- * only HA brokers. Omit to list every broker. */
46601
- kind: string().optional() });
46602
46885
  var GetInputSchema = object({ id: string() });
46603
- var AddInputSchema = object({
46604
- kind: string().min(1),
46605
- name: string().min(1),
46606
- /**
46607
- * ADOPT an existing id instead of minting a new one.
46608
- *
46609
- * Written the day this cost an outage. A broker's id is not a detail: HA
46610
- * devices carry it inside their `stableId` (`ha:ha_004:dev:…`), so a broker
46611
- * lost from config and re-added as `ha_001` leaves every one of its devices
46612
- * bound to a broker that no longer exists. Re-entering the password under the
46613
- * ORIGINAL id turns a multi-step device migration back into re-entering a
46614
- * password.
46615
- *
46616
- * A provider MUST refuse an id that is already in use — adopting a live
46617
- * broker's id would silently take it over.
46618
- */
46619
- id: string().min(1).optional(),
46620
- /** Kind-specific settings (e.g. MQTT `{url,username,password}` or HA
46621
- * `{baseUrl,accessToken}`). Validated by the kind-specific provider
46622
- * branch on receipt — invalid shape rejects the add. */
46623
- settings: record(string(), unknown())
46624
- });
46625
- var AddResultSchema = object({ id: string() });
46626
- var RemoveInputSchema = object({ id: string() });
46627
- var TestConnectionResultSchema = discriminatedUnion("ok", [object({
46628
- ok: literal(true),
46629
- latencyMs: number().nonnegative()
46630
- }), object({
46631
- ok: literal(false),
46632
- error: string()
46633
- })]);
46634
46886
  var SettingsRecordSchema$1 = record(string(), unknown());
46635
- var SettingsSchemaInputSchema = object({ kind: string() });
46636
- var TestSettingsInputSchema = object({
46637
- kind: string(),
46638
- settings: SettingsRecordSchema$1
46639
- });
46640
- var TestSettingsResultSchema = discriminatedUnion("ok", [object({
46641
- ok: literal(true),
46642
- latencyMs: number().nonnegative().optional()
46643
- }).strict(), object({
46644
- ok: literal(false),
46645
- error: string()
46646
- })]);
46647
- var SettingsSchemaResultSchema = unknown().nullable();
46648
46887
  var PublishInputSchema = object({
46649
46888
  brokerId: string(),
46650
46889
  /** Kind-specific routing target.
@@ -46678,25 +46917,7 @@ var GetStateInputSchema = object({
46678
46917
  * HA: entity_id (returns the cached entity state). */
46679
46918
  key: string()
46680
46919
  });
46681
- method(ListInputSchema, array(BrokerInfoSchema)), method(GetInputSchema, BrokerInfoSchema.nullable()), method(_void(), array(BrokerProviderInfoSchema), { auth: "admin" }), method(AddInputSchema, AddResultSchema, {
46682
- kind: "mutation",
46683
- auth: "admin"
46684
- }), method(RemoveInputSchema, _void(), {
46685
- kind: "mutation",
46686
- auth: "admin"
46687
- }), method(GetInputSchema, TestConnectionResultSchema, {
46688
- kind: "mutation",
46689
- auth: "admin"
46690
- }), method(GetInputSchema, SettingsRecordSchema$1.nullable(), { auth: "admin" }), method(object({
46691
- id: string(),
46692
- settings: SettingsRecordSchema$1
46693
- }), _void(), {
46694
- kind: "mutation",
46695
- auth: "admin"
46696
- }), method(GetInputSchema, SettingsRecordSchema$1.nullable(), { auth: "admin" }), method(SettingsSchemaInputSchema, SettingsSchemaResultSchema, { auth: "admin" }), method(TestSettingsInputSchema, TestSettingsResultSchema, {
46697
- kind: "mutation",
46698
- auth: "admin"
46699
- }), method(PublishInputSchema, unknown(), {
46920
+ method(GetInputSchema, SettingsRecordSchema$1.nullable(), { auth: "admin" }), method(PublishInputSchema, unknown(), {
46700
46921
  kind: "mutation",
46701
46922
  auth: "admin"
46702
46923
  }), method(SubscribeInputSchema, SubscribeResultSchema, {
@@ -48610,6 +48831,9 @@ var MediaPlayerStatusSchema = object({
48610
48831
  /** Repeat mode. Null when no repeat surface.
48611
48832
  * Pair with `DeviceFeature.MediaPlayerRepeat`. */
48612
48833
  repeat: MediaPlayerRepeatSchema.nullable(),
48834
+ /** Ms epoch when `position` was read from the device. Null when the driver
48835
+ * does not say; a UI that advances the position while playing counts from it. */
48836
+ positionUpdatedAt: number().nullable().default(null),
48613
48837
  /** Ms epoch when the slice was last updated. */
48614
48838
  lastChangedAt: number()
48615
48839
  });
@@ -49189,7 +49413,9 @@ var ThresholdTransformDraftSchema = object({
49189
49413
  comparison: _enum(["gte", "lte"]),
49190
49414
  threshold: number(),
49191
49415
  startDwellMs: number().nonnegative(),
49192
- stopDwellMs: number().nonnegative()
49416
+ stopDwellMs: number().nonnegative(),
49417
+ /** Samples a start needs; absent = the compiler's default for the source (2 for running power, else 1). */
49418
+ minSamples: number().int().min(1).optional()
49193
49419
  });
49194
49420
  var CustomizeTransformDraftSchema = discriminatedUnion("kind", [
49195
49421
  IdentityTransformDraftSchema,
@@ -50805,7 +51031,14 @@ var DiscoveryCandidateSchema = object({
50805
51031
  /** `stableId` of the gateway candidate this device was found BEHIND. */
50806
51032
  parentStableId: string().optional(),
50807
51033
  /** `false` = shown for context but not pickable. Default true. */
50808
- selectable: boolean().optional()
51034
+ selectable: boolean().optional(),
51035
+ /**
51036
+ * Keys of the provider's creation form (`getChildCreationSchema`) this candidate
51037
+ * cannot be adopted without — a key for an encrypted board, a pairing code. The
51038
+ * admin asks for exactly these, on the creation form prefilled with
51039
+ * `prefilledConfig`, before it adopts. Absent or empty = adopt as it is.
51040
+ */
51041
+ needsParams: array(string()).optional()
50809
51042
  });
50810
51043
  /**
50811
51044
  * Flat device summary returned by `createDevice` / `adoptDiscoveredDevice`.
@@ -50864,12 +51097,24 @@ method(_void(), _void(), { kind: "mutation" }), method(_void(), _void(), { kind:
50864
51097
  }), array(DiscoveryCandidateSchema), {
50865
51098
  kind: "mutation",
50866
51099
  auth: "admin"
50867
- }), method(object({}), CreationSchemaOutputSchema), method(object({}), object({ deviceType: _enum(DeviceType).nullable() })), method(object({ candidate: DiscoveryCandidateSchema }), DeviceSummarySchema, {
51100
+ }), method(object({}), CreationSchemaOutputSchema), method(object({
51101
+ /** The integration asked about; a provider whose integrations differ answers per one. */
51102
+ integrationId: string().optional() }), object({ deviceType: _enum(DeviceType).nullable() })), method(object({
51103
+ candidate: DiscoveryCandidateSchema,
51104
+ /** The integration the operator adopts into; a provider with several instances needs it. */
51105
+ integrationId: string().optional()
51106
+ }), DeviceSummarySchema, {
50868
51107
  kind: "mutation",
50869
51108
  auth: "admin"
50870
- }), method(object({}), boolean()), method(object({ type: _enum(DeviceType) }), CreationSchemaOutputSchema), method(object({
51109
+ }), method(object({}), boolean()), method(object({
50871
51110
  type: _enum(DeviceType),
50872
- config: record(string(), unknown())
51111
+ /** The integration asked about; a provider whose integrations differ answers per one. */
51112
+ integrationId: string().optional()
51113
+ }), CreationSchemaOutputSchema), method(object({
51114
+ type: _enum(DeviceType),
51115
+ config: record(string(), unknown()),
51116
+ /** The integration the operator adds the device to; a provider with several instances needs it. */
51117
+ integrationId: string().optional()
50873
51118
  }), DeviceSummarySchema, {
50874
51119
  kind: "mutation",
50875
51120
  auth: "admin"
@@ -51579,7 +51824,10 @@ method(object({
51579
51824
  auth: "admin"
51580
51825
  }), method(object({
51581
51826
  addonId: string(),
51582
- type: _enum(DeviceType)
51827
+ type: _enum(DeviceType),
51828
+ /** The integration the form is for; a provider whose integrations differ (a hub
51829
+ * integration takes no manual add) answers per integration. Absent = the addon's own. */
51830
+ integrationId: string().optional()
51583
51831
  }), unknown().nullable()), method(object({
51584
51832
  addonId: string(),
51585
51833
  type: _enum(DeviceType),
@@ -51663,7 +51911,11 @@ method(object({
51663
51911
  kind: "mutation",
51664
51912
  auth: "admin",
51665
51913
  timeoutMs: 12e4
51666
- }), method(object({ addonId: string() }), object({ deviceType: _enum(DeviceType).nullable() }), { auth: "admin" }), method(object({ addonId: string() }), unknown(), { auth: "admin" }), method(object({
51914
+ }), method(object({
51915
+ addonId: string(),
51916
+ /** The integration the Add-Device dialog is open on; absent = the addon's own. */
51917
+ integrationId: string().optional()
51918
+ }), object({ deviceType: _enum(DeviceType).nullable() }), { auth: "admin" }), method(object({ addonId: string() }), unknown(), { auth: "admin" }), method(object({
51667
51919
  deviceId: number(),
51668
51920
  key: string(),
51669
51921
  value: unknown()
@@ -54165,6 +54417,7 @@ var IntegrationWithStateSchema = object({
54165
54417
  id: string(),
54166
54418
  addonId: string(),
54167
54419
  name: string(),
54420
+ /** A projection of the instance body's switch (`setInstanceEnabled` is the only writer). */
54168
54421
  enabled: boolean(),
54169
54422
  info: record(string(), unknown()).readonly(),
54170
54423
  /** The discovery candidate this integration was set up from (D984). */
@@ -54177,6 +54430,7 @@ var IntegrationLiteSchema = object({
54177
54430
  id: string(),
54178
54431
  addonId: string(),
54179
54432
  name: string(),
54433
+ /** A projection of the instance body's switch (`setInstanceEnabled` is the only writer). */
54180
54434
  enabled: boolean(),
54181
54435
  info: record(string(), unknown()).readonly(),
54182
54436
  /** The discovery candidate this integration was set up from (D984). */
@@ -54259,7 +54513,7 @@ var TestConnectionStatusEnum = _enum([
54259
54513
  "inconclusive",
54260
54514
  "unsupported"
54261
54515
  ]);
54262
- var TestConnectionResultSchema$1 = object({
54516
+ var TestConnectionResultSchema = object({
54263
54517
  /** True ONLY for `validated`. Never true for a test that did not run. */
54264
54518
  success: boolean(),
54265
54519
  error: string().optional(),
@@ -54276,7 +54530,6 @@ var TestConnectionResultSchema$1 = object({
54276
54530
  var CreateIntegrationInputSchema = object({
54277
54531
  addonId: string(),
54278
54532
  name: string(),
54279
- enabled: boolean().optional(),
54280
54533
  info: record(string(), unknown()).optional(),
54281
54534
  /** `stableId` of the discovery candidate the form was seeded from (D984). */
54282
54535
  originStableId: string().optional(),
@@ -54285,6 +54538,11 @@ var CreateIntegrationInputSchema = object({
54285
54538
  var UpdateIntegrationInputSchema = object({
54286
54539
  id: string(),
54287
54540
  name: string().optional(),
54541
+ /**
54542
+ * Accepted for a FIXED builtin only (`info.fixed`: alarm panel, camera grid, core blocks,
54543
+ * terminal), which keeps no instance record: the registry flag is its one store. Any other
54544
+ * integration is switched through `integration-instances.setInstanceEnabled`.
54545
+ */
54288
54546
  enabled: boolean().optional(),
54289
54547
  info: record(string(), unknown()).optional()
54290
54548
  });
@@ -54304,7 +54562,7 @@ method(_void(), array(IntegrationWithStateSchema)), method(object({ id: string()
54304
54562
  }), method(_void(), array(AvailableIntegrationTypeSchema), { auth: "admin" }), method(object({
54305
54563
  addonId: string(),
54306
54564
  settings: record(string(), unknown())
54307
- }), TestConnectionResultSchema$1, {
54565
+ }), TestConnectionResultSchema, {
54308
54566
  kind: "mutation",
54309
54567
  auth: "admin"
54310
54568
  });
@@ -54331,6 +54589,14 @@ var ConfigSchemaPassthrough$3 = custom();
54331
54589
  var IntegrationInstanceIdSchema = string().min(1);
54332
54590
  var IntegrationInstanceModeSchema = _enum(["single", "multiple"]);
54333
54591
  /**
54592
+ * What the addon's instances ARE for the Integrations page (planning#416). `devices`: each
54593
+ * instance is an integration that brings devices (its record body owns the on/off switch);
54594
+ * `services`: a connection configured from the addon's own function page, never listed on
54595
+ * Integrations.
54596
+ * It is the same vocabulary as the manifest's `integrationRole`, which stays as an override.
54597
+ */
54598
+ var IntegrationInstanceRoleSchema = _enum(["devices", "services"]);
54599
+ /**
54334
54600
  * One kind of instance a provider can create (an adapter, an account type). The sign-in and
54335
54601
  * connect fields follow the `broker` contract (`broker.cap.ts`): `signIn.basePath` is a
54336
54602
  * hub-relative route set speaking the sign-in contract, `connectPath` / `disconnectPath` open an
@@ -54341,6 +54607,22 @@ var IntegrationInstanceKindSchema = object({
54341
54607
  /** Stable id of the kind, sent back as `createInstance.kind`. */
54342
54608
  id: string().min(1),
54343
54609
  label: string().min(1),
54610
+ /**
54611
+ * The function capability this kind is configured for (`broker`, `smtp-provider`,
54612
+ * `device-provider`, ...). A page section is the kinds whose `functionCap` it names (D1013); a
54613
+ * provider with more than one section must name it on every kind.
54614
+ */
54615
+ functionCap: string().min(1),
54616
+ /**
54617
+ * For `functionCap: 'broker'`: the registry kind of the broker an instance of this kind is
54618
+ * (`matter`, `home-assistant`, ...). A caller that needs a broker of one kind (a link field)
54619
+ * finds the instances whose kind names it; absent takes the kind `id`.
54620
+ */
54621
+ brokerKind: string().min(1).optional(),
54622
+ /** What instances of this kind are for the Integrations page; absent takes the provider's `role`. */
54623
+ role: IntegrationInstanceRoleSchema.optional(),
54624
+ /** `testInstance` really probes the remote for this kind; absent takes the provider's `canTest`. */
54625
+ canTest: boolean().optional(),
54344
54626
  /** The kind signs in through a server-held interactive session. */
54345
54627
  signIn: object({
54346
54628
  basePath: string().min(1),
@@ -54351,22 +54633,38 @@ var IntegrationInstanceKindSchema = object({
54351
54633
  /** Relative hub path to disconnect that account. */
54352
54634
  disconnectPath: string().min(1).optional()
54353
54635
  });
54636
+ /**
54637
+ * How devices of an instance are found. `none`: the operator adds them by hand; `lan`: the addon
54638
+ * scans the network before any instance exists (the wizard offers the candidates); `account`: the
54639
+ * devices appear after the instance signs in. `scopedToInstance`: a discovery run belongs to ONE
54640
+ * instance and its candidates are claimed by it.
54641
+ */
54642
+ var IntegrationInstanceDiscoverySchema = object({
54643
+ mode: _enum([
54644
+ "none",
54645
+ "lan",
54646
+ "account"
54647
+ ]),
54648
+ scopedToInstance: boolean()
54649
+ });
54650
+ /**
54651
+ * One link a kind of this provider declares (D1013 rule 5): the body `field` of an instance of
54652
+ * `kind` holds the id of an instance of the function cap `to.cap` (of kind `to.kind`, when set).
54653
+ * The hub indexes these so the target's delete is refused while a link names it.
54654
+ */
54655
+ var IntegrationInstanceLinkSchema = object({
54656
+ kind: string().min(1),
54657
+ field: string().min(1),
54658
+ to: object({
54659
+ cap: string().min(1),
54660
+ kind: string().min(1).optional()
54661
+ })
54662
+ });
54354
54663
  var IntegrationInstanceDescriptionSchema = object({
54355
54664
  /** What the instances are for the Integrations page; see {@link IntegrationInstanceRoleSchema}. */
54356
- role: _enum([
54357
- "devices",
54358
- "services",
54359
- "both"
54360
- ]),
54665
+ role: IntegrationInstanceRoleSchema,
54361
54666
  /** How the devices of an instance are found; absent means `{ mode: 'none' }`. */
54362
- discovery: object({
54363
- mode: _enum([
54364
- "none",
54365
- "lan",
54366
- "account"
54367
- ]),
54368
- scopedToInstance: boolean()
54369
- }).optional(),
54667
+ discovery: IntegrationInstanceDiscoverySchema.optional(),
54370
54668
  /** `single`: at most one instance can exist (Loki). `multiple`: an account each. */
54371
54669
  instanceMode: IntegrationInstanceModeSchema,
54372
54670
  /** What the instance is, for the UI (`destination`, `relay`, `account`). */
@@ -54387,7 +54685,9 @@ var IntegrationInstanceDescriptionSchema = object({
54387
54685
  * `createInstance` without an `id` works: the provider mints it. Absent means the caller must
54388
54686
  * send an id (the UI then mints an opaque one).
54389
54687
  */
54390
- mintsId: boolean().optional()
54688
+ mintsId: boolean().optional(),
54689
+ /** The links to other instances the provider's kinds declare; absent means none. */
54690
+ links: array(IntegrationInstanceLinkSchema).optional()
54391
54691
  });
54392
54692
  var IntegrationInstanceStatusSchema = object({
54393
54693
  state: _enum([
@@ -54407,8 +54707,8 @@ var IntegrationInstanceSchema = object({
54407
54707
  configured: boolean(),
54408
54708
  /**
54409
54709
  * The instance's own on/off switch (D996), derived from the record body (`enabled !== false`,
54410
- * so a row written before the field existed is on). Absent when the `integrations` registry
54411
- * owns the switch (`describe().role` is `devices`): read it from the registry row.
54710
+ * so a row written before the field existed is on). The same for every role, `devices` included:
54711
+ * the body is the one store, `setInstanceEnabled` the one writer (epic #440, step 3).
54412
54712
  */
54413
54713
  enabled: boolean().optional(),
54414
54714
  /** The kind of this instance (one of `describe().kinds[].id`), when the provider has kinds. */
@@ -54432,7 +54732,11 @@ var integrationInstancesCapability = {
54432
54732
  methods: {
54433
54733
  describe: method(_void(), IntegrationInstanceDescriptionSchema, { auth: "admin" }),
54434
54734
  /** The form; `id: null` is the create form. */
54435
- instanceFormSchema: method(object({ id: IntegrationInstanceIdSchema.nullable() }), ConfigSchemaPassthrough$3, { auth: "admin" }),
54735
+ instanceFormSchema: method(object({
54736
+ id: IntegrationInstanceIdSchema.nullable(),
54737
+ /** The kind of the create form (`id: null`) of a provider with several. */
54738
+ kind: string().min(1).optional()
54739
+ }), ConfigSchemaPassthrough$3, { auth: "admin" }),
54436
54740
  listInstances: method(_void(), array(IntegrationInstanceSchema).readonly(), { auth: "admin" }),
54437
54741
  getInstance: method(object({ id: IntegrationInstanceIdSchema }), IntegrationInstanceSchema.nullable(), { auth: "admin" }),
54438
54742
  /**
@@ -54442,7 +54746,9 @@ var integrationInstancesCapability = {
54442
54746
  createInstance: method(object({
54443
54747
  id: IntegrationInstanceIdSchema.optional(),
54444
54748
  name: string().min(1),
54445
- kind: string().min(1).optional()
54749
+ kind: string().min(1).optional(),
54750
+ /** Form values written with the record (a link picked in the create dialog). */
54751
+ values: record(string(), unknown()).optional()
54446
54752
  }), object({ id: string() }), {
54447
54753
  kind: "mutation",
54448
54754
  auth: "admin"
@@ -54452,7 +54758,8 @@ var integrationInstancesCapability = {
54452
54758
  auth: "admin"
54453
54759
  }),
54454
54760
  /**
54455
- * Switch ONE instance on or off. A row control, not a form field: `updateInstance.values` is the
54761
+ * Switch ONE instance on or off, for every role; a missing record is created from the addon's
54762
+ * initial body. A row control, not a form field: `updateInstance.values` is the
54456
54763
  * form patch (D62, D996). An off instance keeps its record and secrets and does no work.
54457
54764
  */
54458
54765
  setInstanceEnabled: method(object({
@@ -54469,8 +54776,10 @@ var integrationInstancesCapability = {
54469
54776
  }),
54470
54777
  testInstance: optionalMethod(object({
54471
54778
  id: IntegrationInstanceIdSchema.nullable(),
54472
- values: record(string(), unknown())
54473
- }), TestConnectionResultSchema$1, {
54779
+ values: record(string(), unknown()),
54780
+ /** The kind to test when `id` is null and the provider has several. */
54781
+ kind: string().min(1).optional()
54782
+ }), TestConnectionResultSchema, {
54474
54783
  kind: "mutation",
54475
54784
  auth: "admin"
54476
54785
  })
@@ -56975,6 +57284,382 @@ var SystemMetricsSchema = object({
56975
57284
  gpuMemoryPercent: number().optional()
56976
57285
  });
56977
57286
  method(_void(), SystemResourceSnapshotSchema), method(_void(), SystemResourceSnapshotSchema.nullable()), method(_void(), SystemMetricsSchema), method(object({ dirPath: string() }), DiskSpaceInfoSchema), method(_void(), MetricsGpuInfoSchema.nullable()), method(_void(), number().nullable()), method(object({ pids: array(number()) }), array(PidResourceStatsSchema)), method(_void(), array(AddonInstanceSchema).readonly()), method(object({ addonId: string() }), PidResourceStatsSchema.nullable()), method(_void(), array(NodeProcessSchema).readonly()), method(GetLoadSeriesInputSchema, NodeLoadSeriesSchema);
57287
+ /**
57288
+ * records - an addon's own facts and documents (D881): ledgers, audit rows,
57289
+ * config documents, mirrors. The third storage API next to `ctx.settings`
57290
+ * (operator intent, D870) and device-history (numbers over time, D850).
57291
+ *
57292
+ * Who the OWNER is: `callerAddonId`, stamped by the transport on a call that
57293
+ * crossed a process and stated by a hub in-process caller (`ctx.records` does
57294
+ * that with the addon id closed over). It is deliberately NOT in any input
57295
+ * schema, so a session can never supply it, and a call with no stamp is refused
57296
+ * `records/no-caller`. A kind is readable and writable only by its owner; other
57297
+ * addons go through the owner's capability.
57298
+ *
57299
+ * Every read is three-way: a row, `null`, or the call THROWS. A failed read is
57300
+ * never `[]`. Secret fields are never on the wire: a read shows the
57301
+ * redaction token, `secretRefs` hands the owner's `ctx.secrets` the refs it
57302
+ * resolves itself, and a write may carry only a keychain marker bound to the
57303
+ * row's own ref.
57304
+ *
57305
+ * Internal: addons reach it through `ctx.records`, never directly.
57306
+ */
57307
+ var RecordIdSchema = string().min(1).max(256);
57308
+ /** A JSON object body. Size is the engine's check (`maxDataBytes`), not a schema's. */
57309
+ var RecordBodySchema = record(string(), unknown());
57310
+ var RecordInputSchema = object({
57311
+ id: RecordIdSchema,
57312
+ /** The device this row belongs to (D865 removal, per-device reads). */
57313
+ deviceId: number().int().optional(),
57314
+ /** The domain clock, ms: observed / created / opened. */
57315
+ at: number().int().optional(),
57316
+ /** Producer-set expiry, ms. Refused on a kind whose retention is an engine TTL. */
57317
+ expiresAt: number().int().optional(),
57318
+ data: RecordBodySchema
57319
+ });
57320
+ var RecordViewSchema = object({
57321
+ id: string(),
57322
+ deviceId: number().int().nullable(),
57323
+ at: number().nullable(),
57324
+ expiresAt: number().nullable(),
57325
+ rev: number().int(),
57326
+ updatedAt: number(),
57327
+ data: RecordBodySchema
57328
+ });
57329
+ /** Declared index fields only. Anything else does not compile, by design. */
57330
+ var RecordWhereSchema = record(RecordFieldPathSchema, union([
57331
+ string(),
57332
+ number(),
57333
+ boolean(),
57334
+ object({ in: array(union([
57335
+ string(),
57336
+ number(),
57337
+ boolean()
57338
+ ])).min(1).max(RECORD_BATCH_MAX) }),
57339
+ object({
57340
+ gt: union([string(), number()]).optional(),
57341
+ gte: union([string(), number()]).optional(),
57342
+ lt: union([string(), number()]).optional(),
57343
+ lte: union([string(), number()]).optional()
57344
+ }).refine((r) => Object.keys(r).length > 0, { message: "name at least one bound" })
57345
+ ]));
57346
+ var KindShape = { kind: RecordKindNameSchema };
57347
+ var TimeWindowShape = {
57348
+ deviceId: number().int().optional(),
57349
+ atFrom: number().optional(),
57350
+ atTo: number().optional()
57351
+ };
57352
+ var RecordQueryInputSchema = object({
57353
+ ...KindShape,
57354
+ ...TimeWindowShape,
57355
+ where: RecordWhereSchema.optional(),
57356
+ /** Without `where`: `at` (default for a kind with a clock) or `id`. With `where` the order is the index's. */
57357
+ order: _enum(["at", "id"]).optional(),
57358
+ desc: boolean().optional(),
57359
+ limit: number().int().min(1).max(RECORD_QUERY_MAX).default(100),
57360
+ /** Opaque keyset cursor from a previous answer. There is no offset. */
57361
+ cursor: string().min(1).optional()
57362
+ });
57363
+ var RecordQueryResultSchema = object({
57364
+ records: array(RecordViewSchema),
57365
+ nextCursor: string().nullable()
57366
+ });
57367
+ var RecordKindStateSchema = _enum([
57368
+ "created",
57369
+ "unchanged",
57370
+ "updated"
57371
+ ]);
57372
+ var DeclareKindResultSchema = object({
57373
+ kindId: number().int(),
57374
+ state: RecordKindStateSchema,
57375
+ createdIndexes: array(string())
57376
+ });
57377
+ /** Keychain refs a write released (the old marker is gone from the row): the owner deletes the values. */
57378
+ var SecretRefsList = array(string());
57379
+ /**
57380
+ * One op of a `transact`: the single-row writes, each on a kind of the caller.
57381
+ * All ops of one call share ONE database file and ONE `transactFamily`.
57382
+ */
57383
+ var RecordTransactOpSchema = discriminatedUnion("op", [
57384
+ object({
57385
+ op: literal("put"),
57386
+ kind: RecordKindNameSchema,
57387
+ record: RecordInputSchema,
57388
+ ifRev: number().int().min(0).optional()
57389
+ }),
57390
+ object({
57391
+ op: literal("patch"),
57392
+ kind: RecordKindNameSchema,
57393
+ id: RecordIdSchema,
57394
+ data: RecordBodySchema,
57395
+ at: number().int().nullable().optional(),
57396
+ expiresAt: number().int().nullable().optional(),
57397
+ ifRev: number().int().min(1).optional()
57398
+ }),
57399
+ object({
57400
+ op: literal("delete"),
57401
+ kind: RecordKindNameSchema,
57402
+ id: RecordIdSchema
57403
+ })
57404
+ ]);
57405
+ var RecordSecretRefsSchema = record(string(), record(string(), string()));
57406
+ method(object({ kinds: record(RecordKindNameSchema, RecordKindDeclarationSchema) }), object({ kinds: record(string(), DeclareKindResultSchema) }), {
57407
+ kind: "mutation",
57408
+ auth: "admin"
57409
+ }), method(object({
57410
+ ...KindShape,
57411
+ id: RecordIdSchema
57412
+ }), RecordViewSchema.nullable(), { auth: "admin" }), method(object({
57413
+ ...KindShape,
57414
+ ids: array(RecordIdSchema).min(1).max(RECORD_BATCH_MAX)
57415
+ }), array(RecordViewSchema), { auth: "admin" }), method(object({
57416
+ ...KindShape,
57417
+ ids: array(RecordIdSchema).min(1).max(RECORD_BATCH_MAX)
57418
+ }), RecordSecretRefsSchema, { auth: "admin" }), method(object({
57419
+ ...KindShape,
57420
+ record: RecordInputSchema,
57421
+ /** Compare-and-set. `0` means "the row must not exist". */
57422
+ ifRev: number().int().min(0).optional()
57423
+ }), object({
57424
+ rev: number().int(),
57425
+ releasedRefs: SecretRefsList
57426
+ }), {
57427
+ kind: "mutation",
57428
+ auth: "admin"
57429
+ }), method(object({
57430
+ ...KindShape,
57431
+ records: array(RecordInputSchema).min(1).max(RECORD_BATCH_MAX)
57432
+ }), object({
57433
+ count: number().int(),
57434
+ releasedRefs: SecretRefsList
57435
+ }), {
57436
+ kind: "mutation",
57437
+ auth: "admin"
57438
+ }), method(object({
57439
+ ...KindShape,
57440
+ id: RecordIdSchema,
57441
+ data: RecordBodySchema,
57442
+ at: number().int().nullable().optional(),
57443
+ expiresAt: number().int().nullable().optional(),
57444
+ ifRev: number().int().min(1).optional()
57445
+ }), object({
57446
+ rev: number().int(),
57447
+ releasedRefs: SecretRefsList
57448
+ }), {
57449
+ kind: "mutation",
57450
+ auth: "admin"
57451
+ }), method(object({
57452
+ ...KindShape,
57453
+ id: RecordIdSchema
57454
+ }), object({
57455
+ deleted: boolean(),
57456
+ secretRefs: SecretRefsList
57457
+ }), {
57458
+ kind: "mutation",
57459
+ auth: "admin"
57460
+ }), method(object({
57461
+ ...KindShape,
57462
+ ids: array(RecordIdSchema).min(1).max(RECORD_BATCH_MAX)
57463
+ }), object({
57464
+ deleted: number().int(),
57465
+ secretRefs: SecretRefsList
57466
+ }), {
57467
+ kind: "mutation",
57468
+ auth: "admin"
57469
+ }), method(RecordQueryInputSchema, RecordQueryResultSchema, { auth: "admin" }), method(object({
57470
+ ...KindShape,
57471
+ ...TimeWindowShape,
57472
+ where: RecordWhereSchema.optional()
57473
+ }), object({ count: number().int() }), { auth: "admin" }), method(object({
57474
+ ...KindShape,
57475
+ deviceId: number().int().optional(),
57476
+ from: number(),
57477
+ to: number(),
57478
+ bucketMs: number().int().positive()
57479
+ }), object({ buckets: array(object({
57480
+ bucketStart: number(),
57481
+ count: number().int()
57482
+ })) }), { auth: "admin" }), method(object({
57483
+ ...KindShape,
57484
+ op: _enum([
57485
+ "sum",
57486
+ "min",
57487
+ "max",
57488
+ "count"
57489
+ ]),
57490
+ field: RecordFieldPathSchema.optional(),
57491
+ groupBy: RecordFieldPathSchema.optional(),
57492
+ where: RecordWhereSchema.optional()
57493
+ }), object({ rows: array(object({
57494
+ group: union([
57495
+ string(),
57496
+ number(),
57497
+ _null()
57498
+ ]),
57499
+ value: number().nullable()
57500
+ })) }), { auth: "admin" }), method(object({
57501
+ ...KindShape,
57502
+ deviceId: number().int().optional(),
57503
+ atBefore: number().optional(),
57504
+ where: RecordWhereSchema.optional()
57505
+ }), object({
57506
+ deleted: number().int(),
57507
+ secretRefs: SecretRefsList
57508
+ }), {
57509
+ kind: "mutation",
57510
+ auth: "admin"
57511
+ }), method(object({ ops: array(RecordTransactOpSchema).min(1).max(RECORD_BATCH_MAX) }), object({
57512
+ results: array(object({
57513
+ rev: number().int().nullable(),
57514
+ deleted: boolean()
57515
+ })),
57516
+ releasedRefs: SecretRefsList,
57517
+ secretRefs: SecretRefsList
57518
+ }), {
57519
+ kind: "mutation",
57520
+ auth: "admin"
57521
+ }), method(object({
57522
+ deviceId: number().int(),
57523
+ kinds: array(RecordKindNameSchema).optional()
57524
+ }), object({
57525
+ deleted: record(string(), number().int()),
57526
+ secretRefs: SecretRefsList
57527
+ }), {
57528
+ kind: "mutation",
57529
+ auth: "admin"
57530
+ }), method(object(KindShape), object({ id: number().int() }), {
57531
+ kind: "mutation",
57532
+ auth: "admin"
57533
+ });
57534
+ /**
57535
+ * The wire shapes of the migration API, version 1 (planning#447).
57536
+ *
57537
+ * A migration is code that outlives the server it was written against: an addon at
57538
+ * version 1.4 that is brought to 1.9 in one jump still runs its 1.4 catalogue, against
57539
+ * the 1.9 kernel. The only thing that code may call is {@link MigrationApiV1}; this file
57540
+ * is the contract of every method of it, one Zod pair per method.
57541
+ *
57542
+ * APPEND-ONLY. A released method is never removed and never changes meaning: an input
57543
+ * field is never removed or made required, an enum never narrows, an output field is
57544
+ * never removed. A change that cannot be expressed that way is `migration-api.v2`, next
57545
+ * to this file. `scripts/check-migration-api-append-only.ts` holds the line against
57546
+ * `scripts/migration-api-contract.json`, and every `behaviours` id below must have an
57547
+ * `it('<id>'` in `migration-api.contract.spec.ts`.
57548
+ */
57549
+ var Rows = record(string(), unknown());
57550
+ var IntegrationId = object({ integrationId: string().min(1) });
57551
+ var RecordId = object({ id: string().min(1) });
57552
+ var RecordRowSchema = object({
57553
+ id: string(),
57554
+ deviceId: number().int().nullable(),
57555
+ at: number().nullable(),
57556
+ expiresAt: number().nullable(),
57557
+ rev: number().int(),
57558
+ updatedAt: number(),
57559
+ data: Rows
57560
+ });
57561
+ var RecordPutShape = {
57562
+ id: string().min(1),
57563
+ deviceId: number().int().optional(),
57564
+ at: number().int().optional(),
57565
+ expiresAt: number().int().optional(),
57566
+ data: Rows
57567
+ };
57568
+ var MigrationIntegrationSchema = object({
57569
+ id: string(),
57570
+ addonId: string(),
57571
+ name: string(),
57572
+ info: Rows,
57573
+ /** The registry's stored switch: read by the one-switch migration, nothing else. */
57574
+ enabled: boolean().optional(),
57575
+ originStableId: string().optional()
57576
+ });
57577
+ var MigrationDeviceSchema = object({
57578
+ id: number().int(),
57579
+ integrationId: string().nullable().optional(),
57580
+ /** The owning device; null or absent for a root. */
57581
+ parentDeviceId: number().int().nullable().optional(),
57582
+ type: string().optional(),
57583
+ name: string().optional(),
57584
+ stableId: string().optional()
57585
+ });
57586
+ /** What the engine says about the migration API it serves: lets an addon notice an older server. */
57587
+ var MigrationApiInfoSchema = object({
57588
+ version: number().int(),
57589
+ methods: array(string())
57590
+ });
57591
+ object({
57592
+ message: string(),
57593
+ meta: Rows.optional(),
57594
+ /** Grouping tags of the line; a line about a device carries `{ deviceId }`. */
57595
+ tags: object({ deviceId: number().int().optional() }).optional()
57596
+ });
57597
+ object({
57598
+ owner: string().min(1),
57599
+ metas: array(MigrationMetaSchema)
57600
+ }), object({
57601
+ bootId: string(),
57602
+ snapshot: _enum([
57603
+ "none",
57604
+ "written",
57605
+ "refused"
57606
+ ]),
57607
+ steps: array(MigrationOwnerStepSchema),
57608
+ /** The migration API the engine serves; absent from a server that predates it. */
57609
+ migrationApi: MigrationApiInfoSchema.optional()
57610
+ }), object({ id: string().min(1) }), object({
57611
+ proceed: boolean(),
57612
+ state: union([literal("pending"), MigrationStatusSchema]),
57613
+ reason: string().nullable()
57614
+ }), object({
57615
+ id: string().min(1),
57616
+ result: MigrationOwnerResultSchema
57617
+ }), object({
57618
+ status: MigrationStatusSchema,
57619
+ error: string().nullable(),
57620
+ rowsChanged: number().int().nonnegative()
57621
+ }), object({
57622
+ rows: number().int().nonnegative(),
57623
+ secrets: number().int().nonnegative()
57624
+ }), IntegrationId.extend({ patch: Rows }), object({ written: boolean() }), IntegrationId.extend({ keys: array(string().min(1)) }), object({
57625
+ present: boolean(),
57626
+ removed: Rows
57627
+ }), RecordRowSchema.nullable(), RecordRowSchema.nullable(), object({
57628
+ ...RecordPutShape,
57629
+ ifRev: number().int().optional()
57630
+ }), object({ rev: number().int() }), object({ records: array(object(RecordPutShape)) }), object({ count: number().int().nonnegative() }), RecordId.extend({
57631
+ partial: Rows,
57632
+ ifRev: number().int().optional()
57633
+ }), object({ rev: number().int() }), object({ deleted: boolean() }), object({
57634
+ deviceId: number().int().optional(),
57635
+ atFrom: number().optional(),
57636
+ atTo: number().optional(),
57637
+ where: RecordWhereSchema.optional(),
57638
+ limit: number().int().min(1).optional(),
57639
+ cursor: string().min(1).optional(),
57640
+ resolveSecrets: boolean().optional()
57641
+ }), object({
57642
+ records: array(RecordRowSchema),
57643
+ nextCursor: string().nullable()
57644
+ }), object({
57645
+ deviceId: number().int().optional(),
57646
+ atBefore: number().optional(),
57647
+ where: RecordWhereSchema.optional()
57648
+ }), object({ count: number().int().nonnegative() }), object({}), object({ store: Rows }), object({ patch: Rows }), object({}), object({ keys: array(string().min(1)) }), object({ removed: array(string()) }), object({ refs: array(string()) }), object({ values: record(string(), string().nullable()) }), object({
57649
+ ref: string().min(1),
57650
+ value: string()
57651
+ }), object({}), object({ refs: array(string()) }), object({ deleted: number().int().nonnegative() }), object({}), object({ integrations: array(MigrationIntegrationSchema) }), object({ id: string().min(1) }), MigrationIntegrationSchema.nullable(), object({
57652
+ addonId: string().min(1),
57653
+ integrationId: string().min(1).optional()
57654
+ }), object({ devices: array(MigrationDeviceSchema) }), object({ deviceId: number().int() }), object({
57655
+ id: number().int(),
57656
+ integrationId: string().nullable(),
57657
+ /** Whether the device carries any stored config; its content is not offered. */
57658
+ hasConfig: boolean()
57659
+ }).nullable(), object({
57660
+ deviceId: number().int(),
57661
+ integrationId: string().min(1)
57662
+ }), object({}), object({}), object({ nodeId: string() }), object({}), object({});
56978
57663
  method(object({}), object({ entries: array(MigrationLedgerEntrySchema) }), { auth: "admin" }), method(object({ owner: string().optional() }), object({ pending: array(MigrationPendingEntrySchema) }), { auth: "admin" }), method(object({ id: string().min(1) }), MigrationDryRunResultSchema, { auth: "admin" }), method(object({
56979
57664
  id: string().min(1),
56980
57665
  error: string().min(1)
@@ -57004,7 +57689,9 @@ method(object({}), object({ entries: array(MigrationLedgerEntrySchema) }), { aut
57004
57689
  "written",
57005
57690
  "refused"
57006
57691
  ]),
57007
- steps: array(MigrationOwnerStepSchema)
57692
+ steps: array(MigrationOwnerStepSchema),
57693
+ /** The migration API this engine serves (additive: a server that predates it omits it). */
57694
+ migrationApi: MigrationApiInfoSchema.optional()
57008
57695
  }), {
57009
57696
  kind: "mutation",
57010
57697
  auth: "admin"
@@ -59671,7 +60358,10 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
59671
60358
  }), method(RelocateMediaInputSchema, object({ jobId: string() }), {
59672
60359
  kind: "mutation",
59673
60360
  auth: "admin"
59674
- }), method(object({}), UnstampedEventMediaCountSchema, { auth: "admin" }), method(RelocatableMediaCountInputSchema, RelocatableMediaCountSchema, {
60361
+ }), method(object({}), UnstampedEventMediaCountSchema, { auth: "admin" }), method(MediaLocationCensusInputSchema, MediaLocationCensusSchema, {
60362
+ kind: "query",
60363
+ auth: "admin"
60364
+ }), method(RelocatableMediaCountInputSchema, RelocatableMediaCountSchema, {
59675
60365
  kind: "query",
59676
60366
  auth: "admin"
59677
60367
  }), method(object({}), array(RelocateJobSchema).readonly(), {
@@ -62078,7 +62768,7 @@ var BrokerStatusSchema$1 = _enum([
62078
62768
  "unreachable",
62079
62769
  "tls-error"
62080
62770
  ]);
62081
- var BrokerInfoSchema$1 = object({
62771
+ var BrokerInfoSchema = object({
62082
62772
  id: string(),
62083
62773
  name: string(),
62084
62774
  url: string(),
@@ -62141,7 +62831,7 @@ var StatusSchema = object({
62141
62831
  brokerCount: number(),
62142
62832
  embeddedRunning: boolean()
62143
62833
  });
62144
- method(_void(), array(BrokerInfoSchema$1)), method(IdInputSchema, BrokerConnectionDetailsSchema, { auth: "admin" }), method(AddBrokerInputSchema, AddBrokerResultSchema, {
62834
+ method(_void(), array(BrokerInfoSchema)), method(IdInputSchema, BrokerConnectionDetailsSchema, { auth: "admin" }), method(AddBrokerInputSchema, AddBrokerResultSchema, {
62145
62835
  kind: "mutation",
62146
62836
  auth: "admin"
62147
62837
  }), method(IdInputSchema, _void(), {
@@ -66416,14 +67106,6 @@ object({
66416
67106
  empty: boolean().nullable(),
66417
67107
  /** True while the pump is running. Null while unknown. */
66418
67108
  pumpRunning: boolean().nullable(),
66419
- /** Water drunk in the last drink, in litres. */
66420
- lastDrink: number().min(0).nullable().meta(readingMeta("volume")),
66421
- /** Water drunk in the current hour, in litres. */
66422
- currentHourDrink: number().min(0).nullable().meta(readingMeta("volume")),
66423
- /** Water drunk over the last 24 hours (rolling), in litres. */
66424
- last24hDrink: number().min(0).nullable().meta(readingMeta("volume")),
66425
- /** Water drunk since local midnight, in litres. Null when the fountain has no such sensor. */
66426
- todayDrink: number().min(0).nullable().meta(readingMeta("volume")),
66427
67109
  /** Decoded fault message. Null means healthy; a non-null string is an active fault. */
66428
67110
  error: string().nullable(),
66429
67111
  /** Ms epoch when the slice was last refreshed. */
@@ -66436,9 +67118,6 @@ DeviceType.PetFountain, method(object({
66436
67118
  }), _void(), {
66437
67119
  kind: "mutation",
66438
67120
  auth: "protected"
66439
- }), method(object({ deviceId: DeviceIdSchema$1 }), _void(), {
66440
- kind: "mutation",
66441
- auth: "protected"
66442
67121
  });
66443
67122
  /**
66444
67123
  * The wire shapes of the Auto tune plan and apply (D745), used by the
@@ -68475,253 +69154,6 @@ DeviceType.Camera, DeviceType.Sensor, DeviceType.Switch, DeviceType.Gateway, met
68475
69154
  auth: "admin"
68476
69155
  });
68477
69156
  /**
68478
- * records - an addon's own facts and documents (D881): ledgers, audit rows,
68479
- * config documents, mirrors. The third storage API next to `ctx.settings`
68480
- * (operator intent, D870) and device-history (numbers over time, D850).
68481
- *
68482
- * Who the OWNER is: `callerAddonId`, stamped by the transport on a call that
68483
- * crossed a process and stated by a hub in-process caller (`ctx.records` does
68484
- * that with the addon id closed over). It is deliberately NOT in any input
68485
- * schema, so a session can never supply it, and a call with no stamp is refused
68486
- * `records/no-caller`. A kind is readable and writable only by its owner; other
68487
- * addons go through the owner's capability.
68488
- *
68489
- * Every read is three-way: a row, `null`, or the call THROWS. A failed read is
68490
- * never `[]`. Secret fields are never on the wire: a read shows the
68491
- * redaction token, `secretRefs` hands the owner's `ctx.secrets` the refs it
68492
- * resolves itself, and a write may carry only a keychain marker bound to the
68493
- * row's own ref.
68494
- *
68495
- * Internal: addons reach it through `ctx.records`, never directly.
68496
- */
68497
- var RecordIdSchema = string().min(1).max(256);
68498
- /** A JSON object body. Size is the engine's check (`maxDataBytes`), not a schema's. */
68499
- var RecordBodySchema = record(string(), unknown());
68500
- var RecordInputSchema = object({
68501
- id: RecordIdSchema,
68502
- /** The device this row belongs to (D865 removal, per-device reads). */
68503
- deviceId: number().int().optional(),
68504
- /** The domain clock, ms: observed / created / opened. */
68505
- at: number().int().optional(),
68506
- /** Producer-set expiry, ms. Refused on a kind whose retention is an engine TTL. */
68507
- expiresAt: number().int().optional(),
68508
- data: RecordBodySchema
68509
- });
68510
- var RecordViewSchema = object({
68511
- id: string(),
68512
- deviceId: number().int().nullable(),
68513
- at: number().nullable(),
68514
- expiresAt: number().nullable(),
68515
- rev: number().int(),
68516
- updatedAt: number(),
68517
- data: RecordBodySchema
68518
- });
68519
- /** Declared index fields only. Anything else does not compile, by design. */
68520
- var RecordWhereSchema = record(RecordFieldPathSchema, union([
68521
- string(),
68522
- number(),
68523
- boolean(),
68524
- object({ in: array(union([
68525
- string(),
68526
- number(),
68527
- boolean()
68528
- ])).min(1).max(RECORD_BATCH_MAX) }),
68529
- object({
68530
- gt: union([string(), number()]).optional(),
68531
- gte: union([string(), number()]).optional(),
68532
- lt: union([string(), number()]).optional(),
68533
- lte: union([string(), number()]).optional()
68534
- }).refine((r) => Object.keys(r).length > 0, { message: "name at least one bound" })
68535
- ]));
68536
- var KindShape = { kind: RecordKindNameSchema };
68537
- var TimeWindowShape = {
68538
- deviceId: number().int().optional(),
68539
- atFrom: number().optional(),
68540
- atTo: number().optional()
68541
- };
68542
- var RecordQueryInputSchema = object({
68543
- ...KindShape,
68544
- ...TimeWindowShape,
68545
- where: RecordWhereSchema.optional(),
68546
- /** Without `where`: `at` (default for a kind with a clock) or `id`. With `where` the order is the index's. */
68547
- order: _enum(["at", "id"]).optional(),
68548
- desc: boolean().optional(),
68549
- limit: number().int().min(1).max(RECORD_QUERY_MAX).default(100),
68550
- /** Opaque keyset cursor from a previous answer. There is no offset. */
68551
- cursor: string().min(1).optional()
68552
- });
68553
- var RecordQueryResultSchema = object({
68554
- records: array(RecordViewSchema),
68555
- nextCursor: string().nullable()
68556
- });
68557
- var RecordKindStateSchema = _enum([
68558
- "created",
68559
- "unchanged",
68560
- "updated"
68561
- ]);
68562
- var DeclareKindResultSchema = object({
68563
- kindId: number().int(),
68564
- state: RecordKindStateSchema,
68565
- createdIndexes: array(string())
68566
- });
68567
- /** Keychain refs a write released (the old marker is gone from the row): the owner deletes the values. */
68568
- var SecretRefsList = array(string());
68569
- /**
68570
- * One op of a `transact`: the single-row writes, each on a kind of the caller.
68571
- * All ops of one call share ONE database file and ONE `transactFamily`.
68572
- */
68573
- var RecordTransactOpSchema = discriminatedUnion("op", [
68574
- object({
68575
- op: literal("put"),
68576
- kind: RecordKindNameSchema,
68577
- record: RecordInputSchema,
68578
- ifRev: number().int().min(0).optional()
68579
- }),
68580
- object({
68581
- op: literal("patch"),
68582
- kind: RecordKindNameSchema,
68583
- id: RecordIdSchema,
68584
- data: RecordBodySchema,
68585
- at: number().int().nullable().optional(),
68586
- expiresAt: number().int().nullable().optional(),
68587
- ifRev: number().int().min(1).optional()
68588
- }),
68589
- object({
68590
- op: literal("delete"),
68591
- kind: RecordKindNameSchema,
68592
- id: RecordIdSchema
68593
- })
68594
- ]);
68595
- var RecordSecretRefsSchema = record(string(), record(string(), string()));
68596
- method(object({ kinds: record(RecordKindNameSchema, RecordKindDeclarationSchema) }), object({ kinds: record(string(), DeclareKindResultSchema) }), {
68597
- kind: "mutation",
68598
- auth: "admin"
68599
- }), method(object({
68600
- ...KindShape,
68601
- id: RecordIdSchema
68602
- }), RecordViewSchema.nullable(), { auth: "admin" }), method(object({
68603
- ...KindShape,
68604
- ids: array(RecordIdSchema).min(1).max(RECORD_BATCH_MAX)
68605
- }), array(RecordViewSchema), { auth: "admin" }), method(object({
68606
- ...KindShape,
68607
- ids: array(RecordIdSchema).min(1).max(RECORD_BATCH_MAX)
68608
- }), RecordSecretRefsSchema, { auth: "admin" }), method(object({
68609
- ...KindShape,
68610
- record: RecordInputSchema,
68611
- /** Compare-and-set. `0` means "the row must not exist". */
68612
- ifRev: number().int().min(0).optional()
68613
- }), object({
68614
- rev: number().int(),
68615
- releasedRefs: SecretRefsList
68616
- }), {
68617
- kind: "mutation",
68618
- auth: "admin"
68619
- }), method(object({
68620
- ...KindShape,
68621
- records: array(RecordInputSchema).min(1).max(RECORD_BATCH_MAX)
68622
- }), object({
68623
- count: number().int(),
68624
- releasedRefs: SecretRefsList
68625
- }), {
68626
- kind: "mutation",
68627
- auth: "admin"
68628
- }), method(object({
68629
- ...KindShape,
68630
- id: RecordIdSchema,
68631
- data: RecordBodySchema,
68632
- at: number().int().nullable().optional(),
68633
- expiresAt: number().int().nullable().optional(),
68634
- ifRev: number().int().min(1).optional()
68635
- }), object({
68636
- rev: number().int(),
68637
- releasedRefs: SecretRefsList
68638
- }), {
68639
- kind: "mutation",
68640
- auth: "admin"
68641
- }), method(object({
68642
- ...KindShape,
68643
- id: RecordIdSchema
68644
- }), object({
68645
- deleted: boolean(),
68646
- secretRefs: SecretRefsList
68647
- }), {
68648
- kind: "mutation",
68649
- auth: "admin"
68650
- }), method(object({
68651
- ...KindShape,
68652
- ids: array(RecordIdSchema).min(1).max(RECORD_BATCH_MAX)
68653
- }), object({
68654
- deleted: number().int(),
68655
- secretRefs: SecretRefsList
68656
- }), {
68657
- kind: "mutation",
68658
- auth: "admin"
68659
- }), method(RecordQueryInputSchema, RecordQueryResultSchema, { auth: "admin" }), method(object({
68660
- ...KindShape,
68661
- ...TimeWindowShape,
68662
- where: RecordWhereSchema.optional()
68663
- }), object({ count: number().int() }), { auth: "admin" }), method(object({
68664
- ...KindShape,
68665
- deviceId: number().int().optional(),
68666
- from: number(),
68667
- to: number(),
68668
- bucketMs: number().int().positive()
68669
- }), object({ buckets: array(object({
68670
- bucketStart: number(),
68671
- count: number().int()
68672
- })) }), { auth: "admin" }), method(object({
68673
- ...KindShape,
68674
- op: _enum([
68675
- "sum",
68676
- "min",
68677
- "max",
68678
- "count"
68679
- ]),
68680
- field: RecordFieldPathSchema.optional(),
68681
- groupBy: RecordFieldPathSchema.optional(),
68682
- where: RecordWhereSchema.optional()
68683
- }), object({ rows: array(object({
68684
- group: union([
68685
- string(),
68686
- number(),
68687
- _null()
68688
- ]),
68689
- value: number().nullable()
68690
- })) }), { auth: "admin" }), method(object({
68691
- ...KindShape,
68692
- deviceId: number().int().optional(),
68693
- atBefore: number().optional(),
68694
- where: RecordWhereSchema.optional()
68695
- }), object({
68696
- deleted: number().int(),
68697
- secretRefs: SecretRefsList
68698
- }), {
68699
- kind: "mutation",
68700
- auth: "admin"
68701
- }), method(object({ ops: array(RecordTransactOpSchema).min(1).max(RECORD_BATCH_MAX) }), object({
68702
- results: array(object({
68703
- rev: number().int().nullable(),
68704
- deleted: boolean()
68705
- })),
68706
- releasedRefs: SecretRefsList,
68707
- secretRefs: SecretRefsList
68708
- }), {
68709
- kind: "mutation",
68710
- auth: "admin"
68711
- }), method(object({
68712
- deviceId: number().int(),
68713
- kinds: array(RecordKindNameSchema).optional()
68714
- }), object({
68715
- deleted: record(string(), number().int()),
68716
- secretRefs: SecretRefsList
68717
- }), {
68718
- kind: "mutation",
68719
- auth: "admin"
68720
- }), method(object(KindShape), object({ id: number().int() }), {
68721
- kind: "mutation",
68722
- auth: "admin"
68723
- });
68724
- /**
68725
69157
  * record-entries - the ONE admin surface for every list of user-created entries
68726
69158
  * (D881): notification targets, brokers, LLM profiles, anything an addon
68727
69159
  * declares as an ENTRY kind (`entry: { title }` in `defineRecordKinds`).
@@ -77271,20 +77703,6 @@ Object.freeze({
77271
77703
  access: "create",
77272
77704
  role: "viewer"
77273
77705
  },
77274
- "broker.add": {
77275
- capName: "broker",
77276
- capScope: "system",
77277
- addonId: null,
77278
- access: "create",
77279
- role: "admin"
77280
- },
77281
- "broker.get": {
77282
- capName: "broker",
77283
- capScope: "system",
77284
- addonId: null,
77285
- access: "view",
77286
- role: "admin"
77287
- },
77288
77706
  "broker.getBrokerConfig": {
77289
77707
  capName: "broker",
77290
77708
  capScope: "system",
@@ -77292,20 +77710,6 @@ Object.freeze({
77292
77710
  access: "view",
77293
77711
  role: "admin"
77294
77712
  },
77295
- "broker.getSettings": {
77296
- capName: "broker",
77297
- capScope: "system",
77298
- addonId: null,
77299
- access: "view",
77300
- role: "admin"
77301
- },
77302
- "broker.getSettingsSchema": {
77303
- capName: "broker",
77304
- capScope: "system",
77305
- addonId: null,
77306
- access: "view",
77307
- role: "admin"
77308
- },
77309
77713
  "broker.getState": {
77310
77714
  capName: "broker",
77311
77715
  capScope: "system",
@@ -77320,20 +77724,6 @@ Object.freeze({
77320
77724
  access: "view",
77321
77725
  role: "admin"
77322
77726
  },
77323
- "broker.list": {
77324
- capName: "broker",
77325
- capScope: "system",
77326
- addonId: null,
77327
- access: "view",
77328
- role: "admin"
77329
- },
77330
- "broker.listProviders": {
77331
- capName: "broker",
77332
- capScope: "system",
77333
- addonId: null,
77334
- access: "view",
77335
- role: "admin"
77336
- },
77337
77727
  "broker.publish": {
77338
77728
  capName: "broker",
77339
77729
  capScope: "system",
@@ -77341,20 +77731,6 @@ Object.freeze({
77341
77731
  access: "create",
77342
77732
  role: "admin"
77343
77733
  },
77344
- "broker.remove": {
77345
- capName: "broker",
77346
- capScope: "system",
77347
- addonId: null,
77348
- access: "delete",
77349
- role: "admin"
77350
- },
77351
- "broker.setSettings": {
77352
- capName: "broker",
77353
- capScope: "system",
77354
- addonId: null,
77355
- access: "create",
77356
- role: "admin"
77357
- },
77358
77734
  "broker.subscribe": {
77359
77735
  capName: "broker",
77360
77736
  capScope: "system",
@@ -77362,20 +77738,6 @@ Object.freeze({
77362
77738
  access: "create",
77363
77739
  role: "admin"
77364
77740
  },
77365
- "broker.testConnection": {
77366
- capName: "broker",
77367
- capScope: "system",
77368
- addonId: null,
77369
- access: "create",
77370
- role: "admin"
77371
- },
77372
- "broker.testSettings": {
77373
- capName: "broker",
77374
- capScope: "system",
77375
- addonId: null,
77376
- access: "create",
77377
- role: "admin"
77378
- },
77379
77741
  "broker.unsubscribe": {
77380
77742
  capName: "broker",
77381
77743
  capScope: "system",
@@ -82136,13 +82498,6 @@ Object.freeze({
82136
82498
  access: "view",
82137
82499
  role: "viewer"
82138
82500
  },
82139
- "petFountain.resetDailyConsumption": {
82140
- capName: "pet-fountain",
82141
- capScope: "device",
82142
- addonId: null,
82143
- access: "delete",
82144
- role: "viewer"
82145
- },
82146
82501
  "petFountain.setPump": {
82147
82502
  capName: "pet-fountain",
82148
82503
  capScope: "device",
@@ -82339,6 +82694,13 @@ Object.freeze({
82339
82694
  access: "view",
82340
82695
  role: "viewer"
82341
82696
  },
82697
+ "pipelineAnalytics.getMediaLocationCensus": {
82698
+ capName: "pipeline-analytics",
82699
+ capScope: "device",
82700
+ addonId: null,
82701
+ access: "view",
82702
+ role: "admin"
82703
+ },
82342
82704
  "pipelineAnalytics.getMediaReclaimStatus": {
82343
82705
  capName: "pipeline-analytics",
82344
82706
  capScope: "device",
@@ -88557,11 +88919,6 @@ Object.freeze({
88557
88919
  form: "single",
88558
88920
  optional: false
88559
88921
  }],
88560
- "petFountain.resetDailyConsumption": [{
88561
- name: "deviceId",
88562
- form: "single",
88563
- optional: false
88564
- }],
88565
88922
  "petFountain.setPump": [{
88566
88923
  name: "deviceId",
88567
88924
  form: "single",
@@ -91599,7 +91956,7 @@ var GoogleInstance = class {
91599
91956
  return this.home.name;
91600
91957
  }
91601
91958
  get enabled() {
91602
- return this.home.enabled !== false;
91959
+ return isInstanceEnabled(this.home);
91603
91960
  }
91604
91961
  get devices() {
91605
91962
  return this.exportsRow.devices;
@@ -93010,7 +93367,7 @@ var ExportGoogleAddon = class extends BaseAddon {
93010
93367
  initialBody: (name) => ({ name }),
93011
93368
  mintId: () => `google-home-${randomUUID().slice(0, 8)}`,
93012
93369
  health: (body, id) => {
93013
- if (body.enabled === false) return { status: {
93370
+ if (!isInstanceEnabled(body)) return { status: {
93014
93371
  state: "off",
93015
93372
  label: "Off"
93016
93373
  } };
@@ -93217,7 +93574,7 @@ var ExportGoogleAddon = class extends BaseAddon {
93217
93574
  listInstances: async () => (await this.requireRegistry().list()).map((row) => ({
93218
93575
  instanceId: row.id,
93219
93576
  name: row.body.name,
93220
- enabled: row.body.enabled !== false,
93577
+ enabled: isInstanceEnabled(row.body),
93221
93578
  kind: "google-home"
93222
93579
  })),
93223
93580
  listSupportedDeviceKinds: async ({ instanceId }) => {
@@ -93326,7 +93683,7 @@ var ExportGoogleAddon = class extends BaseAddon {
93326
93683
  const descriptors = traitsForCaps(facts.capNames);
93327
93684
  if (descriptors.length === 0) return null;
93328
93685
  const registry = this.requireRegistry();
93329
- const rows = (await registry.list()).filter((row) => row.body.enabled !== false);
93686
+ const rows = (await registry.list()).filter((row) => isInstanceEnabled(row.body));
93330
93687
  const sections = [];
93331
93688
  for (const row of rows) {
93332
93689
  const instance = await registry.get(row.id);