@camstack/addon-provider-ecowitt 0.2.123 → 0.2.124

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 +1845 -56
  2. package/dist/addon.mjs +1845 -56
  3. package/package.json +1 -1
package/dist/addon.js CHANGED
@@ -2,7 +2,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  let http = require("http");
3
3
  let events = require("events");
4
4
  let dgram = require("dgram");
5
- //#region ../types/dist/event-category-B_0XEcLF.mjs
5
+ //#region ../types/dist/event-category-DaIZi00R.mjs
6
6
  var EventCategory = /* @__PURE__ */ function(EventCategory) {
7
7
  EventCategory["SystemBoot"] = "system.boot";
8
8
  EventCategory["SystemAddonsReady"] = "system.addons-ready";
@@ -81,6 +81,13 @@ var EventCategory = /* @__PURE__ */ function(EventCategory) {
81
81
  */
82
82
  EventCategory["AddonLoadFailed"] = "addon.load-failed";
83
83
  /**
84
+ * A keychain value was stored or removed (D787). Carries the ref, its
85
+ * owner and the new version — NEVER the value. A process holding the ref
86
+ * drops its cached copy and the owning `BaseAddon` re-resolves its config.
87
+ * Telemetry (D8): a process that misses it still revalidates by version.
88
+ */
89
+ EventCategory["KeychainChanged"] = "keychain.changed";
90
+ /**
84
91
  * Addon recovered from a previous failure. Emitted when an addon
85
92
  * transitions from `failed` back to `healthy` (typically via the
86
93
  * monitor's auto-retry loop, or after manual `addons.retryLoad`).
@@ -5373,7 +5380,7 @@ var ZodIssueCode$1 = {
5373
5380
  var ZodFirstPartyTypeKind$1;
5374
5381
  ZodFirstPartyTypeKind$1 || (ZodFirstPartyTypeKind$1 = {});
5375
5382
  //#endregion
5376
- //#region ../types/dist/sleep-B0JG7-_F.mjs
5383
+ //#region ../types/dist/sleep-Cr5YOk3m.mjs
5377
5384
  /**
5378
5385
  * The audio chunk plane's byte format, and the ONE expansion from a coded
5379
5386
  * window to float samples (D455).
@@ -5452,6 +5459,97 @@ function buildAlawTable() {
5452
5459
  }
5453
5460
  buildUlawTable();
5454
5461
  buildAlawTable();
5462
+ /** Is this field's stored value a credential? */
5463
+ function isSecretConfigField(field) {
5464
+ if (field.type === "password") return true;
5465
+ return "secret" in field && field.secret === true;
5466
+ }
5467
+ /**
5468
+ * Is this field's value stored in the KEYCHAIN (D787)? Every secret field is,
5469
+ * by its TYPE, unless it opts out with `storage: 'inline'` — never by its name.
5470
+ */
5471
+ function isKeychainStoredField(field) {
5472
+ if (!isSecretConfigField(field)) return false;
5473
+ if (field.type === "textarea" && field.isJson === true) return false;
5474
+ return !("storage" in field && field.storage === "inline");
5475
+ }
5476
+ /**
5477
+ * What a settings blob holds where a secret used to be.
5478
+ *
5479
+ * A keychain-stored field never holds its value. It holds a self-describing
5480
+ * MARKER, `{"$secret":"secret://…","v":1}` — an object, never a string, so no
5481
+ * code can mistake it for a credential and no form can send it to a camera as
5482
+ * a password. The empty state is `null` / absent, never `''`.
5483
+ *
5484
+ * The same shapes travel to and from the admin UI:
5485
+ *
5486
+ * - read: `hydrateSchema` hands a secret field a {@link SecretFieldView}
5487
+ * (`{ $secret, v, set: true }`) or `null` — the browser learns whether a
5488
+ * value is set, never the value.
5489
+ * - write: an untouched field submits the view back unchanged (KEEP); a typed
5490
+ * value is a plain non-empty string (CHANGE); the Clear button submits
5491
+ * {@link SECRET_CLEAR} (CLEAR). `''`, `null` and the legacy redaction tokens
5492
+ * are KEEP — an empty string is what a defaults-fallback pushes back, and
5493
+ * treating it as "clear" is how a save destroyed a stored credential before.
5494
+ *
5495
+ * Pure and browser-safe.
5496
+ */
5497
+ var SECRET_CLEAR = { $secretClear: true };
5498
+ /** The `'***'` token D634 redaction writes for non-admins. */
5499
+ var LEGACY_DEVICE_REDACTION = "***";
5500
+ function isRecord$1(value) {
5501
+ return typeof value === "object" && value !== null && !Array.isArray(value);
5502
+ }
5503
+ function makeSecretMarker(ref) {
5504
+ return {
5505
+ $secret: ref,
5506
+ v: 1
5507
+ };
5508
+ }
5509
+ /** A stored marker: an object whose `$secret` is a non-empty string. */
5510
+ function isSecretMarker(value) {
5511
+ if (!isRecord$1(value)) return false;
5512
+ const ref = value["$secret"];
5513
+ return typeof ref === "string" && ref.length > 0;
5514
+ }
5515
+ function isSecretClear(value) {
5516
+ return isRecord$1(value) && value["$secretClear"] === true;
5517
+ }
5518
+ /**
5519
+ * The UI view of a stored secret field value: a marker becomes "set", inline
5520
+ * plaintext becomes "set (inline)", nothing becomes `null`. A value never
5521
+ * survives this function.
5522
+ */
5523
+ function toSecretFieldView(stored) {
5524
+ if (isSecretMarker(stored)) return {
5525
+ $secret: stored.$secret,
5526
+ v: 1,
5527
+ set: true
5528
+ };
5529
+ if (typeof stored === "string" && stored.length > 0) return {
5530
+ $secret: null,
5531
+ v: 1,
5532
+ set: true,
5533
+ inline: true
5534
+ };
5535
+ return null;
5536
+ }
5537
+ /**
5538
+ * Classify an incoming value for a secret path. Only a non-empty string that is
5539
+ * not a redaction token sets a value; only {@link SECRET_CLEAR} clears.
5540
+ * Everything else — a marker (ours or anyone's), a UI view, `''`, `null`,
5541
+ * `undefined`, a redaction token, a non-string — keeps what is stored.
5542
+ */
5543
+ function classifySecretWrite(incoming) {
5544
+ if (isSecretClear(incoming)) return { kind: "clear" };
5545
+ if (typeof incoming !== "string") return { kind: "keep" };
5546
+ if (incoming.length === 0) return { kind: "keep" };
5547
+ if (incoming === "__camstack_redacted__" || incoming === LEGACY_DEVICE_REDACTION) return { kind: "keep" };
5548
+ return {
5549
+ kind: "set",
5550
+ value: incoming
5551
+ };
5552
+ }
5455
5553
  Object.fromEntries([
5456
5554
  {
5457
5555
  id: "overview",
@@ -5623,33 +5721,19 @@ Object.fromEntries([
5623
5721
  function isValuelessField(field) {
5624
5722
  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";
5625
5723
  }
5626
- /**
5627
- * Merge a `ConfigUISchema` with a raw `values` record into a
5628
- * `ConfigUISchemaWithValues`. Used by every `get*Settings` backend endpoint
5629
- * before returning to the admin UI. Groups are walked recursively.
5630
- *
5631
- * For each leaf field:
5632
- * - structural fields (`separator`, `info`, `button`) pass through unchanged
5633
- * - other fields get `value = values[key] ?? field.default ?? null`
5634
- *
5635
- * Unknown keys in `values` (keys not declared in the schema) are silently
5636
- * ignored — they don't contribute to the output. Missing keys fall back to
5637
- * the schema default or `null`. This mirrors the old backend behaviour where
5638
- * `FormBuilder` rendered `values[key] ?? field.default`.
5639
- */
5640
- function hydrateSchema(schema, values) {
5724
+ function hydrateSchema(schema, values, options = {}) {
5641
5725
  return {
5642
5726
  ...schema.tabs ? { tabs: [...schema.tabs] } : {},
5643
5727
  sections: schema.sections.map((section) => ({
5644
5728
  ...section,
5645
- fields: section.fields.map((field) => hydrateField(field, values))
5729
+ fields: section.fields.map((field) => hydrateField(field, values, options))
5646
5730
  }))
5647
5731
  };
5648
5732
  }
5649
- function hydrateField(field, values) {
5733
+ function hydrateField(field, values, options) {
5650
5734
  if (isValuelessField(field)) return field;
5651
5735
  if (field.type === "group") {
5652
- const hydratedChildren = field.fields.map((child) => hydrateField(child, values));
5736
+ const hydratedChildren = field.fields.map((child) => hydrateField(child, values, options));
5653
5737
  return {
5654
5738
  ...field,
5655
5739
  fields: hydratedChildren
@@ -5658,7 +5742,7 @@ function hydrateField(field, values) {
5658
5742
  if (field.type === "sub-tabs") {
5659
5743
  const hydratedTabs = field.tabs.map((tab) => ({
5660
5744
  ...tab,
5661
- fields: tab.fields.map((child) => hydrateField(child, values))
5745
+ fields: tab.fields.map((child) => hydrateField(child, values, options))
5662
5746
  }));
5663
5747
  return {
5664
5748
  ...field,
@@ -5668,6 +5752,33 @@ function hydrateField(field, values) {
5668
5752
  const key = field.key;
5669
5753
  const storedValue = Object.prototype.hasOwnProperty.call(values, key) ? values[key] : void 0;
5670
5754
  const defaultValue = field.default;
5755
+ const asView = (v) => isSecretMarker(v) || options.inlineSecretsAsViews === true && v !== void 0;
5756
+ if (isKeychainStoredField(field) && asView(storedValue)) return {
5757
+ ...field,
5758
+ value: toSecretFieldView(storedValue)
5759
+ };
5760
+ if (isKeychainStoredField(field) && options.inlineSecretsAsViews === true) return {
5761
+ ...field,
5762
+ value: null
5763
+ };
5764
+ if (field.type === "editable-array" && Array.isArray(storedValue)) {
5765
+ const secretItemKeys = field.itemFields.filter((item) => "key" in item && isKeychainStoredField(item)).map((item) => "key" in item ? item.key : "");
5766
+ if (secretItemKeys.length > 0) {
5767
+ const rows = storedValue.map((row) => {
5768
+ if (row === null || typeof row !== "object" || Array.isArray(row)) return row;
5769
+ const out = { ...row };
5770
+ for (const k of secretItemKeys) {
5771
+ const v = Reflect.get(row, k);
5772
+ if (asView(v)) out[k] = toSecretFieldView(v);
5773
+ }
5774
+ return out;
5775
+ });
5776
+ return {
5777
+ ...field,
5778
+ value: rows
5779
+ };
5780
+ }
5781
+ }
5671
5782
  if (field.multiple) {
5672
5783
  const stored = Array.isArray(storedValue) ? storedValue : storedValue !== void 0 && storedValue !== null ? [storedValue] : [];
5673
5784
  const itemFallback = field.multiple.itemDefault !== void 0 ? field.multiple.itemDefault : defaultValue !== void 0 ? defaultValue : typeOf(field) === "string" ? "" : null;
@@ -5910,6 +6021,431 @@ function projectStore(store, perNodeKeys, nodeId) {
5910
6021
  }
5911
6022
  return out;
5912
6023
  }
6024
+ var GLOBAL_SCOPE = { kind: "global" };
6025
+ /** The scope every addon-wide (not per-node, not per-device) setting lives in. */
6026
+ function globalSecretScope() {
6027
+ return GLOBAL_SCOPE;
6028
+ }
6029
+ function encodeSegment(value) {
6030
+ return encodeURIComponent(value);
6031
+ }
6032
+ /**
6033
+ * The field path of a value inside an array item, addressed by the item's id:
6034
+ * `arrayItemFieldPath('providers', 'authentik', 'clientSecret')` →
6035
+ * `providers[authentik].clientSecret`.
6036
+ */
6037
+ function arrayItemFieldPath(arrayKey, itemId, fieldKey) {
6038
+ return `${arrayKey}[${encodeSegment(itemId)}].${fieldKey}`;
6039
+ }
6040
+ /** A write to a secret path could not be stored in the keychain, so it was refused. */
6041
+ var KeychainWriteRefusedError = class extends Error {
6042
+ fieldPath;
6043
+ constructor(fieldPath, cause) {
6044
+ super(`secret "${fieldPath}" was not saved: the keychain could not store it (${cause instanceof Error ? cause.message : String(cause)}). Nothing was written.`);
6045
+ this.fieldPath = fieldPath;
6046
+ this.name = "KeychainWriteRefusedError";
6047
+ }
6048
+ };
6049
+ var KEEP = { kind: "keep" };
6050
+ function isRecord(value) {
6051
+ return typeof value === "object" && value !== null && !Array.isArray(value);
6052
+ }
6053
+ function defaultMintId() {
6054
+ return globalThis.crypto.randomUUID();
6055
+ }
6056
+ /** Every marker ref anywhere under `value`. */
6057
+ function collectSecretMarkerRefs(value, out = []) {
6058
+ if (isSecretMarker(value)) {
6059
+ out.push(value.$secret);
6060
+ return out;
6061
+ }
6062
+ if (Array.isArray(value)) for (const item of value) collectSecretMarkerRefs(item, out);
6063
+ else if (isRecord(value)) for (const child of Object.values(value)) collectSecretMarkerRefs(child, out);
6064
+ return out;
6065
+ }
6066
+ async function storedValueEquals(secrets, marker, candidate) {
6067
+ const resolved = (await secrets.resolve([marker.$secret]))[marker.$secret];
6068
+ return resolved?.kind === "value" && resolved.value === candidate;
6069
+ }
6070
+ async function writeLeaf(ctx, incoming, stored, fieldPath) {
6071
+ const intent = classifySecretWrite(incoming);
6072
+ const ref = ctx.secrets.ref(ctx.scope, fieldPath);
6073
+ const storedIsOurs = isSecretMarker(stored) && stored.$secret === ref;
6074
+ if (intent.kind === "keep") return KEEP;
6075
+ if (intent.kind === "set" && !ctx.operatorWrite && typeof stored === "string" && stored === intent.value) return KEEP;
6076
+ if (intent.kind === "clear") {
6077
+ if (storedIsOurs) ctx.deletes.push(ref);
6078
+ return {
6079
+ kind: "value",
6080
+ value: null
6081
+ };
6082
+ }
6083
+ if (storedIsOurs && await storedValueEquals(ctx.secrets, stored, intent.value)) return {
6084
+ kind: "value",
6085
+ value: stored
6086
+ };
6087
+ try {
6088
+ await ctx.secrets.put(ref, intent.value);
6089
+ } catch (err) {
6090
+ throw new KeychainWriteRefusedError(fieldPath, err);
6091
+ }
6092
+ return {
6093
+ kind: "value",
6094
+ value: makeSecretMarker(ref)
6095
+ };
6096
+ }
6097
+ /** Apply a member result onto `out`: KEEP restores the stored member, or removes it. */
6098
+ function applyMember(out, key, result, storedParent) {
6099
+ if (result.kind === "value") {
6100
+ out[key] = result.value;
6101
+ return;
6102
+ }
6103
+ if (Object.prototype.hasOwnProperty.call(storedParent, key)) out[key] = storedParent[key];
6104
+ else delete out[key];
6105
+ }
6106
+ async function writeMembers(ctx, children, incoming, stored, pathOf) {
6107
+ const out = { ...incoming };
6108
+ for (const [member, node] of children) applyMember(out, member, await writeNode(ctx, node, incoming[member], stored[member], pathOf(member)), stored);
6109
+ return out;
6110
+ }
6111
+ function rowId(row, idKey) {
6112
+ const raw = row[idKey];
6113
+ if (typeof raw === "string" && raw.length > 0) return raw;
6114
+ if (typeof raw === "number" && Number.isFinite(raw)) return String(raw);
6115
+ return null;
6116
+ }
6117
+ async function writeArray(ctx, node, incoming, stored, fieldPath) {
6118
+ const storedRows = Array.isArray(stored) ? stored.filter(isRecord) : [];
6119
+ if (!Array.isArray(incoming)) {
6120
+ ctx.deletes.push(...collectSecretMarkerRefs(storedRows));
6121
+ return {
6122
+ kind: "value",
6123
+ value: incoming
6124
+ };
6125
+ }
6126
+ const storedById = /* @__PURE__ */ new Map();
6127
+ for (const row of storedRows) {
6128
+ const id = rowId(row, node.idKey);
6129
+ if (id !== null) storedById.set(id, row);
6130
+ }
6131
+ const kept = /* @__PURE__ */ new Set();
6132
+ const rows = [];
6133
+ for (const row of incoming) {
6134
+ if (!isRecord(row)) {
6135
+ rows.push(row);
6136
+ continue;
6137
+ }
6138
+ const id = rowId(row, node.idKey) ?? ctx.mintId();
6139
+ kept.add(id);
6140
+ const withId = {
6141
+ ...row,
6142
+ [node.idKey]: row[node.idKey] ?? id
6143
+ };
6144
+ if (rowId(withId, node.idKey) === null) withId[node.idKey] = id;
6145
+ const storedRow = storedById.get(id) ?? {};
6146
+ rows.push(await writeMembers(ctx, node.item, withId, storedRow, (member) => arrayItemFieldPath(fieldPath, id, member)));
6147
+ }
6148
+ for (const [id, row] of storedById) if (!kept.has(id)) ctx.deletes.push(...collectSecretMarkerRefs(row));
6149
+ return {
6150
+ kind: "value",
6151
+ value: rows
6152
+ };
6153
+ }
6154
+ async function writeNode(ctx, node, incoming, stored, fieldPath) {
6155
+ switch (node.kind) {
6156
+ case "leaf": return writeLeaf(ctx, incoming, stored, fieldPath);
6157
+ case "array": return writeArray(ctx, node, incoming, stored, fieldPath);
6158
+ case "object": {
6159
+ if (!isRecord(incoming)) {
6160
+ if (incoming === void 0) return KEEP;
6161
+ ctx.deletes.push(...collectSecretMarkerRefs(stored));
6162
+ return {
6163
+ kind: "value",
6164
+ value: incoming
6165
+ };
6166
+ }
6167
+ const storedObj = isRecord(stored) ? stored : {};
6168
+ return {
6169
+ kind: "value",
6170
+ value: await writeMembers(ctx, node.children, incoming, storedObj, (m) => `${fieldPath}.${m}`)
6171
+ };
6172
+ }
6173
+ }
6174
+ }
6175
+ /** Split a perNode-scoped key (`key@nodeId`). */
6176
+ function splitNodeKey(key) {
6177
+ const at = key.indexOf("@");
6178
+ return at <= 0 ? {
6179
+ base: key,
6180
+ nodeId: null
6181
+ } : {
6182
+ base: key.slice(0, at),
6183
+ nodeId: key.slice(at + 1)
6184
+ };
6185
+ }
6186
+ /** Rewrite a settings patch so no secret value reaches the blob. See the file doc. */
6187
+ async function transformSecretWrite(input) {
6188
+ const deletes = [];
6189
+ const base = {
6190
+ secrets: input.secrets,
6191
+ mintId: input.mintId ?? defaultMintId,
6192
+ deletes,
6193
+ operatorWrite: input.operatorWrite === true
6194
+ };
6195
+ const out = {};
6196
+ for (const [key, incoming] of Object.entries(input.patch)) {
6197
+ const { base: baseKey, nodeId } = splitNodeKey(key);
6198
+ const node = input.tree.get(baseKey);
6199
+ if (node === void 0) {
6200
+ out[key] = incoming;
6201
+ continue;
6202
+ }
6203
+ const scope = nodeId !== null && nodeId.length > 0 ? {
6204
+ kind: "node",
6205
+ nodeId
6206
+ } : input.scope ?? globalSecretScope();
6207
+ const result = await writeNode({
6208
+ ...base,
6209
+ scope
6210
+ }, node, incoming, input.stored[key], baseKey);
6211
+ if (result.kind === "value") out[key] = result.value;
6212
+ }
6213
+ return {
6214
+ patch: out,
6215
+ afterWrite: async () => {
6216
+ if (deletes.length === 0) return { orphaned: [] };
6217
+ try {
6218
+ await input.secrets.delete([...new Set(deletes)]);
6219
+ return { orphaned: [] };
6220
+ } catch {
6221
+ return { orphaned: [...new Set(deletes)] };
6222
+ }
6223
+ }
6224
+ };
6225
+ }
6226
+ /**
6227
+ * Replace every marker in `value` with its keychain value. Returns the SAME
6228
+ * reference when there is no marker (no allocation, no keychain call).
6229
+ */
6230
+ async function resolveSecretMarkers(value, secrets) {
6231
+ const refs = collectSecretMarkerRefs(value);
6232
+ if (refs.length === 0) return {
6233
+ value,
6234
+ unresolved: []
6235
+ };
6236
+ const answers = await secrets.resolve(refs);
6237
+ const unresolved = [];
6238
+ for (const ref of new Set(refs)) {
6239
+ const answer = answers[ref];
6240
+ if (answer === void 0) unresolved.push({
6241
+ ref,
6242
+ reason: "not-initialized"
6243
+ });
6244
+ else if (answer.kind === "unavailable") unresolved.push({
6245
+ ref,
6246
+ reason: answer.reason
6247
+ });
6248
+ else if (answer.kind === "missing" || answer.kind === "forbidden") unresolved.push({
6249
+ ref,
6250
+ reason: answer.kind
6251
+ });
6252
+ }
6253
+ const substitute = (v) => {
6254
+ if (isSecretMarker(v)) {
6255
+ const answer = answers[v.$secret];
6256
+ return answer?.kind === "value" ? {
6257
+ keep: true,
6258
+ value: answer.value
6259
+ } : {
6260
+ keep: false,
6261
+ value: void 0
6262
+ };
6263
+ }
6264
+ if (Array.isArray(v)) {
6265
+ const items = [];
6266
+ for (const item of v) {
6267
+ const s = substitute(item);
6268
+ if (s.keep) items.push(s.value);
6269
+ }
6270
+ return {
6271
+ keep: true,
6272
+ value: items
6273
+ };
6274
+ }
6275
+ if (isRecord(v)) {
6276
+ const out = {};
6277
+ for (const [k, child] of Object.entries(v)) {
6278
+ const s = substitute(child);
6279
+ if (s.keep) out[k] = s.value;
6280
+ }
6281
+ return {
6282
+ keep: true,
6283
+ value: out
6284
+ };
6285
+ }
6286
+ return {
6287
+ keep: true,
6288
+ value: v
6289
+ };
6290
+ };
6291
+ return {
6292
+ value: substitute(value).value,
6293
+ unresolved
6294
+ };
6295
+ }
6296
+ function touchesTree(tree, patch) {
6297
+ if (tree.size === 0) return false;
6298
+ for (const key of Object.keys(patch)) {
6299
+ const at = key.indexOf("@");
6300
+ if (tree.has(at > 0 ? key.slice(0, at) : key)) return true;
6301
+ }
6302
+ return false;
6303
+ }
6304
+ /** The blob as stored now; a failed read REFUSES the write instead of guessing. */
6305
+ async function readStoredAddonBlob(raw) {
6306
+ const threeWay = raw.readAddonStoreResult;
6307
+ if (threeWay === void 0) return raw.readAddonStore();
6308
+ const result = await threeWay.call(raw);
6309
+ if (result.kind === "failed") throw new Error(`settings write refused: the stored blob could not be read (${result.error})`);
6310
+ return result.kind === "missing" ? {} : result.value;
6311
+ }
6312
+ function createSecretAwareSettings(raw, opts) {
6313
+ const chains = /* @__PURE__ */ new Map();
6314
+ const serialize = (key, fn) => {
6315
+ const next = (chains.get(key) ?? Promise.resolve()).then(fn, fn);
6316
+ const tail = next.catch(() => void 0);
6317
+ chains.set(key, tail);
6318
+ tail.then(() => {
6319
+ if (chains.get(key) === tail) chains.delete(key);
6320
+ });
6321
+ return next;
6322
+ };
6323
+ const write = async (chainKey, tree, scope, patch, readStored, rawWrite) => {
6324
+ if (!touchesTree(tree, patch)) return rawWrite(patch);
6325
+ return serialize(chainKey, async () => {
6326
+ const stored = await readStored();
6327
+ const result = await transformSecretWrite({
6328
+ tree,
6329
+ secrets: opts.secrets,
6330
+ patch,
6331
+ stored,
6332
+ ...scope !== void 0 ? { scope } : {},
6333
+ operatorWrite: opts.isOperatorWrite?.() === true
6334
+ });
6335
+ if (Object.keys(result.patch).length > 0) await rawWrite(result.patch);
6336
+ const { orphaned } = await result.afterWrite();
6337
+ if (orphaned.length > 0) opts.onOrphaned(orphaned);
6338
+ });
6339
+ };
6340
+ const wrapped = {
6341
+ writeAddonStore: (patch) => write("addon", opts.addonTree(), void 0, patch, () => readStoredAddonBlob(raw), (p) => raw.writeAddonStore(p)),
6342
+ writeDeviceStore: (deviceId, patch) => write(`device:${deviceId}`, opts.deviceTree(), {
6343
+ kind: "device",
6344
+ deviceId
6345
+ }, patch, () => raw.readDeviceStore(deviceId), (p) => raw.writeDeviceStore(deviceId, p))
6346
+ };
6347
+ return new Proxy(raw, { get(target, prop, receiver) {
6348
+ if (prop === "writeAddonStore") return wrapped.writeAddonStore;
6349
+ if (prop === "writeDeviceStore") return wrapped.writeDeviceStore;
6350
+ const value = Reflect.get(target, prop, receiver);
6351
+ return typeof value === "function" ? value.bind(target) : value;
6352
+ } });
6353
+ }
6354
+ /** The context the addon sees: identical, except that its settings writes are secret-aware. */
6355
+ function withSecretAwareSettings(context, opts) {
6356
+ const raw = context.settings;
6357
+ if (raw === void 0) return context;
6358
+ const settings = createSecretAwareSettings(raw, opts);
6359
+ return new Proxy(context, { get(target, prop, receiver) {
6360
+ if (prop === "settings") return settings;
6361
+ return Reflect.get(target, prop, receiver);
6362
+ } });
6363
+ }
6364
+ var LEAF = { kind: "leaf" };
6365
+ var DEFAULT_ITEM_ID_KEY = "id";
6366
+ function collectFields(fields, out) {
6367
+ for (const field of fields) {
6368
+ if (field.type === "group") {
6369
+ collectFields(field.fields, out);
6370
+ continue;
6371
+ }
6372
+ if (field.type === "sub-tabs") {
6373
+ for (const tab of field.tabs) collectFields(tab.fields, out);
6374
+ continue;
6375
+ }
6376
+ if (field.type === "editable-array") {
6377
+ const item = /* @__PURE__ */ new Map();
6378
+ for (const itemField of field.itemFields) if ("key" in itemField && isKeychainStoredField(itemField)) item.set(itemField.key, LEAF);
6379
+ if (item.size > 0) out.set(field.key, {
6380
+ kind: "array",
6381
+ idKey: field.itemIdKey ?? DEFAULT_ITEM_ID_KEY,
6382
+ item
6383
+ });
6384
+ continue;
6385
+ }
6386
+ if (!("key" in field) || typeof field.key !== "string") continue;
6387
+ if (isKeychainStoredField(field)) out.set(field.key, LEAF);
6388
+ }
6389
+ }
6390
+ /** The secret tree a settings schema declares. */
6391
+ function secretTreeFromSchema(schema) {
6392
+ const out = /* @__PURE__ */ new Map();
6393
+ if (schema === null) return out;
6394
+ for (const section of schema.sections) collectFields(section.fields, out);
6395
+ return out;
6396
+ }
6397
+ /** Parse `a.b[id].c` into segments; throws on a malformed path (a declaration bug). */
6398
+ function parseSecretStatePath(path) {
6399
+ const segments = [];
6400
+ for (const raw of path.split(".")) {
6401
+ const m = /^([^[\]]+)(?:\[([^[\]]+)\])?$/.exec(raw);
6402
+ if (m === null || m[1] === void 0) throw new Error(`secretStatePaths: malformed path "${path}"`);
6403
+ segments.push(m[2] !== void 0 ? {
6404
+ key: m[1],
6405
+ idKey: m[2]
6406
+ } : { key: m[1] });
6407
+ }
6408
+ if (segments.length === 0) throw new Error(`secretStatePaths: empty path`);
6409
+ if (segments[segments.length - 1]?.idKey !== void 0) throw new Error(`secretStatePaths: "${path}" ends on an array — name the member that is secret`);
6410
+ return segments;
6411
+ }
6412
+ function insert(into, segments) {
6413
+ const [head, ...rest] = segments;
6414
+ if (head === void 0) return;
6415
+ if (rest.length === 0) {
6416
+ into.set(head.key, LEAF);
6417
+ return;
6418
+ }
6419
+ const existing = into.get(head.key);
6420
+ if (head.idKey !== void 0) {
6421
+ const item = new Map(existing?.kind === "array" ? existing.item : []);
6422
+ insert(item, rest);
6423
+ into.set(head.key, {
6424
+ kind: "array",
6425
+ idKey: head.idKey,
6426
+ item
6427
+ });
6428
+ return;
6429
+ }
6430
+ const children = new Map(existing?.kind === "object" ? existing.children : []);
6431
+ insert(children, rest);
6432
+ into.set(head.key, {
6433
+ kind: "object",
6434
+ children
6435
+ });
6436
+ }
6437
+ /** Add hidden-state paths (`secretStatePaths`) to a schema-derived tree. */
6438
+ function mergeSecretStatePaths(tree, paths) {
6439
+ if (paths.length === 0) return tree;
6440
+ const out = new Map(tree);
6441
+ for (const path of paths) insert(out, parseSecretStatePath(path));
6442
+ return out;
6443
+ }
6444
+ /** First retry of a secret the keychain could not serve; doubles to {@link SECRET_RETRY_MAX_MS}. */
6445
+ var SECRET_RETRY_FIRST_MS = 5e3;
6446
+ var SECRET_RETRY_MAX_MS = 5 * 6e4;
6447
+ /** Coalesces a burst of `keychain.changed` events into one re-resolve. */
6448
+ var SECRET_CHANGE_DEBOUNCE_MS = 250;
5913
6449
  /**
5914
6450
  * Base class for CamStack addons. Eliminates settings boilerplate:
5915
6451
  *
@@ -5979,6 +6515,25 @@ var BaseAddon = class {
5979
6515
  settingsStoreReady = false;
5980
6516
  /** Default config values. Provided via constructor. */
5981
6517
  defaults;
6518
+ /**
6519
+ * Hidden-state paths that hold secrets (D787) — values the addon writes
6520
+ * itself (`updateGlobalSettings`, `state()`) that no form field declares.
6521
+ * Stored in the keychain exactly like a `password` field. Syntax:
6522
+ * `'snapshotSigningKey'`, `'identity.pincode'`, `'tokens[userId].accessToken'`
6523
+ * (`key[<id field>]` addresses array items by id, never by index).
6524
+ */
6525
+ secretStatePaths = [];
6526
+ _addonSecretTree = null;
6527
+ _deviceSecretTree = null;
6528
+ /** Refs the last resolved config pointed at — a change to one re-resolves. */
6529
+ _configSecretRefs = /* @__PURE__ */ new Set();
6530
+ _unresolvedSecrets = [];
6531
+ _secretRetryTimer = null;
6532
+ _secretRetryDelayMs = SECRET_RETRY_FIRST_MS;
6533
+ _secretChangeTimer = null;
6534
+ _secretChangeUnsub = null;
6535
+ /** >0 while an OPERATOR's settings write is being applied. */
6536
+ _operatorWriteDepth = 0;
5982
6537
  constructor(defaults) {
5983
6538
  this.defaults = defaults;
5984
6539
  this._config = { ...defaults };
@@ -6014,8 +6569,18 @@ var BaseAddon = class {
6014
6569
  return this._config;
6015
6570
  }
6016
6571
  async initialize(context) {
6017
- this._ctx = context;
6572
+ const secrets = context.secrets;
6573
+ this._ctx = secrets !== void 0 ? withSecretAwareSettings(context, {
6574
+ secrets,
6575
+ addonTree: () => this.addonSecretTree(),
6576
+ deviceTree: () => this.deviceSecretTree(),
6577
+ onOrphaned: (refs) => context.logger.warn("keychain refs dropped by a settings write could not be deleted", { meta: { refs: [...refs] } }),
6578
+ isOperatorWrite: () => this._operatorWriteDepth > 0
6579
+ }) : context;
6018
6580
  await this.resolveConfig();
6581
+ if (secrets !== void 0) this._secretChangeUnsub = secrets.onChange((ref) => {
6582
+ if (this._configSecretRefs.has(ref)) this.scheduleSecretReresolve(SECRET_CHANGE_DEBOUNCE_MS);
6583
+ });
6019
6584
  const result = await this.onInitialize();
6020
6585
  this.emitLifecycle(EventCategory.AddonStarted);
6021
6586
  const normalized = normalizeAddonInitResult(result);
@@ -6048,6 +6613,12 @@ var BaseAddon = class {
6048
6613
  */
6049
6614
  async onHubReachable() {}
6050
6615
  async shutdown() {
6616
+ this._secretChangeUnsub?.();
6617
+ this._secretChangeUnsub = null;
6618
+ if (this._secretRetryTimer !== null) clearTimeout(this._secretRetryTimer);
6619
+ if (this._secretChangeTimer !== null) clearTimeout(this._secretChangeTimer);
6620
+ this._secretRetryTimer = null;
6621
+ this._secretChangeTimer = null;
6051
6622
  this.emitLifecycle(EventCategory.AddonStopped);
6052
6623
  if (this.autoEmitReadiness) this.emitReadinessForProviders("down");
6053
6624
  await this.onShutdown();
@@ -6126,7 +6697,7 @@ var BaseAddon = class {
6126
6697
  return hydrateSchema(schema, overlay ? {
6127
6698
  ...projected,
6128
6699
  ...overlay
6129
- } : projected);
6700
+ } : projected, { inlineSecretsAsViews: true });
6130
6701
  }
6131
6702
  /**
6132
6703
  * The integration-level view of this addon's settings: exactly the sections
@@ -6175,7 +6746,7 @@ var BaseAddon = class {
6175
6746
  return hydrateSchema({
6176
6747
  ...schema,
6177
6748
  sections
6178
- }, projected);
6749
+ }, projected, { inlineSecretsAsViews: true });
6179
6750
  }
6180
6751
  /**
6181
6752
  * The raw addon store PROJECTED onto the target node's bare per-node keys:
@@ -6229,18 +6800,50 @@ var BaseAddon = class {
6229
6800
  value: result.value[key]
6230
6801
  };
6231
6802
  }
6803
+ /**
6804
+ * The OPERATOR's write — a settings form or an admin API call, dispatched by
6805
+ * the kernel. Identical to {@link updateGlobalSettings}, except that a secret
6806
+ * the operator sends is stored as sent even when it equals a pre-keychain
6807
+ * inline value: the operator re-entering a password is a change, an addon
6808
+ * writing back what it read is not (D787).
6809
+ */
6810
+ async updateGlobalSettingsAsOperator(patch, nodeId) {
6811
+ this._operatorWriteDepth++;
6812
+ try {
6813
+ await this.applyGlobalPatch(patch, nodeId);
6814
+ } finally {
6815
+ this._operatorWriteDepth--;
6816
+ }
6817
+ }
6232
6818
  async updateGlobalSettings(patch, nodeId) {
6819
+ await this.applyGlobalPatch(patch, nodeId);
6820
+ }
6821
+ /**
6822
+ * REMOVE stored secrets — their keychain values and their markers (D787).
6823
+ *
6824
+ * Writing `''` to a secret field KEEPS what is stored (an empty string is
6825
+ * what a defaults fallback writes back, and it must never destroy a
6826
+ * credential), so code that means "forget this token" says so here. Without
6827
+ * a keychain (an older kernel) it writes `''`, as such code always did.
6828
+ */
6829
+ async clearSecrets(keys, nodeId) {
6830
+ const tree = this.addonSecretTree();
6831
+ const keychain = this._ctx?.secrets !== void 0;
6832
+ const patch = {};
6833
+ for (const key of keys) patch[key] = keychain && tree.has(key) ? SECRET_CLEAR : "";
6834
+ await this.applyGlobalPatch(patch, nodeId);
6835
+ }
6836
+ async applyGlobalPatch(barePatch, nodeId) {
6233
6837
  const keys = this.perNodeKeys();
6234
6838
  const localNode = normalizeNodeId(this._ctx?.kernel?.localNodeId);
6235
6839
  const target = normalizeNodeId(nodeId ?? this._ctx?.kernel?.localNodeId);
6236
- const barePatch = patch;
6237
6840
  const scoped = keys.size > 0 ? scopePatch(barePatch, keys, target) : barePatch;
6238
6841
  await this._ctx?.settings?.writeAddonStore(scoped);
6239
6842
  if (target !== localNode) return;
6240
6843
  await this.resolveConfig();
6241
6844
  await this.onConfigChanged();
6242
6845
  this.emitLifecycle(EventCategory.AddonUpdated, { level: "global" });
6243
- this.maybeAutoRestart(patch, this.globalSettingsSchema());
6846
+ this.maybeAutoRestart(Object.keys(barePatch), this.globalSettingsSchema());
6244
6847
  }
6245
6848
  /**
6246
6849
  * The set of field keys the global settings schema declares `perNode: true`
@@ -6265,7 +6868,7 @@ var BaseAddon = class {
6265
6868
  * time to return its response before the addon is torn down and
6266
6869
  * re-initialised by `AddonRegistryService.restartAddon`.
6267
6870
  */
6268
- maybeAutoRestart(patch, schema) {
6871
+ maybeAutoRestart(patchKeys, schema) {
6269
6872
  if (!schema) return;
6270
6873
  const restartKeys = /* @__PURE__ */ new Set();
6271
6874
  for (const section of schema.sections) for (const field of section.fields) {
@@ -6273,13 +6876,13 @@ var BaseAddon = class {
6273
6876
  if (field.requiresRestart) restartKeys.add(field.key);
6274
6877
  }
6275
6878
  if (restartKeys.size === 0) return;
6276
- if (!Object.keys(patch).some((k) => restartKeys.has(k))) return;
6879
+ if (!patchKeys.some((k) => restartKeys.has(k))) return;
6277
6880
  const ctx = this._ctx;
6278
6881
  if (!ctx) return;
6279
6882
  const addonId = ctx.id;
6280
6883
  setImmediate(() => {
6281
6884
  ctx.api.addons?.restartAddon?.mutate({ addonId }).then(() => {
6282
- ctx.logger.info("addon auto-restart triggered by restart-required setting change", { meta: { changedFields: Object.keys(patch).filter((k) => restartKeys.has(k)) } });
6885
+ ctx.logger.info("addon auto-restart triggered by restart-required setting change", { meta: { changedFields: patchKeys.filter((k) => restartKeys.has(k)) } });
6283
6886
  }).catch((err) => {
6284
6887
  ctx.logger.error("addon auto-restart failed", { meta: { error: err instanceof Error ? err.message : String(err) } });
6285
6888
  });
@@ -6288,7 +6891,7 @@ var BaseAddon = class {
6288
6891
  async getDeviceSettings(deviceId) {
6289
6892
  const schema = this.deviceSettingsSchema();
6290
6893
  if (!schema) return { sections: [] };
6291
- return hydrateSchema(schema, await this._ctx?.settings?.readDeviceStore(deviceId) ?? {});
6894
+ return hydrateSchema(schema, await this._ctx?.settings?.readDeviceStore(deviceId) ?? {}, { inlineSecretsAsViews: true });
6292
6895
  }
6293
6896
  async updateDeviceSettings(deviceId, patch) {
6294
6897
  await this._ctx?.settings?.writeDeviceStore(deviceId, patch);
@@ -6418,7 +7021,7 @@ var BaseAddon = class {
6418
7021
  * selection at boot (absent scoped key ⇒ the constructor default wins).
6419
7022
  */
6420
7023
  async resolveConfig() {
6421
- const stored = await this.readAddonStoreWithRetry();
7024
+ const stored = await this.resolveStoredSecrets(await this.readAddonStoreWithRetry());
6422
7025
  const perNode = this.perNodeKeys();
6423
7026
  const localNode = normalizeNodeId(this._ctx?.kernel?.localNodeId);
6424
7027
  const resolved = { ...this.defaults };
@@ -6443,7 +7046,7 @@ var BaseAddon = class {
6443
7046
  key,
6444
7047
  schema,
6445
7048
  fallback,
6446
- read: () => this.readAddonStoreWithRetry(),
7049
+ read: async () => this.resolveStoredSecrets(await this.readAddonStoreWithRetry()),
6447
7050
  write: async (patch) => {
6448
7051
  await this._ctx?.settings?.writeAddonStore(patch);
6449
7052
  },
@@ -6460,7 +7063,7 @@ var BaseAddon = class {
6460
7063
  key,
6461
7064
  schema,
6462
7065
  fallback,
6463
- read: async () => await this._ctx?.settings?.readDeviceStore(deviceId) ?? {},
7066
+ read: async () => this.resolveStoredSecrets(await this._ctx?.settings?.readDeviceStore(deviceId) ?? {}, false),
6464
7067
  write: async (patch) => {
6465
7068
  await this._ctx?.settings?.writeDeviceStore(deviceId, patch);
6466
7069
  },
@@ -6472,6 +7075,70 @@ var BaseAddon = class {
6472
7075
  } })
6473
7076
  });
6474
7077
  }
7078
+ /** The addon store's secret tree: schema fields by TYPE, plus `secretStatePaths`. */
7079
+ addonSecretTree() {
7080
+ this._addonSecretTree ??= mergeSecretStatePaths(secretTreeFromSchema(this.globalSettingsSchema()), this.secretStatePaths);
7081
+ return this._addonSecretTree;
7082
+ }
7083
+ deviceSecretTree() {
7084
+ this._deviceSecretTree ??= secretTreeFromSchema(this.deviceSettingsSchema());
7085
+ return this._deviceSecretTree;
7086
+ }
7087
+ /**
7088
+ * Secrets of this addon's stored config that could not be resolved on the
7089
+ * last read, with why. Non-empty means the addon is running WITHOUT them —
7090
+ * an addon whose function needs one should report itself degraded rather
7091
+ * than start on an empty credential.
7092
+ */
7093
+ get unresolvedSecrets() {
7094
+ return this._unresolvedSecrets;
7095
+ }
7096
+ /**
7097
+ * Substitute every keychain marker in a stored blob with its value. With no
7098
+ * keychain (no `ctx.secrets`) or no marker, the blob comes back unchanged.
7099
+ * An unresolvable value is LEFT OUT (never `''`), logged by ref — never by
7100
+ * value — and, when the cause can pass, retried with backoff. Nothing is
7101
+ * ever written back from here.
7102
+ */
7103
+ async resolveStoredSecrets(blob, trackForConfig = true) {
7104
+ const secrets = this._ctx?.secrets;
7105
+ if (secrets === void 0) return blob;
7106
+ const refs = collectSecretMarkerRefs(blob);
7107
+ if (trackForConfig) this._configSecretRefs = new Set(refs);
7108
+ if (refs.length === 0) {
7109
+ if (trackForConfig) this._unresolvedSecrets = [];
7110
+ return blob;
7111
+ }
7112
+ const { value, unresolved } = await resolveSecretMarkers(blob, secrets);
7113
+ if (trackForConfig) {
7114
+ this._unresolvedSecrets = unresolved;
7115
+ if (unresolved.length > 0) {
7116
+ this._ctx?.logger?.error?.("secret unavailable — running without it, will retry", { meta: { secrets: unresolved.map((u) => ({
7117
+ ref: u.ref,
7118
+ reason: u.reason
7119
+ })) } });
7120
+ if (unresolved.some((u) => u.reason !== "missing" && u.reason !== "forbidden")) {
7121
+ this.scheduleSecretReresolve(this._secretRetryDelayMs);
7122
+ this._secretRetryDelayMs = Math.min(this._secretRetryDelayMs * 2, SECRET_RETRY_MAX_MS);
7123
+ }
7124
+ } else this._secretRetryDelayMs = SECRET_RETRY_FIRST_MS;
7125
+ }
7126
+ return value;
7127
+ }
7128
+ /** Re-resolve the config (a keychain-only change, or a retry) and apply it. */
7129
+ scheduleSecretReresolve(delayMs) {
7130
+ const timerOf = delayMs === SECRET_CHANGE_DEBOUNCE_MS ? "_secretChangeTimer" : "_secretRetryTimer";
7131
+ if (this[timerOf] !== null) return;
7132
+ const timer = setTimeout(() => {
7133
+ this[timerOf] = null;
7134
+ if (this._ctx === null) return;
7135
+ this.resolveConfig().then(() => this.onConfigChanged()).catch((err) => {
7136
+ this._ctx?.logger?.error?.("re-resolving secrets failed", { meta: { error: err instanceof Error ? err.message : String(err) } });
7137
+ });
7138
+ }, delayMs);
7139
+ timer.unref?.();
7140
+ this[timerOf] = timer;
7141
+ }
6475
7142
  /**
6476
7143
  * Wrap `ctx.settings.readAddonStore()` with a short retry budget so a
6477
7144
  * transient settings-store outage (mid-restart of sqlite-settings, tsx-watch
@@ -7047,6 +7714,69 @@ method(object({ deviceId: number() }), array(StreamSourceEntrySchema)), method(o
7047
7714
  kind: "mutation",
7048
7715
  auth: "admin"
7049
7716
  }), method(object({ deviceId: number() }), unknown().nullable()), method(object({ deviceId: number() }), RawStateResultSchema.nullable(), { auth: "protected" });
7717
+ function defOf(schema) {
7718
+ return schema._zod?.def ?? {};
7719
+ }
7720
+ function declaredHere(schema) {
7721
+ return globalRegistry.get(schema)?.secret === true;
7722
+ }
7723
+ /** Wrapper kinds whose `innerType` is the field itself. */
7724
+ var WRAPPERS = new Set([
7725
+ "optional",
7726
+ "nullable",
7727
+ "default",
7728
+ "prefault",
7729
+ "catch",
7730
+ "readonly",
7731
+ "nonoptional"
7732
+ ]);
7733
+ /**
7734
+ * The schema layers that make up ONE field: the schema itself and every
7735
+ * wrapper below it (optional / default / nullable / readonly / catch), plus
7736
+ * both sides of a pipe (`z.preprocess` puts the real schema on `out`,
7737
+ * `.transform` on `in`).
7738
+ */
7739
+ function layersOf(schema) {
7740
+ const out = [];
7741
+ const queue = [schema];
7742
+ while (queue.length > 0) {
7743
+ const s = queue.shift();
7744
+ if (!s || out.includes(s)) continue;
7745
+ out.push(s);
7746
+ const def = defOf(s);
7747
+ if (def.type !== void 0 && WRAPPERS.has(def.type) && def.innerType) queue.push(def.innerType);
7748
+ if (def.type === "pipe") {
7749
+ if (def.in) queue.push(def.in);
7750
+ if (def.out) queue.push(def.out);
7751
+ }
7752
+ }
7753
+ return out;
7754
+ }
7755
+ /** True when any layer of this field declares `.meta({ secret: true })`. */
7756
+ function isZodSecret(schema) {
7757
+ return layersOf(schema).some(declaredHere);
7758
+ }
7759
+ /**
7760
+ * Every declared secret path in a config schema: dotted keys, `[]` for "each
7761
+ * element of this array" (`connection.password`, `rows[].token`). A declared
7762
+ * object or array is reported as one path and not descended into — everything
7763
+ * under it is secret.
7764
+ */
7765
+ function collectZodSecretPaths(schema, prefix = "") {
7766
+ if (isZodSecret(schema)) return prefix.length > 0 ? [prefix] : [];
7767
+ const paths = [];
7768
+ for (const layer of layersOf(schema)) {
7769
+ const def = defOf(layer);
7770
+ if (def.type === "object" && def.shape) for (const [key, child] of Object.entries(def.shape)) paths.push(...collectZodSecretPaths(child, prefix ? `${prefix}.${key}` : key));
7771
+ else if (def.type === "array" && def.element) paths.push(...collectZodSecretPaths(def.element, `${prefix}[]`));
7772
+ else if (def.type === "union" && def.options) for (const option of def.options) paths.push(...collectZodSecretPaths(option, prefix));
7773
+ else if (def.type === "intersection") {
7774
+ if (def.left) paths.push(...collectZodSecretPaths(def.left, prefix));
7775
+ if (def.right) paths.push(...collectZodSecretPaths(def.right, prefix));
7776
+ }
7777
+ }
7778
+ return [...new Set(paths)];
7779
+ }
7050
7780
  //#endregion
7051
7781
  //#region ../types/dist/err-msg-DX6i_MY4.mjs
7052
7782
  var DeviceType = /* @__PURE__ */ function(DeviceType) {
@@ -14077,6 +14807,196 @@ id: union([string(), number()]) }), {
14077
14807
  kind: "mutation",
14078
14808
  auth: "admin"
14079
14809
  });
14810
+ /**
14811
+ * `keychain` — the hub's encrypted store of secret values (D787).
14812
+ *
14813
+ * Settings blobs never hold a secret: they hold a marker
14814
+ * `{"$secret":"secret://<owner>/<scope>/<fieldPath>","v":1}` and the value
14815
+ * lives here, AES-256-GCM under a data key that a master key wraps. This cap
14816
+ * is the OWNER's door to its own values: every method is owner-checked
14817
+ * against the CALLER, never against anything the caller claims.
14818
+ *
14819
+ * Who the caller is: the transport stamps `callerAddonId` into the args of a
14820
+ * call that crossed a process (the parent `LocalChildRegistry` from the UDS
14821
+ * connection, the agent from its child's connection carried in
14822
+ * `$hub-cap-fwd`'s envelope). A stamp always overwrites; a wire call with no
14823
+ * stamp has its claim stripped. Only a hub in-process caller may state its own
14824
+ * identity — `ctx.secrets` does that with the addon id closed over. This is
14825
+ * identity against BUGS and misrouting, not against a malicious addon (every
14826
+ * runner is the same OS user): see the threat model in
14827
+ * `docs/design/2026-10-08-secrets-keychain.md`.
14828
+ *
14829
+ * `callerAddonId` is deliberately NOT in any input schema: the tRPC router
14830
+ * parses the input, so a session can never supply it, and the internal mount
14831
+ * floors every method to admin anyway (D240).
14832
+ *
14833
+ * Internal: addons reach it through `ctx.secrets`, never directly.
14834
+ */
14835
+ /** Why a value cannot be served right now. Never folded into "missing". */
14836
+ var KeychainUnavailableReasonSchema = _enum([
14837
+ "key-missing",
14838
+ "wrong-key",
14839
+ "key-file-unreadable",
14840
+ "store-unavailable",
14841
+ "not-initialized",
14842
+ "decrypt-failed"
14843
+ ]);
14844
+ var KeychainStateSchema = discriminatedUnion("state", [object({ state: literal("ready") }), object({
14845
+ state: literal("locked"),
14846
+ reason: KeychainUnavailableReasonSchema
14847
+ })]);
14848
+ var KeychainResolveEntrySchema = discriminatedUnion("kind", [
14849
+ object({
14850
+ kind: literal("value"),
14851
+ value: string(),
14852
+ version: number().int()
14853
+ }),
14854
+ object({ kind: literal("missing") }),
14855
+ object({
14856
+ kind: literal("unavailable"),
14857
+ reason: KeychainUnavailableReasonSchema
14858
+ }),
14859
+ object({ kind: literal("forbidden") })
14860
+ ]);
14861
+ var KeychainResolveResultSchema = record(string(), KeychainResolveEntrySchema);
14862
+ /** Metadata of one stored value — never the value. */
14863
+ var KeychainSecretMetaSchema = object({
14864
+ ref: string(),
14865
+ owner: string(),
14866
+ /** Formatted scope (`global`, `node/<id>`, `device/<id>`, …). */
14867
+ scope: string(),
14868
+ fieldPath: string(),
14869
+ version: number().int(),
14870
+ createdAt: number(),
14871
+ updatedAt: number(),
14872
+ /** `addon:<id>` | `user:<id>` | `system`. */
14873
+ updatedBy: string(),
14874
+ /** Coarse — written at most once an hour per ref. `null` = never read. */
14875
+ lastReadAt: number().nullable()
14876
+ });
14877
+ var RefListSchema = array(string().min(1)).max(512);
14878
+ method(object({
14879
+ ref: string().min(1),
14880
+ value: string().min(1)
14881
+ }), object({
14882
+ ref: string(),
14883
+ version: number().int()
14884
+ }), {
14885
+ kind: "mutation",
14886
+ auth: "admin"
14887
+ }), method(object({ refs: RefListSchema }), KeychainResolveResultSchema, { auth: "admin" }), method(object({ refs: RefListSchema }), object({ deleted: number().int() }), {
14888
+ kind: "mutation",
14889
+ auth: "admin"
14890
+ }), method(object({}), array(KeychainSecretMetaSchema).readonly(), { auth: "admin" }), method(object({}), KeychainStateSchema, { auth: "admin" });
14891
+ var KeychainKeySourceSchema = object({
14892
+ kind: _enum([
14893
+ "config-file",
14894
+ "previous-config-file",
14895
+ "platform",
14896
+ "default-file"
14897
+ ]),
14898
+ /** File sources only — a path is not a secret. */
14899
+ path: string().optional(),
14900
+ /**
14901
+ * True when a whole-volume backup of the data directory carries this key
14902
+ * next to the database it protects (the default file). The page warns.
14903
+ */
14904
+ sharesBackupWithDatabase: boolean()
14905
+ });
14906
+ var KeychainStatusSchema = object({
14907
+ keychain: KeychainStateSchema,
14908
+ /** The source of the master key in use; `null` while locked. */
14909
+ keySource: KeychainKeySourceSchema.nullable(),
14910
+ /** The source configured to be primary — differs from `keySource` while a rotation is pending. */
14911
+ configuredSource: KeychainKeySourceSchema,
14912
+ /** Short fingerprint of the master key in use (`HMAC(KEK, label)`, 16 hex). */
14913
+ fingerprint: string().nullable(),
14914
+ activeKeyId: string().nullable(),
14915
+ /**
14916
+ * The keychain unlocked with a NON-primary source: the configured primary
14917
+ * key is not the one that wraps the data key yet. `rotateMasterKey` moves it.
14918
+ */
14919
+ rotationPending: boolean(),
14920
+ /** Wrapped copies of the data key under a previous master key, kept until purged. */
14921
+ retiredWraps: number().int(),
14922
+ recoveryKeyDownloadedAt: number().nullable(),
14923
+ secretCount: number().int()
14924
+ });
14925
+ /**
14926
+ * Whether a stored value is still pointed at by its owner's settings.
14927
+ * `unknown` is a first-class answer: a scope whose blob could not be read is
14928
+ * never reported as an orphan (and never deleted as one).
14929
+ */
14930
+ var KeychainSecretUsageSchema = _enum([
14931
+ "in-use",
14932
+ "orphan",
14933
+ "unknown"
14934
+ ]);
14935
+ var KeychainAdminSecretSchema = KeychainSecretMetaSchema.extend({ usage: KeychainSecretUsageSchema });
14936
+ var KeychainAuditActionSchema = _enum([
14937
+ "put",
14938
+ "delete",
14939
+ "reveal",
14940
+ "rotate-master-key",
14941
+ "purge-retired-keys",
14942
+ "download-recovery-key",
14943
+ "delete-orphans",
14944
+ "reset",
14945
+ "initialize"
14946
+ ]);
14947
+ var KeychainAuditEntrySchema = object({
14948
+ id: string(),
14949
+ at: number(),
14950
+ action: KeychainAuditActionSchema,
14951
+ /** `addon:<id>` | `user:<id>` | `system`. */
14952
+ actor: string(),
14953
+ ref: string().nullable(),
14954
+ detail: string().nullable()
14955
+ });
14956
+ 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({
14957
+ value: string(),
14958
+ version: number().int()
14959
+ }), {
14960
+ kind: "mutation",
14961
+ auth: "admin",
14962
+ caller: "required"
14963
+ }), method(object({ refs: array(string().min(1)).max(1e3) }), object({
14964
+ deleted: array(string()).readonly(),
14965
+ kept: array(object({
14966
+ ref: string(),
14967
+ usage: KeychainSecretUsageSchema
14968
+ })).readonly()
14969
+ }), {
14970
+ kind: "mutation",
14971
+ auth: "admin",
14972
+ caller: "required"
14973
+ }), method(object({}), object({
14974
+ fingerprint: string(),
14975
+ keySource: KeychainKeySourceSchema
14976
+ }), {
14977
+ kind: "mutation",
14978
+ auth: "admin",
14979
+ caller: "required"
14980
+ }), method(object({}), object({ purged: number().int() }), {
14981
+ kind: "mutation",
14982
+ auth: "admin",
14983
+ caller: "required"
14984
+ }), method(object({}), object({
14985
+ key: string(),
14986
+ fingerprint: string(),
14987
+ keySource: KeychainKeySourceSchema
14988
+ }), {
14989
+ kind: "mutation",
14990
+ auth: "admin",
14991
+ caller: "required"
14992
+ }), method(object({ confirm: literal("RESET KEYCHAIN") }), object({
14993
+ archivedCollection: string().nullable(),
14994
+ archived: number().int()
14995
+ }), {
14996
+ kind: "mutation",
14997
+ auth: "admin",
14998
+ caller: "required"
14999
+ });
14080
15000
  method(_void(), object({
14081
15001
  id: string(),
14082
15002
  name: string(),
@@ -15415,7 +16335,11 @@ var DeviceRegisterPayloadSchema = object({
15415
16335
  var DeviceRemovePayloadSchema = object({ deviceId: number() });
15416
16336
  var DevicePersistConfigPayloadSchema = object({
15417
16337
  deviceId: number(),
15418
- data: record(string(), unknown())
16338
+ data: record(string(), unknown()),
16339
+ /** The paths the device's schema declares secret (D783), when the caller
16340
+ * knows them — those values are kept in the keychain, not the blob (D787).
16341
+ * Absent: the paths the device last reported at `registerDevice` apply. */
16342
+ secretConfigPaths: array(string()).optional()
15419
16343
  });
15420
16344
  /** What a migration actually did, per switch. `unreachable` is a first-class
15421
16345
  * answer: a camera that could not be asked is not a camera that was silenced. */
@@ -22432,8 +23356,23 @@ var RetrainMacroClassSchema = _enum([
22432
23356
  ]);
22433
23357
  /** A subject to learn, or a phantom to unlearn (taught by OMISSION). */
22434
23358
  var RetrainAnnotationKindSchema = _enum(["subject", "model_error"]);
22435
- /** Did a human draw this box, or did the assist propose it? */
22436
- var RetrainAnnotationSourceSchema = _enum(["operator", "assist"]);
23359
+ /**
23360
+ * Where a box came from. A machine-sourced box is a DRAFT on the page until
23361
+ * the operator confirms it; once saved it keeps its source as provenance.
23362
+ *
23363
+ * - `operator` — drawn by hand.
23364
+ * - `assist` — proposed by a detector run on the copy (the camera's own
23365
+ * model, or a larger teacher model).
23366
+ * - `pipeline` — the box the live pipeline actually drew on that frame, read
23367
+ * back from the track store (never a re-run).
23368
+ * - `llm` — proposed by a vision-capable LLM profile.
23369
+ */
23370
+ var RetrainAnnotationSourceSchema = _enum([
23371
+ "operator",
23372
+ "assist",
23373
+ "pipeline",
23374
+ "llm"
23375
+ ]);
22437
23376
  /** Normalised `[0,1]` rectangle against the FULL frame — the canonical form. */
22438
23377
  var RetrainBboxSchema = object({
22439
23378
  x: number(),
@@ -22451,7 +23390,8 @@ var RetrainBboxSchema = object({
22451
23390
  */
22452
23391
  var RetrainAnnotationSchema = object({
22453
23392
  id: string(),
22454
- trackId: string(),
23393
+ /** The frame's track. Absent on a recording still, which has none. */
23394
+ trackId: string().optional(),
22455
23395
  deviceId: number(),
22456
23396
  /** The COPY in retrain storage — never the source track's media key. */
22457
23397
  mediaKey: string(),
@@ -22500,13 +23440,47 @@ var RetrainFrameCandidateSchema = object({
22500
23440
  * fail, whatever became of the original. */
22501
23441
  copied: boolean()
22502
23442
  });
23443
+ /**
23444
+ * One box the live pipeline drew on a copied frame — what a correction starts
23445
+ * from. Derived when the frame is listed, from the track store: the subject
23446
+ * box recorded on the source media row when there is one, else the track
23447
+ * position nearest the frame's capture time. Never stored as an annotation
23448
+ * until the operator confirms it.
23449
+ */
23450
+ var RetrainPipelineBoxSchema = object({
23451
+ /** Normalised `[0,1]` against the full frame. */
23452
+ bbox: RetrainBboxSchema,
23453
+ macroClass: RetrainMacroClassSchema,
23454
+ label: string().optional(),
23455
+ subLabel: string().optional(),
23456
+ /** The detection score of the position used, when it was recorded. */
23457
+ score: number().optional(),
23458
+ /** The root model that produced the track, when it was recorded. */
23459
+ modelId: string().optional(),
23460
+ trackId: string(),
23461
+ /** `subject-box`: recorded on this very frame. `position`: the track's
23462
+ * position nearest the capture time, `deltaMs` away. */
23463
+ basis: _enum(["subject-box", "position"]),
23464
+ deltaMs: number()
23465
+ });
23466
+ /**
23467
+ * Where a retrain frame came from: a TRACK's stored media (copy-on-select),
23468
+ * or the RECORDING at an instant — the frame a model saw nothing in has no
23469
+ * track at all.
23470
+ */
23471
+ var RetrainFrameOriginSchema = _enum(["track", "recording"]);
22503
23472
  /** A frame the dataset OWNS: bytes copied at selection time. */
22504
23473
  var RetrainFrameSchema = object({
22505
23474
  frameId: string(),
22506
23475
  deviceId: number(),
22507
- trackId: string(),
22508
- /** Provenance only. It may already point at nothing — that is expected. */
22509
- sourceMediaId: number().int(),
23476
+ origin: RetrainFrameOriginSchema,
23477
+ /** The track it was copied from. Absent on a recording still. */
23478
+ trackId: string().optional(),
23479
+ /** Provenance only. It may already point at nothing — that is expected.
23480
+ * Absent on a recording still. */
23481
+ sourceMediaId: number().int().optional(),
23482
+ /** A recording still: the playhead instant it was taken at. */
23483
+ epochMs: number().optional(),
22510
23484
  sourceKind: MediaFileKindEnum,
22511
23485
  sizeBytes: number().int(),
22512
23486
  width: number().int(),
@@ -22517,7 +23491,12 @@ var RetrainFrameSchema = object({
22517
23491
  /** The operator's "every subject in this frame is boxed". Detector
22518
23492
  * evaluation keeps only complete frames: an unboxed subject would count as
22519
23493
  * a false positive. */
22520
- complete: boolean()
23494
+ complete: boolean(),
23495
+ /** The boxes the pipeline drew on this frame. Present on list answers;
23496
+ * empty when nothing the track store holds can be placed on it. */
23497
+ pipelineBoxes: array(RetrainPipelineBoxSchema).readonly().optional(),
23498
+ /** The named collections this frame belongs to. Present on list answers. */
23499
+ collectionIds: array(string()).readonly().optional()
22521
23500
  });
22522
23501
  /** Why a copy-on-select could not be honoured — named, never a silent skip. */
22523
23502
  var RetrainCopyRefusalSchema = _enum([
@@ -22548,6 +23527,8 @@ var RetrainFrameListSchema = object({
22548
23527
  var RetrainExportFilterSchema = object({
22549
23528
  deviceIds: array(number()).optional(),
22550
23529
  frameIds: array(string()).max(2e4).optional(),
23530
+ /** Only frames in at least one of these named collections. */
23531
+ collectionIds: array(string()).max(200).optional(),
22551
23532
  batchId: string().optional(),
22552
23533
  /** Only frames the operator marked complete (all subjects boxed). */
22553
23534
  completeOnly: boolean().optional()
@@ -22612,6 +23593,109 @@ var RetrainAssistResultSchema = discriminatedUnion("kind", [object({
22612
23593
  reason: string(),
22613
23594
  detail: string().optional()
22614
23595
  })]);
23596
+ /** A named set over the retrain corpus — membership only, it owns no pixels. */
23597
+ var RetrainCollectionSchema = object({
23598
+ id: string(),
23599
+ name: string(),
23600
+ createdAt: number(),
23601
+ frameCount: number().int()
23602
+ });
23603
+ var RetrainCollectionCreateResultSchema = discriminatedUnion("kind", [object({
23604
+ kind: literal("created"),
23605
+ collection: RetrainCollectionSchema
23606
+ }), object({
23607
+ kind: literal("refused"),
23608
+ reason: _enum(["empty-name", "duplicate-name"])
23609
+ })]);
23610
+ var RetrainCollectionRenameResultSchema = discriminatedUnion("kind", [object({
23611
+ kind: literal("renamed"),
23612
+ collection: RetrainCollectionSchema
23613
+ }), object({
23614
+ kind: literal("refused"),
23615
+ reason: _enum([
23616
+ "empty-name",
23617
+ "duplicate-name",
23618
+ "unknown-collection"
23619
+ ])
23620
+ })]);
23621
+ /**
23622
+ * The outcome of adding the frame at a recording instant. Every refusal is
23623
+ * named: `still-unavailable` (not recording, a gap, or an undecodable frame —
23624
+ * `detail` says which), `still-busy` (the recorder is at its decode bound; try
23625
+ * again), `unreadable-image`, `write-failed`, `unknown-collection`.
23626
+ */
23627
+ var AddRetrainFrameFromRecordingResultSchema = discriminatedUnion("kind", [object({
23628
+ kind: literal("added"),
23629
+ collectionId: string(),
23630
+ frame: RetrainFrameSchema,
23631
+ /** The moment was already in the dataset; nothing was decoded. */
23632
+ reused: boolean()
23633
+ }), object({
23634
+ kind: literal("refused"),
23635
+ reason: _enum([
23636
+ "unknown-collection",
23637
+ "still-unavailable",
23638
+ "still-busy",
23639
+ "unreadable-image",
23640
+ "write-failed"
23641
+ ]),
23642
+ detail: string().optional()
23643
+ })]);
23644
+ /** A vision LLM profile the AI assist may use, and where it sends the frame. */
23645
+ var RetrainAssistProfileSchema = object({
23646
+ id: string(),
23647
+ name: string(),
23648
+ model: string(),
23649
+ kind: string(),
23650
+ /** `true` when the frame would leave the house (a cloud vendor, or an
23651
+ * endpoint that is not on the local network). The page confirms each such
23652
+ * run, and the provider refuses one without `allowCloud`. */
23653
+ leavesHouse: boolean()
23654
+ });
23655
+ /** A box the AI assist proposed: a draft, plus the model's own reason. */
23656
+ var RetrainLlmProposalSchema = RetrainAnnotationDraftSchema.extend({ reason: string() });
23657
+ /** What the AI assist said about a box that was already on the canvas. */
23658
+ var RetrainLlmReviewSchema = object({
23659
+ /** The `ref` the page sent the box under. */
23660
+ ref: string(),
23661
+ verdict: _enum([
23662
+ "confirmed",
23663
+ "wrong-class",
23664
+ "not-an-object",
23665
+ "uncertain"
23666
+ ]),
23667
+ suggestedClass: RetrainMacroClassSchema.optional(),
23668
+ reason: string()
23669
+ });
23670
+ /**
23671
+ * The AI assist's answer. `proposed` carries drafts (`source: 'llm'`, the
23672
+ * model and its confidence) and reviews; items the model got wrong (a box off
23673
+ * the frame, an unasked class, an unknown ref) are dropped and counted in
23674
+ * `rejected`. A whole answer that is not the schema is `malformed-answer`.
23675
+ */
23676
+ var RetrainLlmAssistResultSchema = discriminatedUnion("kind", [object({
23677
+ kind: literal("proposed"),
23678
+ profileId: string(),
23679
+ model: string(),
23680
+ /** The frame was sent outside the house for this answer. */
23681
+ leftHouse: boolean(),
23682
+ proposals: array(RetrainLlmProposalSchema).readonly(),
23683
+ reviews: array(RetrainLlmReviewSchema).readonly(),
23684
+ rejected: number().int()
23685
+ }), object({
23686
+ kind: literal("refused"),
23687
+ reason: _enum([
23688
+ "unknown-frame",
23689
+ "unreadable-frame",
23690
+ "unknown-profile",
23691
+ "profile-disabled",
23692
+ "no-vision",
23693
+ "cloud-not-confirmed",
23694
+ "llm-error",
23695
+ "malformed-answer"
23696
+ ]),
23697
+ detail: string().optional()
23698
+ })]);
22615
23699
  /** The outcome of a lifecycle move owned by the retrain page. */
22616
23700
  var RetrainTransitionResultSchema = object({
22617
23701
  trackId: string(),
@@ -23329,7 +24413,7 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
23329
24413
  auth: "admin"
23330
24414
  }), method(object({
23331
24415
  deviceId: number(),
23332
- trackId: string(),
24416
+ trackId: string().optional(),
23333
24417
  frameId: string()
23334
24418
  }), object({
23335
24419
  removed: boolean(),
@@ -23346,7 +24430,8 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
23346
24430
  auth: "admin"
23347
24431
  }), method(object({
23348
24432
  deviceId: number(),
23349
- trackId: string(),
24433
+ /** The frame's track, when it has one — checked against the frame. */
24434
+ trackId: string().optional(),
23350
24435
  frameId: string(),
23351
24436
  subject: RetrainAssistSubjectSchema,
23352
24437
  /** Which node runs it. Absent ⇒ wherever an unowned call lands. */
@@ -23354,12 +24439,16 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
23354
24439
  }), RetrainAssistResultSchema, {
23355
24440
  kind: "mutation",
23356
24441
  auth: "admin"
23357
- }), method(object({ trackId: string() }), array(RetrainAnnotationSchema).readonly(), {
24442
+ }), method(object({
24443
+ trackId: string().optional(),
24444
+ frameIds: array(string()).max(2e3).optional()
24445
+ }), array(RetrainAnnotationSchema).readonly(), {
23358
24446
  kind: "query",
23359
24447
  auth: "admin"
23360
24448
  }), method(object({
23361
24449
  deviceId: number(),
23362
- trackId: string(),
24450
+ /** The frame's track, when it has one — checked against the frame. */
24451
+ trackId: string().optional(),
23363
24452
  frameId: string(),
23364
24453
  annotations: array(RetrainAnnotationDraftSchema)
23365
24454
  }), array(RetrainAnnotationSchema).readonly(), {
@@ -23382,7 +24471,7 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
23382
24471
  auth: "admin"
23383
24472
  }), method(object({
23384
24473
  deviceId: number(),
23385
- trackId: string(),
24474
+ trackId: string().optional(),
23386
24475
  frameId: string(),
23387
24476
  complete: boolean()
23388
24477
  }), RetrainFrameSchema, {
@@ -23396,6 +24485,74 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
23396
24485
  kind: "mutation",
23397
24486
  auth: "admin",
23398
24487
  timeoutMs: 60 * 6e4
24488
+ }), method(object({}), array(RetrainAssistProfileSchema).readonly(), {
24489
+ kind: "query",
24490
+ auth: "admin"
24491
+ }), method(object({
24492
+ deviceId: number(),
24493
+ trackId: string().optional(),
24494
+ frameId: string(),
24495
+ profileId: string(),
24496
+ classes: array(RetrainMacroClassSchema).min(1),
24497
+ boxes: array(object({
24498
+ ref: string(),
24499
+ bbox: RetrainBboxSchema,
24500
+ macroClass: RetrainMacroClassSchema,
24501
+ label: string().optional()
24502
+ })).max(50),
24503
+ allowCloud: boolean()
24504
+ }), RetrainLlmAssistResultSchema, {
24505
+ kind: "mutation",
24506
+ auth: "admin",
24507
+ timeoutMs: 18e4
24508
+ }), method(object({ name: string().max(120) }), RetrainCollectionCreateResultSchema, {
24509
+ kind: "mutation",
24510
+ auth: "admin"
24511
+ }), method(object({}), array(RetrainCollectionSchema).readonly(), {
24512
+ kind: "query",
24513
+ auth: "admin"
24514
+ }), method(object({
24515
+ id: string(),
24516
+ name: string().max(120)
24517
+ }), RetrainCollectionRenameResultSchema, {
24518
+ kind: "mutation",
24519
+ auth: "admin"
24520
+ }), method(object({ id: string() }), object({
24521
+ deleted: boolean(),
24522
+ removedFrames: number().int()
24523
+ }), {
24524
+ kind: "mutation",
24525
+ auth: "admin"
24526
+ }), method(object({
24527
+ collectionId: string(),
24528
+ deviceId: number(),
24529
+ epochMs: number()
24530
+ }), AddRetrainFrameFromRecordingResultSchema, {
24531
+ kind: "mutation",
24532
+ auth: "admin",
24533
+ timeoutMs: 6e4
24534
+ }), method(object({
24535
+ collectionId: string(),
24536
+ frameIds: array(string()).min(1).max(500)
24537
+ }), object({
24538
+ added: number().int(),
24539
+ alreadyMember: number().int(),
24540
+ unknownFrameIds: array(string()).readonly()
24541
+ }), {
24542
+ kind: "mutation",
24543
+ auth: "admin"
24544
+ }), method(object({
24545
+ collectionId: string(),
24546
+ frameId: string()
24547
+ }), object({
24548
+ removed: boolean(),
24549
+ deletedFrame: boolean()
24550
+ }), {
24551
+ kind: "mutation",
24552
+ auth: "admin"
24553
+ }), method(object({ collectionId: string() }), array(RetrainFrameSchema).readonly(), {
24554
+ kind: "query",
24555
+ auth: "admin"
23399
24556
  }), method(object({
23400
24557
  /** Which of the three event tables owns the row. */
23401
24558
  ownerType: EventOwnerTypeSchema,
@@ -24019,13 +25176,31 @@ var RecommendationReasonSchema = discriminatedUnion("kind", [
24019
25176
  object({
24020
25177
  kind: literal("no-family-build"),
24021
25178
  format: ModelFormatSchema$1
25179
+ }),
25180
+ object({
25181
+ kind: literal("kept-custom-pin"),
25182
+ modelId: string(),
25183
+ deviceKey: string()
24022
25184
  })
24023
25185
  ]);
25186
+ /** Why a device is left exactly as it is, whatever the plan would pick (D786). */
25187
+ var KeptReasonSchema = _enum(["custom-pin"]);
25188
+ /**
25189
+ * Where a choice's latency came from (D791): this node's own benchmark
25190
+ * result, or the hardware-class table. Measured on the node beats the table.
25191
+ */
25192
+ var LatencySourceSchema = discriminatedUnion("kind", [object({ kind: literal("table") }), object({
25193
+ kind: literal("node-benchmark"),
25194
+ resultId: string(),
25195
+ measuredAtMs: number()
25196
+ })]);
24024
25197
  var DeviceModelChoiceSchema = object({
24025
25198
  modelId: string(),
24026
25199
  p50Ms: number(),
24027
25200
  fps: number(),
24028
25201
  measured: boolean(),
25202
+ /** Absent on a plan from before D791 — read as the table. */
25203
+ source: LatencySourceSchema.optional(),
24029
25204
  /** Parallel sessions at the camera rate with the headroom kept free: ⌊fps × (1 − headroom) / camera fps⌋. */
24030
25205
  capacitySessions: number(),
24031
25206
  personRecall: number()
@@ -24036,6 +25211,8 @@ var DeviceRecommendationSchema = object({
24036
25211
  enabled: boolean(),
24037
25212
  available: boolean(),
24038
25213
  chosen: DeviceModelChoiceSchema.nullable(),
25214
+ /** Present when the device is kept as is: Apply writes nothing on it. */
25215
+ kept: KeptReasonSchema.optional(),
24039
25216
  reasons: array(RecommendationReasonSchema).readonly()
24040
25217
  });
24041
25218
  var NodeRecommendationSchema = object({
@@ -24089,6 +25266,17 @@ var AutoTuneWarningSchema = discriminatedUnion("kind", [
24089
25266
  kind: literal("coral-enabled"),
24090
25267
  nodeId: string(),
24091
25268
  deviceKey: string()
25269
+ }),
25270
+ object({
25271
+ kind: literal("custom-pin-kept"),
25272
+ nodeId: string(),
25273
+ deviceKey: string().nullable(),
25274
+ deviceId: number().nullable(),
25275
+ modelId: string()
25276
+ }),
25277
+ object({
25278
+ kind: literal("custom-registry-unreadable"),
25279
+ error: string()
24092
25280
  })
24093
25281
  ]);
24094
25282
  var AutoTuneOptionsSchema = object({
@@ -24267,13 +25455,14 @@ var SuggestSharesResultSchema = object({
24267
25455
  nodes: array(SuggestedNodeShareSchema).readonly()
24268
25456
  });
24269
25457
  /**
24270
- * Where the node and device shares come from (D750, D755).
24271
- * - `hardware` (default) — computed by the system from each node's static
24272
- * capacity (its accelerators at their Auto tune models, from the measured
24273
- * latency table), recomputed whenever a node or device joins, leaves, is
24274
- * switched on or off, or changes model. No load input.
24275
- * - `benchmark` — the same, from each node's measured capacity (node
24276
- * benchmark results); a node without results falls back to `hardware`.
25458
+ * Where the node and device shares come from (D750, D755, D791).
25459
+ * - `benchmark` (default since D791) — each node's capacity as its own node
25460
+ * benchmark measured it; a node without fresh results is sized from
25461
+ * `hardware` and says so. Measured on the node beats the table.
25462
+ * - `hardware` — computed from each node's static capacity only (its
25463
+ * accelerators at their Auto tune models, from the latency table).
25464
+ * Both are recomputed whenever a node or device joins, leaves, is switched
25465
+ * on or off, changes model, or a benchmark result is written. No load input.
24277
25466
  * - `manual` — the operator's stored sliders.
24278
25467
  * Either way a node or device that cannot take sessions gives its share to
24279
25468
  * the others in proportion; the stored values are never rewritten for that.
@@ -24322,6 +25511,362 @@ var EffectiveSharesSchema = object({
24322
25511
  nodeWeights: record(string(), number()),
24323
25512
  deviceWeights: record(string(), record(string(), number()))
24324
25513
  });
25514
+ /**
25515
+ * Wire shapes of the node benchmark (D791): the operator's plan, the
25516
+ * preflight the confirmation shows, the run the orchestrator owns, what the
25517
+ * measuring runner reports, and the result rows Auto tune and the automatic
25518
+ * shares read.
25519
+ *
25520
+ * ONE node at a time, owned by the pipeline orchestrator. While a run is
25521
+ * active the cluster is in BENCHMARK MODE for that node: it is not a
25522
+ * detection candidate, camera pins naming it are ignored so its sessions move
25523
+ * elsewhere, and both come back when the mode ends — after a crash or a hub
25524
+ * restart too (a persisted manifest, reconciled against the registry).
25525
+ *
25526
+ * Two measurements, both on the node, driven by its own runner (frames never
25527
+ * cross a process at frame rate, D9):
25528
+ * - `device` — one accelerator × one candidate detector, root only, open
25529
+ * loop: how many streams at the camera rate it carries inside the frame
25530
+ * interval;
25531
+ * - `pipeline` — the chosen detector plus the operator's detail steps
25532
+ * (faces, plates, classifiers, CLIP…), on varied frames from the bench
25533
+ * clip: how many parallel sessions the node carries before latency, drops,
25534
+ * CPU, RAM or the event loop give out.
25535
+ */
25536
+ /** Defaults and bounds, one place. */
25537
+ var NODE_BENCHMARK_DEFAULTS = {
25538
+ fpsPerStream: 10,
25539
+ budgetMinutes: 45,
25540
+ minBudgetMinutes: 10,
25541
+ maxBudgetMinutes: 120,
25542
+ /** A result older than this no longer beats the table. */
25543
+ staleAfterDays: 30,
25544
+ /** Warm-in per ramp step (not accounted). */
25545
+ settleSec: 5,
25546
+ /** Accounted window per ramp step. */
25547
+ measureSec: 20,
25548
+ /** Longest the drain may take before the run is refused. */
25549
+ drainTimeoutSec: 120,
25550
+ /** Candidate models per device in one run. */
25551
+ maxModelsPerDevice: 6
25552
+ };
25553
+ /** The two measurements a run can make. */
25554
+ var NodeBenchmarkPhaseSchema = _enum(["device", "pipeline"]);
25555
+ var NodeBenchmarkDevicePlanSchema = object({
25556
+ /** `<backend>:<device>` — `openvino:npu`, `coreml:all`, `cpu`. */
25557
+ deviceKey: string().min(1),
25558
+ /**
25559
+ * Root detector candidates for the `device` measurement, in the order
25560
+ * measured. The FIRST is the one the `pipeline` measurement runs.
25561
+ */
25562
+ modelIds: array(string().min(1)).min(1).max(NODE_BENCHMARK_DEFAULTS.maxModelsPerDevice)
25563
+ });
25564
+ /** What the operator confirmed. */
25565
+ var NodeBenchmarkPlanSchema = object({
25566
+ nodeId: string().min(1),
25567
+ devices: array(NodeBenchmarkDevicePlanSchema).min(1),
25568
+ /** Which measurements run. At least one. */
25569
+ phases: array(NodeBenchmarkPhaseSchema).min(1).default(["device", "pipeline"]),
25570
+ /**
25571
+ * Detail steps (catalog step ids under the root: faces, plates,
25572
+ * classifiers, CLIP…) the `pipeline` measurement enables. The root
25573
+ * detector always runs.
25574
+ */
25575
+ steps: array(string().min(1)).default([]),
25576
+ /** Offered rate of one stream / session. */
25577
+ fpsPerStream: number().int().min(1).max(30).default(NODE_BENCHMARK_DEFAULTS.fpsPerStream),
25578
+ /** Hard deadline: the mode ends and the cluster is restored when it passes. */
25579
+ budgetMinutes: number().int().min(NODE_BENCHMARK_DEFAULTS.minBudgetMinutes).max(NODE_BENCHMARK_DEFAULTS.maxBudgetMinutes).default(NODE_BENCHMARK_DEFAULTS.budgetMinutes),
25580
+ /** Keep the models the run downloaded (default: delete what was not installed before). */
25581
+ keepDownloadedModels: boolean().default(false),
25582
+ /** Start although the other nodes' capacity does not cover the sessions running now. */
25583
+ acceptInsufficientHeadroom: boolean().default(false)
25584
+ });
25585
+ var NodeBenchmarkRefusalSchema = object({
25586
+ kind: _enum([
25587
+ "benchmark-active",
25588
+ "node-offline",
25589
+ "unknown-device",
25590
+ "no-phase",
25591
+ "insufficient-headroom"
25592
+ ]),
25593
+ detail: string(),
25594
+ overridable: boolean()
25595
+ });
25596
+ /** A camera whose detection leaves the node for the run. */
25597
+ var NodeBenchmarkMovingCameraSchema = object({
25598
+ deviceId: number(),
25599
+ /** Placed on the node now (a standing attach or a running session). */
25600
+ placedOnNode: boolean(),
25601
+ /** A node pin naming this node, ignored for the run. */
25602
+ pinnedToNode: boolean()
25603
+ });
25604
+ /** A camera that cannot leave: no other node can obtain its frames. */
25605
+ var NodeBenchmarkStayingCameraSchema = object({
25606
+ deviceId: number(),
25607
+ reason: literal("only-frame-source")
25608
+ });
25609
+ var NodeBenchmarkPreflightSchema = object({
25610
+ nodeId: string(),
25611
+ online: boolean(),
25612
+ moving: array(NodeBenchmarkMovingCameraSchema).readonly(),
25613
+ /** Keep running on the node during the run; the result is flagged contaminated. */
25614
+ staying: array(NodeBenchmarkStayingCameraSchema).readonly(),
25615
+ estimatedDurationMs: number(),
25616
+ /** The run ends and the cluster is restored at the latest after this long. */
25617
+ budgetMs: number(),
25618
+ phases: array(NodeBenchmarkPhaseSchema).readonly(),
25619
+ steps: array(string()).readonly(),
25620
+ devices: array(NodeBenchmarkDevicePlanSchema).readonly(),
25621
+ /** Parallel sessions the cluster runs now, and what the other nodes can carry. */
25622
+ headroom: object({
25623
+ sessionsNow: number(),
25624
+ otherNodesCapacitySessions: number().nullable()
25625
+ }),
25626
+ refusals: array(NodeBenchmarkRefusalSchema).readonly(),
25627
+ canStart: boolean()
25628
+ });
25629
+ /** Where the measuring runner is. */
25630
+ var NodeBenchProgressSchema = object({
25631
+ phase: _enum([
25632
+ "preparing",
25633
+ "device",
25634
+ "pipeline",
25635
+ "cleanup"
25636
+ ]),
25637
+ deviceKey: string().nullable(),
25638
+ modelId: string().nullable(),
25639
+ /** Streams (device) or sessions (pipeline) of the step running now. */
25640
+ load: number().nullable(),
25641
+ cellsDone: number(),
25642
+ cellsTotal: number(),
25643
+ message: string()
25644
+ });
25645
+ /** What limited a ramp. `none` = the ramp ran out of steps still passing. */
25646
+ var NodeBenchLimitSchema = _enum([
25647
+ "p95",
25648
+ "drops",
25649
+ "errors",
25650
+ "stall",
25651
+ "cpu",
25652
+ "ram",
25653
+ "none"
25654
+ ]);
25655
+ var NodeBenchRampStepSchema = object({
25656
+ load: number(),
25657
+ pass: boolean(),
25658
+ p95Ms: number(),
25659
+ dropRatio: number(),
25660
+ /** Completed frames per second over the accounted window. */
25661
+ fps: number(),
25662
+ cpuPct: number().nullable(),
25663
+ ramFreePct: number().nullable(),
25664
+ failReasons: array(string()).readonly()
25665
+ });
25666
+ var NodeBenchCellSchema = discriminatedUnion("phase", [object({
25667
+ phase: literal("device"),
25668
+ deviceKey: string(),
25669
+ modelId: string(),
25670
+ /** Single-stream latency (the K = 1 step). */
25671
+ p50Ms: number(),
25672
+ p95Ms: number(),
25673
+ p99Ms: number(),
25674
+ /** Frames per second sustained at the last passing step. */
25675
+ fps: number(),
25676
+ /** Streams at the camera rate the device carried inside the frame interval; 0 = not even one. */
25677
+ kMax: number(),
25678
+ limitedBy: NodeBenchLimitSchema,
25679
+ /** First call (model load + warm-up). */
25680
+ warmupMs: number(),
25681
+ ramp: array(NodeBenchRampStepSchema).readonly()
25682
+ }), object({
25683
+ phase: literal("pipeline"),
25684
+ deviceKey: string(),
25685
+ modelId: string(),
25686
+ steps: array(string()).readonly(),
25687
+ /** Parallel sessions at the camera rate the node carried; 0 = not even one. */
25688
+ maxSessions: number(),
25689
+ limitedBy: NodeBenchLimitSchema,
25690
+ /** Detail steps that produced at least one result on the clip — a step that never fired measured nothing. */
25691
+ stepsFired: array(string()).readonly(),
25692
+ warmupMs: number(),
25693
+ ramp: array(NodeBenchRampStepSchema).readonly()
25694
+ })]);
25695
+ /**
25696
+ * What a result was measured ON. A result whose fingerprint no longer matches
25697
+ * the node no longer beats the table.
25698
+ */
25699
+ var NodeBenchFingerprintSchema = object({
25700
+ pipelineVersion: string().nullable(),
25701
+ cpuModel: string().nullable(),
25702
+ ramGb: number().nullable(),
25703
+ os: string().nullable(),
25704
+ /** Per device: the pool the cells ran on (runtime + tuning). */
25705
+ pools: record(string(), object({
25706
+ runtime: string(),
25707
+ numWorkers: number(),
25708
+ concurrency: number(),
25709
+ batchMode: string()
25710
+ })).default({})
25711
+ });
25712
+ /** The frames the run used. */
25713
+ var NodeBenchClipSchema = object({
25714
+ /** `camstack-bench-v1` or `reference-images` (the fallback when the clip is not reachable). */
25715
+ id: string(),
25716
+ revision: string().nullable(),
25717
+ frames: number(),
25718
+ width: number(),
25719
+ height: number()
25720
+ });
25721
+ var NodeBenchRunnerInputSchema = object({
25722
+ runId: string().min(1),
25723
+ devices: array(NodeBenchmarkDevicePlanSchema).min(1),
25724
+ phases: array(NodeBenchmarkPhaseSchema).min(1),
25725
+ /** The full detail step tree root for the `pipeline` measurement is built on the node from these ids. */
25726
+ steps: array(string()).default([]),
25727
+ fpsPerStream: number().int().min(1).max(30),
25728
+ /** The runner stops on its own past this instant, whatever the hub does. */
25729
+ deadlineAtMs: number(),
25730
+ settleSec: number().min(0).max(60).default(NODE_BENCHMARK_DEFAULTS.settleSec),
25731
+ measureSec: number().min(2).max(300).default(NODE_BENCHMARK_DEFAULTS.measureSec),
25732
+ keepDownloadedModels: boolean().default(false)
25733
+ });
25734
+ var NodeBenchRunnerStateSchema = _enum([
25735
+ "running",
25736
+ "done",
25737
+ "failed",
25738
+ "aborted"
25739
+ ]);
25740
+ var NodeBenchRunnerStatusSchema = object({
25741
+ runId: string(),
25742
+ nodeId: string(),
25743
+ state: NodeBenchRunnerStateSchema,
25744
+ progress: NodeBenchProgressSchema.nullable(),
25745
+ /** Every finished cell so far — a run stopped half way keeps what it measured. */
25746
+ cells: array(NodeBenchCellSchema).readonly(),
25747
+ fingerprint: NodeBenchFingerprintSchema.nullable(),
25748
+ clip: NodeBenchClipSchema.nullable(),
25749
+ /** Cameras seen running on the node during the run (they share its pools). */
25750
+ activeCameraIds: array(number()).readonly(),
25751
+ /** Models the run downloaded and then deleted (not installed before). */
25752
+ deletedModels: array(string()).readonly(),
25753
+ error: string().nullable(),
25754
+ startedAtMs: number(),
25755
+ finishedAtMs: number().nullable()
25756
+ });
25757
+ var NodeBenchmarkStateSchema = _enum([
25758
+ "draining",
25759
+ "measuring",
25760
+ "restoring",
25761
+ "done",
25762
+ "failed",
25763
+ "aborted"
25764
+ ]);
25765
+ /** Why a run ended. */
25766
+ var NodeBenchmarkEndReasonSchema = _enum([
25767
+ "completed",
25768
+ "operator-abort",
25769
+ "deadline",
25770
+ "node-lost",
25771
+ "runner-lost",
25772
+ "hub-restart",
25773
+ "drain-timeout",
25774
+ "failed"
25775
+ ]);
25776
+ var NodeBenchmarkRunSchema = object({
25777
+ runId: string(),
25778
+ nodeId: string(),
25779
+ state: NodeBenchmarkStateSchema,
25780
+ plan: NodeBenchmarkPlanSchema,
25781
+ startedAtMs: number(),
25782
+ deadlineAtMs: number(),
25783
+ finishedAtMs: number().nullable(),
25784
+ endReason: NodeBenchmarkEndReasonSchema.nullable(),
25785
+ error: string().nullable(),
25786
+ /** Cameras moved off the node for the run. */
25787
+ moved: array(number()).readonly(),
25788
+ /** Cameras that stayed (their only frame source is the node). */
25789
+ staying: array(number()).readonly(),
25790
+ /** Something else ran on the node's pools during the run. */
25791
+ contaminated: boolean(),
25792
+ progress: NodeBenchProgressSchema.nullable(),
25793
+ resultIds: array(string()).readonly()
25794
+ });
25795
+ /** `getNodeBenchmarkStatus`: the active run (or the last one), and whether benchmark mode is on. */
25796
+ var NodeBenchmarkStatusSchema = object({
25797
+ /** The node the cluster is in benchmark mode for; null = none. */
25798
+ modeNodeId: string().nullable(),
25799
+ run: NodeBenchmarkRunSchema.nullable()
25800
+ });
25801
+ /**
25802
+ * One stored measurement — the only authority Auto tune and the automatic
25803
+ * shares read measured capacity from. Written by the orchestrator when a run
25804
+ * ends, never by anyone else.
25805
+ */
25806
+ var NodeBenchmarkResultSchema = object({
25807
+ id: string(),
25808
+ runId: string(),
25809
+ nodeId: string(),
25810
+ cell: NodeBenchCellSchema,
25811
+ fpsPerStream: number(),
25812
+ fingerprint: NodeBenchFingerprintSchema.nullable(),
25813
+ clip: NodeBenchClipSchema.nullable(),
25814
+ /** Other work shared the node's pools (a camera that could not move, or the hub's own duties). */
25815
+ contaminated: boolean(),
25816
+ stayingCameras: array(number()).readonly(),
25817
+ /** The run ended early; the cell itself completed. */
25818
+ partialRun: boolean(),
25819
+ measuredAtMs: number()
25820
+ });
25821
+ var ListNodeBenchmarkResultsInputSchema = object({
25822
+ nodeId: string().optional(),
25823
+ deviceKey: string().optional()
25824
+ });
25825
+ /** A result with its standing today: does it still beat the table? */
25826
+ var NodeBenchmarkResultViewSchema = NodeBenchmarkResultSchema.extend({
25827
+ /** `fresh` beats the table; `stale` falls back to it; `superseded` = a newer row covers the same cell. */
25828
+ standing: _enum([
25829
+ "fresh",
25830
+ "stale",
25831
+ "superseded"
25832
+ ]),
25833
+ staleWhy: _enum([
25834
+ "age",
25835
+ "runtime",
25836
+ "pool-tuning"
25837
+ ]).nullable()
25838
+ });
25839
+ object({
25840
+ runId: string(),
25841
+ nodeId: string(),
25842
+ startedAtMs: number(),
25843
+ deadlineAtMs: number(),
25844
+ plan: NodeBenchmarkPlanSchema,
25845
+ moved: array(number()).readonly(),
25846
+ staying: array(number()).readonly()
25847
+ });
25848
+ /** Candidate detectors per device, for the plan editor. */
25849
+ var NodeBenchmarkCandidatesSchema = object({
25850
+ nodeId: string(),
25851
+ reachable: boolean(),
25852
+ devices: array(object({
25853
+ deviceKey: string(),
25854
+ enabled: boolean(),
25855
+ available: boolean(),
25856
+ /** Ordered: what Auto tune would pick first, then the rest of the family by accuracy. */
25857
+ suggested: array(string()).readonly(),
25858
+ /** Every root detector the device has a build for. */
25859
+ all: array(string()).readonly(),
25860
+ /** The model the device runs now, when pinned. */
25861
+ currentModelId: string().nullable()
25862
+ })).readonly(),
25863
+ /** Detail steps the node's catalog offers under the root (for the `pipeline` measurement). */
25864
+ steps: array(object({
25865
+ id: string(),
25866
+ name: string(),
25867
+ slot: string()
25868
+ })).readonly()
25869
+ });
24325
25870
  object({
24326
25871
  activeCameras: number(),
24327
25872
  throttledCameras: number(),
@@ -25450,7 +26995,16 @@ method(RunnerCameraConfigSchema, object({ success: literal(true) }), { kind: "mu
25450
26995
  }), ParkedTrackFrameSchema.nullable()), method(object({
25451
26996
  deviceId: number(),
25452
26997
  trackId: string()
25453
- }), object({ released: number().int().nonnegative() }), { kind: "mutation" });
26998
+ }), object({ released: number().int().nonnegative() }), { kind: "mutation" }), method(NodeBenchRunnerInputSchema, object({
26999
+ accepted: literal(true),
27000
+ runId: string()
27001
+ }), {
27002
+ kind: "mutation",
27003
+ auth: "admin"
27004
+ }), method(object({ runId: string() }), NodeBenchRunnerStatusSchema.nullable(), { auth: "admin" }), method(object({ runId: string() }), object({ aborted: boolean() }), {
27005
+ kind: "mutation",
27006
+ auth: "admin"
27007
+ });
25454
27008
  var CameraPipelineConfigSchema = object({
25455
27009
  engine: PipelineEngineChoiceSchema.optional(),
25456
27010
  steps: array(PipelineStepInputSchema).readonly(),
@@ -26089,6 +27643,21 @@ method(object({
26089
27643
  }), method(PlacementStatsInputSchema, PlacementStatsSchema, { auth: "admin" }), method(SuggestSharesInputSchema, SuggestSharesResultSchema, { auth: "admin" }), method(_void(), EffectiveSharesSchema, { auth: "admin" }), method(SetShareSourceInputSchema, object({ success: literal(true) }), {
26090
27644
  kind: "mutation",
26091
27645
  auth: "admin"
27646
+ }), method(NodeBenchmarkPlanSchema, NodeBenchmarkPreflightSchema, { auth: "admin" }), method(NodeBenchmarkPlanSchema, discriminatedUnion("kind", [object({
27647
+ kind: literal("started"),
27648
+ runId: string()
27649
+ }), object({
27650
+ kind: literal("refused"),
27651
+ preflight: NodeBenchmarkPreflightSchema
27652
+ })]), {
27653
+ kind: "mutation",
27654
+ auth: "admin"
27655
+ }), method(_void(), NodeBenchmarkStatusSchema, { auth: "admin" }), method(object({ runId: string() }), object({ aborted: boolean() }), {
27656
+ kind: "mutation",
27657
+ auth: "admin"
27658
+ }), method(object({ nodeId: string() }), NodeBenchmarkCandidatesSchema, { auth: "admin" }), method(ListNodeBenchmarkResultsInputSchema, array(NodeBenchmarkResultViewSchema).readonly(), { auth: "admin" }), method(object({ id: string() }), object({ deleted: boolean() }), {
27659
+ kind: "mutation",
27660
+ auth: "admin"
26092
27661
  }), method(object({ deviceId: number() }), CameraPipelineSettingsSchema.nullable()), method(object({
26093
27662
  deviceId: number(),
26094
27663
  addonId: string(),
@@ -32196,6 +33765,9 @@ var CreateIntegrationInputSchema = object({
32196
33765
  enabled: boolean().optional(),
32197
33766
  info: record(string(), unknown()).optional(),
32198
33767
  settings: record(string(), unknown()).optional(),
33768
+ /** Keys of `settings` the form's schema declares secret (by type) — kept in
33769
+ * the keychain, not the table (D787). */
33770
+ secretKeys: array(string()).optional(),
32199
33771
  skipRestart: boolean().optional()
32200
33772
  });
32201
33773
  var UpdateIntegrationInputSchema = object({
@@ -32219,7 +33791,9 @@ method(_void(), array(IntegrationWithStateSchema)), method(object({ id: string()
32219
33791
  auth: "admin"
32220
33792
  }), method(object({ id: string() }), record(string(), unknown()), { auth: "admin" }), method(object({
32221
33793
  id: string(),
32222
- settings: record(string(), unknown())
33794
+ settings: record(string(), unknown()),
33795
+ /** Keys the form's schema declares secret (by type) — keychain-stored (D787). */
33796
+ secretKeys: array(string()).optional()
32223
33797
  }), object({ success: boolean() }), {
32224
33798
  kind: "mutation",
32225
33799
  auth: "admin"
@@ -40382,7 +41956,8 @@ var BaseDevice = class {
40382
41956
  this.role = options.role;
40383
41957
  this.parentDeviceId = ctx.parentDeviceId;
40384
41958
  const seedData = ctx.persistedConfig ?? {};
40385
- this.config = DeviceConfig.fromSchema(schema, (data) => ctx.persistConfig(data), seedData, ({ droppedKeys, issues }) => {
41959
+ const declaredSecretPaths = collectZodSecretPaths(schema);
41960
+ this.config = DeviceConfig.fromSchema(schema, (data) => ctx.persistConfig(data, { secretConfigPaths: declaredSecretPaths }), seedData, ({ droppedKeys, issues }) => {
40386
41961
  ctx.logger.warn("Device config recovery: dropping invalid persisted fields", {
40387
41962
  tags: {
40388
41963
  deviceId: ctx.id,
@@ -44071,6 +45646,90 @@ Object.freeze({
44071
45646
  addonId: null,
44072
45647
  access: "create"
44073
45648
  },
45649
+ "keychain.delete": {
45650
+ capName: "keychain",
45651
+ capScope: "system",
45652
+ addonId: null,
45653
+ access: "delete"
45654
+ },
45655
+ "keychain.getState": {
45656
+ capName: "keychain",
45657
+ capScope: "system",
45658
+ addonId: null,
45659
+ access: "view"
45660
+ },
45661
+ "keychain.listMeta": {
45662
+ capName: "keychain",
45663
+ capScope: "system",
45664
+ addonId: null,
45665
+ access: "view"
45666
+ },
45667
+ "keychain.put": {
45668
+ capName: "keychain",
45669
+ capScope: "system",
45670
+ addonId: null,
45671
+ access: "create"
45672
+ },
45673
+ "keychain.resolve": {
45674
+ capName: "keychain",
45675
+ capScope: "system",
45676
+ addonId: null,
45677
+ access: "view"
45678
+ },
45679
+ "keychainAdmin.deleteOrphans": {
45680
+ capName: "keychain-admin",
45681
+ capScope: "system",
45682
+ addonId: null,
45683
+ access: "delete"
45684
+ },
45685
+ "keychainAdmin.downloadRecoveryKey": {
45686
+ capName: "keychain-admin",
45687
+ capScope: "system",
45688
+ addonId: null,
45689
+ access: "create"
45690
+ },
45691
+ "keychainAdmin.listAudit": {
45692
+ capName: "keychain-admin",
45693
+ capScope: "system",
45694
+ addonId: null,
45695
+ access: "view"
45696
+ },
45697
+ "keychainAdmin.listSecrets": {
45698
+ capName: "keychain-admin",
45699
+ capScope: "system",
45700
+ addonId: null,
45701
+ access: "view"
45702
+ },
45703
+ "keychainAdmin.purgeRetiredKeys": {
45704
+ capName: "keychain-admin",
45705
+ capScope: "system",
45706
+ addonId: null,
45707
+ access: "delete"
45708
+ },
45709
+ "keychainAdmin.resetKeychain": {
45710
+ capName: "keychain-admin",
45711
+ capScope: "system",
45712
+ addonId: null,
45713
+ access: "delete"
45714
+ },
45715
+ "keychainAdmin.reveal": {
45716
+ capName: "keychain-admin",
45717
+ capScope: "system",
45718
+ addonId: null,
45719
+ access: "create"
45720
+ },
45721
+ "keychainAdmin.rotateMasterKey": {
45722
+ capName: "keychain-admin",
45723
+ capScope: "system",
45724
+ addonId: null,
45725
+ access: "create"
45726
+ },
45727
+ "keychainAdmin.status": {
45728
+ capName: "keychain-admin",
45729
+ capScope: "system",
45730
+ addonId: null,
45731
+ access: "view"
45732
+ },
44074
45733
  "lawnMowerControl.dock": {
44075
45734
  capName: "lawn-mower-control",
44076
45735
  capScope: "device",
@@ -45445,6 +47104,18 @@ Object.freeze({
45445
47104
  addonId: null,
45446
47105
  access: "create"
45447
47106
  },
47107
+ "pipelineAnalytics.addRetrainFrameFromRecording": {
47108
+ capName: "pipeline-analytics",
47109
+ capScope: "device",
47110
+ addonId: null,
47111
+ access: "create"
47112
+ },
47113
+ "pipelineAnalytics.addRetrainFramesToCollection": {
47114
+ capName: "pipeline-analytics",
47115
+ capScope: "device",
47116
+ addonId: null,
47117
+ access: "create"
47118
+ },
45448
47119
  "pipelineAnalytics.applyDeviceSettingsPatch": {
45449
47120
  capName: "pipeline-analytics",
45450
47121
  capScope: "device",
@@ -45493,12 +47164,24 @@ Object.freeze({
45493
47164
  addonId: null,
45494
47165
  access: "view"
45495
47166
  },
47167
+ "pipelineAnalytics.createRetrainCollection": {
47168
+ capName: "pipeline-analytics",
47169
+ capScope: "device",
47170
+ addonId: null,
47171
+ access: "create"
47172
+ },
45496
47173
  "pipelineAnalytics.deleteDeviceEvents": {
45497
47174
  capName: "pipeline-analytics",
45498
47175
  capScope: "device",
45499
47176
  addonId: null,
45500
47177
  access: "delete"
45501
47178
  },
47179
+ "pipelineAnalytics.deleteRetrainCollection": {
47180
+ capName: "pipeline-analytics",
47181
+ capScope: "device",
47182
+ addonId: null,
47183
+ access: "delete"
47184
+ },
45502
47185
  "pipelineAnalytics.deleteTracks": {
45503
47186
  capName: "pipeline-analytics",
45504
47187
  capScope: "device",
@@ -45703,6 +47386,24 @@ Object.freeze({
45703
47386
  addonId: null,
45704
47387
  access: "view"
45705
47388
  },
47389
+ "pipelineAnalytics.listRetrainAssistProfiles": {
47390
+ capName: "pipeline-analytics",
47391
+ capScope: "device",
47392
+ addonId: null,
47393
+ access: "view"
47394
+ },
47395
+ "pipelineAnalytics.listRetrainCollectionFrames": {
47396
+ capName: "pipeline-analytics",
47397
+ capScope: "device",
47398
+ addonId: null,
47399
+ access: "view"
47400
+ },
47401
+ "pipelineAnalytics.listRetrainCollections": {
47402
+ capName: "pipeline-analytics",
47403
+ capScope: "device",
47404
+ addonId: null,
47405
+ access: "view"
47406
+ },
45706
47407
  "pipelineAnalytics.listRetrainFrames": {
45707
47408
  capName: "pipeline-analytics",
45708
47409
  capScope: "device",
@@ -45751,6 +47452,12 @@ Object.freeze({
45751
47452
  addonId: null,
45752
47453
  access: "create"
45753
47454
  },
47455
+ "pipelineAnalytics.proposeRetrainAnnotationsWithLlm": {
47456
+ capName: "pipeline-analytics",
47457
+ capScope: "device",
47458
+ addonId: null,
47459
+ access: "create"
47460
+ },
45754
47461
  "pipelineAnalytics.pruneEvents": {
45755
47462
  capName: "pipeline-analytics",
45756
47463
  capScope: "device",
@@ -45805,6 +47512,18 @@ Object.freeze({
45805
47512
  addonId: null,
45806
47513
  access: "create"
45807
47514
  },
47515
+ "pipelineAnalytics.removeRetrainFrameFromCollection": {
47516
+ capName: "pipeline-analytics",
47517
+ capScope: "device",
47518
+ addonId: null,
47519
+ access: "delete"
47520
+ },
47521
+ "pipelineAnalytics.renameRetrainCollection": {
47522
+ capName: "pipeline-analytics",
47523
+ capScope: "device",
47524
+ addonId: null,
47525
+ access: "create"
47526
+ },
45808
47527
  "pipelineAnalytics.restageRetrainTrack": {
45809
47528
  capName: "pipeline-analytics",
45810
47529
  capScope: "device",
@@ -46093,6 +47812,12 @@ Object.freeze({
46093
47812
  addonId: null,
46094
47813
  access: "view"
46095
47814
  },
47815
+ "pipelineOrchestrator.abortNodeBenchmark": {
47816
+ capName: "pipeline-orchestrator",
47817
+ capScope: "system",
47818
+ addonId: null,
47819
+ access: "create"
47820
+ },
46096
47821
  "pipelineOrchestrator.applyAutoTune": {
46097
47822
  capName: "pipeline-orchestrator",
46098
47823
  capScope: "system",
@@ -46117,6 +47842,12 @@ Object.freeze({
46117
47842
  addonId: null,
46118
47843
  access: "create"
46119
47844
  },
47845
+ "pipelineOrchestrator.deleteNodeBenchmarkResult": {
47846
+ capName: "pipeline-orchestrator",
47847
+ capScope: "system",
47848
+ addonId: null,
47849
+ access: "delete"
47850
+ },
46120
47851
  "pipelineOrchestrator.getAgentLoad": {
46121
47852
  capName: "pipeline-orchestrator",
46122
47853
  capScope: "system",
@@ -46225,6 +47956,24 @@ Object.freeze({
46225
47956
  addonId: null,
46226
47957
  access: "view"
46227
47958
  },
47959
+ "pipelineOrchestrator.getNodeBenchmarkCandidates": {
47960
+ capName: "pipeline-orchestrator",
47961
+ capScope: "system",
47962
+ addonId: null,
47963
+ access: "view"
47964
+ },
47965
+ "pipelineOrchestrator.getNodeBenchmarkPreflight": {
47966
+ capName: "pipeline-orchestrator",
47967
+ capScope: "system",
47968
+ addonId: null,
47969
+ access: "view"
47970
+ },
47971
+ "pipelineOrchestrator.getNodeBenchmarkStatus": {
47972
+ capName: "pipeline-orchestrator",
47973
+ capScope: "system",
47974
+ addonId: null,
47975
+ access: "view"
47976
+ },
46228
47977
  "pipelineOrchestrator.getNodeInferenceDevices": {
46229
47978
  capName: "pipeline-orchestrator",
46230
47979
  capScope: "system",
@@ -46267,6 +48016,12 @@ Object.freeze({
46267
48016
  addonId: null,
46268
48017
  access: "view"
46269
48018
  },
48019
+ "pipelineOrchestrator.listNodeBenchmarkResults": {
48020
+ capName: "pipeline-orchestrator",
48021
+ capScope: "system",
48022
+ addonId: null,
48023
+ access: "view"
48024
+ },
46270
48025
  "pipelineOrchestrator.pauseForStorageMigration": {
46271
48026
  capName: "pipeline-orchestrator",
46272
48027
  capScope: "system",
@@ -46411,6 +48166,12 @@ Object.freeze({
46411
48166
  addonId: null,
46412
48167
  access: "create"
46413
48168
  },
48169
+ "pipelineOrchestrator.startNodeBenchmark": {
48170
+ capName: "pipeline-orchestrator",
48171
+ capScope: "system",
48172
+ addonId: null,
48173
+ access: "create"
48174
+ },
46414
48175
  "pipelineOrchestrator.suggestShares": {
46415
48176
  capName: "pipeline-orchestrator",
46416
48177
  capScope: "system",
@@ -46429,6 +48190,12 @@ Object.freeze({
46429
48190
  addonId: null,
46430
48191
  access: "create"
46431
48192
  },
48193
+ "pipelineRunner.abortNodeBench": {
48194
+ capName: "pipeline-runner",
48195
+ capScope: "system",
48196
+ addonId: null,
48197
+ access: "create"
48198
+ },
46432
48199
  "pipelineRunner.attachCamera": {
46433
48200
  capName: "pipeline-runner",
46434
48201
  capScope: "system",
@@ -46477,6 +48244,12 @@ Object.freeze({
46477
48244
  addonId: null,
46478
48245
  access: "view"
46479
48246
  },
48247
+ "pipelineRunner.getNodeBenchStatus": {
48248
+ capName: "pipeline-runner",
48249
+ capScope: "system",
48250
+ addonId: null,
48251
+ access: "view"
48252
+ },
46480
48253
  "pipelineRunner.getParkedTrackFrame": {
46481
48254
  capName: "pipeline-runner",
46482
48255
  capScope: "system",
@@ -46519,6 +48292,12 @@ Object.freeze({
46519
48292
  addonId: null,
46520
48293
  access: "create"
46521
48294
  },
48295
+ "pipelineRunner.startNodeBench": {
48296
+ capName: "pipeline-runner",
48297
+ capScope: "system",
48298
+ addonId: null,
48299
+ access: "create"
48300
+ },
46522
48301
  "plateGallery.assignPlate": {
46523
48302
  capName: "plate-gallery",
46524
48303
  capScope: "system",
@@ -51448,6 +53227,11 @@ Object.freeze({
51448
53227
  form: "single",
51449
53228
  optional: false
51450
53229
  }],
53230
+ "pipelineAnalytics.addRetrainFrameFromRecording": [{
53231
+ name: "deviceId",
53232
+ form: "single",
53233
+ optional: false
53234
+ }],
51451
53235
  "pipelineAnalytics.applyDeviceSettingsPatch": [{
51452
53236
  name: "deviceId",
51453
53237
  form: "single",
@@ -51638,6 +53422,11 @@ Object.freeze({
51638
53422
  form: "single",
51639
53423
  optional: false
51640
53424
  }],
53425
+ "pipelineAnalytics.proposeRetrainAnnotationsWithLlm": [{
53426
+ name: "deviceId",
53427
+ form: "single",
53428
+ optional: false
53429
+ }],
51641
53430
  "pipelineAnalytics.pruneEventsBefore": [{
51642
53431
  name: "deviceId",
51643
53432
  form: "single",