@camstack/addon-provider-reolink 1.2.178 → 1.2.180

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 +2080 -66
  2. package/dist/addon.mjs +2080 -66
  3. package/package.json +1 -1
package/dist/addon.js CHANGED
@@ -35,7 +35,7 @@ let node_os = require("node:os");
35
35
  node_os = require_chunk.__toESM(node_os);
36
36
  let node_fs = require("node:fs");
37
37
  node_fs = require_chunk.__toESM(node_fs, 1);
38
- //#region ../types/dist/event-category-B_0XEcLF.mjs
38
+ //#region ../types/dist/event-category-DaIZi00R.mjs
39
39
  var EventCategory = /* @__PURE__ */ function(EventCategory) {
40
40
  EventCategory["SystemBoot"] = "system.boot";
41
41
  EventCategory["SystemAddonsReady"] = "system.addons-ready";
@@ -114,6 +114,13 @@ var EventCategory = /* @__PURE__ */ function(EventCategory) {
114
114
  */
115
115
  EventCategory["AddonLoadFailed"] = "addon.load-failed";
116
116
  /**
117
+ * A keychain value was stored or removed (D787). Carries the ref, its
118
+ * owner and the new version — NEVER the value. A process holding the ref
119
+ * drops its cached copy and the owning `BaseAddon` re-resolves its config.
120
+ * Telemetry (D8): a process that misses it still revalidates by version.
121
+ */
122
+ EventCategory["KeychainChanged"] = "keychain.changed";
123
+ /**
117
124
  * Addon recovered from a previous failure. Emitted when an addon
118
125
  * transitions from `failed` back to `healthy` (typically via the
119
126
  * monitor's auto-retry loop, or after manual `addons.retryLoad`).
@@ -5406,7 +5413,7 @@ var ZodIssueCode = {
5406
5413
  var ZodFirstPartyTypeKind;
5407
5414
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
5408
5415
  //#endregion
5409
- //#region ../types/dist/sleep-B0JG7-_F.mjs
5416
+ //#region ../types/dist/sleep-DujUvOcb.mjs
5410
5417
  /**
5411
5418
  * The audio chunk plane's byte format, and the ONE expansion from a coded
5412
5419
  * window to float samples (D455).
@@ -5485,6 +5492,97 @@ function buildAlawTable() {
5485
5492
  }
5486
5493
  buildUlawTable();
5487
5494
  buildAlawTable();
5495
+ /** Is this field's stored value a credential? */
5496
+ function isSecretConfigField(field) {
5497
+ if (field.type === "password") return true;
5498
+ return "secret" in field && field.secret === true;
5499
+ }
5500
+ /**
5501
+ * Is this field's value stored in the KEYCHAIN (D787)? Every secret field is,
5502
+ * by its TYPE, unless it opts out with `storage: 'inline'` — never by its name.
5503
+ */
5504
+ function isKeychainStoredField(field) {
5505
+ if (!isSecretConfigField(field)) return false;
5506
+ if (field.type === "textarea" && field.isJson === true) return false;
5507
+ return !("storage" in field && field.storage === "inline");
5508
+ }
5509
+ /**
5510
+ * What a settings blob holds where a secret used to be.
5511
+ *
5512
+ * A keychain-stored field never holds its value. It holds a self-describing
5513
+ * MARKER, `{"$secret":"secret://…","v":1}` — an object, never a string, so no
5514
+ * code can mistake it for a credential and no form can send it to a camera as
5515
+ * a password. The empty state is `null` / absent, never `''`.
5516
+ *
5517
+ * The same shapes travel to and from the admin UI:
5518
+ *
5519
+ * - read: `hydrateSchema` hands a secret field a {@link SecretFieldView}
5520
+ * (`{ $secret, v, set: true }`) or `null` — the browser learns whether a
5521
+ * value is set, never the value.
5522
+ * - write: an untouched field submits the view back unchanged (KEEP); a typed
5523
+ * value is a plain non-empty string (CHANGE); the Clear button submits
5524
+ * {@link SECRET_CLEAR} (CLEAR). `''`, `null` and the legacy redaction tokens
5525
+ * are KEEP — an empty string is what a defaults-fallback pushes back, and
5526
+ * treating it as "clear" is how a save destroyed a stored credential before.
5527
+ *
5528
+ * Pure and browser-safe.
5529
+ */
5530
+ var SECRET_CLEAR = { $secretClear: true };
5531
+ /** The `'***'` token D634 redaction writes for non-admins. */
5532
+ var LEGACY_DEVICE_REDACTION = "***";
5533
+ function isRecord$1(value) {
5534
+ return typeof value === "object" && value !== null && !Array.isArray(value);
5535
+ }
5536
+ function makeSecretMarker(ref) {
5537
+ return {
5538
+ $secret: ref,
5539
+ v: 1
5540
+ };
5541
+ }
5542
+ /** A stored marker: an object whose `$secret` is a non-empty string. */
5543
+ function isSecretMarker(value) {
5544
+ if (!isRecord$1(value)) return false;
5545
+ const ref = value["$secret"];
5546
+ return typeof ref === "string" && ref.length > 0;
5547
+ }
5548
+ function isSecretClear(value) {
5549
+ return isRecord$1(value) && value["$secretClear"] === true;
5550
+ }
5551
+ /**
5552
+ * The UI view of a stored secret field value: a marker becomes "set", inline
5553
+ * plaintext becomes "set (inline)", nothing becomes `null`. A value never
5554
+ * survives this function.
5555
+ */
5556
+ function toSecretFieldView(stored) {
5557
+ if (isSecretMarker(stored)) return {
5558
+ $secret: stored.$secret,
5559
+ v: 1,
5560
+ set: true
5561
+ };
5562
+ if (typeof stored === "string" && stored.length > 0) return {
5563
+ $secret: null,
5564
+ v: 1,
5565
+ set: true,
5566
+ inline: true
5567
+ };
5568
+ return null;
5569
+ }
5570
+ /**
5571
+ * Classify an incoming value for a secret path. Only a non-empty string that is
5572
+ * not a redaction token sets a value; only {@link SECRET_CLEAR} clears.
5573
+ * Everything else — a marker (ours or anyone's), a UI view, `''`, `null`,
5574
+ * `undefined`, a redaction token, a non-string — keeps what is stored.
5575
+ */
5576
+ function classifySecretWrite(incoming) {
5577
+ if (isSecretClear(incoming)) return { kind: "clear" };
5578
+ if (typeof incoming !== "string") return { kind: "keep" };
5579
+ if (incoming.length === 0) return { kind: "keep" };
5580
+ if (incoming === "__camstack_redacted__" || incoming === LEGACY_DEVICE_REDACTION) return { kind: "keep" };
5581
+ return {
5582
+ kind: "set",
5583
+ value: incoming
5584
+ };
5585
+ }
5488
5586
  Object.fromEntries([
5489
5587
  {
5490
5588
  id: "overview",
@@ -5656,33 +5754,19 @@ Object.fromEntries([
5656
5754
  function isValuelessField(field) {
5657
5755
  return field.type === "separator" || field.type === "info" || field.type === "qr-code" || field.type === "button" || field.type === "object-array" || field.type === "widget" || field.type === "addon-action-button" || field.type === "device-action-button";
5658
5756
  }
5659
- /**
5660
- * Merge a `ConfigUISchema` with a raw `values` record into a
5661
- * `ConfigUISchemaWithValues`. Used by every `get*Settings` backend endpoint
5662
- * before returning to the admin UI. Groups are walked recursively.
5663
- *
5664
- * For each leaf field:
5665
- * - structural fields (`separator`, `info`, `button`) pass through unchanged
5666
- * - other fields get `value = values[key] ?? field.default ?? null`
5667
- *
5668
- * Unknown keys in `values` (keys not declared in the schema) are silently
5669
- * ignored — they don't contribute to the output. Missing keys fall back to
5670
- * the schema default or `null`. This mirrors the old backend behaviour where
5671
- * `FormBuilder` rendered `values[key] ?? field.default`.
5672
- */
5673
- function hydrateSchema(schema, values) {
5757
+ function hydrateSchema(schema, values, options = {}) {
5674
5758
  return {
5675
5759
  ...schema.tabs ? { tabs: [...schema.tabs] } : {},
5676
5760
  sections: schema.sections.map((section) => ({
5677
5761
  ...section,
5678
- fields: section.fields.map((field) => hydrateField(field, values))
5762
+ fields: section.fields.map((field) => hydrateField(field, values, options))
5679
5763
  }))
5680
5764
  };
5681
5765
  }
5682
- function hydrateField(field, values) {
5766
+ function hydrateField(field, values, options) {
5683
5767
  if (isValuelessField(field)) return field;
5684
5768
  if (field.type === "group") {
5685
- const hydratedChildren = field.fields.map((child) => hydrateField(child, values));
5769
+ const hydratedChildren = field.fields.map((child) => hydrateField(child, values, options));
5686
5770
  return {
5687
5771
  ...field,
5688
5772
  fields: hydratedChildren
@@ -5691,7 +5775,7 @@ function hydrateField(field, values) {
5691
5775
  if (field.type === "sub-tabs") {
5692
5776
  const hydratedTabs = field.tabs.map((tab) => ({
5693
5777
  ...tab,
5694
- fields: tab.fields.map((child) => hydrateField(child, values))
5778
+ fields: tab.fields.map((child) => hydrateField(child, values, options))
5695
5779
  }));
5696
5780
  return {
5697
5781
  ...field,
@@ -5701,6 +5785,33 @@ function hydrateField(field, values) {
5701
5785
  const key = field.key;
5702
5786
  const storedValue = Object.prototype.hasOwnProperty.call(values, key) ? values[key] : void 0;
5703
5787
  const defaultValue = field.default;
5788
+ const asView = (v) => isSecretMarker(v) || options.inlineSecretsAsViews === true && v !== void 0;
5789
+ if (isKeychainStoredField(field) && asView(storedValue)) return {
5790
+ ...field,
5791
+ value: toSecretFieldView(storedValue)
5792
+ };
5793
+ if (isKeychainStoredField(field) && options.inlineSecretsAsViews === true) return {
5794
+ ...field,
5795
+ value: null
5796
+ };
5797
+ if (field.type === "editable-array" && Array.isArray(storedValue)) {
5798
+ const secretItemKeys = field.itemFields.filter((item) => "key" in item && isKeychainStoredField(item)).map((item) => "key" in item ? item.key : "");
5799
+ if (secretItemKeys.length > 0) {
5800
+ const rows = storedValue.map((row) => {
5801
+ if (row === null || typeof row !== "object" || Array.isArray(row)) return row;
5802
+ const out = { ...row };
5803
+ for (const k of secretItemKeys) {
5804
+ const v = Reflect.get(row, k);
5805
+ if (asView(v)) out[k] = toSecretFieldView(v);
5806
+ }
5807
+ return out;
5808
+ });
5809
+ return {
5810
+ ...field,
5811
+ value: rows
5812
+ };
5813
+ }
5814
+ }
5704
5815
  if (field.multiple) {
5705
5816
  const stored = Array.isArray(storedValue) ? storedValue : storedValue !== void 0 && storedValue !== null ? [storedValue] : [];
5706
5817
  const itemFallback = field.multiple.itemDefault !== void 0 ? field.multiple.itemDefault : defaultValue !== void 0 ? defaultValue : typeOf(field) === "string" ? "" : null;
@@ -5943,6 +6054,431 @@ function projectStore(store, perNodeKeys, nodeId) {
5943
6054
  }
5944
6055
  return out;
5945
6056
  }
6057
+ var GLOBAL_SCOPE = { kind: "global" };
6058
+ /** The scope every addon-wide (not per-node, not per-device) setting lives in. */
6059
+ function globalSecretScope() {
6060
+ return GLOBAL_SCOPE;
6061
+ }
6062
+ function encodeSegment(value) {
6063
+ return encodeURIComponent(value);
6064
+ }
6065
+ /**
6066
+ * The field path of a value inside an array item, addressed by the item's id:
6067
+ * `arrayItemFieldPath('providers', 'authentik', 'clientSecret')` →
6068
+ * `providers[authentik].clientSecret`.
6069
+ */
6070
+ function arrayItemFieldPath(arrayKey, itemId, fieldKey) {
6071
+ return `${arrayKey}[${encodeSegment(itemId)}].${fieldKey}`;
6072
+ }
6073
+ /** A write to a secret path could not be stored in the keychain, so it was refused. */
6074
+ var KeychainWriteRefusedError = class extends Error {
6075
+ fieldPath;
6076
+ constructor(fieldPath, cause) {
6077
+ super(`secret "${fieldPath}" was not saved: the keychain could not store it (${cause instanceof Error ? cause.message : String(cause)}). Nothing was written.`);
6078
+ this.fieldPath = fieldPath;
6079
+ this.name = "KeychainWriteRefusedError";
6080
+ }
6081
+ };
6082
+ var KEEP = { kind: "keep" };
6083
+ function isRecord$2(value) {
6084
+ return typeof value === "object" && value !== null && !Array.isArray(value);
6085
+ }
6086
+ function defaultMintId() {
6087
+ return globalThis.crypto.randomUUID();
6088
+ }
6089
+ /** Every marker ref anywhere under `value`. */
6090
+ function collectSecretMarkerRefs(value, out = []) {
6091
+ if (isSecretMarker(value)) {
6092
+ out.push(value.$secret);
6093
+ return out;
6094
+ }
6095
+ if (Array.isArray(value)) for (const item of value) collectSecretMarkerRefs(item, out);
6096
+ else if (isRecord$2(value)) for (const child of Object.values(value)) collectSecretMarkerRefs(child, out);
6097
+ return out;
6098
+ }
6099
+ async function storedValueEquals(secrets, marker, candidate) {
6100
+ const resolved = (await secrets.resolve([marker.$secret]))[marker.$secret];
6101
+ return resolved?.kind === "value" && resolved.value === candidate;
6102
+ }
6103
+ async function writeLeaf(ctx, incoming, stored, fieldPath) {
6104
+ const intent = classifySecretWrite(incoming);
6105
+ const ref = ctx.secrets.ref(ctx.scope, fieldPath);
6106
+ const storedIsOurs = isSecretMarker(stored) && stored.$secret === ref;
6107
+ if (intent.kind === "keep") return KEEP;
6108
+ if (intent.kind === "set" && !ctx.operatorWrite && typeof stored === "string" && stored === intent.value) return KEEP;
6109
+ if (intent.kind === "clear") {
6110
+ if (storedIsOurs) ctx.deletes.push(ref);
6111
+ return {
6112
+ kind: "value",
6113
+ value: null
6114
+ };
6115
+ }
6116
+ if (storedIsOurs && await storedValueEquals(ctx.secrets, stored, intent.value)) return {
6117
+ kind: "value",
6118
+ value: stored
6119
+ };
6120
+ try {
6121
+ await ctx.secrets.put(ref, intent.value);
6122
+ } catch (err) {
6123
+ throw new KeychainWriteRefusedError(fieldPath, err);
6124
+ }
6125
+ return {
6126
+ kind: "value",
6127
+ value: makeSecretMarker(ref)
6128
+ };
6129
+ }
6130
+ /** Apply a member result onto `out`: KEEP restores the stored member, or removes it. */
6131
+ function applyMember(out, key, result, storedParent) {
6132
+ if (result.kind === "value") {
6133
+ out[key] = result.value;
6134
+ return;
6135
+ }
6136
+ if (Object.prototype.hasOwnProperty.call(storedParent, key)) out[key] = storedParent[key];
6137
+ else delete out[key];
6138
+ }
6139
+ async function writeMembers(ctx, children, incoming, stored, pathOf) {
6140
+ const out = { ...incoming };
6141
+ for (const [member, node] of children) applyMember(out, member, await writeNode(ctx, node, incoming[member], stored[member], pathOf(member)), stored);
6142
+ return out;
6143
+ }
6144
+ function rowId(row, idKey) {
6145
+ const raw = row[idKey];
6146
+ if (typeof raw === "string" && raw.length > 0) return raw;
6147
+ if (typeof raw === "number" && Number.isFinite(raw)) return String(raw);
6148
+ return null;
6149
+ }
6150
+ async function writeArray(ctx, node, incoming, stored, fieldPath) {
6151
+ const storedRows = Array.isArray(stored) ? stored.filter(isRecord$2) : [];
6152
+ if (!Array.isArray(incoming)) {
6153
+ ctx.deletes.push(...collectSecretMarkerRefs(storedRows));
6154
+ return {
6155
+ kind: "value",
6156
+ value: incoming
6157
+ };
6158
+ }
6159
+ const storedById = /* @__PURE__ */ new Map();
6160
+ for (const row of storedRows) {
6161
+ const id = rowId(row, node.idKey);
6162
+ if (id !== null) storedById.set(id, row);
6163
+ }
6164
+ const kept = /* @__PURE__ */ new Set();
6165
+ const rows = [];
6166
+ for (const row of incoming) {
6167
+ if (!isRecord$2(row)) {
6168
+ rows.push(row);
6169
+ continue;
6170
+ }
6171
+ const id = rowId(row, node.idKey) ?? ctx.mintId();
6172
+ kept.add(id);
6173
+ const withId = {
6174
+ ...row,
6175
+ [node.idKey]: row[node.idKey] ?? id
6176
+ };
6177
+ if (rowId(withId, node.idKey) === null) withId[node.idKey] = id;
6178
+ const storedRow = storedById.get(id) ?? {};
6179
+ rows.push(await writeMembers(ctx, node.item, withId, storedRow, (member) => arrayItemFieldPath(fieldPath, id, member)));
6180
+ }
6181
+ for (const [id, row] of storedById) if (!kept.has(id)) ctx.deletes.push(...collectSecretMarkerRefs(row));
6182
+ return {
6183
+ kind: "value",
6184
+ value: rows
6185
+ };
6186
+ }
6187
+ async function writeNode(ctx, node, incoming, stored, fieldPath) {
6188
+ switch (node.kind) {
6189
+ case "leaf": return writeLeaf(ctx, incoming, stored, fieldPath);
6190
+ case "array": return writeArray(ctx, node, incoming, stored, fieldPath);
6191
+ case "object": {
6192
+ if (!isRecord$2(incoming)) {
6193
+ if (incoming === void 0) return KEEP;
6194
+ ctx.deletes.push(...collectSecretMarkerRefs(stored));
6195
+ return {
6196
+ kind: "value",
6197
+ value: incoming
6198
+ };
6199
+ }
6200
+ const storedObj = isRecord$2(stored) ? stored : {};
6201
+ return {
6202
+ kind: "value",
6203
+ value: await writeMembers(ctx, node.children, incoming, storedObj, (m) => `${fieldPath}.${m}`)
6204
+ };
6205
+ }
6206
+ }
6207
+ }
6208
+ /** Split a perNode-scoped key (`key@nodeId`). */
6209
+ function splitNodeKey(key) {
6210
+ const at = key.indexOf("@");
6211
+ return at <= 0 ? {
6212
+ base: key,
6213
+ nodeId: null
6214
+ } : {
6215
+ base: key.slice(0, at),
6216
+ nodeId: key.slice(at + 1)
6217
+ };
6218
+ }
6219
+ /** Rewrite a settings patch so no secret value reaches the blob. See the file doc. */
6220
+ async function transformSecretWrite(input) {
6221
+ const deletes = [];
6222
+ const base = {
6223
+ secrets: input.secrets,
6224
+ mintId: input.mintId ?? defaultMintId,
6225
+ deletes,
6226
+ operatorWrite: input.operatorWrite === true
6227
+ };
6228
+ const out = {};
6229
+ for (const [key, incoming] of Object.entries(input.patch)) {
6230
+ const { base: baseKey, nodeId } = splitNodeKey(key);
6231
+ const node = input.tree.get(baseKey);
6232
+ if (node === void 0) {
6233
+ out[key] = incoming;
6234
+ continue;
6235
+ }
6236
+ const scope = nodeId !== null && nodeId.length > 0 ? {
6237
+ kind: "node",
6238
+ nodeId
6239
+ } : input.scope ?? globalSecretScope();
6240
+ const result = await writeNode({
6241
+ ...base,
6242
+ scope
6243
+ }, node, incoming, input.stored[key], baseKey);
6244
+ if (result.kind === "value") out[key] = result.value;
6245
+ }
6246
+ return {
6247
+ patch: out,
6248
+ afterWrite: async () => {
6249
+ if (deletes.length === 0) return { orphaned: [] };
6250
+ try {
6251
+ await input.secrets.delete([...new Set(deletes)]);
6252
+ return { orphaned: [] };
6253
+ } catch {
6254
+ return { orphaned: [...new Set(deletes)] };
6255
+ }
6256
+ }
6257
+ };
6258
+ }
6259
+ /**
6260
+ * Replace every marker in `value` with its keychain value. Returns the SAME
6261
+ * reference when there is no marker (no allocation, no keychain call).
6262
+ */
6263
+ async function resolveSecretMarkers(value, secrets) {
6264
+ const refs = collectSecretMarkerRefs(value);
6265
+ if (refs.length === 0) return {
6266
+ value,
6267
+ unresolved: []
6268
+ };
6269
+ const answers = await secrets.resolve(refs);
6270
+ const unresolved = [];
6271
+ for (const ref of new Set(refs)) {
6272
+ const answer = answers[ref];
6273
+ if (answer === void 0) unresolved.push({
6274
+ ref,
6275
+ reason: "not-initialized"
6276
+ });
6277
+ else if (answer.kind === "unavailable") unresolved.push({
6278
+ ref,
6279
+ reason: answer.reason
6280
+ });
6281
+ else if (answer.kind === "missing" || answer.kind === "forbidden") unresolved.push({
6282
+ ref,
6283
+ reason: answer.kind
6284
+ });
6285
+ }
6286
+ const substitute = (v) => {
6287
+ if (isSecretMarker(v)) {
6288
+ const answer = answers[v.$secret];
6289
+ return answer?.kind === "value" ? {
6290
+ keep: true,
6291
+ value: answer.value
6292
+ } : {
6293
+ keep: false,
6294
+ value: void 0
6295
+ };
6296
+ }
6297
+ if (Array.isArray(v)) {
6298
+ const items = [];
6299
+ for (const item of v) {
6300
+ const s = substitute(item);
6301
+ if (s.keep) items.push(s.value);
6302
+ }
6303
+ return {
6304
+ keep: true,
6305
+ value: items
6306
+ };
6307
+ }
6308
+ if (isRecord$2(v)) {
6309
+ const out = {};
6310
+ for (const [k, child] of Object.entries(v)) {
6311
+ const s = substitute(child);
6312
+ if (s.keep) out[k] = s.value;
6313
+ }
6314
+ return {
6315
+ keep: true,
6316
+ value: out
6317
+ };
6318
+ }
6319
+ return {
6320
+ keep: true,
6321
+ value: v
6322
+ };
6323
+ };
6324
+ return {
6325
+ value: substitute(value).value,
6326
+ unresolved
6327
+ };
6328
+ }
6329
+ function touchesTree(tree, patch) {
6330
+ if (tree.size === 0) return false;
6331
+ for (const key of Object.keys(patch)) {
6332
+ const at = key.indexOf("@");
6333
+ if (tree.has(at > 0 ? key.slice(0, at) : key)) return true;
6334
+ }
6335
+ return false;
6336
+ }
6337
+ /** The blob as stored now; a failed read REFUSES the write instead of guessing. */
6338
+ async function readStoredAddonBlob(raw) {
6339
+ const threeWay = raw.readAddonStoreResult;
6340
+ if (threeWay === void 0) return raw.readAddonStore();
6341
+ const result = await threeWay.call(raw);
6342
+ if (result.kind === "failed") throw new Error(`settings write refused: the stored blob could not be read (${result.error})`);
6343
+ return result.kind === "missing" ? {} : result.value;
6344
+ }
6345
+ function createSecretAwareSettings(raw, opts) {
6346
+ const chains = /* @__PURE__ */ new Map();
6347
+ const serialize = (key, fn) => {
6348
+ const next = (chains.get(key) ?? Promise.resolve()).then(fn, fn);
6349
+ const tail = next.catch(() => void 0);
6350
+ chains.set(key, tail);
6351
+ tail.then(() => {
6352
+ if (chains.get(key) === tail) chains.delete(key);
6353
+ });
6354
+ return next;
6355
+ };
6356
+ const write = async (chainKey, tree, scope, patch, readStored, rawWrite) => {
6357
+ if (!touchesTree(tree, patch)) return rawWrite(patch);
6358
+ return serialize(chainKey, async () => {
6359
+ const stored = await readStored();
6360
+ const result = await transformSecretWrite({
6361
+ tree,
6362
+ secrets: opts.secrets,
6363
+ patch,
6364
+ stored,
6365
+ ...scope !== void 0 ? { scope } : {},
6366
+ operatorWrite: opts.isOperatorWrite?.() === true
6367
+ });
6368
+ if (Object.keys(result.patch).length > 0) await rawWrite(result.patch);
6369
+ const { orphaned } = await result.afterWrite();
6370
+ if (orphaned.length > 0) opts.onOrphaned(orphaned);
6371
+ });
6372
+ };
6373
+ const wrapped = {
6374
+ writeAddonStore: (patch) => write("addon", opts.addonTree(), void 0, patch, () => readStoredAddonBlob(raw), (p) => raw.writeAddonStore(p)),
6375
+ writeDeviceStore: (deviceId, patch) => write(`device:${deviceId}`, opts.deviceTree(), {
6376
+ kind: "device",
6377
+ deviceId
6378
+ }, patch, () => raw.readDeviceStore(deviceId), (p) => raw.writeDeviceStore(deviceId, p))
6379
+ };
6380
+ return new Proxy(raw, { get(target, prop, receiver) {
6381
+ if (prop === "writeAddonStore") return wrapped.writeAddonStore;
6382
+ if (prop === "writeDeviceStore") return wrapped.writeDeviceStore;
6383
+ const value = Reflect.get(target, prop, receiver);
6384
+ return typeof value === "function" ? value.bind(target) : value;
6385
+ } });
6386
+ }
6387
+ /** The context the addon sees: identical, except that its settings writes are secret-aware. */
6388
+ function withSecretAwareSettings(context, opts) {
6389
+ const raw = context.settings;
6390
+ if (raw === void 0) return context;
6391
+ const settings = createSecretAwareSettings(raw, opts);
6392
+ return new Proxy(context, { get(target, prop, receiver) {
6393
+ if (prop === "settings") return settings;
6394
+ return Reflect.get(target, prop, receiver);
6395
+ } });
6396
+ }
6397
+ var LEAF = { kind: "leaf" };
6398
+ var DEFAULT_ITEM_ID_KEY = "id";
6399
+ function collectFields(fields, out) {
6400
+ for (const field of fields) {
6401
+ if (field.type === "group") {
6402
+ collectFields(field.fields, out);
6403
+ continue;
6404
+ }
6405
+ if (field.type === "sub-tabs") {
6406
+ for (const tab of field.tabs) collectFields(tab.fields, out);
6407
+ continue;
6408
+ }
6409
+ if (field.type === "editable-array") {
6410
+ const item = /* @__PURE__ */ new Map();
6411
+ for (const itemField of field.itemFields) if ("key" in itemField && isKeychainStoredField(itemField)) item.set(itemField.key, LEAF);
6412
+ if (item.size > 0) out.set(field.key, {
6413
+ kind: "array",
6414
+ idKey: field.itemIdKey ?? DEFAULT_ITEM_ID_KEY,
6415
+ item
6416
+ });
6417
+ continue;
6418
+ }
6419
+ if (!("key" in field) || typeof field.key !== "string") continue;
6420
+ if (isKeychainStoredField(field)) out.set(field.key, LEAF);
6421
+ }
6422
+ }
6423
+ /** The secret tree a settings schema declares. */
6424
+ function secretTreeFromSchema(schema) {
6425
+ const out = /* @__PURE__ */ new Map();
6426
+ if (schema === null) return out;
6427
+ for (const section of schema.sections) collectFields(section.fields, out);
6428
+ return out;
6429
+ }
6430
+ /** Parse `a.b[id].c` into segments; throws on a malformed path (a declaration bug). */
6431
+ function parseSecretStatePath(path) {
6432
+ const segments = [];
6433
+ for (const raw of path.split(".")) {
6434
+ const m = /^([^[\]]+)(?:\[([^[\]]+)\])?$/.exec(raw);
6435
+ if (m === null || m[1] === void 0) throw new Error(`secretStatePaths: malformed path "${path}"`);
6436
+ segments.push(m[2] !== void 0 ? {
6437
+ key: m[1],
6438
+ idKey: m[2]
6439
+ } : { key: m[1] });
6440
+ }
6441
+ if (segments.length === 0) throw new Error(`secretStatePaths: empty path`);
6442
+ if (segments[segments.length - 1]?.idKey !== void 0) throw new Error(`secretStatePaths: "${path}" ends on an array — name the member that is secret`);
6443
+ return segments;
6444
+ }
6445
+ function insert(into, segments) {
6446
+ const [head, ...rest] = segments;
6447
+ if (head === void 0) return;
6448
+ if (rest.length === 0) {
6449
+ into.set(head.key, LEAF);
6450
+ return;
6451
+ }
6452
+ const existing = into.get(head.key);
6453
+ if (head.idKey !== void 0) {
6454
+ const item = new Map(existing?.kind === "array" ? existing.item : []);
6455
+ insert(item, rest);
6456
+ into.set(head.key, {
6457
+ kind: "array",
6458
+ idKey: head.idKey,
6459
+ item
6460
+ });
6461
+ return;
6462
+ }
6463
+ const children = new Map(existing?.kind === "object" ? existing.children : []);
6464
+ insert(children, rest);
6465
+ into.set(head.key, {
6466
+ kind: "object",
6467
+ children
6468
+ });
6469
+ }
6470
+ /** Add hidden-state paths (`secretStatePaths`) to a schema-derived tree. */
6471
+ function mergeSecretStatePaths(tree, paths) {
6472
+ if (paths.length === 0) return tree;
6473
+ const out = new Map(tree);
6474
+ for (const path of paths) insert(out, parseSecretStatePath(path));
6475
+ return out;
6476
+ }
6477
+ /** First retry of a secret the keychain could not serve; doubles to {@link SECRET_RETRY_MAX_MS}. */
6478
+ var SECRET_RETRY_FIRST_MS = 5e3;
6479
+ var SECRET_RETRY_MAX_MS = 5 * 6e4;
6480
+ /** Coalesces a burst of `keychain.changed` events into one re-resolve. */
6481
+ var SECRET_CHANGE_DEBOUNCE_MS = 250;
5946
6482
  /**
5947
6483
  * Base class for CamStack addons. Eliminates settings boilerplate:
5948
6484
  *
@@ -6012,6 +6548,25 @@ var BaseAddon = class {
6012
6548
  settingsStoreReady = false;
6013
6549
  /** Default config values. Provided via constructor. */
6014
6550
  defaults;
6551
+ /**
6552
+ * Hidden-state paths that hold secrets (D787) — values the addon writes
6553
+ * itself (`updateGlobalSettings`, `state()`) that no form field declares.
6554
+ * Stored in the keychain exactly like a `password` field. Syntax:
6555
+ * `'snapshotSigningKey'`, `'identity.pincode'`, `'tokens[userId].accessToken'`
6556
+ * (`key[<id field>]` addresses array items by id, never by index).
6557
+ */
6558
+ secretStatePaths = [];
6559
+ _addonSecretTree = null;
6560
+ _deviceSecretTree = null;
6561
+ /** Refs the last resolved config pointed at — a change to one re-resolves. */
6562
+ _configSecretRefs = /* @__PURE__ */ new Set();
6563
+ _unresolvedSecrets = [];
6564
+ _secretRetryTimer = null;
6565
+ _secretRetryDelayMs = SECRET_RETRY_FIRST_MS;
6566
+ _secretChangeTimer = null;
6567
+ _secretChangeUnsub = null;
6568
+ /** >0 while an OPERATOR's settings write is being applied. */
6569
+ _operatorWriteDepth = 0;
6015
6570
  constructor(defaults) {
6016
6571
  this.defaults = defaults;
6017
6572
  this._config = { ...defaults };
@@ -6047,8 +6602,18 @@ var BaseAddon = class {
6047
6602
  return this._config;
6048
6603
  }
6049
6604
  async initialize(context) {
6050
- this._ctx = context;
6605
+ const secrets = context.secrets;
6606
+ this._ctx = secrets !== void 0 ? withSecretAwareSettings(context, {
6607
+ secrets,
6608
+ addonTree: () => this.addonSecretTree(),
6609
+ deviceTree: () => this.deviceSecretTree(),
6610
+ onOrphaned: (refs) => context.logger.warn("keychain refs dropped by a settings write could not be deleted", { meta: { refs: [...refs] } }),
6611
+ isOperatorWrite: () => this._operatorWriteDepth > 0
6612
+ }) : context;
6051
6613
  await this.resolveConfig();
6614
+ if (secrets !== void 0) this._secretChangeUnsub = secrets.onChange((ref) => {
6615
+ if (this._configSecretRefs.has(ref)) this.scheduleSecretReresolve(SECRET_CHANGE_DEBOUNCE_MS);
6616
+ });
6052
6617
  const result = await this.onInitialize();
6053
6618
  this.emitLifecycle(EventCategory.AddonStarted);
6054
6619
  const normalized = normalizeAddonInitResult(result);
@@ -6081,6 +6646,12 @@ var BaseAddon = class {
6081
6646
  */
6082
6647
  async onHubReachable() {}
6083
6648
  async shutdown() {
6649
+ this._secretChangeUnsub?.();
6650
+ this._secretChangeUnsub = null;
6651
+ if (this._secretRetryTimer !== null) clearTimeout(this._secretRetryTimer);
6652
+ if (this._secretChangeTimer !== null) clearTimeout(this._secretChangeTimer);
6653
+ this._secretRetryTimer = null;
6654
+ this._secretChangeTimer = null;
6084
6655
  this.emitLifecycle(EventCategory.AddonStopped);
6085
6656
  if (this.autoEmitReadiness) this.emitReadinessForProviders("down");
6086
6657
  await this.onShutdown();
@@ -6159,7 +6730,7 @@ var BaseAddon = class {
6159
6730
  return hydrateSchema(schema, overlay ? {
6160
6731
  ...projected,
6161
6732
  ...overlay
6162
- } : projected);
6733
+ } : projected, { inlineSecretsAsViews: true });
6163
6734
  }
6164
6735
  /**
6165
6736
  * The integration-level view of this addon's settings: exactly the sections
@@ -6208,7 +6779,7 @@ var BaseAddon = class {
6208
6779
  return hydrateSchema({
6209
6780
  ...schema,
6210
6781
  sections
6211
- }, projected);
6782
+ }, projected, { inlineSecretsAsViews: true });
6212
6783
  }
6213
6784
  /**
6214
6785
  * The raw addon store PROJECTED onto the target node's bare per-node keys:
@@ -6262,18 +6833,50 @@ var BaseAddon = class {
6262
6833
  value: result.value[key]
6263
6834
  };
6264
6835
  }
6836
+ /**
6837
+ * The OPERATOR's write — a settings form or an admin API call, dispatched by
6838
+ * the kernel. Identical to {@link updateGlobalSettings}, except that a secret
6839
+ * the operator sends is stored as sent even when it equals a pre-keychain
6840
+ * inline value: the operator re-entering a password is a change, an addon
6841
+ * writing back what it read is not (D787).
6842
+ */
6843
+ async updateGlobalSettingsAsOperator(patch, nodeId) {
6844
+ this._operatorWriteDepth++;
6845
+ try {
6846
+ await this.applyGlobalPatch(patch, nodeId);
6847
+ } finally {
6848
+ this._operatorWriteDepth--;
6849
+ }
6850
+ }
6265
6851
  async updateGlobalSettings(patch, nodeId) {
6852
+ await this.applyGlobalPatch(patch, nodeId);
6853
+ }
6854
+ /**
6855
+ * REMOVE stored secrets — their keychain values and their markers (D787).
6856
+ *
6857
+ * Writing `''` to a secret field KEEPS what is stored (an empty string is
6858
+ * what a defaults fallback writes back, and it must never destroy a
6859
+ * credential), so code that means "forget this token" says so here. Without
6860
+ * a keychain (an older kernel) it writes `''`, as such code always did.
6861
+ */
6862
+ async clearSecrets(keys, nodeId) {
6863
+ const tree = this.addonSecretTree();
6864
+ const keychain = this._ctx?.secrets !== void 0;
6865
+ const patch = {};
6866
+ for (const key of keys) patch[key] = keychain && tree.has(key) ? SECRET_CLEAR : "";
6867
+ await this.applyGlobalPatch(patch, nodeId);
6868
+ }
6869
+ async applyGlobalPatch(barePatch, nodeId) {
6266
6870
  const keys = this.perNodeKeys();
6267
6871
  const localNode = normalizeNodeId(this._ctx?.kernel?.localNodeId);
6268
6872
  const target = normalizeNodeId(nodeId ?? this._ctx?.kernel?.localNodeId);
6269
- const barePatch = patch;
6270
6873
  const scoped = keys.size > 0 ? scopePatch(barePatch, keys, target) : barePatch;
6271
6874
  await this._ctx?.settings?.writeAddonStore(scoped);
6272
6875
  if (target !== localNode) return;
6273
6876
  await this.resolveConfig();
6274
6877
  await this.onConfigChanged();
6275
6878
  this.emitLifecycle(EventCategory.AddonUpdated, { level: "global" });
6276
- this.maybeAutoRestart(patch, this.globalSettingsSchema());
6879
+ this.maybeAutoRestart(Object.keys(barePatch), this.globalSettingsSchema());
6277
6880
  }
6278
6881
  /**
6279
6882
  * The set of field keys the global settings schema declares `perNode: true`
@@ -6298,7 +6901,7 @@ var BaseAddon = class {
6298
6901
  * time to return its response before the addon is torn down and
6299
6902
  * re-initialised by `AddonRegistryService.restartAddon`.
6300
6903
  */
6301
- maybeAutoRestart(patch, schema) {
6904
+ maybeAutoRestart(patchKeys, schema) {
6302
6905
  if (!schema) return;
6303
6906
  const restartKeys = /* @__PURE__ */ new Set();
6304
6907
  for (const section of schema.sections) for (const field of section.fields) {
@@ -6306,13 +6909,13 @@ var BaseAddon = class {
6306
6909
  if (field.requiresRestart) restartKeys.add(field.key);
6307
6910
  }
6308
6911
  if (restartKeys.size === 0) return;
6309
- if (!Object.keys(patch).some((k) => restartKeys.has(k))) return;
6912
+ if (!patchKeys.some((k) => restartKeys.has(k))) return;
6310
6913
  const ctx = this._ctx;
6311
6914
  if (!ctx) return;
6312
6915
  const addonId = ctx.id;
6313
6916
  setImmediate(() => {
6314
6917
  ctx.api.addons?.restartAddon?.mutate({ addonId }).then(() => {
6315
- ctx.logger.info("addon auto-restart triggered by restart-required setting change", { meta: { changedFields: Object.keys(patch).filter((k) => restartKeys.has(k)) } });
6918
+ ctx.logger.info("addon auto-restart triggered by restart-required setting change", { meta: { changedFields: patchKeys.filter((k) => restartKeys.has(k)) } });
6316
6919
  }).catch((err) => {
6317
6920
  ctx.logger.error("addon auto-restart failed", { meta: { error: err instanceof Error ? err.message : String(err) } });
6318
6921
  });
@@ -6321,7 +6924,7 @@ var BaseAddon = class {
6321
6924
  async getDeviceSettings(deviceId) {
6322
6925
  const schema = this.deviceSettingsSchema();
6323
6926
  if (!schema) return { sections: [] };
6324
- return hydrateSchema(schema, await this._ctx?.settings?.readDeviceStore(deviceId) ?? {});
6927
+ return hydrateSchema(schema, await this._ctx?.settings?.readDeviceStore(deviceId) ?? {}, { inlineSecretsAsViews: true });
6325
6928
  }
6326
6929
  async updateDeviceSettings(deviceId, patch) {
6327
6930
  await this._ctx?.settings?.writeDeviceStore(deviceId, patch);
@@ -6451,7 +7054,7 @@ var BaseAddon = class {
6451
7054
  * selection at boot (absent scoped key ⇒ the constructor default wins).
6452
7055
  */
6453
7056
  async resolveConfig() {
6454
- const stored = await this.readAddonStoreWithRetry();
7057
+ const stored = await this.resolveStoredSecrets(await this.readAddonStoreWithRetry());
6455
7058
  const perNode = this.perNodeKeys();
6456
7059
  const localNode = normalizeNodeId(this._ctx?.kernel?.localNodeId);
6457
7060
  const resolved = { ...this.defaults };
@@ -6476,7 +7079,7 @@ var BaseAddon = class {
6476
7079
  key,
6477
7080
  schema,
6478
7081
  fallback,
6479
- read: () => this.readAddonStoreWithRetry(),
7082
+ read: async () => this.resolveStoredSecrets(await this.readAddonStoreWithRetry()),
6480
7083
  write: async (patch) => {
6481
7084
  await this._ctx?.settings?.writeAddonStore(patch);
6482
7085
  },
@@ -6493,7 +7096,7 @@ var BaseAddon = class {
6493
7096
  key,
6494
7097
  schema,
6495
7098
  fallback,
6496
- read: async () => await this._ctx?.settings?.readDeviceStore(deviceId) ?? {},
7099
+ read: async () => this.resolveStoredSecrets(await this._ctx?.settings?.readDeviceStore(deviceId) ?? {}, false),
6497
7100
  write: async (patch) => {
6498
7101
  await this._ctx?.settings?.writeDeviceStore(deviceId, patch);
6499
7102
  },
@@ -6505,6 +7108,70 @@ var BaseAddon = class {
6505
7108
  } })
6506
7109
  });
6507
7110
  }
7111
+ /** The addon store's secret tree: schema fields by TYPE, plus `secretStatePaths`. */
7112
+ addonSecretTree() {
7113
+ this._addonSecretTree ??= mergeSecretStatePaths(secretTreeFromSchema(this.globalSettingsSchema()), this.secretStatePaths);
7114
+ return this._addonSecretTree;
7115
+ }
7116
+ deviceSecretTree() {
7117
+ this._deviceSecretTree ??= secretTreeFromSchema(this.deviceSettingsSchema());
7118
+ return this._deviceSecretTree;
7119
+ }
7120
+ /**
7121
+ * Secrets of this addon's stored config that could not be resolved on the
7122
+ * last read, with why. Non-empty means the addon is running WITHOUT them —
7123
+ * an addon whose function needs one should report itself degraded rather
7124
+ * than start on an empty credential.
7125
+ */
7126
+ get unresolvedSecrets() {
7127
+ return this._unresolvedSecrets;
7128
+ }
7129
+ /**
7130
+ * Substitute every keychain marker in a stored blob with its value. With no
7131
+ * keychain (no `ctx.secrets`) or no marker, the blob comes back unchanged.
7132
+ * An unresolvable value is LEFT OUT (never `''`), logged by ref — never by
7133
+ * value — and, when the cause can pass, retried with backoff. Nothing is
7134
+ * ever written back from here.
7135
+ */
7136
+ async resolveStoredSecrets(blob, trackForConfig = true) {
7137
+ const secrets = this._ctx?.secrets;
7138
+ if (secrets === void 0) return blob;
7139
+ const refs = collectSecretMarkerRefs(blob);
7140
+ if (trackForConfig) this._configSecretRefs = new Set(refs);
7141
+ if (refs.length === 0) {
7142
+ if (trackForConfig) this._unresolvedSecrets = [];
7143
+ return blob;
7144
+ }
7145
+ const { value, unresolved } = await resolveSecretMarkers(blob, secrets);
7146
+ if (trackForConfig) {
7147
+ this._unresolvedSecrets = unresolved;
7148
+ if (unresolved.length > 0) {
7149
+ this._ctx?.logger?.error?.("secret unavailable — running without it, will retry", { meta: { secrets: unresolved.map((u) => ({
7150
+ ref: u.ref,
7151
+ reason: u.reason
7152
+ })) } });
7153
+ if (unresolved.some((u) => u.reason !== "missing" && u.reason !== "forbidden")) {
7154
+ this.scheduleSecretReresolve(this._secretRetryDelayMs);
7155
+ this._secretRetryDelayMs = Math.min(this._secretRetryDelayMs * 2, SECRET_RETRY_MAX_MS);
7156
+ }
7157
+ } else this._secretRetryDelayMs = SECRET_RETRY_FIRST_MS;
7158
+ }
7159
+ return value;
7160
+ }
7161
+ /** Re-resolve the config (a keychain-only change, or a retry) and apply it. */
7162
+ scheduleSecretReresolve(delayMs) {
7163
+ const timerOf = delayMs === SECRET_CHANGE_DEBOUNCE_MS ? "_secretChangeTimer" : "_secretRetryTimer";
7164
+ if (this[timerOf] !== null) return;
7165
+ const timer = setTimeout(() => {
7166
+ this[timerOf] = null;
7167
+ if (this._ctx === null) return;
7168
+ this.resolveConfig().then(() => this.onConfigChanged()).catch((err) => {
7169
+ this._ctx?.logger?.error?.("re-resolving secrets failed", { meta: { error: err instanceof Error ? err.message : String(err) } });
7170
+ });
7171
+ }, delayMs);
7172
+ timer.unref?.();
7173
+ this[timerOf] = timer;
7174
+ }
6508
7175
  /**
6509
7176
  * Wrap `ctx.settings.readAddonStore()` with a short retry budget so a
6510
7177
  * transient settings-store outage (mid-restart of sqlite-settings, tsx-watch
@@ -7114,6 +7781,69 @@ method(object({ deviceId: number() }), array(StreamSourceEntrySchema)), method(o
7114
7781
  kind: "mutation",
7115
7782
  auth: "admin"
7116
7783
  }), method(object({ deviceId: number() }), unknown().nullable()), method(object({ deviceId: number() }), RawStateResultSchema.nullable(), { auth: "protected" });
7784
+ function defOf(schema) {
7785
+ return schema._zod?.def ?? {};
7786
+ }
7787
+ function declaredHere(schema) {
7788
+ return globalRegistry.get(schema)?.secret === true;
7789
+ }
7790
+ /** Wrapper kinds whose `innerType` is the field itself. */
7791
+ var WRAPPERS = new Set([
7792
+ "optional",
7793
+ "nullable",
7794
+ "default",
7795
+ "prefault",
7796
+ "catch",
7797
+ "readonly",
7798
+ "nonoptional"
7799
+ ]);
7800
+ /**
7801
+ * The schema layers that make up ONE field: the schema itself and every
7802
+ * wrapper below it (optional / default / nullable / readonly / catch), plus
7803
+ * both sides of a pipe (`z.preprocess` puts the real schema on `out`,
7804
+ * `.transform` on `in`).
7805
+ */
7806
+ function layersOf(schema) {
7807
+ const out = [];
7808
+ const queue = [schema];
7809
+ while (queue.length > 0) {
7810
+ const s = queue.shift();
7811
+ if (!s || out.includes(s)) continue;
7812
+ out.push(s);
7813
+ const def = defOf(s);
7814
+ if (def.type !== void 0 && WRAPPERS.has(def.type) && def.innerType) queue.push(def.innerType);
7815
+ if (def.type === "pipe") {
7816
+ if (def.in) queue.push(def.in);
7817
+ if (def.out) queue.push(def.out);
7818
+ }
7819
+ }
7820
+ return out;
7821
+ }
7822
+ /** True when any layer of this field declares `.meta({ secret: true })`. */
7823
+ function isZodSecret(schema) {
7824
+ return layersOf(schema).some(declaredHere);
7825
+ }
7826
+ /**
7827
+ * Every declared secret path in a config schema: dotted keys, `[]` for "each
7828
+ * element of this array" (`connection.password`, `rows[].token`). A declared
7829
+ * object or array is reported as one path and not descended into — everything
7830
+ * under it is secret.
7831
+ */
7832
+ function collectZodSecretPaths(schema, prefix = "") {
7833
+ if (isZodSecret(schema)) return prefix.length > 0 ? [prefix] : [];
7834
+ const paths = [];
7835
+ for (const layer of layersOf(schema)) {
7836
+ const def = defOf(layer);
7837
+ if (def.type === "object" && def.shape) for (const [key, child] of Object.entries(def.shape)) paths.push(...collectZodSecretPaths(child, prefix ? `${prefix}.${key}` : key));
7838
+ else if (def.type === "array" && def.element) paths.push(...collectZodSecretPaths(def.element, `${prefix}[]`));
7839
+ else if (def.type === "union" && def.options) for (const option of def.options) paths.push(...collectZodSecretPaths(option, prefix));
7840
+ else if (def.type === "intersection") {
7841
+ if (def.left) paths.push(...collectZodSecretPaths(def.left, prefix));
7842
+ if (def.right) paths.push(...collectZodSecretPaths(def.right, prefix));
7843
+ }
7844
+ }
7845
+ return [...new Set(paths)];
7846
+ }
7117
7847
  /**
7118
7848
  * Promise-based timer helpers — used everywhere the codebase needs to
7119
7849
  * wait, back off, or schedule a retry. Before these helpers landed, each
@@ -14710,6 +15440,196 @@ id: union([string(), number()]) }), {
14710
15440
  kind: "mutation",
14711
15441
  auth: "admin"
14712
15442
  });
15443
+ /**
15444
+ * `keychain` — the hub's encrypted store of secret values (D787).
15445
+ *
15446
+ * Settings blobs never hold a secret: they hold a marker
15447
+ * `{"$secret":"secret://<owner>/<scope>/<fieldPath>","v":1}` and the value
15448
+ * lives here, AES-256-GCM under a data key that a master key wraps. This cap
15449
+ * is the OWNER's door to its own values: every method is owner-checked
15450
+ * against the CALLER, never against anything the caller claims.
15451
+ *
15452
+ * Who the caller is: the transport stamps `callerAddonId` into the args of a
15453
+ * call that crossed a process (the parent `LocalChildRegistry` from the UDS
15454
+ * connection, the agent from its child's connection carried in
15455
+ * `$hub-cap-fwd`'s envelope). A stamp always overwrites; a wire call with no
15456
+ * stamp has its claim stripped. Only a hub in-process caller may state its own
15457
+ * identity — `ctx.secrets` does that with the addon id closed over. This is
15458
+ * identity against BUGS and misrouting, not against a malicious addon (every
15459
+ * runner is the same OS user): see the threat model in
15460
+ * `docs/design/2026-10-08-secrets-keychain.md`.
15461
+ *
15462
+ * `callerAddonId` is deliberately NOT in any input schema: the tRPC router
15463
+ * parses the input, so a session can never supply it, and the internal mount
15464
+ * floors every method to admin anyway (D240).
15465
+ *
15466
+ * Internal: addons reach it through `ctx.secrets`, never directly.
15467
+ */
15468
+ /** Why a value cannot be served right now. Never folded into "missing". */
15469
+ var KeychainUnavailableReasonSchema = _enum([
15470
+ "key-missing",
15471
+ "wrong-key",
15472
+ "key-file-unreadable",
15473
+ "store-unavailable",
15474
+ "not-initialized",
15475
+ "decrypt-failed"
15476
+ ]);
15477
+ var KeychainStateSchema = discriminatedUnion("state", [object({ state: literal("ready") }), object({
15478
+ state: literal("locked"),
15479
+ reason: KeychainUnavailableReasonSchema
15480
+ })]);
15481
+ var KeychainResolveEntrySchema = discriminatedUnion("kind", [
15482
+ object({
15483
+ kind: literal("value"),
15484
+ value: string(),
15485
+ version: number().int()
15486
+ }),
15487
+ object({ kind: literal("missing") }),
15488
+ object({
15489
+ kind: literal("unavailable"),
15490
+ reason: KeychainUnavailableReasonSchema
15491
+ }),
15492
+ object({ kind: literal("forbidden") })
15493
+ ]);
15494
+ var KeychainResolveResultSchema = record(string(), KeychainResolveEntrySchema);
15495
+ /** Metadata of one stored value — never the value. */
15496
+ var KeychainSecretMetaSchema = object({
15497
+ ref: string(),
15498
+ owner: string(),
15499
+ /** Formatted scope (`global`, `node/<id>`, `device/<id>`, …). */
15500
+ scope: string(),
15501
+ fieldPath: string(),
15502
+ version: number().int(),
15503
+ createdAt: number(),
15504
+ updatedAt: number(),
15505
+ /** `addon:<id>` | `user:<id>` | `system`. */
15506
+ updatedBy: string(),
15507
+ /** Coarse — written at most once an hour per ref. `null` = never read. */
15508
+ lastReadAt: number().nullable()
15509
+ });
15510
+ var RefListSchema = array(string().min(1)).max(512);
15511
+ method(object({
15512
+ ref: string().min(1),
15513
+ value: string().min(1)
15514
+ }), object({
15515
+ ref: string(),
15516
+ version: number().int()
15517
+ }), {
15518
+ kind: "mutation",
15519
+ auth: "admin"
15520
+ }), method(object({ refs: RefListSchema }), KeychainResolveResultSchema, { auth: "admin" }), method(object({ refs: RefListSchema }), object({ deleted: number().int() }), {
15521
+ kind: "mutation",
15522
+ auth: "admin"
15523
+ }), method(object({}), array(KeychainSecretMetaSchema).readonly(), { auth: "admin" }), method(object({}), KeychainStateSchema, { auth: "admin" });
15524
+ var KeychainKeySourceSchema = object({
15525
+ kind: _enum([
15526
+ "config-file",
15527
+ "previous-config-file",
15528
+ "platform",
15529
+ "default-file"
15530
+ ]),
15531
+ /** File sources only — a path is not a secret. */
15532
+ path: string().optional(),
15533
+ /**
15534
+ * True when a whole-volume backup of the data directory carries this key
15535
+ * next to the database it protects (the default file). The page warns.
15536
+ */
15537
+ sharesBackupWithDatabase: boolean()
15538
+ });
15539
+ var KeychainStatusSchema = object({
15540
+ keychain: KeychainStateSchema,
15541
+ /** The source of the master key in use; `null` while locked. */
15542
+ keySource: KeychainKeySourceSchema.nullable(),
15543
+ /** The source configured to be primary — differs from `keySource` while a rotation is pending. */
15544
+ configuredSource: KeychainKeySourceSchema,
15545
+ /** Short fingerprint of the master key in use (`HMAC(KEK, label)`, 16 hex). */
15546
+ fingerprint: string().nullable(),
15547
+ activeKeyId: string().nullable(),
15548
+ /**
15549
+ * The keychain unlocked with a NON-primary source: the configured primary
15550
+ * key is not the one that wraps the data key yet. `rotateMasterKey` moves it.
15551
+ */
15552
+ rotationPending: boolean(),
15553
+ /** Wrapped copies of the data key under a previous master key, kept until purged. */
15554
+ retiredWraps: number().int(),
15555
+ recoveryKeyDownloadedAt: number().nullable(),
15556
+ secretCount: number().int()
15557
+ });
15558
+ /**
15559
+ * Whether a stored value is still pointed at by its owner's settings.
15560
+ * `unknown` is a first-class answer: a scope whose blob could not be read is
15561
+ * never reported as an orphan (and never deleted as one).
15562
+ */
15563
+ var KeychainSecretUsageSchema = _enum([
15564
+ "in-use",
15565
+ "orphan",
15566
+ "unknown"
15567
+ ]);
15568
+ var KeychainAdminSecretSchema = KeychainSecretMetaSchema.extend({ usage: KeychainSecretUsageSchema });
15569
+ var KeychainAuditActionSchema = _enum([
15570
+ "put",
15571
+ "delete",
15572
+ "reveal",
15573
+ "rotate-master-key",
15574
+ "purge-retired-keys",
15575
+ "download-recovery-key",
15576
+ "delete-orphans",
15577
+ "reset",
15578
+ "initialize"
15579
+ ]);
15580
+ var KeychainAuditEntrySchema = object({
15581
+ id: string(),
15582
+ at: number(),
15583
+ action: KeychainAuditActionSchema,
15584
+ /** `addon:<id>` | `user:<id>` | `system`. */
15585
+ actor: string(),
15586
+ ref: string().nullable(),
15587
+ detail: string().nullable()
15588
+ });
15589
+ method(object({}), KeychainStatusSchema, { auth: "admin" }), method(object({}), array(KeychainAdminSecretSchema).readonly(), { auth: "admin" }), method(object({ limit: number().int().min(1).max(500).optional() }), array(KeychainAuditEntrySchema).readonly(), { auth: "admin" }), method(object({ ref: string().min(1) }), object({
15590
+ value: string(),
15591
+ version: number().int()
15592
+ }), {
15593
+ kind: "mutation",
15594
+ auth: "admin",
15595
+ caller: "required"
15596
+ }), method(object({ refs: array(string().min(1)).max(1e3) }), object({
15597
+ deleted: array(string()).readonly(),
15598
+ kept: array(object({
15599
+ ref: string(),
15600
+ usage: KeychainSecretUsageSchema
15601
+ })).readonly()
15602
+ }), {
15603
+ kind: "mutation",
15604
+ auth: "admin",
15605
+ caller: "required"
15606
+ }), method(object({}), object({
15607
+ fingerprint: string(),
15608
+ keySource: KeychainKeySourceSchema
15609
+ }), {
15610
+ kind: "mutation",
15611
+ auth: "admin",
15612
+ caller: "required"
15613
+ }), method(object({}), object({ purged: number().int() }), {
15614
+ kind: "mutation",
15615
+ auth: "admin",
15616
+ caller: "required"
15617
+ }), method(object({}), object({
15618
+ key: string(),
15619
+ fingerprint: string(),
15620
+ keySource: KeychainKeySourceSchema
15621
+ }), {
15622
+ kind: "mutation",
15623
+ auth: "admin",
15624
+ caller: "required"
15625
+ }), method(object({ confirm: literal("RESET KEYCHAIN") }), object({
15626
+ archivedCollection: string().nullable(),
15627
+ archived: number().int()
15628
+ }), {
15629
+ kind: "mutation",
15630
+ auth: "admin",
15631
+ caller: "required"
15632
+ });
14713
15633
  method(_void(), object({
14714
15634
  id: string(),
14715
15635
  name: string(),
@@ -16048,7 +16968,11 @@ var DeviceRegisterPayloadSchema = object({
16048
16968
  var DeviceRemovePayloadSchema = object({ deviceId: number() });
16049
16969
  var DevicePersistConfigPayloadSchema = object({
16050
16970
  deviceId: number(),
16051
- data: record(string(), unknown())
16971
+ data: record(string(), unknown()),
16972
+ /** The paths the device's schema declares secret (D783), when the caller
16973
+ * knows them — those values are kept in the keychain, not the blob (D787).
16974
+ * Absent: the paths the device last reported at `registerDevice` apply. */
16975
+ secretConfigPaths: array(string()).optional()
16052
16976
  });
16053
16977
  /** What a migration actually did, per switch. `unreachable` is a first-class
16054
16978
  * answer: a camera that could not be asked is not a camera that was silenced. */
@@ -23105,8 +24029,23 @@ var RetrainMacroClassSchema = _enum([
23105
24029
  ]);
23106
24030
  /** A subject to learn, or a phantom to unlearn (taught by OMISSION). */
23107
24031
  var RetrainAnnotationKindSchema = _enum(["subject", "model_error"]);
23108
- /** Did a human draw this box, or did the assist propose it? */
23109
- var RetrainAnnotationSourceSchema = _enum(["operator", "assist"]);
24032
+ /**
24033
+ * Where a box came from. A machine-sourced box is a DRAFT on the page until
24034
+ * the operator confirms it; once saved it keeps its source as provenance.
24035
+ *
24036
+ * - `operator` — drawn by hand.
24037
+ * - `assist` — proposed by a detector run on the copy (the camera's own
24038
+ * model, or a larger teacher model).
24039
+ * - `pipeline` — the box the live pipeline actually drew on that frame, read
24040
+ * back from the track store (never a re-run).
24041
+ * - `llm` — proposed by a vision-capable LLM profile.
24042
+ */
24043
+ var RetrainAnnotationSourceSchema = _enum([
24044
+ "operator",
24045
+ "assist",
24046
+ "pipeline",
24047
+ "llm"
24048
+ ]);
23110
24049
  /** Normalised `[0,1]` rectangle against the FULL frame — the canonical form. */
23111
24050
  var RetrainBboxSchema = object({
23112
24051
  x: number(),
@@ -23124,7 +24063,8 @@ var RetrainBboxSchema = object({
23124
24063
  */
23125
24064
  var RetrainAnnotationSchema = object({
23126
24065
  id: string(),
23127
- trackId: string(),
24066
+ /** The frame's track. Absent on a recording still, which has none. */
24067
+ trackId: string().optional(),
23128
24068
  deviceId: number(),
23129
24069
  /** The COPY in retrain storage — never the source track's media key. */
23130
24070
  mediaKey: string(),
@@ -23173,13 +24113,47 @@ var RetrainFrameCandidateSchema = object({
23173
24113
  * fail, whatever became of the original. */
23174
24114
  copied: boolean()
23175
24115
  });
24116
+ /**
24117
+ * One box the live pipeline drew on a copied frame — what a correction starts
24118
+ * from. Derived when the frame is listed, from the track store: the subject
24119
+ * box recorded on the source media row when there is one, else the track
24120
+ * position nearest the frame's capture time. Never stored as an annotation
24121
+ * until the operator confirms it.
24122
+ */
24123
+ var RetrainPipelineBoxSchema = object({
24124
+ /** Normalised `[0,1]` against the full frame. */
24125
+ bbox: RetrainBboxSchema,
24126
+ macroClass: RetrainMacroClassSchema,
24127
+ label: string().optional(),
24128
+ subLabel: string().optional(),
24129
+ /** The detection score of the position used, when it was recorded. */
24130
+ score: number().optional(),
24131
+ /** The root model that produced the track, when it was recorded. */
24132
+ modelId: string().optional(),
24133
+ trackId: string(),
24134
+ /** `subject-box`: recorded on this very frame. `position`: the track's
24135
+ * position nearest the capture time, `deltaMs` away. */
24136
+ basis: _enum(["subject-box", "position"]),
24137
+ deltaMs: number()
24138
+ });
24139
+ /**
24140
+ * Where a retrain frame came from: a TRACK's stored media (copy-on-select),
24141
+ * or the RECORDING at an instant — the frame a model saw nothing in has no
24142
+ * track at all.
24143
+ */
24144
+ var RetrainFrameOriginSchema = _enum(["track", "recording"]);
23176
24145
  /** A frame the dataset OWNS: bytes copied at selection time. */
23177
24146
  var RetrainFrameSchema = object({
23178
24147
  frameId: string(),
23179
24148
  deviceId: number(),
23180
- trackId: string(),
23181
- /** Provenance only. It may already point at nothing — that is expected. */
23182
- sourceMediaId: number().int(),
24149
+ origin: RetrainFrameOriginSchema,
24150
+ /** The track it was copied from. Absent on a recording still. */
24151
+ trackId: string().optional(),
24152
+ /** Provenance only. It may already point at nothing — that is expected.
24153
+ * Absent on a recording still. */
24154
+ sourceMediaId: number().int().optional(),
24155
+ /** A recording still: the playhead instant it was taken at. */
24156
+ epochMs: number().optional(),
23183
24157
  sourceKind: MediaFileKindEnum,
23184
24158
  sizeBytes: number().int(),
23185
24159
  width: number().int(),
@@ -23190,7 +24164,12 @@ var RetrainFrameSchema = object({
23190
24164
  /** The operator's "every subject in this frame is boxed". Detector
23191
24165
  * evaluation keeps only complete frames: an unboxed subject would count as
23192
24166
  * a false positive. */
23193
- complete: boolean()
24167
+ complete: boolean(),
24168
+ /** The boxes the pipeline drew on this frame. Present on list answers;
24169
+ * empty when nothing the track store holds can be placed on it. */
24170
+ pipelineBoxes: array(RetrainPipelineBoxSchema).readonly().optional(),
24171
+ /** The named collections this frame belongs to. Present on list answers. */
24172
+ collectionIds: array(string()).readonly().optional()
23194
24173
  });
23195
24174
  /** Why a copy-on-select could not be honoured — named, never a silent skip. */
23196
24175
  var RetrainCopyRefusalSchema = _enum([
@@ -23221,6 +24200,11 @@ var RetrainFrameListSchema = object({
23221
24200
  var RetrainExportFilterSchema = object({
23222
24201
  deviceIds: array(number()).optional(),
23223
24202
  frameIds: array(string()).max(2e4).optional(),
24203
+ /** Only frames in at least one of these named collections. */
24204
+ collectionIds: array(string()).max(200).optional(),
24205
+ /** Exactly the frames of this dataset version (and its completeOnly). An
24206
+ * unknown id selects nothing. */
24207
+ datasetVersionId: string().optional(),
23224
24208
  batchId: string().optional(),
23225
24209
  /** Only frames the operator marked complete (all subjects boxed). */
23226
24210
  completeOnly: boolean().optional()
@@ -23285,6 +24269,170 @@ var RetrainAssistResultSchema = discriminatedUnion("kind", [object({
23285
24269
  reason: string(),
23286
24270
  detail: string().optional()
23287
24271
  })]);
24272
+ /** A named set over the retrain corpus — membership only, it owns no pixels. */
24273
+ var RetrainCollectionSchema = object({
24274
+ id: string(),
24275
+ name: string(),
24276
+ createdAt: number(),
24277
+ frameCount: number().int()
24278
+ });
24279
+ var RetrainCollectionCreateResultSchema = discriminatedUnion("kind", [object({
24280
+ kind: literal("created"),
24281
+ collection: RetrainCollectionSchema
24282
+ }), object({
24283
+ kind: literal("refused"),
24284
+ reason: _enum(["empty-name", "duplicate-name"])
24285
+ })]);
24286
+ var RetrainCollectionRenameResultSchema = discriminatedUnion("kind", [object({
24287
+ kind: literal("renamed"),
24288
+ collection: RetrainCollectionSchema
24289
+ }), object({
24290
+ kind: literal("refused"),
24291
+ reason: _enum([
24292
+ "empty-name",
24293
+ "duplicate-name",
24294
+ "unknown-collection"
24295
+ ])
24296
+ })]);
24297
+ /**
24298
+ * The outcome of adding the frame at a recording instant. Every refusal is
24299
+ * named: `still-unavailable` (not recording, a gap, or an undecodable frame —
24300
+ * `detail` says which), `still-busy` (the recorder is at its decode bound; try
24301
+ * again), `unreadable-image`, `write-failed`, `unknown-collection`.
24302
+ */
24303
+ var AddRetrainFrameFromRecordingResultSchema = discriminatedUnion("kind", [object({
24304
+ kind: literal("added"),
24305
+ collectionId: string(),
24306
+ frame: RetrainFrameSchema,
24307
+ /** The moment was already in the dataset; nothing was decoded. */
24308
+ reused: boolean()
24309
+ }), object({
24310
+ kind: literal("refused"),
24311
+ reason: _enum([
24312
+ "unknown-collection",
24313
+ "still-unavailable",
24314
+ "still-busy",
24315
+ "unreadable-image",
24316
+ "write-failed"
24317
+ ]),
24318
+ detail: string().optional()
24319
+ })]);
24320
+ /** A vision LLM profile the AI assist may use, and where it sends the frame. */
24321
+ var RetrainAssistProfileSchema = object({
24322
+ id: string(),
24323
+ name: string(),
24324
+ model: string(),
24325
+ kind: string(),
24326
+ /** `true` when the frame would leave the house (a cloud vendor, or an
24327
+ * endpoint that is not on the local network). The page confirms each such
24328
+ * run, and the provider refuses one without `allowCloud`. */
24329
+ leavesHouse: boolean()
24330
+ });
24331
+ /** A box the AI assist proposed: a draft, plus the model's own reason. */
24332
+ var RetrainLlmProposalSchema = RetrainAnnotationDraftSchema.extend({ reason: string() });
24333
+ /** What the AI assist said about a box that was already on the canvas. */
24334
+ var RetrainLlmReviewSchema = object({
24335
+ /** The `ref` the page sent the box under. */
24336
+ ref: string(),
24337
+ verdict: _enum([
24338
+ "confirmed",
24339
+ "wrong-class",
24340
+ "not-an-object",
24341
+ "uncertain"
24342
+ ]),
24343
+ suggestedClass: RetrainMacroClassSchema.optional(),
24344
+ reason: string()
24345
+ });
24346
+ /**
24347
+ * The AI assist's answer. `proposed` carries drafts (`source: 'llm'`, the
24348
+ * model and its confidence) and reviews; items the model got wrong (a box off
24349
+ * the frame, an unasked class, an unknown ref) are dropped and counted in
24350
+ * `rejected`. A whole answer that is not the schema is `malformed-answer`.
24351
+ */
24352
+ var RetrainLlmAssistResultSchema = discriminatedUnion("kind", [object({
24353
+ kind: literal("proposed"),
24354
+ profileId: string(),
24355
+ model: string(),
24356
+ /** The frame was sent outside the house for this answer. */
24357
+ leftHouse: boolean(),
24358
+ proposals: array(RetrainLlmProposalSchema).readonly(),
24359
+ reviews: array(RetrainLlmReviewSchema).readonly(),
24360
+ rejected: number().int()
24361
+ }), object({
24362
+ kind: literal("refused"),
24363
+ reason: _enum([
24364
+ "unknown-frame",
24365
+ "unreadable-frame",
24366
+ "unknown-profile",
24367
+ "profile-disabled",
24368
+ "no-vision",
24369
+ "cloud-not-confirmed",
24370
+ "llm-error",
24371
+ "malformed-answer"
24372
+ ]),
24373
+ detail: string().optional()
24374
+ })]);
24375
+ /** What a dataset version is cut from. Every field narrows. */
24376
+ var RetrainDatasetSelectionSchema = object({
24377
+ deviceIds: array(number()).readonly().optional(),
24378
+ collectionIds: array(string()).max(200).readonly().optional(),
24379
+ frameIds: array(string()).max(2e4).readonly().optional()
24380
+ });
24381
+ /** The counts a dataset is judged by. */
24382
+ var RetrainDatasetStatsSchema = object({
24383
+ frames: number().int(),
24384
+ completeFrames: number().int(),
24385
+ /** `completeFrames / frames`, 0..1. */
24386
+ completeness: number(),
24387
+ /** Boxes to learn (model errors excluded). */
24388
+ subjects: number().int(),
24389
+ modelErrors: number().int(),
24390
+ /** Complete frames with no subject. */
24391
+ hardNegatives: number().int(),
24392
+ /** Subjects per class × camera × day/night. */
24393
+ cells: array(object({
24394
+ macroClass: string(),
24395
+ deviceId: number(),
24396
+ lighting: _enum([
24397
+ "day",
24398
+ "night",
24399
+ "unknown"
24400
+ ]),
24401
+ subjects: number().int(),
24402
+ frames: number().int()
24403
+ })).readonly(),
24404
+ cameras: array(object({
24405
+ deviceId: number(),
24406
+ frames: number().int(),
24407
+ completeFrames: number().int()
24408
+ })).readonly()
24409
+ });
24410
+ /** An immutable dataset version, without its frame list. */
24411
+ var RetrainDatasetVersionSchema = object({
24412
+ id: string(),
24413
+ name: string(),
24414
+ createdAt: number(),
24415
+ selection: RetrainDatasetSelectionSchema,
24416
+ layout: RetrainExportLayoutSchema,
24417
+ completeOnly: boolean(),
24418
+ frameCount: number().int(),
24419
+ /** sha256 of what the frames taught when the version was frozen. */
24420
+ annotationHash: string(),
24421
+ /** The export manifest schema the version was cut under. */
24422
+ manifestSchema: string(),
24423
+ stats: RetrainDatasetStatsSchema
24424
+ });
24425
+ var CreateRetrainDatasetVersionResultSchema = discriminatedUnion("kind", [object({
24426
+ kind: literal("created"),
24427
+ version: RetrainDatasetVersionSchema
24428
+ }), object({
24429
+ kind: literal("refused"),
24430
+ reason: _enum([
24431
+ "empty-name",
24432
+ "duplicate-name",
24433
+ "no-frames"
24434
+ ])
24435
+ })]);
23288
24436
  /** The outcome of a lifecycle move owned by the retrain page. */
23289
24437
  var RetrainTransitionResultSchema = object({
23290
24438
  trackId: string(),
@@ -24002,7 +25150,7 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
24002
25150
  auth: "admin"
24003
25151
  }), method(object({
24004
25152
  deviceId: number(),
24005
- trackId: string(),
25153
+ trackId: string().optional(),
24006
25154
  frameId: string()
24007
25155
  }), object({
24008
25156
  removed: boolean(),
@@ -24019,7 +25167,8 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
24019
25167
  auth: "admin"
24020
25168
  }), method(object({
24021
25169
  deviceId: number(),
24022
- trackId: string(),
25170
+ /** The frame's track, when it has one — checked against the frame. */
25171
+ trackId: string().optional(),
24023
25172
  frameId: string(),
24024
25173
  subject: RetrainAssistSubjectSchema,
24025
25174
  /** Which node runs it. Absent ⇒ wherever an unowned call lands. */
@@ -24027,12 +25176,16 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
24027
25176
  }), RetrainAssistResultSchema, {
24028
25177
  kind: "mutation",
24029
25178
  auth: "admin"
24030
- }), method(object({ trackId: string() }), array(RetrainAnnotationSchema).readonly(), {
25179
+ }), method(object({
25180
+ trackId: string().optional(),
25181
+ frameIds: array(string()).max(2e3).optional()
25182
+ }), array(RetrainAnnotationSchema).readonly(), {
24031
25183
  kind: "query",
24032
25184
  auth: "admin"
24033
25185
  }), method(object({
24034
25186
  deviceId: number(),
24035
- trackId: string(),
25187
+ /** The frame's track, when it has one — checked against the frame. */
25188
+ trackId: string().optional(),
24036
25189
  frameId: string(),
24037
25190
  annotations: array(RetrainAnnotationDraftSchema)
24038
25191
  }), array(RetrainAnnotationSchema).readonly(), {
@@ -24055,7 +25208,7 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
24055
25208
  auth: "admin"
24056
25209
  }), method(object({
24057
25210
  deviceId: number(),
24058
- trackId: string(),
25211
+ trackId: string().optional(),
24059
25212
  frameId: string(),
24060
25213
  complete: boolean()
24061
25214
  }), RetrainFrameSchema, {
@@ -24069,6 +25222,104 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
24069
25222
  kind: "mutation",
24070
25223
  auth: "admin",
24071
25224
  timeoutMs: 60 * 6e4
25225
+ }), method(object({
25226
+ selection: RetrainDatasetSelectionSchema,
25227
+ completeOnly: boolean().optional()
25228
+ }), RetrainDatasetStatsSchema, {
25229
+ kind: "query",
25230
+ auth: "admin"
25231
+ }), method(object({
25232
+ name: string().max(120),
25233
+ selection: RetrainDatasetSelectionSchema,
25234
+ layout: RetrainExportLayoutSchema,
25235
+ completeOnly: boolean()
25236
+ }), CreateRetrainDatasetVersionResultSchema, {
25237
+ kind: "mutation",
25238
+ auth: "admin",
25239
+ timeoutMs: 12e4
25240
+ }), method(object({}), array(RetrainDatasetVersionSchema).readonly(), {
25241
+ kind: "query",
25242
+ auth: "admin"
25243
+ }), method(object({ id: string() }), object({ deleted: boolean() }), {
25244
+ kind: "mutation",
25245
+ auth: "admin"
25246
+ }), method(object({ id: string() }), object({
25247
+ found: boolean(),
25248
+ annotationHash: string(),
25249
+ matches: boolean(),
25250
+ missingFrames: number().int()
25251
+ }), {
25252
+ kind: "query",
25253
+ auth: "admin",
25254
+ timeoutMs: 12e4
25255
+ }), method(object({}), array(RetrainAssistProfileSchema).readonly(), {
25256
+ kind: "query",
25257
+ auth: "admin"
25258
+ }), method(object({
25259
+ deviceId: number(),
25260
+ trackId: string().optional(),
25261
+ frameId: string(),
25262
+ profileId: string(),
25263
+ classes: array(RetrainMacroClassSchema).min(1),
25264
+ boxes: array(object({
25265
+ ref: string(),
25266
+ bbox: RetrainBboxSchema,
25267
+ macroClass: RetrainMacroClassSchema,
25268
+ label: string().optional()
25269
+ })).max(50),
25270
+ allowCloud: boolean()
25271
+ }), RetrainLlmAssistResultSchema, {
25272
+ kind: "mutation",
25273
+ auth: "admin",
25274
+ timeoutMs: 18e4
25275
+ }), method(object({ name: string().max(120) }), RetrainCollectionCreateResultSchema, {
25276
+ kind: "mutation",
25277
+ auth: "admin"
25278
+ }), method(object({}), array(RetrainCollectionSchema).readonly(), {
25279
+ kind: "query",
25280
+ auth: "admin"
25281
+ }), method(object({
25282
+ id: string(),
25283
+ name: string().max(120)
25284
+ }), RetrainCollectionRenameResultSchema, {
25285
+ kind: "mutation",
25286
+ auth: "admin"
25287
+ }), method(object({ id: string() }), object({
25288
+ deleted: boolean(),
25289
+ removedFrames: number().int()
25290
+ }), {
25291
+ kind: "mutation",
25292
+ auth: "admin"
25293
+ }), method(object({
25294
+ collectionId: string(),
25295
+ deviceId: number(),
25296
+ epochMs: number()
25297
+ }), AddRetrainFrameFromRecordingResultSchema, {
25298
+ kind: "mutation",
25299
+ auth: "admin",
25300
+ timeoutMs: 6e4
25301
+ }), method(object({
25302
+ collectionId: string(),
25303
+ frameIds: array(string()).min(1).max(500)
25304
+ }), object({
25305
+ added: number().int(),
25306
+ alreadyMember: number().int(),
25307
+ unknownFrameIds: array(string()).readonly()
25308
+ }), {
25309
+ kind: "mutation",
25310
+ auth: "admin"
25311
+ }), method(object({
25312
+ collectionId: string(),
25313
+ frameId: string()
25314
+ }), object({
25315
+ removed: boolean(),
25316
+ deletedFrame: boolean()
25317
+ }), {
25318
+ kind: "mutation",
25319
+ auth: "admin"
25320
+ }), method(object({ collectionId: string() }), array(RetrainFrameSchema).readonly(), {
25321
+ kind: "query",
25322
+ auth: "admin"
24072
25323
  }), method(object({
24073
25324
  /** Which of the three event tables owns the row. */
24074
25325
  ownerType: EventOwnerTypeSchema,
@@ -24692,13 +25943,31 @@ var RecommendationReasonSchema = discriminatedUnion("kind", [
24692
25943
  object({
24693
25944
  kind: literal("no-family-build"),
24694
25945
  format: ModelFormatSchema$1
25946
+ }),
25947
+ object({
25948
+ kind: literal("kept-custom-pin"),
25949
+ modelId: string(),
25950
+ deviceKey: string()
24695
25951
  })
24696
25952
  ]);
25953
+ /** Why a device is left exactly as it is, whatever the plan would pick (D786). */
25954
+ var KeptReasonSchema = _enum(["custom-pin"]);
25955
+ /**
25956
+ * Where a choice's latency came from (D791): this node's own benchmark
25957
+ * result, or the hardware-class table. Measured on the node beats the table.
25958
+ */
25959
+ var LatencySourceSchema = discriminatedUnion("kind", [object({ kind: literal("table") }), object({
25960
+ kind: literal("node-benchmark"),
25961
+ resultId: string(),
25962
+ measuredAtMs: number()
25963
+ })]);
24697
25964
  var DeviceModelChoiceSchema = object({
24698
25965
  modelId: string(),
24699
25966
  p50Ms: number(),
24700
25967
  fps: number(),
24701
25968
  measured: boolean(),
25969
+ /** Absent on a plan from before D791 — read as the table. */
25970
+ source: LatencySourceSchema.optional(),
24702
25971
  /** Parallel sessions at the camera rate with the headroom kept free: ⌊fps × (1 − headroom) / camera fps⌋. */
24703
25972
  capacitySessions: number(),
24704
25973
  personRecall: number()
@@ -24709,6 +25978,8 @@ var DeviceRecommendationSchema = object({
24709
25978
  enabled: boolean(),
24710
25979
  available: boolean(),
24711
25980
  chosen: DeviceModelChoiceSchema.nullable(),
25981
+ /** Present when the device is kept as is: Apply writes nothing on it. */
25982
+ kept: KeptReasonSchema.optional(),
24712
25983
  reasons: array(RecommendationReasonSchema).readonly()
24713
25984
  });
24714
25985
  var NodeRecommendationSchema = object({
@@ -24762,6 +26033,17 @@ var AutoTuneWarningSchema = discriminatedUnion("kind", [
24762
26033
  kind: literal("coral-enabled"),
24763
26034
  nodeId: string(),
24764
26035
  deviceKey: string()
26036
+ }),
26037
+ object({
26038
+ kind: literal("custom-pin-kept"),
26039
+ nodeId: string(),
26040
+ deviceKey: string().nullable(),
26041
+ deviceId: number().nullable(),
26042
+ modelId: string()
26043
+ }),
26044
+ object({
26045
+ kind: literal("custom-registry-unreadable"),
26046
+ error: string()
24765
26047
  })
24766
26048
  ]);
24767
26049
  var AutoTuneOptionsSchema = object({
@@ -24940,13 +26222,14 @@ var SuggestSharesResultSchema = object({
24940
26222
  nodes: array(SuggestedNodeShareSchema).readonly()
24941
26223
  });
24942
26224
  /**
24943
- * Where the node and device shares come from (D750, D755).
24944
- * - `hardware` (default) — computed by the system from each node's static
24945
- * capacity (its accelerators at their Auto tune models, from the measured
24946
- * latency table), recomputed whenever a node or device joins, leaves, is
24947
- * switched on or off, or changes model. No load input.
24948
- * - `benchmark` — the same, from each node's measured capacity (node
24949
- * benchmark results); a node without results falls back to `hardware`.
26225
+ * Where the node and device shares come from (D750, D755, D791).
26226
+ * - `benchmark` (default since D791) — each node's capacity as its own node
26227
+ * benchmark measured it; a node without fresh results is sized from
26228
+ * `hardware` and says so. Measured on the node beats the table.
26229
+ * - `hardware` — computed from each node's static capacity only (its
26230
+ * accelerators at their Auto tune models, from the latency table).
26231
+ * Both are recomputed whenever a node or device joins, leaves, is switched
26232
+ * on or off, changes model, or a benchmark result is written. No load input.
24950
26233
  * - `manual` — the operator's stored sliders.
24951
26234
  * Either way a node or device that cannot take sessions gives its share to
24952
26235
  * the others in proportion; the stored values are never rewritten for that.
@@ -24995,6 +26278,362 @@ var EffectiveSharesSchema = object({
24995
26278
  nodeWeights: record(string(), number()),
24996
26279
  deviceWeights: record(string(), record(string(), number()))
24997
26280
  });
26281
+ /**
26282
+ * Wire shapes of the node benchmark (D791): the operator's plan, the
26283
+ * preflight the confirmation shows, the run the orchestrator owns, what the
26284
+ * measuring runner reports, and the result rows Auto tune and the automatic
26285
+ * shares read.
26286
+ *
26287
+ * ONE node at a time, owned by the pipeline orchestrator. While a run is
26288
+ * active the cluster is in BENCHMARK MODE for that node: it is not a
26289
+ * detection candidate, camera pins naming it are ignored so its sessions move
26290
+ * elsewhere, and both come back when the mode ends — after a crash or a hub
26291
+ * restart too (a persisted manifest, reconciled against the registry).
26292
+ *
26293
+ * Two measurements, both on the node, driven by its own runner (frames never
26294
+ * cross a process at frame rate, D9):
26295
+ * - `device` — one accelerator × one candidate detector, root only, open
26296
+ * loop: how many streams at the camera rate it carries inside the frame
26297
+ * interval;
26298
+ * - `pipeline` — the chosen detector plus the operator's detail steps
26299
+ * (faces, plates, classifiers, CLIP…), on varied frames from the bench
26300
+ * clip: how many parallel sessions the node carries before latency, drops,
26301
+ * CPU, RAM or the event loop give out.
26302
+ */
26303
+ /** Defaults and bounds, one place. */
26304
+ var NODE_BENCHMARK_DEFAULTS = {
26305
+ fpsPerStream: 10,
26306
+ budgetMinutes: 45,
26307
+ minBudgetMinutes: 10,
26308
+ maxBudgetMinutes: 120,
26309
+ /** A result older than this no longer beats the table. */
26310
+ staleAfterDays: 30,
26311
+ /** Warm-in per ramp step (not accounted). */
26312
+ settleSec: 5,
26313
+ /** Accounted window per ramp step. */
26314
+ measureSec: 20,
26315
+ /** Longest the drain may take before the run is refused. */
26316
+ drainTimeoutSec: 120,
26317
+ /** Candidate models per device in one run. */
26318
+ maxModelsPerDevice: 6
26319
+ };
26320
+ /** The two measurements a run can make. */
26321
+ var NodeBenchmarkPhaseSchema = _enum(["device", "pipeline"]);
26322
+ var NodeBenchmarkDevicePlanSchema = object({
26323
+ /** `<backend>:<device>` — `openvino:npu`, `coreml:all`, `cpu`. */
26324
+ deviceKey: string().min(1),
26325
+ /**
26326
+ * Root detector candidates for the `device` measurement, in the order
26327
+ * measured. The FIRST is the one the `pipeline` measurement runs.
26328
+ */
26329
+ modelIds: array(string().min(1)).min(1).max(NODE_BENCHMARK_DEFAULTS.maxModelsPerDevice)
26330
+ });
26331
+ /** What the operator confirmed. */
26332
+ var NodeBenchmarkPlanSchema = object({
26333
+ nodeId: string().min(1),
26334
+ devices: array(NodeBenchmarkDevicePlanSchema).min(1),
26335
+ /** Which measurements run. At least one. */
26336
+ phases: array(NodeBenchmarkPhaseSchema).min(1).default(["device", "pipeline"]),
26337
+ /**
26338
+ * Detail steps (catalog step ids under the root: faces, plates,
26339
+ * classifiers, CLIP…) the `pipeline` measurement enables. The root
26340
+ * detector always runs.
26341
+ */
26342
+ steps: array(string().min(1)).default([]),
26343
+ /** Offered rate of one stream / session. */
26344
+ fpsPerStream: number().int().min(1).max(30).default(NODE_BENCHMARK_DEFAULTS.fpsPerStream),
26345
+ /** Hard deadline: the mode ends and the cluster is restored when it passes. */
26346
+ budgetMinutes: number().int().min(NODE_BENCHMARK_DEFAULTS.minBudgetMinutes).max(NODE_BENCHMARK_DEFAULTS.maxBudgetMinutes).default(NODE_BENCHMARK_DEFAULTS.budgetMinutes),
26347
+ /** Keep the models the run downloaded (default: delete what was not installed before). */
26348
+ keepDownloadedModels: boolean().default(false),
26349
+ /** Start although the other nodes' capacity does not cover the sessions running now. */
26350
+ acceptInsufficientHeadroom: boolean().default(false)
26351
+ });
26352
+ var NodeBenchmarkRefusalSchema = object({
26353
+ kind: _enum([
26354
+ "benchmark-active",
26355
+ "node-offline",
26356
+ "unknown-device",
26357
+ "no-phase",
26358
+ "insufficient-headroom"
26359
+ ]),
26360
+ detail: string(),
26361
+ overridable: boolean()
26362
+ });
26363
+ /** A camera whose detection leaves the node for the run. */
26364
+ var NodeBenchmarkMovingCameraSchema = object({
26365
+ deviceId: number(),
26366
+ /** Placed on the node now (a standing attach or a running session). */
26367
+ placedOnNode: boolean(),
26368
+ /** A node pin naming this node, ignored for the run. */
26369
+ pinnedToNode: boolean()
26370
+ });
26371
+ /** A camera that cannot leave: no other node can obtain its frames. */
26372
+ var NodeBenchmarkStayingCameraSchema = object({
26373
+ deviceId: number(),
26374
+ reason: literal("only-frame-source")
26375
+ });
26376
+ var NodeBenchmarkPreflightSchema = object({
26377
+ nodeId: string(),
26378
+ online: boolean(),
26379
+ moving: array(NodeBenchmarkMovingCameraSchema).readonly(),
26380
+ /** Keep running on the node during the run; the result is flagged contaminated. */
26381
+ staying: array(NodeBenchmarkStayingCameraSchema).readonly(),
26382
+ estimatedDurationMs: number(),
26383
+ /** The run ends and the cluster is restored at the latest after this long. */
26384
+ budgetMs: number(),
26385
+ phases: array(NodeBenchmarkPhaseSchema).readonly(),
26386
+ steps: array(string()).readonly(),
26387
+ devices: array(NodeBenchmarkDevicePlanSchema).readonly(),
26388
+ /** Parallel sessions the cluster runs now, and what the other nodes can carry. */
26389
+ headroom: object({
26390
+ sessionsNow: number(),
26391
+ otherNodesCapacitySessions: number().nullable()
26392
+ }),
26393
+ refusals: array(NodeBenchmarkRefusalSchema).readonly(),
26394
+ canStart: boolean()
26395
+ });
26396
+ /** Where the measuring runner is. */
26397
+ var NodeBenchProgressSchema = object({
26398
+ phase: _enum([
26399
+ "preparing",
26400
+ "device",
26401
+ "pipeline",
26402
+ "cleanup"
26403
+ ]),
26404
+ deviceKey: string().nullable(),
26405
+ modelId: string().nullable(),
26406
+ /** Streams (device) or sessions (pipeline) of the step running now. */
26407
+ load: number().nullable(),
26408
+ cellsDone: number(),
26409
+ cellsTotal: number(),
26410
+ message: string()
26411
+ });
26412
+ /** What limited a ramp. `none` = the ramp ran out of steps still passing. */
26413
+ var NodeBenchLimitSchema = _enum([
26414
+ "p95",
26415
+ "drops",
26416
+ "errors",
26417
+ "stall",
26418
+ "cpu",
26419
+ "ram",
26420
+ "none"
26421
+ ]);
26422
+ var NodeBenchRampStepSchema = object({
26423
+ load: number(),
26424
+ pass: boolean(),
26425
+ p95Ms: number(),
26426
+ dropRatio: number(),
26427
+ /** Completed frames per second over the accounted window. */
26428
+ fps: number(),
26429
+ cpuPct: number().nullable(),
26430
+ ramFreePct: number().nullable(),
26431
+ failReasons: array(string()).readonly()
26432
+ });
26433
+ var NodeBenchCellSchema = discriminatedUnion("phase", [object({
26434
+ phase: literal("device"),
26435
+ deviceKey: string(),
26436
+ modelId: string(),
26437
+ /** Single-stream latency (the K = 1 step). */
26438
+ p50Ms: number(),
26439
+ p95Ms: number(),
26440
+ p99Ms: number(),
26441
+ /** Frames per second sustained at the last passing step. */
26442
+ fps: number(),
26443
+ /** Streams at the camera rate the device carried inside the frame interval; 0 = not even one. */
26444
+ kMax: number(),
26445
+ limitedBy: NodeBenchLimitSchema,
26446
+ /** First call (model load + warm-up). */
26447
+ warmupMs: number(),
26448
+ ramp: array(NodeBenchRampStepSchema).readonly()
26449
+ }), object({
26450
+ phase: literal("pipeline"),
26451
+ deviceKey: string(),
26452
+ modelId: string(),
26453
+ steps: array(string()).readonly(),
26454
+ /** Parallel sessions at the camera rate the node carried; 0 = not even one. */
26455
+ maxSessions: number(),
26456
+ limitedBy: NodeBenchLimitSchema,
26457
+ /** Detail steps that produced at least one result on the clip — a step that never fired measured nothing. */
26458
+ stepsFired: array(string()).readonly(),
26459
+ warmupMs: number(),
26460
+ ramp: array(NodeBenchRampStepSchema).readonly()
26461
+ })]);
26462
+ /**
26463
+ * What a result was measured ON. A result whose fingerprint no longer matches
26464
+ * the node no longer beats the table.
26465
+ */
26466
+ var NodeBenchFingerprintSchema = object({
26467
+ pipelineVersion: string().nullable(),
26468
+ cpuModel: string().nullable(),
26469
+ ramGb: number().nullable(),
26470
+ os: string().nullable(),
26471
+ /** Per device: the pool the cells ran on (runtime + tuning). */
26472
+ pools: record(string(), object({
26473
+ runtime: string(),
26474
+ numWorkers: number(),
26475
+ concurrency: number(),
26476
+ batchMode: string()
26477
+ })).default({})
26478
+ });
26479
+ /** The frames the run used. */
26480
+ var NodeBenchClipSchema = object({
26481
+ /** `camstack-bench-v1` or `reference-images` (the fallback when the clip is not reachable). */
26482
+ id: string(),
26483
+ revision: string().nullable(),
26484
+ frames: number(),
26485
+ width: number(),
26486
+ height: number()
26487
+ });
26488
+ var NodeBenchRunnerInputSchema = object({
26489
+ runId: string().min(1),
26490
+ devices: array(NodeBenchmarkDevicePlanSchema).min(1),
26491
+ phases: array(NodeBenchmarkPhaseSchema).min(1),
26492
+ /** The full detail step tree root for the `pipeline` measurement is built on the node from these ids. */
26493
+ steps: array(string()).default([]),
26494
+ fpsPerStream: number().int().min(1).max(30),
26495
+ /** The runner stops on its own past this instant, whatever the hub does. */
26496
+ deadlineAtMs: number(),
26497
+ settleSec: number().min(0).max(60).default(NODE_BENCHMARK_DEFAULTS.settleSec),
26498
+ measureSec: number().min(2).max(300).default(NODE_BENCHMARK_DEFAULTS.measureSec),
26499
+ keepDownloadedModels: boolean().default(false)
26500
+ });
26501
+ var NodeBenchRunnerStateSchema = _enum([
26502
+ "running",
26503
+ "done",
26504
+ "failed",
26505
+ "aborted"
26506
+ ]);
26507
+ var NodeBenchRunnerStatusSchema = object({
26508
+ runId: string(),
26509
+ nodeId: string(),
26510
+ state: NodeBenchRunnerStateSchema,
26511
+ progress: NodeBenchProgressSchema.nullable(),
26512
+ /** Every finished cell so far — a run stopped half way keeps what it measured. */
26513
+ cells: array(NodeBenchCellSchema).readonly(),
26514
+ fingerprint: NodeBenchFingerprintSchema.nullable(),
26515
+ clip: NodeBenchClipSchema.nullable(),
26516
+ /** Cameras seen running on the node during the run (they share its pools). */
26517
+ activeCameraIds: array(number()).readonly(),
26518
+ /** Models the run downloaded and then deleted (not installed before). */
26519
+ deletedModels: array(string()).readonly(),
26520
+ error: string().nullable(),
26521
+ startedAtMs: number(),
26522
+ finishedAtMs: number().nullable()
26523
+ });
26524
+ var NodeBenchmarkStateSchema = _enum([
26525
+ "draining",
26526
+ "measuring",
26527
+ "restoring",
26528
+ "done",
26529
+ "failed",
26530
+ "aborted"
26531
+ ]);
26532
+ /** Why a run ended. */
26533
+ var NodeBenchmarkEndReasonSchema = _enum([
26534
+ "completed",
26535
+ "operator-abort",
26536
+ "deadline",
26537
+ "node-lost",
26538
+ "runner-lost",
26539
+ "hub-restart",
26540
+ "drain-timeout",
26541
+ "failed"
26542
+ ]);
26543
+ var NodeBenchmarkRunSchema = object({
26544
+ runId: string(),
26545
+ nodeId: string(),
26546
+ state: NodeBenchmarkStateSchema,
26547
+ plan: NodeBenchmarkPlanSchema,
26548
+ startedAtMs: number(),
26549
+ deadlineAtMs: number(),
26550
+ finishedAtMs: number().nullable(),
26551
+ endReason: NodeBenchmarkEndReasonSchema.nullable(),
26552
+ error: string().nullable(),
26553
+ /** Cameras moved off the node for the run. */
26554
+ moved: array(number()).readonly(),
26555
+ /** Cameras that stayed (their only frame source is the node). */
26556
+ staying: array(number()).readonly(),
26557
+ /** Something else ran on the node's pools during the run. */
26558
+ contaminated: boolean(),
26559
+ progress: NodeBenchProgressSchema.nullable(),
26560
+ resultIds: array(string()).readonly()
26561
+ });
26562
+ /** `getNodeBenchmarkStatus`: the active run (or the last one), and whether benchmark mode is on. */
26563
+ var NodeBenchmarkStatusSchema = object({
26564
+ /** The node the cluster is in benchmark mode for; null = none. */
26565
+ modeNodeId: string().nullable(),
26566
+ run: NodeBenchmarkRunSchema.nullable()
26567
+ });
26568
+ /**
26569
+ * One stored measurement — the only authority Auto tune and the automatic
26570
+ * shares read measured capacity from. Written by the orchestrator when a run
26571
+ * ends, never by anyone else.
26572
+ */
26573
+ var NodeBenchmarkResultSchema = object({
26574
+ id: string(),
26575
+ runId: string(),
26576
+ nodeId: string(),
26577
+ cell: NodeBenchCellSchema,
26578
+ fpsPerStream: number(),
26579
+ fingerprint: NodeBenchFingerprintSchema.nullable(),
26580
+ clip: NodeBenchClipSchema.nullable(),
26581
+ /** Other work shared the node's pools (a camera that could not move, or the hub's own duties). */
26582
+ contaminated: boolean(),
26583
+ stayingCameras: array(number()).readonly(),
26584
+ /** The run ended early; the cell itself completed. */
26585
+ partialRun: boolean(),
26586
+ measuredAtMs: number()
26587
+ });
26588
+ var ListNodeBenchmarkResultsInputSchema = object({
26589
+ nodeId: string().optional(),
26590
+ deviceKey: string().optional()
26591
+ });
26592
+ /** A result with its standing today: does it still beat the table? */
26593
+ var NodeBenchmarkResultViewSchema = NodeBenchmarkResultSchema.extend({
26594
+ /** `fresh` beats the table; `stale` falls back to it; `superseded` = a newer row covers the same cell. */
26595
+ standing: _enum([
26596
+ "fresh",
26597
+ "stale",
26598
+ "superseded"
26599
+ ]),
26600
+ staleWhy: _enum([
26601
+ "age",
26602
+ "runtime",
26603
+ "pool-tuning"
26604
+ ]).nullable()
26605
+ });
26606
+ object({
26607
+ runId: string(),
26608
+ nodeId: string(),
26609
+ startedAtMs: number(),
26610
+ deadlineAtMs: number(),
26611
+ plan: NodeBenchmarkPlanSchema,
26612
+ moved: array(number()).readonly(),
26613
+ staying: array(number()).readonly()
26614
+ });
26615
+ /** Candidate detectors per device, for the plan editor. */
26616
+ var NodeBenchmarkCandidatesSchema = object({
26617
+ nodeId: string(),
26618
+ reachable: boolean(),
26619
+ devices: array(object({
26620
+ deviceKey: string(),
26621
+ enabled: boolean(),
26622
+ available: boolean(),
26623
+ /** Ordered: what Auto tune would pick first, then the rest of the family by accuracy. */
26624
+ suggested: array(string()).readonly(),
26625
+ /** Every root detector the device has a build for. */
26626
+ all: array(string()).readonly(),
26627
+ /** The model the device runs now, when pinned. */
26628
+ currentModelId: string().nullable()
26629
+ })).readonly(),
26630
+ /** Detail steps the node's catalog offers under the root (for the `pipeline` measurement). */
26631
+ steps: array(object({
26632
+ id: string(),
26633
+ name: string(),
26634
+ slot: string()
26635
+ })).readonly()
26636
+ });
24998
26637
  object({
24999
26638
  activeCameras: number(),
25000
26639
  throttledCameras: number(),
@@ -26123,7 +27762,16 @@ method(RunnerCameraConfigSchema, object({ success: literal(true) }), { kind: "mu
26123
27762
  }), ParkedTrackFrameSchema.nullable()), method(object({
26124
27763
  deviceId: number(),
26125
27764
  trackId: string()
26126
- }), object({ released: number().int().nonnegative() }), { kind: "mutation" });
27765
+ }), object({ released: number().int().nonnegative() }), { kind: "mutation" }), method(NodeBenchRunnerInputSchema, object({
27766
+ accepted: literal(true),
27767
+ runId: string()
27768
+ }), {
27769
+ kind: "mutation",
27770
+ auth: "admin"
27771
+ }), method(object({ runId: string() }), NodeBenchRunnerStatusSchema.nullable(), { auth: "admin" }), method(object({ runId: string() }), object({ aborted: boolean() }), {
27772
+ kind: "mutation",
27773
+ auth: "admin"
27774
+ });
26127
27775
  var CameraPipelineConfigSchema = object({
26128
27776
  engine: PipelineEngineChoiceSchema.optional(),
26129
27777
  steps: array(PipelineStepInputSchema).readonly(),
@@ -26762,6 +28410,21 @@ method(object({
26762
28410
  }), method(PlacementStatsInputSchema, PlacementStatsSchema, { auth: "admin" }), method(SuggestSharesInputSchema, SuggestSharesResultSchema, { auth: "admin" }), method(_void(), EffectiveSharesSchema, { auth: "admin" }), method(SetShareSourceInputSchema, object({ success: literal(true) }), {
26763
28411
  kind: "mutation",
26764
28412
  auth: "admin"
28413
+ }), method(NodeBenchmarkPlanSchema, NodeBenchmarkPreflightSchema, { auth: "admin" }), method(NodeBenchmarkPlanSchema, discriminatedUnion("kind", [object({
28414
+ kind: literal("started"),
28415
+ runId: string()
28416
+ }), object({
28417
+ kind: literal("refused"),
28418
+ preflight: NodeBenchmarkPreflightSchema
28419
+ })]), {
28420
+ kind: "mutation",
28421
+ auth: "admin"
28422
+ }), method(_void(), NodeBenchmarkStatusSchema, { auth: "admin" }), method(object({ runId: string() }), object({ aborted: boolean() }), {
28423
+ kind: "mutation",
28424
+ auth: "admin"
28425
+ }), method(object({ nodeId: string() }), NodeBenchmarkCandidatesSchema, { auth: "admin" }), method(ListNodeBenchmarkResultsInputSchema, array(NodeBenchmarkResultViewSchema).readonly(), { auth: "admin" }), method(object({ id: string() }), object({ deleted: boolean() }), {
28426
+ kind: "mutation",
28427
+ auth: "admin"
26765
28428
  }), method(object({ deviceId: number() }), CameraPipelineSettingsSchema.nullable()), method(object({
26766
28429
  deviceId: number(),
26767
28430
  addonId: string(),
@@ -33391,6 +35054,9 @@ var CreateIntegrationInputSchema = object({
33391
35054
  enabled: boolean().optional(),
33392
35055
  info: record(string(), unknown()).optional(),
33393
35056
  settings: record(string(), unknown()).optional(),
35057
+ /** Keys of `settings` the form's schema declares secret (by type) — kept in
35058
+ * the keychain, not the table (D787). */
35059
+ secretKeys: array(string()).optional(),
33394
35060
  skipRestart: boolean().optional()
33395
35061
  });
33396
35062
  var UpdateIntegrationInputSchema = object({
@@ -33414,7 +35080,9 @@ method(_void(), array(IntegrationWithStateSchema)), method(object({ id: string()
33414
35080
  auth: "admin"
33415
35081
  }), method(object({ id: string() }), record(string(), unknown()), { auth: "admin" }), method(object({
33416
35082
  id: string(),
33417
- settings: record(string(), unknown())
35083
+ settings: record(string(), unknown()),
35084
+ /** Keys the form's schema declares secret (by type) — keychain-stored (D787). */
35085
+ secretKeys: array(string()).optional()
33418
35086
  }), object({ success: boolean() }), {
33419
35087
  kind: "mutation",
33420
35088
  auth: "admin"
@@ -42162,7 +43830,8 @@ var BaseDevice = class {
42162
43830
  this.role = options.role;
42163
43831
  this.parentDeviceId = ctx.parentDeviceId;
42164
43832
  const seedData = ctx.persistedConfig ?? {};
42165
- this.config = DeviceConfig.fromSchema(schema, (data) => ctx.persistConfig(data), seedData, ({ droppedKeys, issues }) => {
43833
+ const declaredSecretPaths = collectZodSecretPaths(schema);
43834
+ this.config = DeviceConfig.fromSchema(schema, (data) => ctx.persistConfig(data, { secretConfigPaths: declaredSecretPaths }), seedData, ({ droppedKeys, issues }) => {
42166
43835
  ctx.logger.warn("Device config recovery: dropping invalid persisted fields", {
42167
43836
  tags: {
42168
43837
  deviceId: ctx.id,
@@ -45862,6 +47531,90 @@ Object.freeze({
45862
47531
  addonId: null,
45863
47532
  access: "create"
45864
47533
  },
47534
+ "keychain.delete": {
47535
+ capName: "keychain",
47536
+ capScope: "system",
47537
+ addonId: null,
47538
+ access: "delete"
47539
+ },
47540
+ "keychain.getState": {
47541
+ capName: "keychain",
47542
+ capScope: "system",
47543
+ addonId: null,
47544
+ access: "view"
47545
+ },
47546
+ "keychain.listMeta": {
47547
+ capName: "keychain",
47548
+ capScope: "system",
47549
+ addonId: null,
47550
+ access: "view"
47551
+ },
47552
+ "keychain.put": {
47553
+ capName: "keychain",
47554
+ capScope: "system",
47555
+ addonId: null,
47556
+ access: "create"
47557
+ },
47558
+ "keychain.resolve": {
47559
+ capName: "keychain",
47560
+ capScope: "system",
47561
+ addonId: null,
47562
+ access: "view"
47563
+ },
47564
+ "keychainAdmin.deleteOrphans": {
47565
+ capName: "keychain-admin",
47566
+ capScope: "system",
47567
+ addonId: null,
47568
+ access: "delete"
47569
+ },
47570
+ "keychainAdmin.downloadRecoveryKey": {
47571
+ capName: "keychain-admin",
47572
+ capScope: "system",
47573
+ addonId: null,
47574
+ access: "create"
47575
+ },
47576
+ "keychainAdmin.listAudit": {
47577
+ capName: "keychain-admin",
47578
+ capScope: "system",
47579
+ addonId: null,
47580
+ access: "view"
47581
+ },
47582
+ "keychainAdmin.listSecrets": {
47583
+ capName: "keychain-admin",
47584
+ capScope: "system",
47585
+ addonId: null,
47586
+ access: "view"
47587
+ },
47588
+ "keychainAdmin.purgeRetiredKeys": {
47589
+ capName: "keychain-admin",
47590
+ capScope: "system",
47591
+ addonId: null,
47592
+ access: "delete"
47593
+ },
47594
+ "keychainAdmin.resetKeychain": {
47595
+ capName: "keychain-admin",
47596
+ capScope: "system",
47597
+ addonId: null,
47598
+ access: "delete"
47599
+ },
47600
+ "keychainAdmin.reveal": {
47601
+ capName: "keychain-admin",
47602
+ capScope: "system",
47603
+ addonId: null,
47604
+ access: "create"
47605
+ },
47606
+ "keychainAdmin.rotateMasterKey": {
47607
+ capName: "keychain-admin",
47608
+ capScope: "system",
47609
+ addonId: null,
47610
+ access: "create"
47611
+ },
47612
+ "keychainAdmin.status": {
47613
+ capName: "keychain-admin",
47614
+ capScope: "system",
47615
+ addonId: null,
47616
+ access: "view"
47617
+ },
45865
47618
  "lawnMowerControl.dock": {
45866
47619
  capName: "lawn-mower-control",
45867
47620
  capScope: "device",
@@ -47236,6 +48989,18 @@ Object.freeze({
47236
48989
  addonId: null,
47237
48990
  access: "create"
47238
48991
  },
48992
+ "pipelineAnalytics.addRetrainFrameFromRecording": {
48993
+ capName: "pipeline-analytics",
48994
+ capScope: "device",
48995
+ addonId: null,
48996
+ access: "create"
48997
+ },
48998
+ "pipelineAnalytics.addRetrainFramesToCollection": {
48999
+ capName: "pipeline-analytics",
49000
+ capScope: "device",
49001
+ addonId: null,
49002
+ access: "create"
49003
+ },
47239
49004
  "pipelineAnalytics.applyDeviceSettingsPatch": {
47240
49005
  capName: "pipeline-analytics",
47241
49006
  capScope: "device",
@@ -47284,12 +49049,36 @@ Object.freeze({
47284
49049
  addonId: null,
47285
49050
  access: "view"
47286
49051
  },
49052
+ "pipelineAnalytics.createRetrainCollection": {
49053
+ capName: "pipeline-analytics",
49054
+ capScope: "device",
49055
+ addonId: null,
49056
+ access: "create"
49057
+ },
49058
+ "pipelineAnalytics.createRetrainDatasetVersion": {
49059
+ capName: "pipeline-analytics",
49060
+ capScope: "device",
49061
+ addonId: null,
49062
+ access: "create"
49063
+ },
47287
49064
  "pipelineAnalytics.deleteDeviceEvents": {
47288
49065
  capName: "pipeline-analytics",
47289
49066
  capScope: "device",
47290
49067
  addonId: null,
47291
49068
  access: "delete"
47292
49069
  },
49070
+ "pipelineAnalytics.deleteRetrainCollection": {
49071
+ capName: "pipeline-analytics",
49072
+ capScope: "device",
49073
+ addonId: null,
49074
+ access: "delete"
49075
+ },
49076
+ "pipelineAnalytics.deleteRetrainDatasetVersion": {
49077
+ capName: "pipeline-analytics",
49078
+ capScope: "device",
49079
+ addonId: null,
49080
+ access: "delete"
49081
+ },
47293
49082
  "pipelineAnalytics.deleteTracks": {
47294
49083
  capName: "pipeline-analytics",
47295
49084
  capScope: "device",
@@ -47494,6 +49283,30 @@ Object.freeze({
47494
49283
  addonId: null,
47495
49284
  access: "view"
47496
49285
  },
49286
+ "pipelineAnalytics.listRetrainAssistProfiles": {
49287
+ capName: "pipeline-analytics",
49288
+ capScope: "device",
49289
+ addonId: null,
49290
+ access: "view"
49291
+ },
49292
+ "pipelineAnalytics.listRetrainCollectionFrames": {
49293
+ capName: "pipeline-analytics",
49294
+ capScope: "device",
49295
+ addonId: null,
49296
+ access: "view"
49297
+ },
49298
+ "pipelineAnalytics.listRetrainCollections": {
49299
+ capName: "pipeline-analytics",
49300
+ capScope: "device",
49301
+ addonId: null,
49302
+ access: "view"
49303
+ },
49304
+ "pipelineAnalytics.listRetrainDatasetVersions": {
49305
+ capName: "pipeline-analytics",
49306
+ capScope: "device",
49307
+ addonId: null,
49308
+ access: "view"
49309
+ },
47497
49310
  "pipelineAnalytics.listRetrainFrames": {
47498
49311
  capName: "pipeline-analytics",
47499
49312
  capScope: "device",
@@ -47536,12 +49349,24 @@ Object.freeze({
47536
49349
  addonId: null,
47537
49350
  access: "create"
47538
49351
  },
49352
+ "pipelineAnalytics.previewRetrainDataset": {
49353
+ capName: "pipeline-analytics",
49354
+ capScope: "device",
49355
+ addonId: null,
49356
+ access: "view"
49357
+ },
47539
49358
  "pipelineAnalytics.proposeRetrainAnnotations": {
47540
49359
  capName: "pipeline-analytics",
47541
49360
  capScope: "device",
47542
49361
  addonId: null,
47543
49362
  access: "create"
47544
49363
  },
49364
+ "pipelineAnalytics.proposeRetrainAnnotationsWithLlm": {
49365
+ capName: "pipeline-analytics",
49366
+ capScope: "device",
49367
+ addonId: null,
49368
+ access: "create"
49369
+ },
47545
49370
  "pipelineAnalytics.pruneEvents": {
47546
49371
  capName: "pipeline-analytics",
47547
49372
  capScope: "device",
@@ -47596,6 +49421,18 @@ Object.freeze({
47596
49421
  addonId: null,
47597
49422
  access: "create"
47598
49423
  },
49424
+ "pipelineAnalytics.removeRetrainFrameFromCollection": {
49425
+ capName: "pipeline-analytics",
49426
+ capScope: "device",
49427
+ addonId: null,
49428
+ access: "delete"
49429
+ },
49430
+ "pipelineAnalytics.renameRetrainCollection": {
49431
+ capName: "pipeline-analytics",
49432
+ capScope: "device",
49433
+ addonId: null,
49434
+ access: "create"
49435
+ },
47599
49436
  "pipelineAnalytics.restageRetrainTrack": {
47600
49437
  capName: "pipeline-analytics",
47601
49438
  capScope: "device",
@@ -47656,6 +49493,12 @@ Object.freeze({
47656
49493
  addonId: null,
47657
49494
  access: "create"
47658
49495
  },
49496
+ "pipelineAnalytics.verifyRetrainDatasetVersion": {
49497
+ capName: "pipeline-analytics",
49498
+ capScope: "device",
49499
+ addonId: null,
49500
+ access: "view"
49501
+ },
47659
49502
  "pipelineAnalytics.wipeAllAnalytics": {
47660
49503
  capName: "pipeline-analytics",
47661
49504
  capScope: "device",
@@ -47884,6 +49727,12 @@ Object.freeze({
47884
49727
  addonId: null,
47885
49728
  access: "view"
47886
49729
  },
49730
+ "pipelineOrchestrator.abortNodeBenchmark": {
49731
+ capName: "pipeline-orchestrator",
49732
+ capScope: "system",
49733
+ addonId: null,
49734
+ access: "create"
49735
+ },
47887
49736
  "pipelineOrchestrator.applyAutoTune": {
47888
49737
  capName: "pipeline-orchestrator",
47889
49738
  capScope: "system",
@@ -47908,6 +49757,12 @@ Object.freeze({
47908
49757
  addonId: null,
47909
49758
  access: "create"
47910
49759
  },
49760
+ "pipelineOrchestrator.deleteNodeBenchmarkResult": {
49761
+ capName: "pipeline-orchestrator",
49762
+ capScope: "system",
49763
+ addonId: null,
49764
+ access: "delete"
49765
+ },
47911
49766
  "pipelineOrchestrator.getAgentLoad": {
47912
49767
  capName: "pipeline-orchestrator",
47913
49768
  capScope: "system",
@@ -48016,6 +49871,24 @@ Object.freeze({
48016
49871
  addonId: null,
48017
49872
  access: "view"
48018
49873
  },
49874
+ "pipelineOrchestrator.getNodeBenchmarkCandidates": {
49875
+ capName: "pipeline-orchestrator",
49876
+ capScope: "system",
49877
+ addonId: null,
49878
+ access: "view"
49879
+ },
49880
+ "pipelineOrchestrator.getNodeBenchmarkPreflight": {
49881
+ capName: "pipeline-orchestrator",
49882
+ capScope: "system",
49883
+ addonId: null,
49884
+ access: "view"
49885
+ },
49886
+ "pipelineOrchestrator.getNodeBenchmarkStatus": {
49887
+ capName: "pipeline-orchestrator",
49888
+ capScope: "system",
49889
+ addonId: null,
49890
+ access: "view"
49891
+ },
48019
49892
  "pipelineOrchestrator.getNodeInferenceDevices": {
48020
49893
  capName: "pipeline-orchestrator",
48021
49894
  capScope: "system",
@@ -48058,6 +49931,12 @@ Object.freeze({
48058
49931
  addonId: null,
48059
49932
  access: "view"
48060
49933
  },
49934
+ "pipelineOrchestrator.listNodeBenchmarkResults": {
49935
+ capName: "pipeline-orchestrator",
49936
+ capScope: "system",
49937
+ addonId: null,
49938
+ access: "view"
49939
+ },
48061
49940
  "pipelineOrchestrator.pauseForStorageMigration": {
48062
49941
  capName: "pipeline-orchestrator",
48063
49942
  capScope: "system",
@@ -48202,6 +50081,12 @@ Object.freeze({
48202
50081
  addonId: null,
48203
50082
  access: "create"
48204
50083
  },
50084
+ "pipelineOrchestrator.startNodeBenchmark": {
50085
+ capName: "pipeline-orchestrator",
50086
+ capScope: "system",
50087
+ addonId: null,
50088
+ access: "create"
50089
+ },
48205
50090
  "pipelineOrchestrator.suggestShares": {
48206
50091
  capName: "pipeline-orchestrator",
48207
50092
  capScope: "system",
@@ -48220,6 +50105,12 @@ Object.freeze({
48220
50105
  addonId: null,
48221
50106
  access: "create"
48222
50107
  },
50108
+ "pipelineRunner.abortNodeBench": {
50109
+ capName: "pipeline-runner",
50110
+ capScope: "system",
50111
+ addonId: null,
50112
+ access: "create"
50113
+ },
48223
50114
  "pipelineRunner.attachCamera": {
48224
50115
  capName: "pipeline-runner",
48225
50116
  capScope: "system",
@@ -48268,6 +50159,12 @@ Object.freeze({
48268
50159
  addonId: null,
48269
50160
  access: "view"
48270
50161
  },
50162
+ "pipelineRunner.getNodeBenchStatus": {
50163
+ capName: "pipeline-runner",
50164
+ capScope: "system",
50165
+ addonId: null,
50166
+ access: "view"
50167
+ },
48271
50168
  "pipelineRunner.getParkedTrackFrame": {
48272
50169
  capName: "pipeline-runner",
48273
50170
  capScope: "system",
@@ -48310,6 +50207,12 @@ Object.freeze({
48310
50207
  addonId: null,
48311
50208
  access: "create"
48312
50209
  },
50210
+ "pipelineRunner.startNodeBench": {
50211
+ capName: "pipeline-runner",
50212
+ capScope: "system",
50213
+ addonId: null,
50214
+ access: "create"
50215
+ },
48313
50216
  "plateGallery.assignPlate": {
48314
50217
  capName: "plate-gallery",
48315
50218
  capScope: "system",
@@ -53391,6 +55294,11 @@ Object.freeze({
53391
55294
  form: "single",
53392
55295
  optional: false
53393
55296
  }],
55297
+ "pipelineAnalytics.addRetrainFrameFromRecording": [{
55298
+ name: "deviceId",
55299
+ form: "single",
55300
+ optional: false
55301
+ }],
53394
55302
  "pipelineAnalytics.applyDeviceSettingsPatch": [{
53395
55303
  name: "deviceId",
53396
55304
  form: "single",
@@ -53581,6 +55489,11 @@ Object.freeze({
53581
55489
  form: "single",
53582
55490
  optional: false
53583
55491
  }],
55492
+ "pipelineAnalytics.proposeRetrainAnnotationsWithLlm": [{
55493
+ name: "deviceId",
55494
+ form: "single",
55495
+ optional: false
55496
+ }],
53584
55497
  "pipelineAnalytics.pruneEventsBefore": [{
53585
55498
  name: "deviceId",
53586
55499
  form: "single",
@@ -165341,6 +167254,31 @@ function createAccessoryDevice(kind, ctx, parent) {
165341
167254
  }
165342
167255
  //#endregion
165343
167256
  //#region src/accessory-probe-flags.ts
167257
+ /**
167258
+ * Pure helpers that decide which probe flags drive accessory-child
167259
+ * derivation, and whether a Reolink camera has *ever* been probed.
167260
+ *
167261
+ * Why this exists as its own module: the `feature-probe` runtime-state
167262
+ * slice is the live, in-session source of the camera's ability flags
167263
+ * (`hasSiren` / `hasFloodlight` / `hasPirSensor` / …). It is rehydrated
167264
+ * on restart, BUT a camera whose Baichuan `getDeviceCapabilities`
167265
+ * round-trip is slow or flaky (observed: a doorbell that times out the
167266
+ * kernel's 30s `onProbe` window on every boot) restores with an empty
167267
+ * slice (`lastProbedAt === 0`). The `deviceCache` config blob — written
167268
+ * alongside the slice on the LAST successful probe and preserved across
167269
+ * restarts by the camera schema's `.loose()` passthrough — still carries
167270
+ * that probe's flags plus a `probedAt` stamp.
167271
+ *
167272
+ * Deriving accessory specs from the `deviceCache` fallback lets the
167273
+ * kernel re-spawn the persisted accessory children (and therefore
167274
+ * re-mount their kernel-managed `device-ops` provider) even when this
167275
+ * session's live probe never completes. Without it, every accessory of
167276
+ * a slow-probing camera is left as a DB row with no live provider
167277
+ * ("device-ops not registered for device N").
167278
+ *
167279
+ * Kept pure (no `this`, no I/O) so the slice-vs-cache precedence is
167280
+ * unit-testable without standing up a full camera device.
167281
+ */
165344
167282
  var FLAG_KEYS = [
165345
167283
  "hasBattery",
165346
167284
  "hasPtz",
@@ -165378,6 +167316,59 @@ function resolveAccessoryProbeFlags(sliceProbed, sliceFlags, deviceCache) {
165378
167316
  }
165379
167317
  return out;
165380
167318
  }
167319
+ /**
167320
+ * The `deviceCache` blob a successful feature probe leaves behind: the
167321
+ * previous blob, plus the `probedAt` stamp and every boolean ability flag
167322
+ * the probe resolved. This is what lets {@link resolveAccessoryProbeFlags}
167323
+ * fall back on the next boot — a battery camera asleep at boot skips its
167324
+ * probe, and the `feature-probe` slice alone does not carry the flags
167325
+ * across a provider restart. Returns a new object; `previous` is untouched.
167326
+ */
167327
+ function withPersistedProbe(previous, flags, probedAt) {
167328
+ const persisted = {};
167329
+ for (const key of FLAG_KEYS) {
167330
+ const value = flags[key];
167331
+ if (typeof value === "boolean") persisted[key] = value;
167332
+ }
167333
+ return {
167334
+ ...previous,
167335
+ ...persisted,
167336
+ probedAt
167337
+ };
167338
+ }
167339
+ /** The accessory children a probe flag set spawns, in spawn order. */
167340
+ var ACCESSORY_FLAGS = [
167341
+ ["hasSiren", AccessoryKind.Siren],
167342
+ ["hasFloodlight", AccessoryKind.Floodlight],
167343
+ ["hasPirSensor", AccessoryKind.PirSensor]
167344
+ ];
167345
+ /**
167346
+ * Accessory kinds a camera should spawn: none until it has EVER probed
167347
+ * (live slice this session, or a persisted `probedAt`), then one per
167348
+ * ability flag that is exactly `true` — live slice first, persisted
167349
+ * `deviceCache` flags as the fallback.
167350
+ */
167351
+ function accessoryKindsFor(sliceProbed, sliceFlags, deviceCache) {
167352
+ if (!hasEverProbed(sliceProbed, deviceCache)) return [];
167353
+ const flags = resolveAccessoryProbeFlags(sliceProbed, sliceFlags, deviceCache);
167354
+ return ACCESSORY_FLAGS.filter(([flag]) => flags[flag] === true).map(([, kind]) => kind);
167355
+ }
167356
+ /**
167357
+ * The probe flags every probe-gated decision should read (PTZ, intercom,
167358
+ * doorbell, autotrack caps, the device features, accessory children):
167359
+ * the live slice once this session has probed; otherwise the slice
167360
+ * overlaid with the flags persisted by the last successful probe. A
167361
+ * battery camera asleep at boot skips its probe, so without the overlay
167362
+ * its probe-gated caps vanish across every provider restart. With no
167363
+ * persisted probe stamp, the slice is returned unchanged.
167364
+ */
167365
+ function effectiveProbeFlags(sliceProbed, sliceFlags, deviceCache) {
167366
+ if (sliceProbed || deviceCache?.probedAt === void 0) return sliceFlags;
167367
+ return {
167368
+ ...sliceFlags,
167369
+ ...resolveAccessoryProbeFlags(false, {}, deviceCache)
167370
+ };
167371
+ }
165381
167372
  //#endregion
165382
167373
  //#region src/metadata-populator.ts
165383
167374
  var EXTENDED_INFO_TAGS = [
@@ -167329,6 +169320,19 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
167329
169320
  * underlying state. The set is small (≤6 entries) so allocation cost
167330
169321
  * is negligible vs the staleness of caching.
167331
169322
  */
169323
+ /**
169324
+ * Probe flags with the persisted fallback: until this session has probed
169325
+ * (a battery camera asleep at boot skips `onProbe`), the flags of the last
169326
+ * successful probe stored in `deviceCache` stand in for the empty
169327
+ * `feature-probe` slice. Every probe-gated read — PTZ / intercom /
169328
+ * doorbell / autotrack registration, `features`, accessory children —
169329
+ * goes through here, so a sleeping camera keeps those caps across a
169330
+ * provider restart. `config` is read defensively: the base constructor
169331
+ * may read flags before this class's fields exist.
169332
+ */
169333
+ getProbeFlags() {
169334
+ return effectiveProbeFlags(this.hasProbed(), super.getProbeFlags(), this.config?.get("deviceCache"));
169335
+ }
167332
169336
  get features() {
167333
169337
  return deriveReolinkCameraFeatures({
167334
169338
  probe: this.getProbeFlags(),
@@ -168193,9 +170197,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
168193
170197
  * parent register.
168194
170198
  */
168195
170199
  getAccessoryChildren() {
168196
- const deviceCache = this.config.get("deviceCache");
168197
- if (!hasEverProbed(this.hasProbed(), deviceCache)) return [];
168198
- const probe = resolveAccessoryProbeFlags(this.hasProbed(), this.getProbeFlags(), deviceCache);
170200
+ const kinds = accessoryKindsFor(this.hasProbed(), this.getProbeFlags(), this.config.get("deviceCache"));
168199
170201
  const out = [];
168200
170202
  const push = (kind, type, label) => {
168201
170203
  out.push({
@@ -168211,9 +170213,9 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
168211
170213
  factory: (ctx) => createAccessoryDevice(kind, ctx, this)
168212
170214
  });
168213
170215
  };
168214
- if (probe.hasSiren === true) push(AccessoryKind.Siren, DeviceType.Siren, ACCESSORY_LABEL[AccessoryKind.Siren]);
168215
- if (probe.hasFloodlight === true) push(AccessoryKind.Floodlight, DeviceType.Light, ACCESSORY_LABEL[AccessoryKind.Floodlight]);
168216
- if (probe.hasPirSensor === true) push(AccessoryKind.PirSensor, DeviceType.Switch, ACCESSORY_LABEL[AccessoryKind.PirSensor]);
170216
+ if (kinds.includes(AccessoryKind.Siren)) push(AccessoryKind.Siren, DeviceType.Siren, ACCESSORY_LABEL[AccessoryKind.Siren]);
170217
+ if (kinds.includes(AccessoryKind.Floodlight)) push(AccessoryKind.Floodlight, DeviceType.Light, ACCESSORY_LABEL[AccessoryKind.Floodlight]);
170218
+ if (kinds.includes(AccessoryKind.PirSensor)) push(AccessoryKind.PirSensor, DeviceType.Switch, ACCESSORY_LABEL[AccessoryKind.PirSensor]);
168217
170219
  return out;
168218
170220
  }
168219
170221
  /**
@@ -172664,6 +174666,14 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
172664
174666
  meta: { error: err instanceof Error ? err.message : String(err) }
172665
174667
  });
172666
174668
  }
174669
+ if (!this.hasProbed()) try {
174670
+ await this.reprobe();
174671
+ } catch (err) {
174672
+ this.ctx.logger.debug("onWakeTransition: feature probe failed — next wake retries", {
174673
+ tags: { deviceId: this.id },
174674
+ meta: { error: err instanceof Error ? err.message : String(err) }
174675
+ });
174676
+ }
172667
174677
  await this.warmCapSlicesOnWake();
172668
174678
  await this.warmSnapshotOnWake();
172669
174679
  await this.alignAuxDevicesState("wake");
@@ -174732,6 +176742,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
174732
176742
  let hasBattery;
174733
176743
  let hasPirSensor;
174734
176744
  let hasAutotrack;
176745
+ let capabilitiesRead = false;
174735
176746
  try {
174736
176747
  channelCount = await api.getChannelCount();
174737
176748
  } catch {}
@@ -174745,6 +176756,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
174745
176756
  hasBattery = capabilities.hasBattery;
174746
176757
  hasPirSensor = capabilities.hasPir;
174747
176758
  hasAutotrack = capabilities.hasAutotracking;
176759
+ capabilitiesRead = true;
174748
176760
  } catch (err) {
174749
176761
  this.ctx.logger.debug("getDeviceCapabilities failed — leaving flags unset", {
174750
176762
  tags: { deviceId: this.id },
@@ -174781,12 +176793,12 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
174781
176793
  };
174782
176794
  this.runtimeState.setCapState("feature-probe", next);
174783
176795
  try {
174784
- const previous = this.config.get("deviceCache") ?? {};
174785
- await this.config.setAll({ deviceCache: {
174786
- ...previous,
176796
+ const identity = {
176797
+ ...this.config.get("deviceCache") ?? {},
174787
176798
  ...inferredDeviceType ? { deviceType: inferredDeviceType } : {},
174788
176799
  ...channelCount !== void 0 ? { channelCount } : {}
174789
- } });
176800
+ };
176801
+ await this.config.setAll({ deviceCache: capabilitiesRead ? withPersistedProbe(identity, flags, now) : identity });
174790
176802
  } catch (err) {
174791
176803
  this.ctx.logger.debug("deviceCache identity persist failed (non-fatal)", {
174792
176804
  tags: { deviceId: this.id },
@@ -177237,6 +179249,8 @@ async function enrichHostIdentifiersFromLiveApi(detection, logger) {
177237
179249
  }
177238
179250
  }
177239
179251
  var ReolinkProviderAddon = class extends BaseDeviceProvider {
179252
+ /** The email-push SMTP password is hidden state — kept in the keychain (D787). */
179253
+ secretStatePaths = ["emailPushAuthPassword"];
177240
179254
  addonId = REOLINK_ADDON_ID;
177241
179255
  providerName = "Reolink";
177242
179256
  deviceClasses = {