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