@camstack/addon-provider-dreame 0.2.129 → 0.2.130

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 +1847 -58
  2. package/dist/addon.mjs +1847 -58
  3. package/package.json +1 -1
package/dist/addon.js CHANGED
@@ -46208,13 +46208,13 @@ var AI_FEATURE_JSON_KEY = {
46208
46208
  furnitureDetection: "furniture_detect_switch",
46209
46209
  fluidDetection: "fluid_detect_switch"
46210
46210
  };
46211
- function isRecord(v) {
46211
+ function isRecord$2(v) {
46212
46212
  return v !== null && typeof v === "object" && !Array.isArray(v);
46213
46213
  }
46214
46214
  function parseJsonPayload(raw) {
46215
46215
  try {
46216
46216
  const parsed = JSON.parse(raw);
46217
- return isRecord(parsed) ? parsed : null;
46217
+ return isRecord$2(parsed) ? parsed : null;
46218
46218
  } catch {
46219
46219
  return null;
46220
46220
  }
@@ -52902,7 +52902,7 @@ var DreameCameraStream = class extends TypedEmitter {
52902
52902
  }
52903
52903
  };
52904
52904
  //#endregion
52905
- //#region ../types/dist/event-category-B_0XEcLF.mjs
52905
+ //#region ../types/dist/event-category-DaIZi00R.mjs
52906
52906
  var EventCategory = /* @__PURE__ */ function(EventCategory) {
52907
52907
  EventCategory["SystemBoot"] = "system.boot";
52908
52908
  EventCategory["SystemAddonsReady"] = "system.addons-ready";
@@ -52981,6 +52981,13 @@ var EventCategory = /* @__PURE__ */ function(EventCategory) {
52981
52981
  */
52982
52982
  EventCategory["AddonLoadFailed"] = "addon.load-failed";
52983
52983
  /**
52984
+ * A keychain value was stored or removed (D787). Carries the ref, its
52985
+ * owner and the new version — NEVER the value. A process holding the ref
52986
+ * drops its cached copy and the owning `BaseAddon` re-resolves its config.
52987
+ * Telemetry (D8): a process that misses it still revalidates by version.
52988
+ */
52989
+ EventCategory["KeychainChanged"] = "keychain.changed";
52990
+ /**
52984
52991
  * Addon recovered from a previous failure. Emitted when an addon
52985
52992
  * transitions from `failed` back to `healthy` (typically via the
52986
52993
  * monitor's auto-retry loop, or after manual `addons.retryLoad`).
@@ -58273,7 +58280,7 @@ var ZodIssueCode = {
58273
58280
  var ZodFirstPartyTypeKind;
58274
58281
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
58275
58282
  //#endregion
58276
- //#region ../types/dist/sleep-B0JG7-_F.mjs
58283
+ //#region ../types/dist/sleep-Cr5YOk3m.mjs
58277
58284
  /**
58278
58285
  * The audio chunk plane's byte format, and the ONE expansion from a coded
58279
58286
  * window to float samples (D455).
@@ -58352,6 +58359,97 @@ function buildAlawTable() {
58352
58359
  }
58353
58360
  buildUlawTable();
58354
58361
  buildAlawTable();
58362
+ /** Is this field's stored value a credential? */
58363
+ function isSecretConfigField(field) {
58364
+ if (field.type === "password") return true;
58365
+ return "secret" in field && field.secret === true;
58366
+ }
58367
+ /**
58368
+ * Is this field's value stored in the KEYCHAIN (D787)? Every secret field is,
58369
+ * by its TYPE, unless it opts out with `storage: 'inline'` — never by its name.
58370
+ */
58371
+ function isKeychainStoredField(field) {
58372
+ if (!isSecretConfigField(field)) return false;
58373
+ if (field.type === "textarea" && field.isJson === true) return false;
58374
+ return !("storage" in field && field.storage === "inline");
58375
+ }
58376
+ /**
58377
+ * What a settings blob holds where a secret used to be.
58378
+ *
58379
+ * A keychain-stored field never holds its value. It holds a self-describing
58380
+ * MARKER, `{"$secret":"secret://…","v":1}` — an object, never a string, so no
58381
+ * code can mistake it for a credential and no form can send it to a camera as
58382
+ * a password. The empty state is `null` / absent, never `''`.
58383
+ *
58384
+ * The same shapes travel to and from the admin UI:
58385
+ *
58386
+ * - read: `hydrateSchema` hands a secret field a {@link SecretFieldView}
58387
+ * (`{ $secret, v, set: true }`) or `null` — the browser learns whether a
58388
+ * value is set, never the value.
58389
+ * - write: an untouched field submits the view back unchanged (KEEP); a typed
58390
+ * value is a plain non-empty string (CHANGE); the Clear button submits
58391
+ * {@link SECRET_CLEAR} (CLEAR). `''`, `null` and the legacy redaction tokens
58392
+ * are KEEP — an empty string is what a defaults-fallback pushes back, and
58393
+ * treating it as "clear" is how a save destroyed a stored credential before.
58394
+ *
58395
+ * Pure and browser-safe.
58396
+ */
58397
+ var SECRET_CLEAR = { $secretClear: true };
58398
+ /** The `'***'` token D634 redaction writes for non-admins. */
58399
+ var LEGACY_DEVICE_REDACTION = "***";
58400
+ function isRecord$1(value) {
58401
+ return typeof value === "object" && value !== null && !Array.isArray(value);
58402
+ }
58403
+ function makeSecretMarker(ref) {
58404
+ return {
58405
+ $secret: ref,
58406
+ v: 1
58407
+ };
58408
+ }
58409
+ /** A stored marker: an object whose `$secret` is a non-empty string. */
58410
+ function isSecretMarker(value) {
58411
+ if (!isRecord$1(value)) return false;
58412
+ const ref = value["$secret"];
58413
+ return typeof ref === "string" && ref.length > 0;
58414
+ }
58415
+ function isSecretClear(value) {
58416
+ return isRecord$1(value) && value["$secretClear"] === true;
58417
+ }
58418
+ /**
58419
+ * The UI view of a stored secret field value: a marker becomes "set", inline
58420
+ * plaintext becomes "set (inline)", nothing becomes `null`. A value never
58421
+ * survives this function.
58422
+ */
58423
+ function toSecretFieldView(stored) {
58424
+ if (isSecretMarker(stored)) return {
58425
+ $secret: stored.$secret,
58426
+ v: 1,
58427
+ set: true
58428
+ };
58429
+ if (typeof stored === "string" && stored.length > 0) return {
58430
+ $secret: null,
58431
+ v: 1,
58432
+ set: true,
58433
+ inline: true
58434
+ };
58435
+ return null;
58436
+ }
58437
+ /**
58438
+ * Classify an incoming value for a secret path. Only a non-empty string that is
58439
+ * not a redaction token sets a value; only {@link SECRET_CLEAR} clears.
58440
+ * Everything else — a marker (ours or anyone's), a UI view, `''`, `null`,
58441
+ * `undefined`, a redaction token, a non-string — keeps what is stored.
58442
+ */
58443
+ function classifySecretWrite(incoming) {
58444
+ if (isSecretClear(incoming)) return { kind: "clear" };
58445
+ if (typeof incoming !== "string") return { kind: "keep" };
58446
+ if (incoming.length === 0) return { kind: "keep" };
58447
+ if (incoming === "__camstack_redacted__" || incoming === LEGACY_DEVICE_REDACTION) return { kind: "keep" };
58448
+ return {
58449
+ kind: "set",
58450
+ value: incoming
58451
+ };
58452
+ }
58355
58453
  Object.fromEntries([
58356
58454
  {
58357
58455
  id: "overview",
@@ -58523,33 +58621,19 @@ Object.fromEntries([
58523
58621
  function isValuelessField(field) {
58524
58622
  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";
58525
58623
  }
58526
- /**
58527
- * Merge a `ConfigUISchema` with a raw `values` record into a
58528
- * `ConfigUISchemaWithValues`. Used by every `get*Settings` backend endpoint
58529
- * before returning to the admin UI. Groups are walked recursively.
58530
- *
58531
- * For each leaf field:
58532
- * - structural fields (`separator`, `info`, `button`) pass through unchanged
58533
- * - other fields get `value = values[key] ?? field.default ?? null`
58534
- *
58535
- * Unknown keys in `values` (keys not declared in the schema) are silently
58536
- * ignored — they don't contribute to the output. Missing keys fall back to
58537
- * the schema default or `null`. This mirrors the old backend behaviour where
58538
- * `FormBuilder` rendered `values[key] ?? field.default`.
58539
- */
58540
- function hydrateSchema(schema, values) {
58624
+ function hydrateSchema(schema, values, options = {}) {
58541
58625
  return {
58542
58626
  ...schema.tabs ? { tabs: [...schema.tabs] } : {},
58543
58627
  sections: schema.sections.map((section) => ({
58544
58628
  ...section,
58545
- fields: section.fields.map((field) => hydrateField(field, values))
58629
+ fields: section.fields.map((field) => hydrateField(field, values, options))
58546
58630
  }))
58547
58631
  };
58548
58632
  }
58549
- function hydrateField(field, values) {
58633
+ function hydrateField(field, values, options) {
58550
58634
  if (isValuelessField(field)) return field;
58551
58635
  if (field.type === "group") {
58552
- const hydratedChildren = field.fields.map((child) => hydrateField(child, values));
58636
+ const hydratedChildren = field.fields.map((child) => hydrateField(child, values, options));
58553
58637
  return {
58554
58638
  ...field,
58555
58639
  fields: hydratedChildren
@@ -58558,7 +58642,7 @@ function hydrateField(field, values) {
58558
58642
  if (field.type === "sub-tabs") {
58559
58643
  const hydratedTabs = field.tabs.map((tab) => ({
58560
58644
  ...tab,
58561
- fields: tab.fields.map((child) => hydrateField(child, values))
58645
+ fields: tab.fields.map((child) => hydrateField(child, values, options))
58562
58646
  }));
58563
58647
  return {
58564
58648
  ...field,
@@ -58568,6 +58652,33 @@ function hydrateField(field, values) {
58568
58652
  const key = field.key;
58569
58653
  const storedValue = Object.prototype.hasOwnProperty.call(values, key) ? values[key] : void 0;
58570
58654
  const defaultValue = field.default;
58655
+ const asView = (v) => isSecretMarker(v) || options.inlineSecretsAsViews === true && v !== void 0;
58656
+ if (isKeychainStoredField(field) && asView(storedValue)) return {
58657
+ ...field,
58658
+ value: toSecretFieldView(storedValue)
58659
+ };
58660
+ if (isKeychainStoredField(field) && options.inlineSecretsAsViews === true) return {
58661
+ ...field,
58662
+ value: null
58663
+ };
58664
+ if (field.type === "editable-array" && Array.isArray(storedValue)) {
58665
+ const secretItemKeys = field.itemFields.filter((item) => "key" in item && isKeychainStoredField(item)).map((item) => "key" in item ? item.key : "");
58666
+ if (secretItemKeys.length > 0) {
58667
+ const rows = storedValue.map((row) => {
58668
+ if (row === null || typeof row !== "object" || Array.isArray(row)) return row;
58669
+ const out = { ...row };
58670
+ for (const k of secretItemKeys) {
58671
+ const v = Reflect.get(row, k);
58672
+ if (asView(v)) out[k] = toSecretFieldView(v);
58673
+ }
58674
+ return out;
58675
+ });
58676
+ return {
58677
+ ...field,
58678
+ value: rows
58679
+ };
58680
+ }
58681
+ }
58571
58682
  if (field.multiple) {
58572
58683
  const stored = Array.isArray(storedValue) ? storedValue : storedValue !== void 0 && storedValue !== null ? [storedValue] : [];
58573
58684
  const itemFallback = field.multiple.itemDefault !== void 0 ? field.multiple.itemDefault : defaultValue !== void 0 ? defaultValue : typeOf(field) === "string" ? "" : null;
@@ -58810,6 +58921,431 @@ function projectStore(store, perNodeKeys, nodeId) {
58810
58921
  }
58811
58922
  return out;
58812
58923
  }
58924
+ var GLOBAL_SCOPE = { kind: "global" };
58925
+ /** The scope every addon-wide (not per-node, not per-device) setting lives in. */
58926
+ function globalSecretScope() {
58927
+ return GLOBAL_SCOPE;
58928
+ }
58929
+ function encodeSegment(value) {
58930
+ return encodeURIComponent(value);
58931
+ }
58932
+ /**
58933
+ * The field path of a value inside an array item, addressed by the item's id:
58934
+ * `arrayItemFieldPath('providers', 'authentik', 'clientSecret')` →
58935
+ * `providers[authentik].clientSecret`.
58936
+ */
58937
+ function arrayItemFieldPath(arrayKey, itemId, fieldKey) {
58938
+ return `${arrayKey}[${encodeSegment(itemId)}].${fieldKey}`;
58939
+ }
58940
+ /** A write to a secret path could not be stored in the keychain, so it was refused. */
58941
+ var KeychainWriteRefusedError = class extends Error {
58942
+ fieldPath;
58943
+ constructor(fieldPath, cause) {
58944
+ super(`secret "${fieldPath}" was not saved: the keychain could not store it (${cause instanceof Error ? cause.message : String(cause)}). Nothing was written.`);
58945
+ this.fieldPath = fieldPath;
58946
+ this.name = "KeychainWriteRefusedError";
58947
+ }
58948
+ };
58949
+ var KEEP = { kind: "keep" };
58950
+ function isRecord(value) {
58951
+ return typeof value === "object" && value !== null && !Array.isArray(value);
58952
+ }
58953
+ function defaultMintId() {
58954
+ return globalThis.crypto.randomUUID();
58955
+ }
58956
+ /** Every marker ref anywhere under `value`. */
58957
+ function collectSecretMarkerRefs(value, out = []) {
58958
+ if (isSecretMarker(value)) {
58959
+ out.push(value.$secret);
58960
+ return out;
58961
+ }
58962
+ if (Array.isArray(value)) for (const item of value) collectSecretMarkerRefs(item, out);
58963
+ else if (isRecord(value)) for (const child of Object.values(value)) collectSecretMarkerRefs(child, out);
58964
+ return out;
58965
+ }
58966
+ async function storedValueEquals(secrets, marker, candidate) {
58967
+ const resolved = (await secrets.resolve([marker.$secret]))[marker.$secret];
58968
+ return resolved?.kind === "value" && resolved.value === candidate;
58969
+ }
58970
+ async function writeLeaf(ctx, incoming, stored, fieldPath) {
58971
+ const intent = classifySecretWrite(incoming);
58972
+ const ref = ctx.secrets.ref(ctx.scope, fieldPath);
58973
+ const storedIsOurs = isSecretMarker(stored) && stored.$secret === ref;
58974
+ if (intent.kind === "keep") return KEEP;
58975
+ if (intent.kind === "set" && !ctx.operatorWrite && typeof stored === "string" && stored === intent.value) return KEEP;
58976
+ if (intent.kind === "clear") {
58977
+ if (storedIsOurs) ctx.deletes.push(ref);
58978
+ return {
58979
+ kind: "value",
58980
+ value: null
58981
+ };
58982
+ }
58983
+ if (storedIsOurs && await storedValueEquals(ctx.secrets, stored, intent.value)) return {
58984
+ kind: "value",
58985
+ value: stored
58986
+ };
58987
+ try {
58988
+ await ctx.secrets.put(ref, intent.value);
58989
+ } catch (err) {
58990
+ throw new KeychainWriteRefusedError(fieldPath, err);
58991
+ }
58992
+ return {
58993
+ kind: "value",
58994
+ value: makeSecretMarker(ref)
58995
+ };
58996
+ }
58997
+ /** Apply a member result onto `out`: KEEP restores the stored member, or removes it. */
58998
+ function applyMember(out, key, result, storedParent) {
58999
+ if (result.kind === "value") {
59000
+ out[key] = result.value;
59001
+ return;
59002
+ }
59003
+ if (Object.prototype.hasOwnProperty.call(storedParent, key)) out[key] = storedParent[key];
59004
+ else delete out[key];
59005
+ }
59006
+ async function writeMembers(ctx, children, incoming, stored, pathOf) {
59007
+ const out = { ...incoming };
59008
+ for (const [member, node] of children) applyMember(out, member, await writeNode(ctx, node, incoming[member], stored[member], pathOf(member)), stored);
59009
+ return out;
59010
+ }
59011
+ function rowId(row, idKey) {
59012
+ const raw = row[idKey];
59013
+ if (typeof raw === "string" && raw.length > 0) return raw;
59014
+ if (typeof raw === "number" && Number.isFinite(raw)) return String(raw);
59015
+ return null;
59016
+ }
59017
+ async function writeArray(ctx, node, incoming, stored, fieldPath) {
59018
+ const storedRows = Array.isArray(stored) ? stored.filter(isRecord) : [];
59019
+ if (!Array.isArray(incoming)) {
59020
+ ctx.deletes.push(...collectSecretMarkerRefs(storedRows));
59021
+ return {
59022
+ kind: "value",
59023
+ value: incoming
59024
+ };
59025
+ }
59026
+ const storedById = /* @__PURE__ */ new Map();
59027
+ for (const row of storedRows) {
59028
+ const id = rowId(row, node.idKey);
59029
+ if (id !== null) storedById.set(id, row);
59030
+ }
59031
+ const kept = /* @__PURE__ */ new Set();
59032
+ const rows = [];
59033
+ for (const row of incoming) {
59034
+ if (!isRecord(row)) {
59035
+ rows.push(row);
59036
+ continue;
59037
+ }
59038
+ const id = rowId(row, node.idKey) ?? ctx.mintId();
59039
+ kept.add(id);
59040
+ const withId = {
59041
+ ...row,
59042
+ [node.idKey]: row[node.idKey] ?? id
59043
+ };
59044
+ if (rowId(withId, node.idKey) === null) withId[node.idKey] = id;
59045
+ const storedRow = storedById.get(id) ?? {};
59046
+ rows.push(await writeMembers(ctx, node.item, withId, storedRow, (member) => arrayItemFieldPath(fieldPath, id, member)));
59047
+ }
59048
+ for (const [id, row] of storedById) if (!kept.has(id)) ctx.deletes.push(...collectSecretMarkerRefs(row));
59049
+ return {
59050
+ kind: "value",
59051
+ value: rows
59052
+ };
59053
+ }
59054
+ async function writeNode(ctx, node, incoming, stored, fieldPath) {
59055
+ switch (node.kind) {
59056
+ case "leaf": return writeLeaf(ctx, incoming, stored, fieldPath);
59057
+ case "array": return writeArray(ctx, node, incoming, stored, fieldPath);
59058
+ case "object": {
59059
+ if (!isRecord(incoming)) {
59060
+ if (incoming === void 0) return KEEP;
59061
+ ctx.deletes.push(...collectSecretMarkerRefs(stored));
59062
+ return {
59063
+ kind: "value",
59064
+ value: incoming
59065
+ };
59066
+ }
59067
+ const storedObj = isRecord(stored) ? stored : {};
59068
+ return {
59069
+ kind: "value",
59070
+ value: await writeMembers(ctx, node.children, incoming, storedObj, (m) => `${fieldPath}.${m}`)
59071
+ };
59072
+ }
59073
+ }
59074
+ }
59075
+ /** Split a perNode-scoped key (`key@nodeId`). */
59076
+ function splitNodeKey(key) {
59077
+ const at = key.indexOf("@");
59078
+ return at <= 0 ? {
59079
+ base: key,
59080
+ nodeId: null
59081
+ } : {
59082
+ base: key.slice(0, at),
59083
+ nodeId: key.slice(at + 1)
59084
+ };
59085
+ }
59086
+ /** Rewrite a settings patch so no secret value reaches the blob. See the file doc. */
59087
+ async function transformSecretWrite(input) {
59088
+ const deletes = [];
59089
+ const base = {
59090
+ secrets: input.secrets,
59091
+ mintId: input.mintId ?? defaultMintId,
59092
+ deletes,
59093
+ operatorWrite: input.operatorWrite === true
59094
+ };
59095
+ const out = {};
59096
+ for (const [key, incoming] of Object.entries(input.patch)) {
59097
+ const { base: baseKey, nodeId } = splitNodeKey(key);
59098
+ const node = input.tree.get(baseKey);
59099
+ if (node === void 0) {
59100
+ out[key] = incoming;
59101
+ continue;
59102
+ }
59103
+ const scope = nodeId !== null && nodeId.length > 0 ? {
59104
+ kind: "node",
59105
+ nodeId
59106
+ } : input.scope ?? globalSecretScope();
59107
+ const result = await writeNode({
59108
+ ...base,
59109
+ scope
59110
+ }, node, incoming, input.stored[key], baseKey);
59111
+ if (result.kind === "value") out[key] = result.value;
59112
+ }
59113
+ return {
59114
+ patch: out,
59115
+ afterWrite: async () => {
59116
+ if (deletes.length === 0) return { orphaned: [] };
59117
+ try {
59118
+ await input.secrets.delete([...new Set(deletes)]);
59119
+ return { orphaned: [] };
59120
+ } catch {
59121
+ return { orphaned: [...new Set(deletes)] };
59122
+ }
59123
+ }
59124
+ };
59125
+ }
59126
+ /**
59127
+ * Replace every marker in `value` with its keychain value. Returns the SAME
59128
+ * reference when there is no marker (no allocation, no keychain call).
59129
+ */
59130
+ async function resolveSecretMarkers(value, secrets) {
59131
+ const refs = collectSecretMarkerRefs(value);
59132
+ if (refs.length === 0) return {
59133
+ value,
59134
+ unresolved: []
59135
+ };
59136
+ const answers = await secrets.resolve(refs);
59137
+ const unresolved = [];
59138
+ for (const ref of new Set(refs)) {
59139
+ const answer = answers[ref];
59140
+ if (answer === void 0) unresolved.push({
59141
+ ref,
59142
+ reason: "not-initialized"
59143
+ });
59144
+ else if (answer.kind === "unavailable") unresolved.push({
59145
+ ref,
59146
+ reason: answer.reason
59147
+ });
59148
+ else if (answer.kind === "missing" || answer.kind === "forbidden") unresolved.push({
59149
+ ref,
59150
+ reason: answer.kind
59151
+ });
59152
+ }
59153
+ const substitute = (v) => {
59154
+ if (isSecretMarker(v)) {
59155
+ const answer = answers[v.$secret];
59156
+ return answer?.kind === "value" ? {
59157
+ keep: true,
59158
+ value: answer.value
59159
+ } : {
59160
+ keep: false,
59161
+ value: void 0
59162
+ };
59163
+ }
59164
+ if (Array.isArray(v)) {
59165
+ const items = [];
59166
+ for (const item of v) {
59167
+ const s = substitute(item);
59168
+ if (s.keep) items.push(s.value);
59169
+ }
59170
+ return {
59171
+ keep: true,
59172
+ value: items
59173
+ };
59174
+ }
59175
+ if (isRecord(v)) {
59176
+ const out = {};
59177
+ for (const [k, child] of Object.entries(v)) {
59178
+ const s = substitute(child);
59179
+ if (s.keep) out[k] = s.value;
59180
+ }
59181
+ return {
59182
+ keep: true,
59183
+ value: out
59184
+ };
59185
+ }
59186
+ return {
59187
+ keep: true,
59188
+ value: v
59189
+ };
59190
+ };
59191
+ return {
59192
+ value: substitute(value).value,
59193
+ unresolved
59194
+ };
59195
+ }
59196
+ function touchesTree(tree, patch) {
59197
+ if (tree.size === 0) return false;
59198
+ for (const key of Object.keys(patch)) {
59199
+ const at = key.indexOf("@");
59200
+ if (tree.has(at > 0 ? key.slice(0, at) : key)) return true;
59201
+ }
59202
+ return false;
59203
+ }
59204
+ /** The blob as stored now; a failed read REFUSES the write instead of guessing. */
59205
+ async function readStoredAddonBlob(raw) {
59206
+ const threeWay = raw.readAddonStoreResult;
59207
+ if (threeWay === void 0) return raw.readAddonStore();
59208
+ const result = await threeWay.call(raw);
59209
+ if (result.kind === "failed") throw new Error(`settings write refused: the stored blob could not be read (${result.error})`);
59210
+ return result.kind === "missing" ? {} : result.value;
59211
+ }
59212
+ function createSecretAwareSettings(raw, opts) {
59213
+ const chains = /* @__PURE__ */ new Map();
59214
+ const serialize = (key, fn) => {
59215
+ const next = (chains.get(key) ?? Promise.resolve()).then(fn, fn);
59216
+ const tail = next.catch(() => void 0);
59217
+ chains.set(key, tail);
59218
+ tail.then(() => {
59219
+ if (chains.get(key) === tail) chains.delete(key);
59220
+ });
59221
+ return next;
59222
+ };
59223
+ const write = async (chainKey, tree, scope, patch, readStored, rawWrite) => {
59224
+ if (!touchesTree(tree, patch)) return rawWrite(patch);
59225
+ return serialize(chainKey, async () => {
59226
+ const stored = await readStored();
59227
+ const result = await transformSecretWrite({
59228
+ tree,
59229
+ secrets: opts.secrets,
59230
+ patch,
59231
+ stored,
59232
+ ...scope !== void 0 ? { scope } : {},
59233
+ operatorWrite: opts.isOperatorWrite?.() === true
59234
+ });
59235
+ if (Object.keys(result.patch).length > 0) await rawWrite(result.patch);
59236
+ const { orphaned } = await result.afterWrite();
59237
+ if (orphaned.length > 0) opts.onOrphaned(orphaned);
59238
+ });
59239
+ };
59240
+ const wrapped = {
59241
+ writeAddonStore: (patch) => write("addon", opts.addonTree(), void 0, patch, () => readStoredAddonBlob(raw), (p) => raw.writeAddonStore(p)),
59242
+ writeDeviceStore: (deviceId, patch) => write(`device:${deviceId}`, opts.deviceTree(), {
59243
+ kind: "device",
59244
+ deviceId
59245
+ }, patch, () => raw.readDeviceStore(deviceId), (p) => raw.writeDeviceStore(deviceId, p))
59246
+ };
59247
+ return new Proxy(raw, { get(target, prop, receiver) {
59248
+ if (prop === "writeAddonStore") return wrapped.writeAddonStore;
59249
+ if (prop === "writeDeviceStore") return wrapped.writeDeviceStore;
59250
+ const value = Reflect.get(target, prop, receiver);
59251
+ return typeof value === "function" ? value.bind(target) : value;
59252
+ } });
59253
+ }
59254
+ /** The context the addon sees: identical, except that its settings writes are secret-aware. */
59255
+ function withSecretAwareSettings(context, opts) {
59256
+ const raw = context.settings;
59257
+ if (raw === void 0) return context;
59258
+ const settings = createSecretAwareSettings(raw, opts);
59259
+ return new Proxy(context, { get(target, prop, receiver) {
59260
+ if (prop === "settings") return settings;
59261
+ return Reflect.get(target, prop, receiver);
59262
+ } });
59263
+ }
59264
+ var LEAF = { kind: "leaf" };
59265
+ var DEFAULT_ITEM_ID_KEY = "id";
59266
+ function collectFields(fields, out) {
59267
+ for (const field of fields) {
59268
+ if (field.type === "group") {
59269
+ collectFields(field.fields, out);
59270
+ continue;
59271
+ }
59272
+ if (field.type === "sub-tabs") {
59273
+ for (const tab of field.tabs) collectFields(tab.fields, out);
59274
+ continue;
59275
+ }
59276
+ if (field.type === "editable-array") {
59277
+ const item = /* @__PURE__ */ new Map();
59278
+ for (const itemField of field.itemFields) if ("key" in itemField && isKeychainStoredField(itemField)) item.set(itemField.key, LEAF);
59279
+ if (item.size > 0) out.set(field.key, {
59280
+ kind: "array",
59281
+ idKey: field.itemIdKey ?? DEFAULT_ITEM_ID_KEY,
59282
+ item
59283
+ });
59284
+ continue;
59285
+ }
59286
+ if (!("key" in field) || typeof field.key !== "string") continue;
59287
+ if (isKeychainStoredField(field)) out.set(field.key, LEAF);
59288
+ }
59289
+ }
59290
+ /** The secret tree a settings schema declares. */
59291
+ function secretTreeFromSchema(schema) {
59292
+ const out = /* @__PURE__ */ new Map();
59293
+ if (schema === null) return out;
59294
+ for (const section of schema.sections) collectFields(section.fields, out);
59295
+ return out;
59296
+ }
59297
+ /** Parse `a.b[id].c` into segments; throws on a malformed path (a declaration bug). */
59298
+ function parseSecretStatePath(path) {
59299
+ const segments = [];
59300
+ for (const raw of path.split(".")) {
59301
+ const m = /^([^[\]]+)(?:\[([^[\]]+)\])?$/.exec(raw);
59302
+ if (m === null || m[1] === void 0) throw new Error(`secretStatePaths: malformed path "${path}"`);
59303
+ segments.push(m[2] !== void 0 ? {
59304
+ key: m[1],
59305
+ idKey: m[2]
59306
+ } : { key: m[1] });
59307
+ }
59308
+ if (segments.length === 0) throw new Error(`secretStatePaths: empty path`);
59309
+ if (segments[segments.length - 1]?.idKey !== void 0) throw new Error(`secretStatePaths: "${path}" ends on an array — name the member that is secret`);
59310
+ return segments;
59311
+ }
59312
+ function insert(into, segments) {
59313
+ const [head, ...rest] = segments;
59314
+ if (head === void 0) return;
59315
+ if (rest.length === 0) {
59316
+ into.set(head.key, LEAF);
59317
+ return;
59318
+ }
59319
+ const existing = into.get(head.key);
59320
+ if (head.idKey !== void 0) {
59321
+ const item = new Map(existing?.kind === "array" ? existing.item : []);
59322
+ insert(item, rest);
59323
+ into.set(head.key, {
59324
+ kind: "array",
59325
+ idKey: head.idKey,
59326
+ item
59327
+ });
59328
+ return;
59329
+ }
59330
+ const children = new Map(existing?.kind === "object" ? existing.children : []);
59331
+ insert(children, rest);
59332
+ into.set(head.key, {
59333
+ kind: "object",
59334
+ children
59335
+ });
59336
+ }
59337
+ /** Add hidden-state paths (`secretStatePaths`) to a schema-derived tree. */
59338
+ function mergeSecretStatePaths(tree, paths) {
59339
+ if (paths.length === 0) return tree;
59340
+ const out = new Map(tree);
59341
+ for (const path of paths) insert(out, parseSecretStatePath(path));
59342
+ return out;
59343
+ }
59344
+ /** First retry of a secret the keychain could not serve; doubles to {@link SECRET_RETRY_MAX_MS}. */
59345
+ var SECRET_RETRY_FIRST_MS = 5e3;
59346
+ var SECRET_RETRY_MAX_MS = 5 * 6e4;
59347
+ /** Coalesces a burst of `keychain.changed` events into one re-resolve. */
59348
+ var SECRET_CHANGE_DEBOUNCE_MS = 250;
58813
59349
  /**
58814
59350
  * Base class for CamStack addons. Eliminates settings boilerplate:
58815
59351
  *
@@ -58879,6 +59415,25 @@ var BaseAddon = class {
58879
59415
  settingsStoreReady = false;
58880
59416
  /** Default config values. Provided via constructor. */
58881
59417
  defaults;
59418
+ /**
59419
+ * Hidden-state paths that hold secrets (D787) — values the addon writes
59420
+ * itself (`updateGlobalSettings`, `state()`) that no form field declares.
59421
+ * Stored in the keychain exactly like a `password` field. Syntax:
59422
+ * `'snapshotSigningKey'`, `'identity.pincode'`, `'tokens[userId].accessToken'`
59423
+ * (`key[<id field>]` addresses array items by id, never by index).
59424
+ */
59425
+ secretStatePaths = [];
59426
+ _addonSecretTree = null;
59427
+ _deviceSecretTree = null;
59428
+ /** Refs the last resolved config pointed at — a change to one re-resolves. */
59429
+ _configSecretRefs = /* @__PURE__ */ new Set();
59430
+ _unresolvedSecrets = [];
59431
+ _secretRetryTimer = null;
59432
+ _secretRetryDelayMs = SECRET_RETRY_FIRST_MS;
59433
+ _secretChangeTimer = null;
59434
+ _secretChangeUnsub = null;
59435
+ /** >0 while an OPERATOR's settings write is being applied. */
59436
+ _operatorWriteDepth = 0;
58882
59437
  constructor(defaults) {
58883
59438
  this.defaults = defaults;
58884
59439
  this._config = { ...defaults };
@@ -58914,8 +59469,18 @@ var BaseAddon = class {
58914
59469
  return this._config;
58915
59470
  }
58916
59471
  async initialize(context) {
58917
- this._ctx = context;
59472
+ const secrets = context.secrets;
59473
+ this._ctx = secrets !== void 0 ? withSecretAwareSettings(context, {
59474
+ secrets,
59475
+ addonTree: () => this.addonSecretTree(),
59476
+ deviceTree: () => this.deviceSecretTree(),
59477
+ onOrphaned: (refs) => context.logger.warn("keychain refs dropped by a settings write could not be deleted", { meta: { refs: [...refs] } }),
59478
+ isOperatorWrite: () => this._operatorWriteDepth > 0
59479
+ }) : context;
58918
59480
  await this.resolveConfig();
59481
+ if (secrets !== void 0) this._secretChangeUnsub = secrets.onChange((ref) => {
59482
+ if (this._configSecretRefs.has(ref)) this.scheduleSecretReresolve(SECRET_CHANGE_DEBOUNCE_MS);
59483
+ });
58919
59484
  const result = await this.onInitialize();
58920
59485
  this.emitLifecycle(EventCategory.AddonStarted);
58921
59486
  const normalized = normalizeAddonInitResult(result);
@@ -58948,6 +59513,12 @@ var BaseAddon = class {
58948
59513
  */
58949
59514
  async onHubReachable() {}
58950
59515
  async shutdown() {
59516
+ this._secretChangeUnsub?.();
59517
+ this._secretChangeUnsub = null;
59518
+ if (this._secretRetryTimer !== null) clearTimeout(this._secretRetryTimer);
59519
+ if (this._secretChangeTimer !== null) clearTimeout(this._secretChangeTimer);
59520
+ this._secretRetryTimer = null;
59521
+ this._secretChangeTimer = null;
58951
59522
  this.emitLifecycle(EventCategory.AddonStopped);
58952
59523
  if (this.autoEmitReadiness) this.emitReadinessForProviders("down");
58953
59524
  await this.onShutdown();
@@ -59026,7 +59597,7 @@ var BaseAddon = class {
59026
59597
  return hydrateSchema(schema, overlay ? {
59027
59598
  ...projected,
59028
59599
  ...overlay
59029
- } : projected);
59600
+ } : projected, { inlineSecretsAsViews: true });
59030
59601
  }
59031
59602
  /**
59032
59603
  * The integration-level view of this addon's settings: exactly the sections
@@ -59075,7 +59646,7 @@ var BaseAddon = class {
59075
59646
  return hydrateSchema({
59076
59647
  ...schema,
59077
59648
  sections
59078
- }, projected);
59649
+ }, projected, { inlineSecretsAsViews: true });
59079
59650
  }
59080
59651
  /**
59081
59652
  * The raw addon store PROJECTED onto the target node's bare per-node keys:
@@ -59129,18 +59700,50 @@ var BaseAddon = class {
59129
59700
  value: result.value[key]
59130
59701
  };
59131
59702
  }
59703
+ /**
59704
+ * The OPERATOR's write — a settings form or an admin API call, dispatched by
59705
+ * the kernel. Identical to {@link updateGlobalSettings}, except that a secret
59706
+ * the operator sends is stored as sent even when it equals a pre-keychain
59707
+ * inline value: the operator re-entering a password is a change, an addon
59708
+ * writing back what it read is not (D787).
59709
+ */
59710
+ async updateGlobalSettingsAsOperator(patch, nodeId) {
59711
+ this._operatorWriteDepth++;
59712
+ try {
59713
+ await this.applyGlobalPatch(patch, nodeId);
59714
+ } finally {
59715
+ this._operatorWriteDepth--;
59716
+ }
59717
+ }
59132
59718
  async updateGlobalSettings(patch, nodeId) {
59719
+ await this.applyGlobalPatch(patch, nodeId);
59720
+ }
59721
+ /**
59722
+ * REMOVE stored secrets — their keychain values and their markers (D787).
59723
+ *
59724
+ * Writing `''` to a secret field KEEPS what is stored (an empty string is
59725
+ * what a defaults fallback writes back, and it must never destroy a
59726
+ * credential), so code that means "forget this token" says so here. Without
59727
+ * a keychain (an older kernel) it writes `''`, as such code always did.
59728
+ */
59729
+ async clearSecrets(keys, nodeId) {
59730
+ const tree = this.addonSecretTree();
59731
+ const keychain = this._ctx?.secrets !== void 0;
59732
+ const patch = {};
59733
+ for (const key of keys) patch[key] = keychain && tree.has(key) ? SECRET_CLEAR : "";
59734
+ await this.applyGlobalPatch(patch, nodeId);
59735
+ }
59736
+ async applyGlobalPatch(barePatch, nodeId) {
59133
59737
  const keys = this.perNodeKeys();
59134
59738
  const localNode = normalizeNodeId(this._ctx?.kernel?.localNodeId);
59135
59739
  const target = normalizeNodeId(nodeId ?? this._ctx?.kernel?.localNodeId);
59136
- const barePatch = patch;
59137
59740
  const scoped = keys.size > 0 ? scopePatch(barePatch, keys, target) : barePatch;
59138
59741
  await this._ctx?.settings?.writeAddonStore(scoped);
59139
59742
  if (target !== localNode) return;
59140
59743
  await this.resolveConfig();
59141
59744
  await this.onConfigChanged();
59142
59745
  this.emitLifecycle(EventCategory.AddonUpdated, { level: "global" });
59143
- this.maybeAutoRestart(patch, this.globalSettingsSchema());
59746
+ this.maybeAutoRestart(Object.keys(barePatch), this.globalSettingsSchema());
59144
59747
  }
59145
59748
  /**
59146
59749
  * The set of field keys the global settings schema declares `perNode: true`
@@ -59165,7 +59768,7 @@ var BaseAddon = class {
59165
59768
  * time to return its response before the addon is torn down and
59166
59769
  * re-initialised by `AddonRegistryService.restartAddon`.
59167
59770
  */
59168
- maybeAutoRestart(patch, schema) {
59771
+ maybeAutoRestart(patchKeys, schema) {
59169
59772
  if (!schema) return;
59170
59773
  const restartKeys = /* @__PURE__ */ new Set();
59171
59774
  for (const section of schema.sections) for (const field of section.fields) {
@@ -59173,13 +59776,13 @@ var BaseAddon = class {
59173
59776
  if (field.requiresRestart) restartKeys.add(field.key);
59174
59777
  }
59175
59778
  if (restartKeys.size === 0) return;
59176
- if (!Object.keys(patch).some((k) => restartKeys.has(k))) return;
59779
+ if (!patchKeys.some((k) => restartKeys.has(k))) return;
59177
59780
  const ctx = this._ctx;
59178
59781
  if (!ctx) return;
59179
59782
  const addonId = ctx.id;
59180
59783
  setImmediate(() => {
59181
59784
  ctx.api.addons?.restartAddon?.mutate({ addonId }).then(() => {
59182
- ctx.logger.info("addon auto-restart triggered by restart-required setting change", { meta: { changedFields: Object.keys(patch).filter((k) => restartKeys.has(k)) } });
59785
+ ctx.logger.info("addon auto-restart triggered by restart-required setting change", { meta: { changedFields: patchKeys.filter((k) => restartKeys.has(k)) } });
59183
59786
  }).catch((err) => {
59184
59787
  ctx.logger.error("addon auto-restart failed", { meta: { error: err instanceof Error ? err.message : String(err) } });
59185
59788
  });
@@ -59188,7 +59791,7 @@ var BaseAddon = class {
59188
59791
  async getDeviceSettings(deviceId) {
59189
59792
  const schema = this.deviceSettingsSchema();
59190
59793
  if (!schema) return { sections: [] };
59191
- return hydrateSchema(schema, await this._ctx?.settings?.readDeviceStore(deviceId) ?? {});
59794
+ return hydrateSchema(schema, await this._ctx?.settings?.readDeviceStore(deviceId) ?? {}, { inlineSecretsAsViews: true });
59192
59795
  }
59193
59796
  async updateDeviceSettings(deviceId, patch) {
59194
59797
  await this._ctx?.settings?.writeDeviceStore(deviceId, patch);
@@ -59318,7 +59921,7 @@ var BaseAddon = class {
59318
59921
  * selection at boot (absent scoped key ⇒ the constructor default wins).
59319
59922
  */
59320
59923
  async resolveConfig() {
59321
- const stored = await this.readAddonStoreWithRetry();
59924
+ const stored = await this.resolveStoredSecrets(await this.readAddonStoreWithRetry());
59322
59925
  const perNode = this.perNodeKeys();
59323
59926
  const localNode = normalizeNodeId(this._ctx?.kernel?.localNodeId);
59324
59927
  const resolved = { ...this.defaults };
@@ -59343,7 +59946,7 @@ var BaseAddon = class {
59343
59946
  key,
59344
59947
  schema,
59345
59948
  fallback,
59346
- read: () => this.readAddonStoreWithRetry(),
59949
+ read: async () => this.resolveStoredSecrets(await this.readAddonStoreWithRetry()),
59347
59950
  write: async (patch) => {
59348
59951
  await this._ctx?.settings?.writeAddonStore(patch);
59349
59952
  },
@@ -59360,7 +59963,7 @@ var BaseAddon = class {
59360
59963
  key,
59361
59964
  schema,
59362
59965
  fallback,
59363
- read: async () => await this._ctx?.settings?.readDeviceStore(deviceId) ?? {},
59966
+ read: async () => this.resolveStoredSecrets(await this._ctx?.settings?.readDeviceStore(deviceId) ?? {}, false),
59364
59967
  write: async (patch) => {
59365
59968
  await this._ctx?.settings?.writeDeviceStore(deviceId, patch);
59366
59969
  },
@@ -59372,6 +59975,70 @@ var BaseAddon = class {
59372
59975
  } })
59373
59976
  });
59374
59977
  }
59978
+ /** The addon store's secret tree: schema fields by TYPE, plus `secretStatePaths`. */
59979
+ addonSecretTree() {
59980
+ this._addonSecretTree ??= mergeSecretStatePaths(secretTreeFromSchema(this.globalSettingsSchema()), this.secretStatePaths);
59981
+ return this._addonSecretTree;
59982
+ }
59983
+ deviceSecretTree() {
59984
+ this._deviceSecretTree ??= secretTreeFromSchema(this.deviceSettingsSchema());
59985
+ return this._deviceSecretTree;
59986
+ }
59987
+ /**
59988
+ * Secrets of this addon's stored config that could not be resolved on the
59989
+ * last read, with why. Non-empty means the addon is running WITHOUT them —
59990
+ * an addon whose function needs one should report itself degraded rather
59991
+ * than start on an empty credential.
59992
+ */
59993
+ get unresolvedSecrets() {
59994
+ return this._unresolvedSecrets;
59995
+ }
59996
+ /**
59997
+ * Substitute every keychain marker in a stored blob with its value. With no
59998
+ * keychain (no `ctx.secrets`) or no marker, the blob comes back unchanged.
59999
+ * An unresolvable value is LEFT OUT (never `''`), logged by ref — never by
60000
+ * value — and, when the cause can pass, retried with backoff. Nothing is
60001
+ * ever written back from here.
60002
+ */
60003
+ async resolveStoredSecrets(blob, trackForConfig = true) {
60004
+ const secrets = this._ctx?.secrets;
60005
+ if (secrets === void 0) return blob;
60006
+ const refs = collectSecretMarkerRefs(blob);
60007
+ if (trackForConfig) this._configSecretRefs = new Set(refs);
60008
+ if (refs.length === 0) {
60009
+ if (trackForConfig) this._unresolvedSecrets = [];
60010
+ return blob;
60011
+ }
60012
+ const { value, unresolved } = await resolveSecretMarkers(blob, secrets);
60013
+ if (trackForConfig) {
60014
+ this._unresolvedSecrets = unresolved;
60015
+ if (unresolved.length > 0) {
60016
+ this._ctx?.logger?.error?.("secret unavailable — running without it, will retry", { meta: { secrets: unresolved.map((u) => ({
60017
+ ref: u.ref,
60018
+ reason: u.reason
60019
+ })) } });
60020
+ if (unresolved.some((u) => u.reason !== "missing" && u.reason !== "forbidden")) {
60021
+ this.scheduleSecretReresolve(this._secretRetryDelayMs);
60022
+ this._secretRetryDelayMs = Math.min(this._secretRetryDelayMs * 2, SECRET_RETRY_MAX_MS);
60023
+ }
60024
+ } else this._secretRetryDelayMs = SECRET_RETRY_FIRST_MS;
60025
+ }
60026
+ return value;
60027
+ }
60028
+ /** Re-resolve the config (a keychain-only change, or a retry) and apply it. */
60029
+ scheduleSecretReresolve(delayMs) {
60030
+ const timerOf = delayMs === SECRET_CHANGE_DEBOUNCE_MS ? "_secretChangeTimer" : "_secretRetryTimer";
60031
+ if (this[timerOf] !== null) return;
60032
+ const timer = setTimeout(() => {
60033
+ this[timerOf] = null;
60034
+ if (this._ctx === null) return;
60035
+ this.resolveConfig().then(() => this.onConfigChanged()).catch((err) => {
60036
+ this._ctx?.logger?.error?.("re-resolving secrets failed", { meta: { error: err instanceof Error ? err.message : String(err) } });
60037
+ });
60038
+ }, delayMs);
60039
+ timer.unref?.();
60040
+ this[timerOf] = timer;
60041
+ }
59375
60042
  /**
59376
60043
  * Wrap `ctx.settings.readAddonStore()` with a short retry budget so a
59377
60044
  * transient settings-store outage (mid-restart of sqlite-settings, tsx-watch
@@ -59947,6 +60614,69 @@ method(object({ deviceId: number() }), array(StreamSourceEntrySchema)), method(o
59947
60614
  kind: "mutation",
59948
60615
  auth: "admin"
59949
60616
  }), method(object({ deviceId: number() }), unknown().nullable()), method(object({ deviceId: number() }), RawStateResultSchema.nullable(), { auth: "protected" });
60617
+ function defOf(schema) {
60618
+ return schema._zod?.def ?? {};
60619
+ }
60620
+ function declaredHere(schema) {
60621
+ return globalRegistry.get(schema)?.secret === true;
60622
+ }
60623
+ /** Wrapper kinds whose `innerType` is the field itself. */
60624
+ var WRAPPERS = new Set([
60625
+ "optional",
60626
+ "nullable",
60627
+ "default",
60628
+ "prefault",
60629
+ "catch",
60630
+ "readonly",
60631
+ "nonoptional"
60632
+ ]);
60633
+ /**
60634
+ * The schema layers that make up ONE field: the schema itself and every
60635
+ * wrapper below it (optional / default / nullable / readonly / catch), plus
60636
+ * both sides of a pipe (`z.preprocess` puts the real schema on `out`,
60637
+ * `.transform` on `in`).
60638
+ */
60639
+ function layersOf(schema) {
60640
+ const out = [];
60641
+ const queue = [schema];
60642
+ while (queue.length > 0) {
60643
+ const s = queue.shift();
60644
+ if (!s || out.includes(s)) continue;
60645
+ out.push(s);
60646
+ const def = defOf(s);
60647
+ if (def.type !== void 0 && WRAPPERS.has(def.type) && def.innerType) queue.push(def.innerType);
60648
+ if (def.type === "pipe") {
60649
+ if (def.in) queue.push(def.in);
60650
+ if (def.out) queue.push(def.out);
60651
+ }
60652
+ }
60653
+ return out;
60654
+ }
60655
+ /** True when any layer of this field declares `.meta({ secret: true })`. */
60656
+ function isZodSecret(schema) {
60657
+ return layersOf(schema).some(declaredHere);
60658
+ }
60659
+ /**
60660
+ * Every declared secret path in a config schema: dotted keys, `[]` for "each
60661
+ * element of this array" (`connection.password`, `rows[].token`). A declared
60662
+ * object or array is reported as one path and not descended into — everything
60663
+ * under it is secret.
60664
+ */
60665
+ function collectZodSecretPaths(schema, prefix = "") {
60666
+ if (isZodSecret(schema)) return prefix.length > 0 ? [prefix] : [];
60667
+ const paths = [];
60668
+ for (const layer of layersOf(schema)) {
60669
+ const def = defOf(layer);
60670
+ if (def.type === "object" && def.shape) for (const [key, child] of Object.entries(def.shape)) paths.push(...collectZodSecretPaths(child, prefix ? `${prefix}.${key}` : key));
60671
+ else if (def.type === "array" && def.element) paths.push(...collectZodSecretPaths(def.element, `${prefix}[]`));
60672
+ else if (def.type === "union" && def.options) for (const option of def.options) paths.push(...collectZodSecretPaths(option, prefix));
60673
+ else if (def.type === "intersection") {
60674
+ if (def.left) paths.push(...collectZodSecretPaths(def.left, prefix));
60675
+ if (def.right) paths.push(...collectZodSecretPaths(def.right, prefix));
60676
+ }
60677
+ }
60678
+ return [...new Set(paths)];
60679
+ }
59950
60680
  //#endregion
59951
60681
  //#region ../types/dist/err-msg-DX6i_MY4.mjs
59952
60682
  var DeviceType = /* @__PURE__ */ function(DeviceType) {
@@ -66977,6 +67707,196 @@ id: union([string(), number()]) }), {
66977
67707
  kind: "mutation",
66978
67708
  auth: "admin"
66979
67709
  });
67710
+ /**
67711
+ * `keychain` — the hub's encrypted store of secret values (D787).
67712
+ *
67713
+ * Settings blobs never hold a secret: they hold a marker
67714
+ * `{"$secret":"secret://<owner>/<scope>/<fieldPath>","v":1}` and the value
67715
+ * lives here, AES-256-GCM under a data key that a master key wraps. This cap
67716
+ * is the OWNER's door to its own values: every method is owner-checked
67717
+ * against the CALLER, never against anything the caller claims.
67718
+ *
67719
+ * Who the caller is: the transport stamps `callerAddonId` into the args of a
67720
+ * call that crossed a process (the parent `LocalChildRegistry` from the UDS
67721
+ * connection, the agent from its child's connection carried in
67722
+ * `$hub-cap-fwd`'s envelope). A stamp always overwrites; a wire call with no
67723
+ * stamp has its claim stripped. Only a hub in-process caller may state its own
67724
+ * identity — `ctx.secrets` does that with the addon id closed over. This is
67725
+ * identity against BUGS and misrouting, not against a malicious addon (every
67726
+ * runner is the same OS user): see the threat model in
67727
+ * `docs/design/2026-10-08-secrets-keychain.md`.
67728
+ *
67729
+ * `callerAddonId` is deliberately NOT in any input schema: the tRPC router
67730
+ * parses the input, so a session can never supply it, and the internal mount
67731
+ * floors every method to admin anyway (D240).
67732
+ *
67733
+ * Internal: addons reach it through `ctx.secrets`, never directly.
67734
+ */
67735
+ /** Why a value cannot be served right now. Never folded into "missing". */
67736
+ var KeychainUnavailableReasonSchema = _enum([
67737
+ "key-missing",
67738
+ "wrong-key",
67739
+ "key-file-unreadable",
67740
+ "store-unavailable",
67741
+ "not-initialized",
67742
+ "decrypt-failed"
67743
+ ]);
67744
+ var KeychainStateSchema = discriminatedUnion("state", [object({ state: literal("ready") }), object({
67745
+ state: literal("locked"),
67746
+ reason: KeychainUnavailableReasonSchema
67747
+ })]);
67748
+ var KeychainResolveEntrySchema = discriminatedUnion("kind", [
67749
+ object({
67750
+ kind: literal("value"),
67751
+ value: string(),
67752
+ version: number().int()
67753
+ }),
67754
+ object({ kind: literal("missing") }),
67755
+ object({
67756
+ kind: literal("unavailable"),
67757
+ reason: KeychainUnavailableReasonSchema
67758
+ }),
67759
+ object({ kind: literal("forbidden") })
67760
+ ]);
67761
+ var KeychainResolveResultSchema = record(string(), KeychainResolveEntrySchema);
67762
+ /** Metadata of one stored value — never the value. */
67763
+ var KeychainSecretMetaSchema = object({
67764
+ ref: string(),
67765
+ owner: string(),
67766
+ /** Formatted scope (`global`, `node/<id>`, `device/<id>`, …). */
67767
+ scope: string(),
67768
+ fieldPath: string(),
67769
+ version: number().int(),
67770
+ createdAt: number(),
67771
+ updatedAt: number(),
67772
+ /** `addon:<id>` | `user:<id>` | `system`. */
67773
+ updatedBy: string(),
67774
+ /** Coarse — written at most once an hour per ref. `null` = never read. */
67775
+ lastReadAt: number().nullable()
67776
+ });
67777
+ var RefListSchema = array(string().min(1)).max(512);
67778
+ method(object({
67779
+ ref: string().min(1),
67780
+ value: string().min(1)
67781
+ }), object({
67782
+ ref: string(),
67783
+ version: number().int()
67784
+ }), {
67785
+ kind: "mutation",
67786
+ auth: "admin"
67787
+ }), method(object({ refs: RefListSchema }), KeychainResolveResultSchema, { auth: "admin" }), method(object({ refs: RefListSchema }), object({ deleted: number().int() }), {
67788
+ kind: "mutation",
67789
+ auth: "admin"
67790
+ }), method(object({}), array(KeychainSecretMetaSchema).readonly(), { auth: "admin" }), method(object({}), KeychainStateSchema, { auth: "admin" });
67791
+ var KeychainKeySourceSchema = object({
67792
+ kind: _enum([
67793
+ "config-file",
67794
+ "previous-config-file",
67795
+ "platform",
67796
+ "default-file"
67797
+ ]),
67798
+ /** File sources only — a path is not a secret. */
67799
+ path: string().optional(),
67800
+ /**
67801
+ * True when a whole-volume backup of the data directory carries this key
67802
+ * next to the database it protects (the default file). The page warns.
67803
+ */
67804
+ sharesBackupWithDatabase: boolean()
67805
+ });
67806
+ var KeychainStatusSchema = object({
67807
+ keychain: KeychainStateSchema,
67808
+ /** The source of the master key in use; `null` while locked. */
67809
+ keySource: KeychainKeySourceSchema.nullable(),
67810
+ /** The source configured to be primary — differs from `keySource` while a rotation is pending. */
67811
+ configuredSource: KeychainKeySourceSchema,
67812
+ /** Short fingerprint of the master key in use (`HMAC(KEK, label)`, 16 hex). */
67813
+ fingerprint: string().nullable(),
67814
+ activeKeyId: string().nullable(),
67815
+ /**
67816
+ * The keychain unlocked with a NON-primary source: the configured primary
67817
+ * key is not the one that wraps the data key yet. `rotateMasterKey` moves it.
67818
+ */
67819
+ rotationPending: boolean(),
67820
+ /** Wrapped copies of the data key under a previous master key, kept until purged. */
67821
+ retiredWraps: number().int(),
67822
+ recoveryKeyDownloadedAt: number().nullable(),
67823
+ secretCount: number().int()
67824
+ });
67825
+ /**
67826
+ * Whether a stored value is still pointed at by its owner's settings.
67827
+ * `unknown` is a first-class answer: a scope whose blob could not be read is
67828
+ * never reported as an orphan (and never deleted as one).
67829
+ */
67830
+ var KeychainSecretUsageSchema = _enum([
67831
+ "in-use",
67832
+ "orphan",
67833
+ "unknown"
67834
+ ]);
67835
+ var KeychainAdminSecretSchema = KeychainSecretMetaSchema.extend({ usage: KeychainSecretUsageSchema });
67836
+ var KeychainAuditActionSchema = _enum([
67837
+ "put",
67838
+ "delete",
67839
+ "reveal",
67840
+ "rotate-master-key",
67841
+ "purge-retired-keys",
67842
+ "download-recovery-key",
67843
+ "delete-orphans",
67844
+ "reset",
67845
+ "initialize"
67846
+ ]);
67847
+ var KeychainAuditEntrySchema = object({
67848
+ id: string(),
67849
+ at: number(),
67850
+ action: KeychainAuditActionSchema,
67851
+ /** `addon:<id>` | `user:<id>` | `system`. */
67852
+ actor: string(),
67853
+ ref: string().nullable(),
67854
+ detail: string().nullable()
67855
+ });
67856
+ 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({
67857
+ value: string(),
67858
+ version: number().int()
67859
+ }), {
67860
+ kind: "mutation",
67861
+ auth: "admin",
67862
+ caller: "required"
67863
+ }), method(object({ refs: array(string().min(1)).max(1e3) }), object({
67864
+ deleted: array(string()).readonly(),
67865
+ kept: array(object({
67866
+ ref: string(),
67867
+ usage: KeychainSecretUsageSchema
67868
+ })).readonly()
67869
+ }), {
67870
+ kind: "mutation",
67871
+ auth: "admin",
67872
+ caller: "required"
67873
+ }), method(object({}), object({
67874
+ fingerprint: string(),
67875
+ keySource: KeychainKeySourceSchema
67876
+ }), {
67877
+ kind: "mutation",
67878
+ auth: "admin",
67879
+ caller: "required"
67880
+ }), method(object({}), object({ purged: number().int() }), {
67881
+ kind: "mutation",
67882
+ auth: "admin",
67883
+ caller: "required"
67884
+ }), method(object({}), object({
67885
+ key: string(),
67886
+ fingerprint: string(),
67887
+ keySource: KeychainKeySourceSchema
67888
+ }), {
67889
+ kind: "mutation",
67890
+ auth: "admin",
67891
+ caller: "required"
67892
+ }), method(object({ confirm: literal("RESET KEYCHAIN") }), object({
67893
+ archivedCollection: string().nullable(),
67894
+ archived: number().int()
67895
+ }), {
67896
+ kind: "mutation",
67897
+ auth: "admin",
67898
+ caller: "required"
67899
+ });
66980
67900
  method(_void(), object({
66981
67901
  id: string(),
66982
67902
  name: string(),
@@ -68219,7 +69139,11 @@ var DeviceRegisterPayloadSchema = object({
68219
69139
  var DeviceRemovePayloadSchema = object({ deviceId: number() });
68220
69140
  var DevicePersistConfigPayloadSchema = object({
68221
69141
  deviceId: number(),
68222
- data: record(string(), unknown())
69142
+ data: record(string(), unknown()),
69143
+ /** The paths the device's schema declares secret (D783), when the caller
69144
+ * knows them — those values are kept in the keychain, not the blob (D787).
69145
+ * Absent: the paths the device last reported at `registerDevice` apply. */
69146
+ secretConfigPaths: array(string()).optional()
68223
69147
  });
68224
69148
  /** What a migration actually did, per switch. `unreachable` is a first-class
68225
69149
  * answer: a camera that could not be asked is not a camera that was silenced. */
@@ -75248,8 +76172,23 @@ var RetrainMacroClassSchema = _enum([
75248
76172
  ]);
75249
76173
  /** A subject to learn, or a phantom to unlearn (taught by OMISSION). */
75250
76174
  var RetrainAnnotationKindSchema = _enum(["subject", "model_error"]);
75251
- /** Did a human draw this box, or did the assist propose it? */
75252
- var RetrainAnnotationSourceSchema = _enum(["operator", "assist"]);
76175
+ /**
76176
+ * Where a box came from. A machine-sourced box is a DRAFT on the page until
76177
+ * the operator confirms it; once saved it keeps its source as provenance.
76178
+ *
76179
+ * - `operator` — drawn by hand.
76180
+ * - `assist` — proposed by a detector run on the copy (the camera's own
76181
+ * model, or a larger teacher model).
76182
+ * - `pipeline` — the box the live pipeline actually drew on that frame, read
76183
+ * back from the track store (never a re-run).
76184
+ * - `llm` — proposed by a vision-capable LLM profile.
76185
+ */
76186
+ var RetrainAnnotationSourceSchema = _enum([
76187
+ "operator",
76188
+ "assist",
76189
+ "pipeline",
76190
+ "llm"
76191
+ ]);
75253
76192
  /** Normalised `[0,1]` rectangle against the FULL frame — the canonical form. */
75254
76193
  var RetrainBboxSchema = object({
75255
76194
  x: number(),
@@ -75267,7 +76206,8 @@ var RetrainBboxSchema = object({
75267
76206
  */
75268
76207
  var RetrainAnnotationSchema = object({
75269
76208
  id: string(),
75270
- trackId: string(),
76209
+ /** The frame's track. Absent on a recording still, which has none. */
76210
+ trackId: string().optional(),
75271
76211
  deviceId: number(),
75272
76212
  /** The COPY in retrain storage — never the source track's media key. */
75273
76213
  mediaKey: string(),
@@ -75316,13 +76256,47 @@ var RetrainFrameCandidateSchema = object({
75316
76256
  * fail, whatever became of the original. */
75317
76257
  copied: boolean()
75318
76258
  });
76259
+ /**
76260
+ * One box the live pipeline drew on a copied frame — what a correction starts
76261
+ * from. Derived when the frame is listed, from the track store: the subject
76262
+ * box recorded on the source media row when there is one, else the track
76263
+ * position nearest the frame's capture time. Never stored as an annotation
76264
+ * until the operator confirms it.
76265
+ */
76266
+ var RetrainPipelineBoxSchema = object({
76267
+ /** Normalised `[0,1]` against the full frame. */
76268
+ bbox: RetrainBboxSchema,
76269
+ macroClass: RetrainMacroClassSchema,
76270
+ label: string().optional(),
76271
+ subLabel: string().optional(),
76272
+ /** The detection score of the position used, when it was recorded. */
76273
+ score: number().optional(),
76274
+ /** The root model that produced the track, when it was recorded. */
76275
+ modelId: string().optional(),
76276
+ trackId: string(),
76277
+ /** `subject-box`: recorded on this very frame. `position`: the track's
76278
+ * position nearest the capture time, `deltaMs` away. */
76279
+ basis: _enum(["subject-box", "position"]),
76280
+ deltaMs: number()
76281
+ });
76282
+ /**
76283
+ * Where a retrain frame came from: a TRACK's stored media (copy-on-select),
76284
+ * or the RECORDING at an instant — the frame a model saw nothing in has no
76285
+ * track at all.
76286
+ */
76287
+ var RetrainFrameOriginSchema = _enum(["track", "recording"]);
75319
76288
  /** A frame the dataset OWNS: bytes copied at selection time. */
75320
76289
  var RetrainFrameSchema = object({
75321
76290
  frameId: string(),
75322
76291
  deviceId: number(),
75323
- trackId: string(),
75324
- /** Provenance only. It may already point at nothing — that is expected. */
75325
- sourceMediaId: number().int(),
76292
+ origin: RetrainFrameOriginSchema,
76293
+ /** The track it was copied from. Absent on a recording still. */
76294
+ trackId: string().optional(),
76295
+ /** Provenance only. It may already point at nothing — that is expected.
76296
+ * Absent on a recording still. */
76297
+ sourceMediaId: number().int().optional(),
76298
+ /** A recording still: the playhead instant it was taken at. */
76299
+ epochMs: number().optional(),
75326
76300
  sourceKind: MediaFileKindEnum,
75327
76301
  sizeBytes: number().int(),
75328
76302
  width: number().int(),
@@ -75333,7 +76307,12 @@ var RetrainFrameSchema = object({
75333
76307
  /** The operator's "every subject in this frame is boxed". Detector
75334
76308
  * evaluation keeps only complete frames: an unboxed subject would count as
75335
76309
  * a false positive. */
75336
- complete: boolean()
76310
+ complete: boolean(),
76311
+ /** The boxes the pipeline drew on this frame. Present on list answers;
76312
+ * empty when nothing the track store holds can be placed on it. */
76313
+ pipelineBoxes: array(RetrainPipelineBoxSchema).readonly().optional(),
76314
+ /** The named collections this frame belongs to. Present on list answers. */
76315
+ collectionIds: array(string()).readonly().optional()
75337
76316
  });
75338
76317
  /** Why a copy-on-select could not be honoured — named, never a silent skip. */
75339
76318
  var RetrainCopyRefusalSchema = _enum([
@@ -75364,6 +76343,8 @@ var RetrainFrameListSchema = object({
75364
76343
  var RetrainExportFilterSchema = object({
75365
76344
  deviceIds: array(number()).optional(),
75366
76345
  frameIds: array(string()).max(2e4).optional(),
76346
+ /** Only frames in at least one of these named collections. */
76347
+ collectionIds: array(string()).max(200).optional(),
75367
76348
  batchId: string().optional(),
75368
76349
  /** Only frames the operator marked complete (all subjects boxed). */
75369
76350
  completeOnly: boolean().optional()
@@ -75428,6 +76409,109 @@ var RetrainAssistResultSchema = discriminatedUnion("kind", [object({
75428
76409
  reason: string(),
75429
76410
  detail: string().optional()
75430
76411
  })]);
76412
+ /** A named set over the retrain corpus — membership only, it owns no pixels. */
76413
+ var RetrainCollectionSchema = object({
76414
+ id: string(),
76415
+ name: string(),
76416
+ createdAt: number(),
76417
+ frameCount: number().int()
76418
+ });
76419
+ var RetrainCollectionCreateResultSchema = discriminatedUnion("kind", [object({
76420
+ kind: literal("created"),
76421
+ collection: RetrainCollectionSchema
76422
+ }), object({
76423
+ kind: literal("refused"),
76424
+ reason: _enum(["empty-name", "duplicate-name"])
76425
+ })]);
76426
+ var RetrainCollectionRenameResultSchema = discriminatedUnion("kind", [object({
76427
+ kind: literal("renamed"),
76428
+ collection: RetrainCollectionSchema
76429
+ }), object({
76430
+ kind: literal("refused"),
76431
+ reason: _enum([
76432
+ "empty-name",
76433
+ "duplicate-name",
76434
+ "unknown-collection"
76435
+ ])
76436
+ })]);
76437
+ /**
76438
+ * The outcome of adding the frame at a recording instant. Every refusal is
76439
+ * named: `still-unavailable` (not recording, a gap, or an undecodable frame —
76440
+ * `detail` says which), `still-busy` (the recorder is at its decode bound; try
76441
+ * again), `unreadable-image`, `write-failed`, `unknown-collection`.
76442
+ */
76443
+ var AddRetrainFrameFromRecordingResultSchema = discriminatedUnion("kind", [object({
76444
+ kind: literal("added"),
76445
+ collectionId: string(),
76446
+ frame: RetrainFrameSchema,
76447
+ /** The moment was already in the dataset; nothing was decoded. */
76448
+ reused: boolean()
76449
+ }), object({
76450
+ kind: literal("refused"),
76451
+ reason: _enum([
76452
+ "unknown-collection",
76453
+ "still-unavailable",
76454
+ "still-busy",
76455
+ "unreadable-image",
76456
+ "write-failed"
76457
+ ]),
76458
+ detail: string().optional()
76459
+ })]);
76460
+ /** A vision LLM profile the AI assist may use, and where it sends the frame. */
76461
+ var RetrainAssistProfileSchema = object({
76462
+ id: string(),
76463
+ name: string(),
76464
+ model: string(),
76465
+ kind: string(),
76466
+ /** `true` when the frame would leave the house (a cloud vendor, or an
76467
+ * endpoint that is not on the local network). The page confirms each such
76468
+ * run, and the provider refuses one without `allowCloud`. */
76469
+ leavesHouse: boolean()
76470
+ });
76471
+ /** A box the AI assist proposed: a draft, plus the model's own reason. */
76472
+ var RetrainLlmProposalSchema = RetrainAnnotationDraftSchema.extend({ reason: string() });
76473
+ /** What the AI assist said about a box that was already on the canvas. */
76474
+ var RetrainLlmReviewSchema = object({
76475
+ /** The `ref` the page sent the box under. */
76476
+ ref: string(),
76477
+ verdict: _enum([
76478
+ "confirmed",
76479
+ "wrong-class",
76480
+ "not-an-object",
76481
+ "uncertain"
76482
+ ]),
76483
+ suggestedClass: RetrainMacroClassSchema.optional(),
76484
+ reason: string()
76485
+ });
76486
+ /**
76487
+ * The AI assist's answer. `proposed` carries drafts (`source: 'llm'`, the
76488
+ * model and its confidence) and reviews; items the model got wrong (a box off
76489
+ * the frame, an unasked class, an unknown ref) are dropped and counted in
76490
+ * `rejected`. A whole answer that is not the schema is `malformed-answer`.
76491
+ */
76492
+ var RetrainLlmAssistResultSchema = discriminatedUnion("kind", [object({
76493
+ kind: literal("proposed"),
76494
+ profileId: string(),
76495
+ model: string(),
76496
+ /** The frame was sent outside the house for this answer. */
76497
+ leftHouse: boolean(),
76498
+ proposals: array(RetrainLlmProposalSchema).readonly(),
76499
+ reviews: array(RetrainLlmReviewSchema).readonly(),
76500
+ rejected: number().int()
76501
+ }), object({
76502
+ kind: literal("refused"),
76503
+ reason: _enum([
76504
+ "unknown-frame",
76505
+ "unreadable-frame",
76506
+ "unknown-profile",
76507
+ "profile-disabled",
76508
+ "no-vision",
76509
+ "cloud-not-confirmed",
76510
+ "llm-error",
76511
+ "malformed-answer"
76512
+ ]),
76513
+ detail: string().optional()
76514
+ })]);
75431
76515
  /** The outcome of a lifecycle move owned by the retrain page. */
75432
76516
  var RetrainTransitionResultSchema = object({
75433
76517
  trackId: string(),
@@ -76145,7 +77229,7 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
76145
77229
  auth: "admin"
76146
77230
  }), method(object({
76147
77231
  deviceId: number(),
76148
- trackId: string(),
77232
+ trackId: string().optional(),
76149
77233
  frameId: string()
76150
77234
  }), object({
76151
77235
  removed: boolean(),
@@ -76162,7 +77246,8 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
76162
77246
  auth: "admin"
76163
77247
  }), method(object({
76164
77248
  deviceId: number(),
76165
- trackId: string(),
77249
+ /** The frame's track, when it has one — checked against the frame. */
77250
+ trackId: string().optional(),
76166
77251
  frameId: string(),
76167
77252
  subject: RetrainAssistSubjectSchema,
76168
77253
  /** Which node runs it. Absent ⇒ wherever an unowned call lands. */
@@ -76170,12 +77255,16 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
76170
77255
  }), RetrainAssistResultSchema, {
76171
77256
  kind: "mutation",
76172
77257
  auth: "admin"
76173
- }), method(object({ trackId: string() }), array(RetrainAnnotationSchema).readonly(), {
77258
+ }), method(object({
77259
+ trackId: string().optional(),
77260
+ frameIds: array(string()).max(2e3).optional()
77261
+ }), array(RetrainAnnotationSchema).readonly(), {
76174
77262
  kind: "query",
76175
77263
  auth: "admin"
76176
77264
  }), method(object({
76177
77265
  deviceId: number(),
76178
- trackId: string(),
77266
+ /** The frame's track, when it has one — checked against the frame. */
77267
+ trackId: string().optional(),
76179
77268
  frameId: string(),
76180
77269
  annotations: array(RetrainAnnotationDraftSchema)
76181
77270
  }), array(RetrainAnnotationSchema).readonly(), {
@@ -76198,7 +77287,7 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
76198
77287
  auth: "admin"
76199
77288
  }), method(object({
76200
77289
  deviceId: number(),
76201
- trackId: string(),
77290
+ trackId: string().optional(),
76202
77291
  frameId: string(),
76203
77292
  complete: boolean()
76204
77293
  }), RetrainFrameSchema, {
@@ -76212,6 +77301,74 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
76212
77301
  kind: "mutation",
76213
77302
  auth: "admin",
76214
77303
  timeoutMs: 60 * 6e4
77304
+ }), method(object({}), array(RetrainAssistProfileSchema).readonly(), {
77305
+ kind: "query",
77306
+ auth: "admin"
77307
+ }), method(object({
77308
+ deviceId: number(),
77309
+ trackId: string().optional(),
77310
+ frameId: string(),
77311
+ profileId: string(),
77312
+ classes: array(RetrainMacroClassSchema).min(1),
77313
+ boxes: array(object({
77314
+ ref: string(),
77315
+ bbox: RetrainBboxSchema,
77316
+ macroClass: RetrainMacroClassSchema,
77317
+ label: string().optional()
77318
+ })).max(50),
77319
+ allowCloud: boolean()
77320
+ }), RetrainLlmAssistResultSchema, {
77321
+ kind: "mutation",
77322
+ auth: "admin",
77323
+ timeoutMs: 18e4
77324
+ }), method(object({ name: string().max(120) }), RetrainCollectionCreateResultSchema, {
77325
+ kind: "mutation",
77326
+ auth: "admin"
77327
+ }), method(object({}), array(RetrainCollectionSchema).readonly(), {
77328
+ kind: "query",
77329
+ auth: "admin"
77330
+ }), method(object({
77331
+ id: string(),
77332
+ name: string().max(120)
77333
+ }), RetrainCollectionRenameResultSchema, {
77334
+ kind: "mutation",
77335
+ auth: "admin"
77336
+ }), method(object({ id: string() }), object({
77337
+ deleted: boolean(),
77338
+ removedFrames: number().int()
77339
+ }), {
77340
+ kind: "mutation",
77341
+ auth: "admin"
77342
+ }), method(object({
77343
+ collectionId: string(),
77344
+ deviceId: number(),
77345
+ epochMs: number()
77346
+ }), AddRetrainFrameFromRecordingResultSchema, {
77347
+ kind: "mutation",
77348
+ auth: "admin",
77349
+ timeoutMs: 6e4
77350
+ }), method(object({
77351
+ collectionId: string(),
77352
+ frameIds: array(string()).min(1).max(500)
77353
+ }), object({
77354
+ added: number().int(),
77355
+ alreadyMember: number().int(),
77356
+ unknownFrameIds: array(string()).readonly()
77357
+ }), {
77358
+ kind: "mutation",
77359
+ auth: "admin"
77360
+ }), method(object({
77361
+ collectionId: string(),
77362
+ frameId: string()
77363
+ }), object({
77364
+ removed: boolean(),
77365
+ deletedFrame: boolean()
77366
+ }), {
77367
+ kind: "mutation",
77368
+ auth: "admin"
77369
+ }), method(object({ collectionId: string() }), array(RetrainFrameSchema).readonly(), {
77370
+ kind: "query",
77371
+ auth: "admin"
76215
77372
  }), method(object({
76216
77373
  /** Which of the three event tables owns the row. */
76217
77374
  ownerType: EventOwnerTypeSchema,
@@ -76835,13 +77992,31 @@ var RecommendationReasonSchema = discriminatedUnion("kind", [
76835
77992
  object({
76836
77993
  kind: literal("no-family-build"),
76837
77994
  format: ModelFormatSchema$1
77995
+ }),
77996
+ object({
77997
+ kind: literal("kept-custom-pin"),
77998
+ modelId: string(),
77999
+ deviceKey: string()
76838
78000
  })
76839
78001
  ]);
78002
+ /** Why a device is left exactly as it is, whatever the plan would pick (D786). */
78003
+ var KeptReasonSchema = _enum(["custom-pin"]);
78004
+ /**
78005
+ * Where a choice's latency came from (D791): this node's own benchmark
78006
+ * result, or the hardware-class table. Measured on the node beats the table.
78007
+ */
78008
+ var LatencySourceSchema = discriminatedUnion("kind", [object({ kind: literal("table") }), object({
78009
+ kind: literal("node-benchmark"),
78010
+ resultId: string(),
78011
+ measuredAtMs: number()
78012
+ })]);
76840
78013
  var DeviceModelChoiceSchema = object({
76841
78014
  modelId: string(),
76842
78015
  p50Ms: number(),
76843
78016
  fps: number(),
76844
78017
  measured: boolean(),
78018
+ /** Absent on a plan from before D791 — read as the table. */
78019
+ source: LatencySourceSchema.optional(),
76845
78020
  /** Parallel sessions at the camera rate with the headroom kept free: ⌊fps × (1 − headroom) / camera fps⌋. */
76846
78021
  capacitySessions: number(),
76847
78022
  personRecall: number()
@@ -76852,6 +78027,8 @@ var DeviceRecommendationSchema = object({
76852
78027
  enabled: boolean(),
76853
78028
  available: boolean(),
76854
78029
  chosen: DeviceModelChoiceSchema.nullable(),
78030
+ /** Present when the device is kept as is: Apply writes nothing on it. */
78031
+ kept: KeptReasonSchema.optional(),
76855
78032
  reasons: array(RecommendationReasonSchema).readonly()
76856
78033
  });
76857
78034
  var NodeRecommendationSchema = object({
@@ -76905,6 +78082,17 @@ var AutoTuneWarningSchema = discriminatedUnion("kind", [
76905
78082
  kind: literal("coral-enabled"),
76906
78083
  nodeId: string(),
76907
78084
  deviceKey: string()
78085
+ }),
78086
+ object({
78087
+ kind: literal("custom-pin-kept"),
78088
+ nodeId: string(),
78089
+ deviceKey: string().nullable(),
78090
+ deviceId: number().nullable(),
78091
+ modelId: string()
78092
+ }),
78093
+ object({
78094
+ kind: literal("custom-registry-unreadable"),
78095
+ error: string()
76908
78096
  })
76909
78097
  ]);
76910
78098
  var AutoTuneOptionsSchema = object({
@@ -77083,13 +78271,14 @@ var SuggestSharesResultSchema = object({
77083
78271
  nodes: array(SuggestedNodeShareSchema).readonly()
77084
78272
  });
77085
78273
  /**
77086
- * Where the node and device shares come from (D750, D755).
77087
- * - `hardware` (default) — computed by the system from each node's static
77088
- * capacity (its accelerators at their Auto tune models, from the measured
77089
- * latency table), recomputed whenever a node or device joins, leaves, is
77090
- * switched on or off, or changes model. No load input.
77091
- * - `benchmark` — the same, from each node's measured capacity (node
77092
- * benchmark results); a node without results falls back to `hardware`.
78274
+ * Where the node and device shares come from (D750, D755, D791).
78275
+ * - `benchmark` (default since D791) — each node's capacity as its own node
78276
+ * benchmark measured it; a node without fresh results is sized from
78277
+ * `hardware` and says so. Measured on the node beats the table.
78278
+ * - `hardware` — computed from each node's static capacity only (its
78279
+ * accelerators at their Auto tune models, from the latency table).
78280
+ * Both are recomputed whenever a node or device joins, leaves, is switched
78281
+ * on or off, changes model, or a benchmark result is written. No load input.
77093
78282
  * - `manual` — the operator's stored sliders.
77094
78283
  * Either way a node or device that cannot take sessions gives its share to
77095
78284
  * the others in proportion; the stored values are never rewritten for that.
@@ -77138,6 +78327,362 @@ var EffectiveSharesSchema = object({
77138
78327
  nodeWeights: record(string(), number()),
77139
78328
  deviceWeights: record(string(), record(string(), number()))
77140
78329
  });
78330
+ /**
78331
+ * Wire shapes of the node benchmark (D791): the operator's plan, the
78332
+ * preflight the confirmation shows, the run the orchestrator owns, what the
78333
+ * measuring runner reports, and the result rows Auto tune and the automatic
78334
+ * shares read.
78335
+ *
78336
+ * ONE node at a time, owned by the pipeline orchestrator. While a run is
78337
+ * active the cluster is in BENCHMARK MODE for that node: it is not a
78338
+ * detection candidate, camera pins naming it are ignored so its sessions move
78339
+ * elsewhere, and both come back when the mode ends — after a crash or a hub
78340
+ * restart too (a persisted manifest, reconciled against the registry).
78341
+ *
78342
+ * Two measurements, both on the node, driven by its own runner (frames never
78343
+ * cross a process at frame rate, D9):
78344
+ * - `device` — one accelerator × one candidate detector, root only, open
78345
+ * loop: how many streams at the camera rate it carries inside the frame
78346
+ * interval;
78347
+ * - `pipeline` — the chosen detector plus the operator's detail steps
78348
+ * (faces, plates, classifiers, CLIP…), on varied frames from the bench
78349
+ * clip: how many parallel sessions the node carries before latency, drops,
78350
+ * CPU, RAM or the event loop give out.
78351
+ */
78352
+ /** Defaults and bounds, one place. */
78353
+ var NODE_BENCHMARK_DEFAULTS = {
78354
+ fpsPerStream: 10,
78355
+ budgetMinutes: 45,
78356
+ minBudgetMinutes: 10,
78357
+ maxBudgetMinutes: 120,
78358
+ /** A result older than this no longer beats the table. */
78359
+ staleAfterDays: 30,
78360
+ /** Warm-in per ramp step (not accounted). */
78361
+ settleSec: 5,
78362
+ /** Accounted window per ramp step. */
78363
+ measureSec: 20,
78364
+ /** Longest the drain may take before the run is refused. */
78365
+ drainTimeoutSec: 120,
78366
+ /** Candidate models per device in one run. */
78367
+ maxModelsPerDevice: 6
78368
+ };
78369
+ /** The two measurements a run can make. */
78370
+ var NodeBenchmarkPhaseSchema = _enum(["device", "pipeline"]);
78371
+ var NodeBenchmarkDevicePlanSchema = object({
78372
+ /** `<backend>:<device>` — `openvino:npu`, `coreml:all`, `cpu`. */
78373
+ deviceKey: string().min(1),
78374
+ /**
78375
+ * Root detector candidates for the `device` measurement, in the order
78376
+ * measured. The FIRST is the one the `pipeline` measurement runs.
78377
+ */
78378
+ modelIds: array(string().min(1)).min(1).max(NODE_BENCHMARK_DEFAULTS.maxModelsPerDevice)
78379
+ });
78380
+ /** What the operator confirmed. */
78381
+ var NodeBenchmarkPlanSchema = object({
78382
+ nodeId: string().min(1),
78383
+ devices: array(NodeBenchmarkDevicePlanSchema).min(1),
78384
+ /** Which measurements run. At least one. */
78385
+ phases: array(NodeBenchmarkPhaseSchema).min(1).default(["device", "pipeline"]),
78386
+ /**
78387
+ * Detail steps (catalog step ids under the root: faces, plates,
78388
+ * classifiers, CLIP…) the `pipeline` measurement enables. The root
78389
+ * detector always runs.
78390
+ */
78391
+ steps: array(string().min(1)).default([]),
78392
+ /** Offered rate of one stream / session. */
78393
+ fpsPerStream: number().int().min(1).max(30).default(NODE_BENCHMARK_DEFAULTS.fpsPerStream),
78394
+ /** Hard deadline: the mode ends and the cluster is restored when it passes. */
78395
+ budgetMinutes: number().int().min(NODE_BENCHMARK_DEFAULTS.minBudgetMinutes).max(NODE_BENCHMARK_DEFAULTS.maxBudgetMinutes).default(NODE_BENCHMARK_DEFAULTS.budgetMinutes),
78396
+ /** Keep the models the run downloaded (default: delete what was not installed before). */
78397
+ keepDownloadedModels: boolean().default(false),
78398
+ /** Start although the other nodes' capacity does not cover the sessions running now. */
78399
+ acceptInsufficientHeadroom: boolean().default(false)
78400
+ });
78401
+ var NodeBenchmarkRefusalSchema = object({
78402
+ kind: _enum([
78403
+ "benchmark-active",
78404
+ "node-offline",
78405
+ "unknown-device",
78406
+ "no-phase",
78407
+ "insufficient-headroom"
78408
+ ]),
78409
+ detail: string(),
78410
+ overridable: boolean()
78411
+ });
78412
+ /** A camera whose detection leaves the node for the run. */
78413
+ var NodeBenchmarkMovingCameraSchema = object({
78414
+ deviceId: number(),
78415
+ /** Placed on the node now (a standing attach or a running session). */
78416
+ placedOnNode: boolean(),
78417
+ /** A node pin naming this node, ignored for the run. */
78418
+ pinnedToNode: boolean()
78419
+ });
78420
+ /** A camera that cannot leave: no other node can obtain its frames. */
78421
+ var NodeBenchmarkStayingCameraSchema = object({
78422
+ deviceId: number(),
78423
+ reason: literal("only-frame-source")
78424
+ });
78425
+ var NodeBenchmarkPreflightSchema = object({
78426
+ nodeId: string(),
78427
+ online: boolean(),
78428
+ moving: array(NodeBenchmarkMovingCameraSchema).readonly(),
78429
+ /** Keep running on the node during the run; the result is flagged contaminated. */
78430
+ staying: array(NodeBenchmarkStayingCameraSchema).readonly(),
78431
+ estimatedDurationMs: number(),
78432
+ /** The run ends and the cluster is restored at the latest after this long. */
78433
+ budgetMs: number(),
78434
+ phases: array(NodeBenchmarkPhaseSchema).readonly(),
78435
+ steps: array(string()).readonly(),
78436
+ devices: array(NodeBenchmarkDevicePlanSchema).readonly(),
78437
+ /** Parallel sessions the cluster runs now, and what the other nodes can carry. */
78438
+ headroom: object({
78439
+ sessionsNow: number(),
78440
+ otherNodesCapacitySessions: number().nullable()
78441
+ }),
78442
+ refusals: array(NodeBenchmarkRefusalSchema).readonly(),
78443
+ canStart: boolean()
78444
+ });
78445
+ /** Where the measuring runner is. */
78446
+ var NodeBenchProgressSchema = object({
78447
+ phase: _enum([
78448
+ "preparing",
78449
+ "device",
78450
+ "pipeline",
78451
+ "cleanup"
78452
+ ]),
78453
+ deviceKey: string().nullable(),
78454
+ modelId: string().nullable(),
78455
+ /** Streams (device) or sessions (pipeline) of the step running now. */
78456
+ load: number().nullable(),
78457
+ cellsDone: number(),
78458
+ cellsTotal: number(),
78459
+ message: string()
78460
+ });
78461
+ /** What limited a ramp. `none` = the ramp ran out of steps still passing. */
78462
+ var NodeBenchLimitSchema = _enum([
78463
+ "p95",
78464
+ "drops",
78465
+ "errors",
78466
+ "stall",
78467
+ "cpu",
78468
+ "ram",
78469
+ "none"
78470
+ ]);
78471
+ var NodeBenchRampStepSchema = object({
78472
+ load: number(),
78473
+ pass: boolean(),
78474
+ p95Ms: number(),
78475
+ dropRatio: number(),
78476
+ /** Completed frames per second over the accounted window. */
78477
+ fps: number(),
78478
+ cpuPct: number().nullable(),
78479
+ ramFreePct: number().nullable(),
78480
+ failReasons: array(string()).readonly()
78481
+ });
78482
+ var NodeBenchCellSchema = discriminatedUnion("phase", [object({
78483
+ phase: literal("device"),
78484
+ deviceKey: string(),
78485
+ modelId: string(),
78486
+ /** Single-stream latency (the K = 1 step). */
78487
+ p50Ms: number(),
78488
+ p95Ms: number(),
78489
+ p99Ms: number(),
78490
+ /** Frames per second sustained at the last passing step. */
78491
+ fps: number(),
78492
+ /** Streams at the camera rate the device carried inside the frame interval; 0 = not even one. */
78493
+ kMax: number(),
78494
+ limitedBy: NodeBenchLimitSchema,
78495
+ /** First call (model load + warm-up). */
78496
+ warmupMs: number(),
78497
+ ramp: array(NodeBenchRampStepSchema).readonly()
78498
+ }), object({
78499
+ phase: literal("pipeline"),
78500
+ deviceKey: string(),
78501
+ modelId: string(),
78502
+ steps: array(string()).readonly(),
78503
+ /** Parallel sessions at the camera rate the node carried; 0 = not even one. */
78504
+ maxSessions: number(),
78505
+ limitedBy: NodeBenchLimitSchema,
78506
+ /** Detail steps that produced at least one result on the clip — a step that never fired measured nothing. */
78507
+ stepsFired: array(string()).readonly(),
78508
+ warmupMs: number(),
78509
+ ramp: array(NodeBenchRampStepSchema).readonly()
78510
+ })]);
78511
+ /**
78512
+ * What a result was measured ON. A result whose fingerprint no longer matches
78513
+ * the node no longer beats the table.
78514
+ */
78515
+ var NodeBenchFingerprintSchema = object({
78516
+ pipelineVersion: string().nullable(),
78517
+ cpuModel: string().nullable(),
78518
+ ramGb: number().nullable(),
78519
+ os: string().nullable(),
78520
+ /** Per device: the pool the cells ran on (runtime + tuning). */
78521
+ pools: record(string(), object({
78522
+ runtime: string(),
78523
+ numWorkers: number(),
78524
+ concurrency: number(),
78525
+ batchMode: string()
78526
+ })).default({})
78527
+ });
78528
+ /** The frames the run used. */
78529
+ var NodeBenchClipSchema = object({
78530
+ /** `camstack-bench-v1` or `reference-images` (the fallback when the clip is not reachable). */
78531
+ id: string(),
78532
+ revision: string().nullable(),
78533
+ frames: number(),
78534
+ width: number(),
78535
+ height: number()
78536
+ });
78537
+ var NodeBenchRunnerInputSchema = object({
78538
+ runId: string().min(1),
78539
+ devices: array(NodeBenchmarkDevicePlanSchema).min(1),
78540
+ phases: array(NodeBenchmarkPhaseSchema).min(1),
78541
+ /** The full detail step tree root for the `pipeline` measurement is built on the node from these ids. */
78542
+ steps: array(string()).default([]),
78543
+ fpsPerStream: number().int().min(1).max(30),
78544
+ /** The runner stops on its own past this instant, whatever the hub does. */
78545
+ deadlineAtMs: number(),
78546
+ settleSec: number().min(0).max(60).default(NODE_BENCHMARK_DEFAULTS.settleSec),
78547
+ measureSec: number().min(2).max(300).default(NODE_BENCHMARK_DEFAULTS.measureSec),
78548
+ keepDownloadedModels: boolean().default(false)
78549
+ });
78550
+ var NodeBenchRunnerStateSchema = _enum([
78551
+ "running",
78552
+ "done",
78553
+ "failed",
78554
+ "aborted"
78555
+ ]);
78556
+ var NodeBenchRunnerStatusSchema = object({
78557
+ runId: string(),
78558
+ nodeId: string(),
78559
+ state: NodeBenchRunnerStateSchema,
78560
+ progress: NodeBenchProgressSchema.nullable(),
78561
+ /** Every finished cell so far — a run stopped half way keeps what it measured. */
78562
+ cells: array(NodeBenchCellSchema).readonly(),
78563
+ fingerprint: NodeBenchFingerprintSchema.nullable(),
78564
+ clip: NodeBenchClipSchema.nullable(),
78565
+ /** Cameras seen running on the node during the run (they share its pools). */
78566
+ activeCameraIds: array(number()).readonly(),
78567
+ /** Models the run downloaded and then deleted (not installed before). */
78568
+ deletedModels: array(string()).readonly(),
78569
+ error: string().nullable(),
78570
+ startedAtMs: number(),
78571
+ finishedAtMs: number().nullable()
78572
+ });
78573
+ var NodeBenchmarkStateSchema = _enum([
78574
+ "draining",
78575
+ "measuring",
78576
+ "restoring",
78577
+ "done",
78578
+ "failed",
78579
+ "aborted"
78580
+ ]);
78581
+ /** Why a run ended. */
78582
+ var NodeBenchmarkEndReasonSchema = _enum([
78583
+ "completed",
78584
+ "operator-abort",
78585
+ "deadline",
78586
+ "node-lost",
78587
+ "runner-lost",
78588
+ "hub-restart",
78589
+ "drain-timeout",
78590
+ "failed"
78591
+ ]);
78592
+ var NodeBenchmarkRunSchema = object({
78593
+ runId: string(),
78594
+ nodeId: string(),
78595
+ state: NodeBenchmarkStateSchema,
78596
+ plan: NodeBenchmarkPlanSchema,
78597
+ startedAtMs: number(),
78598
+ deadlineAtMs: number(),
78599
+ finishedAtMs: number().nullable(),
78600
+ endReason: NodeBenchmarkEndReasonSchema.nullable(),
78601
+ error: string().nullable(),
78602
+ /** Cameras moved off the node for the run. */
78603
+ moved: array(number()).readonly(),
78604
+ /** Cameras that stayed (their only frame source is the node). */
78605
+ staying: array(number()).readonly(),
78606
+ /** Something else ran on the node's pools during the run. */
78607
+ contaminated: boolean(),
78608
+ progress: NodeBenchProgressSchema.nullable(),
78609
+ resultIds: array(string()).readonly()
78610
+ });
78611
+ /** `getNodeBenchmarkStatus`: the active run (or the last one), and whether benchmark mode is on. */
78612
+ var NodeBenchmarkStatusSchema = object({
78613
+ /** The node the cluster is in benchmark mode for; null = none. */
78614
+ modeNodeId: string().nullable(),
78615
+ run: NodeBenchmarkRunSchema.nullable()
78616
+ });
78617
+ /**
78618
+ * One stored measurement — the only authority Auto tune and the automatic
78619
+ * shares read measured capacity from. Written by the orchestrator when a run
78620
+ * ends, never by anyone else.
78621
+ */
78622
+ var NodeBenchmarkResultSchema = object({
78623
+ id: string(),
78624
+ runId: string(),
78625
+ nodeId: string(),
78626
+ cell: NodeBenchCellSchema,
78627
+ fpsPerStream: number(),
78628
+ fingerprint: NodeBenchFingerprintSchema.nullable(),
78629
+ clip: NodeBenchClipSchema.nullable(),
78630
+ /** Other work shared the node's pools (a camera that could not move, or the hub's own duties). */
78631
+ contaminated: boolean(),
78632
+ stayingCameras: array(number()).readonly(),
78633
+ /** The run ended early; the cell itself completed. */
78634
+ partialRun: boolean(),
78635
+ measuredAtMs: number()
78636
+ });
78637
+ var ListNodeBenchmarkResultsInputSchema = object({
78638
+ nodeId: string().optional(),
78639
+ deviceKey: string().optional()
78640
+ });
78641
+ /** A result with its standing today: does it still beat the table? */
78642
+ var NodeBenchmarkResultViewSchema = NodeBenchmarkResultSchema.extend({
78643
+ /** `fresh` beats the table; `stale` falls back to it; `superseded` = a newer row covers the same cell. */
78644
+ standing: _enum([
78645
+ "fresh",
78646
+ "stale",
78647
+ "superseded"
78648
+ ]),
78649
+ staleWhy: _enum([
78650
+ "age",
78651
+ "runtime",
78652
+ "pool-tuning"
78653
+ ]).nullable()
78654
+ });
78655
+ object({
78656
+ runId: string(),
78657
+ nodeId: string(),
78658
+ startedAtMs: number(),
78659
+ deadlineAtMs: number(),
78660
+ plan: NodeBenchmarkPlanSchema,
78661
+ moved: array(number()).readonly(),
78662
+ staying: array(number()).readonly()
78663
+ });
78664
+ /** Candidate detectors per device, for the plan editor. */
78665
+ var NodeBenchmarkCandidatesSchema = object({
78666
+ nodeId: string(),
78667
+ reachable: boolean(),
78668
+ devices: array(object({
78669
+ deviceKey: string(),
78670
+ enabled: boolean(),
78671
+ available: boolean(),
78672
+ /** Ordered: what Auto tune would pick first, then the rest of the family by accuracy. */
78673
+ suggested: array(string()).readonly(),
78674
+ /** Every root detector the device has a build for. */
78675
+ all: array(string()).readonly(),
78676
+ /** The model the device runs now, when pinned. */
78677
+ currentModelId: string().nullable()
78678
+ })).readonly(),
78679
+ /** Detail steps the node's catalog offers under the root (for the `pipeline` measurement). */
78680
+ steps: array(object({
78681
+ id: string(),
78682
+ name: string(),
78683
+ slot: string()
78684
+ })).readonly()
78685
+ });
77141
78686
  object({
77142
78687
  activeCameras: number(),
77143
78688
  throttledCameras: number(),
@@ -78266,7 +79811,16 @@ method(RunnerCameraConfigSchema, object({ success: literal(true) }), { kind: "mu
78266
79811
  }), ParkedTrackFrameSchema.nullable()), method(object({
78267
79812
  deviceId: number(),
78268
79813
  trackId: string()
78269
- }), object({ released: number().int().nonnegative() }), { kind: "mutation" });
79814
+ }), object({ released: number().int().nonnegative() }), { kind: "mutation" }), method(NodeBenchRunnerInputSchema, object({
79815
+ accepted: literal(true),
79816
+ runId: string()
79817
+ }), {
79818
+ kind: "mutation",
79819
+ auth: "admin"
79820
+ }), method(object({ runId: string() }), NodeBenchRunnerStatusSchema.nullable(), { auth: "admin" }), method(object({ runId: string() }), object({ aborted: boolean() }), {
79821
+ kind: "mutation",
79822
+ auth: "admin"
79823
+ });
78270
79824
  var CameraPipelineConfigSchema = object({
78271
79825
  engine: PipelineEngineChoiceSchema.optional(),
78272
79826
  steps: array(PipelineStepInputSchema).readonly(),
@@ -78905,6 +80459,21 @@ method(object({
78905
80459
  }), method(PlacementStatsInputSchema, PlacementStatsSchema, { auth: "admin" }), method(SuggestSharesInputSchema, SuggestSharesResultSchema, { auth: "admin" }), method(_void(), EffectiveSharesSchema, { auth: "admin" }), method(SetShareSourceInputSchema, object({ success: literal(true) }), {
78906
80460
  kind: "mutation",
78907
80461
  auth: "admin"
80462
+ }), method(NodeBenchmarkPlanSchema, NodeBenchmarkPreflightSchema, { auth: "admin" }), method(NodeBenchmarkPlanSchema, discriminatedUnion("kind", [object({
80463
+ kind: literal("started"),
80464
+ runId: string()
80465
+ }), object({
80466
+ kind: literal("refused"),
80467
+ preflight: NodeBenchmarkPreflightSchema
80468
+ })]), {
80469
+ kind: "mutation",
80470
+ auth: "admin"
80471
+ }), method(_void(), NodeBenchmarkStatusSchema, { auth: "admin" }), method(object({ runId: string() }), object({ aborted: boolean() }), {
80472
+ kind: "mutation",
80473
+ auth: "admin"
80474
+ }), method(object({ nodeId: string() }), NodeBenchmarkCandidatesSchema, { auth: "admin" }), method(ListNodeBenchmarkResultsInputSchema, array(NodeBenchmarkResultViewSchema).readonly(), { auth: "admin" }), method(object({ id: string() }), object({ deleted: boolean() }), {
80475
+ kind: "mutation",
80476
+ auth: "admin"
78908
80477
  }), method(object({ deviceId: number() }), CameraPipelineSettingsSchema.nullable()), method(object({
78909
80478
  deviceId: number(),
78910
80479
  addonId: string(),
@@ -85037,6 +86606,9 @@ var CreateIntegrationInputSchema = object({
85037
86606
  enabled: boolean().optional(),
85038
86607
  info: record(string(), unknown()).optional(),
85039
86608
  settings: record(string(), unknown()).optional(),
86609
+ /** Keys of `settings` the form's schema declares secret (by type) — kept in
86610
+ * the keychain, not the table (D787). */
86611
+ secretKeys: array(string()).optional(),
85040
86612
  skipRestart: boolean().optional()
85041
86613
  });
85042
86614
  var UpdateIntegrationInputSchema = object({
@@ -85060,7 +86632,9 @@ method(_void(), array(IntegrationWithStateSchema)), method(object({ id: string()
85060
86632
  auth: "admin"
85061
86633
  }), method(object({ id: string() }), record(string(), unknown()), { auth: "admin" }), method(object({
85062
86634
  id: string(),
85063
- settings: record(string(), unknown())
86635
+ settings: record(string(), unknown()),
86636
+ /** Keys the form's schema declares secret (by type) — keychain-stored (D787). */
86637
+ secretKeys: array(string()).optional()
85064
86638
  }), object({ success: boolean() }), {
85065
86639
  kind: "mutation",
85066
86640
  auth: "admin"
@@ -93371,7 +94945,8 @@ var BaseDevice = class {
93371
94945
  this.role = options.role;
93372
94946
  this.parentDeviceId = ctx.parentDeviceId;
93373
94947
  const seedData = ctx.persistedConfig ?? {};
93374
- this.config = DeviceConfig.fromSchema(schema, (data) => ctx.persistConfig(data), seedData, ({ droppedKeys, issues }) => {
94948
+ const declaredSecretPaths = collectZodSecretPaths(schema);
94949
+ this.config = DeviceConfig.fromSchema(schema, (data) => ctx.persistConfig(data, { secretConfigPaths: declaredSecretPaths }), seedData, ({ droppedKeys, issues }) => {
93375
94950
  ctx.logger.warn("Device config recovery: dropping invalid persisted fields", {
93376
94951
  tags: {
93377
94952
  deviceId: ctx.id,
@@ -97060,6 +98635,90 @@ Object.freeze({
97060
98635
  addonId: null,
97061
98636
  access: "create"
97062
98637
  },
98638
+ "keychain.delete": {
98639
+ capName: "keychain",
98640
+ capScope: "system",
98641
+ addonId: null,
98642
+ access: "delete"
98643
+ },
98644
+ "keychain.getState": {
98645
+ capName: "keychain",
98646
+ capScope: "system",
98647
+ addonId: null,
98648
+ access: "view"
98649
+ },
98650
+ "keychain.listMeta": {
98651
+ capName: "keychain",
98652
+ capScope: "system",
98653
+ addonId: null,
98654
+ access: "view"
98655
+ },
98656
+ "keychain.put": {
98657
+ capName: "keychain",
98658
+ capScope: "system",
98659
+ addonId: null,
98660
+ access: "create"
98661
+ },
98662
+ "keychain.resolve": {
98663
+ capName: "keychain",
98664
+ capScope: "system",
98665
+ addonId: null,
98666
+ access: "view"
98667
+ },
98668
+ "keychainAdmin.deleteOrphans": {
98669
+ capName: "keychain-admin",
98670
+ capScope: "system",
98671
+ addonId: null,
98672
+ access: "delete"
98673
+ },
98674
+ "keychainAdmin.downloadRecoveryKey": {
98675
+ capName: "keychain-admin",
98676
+ capScope: "system",
98677
+ addonId: null,
98678
+ access: "create"
98679
+ },
98680
+ "keychainAdmin.listAudit": {
98681
+ capName: "keychain-admin",
98682
+ capScope: "system",
98683
+ addonId: null,
98684
+ access: "view"
98685
+ },
98686
+ "keychainAdmin.listSecrets": {
98687
+ capName: "keychain-admin",
98688
+ capScope: "system",
98689
+ addonId: null,
98690
+ access: "view"
98691
+ },
98692
+ "keychainAdmin.purgeRetiredKeys": {
98693
+ capName: "keychain-admin",
98694
+ capScope: "system",
98695
+ addonId: null,
98696
+ access: "delete"
98697
+ },
98698
+ "keychainAdmin.resetKeychain": {
98699
+ capName: "keychain-admin",
98700
+ capScope: "system",
98701
+ addonId: null,
98702
+ access: "delete"
98703
+ },
98704
+ "keychainAdmin.reveal": {
98705
+ capName: "keychain-admin",
98706
+ capScope: "system",
98707
+ addonId: null,
98708
+ access: "create"
98709
+ },
98710
+ "keychainAdmin.rotateMasterKey": {
98711
+ capName: "keychain-admin",
98712
+ capScope: "system",
98713
+ addonId: null,
98714
+ access: "create"
98715
+ },
98716
+ "keychainAdmin.status": {
98717
+ capName: "keychain-admin",
98718
+ capScope: "system",
98719
+ addonId: null,
98720
+ access: "view"
98721
+ },
97063
98722
  "lawnMowerControl.dock": {
97064
98723
  capName: "lawn-mower-control",
97065
98724
  capScope: "device",
@@ -98434,6 +100093,18 @@ Object.freeze({
98434
100093
  addonId: null,
98435
100094
  access: "create"
98436
100095
  },
100096
+ "pipelineAnalytics.addRetrainFrameFromRecording": {
100097
+ capName: "pipeline-analytics",
100098
+ capScope: "device",
100099
+ addonId: null,
100100
+ access: "create"
100101
+ },
100102
+ "pipelineAnalytics.addRetrainFramesToCollection": {
100103
+ capName: "pipeline-analytics",
100104
+ capScope: "device",
100105
+ addonId: null,
100106
+ access: "create"
100107
+ },
98437
100108
  "pipelineAnalytics.applyDeviceSettingsPatch": {
98438
100109
  capName: "pipeline-analytics",
98439
100110
  capScope: "device",
@@ -98482,12 +100153,24 @@ Object.freeze({
98482
100153
  addonId: null,
98483
100154
  access: "view"
98484
100155
  },
100156
+ "pipelineAnalytics.createRetrainCollection": {
100157
+ capName: "pipeline-analytics",
100158
+ capScope: "device",
100159
+ addonId: null,
100160
+ access: "create"
100161
+ },
98485
100162
  "pipelineAnalytics.deleteDeviceEvents": {
98486
100163
  capName: "pipeline-analytics",
98487
100164
  capScope: "device",
98488
100165
  addonId: null,
98489
100166
  access: "delete"
98490
100167
  },
100168
+ "pipelineAnalytics.deleteRetrainCollection": {
100169
+ capName: "pipeline-analytics",
100170
+ capScope: "device",
100171
+ addonId: null,
100172
+ access: "delete"
100173
+ },
98491
100174
  "pipelineAnalytics.deleteTracks": {
98492
100175
  capName: "pipeline-analytics",
98493
100176
  capScope: "device",
@@ -98692,6 +100375,24 @@ Object.freeze({
98692
100375
  addonId: null,
98693
100376
  access: "view"
98694
100377
  },
100378
+ "pipelineAnalytics.listRetrainAssistProfiles": {
100379
+ capName: "pipeline-analytics",
100380
+ capScope: "device",
100381
+ addonId: null,
100382
+ access: "view"
100383
+ },
100384
+ "pipelineAnalytics.listRetrainCollectionFrames": {
100385
+ capName: "pipeline-analytics",
100386
+ capScope: "device",
100387
+ addonId: null,
100388
+ access: "view"
100389
+ },
100390
+ "pipelineAnalytics.listRetrainCollections": {
100391
+ capName: "pipeline-analytics",
100392
+ capScope: "device",
100393
+ addonId: null,
100394
+ access: "view"
100395
+ },
98695
100396
  "pipelineAnalytics.listRetrainFrames": {
98696
100397
  capName: "pipeline-analytics",
98697
100398
  capScope: "device",
@@ -98740,6 +100441,12 @@ Object.freeze({
98740
100441
  addonId: null,
98741
100442
  access: "create"
98742
100443
  },
100444
+ "pipelineAnalytics.proposeRetrainAnnotationsWithLlm": {
100445
+ capName: "pipeline-analytics",
100446
+ capScope: "device",
100447
+ addonId: null,
100448
+ access: "create"
100449
+ },
98743
100450
  "pipelineAnalytics.pruneEvents": {
98744
100451
  capName: "pipeline-analytics",
98745
100452
  capScope: "device",
@@ -98794,6 +100501,18 @@ Object.freeze({
98794
100501
  addonId: null,
98795
100502
  access: "create"
98796
100503
  },
100504
+ "pipelineAnalytics.removeRetrainFrameFromCollection": {
100505
+ capName: "pipeline-analytics",
100506
+ capScope: "device",
100507
+ addonId: null,
100508
+ access: "delete"
100509
+ },
100510
+ "pipelineAnalytics.renameRetrainCollection": {
100511
+ capName: "pipeline-analytics",
100512
+ capScope: "device",
100513
+ addonId: null,
100514
+ access: "create"
100515
+ },
98797
100516
  "pipelineAnalytics.restageRetrainTrack": {
98798
100517
  capName: "pipeline-analytics",
98799
100518
  capScope: "device",
@@ -99082,6 +100801,12 @@ Object.freeze({
99082
100801
  addonId: null,
99083
100802
  access: "view"
99084
100803
  },
100804
+ "pipelineOrchestrator.abortNodeBenchmark": {
100805
+ capName: "pipeline-orchestrator",
100806
+ capScope: "system",
100807
+ addonId: null,
100808
+ access: "create"
100809
+ },
99085
100810
  "pipelineOrchestrator.applyAutoTune": {
99086
100811
  capName: "pipeline-orchestrator",
99087
100812
  capScope: "system",
@@ -99106,6 +100831,12 @@ Object.freeze({
99106
100831
  addonId: null,
99107
100832
  access: "create"
99108
100833
  },
100834
+ "pipelineOrchestrator.deleteNodeBenchmarkResult": {
100835
+ capName: "pipeline-orchestrator",
100836
+ capScope: "system",
100837
+ addonId: null,
100838
+ access: "delete"
100839
+ },
99109
100840
  "pipelineOrchestrator.getAgentLoad": {
99110
100841
  capName: "pipeline-orchestrator",
99111
100842
  capScope: "system",
@@ -99214,6 +100945,24 @@ Object.freeze({
99214
100945
  addonId: null,
99215
100946
  access: "view"
99216
100947
  },
100948
+ "pipelineOrchestrator.getNodeBenchmarkCandidates": {
100949
+ capName: "pipeline-orchestrator",
100950
+ capScope: "system",
100951
+ addonId: null,
100952
+ access: "view"
100953
+ },
100954
+ "pipelineOrchestrator.getNodeBenchmarkPreflight": {
100955
+ capName: "pipeline-orchestrator",
100956
+ capScope: "system",
100957
+ addonId: null,
100958
+ access: "view"
100959
+ },
100960
+ "pipelineOrchestrator.getNodeBenchmarkStatus": {
100961
+ capName: "pipeline-orchestrator",
100962
+ capScope: "system",
100963
+ addonId: null,
100964
+ access: "view"
100965
+ },
99217
100966
  "pipelineOrchestrator.getNodeInferenceDevices": {
99218
100967
  capName: "pipeline-orchestrator",
99219
100968
  capScope: "system",
@@ -99256,6 +101005,12 @@ Object.freeze({
99256
101005
  addonId: null,
99257
101006
  access: "view"
99258
101007
  },
101008
+ "pipelineOrchestrator.listNodeBenchmarkResults": {
101009
+ capName: "pipeline-orchestrator",
101010
+ capScope: "system",
101011
+ addonId: null,
101012
+ access: "view"
101013
+ },
99259
101014
  "pipelineOrchestrator.pauseForStorageMigration": {
99260
101015
  capName: "pipeline-orchestrator",
99261
101016
  capScope: "system",
@@ -99400,6 +101155,12 @@ Object.freeze({
99400
101155
  addonId: null,
99401
101156
  access: "create"
99402
101157
  },
101158
+ "pipelineOrchestrator.startNodeBenchmark": {
101159
+ capName: "pipeline-orchestrator",
101160
+ capScope: "system",
101161
+ addonId: null,
101162
+ access: "create"
101163
+ },
99403
101164
  "pipelineOrchestrator.suggestShares": {
99404
101165
  capName: "pipeline-orchestrator",
99405
101166
  capScope: "system",
@@ -99418,6 +101179,12 @@ Object.freeze({
99418
101179
  addonId: null,
99419
101180
  access: "create"
99420
101181
  },
101182
+ "pipelineRunner.abortNodeBench": {
101183
+ capName: "pipeline-runner",
101184
+ capScope: "system",
101185
+ addonId: null,
101186
+ access: "create"
101187
+ },
99421
101188
  "pipelineRunner.attachCamera": {
99422
101189
  capName: "pipeline-runner",
99423
101190
  capScope: "system",
@@ -99466,6 +101233,12 @@ Object.freeze({
99466
101233
  addonId: null,
99467
101234
  access: "view"
99468
101235
  },
101236
+ "pipelineRunner.getNodeBenchStatus": {
101237
+ capName: "pipeline-runner",
101238
+ capScope: "system",
101239
+ addonId: null,
101240
+ access: "view"
101241
+ },
99469
101242
  "pipelineRunner.getParkedTrackFrame": {
99470
101243
  capName: "pipeline-runner",
99471
101244
  capScope: "system",
@@ -99508,6 +101281,12 @@ Object.freeze({
99508
101281
  addonId: null,
99509
101282
  access: "create"
99510
101283
  },
101284
+ "pipelineRunner.startNodeBench": {
101285
+ capName: "pipeline-runner",
101286
+ capScope: "system",
101287
+ addonId: null,
101288
+ access: "create"
101289
+ },
99511
101290
  "plateGallery.assignPlate": {
99512
101291
  capName: "plate-gallery",
99513
101292
  capScope: "system",
@@ -104437,6 +106216,11 @@ Object.freeze({
104437
106216
  form: "single",
104438
106217
  optional: false
104439
106218
  }],
106219
+ "pipelineAnalytics.addRetrainFrameFromRecording": [{
106220
+ name: "deviceId",
106221
+ form: "single",
106222
+ optional: false
106223
+ }],
104440
106224
  "pipelineAnalytics.applyDeviceSettingsPatch": [{
104441
106225
  name: "deviceId",
104442
106226
  form: "single",
@@ -104627,6 +106411,11 @@ Object.freeze({
104627
106411
  form: "single",
104628
106412
  optional: false
104629
106413
  }],
106414
+ "pipelineAnalytics.proposeRetrainAnnotationsWithLlm": [{
106415
+ name: "deviceId",
106416
+ form: "single",
106417
+ optional: false
106418
+ }],
104630
106419
  "pipelineAnalytics.pruneEventsBefore": [{
104631
106420
  name: "deviceId",
104632
106421
  form: "single",