@camstack/addon-provider-wyze 0.2.131 → 0.2.132

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
@@ -31,7 +31,7 @@ let net = require("net");
31
31
  net = __toESM(net, 1);
32
32
  let node_child_process = require("node:child_process");
33
33
  let node_tls = require("node:tls");
34
- //#region ../types/dist/event-category-B_0XEcLF.mjs
34
+ //#region ../types/dist/event-category-DaIZi00R.mjs
35
35
  var EventCategory = /* @__PURE__ */ function(EventCategory) {
36
36
  EventCategory["SystemBoot"] = "system.boot";
37
37
  EventCategory["SystemAddonsReady"] = "system.addons-ready";
@@ -110,6 +110,13 @@ var EventCategory = /* @__PURE__ */ function(EventCategory) {
110
110
  */
111
111
  EventCategory["AddonLoadFailed"] = "addon.load-failed";
112
112
  /**
113
+ * A keychain value was stored or removed (D787). Carries the ref, its
114
+ * owner and the new version — NEVER the value. A process holding the ref
115
+ * drops its cached copy and the owning `BaseAddon` re-resolves its config.
116
+ * Telemetry (D8): a process that misses it still revalidates by version.
117
+ */
118
+ EventCategory["KeychainChanged"] = "keychain.changed";
119
+ /**
113
120
  * Addon recovered from a previous failure. Emitted when an addon
114
121
  * transitions from `failed` back to `healthy` (typically via the
115
122
  * monitor's auto-retry loop, or after manual `addons.retryLoad`).
@@ -5402,7 +5409,7 @@ var ZodIssueCode = {
5402
5409
  var ZodFirstPartyTypeKind;
5403
5410
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
5404
5411
  //#endregion
5405
- //#region ../types/dist/sleep-B0JG7-_F.mjs
5412
+ //#region ../types/dist/sleep-Cr5YOk3m.mjs
5406
5413
  /**
5407
5414
  * The audio chunk plane's byte format, and the ONE expansion from a coded
5408
5415
  * window to float samples (D455).
@@ -5481,6 +5488,97 @@ function buildAlawTable() {
5481
5488
  }
5482
5489
  buildUlawTable();
5483
5490
  buildAlawTable();
5491
+ /** Is this field's stored value a credential? */
5492
+ function isSecretConfigField(field) {
5493
+ if (field.type === "password") return true;
5494
+ return "secret" in field && field.secret === true;
5495
+ }
5496
+ /**
5497
+ * Is this field's value stored in the KEYCHAIN (D787)? Every secret field is,
5498
+ * by its TYPE, unless it opts out with `storage: 'inline'` — never by its name.
5499
+ */
5500
+ function isKeychainStoredField(field) {
5501
+ if (!isSecretConfigField(field)) return false;
5502
+ if (field.type === "textarea" && field.isJson === true) return false;
5503
+ return !("storage" in field && field.storage === "inline");
5504
+ }
5505
+ /**
5506
+ * What a settings blob holds where a secret used to be.
5507
+ *
5508
+ * A keychain-stored field never holds its value. It holds a self-describing
5509
+ * MARKER, `{"$secret":"secret://…","v":1}` — an object, never a string, so no
5510
+ * code can mistake it for a credential and no form can send it to a camera as
5511
+ * a password. The empty state is `null` / absent, never `''`.
5512
+ *
5513
+ * The same shapes travel to and from the admin UI:
5514
+ *
5515
+ * - read: `hydrateSchema` hands a secret field a {@link SecretFieldView}
5516
+ * (`{ $secret, v, set: true }`) or `null` — the browser learns whether a
5517
+ * value is set, never the value.
5518
+ * - write: an untouched field submits the view back unchanged (KEEP); a typed
5519
+ * value is a plain non-empty string (CHANGE); the Clear button submits
5520
+ * {@link SECRET_CLEAR} (CLEAR). `''`, `null` and the legacy redaction tokens
5521
+ * are KEEP — an empty string is what a defaults-fallback pushes back, and
5522
+ * treating it as "clear" is how a save destroyed a stored credential before.
5523
+ *
5524
+ * Pure and browser-safe.
5525
+ */
5526
+ var SECRET_CLEAR = { $secretClear: true };
5527
+ /** The `'***'` token D634 redaction writes for non-admins. */
5528
+ var LEGACY_DEVICE_REDACTION = "***";
5529
+ function isRecord$1(value) {
5530
+ return typeof value === "object" && value !== null && !Array.isArray(value);
5531
+ }
5532
+ function makeSecretMarker(ref) {
5533
+ return {
5534
+ $secret: ref,
5535
+ v: 1
5536
+ };
5537
+ }
5538
+ /** A stored marker: an object whose `$secret` is a non-empty string. */
5539
+ function isSecretMarker(value) {
5540
+ if (!isRecord$1(value)) return false;
5541
+ const ref = value["$secret"];
5542
+ return typeof ref === "string" && ref.length > 0;
5543
+ }
5544
+ function isSecretClear(value) {
5545
+ return isRecord$1(value) && value["$secretClear"] === true;
5546
+ }
5547
+ /**
5548
+ * The UI view of a stored secret field value: a marker becomes "set", inline
5549
+ * plaintext becomes "set (inline)", nothing becomes `null`. A value never
5550
+ * survives this function.
5551
+ */
5552
+ function toSecretFieldView(stored) {
5553
+ if (isSecretMarker(stored)) return {
5554
+ $secret: stored.$secret,
5555
+ v: 1,
5556
+ set: true
5557
+ };
5558
+ if (typeof stored === "string" && stored.length > 0) return {
5559
+ $secret: null,
5560
+ v: 1,
5561
+ set: true,
5562
+ inline: true
5563
+ };
5564
+ return null;
5565
+ }
5566
+ /**
5567
+ * Classify an incoming value for a secret path. Only a non-empty string that is
5568
+ * not a redaction token sets a value; only {@link SECRET_CLEAR} clears.
5569
+ * Everything else — a marker (ours or anyone's), a UI view, `''`, `null`,
5570
+ * `undefined`, a redaction token, a non-string — keeps what is stored.
5571
+ */
5572
+ function classifySecretWrite(incoming) {
5573
+ if (isSecretClear(incoming)) return { kind: "clear" };
5574
+ if (typeof incoming !== "string") return { kind: "keep" };
5575
+ if (incoming.length === 0) return { kind: "keep" };
5576
+ if (incoming === "__camstack_redacted__" || incoming === LEGACY_DEVICE_REDACTION) return { kind: "keep" };
5577
+ return {
5578
+ kind: "set",
5579
+ value: incoming
5580
+ };
5581
+ }
5484
5582
  Object.fromEntries([
5485
5583
  {
5486
5584
  id: "overview",
@@ -5652,33 +5750,19 @@ Object.fromEntries([
5652
5750
  function isValuelessField(field) {
5653
5751
  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";
5654
5752
  }
5655
- /**
5656
- * Merge a `ConfigUISchema` with a raw `values` record into a
5657
- * `ConfigUISchemaWithValues`. Used by every `get*Settings` backend endpoint
5658
- * before returning to the admin UI. Groups are walked recursively.
5659
- *
5660
- * For each leaf field:
5661
- * - structural fields (`separator`, `info`, `button`) pass through unchanged
5662
- * - other fields get `value = values[key] ?? field.default ?? null`
5663
- *
5664
- * Unknown keys in `values` (keys not declared in the schema) are silently
5665
- * ignored — they don't contribute to the output. Missing keys fall back to
5666
- * the schema default or `null`. This mirrors the old backend behaviour where
5667
- * `FormBuilder` rendered `values[key] ?? field.default`.
5668
- */
5669
- function hydrateSchema(schema, values) {
5753
+ function hydrateSchema(schema, values, options = {}) {
5670
5754
  return {
5671
5755
  ...schema.tabs ? { tabs: [...schema.tabs] } : {},
5672
5756
  sections: schema.sections.map((section) => ({
5673
5757
  ...section,
5674
- fields: section.fields.map((field) => hydrateField(field, values))
5758
+ fields: section.fields.map((field) => hydrateField(field, values, options))
5675
5759
  }))
5676
5760
  };
5677
5761
  }
5678
- function hydrateField(field, values) {
5762
+ function hydrateField(field, values, options) {
5679
5763
  if (isValuelessField(field)) return field;
5680
5764
  if (field.type === "group") {
5681
- const hydratedChildren = field.fields.map((child) => hydrateField(child, values));
5765
+ const hydratedChildren = field.fields.map((child) => hydrateField(child, values, options));
5682
5766
  return {
5683
5767
  ...field,
5684
5768
  fields: hydratedChildren
@@ -5687,7 +5771,7 @@ function hydrateField(field, values) {
5687
5771
  if (field.type === "sub-tabs") {
5688
5772
  const hydratedTabs = field.tabs.map((tab) => ({
5689
5773
  ...tab,
5690
- fields: tab.fields.map((child) => hydrateField(child, values))
5774
+ fields: tab.fields.map((child) => hydrateField(child, values, options))
5691
5775
  }));
5692
5776
  return {
5693
5777
  ...field,
@@ -5697,6 +5781,33 @@ function hydrateField(field, values) {
5697
5781
  const key = field.key;
5698
5782
  const storedValue = Object.prototype.hasOwnProperty.call(values, key) ? values[key] : void 0;
5699
5783
  const defaultValue = field.default;
5784
+ const asView = (v) => isSecretMarker(v) || options.inlineSecretsAsViews === true && v !== void 0;
5785
+ if (isKeychainStoredField(field) && asView(storedValue)) return {
5786
+ ...field,
5787
+ value: toSecretFieldView(storedValue)
5788
+ };
5789
+ if (isKeychainStoredField(field) && options.inlineSecretsAsViews === true) return {
5790
+ ...field,
5791
+ value: null
5792
+ };
5793
+ if (field.type === "editable-array" && Array.isArray(storedValue)) {
5794
+ const secretItemKeys = field.itemFields.filter((item) => "key" in item && isKeychainStoredField(item)).map((item) => "key" in item ? item.key : "");
5795
+ if (secretItemKeys.length > 0) {
5796
+ const rows = storedValue.map((row) => {
5797
+ if (row === null || typeof row !== "object" || Array.isArray(row)) return row;
5798
+ const out = { ...row };
5799
+ for (const k of secretItemKeys) {
5800
+ const v = Reflect.get(row, k);
5801
+ if (asView(v)) out[k] = toSecretFieldView(v);
5802
+ }
5803
+ return out;
5804
+ });
5805
+ return {
5806
+ ...field,
5807
+ value: rows
5808
+ };
5809
+ }
5810
+ }
5700
5811
  if (field.multiple) {
5701
5812
  const stored = Array.isArray(storedValue) ? storedValue : storedValue !== void 0 && storedValue !== null ? [storedValue] : [];
5702
5813
  const itemFallback = field.multiple.itemDefault !== void 0 ? field.multiple.itemDefault : defaultValue !== void 0 ? defaultValue : typeOf(field) === "string" ? "" : null;
@@ -5939,6 +6050,431 @@ function projectStore(store, perNodeKeys, nodeId) {
5939
6050
  }
5940
6051
  return out;
5941
6052
  }
6053
+ var GLOBAL_SCOPE = { kind: "global" };
6054
+ /** The scope every addon-wide (not per-node, not per-device) setting lives in. */
6055
+ function globalSecretScope() {
6056
+ return GLOBAL_SCOPE;
6057
+ }
6058
+ function encodeSegment(value) {
6059
+ return encodeURIComponent(value);
6060
+ }
6061
+ /**
6062
+ * The field path of a value inside an array item, addressed by the item's id:
6063
+ * `arrayItemFieldPath('providers', 'authentik', 'clientSecret')` →
6064
+ * `providers[authentik].clientSecret`.
6065
+ */
6066
+ function arrayItemFieldPath(arrayKey, itemId, fieldKey) {
6067
+ return `${arrayKey}[${encodeSegment(itemId)}].${fieldKey}`;
6068
+ }
6069
+ /** A write to a secret path could not be stored in the keychain, so it was refused. */
6070
+ var KeychainWriteRefusedError = class extends Error {
6071
+ fieldPath;
6072
+ constructor(fieldPath, cause) {
6073
+ super(`secret "${fieldPath}" was not saved: the keychain could not store it (${cause instanceof Error ? cause.message : String(cause)}). Nothing was written.`);
6074
+ this.fieldPath = fieldPath;
6075
+ this.name = "KeychainWriteRefusedError";
6076
+ }
6077
+ };
6078
+ var KEEP = { kind: "keep" };
6079
+ function isRecord(value) {
6080
+ return typeof value === "object" && value !== null && !Array.isArray(value);
6081
+ }
6082
+ function defaultMintId() {
6083
+ return globalThis.crypto.randomUUID();
6084
+ }
6085
+ /** Every marker ref anywhere under `value`. */
6086
+ function collectSecretMarkerRefs(value, out = []) {
6087
+ if (isSecretMarker(value)) {
6088
+ out.push(value.$secret);
6089
+ return out;
6090
+ }
6091
+ if (Array.isArray(value)) for (const item of value) collectSecretMarkerRefs(item, out);
6092
+ else if (isRecord(value)) for (const child of Object.values(value)) collectSecretMarkerRefs(child, out);
6093
+ return out;
6094
+ }
6095
+ async function storedValueEquals(secrets, marker, candidate) {
6096
+ const resolved = (await secrets.resolve([marker.$secret]))[marker.$secret];
6097
+ return resolved?.kind === "value" && resolved.value === candidate;
6098
+ }
6099
+ async function writeLeaf(ctx, incoming, stored, fieldPath) {
6100
+ const intent = classifySecretWrite(incoming);
6101
+ const ref = ctx.secrets.ref(ctx.scope, fieldPath);
6102
+ const storedIsOurs = isSecretMarker(stored) && stored.$secret === ref;
6103
+ if (intent.kind === "keep") return KEEP;
6104
+ if (intent.kind === "set" && !ctx.operatorWrite && typeof stored === "string" && stored === intent.value) return KEEP;
6105
+ if (intent.kind === "clear") {
6106
+ if (storedIsOurs) ctx.deletes.push(ref);
6107
+ return {
6108
+ kind: "value",
6109
+ value: null
6110
+ };
6111
+ }
6112
+ if (storedIsOurs && await storedValueEquals(ctx.secrets, stored, intent.value)) return {
6113
+ kind: "value",
6114
+ value: stored
6115
+ };
6116
+ try {
6117
+ await ctx.secrets.put(ref, intent.value);
6118
+ } catch (err) {
6119
+ throw new KeychainWriteRefusedError(fieldPath, err);
6120
+ }
6121
+ return {
6122
+ kind: "value",
6123
+ value: makeSecretMarker(ref)
6124
+ };
6125
+ }
6126
+ /** Apply a member result onto `out`: KEEP restores the stored member, or removes it. */
6127
+ function applyMember(out, key, result, storedParent) {
6128
+ if (result.kind === "value") {
6129
+ out[key] = result.value;
6130
+ return;
6131
+ }
6132
+ if (Object.prototype.hasOwnProperty.call(storedParent, key)) out[key] = storedParent[key];
6133
+ else delete out[key];
6134
+ }
6135
+ async function writeMembers(ctx, children, incoming, stored, pathOf) {
6136
+ const out = { ...incoming };
6137
+ for (const [member, node] of children) applyMember(out, member, await writeNode(ctx, node, incoming[member], stored[member], pathOf(member)), stored);
6138
+ return out;
6139
+ }
6140
+ function rowId(row, idKey) {
6141
+ const raw = row[idKey];
6142
+ if (typeof raw === "string" && raw.length > 0) return raw;
6143
+ if (typeof raw === "number" && Number.isFinite(raw)) return String(raw);
6144
+ return null;
6145
+ }
6146
+ async function writeArray(ctx, node, incoming, stored, fieldPath) {
6147
+ const storedRows = Array.isArray(stored) ? stored.filter(isRecord) : [];
6148
+ if (!Array.isArray(incoming)) {
6149
+ ctx.deletes.push(...collectSecretMarkerRefs(storedRows));
6150
+ return {
6151
+ kind: "value",
6152
+ value: incoming
6153
+ };
6154
+ }
6155
+ const storedById = /* @__PURE__ */ new Map();
6156
+ for (const row of storedRows) {
6157
+ const id = rowId(row, node.idKey);
6158
+ if (id !== null) storedById.set(id, row);
6159
+ }
6160
+ const kept = /* @__PURE__ */ new Set();
6161
+ const rows = [];
6162
+ for (const row of incoming) {
6163
+ if (!isRecord(row)) {
6164
+ rows.push(row);
6165
+ continue;
6166
+ }
6167
+ const id = rowId(row, node.idKey) ?? ctx.mintId();
6168
+ kept.add(id);
6169
+ const withId = {
6170
+ ...row,
6171
+ [node.idKey]: row[node.idKey] ?? id
6172
+ };
6173
+ if (rowId(withId, node.idKey) === null) withId[node.idKey] = id;
6174
+ const storedRow = storedById.get(id) ?? {};
6175
+ rows.push(await writeMembers(ctx, node.item, withId, storedRow, (member) => arrayItemFieldPath(fieldPath, id, member)));
6176
+ }
6177
+ for (const [id, row] of storedById) if (!kept.has(id)) ctx.deletes.push(...collectSecretMarkerRefs(row));
6178
+ return {
6179
+ kind: "value",
6180
+ value: rows
6181
+ };
6182
+ }
6183
+ async function writeNode(ctx, node, incoming, stored, fieldPath) {
6184
+ switch (node.kind) {
6185
+ case "leaf": return writeLeaf(ctx, incoming, stored, fieldPath);
6186
+ case "array": return writeArray(ctx, node, incoming, stored, fieldPath);
6187
+ case "object": {
6188
+ if (!isRecord(incoming)) {
6189
+ if (incoming === void 0) return KEEP;
6190
+ ctx.deletes.push(...collectSecretMarkerRefs(stored));
6191
+ return {
6192
+ kind: "value",
6193
+ value: incoming
6194
+ };
6195
+ }
6196
+ const storedObj = isRecord(stored) ? stored : {};
6197
+ return {
6198
+ kind: "value",
6199
+ value: await writeMembers(ctx, node.children, incoming, storedObj, (m) => `${fieldPath}.${m}`)
6200
+ };
6201
+ }
6202
+ }
6203
+ }
6204
+ /** Split a perNode-scoped key (`key@nodeId`). */
6205
+ function splitNodeKey(key) {
6206
+ const at = key.indexOf("@");
6207
+ return at <= 0 ? {
6208
+ base: key,
6209
+ nodeId: null
6210
+ } : {
6211
+ base: key.slice(0, at),
6212
+ nodeId: key.slice(at + 1)
6213
+ };
6214
+ }
6215
+ /** Rewrite a settings patch so no secret value reaches the blob. See the file doc. */
6216
+ async function transformSecretWrite(input) {
6217
+ const deletes = [];
6218
+ const base = {
6219
+ secrets: input.secrets,
6220
+ mintId: input.mintId ?? defaultMintId,
6221
+ deletes,
6222
+ operatorWrite: input.operatorWrite === true
6223
+ };
6224
+ const out = {};
6225
+ for (const [key, incoming] of Object.entries(input.patch)) {
6226
+ const { base: baseKey, nodeId } = splitNodeKey(key);
6227
+ const node = input.tree.get(baseKey);
6228
+ if (node === void 0) {
6229
+ out[key] = incoming;
6230
+ continue;
6231
+ }
6232
+ const scope = nodeId !== null && nodeId.length > 0 ? {
6233
+ kind: "node",
6234
+ nodeId
6235
+ } : input.scope ?? globalSecretScope();
6236
+ const result = await writeNode({
6237
+ ...base,
6238
+ scope
6239
+ }, node, incoming, input.stored[key], baseKey);
6240
+ if (result.kind === "value") out[key] = result.value;
6241
+ }
6242
+ return {
6243
+ patch: out,
6244
+ afterWrite: async () => {
6245
+ if (deletes.length === 0) return { orphaned: [] };
6246
+ try {
6247
+ await input.secrets.delete([...new Set(deletes)]);
6248
+ return { orphaned: [] };
6249
+ } catch {
6250
+ return { orphaned: [...new Set(deletes)] };
6251
+ }
6252
+ }
6253
+ };
6254
+ }
6255
+ /**
6256
+ * Replace every marker in `value` with its keychain value. Returns the SAME
6257
+ * reference when there is no marker (no allocation, no keychain call).
6258
+ */
6259
+ async function resolveSecretMarkers(value, secrets) {
6260
+ const refs = collectSecretMarkerRefs(value);
6261
+ if (refs.length === 0) return {
6262
+ value,
6263
+ unresolved: []
6264
+ };
6265
+ const answers = await secrets.resolve(refs);
6266
+ const unresolved = [];
6267
+ for (const ref of new Set(refs)) {
6268
+ const answer = answers[ref];
6269
+ if (answer === void 0) unresolved.push({
6270
+ ref,
6271
+ reason: "not-initialized"
6272
+ });
6273
+ else if (answer.kind === "unavailable") unresolved.push({
6274
+ ref,
6275
+ reason: answer.reason
6276
+ });
6277
+ else if (answer.kind === "missing" || answer.kind === "forbidden") unresolved.push({
6278
+ ref,
6279
+ reason: answer.kind
6280
+ });
6281
+ }
6282
+ const substitute = (v) => {
6283
+ if (isSecretMarker(v)) {
6284
+ const answer = answers[v.$secret];
6285
+ return answer?.kind === "value" ? {
6286
+ keep: true,
6287
+ value: answer.value
6288
+ } : {
6289
+ keep: false,
6290
+ value: void 0
6291
+ };
6292
+ }
6293
+ if (Array.isArray(v)) {
6294
+ const items = [];
6295
+ for (const item of v) {
6296
+ const s = substitute(item);
6297
+ if (s.keep) items.push(s.value);
6298
+ }
6299
+ return {
6300
+ keep: true,
6301
+ value: items
6302
+ };
6303
+ }
6304
+ if (isRecord(v)) {
6305
+ const out = {};
6306
+ for (const [k, child] of Object.entries(v)) {
6307
+ const s = substitute(child);
6308
+ if (s.keep) out[k] = s.value;
6309
+ }
6310
+ return {
6311
+ keep: true,
6312
+ value: out
6313
+ };
6314
+ }
6315
+ return {
6316
+ keep: true,
6317
+ value: v
6318
+ };
6319
+ };
6320
+ return {
6321
+ value: substitute(value).value,
6322
+ unresolved
6323
+ };
6324
+ }
6325
+ function touchesTree(tree, patch) {
6326
+ if (tree.size === 0) return false;
6327
+ for (const key of Object.keys(patch)) {
6328
+ const at = key.indexOf("@");
6329
+ if (tree.has(at > 0 ? key.slice(0, at) : key)) return true;
6330
+ }
6331
+ return false;
6332
+ }
6333
+ /** The blob as stored now; a failed read REFUSES the write instead of guessing. */
6334
+ async function readStoredAddonBlob(raw) {
6335
+ const threeWay = raw.readAddonStoreResult;
6336
+ if (threeWay === void 0) return raw.readAddonStore();
6337
+ const result = await threeWay.call(raw);
6338
+ if (result.kind === "failed") throw new Error(`settings write refused: the stored blob could not be read (${result.error})`);
6339
+ return result.kind === "missing" ? {} : result.value;
6340
+ }
6341
+ function createSecretAwareSettings(raw, opts) {
6342
+ const chains = /* @__PURE__ */ new Map();
6343
+ const serialize = (key, fn) => {
6344
+ const next = (chains.get(key) ?? Promise.resolve()).then(fn, fn);
6345
+ const tail = next.catch(() => void 0);
6346
+ chains.set(key, tail);
6347
+ tail.then(() => {
6348
+ if (chains.get(key) === tail) chains.delete(key);
6349
+ });
6350
+ return next;
6351
+ };
6352
+ const write = async (chainKey, tree, scope, patch, readStored, rawWrite) => {
6353
+ if (!touchesTree(tree, patch)) return rawWrite(patch);
6354
+ return serialize(chainKey, async () => {
6355
+ const stored = await readStored();
6356
+ const result = await transformSecretWrite({
6357
+ tree,
6358
+ secrets: opts.secrets,
6359
+ patch,
6360
+ stored,
6361
+ ...scope !== void 0 ? { scope } : {},
6362
+ operatorWrite: opts.isOperatorWrite?.() === true
6363
+ });
6364
+ if (Object.keys(result.patch).length > 0) await rawWrite(result.patch);
6365
+ const { orphaned } = await result.afterWrite();
6366
+ if (orphaned.length > 0) opts.onOrphaned(orphaned);
6367
+ });
6368
+ };
6369
+ const wrapped = {
6370
+ writeAddonStore: (patch) => write("addon", opts.addonTree(), void 0, patch, () => readStoredAddonBlob(raw), (p) => raw.writeAddonStore(p)),
6371
+ writeDeviceStore: (deviceId, patch) => write(`device:${deviceId}`, opts.deviceTree(), {
6372
+ kind: "device",
6373
+ deviceId
6374
+ }, patch, () => raw.readDeviceStore(deviceId), (p) => raw.writeDeviceStore(deviceId, p))
6375
+ };
6376
+ return new Proxy(raw, { get(target, prop, receiver) {
6377
+ if (prop === "writeAddonStore") return wrapped.writeAddonStore;
6378
+ if (prop === "writeDeviceStore") return wrapped.writeDeviceStore;
6379
+ const value = Reflect.get(target, prop, receiver);
6380
+ return typeof value === "function" ? value.bind(target) : value;
6381
+ } });
6382
+ }
6383
+ /** The context the addon sees: identical, except that its settings writes are secret-aware. */
6384
+ function withSecretAwareSettings(context, opts) {
6385
+ const raw = context.settings;
6386
+ if (raw === void 0) return context;
6387
+ const settings = createSecretAwareSettings(raw, opts);
6388
+ return new Proxy(context, { get(target, prop, receiver) {
6389
+ if (prop === "settings") return settings;
6390
+ return Reflect.get(target, prop, receiver);
6391
+ } });
6392
+ }
6393
+ var LEAF = { kind: "leaf" };
6394
+ var DEFAULT_ITEM_ID_KEY = "id";
6395
+ function collectFields(fields, out) {
6396
+ for (const field of fields) {
6397
+ if (field.type === "group") {
6398
+ collectFields(field.fields, out);
6399
+ continue;
6400
+ }
6401
+ if (field.type === "sub-tabs") {
6402
+ for (const tab of field.tabs) collectFields(tab.fields, out);
6403
+ continue;
6404
+ }
6405
+ if (field.type === "editable-array") {
6406
+ const item = /* @__PURE__ */ new Map();
6407
+ for (const itemField of field.itemFields) if ("key" in itemField && isKeychainStoredField(itemField)) item.set(itemField.key, LEAF);
6408
+ if (item.size > 0) out.set(field.key, {
6409
+ kind: "array",
6410
+ idKey: field.itemIdKey ?? DEFAULT_ITEM_ID_KEY,
6411
+ item
6412
+ });
6413
+ continue;
6414
+ }
6415
+ if (!("key" in field) || typeof field.key !== "string") continue;
6416
+ if (isKeychainStoredField(field)) out.set(field.key, LEAF);
6417
+ }
6418
+ }
6419
+ /** The secret tree a settings schema declares. */
6420
+ function secretTreeFromSchema(schema) {
6421
+ const out = /* @__PURE__ */ new Map();
6422
+ if (schema === null) return out;
6423
+ for (const section of schema.sections) collectFields(section.fields, out);
6424
+ return out;
6425
+ }
6426
+ /** Parse `a.b[id].c` into segments; throws on a malformed path (a declaration bug). */
6427
+ function parseSecretStatePath(path) {
6428
+ const segments = [];
6429
+ for (const raw of path.split(".")) {
6430
+ const m = /^([^[\]]+)(?:\[([^[\]]+)\])?$/.exec(raw);
6431
+ if (m === null || m[1] === void 0) throw new Error(`secretStatePaths: malformed path "${path}"`);
6432
+ segments.push(m[2] !== void 0 ? {
6433
+ key: m[1],
6434
+ idKey: m[2]
6435
+ } : { key: m[1] });
6436
+ }
6437
+ if (segments.length === 0) throw new Error(`secretStatePaths: empty path`);
6438
+ if (segments[segments.length - 1]?.idKey !== void 0) throw new Error(`secretStatePaths: "${path}" ends on an array — name the member that is secret`);
6439
+ return segments;
6440
+ }
6441
+ function insert(into, segments) {
6442
+ const [head, ...rest] = segments;
6443
+ if (head === void 0) return;
6444
+ if (rest.length === 0) {
6445
+ into.set(head.key, LEAF);
6446
+ return;
6447
+ }
6448
+ const existing = into.get(head.key);
6449
+ if (head.idKey !== void 0) {
6450
+ const item = new Map(existing?.kind === "array" ? existing.item : []);
6451
+ insert(item, rest);
6452
+ into.set(head.key, {
6453
+ kind: "array",
6454
+ idKey: head.idKey,
6455
+ item
6456
+ });
6457
+ return;
6458
+ }
6459
+ const children = new Map(existing?.kind === "object" ? existing.children : []);
6460
+ insert(children, rest);
6461
+ into.set(head.key, {
6462
+ kind: "object",
6463
+ children
6464
+ });
6465
+ }
6466
+ /** Add hidden-state paths (`secretStatePaths`) to a schema-derived tree. */
6467
+ function mergeSecretStatePaths(tree, paths) {
6468
+ if (paths.length === 0) return tree;
6469
+ const out = new Map(tree);
6470
+ for (const path of paths) insert(out, parseSecretStatePath(path));
6471
+ return out;
6472
+ }
6473
+ /** First retry of a secret the keychain could not serve; doubles to {@link SECRET_RETRY_MAX_MS}. */
6474
+ var SECRET_RETRY_FIRST_MS = 5e3;
6475
+ var SECRET_RETRY_MAX_MS = 5 * 6e4;
6476
+ /** Coalesces a burst of `keychain.changed` events into one re-resolve. */
6477
+ var SECRET_CHANGE_DEBOUNCE_MS = 250;
5942
6478
  /**
5943
6479
  * Base class for CamStack addons. Eliminates settings boilerplate:
5944
6480
  *
@@ -6008,6 +6544,25 @@ var BaseAddon = class {
6008
6544
  settingsStoreReady = false;
6009
6545
  /** Default config values. Provided via constructor. */
6010
6546
  defaults;
6547
+ /**
6548
+ * Hidden-state paths that hold secrets (D787) — values the addon writes
6549
+ * itself (`updateGlobalSettings`, `state()`) that no form field declares.
6550
+ * Stored in the keychain exactly like a `password` field. Syntax:
6551
+ * `'snapshotSigningKey'`, `'identity.pincode'`, `'tokens[userId].accessToken'`
6552
+ * (`key[<id field>]` addresses array items by id, never by index).
6553
+ */
6554
+ secretStatePaths = [];
6555
+ _addonSecretTree = null;
6556
+ _deviceSecretTree = null;
6557
+ /** Refs the last resolved config pointed at — a change to one re-resolves. */
6558
+ _configSecretRefs = /* @__PURE__ */ new Set();
6559
+ _unresolvedSecrets = [];
6560
+ _secretRetryTimer = null;
6561
+ _secretRetryDelayMs = SECRET_RETRY_FIRST_MS;
6562
+ _secretChangeTimer = null;
6563
+ _secretChangeUnsub = null;
6564
+ /** >0 while an OPERATOR's settings write is being applied. */
6565
+ _operatorWriteDepth = 0;
6011
6566
  constructor(defaults) {
6012
6567
  this.defaults = defaults;
6013
6568
  this._config = { ...defaults };
@@ -6043,8 +6598,18 @@ var BaseAddon = class {
6043
6598
  return this._config;
6044
6599
  }
6045
6600
  async initialize(context) {
6046
- this._ctx = context;
6601
+ const secrets = context.secrets;
6602
+ this._ctx = secrets !== void 0 ? withSecretAwareSettings(context, {
6603
+ secrets,
6604
+ addonTree: () => this.addonSecretTree(),
6605
+ deviceTree: () => this.deviceSecretTree(),
6606
+ onOrphaned: (refs) => context.logger.warn("keychain refs dropped by a settings write could not be deleted", { meta: { refs: [...refs] } }),
6607
+ isOperatorWrite: () => this._operatorWriteDepth > 0
6608
+ }) : context;
6047
6609
  await this.resolveConfig();
6610
+ if (secrets !== void 0) this._secretChangeUnsub = secrets.onChange((ref) => {
6611
+ if (this._configSecretRefs.has(ref)) this.scheduleSecretReresolve(SECRET_CHANGE_DEBOUNCE_MS);
6612
+ });
6048
6613
  const result = await this.onInitialize();
6049
6614
  this.emitLifecycle(EventCategory.AddonStarted);
6050
6615
  const normalized = normalizeAddonInitResult(result);
@@ -6077,6 +6642,12 @@ var BaseAddon = class {
6077
6642
  */
6078
6643
  async onHubReachable() {}
6079
6644
  async shutdown() {
6645
+ this._secretChangeUnsub?.();
6646
+ this._secretChangeUnsub = null;
6647
+ if (this._secretRetryTimer !== null) clearTimeout(this._secretRetryTimer);
6648
+ if (this._secretChangeTimer !== null) clearTimeout(this._secretChangeTimer);
6649
+ this._secretRetryTimer = null;
6650
+ this._secretChangeTimer = null;
6080
6651
  this.emitLifecycle(EventCategory.AddonStopped);
6081
6652
  if (this.autoEmitReadiness) this.emitReadinessForProviders("down");
6082
6653
  await this.onShutdown();
@@ -6155,7 +6726,7 @@ var BaseAddon = class {
6155
6726
  return hydrateSchema(schema, overlay ? {
6156
6727
  ...projected,
6157
6728
  ...overlay
6158
- } : projected);
6729
+ } : projected, { inlineSecretsAsViews: true });
6159
6730
  }
6160
6731
  /**
6161
6732
  * The integration-level view of this addon's settings: exactly the sections
@@ -6204,7 +6775,7 @@ var BaseAddon = class {
6204
6775
  return hydrateSchema({
6205
6776
  ...schema,
6206
6777
  sections
6207
- }, projected);
6778
+ }, projected, { inlineSecretsAsViews: true });
6208
6779
  }
6209
6780
  /**
6210
6781
  * The raw addon store PROJECTED onto the target node's bare per-node keys:
@@ -6258,18 +6829,50 @@ var BaseAddon = class {
6258
6829
  value: result.value[key]
6259
6830
  };
6260
6831
  }
6832
+ /**
6833
+ * The OPERATOR's write — a settings form or an admin API call, dispatched by
6834
+ * the kernel. Identical to {@link updateGlobalSettings}, except that a secret
6835
+ * the operator sends is stored as sent even when it equals a pre-keychain
6836
+ * inline value: the operator re-entering a password is a change, an addon
6837
+ * writing back what it read is not (D787).
6838
+ */
6839
+ async updateGlobalSettingsAsOperator(patch, nodeId) {
6840
+ this._operatorWriteDepth++;
6841
+ try {
6842
+ await this.applyGlobalPatch(patch, nodeId);
6843
+ } finally {
6844
+ this._operatorWriteDepth--;
6845
+ }
6846
+ }
6261
6847
  async updateGlobalSettings(patch, nodeId) {
6848
+ await this.applyGlobalPatch(patch, nodeId);
6849
+ }
6850
+ /**
6851
+ * REMOVE stored secrets — their keychain values and their markers (D787).
6852
+ *
6853
+ * Writing `''` to a secret field KEEPS what is stored (an empty string is
6854
+ * what a defaults fallback writes back, and it must never destroy a
6855
+ * credential), so code that means "forget this token" says so here. Without
6856
+ * a keychain (an older kernel) it writes `''`, as such code always did.
6857
+ */
6858
+ async clearSecrets(keys, nodeId) {
6859
+ const tree = this.addonSecretTree();
6860
+ const keychain = this._ctx?.secrets !== void 0;
6861
+ const patch = {};
6862
+ for (const key of keys) patch[key] = keychain && tree.has(key) ? SECRET_CLEAR : "";
6863
+ await this.applyGlobalPatch(patch, nodeId);
6864
+ }
6865
+ async applyGlobalPatch(barePatch, nodeId) {
6262
6866
  const keys = this.perNodeKeys();
6263
6867
  const localNode = normalizeNodeId(this._ctx?.kernel?.localNodeId);
6264
6868
  const target = normalizeNodeId(nodeId ?? this._ctx?.kernel?.localNodeId);
6265
- const barePatch = patch;
6266
6869
  const scoped = keys.size > 0 ? scopePatch(barePatch, keys, target) : barePatch;
6267
6870
  await this._ctx?.settings?.writeAddonStore(scoped);
6268
6871
  if (target !== localNode) return;
6269
6872
  await this.resolveConfig();
6270
6873
  await this.onConfigChanged();
6271
6874
  this.emitLifecycle(EventCategory.AddonUpdated, { level: "global" });
6272
- this.maybeAutoRestart(patch, this.globalSettingsSchema());
6875
+ this.maybeAutoRestart(Object.keys(barePatch), this.globalSettingsSchema());
6273
6876
  }
6274
6877
  /**
6275
6878
  * The set of field keys the global settings schema declares `perNode: true`
@@ -6294,7 +6897,7 @@ var BaseAddon = class {
6294
6897
  * time to return its response before the addon is torn down and
6295
6898
  * re-initialised by `AddonRegistryService.restartAddon`.
6296
6899
  */
6297
- maybeAutoRestart(patch, schema) {
6900
+ maybeAutoRestart(patchKeys, schema) {
6298
6901
  if (!schema) return;
6299
6902
  const restartKeys = /* @__PURE__ */ new Set();
6300
6903
  for (const section of schema.sections) for (const field of section.fields) {
@@ -6302,13 +6905,13 @@ var BaseAddon = class {
6302
6905
  if (field.requiresRestart) restartKeys.add(field.key);
6303
6906
  }
6304
6907
  if (restartKeys.size === 0) return;
6305
- if (!Object.keys(patch).some((k) => restartKeys.has(k))) return;
6908
+ if (!patchKeys.some((k) => restartKeys.has(k))) return;
6306
6909
  const ctx = this._ctx;
6307
6910
  if (!ctx) return;
6308
6911
  const addonId = ctx.id;
6309
6912
  setImmediate(() => {
6310
6913
  ctx.api.addons?.restartAddon?.mutate({ addonId }).then(() => {
6311
- ctx.logger.info("addon auto-restart triggered by restart-required setting change", { meta: { changedFields: Object.keys(patch).filter((k) => restartKeys.has(k)) } });
6914
+ ctx.logger.info("addon auto-restart triggered by restart-required setting change", { meta: { changedFields: patchKeys.filter((k) => restartKeys.has(k)) } });
6312
6915
  }).catch((err) => {
6313
6916
  ctx.logger.error("addon auto-restart failed", { meta: { error: err instanceof Error ? err.message : String(err) } });
6314
6917
  });
@@ -6317,7 +6920,7 @@ var BaseAddon = class {
6317
6920
  async getDeviceSettings(deviceId) {
6318
6921
  const schema = this.deviceSettingsSchema();
6319
6922
  if (!schema) return { sections: [] };
6320
- return hydrateSchema(schema, await this._ctx?.settings?.readDeviceStore(deviceId) ?? {});
6923
+ return hydrateSchema(schema, await this._ctx?.settings?.readDeviceStore(deviceId) ?? {}, { inlineSecretsAsViews: true });
6321
6924
  }
6322
6925
  async updateDeviceSettings(deviceId, patch) {
6323
6926
  await this._ctx?.settings?.writeDeviceStore(deviceId, patch);
@@ -6447,7 +7050,7 @@ var BaseAddon = class {
6447
7050
  * selection at boot (absent scoped key ⇒ the constructor default wins).
6448
7051
  */
6449
7052
  async resolveConfig() {
6450
- const stored = await this.readAddonStoreWithRetry();
7053
+ const stored = await this.resolveStoredSecrets(await this.readAddonStoreWithRetry());
6451
7054
  const perNode = this.perNodeKeys();
6452
7055
  const localNode = normalizeNodeId(this._ctx?.kernel?.localNodeId);
6453
7056
  const resolved = { ...this.defaults };
@@ -6472,7 +7075,7 @@ var BaseAddon = class {
6472
7075
  key,
6473
7076
  schema,
6474
7077
  fallback,
6475
- read: () => this.readAddonStoreWithRetry(),
7078
+ read: async () => this.resolveStoredSecrets(await this.readAddonStoreWithRetry()),
6476
7079
  write: async (patch) => {
6477
7080
  await this._ctx?.settings?.writeAddonStore(patch);
6478
7081
  },
@@ -6489,7 +7092,7 @@ var BaseAddon = class {
6489
7092
  key,
6490
7093
  schema,
6491
7094
  fallback,
6492
- read: async () => await this._ctx?.settings?.readDeviceStore(deviceId) ?? {},
7095
+ read: async () => this.resolveStoredSecrets(await this._ctx?.settings?.readDeviceStore(deviceId) ?? {}, false),
6493
7096
  write: async (patch) => {
6494
7097
  await this._ctx?.settings?.writeDeviceStore(deviceId, patch);
6495
7098
  },
@@ -6501,6 +7104,70 @@ var BaseAddon = class {
6501
7104
  } })
6502
7105
  });
6503
7106
  }
7107
+ /** The addon store's secret tree: schema fields by TYPE, plus `secretStatePaths`. */
7108
+ addonSecretTree() {
7109
+ this._addonSecretTree ??= mergeSecretStatePaths(secretTreeFromSchema(this.globalSettingsSchema()), this.secretStatePaths);
7110
+ return this._addonSecretTree;
7111
+ }
7112
+ deviceSecretTree() {
7113
+ this._deviceSecretTree ??= secretTreeFromSchema(this.deviceSettingsSchema());
7114
+ return this._deviceSecretTree;
7115
+ }
7116
+ /**
7117
+ * Secrets of this addon's stored config that could not be resolved on the
7118
+ * last read, with why. Non-empty means the addon is running WITHOUT them —
7119
+ * an addon whose function needs one should report itself degraded rather
7120
+ * than start on an empty credential.
7121
+ */
7122
+ get unresolvedSecrets() {
7123
+ return this._unresolvedSecrets;
7124
+ }
7125
+ /**
7126
+ * Substitute every keychain marker in a stored blob with its value. With no
7127
+ * keychain (no `ctx.secrets`) or no marker, the blob comes back unchanged.
7128
+ * An unresolvable value is LEFT OUT (never `''`), logged by ref — never by
7129
+ * value — and, when the cause can pass, retried with backoff. Nothing is
7130
+ * ever written back from here.
7131
+ */
7132
+ async resolveStoredSecrets(blob, trackForConfig = true) {
7133
+ const secrets = this._ctx?.secrets;
7134
+ if (secrets === void 0) return blob;
7135
+ const refs = collectSecretMarkerRefs(blob);
7136
+ if (trackForConfig) this._configSecretRefs = new Set(refs);
7137
+ if (refs.length === 0) {
7138
+ if (trackForConfig) this._unresolvedSecrets = [];
7139
+ return blob;
7140
+ }
7141
+ const { value, unresolved } = await resolveSecretMarkers(blob, secrets);
7142
+ if (trackForConfig) {
7143
+ this._unresolvedSecrets = unresolved;
7144
+ if (unresolved.length > 0) {
7145
+ this._ctx?.logger?.error?.("secret unavailable — running without it, will retry", { meta: { secrets: unresolved.map((u) => ({
7146
+ ref: u.ref,
7147
+ reason: u.reason
7148
+ })) } });
7149
+ if (unresolved.some((u) => u.reason !== "missing" && u.reason !== "forbidden")) {
7150
+ this.scheduleSecretReresolve(this._secretRetryDelayMs);
7151
+ this._secretRetryDelayMs = Math.min(this._secretRetryDelayMs * 2, SECRET_RETRY_MAX_MS);
7152
+ }
7153
+ } else this._secretRetryDelayMs = SECRET_RETRY_FIRST_MS;
7154
+ }
7155
+ return value;
7156
+ }
7157
+ /** Re-resolve the config (a keychain-only change, or a retry) and apply it. */
7158
+ scheduleSecretReresolve(delayMs) {
7159
+ const timerOf = delayMs === SECRET_CHANGE_DEBOUNCE_MS ? "_secretChangeTimer" : "_secretRetryTimer";
7160
+ if (this[timerOf] !== null) return;
7161
+ const timer = setTimeout(() => {
7162
+ this[timerOf] = null;
7163
+ if (this._ctx === null) return;
7164
+ this.resolveConfig().then(() => this.onConfigChanged()).catch((err) => {
7165
+ this._ctx?.logger?.error?.("re-resolving secrets failed", { meta: { error: err instanceof Error ? err.message : String(err) } });
7166
+ });
7167
+ }, delayMs);
7168
+ timer.unref?.();
7169
+ this[timerOf] = timer;
7170
+ }
6504
7171
  /**
6505
7172
  * Wrap `ctx.settings.readAddonStore()` with a short retry budget so a
6506
7173
  * transient settings-store outage (mid-restart of sqlite-settings, tsx-watch
@@ -7076,6 +7743,69 @@ method(object({ deviceId: number() }), array(StreamSourceEntrySchema)), method(o
7076
7743
  kind: "mutation",
7077
7744
  auth: "admin"
7078
7745
  }), method(object({ deviceId: number() }), unknown().nullable()), method(object({ deviceId: number() }), RawStateResultSchema.nullable(), { auth: "protected" });
7746
+ function defOf(schema) {
7747
+ return schema._zod?.def ?? {};
7748
+ }
7749
+ function declaredHere(schema) {
7750
+ return globalRegistry.get(schema)?.secret === true;
7751
+ }
7752
+ /** Wrapper kinds whose `innerType` is the field itself. */
7753
+ var WRAPPERS = new Set([
7754
+ "optional",
7755
+ "nullable",
7756
+ "default",
7757
+ "prefault",
7758
+ "catch",
7759
+ "readonly",
7760
+ "nonoptional"
7761
+ ]);
7762
+ /**
7763
+ * The schema layers that make up ONE field: the schema itself and every
7764
+ * wrapper below it (optional / default / nullable / readonly / catch), plus
7765
+ * both sides of a pipe (`z.preprocess` puts the real schema on `out`,
7766
+ * `.transform` on `in`).
7767
+ */
7768
+ function layersOf(schema) {
7769
+ const out = [];
7770
+ const queue = [schema];
7771
+ while (queue.length > 0) {
7772
+ const s = queue.shift();
7773
+ if (!s || out.includes(s)) continue;
7774
+ out.push(s);
7775
+ const def = defOf(s);
7776
+ if (def.type !== void 0 && WRAPPERS.has(def.type) && def.innerType) queue.push(def.innerType);
7777
+ if (def.type === "pipe") {
7778
+ if (def.in) queue.push(def.in);
7779
+ if (def.out) queue.push(def.out);
7780
+ }
7781
+ }
7782
+ return out;
7783
+ }
7784
+ /** True when any layer of this field declares `.meta({ secret: true })`. */
7785
+ function isZodSecret(schema) {
7786
+ return layersOf(schema).some(declaredHere);
7787
+ }
7788
+ /**
7789
+ * Every declared secret path in a config schema: dotted keys, `[]` for "each
7790
+ * element of this array" (`connection.password`, `rows[].token`). A declared
7791
+ * object or array is reported as one path and not descended into — everything
7792
+ * under it is secret.
7793
+ */
7794
+ function collectZodSecretPaths(schema, prefix = "") {
7795
+ if (isZodSecret(schema)) return prefix.length > 0 ? [prefix] : [];
7796
+ const paths = [];
7797
+ for (const layer of layersOf(schema)) {
7798
+ const def = defOf(layer);
7799
+ if (def.type === "object" && def.shape) for (const [key, child] of Object.entries(def.shape)) paths.push(...collectZodSecretPaths(child, prefix ? `${prefix}.${key}` : key));
7800
+ else if (def.type === "array" && def.element) paths.push(...collectZodSecretPaths(def.element, `${prefix}[]`));
7801
+ else if (def.type === "union" && def.options) for (const option of def.options) paths.push(...collectZodSecretPaths(option, prefix));
7802
+ else if (def.type === "intersection") {
7803
+ if (def.left) paths.push(...collectZodSecretPaths(def.left, prefix));
7804
+ if (def.right) paths.push(...collectZodSecretPaths(def.right, prefix));
7805
+ }
7806
+ }
7807
+ return [...new Set(paths)];
7808
+ }
7079
7809
  //#endregion
7080
7810
  //#region ../types/dist/err-msg-DX6i_MY4.mjs
7081
7811
  var DeviceType = /* @__PURE__ */ function(DeviceType) {
@@ -14126,6 +14856,196 @@ id: union([string(), number()]) }), {
14126
14856
  kind: "mutation",
14127
14857
  auth: "admin"
14128
14858
  });
14859
+ /**
14860
+ * `keychain` — the hub's encrypted store of secret values (D787).
14861
+ *
14862
+ * Settings blobs never hold a secret: they hold a marker
14863
+ * `{"$secret":"secret://<owner>/<scope>/<fieldPath>","v":1}` and the value
14864
+ * lives here, AES-256-GCM under a data key that a master key wraps. This cap
14865
+ * is the OWNER's door to its own values: every method is owner-checked
14866
+ * against the CALLER, never against anything the caller claims.
14867
+ *
14868
+ * Who the caller is: the transport stamps `callerAddonId` into the args of a
14869
+ * call that crossed a process (the parent `LocalChildRegistry` from the UDS
14870
+ * connection, the agent from its child's connection carried in
14871
+ * `$hub-cap-fwd`'s envelope). A stamp always overwrites; a wire call with no
14872
+ * stamp has its claim stripped. Only a hub in-process caller may state its own
14873
+ * identity — `ctx.secrets` does that with the addon id closed over. This is
14874
+ * identity against BUGS and misrouting, not against a malicious addon (every
14875
+ * runner is the same OS user): see the threat model in
14876
+ * `docs/design/2026-10-08-secrets-keychain.md`.
14877
+ *
14878
+ * `callerAddonId` is deliberately NOT in any input schema: the tRPC router
14879
+ * parses the input, so a session can never supply it, and the internal mount
14880
+ * floors every method to admin anyway (D240).
14881
+ *
14882
+ * Internal: addons reach it through `ctx.secrets`, never directly.
14883
+ */
14884
+ /** Why a value cannot be served right now. Never folded into "missing". */
14885
+ var KeychainUnavailableReasonSchema = _enum([
14886
+ "key-missing",
14887
+ "wrong-key",
14888
+ "key-file-unreadable",
14889
+ "store-unavailable",
14890
+ "not-initialized",
14891
+ "decrypt-failed"
14892
+ ]);
14893
+ var KeychainStateSchema = discriminatedUnion("state", [object({ state: literal("ready") }), object({
14894
+ state: literal("locked"),
14895
+ reason: KeychainUnavailableReasonSchema
14896
+ })]);
14897
+ var KeychainResolveEntrySchema = discriminatedUnion("kind", [
14898
+ object({
14899
+ kind: literal("value"),
14900
+ value: string(),
14901
+ version: number().int()
14902
+ }),
14903
+ object({ kind: literal("missing") }),
14904
+ object({
14905
+ kind: literal("unavailable"),
14906
+ reason: KeychainUnavailableReasonSchema
14907
+ }),
14908
+ object({ kind: literal("forbidden") })
14909
+ ]);
14910
+ var KeychainResolveResultSchema = record(string(), KeychainResolveEntrySchema);
14911
+ /** Metadata of one stored value — never the value. */
14912
+ var KeychainSecretMetaSchema = object({
14913
+ ref: string(),
14914
+ owner: string(),
14915
+ /** Formatted scope (`global`, `node/<id>`, `device/<id>`, …). */
14916
+ scope: string(),
14917
+ fieldPath: string(),
14918
+ version: number().int(),
14919
+ createdAt: number(),
14920
+ updatedAt: number(),
14921
+ /** `addon:<id>` | `user:<id>` | `system`. */
14922
+ updatedBy: string(),
14923
+ /** Coarse — written at most once an hour per ref. `null` = never read. */
14924
+ lastReadAt: number().nullable()
14925
+ });
14926
+ var RefListSchema = array(string().min(1)).max(512);
14927
+ method(object({
14928
+ ref: string().min(1),
14929
+ value: string().min(1)
14930
+ }), object({
14931
+ ref: string(),
14932
+ version: number().int()
14933
+ }), {
14934
+ kind: "mutation",
14935
+ auth: "admin"
14936
+ }), method(object({ refs: RefListSchema }), KeychainResolveResultSchema, { auth: "admin" }), method(object({ refs: RefListSchema }), object({ deleted: number().int() }), {
14937
+ kind: "mutation",
14938
+ auth: "admin"
14939
+ }), method(object({}), array(KeychainSecretMetaSchema).readonly(), { auth: "admin" }), method(object({}), KeychainStateSchema, { auth: "admin" });
14940
+ var KeychainKeySourceSchema = object({
14941
+ kind: _enum([
14942
+ "config-file",
14943
+ "previous-config-file",
14944
+ "platform",
14945
+ "default-file"
14946
+ ]),
14947
+ /** File sources only — a path is not a secret. */
14948
+ path: string().optional(),
14949
+ /**
14950
+ * True when a whole-volume backup of the data directory carries this key
14951
+ * next to the database it protects (the default file). The page warns.
14952
+ */
14953
+ sharesBackupWithDatabase: boolean()
14954
+ });
14955
+ var KeychainStatusSchema = object({
14956
+ keychain: KeychainStateSchema,
14957
+ /** The source of the master key in use; `null` while locked. */
14958
+ keySource: KeychainKeySourceSchema.nullable(),
14959
+ /** The source configured to be primary — differs from `keySource` while a rotation is pending. */
14960
+ configuredSource: KeychainKeySourceSchema,
14961
+ /** Short fingerprint of the master key in use (`HMAC(KEK, label)`, 16 hex). */
14962
+ fingerprint: string().nullable(),
14963
+ activeKeyId: string().nullable(),
14964
+ /**
14965
+ * The keychain unlocked with a NON-primary source: the configured primary
14966
+ * key is not the one that wraps the data key yet. `rotateMasterKey` moves it.
14967
+ */
14968
+ rotationPending: boolean(),
14969
+ /** Wrapped copies of the data key under a previous master key, kept until purged. */
14970
+ retiredWraps: number().int(),
14971
+ recoveryKeyDownloadedAt: number().nullable(),
14972
+ secretCount: number().int()
14973
+ });
14974
+ /**
14975
+ * Whether a stored value is still pointed at by its owner's settings.
14976
+ * `unknown` is a first-class answer: a scope whose blob could not be read is
14977
+ * never reported as an orphan (and never deleted as one).
14978
+ */
14979
+ var KeychainSecretUsageSchema = _enum([
14980
+ "in-use",
14981
+ "orphan",
14982
+ "unknown"
14983
+ ]);
14984
+ var KeychainAdminSecretSchema = KeychainSecretMetaSchema.extend({ usage: KeychainSecretUsageSchema });
14985
+ var KeychainAuditActionSchema = _enum([
14986
+ "put",
14987
+ "delete",
14988
+ "reveal",
14989
+ "rotate-master-key",
14990
+ "purge-retired-keys",
14991
+ "download-recovery-key",
14992
+ "delete-orphans",
14993
+ "reset",
14994
+ "initialize"
14995
+ ]);
14996
+ var KeychainAuditEntrySchema = object({
14997
+ id: string(),
14998
+ at: number(),
14999
+ action: KeychainAuditActionSchema,
15000
+ /** `addon:<id>` | `user:<id>` | `system`. */
15001
+ actor: string(),
15002
+ ref: string().nullable(),
15003
+ detail: string().nullable()
15004
+ });
15005
+ 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({
15006
+ value: string(),
15007
+ version: number().int()
15008
+ }), {
15009
+ kind: "mutation",
15010
+ auth: "admin",
15011
+ caller: "required"
15012
+ }), method(object({ refs: array(string().min(1)).max(1e3) }), object({
15013
+ deleted: array(string()).readonly(),
15014
+ kept: array(object({
15015
+ ref: string(),
15016
+ usage: KeychainSecretUsageSchema
15017
+ })).readonly()
15018
+ }), {
15019
+ kind: "mutation",
15020
+ auth: "admin",
15021
+ caller: "required"
15022
+ }), method(object({}), object({
15023
+ fingerprint: string(),
15024
+ keySource: KeychainKeySourceSchema
15025
+ }), {
15026
+ kind: "mutation",
15027
+ auth: "admin",
15028
+ caller: "required"
15029
+ }), method(object({}), object({ purged: number().int() }), {
15030
+ kind: "mutation",
15031
+ auth: "admin",
15032
+ caller: "required"
15033
+ }), method(object({}), object({
15034
+ key: string(),
15035
+ fingerprint: string(),
15036
+ keySource: KeychainKeySourceSchema
15037
+ }), {
15038
+ kind: "mutation",
15039
+ auth: "admin",
15040
+ caller: "required"
15041
+ }), method(object({ confirm: literal("RESET KEYCHAIN") }), object({
15042
+ archivedCollection: string().nullable(),
15043
+ archived: number().int()
15044
+ }), {
15045
+ kind: "mutation",
15046
+ auth: "admin",
15047
+ caller: "required"
15048
+ });
14129
15049
  method(_void(), object({
14130
15050
  id: string(),
14131
15051
  name: string(),
@@ -15368,7 +16288,11 @@ var DeviceRegisterPayloadSchema = object({
15368
16288
  var DeviceRemovePayloadSchema = object({ deviceId: number() });
15369
16289
  var DevicePersistConfigPayloadSchema = object({
15370
16290
  deviceId: number(),
15371
- data: record(string(), unknown())
16291
+ data: record(string(), unknown()),
16292
+ /** The paths the device's schema declares secret (D783), when the caller
16293
+ * knows them — those values are kept in the keychain, not the blob (D787).
16294
+ * Absent: the paths the device last reported at `registerDevice` apply. */
16295
+ secretConfigPaths: array(string()).optional()
15372
16296
  });
15373
16297
  /** What a migration actually did, per switch. `unreachable` is a first-class
15374
16298
  * answer: a camera that could not be asked is not a camera that was silenced. */
@@ -22385,8 +23309,23 @@ var RetrainMacroClassSchema = _enum([
22385
23309
  ]);
22386
23310
  /** A subject to learn, or a phantom to unlearn (taught by OMISSION). */
22387
23311
  var RetrainAnnotationKindSchema = _enum(["subject", "model_error"]);
22388
- /** Did a human draw this box, or did the assist propose it? */
22389
- var RetrainAnnotationSourceSchema = _enum(["operator", "assist"]);
23312
+ /**
23313
+ * Where a box came from. A machine-sourced box is a DRAFT on the page until
23314
+ * the operator confirms it; once saved it keeps its source as provenance.
23315
+ *
23316
+ * - `operator` — drawn by hand.
23317
+ * - `assist` — proposed by a detector run on the copy (the camera's own
23318
+ * model, or a larger teacher model).
23319
+ * - `pipeline` — the box the live pipeline actually drew on that frame, read
23320
+ * back from the track store (never a re-run).
23321
+ * - `llm` — proposed by a vision-capable LLM profile.
23322
+ */
23323
+ var RetrainAnnotationSourceSchema = _enum([
23324
+ "operator",
23325
+ "assist",
23326
+ "pipeline",
23327
+ "llm"
23328
+ ]);
22390
23329
  /** Normalised `[0,1]` rectangle against the FULL frame — the canonical form. */
22391
23330
  var RetrainBboxSchema = object({
22392
23331
  x: number(),
@@ -22404,7 +23343,8 @@ var RetrainBboxSchema = object({
22404
23343
  */
22405
23344
  var RetrainAnnotationSchema = object({
22406
23345
  id: string(),
22407
- trackId: string(),
23346
+ /** The frame's track. Absent on a recording still, which has none. */
23347
+ trackId: string().optional(),
22408
23348
  deviceId: number(),
22409
23349
  /** The COPY in retrain storage — never the source track's media key. */
22410
23350
  mediaKey: string(),
@@ -22453,13 +23393,47 @@ var RetrainFrameCandidateSchema = object({
22453
23393
  * fail, whatever became of the original. */
22454
23394
  copied: boolean()
22455
23395
  });
23396
+ /**
23397
+ * One box the live pipeline drew on a copied frame — what a correction starts
23398
+ * from. Derived when the frame is listed, from the track store: the subject
23399
+ * box recorded on the source media row when there is one, else the track
23400
+ * position nearest the frame's capture time. Never stored as an annotation
23401
+ * until the operator confirms it.
23402
+ */
23403
+ var RetrainPipelineBoxSchema = object({
23404
+ /** Normalised `[0,1]` against the full frame. */
23405
+ bbox: RetrainBboxSchema,
23406
+ macroClass: RetrainMacroClassSchema,
23407
+ label: string().optional(),
23408
+ subLabel: string().optional(),
23409
+ /** The detection score of the position used, when it was recorded. */
23410
+ score: number().optional(),
23411
+ /** The root model that produced the track, when it was recorded. */
23412
+ modelId: string().optional(),
23413
+ trackId: string(),
23414
+ /** `subject-box`: recorded on this very frame. `position`: the track's
23415
+ * position nearest the capture time, `deltaMs` away. */
23416
+ basis: _enum(["subject-box", "position"]),
23417
+ deltaMs: number()
23418
+ });
23419
+ /**
23420
+ * Where a retrain frame came from: a TRACK's stored media (copy-on-select),
23421
+ * or the RECORDING at an instant — the frame a model saw nothing in has no
23422
+ * track at all.
23423
+ */
23424
+ var RetrainFrameOriginSchema = _enum(["track", "recording"]);
22456
23425
  /** A frame the dataset OWNS: bytes copied at selection time. */
22457
23426
  var RetrainFrameSchema = object({
22458
23427
  frameId: string(),
22459
23428
  deviceId: number(),
22460
- trackId: string(),
22461
- /** Provenance only. It may already point at nothing — that is expected. */
22462
- sourceMediaId: number().int(),
23429
+ origin: RetrainFrameOriginSchema,
23430
+ /** The track it was copied from. Absent on a recording still. */
23431
+ trackId: string().optional(),
23432
+ /** Provenance only. It may already point at nothing — that is expected.
23433
+ * Absent on a recording still. */
23434
+ sourceMediaId: number().int().optional(),
23435
+ /** A recording still: the playhead instant it was taken at. */
23436
+ epochMs: number().optional(),
22463
23437
  sourceKind: MediaFileKindEnum,
22464
23438
  sizeBytes: number().int(),
22465
23439
  width: number().int(),
@@ -22470,7 +23444,12 @@ var RetrainFrameSchema = object({
22470
23444
  /** The operator's "every subject in this frame is boxed". Detector
22471
23445
  * evaluation keeps only complete frames: an unboxed subject would count as
22472
23446
  * a false positive. */
22473
- complete: boolean()
23447
+ complete: boolean(),
23448
+ /** The boxes the pipeline drew on this frame. Present on list answers;
23449
+ * empty when nothing the track store holds can be placed on it. */
23450
+ pipelineBoxes: array(RetrainPipelineBoxSchema).readonly().optional(),
23451
+ /** The named collections this frame belongs to. Present on list answers. */
23452
+ collectionIds: array(string()).readonly().optional()
22474
23453
  });
22475
23454
  /** Why a copy-on-select could not be honoured — named, never a silent skip. */
22476
23455
  var RetrainCopyRefusalSchema = _enum([
@@ -22501,6 +23480,8 @@ var RetrainFrameListSchema = object({
22501
23480
  var RetrainExportFilterSchema = object({
22502
23481
  deviceIds: array(number()).optional(),
22503
23482
  frameIds: array(string()).max(2e4).optional(),
23483
+ /** Only frames in at least one of these named collections. */
23484
+ collectionIds: array(string()).max(200).optional(),
22504
23485
  batchId: string().optional(),
22505
23486
  /** Only frames the operator marked complete (all subjects boxed). */
22506
23487
  completeOnly: boolean().optional()
@@ -22565,6 +23546,109 @@ var RetrainAssistResultSchema = discriminatedUnion("kind", [object({
22565
23546
  reason: string(),
22566
23547
  detail: string().optional()
22567
23548
  })]);
23549
+ /** A named set over the retrain corpus — membership only, it owns no pixels. */
23550
+ var RetrainCollectionSchema = object({
23551
+ id: string(),
23552
+ name: string(),
23553
+ createdAt: number(),
23554
+ frameCount: number().int()
23555
+ });
23556
+ var RetrainCollectionCreateResultSchema = discriminatedUnion("kind", [object({
23557
+ kind: literal("created"),
23558
+ collection: RetrainCollectionSchema
23559
+ }), object({
23560
+ kind: literal("refused"),
23561
+ reason: _enum(["empty-name", "duplicate-name"])
23562
+ })]);
23563
+ var RetrainCollectionRenameResultSchema = discriminatedUnion("kind", [object({
23564
+ kind: literal("renamed"),
23565
+ collection: RetrainCollectionSchema
23566
+ }), object({
23567
+ kind: literal("refused"),
23568
+ reason: _enum([
23569
+ "empty-name",
23570
+ "duplicate-name",
23571
+ "unknown-collection"
23572
+ ])
23573
+ })]);
23574
+ /**
23575
+ * The outcome of adding the frame at a recording instant. Every refusal is
23576
+ * named: `still-unavailable` (not recording, a gap, or an undecodable frame —
23577
+ * `detail` says which), `still-busy` (the recorder is at its decode bound; try
23578
+ * again), `unreadable-image`, `write-failed`, `unknown-collection`.
23579
+ */
23580
+ var AddRetrainFrameFromRecordingResultSchema = discriminatedUnion("kind", [object({
23581
+ kind: literal("added"),
23582
+ collectionId: string(),
23583
+ frame: RetrainFrameSchema,
23584
+ /** The moment was already in the dataset; nothing was decoded. */
23585
+ reused: boolean()
23586
+ }), object({
23587
+ kind: literal("refused"),
23588
+ reason: _enum([
23589
+ "unknown-collection",
23590
+ "still-unavailable",
23591
+ "still-busy",
23592
+ "unreadable-image",
23593
+ "write-failed"
23594
+ ]),
23595
+ detail: string().optional()
23596
+ })]);
23597
+ /** A vision LLM profile the AI assist may use, and where it sends the frame. */
23598
+ var RetrainAssistProfileSchema = object({
23599
+ id: string(),
23600
+ name: string(),
23601
+ model: string(),
23602
+ kind: string(),
23603
+ /** `true` when the frame would leave the house (a cloud vendor, or an
23604
+ * endpoint that is not on the local network). The page confirms each such
23605
+ * run, and the provider refuses one without `allowCloud`. */
23606
+ leavesHouse: boolean()
23607
+ });
23608
+ /** A box the AI assist proposed: a draft, plus the model's own reason. */
23609
+ var RetrainLlmProposalSchema = RetrainAnnotationDraftSchema.extend({ reason: string() });
23610
+ /** What the AI assist said about a box that was already on the canvas. */
23611
+ var RetrainLlmReviewSchema = object({
23612
+ /** The `ref` the page sent the box under. */
23613
+ ref: string(),
23614
+ verdict: _enum([
23615
+ "confirmed",
23616
+ "wrong-class",
23617
+ "not-an-object",
23618
+ "uncertain"
23619
+ ]),
23620
+ suggestedClass: RetrainMacroClassSchema.optional(),
23621
+ reason: string()
23622
+ });
23623
+ /**
23624
+ * The AI assist's answer. `proposed` carries drafts (`source: 'llm'`, the
23625
+ * model and its confidence) and reviews; items the model got wrong (a box off
23626
+ * the frame, an unasked class, an unknown ref) are dropped and counted in
23627
+ * `rejected`. A whole answer that is not the schema is `malformed-answer`.
23628
+ */
23629
+ var RetrainLlmAssistResultSchema = discriminatedUnion("kind", [object({
23630
+ kind: literal("proposed"),
23631
+ profileId: string(),
23632
+ model: string(),
23633
+ /** The frame was sent outside the house for this answer. */
23634
+ leftHouse: boolean(),
23635
+ proposals: array(RetrainLlmProposalSchema).readonly(),
23636
+ reviews: array(RetrainLlmReviewSchema).readonly(),
23637
+ rejected: number().int()
23638
+ }), object({
23639
+ kind: literal("refused"),
23640
+ reason: _enum([
23641
+ "unknown-frame",
23642
+ "unreadable-frame",
23643
+ "unknown-profile",
23644
+ "profile-disabled",
23645
+ "no-vision",
23646
+ "cloud-not-confirmed",
23647
+ "llm-error",
23648
+ "malformed-answer"
23649
+ ]),
23650
+ detail: string().optional()
23651
+ })]);
22568
23652
  /** The outcome of a lifecycle move owned by the retrain page. */
22569
23653
  var RetrainTransitionResultSchema = object({
22570
23654
  trackId: string(),
@@ -23282,7 +24366,7 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
23282
24366
  auth: "admin"
23283
24367
  }), method(object({
23284
24368
  deviceId: number(),
23285
- trackId: string(),
24369
+ trackId: string().optional(),
23286
24370
  frameId: string()
23287
24371
  }), object({
23288
24372
  removed: boolean(),
@@ -23299,7 +24383,8 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
23299
24383
  auth: "admin"
23300
24384
  }), method(object({
23301
24385
  deviceId: number(),
23302
- trackId: string(),
24386
+ /** The frame's track, when it has one — checked against the frame. */
24387
+ trackId: string().optional(),
23303
24388
  frameId: string(),
23304
24389
  subject: RetrainAssistSubjectSchema,
23305
24390
  /** Which node runs it. Absent ⇒ wherever an unowned call lands. */
@@ -23307,12 +24392,16 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
23307
24392
  }), RetrainAssistResultSchema, {
23308
24393
  kind: "mutation",
23309
24394
  auth: "admin"
23310
- }), method(object({ trackId: string() }), array(RetrainAnnotationSchema).readonly(), {
24395
+ }), method(object({
24396
+ trackId: string().optional(),
24397
+ frameIds: array(string()).max(2e3).optional()
24398
+ }), array(RetrainAnnotationSchema).readonly(), {
23311
24399
  kind: "query",
23312
24400
  auth: "admin"
23313
24401
  }), method(object({
23314
24402
  deviceId: number(),
23315
- trackId: string(),
24403
+ /** The frame's track, when it has one — checked against the frame. */
24404
+ trackId: string().optional(),
23316
24405
  frameId: string(),
23317
24406
  annotations: array(RetrainAnnotationDraftSchema)
23318
24407
  }), array(RetrainAnnotationSchema).readonly(), {
@@ -23335,7 +24424,7 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
23335
24424
  auth: "admin"
23336
24425
  }), method(object({
23337
24426
  deviceId: number(),
23338
- trackId: string(),
24427
+ trackId: string().optional(),
23339
24428
  frameId: string(),
23340
24429
  complete: boolean()
23341
24430
  }), RetrainFrameSchema, {
@@ -23349,6 +24438,74 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
23349
24438
  kind: "mutation",
23350
24439
  auth: "admin",
23351
24440
  timeoutMs: 60 * 6e4
24441
+ }), method(object({}), array(RetrainAssistProfileSchema).readonly(), {
24442
+ kind: "query",
24443
+ auth: "admin"
24444
+ }), method(object({
24445
+ deviceId: number(),
24446
+ trackId: string().optional(),
24447
+ frameId: string(),
24448
+ profileId: string(),
24449
+ classes: array(RetrainMacroClassSchema).min(1),
24450
+ boxes: array(object({
24451
+ ref: string(),
24452
+ bbox: RetrainBboxSchema,
24453
+ macroClass: RetrainMacroClassSchema,
24454
+ label: string().optional()
24455
+ })).max(50),
24456
+ allowCloud: boolean()
24457
+ }), RetrainLlmAssistResultSchema, {
24458
+ kind: "mutation",
24459
+ auth: "admin",
24460
+ timeoutMs: 18e4
24461
+ }), method(object({ name: string().max(120) }), RetrainCollectionCreateResultSchema, {
24462
+ kind: "mutation",
24463
+ auth: "admin"
24464
+ }), method(object({}), array(RetrainCollectionSchema).readonly(), {
24465
+ kind: "query",
24466
+ auth: "admin"
24467
+ }), method(object({
24468
+ id: string(),
24469
+ name: string().max(120)
24470
+ }), RetrainCollectionRenameResultSchema, {
24471
+ kind: "mutation",
24472
+ auth: "admin"
24473
+ }), method(object({ id: string() }), object({
24474
+ deleted: boolean(),
24475
+ removedFrames: number().int()
24476
+ }), {
24477
+ kind: "mutation",
24478
+ auth: "admin"
24479
+ }), method(object({
24480
+ collectionId: string(),
24481
+ deviceId: number(),
24482
+ epochMs: number()
24483
+ }), AddRetrainFrameFromRecordingResultSchema, {
24484
+ kind: "mutation",
24485
+ auth: "admin",
24486
+ timeoutMs: 6e4
24487
+ }), method(object({
24488
+ collectionId: string(),
24489
+ frameIds: array(string()).min(1).max(500)
24490
+ }), object({
24491
+ added: number().int(),
24492
+ alreadyMember: number().int(),
24493
+ unknownFrameIds: array(string()).readonly()
24494
+ }), {
24495
+ kind: "mutation",
24496
+ auth: "admin"
24497
+ }), method(object({
24498
+ collectionId: string(),
24499
+ frameId: string()
24500
+ }), object({
24501
+ removed: boolean(),
24502
+ deletedFrame: boolean()
24503
+ }), {
24504
+ kind: "mutation",
24505
+ auth: "admin"
24506
+ }), method(object({ collectionId: string() }), array(RetrainFrameSchema).readonly(), {
24507
+ kind: "query",
24508
+ auth: "admin"
23352
24509
  }), method(object({
23353
24510
  /** Which of the three event tables owns the row. */
23354
24511
  ownerType: EventOwnerTypeSchema,
@@ -23972,13 +25129,31 @@ var RecommendationReasonSchema = discriminatedUnion("kind", [
23972
25129
  object({
23973
25130
  kind: literal("no-family-build"),
23974
25131
  format: ModelFormatSchema$1
25132
+ }),
25133
+ object({
25134
+ kind: literal("kept-custom-pin"),
25135
+ modelId: string(),
25136
+ deviceKey: string()
23975
25137
  })
23976
25138
  ]);
25139
+ /** Why a device is left exactly as it is, whatever the plan would pick (D786). */
25140
+ var KeptReasonSchema = _enum(["custom-pin"]);
25141
+ /**
25142
+ * Where a choice's latency came from (D791): this node's own benchmark
25143
+ * result, or the hardware-class table. Measured on the node beats the table.
25144
+ */
25145
+ var LatencySourceSchema = discriminatedUnion("kind", [object({ kind: literal("table") }), object({
25146
+ kind: literal("node-benchmark"),
25147
+ resultId: string(),
25148
+ measuredAtMs: number()
25149
+ })]);
23977
25150
  var DeviceModelChoiceSchema = object({
23978
25151
  modelId: string(),
23979
25152
  p50Ms: number(),
23980
25153
  fps: number(),
23981
25154
  measured: boolean(),
25155
+ /** Absent on a plan from before D791 — read as the table. */
25156
+ source: LatencySourceSchema.optional(),
23982
25157
  /** Parallel sessions at the camera rate with the headroom kept free: ⌊fps × (1 − headroom) / camera fps⌋. */
23983
25158
  capacitySessions: number(),
23984
25159
  personRecall: number()
@@ -23989,6 +25164,8 @@ var DeviceRecommendationSchema = object({
23989
25164
  enabled: boolean(),
23990
25165
  available: boolean(),
23991
25166
  chosen: DeviceModelChoiceSchema.nullable(),
25167
+ /** Present when the device is kept as is: Apply writes nothing on it. */
25168
+ kept: KeptReasonSchema.optional(),
23992
25169
  reasons: array(RecommendationReasonSchema).readonly()
23993
25170
  });
23994
25171
  var NodeRecommendationSchema = object({
@@ -24042,6 +25219,17 @@ var AutoTuneWarningSchema = discriminatedUnion("kind", [
24042
25219
  kind: literal("coral-enabled"),
24043
25220
  nodeId: string(),
24044
25221
  deviceKey: string()
25222
+ }),
25223
+ object({
25224
+ kind: literal("custom-pin-kept"),
25225
+ nodeId: string(),
25226
+ deviceKey: string().nullable(),
25227
+ deviceId: number().nullable(),
25228
+ modelId: string()
25229
+ }),
25230
+ object({
25231
+ kind: literal("custom-registry-unreadable"),
25232
+ error: string()
24045
25233
  })
24046
25234
  ]);
24047
25235
  var AutoTuneOptionsSchema = object({
@@ -24220,13 +25408,14 @@ var SuggestSharesResultSchema = object({
24220
25408
  nodes: array(SuggestedNodeShareSchema).readonly()
24221
25409
  });
24222
25410
  /**
24223
- * Where the node and device shares come from (D750, D755).
24224
- * - `hardware` (default) — computed by the system from each node's static
24225
- * capacity (its accelerators at their Auto tune models, from the measured
24226
- * latency table), recomputed whenever a node or device joins, leaves, is
24227
- * switched on or off, or changes model. No load input.
24228
- * - `benchmark` — the same, from each node's measured capacity (node
24229
- * benchmark results); a node without results falls back to `hardware`.
25411
+ * Where the node and device shares come from (D750, D755, D791).
25412
+ * - `benchmark` (default since D791) — each node's capacity as its own node
25413
+ * benchmark measured it; a node without fresh results is sized from
25414
+ * `hardware` and says so. Measured on the node beats the table.
25415
+ * - `hardware` — computed from each node's static capacity only (its
25416
+ * accelerators at their Auto tune models, from the latency table).
25417
+ * Both are recomputed whenever a node or device joins, leaves, is switched
25418
+ * on or off, changes model, or a benchmark result is written. No load input.
24230
25419
  * - `manual` — the operator's stored sliders.
24231
25420
  * Either way a node or device that cannot take sessions gives its share to
24232
25421
  * the others in proportion; the stored values are never rewritten for that.
@@ -24275,6 +25464,362 @@ var EffectiveSharesSchema = object({
24275
25464
  nodeWeights: record(string(), number()),
24276
25465
  deviceWeights: record(string(), record(string(), number()))
24277
25466
  });
25467
+ /**
25468
+ * Wire shapes of the node benchmark (D791): the operator's plan, the
25469
+ * preflight the confirmation shows, the run the orchestrator owns, what the
25470
+ * measuring runner reports, and the result rows Auto tune and the automatic
25471
+ * shares read.
25472
+ *
25473
+ * ONE node at a time, owned by the pipeline orchestrator. While a run is
25474
+ * active the cluster is in BENCHMARK MODE for that node: it is not a
25475
+ * detection candidate, camera pins naming it are ignored so its sessions move
25476
+ * elsewhere, and both come back when the mode ends — after a crash or a hub
25477
+ * restart too (a persisted manifest, reconciled against the registry).
25478
+ *
25479
+ * Two measurements, both on the node, driven by its own runner (frames never
25480
+ * cross a process at frame rate, D9):
25481
+ * - `device` — one accelerator × one candidate detector, root only, open
25482
+ * loop: how many streams at the camera rate it carries inside the frame
25483
+ * interval;
25484
+ * - `pipeline` — the chosen detector plus the operator's detail steps
25485
+ * (faces, plates, classifiers, CLIP…), on varied frames from the bench
25486
+ * clip: how many parallel sessions the node carries before latency, drops,
25487
+ * CPU, RAM or the event loop give out.
25488
+ */
25489
+ /** Defaults and bounds, one place. */
25490
+ var NODE_BENCHMARK_DEFAULTS = {
25491
+ fpsPerStream: 10,
25492
+ budgetMinutes: 45,
25493
+ minBudgetMinutes: 10,
25494
+ maxBudgetMinutes: 120,
25495
+ /** A result older than this no longer beats the table. */
25496
+ staleAfterDays: 30,
25497
+ /** Warm-in per ramp step (not accounted). */
25498
+ settleSec: 5,
25499
+ /** Accounted window per ramp step. */
25500
+ measureSec: 20,
25501
+ /** Longest the drain may take before the run is refused. */
25502
+ drainTimeoutSec: 120,
25503
+ /** Candidate models per device in one run. */
25504
+ maxModelsPerDevice: 6
25505
+ };
25506
+ /** The two measurements a run can make. */
25507
+ var NodeBenchmarkPhaseSchema = _enum(["device", "pipeline"]);
25508
+ var NodeBenchmarkDevicePlanSchema = object({
25509
+ /** `<backend>:<device>` — `openvino:npu`, `coreml:all`, `cpu`. */
25510
+ deviceKey: string().min(1),
25511
+ /**
25512
+ * Root detector candidates for the `device` measurement, in the order
25513
+ * measured. The FIRST is the one the `pipeline` measurement runs.
25514
+ */
25515
+ modelIds: array(string().min(1)).min(1).max(NODE_BENCHMARK_DEFAULTS.maxModelsPerDevice)
25516
+ });
25517
+ /** What the operator confirmed. */
25518
+ var NodeBenchmarkPlanSchema = object({
25519
+ nodeId: string().min(1),
25520
+ devices: array(NodeBenchmarkDevicePlanSchema).min(1),
25521
+ /** Which measurements run. At least one. */
25522
+ phases: array(NodeBenchmarkPhaseSchema).min(1).default(["device", "pipeline"]),
25523
+ /**
25524
+ * Detail steps (catalog step ids under the root: faces, plates,
25525
+ * classifiers, CLIP…) the `pipeline` measurement enables. The root
25526
+ * detector always runs.
25527
+ */
25528
+ steps: array(string().min(1)).default([]),
25529
+ /** Offered rate of one stream / session. */
25530
+ fpsPerStream: number().int().min(1).max(30).default(NODE_BENCHMARK_DEFAULTS.fpsPerStream),
25531
+ /** Hard deadline: the mode ends and the cluster is restored when it passes. */
25532
+ budgetMinutes: number().int().min(NODE_BENCHMARK_DEFAULTS.minBudgetMinutes).max(NODE_BENCHMARK_DEFAULTS.maxBudgetMinutes).default(NODE_BENCHMARK_DEFAULTS.budgetMinutes),
25533
+ /** Keep the models the run downloaded (default: delete what was not installed before). */
25534
+ keepDownloadedModels: boolean().default(false),
25535
+ /** Start although the other nodes' capacity does not cover the sessions running now. */
25536
+ acceptInsufficientHeadroom: boolean().default(false)
25537
+ });
25538
+ var NodeBenchmarkRefusalSchema = object({
25539
+ kind: _enum([
25540
+ "benchmark-active",
25541
+ "node-offline",
25542
+ "unknown-device",
25543
+ "no-phase",
25544
+ "insufficient-headroom"
25545
+ ]),
25546
+ detail: string(),
25547
+ overridable: boolean()
25548
+ });
25549
+ /** A camera whose detection leaves the node for the run. */
25550
+ var NodeBenchmarkMovingCameraSchema = object({
25551
+ deviceId: number(),
25552
+ /** Placed on the node now (a standing attach or a running session). */
25553
+ placedOnNode: boolean(),
25554
+ /** A node pin naming this node, ignored for the run. */
25555
+ pinnedToNode: boolean()
25556
+ });
25557
+ /** A camera that cannot leave: no other node can obtain its frames. */
25558
+ var NodeBenchmarkStayingCameraSchema = object({
25559
+ deviceId: number(),
25560
+ reason: literal("only-frame-source")
25561
+ });
25562
+ var NodeBenchmarkPreflightSchema = object({
25563
+ nodeId: string(),
25564
+ online: boolean(),
25565
+ moving: array(NodeBenchmarkMovingCameraSchema).readonly(),
25566
+ /** Keep running on the node during the run; the result is flagged contaminated. */
25567
+ staying: array(NodeBenchmarkStayingCameraSchema).readonly(),
25568
+ estimatedDurationMs: number(),
25569
+ /** The run ends and the cluster is restored at the latest after this long. */
25570
+ budgetMs: number(),
25571
+ phases: array(NodeBenchmarkPhaseSchema).readonly(),
25572
+ steps: array(string()).readonly(),
25573
+ devices: array(NodeBenchmarkDevicePlanSchema).readonly(),
25574
+ /** Parallel sessions the cluster runs now, and what the other nodes can carry. */
25575
+ headroom: object({
25576
+ sessionsNow: number(),
25577
+ otherNodesCapacitySessions: number().nullable()
25578
+ }),
25579
+ refusals: array(NodeBenchmarkRefusalSchema).readonly(),
25580
+ canStart: boolean()
25581
+ });
25582
+ /** Where the measuring runner is. */
25583
+ var NodeBenchProgressSchema = object({
25584
+ phase: _enum([
25585
+ "preparing",
25586
+ "device",
25587
+ "pipeline",
25588
+ "cleanup"
25589
+ ]),
25590
+ deviceKey: string().nullable(),
25591
+ modelId: string().nullable(),
25592
+ /** Streams (device) or sessions (pipeline) of the step running now. */
25593
+ load: number().nullable(),
25594
+ cellsDone: number(),
25595
+ cellsTotal: number(),
25596
+ message: string()
25597
+ });
25598
+ /** What limited a ramp. `none` = the ramp ran out of steps still passing. */
25599
+ var NodeBenchLimitSchema = _enum([
25600
+ "p95",
25601
+ "drops",
25602
+ "errors",
25603
+ "stall",
25604
+ "cpu",
25605
+ "ram",
25606
+ "none"
25607
+ ]);
25608
+ var NodeBenchRampStepSchema = object({
25609
+ load: number(),
25610
+ pass: boolean(),
25611
+ p95Ms: number(),
25612
+ dropRatio: number(),
25613
+ /** Completed frames per second over the accounted window. */
25614
+ fps: number(),
25615
+ cpuPct: number().nullable(),
25616
+ ramFreePct: number().nullable(),
25617
+ failReasons: array(string()).readonly()
25618
+ });
25619
+ var NodeBenchCellSchema = discriminatedUnion("phase", [object({
25620
+ phase: literal("device"),
25621
+ deviceKey: string(),
25622
+ modelId: string(),
25623
+ /** Single-stream latency (the K = 1 step). */
25624
+ p50Ms: number(),
25625
+ p95Ms: number(),
25626
+ p99Ms: number(),
25627
+ /** Frames per second sustained at the last passing step. */
25628
+ fps: number(),
25629
+ /** Streams at the camera rate the device carried inside the frame interval; 0 = not even one. */
25630
+ kMax: number(),
25631
+ limitedBy: NodeBenchLimitSchema,
25632
+ /** First call (model load + warm-up). */
25633
+ warmupMs: number(),
25634
+ ramp: array(NodeBenchRampStepSchema).readonly()
25635
+ }), object({
25636
+ phase: literal("pipeline"),
25637
+ deviceKey: string(),
25638
+ modelId: string(),
25639
+ steps: array(string()).readonly(),
25640
+ /** Parallel sessions at the camera rate the node carried; 0 = not even one. */
25641
+ maxSessions: number(),
25642
+ limitedBy: NodeBenchLimitSchema,
25643
+ /** Detail steps that produced at least one result on the clip — a step that never fired measured nothing. */
25644
+ stepsFired: array(string()).readonly(),
25645
+ warmupMs: number(),
25646
+ ramp: array(NodeBenchRampStepSchema).readonly()
25647
+ })]);
25648
+ /**
25649
+ * What a result was measured ON. A result whose fingerprint no longer matches
25650
+ * the node no longer beats the table.
25651
+ */
25652
+ var NodeBenchFingerprintSchema = object({
25653
+ pipelineVersion: string().nullable(),
25654
+ cpuModel: string().nullable(),
25655
+ ramGb: number().nullable(),
25656
+ os: string().nullable(),
25657
+ /** Per device: the pool the cells ran on (runtime + tuning). */
25658
+ pools: record(string(), object({
25659
+ runtime: string(),
25660
+ numWorkers: number(),
25661
+ concurrency: number(),
25662
+ batchMode: string()
25663
+ })).default({})
25664
+ });
25665
+ /** The frames the run used. */
25666
+ var NodeBenchClipSchema = object({
25667
+ /** `camstack-bench-v1` or `reference-images` (the fallback when the clip is not reachable). */
25668
+ id: string(),
25669
+ revision: string().nullable(),
25670
+ frames: number(),
25671
+ width: number(),
25672
+ height: number()
25673
+ });
25674
+ var NodeBenchRunnerInputSchema = object({
25675
+ runId: string().min(1),
25676
+ devices: array(NodeBenchmarkDevicePlanSchema).min(1),
25677
+ phases: array(NodeBenchmarkPhaseSchema).min(1),
25678
+ /** The full detail step tree root for the `pipeline` measurement is built on the node from these ids. */
25679
+ steps: array(string()).default([]),
25680
+ fpsPerStream: number().int().min(1).max(30),
25681
+ /** The runner stops on its own past this instant, whatever the hub does. */
25682
+ deadlineAtMs: number(),
25683
+ settleSec: number().min(0).max(60).default(NODE_BENCHMARK_DEFAULTS.settleSec),
25684
+ measureSec: number().min(2).max(300).default(NODE_BENCHMARK_DEFAULTS.measureSec),
25685
+ keepDownloadedModels: boolean().default(false)
25686
+ });
25687
+ var NodeBenchRunnerStateSchema = _enum([
25688
+ "running",
25689
+ "done",
25690
+ "failed",
25691
+ "aborted"
25692
+ ]);
25693
+ var NodeBenchRunnerStatusSchema = object({
25694
+ runId: string(),
25695
+ nodeId: string(),
25696
+ state: NodeBenchRunnerStateSchema,
25697
+ progress: NodeBenchProgressSchema.nullable(),
25698
+ /** Every finished cell so far — a run stopped half way keeps what it measured. */
25699
+ cells: array(NodeBenchCellSchema).readonly(),
25700
+ fingerprint: NodeBenchFingerprintSchema.nullable(),
25701
+ clip: NodeBenchClipSchema.nullable(),
25702
+ /** Cameras seen running on the node during the run (they share its pools). */
25703
+ activeCameraIds: array(number()).readonly(),
25704
+ /** Models the run downloaded and then deleted (not installed before). */
25705
+ deletedModels: array(string()).readonly(),
25706
+ error: string().nullable(),
25707
+ startedAtMs: number(),
25708
+ finishedAtMs: number().nullable()
25709
+ });
25710
+ var NodeBenchmarkStateSchema = _enum([
25711
+ "draining",
25712
+ "measuring",
25713
+ "restoring",
25714
+ "done",
25715
+ "failed",
25716
+ "aborted"
25717
+ ]);
25718
+ /** Why a run ended. */
25719
+ var NodeBenchmarkEndReasonSchema = _enum([
25720
+ "completed",
25721
+ "operator-abort",
25722
+ "deadline",
25723
+ "node-lost",
25724
+ "runner-lost",
25725
+ "hub-restart",
25726
+ "drain-timeout",
25727
+ "failed"
25728
+ ]);
25729
+ var NodeBenchmarkRunSchema = object({
25730
+ runId: string(),
25731
+ nodeId: string(),
25732
+ state: NodeBenchmarkStateSchema,
25733
+ plan: NodeBenchmarkPlanSchema,
25734
+ startedAtMs: number(),
25735
+ deadlineAtMs: number(),
25736
+ finishedAtMs: number().nullable(),
25737
+ endReason: NodeBenchmarkEndReasonSchema.nullable(),
25738
+ error: string().nullable(),
25739
+ /** Cameras moved off the node for the run. */
25740
+ moved: array(number()).readonly(),
25741
+ /** Cameras that stayed (their only frame source is the node). */
25742
+ staying: array(number()).readonly(),
25743
+ /** Something else ran on the node's pools during the run. */
25744
+ contaminated: boolean(),
25745
+ progress: NodeBenchProgressSchema.nullable(),
25746
+ resultIds: array(string()).readonly()
25747
+ });
25748
+ /** `getNodeBenchmarkStatus`: the active run (or the last one), and whether benchmark mode is on. */
25749
+ var NodeBenchmarkStatusSchema = object({
25750
+ /** The node the cluster is in benchmark mode for; null = none. */
25751
+ modeNodeId: string().nullable(),
25752
+ run: NodeBenchmarkRunSchema.nullable()
25753
+ });
25754
+ /**
25755
+ * One stored measurement — the only authority Auto tune and the automatic
25756
+ * shares read measured capacity from. Written by the orchestrator when a run
25757
+ * ends, never by anyone else.
25758
+ */
25759
+ var NodeBenchmarkResultSchema = object({
25760
+ id: string(),
25761
+ runId: string(),
25762
+ nodeId: string(),
25763
+ cell: NodeBenchCellSchema,
25764
+ fpsPerStream: number(),
25765
+ fingerprint: NodeBenchFingerprintSchema.nullable(),
25766
+ clip: NodeBenchClipSchema.nullable(),
25767
+ /** Other work shared the node's pools (a camera that could not move, or the hub's own duties). */
25768
+ contaminated: boolean(),
25769
+ stayingCameras: array(number()).readonly(),
25770
+ /** The run ended early; the cell itself completed. */
25771
+ partialRun: boolean(),
25772
+ measuredAtMs: number()
25773
+ });
25774
+ var ListNodeBenchmarkResultsInputSchema = object({
25775
+ nodeId: string().optional(),
25776
+ deviceKey: string().optional()
25777
+ });
25778
+ /** A result with its standing today: does it still beat the table? */
25779
+ var NodeBenchmarkResultViewSchema = NodeBenchmarkResultSchema.extend({
25780
+ /** `fresh` beats the table; `stale` falls back to it; `superseded` = a newer row covers the same cell. */
25781
+ standing: _enum([
25782
+ "fresh",
25783
+ "stale",
25784
+ "superseded"
25785
+ ]),
25786
+ staleWhy: _enum([
25787
+ "age",
25788
+ "runtime",
25789
+ "pool-tuning"
25790
+ ]).nullable()
25791
+ });
25792
+ object({
25793
+ runId: string(),
25794
+ nodeId: string(),
25795
+ startedAtMs: number(),
25796
+ deadlineAtMs: number(),
25797
+ plan: NodeBenchmarkPlanSchema,
25798
+ moved: array(number()).readonly(),
25799
+ staying: array(number()).readonly()
25800
+ });
25801
+ /** Candidate detectors per device, for the plan editor. */
25802
+ var NodeBenchmarkCandidatesSchema = object({
25803
+ nodeId: string(),
25804
+ reachable: boolean(),
25805
+ devices: array(object({
25806
+ deviceKey: string(),
25807
+ enabled: boolean(),
25808
+ available: boolean(),
25809
+ /** Ordered: what Auto tune would pick first, then the rest of the family by accuracy. */
25810
+ suggested: array(string()).readonly(),
25811
+ /** Every root detector the device has a build for. */
25812
+ all: array(string()).readonly(),
25813
+ /** The model the device runs now, when pinned. */
25814
+ currentModelId: string().nullable()
25815
+ })).readonly(),
25816
+ /** Detail steps the node's catalog offers under the root (for the `pipeline` measurement). */
25817
+ steps: array(object({
25818
+ id: string(),
25819
+ name: string(),
25820
+ slot: string()
25821
+ })).readonly()
25822
+ });
24278
25823
  object({
24279
25824
  activeCameras: number(),
24280
25825
  throttledCameras: number(),
@@ -25403,7 +26948,16 @@ method(RunnerCameraConfigSchema, object({ success: literal(true) }), { kind: "mu
25403
26948
  }), ParkedTrackFrameSchema.nullable()), method(object({
25404
26949
  deviceId: number(),
25405
26950
  trackId: string()
25406
- }), object({ released: number().int().nonnegative() }), { kind: "mutation" });
26951
+ }), object({ released: number().int().nonnegative() }), { kind: "mutation" }), method(NodeBenchRunnerInputSchema, object({
26952
+ accepted: literal(true),
26953
+ runId: string()
26954
+ }), {
26955
+ kind: "mutation",
26956
+ auth: "admin"
26957
+ }), method(object({ runId: string() }), NodeBenchRunnerStatusSchema.nullable(), { auth: "admin" }), method(object({ runId: string() }), object({ aborted: boolean() }), {
26958
+ kind: "mutation",
26959
+ auth: "admin"
26960
+ });
25407
26961
  var CameraPipelineConfigSchema = object({
25408
26962
  engine: PipelineEngineChoiceSchema.optional(),
25409
26963
  steps: array(PipelineStepInputSchema).readonly(),
@@ -26042,6 +27596,21 @@ method(object({
26042
27596
  }), method(PlacementStatsInputSchema, PlacementStatsSchema, { auth: "admin" }), method(SuggestSharesInputSchema, SuggestSharesResultSchema, { auth: "admin" }), method(_void(), EffectiveSharesSchema, { auth: "admin" }), method(SetShareSourceInputSchema, object({ success: literal(true) }), {
26043
27597
  kind: "mutation",
26044
27598
  auth: "admin"
27599
+ }), method(NodeBenchmarkPlanSchema, NodeBenchmarkPreflightSchema, { auth: "admin" }), method(NodeBenchmarkPlanSchema, discriminatedUnion("kind", [object({
27600
+ kind: literal("started"),
27601
+ runId: string()
27602
+ }), object({
27603
+ kind: literal("refused"),
27604
+ preflight: NodeBenchmarkPreflightSchema
27605
+ })]), {
27606
+ kind: "mutation",
27607
+ auth: "admin"
27608
+ }), method(_void(), NodeBenchmarkStatusSchema, { auth: "admin" }), method(object({ runId: string() }), object({ aborted: boolean() }), {
27609
+ kind: "mutation",
27610
+ auth: "admin"
27611
+ }), method(object({ nodeId: string() }), NodeBenchmarkCandidatesSchema, { auth: "admin" }), method(ListNodeBenchmarkResultsInputSchema, array(NodeBenchmarkResultViewSchema).readonly(), { auth: "admin" }), method(object({ id: string() }), object({ deleted: boolean() }), {
27612
+ kind: "mutation",
27613
+ auth: "admin"
26045
27614
  }), method(object({ deviceId: number() }), CameraPipelineSettingsSchema.nullable()), method(object({
26046
27615
  deviceId: number(),
26047
27616
  addonId: string(),
@@ -32261,6 +33830,9 @@ var CreateIntegrationInputSchema = object({
32261
33830
  enabled: boolean().optional(),
32262
33831
  info: record(string(), unknown()).optional(),
32263
33832
  settings: record(string(), unknown()).optional(),
33833
+ /** Keys of `settings` the form's schema declares secret (by type) — kept in
33834
+ * the keychain, not the table (D787). */
33835
+ secretKeys: array(string()).optional(),
32264
33836
  skipRestart: boolean().optional()
32265
33837
  });
32266
33838
  var UpdateIntegrationInputSchema = object({
@@ -32284,7 +33856,9 @@ method(_void(), array(IntegrationWithStateSchema)), method(object({ id: string()
32284
33856
  auth: "admin"
32285
33857
  }), method(object({ id: string() }), record(string(), unknown()), { auth: "admin" }), method(object({
32286
33858
  id: string(),
32287
- settings: record(string(), unknown())
33859
+ settings: record(string(), unknown()),
33860
+ /** Keys the form's schema declares secret (by type) — keychain-stored (D787). */
33861
+ secretKeys: array(string()).optional()
32288
33862
  }), object({ success: boolean() }), {
32289
33863
  kind: "mutation",
32290
33864
  auth: "admin"
@@ -40447,7 +42021,8 @@ var BaseDevice = class {
40447
42021
  this.role = options.role;
40448
42022
  this.parentDeviceId = ctx.parentDeviceId;
40449
42023
  const seedData = ctx.persistedConfig ?? {};
40450
- this.config = DeviceConfig.fromSchema(schema, (data) => ctx.persistConfig(data), seedData, ({ droppedKeys, issues }) => {
42024
+ const declaredSecretPaths = collectZodSecretPaths(schema);
42025
+ this.config = DeviceConfig.fromSchema(schema, (data) => ctx.persistConfig(data, { secretConfigPaths: declaredSecretPaths }), seedData, ({ droppedKeys, issues }) => {
40451
42026
  ctx.logger.warn("Device config recovery: dropping invalid persisted fields", {
40452
42027
  tags: {
40453
42028
  deviceId: ctx.id,
@@ -44136,6 +45711,90 @@ Object.freeze({
44136
45711
  addonId: null,
44137
45712
  access: "create"
44138
45713
  },
45714
+ "keychain.delete": {
45715
+ capName: "keychain",
45716
+ capScope: "system",
45717
+ addonId: null,
45718
+ access: "delete"
45719
+ },
45720
+ "keychain.getState": {
45721
+ capName: "keychain",
45722
+ capScope: "system",
45723
+ addonId: null,
45724
+ access: "view"
45725
+ },
45726
+ "keychain.listMeta": {
45727
+ capName: "keychain",
45728
+ capScope: "system",
45729
+ addonId: null,
45730
+ access: "view"
45731
+ },
45732
+ "keychain.put": {
45733
+ capName: "keychain",
45734
+ capScope: "system",
45735
+ addonId: null,
45736
+ access: "create"
45737
+ },
45738
+ "keychain.resolve": {
45739
+ capName: "keychain",
45740
+ capScope: "system",
45741
+ addonId: null,
45742
+ access: "view"
45743
+ },
45744
+ "keychainAdmin.deleteOrphans": {
45745
+ capName: "keychain-admin",
45746
+ capScope: "system",
45747
+ addonId: null,
45748
+ access: "delete"
45749
+ },
45750
+ "keychainAdmin.downloadRecoveryKey": {
45751
+ capName: "keychain-admin",
45752
+ capScope: "system",
45753
+ addonId: null,
45754
+ access: "create"
45755
+ },
45756
+ "keychainAdmin.listAudit": {
45757
+ capName: "keychain-admin",
45758
+ capScope: "system",
45759
+ addonId: null,
45760
+ access: "view"
45761
+ },
45762
+ "keychainAdmin.listSecrets": {
45763
+ capName: "keychain-admin",
45764
+ capScope: "system",
45765
+ addonId: null,
45766
+ access: "view"
45767
+ },
45768
+ "keychainAdmin.purgeRetiredKeys": {
45769
+ capName: "keychain-admin",
45770
+ capScope: "system",
45771
+ addonId: null,
45772
+ access: "delete"
45773
+ },
45774
+ "keychainAdmin.resetKeychain": {
45775
+ capName: "keychain-admin",
45776
+ capScope: "system",
45777
+ addonId: null,
45778
+ access: "delete"
45779
+ },
45780
+ "keychainAdmin.reveal": {
45781
+ capName: "keychain-admin",
45782
+ capScope: "system",
45783
+ addonId: null,
45784
+ access: "create"
45785
+ },
45786
+ "keychainAdmin.rotateMasterKey": {
45787
+ capName: "keychain-admin",
45788
+ capScope: "system",
45789
+ addonId: null,
45790
+ access: "create"
45791
+ },
45792
+ "keychainAdmin.status": {
45793
+ capName: "keychain-admin",
45794
+ capScope: "system",
45795
+ addonId: null,
45796
+ access: "view"
45797
+ },
44139
45798
  "lawnMowerControl.dock": {
44140
45799
  capName: "lawn-mower-control",
44141
45800
  capScope: "device",
@@ -45510,6 +47169,18 @@ Object.freeze({
45510
47169
  addonId: null,
45511
47170
  access: "create"
45512
47171
  },
47172
+ "pipelineAnalytics.addRetrainFrameFromRecording": {
47173
+ capName: "pipeline-analytics",
47174
+ capScope: "device",
47175
+ addonId: null,
47176
+ access: "create"
47177
+ },
47178
+ "pipelineAnalytics.addRetrainFramesToCollection": {
47179
+ capName: "pipeline-analytics",
47180
+ capScope: "device",
47181
+ addonId: null,
47182
+ access: "create"
47183
+ },
45513
47184
  "pipelineAnalytics.applyDeviceSettingsPatch": {
45514
47185
  capName: "pipeline-analytics",
45515
47186
  capScope: "device",
@@ -45558,12 +47229,24 @@ Object.freeze({
45558
47229
  addonId: null,
45559
47230
  access: "view"
45560
47231
  },
47232
+ "pipelineAnalytics.createRetrainCollection": {
47233
+ capName: "pipeline-analytics",
47234
+ capScope: "device",
47235
+ addonId: null,
47236
+ access: "create"
47237
+ },
45561
47238
  "pipelineAnalytics.deleteDeviceEvents": {
45562
47239
  capName: "pipeline-analytics",
45563
47240
  capScope: "device",
45564
47241
  addonId: null,
45565
47242
  access: "delete"
45566
47243
  },
47244
+ "pipelineAnalytics.deleteRetrainCollection": {
47245
+ capName: "pipeline-analytics",
47246
+ capScope: "device",
47247
+ addonId: null,
47248
+ access: "delete"
47249
+ },
45567
47250
  "pipelineAnalytics.deleteTracks": {
45568
47251
  capName: "pipeline-analytics",
45569
47252
  capScope: "device",
@@ -45768,6 +47451,24 @@ Object.freeze({
45768
47451
  addonId: null,
45769
47452
  access: "view"
45770
47453
  },
47454
+ "pipelineAnalytics.listRetrainAssistProfiles": {
47455
+ capName: "pipeline-analytics",
47456
+ capScope: "device",
47457
+ addonId: null,
47458
+ access: "view"
47459
+ },
47460
+ "pipelineAnalytics.listRetrainCollectionFrames": {
47461
+ capName: "pipeline-analytics",
47462
+ capScope: "device",
47463
+ addonId: null,
47464
+ access: "view"
47465
+ },
47466
+ "pipelineAnalytics.listRetrainCollections": {
47467
+ capName: "pipeline-analytics",
47468
+ capScope: "device",
47469
+ addonId: null,
47470
+ access: "view"
47471
+ },
45771
47472
  "pipelineAnalytics.listRetrainFrames": {
45772
47473
  capName: "pipeline-analytics",
45773
47474
  capScope: "device",
@@ -45816,6 +47517,12 @@ Object.freeze({
45816
47517
  addonId: null,
45817
47518
  access: "create"
45818
47519
  },
47520
+ "pipelineAnalytics.proposeRetrainAnnotationsWithLlm": {
47521
+ capName: "pipeline-analytics",
47522
+ capScope: "device",
47523
+ addonId: null,
47524
+ access: "create"
47525
+ },
45819
47526
  "pipelineAnalytics.pruneEvents": {
45820
47527
  capName: "pipeline-analytics",
45821
47528
  capScope: "device",
@@ -45870,6 +47577,18 @@ Object.freeze({
45870
47577
  addonId: null,
45871
47578
  access: "create"
45872
47579
  },
47580
+ "pipelineAnalytics.removeRetrainFrameFromCollection": {
47581
+ capName: "pipeline-analytics",
47582
+ capScope: "device",
47583
+ addonId: null,
47584
+ access: "delete"
47585
+ },
47586
+ "pipelineAnalytics.renameRetrainCollection": {
47587
+ capName: "pipeline-analytics",
47588
+ capScope: "device",
47589
+ addonId: null,
47590
+ access: "create"
47591
+ },
45873
47592
  "pipelineAnalytics.restageRetrainTrack": {
45874
47593
  capName: "pipeline-analytics",
45875
47594
  capScope: "device",
@@ -46158,6 +47877,12 @@ Object.freeze({
46158
47877
  addonId: null,
46159
47878
  access: "view"
46160
47879
  },
47880
+ "pipelineOrchestrator.abortNodeBenchmark": {
47881
+ capName: "pipeline-orchestrator",
47882
+ capScope: "system",
47883
+ addonId: null,
47884
+ access: "create"
47885
+ },
46161
47886
  "pipelineOrchestrator.applyAutoTune": {
46162
47887
  capName: "pipeline-orchestrator",
46163
47888
  capScope: "system",
@@ -46182,6 +47907,12 @@ Object.freeze({
46182
47907
  addonId: null,
46183
47908
  access: "create"
46184
47909
  },
47910
+ "pipelineOrchestrator.deleteNodeBenchmarkResult": {
47911
+ capName: "pipeline-orchestrator",
47912
+ capScope: "system",
47913
+ addonId: null,
47914
+ access: "delete"
47915
+ },
46185
47916
  "pipelineOrchestrator.getAgentLoad": {
46186
47917
  capName: "pipeline-orchestrator",
46187
47918
  capScope: "system",
@@ -46290,6 +48021,24 @@ Object.freeze({
46290
48021
  addonId: null,
46291
48022
  access: "view"
46292
48023
  },
48024
+ "pipelineOrchestrator.getNodeBenchmarkCandidates": {
48025
+ capName: "pipeline-orchestrator",
48026
+ capScope: "system",
48027
+ addonId: null,
48028
+ access: "view"
48029
+ },
48030
+ "pipelineOrchestrator.getNodeBenchmarkPreflight": {
48031
+ capName: "pipeline-orchestrator",
48032
+ capScope: "system",
48033
+ addonId: null,
48034
+ access: "view"
48035
+ },
48036
+ "pipelineOrchestrator.getNodeBenchmarkStatus": {
48037
+ capName: "pipeline-orchestrator",
48038
+ capScope: "system",
48039
+ addonId: null,
48040
+ access: "view"
48041
+ },
46293
48042
  "pipelineOrchestrator.getNodeInferenceDevices": {
46294
48043
  capName: "pipeline-orchestrator",
46295
48044
  capScope: "system",
@@ -46332,6 +48081,12 @@ Object.freeze({
46332
48081
  addonId: null,
46333
48082
  access: "view"
46334
48083
  },
48084
+ "pipelineOrchestrator.listNodeBenchmarkResults": {
48085
+ capName: "pipeline-orchestrator",
48086
+ capScope: "system",
48087
+ addonId: null,
48088
+ access: "view"
48089
+ },
46335
48090
  "pipelineOrchestrator.pauseForStorageMigration": {
46336
48091
  capName: "pipeline-orchestrator",
46337
48092
  capScope: "system",
@@ -46476,6 +48231,12 @@ Object.freeze({
46476
48231
  addonId: null,
46477
48232
  access: "create"
46478
48233
  },
48234
+ "pipelineOrchestrator.startNodeBenchmark": {
48235
+ capName: "pipeline-orchestrator",
48236
+ capScope: "system",
48237
+ addonId: null,
48238
+ access: "create"
48239
+ },
46479
48240
  "pipelineOrchestrator.suggestShares": {
46480
48241
  capName: "pipeline-orchestrator",
46481
48242
  capScope: "system",
@@ -46494,6 +48255,12 @@ Object.freeze({
46494
48255
  addonId: null,
46495
48256
  access: "create"
46496
48257
  },
48258
+ "pipelineRunner.abortNodeBench": {
48259
+ capName: "pipeline-runner",
48260
+ capScope: "system",
48261
+ addonId: null,
48262
+ access: "create"
48263
+ },
46497
48264
  "pipelineRunner.attachCamera": {
46498
48265
  capName: "pipeline-runner",
46499
48266
  capScope: "system",
@@ -46542,6 +48309,12 @@ Object.freeze({
46542
48309
  addonId: null,
46543
48310
  access: "view"
46544
48311
  },
48312
+ "pipelineRunner.getNodeBenchStatus": {
48313
+ capName: "pipeline-runner",
48314
+ capScope: "system",
48315
+ addonId: null,
48316
+ access: "view"
48317
+ },
46545
48318
  "pipelineRunner.getParkedTrackFrame": {
46546
48319
  capName: "pipeline-runner",
46547
48320
  capScope: "system",
@@ -46584,6 +48357,12 @@ Object.freeze({
46584
48357
  addonId: null,
46585
48358
  access: "create"
46586
48359
  },
48360
+ "pipelineRunner.startNodeBench": {
48361
+ capName: "pipeline-runner",
48362
+ capScope: "system",
48363
+ addonId: null,
48364
+ access: "create"
48365
+ },
46587
48366
  "plateGallery.assignPlate": {
46588
48367
  capName: "plate-gallery",
46589
48368
  capScope: "system",
@@ -51513,6 +53292,11 @@ Object.freeze({
51513
53292
  form: "single",
51514
53293
  optional: false
51515
53294
  }],
53295
+ "pipelineAnalytics.addRetrainFrameFromRecording": [{
53296
+ name: "deviceId",
53297
+ form: "single",
53298
+ optional: false
53299
+ }],
51516
53300
  "pipelineAnalytics.applyDeviceSettingsPatch": [{
51517
53301
  name: "deviceId",
51518
53302
  form: "single",
@@ -51703,6 +53487,11 @@ Object.freeze({
51703
53487
  form: "single",
51704
53488
  optional: false
51705
53489
  }],
53490
+ "pipelineAnalytics.proposeRetrainAnnotationsWithLlm": [{
53491
+ name: "deviceId",
53492
+ form: "single",
53493
+ optional: false
53494
+ }],
51706
53495
  "pipelineAnalytics.pruneEventsBefore": [{
51707
53496
  name: "deviceId",
51708
53497
  form: "single",