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