@camstack/addon-matter-broker 0.2.126 → 0.2.127

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.
Files changed (3) hide show
  1. package/dist/addon.js +1470 -131
  2. package/dist/addon.mjs +1470 -131
  3. package/package.json +1 -1
package/dist/addon.mjs CHANGED
@@ -11,7 +11,7 @@ import { networkInterfaces, tmpdir, uptime } from "node:os";
11
11
  import { finished } from "node:stream/promises";
12
12
  import { createConnection, createServer as createServer$2 } from "node:net";
13
13
  import * as dgram from "node:dgram";
14
- //#region ../types/dist/event-category-C4hVnRo8.mjs
14
+ //#region ../types/dist/event-category-BvOFi6PY.mjs
15
15
  var EventCategory = /* @__PURE__ */ function(EventCategory) {
16
16
  EventCategory["SystemBoot"] = "system.boot";
17
17
  EventCategory["SystemAddonsReady"] = "system.addons-ready";
@@ -75,6 +75,24 @@ var EventCategory = /* @__PURE__ */ function(EventCategory) {
75
75
  * consumes this category and maps it to the `addon-crash-loop` kind.
76
76
  */
77
77
  EventCategory["AddonRunnerFailed"] = "addon.runner-failed";
78
+ /**
79
+ * A runner whose addon refused to start with a typed reason (D877) - parked
80
+ * in `refused`, never counted by the crash breaker, retried on operator
81
+ * action. One event per refusal.
82
+ */
83
+ EventCategory["AddonRunnerRefused"] = "addon.runner-refused";
84
+ /**
85
+ * A runner settled on a state (D877): `running` (READY), `crashed`, `failed` or
86
+ * `refused`. In-process telemetry for the boot check (re-evaluate while any
87
+ * runner is still pending) and the alert centre (close a recovered runner).
88
+ */
89
+ EventCategory["ProcessStateChanged"] = "process.state-changed";
90
+ /**
91
+ * The node's one-shot runner boot check (D877): planned runners against the
92
+ * process service, `degraded` when any is failed, refused or missing. The
93
+ * alert centre turns it into one alert and a direct critical push.
94
+ */
95
+ EventCategory["SystemRunnerCheck"] = "system.runner-check";
78
96
  EventCategory["AddonError"] = "addon.error";
79
97
  EventCategory["AddonPageReady"] = "addon.page-ready";
80
98
  EventCategory["AddonWidgetReady"] = "addon.widget-ready";
@@ -4117,6 +4135,12 @@ var numberProcessor = (schema, ctx, _json, _params) => {
4117
4135
  var booleanProcessor = (_schema, _ctx, json, _params) => {
4118
4136
  json.type = "boolean";
4119
4137
  };
4138
+ var bigintProcessor = (_schema, ctx, _json, _params) => {
4139
+ if (ctx.unrepresentable === "throw") throw new Error("BigInt cannot be represented in JSON Schema");
4140
+ };
4141
+ var symbolProcessor = (_schema, ctx, _json, _params) => {
4142
+ if (ctx.unrepresentable === "throw") throw new Error("Symbols cannot be represented in JSON Schema");
4143
+ };
4120
4144
  var nullProcessor = (_schema, ctx, json, _params) => {
4121
4145
  if (ctx.target === "openapi-3.0") {
4122
4146
  json.type = "string";
@@ -4124,12 +4148,17 @@ var nullProcessor = (_schema, ctx, json, _params) => {
4124
4148
  json.enum = [null];
4125
4149
  } else json.type = "null";
4126
4150
  };
4151
+ var undefinedProcessor = (_schema, ctx, _json, _params) => {
4152
+ if (ctx.unrepresentable === "throw") throw new Error("Undefined cannot be represented in JSON Schema");
4153
+ };
4127
4154
  var voidProcessor = (_schema, ctx, _json, _params) => {
4128
4155
  if (ctx.unrepresentable === "throw") throw new Error("Void cannot be represented in JSON Schema");
4129
4156
  };
4130
4157
  var neverProcessor = (_schema, _ctx, json, _params) => {
4131
4158
  json.not = {};
4132
4159
  };
4160
+ var anyProcessor = (_schema, _ctx, _json, _params) => {};
4161
+ var unknownProcessor = (_schema, _ctx, _json, _params) => {};
4133
4162
  var dateProcessor = (_schema, ctx, _json, _params) => {
4134
4163
  if (ctx.unrepresentable === "throw") throw new Error("Date cannot be represented in JSON Schema");
4135
4164
  };
@@ -4161,12 +4190,53 @@ var literalProcessor = (schema, ctx, json, _params) => {
4161
4190
  json.enum = vals;
4162
4191
  }
4163
4192
  };
4193
+ var nanProcessor = (_schema, ctx, _json, _params) => {
4194
+ if (ctx.unrepresentable === "throw") throw new Error("NaN cannot be represented in JSON Schema");
4195
+ };
4196
+ var templateLiteralProcessor = (schema, _ctx, json, _params) => {
4197
+ const _json = json;
4198
+ const pattern = schema._zod.pattern;
4199
+ if (!pattern) throw new Error("Pattern not found in template literal");
4200
+ _json.type = "string";
4201
+ _json.pattern = pattern.source;
4202
+ };
4203
+ var fileProcessor = (schema, _ctx, json, _params) => {
4204
+ const _json = json;
4205
+ const file = {
4206
+ type: "string",
4207
+ format: "binary",
4208
+ contentEncoding: "binary"
4209
+ };
4210
+ const { minimum, maximum, mime } = schema._zod.bag;
4211
+ if (minimum !== void 0) file.minLength = minimum;
4212
+ if (maximum !== void 0) file.maxLength = maximum;
4213
+ if (mime) if (mime.length === 1) {
4214
+ file.contentMediaType = mime[0];
4215
+ Object.assign(_json, file);
4216
+ } else {
4217
+ Object.assign(_json, file);
4218
+ _json.anyOf = mime.map((m) => ({ contentMediaType: m }));
4219
+ }
4220
+ else Object.assign(_json, file);
4221
+ };
4222
+ var successProcessor = (_schema, _ctx, json, _params) => {
4223
+ json.type = "boolean";
4224
+ };
4164
4225
  var customProcessor = (_schema, ctx, _json, _params) => {
4165
4226
  if (ctx.unrepresentable === "throw") throw new Error("Custom types cannot be represented in JSON Schema");
4166
4227
  };
4228
+ var functionProcessor = (_schema, ctx, _json, _params) => {
4229
+ if (ctx.unrepresentable === "throw") throw new Error("Function types cannot be represented in JSON Schema");
4230
+ };
4167
4231
  var transformProcessor = (_schema, ctx, _json, _params) => {
4168
4232
  if (ctx.unrepresentable === "throw") throw new Error("Transforms cannot be represented in JSON Schema");
4169
4233
  };
4234
+ var mapProcessor = (_schema, ctx, _json, _params) => {
4235
+ if (ctx.unrepresentable === "throw") throw new Error("Map cannot be represented in JSON Schema");
4236
+ };
4237
+ var setProcessor = (_schema, ctx, _json, _params) => {
4238
+ if (ctx.unrepresentable === "throw") throw new Error("Set cannot be represented in JSON Schema");
4239
+ };
4170
4240
  var arrayProcessor = (schema, ctx, _json, params) => {
4171
4241
  const json = _json;
4172
4242
  const def = schema._zod.def;
@@ -4371,6 +4441,12 @@ var readonlyProcessor = (schema, ctx, json, params) => {
4371
4441
  seen.ref = def.innerType;
4372
4442
  json.readOnly = true;
4373
4443
  };
4444
+ var promiseProcessor = (schema, ctx, _json, params) => {
4445
+ const def = schema._zod.def;
4446
+ process$1(def.innerType, ctx, params);
4447
+ const seen = ctx.seen.get(schema);
4448
+ seen.ref = def.innerType;
4449
+ };
4374
4450
  var optionalProcessor = (schema, ctx, _json, params) => {
4375
4451
  const def = schema._zod.def;
4376
4452
  process$1(def.innerType, ctx, params);
@@ -4383,6 +4459,81 @@ var lazyProcessor = (schema, ctx, _json, params) => {
4383
4459
  const seen = ctx.seen.get(schema);
4384
4460
  seen.ref = innerType;
4385
4461
  };
4462
+ var allProcessors = {
4463
+ string: stringProcessor,
4464
+ number: numberProcessor,
4465
+ boolean: booleanProcessor,
4466
+ bigint: bigintProcessor,
4467
+ symbol: symbolProcessor,
4468
+ null: nullProcessor,
4469
+ undefined: undefinedProcessor,
4470
+ void: voidProcessor,
4471
+ never: neverProcessor,
4472
+ any: anyProcessor,
4473
+ unknown: unknownProcessor,
4474
+ date: dateProcessor,
4475
+ enum: enumProcessor,
4476
+ literal: literalProcessor,
4477
+ nan: nanProcessor,
4478
+ template_literal: templateLiteralProcessor,
4479
+ file: fileProcessor,
4480
+ success: successProcessor,
4481
+ custom: customProcessor,
4482
+ function: functionProcessor,
4483
+ transform: transformProcessor,
4484
+ map: mapProcessor,
4485
+ set: setProcessor,
4486
+ array: arrayProcessor,
4487
+ object: objectProcessor,
4488
+ union: unionProcessor,
4489
+ intersection: intersectionProcessor,
4490
+ tuple: tupleProcessor,
4491
+ record: recordProcessor,
4492
+ nullable: nullableProcessor,
4493
+ nonoptional: nonoptionalProcessor,
4494
+ default: defaultProcessor,
4495
+ prefault: prefaultProcessor,
4496
+ catch: catchProcessor,
4497
+ pipe: pipeProcessor,
4498
+ readonly: readonlyProcessor,
4499
+ promise: promiseProcessor,
4500
+ optional: optionalProcessor,
4501
+ lazy: lazyProcessor
4502
+ };
4503
+ function toJSONSchema(input, params) {
4504
+ if ("_idmap" in input) {
4505
+ const registry = input;
4506
+ const ctx = initializeContext({
4507
+ ...params,
4508
+ processors: allProcessors
4509
+ });
4510
+ const defs = {};
4511
+ for (const entry of registry._idmap.entries()) {
4512
+ const [_, schema] = entry;
4513
+ process$1(schema, ctx);
4514
+ }
4515
+ const schemas = {};
4516
+ ctx.external = {
4517
+ registry,
4518
+ uri: params?.uri,
4519
+ defs
4520
+ };
4521
+ for (const entry of registry._idmap.entries()) {
4522
+ const [key, schema] = entry;
4523
+ extractDefs(ctx, schema);
4524
+ schemas[key] = finalize(ctx, schema);
4525
+ }
4526
+ if (Object.keys(defs).length > 0) schemas.__shared = { [ctx.target === "draft-2020-12" ? "$defs" : "definitions"]: defs };
4527
+ return { schemas };
4528
+ }
4529
+ const ctx = initializeContext({
4530
+ ...params,
4531
+ processors: allProcessors
4532
+ });
4533
+ process$1(input, ctx);
4534
+ extractDefs(ctx, input);
4535
+ return finalize(ctx, input);
4536
+ }
4386
4537
  //#endregion
4387
4538
  //#region ../../node_modules/zod/v4/classic/iso.js
4388
4539
  var ZodISODateTime = /*@__PURE__*/ $constructor("ZodISODateTime", (inst, def) => {
@@ -5399,7 +5550,7 @@ var ZodIssueCode = {
5399
5550
  var ZodFirstPartyTypeKind;
5400
5551
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
5401
5552
  //#endregion
5402
- //#region ../types/dist/sleep-DRqxtc0C.mjs
5553
+ //#region ../types/dist/sleep-bZIhUvjd.mjs
5403
5554
  /**
5404
5555
  * The audio chunk plane's byte format, and the ONE expansion from a coded
5405
5556
  * window to float samples (D455).
@@ -5516,7 +5667,7 @@ function isKeychainStoredField(field) {
5516
5667
  var SECRET_CLEAR = { $secretClear: true };
5517
5668
  /** The `'***'` token D634 redaction writes for non-admins. */
5518
5669
  var LEGACY_DEVICE_REDACTION = "***";
5519
- function isRecord$2(value) {
5670
+ function isRecord$5(value) {
5520
5671
  return typeof value === "object" && value !== null && !Array.isArray(value);
5521
5672
  }
5522
5673
  function makeSecretMarker(ref) {
@@ -5527,12 +5678,12 @@ function makeSecretMarker(ref) {
5527
5678
  }
5528
5679
  /** A stored marker: an object whose `$secret` is a non-empty string. */
5529
5680
  function isSecretMarker(value) {
5530
- if (!isRecord$2(value)) return false;
5681
+ if (!isRecord$5(value)) return false;
5531
5682
  const ref = value["$secret"];
5532
5683
  return typeof ref === "string" && ref.length > 0;
5533
5684
  }
5534
5685
  function isSecretClear(value) {
5535
- return isRecord$2(value) && value["$secretClear"] === true;
5686
+ return isRecord$5(value) && value["$secretClear"] === true;
5536
5687
  }
5537
5688
  /**
5538
5689
  * The UI view of a stored secret field value: a marker becomes "set", inline
@@ -6142,7 +6293,7 @@ var KeychainWriteRefusedError = class extends Error {
6142
6293
  }
6143
6294
  };
6144
6295
  var KEEP = { kind: "keep" };
6145
- function isRecord$1$1(value) {
6296
+ function isRecord$4(value) {
6146
6297
  return typeof value === "object" && value !== null && !Array.isArray(value);
6147
6298
  }
6148
6299
  function defaultMintId() {
@@ -6155,7 +6306,7 @@ function collectSecretMarkerRefs(value, out = []) {
6155
6306
  return out;
6156
6307
  }
6157
6308
  if (Array.isArray(value)) for (const item of value) collectSecretMarkerRefs(item, out);
6158
- else if (isRecord$1$1(value)) for (const child of Object.values(value)) collectSecretMarkerRefs(child, out);
6309
+ else if (isRecord$4(value)) for (const child of Object.values(value)) collectSecretMarkerRefs(child, out);
6159
6310
  return out;
6160
6311
  }
6161
6312
  async function storedValueEquals(secrets, marker, candidate) {
@@ -6210,7 +6361,7 @@ function rowId(row, idKey) {
6210
6361
  return null;
6211
6362
  }
6212
6363
  async function writeArray(ctx, node, incoming, stored, fieldPath) {
6213
- const storedRows = Array.isArray(stored) ? stored.filter(isRecord$1$1) : [];
6364
+ const storedRows = Array.isArray(stored) ? stored.filter(isRecord$4) : [];
6214
6365
  if (!Array.isArray(incoming)) {
6215
6366
  ctx.deletes.push(...collectSecretMarkerRefs(storedRows));
6216
6367
  return {
@@ -6226,7 +6377,7 @@ async function writeArray(ctx, node, incoming, stored, fieldPath) {
6226
6377
  const kept = /* @__PURE__ */ new Set();
6227
6378
  const rows = [];
6228
6379
  for (const row of incoming) {
6229
- if (!isRecord$1$1(row)) {
6380
+ if (!isRecord$4(row)) {
6230
6381
  rows.push(row);
6231
6382
  continue;
6232
6383
  }
@@ -6251,7 +6402,7 @@ async function writeNode(ctx, node, incoming, stored, fieldPath) {
6251
6402
  case "leaf": return writeLeaf(ctx, incoming, stored, fieldPath);
6252
6403
  case "array": return writeArray(ctx, node, incoming, stored, fieldPath);
6253
6404
  case "object": {
6254
- if (!isRecord$1$1(incoming)) {
6405
+ if (!isRecord$4(incoming)) {
6255
6406
  if (incoming === void 0) return KEEP;
6256
6407
  ctx.deletes.push(...collectSecretMarkerRefs(stored));
6257
6408
  return {
@@ -6259,7 +6410,7 @@ async function writeNode(ctx, node, incoming, stored, fieldPath) {
6259
6410
  value: incoming
6260
6411
  };
6261
6412
  }
6262
- const storedObj = isRecord$1$1(stored) ? stored : {};
6413
+ const storedObj = isRecord$4(stored) ? stored : {};
6263
6414
  return {
6264
6415
  kind: "value",
6265
6416
  value: await writeMembers(ctx, node.children, incoming, storedObj, (m) => `${fieldPath}.${m}`)
@@ -6382,7 +6533,7 @@ async function resolveSecretMarkers(value, secrets, options = {}) {
6382
6533
  value: items
6383
6534
  };
6384
6535
  }
6385
- if (isRecord$1$1(v)) {
6536
+ if (isRecord$4(v)) {
6386
6537
  const out = {};
6387
6538
  for (const [k, child] of Object.entries(v)) {
6388
6539
  const s = substitute(child);
@@ -6650,7 +6801,6 @@ function createHandle(raw, opts) {
6650
6801
  const writeAddon = (patch) => write("addon", opts.addonTree(), void 0, patch, () => readStoredAddonBlob(raw), (p) => raw.writeAddonStore(p));
6651
6802
  const readAddonStoreResult = raw.readAddonStoreResult;
6652
6803
  const readAddonStoreKeyResult = raw.readAddonStoreKeyResult;
6653
- const readDeviceStoreBatch = raw.readDeviceStoreBatch;
6654
6804
  const overrides = {
6655
6805
  readAddonStore: async () => resolveRead("addon", await raw.readAddonStore()),
6656
6806
  ...readAddonStoreResult !== void 0 ? { readAddonStoreResult: async () => {
@@ -6674,12 +6824,12 @@ function createHandle(raw, opts) {
6674
6824
  };
6675
6825
  } } : {},
6676
6826
  readDeviceStore: async (deviceId) => resolveRead(`device:${deviceId}`, await raw.readDeviceStore(deviceId)),
6677
- ...readDeviceStoreBatch !== void 0 ? { readDeviceStoreBatch: async (deviceIds) => {
6678
- const rows = await readDeviceStoreBatch.call(raw, deviceIds);
6827
+ readDeviceStoreBatch: async (deviceIds) => {
6828
+ const rows = await raw.readDeviceStoreBatch(deviceIds);
6679
6829
  const out = /* @__PURE__ */ new Map();
6680
6830
  for (const [deviceId, blob] of rows) out.set(deviceId, await resolveRead(`device:${deviceId}`, blob));
6681
6831
  return out;
6682
- } } : {},
6832
+ },
6683
6833
  writeAddonStore: async (patch) => {
6684
6834
  await writeAddon(patch);
6685
6835
  },
@@ -7306,7 +7456,7 @@ var BaseAddon = class {
7306
7456
  if (!ctx) return;
7307
7457
  const addonId = ctx.id;
7308
7458
  setImmediate(() => {
7309
- ctx.api.addons?.restartAddon?.mutate({ addonId }).then(() => {
7459
+ ctx.api.addons.restartAddon.mutate({ addonId }).then(() => {
7310
7460
  ctx.logger.info("addon auto-restart triggered by restart-required setting change", { meta: { changedFields: patchKeys.filter((k) => restartKeys.has(k)) } });
7311
7461
  }).catch((err) => {
7312
7462
  ctx.logger.error("addon auto-restart failed", { meta: { error: err instanceof Error ? err.message : String(err) } });
@@ -7506,7 +7656,7 @@ var BaseAddon = class {
7506
7656
  return this._addonSecretTree;
7507
7657
  }
7508
7658
  deviceSecretTree() {
7509
- this._deviceSecretTree ??= secretTreeFromSchema(this.deviceSettingsSchema());
7659
+ this._deviceSecretTree ??= mergeSecretStatePaths(secretTreeFromSchema(this.deviceSettingsSchema()), this.secretStatePaths);
7510
7660
  return this._deviceSecretTree;
7511
7661
  }
7512
7662
  /**
@@ -7582,42 +7732,135 @@ var BaseAddon = class {
7582
7732
  this[timerOf] = timer;
7583
7733
  }
7584
7734
  /**
7585
- * Wrap `ctx.settings.readAddonStore()` with a short retry budget so a
7586
- * transient settings-store outage (mid-restart of sqlite-settings, tsx-watch
7587
- * swap, or any race where the SqliteSettingsBackend is between shutdown and
7588
- * re-initialize) doesn't propagate up into `initialize()` and leave the
7735
+ * Wrap `ctx.settings.readAddonStore()` with a retry budget so a transient
7736
+ * settings-store outage doesn't propagate up into `initialize()` and leave the
7589
7737
  * addon permanently broken.
7590
7738
  *
7591
- * Retry only the two known infra fingerprints. Anything else propagates so
7592
- * real bugs surface immediately. After the budget expires we fall back to
7593
- * `{}` (defaults) — the addon's first successful patch will rehydrate.
7739
+ * Two kinds of outage, two budgets:
7740
+ * - the store's own restart fingerprints (`SqliteSettingsBackend not
7741
+ * initialized`, `provider not available`): a short budget, then the addon
7742
+ * falls back to `{}` (defaults) - its first successful patch rehydrates;
7743
+ * - a TRANSPORT failure (the hub is restarting while this runner boots:
7744
+ * `discovery deadline exceeded`, `parent could not route`, a refused or
7745
+ * timed-out connection). Since D870 a runner's settings read THROWS instead
7746
+ * of answering `{}`, so without a budget a hub restart ends in a respawn
7747
+ * loop. A long, bounded budget; only after it the error propagates - the
7748
+ * addon never runs on defaults for a store it could not ask.
7749
+ * Anything else propagates immediately so real bugs surface.
7594
7750
  */
7595
7751
  async readAddonStoreWithRetry() {
7596
7752
  const settings = this.rawSettings();
7597
7753
  if (!settings) return {};
7598
- const delaysMs = [
7599
- 150,
7600
- 350,
7601
- 600,
7602
- 900
7603
- ];
7604
7754
  let lastErr;
7605
- for (let attempt = 0; attempt <= delaysMs.length; attempt++) try {
7755
+ for (let attempt = 0;; attempt++) try {
7606
7756
  const stored = await settings.readAddonStore() ?? {};
7607
7757
  this.settingsStoreReady = true;
7608
7758
  return stored;
7609
7759
  } catch (err) {
7610
7760
  lastErr = err;
7611
- const msg = err instanceof Error ? err.message : String(err);
7612
- if (!(msg.includes("SqliteSettingsBackend not initialized") || msg.includes("provider not available"))) throw err;
7613
- if (attempt === delaysMs.length) break;
7614
- await new Promise((r) => setTimeout(r, delaysMs[attempt]));
7761
+ const kind = classifyStoreError(err);
7762
+ if (kind === "permanent") throw err;
7763
+ const delay = (kind === "transport" ? TRANSPORT_RETRY_DELAYS_MS : RESTART_RETRY_DELAYS_MS)[attempt];
7764
+ if (delay === void 0) {
7765
+ if (kind === "transport") throw err;
7766
+ break;
7767
+ }
7768
+ await new Promise((r) => setTimeout(r, delay));
7615
7769
  }
7616
7770
  this.settingsStoreReady = false;
7617
7771
  this._ctx?.logger?.warn?.("readAddonStore: settings-store unavailable after retries — using defaults", { meta: { error: lastErr instanceof Error ? lastErr.message : String(lastErr) } });
7618
7772
  return {};
7619
7773
  }
7620
7774
  };
7775
+ /** The settings store's own restart fingerprints. */
7776
+ var RESTART_RETRY_DELAYS_MS = [
7777
+ 150,
7778
+ 350,
7779
+ 600,
7780
+ 900
7781
+ ];
7782
+ /** A hub restarting under a booting runner: ~100 s in total. */
7783
+ var TRANSPORT_RETRY_DELAYS_MS = [
7784
+ 150,
7785
+ 350,
7786
+ 600,
7787
+ 900,
7788
+ 2e3,
7789
+ 5e3,
7790
+ 1e4,
7791
+ 2e4,
7792
+ 3e4,
7793
+ 3e4
7794
+ ];
7795
+ var RESTART_FINGERPRINTS = ["SqliteSettingsBackend not initialized", "provider not available"];
7796
+ /** Node / socket error codes of a connection that did not happen or broke. */
7797
+ var TRANSPORT_CODES = new Set([
7798
+ "ECONNREFUSED",
7799
+ "ECONNRESET",
7800
+ "ETIMEDOUT",
7801
+ "EPIPE",
7802
+ "EHOSTUNREACH",
7803
+ "ENETUNREACH"
7804
+ ]);
7805
+ /** tRPC error codes that mean "the other side is not answering now", not "your call is wrong". */
7806
+ var UNAVAILABLE_TRPC_CODES = new Set([
7807
+ "TIMEOUT",
7808
+ "SERVICE_UNAVAILABLE",
7809
+ "BAD_GATEWAY",
7810
+ "GATEWAY_TIMEOUT"
7811
+ ]);
7812
+ /** The exact phrases OUR transport raises when it cannot reach the hub. */
7813
+ var TRANSPORT_PHRASES = [
7814
+ "discovery deadline exceeded",
7815
+ "parent could not route child unowned cap call",
7816
+ "UDS request timed out after",
7817
+ "channel closed"
7818
+ ];
7819
+ /** Moleculer error `type`s of a call that could not be served right now. */
7820
+ var MOLECULER_TRANSIENT_TYPES = new Set([
7821
+ "REQUEST_TIMEOUT",
7822
+ "SERVICE_NOT_FOUND",
7823
+ "SERVICE_NOT_AVAILABLE",
7824
+ "REQUEST_REJECTED",
7825
+ "BROKER_DISCONNECTED"
7826
+ ]);
7827
+ function stringProp(value, key) {
7828
+ if (typeof value !== "object" || value === null) return void 0;
7829
+ const found = Reflect.get(value, key);
7830
+ return typeof found === "string" ? found : void 0;
7831
+ }
7832
+ /** The code an error carries: its own, its cause's, or a tRPC `data.code`. */
7833
+ function errorCode(err) {
7834
+ const out = {};
7835
+ const cause = typeof err === "object" && err !== null ? Reflect.get(err, "cause") : void 0;
7836
+ const data = typeof err === "object" && err !== null ? Reflect.get(err, "data") : void 0;
7837
+ const node = stringProp(err, "code") ?? stringProp(cause, "code");
7838
+ if (node !== void 0) out.node = node;
7839
+ const trpc = stringProp(data, "code");
7840
+ if (trpc !== void 0) out.trpc = trpc;
7841
+ return out;
7842
+ }
7843
+ /**
7844
+ * Is a settings read failure worth retrying, and with which budget? Only
7845
+ * EXPLICIT signals count: a socket error code, a tRPC "unavailable" code, or
7846
+ * one of the exact phrases our own transport raises. A message that merely
7847
+ * contains "timed out" or "unreachable" is not evidence of anything, and
7848
+ * `settings store not wired` is a wiring bug that retrying cannot fix.
7849
+ */
7850
+ function classifyStoreError(err) {
7851
+ const message = err instanceof Error ? err.message : String(err);
7852
+ if (RESTART_FINGERPRINTS.some((f) => message.includes(f))) return "restart";
7853
+ const code = errorCode(err);
7854
+ if (code.node !== void 0 && TRANSPORT_CODES.has(code.node)) return "transport";
7855
+ if (code.trpc !== void 0 && UNAVAILABLE_TRPC_CODES.has(code.trpc)) return "transport";
7856
+ if (typeof err === "object" && err !== null) {
7857
+ if (Reflect.get(err, "retryable") === true) return "transport";
7858
+ const type = stringProp(err, "type");
7859
+ if (type !== void 0 && MOLECULER_TRANSIENT_TYPES.has(type)) return "transport";
7860
+ }
7861
+ if (TRANSPORT_PHRASES.some((f) => message.includes(f))) return "transport";
7862
+ return "permanent";
7863
+ }
7621
7864
  /**
7622
7865
  * Collect the keys of every field marked `perNode: true`, recursing into
7623
7866
  * layout containers (`group` fields and `sub-tabs` tabs) the same way
@@ -7707,6 +7950,356 @@ var PeerBytesTicketSchema = object({
7707
7950
  */
7708
7951
  declaredBytes: number().int().nonnegative().nullable()
7709
7952
  });
7953
+ /** Limits and names of `ctx.records` (D881). One authority; the engine and the facade read it. */
7954
+ /** The files a kind may live in. `history` is device-history's (D850), never records. */
7955
+ var RECORD_DATABASES = ["settings", "events"];
7956
+ /** The classes of a kind: the `@durable` vocabulary, one authority (replaces the annotation). */
7957
+ var RECORD_CLASSES = [
7958
+ "config",
7959
+ "ledger",
7960
+ "audit",
7961
+ "mirror",
7962
+ "ephemeral"
7963
+ ];
7964
+ var RECORD_DEFAULT_MAX_DATA_BYTES = 64 * 1024;
7965
+ var RECORD_MAX_DATA_BYTES = 1024 * 1024;
7966
+ var RECORD_BATCH_MAX = 1e3;
7967
+ var RECORD_QUERY_MAX = 1e3;
7968
+ /** A kind in the `settings` file may not bound itself above this (D447: high volume is `events`). */
7969
+ var RECORD_SETTINGS_MAX_ROWS = 5e4;
7970
+ var PREFIX$1 = "records/";
7971
+ /** The base of every records failure. `detail` is the human part of the message. */
7972
+ var RecordsError = class extends Error {
7973
+ code;
7974
+ detail;
7975
+ constructor(code, detail) {
7976
+ super(`${PREFIX$1}${code}: ${detail}`);
7977
+ this.name = "RecordsError";
7978
+ this.code = code;
7979
+ this.detail = detail;
7980
+ }
7981
+ };
7982
+ /** The keychain could not store or serve a value: explicit, never an empty string. */
7983
+ var RecordSecretUnavailableError = class extends RecordsError {
7984
+ constructor(detail) {
7985
+ super("secret-unavailable", detail);
7986
+ this.name = "RecordSecretUnavailableError";
7987
+ }
7988
+ };
7989
+ var InvalidRecordError = class extends RecordsError {
7990
+ constructor(detail) {
7991
+ super("invalid-record", detail);
7992
+ this.name = "InvalidRecordError";
7993
+ }
7994
+ };
7995
+ /** A kind declaration the engine refuses (non-additive change, bad shape, wrong file). */
7996
+ var DeclarationRefusedError = class extends RecordsError {
7997
+ constructor(detail) {
7998
+ super("declaration-refused", detail);
7999
+ this.name = "DeclarationRefusedError";
8000
+ }
8001
+ };
8002
+ function defOf(schema) {
8003
+ const zodBag = Reflect.get(schema, "_zod");
8004
+ if (typeof zodBag !== "object" || zodBag === null) return {};
8005
+ const def = Reflect.get(zodBag, "def");
8006
+ if (typeof def !== "object" || def === null) return {};
8007
+ return def;
8008
+ }
8009
+ function declaredHere(schema) {
8010
+ return globalRegistry.get(schema)?.secret === true;
8011
+ }
8012
+ /** Wrapper kinds whose `innerType` is the field itself. */
8013
+ var WRAPPERS = new Set([
8014
+ "optional",
8015
+ "nullable",
8016
+ "default",
8017
+ "prefault",
8018
+ "catch",
8019
+ "readonly",
8020
+ "nonoptional"
8021
+ ]);
8022
+ /**
8023
+ * The schema layers that make up ONE field: the schema itself and every
8024
+ * wrapper below it (optional / default / nullable / readonly / catch), plus
8025
+ * both sides of a pipe (`z.preprocess` puts the real schema on `out`,
8026
+ * `.transform` on `in`).
8027
+ */
8028
+ function layersOf(schema) {
8029
+ const out = [];
8030
+ const queue = [schema];
8031
+ while (queue.length > 0) {
8032
+ const s = queue.shift();
8033
+ if (!s || out.includes(s)) continue;
8034
+ out.push(s);
8035
+ const def = defOf(s);
8036
+ if (def.type !== void 0 && WRAPPERS.has(def.type) && def.innerType) queue.push(def.innerType);
8037
+ if (def.type === "pipe") {
8038
+ if (def.in) queue.push(def.in);
8039
+ if (def.out) queue.push(def.out);
8040
+ }
8041
+ }
8042
+ return out;
8043
+ }
8044
+ /** True when any layer of this field declares `.meta({ secret: true })`. */
8045
+ function isZodSecret(schema) {
8046
+ return layersOf(schema).some(declaredHere);
8047
+ }
8048
+ /**
8049
+ * Every declared secret path in a config schema: dotted keys, `[]` for "each
8050
+ * element of this array" (`connection.password`, `rows[].token`). A declared
8051
+ * object or array is reported as one path and not descended into — everything
8052
+ * under it is secret.
8053
+ */
8054
+ function collectZodSecretPaths(schema, prefix = "") {
8055
+ if (isZodSecret(schema)) return prefix.length > 0 ? [prefix] : [];
8056
+ const paths = [];
8057
+ for (const layer of layersOf(schema)) {
8058
+ const def = defOf(layer);
8059
+ if (def.type === "object" && def.shape) for (const [key, child] of Object.entries(def.shape)) paths.push(...collectZodSecretPaths(child, prefix ? `${prefix}.${key}` : key));
8060
+ else if (def.type === "array" && def.element) paths.push(...collectZodSecretPaths(def.element, `${prefix}[]`));
8061
+ else if (def.type === "union" && def.options) for (const option of def.options) paths.push(...collectZodSecretPaths(option, prefix));
8062
+ else if (def.type === "intersection") {
8063
+ if (def.left) paths.push(...collectZodSecretPaths(def.left, prefix));
8064
+ if (def.right) paths.push(...collectZodSecretPaths(def.right, prefix));
8065
+ }
8066
+ }
8067
+ return [...new Set(paths)];
8068
+ }
8069
+ /**
8070
+ * Secret fields of a record, addressed the way a Zod schema declares them
8071
+ * (`collectZodSecretPaths`): dotted keys, `[]` for "each element of this array"
8072
+ * (`auth.accessToken`, `headers[].value`).
8073
+ *
8074
+ * Array elements are matched by a DECLARED id key (`secretArrayKeys`:
8075
+ * `{ headers: 'name' }`), never by index, so reordering a list keeps every
8076
+ * keychain ref (the same rule as `arrayItemFieldPath`). The concrete path of a
8077
+ * leaf names its element: `headers[X-Api].value`.
8078
+ *
8079
+ * Pure and browser-safe. Nothing here mutates: every transform returns a new value.
8080
+ */
8081
+ /** The array prefixes (declared form, e.g. `headers` or `a.headers`) of a path. */
8082
+ function parseSecretPath(path) {
8083
+ if (path.length === 0) throw new InvalidRecordError("an empty secret path");
8084
+ return path.split(".").map((raw) => {
8085
+ const each = raw.endsWith("[]");
8086
+ const key = each ? raw.slice(0, -2) : raw;
8087
+ if (key.length === 0) throw new InvalidRecordError(`secret path "${path}" has an empty segment`);
8088
+ return {
8089
+ key,
8090
+ each
8091
+ };
8092
+ });
8093
+ }
8094
+ /** The declared array prefixes of `path` that need an id key (`headers`, `a.rows`). */
8095
+ function secretArrayPrefixes(path) {
8096
+ const segments = parseSecretPath(path);
8097
+ const prefixes = [];
8098
+ const walked = [];
8099
+ for (const segment of segments) {
8100
+ walked.push(segment.key);
8101
+ if (segment.each) prefixes.push(walked.join("."));
8102
+ }
8103
+ return prefixes;
8104
+ }
8105
+ /**
8106
+ * Record kinds (D881): the declaration an addon makes of one kind of fact, the
8107
+ * Zod row schema that describes it, and the helper that turns the two into the
8108
+ * JSON the engine stores.
8109
+ *
8110
+ * A kind is declared ONCE, next to the code that owns it, and the engine's
8111
+ * reconciler creates its indexes - nothing creates DDL at runtime from a write.
8112
+ * Everything the generic machinery needs (secret fields, the entry descriptor)
8113
+ * is DERIVED from the Zod schema: `.meta({ secret: true })` marks a credential,
8114
+ * never a field name (D879).
8115
+ */
8116
+ /** A JSON field path: `trackId`, `auth.accessToken`. Charset-restricted: it is rendered into DDL. */
8117
+ var RecordFieldPathSchema = string$2().regex(/^[A-Za-z_][A-Za-z0-9_]{0,63}(\.[A-Za-z_][A-Za-z0-9_]{0,63}){0,3}$/);
8118
+ var RecordIndexSchema = object({
8119
+ name: string$2().regex(/^[a-z][a-z0-9_]{0,31}$/),
8120
+ fields: array(RecordFieldPathSchema).min(1).max(4),
8121
+ unique: boolean().optional()
8122
+ }).strict();
8123
+ var RecordRetentionSchema = union([
8124
+ object({
8125
+ ttlMs: number().int().positive(),
8126
+ from: _enum(["at", "write"])
8127
+ }).strict(),
8128
+ object({
8129
+ maxRows: number().int().positive().optional(),
8130
+ maxRowsPerDevice: number().int().positive().optional()
8131
+ }).strict().refine((r) => r.maxRows !== void 0 || r.maxRowsPerDevice !== void 0, { message: "name maxRows, maxRowsPerDevice or both" }),
8132
+ object({
8133
+ owner: string$2().min(1),
8134
+ reason: string$2().min(1)
8135
+ }).strict(),
8136
+ object({ none: string$2().min(1) }).strict()
8137
+ ]);
8138
+ /** The descriptor a generic entries UI reads (D881 "generic entries"). */
8139
+ var EntryDescriptorSchema = object({
8140
+ title: string$2().min(1),
8141
+ /** The record body field shown as the entry's name. */
8142
+ nameField: string$2().min(1),
8143
+ /** JSON Schema of the entry body; `secret: true` marks a password field. */
8144
+ fields: record(string$2(), unknown())
8145
+ }).strict();
8146
+ /** What crosses the wire and sits in the engine's catalog: JSON only, no Zod. */
8147
+ var RecordKindDeclarationSchema = object({
8148
+ database: _enum(RECORD_DATABASES).default("settings"),
8149
+ class: _enum(RECORD_CLASSES),
8150
+ writeTrigger: string$2().min(1),
8151
+ device: _enum([
8152
+ "required",
8153
+ "optional",
8154
+ "none"
8155
+ ]).default("none"),
8156
+ at: _enum(["required", "none"]).default("none"),
8157
+ indexes: array(RecordIndexSchema).max(8).default([]),
8158
+ retention: RecordRetentionSchema,
8159
+ deviceRemoval: _enum(["delete", "none"]).default("none"),
8160
+ maxDataBytes: number().int().positive().max(RECORD_MAX_DATA_BYTES).default(RECORD_DEFAULT_MAX_DATA_BYTES),
8161
+ /** Derived from the Zod schema; never written by hand. */
8162
+ secretPaths: array(string$2().min(1)).default([]),
8163
+ /** The id key of each array that carries a secret (`{ headers: 'name' }`). */
8164
+ secretArrayKeys: record(string$2(), string$2()).default({}),
8165
+ /** The legacy table this kind adopts from; the boot guard reads it (D853: no migration code). */
8166
+ adoptsFrom: string$2().min(1).optional(),
8167
+ /** Kinds that must agree through `transact` sit in one file under one family name. */
8168
+ transactFamily: string$2().min(1).optional(),
8169
+ entry: EntryDescriptorSchema.optional()
8170
+ }).strict();
8171
+ /** The kind names: lower-case, dash separated, short enough for an index name. */
8172
+ var RecordKindNameSchema = string$2().regex(/^[a-z][a-z0-9-]{0,47}$/);
8173
+ /** Cross-field rules a declaration must satisfy. Throws {@link DeclarationRefusedError}. */
8174
+ function assertValidDeclaration(name, decl) {
8175
+ const refuse = (why) => {
8176
+ throw new DeclarationRefusedError(`kind "${name}": ${why}`);
8177
+ };
8178
+ if (!RecordKindNameSchema.safeParse(name).success) refuse("the name must be lower-case-dashed");
8179
+ const seen = /* @__PURE__ */ new Set();
8180
+ for (const index of decl.indexes) {
8181
+ if (seen.has(index.name)) refuse(`index name "${index.name}" is declared twice`);
8182
+ seen.add(index.name);
8183
+ }
8184
+ const { retention } = decl;
8185
+ const hasSecrets = decl.secretPaths.length > 0;
8186
+ if ("ttlMs" in retention) {
8187
+ if (retention.from === "at" && decl.at !== "required") refuse("a ttl from \"at\" needs at: \"required\"");
8188
+ if (hasSecrets) refuse("a kind with secret fields cannot use engine TTL (its keychain values would be orphaned)");
8189
+ }
8190
+ if ("maxRows" in retention || "maxRowsPerDevice" in retention) {
8191
+ if (retention.maxRowsPerDevice !== void 0 && decl.device !== "required") refuse("maxRowsPerDevice needs device: \"required\"");
8192
+ if (decl.at !== "required") refuse("a row bound trims the oldest \"at\": it needs at: \"required\"");
8193
+ if (hasSecrets) refuse("a kind with secret fields cannot use an engine row bound");
8194
+ const bound = Math.max(retention.maxRows ?? 0, retention.maxRowsPerDevice ?? 0);
8195
+ if (decl.database === "settings" && bound > 5e4) refuse(`a row bound above ${RECORD_SETTINGS_MAX_ROWS} belongs in database: "events" (a big delete on the settings thread stalls every configuration read)`);
8196
+ }
8197
+ if (decl.deviceRemoval === "delete" && decl.device === "none") refuse("deviceRemoval: \"delete\" needs a device: \"required\" or \"optional\"");
8198
+ for (const path of decl.secretPaths) for (const prefix of secretArrayPrefixes(path)) if (decl.secretArrayKeys[prefix] === void 0) refuse(`secret path "${path}" crosses the array "${prefix}": declare its id key in secretArrayKeys`);
8199
+ }
8200
+ function bodyFieldsOf(schema) {
8201
+ return { ...toJSONSchema(schema, {
8202
+ unrepresentable: "any",
8203
+ io: "input"
8204
+ }) };
8205
+ }
8206
+ function isRecordLike(value) {
8207
+ return typeof value === "object" && value !== null && !Array.isArray(value);
8208
+ }
8209
+ /** Does every branch of the body schema carry `field`? (A discriminated union has several.) */
8210
+ function hasNameField(json, field) {
8211
+ const branches = json["oneOf"] ?? json["anyOf"];
8212
+ if (Array.isArray(branches)) return branches.length > 0 && branches.every((b) => isRecordLike(b) && hasNameField(b, field));
8213
+ const properties = json["properties"];
8214
+ return isRecordLike(properties) && Object.prototype.hasOwnProperty.call(properties, field);
8215
+ }
8216
+ /**
8217
+ * Declare the kinds of a package. The keys are the kind names. The result is
8218
+ * what `ctx.records.declare` sends to the engine and what `ctx.records.kind`
8219
+ * types its handle from.
8220
+ */
8221
+ function defineRecordKinds(specs) {
8222
+ const out = {};
8223
+ for (const [name, spec] of Object.entries(specs)) {
8224
+ const secretPaths = collectZodSecretPaths(spec.schema);
8225
+ const nameField = spec.entry?.nameField ?? "name";
8226
+ const fields = bodyFieldsOf(spec.schema);
8227
+ if (spec.entry !== void 0 && !hasNameField(fields, nameField)) throw new DeclarationRefusedError(`kind "${name}": an entry kind's schema needs a "${nameField}" field`);
8228
+ const parsed = RecordKindDeclarationSchema.parse({
8229
+ database: spec.database,
8230
+ class: spec.class,
8231
+ writeTrigger: spec.writeTrigger,
8232
+ device: spec.device,
8233
+ at: spec.at,
8234
+ indexes: spec.indexes === void 0 ? void 0 : [...spec.indexes],
8235
+ retention: spec.retention,
8236
+ deviceRemoval: spec.deviceRemoval,
8237
+ maxDataBytes: spec.maxDataBytes,
8238
+ secretPaths: [...secretPaths],
8239
+ secretArrayKeys: spec.secretArrayKeys === void 0 ? void 0 : { ...spec.secretArrayKeys },
8240
+ adoptsFrom: spec.adoptsFrom,
8241
+ transactFamily: spec.transactFamily,
8242
+ entry: spec.entry === void 0 ? void 0 : {
8243
+ title: spec.entry.title,
8244
+ nameField,
8245
+ fields
8246
+ }
8247
+ });
8248
+ assertValidDeclaration(name, parsed);
8249
+ out[name] = {
8250
+ name,
8251
+ schema: spec.schema,
8252
+ declaration: parsed
8253
+ };
8254
+ }
8255
+ return out;
8256
+ }
8257
+ /**
8258
+ * Entry kinds (D881): every list of user-created entries (notification
8259
+ * targets, brokers, LLM profiles) is ONE record kind with an id, a name and a
8260
+ * kind-specific body, and the admin UI lists/adds/edits/deletes all of them
8261
+ * through the `record-entries` capability with password fields derived from
8262
+ * the schema (`.meta({ secret: true })`).
8263
+ */
8264
+ /** The body of a plain entry: a name and the fields the kind adds. */
8265
+ function entryBody(shape) {
8266
+ return object({
8267
+ name: string$2().min(1),
8268
+ ...shape
8269
+ });
8270
+ }
8271
+ /**
8272
+ * Declare one entry kind. An entry is configuration: never trimmed by the
8273
+ * engine, never aged, belonging to no device.
8274
+ */
8275
+ function defineEntryKind(name, spec) {
8276
+ const defined = defineRecordKinds({ [name]: {
8277
+ schema: spec.schema,
8278
+ class: "config",
8279
+ writeTrigger: spec.writeTrigger ?? "an operator adds or edits an entry in the entries UI",
8280
+ retention: { none: "an entry goes only when the operator deletes it" },
8281
+ ...spec.database === void 0 ? {} : { database: spec.database },
8282
+ ...spec.indexes === void 0 ? {} : { indexes: spec.indexes },
8283
+ ...spec.secretArrayKeys === void 0 ? {} : { secretArrayKeys: spec.secretArrayKeys },
8284
+ ...spec.adoptsFrom === void 0 ? {} : { adoptsFrom: spec.adoptsFrom },
8285
+ entry: {
8286
+ title: spec.title,
8287
+ ...spec.nameField === void 0 ? {} : { nameField: spec.nameField }
8288
+ }
8289
+ } })[name];
8290
+ if (defined === void 0) throw new DeclarationRefusedError(`entry kind "${name}" was not built`);
8291
+ return defined;
8292
+ }
8293
+ /**
8294
+ * Legacy source for broker entry adoption (B2): brokers live in addon-settings
8295
+ * as one row `<addonId>.brokers` whose value is an array until records-adopt
8296
+ * copies them into the entry kind.
8297
+ */
8298
+ var SETTINGS_BROKERS_ADOPTS_PREFIX = "@settings-brokers/";
8299
+ /** The `adoptsFrom` value for an addon's broker entry kind. */
8300
+ function settingsBrokersAdoptsFrom(addonId) {
8301
+ return `${SETTINGS_BROKERS_ADOPTS_PREFIX}${addonId}`;
8302
+ }
7710
8303
  /** Shared Zod schemas used across streaming capabilities. */
7711
8304
  var CamProfileSchema = _enum([
7712
8305
  "high",
@@ -8171,75 +8764,12 @@ method(object({ deviceId: number() }), array(StreamSourceEntrySchema)), method(o
8171
8764
  kind: "mutation",
8172
8765
  auth: "admin"
8173
8766
  }), method(object({ deviceId: number() }), unknown().nullable()), method(object({ deviceId: number() }), RawStateResultSchema.nullable(), { auth: "protected" });
8174
- function defOf(schema) {
8175
- return schema._zod?.def ?? {};
8176
- }
8177
- function declaredHere(schema) {
8178
- return globalRegistry.get(schema)?.secret === true;
8179
- }
8180
- /** Wrapper kinds whose `innerType` is the field itself. */
8181
- var WRAPPERS = new Set([
8182
- "optional",
8183
- "nullable",
8184
- "default",
8185
- "prefault",
8186
- "catch",
8187
- "readonly",
8188
- "nonoptional"
8189
- ]);
8190
- /**
8191
- * The schema layers that make up ONE field: the schema itself and every
8192
- * wrapper below it (optional / default / nullable / readonly / catch), plus
8193
- * both sides of a pipe (`z.preprocess` puts the real schema on `out`,
8194
- * `.transform` on `in`).
8195
- */
8196
- function layersOf(schema) {
8197
- const out = [];
8198
- const queue = [schema];
8199
- while (queue.length > 0) {
8200
- const s = queue.shift();
8201
- if (!s || out.includes(s)) continue;
8202
- out.push(s);
8203
- const def = defOf(s);
8204
- if (def.type !== void 0 && WRAPPERS.has(def.type) && def.innerType) queue.push(def.innerType);
8205
- if (def.type === "pipe") {
8206
- if (def.in) queue.push(def.in);
8207
- if (def.out) queue.push(def.out);
8208
- }
8209
- }
8210
- return out;
8211
- }
8212
- /** True when any layer of this field declares `.meta({ secret: true })`. */
8213
- function isZodSecret(schema) {
8214
- return layersOf(schema).some(declaredHere);
8215
- }
8216
- /**
8217
- * Every declared secret path in a config schema: dotted keys, `[]` for "each
8218
- * element of this array" (`connection.password`, `rows[].token`). A declared
8219
- * object or array is reported as one path and not descended into — everything
8220
- * under it is secret.
8221
- */
8222
- function collectZodSecretPaths(schema, prefix = "") {
8223
- if (isZodSecret(schema)) return prefix.length > 0 ? [prefix] : [];
8224
- const paths = [];
8225
- for (const layer of layersOf(schema)) {
8226
- const def = defOf(layer);
8227
- if (def.type === "object" && def.shape) for (const [key, child] of Object.entries(def.shape)) paths.push(...collectZodSecretPaths(child, prefix ? `${prefix}.${key}` : key));
8228
- else if (def.type === "array" && def.element) paths.push(...collectZodSecretPaths(def.element, `${prefix}[]`));
8229
- else if (def.type === "union" && def.options) for (const option of def.options) paths.push(...collectZodSecretPaths(option, prefix));
8230
- else if (def.type === "intersection") {
8231
- if (def.left) paths.push(...collectZodSecretPaths(def.left, prefix));
8232
- if (def.right) paths.push(...collectZodSecretPaths(def.right, prefix));
8233
- }
8234
- }
8235
- return [...new Set(paths)];
8236
- }
8237
8767
  object({
8238
8768
  code: string$2().regex(/^[a-z][a-z0-9-]*(\.[a-z0-9-]+)+$/),
8239
8769
  params: record(string$2(), union([string$2(), number()])).optional()
8240
8770
  });
8241
8771
  //#endregion
8242
- //#region ../types/dist/err-msg-DLerKiVO.mjs
8772
+ //#region ../types/dist/err-msg--2RrYiLO.mjs
8243
8773
  var DeviceType = /* @__PURE__ */ function(DeviceType) {
8244
8774
  DeviceType["Camera"] = "camera";
8245
8775
  DeviceType["Hub"] = "hub";
@@ -8508,6 +9038,9 @@ var DeviceRole = /* @__PURE__ */ function(DeviceRole) {
8508
9038
  /** Virtual HA toggle (input_boolean.*) — distinguishable from a
8509
9039
  * real Switch device for UI rendering / export adapters. */
8510
9040
  DeviceRole["BinaryHelper"] = "binary-helper";
9041
+ /** A smart plug: a `switch` whose source says it is an outlet (HA
9042
+ * `device_class: outlet`). The Alexa export shows it as a SMARTPLUG. */
9043
+ DeviceRole["Outlet"] = "outlet";
8511
9044
  /** Generic motion / occupancy / moving event source. Distinct from
8512
9045
  * the camera accessory PirSensor role: that one is a camera child;
8513
9046
  * this is a standalone HA / 3rd-party motion sensor. */
@@ -8585,7 +9118,7 @@ function errMsg(err) {
8585
9118
  return String(err);
8586
9119
  }
8587
9120
  //#endregion
8588
- //#region ../types/dist/composition-EQ9Ok0Ee.mjs
9121
+ //#region ../types/dist/composition-DOwQB_Ua.mjs
8589
9122
  /**
8590
9123
  * The ffmpeg build every CamStack node downloads, per platform and arch.
8591
9124
  *
@@ -11789,11 +12322,10 @@ var ClipModelMetaSchema = object({
11789
12322
  /**
11790
12323
  * The `vector-store` index this model's vectors live in. ONE feature space
11791
12324
  * per index: two models share an index only when their vectors are ranked
11792
- * against each other, which for CLIP means never across families. MobileCLIP
11793
- * S1 and S2 share `object-clip` for history (separated by the row's
11794
- * `modelId`); any other model gets its own.
12325
+ * against each other, which for CLIP means never across families. Every
12326
+ * model gets its own.
11795
12327
  */
11796
- vectorIndex: string$2().regex(/^object-clip(-[a-z0-9][a-z0-9-]*)?$/),
12328
+ vectorIndex: string$2().regex(/^object-clip-[a-z0-9][a-z0-9-]*$/),
11797
12329
  /**
11798
12330
  * The text encoder's tokenizer, a declared SIBLING file of its onnx. The name
11799
12331
  * must be unique per tokenizer: every model's siblings land in ONE flat
@@ -15575,6 +16107,41 @@ var ComposableCapabilitiesSchema = object({ caps: array(object({
15575
16107
  keyField: string$2()
15576
16108
  }).optional()
15577
16109
  })) });
16110
+ /**
16111
+ * The report of a one-shot "move this owner's plaintext secrets into the
16112
+ * keychain" run (D878). COUNTS only - never a value, never a ref.
16113
+ *
16114
+ * The owner runs it on its own rows, through its own write path; an operator
16115
+ * script (`scripts/hub/migrate-raw-secrets.ts`) calls the owner's cap method.
16116
+ * Dry run (`apply: false`) reports what WOULD move and changes nothing.
16117
+ */
16118
+ var RawSecretMigrationInputSchema = object({
16119
+ /** `false` (the default of the script) = report only. */
16120
+ apply: boolean() });
16121
+ var RawSecretMigrationReportSchema = object({
16122
+ apply: boolean(),
16123
+ /** Rows that can carry a secret (a profile, an enrolment). */
16124
+ rows: number().int(),
16125
+ /** Rows whose secret was plaintext when the run started. */
16126
+ raw: number().int(),
16127
+ /** Rows that already held a keychain marker when the run started. */
16128
+ markers: number().int(),
16129
+ /** Plaintext rows moved by THIS run (always 0 on a dry run). */
16130
+ migrated: number().int(),
16131
+ /** Plaintext rows left in place because the move or its read-back failed. */
16132
+ failed: number().int(),
16133
+ /** After the run: rows still holding plaintext. */
16134
+ remainingRaw: number().int(),
16135
+ /** After the run: markers the keychain could not resolve right now. */
16136
+ unresolvedMarkers: number().int(),
16137
+ /**
16138
+ * A second, redundant copy of the secrets' rows that the run found (and, on
16139
+ * `apply`, deleted after verifying the first). Owners with a single copy omit it.
16140
+ */
16141
+ redundantCopies: number().int().optional(),
16142
+ /** True when nothing is raw and every marker resolves. */
16143
+ verified: boolean()
16144
+ });
15578
16145
  /** Where a block runs. The operator chooses — a block driving a device on an
15579
16146
  * agent is the reason placement is not fixed to the hub. */
15580
16147
  var CoreBlockPlacementSchema = union([literal("hub"), string$2().min(1)]);
@@ -15801,6 +16368,9 @@ method(object({}), object({ blocks: array(CoreBlockSchema) }), { auth: "admin" }
15801
16368
  }), SettingsUpdateResultSchema, {
15802
16369
  kind: "mutation",
15803
16370
  auth: "admin"
16371
+ }), method(RawSecretMigrationInputSchema, RawSecretMigrationReportSchema, {
16372
+ kind: "mutation",
16373
+ auth: "admin"
15804
16374
  }), method(object({}), object({ libs: array(object({
15805
16375
  filePath: string$2(),
15806
16376
  content: string$2()
@@ -16064,6 +16634,347 @@ id: union([string$2(), number()]) }), {
16064
16634
  auth: "admin"
16065
16635
  });
16066
16636
  /**
16637
+ * records - an addon's own facts and documents (D881): ledgers, audit rows,
16638
+ * config documents, mirrors. The third storage API next to `ctx.settings`
16639
+ * (operator intent, D870) and device-history (numbers over time, D850).
16640
+ *
16641
+ * Who the OWNER is: `callerAddonId`, stamped by the transport on a call that
16642
+ * crossed a process and stated by a hub in-process caller (`ctx.records` does
16643
+ * that with the addon id closed over). It is deliberately NOT in any input
16644
+ * schema, so a session can never supply it, and a call with no stamp is refused
16645
+ * `records/no-caller`. A kind is readable and writable only by its owner; other
16646
+ * addons go through the owner's capability.
16647
+ *
16648
+ * Every read is three-way: a row, `null`, or the call THROWS. A failed read is
16649
+ * never `[]`. Secret fields are never on the wire: a read shows the
16650
+ * redaction token, `secretRefs` hands the owner's `ctx.secrets` the refs it
16651
+ * resolves itself, and a write may carry only a keychain marker bound to the
16652
+ * row's own ref.
16653
+ *
16654
+ * Internal: addons reach it through `ctx.records`, never directly.
16655
+ */
16656
+ var RecordIdSchema = string$2().min(1).max(256);
16657
+ /** A JSON object body. Size is the engine's check (`maxDataBytes`), not a schema's. */
16658
+ var RecordBodySchema = record(string$2(), unknown());
16659
+ var RecordInputSchema = object({
16660
+ id: RecordIdSchema,
16661
+ /** The device this row belongs to (D865 removal, per-device reads). */
16662
+ deviceId: number().int().optional(),
16663
+ /** The domain clock, ms: observed / created / opened. */
16664
+ at: number().int().optional(),
16665
+ /** Producer-set expiry, ms. Refused on a kind whose retention is an engine TTL. */
16666
+ expiresAt: number().int().optional(),
16667
+ data: RecordBodySchema
16668
+ });
16669
+ var RecordViewSchema = object({
16670
+ id: string$2(),
16671
+ deviceId: number().int().nullable(),
16672
+ at: number().nullable(),
16673
+ expiresAt: number().nullable(),
16674
+ rev: number().int(),
16675
+ updatedAt: number(),
16676
+ data: RecordBodySchema
16677
+ });
16678
+ /** Declared index fields only. Anything else does not compile, by design. */
16679
+ var RecordWhereSchema = record(RecordFieldPathSchema, union([
16680
+ string$2(),
16681
+ number(),
16682
+ boolean(),
16683
+ object({ in: array(union([
16684
+ string$2(),
16685
+ number(),
16686
+ boolean()
16687
+ ])).min(1).max(RECORD_BATCH_MAX) }),
16688
+ object({
16689
+ gt: union([string$2(), number()]).optional(),
16690
+ gte: union([string$2(), number()]).optional(),
16691
+ lt: union([string$2(), number()]).optional(),
16692
+ lte: union([string$2(), number()]).optional()
16693
+ }).refine((r) => Object.keys(r).length > 0, { message: "name at least one bound" })
16694
+ ]));
16695
+ var KindShape = { kind: RecordKindNameSchema };
16696
+ var TimeWindowShape = {
16697
+ deviceId: number().int().optional(),
16698
+ atFrom: number().optional(),
16699
+ atTo: number().optional()
16700
+ };
16701
+ var RecordQueryInputSchema = object({
16702
+ ...KindShape,
16703
+ ...TimeWindowShape,
16704
+ where: RecordWhereSchema.optional(),
16705
+ /** Without `where`: `at` (default for a kind with a clock) or `id`. With `where` the order is the index's. */
16706
+ order: _enum(["at", "id"]).optional(),
16707
+ desc: boolean().optional(),
16708
+ limit: number().int().min(1).max(RECORD_QUERY_MAX).default(100),
16709
+ /** Opaque keyset cursor from a previous answer. There is no offset. */
16710
+ cursor: string$2().min(1).optional()
16711
+ });
16712
+ var RecordQueryResultSchema = object({
16713
+ records: array(RecordViewSchema),
16714
+ nextCursor: string$2().nullable()
16715
+ });
16716
+ var RecordKindStateSchema = _enum([
16717
+ "created",
16718
+ "unchanged",
16719
+ "updated"
16720
+ ]);
16721
+ var DeclareKindResultSchema = object({
16722
+ kindId: number().int(),
16723
+ state: RecordKindStateSchema,
16724
+ createdIndexes: array(string$2()),
16725
+ /** The boot guard: the kind is empty while its legacy table still holds rows. */
16726
+ adoptionPending: object({
16727
+ legacyTable: string$2(),
16728
+ legacyRows: number().int()
16729
+ }).nullable()
16730
+ });
16731
+ /** Keychain refs a write released (the old marker is gone from the row): the owner deletes the values. */
16732
+ var SecretRefsList = array(string$2());
16733
+ var RecordSecretRefsSchema = record(string$2(), record(string$2(), string$2()));
16734
+ method(object({ kinds: record(RecordKindNameSchema, RecordKindDeclarationSchema) }), object({ kinds: record(string$2(), DeclareKindResultSchema) }), {
16735
+ kind: "mutation",
16736
+ auth: "admin"
16737
+ }), method(object({
16738
+ ...KindShape,
16739
+ id: RecordIdSchema
16740
+ }), RecordViewSchema.nullable(), { auth: "admin" }), method(object({
16741
+ ...KindShape,
16742
+ ids: array(RecordIdSchema).min(1).max(RECORD_BATCH_MAX)
16743
+ }), array(RecordViewSchema), { auth: "admin" }), method(object({
16744
+ ...KindShape,
16745
+ ids: array(RecordIdSchema).min(1).max(RECORD_BATCH_MAX)
16746
+ }), RecordSecretRefsSchema, { auth: "admin" }), method(object({
16747
+ ...KindShape,
16748
+ record: RecordInputSchema,
16749
+ /** Compare-and-set. `0` means "the row must not exist". */
16750
+ ifRev: number().int().min(0).optional()
16751
+ }), object({
16752
+ rev: number().int(),
16753
+ releasedRefs: SecretRefsList
16754
+ }), {
16755
+ kind: "mutation",
16756
+ auth: "admin"
16757
+ }), method(object({
16758
+ ...KindShape,
16759
+ records: array(RecordInputSchema).min(1).max(RECORD_BATCH_MAX)
16760
+ }), object({
16761
+ count: number().int(),
16762
+ releasedRefs: SecretRefsList
16763
+ }), {
16764
+ kind: "mutation",
16765
+ auth: "admin"
16766
+ }), method(object({
16767
+ ...KindShape,
16768
+ id: RecordIdSchema,
16769
+ data: RecordBodySchema,
16770
+ at: number().int().nullable().optional(),
16771
+ expiresAt: number().int().nullable().optional(),
16772
+ ifRev: number().int().min(1).optional()
16773
+ }), object({
16774
+ rev: number().int(),
16775
+ releasedRefs: SecretRefsList
16776
+ }), {
16777
+ kind: "mutation",
16778
+ auth: "admin"
16779
+ }), method(object({
16780
+ ...KindShape,
16781
+ id: RecordIdSchema
16782
+ }), object({
16783
+ deleted: boolean(),
16784
+ secretRefs: SecretRefsList
16785
+ }), {
16786
+ kind: "mutation",
16787
+ auth: "admin"
16788
+ }), method(object({
16789
+ ...KindShape,
16790
+ ids: array(RecordIdSchema).min(1).max(RECORD_BATCH_MAX)
16791
+ }), object({
16792
+ deleted: number().int(),
16793
+ secretRefs: SecretRefsList
16794
+ }), {
16795
+ kind: "mutation",
16796
+ auth: "admin"
16797
+ }), method(RecordQueryInputSchema, RecordQueryResultSchema, { auth: "admin" }), method(object({
16798
+ ...KindShape,
16799
+ ...TimeWindowShape,
16800
+ where: RecordWhereSchema.optional()
16801
+ }), object({ count: number().int() }), { auth: "admin" }), method(object({
16802
+ ...KindShape,
16803
+ deviceId: number().int().optional(),
16804
+ from: number(),
16805
+ to: number(),
16806
+ bucketMs: number().int().positive()
16807
+ }), object({ buckets: array(object({
16808
+ bucketStart: number(),
16809
+ count: number().int()
16810
+ })) }), { auth: "admin" }), method(object({
16811
+ ...KindShape,
16812
+ op: _enum([
16813
+ "sum",
16814
+ "min",
16815
+ "max",
16816
+ "count"
16817
+ ]),
16818
+ field: RecordFieldPathSchema.optional(),
16819
+ groupBy: RecordFieldPathSchema.optional(),
16820
+ where: RecordWhereSchema.optional()
16821
+ }), object({ rows: array(object({
16822
+ group: union([
16823
+ string$2(),
16824
+ number(),
16825
+ _null()
16826
+ ]),
16827
+ value: number().nullable()
16828
+ })) }), { auth: "admin" }), method(object({
16829
+ ...KindShape,
16830
+ deviceId: number().int().optional(),
16831
+ atBefore: number().optional(),
16832
+ where: RecordWhereSchema.optional()
16833
+ }), object({
16834
+ deleted: number().int(),
16835
+ secretRefs: SecretRefsList
16836
+ }), {
16837
+ kind: "mutation",
16838
+ auth: "admin"
16839
+ }), method(object({
16840
+ deviceId: number().int(),
16841
+ kinds: array(RecordKindNameSchema).optional()
16842
+ }), object({
16843
+ deleted: record(string$2(), number().int()),
16844
+ secretRefs: SecretRefsList
16845
+ }), {
16846
+ kind: "mutation",
16847
+ auth: "admin"
16848
+ }), method(object(KindShape), object({ id: number().int() }), {
16849
+ kind: "mutation",
16850
+ auth: "admin"
16851
+ });
16852
+ /** One table of the settings database. */
16853
+ var StorageTableSchema = object({
16854
+ /** The table's full name, e.g. `recorder:addon-settings` or `addon-device-settings`. */
16855
+ name: string$2(),
16856
+ /** The owner prefix of a scoped name (`recorder` for `recorder:addon-settings`), else null. */
16857
+ owner: string$2().nullable(),
16858
+ rows: number().int().nonnegative(),
16859
+ /** Bytes the table's pages occupy (`dbstat`); null when the engine cannot measure. */
16860
+ bytes: number().int().nonnegative().nullable(),
16861
+ /** Declared by an addon since this engine process started (a running addon claims it). */
16862
+ declaredThisBoot: boolean()
16863
+ });
16864
+ /** One declared record kind (D881) as System -> Data shows it. */
16865
+ var StorageKindSchema = object({
16866
+ owner: string$2(),
16867
+ kind: string$2(),
16868
+ database: _enum(["settings", "events"]),
16869
+ class: string$2(),
16870
+ state: _enum([
16871
+ "declared",
16872
+ "orphaned",
16873
+ "dropped"
16874
+ ]),
16875
+ /** `null` when the caller asked for no counts (`counts: false`). */
16876
+ rows: number().int().nonnegative().nullable(),
16877
+ /** Rows x the average size of a sample; null for an empty kind. */
16878
+ bytesEstimate: number().int().nonnegative().nullable(),
16879
+ writeTrigger: string$2(),
16880
+ retention: RecordRetentionSchema,
16881
+ /** `true` when the kind is an entry kind (the generic entries UI lists it). */
16882
+ entry: boolean(),
16883
+ /** The whole declaration, secret paths and entry descriptor included (the entries service builds its handle from it). */
16884
+ declaration: RecordKindDeclarationSchema
16885
+ });
16886
+ method(object({ ownerPrefix: string$2().min(1).optional() }), object({ tables: array(StorageTableSchema) }), { auth: "admin" }), method(object({
16887
+ collection: string$2().min(1),
16888
+ expectRows: number().int().nonnegative()
16889
+ }), object({
16890
+ dropped: literal(true),
16891
+ rows: number().int().nonnegative()
16892
+ }), {
16893
+ kind: "mutation",
16894
+ auth: "admin"
16895
+ }), method(object({
16896
+ owner: string$2().min(1).optional(),
16897
+ /** `false` skips the per-kind row count (a catalog read only). Default true. */
16898
+ counts: boolean().optional()
16899
+ }), object({ kinds: array(StorageKindSchema) }), { auth: "admin" }), method(RecordQueryInputSchema.extend({
16900
+ owner: string$2().min(1),
16901
+ kind: RecordKindNameSchema
16902
+ }), RecordQueryResultSchema, { auth: "admin" }), method(object({
16903
+ owner: string$2().min(1),
16904
+ kind: RecordKindNameSchema,
16905
+ records: array(RecordInputSchema).max(RECORD_BATCH_MAX),
16906
+ /** The LAST batch: the copy is complete, the boot guard stops asking. */
16907
+ complete: boolean().optional()
16908
+ }).refine((input) => input.records.length > 0 || input.complete === true, { message: "records must be non-empty unless complete is true" }), object({ adopted: number().int() }), {
16909
+ kind: "mutation",
16910
+ auth: "admin"
16911
+ }), method(object({
16912
+ collection: string$2().min(1),
16913
+ cursor: string$2().optional(),
16914
+ limit: number().int().min(1).max(1e3).optional()
16915
+ }), object({
16916
+ rows: array(object({
16917
+ id: string$2(),
16918
+ data: record(string$2(), unknown())
16919
+ })),
16920
+ nextCursor: string$2().nullable()
16921
+ }), { auth: "admin" }), method(object({ collection: string$2().min(1) }), object({ adopted: boolean() }), { auth: "admin" });
16922
+ /**
16923
+ * record-entries - the ONE admin surface for every list of user-created entries
16924
+ * (D881): notification targets, brokers, LLM profiles, anything an addon
16925
+ * declares as an ENTRY kind (`entry: { title }` in `defineRecordKinds`).
16926
+ *
16927
+ * The UI is generic. `listEntryKinds` hands it, per kind, the JSON Schema of
16928
+ * the entry body with `secret: true` on every credential field, so a password
16929
+ * field is derived from the schema and never from a name. `putEntry` takes the
16930
+ * redaction token for an untouched secret (the stored value is kept), a string
16931
+ * for a new one, and the clear instruction to remove one. A read never carries
16932
+ * a secret value, and a locked keychain refuses the write with
16933
+ * `records/secret-unavailable` instead of storing plaintext.
16934
+ *
16935
+ * Hub-only, served in-process (it acts for each entry's owner on the keychain).
16936
+ */
16937
+ var EntryKindInfoSchema = object({
16938
+ owner: string$2(),
16939
+ kind: RecordKindNameSchema,
16940
+ title: string$2(),
16941
+ nameField: string$2(),
16942
+ /** JSON Schema of the body; `secret: true` marks a password field. */
16943
+ fields: record(string$2(), unknown()),
16944
+ secretPaths: array(string$2()),
16945
+ rows: number().int().nonnegative()
16946
+ });
16947
+ var EntryViewSchema = object({
16948
+ id: RecordIdSchema,
16949
+ name: string$2(),
16950
+ rev: number().int(),
16951
+ updatedAt: number(),
16952
+ /** Secret fields hold the redaction token. */
16953
+ data: RecordBodySchema
16954
+ });
16955
+ var EntryAddress = {
16956
+ owner: string$2().min(1),
16957
+ kind: RecordKindNameSchema
16958
+ };
16959
+ method(object({}), object({ kinds: array(EntryKindInfoSchema) }), { auth: "admin" }), method(object({ ...EntryAddress }), object({ entries: array(EntryViewSchema) }), { auth: "admin" }), method(object({
16960
+ ...EntryAddress,
16961
+ id: RecordIdSchema.optional(),
16962
+ data: RecordBodySchema,
16963
+ ifRev: number().int().min(1).optional()
16964
+ }), object({
16965
+ id: string$2(),
16966
+ rev: number().int()
16967
+ }), {
16968
+ kind: "mutation",
16969
+ auth: "admin"
16970
+ }), method(object({
16971
+ ...EntryAddress,
16972
+ id: RecordIdSchema
16973
+ }), object({ deleted: boolean() }), {
16974
+ kind: "mutation",
16975
+ auth: "admin"
16976
+ });
16977
+ /**
16067
16978
  * `keychain` — the hub's encrypted store of secret values (D787).
16068
16979
  *
16069
16980
  * Settings blobs never hold a secret: they hold a marker
@@ -16604,6 +17515,16 @@ method(object({}), KeychainStatusSchema, { auth: "admin" }), method(object({}),
16604
17515
  kind: "mutation",
16605
17516
  auth: "admin",
16606
17517
  caller: "required"
17518
+ }), method(object({
17519
+ ref: string$2().min(1),
17520
+ value: string$2().min(1)
17521
+ }), object({
17522
+ ref: string$2(),
17523
+ version: number().int()
17524
+ }), {
17525
+ kind: "mutation",
17526
+ auth: "admin",
17527
+ caller: "required"
16607
17528
  }), method(object({ refs: array(string$2().min(1)).max(1e3) }), object({
16608
17529
  deleted: array(string$2()).readonly(),
16609
17530
  kept: array(object({
@@ -39282,6 +40203,9 @@ method(LlmGenerateBaseInputSchema, LlmGenerateResultSchema, {
39282
40203
  }), _void(), { kind: "mutation" }), method(object({}), array(LlmProfileKindDescriptorSchema)), method(object({}), array(LlmProfileSchema)), method(object({ profile: LlmProfileSchema }), LlmProfileSchema, {
39283
40204
  kind: "mutation",
39284
40205
  auth: "admin"
40206
+ }), method(RawSecretMigrationInputSchema, RawSecretMigrationReportSchema, {
40207
+ kind: "mutation",
40208
+ auth: "admin"
39285
40209
  }), method(ProfileRefInputSchema, _void(), {
39286
40210
  kind: "mutation",
39287
40211
  auth: "admin"
@@ -49791,6 +50715,41 @@ var ServerRollbackInfoSchema = object({
49791
50715
  atMs: number(),
49792
50716
  reason: string$2()
49793
50717
  });
50718
+ /**
50719
+ * The runner boot check (D877): the runners this node PLANNED (hub: one per
50720
+ * `resolveRunnerId` over its forked addons; agent: the runners its process
50721
+ * service holds, because only the hub plans) against the states the process
50722
+ * service reports. Kept in memory, recomputed by the same one-shot check after
50723
+ * every boot, served on `getServerPackageStatus`.
50724
+ *
50725
+ * `failed` is the D6 breaker's terminal state, `refused` a deterministic Init
50726
+ * refusal (an addon that said "I will not start, and here is why"), `missing` a
50727
+ * planned runner the process service has no entry for.
50728
+ */
50729
+ var RunnerRefusalSchema = object({
50730
+ runnerId: string$2(),
50731
+ addonIds: array(string$2()),
50732
+ reason: string$2()
50733
+ });
50734
+ var RunnerBootCheckSchema = object({
50735
+ checkedAtMs: number(),
50736
+ /** Runners planned for this node. */
50737
+ expected: number(),
50738
+ /** Planned runners whose process is `running`. */
50739
+ running: number(),
50740
+ failed: array(string$2()),
50741
+ refused: array(RunnerRefusalSchema),
50742
+ missing: array(string$2()),
50743
+ /**
50744
+ * Runners still on their way: `starting`, or `crashed` waiting on a backoff
50745
+ * respawn. The check is FINAL only when this is empty; until then nothing is
50746
+ * pushed and the verdict is re-evaluated on the next runner state change.
50747
+ * Optional for version skew (absent = settled).
50748
+ */
50749
+ pending: array(string$2()).optional(),
50750
+ /** True when the plan is the hub's (`missing` is then meaningful); false on an agent. */
50751
+ planKnown: boolean()
50752
+ });
49794
50753
  var ServerPackageStatusSchema = object({
49795
50754
  /** Root package name (`@camstack/server` on the hub). */
49796
50755
  packageName: string$2(),
@@ -49853,7 +50812,14 @@ var ServerPackageStatusSchema = object({
49853
50812
  * for version skew: an older provider's payload simply omits it, and an
49854
50813
  * absent wrapper is unknown — never `native`.
49855
50814
  */
49856
- wrapper: WrapperIdentitySchema.optional()
50815
+ wrapper: WrapperIdentitySchema.optional(),
50816
+ /**
50817
+ * What this node PLANNED to run against what its process service reports
50818
+ * (D877). Absent until the one-shot boot check has run (~60 s after boot) and
50819
+ * on a provider that predates it. Absent is "not checked yet", never "all
50820
+ * well": a consumer that needs the answer treats it as pending.
50821
+ */
50822
+ runners: RunnerBootCheckSchema.optional()
49857
50823
  });
49858
50824
  var ServerUpdateCheckResultSchema = object({
49859
50825
  packageName: string$2(),
@@ -49904,6 +50870,13 @@ var ServerUpdateOutcomeSchema = _enum([
49904
50870
  "refused",
49905
50871
  "failed"
49906
50872
  ]);
50873
+ /** One addon the pre-flight found the target version would refuse (D877). */
50874
+ var UpdateBlockerSchema = object({
50875
+ addonId: string$2(),
50876
+ reason: string$2(),
50877
+ /** What the operator does about it. */
50878
+ remedy: string$2()
50879
+ });
49907
50880
  var ServerUpdateActionResultSchema = object({
49908
50881
  accepted: boolean(),
49909
50882
  targetVersion: string$2().nullable(),
@@ -49921,14 +50894,27 @@ var ServerUpdateActionResultSchema = object({
49921
50894
  * The failure itself, verbatim enough to act on (the npm output for a
49922
50895
  * staging install). Non-null only for `failed`.
49923
50896
  */
49924
- error: string$2().nullable().optional()
50897
+ error: string$2().nullable().optional(),
50898
+ /**
50899
+ * The addons the target version would refuse to start on this node's live
50900
+ * store (D877), present when the pre-flight refused the update
50901
+ * (`reason: 'addon-would-refuse'`). Optional for version skew.
50902
+ */
50903
+ blockers: array(UpdateBlockerSchema).optional()
49925
50904
  });
49926
50905
  method(_void(), ServerPackageStatusSchema, { auth: "admin" }), method(_void(), ServerUpdateCheckResultSchema, {
49927
50906
  kind: "mutation",
49928
50907
  auth: "admin"
49929
- }), method(object({
49930
- /** Explicit target version; omitted = latest from the registry. */
49931
- version: string$2().optional() }), ServerUpdateActionResultSchema, {
50908
+ }), method(object({
50909
+ /** Explicit target version; omitted = latest from the registry. */
50910
+ version: string$2().optional(),
50911
+ /**
50912
+ * Apply even though the pre-flight (D877) found addons the target would
50913
+ * refuse to start. Off by default: those addons stay down until the
50914
+ * remedy is run, which is the incident this gate exists to prevent.
50915
+ */
50916
+ acknowledgeRefusals: boolean().optional()
50917
+ }), ServerUpdateActionResultSchema, {
49932
50918
  kind: "mutation",
49933
50919
  auth: "admin",
49934
50920
  timeoutMs: 16 * 6e4
@@ -52374,7 +53360,9 @@ var ManifestShapeSchema = object({
52374
53360
  var AddonProcessSchema = object({
52375
53361
  pid: number().optional(),
52376
53362
  mode: string$2(),
52377
- state: string$2()
53363
+ state: string$2(),
53364
+ /** Why the runner is `refused` (an addon's own words), when it is (D877). */
53365
+ reason: string$2().optional()
52378
53366
  });
52379
53367
  /**
52380
53368
  * Per-addon health snapshot from the kernel's AddonHealthMonitor.
@@ -53780,6 +54768,12 @@ var ClimateControlStatusSchema = object({
53780
54768
  /** Horizontal louver swing on/off. Null when the device has no
53781
54769
  * horizontal swing surface (gate with `DeviceFeature.ClimateSwingHorizontal`). */
53782
54770
  swingHorizontal: boolean().nullable(),
54771
+ /** Lowest setpoint the device accepts, Celsius. Absent / null = not reported. */
54772
+ minTemp: number().nullable().optional(),
54773
+ /** Highest setpoint the device accepts, Celsius. Absent / null = not reported. */
54774
+ maxTemp: number().nullable().optional(),
54775
+ /** Setpoint granularity, Celsius (0.5, 1). Absent / null = not reported. */
54776
+ tempStep: number().positive().nullable().optional(),
53783
54777
  /** Ms epoch when the slice was last updated (push or command). */
53784
54778
  lastFetchedAt: number()
53785
54779
  });
@@ -56560,7 +57554,19 @@ var TlsStatusSchema = object({
56560
57554
  sans: array(string$2()),
56561
57555
  caCertPem: string$2().nullable(),
56562
57556
  reissueError: string$2().nullable(),
56563
- restartRequired: boolean()
57557
+ restartRequired: boolean(),
57558
+ /** An uploaded certificate is served but no CA is kept for it and it is not publicly signed (D873). */
57559
+ caMissing: boolean(),
57560
+ /** Does the hub's own generated CA carry a critical name constraint? `null` while it has none. */
57561
+ localCaConstrained: boolean().nullable(),
57562
+ /** ISO time the generated CA was replaced by a constrained one; devices must re-download it. */
57563
+ caReplacedAt: string$2().nullable(),
57564
+ /** The uploaded certificate kept on disk, selectable again after "Revert to generated". */
57565
+ storedUpload: object({
57566
+ leafFingerprintSha256: string$2(),
57567
+ validTo: string$2(),
57568
+ hasCa: boolean()
57569
+ }).nullable()
56564
57570
  });
56565
57571
  method(_void(), ListResultSchema), method(_void(), PreferredSchema), method(object({
56566
57572
  /**
@@ -56616,6 +57622,9 @@ method(_void(), ListResultSchema), method(_void(), PreferredSchema), method(obje
56616
57622
  }), method(_void(), object({ pem: string$2() })), method(_void(), TlsStatusSchema, {
56617
57623
  kind: "mutation",
56618
57624
  auth: "admin"
57625
+ }), method(_void(), TlsStatusSchema, {
57626
+ kind: "mutation",
57627
+ auth: "admin"
56619
57628
  });
56620
57629
  var LockControlStatusSchema = object({
56621
57630
  /** Lifecycle state of the lock. `jammed` means the motor reported
@@ -63109,7 +64118,11 @@ method(_void(), array(UserSummarySchema), { auth: "admin" }), method(CreateUserI
63109
64118
  kind: "mutation",
63110
64119
  auth: "admin",
63111
64120
  access: "delete"
63112
- }), method(object({ userId: string$2() }), TotpStatusSchema, { auth: "admin" }), method(object({
64121
+ }), method(object({ userId: string$2() }), TotpStatusSchema, { auth: "admin" }), method(RawSecretMigrationInputSchema, RawSecretMigrationReportSchema, {
64122
+ kind: "mutation",
64123
+ auth: "admin",
64124
+ access: "create"
64125
+ }), method(object({
63113
64126
  userId: string$2(),
63114
64127
  code: string$2()
63115
64128
  }), object({ valid: boolean() }), {
@@ -64921,13 +65934,14 @@ var BaseDevice = class {
64921
65934
  get state() {
64922
65935
  if (!this._stateProxyCache) {
64923
65936
  const cache = {};
64924
- const handler = { get: (_target, key) => {
65937
+ const handler = { get: (target, key) => {
64925
65938
  const k = key;
64926
- if (k in cache) return cache[k];
65939
+ const existing = Reflect.get(target, k);
65940
+ if (existing !== void 0) return existing;
64927
65941
  const cap = DEVICE_LOCAL_STATE_CAPS[k];
64928
65942
  if (!cap) return void 0;
64929
65943
  const proxy = this.sliceProxy(cap);
64930
- cache[k] = proxy;
65944
+ Reflect.set(target, k, proxy);
64931
65945
  return proxy;
64932
65946
  } };
64933
65947
  this._stateProxyCache = new Proxy(cache, handler);
@@ -65126,7 +66140,7 @@ var BaseDevice = class {
65126
66140
  async updateSourceInfo(patch) {
65127
66141
  const next = mergeSourceInfo(this.sourceInfo, patch);
65128
66142
  this._sourceInfoCache = Object.freeze({ ...next });
65129
- const action = this.ctx.api?.deviceManager?.setMetadata;
66143
+ const action = this.ctx.api.deviceManager?.setMetadata;
65130
66144
  if (action) try {
65131
66145
  await action.mutate({
65132
66146
  deviceId: this.id,
@@ -65161,7 +66175,7 @@ var BaseDevice = class {
65161
66175
  * device boot on a meta refresh.
65162
66176
  */
65163
66177
  async refreshFeatures() {
65164
- const action = this.ctx.api?.deviceManager?.registerDevice;
66178
+ const action = this.ctx.api.deviceManager?.registerDevice;
65165
66179
  if (!action) return;
65166
66180
  try {
65167
66181
  await action.mutate({
@@ -67235,6 +68249,12 @@ Object.freeze({
67235
68249
  addonId: null,
67236
68250
  access: "view"
67237
68251
  },
68252
+ "coreBlocks.migrateRawSecrets": {
68253
+ capName: "core-blocks",
68254
+ capScope: "system",
68255
+ addonId: null,
68256
+ access: "create"
68257
+ },
67238
68258
  "coreBlocks.restart": {
67239
68259
  capName: "core-blocks",
67240
68260
  capScope: "system",
@@ -68921,6 +69941,12 @@ Object.freeze({
68921
69941
  addonId: null,
68922
69942
  access: "create"
68923
69943
  },
69944
+ "keychainAdmin.importSecret": {
69945
+ capName: "keychain-admin",
69946
+ capScope: "system",
69947
+ addonId: null,
69948
+ access: "create"
69949
+ },
68924
69950
  "keychainAdmin.listAudit": {
68925
69951
  capName: "keychain-admin",
68926
69952
  capScope: "system",
@@ -69089,6 +70115,12 @@ Object.freeze({
69089
70115
  addonId: null,
69090
70116
  access: "view"
69091
70117
  },
70118
+ "llm.migrateRawSecrets": {
70119
+ capName: "llm",
70120
+ capScope: "system",
70121
+ addonId: null,
70122
+ access: "create"
70123
+ },
69092
70124
  "llm.resolveModelRef": {
69093
70125
  capName: "llm",
69094
70126
  capScope: "system",
@@ -69317,6 +70349,12 @@ Object.freeze({
69317
70349
  addonId: null,
69318
70350
  access: "create"
69319
70351
  },
70352
+ "localNetwork.useStoredUploadedCertificate": {
70353
+ capName: "local-network",
70354
+ capScope: "system",
70355
+ addonId: null,
70356
+ access: "create"
70357
+ },
69320
70358
  "lockControl.getStatus": {
69321
70359
  capName: "lock-control",
69322
70360
  capScope: "device",
@@ -71969,6 +73007,30 @@ Object.freeze({
71969
73007
  addonId: null,
71970
73008
  access: "create"
71971
73009
  },
73010
+ "recordEntries.deleteEntry": {
73011
+ capName: "record-entries",
73012
+ capScope: "system",
73013
+ addonId: null,
73014
+ access: "delete"
73015
+ },
73016
+ "recordEntries.listEntries": {
73017
+ capName: "record-entries",
73018
+ capScope: "system",
73019
+ addonId: null,
73020
+ access: "view"
73021
+ },
73022
+ "recordEntries.listEntryKinds": {
73023
+ capName: "record-entries",
73024
+ capScope: "system",
73025
+ addonId: null,
73026
+ access: "view"
73027
+ },
73028
+ "recordEntries.putEntry": {
73029
+ capName: "record-entries",
73030
+ capScope: "system",
73031
+ addonId: null,
73032
+ access: "create"
73033
+ },
71972
73034
  "recording.getAvailability": {
71973
73035
  capName: "recording",
71974
73036
  capScope: "device",
@@ -72269,6 +73331,102 @@ Object.freeze({
72269
73331
  addonId: null,
72270
73332
  access: "view"
72271
73333
  },
73334
+ "records.aggregate": {
73335
+ capName: "records",
73336
+ capScope: "system",
73337
+ addonId: null,
73338
+ access: "view"
73339
+ },
73340
+ "records.allocateId": {
73341
+ capName: "records",
73342
+ capScope: "system",
73343
+ addonId: null,
73344
+ access: "create"
73345
+ },
73346
+ "records.count": {
73347
+ capName: "records",
73348
+ capScope: "system",
73349
+ addonId: null,
73350
+ access: "view"
73351
+ },
73352
+ "records.declareKinds": {
73353
+ capName: "records",
73354
+ capScope: "system",
73355
+ addonId: null,
73356
+ access: "create"
73357
+ },
73358
+ "records.delete": {
73359
+ capName: "records",
73360
+ capScope: "system",
73361
+ addonId: null,
73362
+ access: "delete"
73363
+ },
73364
+ "records.deleteDevice": {
73365
+ capName: "records",
73366
+ capScope: "system",
73367
+ addonId: null,
73368
+ access: "delete"
73369
+ },
73370
+ "records.deleteMany": {
73371
+ capName: "records",
73372
+ capScope: "system",
73373
+ addonId: null,
73374
+ access: "delete"
73375
+ },
73376
+ "records.deleteWhere": {
73377
+ capName: "records",
73378
+ capScope: "system",
73379
+ addonId: null,
73380
+ access: "delete"
73381
+ },
73382
+ "records.get": {
73383
+ capName: "records",
73384
+ capScope: "system",
73385
+ addonId: null,
73386
+ access: "view"
73387
+ },
73388
+ "records.getMany": {
73389
+ capName: "records",
73390
+ capScope: "system",
73391
+ addonId: null,
73392
+ access: "view"
73393
+ },
73394
+ "records.histogram": {
73395
+ capName: "records",
73396
+ capScope: "system",
73397
+ addonId: null,
73398
+ access: "view"
73399
+ },
73400
+ "records.patch": {
73401
+ capName: "records",
73402
+ capScope: "system",
73403
+ addonId: null,
73404
+ access: "create"
73405
+ },
73406
+ "records.put": {
73407
+ capName: "records",
73408
+ capScope: "system",
73409
+ addonId: null,
73410
+ access: "create"
73411
+ },
73412
+ "records.putMany": {
73413
+ capName: "records",
73414
+ capScope: "system",
73415
+ addonId: null,
73416
+ access: "create"
73417
+ },
73418
+ "records.query": {
73419
+ capName: "records",
73420
+ capScope: "system",
73421
+ addonId: null,
73422
+ access: "view"
73423
+ },
73424
+ "records.secretRefs": {
73425
+ capName: "records",
73426
+ capScope: "system",
73427
+ addonId: null,
73428
+ access: "view"
73429
+ },
72272
73430
  "sceneMonitor.captureReference": {
72273
73431
  capName: "scene-monitor",
72274
73432
  capScope: "device",
@@ -72701,6 +73859,48 @@ Object.freeze({
72701
73859
  addonId: null,
72702
73860
  access: "create"
72703
73861
  },
73862
+ "storageAdmin.adoptRecords": {
73863
+ capName: "storage-admin",
73864
+ capScope: "system",
73865
+ addonId: null,
73866
+ access: "create"
73867
+ },
73868
+ "storageAdmin.dropCollection": {
73869
+ capName: "storage-admin",
73870
+ capScope: "system",
73871
+ addonId: null,
73872
+ access: "delete"
73873
+ },
73874
+ "storageAdmin.isAdoptedLegacyTable": {
73875
+ capName: "storage-admin",
73876
+ capScope: "system",
73877
+ addonId: null,
73878
+ access: "view"
73879
+ },
73880
+ "storageAdmin.listKinds": {
73881
+ capName: "storage-admin",
73882
+ capScope: "system",
73883
+ addonId: null,
73884
+ access: "view"
73885
+ },
73886
+ "storageAdmin.listTables": {
73887
+ capName: "storage-admin",
73888
+ capScope: "system",
73889
+ addonId: null,
73890
+ access: "view"
73891
+ },
73892
+ "storageAdmin.readLegacyCollection": {
73893
+ capName: "storage-admin",
73894
+ capScope: "system",
73895
+ addonId: null,
73896
+ access: "view"
73897
+ },
73898
+ "storageAdmin.readRecords": {
73899
+ capName: "storage-admin",
73900
+ capScope: "system",
73901
+ addonId: null,
73902
+ access: "view"
73903
+ },
72704
73904
  "storageEvictable.evict": {
72705
73905
  capName: "storage-evictable",
72706
73906
  capScope: "system",
@@ -73613,6 +74813,12 @@ Object.freeze({
73613
74813
  addonId: null,
73614
74814
  access: "view"
73615
74815
  },
74816
+ "userManagement.migrateRawSecrets": {
74817
+ capName: "user-management",
74818
+ capScope: "system",
74819
+ addonId: null,
74820
+ access: "create"
74821
+ },
73616
74822
  "userManagement.oauthExchangeCode": {
73617
74823
  capName: "user-management",
73618
74824
  capScope: "system",
@@ -76289,6 +77495,37 @@ Object.freeze({
76289
77495
  form: "single",
76290
77496
  optional: false
76291
77497
  }],
77498
+ "records.count": [{
77499
+ name: "deviceId",
77500
+ form: "single",
77501
+ optional: true
77502
+ }],
77503
+ "records.deleteDevice": [{
77504
+ name: "deviceId",
77505
+ form: "single",
77506
+ optional: false
77507
+ }],
77508
+ "records.deleteWhere": [{
77509
+ name: "deviceId",
77510
+ form: "single",
77511
+ optional: true
77512
+ }],
77513
+ "records.histogram": [{
77514
+ name: "deviceId",
77515
+ form: "single",
77516
+ optional: true
77517
+ }],
77518
+ "records.putMany": [{
77519
+ name: "records",
77520
+ form: "object-array",
77521
+ optional: false,
77522
+ itemField: "deviceId"
77523
+ }],
77524
+ "records.query": [{
77525
+ name: "deviceId",
77526
+ form: "single",
77527
+ optional: true
77528
+ }],
76292
77529
  "sceneMonitor.captureReference": [{
76293
77530
  name: "deviceId",
76294
77531
  form: "single",
@@ -76405,6 +77642,17 @@ Object.freeze({
76405
77642
  form: "single",
76406
77643
  optional: false
76407
77644
  }],
77645
+ "storageAdmin.adoptRecords": [{
77646
+ name: "records",
77647
+ form: "object-array",
77648
+ optional: false,
77649
+ itemField: "deviceId"
77650
+ }],
77651
+ "storageAdmin.readRecords": [{
77652
+ name: "deviceId",
77653
+ form: "single",
77654
+ optional: true
77655
+ }],
76408
77656
  "streamBroker.acquireEgressTranscode": [{
76409
77657
  name: "deviceId",
76410
77658
  form: "single",
@@ -187810,13 +189058,15 @@ var matterConnectionSchema = object({
187810
189058
  /** PULL-reconcile interval for the commissioned-node inventory. */
187811
189059
  reconcileIntervalMs: preprocess((v) => v === "" || v === null ? void 0 : v, number().int().min(1e4).max(864e5).default(3e5)).describe("Node-inventory reconcile interval (ms)")
187812
189060
  });
187813
- /** Top-level addon config — an ordered list of broker entries (default empty). */
187814
- var matterAddonConfigSchema = object({ brokers: array(object({
189061
+ /** A single registered Matter fabric ("broker"). */
189062
+ var MatterBrokerEntrySchema = object({
187815
189063
  id: string$2().min(1),
187816
189064
  name: string$2().min(1),
187817
189065
  connection: matterConnectionSchema,
187818
189066
  integrationId: string$2().optional()
187819
- })).default([]) });
189067
+ });
189068
+ /** Top-level addon config — an ordered list of broker entries (default empty). */
189069
+ var matterAddonConfigSchema = object({ brokers: array(MatterBrokerEntrySchema).default([]) });
187820
189070
  /** Narrow an `unknown` to a shallow plain-object record (cast-free boundary). */
187821
189071
  function toRecord(value) {
187822
189072
  if (typeof value === "object" && value !== null && !Array.isArray(value)) return Object.fromEntries(Object.entries(value));
@@ -188791,6 +190041,70 @@ var MatterNodeDevice = class extends BaseDevice {
188791
190041
  return specs;
188792
190042
  }
188793
190043
  };
190044
+ var matterBrokersEntryKind = defineEntryKind("brokers", {
190045
+ title: "Matter brokers",
190046
+ schema: entryBody({
190047
+ connection: MatterBrokerEntrySchema.shape.connection,
190048
+ integrationId: string$2().optional()
190049
+ }),
190050
+ writeTrigger: "an operator adds, edits or removes a Matter fabric broker",
190051
+ adoptsFrom: settingsBrokersAdoptsFrom("matter-broker")
190052
+ });
190053
+ //#endregion
190054
+ //#region src/matter-broker-store.ts
190055
+ function rowToEntry(id, data) {
190056
+ const parsed = MatterBrokerEntrySchema.safeParse({
190057
+ id,
190058
+ name: data.name,
190059
+ connection: data.connection,
190060
+ integrationId: data.integrationId
190061
+ });
190062
+ return parsed.success ? parsed.data : null;
190063
+ }
190064
+ var MatterBrokerStore = class MatterBrokerStore {
190065
+ kind;
190066
+ constructor(kind) {
190067
+ this.kind = kind;
190068
+ }
190069
+ static of(records) {
190070
+ return new MatterBrokerStore(records.kind(matterBrokersEntryKind));
190071
+ }
190072
+ async listResolved() {
190073
+ const page = await this.kind.query({ limit: 1e3 });
190074
+ const out = [];
190075
+ for (const record of page.records) {
190076
+ let data = record.data;
190077
+ try {
190078
+ const resolved = await this.kind.getResolved(record.id);
190079
+ if (resolved !== null) data = resolved.data;
190080
+ } catch (err) {
190081
+ if (!(err instanceof RecordSecretUnavailableError)) throw err;
190082
+ }
190083
+ const entry = rowToEntry(record.id, data);
190084
+ if (entry !== null) out.push(entry);
190085
+ }
190086
+ return out;
190087
+ }
190088
+ async replaceAll(entries) {
190089
+ const page = await this.kind.query({ limit: 1e3 });
190090
+ const nextIds = new Set(entries.map((e) => e.id));
190091
+ for (const row of page.records) if (!nextIds.has(row.id)) await this.kind.delete(row.id);
190092
+ for (const entry of entries) {
190093
+ const { id, name, connection, integrationId } = entry;
190094
+ const body = {
190095
+ name,
190096
+ connection,
190097
+ ...integrationId === void 0 ? {} : { integrationId }
190098
+ };
190099
+ const parsed = matterBrokersEntryKind.schema.safeParse(body);
190100
+ if (!parsed.success) throw new Error(`invalid Matter broker '${id}': ${parsed.error.message}`);
190101
+ await this.kind.put({
190102
+ id,
190103
+ data: parsed.data
190104
+ });
190105
+ }
190106
+ }
190107
+ };
188794
190108
  //#endregion
188795
190109
  //#region src/addon.ts
188796
190110
  /** Default config — a fresh install starts with no fabric. */
@@ -188815,11 +190129,18 @@ var MatterBrokerAddon = class extends BaseDeviceProvider {
188815
190129
  providerName = "Matter";
188816
190130
  deviceClasses = { [DeviceType.Container]: MatterNodeDevice };
188817
190131
  registry = null;
190132
+ brokerStore = null;
190133
+ activeBrokers = [];
188818
190134
  constructor() {
188819
190135
  super({ ...DEFAULTS });
188820
190136
  }
188821
190137
  async onInitialize() {
188822
190138
  const regs = await super.onInitialize();
190139
+ const records = this.ctx.records;
190140
+ if (records === void 0) throw new Error("matter-broker: ctx.records is required (hub-only addon)");
190141
+ await records.declare({ brokers: matterBrokersEntryKind });
190142
+ this.brokerStore = MatterBrokerStore.of(records);
190143
+ this.activeBrokers = await this.loadPersistedBrokers();
188823
190144
  this.registry = new MatterBrokerRegistry(this.ctx.logger, {
188824
190145
  dataDir: this.ctx.dataDir,
188825
190146
  onBrokerConnected: (brokerId) => {
@@ -188837,8 +190158,8 @@ var MatterBrokerAddon = class extends BaseDeviceProvider {
188837
190158
  }
188838
190159
  });
188839
190160
  matterCommands.setDispatcher((brokerId, invocation) => this.requireRegistry().invokeCommand(brokerId, invocation));
188840
- await this.registry.restore(this.config.brokers);
188841
- this.ctx.logger.info("Matter: broker addon initialised", { meta: { brokerCount: this.config.brokers.length } });
190161
+ await this.registry.restore(this.activeBrokers);
190162
+ this.ctx.logger.info("Matter: broker addon initialised", { meta: { brokerCount: this.activeBrokers.length } });
188842
190163
  await this.reconcileIntegrationsToBrokers();
188843
190164
  this.subscribeIntegrationLifecycle();
188844
190165
  return [
@@ -188853,10 +190174,28 @@ var MatterBrokerAddon = class extends BaseDeviceProvider {
188853
190174
  }
188854
190175
  ];
188855
190176
  }
190177
+ async loadPersistedBrokers() {
190178
+ const store = this.brokerStore;
190179
+ if (store !== null) {
190180
+ const fromRecords = await store.listResolved();
190181
+ if (fromRecords.length > 0) return fromRecords;
190182
+ }
190183
+ return this.config.brokers;
190184
+ }
190185
+ async persistBrokerEntries(entries) {
190186
+ this.activeBrokers = [...entries];
190187
+ const store = this.brokerStore;
190188
+ if (store !== null) {
190189
+ await store.replaceAll(entries);
190190
+ return;
190191
+ }
190192
+ await this.updateGlobalSettings({ brokers: [...entries] });
190193
+ }
188856
190194
  async onConfigChanged() {
188857
190195
  const reg = this.registry;
188858
190196
  if (!reg) return;
188859
- const persisted = this.config.brokers;
190197
+ this.activeBrokers = await this.loadPersistedBrokers();
190198
+ const persisted = this.activeBrokers;
188860
190199
  const liveIds = new Set(reg.list().map((b) => b.id));
188861
190200
  const persistedIds = new Set(persisted.map((e) => e.id));
188862
190201
  for (const liveId of liveIds) if (!persistedIds.has(liveId)) try {
@@ -188887,7 +190226,7 @@ var MatterBrokerAddon = class extends BaseDeviceProvider {
188887
190226
  ...b,
188888
190227
  id: created.id
188889
190228
  } : b);
188890
- await this.updateGlobalSettings({ brokers: next });
190229
+ await this.persistBrokerEntries(next);
188891
190230
  }
188892
190231
  } catch (err) {
188893
190232
  this.ctx.logger.warn("Matter onConfigChanged: failed to start new broker", { meta: {
@@ -188968,8 +190307,8 @@ var MatterBrokerAddon = class extends BaseDeviceProvider {
188968
190307
  return buildMatterBrokerProvider({
188969
190308
  ownerAddonId: this.ctx.id,
188970
190309
  registry: this.requireRegistry(),
188971
- getBrokers: () => this.config.brokers,
188972
- persistBrokers: (brokers) => this.updateGlobalSettings({ brokers: [...brokers] }),
190310
+ getBrokers: () => this.activeBrokers,
190311
+ persistBrokers: (brokers) => this.persistBrokerEntries(brokers),
188973
190312
  cascadeRemoveDevices: (brokerId) => this.cascadeRemoveDevicesForBroker(brokerId),
188974
190313
  logger: this.ctx.logger
188975
190314
  });
@@ -188994,7 +190333,7 @@ var MatterBrokerAddon = class extends BaseDeviceProvider {
188994
190333
  const settings = await this.ctx.api.integrations.getSettings.query({ id: integration.id });
188995
190334
  const brokerId = typeof settings["brokerId"] === "string" ? settings["brokerId"] : void 0;
188996
190335
  if (brokerId === void 0) continue;
188997
- if (!this.config.brokers.some((b) => b.id === brokerId)) {
190336
+ if (!this.activeBrokers.some((b) => b.id === brokerId)) {
188998
190337
  this.ctx.logger.warn("Matter integration→broker: linked broker not found", { meta: {
188999
190338
  integrationId: integration.id,
189000
190339
  brokerId
@@ -189003,7 +190342,7 @@ var MatterBrokerAddon = class extends BaseDeviceProvider {
189003
190342
  }
189004
190343
  this.requireRegistry().linkIntegration(integration.id, brokerId);
189005
190344
  }
189006
- const toRemove = this.config.brokers.filter((b) => b.integrationId !== void 0 && !surviving.has(b.integrationId)).map((b) => b.id);
190345
+ const toRemove = this.activeBrokers.filter((b) => b.integrationId !== void 0 && !surviving.has(b.integrationId)).map((b) => b.id);
189007
190346
  if (toRemove.length === 0) return;
189008
190347
  for (const id of toRemove) try {
189009
190348
  await this.requireRegistry().removeEntry(id);
@@ -189014,8 +190353,8 @@ var MatterBrokerAddon = class extends BaseDeviceProvider {
189014
190353
  error: errMsg(err)
189015
190354
  } });
189016
190355
  }
189017
- const nextBrokers = this.config.brokers.filter((b) => !toRemove.includes(b.id));
189018
- await this.updateGlobalSettings({ brokers: nextBrokers });
190356
+ const nextBrokers = this.activeBrokers.filter((b) => !toRemove.includes(b.id));
190357
+ await this.persistBrokerEntries(nextBrokers);
189019
190358
  } catch (err) {
189020
190359
  this.ctx.logger.warn("Matter integration→broker reconcile failed", { meta: { error: errMsg(err) } });
189021
190360
  }