@camstack/addon-import-alexa 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 +1468 -131
  2. package/dist/addon.mjs +1468 -131
  3. package/package.json +1 -1
package/dist/addon.js CHANGED
@@ -38,7 +38,7 @@ let node_os = require("node:os");
38
38
  let node_fs = require("node:fs");
39
39
  let node_path = require("node:path");
40
40
  node_path = __toESM(node_path);
41
- //#region ../types/dist/event-category-C4hVnRo8.mjs
41
+ //#region ../types/dist/event-category-BvOFi6PY.mjs
42
42
  var EventCategory = /* @__PURE__ */ function(EventCategory) {
43
43
  EventCategory["SystemBoot"] = "system.boot";
44
44
  EventCategory["SystemAddonsReady"] = "system.addons-ready";
@@ -102,6 +102,24 @@ var EventCategory = /* @__PURE__ */ function(EventCategory) {
102
102
  * consumes this category and maps it to the `addon-crash-loop` kind.
103
103
  */
104
104
  EventCategory["AddonRunnerFailed"] = "addon.runner-failed";
105
+ /**
106
+ * A runner whose addon refused to start with a typed reason (D877) - parked
107
+ * in `refused`, never counted by the crash breaker, retried on operator
108
+ * action. One event per refusal.
109
+ */
110
+ EventCategory["AddonRunnerRefused"] = "addon.runner-refused";
111
+ /**
112
+ * A runner settled on a state (D877): `running` (READY), `crashed`, `failed` or
113
+ * `refused`. In-process telemetry for the boot check (re-evaluate while any
114
+ * runner is still pending) and the alert centre (close a recovered runner).
115
+ */
116
+ EventCategory["ProcessStateChanged"] = "process.state-changed";
117
+ /**
118
+ * The node's one-shot runner boot check (D877): planned runners against the
119
+ * process service, `degraded` when any is failed, refused or missing. The
120
+ * alert centre turns it into one alert and a direct critical push.
121
+ */
122
+ EventCategory["SystemRunnerCheck"] = "system.runner-check";
105
123
  EventCategory["AddonError"] = "addon.error";
106
124
  EventCategory["AddonPageReady"] = "addon.page-ready";
107
125
  EventCategory["AddonWidgetReady"] = "addon.widget-ready";
@@ -4144,6 +4162,12 @@ var numberProcessor = (schema, ctx, _json, _params) => {
4144
4162
  var booleanProcessor = (_schema, _ctx, json, _params) => {
4145
4163
  json.type = "boolean";
4146
4164
  };
4165
+ var bigintProcessor = (_schema, ctx, _json, _params) => {
4166
+ if (ctx.unrepresentable === "throw") throw new Error("BigInt cannot be represented in JSON Schema");
4167
+ };
4168
+ var symbolProcessor = (_schema, ctx, _json, _params) => {
4169
+ if (ctx.unrepresentable === "throw") throw new Error("Symbols cannot be represented in JSON Schema");
4170
+ };
4147
4171
  var nullProcessor = (_schema, ctx, json, _params) => {
4148
4172
  if (ctx.target === "openapi-3.0") {
4149
4173
  json.type = "string";
@@ -4151,12 +4175,17 @@ var nullProcessor = (_schema, ctx, json, _params) => {
4151
4175
  json.enum = [null];
4152
4176
  } else json.type = "null";
4153
4177
  };
4178
+ var undefinedProcessor = (_schema, ctx, _json, _params) => {
4179
+ if (ctx.unrepresentable === "throw") throw new Error("Undefined cannot be represented in JSON Schema");
4180
+ };
4154
4181
  var voidProcessor = (_schema, ctx, _json, _params) => {
4155
4182
  if (ctx.unrepresentable === "throw") throw new Error("Void cannot be represented in JSON Schema");
4156
4183
  };
4157
4184
  var neverProcessor = (_schema, _ctx, json, _params) => {
4158
4185
  json.not = {};
4159
4186
  };
4187
+ var anyProcessor = (_schema, _ctx, _json, _params) => {};
4188
+ var unknownProcessor = (_schema, _ctx, _json, _params) => {};
4160
4189
  var dateProcessor = (_schema, ctx, _json, _params) => {
4161
4190
  if (ctx.unrepresentable === "throw") throw new Error("Date cannot be represented in JSON Schema");
4162
4191
  };
@@ -4188,12 +4217,53 @@ var literalProcessor = (schema, ctx, json, _params) => {
4188
4217
  json.enum = vals;
4189
4218
  }
4190
4219
  };
4220
+ var nanProcessor = (_schema, ctx, _json, _params) => {
4221
+ if (ctx.unrepresentable === "throw") throw new Error("NaN cannot be represented in JSON Schema");
4222
+ };
4223
+ var templateLiteralProcessor = (schema, _ctx, json, _params) => {
4224
+ const _json = json;
4225
+ const pattern = schema._zod.pattern;
4226
+ if (!pattern) throw new Error("Pattern not found in template literal");
4227
+ _json.type = "string";
4228
+ _json.pattern = pattern.source;
4229
+ };
4230
+ var fileProcessor = (schema, _ctx, json, _params) => {
4231
+ const _json = json;
4232
+ const file = {
4233
+ type: "string",
4234
+ format: "binary",
4235
+ contentEncoding: "binary"
4236
+ };
4237
+ const { minimum, maximum, mime } = schema._zod.bag;
4238
+ if (minimum !== void 0) file.minLength = minimum;
4239
+ if (maximum !== void 0) file.maxLength = maximum;
4240
+ if (mime) if (mime.length === 1) {
4241
+ file.contentMediaType = mime[0];
4242
+ Object.assign(_json, file);
4243
+ } else {
4244
+ Object.assign(_json, file);
4245
+ _json.anyOf = mime.map((m) => ({ contentMediaType: m }));
4246
+ }
4247
+ else Object.assign(_json, file);
4248
+ };
4249
+ var successProcessor = (_schema, _ctx, json, _params) => {
4250
+ json.type = "boolean";
4251
+ };
4191
4252
  var customProcessor = (_schema, ctx, _json, _params) => {
4192
4253
  if (ctx.unrepresentable === "throw") throw new Error("Custom types cannot be represented in JSON Schema");
4193
4254
  };
4255
+ var functionProcessor = (_schema, ctx, _json, _params) => {
4256
+ if (ctx.unrepresentable === "throw") throw new Error("Function types cannot be represented in JSON Schema");
4257
+ };
4194
4258
  var transformProcessor = (_schema, ctx, _json, _params) => {
4195
4259
  if (ctx.unrepresentable === "throw") throw new Error("Transforms cannot be represented in JSON Schema");
4196
4260
  };
4261
+ var mapProcessor = (_schema, ctx, _json, _params) => {
4262
+ if (ctx.unrepresentable === "throw") throw new Error("Map cannot be represented in JSON Schema");
4263
+ };
4264
+ var setProcessor = (_schema, ctx, _json, _params) => {
4265
+ if (ctx.unrepresentable === "throw") throw new Error("Set cannot be represented in JSON Schema");
4266
+ };
4197
4267
  var arrayProcessor = (schema, ctx, _json, params) => {
4198
4268
  const json = _json;
4199
4269
  const def = schema._zod.def;
@@ -4398,6 +4468,12 @@ var readonlyProcessor = (schema, ctx, json, params) => {
4398
4468
  seen.ref = def.innerType;
4399
4469
  json.readOnly = true;
4400
4470
  };
4471
+ var promiseProcessor = (schema, ctx, _json, params) => {
4472
+ const def = schema._zod.def;
4473
+ process$1(def.innerType, ctx, params);
4474
+ const seen = ctx.seen.get(schema);
4475
+ seen.ref = def.innerType;
4476
+ };
4401
4477
  var optionalProcessor = (schema, ctx, _json, params) => {
4402
4478
  const def = schema._zod.def;
4403
4479
  process$1(def.innerType, ctx, params);
@@ -4410,6 +4486,81 @@ var lazyProcessor = (schema, ctx, _json, params) => {
4410
4486
  const seen = ctx.seen.get(schema);
4411
4487
  seen.ref = innerType;
4412
4488
  };
4489
+ var allProcessors = {
4490
+ string: stringProcessor,
4491
+ number: numberProcessor,
4492
+ boolean: booleanProcessor,
4493
+ bigint: bigintProcessor,
4494
+ symbol: symbolProcessor,
4495
+ null: nullProcessor,
4496
+ undefined: undefinedProcessor,
4497
+ void: voidProcessor,
4498
+ never: neverProcessor,
4499
+ any: anyProcessor,
4500
+ unknown: unknownProcessor,
4501
+ date: dateProcessor,
4502
+ enum: enumProcessor,
4503
+ literal: literalProcessor,
4504
+ nan: nanProcessor,
4505
+ template_literal: templateLiteralProcessor,
4506
+ file: fileProcessor,
4507
+ success: successProcessor,
4508
+ custom: customProcessor,
4509
+ function: functionProcessor,
4510
+ transform: transformProcessor,
4511
+ map: mapProcessor,
4512
+ set: setProcessor,
4513
+ array: arrayProcessor,
4514
+ object: objectProcessor,
4515
+ union: unionProcessor,
4516
+ intersection: intersectionProcessor,
4517
+ tuple: tupleProcessor,
4518
+ record: recordProcessor,
4519
+ nullable: nullableProcessor,
4520
+ nonoptional: nonoptionalProcessor,
4521
+ default: defaultProcessor,
4522
+ prefault: prefaultProcessor,
4523
+ catch: catchProcessor,
4524
+ pipe: pipeProcessor,
4525
+ readonly: readonlyProcessor,
4526
+ promise: promiseProcessor,
4527
+ optional: optionalProcessor,
4528
+ lazy: lazyProcessor
4529
+ };
4530
+ function toJSONSchema(input, params) {
4531
+ if ("_idmap" in input) {
4532
+ const registry = input;
4533
+ const ctx = initializeContext({
4534
+ ...params,
4535
+ processors: allProcessors
4536
+ });
4537
+ const defs = {};
4538
+ for (const entry of registry._idmap.entries()) {
4539
+ const [_, schema] = entry;
4540
+ process$1(schema, ctx);
4541
+ }
4542
+ const schemas = {};
4543
+ ctx.external = {
4544
+ registry,
4545
+ uri: params?.uri,
4546
+ defs
4547
+ };
4548
+ for (const entry of registry._idmap.entries()) {
4549
+ const [key, schema] = entry;
4550
+ extractDefs(ctx, schema);
4551
+ schemas[key] = finalize(ctx, schema);
4552
+ }
4553
+ if (Object.keys(defs).length > 0) schemas.__shared = { [ctx.target === "draft-2020-12" ? "$defs" : "definitions"]: defs };
4554
+ return { schemas };
4555
+ }
4556
+ const ctx = initializeContext({
4557
+ ...params,
4558
+ processors: allProcessors
4559
+ });
4560
+ process$1(input, ctx);
4561
+ extractDefs(ctx, input);
4562
+ return finalize(ctx, input);
4563
+ }
4413
4564
  //#endregion
4414
4565
  //#region ../../node_modules/zod/v4/classic/iso.js
4415
4566
  var ZodISODateTime = /*@__PURE__*/ $constructor("ZodISODateTime", (inst, def) => {
@@ -5426,7 +5577,7 @@ var ZodIssueCode = {
5426
5577
  var ZodFirstPartyTypeKind;
5427
5578
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
5428
5579
  //#endregion
5429
- //#region ../types/dist/sleep-DRqxtc0C.mjs
5580
+ //#region ../types/dist/sleep-bZIhUvjd.mjs
5430
5581
  /**
5431
5582
  * The audio chunk plane's byte format, and the ONE expansion from a coded
5432
5583
  * window to float samples (D455).
@@ -5543,7 +5694,7 @@ function isKeychainStoredField(field) {
5543
5694
  var SECRET_CLEAR = { $secretClear: true };
5544
5695
  /** The `'***'` token D634 redaction writes for non-admins. */
5545
5696
  var LEGACY_DEVICE_REDACTION = "***";
5546
- function isRecord$2(value) {
5697
+ function isRecord$5(value) {
5547
5698
  return typeof value === "object" && value !== null && !Array.isArray(value);
5548
5699
  }
5549
5700
  function makeSecretMarker(ref) {
@@ -5554,12 +5705,12 @@ function makeSecretMarker(ref) {
5554
5705
  }
5555
5706
  /** A stored marker: an object whose `$secret` is a non-empty string. */
5556
5707
  function isSecretMarker(value) {
5557
- if (!isRecord$2(value)) return false;
5708
+ if (!isRecord$5(value)) return false;
5558
5709
  const ref = value["$secret"];
5559
5710
  return typeof ref === "string" && ref.length > 0;
5560
5711
  }
5561
5712
  function isSecretClear(value) {
5562
- return isRecord$2(value) && value["$secretClear"] === true;
5713
+ return isRecord$5(value) && value["$secretClear"] === true;
5563
5714
  }
5564
5715
  /**
5565
5716
  * The UI view of a stored secret field value: a marker becomes "set", inline
@@ -6169,7 +6320,7 @@ var KeychainWriteRefusedError = class extends Error {
6169
6320
  }
6170
6321
  };
6171
6322
  var KEEP = { kind: "keep" };
6172
- function isRecord$1$1(value) {
6323
+ function isRecord$4(value) {
6173
6324
  return typeof value === "object" && value !== null && !Array.isArray(value);
6174
6325
  }
6175
6326
  function defaultMintId() {
@@ -6182,7 +6333,7 @@ function collectSecretMarkerRefs(value, out = []) {
6182
6333
  return out;
6183
6334
  }
6184
6335
  if (Array.isArray(value)) for (const item of value) collectSecretMarkerRefs(item, out);
6185
- else if (isRecord$1$1(value)) for (const child of Object.values(value)) collectSecretMarkerRefs(child, out);
6336
+ else if (isRecord$4(value)) for (const child of Object.values(value)) collectSecretMarkerRefs(child, out);
6186
6337
  return out;
6187
6338
  }
6188
6339
  async function storedValueEquals(secrets, marker, candidate) {
@@ -6237,7 +6388,7 @@ function rowId(row, idKey) {
6237
6388
  return null;
6238
6389
  }
6239
6390
  async function writeArray(ctx, node, incoming, stored, fieldPath) {
6240
- const storedRows = Array.isArray(stored) ? stored.filter(isRecord$1$1) : [];
6391
+ const storedRows = Array.isArray(stored) ? stored.filter(isRecord$4) : [];
6241
6392
  if (!Array.isArray(incoming)) {
6242
6393
  ctx.deletes.push(...collectSecretMarkerRefs(storedRows));
6243
6394
  return {
@@ -6253,7 +6404,7 @@ async function writeArray(ctx, node, incoming, stored, fieldPath) {
6253
6404
  const kept = /* @__PURE__ */ new Set();
6254
6405
  const rows = [];
6255
6406
  for (const row of incoming) {
6256
- if (!isRecord$1$1(row)) {
6407
+ if (!isRecord$4(row)) {
6257
6408
  rows.push(row);
6258
6409
  continue;
6259
6410
  }
@@ -6278,7 +6429,7 @@ async function writeNode(ctx, node, incoming, stored, fieldPath) {
6278
6429
  case "leaf": return writeLeaf(ctx, incoming, stored, fieldPath);
6279
6430
  case "array": return writeArray(ctx, node, incoming, stored, fieldPath);
6280
6431
  case "object": {
6281
- if (!isRecord$1$1(incoming)) {
6432
+ if (!isRecord$4(incoming)) {
6282
6433
  if (incoming === void 0) return KEEP;
6283
6434
  ctx.deletes.push(...collectSecretMarkerRefs(stored));
6284
6435
  return {
@@ -6286,7 +6437,7 @@ async function writeNode(ctx, node, incoming, stored, fieldPath) {
6286
6437
  value: incoming
6287
6438
  };
6288
6439
  }
6289
- const storedObj = isRecord$1$1(stored) ? stored : {};
6440
+ const storedObj = isRecord$4(stored) ? stored : {};
6290
6441
  return {
6291
6442
  kind: "value",
6292
6443
  value: await writeMembers(ctx, node.children, incoming, storedObj, (m) => `${fieldPath}.${m}`)
@@ -6409,7 +6560,7 @@ async function resolveSecretMarkers(value, secrets, options = {}) {
6409
6560
  value: items
6410
6561
  };
6411
6562
  }
6412
- if (isRecord$1$1(v)) {
6563
+ if (isRecord$4(v)) {
6413
6564
  const out = {};
6414
6565
  for (const [k, child] of Object.entries(v)) {
6415
6566
  const s = substitute(child);
@@ -6677,7 +6828,6 @@ function createHandle(raw, opts) {
6677
6828
  const writeAddon = (patch) => write("addon", opts.addonTree(), void 0, patch, () => readStoredAddonBlob(raw), (p) => raw.writeAddonStore(p));
6678
6829
  const readAddonStoreResult = raw.readAddonStoreResult;
6679
6830
  const readAddonStoreKeyResult = raw.readAddonStoreKeyResult;
6680
- const readDeviceStoreBatch = raw.readDeviceStoreBatch;
6681
6831
  const overrides = {
6682
6832
  readAddonStore: async () => resolveRead("addon", await raw.readAddonStore()),
6683
6833
  ...readAddonStoreResult !== void 0 ? { readAddonStoreResult: async () => {
@@ -6701,12 +6851,12 @@ function createHandle(raw, opts) {
6701
6851
  };
6702
6852
  } } : {},
6703
6853
  readDeviceStore: async (deviceId) => resolveRead(`device:${deviceId}`, await raw.readDeviceStore(deviceId)),
6704
- ...readDeviceStoreBatch !== void 0 ? { readDeviceStoreBatch: async (deviceIds) => {
6705
- const rows = await readDeviceStoreBatch.call(raw, deviceIds);
6854
+ readDeviceStoreBatch: async (deviceIds) => {
6855
+ const rows = await raw.readDeviceStoreBatch(deviceIds);
6706
6856
  const out = /* @__PURE__ */ new Map();
6707
6857
  for (const [deviceId, blob] of rows) out.set(deviceId, await resolveRead(`device:${deviceId}`, blob));
6708
6858
  return out;
6709
- } } : {},
6859
+ },
6710
6860
  writeAddonStore: async (patch) => {
6711
6861
  await writeAddon(patch);
6712
6862
  },
@@ -7333,7 +7483,7 @@ var BaseAddon = class {
7333
7483
  if (!ctx) return;
7334
7484
  const addonId = ctx.id;
7335
7485
  setImmediate(() => {
7336
- ctx.api.addons?.restartAddon?.mutate({ addonId }).then(() => {
7486
+ ctx.api.addons.restartAddon.mutate({ addonId }).then(() => {
7337
7487
  ctx.logger.info("addon auto-restart triggered by restart-required setting change", { meta: { changedFields: patchKeys.filter((k) => restartKeys.has(k)) } });
7338
7488
  }).catch((err) => {
7339
7489
  ctx.logger.error("addon auto-restart failed", { meta: { error: err instanceof Error ? err.message : String(err) } });
@@ -7533,7 +7683,7 @@ var BaseAddon = class {
7533
7683
  return this._addonSecretTree;
7534
7684
  }
7535
7685
  deviceSecretTree() {
7536
- this._deviceSecretTree ??= secretTreeFromSchema(this.deviceSettingsSchema());
7686
+ this._deviceSecretTree ??= mergeSecretStatePaths(secretTreeFromSchema(this.deviceSettingsSchema()), this.secretStatePaths);
7537
7687
  return this._deviceSecretTree;
7538
7688
  }
7539
7689
  /**
@@ -7609,42 +7759,135 @@ var BaseAddon = class {
7609
7759
  this[timerOf] = timer;
7610
7760
  }
7611
7761
  /**
7612
- * Wrap `ctx.settings.readAddonStore()` with a short retry budget so a
7613
- * transient settings-store outage (mid-restart of sqlite-settings, tsx-watch
7614
- * swap, or any race where the SqliteSettingsBackend is between shutdown and
7615
- * re-initialize) doesn't propagate up into `initialize()` and leave the
7762
+ * Wrap `ctx.settings.readAddonStore()` with a retry budget so a transient
7763
+ * settings-store outage doesn't propagate up into `initialize()` and leave the
7616
7764
  * addon permanently broken.
7617
7765
  *
7618
- * Retry only the two known infra fingerprints. Anything else propagates so
7619
- * real bugs surface immediately. After the budget expires we fall back to
7620
- * `{}` (defaults) — the addon's first successful patch will rehydrate.
7766
+ * Two kinds of outage, two budgets:
7767
+ * - the store's own restart fingerprints (`SqliteSettingsBackend not
7768
+ * initialized`, `provider not available`): a short budget, then the addon
7769
+ * falls back to `{}` (defaults) - its first successful patch rehydrates;
7770
+ * - a TRANSPORT failure (the hub is restarting while this runner boots:
7771
+ * `discovery deadline exceeded`, `parent could not route`, a refused or
7772
+ * timed-out connection). Since D870 a runner's settings read THROWS instead
7773
+ * of answering `{}`, so without a budget a hub restart ends in a respawn
7774
+ * loop. A long, bounded budget; only after it the error propagates - the
7775
+ * addon never runs on defaults for a store it could not ask.
7776
+ * Anything else propagates immediately so real bugs surface.
7621
7777
  */
7622
7778
  async readAddonStoreWithRetry() {
7623
7779
  const settings = this.rawSettings();
7624
7780
  if (!settings) return {};
7625
- const delaysMs = [
7626
- 150,
7627
- 350,
7628
- 600,
7629
- 900
7630
- ];
7631
7781
  let lastErr;
7632
- for (let attempt = 0; attempt <= delaysMs.length; attempt++) try {
7782
+ for (let attempt = 0;; attempt++) try {
7633
7783
  const stored = await settings.readAddonStore() ?? {};
7634
7784
  this.settingsStoreReady = true;
7635
7785
  return stored;
7636
7786
  } catch (err) {
7637
7787
  lastErr = err;
7638
- const msg = err instanceof Error ? err.message : String(err);
7639
- if (!(msg.includes("SqliteSettingsBackend not initialized") || msg.includes("provider not available"))) throw err;
7640
- if (attempt === delaysMs.length) break;
7641
- await new Promise((r) => setTimeout(r, delaysMs[attempt]));
7788
+ const kind = classifyStoreError(err);
7789
+ if (kind === "permanent") throw err;
7790
+ const delay = (kind === "transport" ? TRANSPORT_RETRY_DELAYS_MS : RESTART_RETRY_DELAYS_MS)[attempt];
7791
+ if (delay === void 0) {
7792
+ if (kind === "transport") throw err;
7793
+ break;
7794
+ }
7795
+ await new Promise((r) => setTimeout(r, delay));
7642
7796
  }
7643
7797
  this.settingsStoreReady = false;
7644
7798
  this._ctx?.logger?.warn?.("readAddonStore: settings-store unavailable after retries — using defaults", { meta: { error: lastErr instanceof Error ? lastErr.message : String(lastErr) } });
7645
7799
  return {};
7646
7800
  }
7647
7801
  };
7802
+ /** The settings store's own restart fingerprints. */
7803
+ var RESTART_RETRY_DELAYS_MS = [
7804
+ 150,
7805
+ 350,
7806
+ 600,
7807
+ 900
7808
+ ];
7809
+ /** A hub restarting under a booting runner: ~100 s in total. */
7810
+ var TRANSPORT_RETRY_DELAYS_MS = [
7811
+ 150,
7812
+ 350,
7813
+ 600,
7814
+ 900,
7815
+ 2e3,
7816
+ 5e3,
7817
+ 1e4,
7818
+ 2e4,
7819
+ 3e4,
7820
+ 3e4
7821
+ ];
7822
+ var RESTART_FINGERPRINTS = ["SqliteSettingsBackend not initialized", "provider not available"];
7823
+ /** Node / socket error codes of a connection that did not happen or broke. */
7824
+ var TRANSPORT_CODES = new Set([
7825
+ "ECONNREFUSED",
7826
+ "ECONNRESET",
7827
+ "ETIMEDOUT",
7828
+ "EPIPE",
7829
+ "EHOSTUNREACH",
7830
+ "ENETUNREACH"
7831
+ ]);
7832
+ /** tRPC error codes that mean "the other side is not answering now", not "your call is wrong". */
7833
+ var UNAVAILABLE_TRPC_CODES = new Set([
7834
+ "TIMEOUT",
7835
+ "SERVICE_UNAVAILABLE",
7836
+ "BAD_GATEWAY",
7837
+ "GATEWAY_TIMEOUT"
7838
+ ]);
7839
+ /** The exact phrases OUR transport raises when it cannot reach the hub. */
7840
+ var TRANSPORT_PHRASES = [
7841
+ "discovery deadline exceeded",
7842
+ "parent could not route child unowned cap call",
7843
+ "UDS request timed out after",
7844
+ "channel closed"
7845
+ ];
7846
+ /** Moleculer error `type`s of a call that could not be served right now. */
7847
+ var MOLECULER_TRANSIENT_TYPES = new Set([
7848
+ "REQUEST_TIMEOUT",
7849
+ "SERVICE_NOT_FOUND",
7850
+ "SERVICE_NOT_AVAILABLE",
7851
+ "REQUEST_REJECTED",
7852
+ "BROKER_DISCONNECTED"
7853
+ ]);
7854
+ function stringProp(value, key) {
7855
+ if (typeof value !== "object" || value === null) return void 0;
7856
+ const found = Reflect.get(value, key);
7857
+ return typeof found === "string" ? found : void 0;
7858
+ }
7859
+ /** The code an error carries: its own, its cause's, or a tRPC `data.code`. */
7860
+ function errorCode(err) {
7861
+ const out = {};
7862
+ const cause = typeof err === "object" && err !== null ? Reflect.get(err, "cause") : void 0;
7863
+ const data = typeof err === "object" && err !== null ? Reflect.get(err, "data") : void 0;
7864
+ const node = stringProp(err, "code") ?? stringProp(cause, "code");
7865
+ if (node !== void 0) out.node = node;
7866
+ const trpc = stringProp(data, "code");
7867
+ if (trpc !== void 0) out.trpc = trpc;
7868
+ return out;
7869
+ }
7870
+ /**
7871
+ * Is a settings read failure worth retrying, and with which budget? Only
7872
+ * EXPLICIT signals count: a socket error code, a tRPC "unavailable" code, or
7873
+ * one of the exact phrases our own transport raises. A message that merely
7874
+ * contains "timed out" or "unreachable" is not evidence of anything, and
7875
+ * `settings store not wired` is a wiring bug that retrying cannot fix.
7876
+ */
7877
+ function classifyStoreError(err) {
7878
+ const message = err instanceof Error ? err.message : String(err);
7879
+ if (RESTART_FINGERPRINTS.some((f) => message.includes(f))) return "restart";
7880
+ const code = errorCode(err);
7881
+ if (code.node !== void 0 && TRANSPORT_CODES.has(code.node)) return "transport";
7882
+ if (code.trpc !== void 0 && UNAVAILABLE_TRPC_CODES.has(code.trpc)) return "transport";
7883
+ if (typeof err === "object" && err !== null) {
7884
+ if (Reflect.get(err, "retryable") === true) return "transport";
7885
+ const type = stringProp(err, "type");
7886
+ if (type !== void 0 && MOLECULER_TRANSIENT_TYPES.has(type)) return "transport";
7887
+ }
7888
+ if (TRANSPORT_PHRASES.some((f) => message.includes(f))) return "transport";
7889
+ return "permanent";
7890
+ }
7648
7891
  /**
7649
7892
  * Collect the keys of every field marked `perNode: true`, recursing into
7650
7893
  * layout containers (`group` fields and `sub-tabs` tabs) the same way
@@ -7734,6 +7977,356 @@ var PeerBytesTicketSchema = object({
7734
7977
  */
7735
7978
  declaredBytes: number().int().nonnegative().nullable()
7736
7979
  });
7980
+ /** Limits and names of `ctx.records` (D881). One authority; the engine and the facade read it. */
7981
+ /** The files a kind may live in. `history` is device-history's (D850), never records. */
7982
+ var RECORD_DATABASES = ["settings", "events"];
7983
+ /** The classes of a kind: the `@durable` vocabulary, one authority (replaces the annotation). */
7984
+ var RECORD_CLASSES = [
7985
+ "config",
7986
+ "ledger",
7987
+ "audit",
7988
+ "mirror",
7989
+ "ephemeral"
7990
+ ];
7991
+ var RECORD_DEFAULT_MAX_DATA_BYTES = 64 * 1024;
7992
+ var RECORD_MAX_DATA_BYTES = 1024 * 1024;
7993
+ var RECORD_BATCH_MAX = 1e3;
7994
+ var RECORD_QUERY_MAX = 1e3;
7995
+ /** A kind in the `settings` file may not bound itself above this (D447: high volume is `events`). */
7996
+ var RECORD_SETTINGS_MAX_ROWS = 5e4;
7997
+ var PREFIX = "records/";
7998
+ /** The base of every records failure. `detail` is the human part of the message. */
7999
+ var RecordsError = class extends Error {
8000
+ code;
8001
+ detail;
8002
+ constructor(code, detail) {
8003
+ super(`${PREFIX}${code}: ${detail}`);
8004
+ this.name = "RecordsError";
8005
+ this.code = code;
8006
+ this.detail = detail;
8007
+ }
8008
+ };
8009
+ /** The keychain could not store or serve a value: explicit, never an empty string. */
8010
+ var RecordSecretUnavailableError = class extends RecordsError {
8011
+ constructor(detail) {
8012
+ super("secret-unavailable", detail);
8013
+ this.name = "RecordSecretUnavailableError";
8014
+ }
8015
+ };
8016
+ var InvalidRecordError = class extends RecordsError {
8017
+ constructor(detail) {
8018
+ super("invalid-record", detail);
8019
+ this.name = "InvalidRecordError";
8020
+ }
8021
+ };
8022
+ /** A kind declaration the engine refuses (non-additive change, bad shape, wrong file). */
8023
+ var DeclarationRefusedError = class extends RecordsError {
8024
+ constructor(detail) {
8025
+ super("declaration-refused", detail);
8026
+ this.name = "DeclarationRefusedError";
8027
+ }
8028
+ };
8029
+ function defOf(schema) {
8030
+ const zodBag = Reflect.get(schema, "_zod");
8031
+ if (typeof zodBag !== "object" || zodBag === null) return {};
8032
+ const def = Reflect.get(zodBag, "def");
8033
+ if (typeof def !== "object" || def === null) return {};
8034
+ return def;
8035
+ }
8036
+ function declaredHere(schema) {
8037
+ return globalRegistry.get(schema)?.secret === true;
8038
+ }
8039
+ /** Wrapper kinds whose `innerType` is the field itself. */
8040
+ var WRAPPERS = new Set([
8041
+ "optional",
8042
+ "nullable",
8043
+ "default",
8044
+ "prefault",
8045
+ "catch",
8046
+ "readonly",
8047
+ "nonoptional"
8048
+ ]);
8049
+ /**
8050
+ * The schema layers that make up ONE field: the schema itself and every
8051
+ * wrapper below it (optional / default / nullable / readonly / catch), plus
8052
+ * both sides of a pipe (`z.preprocess` puts the real schema on `out`,
8053
+ * `.transform` on `in`).
8054
+ */
8055
+ function layersOf(schema) {
8056
+ const out = [];
8057
+ const queue = [schema];
8058
+ while (queue.length > 0) {
8059
+ const s = queue.shift();
8060
+ if (!s || out.includes(s)) continue;
8061
+ out.push(s);
8062
+ const def = defOf(s);
8063
+ if (def.type !== void 0 && WRAPPERS.has(def.type) && def.innerType) queue.push(def.innerType);
8064
+ if (def.type === "pipe") {
8065
+ if (def.in) queue.push(def.in);
8066
+ if (def.out) queue.push(def.out);
8067
+ }
8068
+ }
8069
+ return out;
8070
+ }
8071
+ /** True when any layer of this field declares `.meta({ secret: true })`. */
8072
+ function isZodSecret(schema) {
8073
+ return layersOf(schema).some(declaredHere);
8074
+ }
8075
+ /**
8076
+ * Every declared secret path in a config schema: dotted keys, `[]` for "each
8077
+ * element of this array" (`connection.password`, `rows[].token`). A declared
8078
+ * object or array is reported as one path and not descended into — everything
8079
+ * under it is secret.
8080
+ */
8081
+ function collectZodSecretPaths(schema, prefix = "") {
8082
+ if (isZodSecret(schema)) return prefix.length > 0 ? [prefix] : [];
8083
+ const paths = [];
8084
+ for (const layer of layersOf(schema)) {
8085
+ const def = defOf(layer);
8086
+ if (def.type === "object" && def.shape) for (const [key, child] of Object.entries(def.shape)) paths.push(...collectZodSecretPaths(child, prefix ? `${prefix}.${key}` : key));
8087
+ else if (def.type === "array" && def.element) paths.push(...collectZodSecretPaths(def.element, `${prefix}[]`));
8088
+ else if (def.type === "union" && def.options) for (const option of def.options) paths.push(...collectZodSecretPaths(option, prefix));
8089
+ else if (def.type === "intersection") {
8090
+ if (def.left) paths.push(...collectZodSecretPaths(def.left, prefix));
8091
+ if (def.right) paths.push(...collectZodSecretPaths(def.right, prefix));
8092
+ }
8093
+ }
8094
+ return [...new Set(paths)];
8095
+ }
8096
+ /**
8097
+ * Secret fields of a record, addressed the way a Zod schema declares them
8098
+ * (`collectZodSecretPaths`): dotted keys, `[]` for "each element of this array"
8099
+ * (`auth.accessToken`, `headers[].value`).
8100
+ *
8101
+ * Array elements are matched by a DECLARED id key (`secretArrayKeys`:
8102
+ * `{ headers: 'name' }`), never by index, so reordering a list keeps every
8103
+ * keychain ref (the same rule as `arrayItemFieldPath`). The concrete path of a
8104
+ * leaf names its element: `headers[X-Api].value`.
8105
+ *
8106
+ * Pure and browser-safe. Nothing here mutates: every transform returns a new value.
8107
+ */
8108
+ /** The array prefixes (declared form, e.g. `headers` or `a.headers`) of a path. */
8109
+ function parseSecretPath(path) {
8110
+ if (path.length === 0) throw new InvalidRecordError("an empty secret path");
8111
+ return path.split(".").map((raw) => {
8112
+ const each = raw.endsWith("[]");
8113
+ const key = each ? raw.slice(0, -2) : raw;
8114
+ if (key.length === 0) throw new InvalidRecordError(`secret path "${path}" has an empty segment`);
8115
+ return {
8116
+ key,
8117
+ each
8118
+ };
8119
+ });
8120
+ }
8121
+ /** The declared array prefixes of `path` that need an id key (`headers`, `a.rows`). */
8122
+ function secretArrayPrefixes(path) {
8123
+ const segments = parseSecretPath(path);
8124
+ const prefixes = [];
8125
+ const walked = [];
8126
+ for (const segment of segments) {
8127
+ walked.push(segment.key);
8128
+ if (segment.each) prefixes.push(walked.join("."));
8129
+ }
8130
+ return prefixes;
8131
+ }
8132
+ /**
8133
+ * Record kinds (D881): the declaration an addon makes of one kind of fact, the
8134
+ * Zod row schema that describes it, and the helper that turns the two into the
8135
+ * JSON the engine stores.
8136
+ *
8137
+ * A kind is declared ONCE, next to the code that owns it, and the engine's
8138
+ * reconciler creates its indexes - nothing creates DDL at runtime from a write.
8139
+ * Everything the generic machinery needs (secret fields, the entry descriptor)
8140
+ * is DERIVED from the Zod schema: `.meta({ secret: true })` marks a credential,
8141
+ * never a field name (D879).
8142
+ */
8143
+ /** A JSON field path: `trackId`, `auth.accessToken`. Charset-restricted: it is rendered into DDL. */
8144
+ var RecordFieldPathSchema = string().regex(/^[A-Za-z_][A-Za-z0-9_]{0,63}(\.[A-Za-z_][A-Za-z0-9_]{0,63}){0,3}$/);
8145
+ var RecordIndexSchema = object({
8146
+ name: string().regex(/^[a-z][a-z0-9_]{0,31}$/),
8147
+ fields: array(RecordFieldPathSchema).min(1).max(4),
8148
+ unique: boolean().optional()
8149
+ }).strict();
8150
+ var RecordRetentionSchema = union([
8151
+ object({
8152
+ ttlMs: number().int().positive(),
8153
+ from: _enum(["at", "write"])
8154
+ }).strict(),
8155
+ object({
8156
+ maxRows: number().int().positive().optional(),
8157
+ maxRowsPerDevice: number().int().positive().optional()
8158
+ }).strict().refine((r) => r.maxRows !== void 0 || r.maxRowsPerDevice !== void 0, { message: "name maxRows, maxRowsPerDevice or both" }),
8159
+ object({
8160
+ owner: string().min(1),
8161
+ reason: string().min(1)
8162
+ }).strict(),
8163
+ object({ none: string().min(1) }).strict()
8164
+ ]);
8165
+ /** The descriptor a generic entries UI reads (D881 "generic entries"). */
8166
+ var EntryDescriptorSchema = object({
8167
+ title: string().min(1),
8168
+ /** The record body field shown as the entry's name. */
8169
+ nameField: string().min(1),
8170
+ /** JSON Schema of the entry body; `secret: true` marks a password field. */
8171
+ fields: record(string(), unknown())
8172
+ }).strict();
8173
+ /** What crosses the wire and sits in the engine's catalog: JSON only, no Zod. */
8174
+ var RecordKindDeclarationSchema = object({
8175
+ database: _enum(RECORD_DATABASES).default("settings"),
8176
+ class: _enum(RECORD_CLASSES),
8177
+ writeTrigger: string().min(1),
8178
+ device: _enum([
8179
+ "required",
8180
+ "optional",
8181
+ "none"
8182
+ ]).default("none"),
8183
+ at: _enum(["required", "none"]).default("none"),
8184
+ indexes: array(RecordIndexSchema).max(8).default([]),
8185
+ retention: RecordRetentionSchema,
8186
+ deviceRemoval: _enum(["delete", "none"]).default("none"),
8187
+ maxDataBytes: number().int().positive().max(RECORD_MAX_DATA_BYTES).default(RECORD_DEFAULT_MAX_DATA_BYTES),
8188
+ /** Derived from the Zod schema; never written by hand. */
8189
+ secretPaths: array(string().min(1)).default([]),
8190
+ /** The id key of each array that carries a secret (`{ headers: 'name' }`). */
8191
+ secretArrayKeys: record(string(), string()).default({}),
8192
+ /** The legacy table this kind adopts from; the boot guard reads it (D853: no migration code). */
8193
+ adoptsFrom: string().min(1).optional(),
8194
+ /** Kinds that must agree through `transact` sit in one file under one family name. */
8195
+ transactFamily: string().min(1).optional(),
8196
+ entry: EntryDescriptorSchema.optional()
8197
+ }).strict();
8198
+ /** The kind names: lower-case, dash separated, short enough for an index name. */
8199
+ var RecordKindNameSchema = string().regex(/^[a-z][a-z0-9-]{0,47}$/);
8200
+ /** Cross-field rules a declaration must satisfy. Throws {@link DeclarationRefusedError}. */
8201
+ function assertValidDeclaration(name, decl) {
8202
+ const refuse = (why) => {
8203
+ throw new DeclarationRefusedError(`kind "${name}": ${why}`);
8204
+ };
8205
+ if (!RecordKindNameSchema.safeParse(name).success) refuse("the name must be lower-case-dashed");
8206
+ const seen = /* @__PURE__ */ new Set();
8207
+ for (const index of decl.indexes) {
8208
+ if (seen.has(index.name)) refuse(`index name "${index.name}" is declared twice`);
8209
+ seen.add(index.name);
8210
+ }
8211
+ const { retention } = decl;
8212
+ const hasSecrets = decl.secretPaths.length > 0;
8213
+ if ("ttlMs" in retention) {
8214
+ if (retention.from === "at" && decl.at !== "required") refuse("a ttl from \"at\" needs at: \"required\"");
8215
+ if (hasSecrets) refuse("a kind with secret fields cannot use engine TTL (its keychain values would be orphaned)");
8216
+ }
8217
+ if ("maxRows" in retention || "maxRowsPerDevice" in retention) {
8218
+ if (retention.maxRowsPerDevice !== void 0 && decl.device !== "required") refuse("maxRowsPerDevice needs device: \"required\"");
8219
+ if (decl.at !== "required") refuse("a row bound trims the oldest \"at\": it needs at: \"required\"");
8220
+ if (hasSecrets) refuse("a kind with secret fields cannot use an engine row bound");
8221
+ const bound = Math.max(retention.maxRows ?? 0, retention.maxRowsPerDevice ?? 0);
8222
+ 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)`);
8223
+ }
8224
+ if (decl.deviceRemoval === "delete" && decl.device === "none") refuse("deviceRemoval: \"delete\" needs a device: \"required\" or \"optional\"");
8225
+ 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`);
8226
+ }
8227
+ function bodyFieldsOf(schema) {
8228
+ return { ...toJSONSchema(schema, {
8229
+ unrepresentable: "any",
8230
+ io: "input"
8231
+ }) };
8232
+ }
8233
+ function isRecordLike(value) {
8234
+ return typeof value === "object" && value !== null && !Array.isArray(value);
8235
+ }
8236
+ /** Does every branch of the body schema carry `field`? (A discriminated union has several.) */
8237
+ function hasNameField(json, field) {
8238
+ const branches = json["oneOf"] ?? json["anyOf"];
8239
+ if (Array.isArray(branches)) return branches.length > 0 && branches.every((b) => isRecordLike(b) && hasNameField(b, field));
8240
+ const properties = json["properties"];
8241
+ return isRecordLike(properties) && Object.prototype.hasOwnProperty.call(properties, field);
8242
+ }
8243
+ /**
8244
+ * Declare the kinds of a package. The keys are the kind names. The result is
8245
+ * what `ctx.records.declare` sends to the engine and what `ctx.records.kind`
8246
+ * types its handle from.
8247
+ */
8248
+ function defineRecordKinds(specs) {
8249
+ const out = {};
8250
+ for (const [name, spec] of Object.entries(specs)) {
8251
+ const secretPaths = collectZodSecretPaths(spec.schema);
8252
+ const nameField = spec.entry?.nameField ?? "name";
8253
+ const fields = bodyFieldsOf(spec.schema);
8254
+ if (spec.entry !== void 0 && !hasNameField(fields, nameField)) throw new DeclarationRefusedError(`kind "${name}": an entry kind's schema needs a "${nameField}" field`);
8255
+ const parsed = RecordKindDeclarationSchema.parse({
8256
+ database: spec.database,
8257
+ class: spec.class,
8258
+ writeTrigger: spec.writeTrigger,
8259
+ device: spec.device,
8260
+ at: spec.at,
8261
+ indexes: spec.indexes === void 0 ? void 0 : [...spec.indexes],
8262
+ retention: spec.retention,
8263
+ deviceRemoval: spec.deviceRemoval,
8264
+ maxDataBytes: spec.maxDataBytes,
8265
+ secretPaths: [...secretPaths],
8266
+ secretArrayKeys: spec.secretArrayKeys === void 0 ? void 0 : { ...spec.secretArrayKeys },
8267
+ adoptsFrom: spec.adoptsFrom,
8268
+ transactFamily: spec.transactFamily,
8269
+ entry: spec.entry === void 0 ? void 0 : {
8270
+ title: spec.entry.title,
8271
+ nameField,
8272
+ fields
8273
+ }
8274
+ });
8275
+ assertValidDeclaration(name, parsed);
8276
+ out[name] = {
8277
+ name,
8278
+ schema: spec.schema,
8279
+ declaration: parsed
8280
+ };
8281
+ }
8282
+ return out;
8283
+ }
8284
+ /**
8285
+ * Entry kinds (D881): every list of user-created entries (notification
8286
+ * targets, brokers, LLM profiles) is ONE record kind with an id, a name and a
8287
+ * kind-specific body, and the admin UI lists/adds/edits/deletes all of them
8288
+ * through the `record-entries` capability with password fields derived from
8289
+ * the schema (`.meta({ secret: true })`).
8290
+ */
8291
+ /** The body of a plain entry: a name and the fields the kind adds. */
8292
+ function entryBody(shape) {
8293
+ return object({
8294
+ name: string().min(1),
8295
+ ...shape
8296
+ });
8297
+ }
8298
+ /**
8299
+ * Declare one entry kind. An entry is configuration: never trimmed by the
8300
+ * engine, never aged, belonging to no device.
8301
+ */
8302
+ function defineEntryKind(name, spec) {
8303
+ const defined = defineRecordKinds({ [name]: {
8304
+ schema: spec.schema,
8305
+ class: "config",
8306
+ writeTrigger: spec.writeTrigger ?? "an operator adds or edits an entry in the entries UI",
8307
+ retention: { none: "an entry goes only when the operator deletes it" },
8308
+ ...spec.database === void 0 ? {} : { database: spec.database },
8309
+ ...spec.indexes === void 0 ? {} : { indexes: spec.indexes },
8310
+ ...spec.secretArrayKeys === void 0 ? {} : { secretArrayKeys: spec.secretArrayKeys },
8311
+ ...spec.adoptsFrom === void 0 ? {} : { adoptsFrom: spec.adoptsFrom },
8312
+ entry: {
8313
+ title: spec.title,
8314
+ ...spec.nameField === void 0 ? {} : { nameField: spec.nameField }
8315
+ }
8316
+ } })[name];
8317
+ if (defined === void 0) throw new DeclarationRefusedError(`entry kind "${name}" was not built`);
8318
+ return defined;
8319
+ }
8320
+ /**
8321
+ * Legacy source for broker entry adoption (B2): brokers live in addon-settings
8322
+ * as one row `<addonId>.brokers` whose value is an array until records-adopt
8323
+ * copies them into the entry kind.
8324
+ */
8325
+ var SETTINGS_BROKERS_ADOPTS_PREFIX = "@settings-brokers/";
8326
+ /** The `adoptsFrom` value for an addon's broker entry kind. */
8327
+ function settingsBrokersAdoptsFrom(addonId) {
8328
+ return `${SETTINGS_BROKERS_ADOPTS_PREFIX}${addonId}`;
8329
+ }
7737
8330
  /** Shared Zod schemas used across streaming capabilities. */
7738
8331
  var CamProfileSchema = _enum([
7739
8332
  "high",
@@ -8198,75 +8791,12 @@ method(object({ deviceId: number() }), array(StreamSourceEntrySchema)), method(o
8198
8791
  kind: "mutation",
8199
8792
  auth: "admin"
8200
8793
  }), method(object({ deviceId: number() }), unknown().nullable()), method(object({ deviceId: number() }), RawStateResultSchema.nullable(), { auth: "protected" });
8201
- function defOf(schema) {
8202
- return schema._zod?.def ?? {};
8203
- }
8204
- function declaredHere(schema) {
8205
- return globalRegistry.get(schema)?.secret === true;
8206
- }
8207
- /** Wrapper kinds whose `innerType` is the field itself. */
8208
- var WRAPPERS = new Set([
8209
- "optional",
8210
- "nullable",
8211
- "default",
8212
- "prefault",
8213
- "catch",
8214
- "readonly",
8215
- "nonoptional"
8216
- ]);
8217
- /**
8218
- * The schema layers that make up ONE field: the schema itself and every
8219
- * wrapper below it (optional / default / nullable / readonly / catch), plus
8220
- * both sides of a pipe (`z.preprocess` puts the real schema on `out`,
8221
- * `.transform` on `in`).
8222
- */
8223
- function layersOf(schema) {
8224
- const out = [];
8225
- const queue = [schema];
8226
- while (queue.length > 0) {
8227
- const s = queue.shift();
8228
- if (!s || out.includes(s)) continue;
8229
- out.push(s);
8230
- const def = defOf(s);
8231
- if (def.type !== void 0 && WRAPPERS.has(def.type) && def.innerType) queue.push(def.innerType);
8232
- if (def.type === "pipe") {
8233
- if (def.in) queue.push(def.in);
8234
- if (def.out) queue.push(def.out);
8235
- }
8236
- }
8237
- return out;
8238
- }
8239
- /** True when any layer of this field declares `.meta({ secret: true })`. */
8240
- function isZodSecret(schema) {
8241
- return layersOf(schema).some(declaredHere);
8242
- }
8243
- /**
8244
- * Every declared secret path in a config schema: dotted keys, `[]` for "each
8245
- * element of this array" (`connection.password`, `rows[].token`). A declared
8246
- * object or array is reported as one path and not descended into — everything
8247
- * under it is secret.
8248
- */
8249
- function collectZodSecretPaths(schema, prefix = "") {
8250
- if (isZodSecret(schema)) return prefix.length > 0 ? [prefix] : [];
8251
- const paths = [];
8252
- for (const layer of layersOf(schema)) {
8253
- const def = defOf(layer);
8254
- if (def.type === "object" && def.shape) for (const [key, child] of Object.entries(def.shape)) paths.push(...collectZodSecretPaths(child, prefix ? `${prefix}.${key}` : key));
8255
- else if (def.type === "array" && def.element) paths.push(...collectZodSecretPaths(def.element, `${prefix}[]`));
8256
- else if (def.type === "union" && def.options) for (const option of def.options) paths.push(...collectZodSecretPaths(option, prefix));
8257
- else if (def.type === "intersection") {
8258
- if (def.left) paths.push(...collectZodSecretPaths(def.left, prefix));
8259
- if (def.right) paths.push(...collectZodSecretPaths(def.right, prefix));
8260
- }
8261
- }
8262
- return [...new Set(paths)];
8263
- }
8264
8794
  object({
8265
8795
  code: string().regex(/^[a-z][a-z0-9-]*(\.[a-z0-9-]+)+$/),
8266
8796
  params: record(string(), union([string(), number()])).optional()
8267
8797
  });
8268
8798
  //#endregion
8269
- //#region ../types/dist/err-msg-DLerKiVO.mjs
8799
+ //#region ../types/dist/err-msg--2RrYiLO.mjs
8270
8800
  var DeviceType = /* @__PURE__ */ function(DeviceType) {
8271
8801
  DeviceType["Camera"] = "camera";
8272
8802
  DeviceType["Hub"] = "hub";
@@ -8535,6 +9065,9 @@ var DeviceRole = /* @__PURE__ */ function(DeviceRole) {
8535
9065
  /** Virtual HA toggle (input_boolean.*) — distinguishable from a
8536
9066
  * real Switch device for UI rendering / export adapters. */
8537
9067
  DeviceRole["BinaryHelper"] = "binary-helper";
9068
+ /** A smart plug: a `switch` whose source says it is an outlet (HA
9069
+ * `device_class: outlet`). The Alexa export shows it as a SMARTPLUG. */
9070
+ DeviceRole["Outlet"] = "outlet";
8538
9071
  /** Generic motion / occupancy / moving event source. Distinct from
8539
9072
  * the camera accessory PirSensor role: that one is a camera child;
8540
9073
  * this is a standalone HA / 3rd-party motion sensor. */
@@ -8612,7 +9145,7 @@ function errMsg(err) {
8612
9145
  return String(err);
8613
9146
  }
8614
9147
  //#endregion
8615
- //#region ../types/dist/composition-EQ9Ok0Ee.mjs
9148
+ //#region ../types/dist/composition-DOwQB_Ua.mjs
8616
9149
  /**
8617
9150
  * The ffmpeg build every CamStack node downloads, per platform and arch.
8618
9151
  *
@@ -11933,11 +12466,10 @@ var ClipModelMetaSchema = object({
11933
12466
  /**
11934
12467
  * The `vector-store` index this model's vectors live in. ONE feature space
11935
12468
  * per index: two models share an index only when their vectors are ranked
11936
- * against each other, which for CLIP means never across families. MobileCLIP
11937
- * S1 and S2 share `object-clip` for history (separated by the row's
11938
- * `modelId`); any other model gets its own.
12469
+ * against each other, which for CLIP means never across families. Every
12470
+ * model gets its own.
11939
12471
  */
11940
- vectorIndex: string().regex(/^object-clip(-[a-z0-9][a-z0-9-]*)?$/),
12472
+ vectorIndex: string().regex(/^object-clip-[a-z0-9][a-z0-9-]*$/),
11941
12473
  /**
11942
12474
  * The text encoder's tokenizer, a declared SIBLING file of its onnx. The name
11943
12475
  * must be unique per tokenizer: every model's siblings land in ONE flat
@@ -15738,6 +16270,41 @@ var ComposableCapabilitiesSchema = object({ caps: array(object({
15738
16270
  keyField: string()
15739
16271
  }).optional()
15740
16272
  })) });
16273
+ /**
16274
+ * The report of a one-shot "move this owner's plaintext secrets into the
16275
+ * keychain" run (D878). COUNTS only - never a value, never a ref.
16276
+ *
16277
+ * The owner runs it on its own rows, through its own write path; an operator
16278
+ * script (`scripts/hub/migrate-raw-secrets.ts`) calls the owner's cap method.
16279
+ * Dry run (`apply: false`) reports what WOULD move and changes nothing.
16280
+ */
16281
+ var RawSecretMigrationInputSchema = object({
16282
+ /** `false` (the default of the script) = report only. */
16283
+ apply: boolean() });
16284
+ var RawSecretMigrationReportSchema = object({
16285
+ apply: boolean(),
16286
+ /** Rows that can carry a secret (a profile, an enrolment). */
16287
+ rows: number().int(),
16288
+ /** Rows whose secret was plaintext when the run started. */
16289
+ raw: number().int(),
16290
+ /** Rows that already held a keychain marker when the run started. */
16291
+ markers: number().int(),
16292
+ /** Plaintext rows moved by THIS run (always 0 on a dry run). */
16293
+ migrated: number().int(),
16294
+ /** Plaintext rows left in place because the move or its read-back failed. */
16295
+ failed: number().int(),
16296
+ /** After the run: rows still holding plaintext. */
16297
+ remainingRaw: number().int(),
16298
+ /** After the run: markers the keychain could not resolve right now. */
16299
+ unresolvedMarkers: number().int(),
16300
+ /**
16301
+ * A second, redundant copy of the secrets' rows that the run found (and, on
16302
+ * `apply`, deleted after verifying the first). Owners with a single copy omit it.
16303
+ */
16304
+ redundantCopies: number().int().optional(),
16305
+ /** True when nothing is raw and every marker resolves. */
16306
+ verified: boolean()
16307
+ });
15741
16308
  /** Where a block runs. The operator chooses — a block driving a device on an
15742
16309
  * agent is the reason placement is not fixed to the hub. */
15743
16310
  var CoreBlockPlacementSchema = union([literal("hub"), string().min(1)]);
@@ -15964,6 +16531,9 @@ method(object({}), object({ blocks: array(CoreBlockSchema) }), { auth: "admin" }
15964
16531
  }), SettingsUpdateResultSchema, {
15965
16532
  kind: "mutation",
15966
16533
  auth: "admin"
16534
+ }), method(RawSecretMigrationInputSchema, RawSecretMigrationReportSchema, {
16535
+ kind: "mutation",
16536
+ auth: "admin"
15967
16537
  }), method(object({}), object({ libs: array(object({
15968
16538
  filePath: string(),
15969
16539
  content: string()
@@ -16227,6 +16797,347 @@ id: union([string(), number()]) }), {
16227
16797
  auth: "admin"
16228
16798
  });
16229
16799
  /**
16800
+ * records - an addon's own facts and documents (D881): ledgers, audit rows,
16801
+ * config documents, mirrors. The third storage API next to `ctx.settings`
16802
+ * (operator intent, D870) and device-history (numbers over time, D850).
16803
+ *
16804
+ * Who the OWNER is: `callerAddonId`, stamped by the transport on a call that
16805
+ * crossed a process and stated by a hub in-process caller (`ctx.records` does
16806
+ * that with the addon id closed over). It is deliberately NOT in any input
16807
+ * schema, so a session can never supply it, and a call with no stamp is refused
16808
+ * `records/no-caller`. A kind is readable and writable only by its owner; other
16809
+ * addons go through the owner's capability.
16810
+ *
16811
+ * Every read is three-way: a row, `null`, or the call THROWS. A failed read is
16812
+ * never `[]`. Secret fields are never on the wire: a read shows the
16813
+ * redaction token, `secretRefs` hands the owner's `ctx.secrets` the refs it
16814
+ * resolves itself, and a write may carry only a keychain marker bound to the
16815
+ * row's own ref.
16816
+ *
16817
+ * Internal: addons reach it through `ctx.records`, never directly.
16818
+ */
16819
+ var RecordIdSchema = string().min(1).max(256);
16820
+ /** A JSON object body. Size is the engine's check (`maxDataBytes`), not a schema's. */
16821
+ var RecordBodySchema = record(string(), unknown());
16822
+ var RecordInputSchema = object({
16823
+ id: RecordIdSchema,
16824
+ /** The device this row belongs to (D865 removal, per-device reads). */
16825
+ deviceId: number().int().optional(),
16826
+ /** The domain clock, ms: observed / created / opened. */
16827
+ at: number().int().optional(),
16828
+ /** Producer-set expiry, ms. Refused on a kind whose retention is an engine TTL. */
16829
+ expiresAt: number().int().optional(),
16830
+ data: RecordBodySchema
16831
+ });
16832
+ var RecordViewSchema = object({
16833
+ id: string(),
16834
+ deviceId: number().int().nullable(),
16835
+ at: number().nullable(),
16836
+ expiresAt: number().nullable(),
16837
+ rev: number().int(),
16838
+ updatedAt: number(),
16839
+ data: RecordBodySchema
16840
+ });
16841
+ /** Declared index fields only. Anything else does not compile, by design. */
16842
+ var RecordWhereSchema = record(RecordFieldPathSchema, union([
16843
+ string(),
16844
+ number(),
16845
+ boolean(),
16846
+ object({ in: array(union([
16847
+ string(),
16848
+ number(),
16849
+ boolean()
16850
+ ])).min(1).max(RECORD_BATCH_MAX) }),
16851
+ object({
16852
+ gt: union([string(), number()]).optional(),
16853
+ gte: union([string(), number()]).optional(),
16854
+ lt: union([string(), number()]).optional(),
16855
+ lte: union([string(), number()]).optional()
16856
+ }).refine((r) => Object.keys(r).length > 0, { message: "name at least one bound" })
16857
+ ]));
16858
+ var KindShape = { kind: RecordKindNameSchema };
16859
+ var TimeWindowShape = {
16860
+ deviceId: number().int().optional(),
16861
+ atFrom: number().optional(),
16862
+ atTo: number().optional()
16863
+ };
16864
+ var RecordQueryInputSchema = object({
16865
+ ...KindShape,
16866
+ ...TimeWindowShape,
16867
+ where: RecordWhereSchema.optional(),
16868
+ /** Without `where`: `at` (default for a kind with a clock) or `id`. With `where` the order is the index's. */
16869
+ order: _enum(["at", "id"]).optional(),
16870
+ desc: boolean().optional(),
16871
+ limit: number().int().min(1).max(RECORD_QUERY_MAX).default(100),
16872
+ /** Opaque keyset cursor from a previous answer. There is no offset. */
16873
+ cursor: string().min(1).optional()
16874
+ });
16875
+ var RecordQueryResultSchema = object({
16876
+ records: array(RecordViewSchema),
16877
+ nextCursor: string().nullable()
16878
+ });
16879
+ var RecordKindStateSchema = _enum([
16880
+ "created",
16881
+ "unchanged",
16882
+ "updated"
16883
+ ]);
16884
+ var DeclareKindResultSchema = object({
16885
+ kindId: number().int(),
16886
+ state: RecordKindStateSchema,
16887
+ createdIndexes: array(string()),
16888
+ /** The boot guard: the kind is empty while its legacy table still holds rows. */
16889
+ adoptionPending: object({
16890
+ legacyTable: string(),
16891
+ legacyRows: number().int()
16892
+ }).nullable()
16893
+ });
16894
+ /** Keychain refs a write released (the old marker is gone from the row): the owner deletes the values. */
16895
+ var SecretRefsList = array(string());
16896
+ var RecordSecretRefsSchema = record(string(), record(string(), string()));
16897
+ method(object({ kinds: record(RecordKindNameSchema, RecordKindDeclarationSchema) }), object({ kinds: record(string(), DeclareKindResultSchema) }), {
16898
+ kind: "mutation",
16899
+ auth: "admin"
16900
+ }), method(object({
16901
+ ...KindShape,
16902
+ id: RecordIdSchema
16903
+ }), RecordViewSchema.nullable(), { auth: "admin" }), method(object({
16904
+ ...KindShape,
16905
+ ids: array(RecordIdSchema).min(1).max(RECORD_BATCH_MAX)
16906
+ }), array(RecordViewSchema), { auth: "admin" }), method(object({
16907
+ ...KindShape,
16908
+ ids: array(RecordIdSchema).min(1).max(RECORD_BATCH_MAX)
16909
+ }), RecordSecretRefsSchema, { auth: "admin" }), method(object({
16910
+ ...KindShape,
16911
+ record: RecordInputSchema,
16912
+ /** Compare-and-set. `0` means "the row must not exist". */
16913
+ ifRev: number().int().min(0).optional()
16914
+ }), object({
16915
+ rev: number().int(),
16916
+ releasedRefs: SecretRefsList
16917
+ }), {
16918
+ kind: "mutation",
16919
+ auth: "admin"
16920
+ }), method(object({
16921
+ ...KindShape,
16922
+ records: array(RecordInputSchema).min(1).max(RECORD_BATCH_MAX)
16923
+ }), object({
16924
+ count: number().int(),
16925
+ releasedRefs: SecretRefsList
16926
+ }), {
16927
+ kind: "mutation",
16928
+ auth: "admin"
16929
+ }), method(object({
16930
+ ...KindShape,
16931
+ id: RecordIdSchema,
16932
+ data: RecordBodySchema,
16933
+ at: number().int().nullable().optional(),
16934
+ expiresAt: number().int().nullable().optional(),
16935
+ ifRev: number().int().min(1).optional()
16936
+ }), object({
16937
+ rev: number().int(),
16938
+ releasedRefs: SecretRefsList
16939
+ }), {
16940
+ kind: "mutation",
16941
+ auth: "admin"
16942
+ }), method(object({
16943
+ ...KindShape,
16944
+ id: RecordIdSchema
16945
+ }), object({
16946
+ deleted: boolean(),
16947
+ secretRefs: SecretRefsList
16948
+ }), {
16949
+ kind: "mutation",
16950
+ auth: "admin"
16951
+ }), method(object({
16952
+ ...KindShape,
16953
+ ids: array(RecordIdSchema).min(1).max(RECORD_BATCH_MAX)
16954
+ }), object({
16955
+ deleted: number().int(),
16956
+ secretRefs: SecretRefsList
16957
+ }), {
16958
+ kind: "mutation",
16959
+ auth: "admin"
16960
+ }), method(RecordQueryInputSchema, RecordQueryResultSchema, { auth: "admin" }), method(object({
16961
+ ...KindShape,
16962
+ ...TimeWindowShape,
16963
+ where: RecordWhereSchema.optional()
16964
+ }), object({ count: number().int() }), { auth: "admin" }), method(object({
16965
+ ...KindShape,
16966
+ deviceId: number().int().optional(),
16967
+ from: number(),
16968
+ to: number(),
16969
+ bucketMs: number().int().positive()
16970
+ }), object({ buckets: array(object({
16971
+ bucketStart: number(),
16972
+ count: number().int()
16973
+ })) }), { auth: "admin" }), method(object({
16974
+ ...KindShape,
16975
+ op: _enum([
16976
+ "sum",
16977
+ "min",
16978
+ "max",
16979
+ "count"
16980
+ ]),
16981
+ field: RecordFieldPathSchema.optional(),
16982
+ groupBy: RecordFieldPathSchema.optional(),
16983
+ where: RecordWhereSchema.optional()
16984
+ }), object({ rows: array(object({
16985
+ group: union([
16986
+ string(),
16987
+ number(),
16988
+ _null()
16989
+ ]),
16990
+ value: number().nullable()
16991
+ })) }), { auth: "admin" }), method(object({
16992
+ ...KindShape,
16993
+ deviceId: number().int().optional(),
16994
+ atBefore: number().optional(),
16995
+ where: RecordWhereSchema.optional()
16996
+ }), object({
16997
+ deleted: number().int(),
16998
+ secretRefs: SecretRefsList
16999
+ }), {
17000
+ kind: "mutation",
17001
+ auth: "admin"
17002
+ }), method(object({
17003
+ deviceId: number().int(),
17004
+ kinds: array(RecordKindNameSchema).optional()
17005
+ }), object({
17006
+ deleted: record(string(), number().int()),
17007
+ secretRefs: SecretRefsList
17008
+ }), {
17009
+ kind: "mutation",
17010
+ auth: "admin"
17011
+ }), method(object(KindShape), object({ id: number().int() }), {
17012
+ kind: "mutation",
17013
+ auth: "admin"
17014
+ });
17015
+ /** One table of the settings database. */
17016
+ var StorageTableSchema = object({
17017
+ /** The table's full name, e.g. `recorder:addon-settings` or `addon-device-settings`. */
17018
+ name: string(),
17019
+ /** The owner prefix of a scoped name (`recorder` for `recorder:addon-settings`), else null. */
17020
+ owner: string().nullable(),
17021
+ rows: number().int().nonnegative(),
17022
+ /** Bytes the table's pages occupy (`dbstat`); null when the engine cannot measure. */
17023
+ bytes: number().int().nonnegative().nullable(),
17024
+ /** Declared by an addon since this engine process started (a running addon claims it). */
17025
+ declaredThisBoot: boolean()
17026
+ });
17027
+ /** One declared record kind (D881) as System -> Data shows it. */
17028
+ var StorageKindSchema = object({
17029
+ owner: string(),
17030
+ kind: string(),
17031
+ database: _enum(["settings", "events"]),
17032
+ class: string(),
17033
+ state: _enum([
17034
+ "declared",
17035
+ "orphaned",
17036
+ "dropped"
17037
+ ]),
17038
+ /** `null` when the caller asked for no counts (`counts: false`). */
17039
+ rows: number().int().nonnegative().nullable(),
17040
+ /** Rows x the average size of a sample; null for an empty kind. */
17041
+ bytesEstimate: number().int().nonnegative().nullable(),
17042
+ writeTrigger: string(),
17043
+ retention: RecordRetentionSchema,
17044
+ /** `true` when the kind is an entry kind (the generic entries UI lists it). */
17045
+ entry: boolean(),
17046
+ /** The whole declaration, secret paths and entry descriptor included (the entries service builds its handle from it). */
17047
+ declaration: RecordKindDeclarationSchema
17048
+ });
17049
+ method(object({ ownerPrefix: string().min(1).optional() }), object({ tables: array(StorageTableSchema) }), { auth: "admin" }), method(object({
17050
+ collection: string().min(1),
17051
+ expectRows: number().int().nonnegative()
17052
+ }), object({
17053
+ dropped: literal(true),
17054
+ rows: number().int().nonnegative()
17055
+ }), {
17056
+ kind: "mutation",
17057
+ auth: "admin"
17058
+ }), method(object({
17059
+ owner: string().min(1).optional(),
17060
+ /** `false` skips the per-kind row count (a catalog read only). Default true. */
17061
+ counts: boolean().optional()
17062
+ }), object({ kinds: array(StorageKindSchema) }), { auth: "admin" }), method(RecordQueryInputSchema.extend({
17063
+ owner: string().min(1),
17064
+ kind: RecordKindNameSchema
17065
+ }), RecordQueryResultSchema, { auth: "admin" }), method(object({
17066
+ owner: string().min(1),
17067
+ kind: RecordKindNameSchema,
17068
+ records: array(RecordInputSchema).max(RECORD_BATCH_MAX),
17069
+ /** The LAST batch: the copy is complete, the boot guard stops asking. */
17070
+ complete: boolean().optional()
17071
+ }).refine((input) => input.records.length > 0 || input.complete === true, { message: "records must be non-empty unless complete is true" }), object({ adopted: number().int() }), {
17072
+ kind: "mutation",
17073
+ auth: "admin"
17074
+ }), method(object({
17075
+ collection: string().min(1),
17076
+ cursor: string().optional(),
17077
+ limit: number().int().min(1).max(1e3).optional()
17078
+ }), object({
17079
+ rows: array(object({
17080
+ id: string(),
17081
+ data: record(string(), unknown())
17082
+ })),
17083
+ nextCursor: string().nullable()
17084
+ }), { auth: "admin" }), method(object({ collection: string().min(1) }), object({ adopted: boolean() }), { auth: "admin" });
17085
+ /**
17086
+ * record-entries - the ONE admin surface for every list of user-created entries
17087
+ * (D881): notification targets, brokers, LLM profiles, anything an addon
17088
+ * declares as an ENTRY kind (`entry: { title }` in `defineRecordKinds`).
17089
+ *
17090
+ * The UI is generic. `listEntryKinds` hands it, per kind, the JSON Schema of
17091
+ * the entry body with `secret: true` on every credential field, so a password
17092
+ * field is derived from the schema and never from a name. `putEntry` takes the
17093
+ * redaction token for an untouched secret (the stored value is kept), a string
17094
+ * for a new one, and the clear instruction to remove one. A read never carries
17095
+ * a secret value, and a locked keychain refuses the write with
17096
+ * `records/secret-unavailable` instead of storing plaintext.
17097
+ *
17098
+ * Hub-only, served in-process (it acts for each entry's owner on the keychain).
17099
+ */
17100
+ var EntryKindInfoSchema = object({
17101
+ owner: string(),
17102
+ kind: RecordKindNameSchema,
17103
+ title: string(),
17104
+ nameField: string(),
17105
+ /** JSON Schema of the body; `secret: true` marks a password field. */
17106
+ fields: record(string(), unknown()),
17107
+ secretPaths: array(string()),
17108
+ rows: number().int().nonnegative()
17109
+ });
17110
+ var EntryViewSchema = object({
17111
+ id: RecordIdSchema,
17112
+ name: string(),
17113
+ rev: number().int(),
17114
+ updatedAt: number(),
17115
+ /** Secret fields hold the redaction token. */
17116
+ data: RecordBodySchema
17117
+ });
17118
+ var EntryAddress = {
17119
+ owner: string().min(1),
17120
+ kind: RecordKindNameSchema
17121
+ };
17122
+ method(object({}), object({ kinds: array(EntryKindInfoSchema) }), { auth: "admin" }), method(object({ ...EntryAddress }), object({ entries: array(EntryViewSchema) }), { auth: "admin" }), method(object({
17123
+ ...EntryAddress,
17124
+ id: RecordIdSchema.optional(),
17125
+ data: RecordBodySchema,
17126
+ ifRev: number().int().min(1).optional()
17127
+ }), object({
17128
+ id: string(),
17129
+ rev: number().int()
17130
+ }), {
17131
+ kind: "mutation",
17132
+ auth: "admin"
17133
+ }), method(object({
17134
+ ...EntryAddress,
17135
+ id: RecordIdSchema
17136
+ }), object({ deleted: boolean() }), {
17137
+ kind: "mutation",
17138
+ auth: "admin"
17139
+ });
17140
+ /**
16230
17141
  * `keychain` — the hub's encrypted store of secret values (D787).
16231
17142
  *
16232
17143
  * Settings blobs never hold a secret: they hold a marker
@@ -16767,6 +17678,16 @@ method(object({}), KeychainStatusSchema, { auth: "admin" }), method(object({}),
16767
17678
  kind: "mutation",
16768
17679
  auth: "admin",
16769
17680
  caller: "required"
17681
+ }), method(object({
17682
+ ref: string().min(1),
17683
+ value: string().min(1)
17684
+ }), object({
17685
+ ref: string(),
17686
+ version: number().int()
17687
+ }), {
17688
+ kind: "mutation",
17689
+ auth: "admin",
17690
+ caller: "required"
16770
17691
  }), method(object({ refs: array(string().min(1)).max(1e3) }), object({
16771
17692
  deleted: array(string()).readonly(),
16772
17693
  kept: array(object({
@@ -39445,6 +40366,9 @@ method(LlmGenerateBaseInputSchema, LlmGenerateResultSchema, {
39445
40366
  }), _void(), { kind: "mutation" }), method(object({}), array(LlmProfileKindDescriptorSchema)), method(object({}), array(LlmProfileSchema)), method(object({ profile: LlmProfileSchema }), LlmProfileSchema, {
39446
40367
  kind: "mutation",
39447
40368
  auth: "admin"
40369
+ }), method(RawSecretMigrationInputSchema, RawSecretMigrationReportSchema, {
40370
+ kind: "mutation",
40371
+ auth: "admin"
39448
40372
  }), method(ProfileRefInputSchema, _void(), {
39449
40373
  kind: "mutation",
39450
40374
  auth: "admin"
@@ -49954,6 +50878,41 @@ var ServerRollbackInfoSchema = object({
49954
50878
  atMs: number(),
49955
50879
  reason: string()
49956
50880
  });
50881
+ /**
50882
+ * The runner boot check (D877): the runners this node PLANNED (hub: one per
50883
+ * `resolveRunnerId` over its forked addons; agent: the runners its process
50884
+ * service holds, because only the hub plans) against the states the process
50885
+ * service reports. Kept in memory, recomputed by the same one-shot check after
50886
+ * every boot, served on `getServerPackageStatus`.
50887
+ *
50888
+ * `failed` is the D6 breaker's terminal state, `refused` a deterministic Init
50889
+ * refusal (an addon that said "I will not start, and here is why"), `missing` a
50890
+ * planned runner the process service has no entry for.
50891
+ */
50892
+ var RunnerRefusalSchema = object({
50893
+ runnerId: string(),
50894
+ addonIds: array(string()),
50895
+ reason: string()
50896
+ });
50897
+ var RunnerBootCheckSchema = object({
50898
+ checkedAtMs: number(),
50899
+ /** Runners planned for this node. */
50900
+ expected: number(),
50901
+ /** Planned runners whose process is `running`. */
50902
+ running: number(),
50903
+ failed: array(string()),
50904
+ refused: array(RunnerRefusalSchema),
50905
+ missing: array(string()),
50906
+ /**
50907
+ * Runners still on their way: `starting`, or `crashed` waiting on a backoff
50908
+ * respawn. The check is FINAL only when this is empty; until then nothing is
50909
+ * pushed and the verdict is re-evaluated on the next runner state change.
50910
+ * Optional for version skew (absent = settled).
50911
+ */
50912
+ pending: array(string()).optional(),
50913
+ /** True when the plan is the hub's (`missing` is then meaningful); false on an agent. */
50914
+ planKnown: boolean()
50915
+ });
49957
50916
  var ServerPackageStatusSchema = object({
49958
50917
  /** Root package name (`@camstack/server` on the hub). */
49959
50918
  packageName: string(),
@@ -50016,7 +50975,14 @@ var ServerPackageStatusSchema = object({
50016
50975
  * for version skew: an older provider's payload simply omits it, and an
50017
50976
  * absent wrapper is unknown — never `native`.
50018
50977
  */
50019
- wrapper: WrapperIdentitySchema.optional()
50978
+ wrapper: WrapperIdentitySchema.optional(),
50979
+ /**
50980
+ * What this node PLANNED to run against what its process service reports
50981
+ * (D877). Absent until the one-shot boot check has run (~60 s after boot) and
50982
+ * on a provider that predates it. Absent is "not checked yet", never "all
50983
+ * well": a consumer that needs the answer treats it as pending.
50984
+ */
50985
+ runners: RunnerBootCheckSchema.optional()
50020
50986
  });
50021
50987
  var ServerUpdateCheckResultSchema = object({
50022
50988
  packageName: string(),
@@ -50067,6 +51033,13 @@ var ServerUpdateOutcomeSchema = _enum([
50067
51033
  "refused",
50068
51034
  "failed"
50069
51035
  ]);
51036
+ /** One addon the pre-flight found the target version would refuse (D877). */
51037
+ var UpdateBlockerSchema = object({
51038
+ addonId: string(),
51039
+ reason: string(),
51040
+ /** What the operator does about it. */
51041
+ remedy: string()
51042
+ });
50070
51043
  var ServerUpdateActionResultSchema = object({
50071
51044
  accepted: boolean(),
50072
51045
  targetVersion: string().nullable(),
@@ -50084,14 +51057,27 @@ var ServerUpdateActionResultSchema = object({
50084
51057
  * The failure itself, verbatim enough to act on (the npm output for a
50085
51058
  * staging install). Non-null only for `failed`.
50086
51059
  */
50087
- error: string().nullable().optional()
51060
+ error: string().nullable().optional(),
51061
+ /**
51062
+ * The addons the target version would refuse to start on this node's live
51063
+ * store (D877), present when the pre-flight refused the update
51064
+ * (`reason: 'addon-would-refuse'`). Optional for version skew.
51065
+ */
51066
+ blockers: array(UpdateBlockerSchema).optional()
50088
51067
  });
50089
51068
  method(_void(), ServerPackageStatusSchema, { auth: "admin" }), method(_void(), ServerUpdateCheckResultSchema, {
50090
51069
  kind: "mutation",
50091
51070
  auth: "admin"
50092
- }), method(object({
50093
- /** Explicit target version; omitted = latest from the registry. */
50094
- version: string().optional() }), ServerUpdateActionResultSchema, {
51071
+ }), method(object({
51072
+ /** Explicit target version; omitted = latest from the registry. */
51073
+ version: string().optional(),
51074
+ /**
51075
+ * Apply even though the pre-flight (D877) found addons the target would
51076
+ * refuse to start. Off by default: those addons stay down until the
51077
+ * remedy is run, which is the incident this gate exists to prevent.
51078
+ */
51079
+ acknowledgeRefusals: boolean().optional()
51080
+ }), ServerUpdateActionResultSchema, {
50095
51081
  kind: "mutation",
50096
51082
  auth: "admin",
50097
51083
  timeoutMs: 16 * 6e4
@@ -52537,7 +53523,9 @@ var ManifestShapeSchema = object({
52537
53523
  var AddonProcessSchema = object({
52538
53524
  pid: number().optional(),
52539
53525
  mode: string(),
52540
- state: string()
53526
+ state: string(),
53527
+ /** Why the runner is `refused` (an addon's own words), when it is (D877). */
53528
+ reason: string().optional()
52541
53529
  });
52542
53530
  /**
52543
53531
  * Per-addon health snapshot from the kernel's AddonHealthMonitor.
@@ -53943,6 +54931,12 @@ var ClimateControlStatusSchema = object({
53943
54931
  /** Horizontal louver swing on/off. Null when the device has no
53944
54932
  * horizontal swing surface (gate with `DeviceFeature.ClimateSwingHorizontal`). */
53945
54933
  swingHorizontal: boolean().nullable(),
54934
+ /** Lowest setpoint the device accepts, Celsius. Absent / null = not reported. */
54935
+ minTemp: number().nullable().optional(),
54936
+ /** Highest setpoint the device accepts, Celsius. Absent / null = not reported. */
54937
+ maxTemp: number().nullable().optional(),
54938
+ /** Setpoint granularity, Celsius (0.5, 1). Absent / null = not reported. */
54939
+ tempStep: number().positive().nullable().optional(),
53946
54940
  /** Ms epoch when the slice was last updated (push or command). */
53947
54941
  lastFetchedAt: number()
53948
54942
  });
@@ -56723,7 +57717,19 @@ var TlsStatusSchema = object({
56723
57717
  sans: array(string()),
56724
57718
  caCertPem: string().nullable(),
56725
57719
  reissueError: string().nullable(),
56726
- restartRequired: boolean()
57720
+ restartRequired: boolean(),
57721
+ /** An uploaded certificate is served but no CA is kept for it and it is not publicly signed (D873). */
57722
+ caMissing: boolean(),
57723
+ /** Does the hub's own generated CA carry a critical name constraint? `null` while it has none. */
57724
+ localCaConstrained: boolean().nullable(),
57725
+ /** ISO time the generated CA was replaced by a constrained one; devices must re-download it. */
57726
+ caReplacedAt: string().nullable(),
57727
+ /** The uploaded certificate kept on disk, selectable again after "Revert to generated". */
57728
+ storedUpload: object({
57729
+ leafFingerprintSha256: string(),
57730
+ validTo: string(),
57731
+ hasCa: boolean()
57732
+ }).nullable()
56727
57733
  });
56728
57734
  method(_void(), ListResultSchema), method(_void(), PreferredSchema), method(object({
56729
57735
  /**
@@ -56779,6 +57785,9 @@ method(_void(), ListResultSchema), method(_void(), PreferredSchema), method(obje
56779
57785
  }), method(_void(), object({ pem: string() })), method(_void(), TlsStatusSchema, {
56780
57786
  kind: "mutation",
56781
57787
  auth: "admin"
57788
+ }), method(_void(), TlsStatusSchema, {
57789
+ kind: "mutation",
57790
+ auth: "admin"
56782
57791
  });
56783
57792
  var LockControlStatusSchema = object({
56784
57793
  /** Lifecycle state of the lock. `jammed` means the motor reported
@@ -63272,7 +64281,11 @@ method(_void(), array(UserSummarySchema), { auth: "admin" }), method(CreateUserI
63272
64281
  kind: "mutation",
63273
64282
  auth: "admin",
63274
64283
  access: "delete"
63275
- }), method(object({ userId: string() }), TotpStatusSchema, { auth: "admin" }), method(object({
64284
+ }), method(object({ userId: string() }), TotpStatusSchema, { auth: "admin" }), method(RawSecretMigrationInputSchema, RawSecretMigrationReportSchema, {
64285
+ kind: "mutation",
64286
+ auth: "admin",
64287
+ access: "create"
64288
+ }), method(object({
63276
64289
  userId: string(),
63277
64290
  code: string()
63278
64291
  }), object({ valid: boolean() }), {
@@ -65084,13 +66097,14 @@ var BaseDevice = class {
65084
66097
  get state() {
65085
66098
  if (!this._stateProxyCache) {
65086
66099
  const cache = {};
65087
- const handler = { get: (_target, key) => {
66100
+ const handler = { get: (target, key) => {
65088
66101
  const k = key;
65089
- if (k in cache) return cache[k];
66102
+ const existing = Reflect.get(target, k);
66103
+ if (existing !== void 0) return existing;
65090
66104
  const cap = DEVICE_LOCAL_STATE_CAPS[k];
65091
66105
  if (!cap) return void 0;
65092
66106
  const proxy = this.sliceProxy(cap);
65093
- cache[k] = proxy;
66107
+ Reflect.set(target, k, proxy);
65094
66108
  return proxy;
65095
66109
  } };
65096
66110
  this._stateProxyCache = new Proxy(cache, handler);
@@ -65289,7 +66303,7 @@ var BaseDevice = class {
65289
66303
  async updateSourceInfo(patch) {
65290
66304
  const next = mergeSourceInfo(this.sourceInfo, patch);
65291
66305
  this._sourceInfoCache = Object.freeze({ ...next });
65292
- const action = this.ctx.api?.deviceManager?.setMetadata;
66306
+ const action = this.ctx.api.deviceManager?.setMetadata;
65293
66307
  if (action) try {
65294
66308
  await action.mutate({
65295
66309
  deviceId: this.id,
@@ -65324,7 +66338,7 @@ var BaseDevice = class {
65324
66338
  * device boot on a meta refresh.
65325
66339
  */
65326
66340
  async refreshFeatures() {
65327
- const action = this.ctx.api?.deviceManager?.registerDevice;
66341
+ const action = this.ctx.api.deviceManager?.registerDevice;
65328
66342
  if (!action) return;
65329
66343
  try {
65330
66344
  await action.mutate({
@@ -67398,6 +68412,12 @@ Object.freeze({
67398
68412
  addonId: null,
67399
68413
  access: "view"
67400
68414
  },
68415
+ "coreBlocks.migrateRawSecrets": {
68416
+ capName: "core-blocks",
68417
+ capScope: "system",
68418
+ addonId: null,
68419
+ access: "create"
68420
+ },
67401
68421
  "coreBlocks.restart": {
67402
68422
  capName: "core-blocks",
67403
68423
  capScope: "system",
@@ -69084,6 +70104,12 @@ Object.freeze({
69084
70104
  addonId: null,
69085
70105
  access: "create"
69086
70106
  },
70107
+ "keychainAdmin.importSecret": {
70108
+ capName: "keychain-admin",
70109
+ capScope: "system",
70110
+ addonId: null,
70111
+ access: "create"
70112
+ },
69087
70113
  "keychainAdmin.listAudit": {
69088
70114
  capName: "keychain-admin",
69089
70115
  capScope: "system",
@@ -69252,6 +70278,12 @@ Object.freeze({
69252
70278
  addonId: null,
69253
70279
  access: "view"
69254
70280
  },
70281
+ "llm.migrateRawSecrets": {
70282
+ capName: "llm",
70283
+ capScope: "system",
70284
+ addonId: null,
70285
+ access: "create"
70286
+ },
69255
70287
  "llm.resolveModelRef": {
69256
70288
  capName: "llm",
69257
70289
  capScope: "system",
@@ -69480,6 +70512,12 @@ Object.freeze({
69480
70512
  addonId: null,
69481
70513
  access: "create"
69482
70514
  },
70515
+ "localNetwork.useStoredUploadedCertificate": {
70516
+ capName: "local-network",
70517
+ capScope: "system",
70518
+ addonId: null,
70519
+ access: "create"
70520
+ },
69483
70521
  "lockControl.getStatus": {
69484
70522
  capName: "lock-control",
69485
70523
  capScope: "device",
@@ -72132,6 +73170,30 @@ Object.freeze({
72132
73170
  addonId: null,
72133
73171
  access: "create"
72134
73172
  },
73173
+ "recordEntries.deleteEntry": {
73174
+ capName: "record-entries",
73175
+ capScope: "system",
73176
+ addonId: null,
73177
+ access: "delete"
73178
+ },
73179
+ "recordEntries.listEntries": {
73180
+ capName: "record-entries",
73181
+ capScope: "system",
73182
+ addonId: null,
73183
+ access: "view"
73184
+ },
73185
+ "recordEntries.listEntryKinds": {
73186
+ capName: "record-entries",
73187
+ capScope: "system",
73188
+ addonId: null,
73189
+ access: "view"
73190
+ },
73191
+ "recordEntries.putEntry": {
73192
+ capName: "record-entries",
73193
+ capScope: "system",
73194
+ addonId: null,
73195
+ access: "create"
73196
+ },
72135
73197
  "recording.getAvailability": {
72136
73198
  capName: "recording",
72137
73199
  capScope: "device",
@@ -72432,6 +73494,102 @@ Object.freeze({
72432
73494
  addonId: null,
72433
73495
  access: "view"
72434
73496
  },
73497
+ "records.aggregate": {
73498
+ capName: "records",
73499
+ capScope: "system",
73500
+ addonId: null,
73501
+ access: "view"
73502
+ },
73503
+ "records.allocateId": {
73504
+ capName: "records",
73505
+ capScope: "system",
73506
+ addonId: null,
73507
+ access: "create"
73508
+ },
73509
+ "records.count": {
73510
+ capName: "records",
73511
+ capScope: "system",
73512
+ addonId: null,
73513
+ access: "view"
73514
+ },
73515
+ "records.declareKinds": {
73516
+ capName: "records",
73517
+ capScope: "system",
73518
+ addonId: null,
73519
+ access: "create"
73520
+ },
73521
+ "records.delete": {
73522
+ capName: "records",
73523
+ capScope: "system",
73524
+ addonId: null,
73525
+ access: "delete"
73526
+ },
73527
+ "records.deleteDevice": {
73528
+ capName: "records",
73529
+ capScope: "system",
73530
+ addonId: null,
73531
+ access: "delete"
73532
+ },
73533
+ "records.deleteMany": {
73534
+ capName: "records",
73535
+ capScope: "system",
73536
+ addonId: null,
73537
+ access: "delete"
73538
+ },
73539
+ "records.deleteWhere": {
73540
+ capName: "records",
73541
+ capScope: "system",
73542
+ addonId: null,
73543
+ access: "delete"
73544
+ },
73545
+ "records.get": {
73546
+ capName: "records",
73547
+ capScope: "system",
73548
+ addonId: null,
73549
+ access: "view"
73550
+ },
73551
+ "records.getMany": {
73552
+ capName: "records",
73553
+ capScope: "system",
73554
+ addonId: null,
73555
+ access: "view"
73556
+ },
73557
+ "records.histogram": {
73558
+ capName: "records",
73559
+ capScope: "system",
73560
+ addonId: null,
73561
+ access: "view"
73562
+ },
73563
+ "records.patch": {
73564
+ capName: "records",
73565
+ capScope: "system",
73566
+ addonId: null,
73567
+ access: "create"
73568
+ },
73569
+ "records.put": {
73570
+ capName: "records",
73571
+ capScope: "system",
73572
+ addonId: null,
73573
+ access: "create"
73574
+ },
73575
+ "records.putMany": {
73576
+ capName: "records",
73577
+ capScope: "system",
73578
+ addonId: null,
73579
+ access: "create"
73580
+ },
73581
+ "records.query": {
73582
+ capName: "records",
73583
+ capScope: "system",
73584
+ addonId: null,
73585
+ access: "view"
73586
+ },
73587
+ "records.secretRefs": {
73588
+ capName: "records",
73589
+ capScope: "system",
73590
+ addonId: null,
73591
+ access: "view"
73592
+ },
72435
73593
  "sceneMonitor.captureReference": {
72436
73594
  capName: "scene-monitor",
72437
73595
  capScope: "device",
@@ -72864,6 +74022,48 @@ Object.freeze({
72864
74022
  addonId: null,
72865
74023
  access: "create"
72866
74024
  },
74025
+ "storageAdmin.adoptRecords": {
74026
+ capName: "storage-admin",
74027
+ capScope: "system",
74028
+ addonId: null,
74029
+ access: "create"
74030
+ },
74031
+ "storageAdmin.dropCollection": {
74032
+ capName: "storage-admin",
74033
+ capScope: "system",
74034
+ addonId: null,
74035
+ access: "delete"
74036
+ },
74037
+ "storageAdmin.isAdoptedLegacyTable": {
74038
+ capName: "storage-admin",
74039
+ capScope: "system",
74040
+ addonId: null,
74041
+ access: "view"
74042
+ },
74043
+ "storageAdmin.listKinds": {
74044
+ capName: "storage-admin",
74045
+ capScope: "system",
74046
+ addonId: null,
74047
+ access: "view"
74048
+ },
74049
+ "storageAdmin.listTables": {
74050
+ capName: "storage-admin",
74051
+ capScope: "system",
74052
+ addonId: null,
74053
+ access: "view"
74054
+ },
74055
+ "storageAdmin.readLegacyCollection": {
74056
+ capName: "storage-admin",
74057
+ capScope: "system",
74058
+ addonId: null,
74059
+ access: "view"
74060
+ },
74061
+ "storageAdmin.readRecords": {
74062
+ capName: "storage-admin",
74063
+ capScope: "system",
74064
+ addonId: null,
74065
+ access: "view"
74066
+ },
72867
74067
  "storageEvictable.evict": {
72868
74068
  capName: "storage-evictable",
72869
74069
  capScope: "system",
@@ -73776,6 +74976,12 @@ Object.freeze({
73776
74976
  addonId: null,
73777
74977
  access: "view"
73778
74978
  },
74979
+ "userManagement.migrateRawSecrets": {
74980
+ capName: "user-management",
74981
+ capScope: "system",
74982
+ addonId: null,
74983
+ access: "create"
74984
+ },
73779
74985
  "userManagement.oauthExchangeCode": {
73780
74986
  capName: "user-management",
73781
74987
  capScope: "system",
@@ -76452,6 +77658,37 @@ Object.freeze({
76452
77658
  form: "single",
76453
77659
  optional: false
76454
77660
  }],
77661
+ "records.count": [{
77662
+ name: "deviceId",
77663
+ form: "single",
77664
+ optional: true
77665
+ }],
77666
+ "records.deleteDevice": [{
77667
+ name: "deviceId",
77668
+ form: "single",
77669
+ optional: false
77670
+ }],
77671
+ "records.deleteWhere": [{
77672
+ name: "deviceId",
77673
+ form: "single",
77674
+ optional: true
77675
+ }],
77676
+ "records.histogram": [{
77677
+ name: "deviceId",
77678
+ form: "single",
77679
+ optional: true
77680
+ }],
77681
+ "records.putMany": [{
77682
+ name: "records",
77683
+ form: "object-array",
77684
+ optional: false,
77685
+ itemField: "deviceId"
77686
+ }],
77687
+ "records.query": [{
77688
+ name: "deviceId",
77689
+ form: "single",
77690
+ optional: true
77691
+ }],
76455
77692
  "sceneMonitor.captureReference": [{
76456
77693
  name: "deviceId",
76457
77694
  form: "single",
@@ -76568,6 +77805,17 @@ Object.freeze({
76568
77805
  form: "single",
76569
77806
  optional: false
76570
77807
  }],
77808
+ "storageAdmin.adoptRecords": [{
77809
+ name: "records",
77810
+ form: "object-array",
77811
+ optional: false,
77812
+ itemField: "deviceId"
77813
+ }],
77814
+ "storageAdmin.readRecords": [{
77815
+ name: "deviceId",
77816
+ form: "single",
77817
+ optional: true
77818
+ }],
76571
77819
  "streamBroker.acquireEgressTranscode": [{
76572
77820
  name: "deviceId",
76573
77821
  form: "single",
@@ -121507,6 +122755,70 @@ var AlexaDevice = class extends BaseDevice {
121507
122755
  function isKnownCap(cap) {
121508
122756
  return KNOWN_CAPS.has(cap);
121509
122757
  }
122758
+ var alexaBrokersEntryKind = defineEntryKind("brokers", {
122759
+ title: "Alexa import brokers",
122760
+ schema: entryBody({
122761
+ connection: AlexaBrokerEntrySchema.shape.connection,
122762
+ integrationId: string().optional()
122763
+ }),
122764
+ writeTrigger: "an operator links or removes an Alexa account broker",
122765
+ adoptsFrom: settingsBrokersAdoptsFrom("import-alexa")
122766
+ });
122767
+ //#endregion
122768
+ //#region src/alexa-broker-store.ts
122769
+ function rowToEntry(id, data) {
122770
+ const parsed = AlexaBrokerEntrySchema.safeParse({
122771
+ id,
122772
+ name: data.name,
122773
+ connection: data.connection,
122774
+ integrationId: data.integrationId
122775
+ });
122776
+ return parsed.success ? parsed.data : null;
122777
+ }
122778
+ var AlexaBrokerStore = class AlexaBrokerStore {
122779
+ kind;
122780
+ constructor(kind) {
122781
+ this.kind = kind;
122782
+ }
122783
+ static of(records) {
122784
+ return new AlexaBrokerStore(records.kind(alexaBrokersEntryKind));
122785
+ }
122786
+ async listResolved() {
122787
+ const page = await this.kind.query({ limit: 1e3 });
122788
+ const out = [];
122789
+ for (const record of page.records) {
122790
+ let data = record.data;
122791
+ try {
122792
+ const resolved = await this.kind.getResolved(record.id);
122793
+ if (resolved !== null) data = resolved.data;
122794
+ } catch (err) {
122795
+ if (!(err instanceof RecordSecretUnavailableError)) throw err;
122796
+ }
122797
+ const entry = rowToEntry(record.id, data);
122798
+ if (entry !== null) out.push(entry);
122799
+ }
122800
+ return out;
122801
+ }
122802
+ async replaceAll(entries) {
122803
+ const page = await this.kind.query({ limit: 1e3 });
122804
+ const nextIds = new Set(entries.map((e) => e.id));
122805
+ for (const row of page.records) if (!nextIds.has(row.id)) await this.kind.delete(row.id);
122806
+ for (const entry of entries) {
122807
+ const { id, name, connection, integrationId } = entry;
122808
+ const body = {
122809
+ name,
122810
+ connection,
122811
+ ...integrationId === void 0 ? {} : { integrationId }
122812
+ };
122813
+ const parsed = alexaBrokersEntryKind.schema.safeParse(body);
122814
+ if (!parsed.success) throw new Error(`invalid Alexa broker '${id}': ${parsed.error.message}`);
122815
+ await this.kind.put({
122816
+ id,
122817
+ data: parsed.data
122818
+ });
122819
+ }
122820
+ }
122821
+ };
121510
122822
  //#endregion
121511
122823
  //#region src/addon.ts
121512
122824
  /** Default config — a fresh install starts with no accounts. */
@@ -121554,11 +122866,18 @@ var AlexaImportAddon = class extends BaseDeviceProvider {
121554
122866
  deviceClasses = Object.fromEntries(ALEXA_DEVICE_TYPES.map((t) => [t, AlexaDevice]));
121555
122867
  registry = null;
121556
122868
  proxyLogin = null;
122869
+ brokerStore = null;
122870
+ activeBrokers = [];
121557
122871
  constructor() {
121558
122872
  super({ ...DEFAULTS });
121559
122873
  }
121560
122874
  async onInitialize() {
121561
122875
  const regs = await super.onInitialize();
122876
+ const records = this.ctx.records;
122877
+ if (records === void 0) throw new Error("import-alexa: ctx.records is required (hub-only addon)");
122878
+ await records.declare({ brokers: alexaBrokersEntryKind });
122879
+ this.brokerStore = AlexaBrokerStore.of(records);
122880
+ this.activeBrokers = await this.loadPersistedBrokers();
121562
122881
  this.registry = new AlexaBrokerRegistry(this.ctx.logger, {
121563
122882
  dataDir: this.ctx.dataDir,
121564
122883
  onBrokerConnected: (brokerId) => {
@@ -121583,7 +122902,7 @@ var AlexaImportAddon = class extends BaseDeviceProvider {
121583
122902
  }
121584
122903
  });
121585
122904
  alexaCommands.setDispatcher((brokerId, command) => this.requireRegistry().sendCommand(brokerId, command));
121586
- await this.registry.restore(this.config.brokers);
122905
+ await this.registry.restore(this.activeBrokers);
121587
122906
  this.proxyLogin = new AlexaProxyLoginManager({
121588
122907
  logger: this.ctx.logger,
121589
122908
  getProxyConfig: () => {
@@ -121594,7 +122913,7 @@ var AlexaImportAddon = class extends BaseDeviceProvider {
121594
122913
  };
121595
122914
  }
121596
122915
  });
121597
- this.ctx.logger.info("Alexa: import addon initialised", { meta: { brokerCount: this.config.brokers.length } });
122916
+ this.ctx.logger.info("Alexa: import addon initialised", { meta: { brokerCount: this.activeBrokers.length } });
121598
122917
  await this.reconcileIntegrationsToBrokers();
121599
122918
  this.subscribeIntegrationLifecycle();
121600
122919
  const loginRoutes = buildAlexaLoginRoutes({
@@ -121618,10 +122937,28 @@ var AlexaImportAddon = class extends BaseDeviceProvider {
121618
122937
  }
121619
122938
  ];
121620
122939
  }
122940
+ async loadPersistedBrokers() {
122941
+ const store = this.brokerStore;
122942
+ if (store !== null) {
122943
+ const fromRecords = await store.listResolved();
122944
+ if (fromRecords.length > 0) return fromRecords;
122945
+ }
122946
+ return this.config.brokers;
122947
+ }
122948
+ async persistBrokerEntries(entries) {
122949
+ this.activeBrokers = [...entries];
122950
+ const store = this.brokerStore;
122951
+ if (store !== null) {
122952
+ await store.replaceAll(entries);
122953
+ return;
122954
+ }
122955
+ await this.updateGlobalSettings({ brokers: [...entries] });
122956
+ }
121621
122957
  async onConfigChanged() {
121622
122958
  const reg = this.registry;
121623
122959
  if (!reg) return;
121624
- const persisted = this.config.brokers;
122960
+ this.activeBrokers = await this.loadPersistedBrokers();
122961
+ const persisted = this.activeBrokers;
121625
122962
  const liveIds = new Set(reg.list().map((b) => b.id));
121626
122963
  const persistedIds = new Set(persisted.map((e) => e.id));
121627
122964
  for (const liveId of liveIds) if (!persistedIds.has(liveId)) try {
@@ -121652,7 +122989,7 @@ var AlexaImportAddon = class extends BaseDeviceProvider {
121652
122989
  ...b,
121653
122990
  id: created.id
121654
122991
  } : b);
121655
- await this.updateGlobalSettings({ brokers: next });
122992
+ await this.persistBrokerEntries(next);
121656
122993
  }
121657
122994
  } catch (err) {
121658
122995
  this.ctx.logger.warn("Alexa onConfigChanged: failed to start new broker", { meta: {
@@ -121740,8 +123077,8 @@ var AlexaImportAddon = class extends BaseDeviceProvider {
121740
123077
  return buildAlexaBrokerProvider({
121741
123078
  ownerAddonId: this.ctx.id,
121742
123079
  registry: this.requireRegistry(),
121743
- getBrokers: () => this.config.brokers,
121744
- persistBrokers: (brokers) => this.updateGlobalSettings({ brokers: [...brokers] }),
123080
+ getBrokers: () => this.activeBrokers,
123081
+ persistBrokers: (brokers) => this.persistBrokerEntries(brokers),
121745
123082
  cascadeRemoveDevices: (brokerId) => this.cascadeRemoveDevicesForBroker(brokerId),
121746
123083
  logger: this.ctx.logger
121747
123084
  });
@@ -121756,7 +123093,7 @@ var AlexaImportAddon = class extends BaseDeviceProvider {
121756
123093
  async commitCapturedCookie(input) {
121757
123094
  const reg = this.requireRegistry();
121758
123095
  if (input.brokerId !== void 0) {
121759
- const existing = this.config.brokers.find((b) => b.id === input.brokerId);
123096
+ const existing = this.activeBrokers.find((b) => b.id === input.brokerId);
121760
123097
  if (existing === void 0) throw new Error(`commitCookie: unknown broker "${input.brokerId}"`);
121761
123098
  const connection = {
121762
123099
  ...existing.connection,
@@ -121764,7 +123101,7 @@ var AlexaImportAddon = class extends BaseDeviceProvider {
121764
123101
  cookie: input.cookie
121765
123102
  };
121766
123103
  const updated = await reg.updateEntry(input.brokerId, connection);
121767
- await this.updateGlobalSettings({ brokers: this.config.brokers.map((b) => b.id === input.brokerId ? updated : b) });
123104
+ await this.persistBrokerEntries(this.activeBrokers.map((b) => b.id === input.brokerId ? updated : b));
121768
123105
  this.ctx.logger.info("Alexa: proxy-login cookie committed to existing broker", { meta: { brokerId: input.brokerId } });
121769
123106
  return { brokerId: input.brokerId };
121770
123107
  }
@@ -121773,7 +123110,7 @@ var AlexaImportAddon = class extends BaseDeviceProvider {
121773
123110
  cookie: input.cookie
121774
123111
  });
121775
123112
  const entry = await reg.createEntry(input.name, connection);
121776
- await this.updateGlobalSettings({ brokers: [...this.config.brokers, entry] });
123113
+ await this.persistBrokerEntries([...this.activeBrokers, entry]);
121777
123114
  this.ctx.logger.info("Alexa: proxy-login cookie committed to new broker", { meta: {
121778
123115
  brokerId: entry.id,
121779
123116
  name: input.name
@@ -121800,7 +123137,7 @@ var AlexaImportAddon = class extends BaseDeviceProvider {
121800
123137
  const settings = await this.ctx.api.integrations.getSettings.query({ id: integration.id });
121801
123138
  const brokerId = typeof settings["brokerId"] === "string" ? settings["brokerId"] : void 0;
121802
123139
  if (brokerId === void 0) continue;
121803
- if (!this.config.brokers.some((b) => b.id === brokerId)) {
123140
+ if (!this.activeBrokers.some((b) => b.id === brokerId)) {
121804
123141
  this.ctx.logger.warn("Alexa integration→broker: linked broker not found", { meta: {
121805
123142
  integrationId: integration.id,
121806
123143
  brokerId
@@ -121809,7 +123146,7 @@ var AlexaImportAddon = class extends BaseDeviceProvider {
121809
123146
  }
121810
123147
  this.requireRegistry().linkIntegration(integration.id, brokerId);
121811
123148
  }
121812
- const toRemove = this.config.brokers.filter((b) => b.integrationId !== void 0 && !surviving.has(b.integrationId)).map((b) => b.id);
123149
+ const toRemove = this.activeBrokers.filter((b) => b.integrationId !== void 0 && !surviving.has(b.integrationId)).map((b) => b.id);
121813
123150
  if (toRemove.length === 0) return;
121814
123151
  for (const id of toRemove) try {
121815
123152
  await this.requireRegistry().removeEntry(id);
@@ -121820,8 +123157,8 @@ var AlexaImportAddon = class extends BaseDeviceProvider {
121820
123157
  error: errMsg(err)
121821
123158
  } });
121822
123159
  }
121823
- const nextBrokers = this.config.brokers.filter((b) => !toRemove.includes(b.id));
121824
- await this.updateGlobalSettings({ brokers: nextBrokers });
123160
+ const nextBrokers = this.activeBrokers.filter((b) => !toRemove.includes(b.id));
123161
+ await this.persistBrokerEntries(nextBrokers);
121825
123162
  } catch (err) {
121826
123163
  this.ctx.logger.warn("Alexa integration→broker reconcile failed", { meta: { error: errMsg(err) } });
121827
123164
  }