@camstack/addon-provider-dreo 0.2.122 → 0.2.123

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
@@ -36,7 +36,7 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
36
36
  var __toCommonJS = (mod) => __hasOwnProp.call(mod, "module.exports") ? mod["module.exports"] : __copyProps(__defProp({}, "__esModule", { value: true }), mod);
37
37
  var __require = /* @__PURE__ */ createRequire(import.meta.url);
38
38
  //#endregion
39
- //#region ../types/dist/event-category-B_0XEcLF.mjs
39
+ //#region ../types/dist/event-category-DaIZi00R.mjs
40
40
  var EventCategory = /* @__PURE__ */ function(EventCategory) {
41
41
  EventCategory["SystemBoot"] = "system.boot";
42
42
  EventCategory["SystemAddonsReady"] = "system.addons-ready";
@@ -115,6 +115,13 @@ var EventCategory = /* @__PURE__ */ function(EventCategory) {
115
115
  */
116
116
  EventCategory["AddonLoadFailed"] = "addon.load-failed";
117
117
  /**
118
+ * A keychain value was stored or removed (D787). Carries the ref, its
119
+ * owner and the new version — NEVER the value. A process holding the ref
120
+ * drops its cached copy and the owning `BaseAddon` re-resolves its config.
121
+ * Telemetry (D8): a process that misses it still revalidates by version.
122
+ */
123
+ EventCategory["KeychainChanged"] = "keychain.changed";
124
+ /**
118
125
  * Addon recovered from a previous failure. Emitted when an addon
119
126
  * transitions from `failed` back to `healthy` (typically via the
120
127
  * monitor's auto-retry loop, or after manual `addons.retryLoad`).
@@ -5407,7 +5414,7 @@ var ZodIssueCode = {
5407
5414
  var ZodFirstPartyTypeKind;
5408
5415
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
5409
5416
  //#endregion
5410
- //#region ../types/dist/sleep-B0JG7-_F.mjs
5417
+ //#region ../types/dist/sleep-Cr5YOk3m.mjs
5411
5418
  /**
5412
5419
  * The audio chunk plane's byte format, and the ONE expansion from a coded
5413
5420
  * window to float samples (D455).
@@ -5486,6 +5493,97 @@ function buildAlawTable() {
5486
5493
  }
5487
5494
  buildUlawTable();
5488
5495
  buildAlawTable();
5496
+ /** Is this field's stored value a credential? */
5497
+ function isSecretConfigField(field) {
5498
+ if (field.type === "password") return true;
5499
+ return "secret" in field && field.secret === true;
5500
+ }
5501
+ /**
5502
+ * Is this field's value stored in the KEYCHAIN (D787)? Every secret field is,
5503
+ * by its TYPE, unless it opts out with `storage: 'inline'` — never by its name.
5504
+ */
5505
+ function isKeychainStoredField(field) {
5506
+ if (!isSecretConfigField(field)) return false;
5507
+ if (field.type === "textarea" && field.isJson === true) return false;
5508
+ return !("storage" in field && field.storage === "inline");
5509
+ }
5510
+ /**
5511
+ * What a settings blob holds where a secret used to be.
5512
+ *
5513
+ * A keychain-stored field never holds its value. It holds a self-describing
5514
+ * MARKER, `{"$secret":"secret://…","v":1}` — an object, never a string, so no
5515
+ * code can mistake it for a credential and no form can send it to a camera as
5516
+ * a password. The empty state is `null` / absent, never `''`.
5517
+ *
5518
+ * The same shapes travel to and from the admin UI:
5519
+ *
5520
+ * - read: `hydrateSchema` hands a secret field a {@link SecretFieldView}
5521
+ * (`{ $secret, v, set: true }`) or `null` — the browser learns whether a
5522
+ * value is set, never the value.
5523
+ * - write: an untouched field submits the view back unchanged (KEEP); a typed
5524
+ * value is a plain non-empty string (CHANGE); the Clear button submits
5525
+ * {@link SECRET_CLEAR} (CLEAR). `''`, `null` and the legacy redaction tokens
5526
+ * are KEEP — an empty string is what a defaults-fallback pushes back, and
5527
+ * treating it as "clear" is how a save destroyed a stored credential before.
5528
+ *
5529
+ * Pure and browser-safe.
5530
+ */
5531
+ var SECRET_CLEAR = { $secretClear: true };
5532
+ /** The `'***'` token D634 redaction writes for non-admins. */
5533
+ var LEGACY_DEVICE_REDACTION = "***";
5534
+ function isRecord$1(value) {
5535
+ return typeof value === "object" && value !== null && !Array.isArray(value);
5536
+ }
5537
+ function makeSecretMarker(ref) {
5538
+ return {
5539
+ $secret: ref,
5540
+ v: 1
5541
+ };
5542
+ }
5543
+ /** A stored marker: an object whose `$secret` is a non-empty string. */
5544
+ function isSecretMarker(value) {
5545
+ if (!isRecord$1(value)) return false;
5546
+ const ref = value["$secret"];
5547
+ return typeof ref === "string" && ref.length > 0;
5548
+ }
5549
+ function isSecretClear(value) {
5550
+ return isRecord$1(value) && value["$secretClear"] === true;
5551
+ }
5552
+ /**
5553
+ * The UI view of a stored secret field value: a marker becomes "set", inline
5554
+ * plaintext becomes "set (inline)", nothing becomes `null`. A value never
5555
+ * survives this function.
5556
+ */
5557
+ function toSecretFieldView(stored) {
5558
+ if (isSecretMarker(stored)) return {
5559
+ $secret: stored.$secret,
5560
+ v: 1,
5561
+ set: true
5562
+ };
5563
+ if (typeof stored === "string" && stored.length > 0) return {
5564
+ $secret: null,
5565
+ v: 1,
5566
+ set: true,
5567
+ inline: true
5568
+ };
5569
+ return null;
5570
+ }
5571
+ /**
5572
+ * Classify an incoming value for a secret path. Only a non-empty string that is
5573
+ * not a redaction token sets a value; only {@link SECRET_CLEAR} clears.
5574
+ * Everything else — a marker (ours or anyone's), a UI view, `''`, `null`,
5575
+ * `undefined`, a redaction token, a non-string — keeps what is stored.
5576
+ */
5577
+ function classifySecretWrite(incoming) {
5578
+ if (isSecretClear(incoming)) return { kind: "clear" };
5579
+ if (typeof incoming !== "string") return { kind: "keep" };
5580
+ if (incoming.length === 0) return { kind: "keep" };
5581
+ if (incoming === "__camstack_redacted__" || incoming === LEGACY_DEVICE_REDACTION) return { kind: "keep" };
5582
+ return {
5583
+ kind: "set",
5584
+ value: incoming
5585
+ };
5586
+ }
5489
5587
  Object.fromEntries([
5490
5588
  {
5491
5589
  id: "overview",
@@ -5657,33 +5755,19 @@ Object.fromEntries([
5657
5755
  function isValuelessField(field) {
5658
5756
  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";
5659
5757
  }
5660
- /**
5661
- * Merge a `ConfigUISchema` with a raw `values` record into a
5662
- * `ConfigUISchemaWithValues`. Used by every `get*Settings` backend endpoint
5663
- * before returning to the admin UI. Groups are walked recursively.
5664
- *
5665
- * For each leaf field:
5666
- * - structural fields (`separator`, `info`, `button`) pass through unchanged
5667
- * - other fields get `value = values[key] ?? field.default ?? null`
5668
- *
5669
- * Unknown keys in `values` (keys not declared in the schema) are silently
5670
- * ignored — they don't contribute to the output. Missing keys fall back to
5671
- * the schema default or `null`. This mirrors the old backend behaviour where
5672
- * `FormBuilder` rendered `values[key] ?? field.default`.
5673
- */
5674
- function hydrateSchema(schema, values) {
5758
+ function hydrateSchema(schema, values, options = {}) {
5675
5759
  return {
5676
5760
  ...schema.tabs ? { tabs: [...schema.tabs] } : {},
5677
5761
  sections: schema.sections.map((section) => ({
5678
5762
  ...section,
5679
- fields: section.fields.map((field) => hydrateField(field, values))
5763
+ fields: section.fields.map((field) => hydrateField(field, values, options))
5680
5764
  }))
5681
5765
  };
5682
5766
  }
5683
- function hydrateField(field, values) {
5767
+ function hydrateField(field, values, options) {
5684
5768
  if (isValuelessField(field)) return field;
5685
5769
  if (field.type === "group") {
5686
- const hydratedChildren = field.fields.map((child) => hydrateField(child, values));
5770
+ const hydratedChildren = field.fields.map((child) => hydrateField(child, values, options));
5687
5771
  return {
5688
5772
  ...field,
5689
5773
  fields: hydratedChildren
@@ -5692,7 +5776,7 @@ function hydrateField(field, values) {
5692
5776
  if (field.type === "sub-tabs") {
5693
5777
  const hydratedTabs = field.tabs.map((tab) => ({
5694
5778
  ...tab,
5695
- fields: tab.fields.map((child) => hydrateField(child, values))
5779
+ fields: tab.fields.map((child) => hydrateField(child, values, options))
5696
5780
  }));
5697
5781
  return {
5698
5782
  ...field,
@@ -5702,6 +5786,33 @@ function hydrateField(field, values) {
5702
5786
  const key = field.key;
5703
5787
  const storedValue = Object.prototype.hasOwnProperty.call(values, key) ? values[key] : void 0;
5704
5788
  const defaultValue = field.default;
5789
+ const asView = (v) => isSecretMarker(v) || options.inlineSecretsAsViews === true && v !== void 0;
5790
+ if (isKeychainStoredField(field) && asView(storedValue)) return {
5791
+ ...field,
5792
+ value: toSecretFieldView(storedValue)
5793
+ };
5794
+ if (isKeychainStoredField(field) && options.inlineSecretsAsViews === true) return {
5795
+ ...field,
5796
+ value: null
5797
+ };
5798
+ if (field.type === "editable-array" && Array.isArray(storedValue)) {
5799
+ const secretItemKeys = field.itemFields.filter((item) => "key" in item && isKeychainStoredField(item)).map((item) => "key" in item ? item.key : "");
5800
+ if (secretItemKeys.length > 0) {
5801
+ const rows = storedValue.map((row) => {
5802
+ if (row === null || typeof row !== "object" || Array.isArray(row)) return row;
5803
+ const out = { ...row };
5804
+ for (const k of secretItemKeys) {
5805
+ const v = Reflect.get(row, k);
5806
+ if (asView(v)) out[k] = toSecretFieldView(v);
5807
+ }
5808
+ return out;
5809
+ });
5810
+ return {
5811
+ ...field,
5812
+ value: rows
5813
+ };
5814
+ }
5815
+ }
5705
5816
  if (field.multiple) {
5706
5817
  const stored = Array.isArray(storedValue) ? storedValue : storedValue !== void 0 && storedValue !== null ? [storedValue] : [];
5707
5818
  const itemFallback = field.multiple.itemDefault !== void 0 ? field.multiple.itemDefault : defaultValue !== void 0 ? defaultValue : typeOf(field) === "string" ? "" : null;
@@ -5944,6 +6055,431 @@ function projectStore(store, perNodeKeys, nodeId) {
5944
6055
  }
5945
6056
  return out;
5946
6057
  }
6058
+ var GLOBAL_SCOPE = { kind: "global" };
6059
+ /** The scope every addon-wide (not per-node, not per-device) setting lives in. */
6060
+ function globalSecretScope() {
6061
+ return GLOBAL_SCOPE;
6062
+ }
6063
+ function encodeSegment(value) {
6064
+ return encodeURIComponent(value);
6065
+ }
6066
+ /**
6067
+ * The field path of a value inside an array item, addressed by the item's id:
6068
+ * `arrayItemFieldPath('providers', 'authentik', 'clientSecret')` →
6069
+ * `providers[authentik].clientSecret`.
6070
+ */
6071
+ function arrayItemFieldPath(arrayKey, itemId, fieldKey) {
6072
+ return `${arrayKey}[${encodeSegment(itemId)}].${fieldKey}`;
6073
+ }
6074
+ /** A write to a secret path could not be stored in the keychain, so it was refused. */
6075
+ var KeychainWriteRefusedError = class extends Error {
6076
+ fieldPath;
6077
+ constructor(fieldPath, cause) {
6078
+ super(`secret "${fieldPath}" was not saved: the keychain could not store it (${cause instanceof Error ? cause.message : String(cause)}). Nothing was written.`);
6079
+ this.fieldPath = fieldPath;
6080
+ this.name = "KeychainWriteRefusedError";
6081
+ }
6082
+ };
6083
+ var KEEP = { kind: "keep" };
6084
+ function isRecord(value) {
6085
+ return typeof value === "object" && value !== null && !Array.isArray(value);
6086
+ }
6087
+ function defaultMintId() {
6088
+ return globalThis.crypto.randomUUID();
6089
+ }
6090
+ /** Every marker ref anywhere under `value`. */
6091
+ function collectSecretMarkerRefs(value, out = []) {
6092
+ if (isSecretMarker(value)) {
6093
+ out.push(value.$secret);
6094
+ return out;
6095
+ }
6096
+ if (Array.isArray(value)) for (const item of value) collectSecretMarkerRefs(item, out);
6097
+ else if (isRecord(value)) for (const child of Object.values(value)) collectSecretMarkerRefs(child, out);
6098
+ return out;
6099
+ }
6100
+ async function storedValueEquals(secrets, marker, candidate) {
6101
+ const resolved = (await secrets.resolve([marker.$secret]))[marker.$secret];
6102
+ return resolved?.kind === "value" && resolved.value === candidate;
6103
+ }
6104
+ async function writeLeaf(ctx, incoming, stored, fieldPath) {
6105
+ const intent = classifySecretWrite(incoming);
6106
+ const ref = ctx.secrets.ref(ctx.scope, fieldPath);
6107
+ const storedIsOurs = isSecretMarker(stored) && stored.$secret === ref;
6108
+ if (intent.kind === "keep") return KEEP;
6109
+ if (intent.kind === "set" && !ctx.operatorWrite && typeof stored === "string" && stored === intent.value) return KEEP;
6110
+ if (intent.kind === "clear") {
6111
+ if (storedIsOurs) ctx.deletes.push(ref);
6112
+ return {
6113
+ kind: "value",
6114
+ value: null
6115
+ };
6116
+ }
6117
+ if (storedIsOurs && await storedValueEquals(ctx.secrets, stored, intent.value)) return {
6118
+ kind: "value",
6119
+ value: stored
6120
+ };
6121
+ try {
6122
+ await ctx.secrets.put(ref, intent.value);
6123
+ } catch (err) {
6124
+ throw new KeychainWriteRefusedError(fieldPath, err);
6125
+ }
6126
+ return {
6127
+ kind: "value",
6128
+ value: makeSecretMarker(ref)
6129
+ };
6130
+ }
6131
+ /** Apply a member result onto `out`: KEEP restores the stored member, or removes it. */
6132
+ function applyMember(out, key, result, storedParent) {
6133
+ if (result.kind === "value") {
6134
+ out[key] = result.value;
6135
+ return;
6136
+ }
6137
+ if (Object.prototype.hasOwnProperty.call(storedParent, key)) out[key] = storedParent[key];
6138
+ else delete out[key];
6139
+ }
6140
+ async function writeMembers(ctx, children, incoming, stored, pathOf) {
6141
+ const out = { ...incoming };
6142
+ for (const [member, node] of children) applyMember(out, member, await writeNode(ctx, node, incoming[member], stored[member], pathOf(member)), stored);
6143
+ return out;
6144
+ }
6145
+ function rowId(row, idKey) {
6146
+ const raw = row[idKey];
6147
+ if (typeof raw === "string" && raw.length > 0) return raw;
6148
+ if (typeof raw === "number" && Number.isFinite(raw)) return String(raw);
6149
+ return null;
6150
+ }
6151
+ async function writeArray(ctx, node, incoming, stored, fieldPath) {
6152
+ const storedRows = Array.isArray(stored) ? stored.filter(isRecord) : [];
6153
+ if (!Array.isArray(incoming)) {
6154
+ ctx.deletes.push(...collectSecretMarkerRefs(storedRows));
6155
+ return {
6156
+ kind: "value",
6157
+ value: incoming
6158
+ };
6159
+ }
6160
+ const storedById = /* @__PURE__ */ new Map();
6161
+ for (const row of storedRows) {
6162
+ const id = rowId(row, node.idKey);
6163
+ if (id !== null) storedById.set(id, row);
6164
+ }
6165
+ const kept = /* @__PURE__ */ new Set();
6166
+ const rows = [];
6167
+ for (const row of incoming) {
6168
+ if (!isRecord(row)) {
6169
+ rows.push(row);
6170
+ continue;
6171
+ }
6172
+ const id = rowId(row, node.idKey) ?? ctx.mintId();
6173
+ kept.add(id);
6174
+ const withId = {
6175
+ ...row,
6176
+ [node.idKey]: row[node.idKey] ?? id
6177
+ };
6178
+ if (rowId(withId, node.idKey) === null) withId[node.idKey] = id;
6179
+ const storedRow = storedById.get(id) ?? {};
6180
+ rows.push(await writeMembers(ctx, node.item, withId, storedRow, (member) => arrayItemFieldPath(fieldPath, id, member)));
6181
+ }
6182
+ for (const [id, row] of storedById) if (!kept.has(id)) ctx.deletes.push(...collectSecretMarkerRefs(row));
6183
+ return {
6184
+ kind: "value",
6185
+ value: rows
6186
+ };
6187
+ }
6188
+ async function writeNode(ctx, node, incoming, stored, fieldPath) {
6189
+ switch (node.kind) {
6190
+ case "leaf": return writeLeaf(ctx, incoming, stored, fieldPath);
6191
+ case "array": return writeArray(ctx, node, incoming, stored, fieldPath);
6192
+ case "object": {
6193
+ if (!isRecord(incoming)) {
6194
+ if (incoming === void 0) return KEEP;
6195
+ ctx.deletes.push(...collectSecretMarkerRefs(stored));
6196
+ return {
6197
+ kind: "value",
6198
+ value: incoming
6199
+ };
6200
+ }
6201
+ const storedObj = isRecord(stored) ? stored : {};
6202
+ return {
6203
+ kind: "value",
6204
+ value: await writeMembers(ctx, node.children, incoming, storedObj, (m) => `${fieldPath}.${m}`)
6205
+ };
6206
+ }
6207
+ }
6208
+ }
6209
+ /** Split a perNode-scoped key (`key@nodeId`). */
6210
+ function splitNodeKey(key) {
6211
+ const at = key.indexOf("@");
6212
+ return at <= 0 ? {
6213
+ base: key,
6214
+ nodeId: null
6215
+ } : {
6216
+ base: key.slice(0, at),
6217
+ nodeId: key.slice(at + 1)
6218
+ };
6219
+ }
6220
+ /** Rewrite a settings patch so no secret value reaches the blob. See the file doc. */
6221
+ async function transformSecretWrite(input) {
6222
+ const deletes = [];
6223
+ const base = {
6224
+ secrets: input.secrets,
6225
+ mintId: input.mintId ?? defaultMintId,
6226
+ deletes,
6227
+ operatorWrite: input.operatorWrite === true
6228
+ };
6229
+ const out = {};
6230
+ for (const [key, incoming] of Object.entries(input.patch)) {
6231
+ const { base: baseKey, nodeId } = splitNodeKey(key);
6232
+ const node = input.tree.get(baseKey);
6233
+ if (node === void 0) {
6234
+ out[key] = incoming;
6235
+ continue;
6236
+ }
6237
+ const scope = nodeId !== null && nodeId.length > 0 ? {
6238
+ kind: "node",
6239
+ nodeId
6240
+ } : input.scope ?? globalSecretScope();
6241
+ const result = await writeNode({
6242
+ ...base,
6243
+ scope
6244
+ }, node, incoming, input.stored[key], baseKey);
6245
+ if (result.kind === "value") out[key] = result.value;
6246
+ }
6247
+ return {
6248
+ patch: out,
6249
+ afterWrite: async () => {
6250
+ if (deletes.length === 0) return { orphaned: [] };
6251
+ try {
6252
+ await input.secrets.delete([...new Set(deletes)]);
6253
+ return { orphaned: [] };
6254
+ } catch {
6255
+ return { orphaned: [...new Set(deletes)] };
6256
+ }
6257
+ }
6258
+ };
6259
+ }
6260
+ /**
6261
+ * Replace every marker in `value` with its keychain value. Returns the SAME
6262
+ * reference when there is no marker (no allocation, no keychain call).
6263
+ */
6264
+ async function resolveSecretMarkers(value, secrets) {
6265
+ const refs = collectSecretMarkerRefs(value);
6266
+ if (refs.length === 0) return {
6267
+ value,
6268
+ unresolved: []
6269
+ };
6270
+ const answers = await secrets.resolve(refs);
6271
+ const unresolved = [];
6272
+ for (const ref of new Set(refs)) {
6273
+ const answer = answers[ref];
6274
+ if (answer === void 0) unresolved.push({
6275
+ ref,
6276
+ reason: "not-initialized"
6277
+ });
6278
+ else if (answer.kind === "unavailable") unresolved.push({
6279
+ ref,
6280
+ reason: answer.reason
6281
+ });
6282
+ else if (answer.kind === "missing" || answer.kind === "forbidden") unresolved.push({
6283
+ ref,
6284
+ reason: answer.kind
6285
+ });
6286
+ }
6287
+ const substitute = (v) => {
6288
+ if (isSecretMarker(v)) {
6289
+ const answer = answers[v.$secret];
6290
+ return answer?.kind === "value" ? {
6291
+ keep: true,
6292
+ value: answer.value
6293
+ } : {
6294
+ keep: false,
6295
+ value: void 0
6296
+ };
6297
+ }
6298
+ if (Array.isArray(v)) {
6299
+ const items = [];
6300
+ for (const item of v) {
6301
+ const s = substitute(item);
6302
+ if (s.keep) items.push(s.value);
6303
+ }
6304
+ return {
6305
+ keep: true,
6306
+ value: items
6307
+ };
6308
+ }
6309
+ if (isRecord(v)) {
6310
+ const out = {};
6311
+ for (const [k, child] of Object.entries(v)) {
6312
+ const s = substitute(child);
6313
+ if (s.keep) out[k] = s.value;
6314
+ }
6315
+ return {
6316
+ keep: true,
6317
+ value: out
6318
+ };
6319
+ }
6320
+ return {
6321
+ keep: true,
6322
+ value: v
6323
+ };
6324
+ };
6325
+ return {
6326
+ value: substitute(value).value,
6327
+ unresolved
6328
+ };
6329
+ }
6330
+ function touchesTree(tree, patch) {
6331
+ if (tree.size === 0) return false;
6332
+ for (const key of Object.keys(patch)) {
6333
+ const at = key.indexOf("@");
6334
+ if (tree.has(at > 0 ? key.slice(0, at) : key)) return true;
6335
+ }
6336
+ return false;
6337
+ }
6338
+ /** The blob as stored now; a failed read REFUSES the write instead of guessing. */
6339
+ async function readStoredAddonBlob(raw) {
6340
+ const threeWay = raw.readAddonStoreResult;
6341
+ if (threeWay === void 0) return raw.readAddonStore();
6342
+ const result = await threeWay.call(raw);
6343
+ if (result.kind === "failed") throw new Error(`settings write refused: the stored blob could not be read (${result.error})`);
6344
+ return result.kind === "missing" ? {} : result.value;
6345
+ }
6346
+ function createSecretAwareSettings(raw, opts) {
6347
+ const chains = /* @__PURE__ */ new Map();
6348
+ const serialize = (key, fn) => {
6349
+ const next = (chains.get(key) ?? Promise.resolve()).then(fn, fn);
6350
+ const tail = next.catch(() => void 0);
6351
+ chains.set(key, tail);
6352
+ tail.then(() => {
6353
+ if (chains.get(key) === tail) chains.delete(key);
6354
+ });
6355
+ return next;
6356
+ };
6357
+ const write = async (chainKey, tree, scope, patch, readStored, rawWrite) => {
6358
+ if (!touchesTree(tree, patch)) return rawWrite(patch);
6359
+ return serialize(chainKey, async () => {
6360
+ const stored = await readStored();
6361
+ const result = await transformSecretWrite({
6362
+ tree,
6363
+ secrets: opts.secrets,
6364
+ patch,
6365
+ stored,
6366
+ ...scope !== void 0 ? { scope } : {},
6367
+ operatorWrite: opts.isOperatorWrite?.() === true
6368
+ });
6369
+ if (Object.keys(result.patch).length > 0) await rawWrite(result.patch);
6370
+ const { orphaned } = await result.afterWrite();
6371
+ if (orphaned.length > 0) opts.onOrphaned(orphaned);
6372
+ });
6373
+ };
6374
+ const wrapped = {
6375
+ writeAddonStore: (patch) => write("addon", opts.addonTree(), void 0, patch, () => readStoredAddonBlob(raw), (p) => raw.writeAddonStore(p)),
6376
+ writeDeviceStore: (deviceId, patch) => write(`device:${deviceId}`, opts.deviceTree(), {
6377
+ kind: "device",
6378
+ deviceId
6379
+ }, patch, () => raw.readDeviceStore(deviceId), (p) => raw.writeDeviceStore(deviceId, p))
6380
+ };
6381
+ return new Proxy(raw, { get(target, prop, receiver) {
6382
+ if (prop === "writeAddonStore") return wrapped.writeAddonStore;
6383
+ if (prop === "writeDeviceStore") return wrapped.writeDeviceStore;
6384
+ const value = Reflect.get(target, prop, receiver);
6385
+ return typeof value === "function" ? value.bind(target) : value;
6386
+ } });
6387
+ }
6388
+ /** The context the addon sees: identical, except that its settings writes are secret-aware. */
6389
+ function withSecretAwareSettings(context, opts) {
6390
+ const raw = context.settings;
6391
+ if (raw === void 0) return context;
6392
+ const settings = createSecretAwareSettings(raw, opts);
6393
+ return new Proxy(context, { get(target, prop, receiver) {
6394
+ if (prop === "settings") return settings;
6395
+ return Reflect.get(target, prop, receiver);
6396
+ } });
6397
+ }
6398
+ var LEAF = { kind: "leaf" };
6399
+ var DEFAULT_ITEM_ID_KEY = "id";
6400
+ function collectFields(fields, out) {
6401
+ for (const field of fields) {
6402
+ if (field.type === "group") {
6403
+ collectFields(field.fields, out);
6404
+ continue;
6405
+ }
6406
+ if (field.type === "sub-tabs") {
6407
+ for (const tab of field.tabs) collectFields(tab.fields, out);
6408
+ continue;
6409
+ }
6410
+ if (field.type === "editable-array") {
6411
+ const item = /* @__PURE__ */ new Map();
6412
+ for (const itemField of field.itemFields) if ("key" in itemField && isKeychainStoredField(itemField)) item.set(itemField.key, LEAF);
6413
+ if (item.size > 0) out.set(field.key, {
6414
+ kind: "array",
6415
+ idKey: field.itemIdKey ?? DEFAULT_ITEM_ID_KEY,
6416
+ item
6417
+ });
6418
+ continue;
6419
+ }
6420
+ if (!("key" in field) || typeof field.key !== "string") continue;
6421
+ if (isKeychainStoredField(field)) out.set(field.key, LEAF);
6422
+ }
6423
+ }
6424
+ /** The secret tree a settings schema declares. */
6425
+ function secretTreeFromSchema(schema) {
6426
+ const out = /* @__PURE__ */ new Map();
6427
+ if (schema === null) return out;
6428
+ for (const section of schema.sections) collectFields(section.fields, out);
6429
+ return out;
6430
+ }
6431
+ /** Parse `a.b[id].c` into segments; throws on a malformed path (a declaration bug). */
6432
+ function parseSecretStatePath(path) {
6433
+ const segments = [];
6434
+ for (const raw of path.split(".")) {
6435
+ const m = /^([^[\]]+)(?:\[([^[\]]+)\])?$/.exec(raw);
6436
+ if (m === null || m[1] === void 0) throw new Error(`secretStatePaths: malformed path "${path}"`);
6437
+ segments.push(m[2] !== void 0 ? {
6438
+ key: m[1],
6439
+ idKey: m[2]
6440
+ } : { key: m[1] });
6441
+ }
6442
+ if (segments.length === 0) throw new Error(`secretStatePaths: empty path`);
6443
+ if (segments[segments.length - 1]?.idKey !== void 0) throw new Error(`secretStatePaths: "${path}" ends on an array — name the member that is secret`);
6444
+ return segments;
6445
+ }
6446
+ function insert(into, segments) {
6447
+ const [head, ...rest] = segments;
6448
+ if (head === void 0) return;
6449
+ if (rest.length === 0) {
6450
+ into.set(head.key, LEAF);
6451
+ return;
6452
+ }
6453
+ const existing = into.get(head.key);
6454
+ if (head.idKey !== void 0) {
6455
+ const item = new Map(existing?.kind === "array" ? existing.item : []);
6456
+ insert(item, rest);
6457
+ into.set(head.key, {
6458
+ kind: "array",
6459
+ idKey: head.idKey,
6460
+ item
6461
+ });
6462
+ return;
6463
+ }
6464
+ const children = new Map(existing?.kind === "object" ? existing.children : []);
6465
+ insert(children, rest);
6466
+ into.set(head.key, {
6467
+ kind: "object",
6468
+ children
6469
+ });
6470
+ }
6471
+ /** Add hidden-state paths (`secretStatePaths`) to a schema-derived tree. */
6472
+ function mergeSecretStatePaths(tree, paths) {
6473
+ if (paths.length === 0) return tree;
6474
+ const out = new Map(tree);
6475
+ for (const path of paths) insert(out, parseSecretStatePath(path));
6476
+ return out;
6477
+ }
6478
+ /** First retry of a secret the keychain could not serve; doubles to {@link SECRET_RETRY_MAX_MS}. */
6479
+ var SECRET_RETRY_FIRST_MS = 5e3;
6480
+ var SECRET_RETRY_MAX_MS = 5 * 6e4;
6481
+ /** Coalesces a burst of `keychain.changed` events into one re-resolve. */
6482
+ var SECRET_CHANGE_DEBOUNCE_MS = 250;
5947
6483
  /**
5948
6484
  * Base class for CamStack addons. Eliminates settings boilerplate:
5949
6485
  *
@@ -6013,6 +6549,25 @@ var BaseAddon = class {
6013
6549
  settingsStoreReady = false;
6014
6550
  /** Default config values. Provided via constructor. */
6015
6551
  defaults;
6552
+ /**
6553
+ * Hidden-state paths that hold secrets (D787) — values the addon writes
6554
+ * itself (`updateGlobalSettings`, `state()`) that no form field declares.
6555
+ * Stored in the keychain exactly like a `password` field. Syntax:
6556
+ * `'snapshotSigningKey'`, `'identity.pincode'`, `'tokens[userId].accessToken'`
6557
+ * (`key[<id field>]` addresses array items by id, never by index).
6558
+ */
6559
+ secretStatePaths = [];
6560
+ _addonSecretTree = null;
6561
+ _deviceSecretTree = null;
6562
+ /** Refs the last resolved config pointed at — a change to one re-resolves. */
6563
+ _configSecretRefs = /* @__PURE__ */ new Set();
6564
+ _unresolvedSecrets = [];
6565
+ _secretRetryTimer = null;
6566
+ _secretRetryDelayMs = SECRET_RETRY_FIRST_MS;
6567
+ _secretChangeTimer = null;
6568
+ _secretChangeUnsub = null;
6569
+ /** >0 while an OPERATOR's settings write is being applied. */
6570
+ _operatorWriteDepth = 0;
6016
6571
  constructor(defaults) {
6017
6572
  this.defaults = defaults;
6018
6573
  this._config = { ...defaults };
@@ -6048,8 +6603,18 @@ var BaseAddon = class {
6048
6603
  return this._config;
6049
6604
  }
6050
6605
  async initialize(context) {
6051
- this._ctx = context;
6606
+ const secrets = context.secrets;
6607
+ this._ctx = secrets !== void 0 ? withSecretAwareSettings(context, {
6608
+ secrets,
6609
+ addonTree: () => this.addonSecretTree(),
6610
+ deviceTree: () => this.deviceSecretTree(),
6611
+ onOrphaned: (refs) => context.logger.warn("keychain refs dropped by a settings write could not be deleted", { meta: { refs: [...refs] } }),
6612
+ isOperatorWrite: () => this._operatorWriteDepth > 0
6613
+ }) : context;
6052
6614
  await this.resolveConfig();
6615
+ if (secrets !== void 0) this._secretChangeUnsub = secrets.onChange((ref) => {
6616
+ if (this._configSecretRefs.has(ref)) this.scheduleSecretReresolve(SECRET_CHANGE_DEBOUNCE_MS);
6617
+ });
6053
6618
  const result = await this.onInitialize();
6054
6619
  this.emitLifecycle(EventCategory.AddonStarted);
6055
6620
  const normalized = normalizeAddonInitResult(result);
@@ -6082,6 +6647,12 @@ var BaseAddon = class {
6082
6647
  */
6083
6648
  async onHubReachable() {}
6084
6649
  async shutdown() {
6650
+ this._secretChangeUnsub?.();
6651
+ this._secretChangeUnsub = null;
6652
+ if (this._secretRetryTimer !== null) clearTimeout(this._secretRetryTimer);
6653
+ if (this._secretChangeTimer !== null) clearTimeout(this._secretChangeTimer);
6654
+ this._secretRetryTimer = null;
6655
+ this._secretChangeTimer = null;
6085
6656
  this.emitLifecycle(EventCategory.AddonStopped);
6086
6657
  if (this.autoEmitReadiness) this.emitReadinessForProviders("down");
6087
6658
  await this.onShutdown();
@@ -6160,7 +6731,7 @@ var BaseAddon = class {
6160
6731
  return hydrateSchema(schema, overlay ? {
6161
6732
  ...projected,
6162
6733
  ...overlay
6163
- } : projected);
6734
+ } : projected, { inlineSecretsAsViews: true });
6164
6735
  }
6165
6736
  /**
6166
6737
  * The integration-level view of this addon's settings: exactly the sections
@@ -6209,7 +6780,7 @@ var BaseAddon = class {
6209
6780
  return hydrateSchema({
6210
6781
  ...schema,
6211
6782
  sections
6212
- }, projected);
6783
+ }, projected, { inlineSecretsAsViews: true });
6213
6784
  }
6214
6785
  /**
6215
6786
  * The raw addon store PROJECTED onto the target node's bare per-node keys:
@@ -6263,18 +6834,50 @@ var BaseAddon = class {
6263
6834
  value: result.value[key]
6264
6835
  };
6265
6836
  }
6837
+ /**
6838
+ * The OPERATOR's write — a settings form or an admin API call, dispatched by
6839
+ * the kernel. Identical to {@link updateGlobalSettings}, except that a secret
6840
+ * the operator sends is stored as sent even when it equals a pre-keychain
6841
+ * inline value: the operator re-entering a password is a change, an addon
6842
+ * writing back what it read is not (D787).
6843
+ */
6844
+ async updateGlobalSettingsAsOperator(patch, nodeId) {
6845
+ this._operatorWriteDepth++;
6846
+ try {
6847
+ await this.applyGlobalPatch(patch, nodeId);
6848
+ } finally {
6849
+ this._operatorWriteDepth--;
6850
+ }
6851
+ }
6266
6852
  async updateGlobalSettings(patch, nodeId) {
6853
+ await this.applyGlobalPatch(patch, nodeId);
6854
+ }
6855
+ /**
6856
+ * REMOVE stored secrets — their keychain values and their markers (D787).
6857
+ *
6858
+ * Writing `''` to a secret field KEEPS what is stored (an empty string is
6859
+ * what a defaults fallback writes back, and it must never destroy a
6860
+ * credential), so code that means "forget this token" says so here. Without
6861
+ * a keychain (an older kernel) it writes `''`, as such code always did.
6862
+ */
6863
+ async clearSecrets(keys, nodeId) {
6864
+ const tree = this.addonSecretTree();
6865
+ const keychain = this._ctx?.secrets !== void 0;
6866
+ const patch = {};
6867
+ for (const key of keys) patch[key] = keychain && tree.has(key) ? SECRET_CLEAR : "";
6868
+ await this.applyGlobalPatch(patch, nodeId);
6869
+ }
6870
+ async applyGlobalPatch(barePatch, nodeId) {
6267
6871
  const keys = this.perNodeKeys();
6268
6872
  const localNode = normalizeNodeId(this._ctx?.kernel?.localNodeId);
6269
6873
  const target = normalizeNodeId(nodeId ?? this._ctx?.kernel?.localNodeId);
6270
- const barePatch = patch;
6271
6874
  const scoped = keys.size > 0 ? scopePatch(barePatch, keys, target) : barePatch;
6272
6875
  await this._ctx?.settings?.writeAddonStore(scoped);
6273
6876
  if (target !== localNode) return;
6274
6877
  await this.resolveConfig();
6275
6878
  await this.onConfigChanged();
6276
6879
  this.emitLifecycle(EventCategory.AddonUpdated, { level: "global" });
6277
- this.maybeAutoRestart(patch, this.globalSettingsSchema());
6880
+ this.maybeAutoRestart(Object.keys(barePatch), this.globalSettingsSchema());
6278
6881
  }
6279
6882
  /**
6280
6883
  * The set of field keys the global settings schema declares `perNode: true`
@@ -6299,7 +6902,7 @@ var BaseAddon = class {
6299
6902
  * time to return its response before the addon is torn down and
6300
6903
  * re-initialised by `AddonRegistryService.restartAddon`.
6301
6904
  */
6302
- maybeAutoRestart(patch, schema) {
6905
+ maybeAutoRestart(patchKeys, schema) {
6303
6906
  if (!schema) return;
6304
6907
  const restartKeys = /* @__PURE__ */ new Set();
6305
6908
  for (const section of schema.sections) for (const field of section.fields) {
@@ -6307,13 +6910,13 @@ var BaseAddon = class {
6307
6910
  if (field.requiresRestart) restartKeys.add(field.key);
6308
6911
  }
6309
6912
  if (restartKeys.size === 0) return;
6310
- if (!Object.keys(patch).some((k) => restartKeys.has(k))) return;
6913
+ if (!patchKeys.some((k) => restartKeys.has(k))) return;
6311
6914
  const ctx = this._ctx;
6312
6915
  if (!ctx) return;
6313
6916
  const addonId = ctx.id;
6314
6917
  setImmediate(() => {
6315
6918
  ctx.api.addons?.restartAddon?.mutate({ addonId }).then(() => {
6316
- ctx.logger.info("addon auto-restart triggered by restart-required setting change", { meta: { changedFields: Object.keys(patch).filter((k) => restartKeys.has(k)) } });
6919
+ ctx.logger.info("addon auto-restart triggered by restart-required setting change", { meta: { changedFields: patchKeys.filter((k) => restartKeys.has(k)) } });
6317
6920
  }).catch((err) => {
6318
6921
  ctx.logger.error("addon auto-restart failed", { meta: { error: err instanceof Error ? err.message : String(err) } });
6319
6922
  });
@@ -6322,7 +6925,7 @@ var BaseAddon = class {
6322
6925
  async getDeviceSettings(deviceId) {
6323
6926
  const schema = this.deviceSettingsSchema();
6324
6927
  if (!schema) return { sections: [] };
6325
- return hydrateSchema(schema, await this._ctx?.settings?.readDeviceStore(deviceId) ?? {});
6928
+ return hydrateSchema(schema, await this._ctx?.settings?.readDeviceStore(deviceId) ?? {}, { inlineSecretsAsViews: true });
6326
6929
  }
6327
6930
  async updateDeviceSettings(deviceId, patch) {
6328
6931
  await this._ctx?.settings?.writeDeviceStore(deviceId, patch);
@@ -6452,7 +7055,7 @@ var BaseAddon = class {
6452
7055
  * selection at boot (absent scoped key ⇒ the constructor default wins).
6453
7056
  */
6454
7057
  async resolveConfig() {
6455
- const stored = await this.readAddonStoreWithRetry();
7058
+ const stored = await this.resolveStoredSecrets(await this.readAddonStoreWithRetry());
6456
7059
  const perNode = this.perNodeKeys();
6457
7060
  const localNode = normalizeNodeId(this._ctx?.kernel?.localNodeId);
6458
7061
  const resolved = { ...this.defaults };
@@ -6477,7 +7080,7 @@ var BaseAddon = class {
6477
7080
  key,
6478
7081
  schema,
6479
7082
  fallback,
6480
- read: () => this.readAddonStoreWithRetry(),
7083
+ read: async () => this.resolveStoredSecrets(await this.readAddonStoreWithRetry()),
6481
7084
  write: async (patch) => {
6482
7085
  await this._ctx?.settings?.writeAddonStore(patch);
6483
7086
  },
@@ -6494,7 +7097,7 @@ var BaseAddon = class {
6494
7097
  key,
6495
7098
  schema,
6496
7099
  fallback,
6497
- read: async () => await this._ctx?.settings?.readDeviceStore(deviceId) ?? {},
7100
+ read: async () => this.resolveStoredSecrets(await this._ctx?.settings?.readDeviceStore(deviceId) ?? {}, false),
6498
7101
  write: async (patch) => {
6499
7102
  await this._ctx?.settings?.writeDeviceStore(deviceId, patch);
6500
7103
  },
@@ -6506,6 +7109,70 @@ var BaseAddon = class {
6506
7109
  } })
6507
7110
  });
6508
7111
  }
7112
+ /** The addon store's secret tree: schema fields by TYPE, plus `secretStatePaths`. */
7113
+ addonSecretTree() {
7114
+ this._addonSecretTree ??= mergeSecretStatePaths(secretTreeFromSchema(this.globalSettingsSchema()), this.secretStatePaths);
7115
+ return this._addonSecretTree;
7116
+ }
7117
+ deviceSecretTree() {
7118
+ this._deviceSecretTree ??= secretTreeFromSchema(this.deviceSettingsSchema());
7119
+ return this._deviceSecretTree;
7120
+ }
7121
+ /**
7122
+ * Secrets of this addon's stored config that could not be resolved on the
7123
+ * last read, with why. Non-empty means the addon is running WITHOUT them —
7124
+ * an addon whose function needs one should report itself degraded rather
7125
+ * than start on an empty credential.
7126
+ */
7127
+ get unresolvedSecrets() {
7128
+ return this._unresolvedSecrets;
7129
+ }
7130
+ /**
7131
+ * Substitute every keychain marker in a stored blob with its value. With no
7132
+ * keychain (no `ctx.secrets`) or no marker, the blob comes back unchanged.
7133
+ * An unresolvable value is LEFT OUT (never `''`), logged by ref — never by
7134
+ * value — and, when the cause can pass, retried with backoff. Nothing is
7135
+ * ever written back from here.
7136
+ */
7137
+ async resolveStoredSecrets(blob, trackForConfig = true) {
7138
+ const secrets = this._ctx?.secrets;
7139
+ if (secrets === void 0) return blob;
7140
+ const refs = collectSecretMarkerRefs(blob);
7141
+ if (trackForConfig) this._configSecretRefs = new Set(refs);
7142
+ if (refs.length === 0) {
7143
+ if (trackForConfig) this._unresolvedSecrets = [];
7144
+ return blob;
7145
+ }
7146
+ const { value, unresolved } = await resolveSecretMarkers(blob, secrets);
7147
+ if (trackForConfig) {
7148
+ this._unresolvedSecrets = unresolved;
7149
+ if (unresolved.length > 0) {
7150
+ this._ctx?.logger?.error?.("secret unavailable — running without it, will retry", { meta: { secrets: unresolved.map((u) => ({
7151
+ ref: u.ref,
7152
+ reason: u.reason
7153
+ })) } });
7154
+ if (unresolved.some((u) => u.reason !== "missing" && u.reason !== "forbidden")) {
7155
+ this.scheduleSecretReresolve(this._secretRetryDelayMs);
7156
+ this._secretRetryDelayMs = Math.min(this._secretRetryDelayMs * 2, SECRET_RETRY_MAX_MS);
7157
+ }
7158
+ } else this._secretRetryDelayMs = SECRET_RETRY_FIRST_MS;
7159
+ }
7160
+ return value;
7161
+ }
7162
+ /** Re-resolve the config (a keychain-only change, or a retry) and apply it. */
7163
+ scheduleSecretReresolve(delayMs) {
7164
+ const timerOf = delayMs === SECRET_CHANGE_DEBOUNCE_MS ? "_secretChangeTimer" : "_secretRetryTimer";
7165
+ if (this[timerOf] !== null) return;
7166
+ const timer = setTimeout(() => {
7167
+ this[timerOf] = null;
7168
+ if (this._ctx === null) return;
7169
+ this.resolveConfig().then(() => this.onConfigChanged()).catch((err) => {
7170
+ this._ctx?.logger?.error?.("re-resolving secrets failed", { meta: { error: err instanceof Error ? err.message : String(err) } });
7171
+ });
7172
+ }, delayMs);
7173
+ timer.unref?.();
7174
+ this[timerOf] = timer;
7175
+ }
6509
7176
  /**
6510
7177
  * Wrap `ctx.settings.readAddonStore()` with a short retry budget so a
6511
7178
  * transient settings-store outage (mid-restart of sqlite-settings, tsx-watch
@@ -7081,6 +7748,69 @@ method(object({ deviceId: number() }), array(StreamSourceEntrySchema)), method(o
7081
7748
  kind: "mutation",
7082
7749
  auth: "admin"
7083
7750
  }), method(object({ deviceId: number() }), unknown().nullable()), method(object({ deviceId: number() }), RawStateResultSchema.nullable(), { auth: "protected" });
7751
+ function defOf(schema) {
7752
+ return schema._zod?.def ?? {};
7753
+ }
7754
+ function declaredHere(schema) {
7755
+ return globalRegistry.get(schema)?.secret === true;
7756
+ }
7757
+ /** Wrapper kinds whose `innerType` is the field itself. */
7758
+ var WRAPPERS = new Set([
7759
+ "optional",
7760
+ "nullable",
7761
+ "default",
7762
+ "prefault",
7763
+ "catch",
7764
+ "readonly",
7765
+ "nonoptional"
7766
+ ]);
7767
+ /**
7768
+ * The schema layers that make up ONE field: the schema itself and every
7769
+ * wrapper below it (optional / default / nullable / readonly / catch), plus
7770
+ * both sides of a pipe (`z.preprocess` puts the real schema on `out`,
7771
+ * `.transform` on `in`).
7772
+ */
7773
+ function layersOf(schema) {
7774
+ const out = [];
7775
+ const queue = [schema];
7776
+ while (queue.length > 0) {
7777
+ const s = queue.shift();
7778
+ if (!s || out.includes(s)) continue;
7779
+ out.push(s);
7780
+ const def = defOf(s);
7781
+ if (def.type !== void 0 && WRAPPERS.has(def.type) && def.innerType) queue.push(def.innerType);
7782
+ if (def.type === "pipe") {
7783
+ if (def.in) queue.push(def.in);
7784
+ if (def.out) queue.push(def.out);
7785
+ }
7786
+ }
7787
+ return out;
7788
+ }
7789
+ /** True when any layer of this field declares `.meta({ secret: true })`. */
7790
+ function isZodSecret(schema) {
7791
+ return layersOf(schema).some(declaredHere);
7792
+ }
7793
+ /**
7794
+ * Every declared secret path in a config schema: dotted keys, `[]` for "each
7795
+ * element of this array" (`connection.password`, `rows[].token`). A declared
7796
+ * object or array is reported as one path and not descended into — everything
7797
+ * under it is secret.
7798
+ */
7799
+ function collectZodSecretPaths(schema, prefix = "") {
7800
+ if (isZodSecret(schema)) return prefix.length > 0 ? [prefix] : [];
7801
+ const paths = [];
7802
+ for (const layer of layersOf(schema)) {
7803
+ const def = defOf(layer);
7804
+ if (def.type === "object" && def.shape) for (const [key, child] of Object.entries(def.shape)) paths.push(...collectZodSecretPaths(child, prefix ? `${prefix}.${key}` : key));
7805
+ else if (def.type === "array" && def.element) paths.push(...collectZodSecretPaths(def.element, `${prefix}[]`));
7806
+ else if (def.type === "union" && def.options) for (const option of def.options) paths.push(...collectZodSecretPaths(option, prefix));
7807
+ else if (def.type === "intersection") {
7808
+ if (def.left) paths.push(...collectZodSecretPaths(def.left, prefix));
7809
+ if (def.right) paths.push(...collectZodSecretPaths(def.right, prefix));
7810
+ }
7811
+ }
7812
+ return [...new Set(paths)];
7813
+ }
7084
7814
  //#endregion
7085
7815
  //#region ../types/dist/err-msg-DX6i_MY4.mjs
7086
7816
  var DeviceType = /* @__PURE__ */ function(DeviceType) {
@@ -14111,6 +14841,196 @@ id: union([string(), number()]) }), {
14111
14841
  kind: "mutation",
14112
14842
  auth: "admin"
14113
14843
  });
14844
+ /**
14845
+ * `keychain` — the hub's encrypted store of secret values (D787).
14846
+ *
14847
+ * Settings blobs never hold a secret: they hold a marker
14848
+ * `{"$secret":"secret://<owner>/<scope>/<fieldPath>","v":1}` and the value
14849
+ * lives here, AES-256-GCM under a data key that a master key wraps. This cap
14850
+ * is the OWNER's door to its own values: every method is owner-checked
14851
+ * against the CALLER, never against anything the caller claims.
14852
+ *
14853
+ * Who the caller is: the transport stamps `callerAddonId` into the args of a
14854
+ * call that crossed a process (the parent `LocalChildRegistry` from the UDS
14855
+ * connection, the agent from its child's connection carried in
14856
+ * `$hub-cap-fwd`'s envelope). A stamp always overwrites; a wire call with no
14857
+ * stamp has its claim stripped. Only a hub in-process caller may state its own
14858
+ * identity — `ctx.secrets` does that with the addon id closed over. This is
14859
+ * identity against BUGS and misrouting, not against a malicious addon (every
14860
+ * runner is the same OS user): see the threat model in
14861
+ * `docs/design/2026-10-08-secrets-keychain.md`.
14862
+ *
14863
+ * `callerAddonId` is deliberately NOT in any input schema: the tRPC router
14864
+ * parses the input, so a session can never supply it, and the internal mount
14865
+ * floors every method to admin anyway (D240).
14866
+ *
14867
+ * Internal: addons reach it through `ctx.secrets`, never directly.
14868
+ */
14869
+ /** Why a value cannot be served right now. Never folded into "missing". */
14870
+ var KeychainUnavailableReasonSchema = _enum([
14871
+ "key-missing",
14872
+ "wrong-key",
14873
+ "key-file-unreadable",
14874
+ "store-unavailable",
14875
+ "not-initialized",
14876
+ "decrypt-failed"
14877
+ ]);
14878
+ var KeychainStateSchema = discriminatedUnion("state", [object({ state: literal("ready") }), object({
14879
+ state: literal("locked"),
14880
+ reason: KeychainUnavailableReasonSchema
14881
+ })]);
14882
+ var KeychainResolveEntrySchema = discriminatedUnion("kind", [
14883
+ object({
14884
+ kind: literal("value"),
14885
+ value: string(),
14886
+ version: number().int()
14887
+ }),
14888
+ object({ kind: literal("missing") }),
14889
+ object({
14890
+ kind: literal("unavailable"),
14891
+ reason: KeychainUnavailableReasonSchema
14892
+ }),
14893
+ object({ kind: literal("forbidden") })
14894
+ ]);
14895
+ var KeychainResolveResultSchema = record(string(), KeychainResolveEntrySchema);
14896
+ /** Metadata of one stored value — never the value. */
14897
+ var KeychainSecretMetaSchema = object({
14898
+ ref: string(),
14899
+ owner: string(),
14900
+ /** Formatted scope (`global`, `node/<id>`, `device/<id>`, …). */
14901
+ scope: string(),
14902
+ fieldPath: string(),
14903
+ version: number().int(),
14904
+ createdAt: number(),
14905
+ updatedAt: number(),
14906
+ /** `addon:<id>` | `user:<id>` | `system`. */
14907
+ updatedBy: string(),
14908
+ /** Coarse — written at most once an hour per ref. `null` = never read. */
14909
+ lastReadAt: number().nullable()
14910
+ });
14911
+ var RefListSchema = array(string().min(1)).max(512);
14912
+ method(object({
14913
+ ref: string().min(1),
14914
+ value: string().min(1)
14915
+ }), object({
14916
+ ref: string(),
14917
+ version: number().int()
14918
+ }), {
14919
+ kind: "mutation",
14920
+ auth: "admin"
14921
+ }), method(object({ refs: RefListSchema }), KeychainResolveResultSchema, { auth: "admin" }), method(object({ refs: RefListSchema }), object({ deleted: number().int() }), {
14922
+ kind: "mutation",
14923
+ auth: "admin"
14924
+ }), method(object({}), array(KeychainSecretMetaSchema).readonly(), { auth: "admin" }), method(object({}), KeychainStateSchema, { auth: "admin" });
14925
+ var KeychainKeySourceSchema = object({
14926
+ kind: _enum([
14927
+ "config-file",
14928
+ "previous-config-file",
14929
+ "platform",
14930
+ "default-file"
14931
+ ]),
14932
+ /** File sources only — a path is not a secret. */
14933
+ path: string().optional(),
14934
+ /**
14935
+ * True when a whole-volume backup of the data directory carries this key
14936
+ * next to the database it protects (the default file). The page warns.
14937
+ */
14938
+ sharesBackupWithDatabase: boolean()
14939
+ });
14940
+ var KeychainStatusSchema = object({
14941
+ keychain: KeychainStateSchema,
14942
+ /** The source of the master key in use; `null` while locked. */
14943
+ keySource: KeychainKeySourceSchema.nullable(),
14944
+ /** The source configured to be primary — differs from `keySource` while a rotation is pending. */
14945
+ configuredSource: KeychainKeySourceSchema,
14946
+ /** Short fingerprint of the master key in use (`HMAC(KEK, label)`, 16 hex). */
14947
+ fingerprint: string().nullable(),
14948
+ activeKeyId: string().nullable(),
14949
+ /**
14950
+ * The keychain unlocked with a NON-primary source: the configured primary
14951
+ * key is not the one that wraps the data key yet. `rotateMasterKey` moves it.
14952
+ */
14953
+ rotationPending: boolean(),
14954
+ /** Wrapped copies of the data key under a previous master key, kept until purged. */
14955
+ retiredWraps: number().int(),
14956
+ recoveryKeyDownloadedAt: number().nullable(),
14957
+ secretCount: number().int()
14958
+ });
14959
+ /**
14960
+ * Whether a stored value is still pointed at by its owner's settings.
14961
+ * `unknown` is a first-class answer: a scope whose blob could not be read is
14962
+ * never reported as an orphan (and never deleted as one).
14963
+ */
14964
+ var KeychainSecretUsageSchema = _enum([
14965
+ "in-use",
14966
+ "orphan",
14967
+ "unknown"
14968
+ ]);
14969
+ var KeychainAdminSecretSchema = KeychainSecretMetaSchema.extend({ usage: KeychainSecretUsageSchema });
14970
+ var KeychainAuditActionSchema = _enum([
14971
+ "put",
14972
+ "delete",
14973
+ "reveal",
14974
+ "rotate-master-key",
14975
+ "purge-retired-keys",
14976
+ "download-recovery-key",
14977
+ "delete-orphans",
14978
+ "reset",
14979
+ "initialize"
14980
+ ]);
14981
+ var KeychainAuditEntrySchema = object({
14982
+ id: string(),
14983
+ at: number(),
14984
+ action: KeychainAuditActionSchema,
14985
+ /** `addon:<id>` | `user:<id>` | `system`. */
14986
+ actor: string(),
14987
+ ref: string().nullable(),
14988
+ detail: string().nullable()
14989
+ });
14990
+ 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({
14991
+ value: string(),
14992
+ version: number().int()
14993
+ }), {
14994
+ kind: "mutation",
14995
+ auth: "admin",
14996
+ caller: "required"
14997
+ }), method(object({ refs: array(string().min(1)).max(1e3) }), object({
14998
+ deleted: array(string()).readonly(),
14999
+ kept: array(object({
15000
+ ref: string(),
15001
+ usage: KeychainSecretUsageSchema
15002
+ })).readonly()
15003
+ }), {
15004
+ kind: "mutation",
15005
+ auth: "admin",
15006
+ caller: "required"
15007
+ }), method(object({}), object({
15008
+ fingerprint: string(),
15009
+ keySource: KeychainKeySourceSchema
15010
+ }), {
15011
+ kind: "mutation",
15012
+ auth: "admin",
15013
+ caller: "required"
15014
+ }), method(object({}), object({ purged: number().int() }), {
15015
+ kind: "mutation",
15016
+ auth: "admin",
15017
+ caller: "required"
15018
+ }), method(object({}), object({
15019
+ key: string(),
15020
+ fingerprint: string(),
15021
+ keySource: KeychainKeySourceSchema
15022
+ }), {
15023
+ kind: "mutation",
15024
+ auth: "admin",
15025
+ caller: "required"
15026
+ }), method(object({ confirm: literal("RESET KEYCHAIN") }), object({
15027
+ archivedCollection: string().nullable(),
15028
+ archived: number().int()
15029
+ }), {
15030
+ kind: "mutation",
15031
+ auth: "admin",
15032
+ caller: "required"
15033
+ });
14114
15034
  method(_void(), object({
14115
15035
  id: string(),
14116
15036
  name: string(),
@@ -15353,7 +16273,11 @@ var DeviceRegisterPayloadSchema = object({
15353
16273
  var DeviceRemovePayloadSchema = object({ deviceId: number() });
15354
16274
  var DevicePersistConfigPayloadSchema = object({
15355
16275
  deviceId: number(),
15356
- data: record(string(), unknown())
16276
+ data: record(string(), unknown()),
16277
+ /** The paths the device's schema declares secret (D783), when the caller
16278
+ * knows them — those values are kept in the keychain, not the blob (D787).
16279
+ * Absent: the paths the device last reported at `registerDevice` apply. */
16280
+ secretConfigPaths: array(string()).optional()
15357
16281
  });
15358
16282
  /** What a migration actually did, per switch. `unreachable` is a first-class
15359
16283
  * answer: a camera that could not be asked is not a camera that was silenced. */
@@ -22370,8 +23294,23 @@ var RetrainMacroClassSchema = _enum([
22370
23294
  ]);
22371
23295
  /** A subject to learn, or a phantom to unlearn (taught by OMISSION). */
22372
23296
  var RetrainAnnotationKindSchema = _enum(["subject", "model_error"]);
22373
- /** Did a human draw this box, or did the assist propose it? */
22374
- var RetrainAnnotationSourceSchema = _enum(["operator", "assist"]);
23297
+ /**
23298
+ * Where a box came from. A machine-sourced box is a DRAFT on the page until
23299
+ * the operator confirms it; once saved it keeps its source as provenance.
23300
+ *
23301
+ * - `operator` — drawn by hand.
23302
+ * - `assist` — proposed by a detector run on the copy (the camera's own
23303
+ * model, or a larger teacher model).
23304
+ * - `pipeline` — the box the live pipeline actually drew on that frame, read
23305
+ * back from the track store (never a re-run).
23306
+ * - `llm` — proposed by a vision-capable LLM profile.
23307
+ */
23308
+ var RetrainAnnotationSourceSchema = _enum([
23309
+ "operator",
23310
+ "assist",
23311
+ "pipeline",
23312
+ "llm"
23313
+ ]);
22375
23314
  /** Normalised `[0,1]` rectangle against the FULL frame — the canonical form. */
22376
23315
  var RetrainBboxSchema = object({
22377
23316
  x: number(),
@@ -22389,7 +23328,8 @@ var RetrainBboxSchema = object({
22389
23328
  */
22390
23329
  var RetrainAnnotationSchema = object({
22391
23330
  id: string(),
22392
- trackId: string(),
23331
+ /** The frame's track. Absent on a recording still, which has none. */
23332
+ trackId: string().optional(),
22393
23333
  deviceId: number(),
22394
23334
  /** The COPY in retrain storage — never the source track's media key. */
22395
23335
  mediaKey: string(),
@@ -22438,13 +23378,47 @@ var RetrainFrameCandidateSchema = object({
22438
23378
  * fail, whatever became of the original. */
22439
23379
  copied: boolean()
22440
23380
  });
23381
+ /**
23382
+ * One box the live pipeline drew on a copied frame — what a correction starts
23383
+ * from. Derived when the frame is listed, from the track store: the subject
23384
+ * box recorded on the source media row when there is one, else the track
23385
+ * position nearest the frame's capture time. Never stored as an annotation
23386
+ * until the operator confirms it.
23387
+ */
23388
+ var RetrainPipelineBoxSchema = object({
23389
+ /** Normalised `[0,1]` against the full frame. */
23390
+ bbox: RetrainBboxSchema,
23391
+ macroClass: RetrainMacroClassSchema,
23392
+ label: string().optional(),
23393
+ subLabel: string().optional(),
23394
+ /** The detection score of the position used, when it was recorded. */
23395
+ score: number().optional(),
23396
+ /** The root model that produced the track, when it was recorded. */
23397
+ modelId: string().optional(),
23398
+ trackId: string(),
23399
+ /** `subject-box`: recorded on this very frame. `position`: the track's
23400
+ * position nearest the capture time, `deltaMs` away. */
23401
+ basis: _enum(["subject-box", "position"]),
23402
+ deltaMs: number()
23403
+ });
23404
+ /**
23405
+ * Where a retrain frame came from: a TRACK's stored media (copy-on-select),
23406
+ * or the RECORDING at an instant — the frame a model saw nothing in has no
23407
+ * track at all.
23408
+ */
23409
+ var RetrainFrameOriginSchema = _enum(["track", "recording"]);
22441
23410
  /** A frame the dataset OWNS: bytes copied at selection time. */
22442
23411
  var RetrainFrameSchema = object({
22443
23412
  frameId: string(),
22444
23413
  deviceId: number(),
22445
- trackId: string(),
22446
- /** Provenance only. It may already point at nothing — that is expected. */
22447
- sourceMediaId: number().int(),
23414
+ origin: RetrainFrameOriginSchema,
23415
+ /** The track it was copied from. Absent on a recording still. */
23416
+ trackId: string().optional(),
23417
+ /** Provenance only. It may already point at nothing — that is expected.
23418
+ * Absent on a recording still. */
23419
+ sourceMediaId: number().int().optional(),
23420
+ /** A recording still: the playhead instant it was taken at. */
23421
+ epochMs: number().optional(),
22448
23422
  sourceKind: MediaFileKindEnum,
22449
23423
  sizeBytes: number().int(),
22450
23424
  width: number().int(),
@@ -22455,7 +23429,12 @@ var RetrainFrameSchema = object({
22455
23429
  /** The operator's "every subject in this frame is boxed". Detector
22456
23430
  * evaluation keeps only complete frames: an unboxed subject would count as
22457
23431
  * a false positive. */
22458
- complete: boolean()
23432
+ complete: boolean(),
23433
+ /** The boxes the pipeline drew on this frame. Present on list answers;
23434
+ * empty when nothing the track store holds can be placed on it. */
23435
+ pipelineBoxes: array(RetrainPipelineBoxSchema).readonly().optional(),
23436
+ /** The named collections this frame belongs to. Present on list answers. */
23437
+ collectionIds: array(string()).readonly().optional()
22459
23438
  });
22460
23439
  /** Why a copy-on-select could not be honoured — named, never a silent skip. */
22461
23440
  var RetrainCopyRefusalSchema = _enum([
@@ -22486,6 +23465,8 @@ var RetrainFrameListSchema = object({
22486
23465
  var RetrainExportFilterSchema = object({
22487
23466
  deviceIds: array(number()).optional(),
22488
23467
  frameIds: array(string()).max(2e4).optional(),
23468
+ /** Only frames in at least one of these named collections. */
23469
+ collectionIds: array(string()).max(200).optional(),
22489
23470
  batchId: string().optional(),
22490
23471
  /** Only frames the operator marked complete (all subjects boxed). */
22491
23472
  completeOnly: boolean().optional()
@@ -22550,6 +23531,109 @@ var RetrainAssistResultSchema = discriminatedUnion("kind", [object({
22550
23531
  reason: string(),
22551
23532
  detail: string().optional()
22552
23533
  })]);
23534
+ /** A named set over the retrain corpus — membership only, it owns no pixels. */
23535
+ var RetrainCollectionSchema = object({
23536
+ id: string(),
23537
+ name: string(),
23538
+ createdAt: number(),
23539
+ frameCount: number().int()
23540
+ });
23541
+ var RetrainCollectionCreateResultSchema = discriminatedUnion("kind", [object({
23542
+ kind: literal("created"),
23543
+ collection: RetrainCollectionSchema
23544
+ }), object({
23545
+ kind: literal("refused"),
23546
+ reason: _enum(["empty-name", "duplicate-name"])
23547
+ })]);
23548
+ var RetrainCollectionRenameResultSchema = discriminatedUnion("kind", [object({
23549
+ kind: literal("renamed"),
23550
+ collection: RetrainCollectionSchema
23551
+ }), object({
23552
+ kind: literal("refused"),
23553
+ reason: _enum([
23554
+ "empty-name",
23555
+ "duplicate-name",
23556
+ "unknown-collection"
23557
+ ])
23558
+ })]);
23559
+ /**
23560
+ * The outcome of adding the frame at a recording instant. Every refusal is
23561
+ * named: `still-unavailable` (not recording, a gap, or an undecodable frame —
23562
+ * `detail` says which), `still-busy` (the recorder is at its decode bound; try
23563
+ * again), `unreadable-image`, `write-failed`, `unknown-collection`.
23564
+ */
23565
+ var AddRetrainFrameFromRecordingResultSchema = discriminatedUnion("kind", [object({
23566
+ kind: literal("added"),
23567
+ collectionId: string(),
23568
+ frame: RetrainFrameSchema,
23569
+ /** The moment was already in the dataset; nothing was decoded. */
23570
+ reused: boolean()
23571
+ }), object({
23572
+ kind: literal("refused"),
23573
+ reason: _enum([
23574
+ "unknown-collection",
23575
+ "still-unavailable",
23576
+ "still-busy",
23577
+ "unreadable-image",
23578
+ "write-failed"
23579
+ ]),
23580
+ detail: string().optional()
23581
+ })]);
23582
+ /** A vision LLM profile the AI assist may use, and where it sends the frame. */
23583
+ var RetrainAssistProfileSchema = object({
23584
+ id: string(),
23585
+ name: string(),
23586
+ model: string(),
23587
+ kind: string(),
23588
+ /** `true` when the frame would leave the house (a cloud vendor, or an
23589
+ * endpoint that is not on the local network). The page confirms each such
23590
+ * run, and the provider refuses one without `allowCloud`. */
23591
+ leavesHouse: boolean()
23592
+ });
23593
+ /** A box the AI assist proposed: a draft, plus the model's own reason. */
23594
+ var RetrainLlmProposalSchema = RetrainAnnotationDraftSchema.extend({ reason: string() });
23595
+ /** What the AI assist said about a box that was already on the canvas. */
23596
+ var RetrainLlmReviewSchema = object({
23597
+ /** The `ref` the page sent the box under. */
23598
+ ref: string(),
23599
+ verdict: _enum([
23600
+ "confirmed",
23601
+ "wrong-class",
23602
+ "not-an-object",
23603
+ "uncertain"
23604
+ ]),
23605
+ suggestedClass: RetrainMacroClassSchema.optional(),
23606
+ reason: string()
23607
+ });
23608
+ /**
23609
+ * The AI assist's answer. `proposed` carries drafts (`source: 'llm'`, the
23610
+ * model and its confidence) and reviews; items the model got wrong (a box off
23611
+ * the frame, an unasked class, an unknown ref) are dropped and counted in
23612
+ * `rejected`. A whole answer that is not the schema is `malformed-answer`.
23613
+ */
23614
+ var RetrainLlmAssistResultSchema = discriminatedUnion("kind", [object({
23615
+ kind: literal("proposed"),
23616
+ profileId: string(),
23617
+ model: string(),
23618
+ /** The frame was sent outside the house for this answer. */
23619
+ leftHouse: boolean(),
23620
+ proposals: array(RetrainLlmProposalSchema).readonly(),
23621
+ reviews: array(RetrainLlmReviewSchema).readonly(),
23622
+ rejected: number().int()
23623
+ }), object({
23624
+ kind: literal("refused"),
23625
+ reason: _enum([
23626
+ "unknown-frame",
23627
+ "unreadable-frame",
23628
+ "unknown-profile",
23629
+ "profile-disabled",
23630
+ "no-vision",
23631
+ "cloud-not-confirmed",
23632
+ "llm-error",
23633
+ "malformed-answer"
23634
+ ]),
23635
+ detail: string().optional()
23636
+ })]);
22553
23637
  /** The outcome of a lifecycle move owned by the retrain page. */
22554
23638
  var RetrainTransitionResultSchema = object({
22555
23639
  trackId: string(),
@@ -23267,7 +24351,7 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
23267
24351
  auth: "admin"
23268
24352
  }), method(object({
23269
24353
  deviceId: number(),
23270
- trackId: string(),
24354
+ trackId: string().optional(),
23271
24355
  frameId: string()
23272
24356
  }), object({
23273
24357
  removed: boolean(),
@@ -23284,7 +24368,8 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
23284
24368
  auth: "admin"
23285
24369
  }), method(object({
23286
24370
  deviceId: number(),
23287
- trackId: string(),
24371
+ /** The frame's track, when it has one — checked against the frame. */
24372
+ trackId: string().optional(),
23288
24373
  frameId: string(),
23289
24374
  subject: RetrainAssistSubjectSchema,
23290
24375
  /** Which node runs it. Absent ⇒ wherever an unowned call lands. */
@@ -23292,12 +24377,16 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
23292
24377
  }), RetrainAssistResultSchema, {
23293
24378
  kind: "mutation",
23294
24379
  auth: "admin"
23295
- }), method(object({ trackId: string() }), array(RetrainAnnotationSchema).readonly(), {
24380
+ }), method(object({
24381
+ trackId: string().optional(),
24382
+ frameIds: array(string()).max(2e3).optional()
24383
+ }), array(RetrainAnnotationSchema).readonly(), {
23296
24384
  kind: "query",
23297
24385
  auth: "admin"
23298
24386
  }), method(object({
23299
24387
  deviceId: number(),
23300
- trackId: string(),
24388
+ /** The frame's track, when it has one — checked against the frame. */
24389
+ trackId: string().optional(),
23301
24390
  frameId: string(),
23302
24391
  annotations: array(RetrainAnnotationDraftSchema)
23303
24392
  }), array(RetrainAnnotationSchema).readonly(), {
@@ -23320,7 +24409,7 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
23320
24409
  auth: "admin"
23321
24410
  }), method(object({
23322
24411
  deviceId: number(),
23323
- trackId: string(),
24412
+ trackId: string().optional(),
23324
24413
  frameId: string(),
23325
24414
  complete: boolean()
23326
24415
  }), RetrainFrameSchema, {
@@ -23334,6 +24423,74 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
23334
24423
  kind: "mutation",
23335
24424
  auth: "admin",
23336
24425
  timeoutMs: 60 * 6e4
24426
+ }), method(object({}), array(RetrainAssistProfileSchema).readonly(), {
24427
+ kind: "query",
24428
+ auth: "admin"
24429
+ }), method(object({
24430
+ deviceId: number(),
24431
+ trackId: string().optional(),
24432
+ frameId: string(),
24433
+ profileId: string(),
24434
+ classes: array(RetrainMacroClassSchema).min(1),
24435
+ boxes: array(object({
24436
+ ref: string(),
24437
+ bbox: RetrainBboxSchema,
24438
+ macroClass: RetrainMacroClassSchema,
24439
+ label: string().optional()
24440
+ })).max(50),
24441
+ allowCloud: boolean()
24442
+ }), RetrainLlmAssistResultSchema, {
24443
+ kind: "mutation",
24444
+ auth: "admin",
24445
+ timeoutMs: 18e4
24446
+ }), method(object({ name: string().max(120) }), RetrainCollectionCreateResultSchema, {
24447
+ kind: "mutation",
24448
+ auth: "admin"
24449
+ }), method(object({}), array(RetrainCollectionSchema).readonly(), {
24450
+ kind: "query",
24451
+ auth: "admin"
24452
+ }), method(object({
24453
+ id: string(),
24454
+ name: string().max(120)
24455
+ }), RetrainCollectionRenameResultSchema, {
24456
+ kind: "mutation",
24457
+ auth: "admin"
24458
+ }), method(object({ id: string() }), object({
24459
+ deleted: boolean(),
24460
+ removedFrames: number().int()
24461
+ }), {
24462
+ kind: "mutation",
24463
+ auth: "admin"
24464
+ }), method(object({
24465
+ collectionId: string(),
24466
+ deviceId: number(),
24467
+ epochMs: number()
24468
+ }), AddRetrainFrameFromRecordingResultSchema, {
24469
+ kind: "mutation",
24470
+ auth: "admin",
24471
+ timeoutMs: 6e4
24472
+ }), method(object({
24473
+ collectionId: string(),
24474
+ frameIds: array(string()).min(1).max(500)
24475
+ }), object({
24476
+ added: number().int(),
24477
+ alreadyMember: number().int(),
24478
+ unknownFrameIds: array(string()).readonly()
24479
+ }), {
24480
+ kind: "mutation",
24481
+ auth: "admin"
24482
+ }), method(object({
24483
+ collectionId: string(),
24484
+ frameId: string()
24485
+ }), object({
24486
+ removed: boolean(),
24487
+ deletedFrame: boolean()
24488
+ }), {
24489
+ kind: "mutation",
24490
+ auth: "admin"
24491
+ }), method(object({ collectionId: string() }), array(RetrainFrameSchema).readonly(), {
24492
+ kind: "query",
24493
+ auth: "admin"
23337
24494
  }), method(object({
23338
24495
  /** Which of the three event tables owns the row. */
23339
24496
  ownerType: EventOwnerTypeSchema,
@@ -23957,13 +25114,31 @@ var RecommendationReasonSchema = discriminatedUnion("kind", [
23957
25114
  object({
23958
25115
  kind: literal("no-family-build"),
23959
25116
  format: ModelFormatSchema$1
25117
+ }),
25118
+ object({
25119
+ kind: literal("kept-custom-pin"),
25120
+ modelId: string(),
25121
+ deviceKey: string()
23960
25122
  })
23961
25123
  ]);
25124
+ /** Why a device is left exactly as it is, whatever the plan would pick (D786). */
25125
+ var KeptReasonSchema = _enum(["custom-pin"]);
25126
+ /**
25127
+ * Where a choice's latency came from (D791): this node's own benchmark
25128
+ * result, or the hardware-class table. Measured on the node beats the table.
25129
+ */
25130
+ var LatencySourceSchema = discriminatedUnion("kind", [object({ kind: literal("table") }), object({
25131
+ kind: literal("node-benchmark"),
25132
+ resultId: string(),
25133
+ measuredAtMs: number()
25134
+ })]);
23962
25135
  var DeviceModelChoiceSchema = object({
23963
25136
  modelId: string(),
23964
25137
  p50Ms: number(),
23965
25138
  fps: number(),
23966
25139
  measured: boolean(),
25140
+ /** Absent on a plan from before D791 — read as the table. */
25141
+ source: LatencySourceSchema.optional(),
23967
25142
  /** Parallel sessions at the camera rate with the headroom kept free: ⌊fps × (1 − headroom) / camera fps⌋. */
23968
25143
  capacitySessions: number(),
23969
25144
  personRecall: number()
@@ -23974,6 +25149,8 @@ var DeviceRecommendationSchema = object({
23974
25149
  enabled: boolean(),
23975
25150
  available: boolean(),
23976
25151
  chosen: DeviceModelChoiceSchema.nullable(),
25152
+ /** Present when the device is kept as is: Apply writes nothing on it. */
25153
+ kept: KeptReasonSchema.optional(),
23977
25154
  reasons: array(RecommendationReasonSchema).readonly()
23978
25155
  });
23979
25156
  var NodeRecommendationSchema = object({
@@ -24027,6 +25204,17 @@ var AutoTuneWarningSchema = discriminatedUnion("kind", [
24027
25204
  kind: literal("coral-enabled"),
24028
25205
  nodeId: string(),
24029
25206
  deviceKey: string()
25207
+ }),
25208
+ object({
25209
+ kind: literal("custom-pin-kept"),
25210
+ nodeId: string(),
25211
+ deviceKey: string().nullable(),
25212
+ deviceId: number().nullable(),
25213
+ modelId: string()
25214
+ }),
25215
+ object({
25216
+ kind: literal("custom-registry-unreadable"),
25217
+ error: string()
24030
25218
  })
24031
25219
  ]);
24032
25220
  var AutoTuneOptionsSchema = object({
@@ -24205,13 +25393,14 @@ var SuggestSharesResultSchema = object({
24205
25393
  nodes: array(SuggestedNodeShareSchema).readonly()
24206
25394
  });
24207
25395
  /**
24208
- * Where the node and device shares come from (D750, D755).
24209
- * - `hardware` (default) — computed by the system from each node's static
24210
- * capacity (its accelerators at their Auto tune models, from the measured
24211
- * latency table), recomputed whenever a node or device joins, leaves, is
24212
- * switched on or off, or changes model. No load input.
24213
- * - `benchmark` — the same, from each node's measured capacity (node
24214
- * benchmark results); a node without results falls back to `hardware`.
25396
+ * Where the node and device shares come from (D750, D755, D791).
25397
+ * - `benchmark` (default since D791) — each node's capacity as its own node
25398
+ * benchmark measured it; a node without fresh results is sized from
25399
+ * `hardware` and says so. Measured on the node beats the table.
25400
+ * - `hardware` — computed from each node's static capacity only (its
25401
+ * accelerators at their Auto tune models, from the latency table).
25402
+ * Both are recomputed whenever a node or device joins, leaves, is switched
25403
+ * on or off, changes model, or a benchmark result is written. No load input.
24215
25404
  * - `manual` — the operator's stored sliders.
24216
25405
  * Either way a node or device that cannot take sessions gives its share to
24217
25406
  * the others in proportion; the stored values are never rewritten for that.
@@ -24260,6 +25449,362 @@ var EffectiveSharesSchema = object({
24260
25449
  nodeWeights: record(string(), number()),
24261
25450
  deviceWeights: record(string(), record(string(), number()))
24262
25451
  });
25452
+ /**
25453
+ * Wire shapes of the node benchmark (D791): the operator's plan, the
25454
+ * preflight the confirmation shows, the run the orchestrator owns, what the
25455
+ * measuring runner reports, and the result rows Auto tune and the automatic
25456
+ * shares read.
25457
+ *
25458
+ * ONE node at a time, owned by the pipeline orchestrator. While a run is
25459
+ * active the cluster is in BENCHMARK MODE for that node: it is not a
25460
+ * detection candidate, camera pins naming it are ignored so its sessions move
25461
+ * elsewhere, and both come back when the mode ends — after a crash or a hub
25462
+ * restart too (a persisted manifest, reconciled against the registry).
25463
+ *
25464
+ * Two measurements, both on the node, driven by its own runner (frames never
25465
+ * cross a process at frame rate, D9):
25466
+ * - `device` — one accelerator × one candidate detector, root only, open
25467
+ * loop: how many streams at the camera rate it carries inside the frame
25468
+ * interval;
25469
+ * - `pipeline` — the chosen detector plus the operator's detail steps
25470
+ * (faces, plates, classifiers, CLIP…), on varied frames from the bench
25471
+ * clip: how many parallel sessions the node carries before latency, drops,
25472
+ * CPU, RAM or the event loop give out.
25473
+ */
25474
+ /** Defaults and bounds, one place. */
25475
+ var NODE_BENCHMARK_DEFAULTS = {
25476
+ fpsPerStream: 10,
25477
+ budgetMinutes: 45,
25478
+ minBudgetMinutes: 10,
25479
+ maxBudgetMinutes: 120,
25480
+ /** A result older than this no longer beats the table. */
25481
+ staleAfterDays: 30,
25482
+ /** Warm-in per ramp step (not accounted). */
25483
+ settleSec: 5,
25484
+ /** Accounted window per ramp step. */
25485
+ measureSec: 20,
25486
+ /** Longest the drain may take before the run is refused. */
25487
+ drainTimeoutSec: 120,
25488
+ /** Candidate models per device in one run. */
25489
+ maxModelsPerDevice: 6
25490
+ };
25491
+ /** The two measurements a run can make. */
25492
+ var NodeBenchmarkPhaseSchema = _enum(["device", "pipeline"]);
25493
+ var NodeBenchmarkDevicePlanSchema = object({
25494
+ /** `<backend>:<device>` — `openvino:npu`, `coreml:all`, `cpu`. */
25495
+ deviceKey: string().min(1),
25496
+ /**
25497
+ * Root detector candidates for the `device` measurement, in the order
25498
+ * measured. The FIRST is the one the `pipeline` measurement runs.
25499
+ */
25500
+ modelIds: array(string().min(1)).min(1).max(NODE_BENCHMARK_DEFAULTS.maxModelsPerDevice)
25501
+ });
25502
+ /** What the operator confirmed. */
25503
+ var NodeBenchmarkPlanSchema = object({
25504
+ nodeId: string().min(1),
25505
+ devices: array(NodeBenchmarkDevicePlanSchema).min(1),
25506
+ /** Which measurements run. At least one. */
25507
+ phases: array(NodeBenchmarkPhaseSchema).min(1).default(["device", "pipeline"]),
25508
+ /**
25509
+ * Detail steps (catalog step ids under the root: faces, plates,
25510
+ * classifiers, CLIP…) the `pipeline` measurement enables. The root
25511
+ * detector always runs.
25512
+ */
25513
+ steps: array(string().min(1)).default([]),
25514
+ /** Offered rate of one stream / session. */
25515
+ fpsPerStream: number().int().min(1).max(30).default(NODE_BENCHMARK_DEFAULTS.fpsPerStream),
25516
+ /** Hard deadline: the mode ends and the cluster is restored when it passes. */
25517
+ budgetMinutes: number().int().min(NODE_BENCHMARK_DEFAULTS.minBudgetMinutes).max(NODE_BENCHMARK_DEFAULTS.maxBudgetMinutes).default(NODE_BENCHMARK_DEFAULTS.budgetMinutes),
25518
+ /** Keep the models the run downloaded (default: delete what was not installed before). */
25519
+ keepDownloadedModels: boolean().default(false),
25520
+ /** Start although the other nodes' capacity does not cover the sessions running now. */
25521
+ acceptInsufficientHeadroom: boolean().default(false)
25522
+ });
25523
+ var NodeBenchmarkRefusalSchema = object({
25524
+ kind: _enum([
25525
+ "benchmark-active",
25526
+ "node-offline",
25527
+ "unknown-device",
25528
+ "no-phase",
25529
+ "insufficient-headroom"
25530
+ ]),
25531
+ detail: string(),
25532
+ overridable: boolean()
25533
+ });
25534
+ /** A camera whose detection leaves the node for the run. */
25535
+ var NodeBenchmarkMovingCameraSchema = object({
25536
+ deviceId: number(),
25537
+ /** Placed on the node now (a standing attach or a running session). */
25538
+ placedOnNode: boolean(),
25539
+ /** A node pin naming this node, ignored for the run. */
25540
+ pinnedToNode: boolean()
25541
+ });
25542
+ /** A camera that cannot leave: no other node can obtain its frames. */
25543
+ var NodeBenchmarkStayingCameraSchema = object({
25544
+ deviceId: number(),
25545
+ reason: literal("only-frame-source")
25546
+ });
25547
+ var NodeBenchmarkPreflightSchema = object({
25548
+ nodeId: string(),
25549
+ online: boolean(),
25550
+ moving: array(NodeBenchmarkMovingCameraSchema).readonly(),
25551
+ /** Keep running on the node during the run; the result is flagged contaminated. */
25552
+ staying: array(NodeBenchmarkStayingCameraSchema).readonly(),
25553
+ estimatedDurationMs: number(),
25554
+ /** The run ends and the cluster is restored at the latest after this long. */
25555
+ budgetMs: number(),
25556
+ phases: array(NodeBenchmarkPhaseSchema).readonly(),
25557
+ steps: array(string()).readonly(),
25558
+ devices: array(NodeBenchmarkDevicePlanSchema).readonly(),
25559
+ /** Parallel sessions the cluster runs now, and what the other nodes can carry. */
25560
+ headroom: object({
25561
+ sessionsNow: number(),
25562
+ otherNodesCapacitySessions: number().nullable()
25563
+ }),
25564
+ refusals: array(NodeBenchmarkRefusalSchema).readonly(),
25565
+ canStart: boolean()
25566
+ });
25567
+ /** Where the measuring runner is. */
25568
+ var NodeBenchProgressSchema = object({
25569
+ phase: _enum([
25570
+ "preparing",
25571
+ "device",
25572
+ "pipeline",
25573
+ "cleanup"
25574
+ ]),
25575
+ deviceKey: string().nullable(),
25576
+ modelId: string().nullable(),
25577
+ /** Streams (device) or sessions (pipeline) of the step running now. */
25578
+ load: number().nullable(),
25579
+ cellsDone: number(),
25580
+ cellsTotal: number(),
25581
+ message: string()
25582
+ });
25583
+ /** What limited a ramp. `none` = the ramp ran out of steps still passing. */
25584
+ var NodeBenchLimitSchema = _enum([
25585
+ "p95",
25586
+ "drops",
25587
+ "errors",
25588
+ "stall",
25589
+ "cpu",
25590
+ "ram",
25591
+ "none"
25592
+ ]);
25593
+ var NodeBenchRampStepSchema = object({
25594
+ load: number(),
25595
+ pass: boolean(),
25596
+ p95Ms: number(),
25597
+ dropRatio: number(),
25598
+ /** Completed frames per second over the accounted window. */
25599
+ fps: number(),
25600
+ cpuPct: number().nullable(),
25601
+ ramFreePct: number().nullable(),
25602
+ failReasons: array(string()).readonly()
25603
+ });
25604
+ var NodeBenchCellSchema = discriminatedUnion("phase", [object({
25605
+ phase: literal("device"),
25606
+ deviceKey: string(),
25607
+ modelId: string(),
25608
+ /** Single-stream latency (the K = 1 step). */
25609
+ p50Ms: number(),
25610
+ p95Ms: number(),
25611
+ p99Ms: number(),
25612
+ /** Frames per second sustained at the last passing step. */
25613
+ fps: number(),
25614
+ /** Streams at the camera rate the device carried inside the frame interval; 0 = not even one. */
25615
+ kMax: number(),
25616
+ limitedBy: NodeBenchLimitSchema,
25617
+ /** First call (model load + warm-up). */
25618
+ warmupMs: number(),
25619
+ ramp: array(NodeBenchRampStepSchema).readonly()
25620
+ }), object({
25621
+ phase: literal("pipeline"),
25622
+ deviceKey: string(),
25623
+ modelId: string(),
25624
+ steps: array(string()).readonly(),
25625
+ /** Parallel sessions at the camera rate the node carried; 0 = not even one. */
25626
+ maxSessions: number(),
25627
+ limitedBy: NodeBenchLimitSchema,
25628
+ /** Detail steps that produced at least one result on the clip — a step that never fired measured nothing. */
25629
+ stepsFired: array(string()).readonly(),
25630
+ warmupMs: number(),
25631
+ ramp: array(NodeBenchRampStepSchema).readonly()
25632
+ })]);
25633
+ /**
25634
+ * What a result was measured ON. A result whose fingerprint no longer matches
25635
+ * the node no longer beats the table.
25636
+ */
25637
+ var NodeBenchFingerprintSchema = object({
25638
+ pipelineVersion: string().nullable(),
25639
+ cpuModel: string().nullable(),
25640
+ ramGb: number().nullable(),
25641
+ os: string().nullable(),
25642
+ /** Per device: the pool the cells ran on (runtime + tuning). */
25643
+ pools: record(string(), object({
25644
+ runtime: string(),
25645
+ numWorkers: number(),
25646
+ concurrency: number(),
25647
+ batchMode: string()
25648
+ })).default({})
25649
+ });
25650
+ /** The frames the run used. */
25651
+ var NodeBenchClipSchema = object({
25652
+ /** `camstack-bench-v1` or `reference-images` (the fallback when the clip is not reachable). */
25653
+ id: string(),
25654
+ revision: string().nullable(),
25655
+ frames: number(),
25656
+ width: number(),
25657
+ height: number()
25658
+ });
25659
+ var NodeBenchRunnerInputSchema = object({
25660
+ runId: string().min(1),
25661
+ devices: array(NodeBenchmarkDevicePlanSchema).min(1),
25662
+ phases: array(NodeBenchmarkPhaseSchema).min(1),
25663
+ /** The full detail step tree root for the `pipeline` measurement is built on the node from these ids. */
25664
+ steps: array(string()).default([]),
25665
+ fpsPerStream: number().int().min(1).max(30),
25666
+ /** The runner stops on its own past this instant, whatever the hub does. */
25667
+ deadlineAtMs: number(),
25668
+ settleSec: number().min(0).max(60).default(NODE_BENCHMARK_DEFAULTS.settleSec),
25669
+ measureSec: number().min(2).max(300).default(NODE_BENCHMARK_DEFAULTS.measureSec),
25670
+ keepDownloadedModels: boolean().default(false)
25671
+ });
25672
+ var NodeBenchRunnerStateSchema = _enum([
25673
+ "running",
25674
+ "done",
25675
+ "failed",
25676
+ "aborted"
25677
+ ]);
25678
+ var NodeBenchRunnerStatusSchema = object({
25679
+ runId: string(),
25680
+ nodeId: string(),
25681
+ state: NodeBenchRunnerStateSchema,
25682
+ progress: NodeBenchProgressSchema.nullable(),
25683
+ /** Every finished cell so far — a run stopped half way keeps what it measured. */
25684
+ cells: array(NodeBenchCellSchema).readonly(),
25685
+ fingerprint: NodeBenchFingerprintSchema.nullable(),
25686
+ clip: NodeBenchClipSchema.nullable(),
25687
+ /** Cameras seen running on the node during the run (they share its pools). */
25688
+ activeCameraIds: array(number()).readonly(),
25689
+ /** Models the run downloaded and then deleted (not installed before). */
25690
+ deletedModels: array(string()).readonly(),
25691
+ error: string().nullable(),
25692
+ startedAtMs: number(),
25693
+ finishedAtMs: number().nullable()
25694
+ });
25695
+ var NodeBenchmarkStateSchema = _enum([
25696
+ "draining",
25697
+ "measuring",
25698
+ "restoring",
25699
+ "done",
25700
+ "failed",
25701
+ "aborted"
25702
+ ]);
25703
+ /** Why a run ended. */
25704
+ var NodeBenchmarkEndReasonSchema = _enum([
25705
+ "completed",
25706
+ "operator-abort",
25707
+ "deadline",
25708
+ "node-lost",
25709
+ "runner-lost",
25710
+ "hub-restart",
25711
+ "drain-timeout",
25712
+ "failed"
25713
+ ]);
25714
+ var NodeBenchmarkRunSchema = object({
25715
+ runId: string(),
25716
+ nodeId: string(),
25717
+ state: NodeBenchmarkStateSchema,
25718
+ plan: NodeBenchmarkPlanSchema,
25719
+ startedAtMs: number(),
25720
+ deadlineAtMs: number(),
25721
+ finishedAtMs: number().nullable(),
25722
+ endReason: NodeBenchmarkEndReasonSchema.nullable(),
25723
+ error: string().nullable(),
25724
+ /** Cameras moved off the node for the run. */
25725
+ moved: array(number()).readonly(),
25726
+ /** Cameras that stayed (their only frame source is the node). */
25727
+ staying: array(number()).readonly(),
25728
+ /** Something else ran on the node's pools during the run. */
25729
+ contaminated: boolean(),
25730
+ progress: NodeBenchProgressSchema.nullable(),
25731
+ resultIds: array(string()).readonly()
25732
+ });
25733
+ /** `getNodeBenchmarkStatus`: the active run (or the last one), and whether benchmark mode is on. */
25734
+ var NodeBenchmarkStatusSchema = object({
25735
+ /** The node the cluster is in benchmark mode for; null = none. */
25736
+ modeNodeId: string().nullable(),
25737
+ run: NodeBenchmarkRunSchema.nullable()
25738
+ });
25739
+ /**
25740
+ * One stored measurement — the only authority Auto tune and the automatic
25741
+ * shares read measured capacity from. Written by the orchestrator when a run
25742
+ * ends, never by anyone else.
25743
+ */
25744
+ var NodeBenchmarkResultSchema = object({
25745
+ id: string(),
25746
+ runId: string(),
25747
+ nodeId: string(),
25748
+ cell: NodeBenchCellSchema,
25749
+ fpsPerStream: number(),
25750
+ fingerprint: NodeBenchFingerprintSchema.nullable(),
25751
+ clip: NodeBenchClipSchema.nullable(),
25752
+ /** Other work shared the node's pools (a camera that could not move, or the hub's own duties). */
25753
+ contaminated: boolean(),
25754
+ stayingCameras: array(number()).readonly(),
25755
+ /** The run ended early; the cell itself completed. */
25756
+ partialRun: boolean(),
25757
+ measuredAtMs: number()
25758
+ });
25759
+ var ListNodeBenchmarkResultsInputSchema = object({
25760
+ nodeId: string().optional(),
25761
+ deviceKey: string().optional()
25762
+ });
25763
+ /** A result with its standing today: does it still beat the table? */
25764
+ var NodeBenchmarkResultViewSchema = NodeBenchmarkResultSchema.extend({
25765
+ /** `fresh` beats the table; `stale` falls back to it; `superseded` = a newer row covers the same cell. */
25766
+ standing: _enum([
25767
+ "fresh",
25768
+ "stale",
25769
+ "superseded"
25770
+ ]),
25771
+ staleWhy: _enum([
25772
+ "age",
25773
+ "runtime",
25774
+ "pool-tuning"
25775
+ ]).nullable()
25776
+ });
25777
+ object({
25778
+ runId: string(),
25779
+ nodeId: string(),
25780
+ startedAtMs: number(),
25781
+ deadlineAtMs: number(),
25782
+ plan: NodeBenchmarkPlanSchema,
25783
+ moved: array(number()).readonly(),
25784
+ staying: array(number()).readonly()
25785
+ });
25786
+ /** Candidate detectors per device, for the plan editor. */
25787
+ var NodeBenchmarkCandidatesSchema = object({
25788
+ nodeId: string(),
25789
+ reachable: boolean(),
25790
+ devices: array(object({
25791
+ deviceKey: string(),
25792
+ enabled: boolean(),
25793
+ available: boolean(),
25794
+ /** Ordered: what Auto tune would pick first, then the rest of the family by accuracy. */
25795
+ suggested: array(string()).readonly(),
25796
+ /** Every root detector the device has a build for. */
25797
+ all: array(string()).readonly(),
25798
+ /** The model the device runs now, when pinned. */
25799
+ currentModelId: string().nullable()
25800
+ })).readonly(),
25801
+ /** Detail steps the node's catalog offers under the root (for the `pipeline` measurement). */
25802
+ steps: array(object({
25803
+ id: string(),
25804
+ name: string(),
25805
+ slot: string()
25806
+ })).readonly()
25807
+ });
24263
25808
  object({
24264
25809
  activeCameras: number(),
24265
25810
  throttledCameras: number(),
@@ -25388,7 +26933,16 @@ method(RunnerCameraConfigSchema, object({ success: literal(true) }), { kind: "mu
25388
26933
  }), ParkedTrackFrameSchema.nullable()), method(object({
25389
26934
  deviceId: number(),
25390
26935
  trackId: string()
25391
- }), object({ released: number().int().nonnegative() }), { kind: "mutation" });
26936
+ }), object({ released: number().int().nonnegative() }), { kind: "mutation" }), method(NodeBenchRunnerInputSchema, object({
26937
+ accepted: literal(true),
26938
+ runId: string()
26939
+ }), {
26940
+ kind: "mutation",
26941
+ auth: "admin"
26942
+ }), method(object({ runId: string() }), NodeBenchRunnerStatusSchema.nullable(), { auth: "admin" }), method(object({ runId: string() }), object({ aborted: boolean() }), {
26943
+ kind: "mutation",
26944
+ auth: "admin"
26945
+ });
25392
26946
  var CameraPipelineConfigSchema = object({
25393
26947
  engine: PipelineEngineChoiceSchema.optional(),
25394
26948
  steps: array(PipelineStepInputSchema).readonly(),
@@ -26027,6 +27581,21 @@ method(object({
26027
27581
  }), method(PlacementStatsInputSchema, PlacementStatsSchema, { auth: "admin" }), method(SuggestSharesInputSchema, SuggestSharesResultSchema, { auth: "admin" }), method(_void(), EffectiveSharesSchema, { auth: "admin" }), method(SetShareSourceInputSchema, object({ success: literal(true) }), {
26028
27582
  kind: "mutation",
26029
27583
  auth: "admin"
27584
+ }), method(NodeBenchmarkPlanSchema, NodeBenchmarkPreflightSchema, { auth: "admin" }), method(NodeBenchmarkPlanSchema, discriminatedUnion("kind", [object({
27585
+ kind: literal("started"),
27586
+ runId: string()
27587
+ }), object({
27588
+ kind: literal("refused"),
27589
+ preflight: NodeBenchmarkPreflightSchema
27590
+ })]), {
27591
+ kind: "mutation",
27592
+ auth: "admin"
27593
+ }), method(_void(), NodeBenchmarkStatusSchema, { auth: "admin" }), method(object({ runId: string() }), object({ aborted: boolean() }), {
27594
+ kind: "mutation",
27595
+ auth: "admin"
27596
+ }), method(object({ nodeId: string() }), NodeBenchmarkCandidatesSchema, { auth: "admin" }), method(ListNodeBenchmarkResultsInputSchema, array(NodeBenchmarkResultViewSchema).readonly(), { auth: "admin" }), method(object({ id: string() }), object({ deleted: boolean() }), {
27597
+ kind: "mutation",
27598
+ auth: "admin"
26030
27599
  }), method(object({ deviceId: number() }), CameraPipelineSettingsSchema.nullable()), method(object({
26031
27600
  deviceId: number(),
26032
27601
  addonId: string(),
@@ -32142,6 +33711,9 @@ var CreateIntegrationInputSchema = object({
32142
33711
  enabled: boolean().optional(),
32143
33712
  info: record(string(), unknown()).optional(),
32144
33713
  settings: record(string(), unknown()).optional(),
33714
+ /** Keys of `settings` the form's schema declares secret (by type) — kept in
33715
+ * the keychain, not the table (D787). */
33716
+ secretKeys: array(string()).optional(),
32145
33717
  skipRestart: boolean().optional()
32146
33718
  });
32147
33719
  var UpdateIntegrationInputSchema = object({
@@ -32165,7 +33737,9 @@ method(_void(), array(IntegrationWithStateSchema)), method(object({ id: string()
32165
33737
  auth: "admin"
32166
33738
  }), method(object({ id: string() }), record(string(), unknown()), { auth: "admin" }), method(object({
32167
33739
  id: string(),
32168
- settings: record(string(), unknown())
33740
+ settings: record(string(), unknown()),
33741
+ /** Keys the form's schema declares secret (by type) — keychain-stored (D787). */
33742
+ secretKeys: array(string()).optional()
32169
33743
  }), object({ success: boolean() }), {
32170
33744
  kind: "mutation",
32171
33745
  auth: "admin"
@@ -40328,7 +41902,8 @@ var BaseDevice$1 = class {
40328
41902
  this.role = options.role;
40329
41903
  this.parentDeviceId = ctx.parentDeviceId;
40330
41904
  const seedData = ctx.persistedConfig ?? {};
40331
- this.config = DeviceConfig.fromSchema(schema, (data) => ctx.persistConfig(data), seedData, ({ droppedKeys, issues }) => {
41905
+ const declaredSecretPaths = collectZodSecretPaths(schema);
41906
+ this.config = DeviceConfig.fromSchema(schema, (data) => ctx.persistConfig(data, { secretConfigPaths: declaredSecretPaths }), seedData, ({ droppedKeys, issues }) => {
40332
41907
  ctx.logger.warn("Device config recovery: dropping invalid persisted fields", {
40333
41908
  tags: {
40334
41909
  deviceId: ctx.id,
@@ -44017,6 +45592,90 @@ Object.freeze({
44017
45592
  addonId: null,
44018
45593
  access: "create"
44019
45594
  },
45595
+ "keychain.delete": {
45596
+ capName: "keychain",
45597
+ capScope: "system",
45598
+ addonId: null,
45599
+ access: "delete"
45600
+ },
45601
+ "keychain.getState": {
45602
+ capName: "keychain",
45603
+ capScope: "system",
45604
+ addonId: null,
45605
+ access: "view"
45606
+ },
45607
+ "keychain.listMeta": {
45608
+ capName: "keychain",
45609
+ capScope: "system",
45610
+ addonId: null,
45611
+ access: "view"
45612
+ },
45613
+ "keychain.put": {
45614
+ capName: "keychain",
45615
+ capScope: "system",
45616
+ addonId: null,
45617
+ access: "create"
45618
+ },
45619
+ "keychain.resolve": {
45620
+ capName: "keychain",
45621
+ capScope: "system",
45622
+ addonId: null,
45623
+ access: "view"
45624
+ },
45625
+ "keychainAdmin.deleteOrphans": {
45626
+ capName: "keychain-admin",
45627
+ capScope: "system",
45628
+ addonId: null,
45629
+ access: "delete"
45630
+ },
45631
+ "keychainAdmin.downloadRecoveryKey": {
45632
+ capName: "keychain-admin",
45633
+ capScope: "system",
45634
+ addonId: null,
45635
+ access: "create"
45636
+ },
45637
+ "keychainAdmin.listAudit": {
45638
+ capName: "keychain-admin",
45639
+ capScope: "system",
45640
+ addonId: null,
45641
+ access: "view"
45642
+ },
45643
+ "keychainAdmin.listSecrets": {
45644
+ capName: "keychain-admin",
45645
+ capScope: "system",
45646
+ addonId: null,
45647
+ access: "view"
45648
+ },
45649
+ "keychainAdmin.purgeRetiredKeys": {
45650
+ capName: "keychain-admin",
45651
+ capScope: "system",
45652
+ addonId: null,
45653
+ access: "delete"
45654
+ },
45655
+ "keychainAdmin.resetKeychain": {
45656
+ capName: "keychain-admin",
45657
+ capScope: "system",
45658
+ addonId: null,
45659
+ access: "delete"
45660
+ },
45661
+ "keychainAdmin.reveal": {
45662
+ capName: "keychain-admin",
45663
+ capScope: "system",
45664
+ addonId: null,
45665
+ access: "create"
45666
+ },
45667
+ "keychainAdmin.rotateMasterKey": {
45668
+ capName: "keychain-admin",
45669
+ capScope: "system",
45670
+ addonId: null,
45671
+ access: "create"
45672
+ },
45673
+ "keychainAdmin.status": {
45674
+ capName: "keychain-admin",
45675
+ capScope: "system",
45676
+ addonId: null,
45677
+ access: "view"
45678
+ },
44020
45679
  "lawnMowerControl.dock": {
44021
45680
  capName: "lawn-mower-control",
44022
45681
  capScope: "device",
@@ -45391,6 +47050,18 @@ Object.freeze({
45391
47050
  addonId: null,
45392
47051
  access: "create"
45393
47052
  },
47053
+ "pipelineAnalytics.addRetrainFrameFromRecording": {
47054
+ capName: "pipeline-analytics",
47055
+ capScope: "device",
47056
+ addonId: null,
47057
+ access: "create"
47058
+ },
47059
+ "pipelineAnalytics.addRetrainFramesToCollection": {
47060
+ capName: "pipeline-analytics",
47061
+ capScope: "device",
47062
+ addonId: null,
47063
+ access: "create"
47064
+ },
45394
47065
  "pipelineAnalytics.applyDeviceSettingsPatch": {
45395
47066
  capName: "pipeline-analytics",
45396
47067
  capScope: "device",
@@ -45439,12 +47110,24 @@ Object.freeze({
45439
47110
  addonId: null,
45440
47111
  access: "view"
45441
47112
  },
47113
+ "pipelineAnalytics.createRetrainCollection": {
47114
+ capName: "pipeline-analytics",
47115
+ capScope: "device",
47116
+ addonId: null,
47117
+ access: "create"
47118
+ },
45442
47119
  "pipelineAnalytics.deleteDeviceEvents": {
45443
47120
  capName: "pipeline-analytics",
45444
47121
  capScope: "device",
45445
47122
  addonId: null,
45446
47123
  access: "delete"
45447
47124
  },
47125
+ "pipelineAnalytics.deleteRetrainCollection": {
47126
+ capName: "pipeline-analytics",
47127
+ capScope: "device",
47128
+ addonId: null,
47129
+ access: "delete"
47130
+ },
45448
47131
  "pipelineAnalytics.deleteTracks": {
45449
47132
  capName: "pipeline-analytics",
45450
47133
  capScope: "device",
@@ -45649,6 +47332,24 @@ Object.freeze({
45649
47332
  addonId: null,
45650
47333
  access: "view"
45651
47334
  },
47335
+ "pipelineAnalytics.listRetrainAssistProfiles": {
47336
+ capName: "pipeline-analytics",
47337
+ capScope: "device",
47338
+ addonId: null,
47339
+ access: "view"
47340
+ },
47341
+ "pipelineAnalytics.listRetrainCollectionFrames": {
47342
+ capName: "pipeline-analytics",
47343
+ capScope: "device",
47344
+ addonId: null,
47345
+ access: "view"
47346
+ },
47347
+ "pipelineAnalytics.listRetrainCollections": {
47348
+ capName: "pipeline-analytics",
47349
+ capScope: "device",
47350
+ addonId: null,
47351
+ access: "view"
47352
+ },
45652
47353
  "pipelineAnalytics.listRetrainFrames": {
45653
47354
  capName: "pipeline-analytics",
45654
47355
  capScope: "device",
@@ -45697,6 +47398,12 @@ Object.freeze({
45697
47398
  addonId: null,
45698
47399
  access: "create"
45699
47400
  },
47401
+ "pipelineAnalytics.proposeRetrainAnnotationsWithLlm": {
47402
+ capName: "pipeline-analytics",
47403
+ capScope: "device",
47404
+ addonId: null,
47405
+ access: "create"
47406
+ },
45700
47407
  "pipelineAnalytics.pruneEvents": {
45701
47408
  capName: "pipeline-analytics",
45702
47409
  capScope: "device",
@@ -45751,6 +47458,18 @@ Object.freeze({
45751
47458
  addonId: null,
45752
47459
  access: "create"
45753
47460
  },
47461
+ "pipelineAnalytics.removeRetrainFrameFromCollection": {
47462
+ capName: "pipeline-analytics",
47463
+ capScope: "device",
47464
+ addonId: null,
47465
+ access: "delete"
47466
+ },
47467
+ "pipelineAnalytics.renameRetrainCollection": {
47468
+ capName: "pipeline-analytics",
47469
+ capScope: "device",
47470
+ addonId: null,
47471
+ access: "create"
47472
+ },
45754
47473
  "pipelineAnalytics.restageRetrainTrack": {
45755
47474
  capName: "pipeline-analytics",
45756
47475
  capScope: "device",
@@ -46039,6 +47758,12 @@ Object.freeze({
46039
47758
  addonId: null,
46040
47759
  access: "view"
46041
47760
  },
47761
+ "pipelineOrchestrator.abortNodeBenchmark": {
47762
+ capName: "pipeline-orchestrator",
47763
+ capScope: "system",
47764
+ addonId: null,
47765
+ access: "create"
47766
+ },
46042
47767
  "pipelineOrchestrator.applyAutoTune": {
46043
47768
  capName: "pipeline-orchestrator",
46044
47769
  capScope: "system",
@@ -46063,6 +47788,12 @@ Object.freeze({
46063
47788
  addonId: null,
46064
47789
  access: "create"
46065
47790
  },
47791
+ "pipelineOrchestrator.deleteNodeBenchmarkResult": {
47792
+ capName: "pipeline-orchestrator",
47793
+ capScope: "system",
47794
+ addonId: null,
47795
+ access: "delete"
47796
+ },
46066
47797
  "pipelineOrchestrator.getAgentLoad": {
46067
47798
  capName: "pipeline-orchestrator",
46068
47799
  capScope: "system",
@@ -46171,6 +47902,24 @@ Object.freeze({
46171
47902
  addonId: null,
46172
47903
  access: "view"
46173
47904
  },
47905
+ "pipelineOrchestrator.getNodeBenchmarkCandidates": {
47906
+ capName: "pipeline-orchestrator",
47907
+ capScope: "system",
47908
+ addonId: null,
47909
+ access: "view"
47910
+ },
47911
+ "pipelineOrchestrator.getNodeBenchmarkPreflight": {
47912
+ capName: "pipeline-orchestrator",
47913
+ capScope: "system",
47914
+ addonId: null,
47915
+ access: "view"
47916
+ },
47917
+ "pipelineOrchestrator.getNodeBenchmarkStatus": {
47918
+ capName: "pipeline-orchestrator",
47919
+ capScope: "system",
47920
+ addonId: null,
47921
+ access: "view"
47922
+ },
46174
47923
  "pipelineOrchestrator.getNodeInferenceDevices": {
46175
47924
  capName: "pipeline-orchestrator",
46176
47925
  capScope: "system",
@@ -46213,6 +47962,12 @@ Object.freeze({
46213
47962
  addonId: null,
46214
47963
  access: "view"
46215
47964
  },
47965
+ "pipelineOrchestrator.listNodeBenchmarkResults": {
47966
+ capName: "pipeline-orchestrator",
47967
+ capScope: "system",
47968
+ addonId: null,
47969
+ access: "view"
47970
+ },
46216
47971
  "pipelineOrchestrator.pauseForStorageMigration": {
46217
47972
  capName: "pipeline-orchestrator",
46218
47973
  capScope: "system",
@@ -46357,6 +48112,12 @@ Object.freeze({
46357
48112
  addonId: null,
46358
48113
  access: "create"
46359
48114
  },
48115
+ "pipelineOrchestrator.startNodeBenchmark": {
48116
+ capName: "pipeline-orchestrator",
48117
+ capScope: "system",
48118
+ addonId: null,
48119
+ access: "create"
48120
+ },
46360
48121
  "pipelineOrchestrator.suggestShares": {
46361
48122
  capName: "pipeline-orchestrator",
46362
48123
  capScope: "system",
@@ -46375,6 +48136,12 @@ Object.freeze({
46375
48136
  addonId: null,
46376
48137
  access: "create"
46377
48138
  },
48139
+ "pipelineRunner.abortNodeBench": {
48140
+ capName: "pipeline-runner",
48141
+ capScope: "system",
48142
+ addonId: null,
48143
+ access: "create"
48144
+ },
46378
48145
  "pipelineRunner.attachCamera": {
46379
48146
  capName: "pipeline-runner",
46380
48147
  capScope: "system",
@@ -46423,6 +48190,12 @@ Object.freeze({
46423
48190
  addonId: null,
46424
48191
  access: "view"
46425
48192
  },
48193
+ "pipelineRunner.getNodeBenchStatus": {
48194
+ capName: "pipeline-runner",
48195
+ capScope: "system",
48196
+ addonId: null,
48197
+ access: "view"
48198
+ },
46426
48199
  "pipelineRunner.getParkedTrackFrame": {
46427
48200
  capName: "pipeline-runner",
46428
48201
  capScope: "system",
@@ -46465,6 +48238,12 @@ Object.freeze({
46465
48238
  addonId: null,
46466
48239
  access: "create"
46467
48240
  },
48241
+ "pipelineRunner.startNodeBench": {
48242
+ capName: "pipeline-runner",
48243
+ capScope: "system",
48244
+ addonId: null,
48245
+ access: "create"
48246
+ },
46468
48247
  "plateGallery.assignPlate": {
46469
48248
  capName: "plate-gallery",
46470
48249
  capScope: "system",
@@ -51394,6 +53173,11 @@ Object.freeze({
51394
53173
  form: "single",
51395
53174
  optional: false
51396
53175
  }],
53176
+ "pipelineAnalytics.addRetrainFrameFromRecording": [{
53177
+ name: "deviceId",
53178
+ form: "single",
53179
+ optional: false
53180
+ }],
51397
53181
  "pipelineAnalytics.applyDeviceSettingsPatch": [{
51398
53182
  name: "deviceId",
51399
53183
  form: "single",
@@ -51584,6 +53368,11 @@ Object.freeze({
51584
53368
  form: "single",
51585
53369
  optional: false
51586
53370
  }],
53371
+ "pipelineAnalytics.proposeRetrainAnnotationsWithLlm": [{
53372
+ name: "deviceId",
53373
+ form: "single",
53374
+ optional: false
53375
+ }],
51587
53376
  "pipelineAnalytics.pruneEventsBefore": [{
51588
53377
  name: "deviceId",
51589
53378
  form: "single",