@camstack/addon-provider-hikvision 1.2.146 → 1.2.147

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/addon.js +1845 -56
  2. package/dist/addon.mjs +1845 -56
  3. package/package.json +1 -1
package/dist/addon.js CHANGED
@@ -33,7 +33,7 @@ let node_net = require("node:net");
33
33
  let node_http = require("node:http");
34
34
  let node_https = require("node:https");
35
35
  let node_os = require("node:os");
36
- //#region ../types/dist/event-category-B_0XEcLF.mjs
36
+ //#region ../types/dist/event-category-DaIZi00R.mjs
37
37
  var EventCategory = /* @__PURE__ */ function(EventCategory) {
38
38
  EventCategory["SystemBoot"] = "system.boot";
39
39
  EventCategory["SystemAddonsReady"] = "system.addons-ready";
@@ -112,6 +112,13 @@ var EventCategory = /* @__PURE__ */ function(EventCategory) {
112
112
  */
113
113
  EventCategory["AddonLoadFailed"] = "addon.load-failed";
114
114
  /**
115
+ * A keychain value was stored or removed (D787). Carries the ref, its
116
+ * owner and the new version — NEVER the value. A process holding the ref
117
+ * drops its cached copy and the owning `BaseAddon` re-resolves its config.
118
+ * Telemetry (D8): a process that misses it still revalidates by version.
119
+ */
120
+ EventCategory["KeychainChanged"] = "keychain.changed";
121
+ /**
115
122
  * Addon recovered from a previous failure. Emitted when an addon
116
123
  * transitions from `failed` back to `healthy` (typically via the
117
124
  * monitor's auto-retry loop, or after manual `addons.retryLoad`).
@@ -5404,7 +5411,7 @@ var ZodIssueCode = {
5404
5411
  var ZodFirstPartyTypeKind;
5405
5412
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
5406
5413
  //#endregion
5407
- //#region ../types/dist/sleep-B0JG7-_F.mjs
5414
+ //#region ../types/dist/sleep-Cr5YOk3m.mjs
5408
5415
  /**
5409
5416
  * The audio chunk plane's byte format, and the ONE expansion from a coded
5410
5417
  * window to float samples (D455).
@@ -5483,6 +5490,97 @@ function buildAlawTable() {
5483
5490
  }
5484
5491
  buildUlawTable();
5485
5492
  buildAlawTable();
5493
+ /** Is this field's stored value a credential? */
5494
+ function isSecretConfigField(field) {
5495
+ if (field.type === "password") return true;
5496
+ return "secret" in field && field.secret === true;
5497
+ }
5498
+ /**
5499
+ * Is this field's value stored in the KEYCHAIN (D787)? Every secret field is,
5500
+ * by its TYPE, unless it opts out with `storage: 'inline'` — never by its name.
5501
+ */
5502
+ function isKeychainStoredField(field) {
5503
+ if (!isSecretConfigField(field)) return false;
5504
+ if (field.type === "textarea" && field.isJson === true) return false;
5505
+ return !("storage" in field && field.storage === "inline");
5506
+ }
5507
+ /**
5508
+ * What a settings blob holds where a secret used to be.
5509
+ *
5510
+ * A keychain-stored field never holds its value. It holds a self-describing
5511
+ * MARKER, `{"$secret":"secret://…","v":1}` — an object, never a string, so no
5512
+ * code can mistake it for a credential and no form can send it to a camera as
5513
+ * a password. The empty state is `null` / absent, never `''`.
5514
+ *
5515
+ * The same shapes travel to and from the admin UI:
5516
+ *
5517
+ * - read: `hydrateSchema` hands a secret field a {@link SecretFieldView}
5518
+ * (`{ $secret, v, set: true }`) or `null` — the browser learns whether a
5519
+ * value is set, never the value.
5520
+ * - write: an untouched field submits the view back unchanged (KEEP); a typed
5521
+ * value is a plain non-empty string (CHANGE); the Clear button submits
5522
+ * {@link SECRET_CLEAR} (CLEAR). `''`, `null` and the legacy redaction tokens
5523
+ * are KEEP — an empty string is what a defaults-fallback pushes back, and
5524
+ * treating it as "clear" is how a save destroyed a stored credential before.
5525
+ *
5526
+ * Pure and browser-safe.
5527
+ */
5528
+ var SECRET_CLEAR = { $secretClear: true };
5529
+ /** The `'***'` token D634 redaction writes for non-admins. */
5530
+ var LEGACY_DEVICE_REDACTION = "***";
5531
+ function isRecord$1(value) {
5532
+ return typeof value === "object" && value !== null && !Array.isArray(value);
5533
+ }
5534
+ function makeSecretMarker(ref) {
5535
+ return {
5536
+ $secret: ref,
5537
+ v: 1
5538
+ };
5539
+ }
5540
+ /** A stored marker: an object whose `$secret` is a non-empty string. */
5541
+ function isSecretMarker(value) {
5542
+ if (!isRecord$1(value)) return false;
5543
+ const ref = value["$secret"];
5544
+ return typeof ref === "string" && ref.length > 0;
5545
+ }
5546
+ function isSecretClear(value) {
5547
+ return isRecord$1(value) && value["$secretClear"] === true;
5548
+ }
5549
+ /**
5550
+ * The UI view of a stored secret field value: a marker becomes "set", inline
5551
+ * plaintext becomes "set (inline)", nothing becomes `null`. A value never
5552
+ * survives this function.
5553
+ */
5554
+ function toSecretFieldView(stored) {
5555
+ if (isSecretMarker(stored)) return {
5556
+ $secret: stored.$secret,
5557
+ v: 1,
5558
+ set: true
5559
+ };
5560
+ if (typeof stored === "string" && stored.length > 0) return {
5561
+ $secret: null,
5562
+ v: 1,
5563
+ set: true,
5564
+ inline: true
5565
+ };
5566
+ return null;
5567
+ }
5568
+ /**
5569
+ * Classify an incoming value for a secret path. Only a non-empty string that is
5570
+ * not a redaction token sets a value; only {@link SECRET_CLEAR} clears.
5571
+ * Everything else — a marker (ours or anyone's), a UI view, `''`, `null`,
5572
+ * `undefined`, a redaction token, a non-string — keeps what is stored.
5573
+ */
5574
+ function classifySecretWrite(incoming) {
5575
+ if (isSecretClear(incoming)) return { kind: "clear" };
5576
+ if (typeof incoming !== "string") return { kind: "keep" };
5577
+ if (incoming.length === 0) return { kind: "keep" };
5578
+ if (incoming === "__camstack_redacted__" || incoming === LEGACY_DEVICE_REDACTION) return { kind: "keep" };
5579
+ return {
5580
+ kind: "set",
5581
+ value: incoming
5582
+ };
5583
+ }
5486
5584
  Object.fromEntries([
5487
5585
  {
5488
5586
  id: "overview",
@@ -5654,33 +5752,19 @@ Object.fromEntries([
5654
5752
  function isValuelessField(field) {
5655
5753
  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";
5656
5754
  }
5657
- /**
5658
- * Merge a `ConfigUISchema` with a raw `values` record into a
5659
- * `ConfigUISchemaWithValues`. Used by every `get*Settings` backend endpoint
5660
- * before returning to the admin UI. Groups are walked recursively.
5661
- *
5662
- * For each leaf field:
5663
- * - structural fields (`separator`, `info`, `button`) pass through unchanged
5664
- * - other fields get `value = values[key] ?? field.default ?? null`
5665
- *
5666
- * Unknown keys in `values` (keys not declared in the schema) are silently
5667
- * ignored — they don't contribute to the output. Missing keys fall back to
5668
- * the schema default or `null`. This mirrors the old backend behaviour where
5669
- * `FormBuilder` rendered `values[key] ?? field.default`.
5670
- */
5671
- function hydrateSchema(schema, values) {
5755
+ function hydrateSchema(schema, values, options = {}) {
5672
5756
  return {
5673
5757
  ...schema.tabs ? { tabs: [...schema.tabs] } : {},
5674
5758
  sections: schema.sections.map((section) => ({
5675
5759
  ...section,
5676
- fields: section.fields.map((field) => hydrateField(field, values))
5760
+ fields: section.fields.map((field) => hydrateField(field, values, options))
5677
5761
  }))
5678
5762
  };
5679
5763
  }
5680
- function hydrateField(field, values) {
5764
+ function hydrateField(field, values, options) {
5681
5765
  if (isValuelessField(field)) return field;
5682
5766
  if (field.type === "group") {
5683
- const hydratedChildren = field.fields.map((child) => hydrateField(child, values));
5767
+ const hydratedChildren = field.fields.map((child) => hydrateField(child, values, options));
5684
5768
  return {
5685
5769
  ...field,
5686
5770
  fields: hydratedChildren
@@ -5689,7 +5773,7 @@ function hydrateField(field, values) {
5689
5773
  if (field.type === "sub-tabs") {
5690
5774
  const hydratedTabs = field.tabs.map((tab) => ({
5691
5775
  ...tab,
5692
- fields: tab.fields.map((child) => hydrateField(child, values))
5776
+ fields: tab.fields.map((child) => hydrateField(child, values, options))
5693
5777
  }));
5694
5778
  return {
5695
5779
  ...field,
@@ -5699,6 +5783,33 @@ function hydrateField(field, values) {
5699
5783
  const key = field.key;
5700
5784
  const storedValue = Object.prototype.hasOwnProperty.call(values, key) ? values[key] : void 0;
5701
5785
  const defaultValue = field.default;
5786
+ const asView = (v) => isSecretMarker(v) || options.inlineSecretsAsViews === true && v !== void 0;
5787
+ if (isKeychainStoredField(field) && asView(storedValue)) return {
5788
+ ...field,
5789
+ value: toSecretFieldView(storedValue)
5790
+ };
5791
+ if (isKeychainStoredField(field) && options.inlineSecretsAsViews === true) return {
5792
+ ...field,
5793
+ value: null
5794
+ };
5795
+ if (field.type === "editable-array" && Array.isArray(storedValue)) {
5796
+ const secretItemKeys = field.itemFields.filter((item) => "key" in item && isKeychainStoredField(item)).map((item) => "key" in item ? item.key : "");
5797
+ if (secretItemKeys.length > 0) {
5798
+ const rows = storedValue.map((row) => {
5799
+ if (row === null || typeof row !== "object" || Array.isArray(row)) return row;
5800
+ const out = { ...row };
5801
+ for (const k of secretItemKeys) {
5802
+ const v = Reflect.get(row, k);
5803
+ if (asView(v)) out[k] = toSecretFieldView(v);
5804
+ }
5805
+ return out;
5806
+ });
5807
+ return {
5808
+ ...field,
5809
+ value: rows
5810
+ };
5811
+ }
5812
+ }
5702
5813
  if (field.multiple) {
5703
5814
  const stored = Array.isArray(storedValue) ? storedValue : storedValue !== void 0 && storedValue !== null ? [storedValue] : [];
5704
5815
  const itemFallback = field.multiple.itemDefault !== void 0 ? field.multiple.itemDefault : defaultValue !== void 0 ? defaultValue : typeOf(field) === "string" ? "" : null;
@@ -5941,6 +6052,431 @@ function projectStore(store, perNodeKeys, nodeId) {
5941
6052
  }
5942
6053
  return out;
5943
6054
  }
6055
+ var GLOBAL_SCOPE = { kind: "global" };
6056
+ /** The scope every addon-wide (not per-node, not per-device) setting lives in. */
6057
+ function globalSecretScope() {
6058
+ return GLOBAL_SCOPE;
6059
+ }
6060
+ function encodeSegment(value) {
6061
+ return encodeURIComponent(value);
6062
+ }
6063
+ /**
6064
+ * The field path of a value inside an array item, addressed by the item's id:
6065
+ * `arrayItemFieldPath('providers', 'authentik', 'clientSecret')` →
6066
+ * `providers[authentik].clientSecret`.
6067
+ */
6068
+ function arrayItemFieldPath(arrayKey, itemId, fieldKey) {
6069
+ return `${arrayKey}[${encodeSegment(itemId)}].${fieldKey}`;
6070
+ }
6071
+ /** A write to a secret path could not be stored in the keychain, so it was refused. */
6072
+ var KeychainWriteRefusedError = class extends Error {
6073
+ fieldPath;
6074
+ constructor(fieldPath, cause) {
6075
+ super(`secret "${fieldPath}" was not saved: the keychain could not store it (${cause instanceof Error ? cause.message : String(cause)}). Nothing was written.`);
6076
+ this.fieldPath = fieldPath;
6077
+ this.name = "KeychainWriteRefusedError";
6078
+ }
6079
+ };
6080
+ var KEEP = { kind: "keep" };
6081
+ function isRecord(value) {
6082
+ return typeof value === "object" && value !== null && !Array.isArray(value);
6083
+ }
6084
+ function defaultMintId() {
6085
+ return globalThis.crypto.randomUUID();
6086
+ }
6087
+ /** Every marker ref anywhere under `value`. */
6088
+ function collectSecretMarkerRefs(value, out = []) {
6089
+ if (isSecretMarker(value)) {
6090
+ out.push(value.$secret);
6091
+ return out;
6092
+ }
6093
+ if (Array.isArray(value)) for (const item of value) collectSecretMarkerRefs(item, out);
6094
+ else if (isRecord(value)) for (const child of Object.values(value)) collectSecretMarkerRefs(child, out);
6095
+ return out;
6096
+ }
6097
+ async function storedValueEquals(secrets, marker, candidate) {
6098
+ const resolved = (await secrets.resolve([marker.$secret]))[marker.$secret];
6099
+ return resolved?.kind === "value" && resolved.value === candidate;
6100
+ }
6101
+ async function writeLeaf(ctx, incoming, stored, fieldPath) {
6102
+ const intent = classifySecretWrite(incoming);
6103
+ const ref = ctx.secrets.ref(ctx.scope, fieldPath);
6104
+ const storedIsOurs = isSecretMarker(stored) && stored.$secret === ref;
6105
+ if (intent.kind === "keep") return KEEP;
6106
+ if (intent.kind === "set" && !ctx.operatorWrite && typeof stored === "string" && stored === intent.value) return KEEP;
6107
+ if (intent.kind === "clear") {
6108
+ if (storedIsOurs) ctx.deletes.push(ref);
6109
+ return {
6110
+ kind: "value",
6111
+ value: null
6112
+ };
6113
+ }
6114
+ if (storedIsOurs && await storedValueEquals(ctx.secrets, stored, intent.value)) return {
6115
+ kind: "value",
6116
+ value: stored
6117
+ };
6118
+ try {
6119
+ await ctx.secrets.put(ref, intent.value);
6120
+ } catch (err) {
6121
+ throw new KeychainWriteRefusedError(fieldPath, err);
6122
+ }
6123
+ return {
6124
+ kind: "value",
6125
+ value: makeSecretMarker(ref)
6126
+ };
6127
+ }
6128
+ /** Apply a member result onto `out`: KEEP restores the stored member, or removes it. */
6129
+ function applyMember(out, key, result, storedParent) {
6130
+ if (result.kind === "value") {
6131
+ out[key] = result.value;
6132
+ return;
6133
+ }
6134
+ if (Object.prototype.hasOwnProperty.call(storedParent, key)) out[key] = storedParent[key];
6135
+ else delete out[key];
6136
+ }
6137
+ async function writeMembers(ctx, children, incoming, stored, pathOf) {
6138
+ const out = { ...incoming };
6139
+ for (const [member, node] of children) applyMember(out, member, await writeNode(ctx, node, incoming[member], stored[member], pathOf(member)), stored);
6140
+ return out;
6141
+ }
6142
+ function rowId(row, idKey) {
6143
+ const raw = row[idKey];
6144
+ if (typeof raw === "string" && raw.length > 0) return raw;
6145
+ if (typeof raw === "number" && Number.isFinite(raw)) return String(raw);
6146
+ return null;
6147
+ }
6148
+ async function writeArray(ctx, node, incoming, stored, fieldPath) {
6149
+ const storedRows = Array.isArray(stored) ? stored.filter(isRecord) : [];
6150
+ if (!Array.isArray(incoming)) {
6151
+ ctx.deletes.push(...collectSecretMarkerRefs(storedRows));
6152
+ return {
6153
+ kind: "value",
6154
+ value: incoming
6155
+ };
6156
+ }
6157
+ const storedById = /* @__PURE__ */ new Map();
6158
+ for (const row of storedRows) {
6159
+ const id = rowId(row, node.idKey);
6160
+ if (id !== null) storedById.set(id, row);
6161
+ }
6162
+ const kept = /* @__PURE__ */ new Set();
6163
+ const rows = [];
6164
+ for (const row of incoming) {
6165
+ if (!isRecord(row)) {
6166
+ rows.push(row);
6167
+ continue;
6168
+ }
6169
+ const id = rowId(row, node.idKey) ?? ctx.mintId();
6170
+ kept.add(id);
6171
+ const withId = {
6172
+ ...row,
6173
+ [node.idKey]: row[node.idKey] ?? id
6174
+ };
6175
+ if (rowId(withId, node.idKey) === null) withId[node.idKey] = id;
6176
+ const storedRow = storedById.get(id) ?? {};
6177
+ rows.push(await writeMembers(ctx, node.item, withId, storedRow, (member) => arrayItemFieldPath(fieldPath, id, member)));
6178
+ }
6179
+ for (const [id, row] of storedById) if (!kept.has(id)) ctx.deletes.push(...collectSecretMarkerRefs(row));
6180
+ return {
6181
+ kind: "value",
6182
+ value: rows
6183
+ };
6184
+ }
6185
+ async function writeNode(ctx, node, incoming, stored, fieldPath) {
6186
+ switch (node.kind) {
6187
+ case "leaf": return writeLeaf(ctx, incoming, stored, fieldPath);
6188
+ case "array": return writeArray(ctx, node, incoming, stored, fieldPath);
6189
+ case "object": {
6190
+ if (!isRecord(incoming)) {
6191
+ if (incoming === void 0) return KEEP;
6192
+ ctx.deletes.push(...collectSecretMarkerRefs(stored));
6193
+ return {
6194
+ kind: "value",
6195
+ value: incoming
6196
+ };
6197
+ }
6198
+ const storedObj = isRecord(stored) ? stored : {};
6199
+ return {
6200
+ kind: "value",
6201
+ value: await writeMembers(ctx, node.children, incoming, storedObj, (m) => `${fieldPath}.${m}`)
6202
+ };
6203
+ }
6204
+ }
6205
+ }
6206
+ /** Split a perNode-scoped key (`key@nodeId`). */
6207
+ function splitNodeKey(key) {
6208
+ const at = key.indexOf("@");
6209
+ return at <= 0 ? {
6210
+ base: key,
6211
+ nodeId: null
6212
+ } : {
6213
+ base: key.slice(0, at),
6214
+ nodeId: key.slice(at + 1)
6215
+ };
6216
+ }
6217
+ /** Rewrite a settings patch so no secret value reaches the blob. See the file doc. */
6218
+ async function transformSecretWrite(input) {
6219
+ const deletes = [];
6220
+ const base = {
6221
+ secrets: input.secrets,
6222
+ mintId: input.mintId ?? defaultMintId,
6223
+ deletes,
6224
+ operatorWrite: input.operatorWrite === true
6225
+ };
6226
+ const out = {};
6227
+ for (const [key, incoming] of Object.entries(input.patch)) {
6228
+ const { base: baseKey, nodeId } = splitNodeKey(key);
6229
+ const node = input.tree.get(baseKey);
6230
+ if (node === void 0) {
6231
+ out[key] = incoming;
6232
+ continue;
6233
+ }
6234
+ const scope = nodeId !== null && nodeId.length > 0 ? {
6235
+ kind: "node",
6236
+ nodeId
6237
+ } : input.scope ?? globalSecretScope();
6238
+ const result = await writeNode({
6239
+ ...base,
6240
+ scope
6241
+ }, node, incoming, input.stored[key], baseKey);
6242
+ if (result.kind === "value") out[key] = result.value;
6243
+ }
6244
+ return {
6245
+ patch: out,
6246
+ afterWrite: async () => {
6247
+ if (deletes.length === 0) return { orphaned: [] };
6248
+ try {
6249
+ await input.secrets.delete([...new Set(deletes)]);
6250
+ return { orphaned: [] };
6251
+ } catch {
6252
+ return { orphaned: [...new Set(deletes)] };
6253
+ }
6254
+ }
6255
+ };
6256
+ }
6257
+ /**
6258
+ * Replace every marker in `value` with its keychain value. Returns the SAME
6259
+ * reference when there is no marker (no allocation, no keychain call).
6260
+ */
6261
+ async function resolveSecretMarkers(value, secrets) {
6262
+ const refs = collectSecretMarkerRefs(value);
6263
+ if (refs.length === 0) return {
6264
+ value,
6265
+ unresolved: []
6266
+ };
6267
+ const answers = await secrets.resolve(refs);
6268
+ const unresolved = [];
6269
+ for (const ref of new Set(refs)) {
6270
+ const answer = answers[ref];
6271
+ if (answer === void 0) unresolved.push({
6272
+ ref,
6273
+ reason: "not-initialized"
6274
+ });
6275
+ else if (answer.kind === "unavailable") unresolved.push({
6276
+ ref,
6277
+ reason: answer.reason
6278
+ });
6279
+ else if (answer.kind === "missing" || answer.kind === "forbidden") unresolved.push({
6280
+ ref,
6281
+ reason: answer.kind
6282
+ });
6283
+ }
6284
+ const substitute = (v) => {
6285
+ if (isSecretMarker(v)) {
6286
+ const answer = answers[v.$secret];
6287
+ return answer?.kind === "value" ? {
6288
+ keep: true,
6289
+ value: answer.value
6290
+ } : {
6291
+ keep: false,
6292
+ value: void 0
6293
+ };
6294
+ }
6295
+ if (Array.isArray(v)) {
6296
+ const items = [];
6297
+ for (const item of v) {
6298
+ const s = substitute(item);
6299
+ if (s.keep) items.push(s.value);
6300
+ }
6301
+ return {
6302
+ keep: true,
6303
+ value: items
6304
+ };
6305
+ }
6306
+ if (isRecord(v)) {
6307
+ const out = {};
6308
+ for (const [k, child] of Object.entries(v)) {
6309
+ const s = substitute(child);
6310
+ if (s.keep) out[k] = s.value;
6311
+ }
6312
+ return {
6313
+ keep: true,
6314
+ value: out
6315
+ };
6316
+ }
6317
+ return {
6318
+ keep: true,
6319
+ value: v
6320
+ };
6321
+ };
6322
+ return {
6323
+ value: substitute(value).value,
6324
+ unresolved
6325
+ };
6326
+ }
6327
+ function touchesTree(tree, patch) {
6328
+ if (tree.size === 0) return false;
6329
+ for (const key of Object.keys(patch)) {
6330
+ const at = key.indexOf("@");
6331
+ if (tree.has(at > 0 ? key.slice(0, at) : key)) return true;
6332
+ }
6333
+ return false;
6334
+ }
6335
+ /** The blob as stored now; a failed read REFUSES the write instead of guessing. */
6336
+ async function readStoredAddonBlob(raw) {
6337
+ const threeWay = raw.readAddonStoreResult;
6338
+ if (threeWay === void 0) return raw.readAddonStore();
6339
+ const result = await threeWay.call(raw);
6340
+ if (result.kind === "failed") throw new Error(`settings write refused: the stored blob could not be read (${result.error})`);
6341
+ return result.kind === "missing" ? {} : result.value;
6342
+ }
6343
+ function createSecretAwareSettings(raw, opts) {
6344
+ const chains = /* @__PURE__ */ new Map();
6345
+ const serialize = (key, fn) => {
6346
+ const next = (chains.get(key) ?? Promise.resolve()).then(fn, fn);
6347
+ const tail = next.catch(() => void 0);
6348
+ chains.set(key, tail);
6349
+ tail.then(() => {
6350
+ if (chains.get(key) === tail) chains.delete(key);
6351
+ });
6352
+ return next;
6353
+ };
6354
+ const write = async (chainKey, tree, scope, patch, readStored, rawWrite) => {
6355
+ if (!touchesTree(tree, patch)) return rawWrite(patch);
6356
+ return serialize(chainKey, async () => {
6357
+ const stored = await readStored();
6358
+ const result = await transformSecretWrite({
6359
+ tree,
6360
+ secrets: opts.secrets,
6361
+ patch,
6362
+ stored,
6363
+ ...scope !== void 0 ? { scope } : {},
6364
+ operatorWrite: opts.isOperatorWrite?.() === true
6365
+ });
6366
+ if (Object.keys(result.patch).length > 0) await rawWrite(result.patch);
6367
+ const { orphaned } = await result.afterWrite();
6368
+ if (orphaned.length > 0) opts.onOrphaned(orphaned);
6369
+ });
6370
+ };
6371
+ const wrapped = {
6372
+ writeAddonStore: (patch) => write("addon", opts.addonTree(), void 0, patch, () => readStoredAddonBlob(raw), (p) => raw.writeAddonStore(p)),
6373
+ writeDeviceStore: (deviceId, patch) => write(`device:${deviceId}`, opts.deviceTree(), {
6374
+ kind: "device",
6375
+ deviceId
6376
+ }, patch, () => raw.readDeviceStore(deviceId), (p) => raw.writeDeviceStore(deviceId, p))
6377
+ };
6378
+ return new Proxy(raw, { get(target, prop, receiver) {
6379
+ if (prop === "writeAddonStore") return wrapped.writeAddonStore;
6380
+ if (prop === "writeDeviceStore") return wrapped.writeDeviceStore;
6381
+ const value = Reflect.get(target, prop, receiver);
6382
+ return typeof value === "function" ? value.bind(target) : value;
6383
+ } });
6384
+ }
6385
+ /** The context the addon sees: identical, except that its settings writes are secret-aware. */
6386
+ function withSecretAwareSettings(context, opts) {
6387
+ const raw = context.settings;
6388
+ if (raw === void 0) return context;
6389
+ const settings = createSecretAwareSettings(raw, opts);
6390
+ return new Proxy(context, { get(target, prop, receiver) {
6391
+ if (prop === "settings") return settings;
6392
+ return Reflect.get(target, prop, receiver);
6393
+ } });
6394
+ }
6395
+ var LEAF = { kind: "leaf" };
6396
+ var DEFAULT_ITEM_ID_KEY = "id";
6397
+ function collectFields(fields, out) {
6398
+ for (const field of fields) {
6399
+ if (field.type === "group") {
6400
+ collectFields(field.fields, out);
6401
+ continue;
6402
+ }
6403
+ if (field.type === "sub-tabs") {
6404
+ for (const tab of field.tabs) collectFields(tab.fields, out);
6405
+ continue;
6406
+ }
6407
+ if (field.type === "editable-array") {
6408
+ const item = /* @__PURE__ */ new Map();
6409
+ for (const itemField of field.itemFields) if ("key" in itemField && isKeychainStoredField(itemField)) item.set(itemField.key, LEAF);
6410
+ if (item.size > 0) out.set(field.key, {
6411
+ kind: "array",
6412
+ idKey: field.itemIdKey ?? DEFAULT_ITEM_ID_KEY,
6413
+ item
6414
+ });
6415
+ continue;
6416
+ }
6417
+ if (!("key" in field) || typeof field.key !== "string") continue;
6418
+ if (isKeychainStoredField(field)) out.set(field.key, LEAF);
6419
+ }
6420
+ }
6421
+ /** The secret tree a settings schema declares. */
6422
+ function secretTreeFromSchema(schema) {
6423
+ const out = /* @__PURE__ */ new Map();
6424
+ if (schema === null) return out;
6425
+ for (const section of schema.sections) collectFields(section.fields, out);
6426
+ return out;
6427
+ }
6428
+ /** Parse `a.b[id].c` into segments; throws on a malformed path (a declaration bug). */
6429
+ function parseSecretStatePath(path) {
6430
+ const segments = [];
6431
+ for (const raw of path.split(".")) {
6432
+ const m = /^([^[\]]+)(?:\[([^[\]]+)\])?$/.exec(raw);
6433
+ if (m === null || m[1] === void 0) throw new Error(`secretStatePaths: malformed path "${path}"`);
6434
+ segments.push(m[2] !== void 0 ? {
6435
+ key: m[1],
6436
+ idKey: m[2]
6437
+ } : { key: m[1] });
6438
+ }
6439
+ if (segments.length === 0) throw new Error(`secretStatePaths: empty path`);
6440
+ if (segments[segments.length - 1]?.idKey !== void 0) throw new Error(`secretStatePaths: "${path}" ends on an array — name the member that is secret`);
6441
+ return segments;
6442
+ }
6443
+ function insert(into, segments) {
6444
+ const [head, ...rest] = segments;
6445
+ if (head === void 0) return;
6446
+ if (rest.length === 0) {
6447
+ into.set(head.key, LEAF);
6448
+ return;
6449
+ }
6450
+ const existing = into.get(head.key);
6451
+ if (head.idKey !== void 0) {
6452
+ const item = new Map(existing?.kind === "array" ? existing.item : []);
6453
+ insert(item, rest);
6454
+ into.set(head.key, {
6455
+ kind: "array",
6456
+ idKey: head.idKey,
6457
+ item
6458
+ });
6459
+ return;
6460
+ }
6461
+ const children = new Map(existing?.kind === "object" ? existing.children : []);
6462
+ insert(children, rest);
6463
+ into.set(head.key, {
6464
+ kind: "object",
6465
+ children
6466
+ });
6467
+ }
6468
+ /** Add hidden-state paths (`secretStatePaths`) to a schema-derived tree. */
6469
+ function mergeSecretStatePaths(tree, paths) {
6470
+ if (paths.length === 0) return tree;
6471
+ const out = new Map(tree);
6472
+ for (const path of paths) insert(out, parseSecretStatePath(path));
6473
+ return out;
6474
+ }
6475
+ /** First retry of a secret the keychain could not serve; doubles to {@link SECRET_RETRY_MAX_MS}. */
6476
+ var SECRET_RETRY_FIRST_MS = 5e3;
6477
+ var SECRET_RETRY_MAX_MS = 5 * 6e4;
6478
+ /** Coalesces a burst of `keychain.changed` events into one re-resolve. */
6479
+ var SECRET_CHANGE_DEBOUNCE_MS = 250;
5944
6480
  /**
5945
6481
  * Base class for CamStack addons. Eliminates settings boilerplate:
5946
6482
  *
@@ -6010,6 +6546,25 @@ var BaseAddon = class {
6010
6546
  settingsStoreReady = false;
6011
6547
  /** Default config values. Provided via constructor. */
6012
6548
  defaults;
6549
+ /**
6550
+ * Hidden-state paths that hold secrets (D787) — values the addon writes
6551
+ * itself (`updateGlobalSettings`, `state()`) that no form field declares.
6552
+ * Stored in the keychain exactly like a `password` field. Syntax:
6553
+ * `'snapshotSigningKey'`, `'identity.pincode'`, `'tokens[userId].accessToken'`
6554
+ * (`key[<id field>]` addresses array items by id, never by index).
6555
+ */
6556
+ secretStatePaths = [];
6557
+ _addonSecretTree = null;
6558
+ _deviceSecretTree = null;
6559
+ /** Refs the last resolved config pointed at — a change to one re-resolves. */
6560
+ _configSecretRefs = /* @__PURE__ */ new Set();
6561
+ _unresolvedSecrets = [];
6562
+ _secretRetryTimer = null;
6563
+ _secretRetryDelayMs = SECRET_RETRY_FIRST_MS;
6564
+ _secretChangeTimer = null;
6565
+ _secretChangeUnsub = null;
6566
+ /** >0 while an OPERATOR's settings write is being applied. */
6567
+ _operatorWriteDepth = 0;
6013
6568
  constructor(defaults) {
6014
6569
  this.defaults = defaults;
6015
6570
  this._config = { ...defaults };
@@ -6045,8 +6600,18 @@ var BaseAddon = class {
6045
6600
  return this._config;
6046
6601
  }
6047
6602
  async initialize(context) {
6048
- this._ctx = context;
6603
+ const secrets = context.secrets;
6604
+ this._ctx = secrets !== void 0 ? withSecretAwareSettings(context, {
6605
+ secrets,
6606
+ addonTree: () => this.addonSecretTree(),
6607
+ deviceTree: () => this.deviceSecretTree(),
6608
+ onOrphaned: (refs) => context.logger.warn("keychain refs dropped by a settings write could not be deleted", { meta: { refs: [...refs] } }),
6609
+ isOperatorWrite: () => this._operatorWriteDepth > 0
6610
+ }) : context;
6049
6611
  await this.resolveConfig();
6612
+ if (secrets !== void 0) this._secretChangeUnsub = secrets.onChange((ref) => {
6613
+ if (this._configSecretRefs.has(ref)) this.scheduleSecretReresolve(SECRET_CHANGE_DEBOUNCE_MS);
6614
+ });
6050
6615
  const result = await this.onInitialize();
6051
6616
  this.emitLifecycle(EventCategory.AddonStarted);
6052
6617
  const normalized = normalizeAddonInitResult(result);
@@ -6079,6 +6644,12 @@ var BaseAddon = class {
6079
6644
  */
6080
6645
  async onHubReachable() {}
6081
6646
  async shutdown() {
6647
+ this._secretChangeUnsub?.();
6648
+ this._secretChangeUnsub = null;
6649
+ if (this._secretRetryTimer !== null) clearTimeout(this._secretRetryTimer);
6650
+ if (this._secretChangeTimer !== null) clearTimeout(this._secretChangeTimer);
6651
+ this._secretRetryTimer = null;
6652
+ this._secretChangeTimer = null;
6082
6653
  this.emitLifecycle(EventCategory.AddonStopped);
6083
6654
  if (this.autoEmitReadiness) this.emitReadinessForProviders("down");
6084
6655
  await this.onShutdown();
@@ -6157,7 +6728,7 @@ var BaseAddon = class {
6157
6728
  return hydrateSchema(schema, overlay ? {
6158
6729
  ...projected,
6159
6730
  ...overlay
6160
- } : projected);
6731
+ } : projected, { inlineSecretsAsViews: true });
6161
6732
  }
6162
6733
  /**
6163
6734
  * The integration-level view of this addon's settings: exactly the sections
@@ -6206,7 +6777,7 @@ var BaseAddon = class {
6206
6777
  return hydrateSchema({
6207
6778
  ...schema,
6208
6779
  sections
6209
- }, projected);
6780
+ }, projected, { inlineSecretsAsViews: true });
6210
6781
  }
6211
6782
  /**
6212
6783
  * The raw addon store PROJECTED onto the target node's bare per-node keys:
@@ -6260,18 +6831,50 @@ var BaseAddon = class {
6260
6831
  value: result.value[key]
6261
6832
  };
6262
6833
  }
6834
+ /**
6835
+ * The OPERATOR's write — a settings form or an admin API call, dispatched by
6836
+ * the kernel. Identical to {@link updateGlobalSettings}, except that a secret
6837
+ * the operator sends is stored as sent even when it equals a pre-keychain
6838
+ * inline value: the operator re-entering a password is a change, an addon
6839
+ * writing back what it read is not (D787).
6840
+ */
6841
+ async updateGlobalSettingsAsOperator(patch, nodeId) {
6842
+ this._operatorWriteDepth++;
6843
+ try {
6844
+ await this.applyGlobalPatch(patch, nodeId);
6845
+ } finally {
6846
+ this._operatorWriteDepth--;
6847
+ }
6848
+ }
6263
6849
  async updateGlobalSettings(patch, nodeId) {
6850
+ await this.applyGlobalPatch(patch, nodeId);
6851
+ }
6852
+ /**
6853
+ * REMOVE stored secrets — their keychain values and their markers (D787).
6854
+ *
6855
+ * Writing `''` to a secret field KEEPS what is stored (an empty string is
6856
+ * what a defaults fallback writes back, and it must never destroy a
6857
+ * credential), so code that means "forget this token" says so here. Without
6858
+ * a keychain (an older kernel) it writes `''`, as such code always did.
6859
+ */
6860
+ async clearSecrets(keys, nodeId) {
6861
+ const tree = this.addonSecretTree();
6862
+ const keychain = this._ctx?.secrets !== void 0;
6863
+ const patch = {};
6864
+ for (const key of keys) patch[key] = keychain && tree.has(key) ? SECRET_CLEAR : "";
6865
+ await this.applyGlobalPatch(patch, nodeId);
6866
+ }
6867
+ async applyGlobalPatch(barePatch, nodeId) {
6264
6868
  const keys = this.perNodeKeys();
6265
6869
  const localNode = normalizeNodeId(this._ctx?.kernel?.localNodeId);
6266
6870
  const target = normalizeNodeId(nodeId ?? this._ctx?.kernel?.localNodeId);
6267
- const barePatch = patch;
6268
6871
  const scoped = keys.size > 0 ? scopePatch(barePatch, keys, target) : barePatch;
6269
6872
  await this._ctx?.settings?.writeAddonStore(scoped);
6270
6873
  if (target !== localNode) return;
6271
6874
  await this.resolveConfig();
6272
6875
  await this.onConfigChanged();
6273
6876
  this.emitLifecycle(EventCategory.AddonUpdated, { level: "global" });
6274
- this.maybeAutoRestart(patch, this.globalSettingsSchema());
6877
+ this.maybeAutoRestart(Object.keys(barePatch), this.globalSettingsSchema());
6275
6878
  }
6276
6879
  /**
6277
6880
  * The set of field keys the global settings schema declares `perNode: true`
@@ -6296,7 +6899,7 @@ var BaseAddon = class {
6296
6899
  * time to return its response before the addon is torn down and
6297
6900
  * re-initialised by `AddonRegistryService.restartAddon`.
6298
6901
  */
6299
- maybeAutoRestart(patch, schema) {
6902
+ maybeAutoRestart(patchKeys, schema) {
6300
6903
  if (!schema) return;
6301
6904
  const restartKeys = /* @__PURE__ */ new Set();
6302
6905
  for (const section of schema.sections) for (const field of section.fields) {
@@ -6304,13 +6907,13 @@ var BaseAddon = class {
6304
6907
  if (field.requiresRestart) restartKeys.add(field.key);
6305
6908
  }
6306
6909
  if (restartKeys.size === 0) return;
6307
- if (!Object.keys(patch).some((k) => restartKeys.has(k))) return;
6910
+ if (!patchKeys.some((k) => restartKeys.has(k))) return;
6308
6911
  const ctx = this._ctx;
6309
6912
  if (!ctx) return;
6310
6913
  const addonId = ctx.id;
6311
6914
  setImmediate(() => {
6312
6915
  ctx.api.addons?.restartAddon?.mutate({ addonId }).then(() => {
6313
- ctx.logger.info("addon auto-restart triggered by restart-required setting change", { meta: { changedFields: Object.keys(patch).filter((k) => restartKeys.has(k)) } });
6916
+ ctx.logger.info("addon auto-restart triggered by restart-required setting change", { meta: { changedFields: patchKeys.filter((k) => restartKeys.has(k)) } });
6314
6917
  }).catch((err) => {
6315
6918
  ctx.logger.error("addon auto-restart failed", { meta: { error: err instanceof Error ? err.message : String(err) } });
6316
6919
  });
@@ -6319,7 +6922,7 @@ var BaseAddon = class {
6319
6922
  async getDeviceSettings(deviceId) {
6320
6923
  const schema = this.deviceSettingsSchema();
6321
6924
  if (!schema) return { sections: [] };
6322
- return hydrateSchema(schema, await this._ctx?.settings?.readDeviceStore(deviceId) ?? {});
6925
+ return hydrateSchema(schema, await this._ctx?.settings?.readDeviceStore(deviceId) ?? {}, { inlineSecretsAsViews: true });
6323
6926
  }
6324
6927
  async updateDeviceSettings(deviceId, patch) {
6325
6928
  await this._ctx?.settings?.writeDeviceStore(deviceId, patch);
@@ -6449,7 +7052,7 @@ var BaseAddon = class {
6449
7052
  * selection at boot (absent scoped key ⇒ the constructor default wins).
6450
7053
  */
6451
7054
  async resolveConfig() {
6452
- const stored = await this.readAddonStoreWithRetry();
7055
+ const stored = await this.resolveStoredSecrets(await this.readAddonStoreWithRetry());
6453
7056
  const perNode = this.perNodeKeys();
6454
7057
  const localNode = normalizeNodeId(this._ctx?.kernel?.localNodeId);
6455
7058
  const resolved = { ...this.defaults };
@@ -6474,7 +7077,7 @@ var BaseAddon = class {
6474
7077
  key,
6475
7078
  schema,
6476
7079
  fallback,
6477
- read: () => this.readAddonStoreWithRetry(),
7080
+ read: async () => this.resolveStoredSecrets(await this.readAddonStoreWithRetry()),
6478
7081
  write: async (patch) => {
6479
7082
  await this._ctx?.settings?.writeAddonStore(patch);
6480
7083
  },
@@ -6491,7 +7094,7 @@ var BaseAddon = class {
6491
7094
  key,
6492
7095
  schema,
6493
7096
  fallback,
6494
- read: async () => await this._ctx?.settings?.readDeviceStore(deviceId) ?? {},
7097
+ read: async () => this.resolveStoredSecrets(await this._ctx?.settings?.readDeviceStore(deviceId) ?? {}, false),
6495
7098
  write: async (patch) => {
6496
7099
  await this._ctx?.settings?.writeDeviceStore(deviceId, patch);
6497
7100
  },
@@ -6503,6 +7106,70 @@ var BaseAddon = class {
6503
7106
  } })
6504
7107
  });
6505
7108
  }
7109
+ /** The addon store's secret tree: schema fields by TYPE, plus `secretStatePaths`. */
7110
+ addonSecretTree() {
7111
+ this._addonSecretTree ??= mergeSecretStatePaths(secretTreeFromSchema(this.globalSettingsSchema()), this.secretStatePaths);
7112
+ return this._addonSecretTree;
7113
+ }
7114
+ deviceSecretTree() {
7115
+ this._deviceSecretTree ??= secretTreeFromSchema(this.deviceSettingsSchema());
7116
+ return this._deviceSecretTree;
7117
+ }
7118
+ /**
7119
+ * Secrets of this addon's stored config that could not be resolved on the
7120
+ * last read, with why. Non-empty means the addon is running WITHOUT them —
7121
+ * an addon whose function needs one should report itself degraded rather
7122
+ * than start on an empty credential.
7123
+ */
7124
+ get unresolvedSecrets() {
7125
+ return this._unresolvedSecrets;
7126
+ }
7127
+ /**
7128
+ * Substitute every keychain marker in a stored blob with its value. With no
7129
+ * keychain (no `ctx.secrets`) or no marker, the blob comes back unchanged.
7130
+ * An unresolvable value is LEFT OUT (never `''`), logged by ref — never by
7131
+ * value — and, when the cause can pass, retried with backoff. Nothing is
7132
+ * ever written back from here.
7133
+ */
7134
+ async resolveStoredSecrets(blob, trackForConfig = true) {
7135
+ const secrets = this._ctx?.secrets;
7136
+ if (secrets === void 0) return blob;
7137
+ const refs = collectSecretMarkerRefs(blob);
7138
+ if (trackForConfig) this._configSecretRefs = new Set(refs);
7139
+ if (refs.length === 0) {
7140
+ if (trackForConfig) this._unresolvedSecrets = [];
7141
+ return blob;
7142
+ }
7143
+ const { value, unresolved } = await resolveSecretMarkers(blob, secrets);
7144
+ if (trackForConfig) {
7145
+ this._unresolvedSecrets = unresolved;
7146
+ if (unresolved.length > 0) {
7147
+ this._ctx?.logger?.error?.("secret unavailable — running without it, will retry", { meta: { secrets: unresolved.map((u) => ({
7148
+ ref: u.ref,
7149
+ reason: u.reason
7150
+ })) } });
7151
+ if (unresolved.some((u) => u.reason !== "missing" && u.reason !== "forbidden")) {
7152
+ this.scheduleSecretReresolve(this._secretRetryDelayMs);
7153
+ this._secretRetryDelayMs = Math.min(this._secretRetryDelayMs * 2, SECRET_RETRY_MAX_MS);
7154
+ }
7155
+ } else this._secretRetryDelayMs = SECRET_RETRY_FIRST_MS;
7156
+ }
7157
+ return value;
7158
+ }
7159
+ /** Re-resolve the config (a keychain-only change, or a retry) and apply it. */
7160
+ scheduleSecretReresolve(delayMs) {
7161
+ const timerOf = delayMs === SECRET_CHANGE_DEBOUNCE_MS ? "_secretChangeTimer" : "_secretRetryTimer";
7162
+ if (this[timerOf] !== null) return;
7163
+ const timer = setTimeout(() => {
7164
+ this[timerOf] = null;
7165
+ if (this._ctx === null) return;
7166
+ this.resolveConfig().then(() => this.onConfigChanged()).catch((err) => {
7167
+ this._ctx?.logger?.error?.("re-resolving secrets failed", { meta: { error: err instanceof Error ? err.message : String(err) } });
7168
+ });
7169
+ }, delayMs);
7170
+ timer.unref?.();
7171
+ this[timerOf] = timer;
7172
+ }
6506
7173
  /**
6507
7174
  * Wrap `ctx.settings.readAddonStore()` with a short retry budget so a
6508
7175
  * transient settings-store outage (mid-restart of sqlite-settings, tsx-watch
@@ -7090,6 +7757,69 @@ method(object({ deviceId: number() }), array(StreamSourceEntrySchema)), method(o
7090
7757
  kind: "mutation",
7091
7758
  auth: "admin"
7092
7759
  }), method(object({ deviceId: number() }), unknown().nullable()), method(object({ deviceId: number() }), RawStateResultSchema.nullable(), { auth: "protected" });
7760
+ function defOf(schema) {
7761
+ return schema._zod?.def ?? {};
7762
+ }
7763
+ function declaredHere(schema) {
7764
+ return globalRegistry.get(schema)?.secret === true;
7765
+ }
7766
+ /** Wrapper kinds whose `innerType` is the field itself. */
7767
+ var WRAPPERS = new Set([
7768
+ "optional",
7769
+ "nullable",
7770
+ "default",
7771
+ "prefault",
7772
+ "catch",
7773
+ "readonly",
7774
+ "nonoptional"
7775
+ ]);
7776
+ /**
7777
+ * The schema layers that make up ONE field: the schema itself and every
7778
+ * wrapper below it (optional / default / nullable / readonly / catch), plus
7779
+ * both sides of a pipe (`z.preprocess` puts the real schema on `out`,
7780
+ * `.transform` on `in`).
7781
+ */
7782
+ function layersOf(schema) {
7783
+ const out = [];
7784
+ const queue = [schema];
7785
+ while (queue.length > 0) {
7786
+ const s = queue.shift();
7787
+ if (!s || out.includes(s)) continue;
7788
+ out.push(s);
7789
+ const def = defOf(s);
7790
+ if (def.type !== void 0 && WRAPPERS.has(def.type) && def.innerType) queue.push(def.innerType);
7791
+ if (def.type === "pipe") {
7792
+ if (def.in) queue.push(def.in);
7793
+ if (def.out) queue.push(def.out);
7794
+ }
7795
+ }
7796
+ return out;
7797
+ }
7798
+ /** True when any layer of this field declares `.meta({ secret: true })`. */
7799
+ function isZodSecret(schema) {
7800
+ return layersOf(schema).some(declaredHere);
7801
+ }
7802
+ /**
7803
+ * Every declared secret path in a config schema: dotted keys, `[]` for "each
7804
+ * element of this array" (`connection.password`, `rows[].token`). A declared
7805
+ * object or array is reported as one path and not descended into — everything
7806
+ * under it is secret.
7807
+ */
7808
+ function collectZodSecretPaths(schema, prefix = "") {
7809
+ if (isZodSecret(schema)) return prefix.length > 0 ? [prefix] : [];
7810
+ const paths = [];
7811
+ for (const layer of layersOf(schema)) {
7812
+ const def = defOf(layer);
7813
+ if (def.type === "object" && def.shape) for (const [key, child] of Object.entries(def.shape)) paths.push(...collectZodSecretPaths(child, prefix ? `${prefix}.${key}` : key));
7814
+ else if (def.type === "array" && def.element) paths.push(...collectZodSecretPaths(def.element, `${prefix}[]`));
7815
+ else if (def.type === "union" && def.options) for (const option of def.options) paths.push(...collectZodSecretPaths(option, prefix));
7816
+ else if (def.type === "intersection") {
7817
+ if (def.left) paths.push(...collectZodSecretPaths(def.left, prefix));
7818
+ if (def.right) paths.push(...collectZodSecretPaths(def.right, prefix));
7819
+ }
7820
+ }
7821
+ return [...new Set(paths)];
7822
+ }
7093
7823
  //#endregion
7094
7824
  //#region ../types/dist/err-msg-DX6i_MY4.mjs
7095
7825
  var DeviceType = /* @__PURE__ */ function(DeviceType) {
@@ -14411,6 +15141,196 @@ id: union([string(), number()]) }), {
14411
15141
  kind: "mutation",
14412
15142
  auth: "admin"
14413
15143
  });
15144
+ /**
15145
+ * `keychain` — the hub's encrypted store of secret values (D787).
15146
+ *
15147
+ * Settings blobs never hold a secret: they hold a marker
15148
+ * `{"$secret":"secret://<owner>/<scope>/<fieldPath>","v":1}` and the value
15149
+ * lives here, AES-256-GCM under a data key that a master key wraps. This cap
15150
+ * is the OWNER's door to its own values: every method is owner-checked
15151
+ * against the CALLER, never against anything the caller claims.
15152
+ *
15153
+ * Who the caller is: the transport stamps `callerAddonId` into the args of a
15154
+ * call that crossed a process (the parent `LocalChildRegistry` from the UDS
15155
+ * connection, the agent from its child's connection carried in
15156
+ * `$hub-cap-fwd`'s envelope). A stamp always overwrites; a wire call with no
15157
+ * stamp has its claim stripped. Only a hub in-process caller may state its own
15158
+ * identity — `ctx.secrets` does that with the addon id closed over. This is
15159
+ * identity against BUGS and misrouting, not against a malicious addon (every
15160
+ * runner is the same OS user): see the threat model in
15161
+ * `docs/design/2026-10-08-secrets-keychain.md`.
15162
+ *
15163
+ * `callerAddonId` is deliberately NOT in any input schema: the tRPC router
15164
+ * parses the input, so a session can never supply it, and the internal mount
15165
+ * floors every method to admin anyway (D240).
15166
+ *
15167
+ * Internal: addons reach it through `ctx.secrets`, never directly.
15168
+ */
15169
+ /** Why a value cannot be served right now. Never folded into "missing". */
15170
+ var KeychainUnavailableReasonSchema = _enum([
15171
+ "key-missing",
15172
+ "wrong-key",
15173
+ "key-file-unreadable",
15174
+ "store-unavailable",
15175
+ "not-initialized",
15176
+ "decrypt-failed"
15177
+ ]);
15178
+ var KeychainStateSchema = discriminatedUnion("state", [object({ state: literal("ready") }), object({
15179
+ state: literal("locked"),
15180
+ reason: KeychainUnavailableReasonSchema
15181
+ })]);
15182
+ var KeychainResolveEntrySchema = discriminatedUnion("kind", [
15183
+ object({
15184
+ kind: literal("value"),
15185
+ value: string(),
15186
+ version: number().int()
15187
+ }),
15188
+ object({ kind: literal("missing") }),
15189
+ object({
15190
+ kind: literal("unavailable"),
15191
+ reason: KeychainUnavailableReasonSchema
15192
+ }),
15193
+ object({ kind: literal("forbidden") })
15194
+ ]);
15195
+ var KeychainResolveResultSchema = record(string(), KeychainResolveEntrySchema);
15196
+ /** Metadata of one stored value — never the value. */
15197
+ var KeychainSecretMetaSchema = object({
15198
+ ref: string(),
15199
+ owner: string(),
15200
+ /** Formatted scope (`global`, `node/<id>`, `device/<id>`, …). */
15201
+ scope: string(),
15202
+ fieldPath: string(),
15203
+ version: number().int(),
15204
+ createdAt: number(),
15205
+ updatedAt: number(),
15206
+ /** `addon:<id>` | `user:<id>` | `system`. */
15207
+ updatedBy: string(),
15208
+ /** Coarse — written at most once an hour per ref. `null` = never read. */
15209
+ lastReadAt: number().nullable()
15210
+ });
15211
+ var RefListSchema = array(string().min(1)).max(512);
15212
+ method(object({
15213
+ ref: string().min(1),
15214
+ value: string().min(1)
15215
+ }), object({
15216
+ ref: string(),
15217
+ version: number().int()
15218
+ }), {
15219
+ kind: "mutation",
15220
+ auth: "admin"
15221
+ }), method(object({ refs: RefListSchema }), KeychainResolveResultSchema, { auth: "admin" }), method(object({ refs: RefListSchema }), object({ deleted: number().int() }), {
15222
+ kind: "mutation",
15223
+ auth: "admin"
15224
+ }), method(object({}), array(KeychainSecretMetaSchema).readonly(), { auth: "admin" }), method(object({}), KeychainStateSchema, { auth: "admin" });
15225
+ var KeychainKeySourceSchema = object({
15226
+ kind: _enum([
15227
+ "config-file",
15228
+ "previous-config-file",
15229
+ "platform",
15230
+ "default-file"
15231
+ ]),
15232
+ /** File sources only — a path is not a secret. */
15233
+ path: string().optional(),
15234
+ /**
15235
+ * True when a whole-volume backup of the data directory carries this key
15236
+ * next to the database it protects (the default file). The page warns.
15237
+ */
15238
+ sharesBackupWithDatabase: boolean()
15239
+ });
15240
+ var KeychainStatusSchema = object({
15241
+ keychain: KeychainStateSchema,
15242
+ /** The source of the master key in use; `null` while locked. */
15243
+ keySource: KeychainKeySourceSchema.nullable(),
15244
+ /** The source configured to be primary — differs from `keySource` while a rotation is pending. */
15245
+ configuredSource: KeychainKeySourceSchema,
15246
+ /** Short fingerprint of the master key in use (`HMAC(KEK, label)`, 16 hex). */
15247
+ fingerprint: string().nullable(),
15248
+ activeKeyId: string().nullable(),
15249
+ /**
15250
+ * The keychain unlocked with a NON-primary source: the configured primary
15251
+ * key is not the one that wraps the data key yet. `rotateMasterKey` moves it.
15252
+ */
15253
+ rotationPending: boolean(),
15254
+ /** Wrapped copies of the data key under a previous master key, kept until purged. */
15255
+ retiredWraps: number().int(),
15256
+ recoveryKeyDownloadedAt: number().nullable(),
15257
+ secretCount: number().int()
15258
+ });
15259
+ /**
15260
+ * Whether a stored value is still pointed at by its owner's settings.
15261
+ * `unknown` is a first-class answer: a scope whose blob could not be read is
15262
+ * never reported as an orphan (and never deleted as one).
15263
+ */
15264
+ var KeychainSecretUsageSchema = _enum([
15265
+ "in-use",
15266
+ "orphan",
15267
+ "unknown"
15268
+ ]);
15269
+ var KeychainAdminSecretSchema = KeychainSecretMetaSchema.extend({ usage: KeychainSecretUsageSchema });
15270
+ var KeychainAuditActionSchema = _enum([
15271
+ "put",
15272
+ "delete",
15273
+ "reveal",
15274
+ "rotate-master-key",
15275
+ "purge-retired-keys",
15276
+ "download-recovery-key",
15277
+ "delete-orphans",
15278
+ "reset",
15279
+ "initialize"
15280
+ ]);
15281
+ var KeychainAuditEntrySchema = object({
15282
+ id: string(),
15283
+ at: number(),
15284
+ action: KeychainAuditActionSchema,
15285
+ /** `addon:<id>` | `user:<id>` | `system`. */
15286
+ actor: string(),
15287
+ ref: string().nullable(),
15288
+ detail: string().nullable()
15289
+ });
15290
+ 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({
15291
+ value: string(),
15292
+ version: number().int()
15293
+ }), {
15294
+ kind: "mutation",
15295
+ auth: "admin",
15296
+ caller: "required"
15297
+ }), method(object({ refs: array(string().min(1)).max(1e3) }), object({
15298
+ deleted: array(string()).readonly(),
15299
+ kept: array(object({
15300
+ ref: string(),
15301
+ usage: KeychainSecretUsageSchema
15302
+ })).readonly()
15303
+ }), {
15304
+ kind: "mutation",
15305
+ auth: "admin",
15306
+ caller: "required"
15307
+ }), method(object({}), object({
15308
+ fingerprint: string(),
15309
+ keySource: KeychainKeySourceSchema
15310
+ }), {
15311
+ kind: "mutation",
15312
+ auth: "admin",
15313
+ caller: "required"
15314
+ }), method(object({}), object({ purged: number().int() }), {
15315
+ kind: "mutation",
15316
+ auth: "admin",
15317
+ caller: "required"
15318
+ }), method(object({}), object({
15319
+ key: string(),
15320
+ fingerprint: string(),
15321
+ keySource: KeychainKeySourceSchema
15322
+ }), {
15323
+ kind: "mutation",
15324
+ auth: "admin",
15325
+ caller: "required"
15326
+ }), method(object({ confirm: literal("RESET KEYCHAIN") }), object({
15327
+ archivedCollection: string().nullable(),
15328
+ archived: number().int()
15329
+ }), {
15330
+ kind: "mutation",
15331
+ auth: "admin",
15332
+ caller: "required"
15333
+ });
14414
15334
  method(_void(), object({
14415
15335
  id: string(),
14416
15336
  name: string(),
@@ -15749,7 +16669,11 @@ var DeviceRegisterPayloadSchema = object({
15749
16669
  var DeviceRemovePayloadSchema = object({ deviceId: number() });
15750
16670
  var DevicePersistConfigPayloadSchema = object({
15751
16671
  deviceId: number(),
15752
- data: record(string(), unknown())
16672
+ data: record(string(), unknown()),
16673
+ /** The paths the device's schema declares secret (D783), when the caller
16674
+ * knows them — those values are kept in the keychain, not the blob (D787).
16675
+ * Absent: the paths the device last reported at `registerDevice` apply. */
16676
+ secretConfigPaths: array(string()).optional()
15753
16677
  });
15754
16678
  /** What a migration actually did, per switch. `unreachable` is a first-class
15755
16679
  * answer: a camera that could not be asked is not a camera that was silenced. */
@@ -22785,8 +23709,23 @@ var RetrainMacroClassSchema = _enum([
22785
23709
  ]);
22786
23710
  /** A subject to learn, or a phantom to unlearn (taught by OMISSION). */
22787
23711
  var RetrainAnnotationKindSchema = _enum(["subject", "model_error"]);
22788
- /** Did a human draw this box, or did the assist propose it? */
22789
- var RetrainAnnotationSourceSchema = _enum(["operator", "assist"]);
23712
+ /**
23713
+ * Where a box came from. A machine-sourced box is a DRAFT on the page until
23714
+ * the operator confirms it; once saved it keeps its source as provenance.
23715
+ *
23716
+ * - `operator` — drawn by hand.
23717
+ * - `assist` — proposed by a detector run on the copy (the camera's own
23718
+ * model, or a larger teacher model).
23719
+ * - `pipeline` — the box the live pipeline actually drew on that frame, read
23720
+ * back from the track store (never a re-run).
23721
+ * - `llm` — proposed by a vision-capable LLM profile.
23722
+ */
23723
+ var RetrainAnnotationSourceSchema = _enum([
23724
+ "operator",
23725
+ "assist",
23726
+ "pipeline",
23727
+ "llm"
23728
+ ]);
22790
23729
  /** Normalised `[0,1]` rectangle against the FULL frame — the canonical form. */
22791
23730
  var RetrainBboxSchema = object({
22792
23731
  x: number(),
@@ -22804,7 +23743,8 @@ var RetrainBboxSchema = object({
22804
23743
  */
22805
23744
  var RetrainAnnotationSchema = object({
22806
23745
  id: string(),
22807
- trackId: string(),
23746
+ /** The frame's track. Absent on a recording still, which has none. */
23747
+ trackId: string().optional(),
22808
23748
  deviceId: number(),
22809
23749
  /** The COPY in retrain storage — never the source track's media key. */
22810
23750
  mediaKey: string(),
@@ -22853,13 +23793,47 @@ var RetrainFrameCandidateSchema = object({
22853
23793
  * fail, whatever became of the original. */
22854
23794
  copied: boolean()
22855
23795
  });
23796
+ /**
23797
+ * One box the live pipeline drew on a copied frame — what a correction starts
23798
+ * from. Derived when the frame is listed, from the track store: the subject
23799
+ * box recorded on the source media row when there is one, else the track
23800
+ * position nearest the frame's capture time. Never stored as an annotation
23801
+ * until the operator confirms it.
23802
+ */
23803
+ var RetrainPipelineBoxSchema = object({
23804
+ /** Normalised `[0,1]` against the full frame. */
23805
+ bbox: RetrainBboxSchema,
23806
+ macroClass: RetrainMacroClassSchema,
23807
+ label: string().optional(),
23808
+ subLabel: string().optional(),
23809
+ /** The detection score of the position used, when it was recorded. */
23810
+ score: number().optional(),
23811
+ /** The root model that produced the track, when it was recorded. */
23812
+ modelId: string().optional(),
23813
+ trackId: string(),
23814
+ /** `subject-box`: recorded on this very frame. `position`: the track's
23815
+ * position nearest the capture time, `deltaMs` away. */
23816
+ basis: _enum(["subject-box", "position"]),
23817
+ deltaMs: number()
23818
+ });
23819
+ /**
23820
+ * Where a retrain frame came from: a TRACK's stored media (copy-on-select),
23821
+ * or the RECORDING at an instant — the frame a model saw nothing in has no
23822
+ * track at all.
23823
+ */
23824
+ var RetrainFrameOriginSchema = _enum(["track", "recording"]);
22856
23825
  /** A frame the dataset OWNS: bytes copied at selection time. */
22857
23826
  var RetrainFrameSchema = object({
22858
23827
  frameId: string(),
22859
23828
  deviceId: number(),
22860
- trackId: string(),
22861
- /** Provenance only. It may already point at nothing — that is expected. */
22862
- sourceMediaId: number().int(),
23829
+ origin: RetrainFrameOriginSchema,
23830
+ /** The track it was copied from. Absent on a recording still. */
23831
+ trackId: string().optional(),
23832
+ /** Provenance only. It may already point at nothing — that is expected.
23833
+ * Absent on a recording still. */
23834
+ sourceMediaId: number().int().optional(),
23835
+ /** A recording still: the playhead instant it was taken at. */
23836
+ epochMs: number().optional(),
22863
23837
  sourceKind: MediaFileKindEnum,
22864
23838
  sizeBytes: number().int(),
22865
23839
  width: number().int(),
@@ -22870,7 +23844,12 @@ var RetrainFrameSchema = object({
22870
23844
  /** The operator's "every subject in this frame is boxed". Detector
22871
23845
  * evaluation keeps only complete frames: an unboxed subject would count as
22872
23846
  * a false positive. */
22873
- complete: boolean()
23847
+ complete: boolean(),
23848
+ /** The boxes the pipeline drew on this frame. Present on list answers;
23849
+ * empty when nothing the track store holds can be placed on it. */
23850
+ pipelineBoxes: array(RetrainPipelineBoxSchema).readonly().optional(),
23851
+ /** The named collections this frame belongs to. Present on list answers. */
23852
+ collectionIds: array(string()).readonly().optional()
22874
23853
  });
22875
23854
  /** Why a copy-on-select could not be honoured — named, never a silent skip. */
22876
23855
  var RetrainCopyRefusalSchema = _enum([
@@ -22901,6 +23880,8 @@ var RetrainFrameListSchema = object({
22901
23880
  var RetrainExportFilterSchema = object({
22902
23881
  deviceIds: array(number()).optional(),
22903
23882
  frameIds: array(string()).max(2e4).optional(),
23883
+ /** Only frames in at least one of these named collections. */
23884
+ collectionIds: array(string()).max(200).optional(),
22904
23885
  batchId: string().optional(),
22905
23886
  /** Only frames the operator marked complete (all subjects boxed). */
22906
23887
  completeOnly: boolean().optional()
@@ -22965,6 +23946,109 @@ var RetrainAssistResultSchema = discriminatedUnion("kind", [object({
22965
23946
  reason: string(),
22966
23947
  detail: string().optional()
22967
23948
  })]);
23949
+ /** A named set over the retrain corpus — membership only, it owns no pixels. */
23950
+ var RetrainCollectionSchema = object({
23951
+ id: string(),
23952
+ name: string(),
23953
+ createdAt: number(),
23954
+ frameCount: number().int()
23955
+ });
23956
+ var RetrainCollectionCreateResultSchema = discriminatedUnion("kind", [object({
23957
+ kind: literal("created"),
23958
+ collection: RetrainCollectionSchema
23959
+ }), object({
23960
+ kind: literal("refused"),
23961
+ reason: _enum(["empty-name", "duplicate-name"])
23962
+ })]);
23963
+ var RetrainCollectionRenameResultSchema = discriminatedUnion("kind", [object({
23964
+ kind: literal("renamed"),
23965
+ collection: RetrainCollectionSchema
23966
+ }), object({
23967
+ kind: literal("refused"),
23968
+ reason: _enum([
23969
+ "empty-name",
23970
+ "duplicate-name",
23971
+ "unknown-collection"
23972
+ ])
23973
+ })]);
23974
+ /**
23975
+ * The outcome of adding the frame at a recording instant. Every refusal is
23976
+ * named: `still-unavailable` (not recording, a gap, or an undecodable frame —
23977
+ * `detail` says which), `still-busy` (the recorder is at its decode bound; try
23978
+ * again), `unreadable-image`, `write-failed`, `unknown-collection`.
23979
+ */
23980
+ var AddRetrainFrameFromRecordingResultSchema = discriminatedUnion("kind", [object({
23981
+ kind: literal("added"),
23982
+ collectionId: string(),
23983
+ frame: RetrainFrameSchema,
23984
+ /** The moment was already in the dataset; nothing was decoded. */
23985
+ reused: boolean()
23986
+ }), object({
23987
+ kind: literal("refused"),
23988
+ reason: _enum([
23989
+ "unknown-collection",
23990
+ "still-unavailable",
23991
+ "still-busy",
23992
+ "unreadable-image",
23993
+ "write-failed"
23994
+ ]),
23995
+ detail: string().optional()
23996
+ })]);
23997
+ /** A vision LLM profile the AI assist may use, and where it sends the frame. */
23998
+ var RetrainAssistProfileSchema = object({
23999
+ id: string(),
24000
+ name: string(),
24001
+ model: string(),
24002
+ kind: string(),
24003
+ /** `true` when the frame would leave the house (a cloud vendor, or an
24004
+ * endpoint that is not on the local network). The page confirms each such
24005
+ * run, and the provider refuses one without `allowCloud`. */
24006
+ leavesHouse: boolean()
24007
+ });
24008
+ /** A box the AI assist proposed: a draft, plus the model's own reason. */
24009
+ var RetrainLlmProposalSchema = RetrainAnnotationDraftSchema.extend({ reason: string() });
24010
+ /** What the AI assist said about a box that was already on the canvas. */
24011
+ var RetrainLlmReviewSchema = object({
24012
+ /** The `ref` the page sent the box under. */
24013
+ ref: string(),
24014
+ verdict: _enum([
24015
+ "confirmed",
24016
+ "wrong-class",
24017
+ "not-an-object",
24018
+ "uncertain"
24019
+ ]),
24020
+ suggestedClass: RetrainMacroClassSchema.optional(),
24021
+ reason: string()
24022
+ });
24023
+ /**
24024
+ * The AI assist's answer. `proposed` carries drafts (`source: 'llm'`, the
24025
+ * model and its confidence) and reviews; items the model got wrong (a box off
24026
+ * the frame, an unasked class, an unknown ref) are dropped and counted in
24027
+ * `rejected`. A whole answer that is not the schema is `malformed-answer`.
24028
+ */
24029
+ var RetrainLlmAssistResultSchema = discriminatedUnion("kind", [object({
24030
+ kind: literal("proposed"),
24031
+ profileId: string(),
24032
+ model: string(),
24033
+ /** The frame was sent outside the house for this answer. */
24034
+ leftHouse: boolean(),
24035
+ proposals: array(RetrainLlmProposalSchema).readonly(),
24036
+ reviews: array(RetrainLlmReviewSchema).readonly(),
24037
+ rejected: number().int()
24038
+ }), object({
24039
+ kind: literal("refused"),
24040
+ reason: _enum([
24041
+ "unknown-frame",
24042
+ "unreadable-frame",
24043
+ "unknown-profile",
24044
+ "profile-disabled",
24045
+ "no-vision",
24046
+ "cloud-not-confirmed",
24047
+ "llm-error",
24048
+ "malformed-answer"
24049
+ ]),
24050
+ detail: string().optional()
24051
+ })]);
22968
24052
  /** The outcome of a lifecycle move owned by the retrain page. */
22969
24053
  var RetrainTransitionResultSchema = object({
22970
24054
  trackId: string(),
@@ -23682,7 +24766,7 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
23682
24766
  auth: "admin"
23683
24767
  }), method(object({
23684
24768
  deviceId: number(),
23685
- trackId: string(),
24769
+ trackId: string().optional(),
23686
24770
  frameId: string()
23687
24771
  }), object({
23688
24772
  removed: boolean(),
@@ -23699,7 +24783,8 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
23699
24783
  auth: "admin"
23700
24784
  }), method(object({
23701
24785
  deviceId: number(),
23702
- trackId: string(),
24786
+ /** The frame's track, when it has one — checked against the frame. */
24787
+ trackId: string().optional(),
23703
24788
  frameId: string(),
23704
24789
  subject: RetrainAssistSubjectSchema,
23705
24790
  /** Which node runs it. Absent ⇒ wherever an unowned call lands. */
@@ -23707,12 +24792,16 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
23707
24792
  }), RetrainAssistResultSchema, {
23708
24793
  kind: "mutation",
23709
24794
  auth: "admin"
23710
- }), method(object({ trackId: string() }), array(RetrainAnnotationSchema).readonly(), {
24795
+ }), method(object({
24796
+ trackId: string().optional(),
24797
+ frameIds: array(string()).max(2e3).optional()
24798
+ }), array(RetrainAnnotationSchema).readonly(), {
23711
24799
  kind: "query",
23712
24800
  auth: "admin"
23713
24801
  }), method(object({
23714
24802
  deviceId: number(),
23715
- trackId: string(),
24803
+ /** The frame's track, when it has one — checked against the frame. */
24804
+ trackId: string().optional(),
23716
24805
  frameId: string(),
23717
24806
  annotations: array(RetrainAnnotationDraftSchema)
23718
24807
  }), array(RetrainAnnotationSchema).readonly(), {
@@ -23735,7 +24824,7 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
23735
24824
  auth: "admin"
23736
24825
  }), method(object({
23737
24826
  deviceId: number(),
23738
- trackId: string(),
24827
+ trackId: string().optional(),
23739
24828
  frameId: string(),
23740
24829
  complete: boolean()
23741
24830
  }), RetrainFrameSchema, {
@@ -23749,6 +24838,74 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
23749
24838
  kind: "mutation",
23750
24839
  auth: "admin",
23751
24840
  timeoutMs: 60 * 6e4
24841
+ }), method(object({}), array(RetrainAssistProfileSchema).readonly(), {
24842
+ kind: "query",
24843
+ auth: "admin"
24844
+ }), method(object({
24845
+ deviceId: number(),
24846
+ trackId: string().optional(),
24847
+ frameId: string(),
24848
+ profileId: string(),
24849
+ classes: array(RetrainMacroClassSchema).min(1),
24850
+ boxes: array(object({
24851
+ ref: string(),
24852
+ bbox: RetrainBboxSchema,
24853
+ macroClass: RetrainMacroClassSchema,
24854
+ label: string().optional()
24855
+ })).max(50),
24856
+ allowCloud: boolean()
24857
+ }), RetrainLlmAssistResultSchema, {
24858
+ kind: "mutation",
24859
+ auth: "admin",
24860
+ timeoutMs: 18e4
24861
+ }), method(object({ name: string().max(120) }), RetrainCollectionCreateResultSchema, {
24862
+ kind: "mutation",
24863
+ auth: "admin"
24864
+ }), method(object({}), array(RetrainCollectionSchema).readonly(), {
24865
+ kind: "query",
24866
+ auth: "admin"
24867
+ }), method(object({
24868
+ id: string(),
24869
+ name: string().max(120)
24870
+ }), RetrainCollectionRenameResultSchema, {
24871
+ kind: "mutation",
24872
+ auth: "admin"
24873
+ }), method(object({ id: string() }), object({
24874
+ deleted: boolean(),
24875
+ removedFrames: number().int()
24876
+ }), {
24877
+ kind: "mutation",
24878
+ auth: "admin"
24879
+ }), method(object({
24880
+ collectionId: string(),
24881
+ deviceId: number(),
24882
+ epochMs: number()
24883
+ }), AddRetrainFrameFromRecordingResultSchema, {
24884
+ kind: "mutation",
24885
+ auth: "admin",
24886
+ timeoutMs: 6e4
24887
+ }), method(object({
24888
+ collectionId: string(),
24889
+ frameIds: array(string()).min(1).max(500)
24890
+ }), object({
24891
+ added: number().int(),
24892
+ alreadyMember: number().int(),
24893
+ unknownFrameIds: array(string()).readonly()
24894
+ }), {
24895
+ kind: "mutation",
24896
+ auth: "admin"
24897
+ }), method(object({
24898
+ collectionId: string(),
24899
+ frameId: string()
24900
+ }), object({
24901
+ removed: boolean(),
24902
+ deletedFrame: boolean()
24903
+ }), {
24904
+ kind: "mutation",
24905
+ auth: "admin"
24906
+ }), method(object({ collectionId: string() }), array(RetrainFrameSchema).readonly(), {
24907
+ kind: "query",
24908
+ auth: "admin"
23752
24909
  }), method(object({
23753
24910
  /** Which of the three event tables owns the row. */
23754
24911
  ownerType: EventOwnerTypeSchema,
@@ -24372,13 +25529,31 @@ var RecommendationReasonSchema = discriminatedUnion("kind", [
24372
25529
  object({
24373
25530
  kind: literal("no-family-build"),
24374
25531
  format: ModelFormatSchema$1
25532
+ }),
25533
+ object({
25534
+ kind: literal("kept-custom-pin"),
25535
+ modelId: string(),
25536
+ deviceKey: string()
24375
25537
  })
24376
25538
  ]);
25539
+ /** Why a device is left exactly as it is, whatever the plan would pick (D786). */
25540
+ var KeptReasonSchema = _enum(["custom-pin"]);
25541
+ /**
25542
+ * Where a choice's latency came from (D791): this node's own benchmark
25543
+ * result, or the hardware-class table. Measured on the node beats the table.
25544
+ */
25545
+ var LatencySourceSchema = discriminatedUnion("kind", [object({ kind: literal("table") }), object({
25546
+ kind: literal("node-benchmark"),
25547
+ resultId: string(),
25548
+ measuredAtMs: number()
25549
+ })]);
24377
25550
  var DeviceModelChoiceSchema = object({
24378
25551
  modelId: string(),
24379
25552
  p50Ms: number(),
24380
25553
  fps: number(),
24381
25554
  measured: boolean(),
25555
+ /** Absent on a plan from before D791 — read as the table. */
25556
+ source: LatencySourceSchema.optional(),
24382
25557
  /** Parallel sessions at the camera rate with the headroom kept free: ⌊fps × (1 − headroom) / camera fps⌋. */
24383
25558
  capacitySessions: number(),
24384
25559
  personRecall: number()
@@ -24389,6 +25564,8 @@ var DeviceRecommendationSchema = object({
24389
25564
  enabled: boolean(),
24390
25565
  available: boolean(),
24391
25566
  chosen: DeviceModelChoiceSchema.nullable(),
25567
+ /** Present when the device is kept as is: Apply writes nothing on it. */
25568
+ kept: KeptReasonSchema.optional(),
24392
25569
  reasons: array(RecommendationReasonSchema).readonly()
24393
25570
  });
24394
25571
  var NodeRecommendationSchema = object({
@@ -24442,6 +25619,17 @@ var AutoTuneWarningSchema = discriminatedUnion("kind", [
24442
25619
  kind: literal("coral-enabled"),
24443
25620
  nodeId: string(),
24444
25621
  deviceKey: string()
25622
+ }),
25623
+ object({
25624
+ kind: literal("custom-pin-kept"),
25625
+ nodeId: string(),
25626
+ deviceKey: string().nullable(),
25627
+ deviceId: number().nullable(),
25628
+ modelId: string()
25629
+ }),
25630
+ object({
25631
+ kind: literal("custom-registry-unreadable"),
25632
+ error: string()
24445
25633
  })
24446
25634
  ]);
24447
25635
  var AutoTuneOptionsSchema = object({
@@ -24620,13 +25808,14 @@ var SuggestSharesResultSchema = object({
24620
25808
  nodes: array(SuggestedNodeShareSchema).readonly()
24621
25809
  });
24622
25810
  /**
24623
- * Where the node and device shares come from (D750, D755).
24624
- * - `hardware` (default) — computed by the system from each node's static
24625
- * capacity (its accelerators at their Auto tune models, from the measured
24626
- * latency table), recomputed whenever a node or device joins, leaves, is
24627
- * switched on or off, or changes model. No load input.
24628
- * - `benchmark` — the same, from each node's measured capacity (node
24629
- * benchmark results); a node without results falls back to `hardware`.
25811
+ * Where the node and device shares come from (D750, D755, D791).
25812
+ * - `benchmark` (default since D791) — each node's capacity as its own node
25813
+ * benchmark measured it; a node without fresh results is sized from
25814
+ * `hardware` and says so. Measured on the node beats the table.
25815
+ * - `hardware` — computed from each node's static capacity only (its
25816
+ * accelerators at their Auto tune models, from the latency table).
25817
+ * Both are recomputed whenever a node or device joins, leaves, is switched
25818
+ * on or off, changes model, or a benchmark result is written. No load input.
24630
25819
  * - `manual` — the operator's stored sliders.
24631
25820
  * Either way a node or device that cannot take sessions gives its share to
24632
25821
  * the others in proportion; the stored values are never rewritten for that.
@@ -24675,6 +25864,362 @@ var EffectiveSharesSchema = object({
24675
25864
  nodeWeights: record(string(), number()),
24676
25865
  deviceWeights: record(string(), record(string(), number()))
24677
25866
  });
25867
+ /**
25868
+ * Wire shapes of the node benchmark (D791): the operator's plan, the
25869
+ * preflight the confirmation shows, the run the orchestrator owns, what the
25870
+ * measuring runner reports, and the result rows Auto tune and the automatic
25871
+ * shares read.
25872
+ *
25873
+ * ONE node at a time, owned by the pipeline orchestrator. While a run is
25874
+ * active the cluster is in BENCHMARK MODE for that node: it is not a
25875
+ * detection candidate, camera pins naming it are ignored so its sessions move
25876
+ * elsewhere, and both come back when the mode ends — after a crash or a hub
25877
+ * restart too (a persisted manifest, reconciled against the registry).
25878
+ *
25879
+ * Two measurements, both on the node, driven by its own runner (frames never
25880
+ * cross a process at frame rate, D9):
25881
+ * - `device` — one accelerator × one candidate detector, root only, open
25882
+ * loop: how many streams at the camera rate it carries inside the frame
25883
+ * interval;
25884
+ * - `pipeline` — the chosen detector plus the operator's detail steps
25885
+ * (faces, plates, classifiers, CLIP…), on varied frames from the bench
25886
+ * clip: how many parallel sessions the node carries before latency, drops,
25887
+ * CPU, RAM or the event loop give out.
25888
+ */
25889
+ /** Defaults and bounds, one place. */
25890
+ var NODE_BENCHMARK_DEFAULTS = {
25891
+ fpsPerStream: 10,
25892
+ budgetMinutes: 45,
25893
+ minBudgetMinutes: 10,
25894
+ maxBudgetMinutes: 120,
25895
+ /** A result older than this no longer beats the table. */
25896
+ staleAfterDays: 30,
25897
+ /** Warm-in per ramp step (not accounted). */
25898
+ settleSec: 5,
25899
+ /** Accounted window per ramp step. */
25900
+ measureSec: 20,
25901
+ /** Longest the drain may take before the run is refused. */
25902
+ drainTimeoutSec: 120,
25903
+ /** Candidate models per device in one run. */
25904
+ maxModelsPerDevice: 6
25905
+ };
25906
+ /** The two measurements a run can make. */
25907
+ var NodeBenchmarkPhaseSchema = _enum(["device", "pipeline"]);
25908
+ var NodeBenchmarkDevicePlanSchema = object({
25909
+ /** `<backend>:<device>` — `openvino:npu`, `coreml:all`, `cpu`. */
25910
+ deviceKey: string().min(1),
25911
+ /**
25912
+ * Root detector candidates for the `device` measurement, in the order
25913
+ * measured. The FIRST is the one the `pipeline` measurement runs.
25914
+ */
25915
+ modelIds: array(string().min(1)).min(1).max(NODE_BENCHMARK_DEFAULTS.maxModelsPerDevice)
25916
+ });
25917
+ /** What the operator confirmed. */
25918
+ var NodeBenchmarkPlanSchema = object({
25919
+ nodeId: string().min(1),
25920
+ devices: array(NodeBenchmarkDevicePlanSchema).min(1),
25921
+ /** Which measurements run. At least one. */
25922
+ phases: array(NodeBenchmarkPhaseSchema).min(1).default(["device", "pipeline"]),
25923
+ /**
25924
+ * Detail steps (catalog step ids under the root: faces, plates,
25925
+ * classifiers, CLIP…) the `pipeline` measurement enables. The root
25926
+ * detector always runs.
25927
+ */
25928
+ steps: array(string().min(1)).default([]),
25929
+ /** Offered rate of one stream / session. */
25930
+ fpsPerStream: number().int().min(1).max(30).default(NODE_BENCHMARK_DEFAULTS.fpsPerStream),
25931
+ /** Hard deadline: the mode ends and the cluster is restored when it passes. */
25932
+ budgetMinutes: number().int().min(NODE_BENCHMARK_DEFAULTS.minBudgetMinutes).max(NODE_BENCHMARK_DEFAULTS.maxBudgetMinutes).default(NODE_BENCHMARK_DEFAULTS.budgetMinutes),
25933
+ /** Keep the models the run downloaded (default: delete what was not installed before). */
25934
+ keepDownloadedModels: boolean().default(false),
25935
+ /** Start although the other nodes' capacity does not cover the sessions running now. */
25936
+ acceptInsufficientHeadroom: boolean().default(false)
25937
+ });
25938
+ var NodeBenchmarkRefusalSchema = object({
25939
+ kind: _enum([
25940
+ "benchmark-active",
25941
+ "node-offline",
25942
+ "unknown-device",
25943
+ "no-phase",
25944
+ "insufficient-headroom"
25945
+ ]),
25946
+ detail: string(),
25947
+ overridable: boolean()
25948
+ });
25949
+ /** A camera whose detection leaves the node for the run. */
25950
+ var NodeBenchmarkMovingCameraSchema = object({
25951
+ deviceId: number(),
25952
+ /** Placed on the node now (a standing attach or a running session). */
25953
+ placedOnNode: boolean(),
25954
+ /** A node pin naming this node, ignored for the run. */
25955
+ pinnedToNode: boolean()
25956
+ });
25957
+ /** A camera that cannot leave: no other node can obtain its frames. */
25958
+ var NodeBenchmarkStayingCameraSchema = object({
25959
+ deviceId: number(),
25960
+ reason: literal("only-frame-source")
25961
+ });
25962
+ var NodeBenchmarkPreflightSchema = object({
25963
+ nodeId: string(),
25964
+ online: boolean(),
25965
+ moving: array(NodeBenchmarkMovingCameraSchema).readonly(),
25966
+ /** Keep running on the node during the run; the result is flagged contaminated. */
25967
+ staying: array(NodeBenchmarkStayingCameraSchema).readonly(),
25968
+ estimatedDurationMs: number(),
25969
+ /** The run ends and the cluster is restored at the latest after this long. */
25970
+ budgetMs: number(),
25971
+ phases: array(NodeBenchmarkPhaseSchema).readonly(),
25972
+ steps: array(string()).readonly(),
25973
+ devices: array(NodeBenchmarkDevicePlanSchema).readonly(),
25974
+ /** Parallel sessions the cluster runs now, and what the other nodes can carry. */
25975
+ headroom: object({
25976
+ sessionsNow: number(),
25977
+ otherNodesCapacitySessions: number().nullable()
25978
+ }),
25979
+ refusals: array(NodeBenchmarkRefusalSchema).readonly(),
25980
+ canStart: boolean()
25981
+ });
25982
+ /** Where the measuring runner is. */
25983
+ var NodeBenchProgressSchema = object({
25984
+ phase: _enum([
25985
+ "preparing",
25986
+ "device",
25987
+ "pipeline",
25988
+ "cleanup"
25989
+ ]),
25990
+ deviceKey: string().nullable(),
25991
+ modelId: string().nullable(),
25992
+ /** Streams (device) or sessions (pipeline) of the step running now. */
25993
+ load: number().nullable(),
25994
+ cellsDone: number(),
25995
+ cellsTotal: number(),
25996
+ message: string()
25997
+ });
25998
+ /** What limited a ramp. `none` = the ramp ran out of steps still passing. */
25999
+ var NodeBenchLimitSchema = _enum([
26000
+ "p95",
26001
+ "drops",
26002
+ "errors",
26003
+ "stall",
26004
+ "cpu",
26005
+ "ram",
26006
+ "none"
26007
+ ]);
26008
+ var NodeBenchRampStepSchema = object({
26009
+ load: number(),
26010
+ pass: boolean(),
26011
+ p95Ms: number(),
26012
+ dropRatio: number(),
26013
+ /** Completed frames per second over the accounted window. */
26014
+ fps: number(),
26015
+ cpuPct: number().nullable(),
26016
+ ramFreePct: number().nullable(),
26017
+ failReasons: array(string()).readonly()
26018
+ });
26019
+ var NodeBenchCellSchema = discriminatedUnion("phase", [object({
26020
+ phase: literal("device"),
26021
+ deviceKey: string(),
26022
+ modelId: string(),
26023
+ /** Single-stream latency (the K = 1 step). */
26024
+ p50Ms: number(),
26025
+ p95Ms: number(),
26026
+ p99Ms: number(),
26027
+ /** Frames per second sustained at the last passing step. */
26028
+ fps: number(),
26029
+ /** Streams at the camera rate the device carried inside the frame interval; 0 = not even one. */
26030
+ kMax: number(),
26031
+ limitedBy: NodeBenchLimitSchema,
26032
+ /** First call (model load + warm-up). */
26033
+ warmupMs: number(),
26034
+ ramp: array(NodeBenchRampStepSchema).readonly()
26035
+ }), object({
26036
+ phase: literal("pipeline"),
26037
+ deviceKey: string(),
26038
+ modelId: string(),
26039
+ steps: array(string()).readonly(),
26040
+ /** Parallel sessions at the camera rate the node carried; 0 = not even one. */
26041
+ maxSessions: number(),
26042
+ limitedBy: NodeBenchLimitSchema,
26043
+ /** Detail steps that produced at least one result on the clip — a step that never fired measured nothing. */
26044
+ stepsFired: array(string()).readonly(),
26045
+ warmupMs: number(),
26046
+ ramp: array(NodeBenchRampStepSchema).readonly()
26047
+ })]);
26048
+ /**
26049
+ * What a result was measured ON. A result whose fingerprint no longer matches
26050
+ * the node no longer beats the table.
26051
+ */
26052
+ var NodeBenchFingerprintSchema = object({
26053
+ pipelineVersion: string().nullable(),
26054
+ cpuModel: string().nullable(),
26055
+ ramGb: number().nullable(),
26056
+ os: string().nullable(),
26057
+ /** Per device: the pool the cells ran on (runtime + tuning). */
26058
+ pools: record(string(), object({
26059
+ runtime: string(),
26060
+ numWorkers: number(),
26061
+ concurrency: number(),
26062
+ batchMode: string()
26063
+ })).default({})
26064
+ });
26065
+ /** The frames the run used. */
26066
+ var NodeBenchClipSchema = object({
26067
+ /** `camstack-bench-v1` or `reference-images` (the fallback when the clip is not reachable). */
26068
+ id: string(),
26069
+ revision: string().nullable(),
26070
+ frames: number(),
26071
+ width: number(),
26072
+ height: number()
26073
+ });
26074
+ var NodeBenchRunnerInputSchema = object({
26075
+ runId: string().min(1),
26076
+ devices: array(NodeBenchmarkDevicePlanSchema).min(1),
26077
+ phases: array(NodeBenchmarkPhaseSchema).min(1),
26078
+ /** The full detail step tree root for the `pipeline` measurement is built on the node from these ids. */
26079
+ steps: array(string()).default([]),
26080
+ fpsPerStream: number().int().min(1).max(30),
26081
+ /** The runner stops on its own past this instant, whatever the hub does. */
26082
+ deadlineAtMs: number(),
26083
+ settleSec: number().min(0).max(60).default(NODE_BENCHMARK_DEFAULTS.settleSec),
26084
+ measureSec: number().min(2).max(300).default(NODE_BENCHMARK_DEFAULTS.measureSec),
26085
+ keepDownloadedModels: boolean().default(false)
26086
+ });
26087
+ var NodeBenchRunnerStateSchema = _enum([
26088
+ "running",
26089
+ "done",
26090
+ "failed",
26091
+ "aborted"
26092
+ ]);
26093
+ var NodeBenchRunnerStatusSchema = object({
26094
+ runId: string(),
26095
+ nodeId: string(),
26096
+ state: NodeBenchRunnerStateSchema,
26097
+ progress: NodeBenchProgressSchema.nullable(),
26098
+ /** Every finished cell so far — a run stopped half way keeps what it measured. */
26099
+ cells: array(NodeBenchCellSchema).readonly(),
26100
+ fingerprint: NodeBenchFingerprintSchema.nullable(),
26101
+ clip: NodeBenchClipSchema.nullable(),
26102
+ /** Cameras seen running on the node during the run (they share its pools). */
26103
+ activeCameraIds: array(number()).readonly(),
26104
+ /** Models the run downloaded and then deleted (not installed before). */
26105
+ deletedModels: array(string()).readonly(),
26106
+ error: string().nullable(),
26107
+ startedAtMs: number(),
26108
+ finishedAtMs: number().nullable()
26109
+ });
26110
+ var NodeBenchmarkStateSchema = _enum([
26111
+ "draining",
26112
+ "measuring",
26113
+ "restoring",
26114
+ "done",
26115
+ "failed",
26116
+ "aborted"
26117
+ ]);
26118
+ /** Why a run ended. */
26119
+ var NodeBenchmarkEndReasonSchema = _enum([
26120
+ "completed",
26121
+ "operator-abort",
26122
+ "deadline",
26123
+ "node-lost",
26124
+ "runner-lost",
26125
+ "hub-restart",
26126
+ "drain-timeout",
26127
+ "failed"
26128
+ ]);
26129
+ var NodeBenchmarkRunSchema = object({
26130
+ runId: string(),
26131
+ nodeId: string(),
26132
+ state: NodeBenchmarkStateSchema,
26133
+ plan: NodeBenchmarkPlanSchema,
26134
+ startedAtMs: number(),
26135
+ deadlineAtMs: number(),
26136
+ finishedAtMs: number().nullable(),
26137
+ endReason: NodeBenchmarkEndReasonSchema.nullable(),
26138
+ error: string().nullable(),
26139
+ /** Cameras moved off the node for the run. */
26140
+ moved: array(number()).readonly(),
26141
+ /** Cameras that stayed (their only frame source is the node). */
26142
+ staying: array(number()).readonly(),
26143
+ /** Something else ran on the node's pools during the run. */
26144
+ contaminated: boolean(),
26145
+ progress: NodeBenchProgressSchema.nullable(),
26146
+ resultIds: array(string()).readonly()
26147
+ });
26148
+ /** `getNodeBenchmarkStatus`: the active run (or the last one), and whether benchmark mode is on. */
26149
+ var NodeBenchmarkStatusSchema = object({
26150
+ /** The node the cluster is in benchmark mode for; null = none. */
26151
+ modeNodeId: string().nullable(),
26152
+ run: NodeBenchmarkRunSchema.nullable()
26153
+ });
26154
+ /**
26155
+ * One stored measurement — the only authority Auto tune and the automatic
26156
+ * shares read measured capacity from. Written by the orchestrator when a run
26157
+ * ends, never by anyone else.
26158
+ */
26159
+ var NodeBenchmarkResultSchema = object({
26160
+ id: string(),
26161
+ runId: string(),
26162
+ nodeId: string(),
26163
+ cell: NodeBenchCellSchema,
26164
+ fpsPerStream: number(),
26165
+ fingerprint: NodeBenchFingerprintSchema.nullable(),
26166
+ clip: NodeBenchClipSchema.nullable(),
26167
+ /** Other work shared the node's pools (a camera that could not move, or the hub's own duties). */
26168
+ contaminated: boolean(),
26169
+ stayingCameras: array(number()).readonly(),
26170
+ /** The run ended early; the cell itself completed. */
26171
+ partialRun: boolean(),
26172
+ measuredAtMs: number()
26173
+ });
26174
+ var ListNodeBenchmarkResultsInputSchema = object({
26175
+ nodeId: string().optional(),
26176
+ deviceKey: string().optional()
26177
+ });
26178
+ /** A result with its standing today: does it still beat the table? */
26179
+ var NodeBenchmarkResultViewSchema = NodeBenchmarkResultSchema.extend({
26180
+ /** `fresh` beats the table; `stale` falls back to it; `superseded` = a newer row covers the same cell. */
26181
+ standing: _enum([
26182
+ "fresh",
26183
+ "stale",
26184
+ "superseded"
26185
+ ]),
26186
+ staleWhy: _enum([
26187
+ "age",
26188
+ "runtime",
26189
+ "pool-tuning"
26190
+ ]).nullable()
26191
+ });
26192
+ object({
26193
+ runId: string(),
26194
+ nodeId: string(),
26195
+ startedAtMs: number(),
26196
+ deadlineAtMs: number(),
26197
+ plan: NodeBenchmarkPlanSchema,
26198
+ moved: array(number()).readonly(),
26199
+ staying: array(number()).readonly()
26200
+ });
26201
+ /** Candidate detectors per device, for the plan editor. */
26202
+ var NodeBenchmarkCandidatesSchema = object({
26203
+ nodeId: string(),
26204
+ reachable: boolean(),
26205
+ devices: array(object({
26206
+ deviceKey: string(),
26207
+ enabled: boolean(),
26208
+ available: boolean(),
26209
+ /** Ordered: what Auto tune would pick first, then the rest of the family by accuracy. */
26210
+ suggested: array(string()).readonly(),
26211
+ /** Every root detector the device has a build for. */
26212
+ all: array(string()).readonly(),
26213
+ /** The model the device runs now, when pinned. */
26214
+ currentModelId: string().nullable()
26215
+ })).readonly(),
26216
+ /** Detail steps the node's catalog offers under the root (for the `pipeline` measurement). */
26217
+ steps: array(object({
26218
+ id: string(),
26219
+ name: string(),
26220
+ slot: string()
26221
+ })).readonly()
26222
+ });
24678
26223
  object({
24679
26224
  activeCameras: number(),
24680
26225
  throttledCameras: number(),
@@ -25803,7 +27348,16 @@ method(RunnerCameraConfigSchema, object({ success: literal(true) }), { kind: "mu
25803
27348
  }), ParkedTrackFrameSchema.nullable()), method(object({
25804
27349
  deviceId: number(),
25805
27350
  trackId: string()
25806
- }), object({ released: number().int().nonnegative() }), { kind: "mutation" });
27351
+ }), object({ released: number().int().nonnegative() }), { kind: "mutation" }), method(NodeBenchRunnerInputSchema, object({
27352
+ accepted: literal(true),
27353
+ runId: string()
27354
+ }), {
27355
+ kind: "mutation",
27356
+ auth: "admin"
27357
+ }), method(object({ runId: string() }), NodeBenchRunnerStatusSchema.nullable(), { auth: "admin" }), method(object({ runId: string() }), object({ aborted: boolean() }), {
27358
+ kind: "mutation",
27359
+ auth: "admin"
27360
+ });
25807
27361
  var CameraPipelineConfigSchema = object({
25808
27362
  engine: PipelineEngineChoiceSchema.optional(),
25809
27363
  steps: array(PipelineStepInputSchema).readonly(),
@@ -26442,6 +27996,21 @@ method(object({
26442
27996
  }), method(PlacementStatsInputSchema, PlacementStatsSchema, { auth: "admin" }), method(SuggestSharesInputSchema, SuggestSharesResultSchema, { auth: "admin" }), method(_void(), EffectiveSharesSchema, { auth: "admin" }), method(SetShareSourceInputSchema, object({ success: literal(true) }), {
26443
27997
  kind: "mutation",
26444
27998
  auth: "admin"
27999
+ }), method(NodeBenchmarkPlanSchema, NodeBenchmarkPreflightSchema, { auth: "admin" }), method(NodeBenchmarkPlanSchema, discriminatedUnion("kind", [object({
28000
+ kind: literal("started"),
28001
+ runId: string()
28002
+ }), object({
28003
+ kind: literal("refused"),
28004
+ preflight: NodeBenchmarkPreflightSchema
28005
+ })]), {
28006
+ kind: "mutation",
28007
+ auth: "admin"
28008
+ }), method(_void(), NodeBenchmarkStatusSchema, { auth: "admin" }), method(object({ runId: string() }), object({ aborted: boolean() }), {
28009
+ kind: "mutation",
28010
+ auth: "admin"
28011
+ }), method(object({ nodeId: string() }), NodeBenchmarkCandidatesSchema, { auth: "admin" }), method(ListNodeBenchmarkResultsInputSchema, array(NodeBenchmarkResultViewSchema).readonly(), { auth: "admin" }), method(object({ id: string() }), object({ deleted: boolean() }), {
28012
+ kind: "mutation",
28013
+ auth: "admin"
26445
28014
  }), method(object({ deviceId: number() }), CameraPipelineSettingsSchema.nullable()), method(object({
26446
28015
  deviceId: number(),
26447
28016
  addonId: string(),
@@ -33071,6 +34640,9 @@ var CreateIntegrationInputSchema = object({
33071
34640
  enabled: boolean().optional(),
33072
34641
  info: record(string(), unknown()).optional(),
33073
34642
  settings: record(string(), unknown()).optional(),
34643
+ /** Keys of `settings` the form's schema declares secret (by type) — kept in
34644
+ * the keychain, not the table (D787). */
34645
+ secretKeys: array(string()).optional(),
33074
34646
  skipRestart: boolean().optional()
33075
34647
  });
33076
34648
  var UpdateIntegrationInputSchema = object({
@@ -33094,7 +34666,9 @@ method(_void(), array(IntegrationWithStateSchema)), method(object({ id: string()
33094
34666
  auth: "admin"
33095
34667
  }), method(object({ id: string() }), record(string(), unknown()), { auth: "admin" }), method(object({
33096
34668
  id: string(),
33097
- settings: record(string(), unknown())
34669
+ settings: record(string(), unknown()),
34670
+ /** Keys the form's schema declares secret (by type) — keychain-stored (D787). */
34671
+ secretKeys: array(string()).optional()
33098
34672
  }), object({ success: boolean() }), {
33099
34673
  kind: "mutation",
33100
34674
  auth: "admin"
@@ -41833,7 +43407,8 @@ var BaseDevice = class {
41833
43407
  this.role = options.role;
41834
43408
  this.parentDeviceId = ctx.parentDeviceId;
41835
43409
  const seedData = ctx.persistedConfig ?? {};
41836
- this.config = DeviceConfig.fromSchema(schema, (data) => ctx.persistConfig(data), seedData, ({ droppedKeys, issues }) => {
43410
+ const declaredSecretPaths = collectZodSecretPaths(schema);
43411
+ this.config = DeviceConfig.fromSchema(schema, (data) => ctx.persistConfig(data, { secretConfigPaths: declaredSecretPaths }), seedData, ({ droppedKeys, issues }) => {
41837
43412
  ctx.logger.warn("Device config recovery: dropping invalid persisted fields", {
41838
43413
  tags: {
41839
43414
  deviceId: ctx.id,
@@ -45522,6 +47097,90 @@ Object.freeze({
45522
47097
  addonId: null,
45523
47098
  access: "create"
45524
47099
  },
47100
+ "keychain.delete": {
47101
+ capName: "keychain",
47102
+ capScope: "system",
47103
+ addonId: null,
47104
+ access: "delete"
47105
+ },
47106
+ "keychain.getState": {
47107
+ capName: "keychain",
47108
+ capScope: "system",
47109
+ addonId: null,
47110
+ access: "view"
47111
+ },
47112
+ "keychain.listMeta": {
47113
+ capName: "keychain",
47114
+ capScope: "system",
47115
+ addonId: null,
47116
+ access: "view"
47117
+ },
47118
+ "keychain.put": {
47119
+ capName: "keychain",
47120
+ capScope: "system",
47121
+ addonId: null,
47122
+ access: "create"
47123
+ },
47124
+ "keychain.resolve": {
47125
+ capName: "keychain",
47126
+ capScope: "system",
47127
+ addonId: null,
47128
+ access: "view"
47129
+ },
47130
+ "keychainAdmin.deleteOrphans": {
47131
+ capName: "keychain-admin",
47132
+ capScope: "system",
47133
+ addonId: null,
47134
+ access: "delete"
47135
+ },
47136
+ "keychainAdmin.downloadRecoveryKey": {
47137
+ capName: "keychain-admin",
47138
+ capScope: "system",
47139
+ addonId: null,
47140
+ access: "create"
47141
+ },
47142
+ "keychainAdmin.listAudit": {
47143
+ capName: "keychain-admin",
47144
+ capScope: "system",
47145
+ addonId: null,
47146
+ access: "view"
47147
+ },
47148
+ "keychainAdmin.listSecrets": {
47149
+ capName: "keychain-admin",
47150
+ capScope: "system",
47151
+ addonId: null,
47152
+ access: "view"
47153
+ },
47154
+ "keychainAdmin.purgeRetiredKeys": {
47155
+ capName: "keychain-admin",
47156
+ capScope: "system",
47157
+ addonId: null,
47158
+ access: "delete"
47159
+ },
47160
+ "keychainAdmin.resetKeychain": {
47161
+ capName: "keychain-admin",
47162
+ capScope: "system",
47163
+ addonId: null,
47164
+ access: "delete"
47165
+ },
47166
+ "keychainAdmin.reveal": {
47167
+ capName: "keychain-admin",
47168
+ capScope: "system",
47169
+ addonId: null,
47170
+ access: "create"
47171
+ },
47172
+ "keychainAdmin.rotateMasterKey": {
47173
+ capName: "keychain-admin",
47174
+ capScope: "system",
47175
+ addonId: null,
47176
+ access: "create"
47177
+ },
47178
+ "keychainAdmin.status": {
47179
+ capName: "keychain-admin",
47180
+ capScope: "system",
47181
+ addonId: null,
47182
+ access: "view"
47183
+ },
45525
47184
  "lawnMowerControl.dock": {
45526
47185
  capName: "lawn-mower-control",
45527
47186
  capScope: "device",
@@ -46896,6 +48555,18 @@ Object.freeze({
46896
48555
  addonId: null,
46897
48556
  access: "create"
46898
48557
  },
48558
+ "pipelineAnalytics.addRetrainFrameFromRecording": {
48559
+ capName: "pipeline-analytics",
48560
+ capScope: "device",
48561
+ addonId: null,
48562
+ access: "create"
48563
+ },
48564
+ "pipelineAnalytics.addRetrainFramesToCollection": {
48565
+ capName: "pipeline-analytics",
48566
+ capScope: "device",
48567
+ addonId: null,
48568
+ access: "create"
48569
+ },
46899
48570
  "pipelineAnalytics.applyDeviceSettingsPatch": {
46900
48571
  capName: "pipeline-analytics",
46901
48572
  capScope: "device",
@@ -46944,12 +48615,24 @@ Object.freeze({
46944
48615
  addonId: null,
46945
48616
  access: "view"
46946
48617
  },
48618
+ "pipelineAnalytics.createRetrainCollection": {
48619
+ capName: "pipeline-analytics",
48620
+ capScope: "device",
48621
+ addonId: null,
48622
+ access: "create"
48623
+ },
46947
48624
  "pipelineAnalytics.deleteDeviceEvents": {
46948
48625
  capName: "pipeline-analytics",
46949
48626
  capScope: "device",
46950
48627
  addonId: null,
46951
48628
  access: "delete"
46952
48629
  },
48630
+ "pipelineAnalytics.deleteRetrainCollection": {
48631
+ capName: "pipeline-analytics",
48632
+ capScope: "device",
48633
+ addonId: null,
48634
+ access: "delete"
48635
+ },
46953
48636
  "pipelineAnalytics.deleteTracks": {
46954
48637
  capName: "pipeline-analytics",
46955
48638
  capScope: "device",
@@ -47154,6 +48837,24 @@ Object.freeze({
47154
48837
  addonId: null,
47155
48838
  access: "view"
47156
48839
  },
48840
+ "pipelineAnalytics.listRetrainAssistProfiles": {
48841
+ capName: "pipeline-analytics",
48842
+ capScope: "device",
48843
+ addonId: null,
48844
+ access: "view"
48845
+ },
48846
+ "pipelineAnalytics.listRetrainCollectionFrames": {
48847
+ capName: "pipeline-analytics",
48848
+ capScope: "device",
48849
+ addonId: null,
48850
+ access: "view"
48851
+ },
48852
+ "pipelineAnalytics.listRetrainCollections": {
48853
+ capName: "pipeline-analytics",
48854
+ capScope: "device",
48855
+ addonId: null,
48856
+ access: "view"
48857
+ },
47157
48858
  "pipelineAnalytics.listRetrainFrames": {
47158
48859
  capName: "pipeline-analytics",
47159
48860
  capScope: "device",
@@ -47202,6 +48903,12 @@ Object.freeze({
47202
48903
  addonId: null,
47203
48904
  access: "create"
47204
48905
  },
48906
+ "pipelineAnalytics.proposeRetrainAnnotationsWithLlm": {
48907
+ capName: "pipeline-analytics",
48908
+ capScope: "device",
48909
+ addonId: null,
48910
+ access: "create"
48911
+ },
47205
48912
  "pipelineAnalytics.pruneEvents": {
47206
48913
  capName: "pipeline-analytics",
47207
48914
  capScope: "device",
@@ -47256,6 +48963,18 @@ Object.freeze({
47256
48963
  addonId: null,
47257
48964
  access: "create"
47258
48965
  },
48966
+ "pipelineAnalytics.removeRetrainFrameFromCollection": {
48967
+ capName: "pipeline-analytics",
48968
+ capScope: "device",
48969
+ addonId: null,
48970
+ access: "delete"
48971
+ },
48972
+ "pipelineAnalytics.renameRetrainCollection": {
48973
+ capName: "pipeline-analytics",
48974
+ capScope: "device",
48975
+ addonId: null,
48976
+ access: "create"
48977
+ },
47259
48978
  "pipelineAnalytics.restageRetrainTrack": {
47260
48979
  capName: "pipeline-analytics",
47261
48980
  capScope: "device",
@@ -47544,6 +49263,12 @@ Object.freeze({
47544
49263
  addonId: null,
47545
49264
  access: "view"
47546
49265
  },
49266
+ "pipelineOrchestrator.abortNodeBenchmark": {
49267
+ capName: "pipeline-orchestrator",
49268
+ capScope: "system",
49269
+ addonId: null,
49270
+ access: "create"
49271
+ },
47547
49272
  "pipelineOrchestrator.applyAutoTune": {
47548
49273
  capName: "pipeline-orchestrator",
47549
49274
  capScope: "system",
@@ -47568,6 +49293,12 @@ Object.freeze({
47568
49293
  addonId: null,
47569
49294
  access: "create"
47570
49295
  },
49296
+ "pipelineOrchestrator.deleteNodeBenchmarkResult": {
49297
+ capName: "pipeline-orchestrator",
49298
+ capScope: "system",
49299
+ addonId: null,
49300
+ access: "delete"
49301
+ },
47571
49302
  "pipelineOrchestrator.getAgentLoad": {
47572
49303
  capName: "pipeline-orchestrator",
47573
49304
  capScope: "system",
@@ -47676,6 +49407,24 @@ Object.freeze({
47676
49407
  addonId: null,
47677
49408
  access: "view"
47678
49409
  },
49410
+ "pipelineOrchestrator.getNodeBenchmarkCandidates": {
49411
+ capName: "pipeline-orchestrator",
49412
+ capScope: "system",
49413
+ addonId: null,
49414
+ access: "view"
49415
+ },
49416
+ "pipelineOrchestrator.getNodeBenchmarkPreflight": {
49417
+ capName: "pipeline-orchestrator",
49418
+ capScope: "system",
49419
+ addonId: null,
49420
+ access: "view"
49421
+ },
49422
+ "pipelineOrchestrator.getNodeBenchmarkStatus": {
49423
+ capName: "pipeline-orchestrator",
49424
+ capScope: "system",
49425
+ addonId: null,
49426
+ access: "view"
49427
+ },
47679
49428
  "pipelineOrchestrator.getNodeInferenceDevices": {
47680
49429
  capName: "pipeline-orchestrator",
47681
49430
  capScope: "system",
@@ -47718,6 +49467,12 @@ Object.freeze({
47718
49467
  addonId: null,
47719
49468
  access: "view"
47720
49469
  },
49470
+ "pipelineOrchestrator.listNodeBenchmarkResults": {
49471
+ capName: "pipeline-orchestrator",
49472
+ capScope: "system",
49473
+ addonId: null,
49474
+ access: "view"
49475
+ },
47721
49476
  "pipelineOrchestrator.pauseForStorageMigration": {
47722
49477
  capName: "pipeline-orchestrator",
47723
49478
  capScope: "system",
@@ -47862,6 +49617,12 @@ Object.freeze({
47862
49617
  addonId: null,
47863
49618
  access: "create"
47864
49619
  },
49620
+ "pipelineOrchestrator.startNodeBenchmark": {
49621
+ capName: "pipeline-orchestrator",
49622
+ capScope: "system",
49623
+ addonId: null,
49624
+ access: "create"
49625
+ },
47865
49626
  "pipelineOrchestrator.suggestShares": {
47866
49627
  capName: "pipeline-orchestrator",
47867
49628
  capScope: "system",
@@ -47880,6 +49641,12 @@ Object.freeze({
47880
49641
  addonId: null,
47881
49642
  access: "create"
47882
49643
  },
49644
+ "pipelineRunner.abortNodeBench": {
49645
+ capName: "pipeline-runner",
49646
+ capScope: "system",
49647
+ addonId: null,
49648
+ access: "create"
49649
+ },
47883
49650
  "pipelineRunner.attachCamera": {
47884
49651
  capName: "pipeline-runner",
47885
49652
  capScope: "system",
@@ -47928,6 +49695,12 @@ Object.freeze({
47928
49695
  addonId: null,
47929
49696
  access: "view"
47930
49697
  },
49698
+ "pipelineRunner.getNodeBenchStatus": {
49699
+ capName: "pipeline-runner",
49700
+ capScope: "system",
49701
+ addonId: null,
49702
+ access: "view"
49703
+ },
47931
49704
  "pipelineRunner.getParkedTrackFrame": {
47932
49705
  capName: "pipeline-runner",
47933
49706
  capScope: "system",
@@ -47970,6 +49743,12 @@ Object.freeze({
47970
49743
  addonId: null,
47971
49744
  access: "create"
47972
49745
  },
49746
+ "pipelineRunner.startNodeBench": {
49747
+ capName: "pipeline-runner",
49748
+ capScope: "system",
49749
+ addonId: null,
49750
+ access: "create"
49751
+ },
47973
49752
  "plateGallery.assignPlate": {
47974
49753
  capName: "plate-gallery",
47975
49754
  capScope: "system",
@@ -53117,6 +54896,11 @@ Object.freeze({
53117
54896
  form: "single",
53118
54897
  optional: false
53119
54898
  }],
54899
+ "pipelineAnalytics.addRetrainFrameFromRecording": [{
54900
+ name: "deviceId",
54901
+ form: "single",
54902
+ optional: false
54903
+ }],
53120
54904
  "pipelineAnalytics.applyDeviceSettingsPatch": [{
53121
54905
  name: "deviceId",
53122
54906
  form: "single",
@@ -53307,6 +55091,11 @@ Object.freeze({
53307
55091
  form: "single",
53308
55092
  optional: false
53309
55093
  }],
55094
+ "pipelineAnalytics.proposeRetrainAnnotationsWithLlm": [{
55095
+ name: "deviceId",
55096
+ form: "single",
55097
+ optional: false
55098
+ }],
53310
55099
  "pipelineAnalytics.pruneEventsBefore": [{
53311
55100
  name: "deviceId",
53312
55101
  form: "single",