@camstack/addon-provider-unifi 0.2.123 → 0.2.124

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/addon.js +1845 -56
  2. package/dist/addon.mjs +1845 -56
  3. package/package.json +1 -1
package/dist/addon.mjs CHANGED
@@ -1,4 +1,4 @@
1
- //#region ../types/dist/event-category-B_0XEcLF.mjs
1
+ //#region ../types/dist/event-category-DaIZi00R.mjs
2
2
  var EventCategory = /* @__PURE__ */ function(EventCategory) {
3
3
  EventCategory["SystemBoot"] = "system.boot";
4
4
  EventCategory["SystemAddonsReady"] = "system.addons-ready";
@@ -77,6 +77,13 @@ var EventCategory = /* @__PURE__ */ function(EventCategory) {
77
77
  */
78
78
  EventCategory["AddonLoadFailed"] = "addon.load-failed";
79
79
  /**
80
+ * A keychain value was stored or removed (D787). Carries the ref, its
81
+ * owner and the new version — NEVER the value. A process holding the ref
82
+ * drops its cached copy and the owning `BaseAddon` re-resolves its config.
83
+ * Telemetry (D8): a process that misses it still revalidates by version.
84
+ */
85
+ EventCategory["KeychainChanged"] = "keychain.changed";
86
+ /**
80
87
  * Addon recovered from a previous failure. Emitted when an addon
81
88
  * transitions from `failed` back to `healthy` (typically via the
82
89
  * monitor's auto-retry loop, or after manual `addons.retryLoad`).
@@ -5369,7 +5376,7 @@ var ZodIssueCode = {
5369
5376
  var ZodFirstPartyTypeKind;
5370
5377
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
5371
5378
  //#endregion
5372
- //#region ../types/dist/sleep-B0JG7-_F.mjs
5379
+ //#region ../types/dist/sleep-Cr5YOk3m.mjs
5373
5380
  /**
5374
5381
  * The audio chunk plane's byte format, and the ONE expansion from a coded
5375
5382
  * window to float samples (D455).
@@ -5448,6 +5455,97 @@ function buildAlawTable() {
5448
5455
  }
5449
5456
  buildUlawTable();
5450
5457
  buildAlawTable();
5458
+ /** Is this field's stored value a credential? */
5459
+ function isSecretConfigField(field) {
5460
+ if (field.type === "password") return true;
5461
+ return "secret" in field && field.secret === true;
5462
+ }
5463
+ /**
5464
+ * Is this field's value stored in the KEYCHAIN (D787)? Every secret field is,
5465
+ * by its TYPE, unless it opts out with `storage: 'inline'` — never by its name.
5466
+ */
5467
+ function isKeychainStoredField(field) {
5468
+ if (!isSecretConfigField(field)) return false;
5469
+ if (field.type === "textarea" && field.isJson === true) return false;
5470
+ return !("storage" in field && field.storage === "inline");
5471
+ }
5472
+ /**
5473
+ * What a settings blob holds where a secret used to be.
5474
+ *
5475
+ * A keychain-stored field never holds its value. It holds a self-describing
5476
+ * MARKER, `{"$secret":"secret://…","v":1}` — an object, never a string, so no
5477
+ * code can mistake it for a credential and no form can send it to a camera as
5478
+ * a password. The empty state is `null` / absent, never `''`.
5479
+ *
5480
+ * The same shapes travel to and from the admin UI:
5481
+ *
5482
+ * - read: `hydrateSchema` hands a secret field a {@link SecretFieldView}
5483
+ * (`{ $secret, v, set: true }`) or `null` — the browser learns whether a
5484
+ * value is set, never the value.
5485
+ * - write: an untouched field submits the view back unchanged (KEEP); a typed
5486
+ * value is a plain non-empty string (CHANGE); the Clear button submits
5487
+ * {@link SECRET_CLEAR} (CLEAR). `''`, `null` and the legacy redaction tokens
5488
+ * are KEEP — an empty string is what a defaults-fallback pushes back, and
5489
+ * treating it as "clear" is how a save destroyed a stored credential before.
5490
+ *
5491
+ * Pure and browser-safe.
5492
+ */
5493
+ var SECRET_CLEAR = { $secretClear: true };
5494
+ /** The `'***'` token D634 redaction writes for non-admins. */
5495
+ var LEGACY_DEVICE_REDACTION = "***";
5496
+ function isRecord$1(value) {
5497
+ return typeof value === "object" && value !== null && !Array.isArray(value);
5498
+ }
5499
+ function makeSecretMarker(ref) {
5500
+ return {
5501
+ $secret: ref,
5502
+ v: 1
5503
+ };
5504
+ }
5505
+ /** A stored marker: an object whose `$secret` is a non-empty string. */
5506
+ function isSecretMarker(value) {
5507
+ if (!isRecord$1(value)) return false;
5508
+ const ref = value["$secret"];
5509
+ return typeof ref === "string" && ref.length > 0;
5510
+ }
5511
+ function isSecretClear(value) {
5512
+ return isRecord$1(value) && value["$secretClear"] === true;
5513
+ }
5514
+ /**
5515
+ * The UI view of a stored secret field value: a marker becomes "set", inline
5516
+ * plaintext becomes "set (inline)", nothing becomes `null`. A value never
5517
+ * survives this function.
5518
+ */
5519
+ function toSecretFieldView(stored) {
5520
+ if (isSecretMarker(stored)) return {
5521
+ $secret: stored.$secret,
5522
+ v: 1,
5523
+ set: true
5524
+ };
5525
+ if (typeof stored === "string" && stored.length > 0) return {
5526
+ $secret: null,
5527
+ v: 1,
5528
+ set: true,
5529
+ inline: true
5530
+ };
5531
+ return null;
5532
+ }
5533
+ /**
5534
+ * Classify an incoming value for a secret path. Only a non-empty string that is
5535
+ * not a redaction token sets a value; only {@link SECRET_CLEAR} clears.
5536
+ * Everything else — a marker (ours or anyone's), a UI view, `''`, `null`,
5537
+ * `undefined`, a redaction token, a non-string — keeps what is stored.
5538
+ */
5539
+ function classifySecretWrite(incoming) {
5540
+ if (isSecretClear(incoming)) return { kind: "clear" };
5541
+ if (typeof incoming !== "string") return { kind: "keep" };
5542
+ if (incoming.length === 0) return { kind: "keep" };
5543
+ if (incoming === "__camstack_redacted__" || incoming === LEGACY_DEVICE_REDACTION) return { kind: "keep" };
5544
+ return {
5545
+ kind: "set",
5546
+ value: incoming
5547
+ };
5548
+ }
5451
5549
  Object.fromEntries([
5452
5550
  {
5453
5551
  id: "overview",
@@ -5619,33 +5717,19 @@ Object.fromEntries([
5619
5717
  function isValuelessField(field) {
5620
5718
  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";
5621
5719
  }
5622
- /**
5623
- * Merge a `ConfigUISchema` with a raw `values` record into a
5624
- * `ConfigUISchemaWithValues`. Used by every `get*Settings` backend endpoint
5625
- * before returning to the admin UI. Groups are walked recursively.
5626
- *
5627
- * For each leaf field:
5628
- * - structural fields (`separator`, `info`, `button`) pass through unchanged
5629
- * - other fields get `value = values[key] ?? field.default ?? null`
5630
- *
5631
- * Unknown keys in `values` (keys not declared in the schema) are silently
5632
- * ignored — they don't contribute to the output. Missing keys fall back to
5633
- * the schema default or `null`. This mirrors the old backend behaviour where
5634
- * `FormBuilder` rendered `values[key] ?? field.default`.
5635
- */
5636
- function hydrateSchema(schema, values) {
5720
+ function hydrateSchema(schema, values, options = {}) {
5637
5721
  return {
5638
5722
  ...schema.tabs ? { tabs: [...schema.tabs] } : {},
5639
5723
  sections: schema.sections.map((section) => ({
5640
5724
  ...section,
5641
- fields: section.fields.map((field) => hydrateField(field, values))
5725
+ fields: section.fields.map((field) => hydrateField(field, values, options))
5642
5726
  }))
5643
5727
  };
5644
5728
  }
5645
- function hydrateField(field, values) {
5729
+ function hydrateField(field, values, options) {
5646
5730
  if (isValuelessField(field)) return field;
5647
5731
  if (field.type === "group") {
5648
- const hydratedChildren = field.fields.map((child) => hydrateField(child, values));
5732
+ const hydratedChildren = field.fields.map((child) => hydrateField(child, values, options));
5649
5733
  return {
5650
5734
  ...field,
5651
5735
  fields: hydratedChildren
@@ -5654,7 +5738,7 @@ function hydrateField(field, values) {
5654
5738
  if (field.type === "sub-tabs") {
5655
5739
  const hydratedTabs = field.tabs.map((tab) => ({
5656
5740
  ...tab,
5657
- fields: tab.fields.map((child) => hydrateField(child, values))
5741
+ fields: tab.fields.map((child) => hydrateField(child, values, options))
5658
5742
  }));
5659
5743
  return {
5660
5744
  ...field,
@@ -5664,6 +5748,33 @@ function hydrateField(field, values) {
5664
5748
  const key = field.key;
5665
5749
  const storedValue = Object.prototype.hasOwnProperty.call(values, key) ? values[key] : void 0;
5666
5750
  const defaultValue = field.default;
5751
+ const asView = (v) => isSecretMarker(v) || options.inlineSecretsAsViews === true && v !== void 0;
5752
+ if (isKeychainStoredField(field) && asView(storedValue)) return {
5753
+ ...field,
5754
+ value: toSecretFieldView(storedValue)
5755
+ };
5756
+ if (isKeychainStoredField(field) && options.inlineSecretsAsViews === true) return {
5757
+ ...field,
5758
+ value: null
5759
+ };
5760
+ if (field.type === "editable-array" && Array.isArray(storedValue)) {
5761
+ const secretItemKeys = field.itemFields.filter((item) => "key" in item && isKeychainStoredField(item)).map((item) => "key" in item ? item.key : "");
5762
+ if (secretItemKeys.length > 0) {
5763
+ const rows = storedValue.map((row) => {
5764
+ if (row === null || typeof row !== "object" || Array.isArray(row)) return row;
5765
+ const out = { ...row };
5766
+ for (const k of secretItemKeys) {
5767
+ const v = Reflect.get(row, k);
5768
+ if (asView(v)) out[k] = toSecretFieldView(v);
5769
+ }
5770
+ return out;
5771
+ });
5772
+ return {
5773
+ ...field,
5774
+ value: rows
5775
+ };
5776
+ }
5777
+ }
5667
5778
  if (field.multiple) {
5668
5779
  const stored = Array.isArray(storedValue) ? storedValue : storedValue !== void 0 && storedValue !== null ? [storedValue] : [];
5669
5780
  const itemFallback = field.multiple.itemDefault !== void 0 ? field.multiple.itemDefault : defaultValue !== void 0 ? defaultValue : typeOf(field) === "string" ? "" : null;
@@ -5906,6 +6017,431 @@ function projectStore(store, perNodeKeys, nodeId) {
5906
6017
  }
5907
6018
  return out;
5908
6019
  }
6020
+ var GLOBAL_SCOPE = { kind: "global" };
6021
+ /** The scope every addon-wide (not per-node, not per-device) setting lives in. */
6022
+ function globalSecretScope() {
6023
+ return GLOBAL_SCOPE;
6024
+ }
6025
+ function encodeSegment(value) {
6026
+ return encodeURIComponent(value);
6027
+ }
6028
+ /**
6029
+ * The field path of a value inside an array item, addressed by the item's id:
6030
+ * `arrayItemFieldPath('providers', 'authentik', 'clientSecret')` →
6031
+ * `providers[authentik].clientSecret`.
6032
+ */
6033
+ function arrayItemFieldPath(arrayKey, itemId, fieldKey) {
6034
+ return `${arrayKey}[${encodeSegment(itemId)}].${fieldKey}`;
6035
+ }
6036
+ /** A write to a secret path could not be stored in the keychain, so it was refused. */
6037
+ var KeychainWriteRefusedError = class extends Error {
6038
+ fieldPath;
6039
+ constructor(fieldPath, cause) {
6040
+ super(`secret "${fieldPath}" was not saved: the keychain could not store it (${cause instanceof Error ? cause.message : String(cause)}). Nothing was written.`);
6041
+ this.fieldPath = fieldPath;
6042
+ this.name = "KeychainWriteRefusedError";
6043
+ }
6044
+ };
6045
+ var KEEP = { kind: "keep" };
6046
+ function isRecord(value) {
6047
+ return typeof value === "object" && value !== null && !Array.isArray(value);
6048
+ }
6049
+ function defaultMintId() {
6050
+ return globalThis.crypto.randomUUID();
6051
+ }
6052
+ /** Every marker ref anywhere under `value`. */
6053
+ function collectSecretMarkerRefs(value, out = []) {
6054
+ if (isSecretMarker(value)) {
6055
+ out.push(value.$secret);
6056
+ return out;
6057
+ }
6058
+ if (Array.isArray(value)) for (const item of value) collectSecretMarkerRefs(item, out);
6059
+ else if (isRecord(value)) for (const child of Object.values(value)) collectSecretMarkerRefs(child, out);
6060
+ return out;
6061
+ }
6062
+ async function storedValueEquals(secrets, marker, candidate) {
6063
+ const resolved = (await secrets.resolve([marker.$secret]))[marker.$secret];
6064
+ return resolved?.kind === "value" && resolved.value === candidate;
6065
+ }
6066
+ async function writeLeaf(ctx, incoming, stored, fieldPath) {
6067
+ const intent = classifySecretWrite(incoming);
6068
+ const ref = ctx.secrets.ref(ctx.scope, fieldPath);
6069
+ const storedIsOurs = isSecretMarker(stored) && stored.$secret === ref;
6070
+ if (intent.kind === "keep") return KEEP;
6071
+ if (intent.kind === "set" && !ctx.operatorWrite && typeof stored === "string" && stored === intent.value) return KEEP;
6072
+ if (intent.kind === "clear") {
6073
+ if (storedIsOurs) ctx.deletes.push(ref);
6074
+ return {
6075
+ kind: "value",
6076
+ value: null
6077
+ };
6078
+ }
6079
+ if (storedIsOurs && await storedValueEquals(ctx.secrets, stored, intent.value)) return {
6080
+ kind: "value",
6081
+ value: stored
6082
+ };
6083
+ try {
6084
+ await ctx.secrets.put(ref, intent.value);
6085
+ } catch (err) {
6086
+ throw new KeychainWriteRefusedError(fieldPath, err);
6087
+ }
6088
+ return {
6089
+ kind: "value",
6090
+ value: makeSecretMarker(ref)
6091
+ };
6092
+ }
6093
+ /** Apply a member result onto `out`: KEEP restores the stored member, or removes it. */
6094
+ function applyMember(out, key, result, storedParent) {
6095
+ if (result.kind === "value") {
6096
+ out[key] = result.value;
6097
+ return;
6098
+ }
6099
+ if (Object.prototype.hasOwnProperty.call(storedParent, key)) out[key] = storedParent[key];
6100
+ else delete out[key];
6101
+ }
6102
+ async function writeMembers(ctx, children, incoming, stored, pathOf) {
6103
+ const out = { ...incoming };
6104
+ for (const [member, node] of children) applyMember(out, member, await writeNode(ctx, node, incoming[member], stored[member], pathOf(member)), stored);
6105
+ return out;
6106
+ }
6107
+ function rowId(row, idKey) {
6108
+ const raw = row[idKey];
6109
+ if (typeof raw === "string" && raw.length > 0) return raw;
6110
+ if (typeof raw === "number" && Number.isFinite(raw)) return String(raw);
6111
+ return null;
6112
+ }
6113
+ async function writeArray(ctx, node, incoming, stored, fieldPath) {
6114
+ const storedRows = Array.isArray(stored) ? stored.filter(isRecord) : [];
6115
+ if (!Array.isArray(incoming)) {
6116
+ ctx.deletes.push(...collectSecretMarkerRefs(storedRows));
6117
+ return {
6118
+ kind: "value",
6119
+ value: incoming
6120
+ };
6121
+ }
6122
+ const storedById = /* @__PURE__ */ new Map();
6123
+ for (const row of storedRows) {
6124
+ const id = rowId(row, node.idKey);
6125
+ if (id !== null) storedById.set(id, row);
6126
+ }
6127
+ const kept = /* @__PURE__ */ new Set();
6128
+ const rows = [];
6129
+ for (const row of incoming) {
6130
+ if (!isRecord(row)) {
6131
+ rows.push(row);
6132
+ continue;
6133
+ }
6134
+ const id = rowId(row, node.idKey) ?? ctx.mintId();
6135
+ kept.add(id);
6136
+ const withId = {
6137
+ ...row,
6138
+ [node.idKey]: row[node.idKey] ?? id
6139
+ };
6140
+ if (rowId(withId, node.idKey) === null) withId[node.idKey] = id;
6141
+ const storedRow = storedById.get(id) ?? {};
6142
+ rows.push(await writeMembers(ctx, node.item, withId, storedRow, (member) => arrayItemFieldPath(fieldPath, id, member)));
6143
+ }
6144
+ for (const [id, row] of storedById) if (!kept.has(id)) ctx.deletes.push(...collectSecretMarkerRefs(row));
6145
+ return {
6146
+ kind: "value",
6147
+ value: rows
6148
+ };
6149
+ }
6150
+ async function writeNode(ctx, node, incoming, stored, fieldPath) {
6151
+ switch (node.kind) {
6152
+ case "leaf": return writeLeaf(ctx, incoming, stored, fieldPath);
6153
+ case "array": return writeArray(ctx, node, incoming, stored, fieldPath);
6154
+ case "object": {
6155
+ if (!isRecord(incoming)) {
6156
+ if (incoming === void 0) return KEEP;
6157
+ ctx.deletes.push(...collectSecretMarkerRefs(stored));
6158
+ return {
6159
+ kind: "value",
6160
+ value: incoming
6161
+ };
6162
+ }
6163
+ const storedObj = isRecord(stored) ? stored : {};
6164
+ return {
6165
+ kind: "value",
6166
+ value: await writeMembers(ctx, node.children, incoming, storedObj, (m) => `${fieldPath}.${m}`)
6167
+ };
6168
+ }
6169
+ }
6170
+ }
6171
+ /** Split a perNode-scoped key (`key@nodeId`). */
6172
+ function splitNodeKey(key) {
6173
+ const at = key.indexOf("@");
6174
+ return at <= 0 ? {
6175
+ base: key,
6176
+ nodeId: null
6177
+ } : {
6178
+ base: key.slice(0, at),
6179
+ nodeId: key.slice(at + 1)
6180
+ };
6181
+ }
6182
+ /** Rewrite a settings patch so no secret value reaches the blob. See the file doc. */
6183
+ async function transformSecretWrite(input) {
6184
+ const deletes = [];
6185
+ const base = {
6186
+ secrets: input.secrets,
6187
+ mintId: input.mintId ?? defaultMintId,
6188
+ deletes,
6189
+ operatorWrite: input.operatorWrite === true
6190
+ };
6191
+ const out = {};
6192
+ for (const [key, incoming] of Object.entries(input.patch)) {
6193
+ const { base: baseKey, nodeId } = splitNodeKey(key);
6194
+ const node = input.tree.get(baseKey);
6195
+ if (node === void 0) {
6196
+ out[key] = incoming;
6197
+ continue;
6198
+ }
6199
+ const scope = nodeId !== null && nodeId.length > 0 ? {
6200
+ kind: "node",
6201
+ nodeId
6202
+ } : input.scope ?? globalSecretScope();
6203
+ const result = await writeNode({
6204
+ ...base,
6205
+ scope
6206
+ }, node, incoming, input.stored[key], baseKey);
6207
+ if (result.kind === "value") out[key] = result.value;
6208
+ }
6209
+ return {
6210
+ patch: out,
6211
+ afterWrite: async () => {
6212
+ if (deletes.length === 0) return { orphaned: [] };
6213
+ try {
6214
+ await input.secrets.delete([...new Set(deletes)]);
6215
+ return { orphaned: [] };
6216
+ } catch {
6217
+ return { orphaned: [...new Set(deletes)] };
6218
+ }
6219
+ }
6220
+ };
6221
+ }
6222
+ /**
6223
+ * Replace every marker in `value` with its keychain value. Returns the SAME
6224
+ * reference when there is no marker (no allocation, no keychain call).
6225
+ */
6226
+ async function resolveSecretMarkers(value, secrets) {
6227
+ const refs = collectSecretMarkerRefs(value);
6228
+ if (refs.length === 0) return {
6229
+ value,
6230
+ unresolved: []
6231
+ };
6232
+ const answers = await secrets.resolve(refs);
6233
+ const unresolved = [];
6234
+ for (const ref of new Set(refs)) {
6235
+ const answer = answers[ref];
6236
+ if (answer === void 0) unresolved.push({
6237
+ ref,
6238
+ reason: "not-initialized"
6239
+ });
6240
+ else if (answer.kind === "unavailable") unresolved.push({
6241
+ ref,
6242
+ reason: answer.reason
6243
+ });
6244
+ else if (answer.kind === "missing" || answer.kind === "forbidden") unresolved.push({
6245
+ ref,
6246
+ reason: answer.kind
6247
+ });
6248
+ }
6249
+ const substitute = (v) => {
6250
+ if (isSecretMarker(v)) {
6251
+ const answer = answers[v.$secret];
6252
+ return answer?.kind === "value" ? {
6253
+ keep: true,
6254
+ value: answer.value
6255
+ } : {
6256
+ keep: false,
6257
+ value: void 0
6258
+ };
6259
+ }
6260
+ if (Array.isArray(v)) {
6261
+ const items = [];
6262
+ for (const item of v) {
6263
+ const s = substitute(item);
6264
+ if (s.keep) items.push(s.value);
6265
+ }
6266
+ return {
6267
+ keep: true,
6268
+ value: items
6269
+ };
6270
+ }
6271
+ if (isRecord(v)) {
6272
+ const out = {};
6273
+ for (const [k, child] of Object.entries(v)) {
6274
+ const s = substitute(child);
6275
+ if (s.keep) out[k] = s.value;
6276
+ }
6277
+ return {
6278
+ keep: true,
6279
+ value: out
6280
+ };
6281
+ }
6282
+ return {
6283
+ keep: true,
6284
+ value: v
6285
+ };
6286
+ };
6287
+ return {
6288
+ value: substitute(value).value,
6289
+ unresolved
6290
+ };
6291
+ }
6292
+ function touchesTree(tree, patch) {
6293
+ if (tree.size === 0) return false;
6294
+ for (const key of Object.keys(patch)) {
6295
+ const at = key.indexOf("@");
6296
+ if (tree.has(at > 0 ? key.slice(0, at) : key)) return true;
6297
+ }
6298
+ return false;
6299
+ }
6300
+ /** The blob as stored now; a failed read REFUSES the write instead of guessing. */
6301
+ async function readStoredAddonBlob(raw) {
6302
+ const threeWay = raw.readAddonStoreResult;
6303
+ if (threeWay === void 0) return raw.readAddonStore();
6304
+ const result = await threeWay.call(raw);
6305
+ if (result.kind === "failed") throw new Error(`settings write refused: the stored blob could not be read (${result.error})`);
6306
+ return result.kind === "missing" ? {} : result.value;
6307
+ }
6308
+ function createSecretAwareSettings(raw, opts) {
6309
+ const chains = /* @__PURE__ */ new Map();
6310
+ const serialize = (key, fn) => {
6311
+ const next = (chains.get(key) ?? Promise.resolve()).then(fn, fn);
6312
+ const tail = next.catch(() => void 0);
6313
+ chains.set(key, tail);
6314
+ tail.then(() => {
6315
+ if (chains.get(key) === tail) chains.delete(key);
6316
+ });
6317
+ return next;
6318
+ };
6319
+ const write = async (chainKey, tree, scope, patch, readStored, rawWrite) => {
6320
+ if (!touchesTree(tree, patch)) return rawWrite(patch);
6321
+ return serialize(chainKey, async () => {
6322
+ const stored = await readStored();
6323
+ const result = await transformSecretWrite({
6324
+ tree,
6325
+ secrets: opts.secrets,
6326
+ patch,
6327
+ stored,
6328
+ ...scope !== void 0 ? { scope } : {},
6329
+ operatorWrite: opts.isOperatorWrite?.() === true
6330
+ });
6331
+ if (Object.keys(result.patch).length > 0) await rawWrite(result.patch);
6332
+ const { orphaned } = await result.afterWrite();
6333
+ if (orphaned.length > 0) opts.onOrphaned(orphaned);
6334
+ });
6335
+ };
6336
+ const wrapped = {
6337
+ writeAddonStore: (patch) => write("addon", opts.addonTree(), void 0, patch, () => readStoredAddonBlob(raw), (p) => raw.writeAddonStore(p)),
6338
+ writeDeviceStore: (deviceId, patch) => write(`device:${deviceId}`, opts.deviceTree(), {
6339
+ kind: "device",
6340
+ deviceId
6341
+ }, patch, () => raw.readDeviceStore(deviceId), (p) => raw.writeDeviceStore(deviceId, p))
6342
+ };
6343
+ return new Proxy(raw, { get(target, prop, receiver) {
6344
+ if (prop === "writeAddonStore") return wrapped.writeAddonStore;
6345
+ if (prop === "writeDeviceStore") return wrapped.writeDeviceStore;
6346
+ const value = Reflect.get(target, prop, receiver);
6347
+ return typeof value === "function" ? value.bind(target) : value;
6348
+ } });
6349
+ }
6350
+ /** The context the addon sees: identical, except that its settings writes are secret-aware. */
6351
+ function withSecretAwareSettings(context, opts) {
6352
+ const raw = context.settings;
6353
+ if (raw === void 0) return context;
6354
+ const settings = createSecretAwareSettings(raw, opts);
6355
+ return new Proxy(context, { get(target, prop, receiver) {
6356
+ if (prop === "settings") return settings;
6357
+ return Reflect.get(target, prop, receiver);
6358
+ } });
6359
+ }
6360
+ var LEAF = { kind: "leaf" };
6361
+ var DEFAULT_ITEM_ID_KEY = "id";
6362
+ function collectFields(fields, out) {
6363
+ for (const field of fields) {
6364
+ if (field.type === "group") {
6365
+ collectFields(field.fields, out);
6366
+ continue;
6367
+ }
6368
+ if (field.type === "sub-tabs") {
6369
+ for (const tab of field.tabs) collectFields(tab.fields, out);
6370
+ continue;
6371
+ }
6372
+ if (field.type === "editable-array") {
6373
+ const item = /* @__PURE__ */ new Map();
6374
+ for (const itemField of field.itemFields) if ("key" in itemField && isKeychainStoredField(itemField)) item.set(itemField.key, LEAF);
6375
+ if (item.size > 0) out.set(field.key, {
6376
+ kind: "array",
6377
+ idKey: field.itemIdKey ?? DEFAULT_ITEM_ID_KEY,
6378
+ item
6379
+ });
6380
+ continue;
6381
+ }
6382
+ if (!("key" in field) || typeof field.key !== "string") continue;
6383
+ if (isKeychainStoredField(field)) out.set(field.key, LEAF);
6384
+ }
6385
+ }
6386
+ /** The secret tree a settings schema declares. */
6387
+ function secretTreeFromSchema(schema) {
6388
+ const out = /* @__PURE__ */ new Map();
6389
+ if (schema === null) return out;
6390
+ for (const section of schema.sections) collectFields(section.fields, out);
6391
+ return out;
6392
+ }
6393
+ /** Parse `a.b[id].c` into segments; throws on a malformed path (a declaration bug). */
6394
+ function parseSecretStatePath(path) {
6395
+ const segments = [];
6396
+ for (const raw of path.split(".")) {
6397
+ const m = /^([^[\]]+)(?:\[([^[\]]+)\])?$/.exec(raw);
6398
+ if (m === null || m[1] === void 0) throw new Error(`secretStatePaths: malformed path "${path}"`);
6399
+ segments.push(m[2] !== void 0 ? {
6400
+ key: m[1],
6401
+ idKey: m[2]
6402
+ } : { key: m[1] });
6403
+ }
6404
+ if (segments.length === 0) throw new Error(`secretStatePaths: empty path`);
6405
+ if (segments[segments.length - 1]?.idKey !== void 0) throw new Error(`secretStatePaths: "${path}" ends on an array — name the member that is secret`);
6406
+ return segments;
6407
+ }
6408
+ function insert(into, segments) {
6409
+ const [head, ...rest] = segments;
6410
+ if (head === void 0) return;
6411
+ if (rest.length === 0) {
6412
+ into.set(head.key, LEAF);
6413
+ return;
6414
+ }
6415
+ const existing = into.get(head.key);
6416
+ if (head.idKey !== void 0) {
6417
+ const item = new Map(existing?.kind === "array" ? existing.item : []);
6418
+ insert(item, rest);
6419
+ into.set(head.key, {
6420
+ kind: "array",
6421
+ idKey: head.idKey,
6422
+ item
6423
+ });
6424
+ return;
6425
+ }
6426
+ const children = new Map(existing?.kind === "object" ? existing.children : []);
6427
+ insert(children, rest);
6428
+ into.set(head.key, {
6429
+ kind: "object",
6430
+ children
6431
+ });
6432
+ }
6433
+ /** Add hidden-state paths (`secretStatePaths`) to a schema-derived tree. */
6434
+ function mergeSecretStatePaths(tree, paths) {
6435
+ if (paths.length === 0) return tree;
6436
+ const out = new Map(tree);
6437
+ for (const path of paths) insert(out, parseSecretStatePath(path));
6438
+ return out;
6439
+ }
6440
+ /** First retry of a secret the keychain could not serve; doubles to {@link SECRET_RETRY_MAX_MS}. */
6441
+ var SECRET_RETRY_FIRST_MS = 5e3;
6442
+ var SECRET_RETRY_MAX_MS = 5 * 6e4;
6443
+ /** Coalesces a burst of `keychain.changed` events into one re-resolve. */
6444
+ var SECRET_CHANGE_DEBOUNCE_MS = 250;
5909
6445
  /**
5910
6446
  * Base class for CamStack addons. Eliminates settings boilerplate:
5911
6447
  *
@@ -5975,6 +6511,25 @@ var BaseAddon = class {
5975
6511
  settingsStoreReady = false;
5976
6512
  /** Default config values. Provided via constructor. */
5977
6513
  defaults;
6514
+ /**
6515
+ * Hidden-state paths that hold secrets (D787) — values the addon writes
6516
+ * itself (`updateGlobalSettings`, `state()`) that no form field declares.
6517
+ * Stored in the keychain exactly like a `password` field. Syntax:
6518
+ * `'snapshotSigningKey'`, `'identity.pincode'`, `'tokens[userId].accessToken'`
6519
+ * (`key[<id field>]` addresses array items by id, never by index).
6520
+ */
6521
+ secretStatePaths = [];
6522
+ _addonSecretTree = null;
6523
+ _deviceSecretTree = null;
6524
+ /** Refs the last resolved config pointed at — a change to one re-resolves. */
6525
+ _configSecretRefs = /* @__PURE__ */ new Set();
6526
+ _unresolvedSecrets = [];
6527
+ _secretRetryTimer = null;
6528
+ _secretRetryDelayMs = SECRET_RETRY_FIRST_MS;
6529
+ _secretChangeTimer = null;
6530
+ _secretChangeUnsub = null;
6531
+ /** >0 while an OPERATOR's settings write is being applied. */
6532
+ _operatorWriteDepth = 0;
5978
6533
  constructor(defaults) {
5979
6534
  this.defaults = defaults;
5980
6535
  this._config = { ...defaults };
@@ -6010,8 +6565,18 @@ var BaseAddon = class {
6010
6565
  return this._config;
6011
6566
  }
6012
6567
  async initialize(context) {
6013
- this._ctx = context;
6568
+ const secrets = context.secrets;
6569
+ this._ctx = secrets !== void 0 ? withSecretAwareSettings(context, {
6570
+ secrets,
6571
+ addonTree: () => this.addonSecretTree(),
6572
+ deviceTree: () => this.deviceSecretTree(),
6573
+ onOrphaned: (refs) => context.logger.warn("keychain refs dropped by a settings write could not be deleted", { meta: { refs: [...refs] } }),
6574
+ isOperatorWrite: () => this._operatorWriteDepth > 0
6575
+ }) : context;
6014
6576
  await this.resolveConfig();
6577
+ if (secrets !== void 0) this._secretChangeUnsub = secrets.onChange((ref) => {
6578
+ if (this._configSecretRefs.has(ref)) this.scheduleSecretReresolve(SECRET_CHANGE_DEBOUNCE_MS);
6579
+ });
6015
6580
  const result = await this.onInitialize();
6016
6581
  this.emitLifecycle(EventCategory.AddonStarted);
6017
6582
  const normalized = normalizeAddonInitResult(result);
@@ -6044,6 +6609,12 @@ var BaseAddon = class {
6044
6609
  */
6045
6610
  async onHubReachable() {}
6046
6611
  async shutdown() {
6612
+ this._secretChangeUnsub?.();
6613
+ this._secretChangeUnsub = null;
6614
+ if (this._secretRetryTimer !== null) clearTimeout(this._secretRetryTimer);
6615
+ if (this._secretChangeTimer !== null) clearTimeout(this._secretChangeTimer);
6616
+ this._secretRetryTimer = null;
6617
+ this._secretChangeTimer = null;
6047
6618
  this.emitLifecycle(EventCategory.AddonStopped);
6048
6619
  if (this.autoEmitReadiness) this.emitReadinessForProviders("down");
6049
6620
  await this.onShutdown();
@@ -6122,7 +6693,7 @@ var BaseAddon = class {
6122
6693
  return hydrateSchema(schema, overlay ? {
6123
6694
  ...projected,
6124
6695
  ...overlay
6125
- } : projected);
6696
+ } : projected, { inlineSecretsAsViews: true });
6126
6697
  }
6127
6698
  /**
6128
6699
  * The integration-level view of this addon's settings: exactly the sections
@@ -6171,7 +6742,7 @@ var BaseAddon = class {
6171
6742
  return hydrateSchema({
6172
6743
  ...schema,
6173
6744
  sections
6174
- }, projected);
6745
+ }, projected, { inlineSecretsAsViews: true });
6175
6746
  }
6176
6747
  /**
6177
6748
  * The raw addon store PROJECTED onto the target node's bare per-node keys:
@@ -6225,18 +6796,50 @@ var BaseAddon = class {
6225
6796
  value: result.value[key]
6226
6797
  };
6227
6798
  }
6799
+ /**
6800
+ * The OPERATOR's write — a settings form or an admin API call, dispatched by
6801
+ * the kernel. Identical to {@link updateGlobalSettings}, except that a secret
6802
+ * the operator sends is stored as sent even when it equals a pre-keychain
6803
+ * inline value: the operator re-entering a password is a change, an addon
6804
+ * writing back what it read is not (D787).
6805
+ */
6806
+ async updateGlobalSettingsAsOperator(patch, nodeId) {
6807
+ this._operatorWriteDepth++;
6808
+ try {
6809
+ await this.applyGlobalPatch(patch, nodeId);
6810
+ } finally {
6811
+ this._operatorWriteDepth--;
6812
+ }
6813
+ }
6228
6814
  async updateGlobalSettings(patch, nodeId) {
6815
+ await this.applyGlobalPatch(patch, nodeId);
6816
+ }
6817
+ /**
6818
+ * REMOVE stored secrets — their keychain values and their markers (D787).
6819
+ *
6820
+ * Writing `''` to a secret field KEEPS what is stored (an empty string is
6821
+ * what a defaults fallback writes back, and it must never destroy a
6822
+ * credential), so code that means "forget this token" says so here. Without
6823
+ * a keychain (an older kernel) it writes `''`, as such code always did.
6824
+ */
6825
+ async clearSecrets(keys, nodeId) {
6826
+ const tree = this.addonSecretTree();
6827
+ const keychain = this._ctx?.secrets !== void 0;
6828
+ const patch = {};
6829
+ for (const key of keys) patch[key] = keychain && tree.has(key) ? SECRET_CLEAR : "";
6830
+ await this.applyGlobalPatch(patch, nodeId);
6831
+ }
6832
+ async applyGlobalPatch(barePatch, nodeId) {
6229
6833
  const keys = this.perNodeKeys();
6230
6834
  const localNode = normalizeNodeId(this._ctx?.kernel?.localNodeId);
6231
6835
  const target = normalizeNodeId(nodeId ?? this._ctx?.kernel?.localNodeId);
6232
- const barePatch = patch;
6233
6836
  const scoped = keys.size > 0 ? scopePatch(barePatch, keys, target) : barePatch;
6234
6837
  await this._ctx?.settings?.writeAddonStore(scoped);
6235
6838
  if (target !== localNode) return;
6236
6839
  await this.resolveConfig();
6237
6840
  await this.onConfigChanged();
6238
6841
  this.emitLifecycle(EventCategory.AddonUpdated, { level: "global" });
6239
- this.maybeAutoRestart(patch, this.globalSettingsSchema());
6842
+ this.maybeAutoRestart(Object.keys(barePatch), this.globalSettingsSchema());
6240
6843
  }
6241
6844
  /**
6242
6845
  * The set of field keys the global settings schema declares `perNode: true`
@@ -6261,7 +6864,7 @@ var BaseAddon = class {
6261
6864
  * time to return its response before the addon is torn down and
6262
6865
  * re-initialised by `AddonRegistryService.restartAddon`.
6263
6866
  */
6264
- maybeAutoRestart(patch, schema) {
6867
+ maybeAutoRestart(patchKeys, schema) {
6265
6868
  if (!schema) return;
6266
6869
  const restartKeys = /* @__PURE__ */ new Set();
6267
6870
  for (const section of schema.sections) for (const field of section.fields) {
@@ -6269,13 +6872,13 @@ var BaseAddon = class {
6269
6872
  if (field.requiresRestart) restartKeys.add(field.key);
6270
6873
  }
6271
6874
  if (restartKeys.size === 0) return;
6272
- if (!Object.keys(patch).some((k) => restartKeys.has(k))) return;
6875
+ if (!patchKeys.some((k) => restartKeys.has(k))) return;
6273
6876
  const ctx = this._ctx;
6274
6877
  if (!ctx) return;
6275
6878
  const addonId = ctx.id;
6276
6879
  setImmediate(() => {
6277
6880
  ctx.api.addons?.restartAddon?.mutate({ addonId }).then(() => {
6278
- ctx.logger.info("addon auto-restart triggered by restart-required setting change", { meta: { changedFields: Object.keys(patch).filter((k) => restartKeys.has(k)) } });
6881
+ ctx.logger.info("addon auto-restart triggered by restart-required setting change", { meta: { changedFields: patchKeys.filter((k) => restartKeys.has(k)) } });
6279
6882
  }).catch((err) => {
6280
6883
  ctx.logger.error("addon auto-restart failed", { meta: { error: err instanceof Error ? err.message : String(err) } });
6281
6884
  });
@@ -6284,7 +6887,7 @@ var BaseAddon = class {
6284
6887
  async getDeviceSettings(deviceId) {
6285
6888
  const schema = this.deviceSettingsSchema();
6286
6889
  if (!schema) return { sections: [] };
6287
- return hydrateSchema(schema, await this._ctx?.settings?.readDeviceStore(deviceId) ?? {});
6890
+ return hydrateSchema(schema, await this._ctx?.settings?.readDeviceStore(deviceId) ?? {}, { inlineSecretsAsViews: true });
6288
6891
  }
6289
6892
  async updateDeviceSettings(deviceId, patch) {
6290
6893
  await this._ctx?.settings?.writeDeviceStore(deviceId, patch);
@@ -6414,7 +7017,7 @@ var BaseAddon = class {
6414
7017
  * selection at boot (absent scoped key ⇒ the constructor default wins).
6415
7018
  */
6416
7019
  async resolveConfig() {
6417
- const stored = await this.readAddonStoreWithRetry();
7020
+ const stored = await this.resolveStoredSecrets(await this.readAddonStoreWithRetry());
6418
7021
  const perNode = this.perNodeKeys();
6419
7022
  const localNode = normalizeNodeId(this._ctx?.kernel?.localNodeId);
6420
7023
  const resolved = { ...this.defaults };
@@ -6439,7 +7042,7 @@ var BaseAddon = class {
6439
7042
  key,
6440
7043
  schema,
6441
7044
  fallback,
6442
- read: () => this.readAddonStoreWithRetry(),
7045
+ read: async () => this.resolveStoredSecrets(await this.readAddonStoreWithRetry()),
6443
7046
  write: async (patch) => {
6444
7047
  await this._ctx?.settings?.writeAddonStore(patch);
6445
7048
  },
@@ -6456,7 +7059,7 @@ var BaseAddon = class {
6456
7059
  key,
6457
7060
  schema,
6458
7061
  fallback,
6459
- read: async () => await this._ctx?.settings?.readDeviceStore(deviceId) ?? {},
7062
+ read: async () => this.resolveStoredSecrets(await this._ctx?.settings?.readDeviceStore(deviceId) ?? {}, false),
6460
7063
  write: async (patch) => {
6461
7064
  await this._ctx?.settings?.writeDeviceStore(deviceId, patch);
6462
7065
  },
@@ -6468,6 +7071,70 @@ var BaseAddon = class {
6468
7071
  } })
6469
7072
  });
6470
7073
  }
7074
+ /** The addon store's secret tree: schema fields by TYPE, plus `secretStatePaths`. */
7075
+ addonSecretTree() {
7076
+ this._addonSecretTree ??= mergeSecretStatePaths(secretTreeFromSchema(this.globalSettingsSchema()), this.secretStatePaths);
7077
+ return this._addonSecretTree;
7078
+ }
7079
+ deviceSecretTree() {
7080
+ this._deviceSecretTree ??= secretTreeFromSchema(this.deviceSettingsSchema());
7081
+ return this._deviceSecretTree;
7082
+ }
7083
+ /**
7084
+ * Secrets of this addon's stored config that could not be resolved on the
7085
+ * last read, with why. Non-empty means the addon is running WITHOUT them —
7086
+ * an addon whose function needs one should report itself degraded rather
7087
+ * than start on an empty credential.
7088
+ */
7089
+ get unresolvedSecrets() {
7090
+ return this._unresolvedSecrets;
7091
+ }
7092
+ /**
7093
+ * Substitute every keychain marker in a stored blob with its value. With no
7094
+ * keychain (no `ctx.secrets`) or no marker, the blob comes back unchanged.
7095
+ * An unresolvable value is LEFT OUT (never `''`), logged by ref — never by
7096
+ * value — and, when the cause can pass, retried with backoff. Nothing is
7097
+ * ever written back from here.
7098
+ */
7099
+ async resolveStoredSecrets(blob, trackForConfig = true) {
7100
+ const secrets = this._ctx?.secrets;
7101
+ if (secrets === void 0) return blob;
7102
+ const refs = collectSecretMarkerRefs(blob);
7103
+ if (trackForConfig) this._configSecretRefs = new Set(refs);
7104
+ if (refs.length === 0) {
7105
+ if (trackForConfig) this._unresolvedSecrets = [];
7106
+ return blob;
7107
+ }
7108
+ const { value, unresolved } = await resolveSecretMarkers(blob, secrets);
7109
+ if (trackForConfig) {
7110
+ this._unresolvedSecrets = unresolved;
7111
+ if (unresolved.length > 0) {
7112
+ this._ctx?.logger?.error?.("secret unavailable — running without it, will retry", { meta: { secrets: unresolved.map((u) => ({
7113
+ ref: u.ref,
7114
+ reason: u.reason
7115
+ })) } });
7116
+ if (unresolved.some((u) => u.reason !== "missing" && u.reason !== "forbidden")) {
7117
+ this.scheduleSecretReresolve(this._secretRetryDelayMs);
7118
+ this._secretRetryDelayMs = Math.min(this._secretRetryDelayMs * 2, SECRET_RETRY_MAX_MS);
7119
+ }
7120
+ } else this._secretRetryDelayMs = SECRET_RETRY_FIRST_MS;
7121
+ }
7122
+ return value;
7123
+ }
7124
+ /** Re-resolve the config (a keychain-only change, or a retry) and apply it. */
7125
+ scheduleSecretReresolve(delayMs) {
7126
+ const timerOf = delayMs === SECRET_CHANGE_DEBOUNCE_MS ? "_secretChangeTimer" : "_secretRetryTimer";
7127
+ if (this[timerOf] !== null) return;
7128
+ const timer = setTimeout(() => {
7129
+ this[timerOf] = null;
7130
+ if (this._ctx === null) return;
7131
+ this.resolveConfig().then(() => this.onConfigChanged()).catch((err) => {
7132
+ this._ctx?.logger?.error?.("re-resolving secrets failed", { meta: { error: err instanceof Error ? err.message : String(err) } });
7133
+ });
7134
+ }, delayMs);
7135
+ timer.unref?.();
7136
+ this[timerOf] = timer;
7137
+ }
6471
7138
  /**
6472
7139
  * Wrap `ctx.settings.readAddonStore()` with a short retry budget so a
6473
7140
  * transient settings-store outage (mid-restart of sqlite-settings, tsx-watch
@@ -7043,6 +7710,69 @@ method(object({ deviceId: number() }), array(StreamSourceEntrySchema)), method(o
7043
7710
  kind: "mutation",
7044
7711
  auth: "admin"
7045
7712
  }), method(object({ deviceId: number() }), unknown().nullable()), method(object({ deviceId: number() }), RawStateResultSchema.nullable(), { auth: "protected" });
7713
+ function defOf(schema) {
7714
+ return schema._zod?.def ?? {};
7715
+ }
7716
+ function declaredHere(schema) {
7717
+ return globalRegistry.get(schema)?.secret === true;
7718
+ }
7719
+ /** Wrapper kinds whose `innerType` is the field itself. */
7720
+ var WRAPPERS = new Set([
7721
+ "optional",
7722
+ "nullable",
7723
+ "default",
7724
+ "prefault",
7725
+ "catch",
7726
+ "readonly",
7727
+ "nonoptional"
7728
+ ]);
7729
+ /**
7730
+ * The schema layers that make up ONE field: the schema itself and every
7731
+ * wrapper below it (optional / default / nullable / readonly / catch), plus
7732
+ * both sides of a pipe (`z.preprocess` puts the real schema on `out`,
7733
+ * `.transform` on `in`).
7734
+ */
7735
+ function layersOf(schema) {
7736
+ const out = [];
7737
+ const queue = [schema];
7738
+ while (queue.length > 0) {
7739
+ const s = queue.shift();
7740
+ if (!s || out.includes(s)) continue;
7741
+ out.push(s);
7742
+ const def = defOf(s);
7743
+ if (def.type !== void 0 && WRAPPERS.has(def.type) && def.innerType) queue.push(def.innerType);
7744
+ if (def.type === "pipe") {
7745
+ if (def.in) queue.push(def.in);
7746
+ if (def.out) queue.push(def.out);
7747
+ }
7748
+ }
7749
+ return out;
7750
+ }
7751
+ /** True when any layer of this field declares `.meta({ secret: true })`. */
7752
+ function isZodSecret(schema) {
7753
+ return layersOf(schema).some(declaredHere);
7754
+ }
7755
+ /**
7756
+ * Every declared secret path in a config schema: dotted keys, `[]` for "each
7757
+ * element of this array" (`connection.password`, `rows[].token`). A declared
7758
+ * object or array is reported as one path and not descended into — everything
7759
+ * under it is secret.
7760
+ */
7761
+ function collectZodSecretPaths(schema, prefix = "") {
7762
+ if (isZodSecret(schema)) return prefix.length > 0 ? [prefix] : [];
7763
+ const paths = [];
7764
+ for (const layer of layersOf(schema)) {
7765
+ const def = defOf(layer);
7766
+ if (def.type === "object" && def.shape) for (const [key, child] of Object.entries(def.shape)) paths.push(...collectZodSecretPaths(child, prefix ? `${prefix}.${key}` : key));
7767
+ else if (def.type === "array" && def.element) paths.push(...collectZodSecretPaths(def.element, `${prefix}[]`));
7768
+ else if (def.type === "union" && def.options) for (const option of def.options) paths.push(...collectZodSecretPaths(option, prefix));
7769
+ else if (def.type === "intersection") {
7770
+ if (def.left) paths.push(...collectZodSecretPaths(def.left, prefix));
7771
+ if (def.right) paths.push(...collectZodSecretPaths(def.right, prefix));
7772
+ }
7773
+ }
7774
+ return [...new Set(paths)];
7775
+ }
7046
7776
  //#endregion
7047
7777
  //#region ../types/dist/err-msg-DX6i_MY4.mjs
7048
7778
  var DeviceType = /* @__PURE__ */ function(DeviceType) {
@@ -14073,6 +14803,196 @@ id: union([string(), number()]) }), {
14073
14803
  kind: "mutation",
14074
14804
  auth: "admin"
14075
14805
  });
14806
+ /**
14807
+ * `keychain` — the hub's encrypted store of secret values (D787).
14808
+ *
14809
+ * Settings blobs never hold a secret: they hold a marker
14810
+ * `{"$secret":"secret://<owner>/<scope>/<fieldPath>","v":1}` and the value
14811
+ * lives here, AES-256-GCM under a data key that a master key wraps. This cap
14812
+ * is the OWNER's door to its own values: every method is owner-checked
14813
+ * against the CALLER, never against anything the caller claims.
14814
+ *
14815
+ * Who the caller is: the transport stamps `callerAddonId` into the args of a
14816
+ * call that crossed a process (the parent `LocalChildRegistry` from the UDS
14817
+ * connection, the agent from its child's connection carried in
14818
+ * `$hub-cap-fwd`'s envelope). A stamp always overwrites; a wire call with no
14819
+ * stamp has its claim stripped. Only a hub in-process caller may state its own
14820
+ * identity — `ctx.secrets` does that with the addon id closed over. This is
14821
+ * identity against BUGS and misrouting, not against a malicious addon (every
14822
+ * runner is the same OS user): see the threat model in
14823
+ * `docs/design/2026-10-08-secrets-keychain.md`.
14824
+ *
14825
+ * `callerAddonId` is deliberately NOT in any input schema: the tRPC router
14826
+ * parses the input, so a session can never supply it, and the internal mount
14827
+ * floors every method to admin anyway (D240).
14828
+ *
14829
+ * Internal: addons reach it through `ctx.secrets`, never directly.
14830
+ */
14831
+ /** Why a value cannot be served right now. Never folded into "missing". */
14832
+ var KeychainUnavailableReasonSchema = _enum([
14833
+ "key-missing",
14834
+ "wrong-key",
14835
+ "key-file-unreadable",
14836
+ "store-unavailable",
14837
+ "not-initialized",
14838
+ "decrypt-failed"
14839
+ ]);
14840
+ var KeychainStateSchema = discriminatedUnion("state", [object({ state: literal("ready") }), object({
14841
+ state: literal("locked"),
14842
+ reason: KeychainUnavailableReasonSchema
14843
+ })]);
14844
+ var KeychainResolveEntrySchema = discriminatedUnion("kind", [
14845
+ object({
14846
+ kind: literal("value"),
14847
+ value: string(),
14848
+ version: number().int()
14849
+ }),
14850
+ object({ kind: literal("missing") }),
14851
+ object({
14852
+ kind: literal("unavailable"),
14853
+ reason: KeychainUnavailableReasonSchema
14854
+ }),
14855
+ object({ kind: literal("forbidden") })
14856
+ ]);
14857
+ var KeychainResolveResultSchema = record(string(), KeychainResolveEntrySchema);
14858
+ /** Metadata of one stored value — never the value. */
14859
+ var KeychainSecretMetaSchema = object({
14860
+ ref: string(),
14861
+ owner: string(),
14862
+ /** Formatted scope (`global`, `node/<id>`, `device/<id>`, …). */
14863
+ scope: string(),
14864
+ fieldPath: string(),
14865
+ version: number().int(),
14866
+ createdAt: number(),
14867
+ updatedAt: number(),
14868
+ /** `addon:<id>` | `user:<id>` | `system`. */
14869
+ updatedBy: string(),
14870
+ /** Coarse — written at most once an hour per ref. `null` = never read. */
14871
+ lastReadAt: number().nullable()
14872
+ });
14873
+ var RefListSchema = array(string().min(1)).max(512);
14874
+ method(object({
14875
+ ref: string().min(1),
14876
+ value: string().min(1)
14877
+ }), object({
14878
+ ref: string(),
14879
+ version: number().int()
14880
+ }), {
14881
+ kind: "mutation",
14882
+ auth: "admin"
14883
+ }), method(object({ refs: RefListSchema }), KeychainResolveResultSchema, { auth: "admin" }), method(object({ refs: RefListSchema }), object({ deleted: number().int() }), {
14884
+ kind: "mutation",
14885
+ auth: "admin"
14886
+ }), method(object({}), array(KeychainSecretMetaSchema).readonly(), { auth: "admin" }), method(object({}), KeychainStateSchema, { auth: "admin" });
14887
+ var KeychainKeySourceSchema = object({
14888
+ kind: _enum([
14889
+ "config-file",
14890
+ "previous-config-file",
14891
+ "platform",
14892
+ "default-file"
14893
+ ]),
14894
+ /** File sources only — a path is not a secret. */
14895
+ path: string().optional(),
14896
+ /**
14897
+ * True when a whole-volume backup of the data directory carries this key
14898
+ * next to the database it protects (the default file). The page warns.
14899
+ */
14900
+ sharesBackupWithDatabase: boolean()
14901
+ });
14902
+ var KeychainStatusSchema = object({
14903
+ keychain: KeychainStateSchema,
14904
+ /** The source of the master key in use; `null` while locked. */
14905
+ keySource: KeychainKeySourceSchema.nullable(),
14906
+ /** The source configured to be primary — differs from `keySource` while a rotation is pending. */
14907
+ configuredSource: KeychainKeySourceSchema,
14908
+ /** Short fingerprint of the master key in use (`HMAC(KEK, label)`, 16 hex). */
14909
+ fingerprint: string().nullable(),
14910
+ activeKeyId: string().nullable(),
14911
+ /**
14912
+ * The keychain unlocked with a NON-primary source: the configured primary
14913
+ * key is not the one that wraps the data key yet. `rotateMasterKey` moves it.
14914
+ */
14915
+ rotationPending: boolean(),
14916
+ /** Wrapped copies of the data key under a previous master key, kept until purged. */
14917
+ retiredWraps: number().int(),
14918
+ recoveryKeyDownloadedAt: number().nullable(),
14919
+ secretCount: number().int()
14920
+ });
14921
+ /**
14922
+ * Whether a stored value is still pointed at by its owner's settings.
14923
+ * `unknown` is a first-class answer: a scope whose blob could not be read is
14924
+ * never reported as an orphan (and never deleted as one).
14925
+ */
14926
+ var KeychainSecretUsageSchema = _enum([
14927
+ "in-use",
14928
+ "orphan",
14929
+ "unknown"
14930
+ ]);
14931
+ var KeychainAdminSecretSchema = KeychainSecretMetaSchema.extend({ usage: KeychainSecretUsageSchema });
14932
+ var KeychainAuditActionSchema = _enum([
14933
+ "put",
14934
+ "delete",
14935
+ "reveal",
14936
+ "rotate-master-key",
14937
+ "purge-retired-keys",
14938
+ "download-recovery-key",
14939
+ "delete-orphans",
14940
+ "reset",
14941
+ "initialize"
14942
+ ]);
14943
+ var KeychainAuditEntrySchema = object({
14944
+ id: string(),
14945
+ at: number(),
14946
+ action: KeychainAuditActionSchema,
14947
+ /** `addon:<id>` | `user:<id>` | `system`. */
14948
+ actor: string(),
14949
+ ref: string().nullable(),
14950
+ detail: string().nullable()
14951
+ });
14952
+ 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({
14953
+ value: string(),
14954
+ version: number().int()
14955
+ }), {
14956
+ kind: "mutation",
14957
+ auth: "admin",
14958
+ caller: "required"
14959
+ }), method(object({ refs: array(string().min(1)).max(1e3) }), object({
14960
+ deleted: array(string()).readonly(),
14961
+ kept: array(object({
14962
+ ref: string(),
14963
+ usage: KeychainSecretUsageSchema
14964
+ })).readonly()
14965
+ }), {
14966
+ kind: "mutation",
14967
+ auth: "admin",
14968
+ caller: "required"
14969
+ }), method(object({}), object({
14970
+ fingerprint: string(),
14971
+ keySource: KeychainKeySourceSchema
14972
+ }), {
14973
+ kind: "mutation",
14974
+ auth: "admin",
14975
+ caller: "required"
14976
+ }), method(object({}), object({ purged: number().int() }), {
14977
+ kind: "mutation",
14978
+ auth: "admin",
14979
+ caller: "required"
14980
+ }), method(object({}), object({
14981
+ key: string(),
14982
+ fingerprint: string(),
14983
+ keySource: KeychainKeySourceSchema
14984
+ }), {
14985
+ kind: "mutation",
14986
+ auth: "admin",
14987
+ caller: "required"
14988
+ }), method(object({ confirm: literal("RESET KEYCHAIN") }), object({
14989
+ archivedCollection: string().nullable(),
14990
+ archived: number().int()
14991
+ }), {
14992
+ kind: "mutation",
14993
+ auth: "admin",
14994
+ caller: "required"
14995
+ });
14076
14996
  method(_void(), object({
14077
14997
  id: string(),
14078
14998
  name: string(),
@@ -15411,7 +16331,11 @@ var DeviceRegisterPayloadSchema = object({
15411
16331
  var DeviceRemovePayloadSchema = object({ deviceId: number() });
15412
16332
  var DevicePersistConfigPayloadSchema = object({
15413
16333
  deviceId: number(),
15414
- data: record(string(), unknown())
16334
+ data: record(string(), unknown()),
16335
+ /** The paths the device's schema declares secret (D783), when the caller
16336
+ * knows them — those values are kept in the keychain, not the blob (D787).
16337
+ * Absent: the paths the device last reported at `registerDevice` apply. */
16338
+ secretConfigPaths: array(string()).optional()
15415
16339
  });
15416
16340
  /** What a migration actually did, per switch. `unreachable` is a first-class
15417
16341
  * answer: a camera that could not be asked is not a camera that was silenced. */
@@ -22428,8 +23352,23 @@ var RetrainMacroClassSchema = _enum([
22428
23352
  ]);
22429
23353
  /** A subject to learn, or a phantom to unlearn (taught by OMISSION). */
22430
23354
  var RetrainAnnotationKindSchema = _enum(["subject", "model_error"]);
22431
- /** Did a human draw this box, or did the assist propose it? */
22432
- var RetrainAnnotationSourceSchema = _enum(["operator", "assist"]);
23355
+ /**
23356
+ * Where a box came from. A machine-sourced box is a DRAFT on the page until
23357
+ * the operator confirms it; once saved it keeps its source as provenance.
23358
+ *
23359
+ * - `operator` — drawn by hand.
23360
+ * - `assist` — proposed by a detector run on the copy (the camera's own
23361
+ * model, or a larger teacher model).
23362
+ * - `pipeline` — the box the live pipeline actually drew on that frame, read
23363
+ * back from the track store (never a re-run).
23364
+ * - `llm` — proposed by a vision-capable LLM profile.
23365
+ */
23366
+ var RetrainAnnotationSourceSchema = _enum([
23367
+ "operator",
23368
+ "assist",
23369
+ "pipeline",
23370
+ "llm"
23371
+ ]);
22433
23372
  /** Normalised `[0,1]` rectangle against the FULL frame — the canonical form. */
22434
23373
  var RetrainBboxSchema = object({
22435
23374
  x: number(),
@@ -22447,7 +23386,8 @@ var RetrainBboxSchema = object({
22447
23386
  */
22448
23387
  var RetrainAnnotationSchema = object({
22449
23388
  id: string(),
22450
- trackId: string(),
23389
+ /** The frame's track. Absent on a recording still, which has none. */
23390
+ trackId: string().optional(),
22451
23391
  deviceId: number(),
22452
23392
  /** The COPY in retrain storage — never the source track's media key. */
22453
23393
  mediaKey: string(),
@@ -22496,13 +23436,47 @@ var RetrainFrameCandidateSchema = object({
22496
23436
  * fail, whatever became of the original. */
22497
23437
  copied: boolean()
22498
23438
  });
23439
+ /**
23440
+ * One box the live pipeline drew on a copied frame — what a correction starts
23441
+ * from. Derived when the frame is listed, from the track store: the subject
23442
+ * box recorded on the source media row when there is one, else the track
23443
+ * position nearest the frame's capture time. Never stored as an annotation
23444
+ * until the operator confirms it.
23445
+ */
23446
+ var RetrainPipelineBoxSchema = object({
23447
+ /** Normalised `[0,1]` against the full frame. */
23448
+ bbox: RetrainBboxSchema,
23449
+ macroClass: RetrainMacroClassSchema,
23450
+ label: string().optional(),
23451
+ subLabel: string().optional(),
23452
+ /** The detection score of the position used, when it was recorded. */
23453
+ score: number().optional(),
23454
+ /** The root model that produced the track, when it was recorded. */
23455
+ modelId: string().optional(),
23456
+ trackId: string(),
23457
+ /** `subject-box`: recorded on this very frame. `position`: the track's
23458
+ * position nearest the capture time, `deltaMs` away. */
23459
+ basis: _enum(["subject-box", "position"]),
23460
+ deltaMs: number()
23461
+ });
23462
+ /**
23463
+ * Where a retrain frame came from: a TRACK's stored media (copy-on-select),
23464
+ * or the RECORDING at an instant — the frame a model saw nothing in has no
23465
+ * track at all.
23466
+ */
23467
+ var RetrainFrameOriginSchema = _enum(["track", "recording"]);
22499
23468
  /** A frame the dataset OWNS: bytes copied at selection time. */
22500
23469
  var RetrainFrameSchema = object({
22501
23470
  frameId: string(),
22502
23471
  deviceId: number(),
22503
- trackId: string(),
22504
- /** Provenance only. It may already point at nothing — that is expected. */
22505
- sourceMediaId: number().int(),
23472
+ origin: RetrainFrameOriginSchema,
23473
+ /** The track it was copied from. Absent on a recording still. */
23474
+ trackId: string().optional(),
23475
+ /** Provenance only. It may already point at nothing — that is expected.
23476
+ * Absent on a recording still. */
23477
+ sourceMediaId: number().int().optional(),
23478
+ /** A recording still: the playhead instant it was taken at. */
23479
+ epochMs: number().optional(),
22506
23480
  sourceKind: MediaFileKindEnum,
22507
23481
  sizeBytes: number().int(),
22508
23482
  width: number().int(),
@@ -22513,7 +23487,12 @@ var RetrainFrameSchema = object({
22513
23487
  /** The operator's "every subject in this frame is boxed". Detector
22514
23488
  * evaluation keeps only complete frames: an unboxed subject would count as
22515
23489
  * a false positive. */
22516
- complete: boolean()
23490
+ complete: boolean(),
23491
+ /** The boxes the pipeline drew on this frame. Present on list answers;
23492
+ * empty when nothing the track store holds can be placed on it. */
23493
+ pipelineBoxes: array(RetrainPipelineBoxSchema).readonly().optional(),
23494
+ /** The named collections this frame belongs to. Present on list answers. */
23495
+ collectionIds: array(string()).readonly().optional()
22517
23496
  });
22518
23497
  /** Why a copy-on-select could not be honoured — named, never a silent skip. */
22519
23498
  var RetrainCopyRefusalSchema = _enum([
@@ -22544,6 +23523,8 @@ var RetrainFrameListSchema = object({
22544
23523
  var RetrainExportFilterSchema = object({
22545
23524
  deviceIds: array(number()).optional(),
22546
23525
  frameIds: array(string()).max(2e4).optional(),
23526
+ /** Only frames in at least one of these named collections. */
23527
+ collectionIds: array(string()).max(200).optional(),
22547
23528
  batchId: string().optional(),
22548
23529
  /** Only frames the operator marked complete (all subjects boxed). */
22549
23530
  completeOnly: boolean().optional()
@@ -22608,6 +23589,109 @@ var RetrainAssistResultSchema = discriminatedUnion("kind", [object({
22608
23589
  reason: string(),
22609
23590
  detail: string().optional()
22610
23591
  })]);
23592
+ /** A named set over the retrain corpus — membership only, it owns no pixels. */
23593
+ var RetrainCollectionSchema = object({
23594
+ id: string(),
23595
+ name: string(),
23596
+ createdAt: number(),
23597
+ frameCount: number().int()
23598
+ });
23599
+ var RetrainCollectionCreateResultSchema = discriminatedUnion("kind", [object({
23600
+ kind: literal("created"),
23601
+ collection: RetrainCollectionSchema
23602
+ }), object({
23603
+ kind: literal("refused"),
23604
+ reason: _enum(["empty-name", "duplicate-name"])
23605
+ })]);
23606
+ var RetrainCollectionRenameResultSchema = discriminatedUnion("kind", [object({
23607
+ kind: literal("renamed"),
23608
+ collection: RetrainCollectionSchema
23609
+ }), object({
23610
+ kind: literal("refused"),
23611
+ reason: _enum([
23612
+ "empty-name",
23613
+ "duplicate-name",
23614
+ "unknown-collection"
23615
+ ])
23616
+ })]);
23617
+ /**
23618
+ * The outcome of adding the frame at a recording instant. Every refusal is
23619
+ * named: `still-unavailable` (not recording, a gap, or an undecodable frame —
23620
+ * `detail` says which), `still-busy` (the recorder is at its decode bound; try
23621
+ * again), `unreadable-image`, `write-failed`, `unknown-collection`.
23622
+ */
23623
+ var AddRetrainFrameFromRecordingResultSchema = discriminatedUnion("kind", [object({
23624
+ kind: literal("added"),
23625
+ collectionId: string(),
23626
+ frame: RetrainFrameSchema,
23627
+ /** The moment was already in the dataset; nothing was decoded. */
23628
+ reused: boolean()
23629
+ }), object({
23630
+ kind: literal("refused"),
23631
+ reason: _enum([
23632
+ "unknown-collection",
23633
+ "still-unavailable",
23634
+ "still-busy",
23635
+ "unreadable-image",
23636
+ "write-failed"
23637
+ ]),
23638
+ detail: string().optional()
23639
+ })]);
23640
+ /** A vision LLM profile the AI assist may use, and where it sends the frame. */
23641
+ var RetrainAssistProfileSchema = object({
23642
+ id: string(),
23643
+ name: string(),
23644
+ model: string(),
23645
+ kind: string(),
23646
+ /** `true` when the frame would leave the house (a cloud vendor, or an
23647
+ * endpoint that is not on the local network). The page confirms each such
23648
+ * run, and the provider refuses one without `allowCloud`. */
23649
+ leavesHouse: boolean()
23650
+ });
23651
+ /** A box the AI assist proposed: a draft, plus the model's own reason. */
23652
+ var RetrainLlmProposalSchema = RetrainAnnotationDraftSchema.extend({ reason: string() });
23653
+ /** What the AI assist said about a box that was already on the canvas. */
23654
+ var RetrainLlmReviewSchema = object({
23655
+ /** The `ref` the page sent the box under. */
23656
+ ref: string(),
23657
+ verdict: _enum([
23658
+ "confirmed",
23659
+ "wrong-class",
23660
+ "not-an-object",
23661
+ "uncertain"
23662
+ ]),
23663
+ suggestedClass: RetrainMacroClassSchema.optional(),
23664
+ reason: string()
23665
+ });
23666
+ /**
23667
+ * The AI assist's answer. `proposed` carries drafts (`source: 'llm'`, the
23668
+ * model and its confidence) and reviews; items the model got wrong (a box off
23669
+ * the frame, an unasked class, an unknown ref) are dropped and counted in
23670
+ * `rejected`. A whole answer that is not the schema is `malformed-answer`.
23671
+ */
23672
+ var RetrainLlmAssistResultSchema = discriminatedUnion("kind", [object({
23673
+ kind: literal("proposed"),
23674
+ profileId: string(),
23675
+ model: string(),
23676
+ /** The frame was sent outside the house for this answer. */
23677
+ leftHouse: boolean(),
23678
+ proposals: array(RetrainLlmProposalSchema).readonly(),
23679
+ reviews: array(RetrainLlmReviewSchema).readonly(),
23680
+ rejected: number().int()
23681
+ }), object({
23682
+ kind: literal("refused"),
23683
+ reason: _enum([
23684
+ "unknown-frame",
23685
+ "unreadable-frame",
23686
+ "unknown-profile",
23687
+ "profile-disabled",
23688
+ "no-vision",
23689
+ "cloud-not-confirmed",
23690
+ "llm-error",
23691
+ "malformed-answer"
23692
+ ]),
23693
+ detail: string().optional()
23694
+ })]);
22611
23695
  /** The outcome of a lifecycle move owned by the retrain page. */
22612
23696
  var RetrainTransitionResultSchema = object({
22613
23697
  trackId: string(),
@@ -23325,7 +24409,7 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
23325
24409
  auth: "admin"
23326
24410
  }), method(object({
23327
24411
  deviceId: number(),
23328
- trackId: string(),
24412
+ trackId: string().optional(),
23329
24413
  frameId: string()
23330
24414
  }), object({
23331
24415
  removed: boolean(),
@@ -23342,7 +24426,8 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
23342
24426
  auth: "admin"
23343
24427
  }), method(object({
23344
24428
  deviceId: number(),
23345
- trackId: string(),
24429
+ /** The frame's track, when it has one — checked against the frame. */
24430
+ trackId: string().optional(),
23346
24431
  frameId: string(),
23347
24432
  subject: RetrainAssistSubjectSchema,
23348
24433
  /** Which node runs it. Absent ⇒ wherever an unowned call lands. */
@@ -23350,12 +24435,16 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
23350
24435
  }), RetrainAssistResultSchema, {
23351
24436
  kind: "mutation",
23352
24437
  auth: "admin"
23353
- }), method(object({ trackId: string() }), array(RetrainAnnotationSchema).readonly(), {
24438
+ }), method(object({
24439
+ trackId: string().optional(),
24440
+ frameIds: array(string()).max(2e3).optional()
24441
+ }), array(RetrainAnnotationSchema).readonly(), {
23354
24442
  kind: "query",
23355
24443
  auth: "admin"
23356
24444
  }), method(object({
23357
24445
  deviceId: number(),
23358
- trackId: string(),
24446
+ /** The frame's track, when it has one — checked against the frame. */
24447
+ trackId: string().optional(),
23359
24448
  frameId: string(),
23360
24449
  annotations: array(RetrainAnnotationDraftSchema)
23361
24450
  }), array(RetrainAnnotationSchema).readonly(), {
@@ -23378,7 +24467,7 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
23378
24467
  auth: "admin"
23379
24468
  }), method(object({
23380
24469
  deviceId: number(),
23381
- trackId: string(),
24470
+ trackId: string().optional(),
23382
24471
  frameId: string(),
23383
24472
  complete: boolean()
23384
24473
  }), RetrainFrameSchema, {
@@ -23392,6 +24481,74 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
23392
24481
  kind: "mutation",
23393
24482
  auth: "admin",
23394
24483
  timeoutMs: 60 * 6e4
24484
+ }), method(object({}), array(RetrainAssistProfileSchema).readonly(), {
24485
+ kind: "query",
24486
+ auth: "admin"
24487
+ }), method(object({
24488
+ deviceId: number(),
24489
+ trackId: string().optional(),
24490
+ frameId: string(),
24491
+ profileId: string(),
24492
+ classes: array(RetrainMacroClassSchema).min(1),
24493
+ boxes: array(object({
24494
+ ref: string(),
24495
+ bbox: RetrainBboxSchema,
24496
+ macroClass: RetrainMacroClassSchema,
24497
+ label: string().optional()
24498
+ })).max(50),
24499
+ allowCloud: boolean()
24500
+ }), RetrainLlmAssistResultSchema, {
24501
+ kind: "mutation",
24502
+ auth: "admin",
24503
+ timeoutMs: 18e4
24504
+ }), method(object({ name: string().max(120) }), RetrainCollectionCreateResultSchema, {
24505
+ kind: "mutation",
24506
+ auth: "admin"
24507
+ }), method(object({}), array(RetrainCollectionSchema).readonly(), {
24508
+ kind: "query",
24509
+ auth: "admin"
24510
+ }), method(object({
24511
+ id: string(),
24512
+ name: string().max(120)
24513
+ }), RetrainCollectionRenameResultSchema, {
24514
+ kind: "mutation",
24515
+ auth: "admin"
24516
+ }), method(object({ id: string() }), object({
24517
+ deleted: boolean(),
24518
+ removedFrames: number().int()
24519
+ }), {
24520
+ kind: "mutation",
24521
+ auth: "admin"
24522
+ }), method(object({
24523
+ collectionId: string(),
24524
+ deviceId: number(),
24525
+ epochMs: number()
24526
+ }), AddRetrainFrameFromRecordingResultSchema, {
24527
+ kind: "mutation",
24528
+ auth: "admin",
24529
+ timeoutMs: 6e4
24530
+ }), method(object({
24531
+ collectionId: string(),
24532
+ frameIds: array(string()).min(1).max(500)
24533
+ }), object({
24534
+ added: number().int(),
24535
+ alreadyMember: number().int(),
24536
+ unknownFrameIds: array(string()).readonly()
24537
+ }), {
24538
+ kind: "mutation",
24539
+ auth: "admin"
24540
+ }), method(object({
24541
+ collectionId: string(),
24542
+ frameId: string()
24543
+ }), object({
24544
+ removed: boolean(),
24545
+ deletedFrame: boolean()
24546
+ }), {
24547
+ kind: "mutation",
24548
+ auth: "admin"
24549
+ }), method(object({ collectionId: string() }), array(RetrainFrameSchema).readonly(), {
24550
+ kind: "query",
24551
+ auth: "admin"
23395
24552
  }), method(object({
23396
24553
  /** Which of the three event tables owns the row. */
23397
24554
  ownerType: EventOwnerTypeSchema,
@@ -24015,13 +25172,31 @@ var RecommendationReasonSchema = discriminatedUnion("kind", [
24015
25172
  object({
24016
25173
  kind: literal("no-family-build"),
24017
25174
  format: ModelFormatSchema$1
25175
+ }),
25176
+ object({
25177
+ kind: literal("kept-custom-pin"),
25178
+ modelId: string(),
25179
+ deviceKey: string()
24018
25180
  })
24019
25181
  ]);
25182
+ /** Why a device is left exactly as it is, whatever the plan would pick (D786). */
25183
+ var KeptReasonSchema = _enum(["custom-pin"]);
25184
+ /**
25185
+ * Where a choice's latency came from (D791): this node's own benchmark
25186
+ * result, or the hardware-class table. Measured on the node beats the table.
25187
+ */
25188
+ var LatencySourceSchema = discriminatedUnion("kind", [object({ kind: literal("table") }), object({
25189
+ kind: literal("node-benchmark"),
25190
+ resultId: string(),
25191
+ measuredAtMs: number()
25192
+ })]);
24020
25193
  var DeviceModelChoiceSchema = object({
24021
25194
  modelId: string(),
24022
25195
  p50Ms: number(),
24023
25196
  fps: number(),
24024
25197
  measured: boolean(),
25198
+ /** Absent on a plan from before D791 — read as the table. */
25199
+ source: LatencySourceSchema.optional(),
24025
25200
  /** Parallel sessions at the camera rate with the headroom kept free: ⌊fps × (1 − headroom) / camera fps⌋. */
24026
25201
  capacitySessions: number(),
24027
25202
  personRecall: number()
@@ -24032,6 +25207,8 @@ var DeviceRecommendationSchema = object({
24032
25207
  enabled: boolean(),
24033
25208
  available: boolean(),
24034
25209
  chosen: DeviceModelChoiceSchema.nullable(),
25210
+ /** Present when the device is kept as is: Apply writes nothing on it. */
25211
+ kept: KeptReasonSchema.optional(),
24035
25212
  reasons: array(RecommendationReasonSchema).readonly()
24036
25213
  });
24037
25214
  var NodeRecommendationSchema = object({
@@ -24085,6 +25262,17 @@ var AutoTuneWarningSchema = discriminatedUnion("kind", [
24085
25262
  kind: literal("coral-enabled"),
24086
25263
  nodeId: string(),
24087
25264
  deviceKey: string()
25265
+ }),
25266
+ object({
25267
+ kind: literal("custom-pin-kept"),
25268
+ nodeId: string(),
25269
+ deviceKey: string().nullable(),
25270
+ deviceId: number().nullable(),
25271
+ modelId: string()
25272
+ }),
25273
+ object({
25274
+ kind: literal("custom-registry-unreadable"),
25275
+ error: string()
24088
25276
  })
24089
25277
  ]);
24090
25278
  var AutoTuneOptionsSchema = object({
@@ -24263,13 +25451,14 @@ var SuggestSharesResultSchema = object({
24263
25451
  nodes: array(SuggestedNodeShareSchema).readonly()
24264
25452
  });
24265
25453
  /**
24266
- * Where the node and device shares come from (D750, D755).
24267
- * - `hardware` (default) — computed by the system from each node's static
24268
- * capacity (its accelerators at their Auto tune models, from the measured
24269
- * latency table), recomputed whenever a node or device joins, leaves, is
24270
- * switched on or off, or changes model. No load input.
24271
- * - `benchmark` — the same, from each node's measured capacity (node
24272
- * benchmark results); a node without results falls back to `hardware`.
25454
+ * Where the node and device shares come from (D750, D755, D791).
25455
+ * - `benchmark` (default since D791) — each node's capacity as its own node
25456
+ * benchmark measured it; a node without fresh results is sized from
25457
+ * `hardware` and says so. Measured on the node beats the table.
25458
+ * - `hardware` — computed from each node's static capacity only (its
25459
+ * accelerators at their Auto tune models, from the latency table).
25460
+ * Both are recomputed whenever a node or device joins, leaves, is switched
25461
+ * on or off, changes model, or a benchmark result is written. No load input.
24273
25462
  * - `manual` — the operator's stored sliders.
24274
25463
  * Either way a node or device that cannot take sessions gives its share to
24275
25464
  * the others in proportion; the stored values are never rewritten for that.
@@ -24318,6 +25507,362 @@ var EffectiveSharesSchema = object({
24318
25507
  nodeWeights: record(string(), number()),
24319
25508
  deviceWeights: record(string(), record(string(), number()))
24320
25509
  });
25510
+ /**
25511
+ * Wire shapes of the node benchmark (D791): the operator's plan, the
25512
+ * preflight the confirmation shows, the run the orchestrator owns, what the
25513
+ * measuring runner reports, and the result rows Auto tune and the automatic
25514
+ * shares read.
25515
+ *
25516
+ * ONE node at a time, owned by the pipeline orchestrator. While a run is
25517
+ * active the cluster is in BENCHMARK MODE for that node: it is not a
25518
+ * detection candidate, camera pins naming it are ignored so its sessions move
25519
+ * elsewhere, and both come back when the mode ends — after a crash or a hub
25520
+ * restart too (a persisted manifest, reconciled against the registry).
25521
+ *
25522
+ * Two measurements, both on the node, driven by its own runner (frames never
25523
+ * cross a process at frame rate, D9):
25524
+ * - `device` — one accelerator × one candidate detector, root only, open
25525
+ * loop: how many streams at the camera rate it carries inside the frame
25526
+ * interval;
25527
+ * - `pipeline` — the chosen detector plus the operator's detail steps
25528
+ * (faces, plates, classifiers, CLIP…), on varied frames from the bench
25529
+ * clip: how many parallel sessions the node carries before latency, drops,
25530
+ * CPU, RAM or the event loop give out.
25531
+ */
25532
+ /** Defaults and bounds, one place. */
25533
+ var NODE_BENCHMARK_DEFAULTS = {
25534
+ fpsPerStream: 10,
25535
+ budgetMinutes: 45,
25536
+ minBudgetMinutes: 10,
25537
+ maxBudgetMinutes: 120,
25538
+ /** A result older than this no longer beats the table. */
25539
+ staleAfterDays: 30,
25540
+ /** Warm-in per ramp step (not accounted). */
25541
+ settleSec: 5,
25542
+ /** Accounted window per ramp step. */
25543
+ measureSec: 20,
25544
+ /** Longest the drain may take before the run is refused. */
25545
+ drainTimeoutSec: 120,
25546
+ /** Candidate models per device in one run. */
25547
+ maxModelsPerDevice: 6
25548
+ };
25549
+ /** The two measurements a run can make. */
25550
+ var NodeBenchmarkPhaseSchema = _enum(["device", "pipeline"]);
25551
+ var NodeBenchmarkDevicePlanSchema = object({
25552
+ /** `<backend>:<device>` — `openvino:npu`, `coreml:all`, `cpu`. */
25553
+ deviceKey: string().min(1),
25554
+ /**
25555
+ * Root detector candidates for the `device` measurement, in the order
25556
+ * measured. The FIRST is the one the `pipeline` measurement runs.
25557
+ */
25558
+ modelIds: array(string().min(1)).min(1).max(NODE_BENCHMARK_DEFAULTS.maxModelsPerDevice)
25559
+ });
25560
+ /** What the operator confirmed. */
25561
+ var NodeBenchmarkPlanSchema = object({
25562
+ nodeId: string().min(1),
25563
+ devices: array(NodeBenchmarkDevicePlanSchema).min(1),
25564
+ /** Which measurements run. At least one. */
25565
+ phases: array(NodeBenchmarkPhaseSchema).min(1).default(["device", "pipeline"]),
25566
+ /**
25567
+ * Detail steps (catalog step ids under the root: faces, plates,
25568
+ * classifiers, CLIP…) the `pipeline` measurement enables. The root
25569
+ * detector always runs.
25570
+ */
25571
+ steps: array(string().min(1)).default([]),
25572
+ /** Offered rate of one stream / session. */
25573
+ fpsPerStream: number().int().min(1).max(30).default(NODE_BENCHMARK_DEFAULTS.fpsPerStream),
25574
+ /** Hard deadline: the mode ends and the cluster is restored when it passes. */
25575
+ budgetMinutes: number().int().min(NODE_BENCHMARK_DEFAULTS.minBudgetMinutes).max(NODE_BENCHMARK_DEFAULTS.maxBudgetMinutes).default(NODE_BENCHMARK_DEFAULTS.budgetMinutes),
25576
+ /** Keep the models the run downloaded (default: delete what was not installed before). */
25577
+ keepDownloadedModels: boolean().default(false),
25578
+ /** Start although the other nodes' capacity does not cover the sessions running now. */
25579
+ acceptInsufficientHeadroom: boolean().default(false)
25580
+ });
25581
+ var NodeBenchmarkRefusalSchema = object({
25582
+ kind: _enum([
25583
+ "benchmark-active",
25584
+ "node-offline",
25585
+ "unknown-device",
25586
+ "no-phase",
25587
+ "insufficient-headroom"
25588
+ ]),
25589
+ detail: string(),
25590
+ overridable: boolean()
25591
+ });
25592
+ /** A camera whose detection leaves the node for the run. */
25593
+ var NodeBenchmarkMovingCameraSchema = object({
25594
+ deviceId: number(),
25595
+ /** Placed on the node now (a standing attach or a running session). */
25596
+ placedOnNode: boolean(),
25597
+ /** A node pin naming this node, ignored for the run. */
25598
+ pinnedToNode: boolean()
25599
+ });
25600
+ /** A camera that cannot leave: no other node can obtain its frames. */
25601
+ var NodeBenchmarkStayingCameraSchema = object({
25602
+ deviceId: number(),
25603
+ reason: literal("only-frame-source")
25604
+ });
25605
+ var NodeBenchmarkPreflightSchema = object({
25606
+ nodeId: string(),
25607
+ online: boolean(),
25608
+ moving: array(NodeBenchmarkMovingCameraSchema).readonly(),
25609
+ /** Keep running on the node during the run; the result is flagged contaminated. */
25610
+ staying: array(NodeBenchmarkStayingCameraSchema).readonly(),
25611
+ estimatedDurationMs: number(),
25612
+ /** The run ends and the cluster is restored at the latest after this long. */
25613
+ budgetMs: number(),
25614
+ phases: array(NodeBenchmarkPhaseSchema).readonly(),
25615
+ steps: array(string()).readonly(),
25616
+ devices: array(NodeBenchmarkDevicePlanSchema).readonly(),
25617
+ /** Parallel sessions the cluster runs now, and what the other nodes can carry. */
25618
+ headroom: object({
25619
+ sessionsNow: number(),
25620
+ otherNodesCapacitySessions: number().nullable()
25621
+ }),
25622
+ refusals: array(NodeBenchmarkRefusalSchema).readonly(),
25623
+ canStart: boolean()
25624
+ });
25625
+ /** Where the measuring runner is. */
25626
+ var NodeBenchProgressSchema = object({
25627
+ phase: _enum([
25628
+ "preparing",
25629
+ "device",
25630
+ "pipeline",
25631
+ "cleanup"
25632
+ ]),
25633
+ deviceKey: string().nullable(),
25634
+ modelId: string().nullable(),
25635
+ /** Streams (device) or sessions (pipeline) of the step running now. */
25636
+ load: number().nullable(),
25637
+ cellsDone: number(),
25638
+ cellsTotal: number(),
25639
+ message: string()
25640
+ });
25641
+ /** What limited a ramp. `none` = the ramp ran out of steps still passing. */
25642
+ var NodeBenchLimitSchema = _enum([
25643
+ "p95",
25644
+ "drops",
25645
+ "errors",
25646
+ "stall",
25647
+ "cpu",
25648
+ "ram",
25649
+ "none"
25650
+ ]);
25651
+ var NodeBenchRampStepSchema = object({
25652
+ load: number(),
25653
+ pass: boolean(),
25654
+ p95Ms: number(),
25655
+ dropRatio: number(),
25656
+ /** Completed frames per second over the accounted window. */
25657
+ fps: number(),
25658
+ cpuPct: number().nullable(),
25659
+ ramFreePct: number().nullable(),
25660
+ failReasons: array(string()).readonly()
25661
+ });
25662
+ var NodeBenchCellSchema = discriminatedUnion("phase", [object({
25663
+ phase: literal("device"),
25664
+ deviceKey: string(),
25665
+ modelId: string(),
25666
+ /** Single-stream latency (the K = 1 step). */
25667
+ p50Ms: number(),
25668
+ p95Ms: number(),
25669
+ p99Ms: number(),
25670
+ /** Frames per second sustained at the last passing step. */
25671
+ fps: number(),
25672
+ /** Streams at the camera rate the device carried inside the frame interval; 0 = not even one. */
25673
+ kMax: number(),
25674
+ limitedBy: NodeBenchLimitSchema,
25675
+ /** First call (model load + warm-up). */
25676
+ warmupMs: number(),
25677
+ ramp: array(NodeBenchRampStepSchema).readonly()
25678
+ }), object({
25679
+ phase: literal("pipeline"),
25680
+ deviceKey: string(),
25681
+ modelId: string(),
25682
+ steps: array(string()).readonly(),
25683
+ /** Parallel sessions at the camera rate the node carried; 0 = not even one. */
25684
+ maxSessions: number(),
25685
+ limitedBy: NodeBenchLimitSchema,
25686
+ /** Detail steps that produced at least one result on the clip — a step that never fired measured nothing. */
25687
+ stepsFired: array(string()).readonly(),
25688
+ warmupMs: number(),
25689
+ ramp: array(NodeBenchRampStepSchema).readonly()
25690
+ })]);
25691
+ /**
25692
+ * What a result was measured ON. A result whose fingerprint no longer matches
25693
+ * the node no longer beats the table.
25694
+ */
25695
+ var NodeBenchFingerprintSchema = object({
25696
+ pipelineVersion: string().nullable(),
25697
+ cpuModel: string().nullable(),
25698
+ ramGb: number().nullable(),
25699
+ os: string().nullable(),
25700
+ /** Per device: the pool the cells ran on (runtime + tuning). */
25701
+ pools: record(string(), object({
25702
+ runtime: string(),
25703
+ numWorkers: number(),
25704
+ concurrency: number(),
25705
+ batchMode: string()
25706
+ })).default({})
25707
+ });
25708
+ /** The frames the run used. */
25709
+ var NodeBenchClipSchema = object({
25710
+ /** `camstack-bench-v1` or `reference-images` (the fallback when the clip is not reachable). */
25711
+ id: string(),
25712
+ revision: string().nullable(),
25713
+ frames: number(),
25714
+ width: number(),
25715
+ height: number()
25716
+ });
25717
+ var NodeBenchRunnerInputSchema = object({
25718
+ runId: string().min(1),
25719
+ devices: array(NodeBenchmarkDevicePlanSchema).min(1),
25720
+ phases: array(NodeBenchmarkPhaseSchema).min(1),
25721
+ /** The full detail step tree root for the `pipeline` measurement is built on the node from these ids. */
25722
+ steps: array(string()).default([]),
25723
+ fpsPerStream: number().int().min(1).max(30),
25724
+ /** The runner stops on its own past this instant, whatever the hub does. */
25725
+ deadlineAtMs: number(),
25726
+ settleSec: number().min(0).max(60).default(NODE_BENCHMARK_DEFAULTS.settleSec),
25727
+ measureSec: number().min(2).max(300).default(NODE_BENCHMARK_DEFAULTS.measureSec),
25728
+ keepDownloadedModels: boolean().default(false)
25729
+ });
25730
+ var NodeBenchRunnerStateSchema = _enum([
25731
+ "running",
25732
+ "done",
25733
+ "failed",
25734
+ "aborted"
25735
+ ]);
25736
+ var NodeBenchRunnerStatusSchema = object({
25737
+ runId: string(),
25738
+ nodeId: string(),
25739
+ state: NodeBenchRunnerStateSchema,
25740
+ progress: NodeBenchProgressSchema.nullable(),
25741
+ /** Every finished cell so far — a run stopped half way keeps what it measured. */
25742
+ cells: array(NodeBenchCellSchema).readonly(),
25743
+ fingerprint: NodeBenchFingerprintSchema.nullable(),
25744
+ clip: NodeBenchClipSchema.nullable(),
25745
+ /** Cameras seen running on the node during the run (they share its pools). */
25746
+ activeCameraIds: array(number()).readonly(),
25747
+ /** Models the run downloaded and then deleted (not installed before). */
25748
+ deletedModels: array(string()).readonly(),
25749
+ error: string().nullable(),
25750
+ startedAtMs: number(),
25751
+ finishedAtMs: number().nullable()
25752
+ });
25753
+ var NodeBenchmarkStateSchema = _enum([
25754
+ "draining",
25755
+ "measuring",
25756
+ "restoring",
25757
+ "done",
25758
+ "failed",
25759
+ "aborted"
25760
+ ]);
25761
+ /** Why a run ended. */
25762
+ var NodeBenchmarkEndReasonSchema = _enum([
25763
+ "completed",
25764
+ "operator-abort",
25765
+ "deadline",
25766
+ "node-lost",
25767
+ "runner-lost",
25768
+ "hub-restart",
25769
+ "drain-timeout",
25770
+ "failed"
25771
+ ]);
25772
+ var NodeBenchmarkRunSchema = object({
25773
+ runId: string(),
25774
+ nodeId: string(),
25775
+ state: NodeBenchmarkStateSchema,
25776
+ plan: NodeBenchmarkPlanSchema,
25777
+ startedAtMs: number(),
25778
+ deadlineAtMs: number(),
25779
+ finishedAtMs: number().nullable(),
25780
+ endReason: NodeBenchmarkEndReasonSchema.nullable(),
25781
+ error: string().nullable(),
25782
+ /** Cameras moved off the node for the run. */
25783
+ moved: array(number()).readonly(),
25784
+ /** Cameras that stayed (their only frame source is the node). */
25785
+ staying: array(number()).readonly(),
25786
+ /** Something else ran on the node's pools during the run. */
25787
+ contaminated: boolean(),
25788
+ progress: NodeBenchProgressSchema.nullable(),
25789
+ resultIds: array(string()).readonly()
25790
+ });
25791
+ /** `getNodeBenchmarkStatus`: the active run (or the last one), and whether benchmark mode is on. */
25792
+ var NodeBenchmarkStatusSchema = object({
25793
+ /** The node the cluster is in benchmark mode for; null = none. */
25794
+ modeNodeId: string().nullable(),
25795
+ run: NodeBenchmarkRunSchema.nullable()
25796
+ });
25797
+ /**
25798
+ * One stored measurement — the only authority Auto tune and the automatic
25799
+ * shares read measured capacity from. Written by the orchestrator when a run
25800
+ * ends, never by anyone else.
25801
+ */
25802
+ var NodeBenchmarkResultSchema = object({
25803
+ id: string(),
25804
+ runId: string(),
25805
+ nodeId: string(),
25806
+ cell: NodeBenchCellSchema,
25807
+ fpsPerStream: number(),
25808
+ fingerprint: NodeBenchFingerprintSchema.nullable(),
25809
+ clip: NodeBenchClipSchema.nullable(),
25810
+ /** Other work shared the node's pools (a camera that could not move, or the hub's own duties). */
25811
+ contaminated: boolean(),
25812
+ stayingCameras: array(number()).readonly(),
25813
+ /** The run ended early; the cell itself completed. */
25814
+ partialRun: boolean(),
25815
+ measuredAtMs: number()
25816
+ });
25817
+ var ListNodeBenchmarkResultsInputSchema = object({
25818
+ nodeId: string().optional(),
25819
+ deviceKey: string().optional()
25820
+ });
25821
+ /** A result with its standing today: does it still beat the table? */
25822
+ var NodeBenchmarkResultViewSchema = NodeBenchmarkResultSchema.extend({
25823
+ /** `fresh` beats the table; `stale` falls back to it; `superseded` = a newer row covers the same cell. */
25824
+ standing: _enum([
25825
+ "fresh",
25826
+ "stale",
25827
+ "superseded"
25828
+ ]),
25829
+ staleWhy: _enum([
25830
+ "age",
25831
+ "runtime",
25832
+ "pool-tuning"
25833
+ ]).nullable()
25834
+ });
25835
+ object({
25836
+ runId: string(),
25837
+ nodeId: string(),
25838
+ startedAtMs: number(),
25839
+ deadlineAtMs: number(),
25840
+ plan: NodeBenchmarkPlanSchema,
25841
+ moved: array(number()).readonly(),
25842
+ staying: array(number()).readonly()
25843
+ });
25844
+ /** Candidate detectors per device, for the plan editor. */
25845
+ var NodeBenchmarkCandidatesSchema = object({
25846
+ nodeId: string(),
25847
+ reachable: boolean(),
25848
+ devices: array(object({
25849
+ deviceKey: string(),
25850
+ enabled: boolean(),
25851
+ available: boolean(),
25852
+ /** Ordered: what Auto tune would pick first, then the rest of the family by accuracy. */
25853
+ suggested: array(string()).readonly(),
25854
+ /** Every root detector the device has a build for. */
25855
+ all: array(string()).readonly(),
25856
+ /** The model the device runs now, when pinned. */
25857
+ currentModelId: string().nullable()
25858
+ })).readonly(),
25859
+ /** Detail steps the node's catalog offers under the root (for the `pipeline` measurement). */
25860
+ steps: array(object({
25861
+ id: string(),
25862
+ name: string(),
25863
+ slot: string()
25864
+ })).readonly()
25865
+ });
24321
25866
  object({
24322
25867
  activeCameras: number(),
24323
25868
  throttledCameras: number(),
@@ -25446,7 +26991,16 @@ method(RunnerCameraConfigSchema, object({ success: literal(true) }), { kind: "mu
25446
26991
  }), ParkedTrackFrameSchema.nullable()), method(object({
25447
26992
  deviceId: number(),
25448
26993
  trackId: string()
25449
- }), object({ released: number().int().nonnegative() }), { kind: "mutation" });
26994
+ }), object({ released: number().int().nonnegative() }), { kind: "mutation" }), method(NodeBenchRunnerInputSchema, object({
26995
+ accepted: literal(true),
26996
+ runId: string()
26997
+ }), {
26998
+ kind: "mutation",
26999
+ auth: "admin"
27000
+ }), method(object({ runId: string() }), NodeBenchRunnerStatusSchema.nullable(), { auth: "admin" }), method(object({ runId: string() }), object({ aborted: boolean() }), {
27001
+ kind: "mutation",
27002
+ auth: "admin"
27003
+ });
25450
27004
  var CameraPipelineConfigSchema = object({
25451
27005
  engine: PipelineEngineChoiceSchema.optional(),
25452
27006
  steps: array(PipelineStepInputSchema).readonly(),
@@ -26085,6 +27639,21 @@ method(object({
26085
27639
  }), method(PlacementStatsInputSchema, PlacementStatsSchema, { auth: "admin" }), method(SuggestSharesInputSchema, SuggestSharesResultSchema, { auth: "admin" }), method(_void(), EffectiveSharesSchema, { auth: "admin" }), method(SetShareSourceInputSchema, object({ success: literal(true) }), {
26086
27640
  kind: "mutation",
26087
27641
  auth: "admin"
27642
+ }), method(NodeBenchmarkPlanSchema, NodeBenchmarkPreflightSchema, { auth: "admin" }), method(NodeBenchmarkPlanSchema, discriminatedUnion("kind", [object({
27643
+ kind: literal("started"),
27644
+ runId: string()
27645
+ }), object({
27646
+ kind: literal("refused"),
27647
+ preflight: NodeBenchmarkPreflightSchema
27648
+ })]), {
27649
+ kind: "mutation",
27650
+ auth: "admin"
27651
+ }), method(_void(), NodeBenchmarkStatusSchema, { auth: "admin" }), method(object({ runId: string() }), object({ aborted: boolean() }), {
27652
+ kind: "mutation",
27653
+ auth: "admin"
27654
+ }), method(object({ nodeId: string() }), NodeBenchmarkCandidatesSchema, { auth: "admin" }), method(ListNodeBenchmarkResultsInputSchema, array(NodeBenchmarkResultViewSchema).readonly(), { auth: "admin" }), method(object({ id: string() }), object({ deleted: boolean() }), {
27655
+ kind: "mutation",
27656
+ auth: "admin"
26088
27657
  }), method(object({ deviceId: number() }), CameraPipelineSettingsSchema.nullable()), method(object({
26089
27658
  deviceId: number(),
26090
27659
  addonId: string(),
@@ -32209,6 +33778,9 @@ var CreateIntegrationInputSchema = object({
32209
33778
  enabled: boolean().optional(),
32210
33779
  info: record(string(), unknown()).optional(),
32211
33780
  settings: record(string(), unknown()).optional(),
33781
+ /** Keys of `settings` the form's schema declares secret (by type) — kept in
33782
+ * the keychain, not the table (D787). */
33783
+ secretKeys: array(string()).optional(),
32212
33784
  skipRestart: boolean().optional()
32213
33785
  });
32214
33786
  var UpdateIntegrationInputSchema = object({
@@ -32232,7 +33804,9 @@ method(_void(), array(IntegrationWithStateSchema)), method(object({ id: string()
32232
33804
  auth: "admin"
32233
33805
  }), method(object({ id: string() }), record(string(), unknown()), { auth: "admin" }), method(object({
32234
33806
  id: string(),
32235
- settings: record(string(), unknown())
33807
+ settings: record(string(), unknown()),
33808
+ /** Keys the form's schema declares secret (by type) — keychain-stored (D787). */
33809
+ secretKeys: array(string()).optional()
32236
33810
  }), object({ success: boolean() }), {
32237
33811
  kind: "mutation",
32238
33812
  auth: "admin"
@@ -40395,7 +41969,8 @@ var BaseDevice = class {
40395
41969
  this.role = options.role;
40396
41970
  this.parentDeviceId = ctx.parentDeviceId;
40397
41971
  const seedData = ctx.persistedConfig ?? {};
40398
- this.config = DeviceConfig.fromSchema(schema, (data) => ctx.persistConfig(data), seedData, ({ droppedKeys, issues }) => {
41972
+ const declaredSecretPaths = collectZodSecretPaths(schema);
41973
+ this.config = DeviceConfig.fromSchema(schema, (data) => ctx.persistConfig(data, { secretConfigPaths: declaredSecretPaths }), seedData, ({ droppedKeys, issues }) => {
40399
41974
  ctx.logger.warn("Device config recovery: dropping invalid persisted fields", {
40400
41975
  tags: {
40401
41976
  deviceId: ctx.id,
@@ -44084,6 +45659,90 @@ Object.freeze({
44084
45659
  addonId: null,
44085
45660
  access: "create"
44086
45661
  },
45662
+ "keychain.delete": {
45663
+ capName: "keychain",
45664
+ capScope: "system",
45665
+ addonId: null,
45666
+ access: "delete"
45667
+ },
45668
+ "keychain.getState": {
45669
+ capName: "keychain",
45670
+ capScope: "system",
45671
+ addonId: null,
45672
+ access: "view"
45673
+ },
45674
+ "keychain.listMeta": {
45675
+ capName: "keychain",
45676
+ capScope: "system",
45677
+ addonId: null,
45678
+ access: "view"
45679
+ },
45680
+ "keychain.put": {
45681
+ capName: "keychain",
45682
+ capScope: "system",
45683
+ addonId: null,
45684
+ access: "create"
45685
+ },
45686
+ "keychain.resolve": {
45687
+ capName: "keychain",
45688
+ capScope: "system",
45689
+ addonId: null,
45690
+ access: "view"
45691
+ },
45692
+ "keychainAdmin.deleteOrphans": {
45693
+ capName: "keychain-admin",
45694
+ capScope: "system",
45695
+ addonId: null,
45696
+ access: "delete"
45697
+ },
45698
+ "keychainAdmin.downloadRecoveryKey": {
45699
+ capName: "keychain-admin",
45700
+ capScope: "system",
45701
+ addonId: null,
45702
+ access: "create"
45703
+ },
45704
+ "keychainAdmin.listAudit": {
45705
+ capName: "keychain-admin",
45706
+ capScope: "system",
45707
+ addonId: null,
45708
+ access: "view"
45709
+ },
45710
+ "keychainAdmin.listSecrets": {
45711
+ capName: "keychain-admin",
45712
+ capScope: "system",
45713
+ addonId: null,
45714
+ access: "view"
45715
+ },
45716
+ "keychainAdmin.purgeRetiredKeys": {
45717
+ capName: "keychain-admin",
45718
+ capScope: "system",
45719
+ addonId: null,
45720
+ access: "delete"
45721
+ },
45722
+ "keychainAdmin.resetKeychain": {
45723
+ capName: "keychain-admin",
45724
+ capScope: "system",
45725
+ addonId: null,
45726
+ access: "delete"
45727
+ },
45728
+ "keychainAdmin.reveal": {
45729
+ capName: "keychain-admin",
45730
+ capScope: "system",
45731
+ addonId: null,
45732
+ access: "create"
45733
+ },
45734
+ "keychainAdmin.rotateMasterKey": {
45735
+ capName: "keychain-admin",
45736
+ capScope: "system",
45737
+ addonId: null,
45738
+ access: "create"
45739
+ },
45740
+ "keychainAdmin.status": {
45741
+ capName: "keychain-admin",
45742
+ capScope: "system",
45743
+ addonId: null,
45744
+ access: "view"
45745
+ },
44087
45746
  "lawnMowerControl.dock": {
44088
45747
  capName: "lawn-mower-control",
44089
45748
  capScope: "device",
@@ -45458,6 +47117,18 @@ Object.freeze({
45458
47117
  addonId: null,
45459
47118
  access: "create"
45460
47119
  },
47120
+ "pipelineAnalytics.addRetrainFrameFromRecording": {
47121
+ capName: "pipeline-analytics",
47122
+ capScope: "device",
47123
+ addonId: null,
47124
+ access: "create"
47125
+ },
47126
+ "pipelineAnalytics.addRetrainFramesToCollection": {
47127
+ capName: "pipeline-analytics",
47128
+ capScope: "device",
47129
+ addonId: null,
47130
+ access: "create"
47131
+ },
45461
47132
  "pipelineAnalytics.applyDeviceSettingsPatch": {
45462
47133
  capName: "pipeline-analytics",
45463
47134
  capScope: "device",
@@ -45506,12 +47177,24 @@ Object.freeze({
45506
47177
  addonId: null,
45507
47178
  access: "view"
45508
47179
  },
47180
+ "pipelineAnalytics.createRetrainCollection": {
47181
+ capName: "pipeline-analytics",
47182
+ capScope: "device",
47183
+ addonId: null,
47184
+ access: "create"
47185
+ },
45509
47186
  "pipelineAnalytics.deleteDeviceEvents": {
45510
47187
  capName: "pipeline-analytics",
45511
47188
  capScope: "device",
45512
47189
  addonId: null,
45513
47190
  access: "delete"
45514
47191
  },
47192
+ "pipelineAnalytics.deleteRetrainCollection": {
47193
+ capName: "pipeline-analytics",
47194
+ capScope: "device",
47195
+ addonId: null,
47196
+ access: "delete"
47197
+ },
45515
47198
  "pipelineAnalytics.deleteTracks": {
45516
47199
  capName: "pipeline-analytics",
45517
47200
  capScope: "device",
@@ -45716,6 +47399,24 @@ Object.freeze({
45716
47399
  addonId: null,
45717
47400
  access: "view"
45718
47401
  },
47402
+ "pipelineAnalytics.listRetrainAssistProfiles": {
47403
+ capName: "pipeline-analytics",
47404
+ capScope: "device",
47405
+ addonId: null,
47406
+ access: "view"
47407
+ },
47408
+ "pipelineAnalytics.listRetrainCollectionFrames": {
47409
+ capName: "pipeline-analytics",
47410
+ capScope: "device",
47411
+ addonId: null,
47412
+ access: "view"
47413
+ },
47414
+ "pipelineAnalytics.listRetrainCollections": {
47415
+ capName: "pipeline-analytics",
47416
+ capScope: "device",
47417
+ addonId: null,
47418
+ access: "view"
47419
+ },
45719
47420
  "pipelineAnalytics.listRetrainFrames": {
45720
47421
  capName: "pipeline-analytics",
45721
47422
  capScope: "device",
@@ -45764,6 +47465,12 @@ Object.freeze({
45764
47465
  addonId: null,
45765
47466
  access: "create"
45766
47467
  },
47468
+ "pipelineAnalytics.proposeRetrainAnnotationsWithLlm": {
47469
+ capName: "pipeline-analytics",
47470
+ capScope: "device",
47471
+ addonId: null,
47472
+ access: "create"
47473
+ },
45767
47474
  "pipelineAnalytics.pruneEvents": {
45768
47475
  capName: "pipeline-analytics",
45769
47476
  capScope: "device",
@@ -45818,6 +47525,18 @@ Object.freeze({
45818
47525
  addonId: null,
45819
47526
  access: "create"
45820
47527
  },
47528
+ "pipelineAnalytics.removeRetrainFrameFromCollection": {
47529
+ capName: "pipeline-analytics",
47530
+ capScope: "device",
47531
+ addonId: null,
47532
+ access: "delete"
47533
+ },
47534
+ "pipelineAnalytics.renameRetrainCollection": {
47535
+ capName: "pipeline-analytics",
47536
+ capScope: "device",
47537
+ addonId: null,
47538
+ access: "create"
47539
+ },
45821
47540
  "pipelineAnalytics.restageRetrainTrack": {
45822
47541
  capName: "pipeline-analytics",
45823
47542
  capScope: "device",
@@ -46106,6 +47825,12 @@ Object.freeze({
46106
47825
  addonId: null,
46107
47826
  access: "view"
46108
47827
  },
47828
+ "pipelineOrchestrator.abortNodeBenchmark": {
47829
+ capName: "pipeline-orchestrator",
47830
+ capScope: "system",
47831
+ addonId: null,
47832
+ access: "create"
47833
+ },
46109
47834
  "pipelineOrchestrator.applyAutoTune": {
46110
47835
  capName: "pipeline-orchestrator",
46111
47836
  capScope: "system",
@@ -46130,6 +47855,12 @@ Object.freeze({
46130
47855
  addonId: null,
46131
47856
  access: "create"
46132
47857
  },
47858
+ "pipelineOrchestrator.deleteNodeBenchmarkResult": {
47859
+ capName: "pipeline-orchestrator",
47860
+ capScope: "system",
47861
+ addonId: null,
47862
+ access: "delete"
47863
+ },
46133
47864
  "pipelineOrchestrator.getAgentLoad": {
46134
47865
  capName: "pipeline-orchestrator",
46135
47866
  capScope: "system",
@@ -46238,6 +47969,24 @@ Object.freeze({
46238
47969
  addonId: null,
46239
47970
  access: "view"
46240
47971
  },
47972
+ "pipelineOrchestrator.getNodeBenchmarkCandidates": {
47973
+ capName: "pipeline-orchestrator",
47974
+ capScope: "system",
47975
+ addonId: null,
47976
+ access: "view"
47977
+ },
47978
+ "pipelineOrchestrator.getNodeBenchmarkPreflight": {
47979
+ capName: "pipeline-orchestrator",
47980
+ capScope: "system",
47981
+ addonId: null,
47982
+ access: "view"
47983
+ },
47984
+ "pipelineOrchestrator.getNodeBenchmarkStatus": {
47985
+ capName: "pipeline-orchestrator",
47986
+ capScope: "system",
47987
+ addonId: null,
47988
+ access: "view"
47989
+ },
46241
47990
  "pipelineOrchestrator.getNodeInferenceDevices": {
46242
47991
  capName: "pipeline-orchestrator",
46243
47992
  capScope: "system",
@@ -46280,6 +48029,12 @@ Object.freeze({
46280
48029
  addonId: null,
46281
48030
  access: "view"
46282
48031
  },
48032
+ "pipelineOrchestrator.listNodeBenchmarkResults": {
48033
+ capName: "pipeline-orchestrator",
48034
+ capScope: "system",
48035
+ addonId: null,
48036
+ access: "view"
48037
+ },
46283
48038
  "pipelineOrchestrator.pauseForStorageMigration": {
46284
48039
  capName: "pipeline-orchestrator",
46285
48040
  capScope: "system",
@@ -46424,6 +48179,12 @@ Object.freeze({
46424
48179
  addonId: null,
46425
48180
  access: "create"
46426
48181
  },
48182
+ "pipelineOrchestrator.startNodeBenchmark": {
48183
+ capName: "pipeline-orchestrator",
48184
+ capScope: "system",
48185
+ addonId: null,
48186
+ access: "create"
48187
+ },
46427
48188
  "pipelineOrchestrator.suggestShares": {
46428
48189
  capName: "pipeline-orchestrator",
46429
48190
  capScope: "system",
@@ -46442,6 +48203,12 @@ Object.freeze({
46442
48203
  addonId: null,
46443
48204
  access: "create"
46444
48205
  },
48206
+ "pipelineRunner.abortNodeBench": {
48207
+ capName: "pipeline-runner",
48208
+ capScope: "system",
48209
+ addonId: null,
48210
+ access: "create"
48211
+ },
46445
48212
  "pipelineRunner.attachCamera": {
46446
48213
  capName: "pipeline-runner",
46447
48214
  capScope: "system",
@@ -46490,6 +48257,12 @@ Object.freeze({
46490
48257
  addonId: null,
46491
48258
  access: "view"
46492
48259
  },
48260
+ "pipelineRunner.getNodeBenchStatus": {
48261
+ capName: "pipeline-runner",
48262
+ capScope: "system",
48263
+ addonId: null,
48264
+ access: "view"
48265
+ },
46493
48266
  "pipelineRunner.getParkedTrackFrame": {
46494
48267
  capName: "pipeline-runner",
46495
48268
  capScope: "system",
@@ -46532,6 +48305,12 @@ Object.freeze({
46532
48305
  addonId: null,
46533
48306
  access: "create"
46534
48307
  },
48308
+ "pipelineRunner.startNodeBench": {
48309
+ capName: "pipeline-runner",
48310
+ capScope: "system",
48311
+ addonId: null,
48312
+ access: "create"
48313
+ },
46535
48314
  "plateGallery.assignPlate": {
46536
48315
  capName: "plate-gallery",
46537
48316
  capScope: "system",
@@ -51461,6 +53240,11 @@ Object.freeze({
51461
53240
  form: "single",
51462
53241
  optional: false
51463
53242
  }],
53243
+ "pipelineAnalytics.addRetrainFrameFromRecording": [{
53244
+ name: "deviceId",
53245
+ form: "single",
53246
+ optional: false
53247
+ }],
51464
53248
  "pipelineAnalytics.applyDeviceSettingsPatch": [{
51465
53249
  name: "deviceId",
51466
53250
  form: "single",
@@ -51651,6 +53435,11 @@ Object.freeze({
51651
53435
  form: "single",
51652
53436
  optional: false
51653
53437
  }],
53438
+ "pipelineAnalytics.proposeRetrainAnnotationsWithLlm": [{
53439
+ name: "deviceId",
53440
+ form: "single",
53441
+ optional: false
53442
+ }],
51654
53443
  "pipelineAnalytics.pruneEventsBefore": [{
51655
53444
  name: "deviceId",
51656
53445
  form: "single",