@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.mjs CHANGED
@@ -12,7 +12,7 @@ import { networkInterfaces } from "node:os";
12
12
  var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
13
13
  var __require = /* @__PURE__ */ createRequire(import.meta.url);
14
14
  //#endregion
15
- //#region ../types/dist/event-category-B_0XEcLF.mjs
15
+ //#region ../types/dist/event-category-DaIZi00R.mjs
16
16
  var EventCategory = /* @__PURE__ */ function(EventCategory) {
17
17
  EventCategory["SystemBoot"] = "system.boot";
18
18
  EventCategory["SystemAddonsReady"] = "system.addons-ready";
@@ -91,6 +91,13 @@ var EventCategory = /* @__PURE__ */ function(EventCategory) {
91
91
  */
92
92
  EventCategory["AddonLoadFailed"] = "addon.load-failed";
93
93
  /**
94
+ * A keychain value was stored or removed (D787). Carries the ref, its
95
+ * owner and the new version — NEVER the value. A process holding the ref
96
+ * drops its cached copy and the owning `BaseAddon` re-resolves its config.
97
+ * Telemetry (D8): a process that misses it still revalidates by version.
98
+ */
99
+ EventCategory["KeychainChanged"] = "keychain.changed";
100
+ /**
94
101
  * Addon recovered from a previous failure. Emitted when an addon
95
102
  * transitions from `failed` back to `healthy` (typically via the
96
103
  * monitor's auto-retry loop, or after manual `addons.retryLoad`).
@@ -5383,7 +5390,7 @@ var ZodIssueCode = {
5383
5390
  var ZodFirstPartyTypeKind;
5384
5391
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
5385
5392
  //#endregion
5386
- //#region ../types/dist/sleep-B0JG7-_F.mjs
5393
+ //#region ../types/dist/sleep-Cr5YOk3m.mjs
5387
5394
  /**
5388
5395
  * The audio chunk plane's byte format, and the ONE expansion from a coded
5389
5396
  * window to float samples (D455).
@@ -5462,6 +5469,97 @@ function buildAlawTable() {
5462
5469
  }
5463
5470
  buildUlawTable();
5464
5471
  buildAlawTable();
5472
+ /** Is this field's stored value a credential? */
5473
+ function isSecretConfigField(field) {
5474
+ if (field.type === "password") return true;
5475
+ return "secret" in field && field.secret === true;
5476
+ }
5477
+ /**
5478
+ * Is this field's value stored in the KEYCHAIN (D787)? Every secret field is,
5479
+ * by its TYPE, unless it opts out with `storage: 'inline'` — never by its name.
5480
+ */
5481
+ function isKeychainStoredField(field) {
5482
+ if (!isSecretConfigField(field)) return false;
5483
+ if (field.type === "textarea" && field.isJson === true) return false;
5484
+ return !("storage" in field && field.storage === "inline");
5485
+ }
5486
+ /**
5487
+ * What a settings blob holds where a secret used to be.
5488
+ *
5489
+ * A keychain-stored field never holds its value. It holds a self-describing
5490
+ * MARKER, `{"$secret":"secret://…","v":1}` — an object, never a string, so no
5491
+ * code can mistake it for a credential and no form can send it to a camera as
5492
+ * a password. The empty state is `null` / absent, never `''`.
5493
+ *
5494
+ * The same shapes travel to and from the admin UI:
5495
+ *
5496
+ * - read: `hydrateSchema` hands a secret field a {@link SecretFieldView}
5497
+ * (`{ $secret, v, set: true }`) or `null` — the browser learns whether a
5498
+ * value is set, never the value.
5499
+ * - write: an untouched field submits the view back unchanged (KEEP); a typed
5500
+ * value is a plain non-empty string (CHANGE); the Clear button submits
5501
+ * {@link SECRET_CLEAR} (CLEAR). `''`, `null` and the legacy redaction tokens
5502
+ * are KEEP — an empty string is what a defaults-fallback pushes back, and
5503
+ * treating it as "clear" is how a save destroyed a stored credential before.
5504
+ *
5505
+ * Pure and browser-safe.
5506
+ */
5507
+ var SECRET_CLEAR = { $secretClear: true };
5508
+ /** The `'***'` token D634 redaction writes for non-admins. */
5509
+ var LEGACY_DEVICE_REDACTION = "***";
5510
+ function isRecord$1(value) {
5511
+ return typeof value === "object" && value !== null && !Array.isArray(value);
5512
+ }
5513
+ function makeSecretMarker(ref) {
5514
+ return {
5515
+ $secret: ref,
5516
+ v: 1
5517
+ };
5518
+ }
5519
+ /** A stored marker: an object whose `$secret` is a non-empty string. */
5520
+ function isSecretMarker(value) {
5521
+ if (!isRecord$1(value)) return false;
5522
+ const ref = value["$secret"];
5523
+ return typeof ref === "string" && ref.length > 0;
5524
+ }
5525
+ function isSecretClear(value) {
5526
+ return isRecord$1(value) && value["$secretClear"] === true;
5527
+ }
5528
+ /**
5529
+ * The UI view of a stored secret field value: a marker becomes "set", inline
5530
+ * plaintext becomes "set (inline)", nothing becomes `null`. A value never
5531
+ * survives this function.
5532
+ */
5533
+ function toSecretFieldView(stored) {
5534
+ if (isSecretMarker(stored)) return {
5535
+ $secret: stored.$secret,
5536
+ v: 1,
5537
+ set: true
5538
+ };
5539
+ if (typeof stored === "string" && stored.length > 0) return {
5540
+ $secret: null,
5541
+ v: 1,
5542
+ set: true,
5543
+ inline: true
5544
+ };
5545
+ return null;
5546
+ }
5547
+ /**
5548
+ * Classify an incoming value for a secret path. Only a non-empty string that is
5549
+ * not a redaction token sets a value; only {@link SECRET_CLEAR} clears.
5550
+ * Everything else — a marker (ours or anyone's), a UI view, `''`, `null`,
5551
+ * `undefined`, a redaction token, a non-string — keeps what is stored.
5552
+ */
5553
+ function classifySecretWrite(incoming) {
5554
+ if (isSecretClear(incoming)) return { kind: "clear" };
5555
+ if (typeof incoming !== "string") return { kind: "keep" };
5556
+ if (incoming.length === 0) return { kind: "keep" };
5557
+ if (incoming === "__camstack_redacted__" || incoming === LEGACY_DEVICE_REDACTION) return { kind: "keep" };
5558
+ return {
5559
+ kind: "set",
5560
+ value: incoming
5561
+ };
5562
+ }
5465
5563
  Object.fromEntries([
5466
5564
  {
5467
5565
  id: "overview",
@@ -5633,33 +5731,19 @@ Object.fromEntries([
5633
5731
  function isValuelessField(field) {
5634
5732
  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";
5635
5733
  }
5636
- /**
5637
- * Merge a `ConfigUISchema` with a raw `values` record into a
5638
- * `ConfigUISchemaWithValues`. Used by every `get*Settings` backend endpoint
5639
- * before returning to the admin UI. Groups are walked recursively.
5640
- *
5641
- * For each leaf field:
5642
- * - structural fields (`separator`, `info`, `button`) pass through unchanged
5643
- * - other fields get `value = values[key] ?? field.default ?? null`
5644
- *
5645
- * Unknown keys in `values` (keys not declared in the schema) are silently
5646
- * ignored — they don't contribute to the output. Missing keys fall back to
5647
- * the schema default or `null`. This mirrors the old backend behaviour where
5648
- * `FormBuilder` rendered `values[key] ?? field.default`.
5649
- */
5650
- function hydrateSchema(schema, values) {
5734
+ function hydrateSchema(schema, values, options = {}) {
5651
5735
  return {
5652
5736
  ...schema.tabs ? { tabs: [...schema.tabs] } : {},
5653
5737
  sections: schema.sections.map((section) => ({
5654
5738
  ...section,
5655
- fields: section.fields.map((field) => hydrateField(field, values))
5739
+ fields: section.fields.map((field) => hydrateField(field, values, options))
5656
5740
  }))
5657
5741
  };
5658
5742
  }
5659
- function hydrateField(field, values) {
5743
+ function hydrateField(field, values, options) {
5660
5744
  if (isValuelessField(field)) return field;
5661
5745
  if (field.type === "group") {
5662
- const hydratedChildren = field.fields.map((child) => hydrateField(child, values));
5746
+ const hydratedChildren = field.fields.map((child) => hydrateField(child, values, options));
5663
5747
  return {
5664
5748
  ...field,
5665
5749
  fields: hydratedChildren
@@ -5668,7 +5752,7 @@ function hydrateField(field, values) {
5668
5752
  if (field.type === "sub-tabs") {
5669
5753
  const hydratedTabs = field.tabs.map((tab) => ({
5670
5754
  ...tab,
5671
- fields: tab.fields.map((child) => hydrateField(child, values))
5755
+ fields: tab.fields.map((child) => hydrateField(child, values, options))
5672
5756
  }));
5673
5757
  return {
5674
5758
  ...field,
@@ -5678,6 +5762,33 @@ function hydrateField(field, values) {
5678
5762
  const key = field.key;
5679
5763
  const storedValue = Object.prototype.hasOwnProperty.call(values, key) ? values[key] : void 0;
5680
5764
  const defaultValue = field.default;
5765
+ const asView = (v) => isSecretMarker(v) || options.inlineSecretsAsViews === true && v !== void 0;
5766
+ if (isKeychainStoredField(field) && asView(storedValue)) return {
5767
+ ...field,
5768
+ value: toSecretFieldView(storedValue)
5769
+ };
5770
+ if (isKeychainStoredField(field) && options.inlineSecretsAsViews === true) return {
5771
+ ...field,
5772
+ value: null
5773
+ };
5774
+ if (field.type === "editable-array" && Array.isArray(storedValue)) {
5775
+ const secretItemKeys = field.itemFields.filter((item) => "key" in item && isKeychainStoredField(item)).map((item) => "key" in item ? item.key : "");
5776
+ if (secretItemKeys.length > 0) {
5777
+ const rows = storedValue.map((row) => {
5778
+ if (row === null || typeof row !== "object" || Array.isArray(row)) return row;
5779
+ const out = { ...row };
5780
+ for (const k of secretItemKeys) {
5781
+ const v = Reflect.get(row, k);
5782
+ if (asView(v)) out[k] = toSecretFieldView(v);
5783
+ }
5784
+ return out;
5785
+ });
5786
+ return {
5787
+ ...field,
5788
+ value: rows
5789
+ };
5790
+ }
5791
+ }
5681
5792
  if (field.multiple) {
5682
5793
  const stored = Array.isArray(storedValue) ? storedValue : storedValue !== void 0 && storedValue !== null ? [storedValue] : [];
5683
5794
  const itemFallback = field.multiple.itemDefault !== void 0 ? field.multiple.itemDefault : defaultValue !== void 0 ? defaultValue : typeOf(field) === "string" ? "" : null;
@@ -5920,6 +6031,431 @@ function projectStore(store, perNodeKeys, nodeId) {
5920
6031
  }
5921
6032
  return out;
5922
6033
  }
6034
+ var GLOBAL_SCOPE = { kind: "global" };
6035
+ /** The scope every addon-wide (not per-node, not per-device) setting lives in. */
6036
+ function globalSecretScope() {
6037
+ return GLOBAL_SCOPE;
6038
+ }
6039
+ function encodeSegment(value) {
6040
+ return encodeURIComponent(value);
6041
+ }
6042
+ /**
6043
+ * The field path of a value inside an array item, addressed by the item's id:
6044
+ * `arrayItemFieldPath('providers', 'authentik', 'clientSecret')` →
6045
+ * `providers[authentik].clientSecret`.
6046
+ */
6047
+ function arrayItemFieldPath(arrayKey, itemId, fieldKey) {
6048
+ return `${arrayKey}[${encodeSegment(itemId)}].${fieldKey}`;
6049
+ }
6050
+ /** A write to a secret path could not be stored in the keychain, so it was refused. */
6051
+ var KeychainWriteRefusedError = class extends Error {
6052
+ fieldPath;
6053
+ constructor(fieldPath, cause) {
6054
+ super(`secret "${fieldPath}" was not saved: the keychain could not store it (${cause instanceof Error ? cause.message : String(cause)}). Nothing was written.`);
6055
+ this.fieldPath = fieldPath;
6056
+ this.name = "KeychainWriteRefusedError";
6057
+ }
6058
+ };
6059
+ var KEEP = { kind: "keep" };
6060
+ function isRecord(value) {
6061
+ return typeof value === "object" && value !== null && !Array.isArray(value);
6062
+ }
6063
+ function defaultMintId() {
6064
+ return globalThis.crypto.randomUUID();
6065
+ }
6066
+ /** Every marker ref anywhere under `value`. */
6067
+ function collectSecretMarkerRefs(value, out = []) {
6068
+ if (isSecretMarker(value)) {
6069
+ out.push(value.$secret);
6070
+ return out;
6071
+ }
6072
+ if (Array.isArray(value)) for (const item of value) collectSecretMarkerRefs(item, out);
6073
+ else if (isRecord(value)) for (const child of Object.values(value)) collectSecretMarkerRefs(child, out);
6074
+ return out;
6075
+ }
6076
+ async function storedValueEquals(secrets, marker, candidate) {
6077
+ const resolved = (await secrets.resolve([marker.$secret]))[marker.$secret];
6078
+ return resolved?.kind === "value" && resolved.value === candidate;
6079
+ }
6080
+ async function writeLeaf(ctx, incoming, stored, fieldPath) {
6081
+ const intent = classifySecretWrite(incoming);
6082
+ const ref = ctx.secrets.ref(ctx.scope, fieldPath);
6083
+ const storedIsOurs = isSecretMarker(stored) && stored.$secret === ref;
6084
+ if (intent.kind === "keep") return KEEP;
6085
+ if (intent.kind === "set" && !ctx.operatorWrite && typeof stored === "string" && stored === intent.value) return KEEP;
6086
+ if (intent.kind === "clear") {
6087
+ if (storedIsOurs) ctx.deletes.push(ref);
6088
+ return {
6089
+ kind: "value",
6090
+ value: null
6091
+ };
6092
+ }
6093
+ if (storedIsOurs && await storedValueEquals(ctx.secrets, stored, intent.value)) return {
6094
+ kind: "value",
6095
+ value: stored
6096
+ };
6097
+ try {
6098
+ await ctx.secrets.put(ref, intent.value);
6099
+ } catch (err) {
6100
+ throw new KeychainWriteRefusedError(fieldPath, err);
6101
+ }
6102
+ return {
6103
+ kind: "value",
6104
+ value: makeSecretMarker(ref)
6105
+ };
6106
+ }
6107
+ /** Apply a member result onto `out`: KEEP restores the stored member, or removes it. */
6108
+ function applyMember(out, key, result, storedParent) {
6109
+ if (result.kind === "value") {
6110
+ out[key] = result.value;
6111
+ return;
6112
+ }
6113
+ if (Object.prototype.hasOwnProperty.call(storedParent, key)) out[key] = storedParent[key];
6114
+ else delete out[key];
6115
+ }
6116
+ async function writeMembers(ctx, children, incoming, stored, pathOf) {
6117
+ const out = { ...incoming };
6118
+ for (const [member, node] of children) applyMember(out, member, await writeNode(ctx, node, incoming[member], stored[member], pathOf(member)), stored);
6119
+ return out;
6120
+ }
6121
+ function rowId(row, idKey) {
6122
+ const raw = row[idKey];
6123
+ if (typeof raw === "string" && raw.length > 0) return raw;
6124
+ if (typeof raw === "number" && Number.isFinite(raw)) return String(raw);
6125
+ return null;
6126
+ }
6127
+ async function writeArray(ctx, node, incoming, stored, fieldPath) {
6128
+ const storedRows = Array.isArray(stored) ? stored.filter(isRecord) : [];
6129
+ if (!Array.isArray(incoming)) {
6130
+ ctx.deletes.push(...collectSecretMarkerRefs(storedRows));
6131
+ return {
6132
+ kind: "value",
6133
+ value: incoming
6134
+ };
6135
+ }
6136
+ const storedById = /* @__PURE__ */ new Map();
6137
+ for (const row of storedRows) {
6138
+ const id = rowId(row, node.idKey);
6139
+ if (id !== null) storedById.set(id, row);
6140
+ }
6141
+ const kept = /* @__PURE__ */ new Set();
6142
+ const rows = [];
6143
+ for (const row of incoming) {
6144
+ if (!isRecord(row)) {
6145
+ rows.push(row);
6146
+ continue;
6147
+ }
6148
+ const id = rowId(row, node.idKey) ?? ctx.mintId();
6149
+ kept.add(id);
6150
+ const withId = {
6151
+ ...row,
6152
+ [node.idKey]: row[node.idKey] ?? id
6153
+ };
6154
+ if (rowId(withId, node.idKey) === null) withId[node.idKey] = id;
6155
+ const storedRow = storedById.get(id) ?? {};
6156
+ rows.push(await writeMembers(ctx, node.item, withId, storedRow, (member) => arrayItemFieldPath(fieldPath, id, member)));
6157
+ }
6158
+ for (const [id, row] of storedById) if (!kept.has(id)) ctx.deletes.push(...collectSecretMarkerRefs(row));
6159
+ return {
6160
+ kind: "value",
6161
+ value: rows
6162
+ };
6163
+ }
6164
+ async function writeNode(ctx, node, incoming, stored, fieldPath) {
6165
+ switch (node.kind) {
6166
+ case "leaf": return writeLeaf(ctx, incoming, stored, fieldPath);
6167
+ case "array": return writeArray(ctx, node, incoming, stored, fieldPath);
6168
+ case "object": {
6169
+ if (!isRecord(incoming)) {
6170
+ if (incoming === void 0) return KEEP;
6171
+ ctx.deletes.push(...collectSecretMarkerRefs(stored));
6172
+ return {
6173
+ kind: "value",
6174
+ value: incoming
6175
+ };
6176
+ }
6177
+ const storedObj = isRecord(stored) ? stored : {};
6178
+ return {
6179
+ kind: "value",
6180
+ value: await writeMembers(ctx, node.children, incoming, storedObj, (m) => `${fieldPath}.${m}`)
6181
+ };
6182
+ }
6183
+ }
6184
+ }
6185
+ /** Split a perNode-scoped key (`key@nodeId`). */
6186
+ function splitNodeKey(key) {
6187
+ const at = key.indexOf("@");
6188
+ return at <= 0 ? {
6189
+ base: key,
6190
+ nodeId: null
6191
+ } : {
6192
+ base: key.slice(0, at),
6193
+ nodeId: key.slice(at + 1)
6194
+ };
6195
+ }
6196
+ /** Rewrite a settings patch so no secret value reaches the blob. See the file doc. */
6197
+ async function transformSecretWrite(input) {
6198
+ const deletes = [];
6199
+ const base = {
6200
+ secrets: input.secrets,
6201
+ mintId: input.mintId ?? defaultMintId,
6202
+ deletes,
6203
+ operatorWrite: input.operatorWrite === true
6204
+ };
6205
+ const out = {};
6206
+ for (const [key, incoming] of Object.entries(input.patch)) {
6207
+ const { base: baseKey, nodeId } = splitNodeKey(key);
6208
+ const node = input.tree.get(baseKey);
6209
+ if (node === void 0) {
6210
+ out[key] = incoming;
6211
+ continue;
6212
+ }
6213
+ const scope = nodeId !== null && nodeId.length > 0 ? {
6214
+ kind: "node",
6215
+ nodeId
6216
+ } : input.scope ?? globalSecretScope();
6217
+ const result = await writeNode({
6218
+ ...base,
6219
+ scope
6220
+ }, node, incoming, input.stored[key], baseKey);
6221
+ if (result.kind === "value") out[key] = result.value;
6222
+ }
6223
+ return {
6224
+ patch: out,
6225
+ afterWrite: async () => {
6226
+ if (deletes.length === 0) return { orphaned: [] };
6227
+ try {
6228
+ await input.secrets.delete([...new Set(deletes)]);
6229
+ return { orphaned: [] };
6230
+ } catch {
6231
+ return { orphaned: [...new Set(deletes)] };
6232
+ }
6233
+ }
6234
+ };
6235
+ }
6236
+ /**
6237
+ * Replace every marker in `value` with its keychain value. Returns the SAME
6238
+ * reference when there is no marker (no allocation, no keychain call).
6239
+ */
6240
+ async function resolveSecretMarkers(value, secrets) {
6241
+ const refs = collectSecretMarkerRefs(value);
6242
+ if (refs.length === 0) return {
6243
+ value,
6244
+ unresolved: []
6245
+ };
6246
+ const answers = await secrets.resolve(refs);
6247
+ const unresolved = [];
6248
+ for (const ref of new Set(refs)) {
6249
+ const answer = answers[ref];
6250
+ if (answer === void 0) unresolved.push({
6251
+ ref,
6252
+ reason: "not-initialized"
6253
+ });
6254
+ else if (answer.kind === "unavailable") unresolved.push({
6255
+ ref,
6256
+ reason: answer.reason
6257
+ });
6258
+ else if (answer.kind === "missing" || answer.kind === "forbidden") unresolved.push({
6259
+ ref,
6260
+ reason: answer.kind
6261
+ });
6262
+ }
6263
+ const substitute = (v) => {
6264
+ if (isSecretMarker(v)) {
6265
+ const answer = answers[v.$secret];
6266
+ return answer?.kind === "value" ? {
6267
+ keep: true,
6268
+ value: answer.value
6269
+ } : {
6270
+ keep: false,
6271
+ value: void 0
6272
+ };
6273
+ }
6274
+ if (Array.isArray(v)) {
6275
+ const items = [];
6276
+ for (const item of v) {
6277
+ const s = substitute(item);
6278
+ if (s.keep) items.push(s.value);
6279
+ }
6280
+ return {
6281
+ keep: true,
6282
+ value: items
6283
+ };
6284
+ }
6285
+ if (isRecord(v)) {
6286
+ const out = {};
6287
+ for (const [k, child] of Object.entries(v)) {
6288
+ const s = substitute(child);
6289
+ if (s.keep) out[k] = s.value;
6290
+ }
6291
+ return {
6292
+ keep: true,
6293
+ value: out
6294
+ };
6295
+ }
6296
+ return {
6297
+ keep: true,
6298
+ value: v
6299
+ };
6300
+ };
6301
+ return {
6302
+ value: substitute(value).value,
6303
+ unresolved
6304
+ };
6305
+ }
6306
+ function touchesTree(tree, patch) {
6307
+ if (tree.size === 0) return false;
6308
+ for (const key of Object.keys(patch)) {
6309
+ const at = key.indexOf("@");
6310
+ if (tree.has(at > 0 ? key.slice(0, at) : key)) return true;
6311
+ }
6312
+ return false;
6313
+ }
6314
+ /** The blob as stored now; a failed read REFUSES the write instead of guessing. */
6315
+ async function readStoredAddonBlob(raw) {
6316
+ const threeWay = raw.readAddonStoreResult;
6317
+ if (threeWay === void 0) return raw.readAddonStore();
6318
+ const result = await threeWay.call(raw);
6319
+ if (result.kind === "failed") throw new Error(`settings write refused: the stored blob could not be read (${result.error})`);
6320
+ return result.kind === "missing" ? {} : result.value;
6321
+ }
6322
+ function createSecretAwareSettings(raw, opts) {
6323
+ const chains = /* @__PURE__ */ new Map();
6324
+ const serialize = (key, fn) => {
6325
+ const next = (chains.get(key) ?? Promise.resolve()).then(fn, fn);
6326
+ const tail = next.catch(() => void 0);
6327
+ chains.set(key, tail);
6328
+ tail.then(() => {
6329
+ if (chains.get(key) === tail) chains.delete(key);
6330
+ });
6331
+ return next;
6332
+ };
6333
+ const write = async (chainKey, tree, scope, patch, readStored, rawWrite) => {
6334
+ if (!touchesTree(tree, patch)) return rawWrite(patch);
6335
+ return serialize(chainKey, async () => {
6336
+ const stored = await readStored();
6337
+ const result = await transformSecretWrite({
6338
+ tree,
6339
+ secrets: opts.secrets,
6340
+ patch,
6341
+ stored,
6342
+ ...scope !== void 0 ? { scope } : {},
6343
+ operatorWrite: opts.isOperatorWrite?.() === true
6344
+ });
6345
+ if (Object.keys(result.patch).length > 0) await rawWrite(result.patch);
6346
+ const { orphaned } = await result.afterWrite();
6347
+ if (orphaned.length > 0) opts.onOrphaned(orphaned);
6348
+ });
6349
+ };
6350
+ const wrapped = {
6351
+ writeAddonStore: (patch) => write("addon", opts.addonTree(), void 0, patch, () => readStoredAddonBlob(raw), (p) => raw.writeAddonStore(p)),
6352
+ writeDeviceStore: (deviceId, patch) => write(`device:${deviceId}`, opts.deviceTree(), {
6353
+ kind: "device",
6354
+ deviceId
6355
+ }, patch, () => raw.readDeviceStore(deviceId), (p) => raw.writeDeviceStore(deviceId, p))
6356
+ };
6357
+ return new Proxy(raw, { get(target, prop, receiver) {
6358
+ if (prop === "writeAddonStore") return wrapped.writeAddonStore;
6359
+ if (prop === "writeDeviceStore") return wrapped.writeDeviceStore;
6360
+ const value = Reflect.get(target, prop, receiver);
6361
+ return typeof value === "function" ? value.bind(target) : value;
6362
+ } });
6363
+ }
6364
+ /** The context the addon sees: identical, except that its settings writes are secret-aware. */
6365
+ function withSecretAwareSettings(context, opts) {
6366
+ const raw = context.settings;
6367
+ if (raw === void 0) return context;
6368
+ const settings = createSecretAwareSettings(raw, opts);
6369
+ return new Proxy(context, { get(target, prop, receiver) {
6370
+ if (prop === "settings") return settings;
6371
+ return Reflect.get(target, prop, receiver);
6372
+ } });
6373
+ }
6374
+ var LEAF = { kind: "leaf" };
6375
+ var DEFAULT_ITEM_ID_KEY = "id";
6376
+ function collectFields(fields, out) {
6377
+ for (const field of fields) {
6378
+ if (field.type === "group") {
6379
+ collectFields(field.fields, out);
6380
+ continue;
6381
+ }
6382
+ if (field.type === "sub-tabs") {
6383
+ for (const tab of field.tabs) collectFields(tab.fields, out);
6384
+ continue;
6385
+ }
6386
+ if (field.type === "editable-array") {
6387
+ const item = /* @__PURE__ */ new Map();
6388
+ for (const itemField of field.itemFields) if ("key" in itemField && isKeychainStoredField(itemField)) item.set(itemField.key, LEAF);
6389
+ if (item.size > 0) out.set(field.key, {
6390
+ kind: "array",
6391
+ idKey: field.itemIdKey ?? DEFAULT_ITEM_ID_KEY,
6392
+ item
6393
+ });
6394
+ continue;
6395
+ }
6396
+ if (!("key" in field) || typeof field.key !== "string") continue;
6397
+ if (isKeychainStoredField(field)) out.set(field.key, LEAF);
6398
+ }
6399
+ }
6400
+ /** The secret tree a settings schema declares. */
6401
+ function secretTreeFromSchema(schema) {
6402
+ const out = /* @__PURE__ */ new Map();
6403
+ if (schema === null) return out;
6404
+ for (const section of schema.sections) collectFields(section.fields, out);
6405
+ return out;
6406
+ }
6407
+ /** Parse `a.b[id].c` into segments; throws on a malformed path (a declaration bug). */
6408
+ function parseSecretStatePath(path) {
6409
+ const segments = [];
6410
+ for (const raw of path.split(".")) {
6411
+ const m = /^([^[\]]+)(?:\[([^[\]]+)\])?$/.exec(raw);
6412
+ if (m === null || m[1] === void 0) throw new Error(`secretStatePaths: malformed path "${path}"`);
6413
+ segments.push(m[2] !== void 0 ? {
6414
+ key: m[1],
6415
+ idKey: m[2]
6416
+ } : { key: m[1] });
6417
+ }
6418
+ if (segments.length === 0) throw new Error(`secretStatePaths: empty path`);
6419
+ if (segments[segments.length - 1]?.idKey !== void 0) throw new Error(`secretStatePaths: "${path}" ends on an array — name the member that is secret`);
6420
+ return segments;
6421
+ }
6422
+ function insert(into, segments) {
6423
+ const [head, ...rest] = segments;
6424
+ if (head === void 0) return;
6425
+ if (rest.length === 0) {
6426
+ into.set(head.key, LEAF);
6427
+ return;
6428
+ }
6429
+ const existing = into.get(head.key);
6430
+ if (head.idKey !== void 0) {
6431
+ const item = new Map(existing?.kind === "array" ? existing.item : []);
6432
+ insert(item, rest);
6433
+ into.set(head.key, {
6434
+ kind: "array",
6435
+ idKey: head.idKey,
6436
+ item
6437
+ });
6438
+ return;
6439
+ }
6440
+ const children = new Map(existing?.kind === "object" ? existing.children : []);
6441
+ insert(children, rest);
6442
+ into.set(head.key, {
6443
+ kind: "object",
6444
+ children
6445
+ });
6446
+ }
6447
+ /** Add hidden-state paths (`secretStatePaths`) to a schema-derived tree. */
6448
+ function mergeSecretStatePaths(tree, paths) {
6449
+ if (paths.length === 0) return tree;
6450
+ const out = new Map(tree);
6451
+ for (const path of paths) insert(out, parseSecretStatePath(path));
6452
+ return out;
6453
+ }
6454
+ /** First retry of a secret the keychain could not serve; doubles to {@link SECRET_RETRY_MAX_MS}. */
6455
+ var SECRET_RETRY_FIRST_MS = 5e3;
6456
+ var SECRET_RETRY_MAX_MS = 5 * 6e4;
6457
+ /** Coalesces a burst of `keychain.changed` events into one re-resolve. */
6458
+ var SECRET_CHANGE_DEBOUNCE_MS = 250;
5923
6459
  /**
5924
6460
  * Base class for CamStack addons. Eliminates settings boilerplate:
5925
6461
  *
@@ -5989,6 +6525,25 @@ var BaseAddon = class {
5989
6525
  settingsStoreReady = false;
5990
6526
  /** Default config values. Provided via constructor. */
5991
6527
  defaults;
6528
+ /**
6529
+ * Hidden-state paths that hold secrets (D787) — values the addon writes
6530
+ * itself (`updateGlobalSettings`, `state()`) that no form field declares.
6531
+ * Stored in the keychain exactly like a `password` field. Syntax:
6532
+ * `'snapshotSigningKey'`, `'identity.pincode'`, `'tokens[userId].accessToken'`
6533
+ * (`key[<id field>]` addresses array items by id, never by index).
6534
+ */
6535
+ secretStatePaths = [];
6536
+ _addonSecretTree = null;
6537
+ _deviceSecretTree = null;
6538
+ /** Refs the last resolved config pointed at — a change to one re-resolves. */
6539
+ _configSecretRefs = /* @__PURE__ */ new Set();
6540
+ _unresolvedSecrets = [];
6541
+ _secretRetryTimer = null;
6542
+ _secretRetryDelayMs = SECRET_RETRY_FIRST_MS;
6543
+ _secretChangeTimer = null;
6544
+ _secretChangeUnsub = null;
6545
+ /** >0 while an OPERATOR's settings write is being applied. */
6546
+ _operatorWriteDepth = 0;
5992
6547
  constructor(defaults) {
5993
6548
  this.defaults = defaults;
5994
6549
  this._config = { ...defaults };
@@ -6024,8 +6579,18 @@ var BaseAddon = class {
6024
6579
  return this._config;
6025
6580
  }
6026
6581
  async initialize(context) {
6027
- this._ctx = context;
6582
+ const secrets = context.secrets;
6583
+ this._ctx = secrets !== void 0 ? withSecretAwareSettings(context, {
6584
+ secrets,
6585
+ addonTree: () => this.addonSecretTree(),
6586
+ deviceTree: () => this.deviceSecretTree(),
6587
+ onOrphaned: (refs) => context.logger.warn("keychain refs dropped by a settings write could not be deleted", { meta: { refs: [...refs] } }),
6588
+ isOperatorWrite: () => this._operatorWriteDepth > 0
6589
+ }) : context;
6028
6590
  await this.resolveConfig();
6591
+ if (secrets !== void 0) this._secretChangeUnsub = secrets.onChange((ref) => {
6592
+ if (this._configSecretRefs.has(ref)) this.scheduleSecretReresolve(SECRET_CHANGE_DEBOUNCE_MS);
6593
+ });
6029
6594
  const result = await this.onInitialize();
6030
6595
  this.emitLifecycle(EventCategory.AddonStarted);
6031
6596
  const normalized = normalizeAddonInitResult(result);
@@ -6058,6 +6623,12 @@ var BaseAddon = class {
6058
6623
  */
6059
6624
  async onHubReachable() {}
6060
6625
  async shutdown() {
6626
+ this._secretChangeUnsub?.();
6627
+ this._secretChangeUnsub = null;
6628
+ if (this._secretRetryTimer !== null) clearTimeout(this._secretRetryTimer);
6629
+ if (this._secretChangeTimer !== null) clearTimeout(this._secretChangeTimer);
6630
+ this._secretRetryTimer = null;
6631
+ this._secretChangeTimer = null;
6061
6632
  this.emitLifecycle(EventCategory.AddonStopped);
6062
6633
  if (this.autoEmitReadiness) this.emitReadinessForProviders("down");
6063
6634
  await this.onShutdown();
@@ -6136,7 +6707,7 @@ var BaseAddon = class {
6136
6707
  return hydrateSchema(schema, overlay ? {
6137
6708
  ...projected,
6138
6709
  ...overlay
6139
- } : projected);
6710
+ } : projected, { inlineSecretsAsViews: true });
6140
6711
  }
6141
6712
  /**
6142
6713
  * The integration-level view of this addon's settings: exactly the sections
@@ -6185,7 +6756,7 @@ var BaseAddon = class {
6185
6756
  return hydrateSchema({
6186
6757
  ...schema,
6187
6758
  sections
6188
- }, projected);
6759
+ }, projected, { inlineSecretsAsViews: true });
6189
6760
  }
6190
6761
  /**
6191
6762
  * The raw addon store PROJECTED onto the target node's bare per-node keys:
@@ -6239,18 +6810,50 @@ var BaseAddon = class {
6239
6810
  value: result.value[key]
6240
6811
  };
6241
6812
  }
6813
+ /**
6814
+ * The OPERATOR's write — a settings form or an admin API call, dispatched by
6815
+ * the kernel. Identical to {@link updateGlobalSettings}, except that a secret
6816
+ * the operator sends is stored as sent even when it equals a pre-keychain
6817
+ * inline value: the operator re-entering a password is a change, an addon
6818
+ * writing back what it read is not (D787).
6819
+ */
6820
+ async updateGlobalSettingsAsOperator(patch, nodeId) {
6821
+ this._operatorWriteDepth++;
6822
+ try {
6823
+ await this.applyGlobalPatch(patch, nodeId);
6824
+ } finally {
6825
+ this._operatorWriteDepth--;
6826
+ }
6827
+ }
6242
6828
  async updateGlobalSettings(patch, nodeId) {
6829
+ await this.applyGlobalPatch(patch, nodeId);
6830
+ }
6831
+ /**
6832
+ * REMOVE stored secrets — their keychain values and their markers (D787).
6833
+ *
6834
+ * Writing `''` to a secret field KEEPS what is stored (an empty string is
6835
+ * what a defaults fallback writes back, and it must never destroy a
6836
+ * credential), so code that means "forget this token" says so here. Without
6837
+ * a keychain (an older kernel) it writes `''`, as such code always did.
6838
+ */
6839
+ async clearSecrets(keys, nodeId) {
6840
+ const tree = this.addonSecretTree();
6841
+ const keychain = this._ctx?.secrets !== void 0;
6842
+ const patch = {};
6843
+ for (const key of keys) patch[key] = keychain && tree.has(key) ? SECRET_CLEAR : "";
6844
+ await this.applyGlobalPatch(patch, nodeId);
6845
+ }
6846
+ async applyGlobalPatch(barePatch, nodeId) {
6243
6847
  const keys = this.perNodeKeys();
6244
6848
  const localNode = normalizeNodeId(this._ctx?.kernel?.localNodeId);
6245
6849
  const target = normalizeNodeId(nodeId ?? this._ctx?.kernel?.localNodeId);
6246
- const barePatch = patch;
6247
6850
  const scoped = keys.size > 0 ? scopePatch(barePatch, keys, target) : barePatch;
6248
6851
  await this._ctx?.settings?.writeAddonStore(scoped);
6249
6852
  if (target !== localNode) return;
6250
6853
  await this.resolveConfig();
6251
6854
  await this.onConfigChanged();
6252
6855
  this.emitLifecycle(EventCategory.AddonUpdated, { level: "global" });
6253
- this.maybeAutoRestart(patch, this.globalSettingsSchema());
6856
+ this.maybeAutoRestart(Object.keys(barePatch), this.globalSettingsSchema());
6254
6857
  }
6255
6858
  /**
6256
6859
  * The set of field keys the global settings schema declares `perNode: true`
@@ -6275,7 +6878,7 @@ var BaseAddon = class {
6275
6878
  * time to return its response before the addon is torn down and
6276
6879
  * re-initialised by `AddonRegistryService.restartAddon`.
6277
6880
  */
6278
- maybeAutoRestart(patch, schema) {
6881
+ maybeAutoRestart(patchKeys, schema) {
6279
6882
  if (!schema) return;
6280
6883
  const restartKeys = /* @__PURE__ */ new Set();
6281
6884
  for (const section of schema.sections) for (const field of section.fields) {
@@ -6283,13 +6886,13 @@ var BaseAddon = class {
6283
6886
  if (field.requiresRestart) restartKeys.add(field.key);
6284
6887
  }
6285
6888
  if (restartKeys.size === 0) return;
6286
- if (!Object.keys(patch).some((k) => restartKeys.has(k))) return;
6889
+ if (!patchKeys.some((k) => restartKeys.has(k))) return;
6287
6890
  const ctx = this._ctx;
6288
6891
  if (!ctx) return;
6289
6892
  const addonId = ctx.id;
6290
6893
  setImmediate(() => {
6291
6894
  ctx.api.addons?.restartAddon?.mutate({ addonId }).then(() => {
6292
- ctx.logger.info("addon auto-restart triggered by restart-required setting change", { meta: { changedFields: Object.keys(patch).filter((k) => restartKeys.has(k)) } });
6895
+ ctx.logger.info("addon auto-restart triggered by restart-required setting change", { meta: { changedFields: patchKeys.filter((k) => restartKeys.has(k)) } });
6293
6896
  }).catch((err) => {
6294
6897
  ctx.logger.error("addon auto-restart failed", { meta: { error: err instanceof Error ? err.message : String(err) } });
6295
6898
  });
@@ -6298,7 +6901,7 @@ var BaseAddon = class {
6298
6901
  async getDeviceSettings(deviceId) {
6299
6902
  const schema = this.deviceSettingsSchema();
6300
6903
  if (!schema) return { sections: [] };
6301
- return hydrateSchema(schema, await this._ctx?.settings?.readDeviceStore(deviceId) ?? {});
6904
+ return hydrateSchema(schema, await this._ctx?.settings?.readDeviceStore(deviceId) ?? {}, { inlineSecretsAsViews: true });
6302
6905
  }
6303
6906
  async updateDeviceSettings(deviceId, patch) {
6304
6907
  await this._ctx?.settings?.writeDeviceStore(deviceId, patch);
@@ -6428,7 +7031,7 @@ var BaseAddon = class {
6428
7031
  * selection at boot (absent scoped key ⇒ the constructor default wins).
6429
7032
  */
6430
7033
  async resolveConfig() {
6431
- const stored = await this.readAddonStoreWithRetry();
7034
+ const stored = await this.resolveStoredSecrets(await this.readAddonStoreWithRetry());
6432
7035
  const perNode = this.perNodeKeys();
6433
7036
  const localNode = normalizeNodeId(this._ctx?.kernel?.localNodeId);
6434
7037
  const resolved = { ...this.defaults };
@@ -6453,7 +7056,7 @@ var BaseAddon = class {
6453
7056
  key,
6454
7057
  schema,
6455
7058
  fallback,
6456
- read: () => this.readAddonStoreWithRetry(),
7059
+ read: async () => this.resolveStoredSecrets(await this.readAddonStoreWithRetry()),
6457
7060
  write: async (patch) => {
6458
7061
  await this._ctx?.settings?.writeAddonStore(patch);
6459
7062
  },
@@ -6470,7 +7073,7 @@ var BaseAddon = class {
6470
7073
  key,
6471
7074
  schema,
6472
7075
  fallback,
6473
- read: async () => await this._ctx?.settings?.readDeviceStore(deviceId) ?? {},
7076
+ read: async () => this.resolveStoredSecrets(await this._ctx?.settings?.readDeviceStore(deviceId) ?? {}, false),
6474
7077
  write: async (patch) => {
6475
7078
  await this._ctx?.settings?.writeDeviceStore(deviceId, patch);
6476
7079
  },
@@ -6482,6 +7085,70 @@ var BaseAddon = class {
6482
7085
  } })
6483
7086
  });
6484
7087
  }
7088
+ /** The addon store's secret tree: schema fields by TYPE, plus `secretStatePaths`. */
7089
+ addonSecretTree() {
7090
+ this._addonSecretTree ??= mergeSecretStatePaths(secretTreeFromSchema(this.globalSettingsSchema()), this.secretStatePaths);
7091
+ return this._addonSecretTree;
7092
+ }
7093
+ deviceSecretTree() {
7094
+ this._deviceSecretTree ??= secretTreeFromSchema(this.deviceSettingsSchema());
7095
+ return this._deviceSecretTree;
7096
+ }
7097
+ /**
7098
+ * Secrets of this addon's stored config that could not be resolved on the
7099
+ * last read, with why. Non-empty means the addon is running WITHOUT them —
7100
+ * an addon whose function needs one should report itself degraded rather
7101
+ * than start on an empty credential.
7102
+ */
7103
+ get unresolvedSecrets() {
7104
+ return this._unresolvedSecrets;
7105
+ }
7106
+ /**
7107
+ * Substitute every keychain marker in a stored blob with its value. With no
7108
+ * keychain (no `ctx.secrets`) or no marker, the blob comes back unchanged.
7109
+ * An unresolvable value is LEFT OUT (never `''`), logged by ref — never by
7110
+ * value — and, when the cause can pass, retried with backoff. Nothing is
7111
+ * ever written back from here.
7112
+ */
7113
+ async resolveStoredSecrets(blob, trackForConfig = true) {
7114
+ const secrets = this._ctx?.secrets;
7115
+ if (secrets === void 0) return blob;
7116
+ const refs = collectSecretMarkerRefs(blob);
7117
+ if (trackForConfig) this._configSecretRefs = new Set(refs);
7118
+ if (refs.length === 0) {
7119
+ if (trackForConfig) this._unresolvedSecrets = [];
7120
+ return blob;
7121
+ }
7122
+ const { value, unresolved } = await resolveSecretMarkers(blob, secrets);
7123
+ if (trackForConfig) {
7124
+ this._unresolvedSecrets = unresolved;
7125
+ if (unresolved.length > 0) {
7126
+ this._ctx?.logger?.error?.("secret unavailable — running without it, will retry", { meta: { secrets: unresolved.map((u) => ({
7127
+ ref: u.ref,
7128
+ reason: u.reason
7129
+ })) } });
7130
+ if (unresolved.some((u) => u.reason !== "missing" && u.reason !== "forbidden")) {
7131
+ this.scheduleSecretReresolve(this._secretRetryDelayMs);
7132
+ this._secretRetryDelayMs = Math.min(this._secretRetryDelayMs * 2, SECRET_RETRY_MAX_MS);
7133
+ }
7134
+ } else this._secretRetryDelayMs = SECRET_RETRY_FIRST_MS;
7135
+ }
7136
+ return value;
7137
+ }
7138
+ /** Re-resolve the config (a keychain-only change, or a retry) and apply it. */
7139
+ scheduleSecretReresolve(delayMs) {
7140
+ const timerOf = delayMs === SECRET_CHANGE_DEBOUNCE_MS ? "_secretChangeTimer" : "_secretRetryTimer";
7141
+ if (this[timerOf] !== null) return;
7142
+ const timer = setTimeout(() => {
7143
+ this[timerOf] = null;
7144
+ if (this._ctx === null) return;
7145
+ this.resolveConfig().then(() => this.onConfigChanged()).catch((err) => {
7146
+ this._ctx?.logger?.error?.("re-resolving secrets failed", { meta: { error: err instanceof Error ? err.message : String(err) } });
7147
+ });
7148
+ }, delayMs);
7149
+ timer.unref?.();
7150
+ this[timerOf] = timer;
7151
+ }
6485
7152
  /**
6486
7153
  * Wrap `ctx.settings.readAddonStore()` with a short retry budget so a
6487
7154
  * transient settings-store outage (mid-restart of sqlite-settings, tsx-watch
@@ -7069,6 +7736,69 @@ method(object({ deviceId: number() }), array(StreamSourceEntrySchema)), method(o
7069
7736
  kind: "mutation",
7070
7737
  auth: "admin"
7071
7738
  }), method(object({ deviceId: number() }), unknown().nullable()), method(object({ deviceId: number() }), RawStateResultSchema.nullable(), { auth: "protected" });
7739
+ function defOf(schema) {
7740
+ return schema._zod?.def ?? {};
7741
+ }
7742
+ function declaredHere(schema) {
7743
+ return globalRegistry.get(schema)?.secret === true;
7744
+ }
7745
+ /** Wrapper kinds whose `innerType` is the field itself. */
7746
+ var WRAPPERS = new Set([
7747
+ "optional",
7748
+ "nullable",
7749
+ "default",
7750
+ "prefault",
7751
+ "catch",
7752
+ "readonly",
7753
+ "nonoptional"
7754
+ ]);
7755
+ /**
7756
+ * The schema layers that make up ONE field: the schema itself and every
7757
+ * wrapper below it (optional / default / nullable / readonly / catch), plus
7758
+ * both sides of a pipe (`z.preprocess` puts the real schema on `out`,
7759
+ * `.transform` on `in`).
7760
+ */
7761
+ function layersOf(schema) {
7762
+ const out = [];
7763
+ const queue = [schema];
7764
+ while (queue.length > 0) {
7765
+ const s = queue.shift();
7766
+ if (!s || out.includes(s)) continue;
7767
+ out.push(s);
7768
+ const def = defOf(s);
7769
+ if (def.type !== void 0 && WRAPPERS.has(def.type) && def.innerType) queue.push(def.innerType);
7770
+ if (def.type === "pipe") {
7771
+ if (def.in) queue.push(def.in);
7772
+ if (def.out) queue.push(def.out);
7773
+ }
7774
+ }
7775
+ return out;
7776
+ }
7777
+ /** True when any layer of this field declares `.meta({ secret: true })`. */
7778
+ function isZodSecret(schema) {
7779
+ return layersOf(schema).some(declaredHere);
7780
+ }
7781
+ /**
7782
+ * Every declared secret path in a config schema: dotted keys, `[]` for "each
7783
+ * element of this array" (`connection.password`, `rows[].token`). A declared
7784
+ * object or array is reported as one path and not descended into — everything
7785
+ * under it is secret.
7786
+ */
7787
+ function collectZodSecretPaths(schema, prefix = "") {
7788
+ if (isZodSecret(schema)) return prefix.length > 0 ? [prefix] : [];
7789
+ const paths = [];
7790
+ for (const layer of layersOf(schema)) {
7791
+ const def = defOf(layer);
7792
+ if (def.type === "object" && def.shape) for (const [key, child] of Object.entries(def.shape)) paths.push(...collectZodSecretPaths(child, prefix ? `${prefix}.${key}` : key));
7793
+ else if (def.type === "array" && def.element) paths.push(...collectZodSecretPaths(def.element, `${prefix}[]`));
7794
+ else if (def.type === "union" && def.options) for (const option of def.options) paths.push(...collectZodSecretPaths(option, prefix));
7795
+ else if (def.type === "intersection") {
7796
+ if (def.left) paths.push(...collectZodSecretPaths(def.left, prefix));
7797
+ if (def.right) paths.push(...collectZodSecretPaths(def.right, prefix));
7798
+ }
7799
+ }
7800
+ return [...new Set(paths)];
7801
+ }
7072
7802
  //#endregion
7073
7803
  //#region ../types/dist/err-msg-DX6i_MY4.mjs
7074
7804
  var DeviceType = /* @__PURE__ */ function(DeviceType) {
@@ -14390,6 +15120,196 @@ id: union([string(), number()]) }), {
14390
15120
  kind: "mutation",
14391
15121
  auth: "admin"
14392
15122
  });
15123
+ /**
15124
+ * `keychain` — the hub's encrypted store of secret values (D787).
15125
+ *
15126
+ * Settings blobs never hold a secret: they hold a marker
15127
+ * `{"$secret":"secret://<owner>/<scope>/<fieldPath>","v":1}` and the value
15128
+ * lives here, AES-256-GCM under a data key that a master key wraps. This cap
15129
+ * is the OWNER's door to its own values: every method is owner-checked
15130
+ * against the CALLER, never against anything the caller claims.
15131
+ *
15132
+ * Who the caller is: the transport stamps `callerAddonId` into the args of a
15133
+ * call that crossed a process (the parent `LocalChildRegistry` from the UDS
15134
+ * connection, the agent from its child's connection carried in
15135
+ * `$hub-cap-fwd`'s envelope). A stamp always overwrites; a wire call with no
15136
+ * stamp has its claim stripped. Only a hub in-process caller may state its own
15137
+ * identity — `ctx.secrets` does that with the addon id closed over. This is
15138
+ * identity against BUGS and misrouting, not against a malicious addon (every
15139
+ * runner is the same OS user): see the threat model in
15140
+ * `docs/design/2026-10-08-secrets-keychain.md`.
15141
+ *
15142
+ * `callerAddonId` is deliberately NOT in any input schema: the tRPC router
15143
+ * parses the input, so a session can never supply it, and the internal mount
15144
+ * floors every method to admin anyway (D240).
15145
+ *
15146
+ * Internal: addons reach it through `ctx.secrets`, never directly.
15147
+ */
15148
+ /** Why a value cannot be served right now. Never folded into "missing". */
15149
+ var KeychainUnavailableReasonSchema = _enum([
15150
+ "key-missing",
15151
+ "wrong-key",
15152
+ "key-file-unreadable",
15153
+ "store-unavailable",
15154
+ "not-initialized",
15155
+ "decrypt-failed"
15156
+ ]);
15157
+ var KeychainStateSchema = discriminatedUnion("state", [object({ state: literal("ready") }), object({
15158
+ state: literal("locked"),
15159
+ reason: KeychainUnavailableReasonSchema
15160
+ })]);
15161
+ var KeychainResolveEntrySchema = discriminatedUnion("kind", [
15162
+ object({
15163
+ kind: literal("value"),
15164
+ value: string(),
15165
+ version: number().int()
15166
+ }),
15167
+ object({ kind: literal("missing") }),
15168
+ object({
15169
+ kind: literal("unavailable"),
15170
+ reason: KeychainUnavailableReasonSchema
15171
+ }),
15172
+ object({ kind: literal("forbidden") })
15173
+ ]);
15174
+ var KeychainResolveResultSchema = record(string(), KeychainResolveEntrySchema);
15175
+ /** Metadata of one stored value — never the value. */
15176
+ var KeychainSecretMetaSchema = object({
15177
+ ref: string(),
15178
+ owner: string(),
15179
+ /** Formatted scope (`global`, `node/<id>`, `device/<id>`, …). */
15180
+ scope: string(),
15181
+ fieldPath: string(),
15182
+ version: number().int(),
15183
+ createdAt: number(),
15184
+ updatedAt: number(),
15185
+ /** `addon:<id>` | `user:<id>` | `system`. */
15186
+ updatedBy: string(),
15187
+ /** Coarse — written at most once an hour per ref. `null` = never read. */
15188
+ lastReadAt: number().nullable()
15189
+ });
15190
+ var RefListSchema = array(string().min(1)).max(512);
15191
+ method(object({
15192
+ ref: string().min(1),
15193
+ value: string().min(1)
15194
+ }), object({
15195
+ ref: string(),
15196
+ version: number().int()
15197
+ }), {
15198
+ kind: "mutation",
15199
+ auth: "admin"
15200
+ }), method(object({ refs: RefListSchema }), KeychainResolveResultSchema, { auth: "admin" }), method(object({ refs: RefListSchema }), object({ deleted: number().int() }), {
15201
+ kind: "mutation",
15202
+ auth: "admin"
15203
+ }), method(object({}), array(KeychainSecretMetaSchema).readonly(), { auth: "admin" }), method(object({}), KeychainStateSchema, { auth: "admin" });
15204
+ var KeychainKeySourceSchema = object({
15205
+ kind: _enum([
15206
+ "config-file",
15207
+ "previous-config-file",
15208
+ "platform",
15209
+ "default-file"
15210
+ ]),
15211
+ /** File sources only — a path is not a secret. */
15212
+ path: string().optional(),
15213
+ /**
15214
+ * True when a whole-volume backup of the data directory carries this key
15215
+ * next to the database it protects (the default file). The page warns.
15216
+ */
15217
+ sharesBackupWithDatabase: boolean()
15218
+ });
15219
+ var KeychainStatusSchema = object({
15220
+ keychain: KeychainStateSchema,
15221
+ /** The source of the master key in use; `null` while locked. */
15222
+ keySource: KeychainKeySourceSchema.nullable(),
15223
+ /** The source configured to be primary — differs from `keySource` while a rotation is pending. */
15224
+ configuredSource: KeychainKeySourceSchema,
15225
+ /** Short fingerprint of the master key in use (`HMAC(KEK, label)`, 16 hex). */
15226
+ fingerprint: string().nullable(),
15227
+ activeKeyId: string().nullable(),
15228
+ /**
15229
+ * The keychain unlocked with a NON-primary source: the configured primary
15230
+ * key is not the one that wraps the data key yet. `rotateMasterKey` moves it.
15231
+ */
15232
+ rotationPending: boolean(),
15233
+ /** Wrapped copies of the data key under a previous master key, kept until purged. */
15234
+ retiredWraps: number().int(),
15235
+ recoveryKeyDownloadedAt: number().nullable(),
15236
+ secretCount: number().int()
15237
+ });
15238
+ /**
15239
+ * Whether a stored value is still pointed at by its owner's settings.
15240
+ * `unknown` is a first-class answer: a scope whose blob could not be read is
15241
+ * never reported as an orphan (and never deleted as one).
15242
+ */
15243
+ var KeychainSecretUsageSchema = _enum([
15244
+ "in-use",
15245
+ "orphan",
15246
+ "unknown"
15247
+ ]);
15248
+ var KeychainAdminSecretSchema = KeychainSecretMetaSchema.extend({ usage: KeychainSecretUsageSchema });
15249
+ var KeychainAuditActionSchema = _enum([
15250
+ "put",
15251
+ "delete",
15252
+ "reveal",
15253
+ "rotate-master-key",
15254
+ "purge-retired-keys",
15255
+ "download-recovery-key",
15256
+ "delete-orphans",
15257
+ "reset",
15258
+ "initialize"
15259
+ ]);
15260
+ var KeychainAuditEntrySchema = object({
15261
+ id: string(),
15262
+ at: number(),
15263
+ action: KeychainAuditActionSchema,
15264
+ /** `addon:<id>` | `user:<id>` | `system`. */
15265
+ actor: string(),
15266
+ ref: string().nullable(),
15267
+ detail: string().nullable()
15268
+ });
15269
+ 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({
15270
+ value: string(),
15271
+ version: number().int()
15272
+ }), {
15273
+ kind: "mutation",
15274
+ auth: "admin",
15275
+ caller: "required"
15276
+ }), method(object({ refs: array(string().min(1)).max(1e3) }), object({
15277
+ deleted: array(string()).readonly(),
15278
+ kept: array(object({
15279
+ ref: string(),
15280
+ usage: KeychainSecretUsageSchema
15281
+ })).readonly()
15282
+ }), {
15283
+ kind: "mutation",
15284
+ auth: "admin",
15285
+ caller: "required"
15286
+ }), method(object({}), object({
15287
+ fingerprint: string(),
15288
+ keySource: KeychainKeySourceSchema
15289
+ }), {
15290
+ kind: "mutation",
15291
+ auth: "admin",
15292
+ caller: "required"
15293
+ }), method(object({}), object({ purged: number().int() }), {
15294
+ kind: "mutation",
15295
+ auth: "admin",
15296
+ caller: "required"
15297
+ }), method(object({}), object({
15298
+ key: string(),
15299
+ fingerprint: string(),
15300
+ keySource: KeychainKeySourceSchema
15301
+ }), {
15302
+ kind: "mutation",
15303
+ auth: "admin",
15304
+ caller: "required"
15305
+ }), method(object({ confirm: literal("RESET KEYCHAIN") }), object({
15306
+ archivedCollection: string().nullable(),
15307
+ archived: number().int()
15308
+ }), {
15309
+ kind: "mutation",
15310
+ auth: "admin",
15311
+ caller: "required"
15312
+ });
14393
15313
  method(_void(), object({
14394
15314
  id: string(),
14395
15315
  name: string(),
@@ -15728,7 +16648,11 @@ var DeviceRegisterPayloadSchema = object({
15728
16648
  var DeviceRemovePayloadSchema = object({ deviceId: number() });
15729
16649
  var DevicePersistConfigPayloadSchema = object({
15730
16650
  deviceId: number(),
15731
- data: record(string(), unknown())
16651
+ data: record(string(), unknown()),
16652
+ /** The paths the device's schema declares secret (D783), when the caller
16653
+ * knows them — those values are kept in the keychain, not the blob (D787).
16654
+ * Absent: the paths the device last reported at `registerDevice` apply. */
16655
+ secretConfigPaths: array(string()).optional()
15732
16656
  });
15733
16657
  /** What a migration actually did, per switch. `unreachable` is a first-class
15734
16658
  * answer: a camera that could not be asked is not a camera that was silenced. */
@@ -22764,8 +23688,23 @@ var RetrainMacroClassSchema = _enum([
22764
23688
  ]);
22765
23689
  /** A subject to learn, or a phantom to unlearn (taught by OMISSION). */
22766
23690
  var RetrainAnnotationKindSchema = _enum(["subject", "model_error"]);
22767
- /** Did a human draw this box, or did the assist propose it? */
22768
- var RetrainAnnotationSourceSchema = _enum(["operator", "assist"]);
23691
+ /**
23692
+ * Where a box came from. A machine-sourced box is a DRAFT on the page until
23693
+ * the operator confirms it; once saved it keeps its source as provenance.
23694
+ *
23695
+ * - `operator` — drawn by hand.
23696
+ * - `assist` — proposed by a detector run on the copy (the camera's own
23697
+ * model, or a larger teacher model).
23698
+ * - `pipeline` — the box the live pipeline actually drew on that frame, read
23699
+ * back from the track store (never a re-run).
23700
+ * - `llm` — proposed by a vision-capable LLM profile.
23701
+ */
23702
+ var RetrainAnnotationSourceSchema = _enum([
23703
+ "operator",
23704
+ "assist",
23705
+ "pipeline",
23706
+ "llm"
23707
+ ]);
22769
23708
  /** Normalised `[0,1]` rectangle against the FULL frame — the canonical form. */
22770
23709
  var RetrainBboxSchema = object({
22771
23710
  x: number(),
@@ -22783,7 +23722,8 @@ var RetrainBboxSchema = object({
22783
23722
  */
22784
23723
  var RetrainAnnotationSchema = object({
22785
23724
  id: string(),
22786
- trackId: string(),
23725
+ /** The frame's track. Absent on a recording still, which has none. */
23726
+ trackId: string().optional(),
22787
23727
  deviceId: number(),
22788
23728
  /** The COPY in retrain storage — never the source track's media key. */
22789
23729
  mediaKey: string(),
@@ -22832,13 +23772,47 @@ var RetrainFrameCandidateSchema = object({
22832
23772
  * fail, whatever became of the original. */
22833
23773
  copied: boolean()
22834
23774
  });
23775
+ /**
23776
+ * One box the live pipeline drew on a copied frame — what a correction starts
23777
+ * from. Derived when the frame is listed, from the track store: the subject
23778
+ * box recorded on the source media row when there is one, else the track
23779
+ * position nearest the frame's capture time. Never stored as an annotation
23780
+ * until the operator confirms it.
23781
+ */
23782
+ var RetrainPipelineBoxSchema = object({
23783
+ /** Normalised `[0,1]` against the full frame. */
23784
+ bbox: RetrainBboxSchema,
23785
+ macroClass: RetrainMacroClassSchema,
23786
+ label: string().optional(),
23787
+ subLabel: string().optional(),
23788
+ /** The detection score of the position used, when it was recorded. */
23789
+ score: number().optional(),
23790
+ /** The root model that produced the track, when it was recorded. */
23791
+ modelId: string().optional(),
23792
+ trackId: string(),
23793
+ /** `subject-box`: recorded on this very frame. `position`: the track's
23794
+ * position nearest the capture time, `deltaMs` away. */
23795
+ basis: _enum(["subject-box", "position"]),
23796
+ deltaMs: number()
23797
+ });
23798
+ /**
23799
+ * Where a retrain frame came from: a TRACK's stored media (copy-on-select),
23800
+ * or the RECORDING at an instant — the frame a model saw nothing in has no
23801
+ * track at all.
23802
+ */
23803
+ var RetrainFrameOriginSchema = _enum(["track", "recording"]);
22835
23804
  /** A frame the dataset OWNS: bytes copied at selection time. */
22836
23805
  var RetrainFrameSchema = object({
22837
23806
  frameId: string(),
22838
23807
  deviceId: number(),
22839
- trackId: string(),
22840
- /** Provenance only. It may already point at nothing — that is expected. */
22841
- sourceMediaId: number().int(),
23808
+ origin: RetrainFrameOriginSchema,
23809
+ /** The track it was copied from. Absent on a recording still. */
23810
+ trackId: string().optional(),
23811
+ /** Provenance only. It may already point at nothing — that is expected.
23812
+ * Absent on a recording still. */
23813
+ sourceMediaId: number().int().optional(),
23814
+ /** A recording still: the playhead instant it was taken at. */
23815
+ epochMs: number().optional(),
22842
23816
  sourceKind: MediaFileKindEnum,
22843
23817
  sizeBytes: number().int(),
22844
23818
  width: number().int(),
@@ -22849,7 +23823,12 @@ var RetrainFrameSchema = object({
22849
23823
  /** The operator's "every subject in this frame is boxed". Detector
22850
23824
  * evaluation keeps only complete frames: an unboxed subject would count as
22851
23825
  * a false positive. */
22852
- complete: boolean()
23826
+ complete: boolean(),
23827
+ /** The boxes the pipeline drew on this frame. Present on list answers;
23828
+ * empty when nothing the track store holds can be placed on it. */
23829
+ pipelineBoxes: array(RetrainPipelineBoxSchema).readonly().optional(),
23830
+ /** The named collections this frame belongs to. Present on list answers. */
23831
+ collectionIds: array(string()).readonly().optional()
22853
23832
  });
22854
23833
  /** Why a copy-on-select could not be honoured — named, never a silent skip. */
22855
23834
  var RetrainCopyRefusalSchema = _enum([
@@ -22880,6 +23859,8 @@ var RetrainFrameListSchema = object({
22880
23859
  var RetrainExportFilterSchema = object({
22881
23860
  deviceIds: array(number()).optional(),
22882
23861
  frameIds: array(string()).max(2e4).optional(),
23862
+ /** Only frames in at least one of these named collections. */
23863
+ collectionIds: array(string()).max(200).optional(),
22883
23864
  batchId: string().optional(),
22884
23865
  /** Only frames the operator marked complete (all subjects boxed). */
22885
23866
  completeOnly: boolean().optional()
@@ -22944,6 +23925,109 @@ var RetrainAssistResultSchema = discriminatedUnion("kind", [object({
22944
23925
  reason: string(),
22945
23926
  detail: string().optional()
22946
23927
  })]);
23928
+ /** A named set over the retrain corpus — membership only, it owns no pixels. */
23929
+ var RetrainCollectionSchema = object({
23930
+ id: string(),
23931
+ name: string(),
23932
+ createdAt: number(),
23933
+ frameCount: number().int()
23934
+ });
23935
+ var RetrainCollectionCreateResultSchema = discriminatedUnion("kind", [object({
23936
+ kind: literal("created"),
23937
+ collection: RetrainCollectionSchema
23938
+ }), object({
23939
+ kind: literal("refused"),
23940
+ reason: _enum(["empty-name", "duplicate-name"])
23941
+ })]);
23942
+ var RetrainCollectionRenameResultSchema = discriminatedUnion("kind", [object({
23943
+ kind: literal("renamed"),
23944
+ collection: RetrainCollectionSchema
23945
+ }), object({
23946
+ kind: literal("refused"),
23947
+ reason: _enum([
23948
+ "empty-name",
23949
+ "duplicate-name",
23950
+ "unknown-collection"
23951
+ ])
23952
+ })]);
23953
+ /**
23954
+ * The outcome of adding the frame at a recording instant. Every refusal is
23955
+ * named: `still-unavailable` (not recording, a gap, or an undecodable frame —
23956
+ * `detail` says which), `still-busy` (the recorder is at its decode bound; try
23957
+ * again), `unreadable-image`, `write-failed`, `unknown-collection`.
23958
+ */
23959
+ var AddRetrainFrameFromRecordingResultSchema = discriminatedUnion("kind", [object({
23960
+ kind: literal("added"),
23961
+ collectionId: string(),
23962
+ frame: RetrainFrameSchema,
23963
+ /** The moment was already in the dataset; nothing was decoded. */
23964
+ reused: boolean()
23965
+ }), object({
23966
+ kind: literal("refused"),
23967
+ reason: _enum([
23968
+ "unknown-collection",
23969
+ "still-unavailable",
23970
+ "still-busy",
23971
+ "unreadable-image",
23972
+ "write-failed"
23973
+ ]),
23974
+ detail: string().optional()
23975
+ })]);
23976
+ /** A vision LLM profile the AI assist may use, and where it sends the frame. */
23977
+ var RetrainAssistProfileSchema = object({
23978
+ id: string(),
23979
+ name: string(),
23980
+ model: string(),
23981
+ kind: string(),
23982
+ /** `true` when the frame would leave the house (a cloud vendor, or an
23983
+ * endpoint that is not on the local network). The page confirms each such
23984
+ * run, and the provider refuses one without `allowCloud`. */
23985
+ leavesHouse: boolean()
23986
+ });
23987
+ /** A box the AI assist proposed: a draft, plus the model's own reason. */
23988
+ var RetrainLlmProposalSchema = RetrainAnnotationDraftSchema.extend({ reason: string() });
23989
+ /** What the AI assist said about a box that was already on the canvas. */
23990
+ var RetrainLlmReviewSchema = object({
23991
+ /** The `ref` the page sent the box under. */
23992
+ ref: string(),
23993
+ verdict: _enum([
23994
+ "confirmed",
23995
+ "wrong-class",
23996
+ "not-an-object",
23997
+ "uncertain"
23998
+ ]),
23999
+ suggestedClass: RetrainMacroClassSchema.optional(),
24000
+ reason: string()
24001
+ });
24002
+ /**
24003
+ * The AI assist's answer. `proposed` carries drafts (`source: 'llm'`, the
24004
+ * model and its confidence) and reviews; items the model got wrong (a box off
24005
+ * the frame, an unasked class, an unknown ref) are dropped and counted in
24006
+ * `rejected`. A whole answer that is not the schema is `malformed-answer`.
24007
+ */
24008
+ var RetrainLlmAssistResultSchema = discriminatedUnion("kind", [object({
24009
+ kind: literal("proposed"),
24010
+ profileId: string(),
24011
+ model: string(),
24012
+ /** The frame was sent outside the house for this answer. */
24013
+ leftHouse: boolean(),
24014
+ proposals: array(RetrainLlmProposalSchema).readonly(),
24015
+ reviews: array(RetrainLlmReviewSchema).readonly(),
24016
+ rejected: number().int()
24017
+ }), object({
24018
+ kind: literal("refused"),
24019
+ reason: _enum([
24020
+ "unknown-frame",
24021
+ "unreadable-frame",
24022
+ "unknown-profile",
24023
+ "profile-disabled",
24024
+ "no-vision",
24025
+ "cloud-not-confirmed",
24026
+ "llm-error",
24027
+ "malformed-answer"
24028
+ ]),
24029
+ detail: string().optional()
24030
+ })]);
22947
24031
  /** The outcome of a lifecycle move owned by the retrain page. */
22948
24032
  var RetrainTransitionResultSchema = object({
22949
24033
  trackId: string(),
@@ -23661,7 +24745,7 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
23661
24745
  auth: "admin"
23662
24746
  }), method(object({
23663
24747
  deviceId: number(),
23664
- trackId: string(),
24748
+ trackId: string().optional(),
23665
24749
  frameId: string()
23666
24750
  }), object({
23667
24751
  removed: boolean(),
@@ -23678,7 +24762,8 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
23678
24762
  auth: "admin"
23679
24763
  }), method(object({
23680
24764
  deviceId: number(),
23681
- trackId: string(),
24765
+ /** The frame's track, when it has one — checked against the frame. */
24766
+ trackId: string().optional(),
23682
24767
  frameId: string(),
23683
24768
  subject: RetrainAssistSubjectSchema,
23684
24769
  /** Which node runs it. Absent ⇒ wherever an unowned call lands. */
@@ -23686,12 +24771,16 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
23686
24771
  }), RetrainAssistResultSchema, {
23687
24772
  kind: "mutation",
23688
24773
  auth: "admin"
23689
- }), method(object({ trackId: string() }), array(RetrainAnnotationSchema).readonly(), {
24774
+ }), method(object({
24775
+ trackId: string().optional(),
24776
+ frameIds: array(string()).max(2e3).optional()
24777
+ }), array(RetrainAnnotationSchema).readonly(), {
23690
24778
  kind: "query",
23691
24779
  auth: "admin"
23692
24780
  }), method(object({
23693
24781
  deviceId: number(),
23694
- trackId: string(),
24782
+ /** The frame's track, when it has one — checked against the frame. */
24783
+ trackId: string().optional(),
23695
24784
  frameId: string(),
23696
24785
  annotations: array(RetrainAnnotationDraftSchema)
23697
24786
  }), array(RetrainAnnotationSchema).readonly(), {
@@ -23714,7 +24803,7 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
23714
24803
  auth: "admin"
23715
24804
  }), method(object({
23716
24805
  deviceId: number(),
23717
- trackId: string(),
24806
+ trackId: string().optional(),
23718
24807
  frameId: string(),
23719
24808
  complete: boolean()
23720
24809
  }), RetrainFrameSchema, {
@@ -23728,6 +24817,74 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
23728
24817
  kind: "mutation",
23729
24818
  auth: "admin",
23730
24819
  timeoutMs: 60 * 6e4
24820
+ }), method(object({}), array(RetrainAssistProfileSchema).readonly(), {
24821
+ kind: "query",
24822
+ auth: "admin"
24823
+ }), method(object({
24824
+ deviceId: number(),
24825
+ trackId: string().optional(),
24826
+ frameId: string(),
24827
+ profileId: string(),
24828
+ classes: array(RetrainMacroClassSchema).min(1),
24829
+ boxes: array(object({
24830
+ ref: string(),
24831
+ bbox: RetrainBboxSchema,
24832
+ macroClass: RetrainMacroClassSchema,
24833
+ label: string().optional()
24834
+ })).max(50),
24835
+ allowCloud: boolean()
24836
+ }), RetrainLlmAssistResultSchema, {
24837
+ kind: "mutation",
24838
+ auth: "admin",
24839
+ timeoutMs: 18e4
24840
+ }), method(object({ name: string().max(120) }), RetrainCollectionCreateResultSchema, {
24841
+ kind: "mutation",
24842
+ auth: "admin"
24843
+ }), method(object({}), array(RetrainCollectionSchema).readonly(), {
24844
+ kind: "query",
24845
+ auth: "admin"
24846
+ }), method(object({
24847
+ id: string(),
24848
+ name: string().max(120)
24849
+ }), RetrainCollectionRenameResultSchema, {
24850
+ kind: "mutation",
24851
+ auth: "admin"
24852
+ }), method(object({ id: string() }), object({
24853
+ deleted: boolean(),
24854
+ removedFrames: number().int()
24855
+ }), {
24856
+ kind: "mutation",
24857
+ auth: "admin"
24858
+ }), method(object({
24859
+ collectionId: string(),
24860
+ deviceId: number(),
24861
+ epochMs: number()
24862
+ }), AddRetrainFrameFromRecordingResultSchema, {
24863
+ kind: "mutation",
24864
+ auth: "admin",
24865
+ timeoutMs: 6e4
24866
+ }), method(object({
24867
+ collectionId: string(),
24868
+ frameIds: array(string()).min(1).max(500)
24869
+ }), object({
24870
+ added: number().int(),
24871
+ alreadyMember: number().int(),
24872
+ unknownFrameIds: array(string()).readonly()
24873
+ }), {
24874
+ kind: "mutation",
24875
+ auth: "admin"
24876
+ }), method(object({
24877
+ collectionId: string(),
24878
+ frameId: string()
24879
+ }), object({
24880
+ removed: boolean(),
24881
+ deletedFrame: boolean()
24882
+ }), {
24883
+ kind: "mutation",
24884
+ auth: "admin"
24885
+ }), method(object({ collectionId: string() }), array(RetrainFrameSchema).readonly(), {
24886
+ kind: "query",
24887
+ auth: "admin"
23731
24888
  }), method(object({
23732
24889
  /** Which of the three event tables owns the row. */
23733
24890
  ownerType: EventOwnerTypeSchema,
@@ -24351,13 +25508,31 @@ var RecommendationReasonSchema = discriminatedUnion("kind", [
24351
25508
  object({
24352
25509
  kind: literal("no-family-build"),
24353
25510
  format: ModelFormatSchema$1
25511
+ }),
25512
+ object({
25513
+ kind: literal("kept-custom-pin"),
25514
+ modelId: string(),
25515
+ deviceKey: string()
24354
25516
  })
24355
25517
  ]);
25518
+ /** Why a device is left exactly as it is, whatever the plan would pick (D786). */
25519
+ var KeptReasonSchema = _enum(["custom-pin"]);
25520
+ /**
25521
+ * Where a choice's latency came from (D791): this node's own benchmark
25522
+ * result, or the hardware-class table. Measured on the node beats the table.
25523
+ */
25524
+ var LatencySourceSchema = discriminatedUnion("kind", [object({ kind: literal("table") }), object({
25525
+ kind: literal("node-benchmark"),
25526
+ resultId: string(),
25527
+ measuredAtMs: number()
25528
+ })]);
24356
25529
  var DeviceModelChoiceSchema = object({
24357
25530
  modelId: string(),
24358
25531
  p50Ms: number(),
24359
25532
  fps: number(),
24360
25533
  measured: boolean(),
25534
+ /** Absent on a plan from before D791 — read as the table. */
25535
+ source: LatencySourceSchema.optional(),
24361
25536
  /** Parallel sessions at the camera rate with the headroom kept free: ⌊fps × (1 − headroom) / camera fps⌋. */
24362
25537
  capacitySessions: number(),
24363
25538
  personRecall: number()
@@ -24368,6 +25543,8 @@ var DeviceRecommendationSchema = object({
24368
25543
  enabled: boolean(),
24369
25544
  available: boolean(),
24370
25545
  chosen: DeviceModelChoiceSchema.nullable(),
25546
+ /** Present when the device is kept as is: Apply writes nothing on it. */
25547
+ kept: KeptReasonSchema.optional(),
24371
25548
  reasons: array(RecommendationReasonSchema).readonly()
24372
25549
  });
24373
25550
  var NodeRecommendationSchema = object({
@@ -24421,6 +25598,17 @@ var AutoTuneWarningSchema = discriminatedUnion("kind", [
24421
25598
  kind: literal("coral-enabled"),
24422
25599
  nodeId: string(),
24423
25600
  deviceKey: string()
25601
+ }),
25602
+ object({
25603
+ kind: literal("custom-pin-kept"),
25604
+ nodeId: string(),
25605
+ deviceKey: string().nullable(),
25606
+ deviceId: number().nullable(),
25607
+ modelId: string()
25608
+ }),
25609
+ object({
25610
+ kind: literal("custom-registry-unreadable"),
25611
+ error: string()
24424
25612
  })
24425
25613
  ]);
24426
25614
  var AutoTuneOptionsSchema = object({
@@ -24599,13 +25787,14 @@ var SuggestSharesResultSchema = object({
24599
25787
  nodes: array(SuggestedNodeShareSchema).readonly()
24600
25788
  });
24601
25789
  /**
24602
- * Where the node and device shares come from (D750, D755).
24603
- * - `hardware` (default) — computed by the system from each node's static
24604
- * capacity (its accelerators at their Auto tune models, from the measured
24605
- * latency table), recomputed whenever a node or device joins, leaves, is
24606
- * switched on or off, or changes model. No load input.
24607
- * - `benchmark` — the same, from each node's measured capacity (node
24608
- * benchmark results); a node without results falls back to `hardware`.
25790
+ * Where the node and device shares come from (D750, D755, D791).
25791
+ * - `benchmark` (default since D791) — each node's capacity as its own node
25792
+ * benchmark measured it; a node without fresh results is sized from
25793
+ * `hardware` and says so. Measured on the node beats the table.
25794
+ * - `hardware` — computed from each node's static capacity only (its
25795
+ * accelerators at their Auto tune models, from the latency table).
25796
+ * Both are recomputed whenever a node or device joins, leaves, is switched
25797
+ * on or off, changes model, or a benchmark result is written. No load input.
24609
25798
  * - `manual` — the operator's stored sliders.
24610
25799
  * Either way a node or device that cannot take sessions gives its share to
24611
25800
  * the others in proportion; the stored values are never rewritten for that.
@@ -24654,6 +25843,362 @@ var EffectiveSharesSchema = object({
24654
25843
  nodeWeights: record(string(), number()),
24655
25844
  deviceWeights: record(string(), record(string(), number()))
24656
25845
  });
25846
+ /**
25847
+ * Wire shapes of the node benchmark (D791): the operator's plan, the
25848
+ * preflight the confirmation shows, the run the orchestrator owns, what the
25849
+ * measuring runner reports, and the result rows Auto tune and the automatic
25850
+ * shares read.
25851
+ *
25852
+ * ONE node at a time, owned by the pipeline orchestrator. While a run is
25853
+ * active the cluster is in BENCHMARK MODE for that node: it is not a
25854
+ * detection candidate, camera pins naming it are ignored so its sessions move
25855
+ * elsewhere, and both come back when the mode ends — after a crash or a hub
25856
+ * restart too (a persisted manifest, reconciled against the registry).
25857
+ *
25858
+ * Two measurements, both on the node, driven by its own runner (frames never
25859
+ * cross a process at frame rate, D9):
25860
+ * - `device` — one accelerator × one candidate detector, root only, open
25861
+ * loop: how many streams at the camera rate it carries inside the frame
25862
+ * interval;
25863
+ * - `pipeline` — the chosen detector plus the operator's detail steps
25864
+ * (faces, plates, classifiers, CLIP…), on varied frames from the bench
25865
+ * clip: how many parallel sessions the node carries before latency, drops,
25866
+ * CPU, RAM or the event loop give out.
25867
+ */
25868
+ /** Defaults and bounds, one place. */
25869
+ var NODE_BENCHMARK_DEFAULTS = {
25870
+ fpsPerStream: 10,
25871
+ budgetMinutes: 45,
25872
+ minBudgetMinutes: 10,
25873
+ maxBudgetMinutes: 120,
25874
+ /** A result older than this no longer beats the table. */
25875
+ staleAfterDays: 30,
25876
+ /** Warm-in per ramp step (not accounted). */
25877
+ settleSec: 5,
25878
+ /** Accounted window per ramp step. */
25879
+ measureSec: 20,
25880
+ /** Longest the drain may take before the run is refused. */
25881
+ drainTimeoutSec: 120,
25882
+ /** Candidate models per device in one run. */
25883
+ maxModelsPerDevice: 6
25884
+ };
25885
+ /** The two measurements a run can make. */
25886
+ var NodeBenchmarkPhaseSchema = _enum(["device", "pipeline"]);
25887
+ var NodeBenchmarkDevicePlanSchema = object({
25888
+ /** `<backend>:<device>` — `openvino:npu`, `coreml:all`, `cpu`. */
25889
+ deviceKey: string().min(1),
25890
+ /**
25891
+ * Root detector candidates for the `device` measurement, in the order
25892
+ * measured. The FIRST is the one the `pipeline` measurement runs.
25893
+ */
25894
+ modelIds: array(string().min(1)).min(1).max(NODE_BENCHMARK_DEFAULTS.maxModelsPerDevice)
25895
+ });
25896
+ /** What the operator confirmed. */
25897
+ var NodeBenchmarkPlanSchema = object({
25898
+ nodeId: string().min(1),
25899
+ devices: array(NodeBenchmarkDevicePlanSchema).min(1),
25900
+ /** Which measurements run. At least one. */
25901
+ phases: array(NodeBenchmarkPhaseSchema).min(1).default(["device", "pipeline"]),
25902
+ /**
25903
+ * Detail steps (catalog step ids under the root: faces, plates,
25904
+ * classifiers, CLIP…) the `pipeline` measurement enables. The root
25905
+ * detector always runs.
25906
+ */
25907
+ steps: array(string().min(1)).default([]),
25908
+ /** Offered rate of one stream / session. */
25909
+ fpsPerStream: number().int().min(1).max(30).default(NODE_BENCHMARK_DEFAULTS.fpsPerStream),
25910
+ /** Hard deadline: the mode ends and the cluster is restored when it passes. */
25911
+ budgetMinutes: number().int().min(NODE_BENCHMARK_DEFAULTS.minBudgetMinutes).max(NODE_BENCHMARK_DEFAULTS.maxBudgetMinutes).default(NODE_BENCHMARK_DEFAULTS.budgetMinutes),
25912
+ /** Keep the models the run downloaded (default: delete what was not installed before). */
25913
+ keepDownloadedModels: boolean().default(false),
25914
+ /** Start although the other nodes' capacity does not cover the sessions running now. */
25915
+ acceptInsufficientHeadroom: boolean().default(false)
25916
+ });
25917
+ var NodeBenchmarkRefusalSchema = object({
25918
+ kind: _enum([
25919
+ "benchmark-active",
25920
+ "node-offline",
25921
+ "unknown-device",
25922
+ "no-phase",
25923
+ "insufficient-headroom"
25924
+ ]),
25925
+ detail: string(),
25926
+ overridable: boolean()
25927
+ });
25928
+ /** A camera whose detection leaves the node for the run. */
25929
+ var NodeBenchmarkMovingCameraSchema = object({
25930
+ deviceId: number(),
25931
+ /** Placed on the node now (a standing attach or a running session). */
25932
+ placedOnNode: boolean(),
25933
+ /** A node pin naming this node, ignored for the run. */
25934
+ pinnedToNode: boolean()
25935
+ });
25936
+ /** A camera that cannot leave: no other node can obtain its frames. */
25937
+ var NodeBenchmarkStayingCameraSchema = object({
25938
+ deviceId: number(),
25939
+ reason: literal("only-frame-source")
25940
+ });
25941
+ var NodeBenchmarkPreflightSchema = object({
25942
+ nodeId: string(),
25943
+ online: boolean(),
25944
+ moving: array(NodeBenchmarkMovingCameraSchema).readonly(),
25945
+ /** Keep running on the node during the run; the result is flagged contaminated. */
25946
+ staying: array(NodeBenchmarkStayingCameraSchema).readonly(),
25947
+ estimatedDurationMs: number(),
25948
+ /** The run ends and the cluster is restored at the latest after this long. */
25949
+ budgetMs: number(),
25950
+ phases: array(NodeBenchmarkPhaseSchema).readonly(),
25951
+ steps: array(string()).readonly(),
25952
+ devices: array(NodeBenchmarkDevicePlanSchema).readonly(),
25953
+ /** Parallel sessions the cluster runs now, and what the other nodes can carry. */
25954
+ headroom: object({
25955
+ sessionsNow: number(),
25956
+ otherNodesCapacitySessions: number().nullable()
25957
+ }),
25958
+ refusals: array(NodeBenchmarkRefusalSchema).readonly(),
25959
+ canStart: boolean()
25960
+ });
25961
+ /** Where the measuring runner is. */
25962
+ var NodeBenchProgressSchema = object({
25963
+ phase: _enum([
25964
+ "preparing",
25965
+ "device",
25966
+ "pipeline",
25967
+ "cleanup"
25968
+ ]),
25969
+ deviceKey: string().nullable(),
25970
+ modelId: string().nullable(),
25971
+ /** Streams (device) or sessions (pipeline) of the step running now. */
25972
+ load: number().nullable(),
25973
+ cellsDone: number(),
25974
+ cellsTotal: number(),
25975
+ message: string()
25976
+ });
25977
+ /** What limited a ramp. `none` = the ramp ran out of steps still passing. */
25978
+ var NodeBenchLimitSchema = _enum([
25979
+ "p95",
25980
+ "drops",
25981
+ "errors",
25982
+ "stall",
25983
+ "cpu",
25984
+ "ram",
25985
+ "none"
25986
+ ]);
25987
+ var NodeBenchRampStepSchema = object({
25988
+ load: number(),
25989
+ pass: boolean(),
25990
+ p95Ms: number(),
25991
+ dropRatio: number(),
25992
+ /** Completed frames per second over the accounted window. */
25993
+ fps: number(),
25994
+ cpuPct: number().nullable(),
25995
+ ramFreePct: number().nullable(),
25996
+ failReasons: array(string()).readonly()
25997
+ });
25998
+ var NodeBenchCellSchema = discriminatedUnion("phase", [object({
25999
+ phase: literal("device"),
26000
+ deviceKey: string(),
26001
+ modelId: string(),
26002
+ /** Single-stream latency (the K = 1 step). */
26003
+ p50Ms: number(),
26004
+ p95Ms: number(),
26005
+ p99Ms: number(),
26006
+ /** Frames per second sustained at the last passing step. */
26007
+ fps: number(),
26008
+ /** Streams at the camera rate the device carried inside the frame interval; 0 = not even one. */
26009
+ kMax: number(),
26010
+ limitedBy: NodeBenchLimitSchema,
26011
+ /** First call (model load + warm-up). */
26012
+ warmupMs: number(),
26013
+ ramp: array(NodeBenchRampStepSchema).readonly()
26014
+ }), object({
26015
+ phase: literal("pipeline"),
26016
+ deviceKey: string(),
26017
+ modelId: string(),
26018
+ steps: array(string()).readonly(),
26019
+ /** Parallel sessions at the camera rate the node carried; 0 = not even one. */
26020
+ maxSessions: number(),
26021
+ limitedBy: NodeBenchLimitSchema,
26022
+ /** Detail steps that produced at least one result on the clip — a step that never fired measured nothing. */
26023
+ stepsFired: array(string()).readonly(),
26024
+ warmupMs: number(),
26025
+ ramp: array(NodeBenchRampStepSchema).readonly()
26026
+ })]);
26027
+ /**
26028
+ * What a result was measured ON. A result whose fingerprint no longer matches
26029
+ * the node no longer beats the table.
26030
+ */
26031
+ var NodeBenchFingerprintSchema = object({
26032
+ pipelineVersion: string().nullable(),
26033
+ cpuModel: string().nullable(),
26034
+ ramGb: number().nullable(),
26035
+ os: string().nullable(),
26036
+ /** Per device: the pool the cells ran on (runtime + tuning). */
26037
+ pools: record(string(), object({
26038
+ runtime: string(),
26039
+ numWorkers: number(),
26040
+ concurrency: number(),
26041
+ batchMode: string()
26042
+ })).default({})
26043
+ });
26044
+ /** The frames the run used. */
26045
+ var NodeBenchClipSchema = object({
26046
+ /** `camstack-bench-v1` or `reference-images` (the fallback when the clip is not reachable). */
26047
+ id: string(),
26048
+ revision: string().nullable(),
26049
+ frames: number(),
26050
+ width: number(),
26051
+ height: number()
26052
+ });
26053
+ var NodeBenchRunnerInputSchema = object({
26054
+ runId: string().min(1),
26055
+ devices: array(NodeBenchmarkDevicePlanSchema).min(1),
26056
+ phases: array(NodeBenchmarkPhaseSchema).min(1),
26057
+ /** The full detail step tree root for the `pipeline` measurement is built on the node from these ids. */
26058
+ steps: array(string()).default([]),
26059
+ fpsPerStream: number().int().min(1).max(30),
26060
+ /** The runner stops on its own past this instant, whatever the hub does. */
26061
+ deadlineAtMs: number(),
26062
+ settleSec: number().min(0).max(60).default(NODE_BENCHMARK_DEFAULTS.settleSec),
26063
+ measureSec: number().min(2).max(300).default(NODE_BENCHMARK_DEFAULTS.measureSec),
26064
+ keepDownloadedModels: boolean().default(false)
26065
+ });
26066
+ var NodeBenchRunnerStateSchema = _enum([
26067
+ "running",
26068
+ "done",
26069
+ "failed",
26070
+ "aborted"
26071
+ ]);
26072
+ var NodeBenchRunnerStatusSchema = object({
26073
+ runId: string(),
26074
+ nodeId: string(),
26075
+ state: NodeBenchRunnerStateSchema,
26076
+ progress: NodeBenchProgressSchema.nullable(),
26077
+ /** Every finished cell so far — a run stopped half way keeps what it measured. */
26078
+ cells: array(NodeBenchCellSchema).readonly(),
26079
+ fingerprint: NodeBenchFingerprintSchema.nullable(),
26080
+ clip: NodeBenchClipSchema.nullable(),
26081
+ /** Cameras seen running on the node during the run (they share its pools). */
26082
+ activeCameraIds: array(number()).readonly(),
26083
+ /** Models the run downloaded and then deleted (not installed before). */
26084
+ deletedModels: array(string()).readonly(),
26085
+ error: string().nullable(),
26086
+ startedAtMs: number(),
26087
+ finishedAtMs: number().nullable()
26088
+ });
26089
+ var NodeBenchmarkStateSchema = _enum([
26090
+ "draining",
26091
+ "measuring",
26092
+ "restoring",
26093
+ "done",
26094
+ "failed",
26095
+ "aborted"
26096
+ ]);
26097
+ /** Why a run ended. */
26098
+ var NodeBenchmarkEndReasonSchema = _enum([
26099
+ "completed",
26100
+ "operator-abort",
26101
+ "deadline",
26102
+ "node-lost",
26103
+ "runner-lost",
26104
+ "hub-restart",
26105
+ "drain-timeout",
26106
+ "failed"
26107
+ ]);
26108
+ var NodeBenchmarkRunSchema = object({
26109
+ runId: string(),
26110
+ nodeId: string(),
26111
+ state: NodeBenchmarkStateSchema,
26112
+ plan: NodeBenchmarkPlanSchema,
26113
+ startedAtMs: number(),
26114
+ deadlineAtMs: number(),
26115
+ finishedAtMs: number().nullable(),
26116
+ endReason: NodeBenchmarkEndReasonSchema.nullable(),
26117
+ error: string().nullable(),
26118
+ /** Cameras moved off the node for the run. */
26119
+ moved: array(number()).readonly(),
26120
+ /** Cameras that stayed (their only frame source is the node). */
26121
+ staying: array(number()).readonly(),
26122
+ /** Something else ran on the node's pools during the run. */
26123
+ contaminated: boolean(),
26124
+ progress: NodeBenchProgressSchema.nullable(),
26125
+ resultIds: array(string()).readonly()
26126
+ });
26127
+ /** `getNodeBenchmarkStatus`: the active run (or the last one), and whether benchmark mode is on. */
26128
+ var NodeBenchmarkStatusSchema = object({
26129
+ /** The node the cluster is in benchmark mode for; null = none. */
26130
+ modeNodeId: string().nullable(),
26131
+ run: NodeBenchmarkRunSchema.nullable()
26132
+ });
26133
+ /**
26134
+ * One stored measurement — the only authority Auto tune and the automatic
26135
+ * shares read measured capacity from. Written by the orchestrator when a run
26136
+ * ends, never by anyone else.
26137
+ */
26138
+ var NodeBenchmarkResultSchema = object({
26139
+ id: string(),
26140
+ runId: string(),
26141
+ nodeId: string(),
26142
+ cell: NodeBenchCellSchema,
26143
+ fpsPerStream: number(),
26144
+ fingerprint: NodeBenchFingerprintSchema.nullable(),
26145
+ clip: NodeBenchClipSchema.nullable(),
26146
+ /** Other work shared the node's pools (a camera that could not move, or the hub's own duties). */
26147
+ contaminated: boolean(),
26148
+ stayingCameras: array(number()).readonly(),
26149
+ /** The run ended early; the cell itself completed. */
26150
+ partialRun: boolean(),
26151
+ measuredAtMs: number()
26152
+ });
26153
+ var ListNodeBenchmarkResultsInputSchema = object({
26154
+ nodeId: string().optional(),
26155
+ deviceKey: string().optional()
26156
+ });
26157
+ /** A result with its standing today: does it still beat the table? */
26158
+ var NodeBenchmarkResultViewSchema = NodeBenchmarkResultSchema.extend({
26159
+ /** `fresh` beats the table; `stale` falls back to it; `superseded` = a newer row covers the same cell. */
26160
+ standing: _enum([
26161
+ "fresh",
26162
+ "stale",
26163
+ "superseded"
26164
+ ]),
26165
+ staleWhy: _enum([
26166
+ "age",
26167
+ "runtime",
26168
+ "pool-tuning"
26169
+ ]).nullable()
26170
+ });
26171
+ object({
26172
+ runId: string(),
26173
+ nodeId: string(),
26174
+ startedAtMs: number(),
26175
+ deadlineAtMs: number(),
26176
+ plan: NodeBenchmarkPlanSchema,
26177
+ moved: array(number()).readonly(),
26178
+ staying: array(number()).readonly()
26179
+ });
26180
+ /** Candidate detectors per device, for the plan editor. */
26181
+ var NodeBenchmarkCandidatesSchema = object({
26182
+ nodeId: string(),
26183
+ reachable: boolean(),
26184
+ devices: array(object({
26185
+ deviceKey: string(),
26186
+ enabled: boolean(),
26187
+ available: boolean(),
26188
+ /** Ordered: what Auto tune would pick first, then the rest of the family by accuracy. */
26189
+ suggested: array(string()).readonly(),
26190
+ /** Every root detector the device has a build for. */
26191
+ all: array(string()).readonly(),
26192
+ /** The model the device runs now, when pinned. */
26193
+ currentModelId: string().nullable()
26194
+ })).readonly(),
26195
+ /** Detail steps the node's catalog offers under the root (for the `pipeline` measurement). */
26196
+ steps: array(object({
26197
+ id: string(),
26198
+ name: string(),
26199
+ slot: string()
26200
+ })).readonly()
26201
+ });
24657
26202
  object({
24658
26203
  activeCameras: number(),
24659
26204
  throttledCameras: number(),
@@ -25782,7 +27327,16 @@ method(RunnerCameraConfigSchema, object({ success: literal(true) }), { kind: "mu
25782
27327
  }), ParkedTrackFrameSchema.nullable()), method(object({
25783
27328
  deviceId: number(),
25784
27329
  trackId: string()
25785
- }), object({ released: number().int().nonnegative() }), { kind: "mutation" });
27330
+ }), object({ released: number().int().nonnegative() }), { kind: "mutation" }), method(NodeBenchRunnerInputSchema, object({
27331
+ accepted: literal(true),
27332
+ runId: string()
27333
+ }), {
27334
+ kind: "mutation",
27335
+ auth: "admin"
27336
+ }), method(object({ runId: string() }), NodeBenchRunnerStatusSchema.nullable(), { auth: "admin" }), method(object({ runId: string() }), object({ aborted: boolean() }), {
27337
+ kind: "mutation",
27338
+ auth: "admin"
27339
+ });
25786
27340
  var CameraPipelineConfigSchema = object({
25787
27341
  engine: PipelineEngineChoiceSchema.optional(),
25788
27342
  steps: array(PipelineStepInputSchema).readonly(),
@@ -26421,6 +27975,21 @@ method(object({
26421
27975
  }), method(PlacementStatsInputSchema, PlacementStatsSchema, { auth: "admin" }), method(SuggestSharesInputSchema, SuggestSharesResultSchema, { auth: "admin" }), method(_void(), EffectiveSharesSchema, { auth: "admin" }), method(SetShareSourceInputSchema, object({ success: literal(true) }), {
26422
27976
  kind: "mutation",
26423
27977
  auth: "admin"
27978
+ }), method(NodeBenchmarkPlanSchema, NodeBenchmarkPreflightSchema, { auth: "admin" }), method(NodeBenchmarkPlanSchema, discriminatedUnion("kind", [object({
27979
+ kind: literal("started"),
27980
+ runId: string()
27981
+ }), object({
27982
+ kind: literal("refused"),
27983
+ preflight: NodeBenchmarkPreflightSchema
27984
+ })]), {
27985
+ kind: "mutation",
27986
+ auth: "admin"
27987
+ }), method(_void(), NodeBenchmarkStatusSchema, { auth: "admin" }), method(object({ runId: string() }), object({ aborted: boolean() }), {
27988
+ kind: "mutation",
27989
+ auth: "admin"
27990
+ }), method(object({ nodeId: string() }), NodeBenchmarkCandidatesSchema, { auth: "admin" }), method(ListNodeBenchmarkResultsInputSchema, array(NodeBenchmarkResultViewSchema).readonly(), { auth: "admin" }), method(object({ id: string() }), object({ deleted: boolean() }), {
27991
+ kind: "mutation",
27992
+ auth: "admin"
26424
27993
  }), method(object({ deviceId: number() }), CameraPipelineSettingsSchema.nullable()), method(object({
26425
27994
  deviceId: number(),
26426
27995
  addonId: string(),
@@ -33050,6 +34619,9 @@ var CreateIntegrationInputSchema = object({
33050
34619
  enabled: boolean().optional(),
33051
34620
  info: record(string(), unknown()).optional(),
33052
34621
  settings: record(string(), unknown()).optional(),
34622
+ /** Keys of `settings` the form's schema declares secret (by type) — kept in
34623
+ * the keychain, not the table (D787). */
34624
+ secretKeys: array(string()).optional(),
33053
34625
  skipRestart: boolean().optional()
33054
34626
  });
33055
34627
  var UpdateIntegrationInputSchema = object({
@@ -33073,7 +34645,9 @@ method(_void(), array(IntegrationWithStateSchema)), method(object({ id: string()
33073
34645
  auth: "admin"
33074
34646
  }), method(object({ id: string() }), record(string(), unknown()), { auth: "admin" }), method(object({
33075
34647
  id: string(),
33076
- settings: record(string(), unknown())
34648
+ settings: record(string(), unknown()),
34649
+ /** Keys the form's schema declares secret (by type) — keychain-stored (D787). */
34650
+ secretKeys: array(string()).optional()
33077
34651
  }), object({ success: boolean() }), {
33078
34652
  kind: "mutation",
33079
34653
  auth: "admin"
@@ -41812,7 +43386,8 @@ var BaseDevice = class {
41812
43386
  this.role = options.role;
41813
43387
  this.parentDeviceId = ctx.parentDeviceId;
41814
43388
  const seedData = ctx.persistedConfig ?? {};
41815
- this.config = DeviceConfig.fromSchema(schema, (data) => ctx.persistConfig(data), seedData, ({ droppedKeys, issues }) => {
43389
+ const declaredSecretPaths = collectZodSecretPaths(schema);
43390
+ this.config = DeviceConfig.fromSchema(schema, (data) => ctx.persistConfig(data, { secretConfigPaths: declaredSecretPaths }), seedData, ({ droppedKeys, issues }) => {
41816
43391
  ctx.logger.warn("Device config recovery: dropping invalid persisted fields", {
41817
43392
  tags: {
41818
43393
  deviceId: ctx.id,
@@ -45501,6 +47076,90 @@ Object.freeze({
45501
47076
  addonId: null,
45502
47077
  access: "create"
45503
47078
  },
47079
+ "keychain.delete": {
47080
+ capName: "keychain",
47081
+ capScope: "system",
47082
+ addonId: null,
47083
+ access: "delete"
47084
+ },
47085
+ "keychain.getState": {
47086
+ capName: "keychain",
47087
+ capScope: "system",
47088
+ addonId: null,
47089
+ access: "view"
47090
+ },
47091
+ "keychain.listMeta": {
47092
+ capName: "keychain",
47093
+ capScope: "system",
47094
+ addonId: null,
47095
+ access: "view"
47096
+ },
47097
+ "keychain.put": {
47098
+ capName: "keychain",
47099
+ capScope: "system",
47100
+ addonId: null,
47101
+ access: "create"
47102
+ },
47103
+ "keychain.resolve": {
47104
+ capName: "keychain",
47105
+ capScope: "system",
47106
+ addonId: null,
47107
+ access: "view"
47108
+ },
47109
+ "keychainAdmin.deleteOrphans": {
47110
+ capName: "keychain-admin",
47111
+ capScope: "system",
47112
+ addonId: null,
47113
+ access: "delete"
47114
+ },
47115
+ "keychainAdmin.downloadRecoveryKey": {
47116
+ capName: "keychain-admin",
47117
+ capScope: "system",
47118
+ addonId: null,
47119
+ access: "create"
47120
+ },
47121
+ "keychainAdmin.listAudit": {
47122
+ capName: "keychain-admin",
47123
+ capScope: "system",
47124
+ addonId: null,
47125
+ access: "view"
47126
+ },
47127
+ "keychainAdmin.listSecrets": {
47128
+ capName: "keychain-admin",
47129
+ capScope: "system",
47130
+ addonId: null,
47131
+ access: "view"
47132
+ },
47133
+ "keychainAdmin.purgeRetiredKeys": {
47134
+ capName: "keychain-admin",
47135
+ capScope: "system",
47136
+ addonId: null,
47137
+ access: "delete"
47138
+ },
47139
+ "keychainAdmin.resetKeychain": {
47140
+ capName: "keychain-admin",
47141
+ capScope: "system",
47142
+ addonId: null,
47143
+ access: "delete"
47144
+ },
47145
+ "keychainAdmin.reveal": {
47146
+ capName: "keychain-admin",
47147
+ capScope: "system",
47148
+ addonId: null,
47149
+ access: "create"
47150
+ },
47151
+ "keychainAdmin.rotateMasterKey": {
47152
+ capName: "keychain-admin",
47153
+ capScope: "system",
47154
+ addonId: null,
47155
+ access: "create"
47156
+ },
47157
+ "keychainAdmin.status": {
47158
+ capName: "keychain-admin",
47159
+ capScope: "system",
47160
+ addonId: null,
47161
+ access: "view"
47162
+ },
45504
47163
  "lawnMowerControl.dock": {
45505
47164
  capName: "lawn-mower-control",
45506
47165
  capScope: "device",
@@ -46875,6 +48534,18 @@ Object.freeze({
46875
48534
  addonId: null,
46876
48535
  access: "create"
46877
48536
  },
48537
+ "pipelineAnalytics.addRetrainFrameFromRecording": {
48538
+ capName: "pipeline-analytics",
48539
+ capScope: "device",
48540
+ addonId: null,
48541
+ access: "create"
48542
+ },
48543
+ "pipelineAnalytics.addRetrainFramesToCollection": {
48544
+ capName: "pipeline-analytics",
48545
+ capScope: "device",
48546
+ addonId: null,
48547
+ access: "create"
48548
+ },
46878
48549
  "pipelineAnalytics.applyDeviceSettingsPatch": {
46879
48550
  capName: "pipeline-analytics",
46880
48551
  capScope: "device",
@@ -46923,12 +48594,24 @@ Object.freeze({
46923
48594
  addonId: null,
46924
48595
  access: "view"
46925
48596
  },
48597
+ "pipelineAnalytics.createRetrainCollection": {
48598
+ capName: "pipeline-analytics",
48599
+ capScope: "device",
48600
+ addonId: null,
48601
+ access: "create"
48602
+ },
46926
48603
  "pipelineAnalytics.deleteDeviceEvents": {
46927
48604
  capName: "pipeline-analytics",
46928
48605
  capScope: "device",
46929
48606
  addonId: null,
46930
48607
  access: "delete"
46931
48608
  },
48609
+ "pipelineAnalytics.deleteRetrainCollection": {
48610
+ capName: "pipeline-analytics",
48611
+ capScope: "device",
48612
+ addonId: null,
48613
+ access: "delete"
48614
+ },
46932
48615
  "pipelineAnalytics.deleteTracks": {
46933
48616
  capName: "pipeline-analytics",
46934
48617
  capScope: "device",
@@ -47133,6 +48816,24 @@ Object.freeze({
47133
48816
  addonId: null,
47134
48817
  access: "view"
47135
48818
  },
48819
+ "pipelineAnalytics.listRetrainAssistProfiles": {
48820
+ capName: "pipeline-analytics",
48821
+ capScope: "device",
48822
+ addonId: null,
48823
+ access: "view"
48824
+ },
48825
+ "pipelineAnalytics.listRetrainCollectionFrames": {
48826
+ capName: "pipeline-analytics",
48827
+ capScope: "device",
48828
+ addonId: null,
48829
+ access: "view"
48830
+ },
48831
+ "pipelineAnalytics.listRetrainCollections": {
48832
+ capName: "pipeline-analytics",
48833
+ capScope: "device",
48834
+ addonId: null,
48835
+ access: "view"
48836
+ },
47136
48837
  "pipelineAnalytics.listRetrainFrames": {
47137
48838
  capName: "pipeline-analytics",
47138
48839
  capScope: "device",
@@ -47181,6 +48882,12 @@ Object.freeze({
47181
48882
  addonId: null,
47182
48883
  access: "create"
47183
48884
  },
48885
+ "pipelineAnalytics.proposeRetrainAnnotationsWithLlm": {
48886
+ capName: "pipeline-analytics",
48887
+ capScope: "device",
48888
+ addonId: null,
48889
+ access: "create"
48890
+ },
47184
48891
  "pipelineAnalytics.pruneEvents": {
47185
48892
  capName: "pipeline-analytics",
47186
48893
  capScope: "device",
@@ -47235,6 +48942,18 @@ Object.freeze({
47235
48942
  addonId: null,
47236
48943
  access: "create"
47237
48944
  },
48945
+ "pipelineAnalytics.removeRetrainFrameFromCollection": {
48946
+ capName: "pipeline-analytics",
48947
+ capScope: "device",
48948
+ addonId: null,
48949
+ access: "delete"
48950
+ },
48951
+ "pipelineAnalytics.renameRetrainCollection": {
48952
+ capName: "pipeline-analytics",
48953
+ capScope: "device",
48954
+ addonId: null,
48955
+ access: "create"
48956
+ },
47238
48957
  "pipelineAnalytics.restageRetrainTrack": {
47239
48958
  capName: "pipeline-analytics",
47240
48959
  capScope: "device",
@@ -47523,6 +49242,12 @@ Object.freeze({
47523
49242
  addonId: null,
47524
49243
  access: "view"
47525
49244
  },
49245
+ "pipelineOrchestrator.abortNodeBenchmark": {
49246
+ capName: "pipeline-orchestrator",
49247
+ capScope: "system",
49248
+ addonId: null,
49249
+ access: "create"
49250
+ },
47526
49251
  "pipelineOrchestrator.applyAutoTune": {
47527
49252
  capName: "pipeline-orchestrator",
47528
49253
  capScope: "system",
@@ -47547,6 +49272,12 @@ Object.freeze({
47547
49272
  addonId: null,
47548
49273
  access: "create"
47549
49274
  },
49275
+ "pipelineOrchestrator.deleteNodeBenchmarkResult": {
49276
+ capName: "pipeline-orchestrator",
49277
+ capScope: "system",
49278
+ addonId: null,
49279
+ access: "delete"
49280
+ },
47550
49281
  "pipelineOrchestrator.getAgentLoad": {
47551
49282
  capName: "pipeline-orchestrator",
47552
49283
  capScope: "system",
@@ -47655,6 +49386,24 @@ Object.freeze({
47655
49386
  addonId: null,
47656
49387
  access: "view"
47657
49388
  },
49389
+ "pipelineOrchestrator.getNodeBenchmarkCandidates": {
49390
+ capName: "pipeline-orchestrator",
49391
+ capScope: "system",
49392
+ addonId: null,
49393
+ access: "view"
49394
+ },
49395
+ "pipelineOrchestrator.getNodeBenchmarkPreflight": {
49396
+ capName: "pipeline-orchestrator",
49397
+ capScope: "system",
49398
+ addonId: null,
49399
+ access: "view"
49400
+ },
49401
+ "pipelineOrchestrator.getNodeBenchmarkStatus": {
49402
+ capName: "pipeline-orchestrator",
49403
+ capScope: "system",
49404
+ addonId: null,
49405
+ access: "view"
49406
+ },
47658
49407
  "pipelineOrchestrator.getNodeInferenceDevices": {
47659
49408
  capName: "pipeline-orchestrator",
47660
49409
  capScope: "system",
@@ -47697,6 +49446,12 @@ Object.freeze({
47697
49446
  addonId: null,
47698
49447
  access: "view"
47699
49448
  },
49449
+ "pipelineOrchestrator.listNodeBenchmarkResults": {
49450
+ capName: "pipeline-orchestrator",
49451
+ capScope: "system",
49452
+ addonId: null,
49453
+ access: "view"
49454
+ },
47700
49455
  "pipelineOrchestrator.pauseForStorageMigration": {
47701
49456
  capName: "pipeline-orchestrator",
47702
49457
  capScope: "system",
@@ -47841,6 +49596,12 @@ Object.freeze({
47841
49596
  addonId: null,
47842
49597
  access: "create"
47843
49598
  },
49599
+ "pipelineOrchestrator.startNodeBenchmark": {
49600
+ capName: "pipeline-orchestrator",
49601
+ capScope: "system",
49602
+ addonId: null,
49603
+ access: "create"
49604
+ },
47844
49605
  "pipelineOrchestrator.suggestShares": {
47845
49606
  capName: "pipeline-orchestrator",
47846
49607
  capScope: "system",
@@ -47859,6 +49620,12 @@ Object.freeze({
47859
49620
  addonId: null,
47860
49621
  access: "create"
47861
49622
  },
49623
+ "pipelineRunner.abortNodeBench": {
49624
+ capName: "pipeline-runner",
49625
+ capScope: "system",
49626
+ addonId: null,
49627
+ access: "create"
49628
+ },
47862
49629
  "pipelineRunner.attachCamera": {
47863
49630
  capName: "pipeline-runner",
47864
49631
  capScope: "system",
@@ -47907,6 +49674,12 @@ Object.freeze({
47907
49674
  addonId: null,
47908
49675
  access: "view"
47909
49676
  },
49677
+ "pipelineRunner.getNodeBenchStatus": {
49678
+ capName: "pipeline-runner",
49679
+ capScope: "system",
49680
+ addonId: null,
49681
+ access: "view"
49682
+ },
47910
49683
  "pipelineRunner.getParkedTrackFrame": {
47911
49684
  capName: "pipeline-runner",
47912
49685
  capScope: "system",
@@ -47949,6 +49722,12 @@ Object.freeze({
47949
49722
  addonId: null,
47950
49723
  access: "create"
47951
49724
  },
49725
+ "pipelineRunner.startNodeBench": {
49726
+ capName: "pipeline-runner",
49727
+ capScope: "system",
49728
+ addonId: null,
49729
+ access: "create"
49730
+ },
47952
49731
  "plateGallery.assignPlate": {
47953
49732
  capName: "plate-gallery",
47954
49733
  capScope: "system",
@@ -53096,6 +54875,11 @@ Object.freeze({
53096
54875
  form: "single",
53097
54876
  optional: false
53098
54877
  }],
54878
+ "pipelineAnalytics.addRetrainFrameFromRecording": [{
54879
+ name: "deviceId",
54880
+ form: "single",
54881
+ optional: false
54882
+ }],
53099
54883
  "pipelineAnalytics.applyDeviceSettingsPatch": [{
53100
54884
  name: "deviceId",
53101
54885
  form: "single",
@@ -53286,6 +55070,11 @@ Object.freeze({
53286
55070
  form: "single",
53287
55071
  optional: false
53288
55072
  }],
55073
+ "pipelineAnalytics.proposeRetrainAnnotationsWithLlm": [{
55074
+ name: "deviceId",
55075
+ form: "single",
55076
+ optional: false
55077
+ }],
53289
55078
  "pipelineAnalytics.pruneEventsBefore": [{
53290
55079
  name: "deviceId",
53291
55080
  form: "single",