@camstack/addon-provider-amcrest 0.2.132 → 0.2.133

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/addon.js +1845 -56
  2. package/dist/addon.mjs +1845 -56
  3. package/package.json +1 -1
package/dist/addon.mjs CHANGED
@@ -13,7 +13,7 @@ import { networkInterfaces } from "node:os";
13
13
  var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
14
14
  var __require = /* @__PURE__ */ createRequire(import.meta.url);
15
15
  //#endregion
16
- //#region ../types/dist/event-category-B_0XEcLF.mjs
16
+ //#region ../types/dist/event-category-DaIZi00R.mjs
17
17
  var EventCategory = /* @__PURE__ */ function(EventCategory) {
18
18
  EventCategory["SystemBoot"] = "system.boot";
19
19
  EventCategory["SystemAddonsReady"] = "system.addons-ready";
@@ -92,6 +92,13 @@ var EventCategory = /* @__PURE__ */ function(EventCategory) {
92
92
  */
93
93
  EventCategory["AddonLoadFailed"] = "addon.load-failed";
94
94
  /**
95
+ * A keychain value was stored or removed (D787). Carries the ref, its
96
+ * owner and the new version — NEVER the value. A process holding the ref
97
+ * drops its cached copy and the owning `BaseAddon` re-resolves its config.
98
+ * Telemetry (D8): a process that misses it still revalidates by version.
99
+ */
100
+ EventCategory["KeychainChanged"] = "keychain.changed";
101
+ /**
95
102
  * Addon recovered from a previous failure. Emitted when an addon
96
103
  * transitions from `failed` back to `healthy` (typically via the
97
104
  * monitor's auto-retry loop, or after manual `addons.retryLoad`).
@@ -5384,7 +5391,7 @@ var ZodIssueCode = {
5384
5391
  var ZodFirstPartyTypeKind;
5385
5392
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
5386
5393
  //#endregion
5387
- //#region ../types/dist/sleep-B0JG7-_F.mjs
5394
+ //#region ../types/dist/sleep-Cr5YOk3m.mjs
5388
5395
  /**
5389
5396
  * The audio chunk plane's byte format, and the ONE expansion from a coded
5390
5397
  * window to float samples (D455).
@@ -5463,6 +5470,97 @@ function buildAlawTable() {
5463
5470
  }
5464
5471
  buildUlawTable();
5465
5472
  buildAlawTable();
5473
+ /** Is this field's stored value a credential? */
5474
+ function isSecretConfigField(field) {
5475
+ if (field.type === "password") return true;
5476
+ return "secret" in field && field.secret === true;
5477
+ }
5478
+ /**
5479
+ * Is this field's value stored in the KEYCHAIN (D787)? Every secret field is,
5480
+ * by its TYPE, unless it opts out with `storage: 'inline'` — never by its name.
5481
+ */
5482
+ function isKeychainStoredField(field) {
5483
+ if (!isSecretConfigField(field)) return false;
5484
+ if (field.type === "textarea" && field.isJson === true) return false;
5485
+ return !("storage" in field && field.storage === "inline");
5486
+ }
5487
+ /**
5488
+ * What a settings blob holds where a secret used to be.
5489
+ *
5490
+ * A keychain-stored field never holds its value. It holds a self-describing
5491
+ * MARKER, `{"$secret":"secret://…","v":1}` — an object, never a string, so no
5492
+ * code can mistake it for a credential and no form can send it to a camera as
5493
+ * a password. The empty state is `null` / absent, never `''`.
5494
+ *
5495
+ * The same shapes travel to and from the admin UI:
5496
+ *
5497
+ * - read: `hydrateSchema` hands a secret field a {@link SecretFieldView}
5498
+ * (`{ $secret, v, set: true }`) or `null` — the browser learns whether a
5499
+ * value is set, never the value.
5500
+ * - write: an untouched field submits the view back unchanged (KEEP); a typed
5501
+ * value is a plain non-empty string (CHANGE); the Clear button submits
5502
+ * {@link SECRET_CLEAR} (CLEAR). `''`, `null` and the legacy redaction tokens
5503
+ * are KEEP — an empty string is what a defaults-fallback pushes back, and
5504
+ * treating it as "clear" is how a save destroyed a stored credential before.
5505
+ *
5506
+ * Pure and browser-safe.
5507
+ */
5508
+ var SECRET_CLEAR = { $secretClear: true };
5509
+ /** The `'***'` token D634 redaction writes for non-admins. */
5510
+ var LEGACY_DEVICE_REDACTION = "***";
5511
+ function isRecord$1$1(value) {
5512
+ return typeof value === "object" && value !== null && !Array.isArray(value);
5513
+ }
5514
+ function makeSecretMarker(ref) {
5515
+ return {
5516
+ $secret: ref,
5517
+ v: 1
5518
+ };
5519
+ }
5520
+ /** A stored marker: an object whose `$secret` is a non-empty string. */
5521
+ function isSecretMarker(value) {
5522
+ if (!isRecord$1$1(value)) return false;
5523
+ const ref = value["$secret"];
5524
+ return typeof ref === "string" && ref.length > 0;
5525
+ }
5526
+ function isSecretClear(value) {
5527
+ return isRecord$1$1(value) && value["$secretClear"] === true;
5528
+ }
5529
+ /**
5530
+ * The UI view of a stored secret field value: a marker becomes "set", inline
5531
+ * plaintext becomes "set (inline)", nothing becomes `null`. A value never
5532
+ * survives this function.
5533
+ */
5534
+ function toSecretFieldView(stored) {
5535
+ if (isSecretMarker(stored)) return {
5536
+ $secret: stored.$secret,
5537
+ v: 1,
5538
+ set: true
5539
+ };
5540
+ if (typeof stored === "string" && stored.length > 0) return {
5541
+ $secret: null,
5542
+ v: 1,
5543
+ set: true,
5544
+ inline: true
5545
+ };
5546
+ return null;
5547
+ }
5548
+ /**
5549
+ * Classify an incoming value for a secret path. Only a non-empty string that is
5550
+ * not a redaction token sets a value; only {@link SECRET_CLEAR} clears.
5551
+ * Everything else — a marker (ours or anyone's), a UI view, `''`, `null`,
5552
+ * `undefined`, a redaction token, a non-string — keeps what is stored.
5553
+ */
5554
+ function classifySecretWrite(incoming) {
5555
+ if (isSecretClear(incoming)) return { kind: "clear" };
5556
+ if (typeof incoming !== "string") return { kind: "keep" };
5557
+ if (incoming.length === 0) return { kind: "keep" };
5558
+ if (incoming === "__camstack_redacted__" || incoming === LEGACY_DEVICE_REDACTION) return { kind: "keep" };
5559
+ return {
5560
+ kind: "set",
5561
+ value: incoming
5562
+ };
5563
+ }
5466
5564
  Object.fromEntries([
5467
5565
  {
5468
5566
  id: "overview",
@@ -5634,33 +5732,19 @@ Object.fromEntries([
5634
5732
  function isValuelessField(field) {
5635
5733
  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";
5636
5734
  }
5637
- /**
5638
- * Merge a `ConfigUISchema` with a raw `values` record into a
5639
- * `ConfigUISchemaWithValues`. Used by every `get*Settings` backend endpoint
5640
- * before returning to the admin UI. Groups are walked recursively.
5641
- *
5642
- * For each leaf field:
5643
- * - structural fields (`separator`, `info`, `button`) pass through unchanged
5644
- * - other fields get `value = values[key] ?? field.default ?? null`
5645
- *
5646
- * Unknown keys in `values` (keys not declared in the schema) are silently
5647
- * ignored — they don't contribute to the output. Missing keys fall back to
5648
- * the schema default or `null`. This mirrors the old backend behaviour where
5649
- * `FormBuilder` rendered `values[key] ?? field.default`.
5650
- */
5651
- function hydrateSchema(schema, values) {
5735
+ function hydrateSchema(schema, values, options = {}) {
5652
5736
  return {
5653
5737
  ...schema.tabs ? { tabs: [...schema.tabs] } : {},
5654
5738
  sections: schema.sections.map((section) => ({
5655
5739
  ...section,
5656
- fields: section.fields.map((field) => hydrateField(field, values))
5740
+ fields: section.fields.map((field) => hydrateField(field, values, options))
5657
5741
  }))
5658
5742
  };
5659
5743
  }
5660
- function hydrateField(field, values) {
5744
+ function hydrateField(field, values, options) {
5661
5745
  if (isValuelessField(field)) return field;
5662
5746
  if (field.type === "group") {
5663
- const hydratedChildren = field.fields.map((child) => hydrateField(child, values));
5747
+ const hydratedChildren = field.fields.map((child) => hydrateField(child, values, options));
5664
5748
  return {
5665
5749
  ...field,
5666
5750
  fields: hydratedChildren
@@ -5669,7 +5753,7 @@ function hydrateField(field, values) {
5669
5753
  if (field.type === "sub-tabs") {
5670
5754
  const hydratedTabs = field.tabs.map((tab) => ({
5671
5755
  ...tab,
5672
- fields: tab.fields.map((child) => hydrateField(child, values))
5756
+ fields: tab.fields.map((child) => hydrateField(child, values, options))
5673
5757
  }));
5674
5758
  return {
5675
5759
  ...field,
@@ -5679,6 +5763,33 @@ function hydrateField(field, values) {
5679
5763
  const key = field.key;
5680
5764
  const storedValue = Object.prototype.hasOwnProperty.call(values, key) ? values[key] : void 0;
5681
5765
  const defaultValue = field.default;
5766
+ const asView = (v) => isSecretMarker(v) || options.inlineSecretsAsViews === true && v !== void 0;
5767
+ if (isKeychainStoredField(field) && asView(storedValue)) return {
5768
+ ...field,
5769
+ value: toSecretFieldView(storedValue)
5770
+ };
5771
+ if (isKeychainStoredField(field) && options.inlineSecretsAsViews === true) return {
5772
+ ...field,
5773
+ value: null
5774
+ };
5775
+ if (field.type === "editable-array" && Array.isArray(storedValue)) {
5776
+ const secretItemKeys = field.itemFields.filter((item) => "key" in item && isKeychainStoredField(item)).map((item) => "key" in item ? item.key : "");
5777
+ if (secretItemKeys.length > 0) {
5778
+ const rows = storedValue.map((row) => {
5779
+ if (row === null || typeof row !== "object" || Array.isArray(row)) return row;
5780
+ const out = { ...row };
5781
+ for (const k of secretItemKeys) {
5782
+ const v = Reflect.get(row, k);
5783
+ if (asView(v)) out[k] = toSecretFieldView(v);
5784
+ }
5785
+ return out;
5786
+ });
5787
+ return {
5788
+ ...field,
5789
+ value: rows
5790
+ };
5791
+ }
5792
+ }
5682
5793
  if (field.multiple) {
5683
5794
  const stored = Array.isArray(storedValue) ? storedValue : storedValue !== void 0 && storedValue !== null ? [storedValue] : [];
5684
5795
  const itemFallback = field.multiple.itemDefault !== void 0 ? field.multiple.itemDefault : defaultValue !== void 0 ? defaultValue : typeOf(field) === "string" ? "" : null;
@@ -5921,6 +6032,431 @@ function projectStore(store, perNodeKeys, nodeId) {
5921
6032
  }
5922
6033
  return out;
5923
6034
  }
6035
+ var GLOBAL_SCOPE = { kind: "global" };
6036
+ /** The scope every addon-wide (not per-node, not per-device) setting lives in. */
6037
+ function globalSecretScope() {
6038
+ return GLOBAL_SCOPE;
6039
+ }
6040
+ function encodeSegment(value) {
6041
+ return encodeURIComponent(value);
6042
+ }
6043
+ /**
6044
+ * The field path of a value inside an array item, addressed by the item's id:
6045
+ * `arrayItemFieldPath('providers', 'authentik', 'clientSecret')` →
6046
+ * `providers[authentik].clientSecret`.
6047
+ */
6048
+ function arrayItemFieldPath(arrayKey, itemId, fieldKey) {
6049
+ return `${arrayKey}[${encodeSegment(itemId)}].${fieldKey}`;
6050
+ }
6051
+ /** A write to a secret path could not be stored in the keychain, so it was refused. */
6052
+ var KeychainWriteRefusedError = class extends Error {
6053
+ fieldPath;
6054
+ constructor(fieldPath, cause) {
6055
+ super(`secret "${fieldPath}" was not saved: the keychain could not store it (${cause instanceof Error ? cause.message : String(cause)}). Nothing was written.`);
6056
+ this.fieldPath = fieldPath;
6057
+ this.name = "KeychainWriteRefusedError";
6058
+ }
6059
+ };
6060
+ var KEEP = { kind: "keep" };
6061
+ function isRecord$2(value) {
6062
+ return typeof value === "object" && value !== null && !Array.isArray(value);
6063
+ }
6064
+ function defaultMintId() {
6065
+ return globalThis.crypto.randomUUID();
6066
+ }
6067
+ /** Every marker ref anywhere under `value`. */
6068
+ function collectSecretMarkerRefs(value, out = []) {
6069
+ if (isSecretMarker(value)) {
6070
+ out.push(value.$secret);
6071
+ return out;
6072
+ }
6073
+ if (Array.isArray(value)) for (const item of value) collectSecretMarkerRefs(item, out);
6074
+ else if (isRecord$2(value)) for (const child of Object.values(value)) collectSecretMarkerRefs(child, out);
6075
+ return out;
6076
+ }
6077
+ async function storedValueEquals(secrets, marker, candidate) {
6078
+ const resolved = (await secrets.resolve([marker.$secret]))[marker.$secret];
6079
+ return resolved?.kind === "value" && resolved.value === candidate;
6080
+ }
6081
+ async function writeLeaf(ctx, incoming, stored, fieldPath) {
6082
+ const intent = classifySecretWrite(incoming);
6083
+ const ref = ctx.secrets.ref(ctx.scope, fieldPath);
6084
+ const storedIsOurs = isSecretMarker(stored) && stored.$secret === ref;
6085
+ if (intent.kind === "keep") return KEEP;
6086
+ if (intent.kind === "set" && !ctx.operatorWrite && typeof stored === "string" && stored === intent.value) return KEEP;
6087
+ if (intent.kind === "clear") {
6088
+ if (storedIsOurs) ctx.deletes.push(ref);
6089
+ return {
6090
+ kind: "value",
6091
+ value: null
6092
+ };
6093
+ }
6094
+ if (storedIsOurs && await storedValueEquals(ctx.secrets, stored, intent.value)) return {
6095
+ kind: "value",
6096
+ value: stored
6097
+ };
6098
+ try {
6099
+ await ctx.secrets.put(ref, intent.value);
6100
+ } catch (err) {
6101
+ throw new KeychainWriteRefusedError(fieldPath, err);
6102
+ }
6103
+ return {
6104
+ kind: "value",
6105
+ value: makeSecretMarker(ref)
6106
+ };
6107
+ }
6108
+ /** Apply a member result onto `out`: KEEP restores the stored member, or removes it. */
6109
+ function applyMember(out, key, result, storedParent) {
6110
+ if (result.kind === "value") {
6111
+ out[key] = result.value;
6112
+ return;
6113
+ }
6114
+ if (Object.prototype.hasOwnProperty.call(storedParent, key)) out[key] = storedParent[key];
6115
+ else delete out[key];
6116
+ }
6117
+ async function writeMembers(ctx, children, incoming, stored, pathOf) {
6118
+ const out = { ...incoming };
6119
+ for (const [member, node] of children) applyMember(out, member, await writeNode(ctx, node, incoming[member], stored[member], pathOf(member)), stored);
6120
+ return out;
6121
+ }
6122
+ function rowId(row, idKey) {
6123
+ const raw = row[idKey];
6124
+ if (typeof raw === "string" && raw.length > 0) return raw;
6125
+ if (typeof raw === "number" && Number.isFinite(raw)) return String(raw);
6126
+ return null;
6127
+ }
6128
+ async function writeArray(ctx, node, incoming, stored, fieldPath) {
6129
+ const storedRows = Array.isArray(stored) ? stored.filter(isRecord$2) : [];
6130
+ if (!Array.isArray(incoming)) {
6131
+ ctx.deletes.push(...collectSecretMarkerRefs(storedRows));
6132
+ return {
6133
+ kind: "value",
6134
+ value: incoming
6135
+ };
6136
+ }
6137
+ const storedById = /* @__PURE__ */ new Map();
6138
+ for (const row of storedRows) {
6139
+ const id = rowId(row, node.idKey);
6140
+ if (id !== null) storedById.set(id, row);
6141
+ }
6142
+ const kept = /* @__PURE__ */ new Set();
6143
+ const rows = [];
6144
+ for (const row of incoming) {
6145
+ if (!isRecord$2(row)) {
6146
+ rows.push(row);
6147
+ continue;
6148
+ }
6149
+ const id = rowId(row, node.idKey) ?? ctx.mintId();
6150
+ kept.add(id);
6151
+ const withId = {
6152
+ ...row,
6153
+ [node.idKey]: row[node.idKey] ?? id
6154
+ };
6155
+ if (rowId(withId, node.idKey) === null) withId[node.idKey] = id;
6156
+ const storedRow = storedById.get(id) ?? {};
6157
+ rows.push(await writeMembers(ctx, node.item, withId, storedRow, (member) => arrayItemFieldPath(fieldPath, id, member)));
6158
+ }
6159
+ for (const [id, row] of storedById) if (!kept.has(id)) ctx.deletes.push(...collectSecretMarkerRefs(row));
6160
+ return {
6161
+ kind: "value",
6162
+ value: rows
6163
+ };
6164
+ }
6165
+ async function writeNode(ctx, node, incoming, stored, fieldPath) {
6166
+ switch (node.kind) {
6167
+ case "leaf": return writeLeaf(ctx, incoming, stored, fieldPath);
6168
+ case "array": return writeArray(ctx, node, incoming, stored, fieldPath);
6169
+ case "object": {
6170
+ if (!isRecord$2(incoming)) {
6171
+ if (incoming === void 0) return KEEP;
6172
+ ctx.deletes.push(...collectSecretMarkerRefs(stored));
6173
+ return {
6174
+ kind: "value",
6175
+ value: incoming
6176
+ };
6177
+ }
6178
+ const storedObj = isRecord$2(stored) ? stored : {};
6179
+ return {
6180
+ kind: "value",
6181
+ value: await writeMembers(ctx, node.children, incoming, storedObj, (m) => `${fieldPath}.${m}`)
6182
+ };
6183
+ }
6184
+ }
6185
+ }
6186
+ /** Split a perNode-scoped key (`key@nodeId`). */
6187
+ function splitNodeKey(key) {
6188
+ const at = key.indexOf("@");
6189
+ return at <= 0 ? {
6190
+ base: key,
6191
+ nodeId: null
6192
+ } : {
6193
+ base: key.slice(0, at),
6194
+ nodeId: key.slice(at + 1)
6195
+ };
6196
+ }
6197
+ /** Rewrite a settings patch so no secret value reaches the blob. See the file doc. */
6198
+ async function transformSecretWrite(input) {
6199
+ const deletes = [];
6200
+ const base = {
6201
+ secrets: input.secrets,
6202
+ mintId: input.mintId ?? defaultMintId,
6203
+ deletes,
6204
+ operatorWrite: input.operatorWrite === true
6205
+ };
6206
+ const out = {};
6207
+ for (const [key, incoming] of Object.entries(input.patch)) {
6208
+ const { base: baseKey, nodeId } = splitNodeKey(key);
6209
+ const node = input.tree.get(baseKey);
6210
+ if (node === void 0) {
6211
+ out[key] = incoming;
6212
+ continue;
6213
+ }
6214
+ const scope = nodeId !== null && nodeId.length > 0 ? {
6215
+ kind: "node",
6216
+ nodeId
6217
+ } : input.scope ?? globalSecretScope();
6218
+ const result = await writeNode({
6219
+ ...base,
6220
+ scope
6221
+ }, node, incoming, input.stored[key], baseKey);
6222
+ if (result.kind === "value") out[key] = result.value;
6223
+ }
6224
+ return {
6225
+ patch: out,
6226
+ afterWrite: async () => {
6227
+ if (deletes.length === 0) return { orphaned: [] };
6228
+ try {
6229
+ await input.secrets.delete([...new Set(deletes)]);
6230
+ return { orphaned: [] };
6231
+ } catch {
6232
+ return { orphaned: [...new Set(deletes)] };
6233
+ }
6234
+ }
6235
+ };
6236
+ }
6237
+ /**
6238
+ * Replace every marker in `value` with its keychain value. Returns the SAME
6239
+ * reference when there is no marker (no allocation, no keychain call).
6240
+ */
6241
+ async function resolveSecretMarkers(value, secrets) {
6242
+ const refs = collectSecretMarkerRefs(value);
6243
+ if (refs.length === 0) return {
6244
+ value,
6245
+ unresolved: []
6246
+ };
6247
+ const answers = await secrets.resolve(refs);
6248
+ const unresolved = [];
6249
+ for (const ref of new Set(refs)) {
6250
+ const answer = answers[ref];
6251
+ if (answer === void 0) unresolved.push({
6252
+ ref,
6253
+ reason: "not-initialized"
6254
+ });
6255
+ else if (answer.kind === "unavailable") unresolved.push({
6256
+ ref,
6257
+ reason: answer.reason
6258
+ });
6259
+ else if (answer.kind === "missing" || answer.kind === "forbidden") unresolved.push({
6260
+ ref,
6261
+ reason: answer.kind
6262
+ });
6263
+ }
6264
+ const substitute = (v) => {
6265
+ if (isSecretMarker(v)) {
6266
+ const answer = answers[v.$secret];
6267
+ return answer?.kind === "value" ? {
6268
+ keep: true,
6269
+ value: answer.value
6270
+ } : {
6271
+ keep: false,
6272
+ value: void 0
6273
+ };
6274
+ }
6275
+ if (Array.isArray(v)) {
6276
+ const items = [];
6277
+ for (const item of v) {
6278
+ const s = substitute(item);
6279
+ if (s.keep) items.push(s.value);
6280
+ }
6281
+ return {
6282
+ keep: true,
6283
+ value: items
6284
+ };
6285
+ }
6286
+ if (isRecord$2(v)) {
6287
+ const out = {};
6288
+ for (const [k, child] of Object.entries(v)) {
6289
+ const s = substitute(child);
6290
+ if (s.keep) out[k] = s.value;
6291
+ }
6292
+ return {
6293
+ keep: true,
6294
+ value: out
6295
+ };
6296
+ }
6297
+ return {
6298
+ keep: true,
6299
+ value: v
6300
+ };
6301
+ };
6302
+ return {
6303
+ value: substitute(value).value,
6304
+ unresolved
6305
+ };
6306
+ }
6307
+ function touchesTree(tree, patch) {
6308
+ if (tree.size === 0) return false;
6309
+ for (const key of Object.keys(patch)) {
6310
+ const at = key.indexOf("@");
6311
+ if (tree.has(at > 0 ? key.slice(0, at) : key)) return true;
6312
+ }
6313
+ return false;
6314
+ }
6315
+ /** The blob as stored now; a failed read REFUSES the write instead of guessing. */
6316
+ async function readStoredAddonBlob(raw) {
6317
+ const threeWay = raw.readAddonStoreResult;
6318
+ if (threeWay === void 0) return raw.readAddonStore();
6319
+ const result = await threeWay.call(raw);
6320
+ if (result.kind === "failed") throw new Error(`settings write refused: the stored blob could not be read (${result.error})`);
6321
+ return result.kind === "missing" ? {} : result.value;
6322
+ }
6323
+ function createSecretAwareSettings(raw, opts) {
6324
+ const chains = /* @__PURE__ */ new Map();
6325
+ const serialize = (key, fn) => {
6326
+ const next = (chains.get(key) ?? Promise.resolve()).then(fn, fn);
6327
+ const tail = next.catch(() => void 0);
6328
+ chains.set(key, tail);
6329
+ tail.then(() => {
6330
+ if (chains.get(key) === tail) chains.delete(key);
6331
+ });
6332
+ return next;
6333
+ };
6334
+ const write = async (chainKey, tree, scope, patch, readStored, rawWrite) => {
6335
+ if (!touchesTree(tree, patch)) return rawWrite(patch);
6336
+ return serialize(chainKey, async () => {
6337
+ const stored = await readStored();
6338
+ const result = await transformSecretWrite({
6339
+ tree,
6340
+ secrets: opts.secrets,
6341
+ patch,
6342
+ stored,
6343
+ ...scope !== void 0 ? { scope } : {},
6344
+ operatorWrite: opts.isOperatorWrite?.() === true
6345
+ });
6346
+ if (Object.keys(result.patch).length > 0) await rawWrite(result.patch);
6347
+ const { orphaned } = await result.afterWrite();
6348
+ if (orphaned.length > 0) opts.onOrphaned(orphaned);
6349
+ });
6350
+ };
6351
+ const wrapped = {
6352
+ writeAddonStore: (patch) => write("addon", opts.addonTree(), void 0, patch, () => readStoredAddonBlob(raw), (p) => raw.writeAddonStore(p)),
6353
+ writeDeviceStore: (deviceId, patch) => write(`device:${deviceId}`, opts.deviceTree(), {
6354
+ kind: "device",
6355
+ deviceId
6356
+ }, patch, () => raw.readDeviceStore(deviceId), (p) => raw.writeDeviceStore(deviceId, p))
6357
+ };
6358
+ return new Proxy(raw, { get(target, prop, receiver) {
6359
+ if (prop === "writeAddonStore") return wrapped.writeAddonStore;
6360
+ if (prop === "writeDeviceStore") return wrapped.writeDeviceStore;
6361
+ const value = Reflect.get(target, prop, receiver);
6362
+ return typeof value === "function" ? value.bind(target) : value;
6363
+ } });
6364
+ }
6365
+ /** The context the addon sees: identical, except that its settings writes are secret-aware. */
6366
+ function withSecretAwareSettings(context, opts) {
6367
+ const raw = context.settings;
6368
+ if (raw === void 0) return context;
6369
+ const settings = createSecretAwareSettings(raw, opts);
6370
+ return new Proxy(context, { get(target, prop, receiver) {
6371
+ if (prop === "settings") return settings;
6372
+ return Reflect.get(target, prop, receiver);
6373
+ } });
6374
+ }
6375
+ var LEAF = { kind: "leaf" };
6376
+ var DEFAULT_ITEM_ID_KEY = "id";
6377
+ function collectFields(fields, out) {
6378
+ for (const field of fields) {
6379
+ if (field.type === "group") {
6380
+ collectFields(field.fields, out);
6381
+ continue;
6382
+ }
6383
+ if (field.type === "sub-tabs") {
6384
+ for (const tab of field.tabs) collectFields(tab.fields, out);
6385
+ continue;
6386
+ }
6387
+ if (field.type === "editable-array") {
6388
+ const item = /* @__PURE__ */ new Map();
6389
+ for (const itemField of field.itemFields) if ("key" in itemField && isKeychainStoredField(itemField)) item.set(itemField.key, LEAF);
6390
+ if (item.size > 0) out.set(field.key, {
6391
+ kind: "array",
6392
+ idKey: field.itemIdKey ?? DEFAULT_ITEM_ID_KEY,
6393
+ item
6394
+ });
6395
+ continue;
6396
+ }
6397
+ if (!("key" in field) || typeof field.key !== "string") continue;
6398
+ if (isKeychainStoredField(field)) out.set(field.key, LEAF);
6399
+ }
6400
+ }
6401
+ /** The secret tree a settings schema declares. */
6402
+ function secretTreeFromSchema(schema) {
6403
+ const out = /* @__PURE__ */ new Map();
6404
+ if (schema === null) return out;
6405
+ for (const section of schema.sections) collectFields(section.fields, out);
6406
+ return out;
6407
+ }
6408
+ /** Parse `a.b[id].c` into segments; throws on a malformed path (a declaration bug). */
6409
+ function parseSecretStatePath(path) {
6410
+ const segments = [];
6411
+ for (const raw of path.split(".")) {
6412
+ const m = /^([^[\]]+)(?:\[([^[\]]+)\])?$/.exec(raw);
6413
+ if (m === null || m[1] === void 0) throw new Error(`secretStatePaths: malformed path "${path}"`);
6414
+ segments.push(m[2] !== void 0 ? {
6415
+ key: m[1],
6416
+ idKey: m[2]
6417
+ } : { key: m[1] });
6418
+ }
6419
+ if (segments.length === 0) throw new Error(`secretStatePaths: empty path`);
6420
+ if (segments[segments.length - 1]?.idKey !== void 0) throw new Error(`secretStatePaths: "${path}" ends on an array — name the member that is secret`);
6421
+ return segments;
6422
+ }
6423
+ function insert(into, segments) {
6424
+ const [head, ...rest] = segments;
6425
+ if (head === void 0) return;
6426
+ if (rest.length === 0) {
6427
+ into.set(head.key, LEAF);
6428
+ return;
6429
+ }
6430
+ const existing = into.get(head.key);
6431
+ if (head.idKey !== void 0) {
6432
+ const item = new Map(existing?.kind === "array" ? existing.item : []);
6433
+ insert(item, rest);
6434
+ into.set(head.key, {
6435
+ kind: "array",
6436
+ idKey: head.idKey,
6437
+ item
6438
+ });
6439
+ return;
6440
+ }
6441
+ const children = new Map(existing?.kind === "object" ? existing.children : []);
6442
+ insert(children, rest);
6443
+ into.set(head.key, {
6444
+ kind: "object",
6445
+ children
6446
+ });
6447
+ }
6448
+ /** Add hidden-state paths (`secretStatePaths`) to a schema-derived tree. */
6449
+ function mergeSecretStatePaths(tree, paths) {
6450
+ if (paths.length === 0) return tree;
6451
+ const out = new Map(tree);
6452
+ for (const path of paths) insert(out, parseSecretStatePath(path));
6453
+ return out;
6454
+ }
6455
+ /** First retry of a secret the keychain could not serve; doubles to {@link SECRET_RETRY_MAX_MS}. */
6456
+ var SECRET_RETRY_FIRST_MS = 5e3;
6457
+ var SECRET_RETRY_MAX_MS = 5 * 6e4;
6458
+ /** Coalesces a burst of `keychain.changed` events into one re-resolve. */
6459
+ var SECRET_CHANGE_DEBOUNCE_MS = 250;
5924
6460
  /**
5925
6461
  * Base class for CamStack addons. Eliminates settings boilerplate:
5926
6462
  *
@@ -5990,6 +6526,25 @@ var BaseAddon = class {
5990
6526
  settingsStoreReady = false;
5991
6527
  /** Default config values. Provided via constructor. */
5992
6528
  defaults;
6529
+ /**
6530
+ * Hidden-state paths that hold secrets (D787) — values the addon writes
6531
+ * itself (`updateGlobalSettings`, `state()`) that no form field declares.
6532
+ * Stored in the keychain exactly like a `password` field. Syntax:
6533
+ * `'snapshotSigningKey'`, `'identity.pincode'`, `'tokens[userId].accessToken'`
6534
+ * (`key[<id field>]` addresses array items by id, never by index).
6535
+ */
6536
+ secretStatePaths = [];
6537
+ _addonSecretTree = null;
6538
+ _deviceSecretTree = null;
6539
+ /** Refs the last resolved config pointed at — a change to one re-resolves. */
6540
+ _configSecretRefs = /* @__PURE__ */ new Set();
6541
+ _unresolvedSecrets = [];
6542
+ _secretRetryTimer = null;
6543
+ _secretRetryDelayMs = SECRET_RETRY_FIRST_MS;
6544
+ _secretChangeTimer = null;
6545
+ _secretChangeUnsub = null;
6546
+ /** >0 while an OPERATOR's settings write is being applied. */
6547
+ _operatorWriteDepth = 0;
5993
6548
  constructor(defaults) {
5994
6549
  this.defaults = defaults;
5995
6550
  this._config = { ...defaults };
@@ -6025,8 +6580,18 @@ var BaseAddon = class {
6025
6580
  return this._config;
6026
6581
  }
6027
6582
  async initialize(context) {
6028
- this._ctx = context;
6583
+ const secrets = context.secrets;
6584
+ this._ctx = secrets !== void 0 ? withSecretAwareSettings(context, {
6585
+ secrets,
6586
+ addonTree: () => this.addonSecretTree(),
6587
+ deviceTree: () => this.deviceSecretTree(),
6588
+ onOrphaned: (refs) => context.logger.warn("keychain refs dropped by a settings write could not be deleted", { meta: { refs: [...refs] } }),
6589
+ isOperatorWrite: () => this._operatorWriteDepth > 0
6590
+ }) : context;
6029
6591
  await this.resolveConfig();
6592
+ if (secrets !== void 0) this._secretChangeUnsub = secrets.onChange((ref) => {
6593
+ if (this._configSecretRefs.has(ref)) this.scheduleSecretReresolve(SECRET_CHANGE_DEBOUNCE_MS);
6594
+ });
6030
6595
  const result = await this.onInitialize();
6031
6596
  this.emitLifecycle(EventCategory.AddonStarted);
6032
6597
  const normalized = normalizeAddonInitResult(result);
@@ -6059,6 +6624,12 @@ var BaseAddon = class {
6059
6624
  */
6060
6625
  async onHubReachable() {}
6061
6626
  async shutdown() {
6627
+ this._secretChangeUnsub?.();
6628
+ this._secretChangeUnsub = null;
6629
+ if (this._secretRetryTimer !== null) clearTimeout(this._secretRetryTimer);
6630
+ if (this._secretChangeTimer !== null) clearTimeout(this._secretChangeTimer);
6631
+ this._secretRetryTimer = null;
6632
+ this._secretChangeTimer = null;
6062
6633
  this.emitLifecycle(EventCategory.AddonStopped);
6063
6634
  if (this.autoEmitReadiness) this.emitReadinessForProviders("down");
6064
6635
  await this.onShutdown();
@@ -6137,7 +6708,7 @@ var BaseAddon = class {
6137
6708
  return hydrateSchema(schema, overlay ? {
6138
6709
  ...projected,
6139
6710
  ...overlay
6140
- } : projected);
6711
+ } : projected, { inlineSecretsAsViews: true });
6141
6712
  }
6142
6713
  /**
6143
6714
  * The integration-level view of this addon's settings: exactly the sections
@@ -6186,7 +6757,7 @@ var BaseAddon = class {
6186
6757
  return hydrateSchema({
6187
6758
  ...schema,
6188
6759
  sections
6189
- }, projected);
6760
+ }, projected, { inlineSecretsAsViews: true });
6190
6761
  }
6191
6762
  /**
6192
6763
  * The raw addon store PROJECTED onto the target node's bare per-node keys:
@@ -6240,18 +6811,50 @@ var BaseAddon = class {
6240
6811
  value: result.value[key]
6241
6812
  };
6242
6813
  }
6814
+ /**
6815
+ * The OPERATOR's write — a settings form or an admin API call, dispatched by
6816
+ * the kernel. Identical to {@link updateGlobalSettings}, except that a secret
6817
+ * the operator sends is stored as sent even when it equals a pre-keychain
6818
+ * inline value: the operator re-entering a password is a change, an addon
6819
+ * writing back what it read is not (D787).
6820
+ */
6821
+ async updateGlobalSettingsAsOperator(patch, nodeId) {
6822
+ this._operatorWriteDepth++;
6823
+ try {
6824
+ await this.applyGlobalPatch(patch, nodeId);
6825
+ } finally {
6826
+ this._operatorWriteDepth--;
6827
+ }
6828
+ }
6243
6829
  async updateGlobalSettings(patch, nodeId) {
6830
+ await this.applyGlobalPatch(patch, nodeId);
6831
+ }
6832
+ /**
6833
+ * REMOVE stored secrets — their keychain values and their markers (D787).
6834
+ *
6835
+ * Writing `''` to a secret field KEEPS what is stored (an empty string is
6836
+ * what a defaults fallback writes back, and it must never destroy a
6837
+ * credential), so code that means "forget this token" says so here. Without
6838
+ * a keychain (an older kernel) it writes `''`, as such code always did.
6839
+ */
6840
+ async clearSecrets(keys, nodeId) {
6841
+ const tree = this.addonSecretTree();
6842
+ const keychain = this._ctx?.secrets !== void 0;
6843
+ const patch = {};
6844
+ for (const key of keys) patch[key] = keychain && tree.has(key) ? SECRET_CLEAR : "";
6845
+ await this.applyGlobalPatch(patch, nodeId);
6846
+ }
6847
+ async applyGlobalPatch(barePatch, nodeId) {
6244
6848
  const keys = this.perNodeKeys();
6245
6849
  const localNode = normalizeNodeId(this._ctx?.kernel?.localNodeId);
6246
6850
  const target = normalizeNodeId(nodeId ?? this._ctx?.kernel?.localNodeId);
6247
- const barePatch = patch;
6248
6851
  const scoped = keys.size > 0 ? scopePatch(barePatch, keys, target) : barePatch;
6249
6852
  await this._ctx?.settings?.writeAddonStore(scoped);
6250
6853
  if (target !== localNode) return;
6251
6854
  await this.resolveConfig();
6252
6855
  await this.onConfigChanged();
6253
6856
  this.emitLifecycle(EventCategory.AddonUpdated, { level: "global" });
6254
- this.maybeAutoRestart(patch, this.globalSettingsSchema());
6857
+ this.maybeAutoRestart(Object.keys(barePatch), this.globalSettingsSchema());
6255
6858
  }
6256
6859
  /**
6257
6860
  * The set of field keys the global settings schema declares `perNode: true`
@@ -6276,7 +6879,7 @@ var BaseAddon = class {
6276
6879
  * time to return its response before the addon is torn down and
6277
6880
  * re-initialised by `AddonRegistryService.restartAddon`.
6278
6881
  */
6279
- maybeAutoRestart(patch, schema) {
6882
+ maybeAutoRestart(patchKeys, schema) {
6280
6883
  if (!schema) return;
6281
6884
  const restartKeys = /* @__PURE__ */ new Set();
6282
6885
  for (const section of schema.sections) for (const field of section.fields) {
@@ -6284,13 +6887,13 @@ var BaseAddon = class {
6284
6887
  if (field.requiresRestart) restartKeys.add(field.key);
6285
6888
  }
6286
6889
  if (restartKeys.size === 0) return;
6287
- if (!Object.keys(patch).some((k) => restartKeys.has(k))) return;
6890
+ if (!patchKeys.some((k) => restartKeys.has(k))) return;
6288
6891
  const ctx = this._ctx;
6289
6892
  if (!ctx) return;
6290
6893
  const addonId = ctx.id;
6291
6894
  setImmediate(() => {
6292
6895
  ctx.api.addons?.restartAddon?.mutate({ addonId }).then(() => {
6293
- ctx.logger.info("addon auto-restart triggered by restart-required setting change", { meta: { changedFields: Object.keys(patch).filter((k) => restartKeys.has(k)) } });
6896
+ ctx.logger.info("addon auto-restart triggered by restart-required setting change", { meta: { changedFields: patchKeys.filter((k) => restartKeys.has(k)) } });
6294
6897
  }).catch((err) => {
6295
6898
  ctx.logger.error("addon auto-restart failed", { meta: { error: err instanceof Error ? err.message : String(err) } });
6296
6899
  });
@@ -6299,7 +6902,7 @@ var BaseAddon = class {
6299
6902
  async getDeviceSettings(deviceId) {
6300
6903
  const schema = this.deviceSettingsSchema();
6301
6904
  if (!schema) return { sections: [] };
6302
- return hydrateSchema(schema, await this._ctx?.settings?.readDeviceStore(deviceId) ?? {});
6905
+ return hydrateSchema(schema, await this._ctx?.settings?.readDeviceStore(deviceId) ?? {}, { inlineSecretsAsViews: true });
6303
6906
  }
6304
6907
  async updateDeviceSettings(deviceId, patch) {
6305
6908
  await this._ctx?.settings?.writeDeviceStore(deviceId, patch);
@@ -6429,7 +7032,7 @@ var BaseAddon = class {
6429
7032
  * selection at boot (absent scoped key ⇒ the constructor default wins).
6430
7033
  */
6431
7034
  async resolveConfig() {
6432
- const stored = await this.readAddonStoreWithRetry();
7035
+ const stored = await this.resolveStoredSecrets(await this.readAddonStoreWithRetry());
6433
7036
  const perNode = this.perNodeKeys();
6434
7037
  const localNode = normalizeNodeId(this._ctx?.kernel?.localNodeId);
6435
7038
  const resolved = { ...this.defaults };
@@ -6454,7 +7057,7 @@ var BaseAddon = class {
6454
7057
  key,
6455
7058
  schema,
6456
7059
  fallback,
6457
- read: () => this.readAddonStoreWithRetry(),
7060
+ read: async () => this.resolveStoredSecrets(await this.readAddonStoreWithRetry()),
6458
7061
  write: async (patch) => {
6459
7062
  await this._ctx?.settings?.writeAddonStore(patch);
6460
7063
  },
@@ -6471,7 +7074,7 @@ var BaseAddon = class {
6471
7074
  key,
6472
7075
  schema,
6473
7076
  fallback,
6474
- read: async () => await this._ctx?.settings?.readDeviceStore(deviceId) ?? {},
7077
+ read: async () => this.resolveStoredSecrets(await this._ctx?.settings?.readDeviceStore(deviceId) ?? {}, false),
6475
7078
  write: async (patch) => {
6476
7079
  await this._ctx?.settings?.writeDeviceStore(deviceId, patch);
6477
7080
  },
@@ -6483,6 +7086,70 @@ var BaseAddon = class {
6483
7086
  } })
6484
7087
  });
6485
7088
  }
7089
+ /** The addon store's secret tree: schema fields by TYPE, plus `secretStatePaths`. */
7090
+ addonSecretTree() {
7091
+ this._addonSecretTree ??= mergeSecretStatePaths(secretTreeFromSchema(this.globalSettingsSchema()), this.secretStatePaths);
7092
+ return this._addonSecretTree;
7093
+ }
7094
+ deviceSecretTree() {
7095
+ this._deviceSecretTree ??= secretTreeFromSchema(this.deviceSettingsSchema());
7096
+ return this._deviceSecretTree;
7097
+ }
7098
+ /**
7099
+ * Secrets of this addon's stored config that could not be resolved on the
7100
+ * last read, with why. Non-empty means the addon is running WITHOUT them —
7101
+ * an addon whose function needs one should report itself degraded rather
7102
+ * than start on an empty credential.
7103
+ */
7104
+ get unresolvedSecrets() {
7105
+ return this._unresolvedSecrets;
7106
+ }
7107
+ /**
7108
+ * Substitute every keychain marker in a stored blob with its value. With no
7109
+ * keychain (no `ctx.secrets`) or no marker, the blob comes back unchanged.
7110
+ * An unresolvable value is LEFT OUT (never `''`), logged by ref — never by
7111
+ * value — and, when the cause can pass, retried with backoff. Nothing is
7112
+ * ever written back from here.
7113
+ */
7114
+ async resolveStoredSecrets(blob, trackForConfig = true) {
7115
+ const secrets = this._ctx?.secrets;
7116
+ if (secrets === void 0) return blob;
7117
+ const refs = collectSecretMarkerRefs(blob);
7118
+ if (trackForConfig) this._configSecretRefs = new Set(refs);
7119
+ if (refs.length === 0) {
7120
+ if (trackForConfig) this._unresolvedSecrets = [];
7121
+ return blob;
7122
+ }
7123
+ const { value, unresolved } = await resolveSecretMarkers(blob, secrets);
7124
+ if (trackForConfig) {
7125
+ this._unresolvedSecrets = unresolved;
7126
+ if (unresolved.length > 0) {
7127
+ this._ctx?.logger?.error?.("secret unavailable — running without it, will retry", { meta: { secrets: unresolved.map((u) => ({
7128
+ ref: u.ref,
7129
+ reason: u.reason
7130
+ })) } });
7131
+ if (unresolved.some((u) => u.reason !== "missing" && u.reason !== "forbidden")) {
7132
+ this.scheduleSecretReresolve(this._secretRetryDelayMs);
7133
+ this._secretRetryDelayMs = Math.min(this._secretRetryDelayMs * 2, SECRET_RETRY_MAX_MS);
7134
+ }
7135
+ } else this._secretRetryDelayMs = SECRET_RETRY_FIRST_MS;
7136
+ }
7137
+ return value;
7138
+ }
7139
+ /** Re-resolve the config (a keychain-only change, or a retry) and apply it. */
7140
+ scheduleSecretReresolve(delayMs) {
7141
+ const timerOf = delayMs === SECRET_CHANGE_DEBOUNCE_MS ? "_secretChangeTimer" : "_secretRetryTimer";
7142
+ if (this[timerOf] !== null) return;
7143
+ const timer = setTimeout(() => {
7144
+ this[timerOf] = null;
7145
+ if (this._ctx === null) return;
7146
+ this.resolveConfig().then(() => this.onConfigChanged()).catch((err) => {
7147
+ this._ctx?.logger?.error?.("re-resolving secrets failed", { meta: { error: err instanceof Error ? err.message : String(err) } });
7148
+ });
7149
+ }, delayMs);
7150
+ timer.unref?.();
7151
+ this[timerOf] = timer;
7152
+ }
6486
7153
  /**
6487
7154
  * Wrap `ctx.settings.readAddonStore()` with a short retry budget so a
6488
7155
  * transient settings-store outage (mid-restart of sqlite-settings, tsx-watch
@@ -7058,6 +7725,69 @@ method(object({ deviceId: number() }), array(StreamSourceEntrySchema)), method(o
7058
7725
  kind: "mutation",
7059
7726
  auth: "admin"
7060
7727
  }), method(object({ deviceId: number() }), unknown().nullable()), method(object({ deviceId: number() }), RawStateResultSchema.nullable(), { auth: "protected" });
7728
+ function defOf(schema) {
7729
+ return schema._zod?.def ?? {};
7730
+ }
7731
+ function declaredHere(schema) {
7732
+ return globalRegistry.get(schema)?.secret === true;
7733
+ }
7734
+ /** Wrapper kinds whose `innerType` is the field itself. */
7735
+ var WRAPPERS = new Set([
7736
+ "optional",
7737
+ "nullable",
7738
+ "default",
7739
+ "prefault",
7740
+ "catch",
7741
+ "readonly",
7742
+ "nonoptional"
7743
+ ]);
7744
+ /**
7745
+ * The schema layers that make up ONE field: the schema itself and every
7746
+ * wrapper below it (optional / default / nullable / readonly / catch), plus
7747
+ * both sides of a pipe (`z.preprocess` puts the real schema on `out`,
7748
+ * `.transform` on `in`).
7749
+ */
7750
+ function layersOf(schema) {
7751
+ const out = [];
7752
+ const queue = [schema];
7753
+ while (queue.length > 0) {
7754
+ const s = queue.shift();
7755
+ if (!s || out.includes(s)) continue;
7756
+ out.push(s);
7757
+ const def = defOf(s);
7758
+ if (def.type !== void 0 && WRAPPERS.has(def.type) && def.innerType) queue.push(def.innerType);
7759
+ if (def.type === "pipe") {
7760
+ if (def.in) queue.push(def.in);
7761
+ if (def.out) queue.push(def.out);
7762
+ }
7763
+ }
7764
+ return out;
7765
+ }
7766
+ /** True when any layer of this field declares `.meta({ secret: true })`. */
7767
+ function isZodSecret(schema) {
7768
+ return layersOf(schema).some(declaredHere);
7769
+ }
7770
+ /**
7771
+ * Every declared secret path in a config schema: dotted keys, `[]` for "each
7772
+ * element of this array" (`connection.password`, `rows[].token`). A declared
7773
+ * object or array is reported as one path and not descended into — everything
7774
+ * under it is secret.
7775
+ */
7776
+ function collectZodSecretPaths(schema, prefix = "") {
7777
+ if (isZodSecret(schema)) return prefix.length > 0 ? [prefix] : [];
7778
+ const paths = [];
7779
+ for (const layer of layersOf(schema)) {
7780
+ const def = defOf(layer);
7781
+ if (def.type === "object" && def.shape) for (const [key, child] of Object.entries(def.shape)) paths.push(...collectZodSecretPaths(child, prefix ? `${prefix}.${key}` : key));
7782
+ else if (def.type === "array" && def.element) paths.push(...collectZodSecretPaths(def.element, `${prefix}[]`));
7783
+ else if (def.type === "union" && def.options) for (const option of def.options) paths.push(...collectZodSecretPaths(option, prefix));
7784
+ else if (def.type === "intersection") {
7785
+ if (def.left) paths.push(...collectZodSecretPaths(def.left, prefix));
7786
+ if (def.right) paths.push(...collectZodSecretPaths(def.right, prefix));
7787
+ }
7788
+ }
7789
+ return [...new Set(paths)];
7790
+ }
7061
7791
  //#endregion
7062
7792
  //#region ../types/dist/err-msg-DX6i_MY4.mjs
7063
7793
  var DeviceType = /* @__PURE__ */ function(DeviceType) {
@@ -14098,6 +14828,196 @@ id: union([string(), number()]) }), {
14098
14828
  kind: "mutation",
14099
14829
  auth: "admin"
14100
14830
  });
14831
+ /**
14832
+ * `keychain` — the hub's encrypted store of secret values (D787).
14833
+ *
14834
+ * Settings blobs never hold a secret: they hold a marker
14835
+ * `{"$secret":"secret://<owner>/<scope>/<fieldPath>","v":1}` and the value
14836
+ * lives here, AES-256-GCM under a data key that a master key wraps. This cap
14837
+ * is the OWNER's door to its own values: every method is owner-checked
14838
+ * against the CALLER, never against anything the caller claims.
14839
+ *
14840
+ * Who the caller is: the transport stamps `callerAddonId` into the args of a
14841
+ * call that crossed a process (the parent `LocalChildRegistry` from the UDS
14842
+ * connection, the agent from its child's connection carried in
14843
+ * `$hub-cap-fwd`'s envelope). A stamp always overwrites; a wire call with no
14844
+ * stamp has its claim stripped. Only a hub in-process caller may state its own
14845
+ * identity — `ctx.secrets` does that with the addon id closed over. This is
14846
+ * identity against BUGS and misrouting, not against a malicious addon (every
14847
+ * runner is the same OS user): see the threat model in
14848
+ * `docs/design/2026-10-08-secrets-keychain.md`.
14849
+ *
14850
+ * `callerAddonId` is deliberately NOT in any input schema: the tRPC router
14851
+ * parses the input, so a session can never supply it, and the internal mount
14852
+ * floors every method to admin anyway (D240).
14853
+ *
14854
+ * Internal: addons reach it through `ctx.secrets`, never directly.
14855
+ */
14856
+ /** Why a value cannot be served right now. Never folded into "missing". */
14857
+ var KeychainUnavailableReasonSchema = _enum([
14858
+ "key-missing",
14859
+ "wrong-key",
14860
+ "key-file-unreadable",
14861
+ "store-unavailable",
14862
+ "not-initialized",
14863
+ "decrypt-failed"
14864
+ ]);
14865
+ var KeychainStateSchema = discriminatedUnion("state", [object({ state: literal("ready") }), object({
14866
+ state: literal("locked"),
14867
+ reason: KeychainUnavailableReasonSchema
14868
+ })]);
14869
+ var KeychainResolveEntrySchema = discriminatedUnion("kind", [
14870
+ object({
14871
+ kind: literal("value"),
14872
+ value: string(),
14873
+ version: number().int()
14874
+ }),
14875
+ object({ kind: literal("missing") }),
14876
+ object({
14877
+ kind: literal("unavailable"),
14878
+ reason: KeychainUnavailableReasonSchema
14879
+ }),
14880
+ object({ kind: literal("forbidden") })
14881
+ ]);
14882
+ var KeychainResolveResultSchema = record(string(), KeychainResolveEntrySchema);
14883
+ /** Metadata of one stored value — never the value. */
14884
+ var KeychainSecretMetaSchema = object({
14885
+ ref: string(),
14886
+ owner: string(),
14887
+ /** Formatted scope (`global`, `node/<id>`, `device/<id>`, …). */
14888
+ scope: string(),
14889
+ fieldPath: string(),
14890
+ version: number().int(),
14891
+ createdAt: number(),
14892
+ updatedAt: number(),
14893
+ /** `addon:<id>` | `user:<id>` | `system`. */
14894
+ updatedBy: string(),
14895
+ /** Coarse — written at most once an hour per ref. `null` = never read. */
14896
+ lastReadAt: number().nullable()
14897
+ });
14898
+ var RefListSchema = array(string().min(1)).max(512);
14899
+ method(object({
14900
+ ref: string().min(1),
14901
+ value: string().min(1)
14902
+ }), object({
14903
+ ref: string(),
14904
+ version: number().int()
14905
+ }), {
14906
+ kind: "mutation",
14907
+ auth: "admin"
14908
+ }), method(object({ refs: RefListSchema }), KeychainResolveResultSchema, { auth: "admin" }), method(object({ refs: RefListSchema }), object({ deleted: number().int() }), {
14909
+ kind: "mutation",
14910
+ auth: "admin"
14911
+ }), method(object({}), array(KeychainSecretMetaSchema).readonly(), { auth: "admin" }), method(object({}), KeychainStateSchema, { auth: "admin" });
14912
+ var KeychainKeySourceSchema = object({
14913
+ kind: _enum([
14914
+ "config-file",
14915
+ "previous-config-file",
14916
+ "platform",
14917
+ "default-file"
14918
+ ]),
14919
+ /** File sources only — a path is not a secret. */
14920
+ path: string().optional(),
14921
+ /**
14922
+ * True when a whole-volume backup of the data directory carries this key
14923
+ * next to the database it protects (the default file). The page warns.
14924
+ */
14925
+ sharesBackupWithDatabase: boolean()
14926
+ });
14927
+ var KeychainStatusSchema = object({
14928
+ keychain: KeychainStateSchema,
14929
+ /** The source of the master key in use; `null` while locked. */
14930
+ keySource: KeychainKeySourceSchema.nullable(),
14931
+ /** The source configured to be primary — differs from `keySource` while a rotation is pending. */
14932
+ configuredSource: KeychainKeySourceSchema,
14933
+ /** Short fingerprint of the master key in use (`HMAC(KEK, label)`, 16 hex). */
14934
+ fingerprint: string().nullable(),
14935
+ activeKeyId: string().nullable(),
14936
+ /**
14937
+ * The keychain unlocked with a NON-primary source: the configured primary
14938
+ * key is not the one that wraps the data key yet. `rotateMasterKey` moves it.
14939
+ */
14940
+ rotationPending: boolean(),
14941
+ /** Wrapped copies of the data key under a previous master key, kept until purged. */
14942
+ retiredWraps: number().int(),
14943
+ recoveryKeyDownloadedAt: number().nullable(),
14944
+ secretCount: number().int()
14945
+ });
14946
+ /**
14947
+ * Whether a stored value is still pointed at by its owner's settings.
14948
+ * `unknown` is a first-class answer: a scope whose blob could not be read is
14949
+ * never reported as an orphan (and never deleted as one).
14950
+ */
14951
+ var KeychainSecretUsageSchema = _enum([
14952
+ "in-use",
14953
+ "orphan",
14954
+ "unknown"
14955
+ ]);
14956
+ var KeychainAdminSecretSchema = KeychainSecretMetaSchema.extend({ usage: KeychainSecretUsageSchema });
14957
+ var KeychainAuditActionSchema = _enum([
14958
+ "put",
14959
+ "delete",
14960
+ "reveal",
14961
+ "rotate-master-key",
14962
+ "purge-retired-keys",
14963
+ "download-recovery-key",
14964
+ "delete-orphans",
14965
+ "reset",
14966
+ "initialize"
14967
+ ]);
14968
+ var KeychainAuditEntrySchema = object({
14969
+ id: string(),
14970
+ at: number(),
14971
+ action: KeychainAuditActionSchema,
14972
+ /** `addon:<id>` | `user:<id>` | `system`. */
14973
+ actor: string(),
14974
+ ref: string().nullable(),
14975
+ detail: string().nullable()
14976
+ });
14977
+ 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({
14978
+ value: string(),
14979
+ version: number().int()
14980
+ }), {
14981
+ kind: "mutation",
14982
+ auth: "admin",
14983
+ caller: "required"
14984
+ }), method(object({ refs: array(string().min(1)).max(1e3) }), object({
14985
+ deleted: array(string()).readonly(),
14986
+ kept: array(object({
14987
+ ref: string(),
14988
+ usage: KeychainSecretUsageSchema
14989
+ })).readonly()
14990
+ }), {
14991
+ kind: "mutation",
14992
+ auth: "admin",
14993
+ caller: "required"
14994
+ }), method(object({}), object({
14995
+ fingerprint: string(),
14996
+ keySource: KeychainKeySourceSchema
14997
+ }), {
14998
+ kind: "mutation",
14999
+ auth: "admin",
15000
+ caller: "required"
15001
+ }), method(object({}), object({ purged: number().int() }), {
15002
+ kind: "mutation",
15003
+ auth: "admin",
15004
+ caller: "required"
15005
+ }), method(object({}), object({
15006
+ key: string(),
15007
+ fingerprint: string(),
15008
+ keySource: KeychainKeySourceSchema
15009
+ }), {
15010
+ kind: "mutation",
15011
+ auth: "admin",
15012
+ caller: "required"
15013
+ }), method(object({ confirm: literal("RESET KEYCHAIN") }), object({
15014
+ archivedCollection: string().nullable(),
15015
+ archived: number().int()
15016
+ }), {
15017
+ kind: "mutation",
15018
+ auth: "admin",
15019
+ caller: "required"
15020
+ });
14101
15021
  method(_void(), object({
14102
15022
  id: string(),
14103
15023
  name: string(),
@@ -15436,7 +16356,11 @@ var DeviceRegisterPayloadSchema = object({
15436
16356
  var DeviceRemovePayloadSchema = object({ deviceId: number() });
15437
16357
  var DevicePersistConfigPayloadSchema = object({
15438
16358
  deviceId: number(),
15439
- data: record(string(), unknown())
16359
+ data: record(string(), unknown()),
16360
+ /** The paths the device's schema declares secret (D783), when the caller
16361
+ * knows them — those values are kept in the keychain, not the blob (D787).
16362
+ * Absent: the paths the device last reported at `registerDevice` apply. */
16363
+ secretConfigPaths: array(string()).optional()
15440
16364
  });
15441
16365
  /** What a migration actually did, per switch. `unreachable` is a first-class
15442
16366
  * answer: a camera that could not be asked is not a camera that was silenced. */
@@ -22453,8 +23377,23 @@ var RetrainMacroClassSchema = _enum([
22453
23377
  ]);
22454
23378
  /** A subject to learn, or a phantom to unlearn (taught by OMISSION). */
22455
23379
  var RetrainAnnotationKindSchema = _enum(["subject", "model_error"]);
22456
- /** Did a human draw this box, or did the assist propose it? */
22457
- var RetrainAnnotationSourceSchema = _enum(["operator", "assist"]);
23380
+ /**
23381
+ * Where a box came from. A machine-sourced box is a DRAFT on the page until
23382
+ * the operator confirms it; once saved it keeps its source as provenance.
23383
+ *
23384
+ * - `operator` — drawn by hand.
23385
+ * - `assist` — proposed by a detector run on the copy (the camera's own
23386
+ * model, or a larger teacher model).
23387
+ * - `pipeline` — the box the live pipeline actually drew on that frame, read
23388
+ * back from the track store (never a re-run).
23389
+ * - `llm` — proposed by a vision-capable LLM profile.
23390
+ */
23391
+ var RetrainAnnotationSourceSchema = _enum([
23392
+ "operator",
23393
+ "assist",
23394
+ "pipeline",
23395
+ "llm"
23396
+ ]);
22458
23397
  /** Normalised `[0,1]` rectangle against the FULL frame — the canonical form. */
22459
23398
  var RetrainBboxSchema = object({
22460
23399
  x: number(),
@@ -22472,7 +23411,8 @@ var RetrainBboxSchema = object({
22472
23411
  */
22473
23412
  var RetrainAnnotationSchema = object({
22474
23413
  id: string(),
22475
- trackId: string(),
23414
+ /** The frame's track. Absent on a recording still, which has none. */
23415
+ trackId: string().optional(),
22476
23416
  deviceId: number(),
22477
23417
  /** The COPY in retrain storage — never the source track's media key. */
22478
23418
  mediaKey: string(),
@@ -22521,13 +23461,47 @@ var RetrainFrameCandidateSchema = object({
22521
23461
  * fail, whatever became of the original. */
22522
23462
  copied: boolean()
22523
23463
  });
23464
+ /**
23465
+ * One box the live pipeline drew on a copied frame — what a correction starts
23466
+ * from. Derived when the frame is listed, from the track store: the subject
23467
+ * box recorded on the source media row when there is one, else the track
23468
+ * position nearest the frame's capture time. Never stored as an annotation
23469
+ * until the operator confirms it.
23470
+ */
23471
+ var RetrainPipelineBoxSchema = object({
23472
+ /** Normalised `[0,1]` against the full frame. */
23473
+ bbox: RetrainBboxSchema,
23474
+ macroClass: RetrainMacroClassSchema,
23475
+ label: string().optional(),
23476
+ subLabel: string().optional(),
23477
+ /** The detection score of the position used, when it was recorded. */
23478
+ score: number().optional(),
23479
+ /** The root model that produced the track, when it was recorded. */
23480
+ modelId: string().optional(),
23481
+ trackId: string(),
23482
+ /** `subject-box`: recorded on this very frame. `position`: the track's
23483
+ * position nearest the capture time, `deltaMs` away. */
23484
+ basis: _enum(["subject-box", "position"]),
23485
+ deltaMs: number()
23486
+ });
23487
+ /**
23488
+ * Where a retrain frame came from: a TRACK's stored media (copy-on-select),
23489
+ * or the RECORDING at an instant — the frame a model saw nothing in has no
23490
+ * track at all.
23491
+ */
23492
+ var RetrainFrameOriginSchema = _enum(["track", "recording"]);
22524
23493
  /** A frame the dataset OWNS: bytes copied at selection time. */
22525
23494
  var RetrainFrameSchema = object({
22526
23495
  frameId: string(),
22527
23496
  deviceId: number(),
22528
- trackId: string(),
22529
- /** Provenance only. It may already point at nothing — that is expected. */
22530
- sourceMediaId: number().int(),
23497
+ origin: RetrainFrameOriginSchema,
23498
+ /** The track it was copied from. Absent on a recording still. */
23499
+ trackId: string().optional(),
23500
+ /** Provenance only. It may already point at nothing — that is expected.
23501
+ * Absent on a recording still. */
23502
+ sourceMediaId: number().int().optional(),
23503
+ /** A recording still: the playhead instant it was taken at. */
23504
+ epochMs: number().optional(),
22531
23505
  sourceKind: MediaFileKindEnum,
22532
23506
  sizeBytes: number().int(),
22533
23507
  width: number().int(),
@@ -22538,7 +23512,12 @@ var RetrainFrameSchema = object({
22538
23512
  /** The operator's "every subject in this frame is boxed". Detector
22539
23513
  * evaluation keeps only complete frames: an unboxed subject would count as
22540
23514
  * a false positive. */
22541
- complete: boolean()
23515
+ complete: boolean(),
23516
+ /** The boxes the pipeline drew on this frame. Present on list answers;
23517
+ * empty when nothing the track store holds can be placed on it. */
23518
+ pipelineBoxes: array(RetrainPipelineBoxSchema).readonly().optional(),
23519
+ /** The named collections this frame belongs to. Present on list answers. */
23520
+ collectionIds: array(string()).readonly().optional()
22542
23521
  });
22543
23522
  /** Why a copy-on-select could not be honoured — named, never a silent skip. */
22544
23523
  var RetrainCopyRefusalSchema = _enum([
@@ -22569,6 +23548,8 @@ var RetrainFrameListSchema = object({
22569
23548
  var RetrainExportFilterSchema = object({
22570
23549
  deviceIds: array(number()).optional(),
22571
23550
  frameIds: array(string()).max(2e4).optional(),
23551
+ /** Only frames in at least one of these named collections. */
23552
+ collectionIds: array(string()).max(200).optional(),
22572
23553
  batchId: string().optional(),
22573
23554
  /** Only frames the operator marked complete (all subjects boxed). */
22574
23555
  completeOnly: boolean().optional()
@@ -22633,6 +23614,109 @@ var RetrainAssistResultSchema = discriminatedUnion("kind", [object({
22633
23614
  reason: string(),
22634
23615
  detail: string().optional()
22635
23616
  })]);
23617
+ /** A named set over the retrain corpus — membership only, it owns no pixels. */
23618
+ var RetrainCollectionSchema = object({
23619
+ id: string(),
23620
+ name: string(),
23621
+ createdAt: number(),
23622
+ frameCount: number().int()
23623
+ });
23624
+ var RetrainCollectionCreateResultSchema = discriminatedUnion("kind", [object({
23625
+ kind: literal("created"),
23626
+ collection: RetrainCollectionSchema
23627
+ }), object({
23628
+ kind: literal("refused"),
23629
+ reason: _enum(["empty-name", "duplicate-name"])
23630
+ })]);
23631
+ var RetrainCollectionRenameResultSchema = discriminatedUnion("kind", [object({
23632
+ kind: literal("renamed"),
23633
+ collection: RetrainCollectionSchema
23634
+ }), object({
23635
+ kind: literal("refused"),
23636
+ reason: _enum([
23637
+ "empty-name",
23638
+ "duplicate-name",
23639
+ "unknown-collection"
23640
+ ])
23641
+ })]);
23642
+ /**
23643
+ * The outcome of adding the frame at a recording instant. Every refusal is
23644
+ * named: `still-unavailable` (not recording, a gap, or an undecodable frame —
23645
+ * `detail` says which), `still-busy` (the recorder is at its decode bound; try
23646
+ * again), `unreadable-image`, `write-failed`, `unknown-collection`.
23647
+ */
23648
+ var AddRetrainFrameFromRecordingResultSchema = discriminatedUnion("kind", [object({
23649
+ kind: literal("added"),
23650
+ collectionId: string(),
23651
+ frame: RetrainFrameSchema,
23652
+ /** The moment was already in the dataset; nothing was decoded. */
23653
+ reused: boolean()
23654
+ }), object({
23655
+ kind: literal("refused"),
23656
+ reason: _enum([
23657
+ "unknown-collection",
23658
+ "still-unavailable",
23659
+ "still-busy",
23660
+ "unreadable-image",
23661
+ "write-failed"
23662
+ ]),
23663
+ detail: string().optional()
23664
+ })]);
23665
+ /** A vision LLM profile the AI assist may use, and where it sends the frame. */
23666
+ var RetrainAssistProfileSchema = object({
23667
+ id: string(),
23668
+ name: string(),
23669
+ model: string(),
23670
+ kind: string(),
23671
+ /** `true` when the frame would leave the house (a cloud vendor, or an
23672
+ * endpoint that is not on the local network). The page confirms each such
23673
+ * run, and the provider refuses one without `allowCloud`. */
23674
+ leavesHouse: boolean()
23675
+ });
23676
+ /** A box the AI assist proposed: a draft, plus the model's own reason. */
23677
+ var RetrainLlmProposalSchema = RetrainAnnotationDraftSchema.extend({ reason: string() });
23678
+ /** What the AI assist said about a box that was already on the canvas. */
23679
+ var RetrainLlmReviewSchema = object({
23680
+ /** The `ref` the page sent the box under. */
23681
+ ref: string(),
23682
+ verdict: _enum([
23683
+ "confirmed",
23684
+ "wrong-class",
23685
+ "not-an-object",
23686
+ "uncertain"
23687
+ ]),
23688
+ suggestedClass: RetrainMacroClassSchema.optional(),
23689
+ reason: string()
23690
+ });
23691
+ /**
23692
+ * The AI assist's answer. `proposed` carries drafts (`source: 'llm'`, the
23693
+ * model and its confidence) and reviews; items the model got wrong (a box off
23694
+ * the frame, an unasked class, an unknown ref) are dropped and counted in
23695
+ * `rejected`. A whole answer that is not the schema is `malformed-answer`.
23696
+ */
23697
+ var RetrainLlmAssistResultSchema = discriminatedUnion("kind", [object({
23698
+ kind: literal("proposed"),
23699
+ profileId: string(),
23700
+ model: string(),
23701
+ /** The frame was sent outside the house for this answer. */
23702
+ leftHouse: boolean(),
23703
+ proposals: array(RetrainLlmProposalSchema).readonly(),
23704
+ reviews: array(RetrainLlmReviewSchema).readonly(),
23705
+ rejected: number().int()
23706
+ }), object({
23707
+ kind: literal("refused"),
23708
+ reason: _enum([
23709
+ "unknown-frame",
23710
+ "unreadable-frame",
23711
+ "unknown-profile",
23712
+ "profile-disabled",
23713
+ "no-vision",
23714
+ "cloud-not-confirmed",
23715
+ "llm-error",
23716
+ "malformed-answer"
23717
+ ]),
23718
+ detail: string().optional()
23719
+ })]);
22636
23720
  /** The outcome of a lifecycle move owned by the retrain page. */
22637
23721
  var RetrainTransitionResultSchema = object({
22638
23722
  trackId: string(),
@@ -23350,7 +24434,7 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
23350
24434
  auth: "admin"
23351
24435
  }), method(object({
23352
24436
  deviceId: number(),
23353
- trackId: string(),
24437
+ trackId: string().optional(),
23354
24438
  frameId: string()
23355
24439
  }), object({
23356
24440
  removed: boolean(),
@@ -23367,7 +24451,8 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
23367
24451
  auth: "admin"
23368
24452
  }), method(object({
23369
24453
  deviceId: number(),
23370
- trackId: string(),
24454
+ /** The frame's track, when it has one — checked against the frame. */
24455
+ trackId: string().optional(),
23371
24456
  frameId: string(),
23372
24457
  subject: RetrainAssistSubjectSchema,
23373
24458
  /** Which node runs it. Absent ⇒ wherever an unowned call lands. */
@@ -23375,12 +24460,16 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
23375
24460
  }), RetrainAssistResultSchema, {
23376
24461
  kind: "mutation",
23377
24462
  auth: "admin"
23378
- }), method(object({ trackId: string() }), array(RetrainAnnotationSchema).readonly(), {
24463
+ }), method(object({
24464
+ trackId: string().optional(),
24465
+ frameIds: array(string()).max(2e3).optional()
24466
+ }), array(RetrainAnnotationSchema).readonly(), {
23379
24467
  kind: "query",
23380
24468
  auth: "admin"
23381
24469
  }), method(object({
23382
24470
  deviceId: number(),
23383
- trackId: string(),
24471
+ /** The frame's track, when it has one — checked against the frame. */
24472
+ trackId: string().optional(),
23384
24473
  frameId: string(),
23385
24474
  annotations: array(RetrainAnnotationDraftSchema)
23386
24475
  }), array(RetrainAnnotationSchema).readonly(), {
@@ -23403,7 +24492,7 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
23403
24492
  auth: "admin"
23404
24493
  }), method(object({
23405
24494
  deviceId: number(),
23406
- trackId: string(),
24495
+ trackId: string().optional(),
23407
24496
  frameId: string(),
23408
24497
  complete: boolean()
23409
24498
  }), RetrainFrameSchema, {
@@ -23417,6 +24506,74 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
23417
24506
  kind: "mutation",
23418
24507
  auth: "admin",
23419
24508
  timeoutMs: 60 * 6e4
24509
+ }), method(object({}), array(RetrainAssistProfileSchema).readonly(), {
24510
+ kind: "query",
24511
+ auth: "admin"
24512
+ }), method(object({
24513
+ deviceId: number(),
24514
+ trackId: string().optional(),
24515
+ frameId: string(),
24516
+ profileId: string(),
24517
+ classes: array(RetrainMacroClassSchema).min(1),
24518
+ boxes: array(object({
24519
+ ref: string(),
24520
+ bbox: RetrainBboxSchema,
24521
+ macroClass: RetrainMacroClassSchema,
24522
+ label: string().optional()
24523
+ })).max(50),
24524
+ allowCloud: boolean()
24525
+ }), RetrainLlmAssistResultSchema, {
24526
+ kind: "mutation",
24527
+ auth: "admin",
24528
+ timeoutMs: 18e4
24529
+ }), method(object({ name: string().max(120) }), RetrainCollectionCreateResultSchema, {
24530
+ kind: "mutation",
24531
+ auth: "admin"
24532
+ }), method(object({}), array(RetrainCollectionSchema).readonly(), {
24533
+ kind: "query",
24534
+ auth: "admin"
24535
+ }), method(object({
24536
+ id: string(),
24537
+ name: string().max(120)
24538
+ }), RetrainCollectionRenameResultSchema, {
24539
+ kind: "mutation",
24540
+ auth: "admin"
24541
+ }), method(object({ id: string() }), object({
24542
+ deleted: boolean(),
24543
+ removedFrames: number().int()
24544
+ }), {
24545
+ kind: "mutation",
24546
+ auth: "admin"
24547
+ }), method(object({
24548
+ collectionId: string(),
24549
+ deviceId: number(),
24550
+ epochMs: number()
24551
+ }), AddRetrainFrameFromRecordingResultSchema, {
24552
+ kind: "mutation",
24553
+ auth: "admin",
24554
+ timeoutMs: 6e4
24555
+ }), method(object({
24556
+ collectionId: string(),
24557
+ frameIds: array(string()).min(1).max(500)
24558
+ }), object({
24559
+ added: number().int(),
24560
+ alreadyMember: number().int(),
24561
+ unknownFrameIds: array(string()).readonly()
24562
+ }), {
24563
+ kind: "mutation",
24564
+ auth: "admin"
24565
+ }), method(object({
24566
+ collectionId: string(),
24567
+ frameId: string()
24568
+ }), object({
24569
+ removed: boolean(),
24570
+ deletedFrame: boolean()
24571
+ }), {
24572
+ kind: "mutation",
24573
+ auth: "admin"
24574
+ }), method(object({ collectionId: string() }), array(RetrainFrameSchema).readonly(), {
24575
+ kind: "query",
24576
+ auth: "admin"
23420
24577
  }), method(object({
23421
24578
  /** Which of the three event tables owns the row. */
23422
24579
  ownerType: EventOwnerTypeSchema,
@@ -24040,13 +25197,31 @@ var RecommendationReasonSchema = discriminatedUnion("kind", [
24040
25197
  object({
24041
25198
  kind: literal("no-family-build"),
24042
25199
  format: ModelFormatSchema$1
25200
+ }),
25201
+ object({
25202
+ kind: literal("kept-custom-pin"),
25203
+ modelId: string(),
25204
+ deviceKey: string()
24043
25205
  })
24044
25206
  ]);
25207
+ /** Why a device is left exactly as it is, whatever the plan would pick (D786). */
25208
+ var KeptReasonSchema = _enum(["custom-pin"]);
25209
+ /**
25210
+ * Where a choice's latency came from (D791): this node's own benchmark
25211
+ * result, or the hardware-class table. Measured on the node beats the table.
25212
+ */
25213
+ var LatencySourceSchema = discriminatedUnion("kind", [object({ kind: literal("table") }), object({
25214
+ kind: literal("node-benchmark"),
25215
+ resultId: string(),
25216
+ measuredAtMs: number()
25217
+ })]);
24045
25218
  var DeviceModelChoiceSchema = object({
24046
25219
  modelId: string(),
24047
25220
  p50Ms: number(),
24048
25221
  fps: number(),
24049
25222
  measured: boolean(),
25223
+ /** Absent on a plan from before D791 — read as the table. */
25224
+ source: LatencySourceSchema.optional(),
24050
25225
  /** Parallel sessions at the camera rate with the headroom kept free: ⌊fps × (1 − headroom) / camera fps⌋. */
24051
25226
  capacitySessions: number(),
24052
25227
  personRecall: number()
@@ -24057,6 +25232,8 @@ var DeviceRecommendationSchema = object({
24057
25232
  enabled: boolean(),
24058
25233
  available: boolean(),
24059
25234
  chosen: DeviceModelChoiceSchema.nullable(),
25235
+ /** Present when the device is kept as is: Apply writes nothing on it. */
25236
+ kept: KeptReasonSchema.optional(),
24060
25237
  reasons: array(RecommendationReasonSchema).readonly()
24061
25238
  });
24062
25239
  var NodeRecommendationSchema = object({
@@ -24110,6 +25287,17 @@ var AutoTuneWarningSchema = discriminatedUnion("kind", [
24110
25287
  kind: literal("coral-enabled"),
24111
25288
  nodeId: string(),
24112
25289
  deviceKey: string()
25290
+ }),
25291
+ object({
25292
+ kind: literal("custom-pin-kept"),
25293
+ nodeId: string(),
25294
+ deviceKey: string().nullable(),
25295
+ deviceId: number().nullable(),
25296
+ modelId: string()
25297
+ }),
25298
+ object({
25299
+ kind: literal("custom-registry-unreadable"),
25300
+ error: string()
24113
25301
  })
24114
25302
  ]);
24115
25303
  var AutoTuneOptionsSchema = object({
@@ -24288,13 +25476,14 @@ var SuggestSharesResultSchema = object({
24288
25476
  nodes: array(SuggestedNodeShareSchema).readonly()
24289
25477
  });
24290
25478
  /**
24291
- * Where the node and device shares come from (D750, D755).
24292
- * - `hardware` (default) — computed by the system from each node's static
24293
- * capacity (its accelerators at their Auto tune models, from the measured
24294
- * latency table), recomputed whenever a node or device joins, leaves, is
24295
- * switched on or off, or changes model. No load input.
24296
- * - `benchmark` — the same, from each node's measured capacity (node
24297
- * benchmark results); a node without results falls back to `hardware`.
25479
+ * Where the node and device shares come from (D750, D755, D791).
25480
+ * - `benchmark` (default since D791) — each node's capacity as its own node
25481
+ * benchmark measured it; a node without fresh results is sized from
25482
+ * `hardware` and says so. Measured on the node beats the table.
25483
+ * - `hardware` — computed from each node's static capacity only (its
25484
+ * accelerators at their Auto tune models, from the latency table).
25485
+ * Both are recomputed whenever a node or device joins, leaves, is switched
25486
+ * on or off, changes model, or a benchmark result is written. No load input.
24298
25487
  * - `manual` — the operator's stored sliders.
24299
25488
  * Either way a node or device that cannot take sessions gives its share to
24300
25489
  * the others in proportion; the stored values are never rewritten for that.
@@ -24343,6 +25532,362 @@ var EffectiveSharesSchema = object({
24343
25532
  nodeWeights: record(string(), number()),
24344
25533
  deviceWeights: record(string(), record(string(), number()))
24345
25534
  });
25535
+ /**
25536
+ * Wire shapes of the node benchmark (D791): the operator's plan, the
25537
+ * preflight the confirmation shows, the run the orchestrator owns, what the
25538
+ * measuring runner reports, and the result rows Auto tune and the automatic
25539
+ * shares read.
25540
+ *
25541
+ * ONE node at a time, owned by the pipeline orchestrator. While a run is
25542
+ * active the cluster is in BENCHMARK MODE for that node: it is not a
25543
+ * detection candidate, camera pins naming it are ignored so its sessions move
25544
+ * elsewhere, and both come back when the mode ends — after a crash or a hub
25545
+ * restart too (a persisted manifest, reconciled against the registry).
25546
+ *
25547
+ * Two measurements, both on the node, driven by its own runner (frames never
25548
+ * cross a process at frame rate, D9):
25549
+ * - `device` — one accelerator × one candidate detector, root only, open
25550
+ * loop: how many streams at the camera rate it carries inside the frame
25551
+ * interval;
25552
+ * - `pipeline` — the chosen detector plus the operator's detail steps
25553
+ * (faces, plates, classifiers, CLIP…), on varied frames from the bench
25554
+ * clip: how many parallel sessions the node carries before latency, drops,
25555
+ * CPU, RAM or the event loop give out.
25556
+ */
25557
+ /** Defaults and bounds, one place. */
25558
+ var NODE_BENCHMARK_DEFAULTS = {
25559
+ fpsPerStream: 10,
25560
+ budgetMinutes: 45,
25561
+ minBudgetMinutes: 10,
25562
+ maxBudgetMinutes: 120,
25563
+ /** A result older than this no longer beats the table. */
25564
+ staleAfterDays: 30,
25565
+ /** Warm-in per ramp step (not accounted). */
25566
+ settleSec: 5,
25567
+ /** Accounted window per ramp step. */
25568
+ measureSec: 20,
25569
+ /** Longest the drain may take before the run is refused. */
25570
+ drainTimeoutSec: 120,
25571
+ /** Candidate models per device in one run. */
25572
+ maxModelsPerDevice: 6
25573
+ };
25574
+ /** The two measurements a run can make. */
25575
+ var NodeBenchmarkPhaseSchema = _enum(["device", "pipeline"]);
25576
+ var NodeBenchmarkDevicePlanSchema = object({
25577
+ /** `<backend>:<device>` — `openvino:npu`, `coreml:all`, `cpu`. */
25578
+ deviceKey: string().min(1),
25579
+ /**
25580
+ * Root detector candidates for the `device` measurement, in the order
25581
+ * measured. The FIRST is the one the `pipeline` measurement runs.
25582
+ */
25583
+ modelIds: array(string().min(1)).min(1).max(NODE_BENCHMARK_DEFAULTS.maxModelsPerDevice)
25584
+ });
25585
+ /** What the operator confirmed. */
25586
+ var NodeBenchmarkPlanSchema = object({
25587
+ nodeId: string().min(1),
25588
+ devices: array(NodeBenchmarkDevicePlanSchema).min(1),
25589
+ /** Which measurements run. At least one. */
25590
+ phases: array(NodeBenchmarkPhaseSchema).min(1).default(["device", "pipeline"]),
25591
+ /**
25592
+ * Detail steps (catalog step ids under the root: faces, plates,
25593
+ * classifiers, CLIP…) the `pipeline` measurement enables. The root
25594
+ * detector always runs.
25595
+ */
25596
+ steps: array(string().min(1)).default([]),
25597
+ /** Offered rate of one stream / session. */
25598
+ fpsPerStream: number().int().min(1).max(30).default(NODE_BENCHMARK_DEFAULTS.fpsPerStream),
25599
+ /** Hard deadline: the mode ends and the cluster is restored when it passes. */
25600
+ budgetMinutes: number().int().min(NODE_BENCHMARK_DEFAULTS.minBudgetMinutes).max(NODE_BENCHMARK_DEFAULTS.maxBudgetMinutes).default(NODE_BENCHMARK_DEFAULTS.budgetMinutes),
25601
+ /** Keep the models the run downloaded (default: delete what was not installed before). */
25602
+ keepDownloadedModels: boolean().default(false),
25603
+ /** Start although the other nodes' capacity does not cover the sessions running now. */
25604
+ acceptInsufficientHeadroom: boolean().default(false)
25605
+ });
25606
+ var NodeBenchmarkRefusalSchema = object({
25607
+ kind: _enum([
25608
+ "benchmark-active",
25609
+ "node-offline",
25610
+ "unknown-device",
25611
+ "no-phase",
25612
+ "insufficient-headroom"
25613
+ ]),
25614
+ detail: string(),
25615
+ overridable: boolean()
25616
+ });
25617
+ /** A camera whose detection leaves the node for the run. */
25618
+ var NodeBenchmarkMovingCameraSchema = object({
25619
+ deviceId: number(),
25620
+ /** Placed on the node now (a standing attach or a running session). */
25621
+ placedOnNode: boolean(),
25622
+ /** A node pin naming this node, ignored for the run. */
25623
+ pinnedToNode: boolean()
25624
+ });
25625
+ /** A camera that cannot leave: no other node can obtain its frames. */
25626
+ var NodeBenchmarkStayingCameraSchema = object({
25627
+ deviceId: number(),
25628
+ reason: literal("only-frame-source")
25629
+ });
25630
+ var NodeBenchmarkPreflightSchema = object({
25631
+ nodeId: string(),
25632
+ online: boolean(),
25633
+ moving: array(NodeBenchmarkMovingCameraSchema).readonly(),
25634
+ /** Keep running on the node during the run; the result is flagged contaminated. */
25635
+ staying: array(NodeBenchmarkStayingCameraSchema).readonly(),
25636
+ estimatedDurationMs: number(),
25637
+ /** The run ends and the cluster is restored at the latest after this long. */
25638
+ budgetMs: number(),
25639
+ phases: array(NodeBenchmarkPhaseSchema).readonly(),
25640
+ steps: array(string()).readonly(),
25641
+ devices: array(NodeBenchmarkDevicePlanSchema).readonly(),
25642
+ /** Parallel sessions the cluster runs now, and what the other nodes can carry. */
25643
+ headroom: object({
25644
+ sessionsNow: number(),
25645
+ otherNodesCapacitySessions: number().nullable()
25646
+ }),
25647
+ refusals: array(NodeBenchmarkRefusalSchema).readonly(),
25648
+ canStart: boolean()
25649
+ });
25650
+ /** Where the measuring runner is. */
25651
+ var NodeBenchProgressSchema = object({
25652
+ phase: _enum([
25653
+ "preparing",
25654
+ "device",
25655
+ "pipeline",
25656
+ "cleanup"
25657
+ ]),
25658
+ deviceKey: string().nullable(),
25659
+ modelId: string().nullable(),
25660
+ /** Streams (device) or sessions (pipeline) of the step running now. */
25661
+ load: number().nullable(),
25662
+ cellsDone: number(),
25663
+ cellsTotal: number(),
25664
+ message: string()
25665
+ });
25666
+ /** What limited a ramp. `none` = the ramp ran out of steps still passing. */
25667
+ var NodeBenchLimitSchema = _enum([
25668
+ "p95",
25669
+ "drops",
25670
+ "errors",
25671
+ "stall",
25672
+ "cpu",
25673
+ "ram",
25674
+ "none"
25675
+ ]);
25676
+ var NodeBenchRampStepSchema = object({
25677
+ load: number(),
25678
+ pass: boolean(),
25679
+ p95Ms: number(),
25680
+ dropRatio: number(),
25681
+ /** Completed frames per second over the accounted window. */
25682
+ fps: number(),
25683
+ cpuPct: number().nullable(),
25684
+ ramFreePct: number().nullable(),
25685
+ failReasons: array(string()).readonly()
25686
+ });
25687
+ var NodeBenchCellSchema = discriminatedUnion("phase", [object({
25688
+ phase: literal("device"),
25689
+ deviceKey: string(),
25690
+ modelId: string(),
25691
+ /** Single-stream latency (the K = 1 step). */
25692
+ p50Ms: number(),
25693
+ p95Ms: number(),
25694
+ p99Ms: number(),
25695
+ /** Frames per second sustained at the last passing step. */
25696
+ fps: number(),
25697
+ /** Streams at the camera rate the device carried inside the frame interval; 0 = not even one. */
25698
+ kMax: number(),
25699
+ limitedBy: NodeBenchLimitSchema,
25700
+ /** First call (model load + warm-up). */
25701
+ warmupMs: number(),
25702
+ ramp: array(NodeBenchRampStepSchema).readonly()
25703
+ }), object({
25704
+ phase: literal("pipeline"),
25705
+ deviceKey: string(),
25706
+ modelId: string(),
25707
+ steps: array(string()).readonly(),
25708
+ /** Parallel sessions at the camera rate the node carried; 0 = not even one. */
25709
+ maxSessions: number(),
25710
+ limitedBy: NodeBenchLimitSchema,
25711
+ /** Detail steps that produced at least one result on the clip — a step that never fired measured nothing. */
25712
+ stepsFired: array(string()).readonly(),
25713
+ warmupMs: number(),
25714
+ ramp: array(NodeBenchRampStepSchema).readonly()
25715
+ })]);
25716
+ /**
25717
+ * What a result was measured ON. A result whose fingerprint no longer matches
25718
+ * the node no longer beats the table.
25719
+ */
25720
+ var NodeBenchFingerprintSchema = object({
25721
+ pipelineVersion: string().nullable(),
25722
+ cpuModel: string().nullable(),
25723
+ ramGb: number().nullable(),
25724
+ os: string().nullable(),
25725
+ /** Per device: the pool the cells ran on (runtime + tuning). */
25726
+ pools: record(string(), object({
25727
+ runtime: string(),
25728
+ numWorkers: number(),
25729
+ concurrency: number(),
25730
+ batchMode: string()
25731
+ })).default({})
25732
+ });
25733
+ /** The frames the run used. */
25734
+ var NodeBenchClipSchema = object({
25735
+ /** `camstack-bench-v1` or `reference-images` (the fallback when the clip is not reachable). */
25736
+ id: string(),
25737
+ revision: string().nullable(),
25738
+ frames: number(),
25739
+ width: number(),
25740
+ height: number()
25741
+ });
25742
+ var NodeBenchRunnerInputSchema = object({
25743
+ runId: string().min(1),
25744
+ devices: array(NodeBenchmarkDevicePlanSchema).min(1),
25745
+ phases: array(NodeBenchmarkPhaseSchema).min(1),
25746
+ /** The full detail step tree root for the `pipeline` measurement is built on the node from these ids. */
25747
+ steps: array(string()).default([]),
25748
+ fpsPerStream: number().int().min(1).max(30),
25749
+ /** The runner stops on its own past this instant, whatever the hub does. */
25750
+ deadlineAtMs: number(),
25751
+ settleSec: number().min(0).max(60).default(NODE_BENCHMARK_DEFAULTS.settleSec),
25752
+ measureSec: number().min(2).max(300).default(NODE_BENCHMARK_DEFAULTS.measureSec),
25753
+ keepDownloadedModels: boolean().default(false)
25754
+ });
25755
+ var NodeBenchRunnerStateSchema = _enum([
25756
+ "running",
25757
+ "done",
25758
+ "failed",
25759
+ "aborted"
25760
+ ]);
25761
+ var NodeBenchRunnerStatusSchema = object({
25762
+ runId: string(),
25763
+ nodeId: string(),
25764
+ state: NodeBenchRunnerStateSchema,
25765
+ progress: NodeBenchProgressSchema.nullable(),
25766
+ /** Every finished cell so far — a run stopped half way keeps what it measured. */
25767
+ cells: array(NodeBenchCellSchema).readonly(),
25768
+ fingerprint: NodeBenchFingerprintSchema.nullable(),
25769
+ clip: NodeBenchClipSchema.nullable(),
25770
+ /** Cameras seen running on the node during the run (they share its pools). */
25771
+ activeCameraIds: array(number()).readonly(),
25772
+ /** Models the run downloaded and then deleted (not installed before). */
25773
+ deletedModels: array(string()).readonly(),
25774
+ error: string().nullable(),
25775
+ startedAtMs: number(),
25776
+ finishedAtMs: number().nullable()
25777
+ });
25778
+ var NodeBenchmarkStateSchema = _enum([
25779
+ "draining",
25780
+ "measuring",
25781
+ "restoring",
25782
+ "done",
25783
+ "failed",
25784
+ "aborted"
25785
+ ]);
25786
+ /** Why a run ended. */
25787
+ var NodeBenchmarkEndReasonSchema = _enum([
25788
+ "completed",
25789
+ "operator-abort",
25790
+ "deadline",
25791
+ "node-lost",
25792
+ "runner-lost",
25793
+ "hub-restart",
25794
+ "drain-timeout",
25795
+ "failed"
25796
+ ]);
25797
+ var NodeBenchmarkRunSchema = object({
25798
+ runId: string(),
25799
+ nodeId: string(),
25800
+ state: NodeBenchmarkStateSchema,
25801
+ plan: NodeBenchmarkPlanSchema,
25802
+ startedAtMs: number(),
25803
+ deadlineAtMs: number(),
25804
+ finishedAtMs: number().nullable(),
25805
+ endReason: NodeBenchmarkEndReasonSchema.nullable(),
25806
+ error: string().nullable(),
25807
+ /** Cameras moved off the node for the run. */
25808
+ moved: array(number()).readonly(),
25809
+ /** Cameras that stayed (their only frame source is the node). */
25810
+ staying: array(number()).readonly(),
25811
+ /** Something else ran on the node's pools during the run. */
25812
+ contaminated: boolean(),
25813
+ progress: NodeBenchProgressSchema.nullable(),
25814
+ resultIds: array(string()).readonly()
25815
+ });
25816
+ /** `getNodeBenchmarkStatus`: the active run (or the last one), and whether benchmark mode is on. */
25817
+ var NodeBenchmarkStatusSchema = object({
25818
+ /** The node the cluster is in benchmark mode for; null = none. */
25819
+ modeNodeId: string().nullable(),
25820
+ run: NodeBenchmarkRunSchema.nullable()
25821
+ });
25822
+ /**
25823
+ * One stored measurement — the only authority Auto tune and the automatic
25824
+ * shares read measured capacity from. Written by the orchestrator when a run
25825
+ * ends, never by anyone else.
25826
+ */
25827
+ var NodeBenchmarkResultSchema = object({
25828
+ id: string(),
25829
+ runId: string(),
25830
+ nodeId: string(),
25831
+ cell: NodeBenchCellSchema,
25832
+ fpsPerStream: number(),
25833
+ fingerprint: NodeBenchFingerprintSchema.nullable(),
25834
+ clip: NodeBenchClipSchema.nullable(),
25835
+ /** Other work shared the node's pools (a camera that could not move, or the hub's own duties). */
25836
+ contaminated: boolean(),
25837
+ stayingCameras: array(number()).readonly(),
25838
+ /** The run ended early; the cell itself completed. */
25839
+ partialRun: boolean(),
25840
+ measuredAtMs: number()
25841
+ });
25842
+ var ListNodeBenchmarkResultsInputSchema = object({
25843
+ nodeId: string().optional(),
25844
+ deviceKey: string().optional()
25845
+ });
25846
+ /** A result with its standing today: does it still beat the table? */
25847
+ var NodeBenchmarkResultViewSchema = NodeBenchmarkResultSchema.extend({
25848
+ /** `fresh` beats the table; `stale` falls back to it; `superseded` = a newer row covers the same cell. */
25849
+ standing: _enum([
25850
+ "fresh",
25851
+ "stale",
25852
+ "superseded"
25853
+ ]),
25854
+ staleWhy: _enum([
25855
+ "age",
25856
+ "runtime",
25857
+ "pool-tuning"
25858
+ ]).nullable()
25859
+ });
25860
+ object({
25861
+ runId: string(),
25862
+ nodeId: string(),
25863
+ startedAtMs: number(),
25864
+ deadlineAtMs: number(),
25865
+ plan: NodeBenchmarkPlanSchema,
25866
+ moved: array(number()).readonly(),
25867
+ staying: array(number()).readonly()
25868
+ });
25869
+ /** Candidate detectors per device, for the plan editor. */
25870
+ var NodeBenchmarkCandidatesSchema = object({
25871
+ nodeId: string(),
25872
+ reachable: boolean(),
25873
+ devices: array(object({
25874
+ deviceKey: string(),
25875
+ enabled: boolean(),
25876
+ available: boolean(),
25877
+ /** Ordered: what Auto tune would pick first, then the rest of the family by accuracy. */
25878
+ suggested: array(string()).readonly(),
25879
+ /** Every root detector the device has a build for. */
25880
+ all: array(string()).readonly(),
25881
+ /** The model the device runs now, when pinned. */
25882
+ currentModelId: string().nullable()
25883
+ })).readonly(),
25884
+ /** Detail steps the node's catalog offers under the root (for the `pipeline` measurement). */
25885
+ steps: array(object({
25886
+ id: string(),
25887
+ name: string(),
25888
+ slot: string()
25889
+ })).readonly()
25890
+ });
24346
25891
  object({
24347
25892
  activeCameras: number(),
24348
25893
  throttledCameras: number(),
@@ -25471,7 +27016,16 @@ method(RunnerCameraConfigSchema, object({ success: literal(true) }), { kind: "mu
25471
27016
  }), ParkedTrackFrameSchema.nullable()), method(object({
25472
27017
  deviceId: number(),
25473
27018
  trackId: string()
25474
- }), object({ released: number().int().nonnegative() }), { kind: "mutation" });
27019
+ }), object({ released: number().int().nonnegative() }), { kind: "mutation" }), method(NodeBenchRunnerInputSchema, object({
27020
+ accepted: literal(true),
27021
+ runId: string()
27022
+ }), {
27023
+ kind: "mutation",
27024
+ auth: "admin"
27025
+ }), method(object({ runId: string() }), NodeBenchRunnerStatusSchema.nullable(), { auth: "admin" }), method(object({ runId: string() }), object({ aborted: boolean() }), {
27026
+ kind: "mutation",
27027
+ auth: "admin"
27028
+ });
25475
27029
  var CameraPipelineConfigSchema = object({
25476
27030
  engine: PipelineEngineChoiceSchema.optional(),
25477
27031
  steps: array(PipelineStepInputSchema).readonly(),
@@ -26110,6 +27664,21 @@ method(object({
26110
27664
  }), method(PlacementStatsInputSchema, PlacementStatsSchema, { auth: "admin" }), method(SuggestSharesInputSchema, SuggestSharesResultSchema, { auth: "admin" }), method(_void(), EffectiveSharesSchema, { auth: "admin" }), method(SetShareSourceInputSchema, object({ success: literal(true) }), {
26111
27665
  kind: "mutation",
26112
27666
  auth: "admin"
27667
+ }), method(NodeBenchmarkPlanSchema, NodeBenchmarkPreflightSchema, { auth: "admin" }), method(NodeBenchmarkPlanSchema, discriminatedUnion("kind", [object({
27668
+ kind: literal("started"),
27669
+ runId: string()
27670
+ }), object({
27671
+ kind: literal("refused"),
27672
+ preflight: NodeBenchmarkPreflightSchema
27673
+ })]), {
27674
+ kind: "mutation",
27675
+ auth: "admin"
27676
+ }), method(_void(), NodeBenchmarkStatusSchema, { auth: "admin" }), method(object({ runId: string() }), object({ aborted: boolean() }), {
27677
+ kind: "mutation",
27678
+ auth: "admin"
27679
+ }), method(object({ nodeId: string() }), NodeBenchmarkCandidatesSchema, { auth: "admin" }), method(ListNodeBenchmarkResultsInputSchema, array(NodeBenchmarkResultViewSchema).readonly(), { auth: "admin" }), method(object({ id: string() }), object({ deleted: boolean() }), {
27680
+ kind: "mutation",
27681
+ auth: "admin"
26113
27682
  }), method(object({ deviceId: number() }), CameraPipelineSettingsSchema.nullable()), method(object({
26114
27683
  deviceId: number(),
26115
27684
  addonId: string(),
@@ -32730,6 +34299,9 @@ var CreateIntegrationInputSchema = object({
32730
34299
  enabled: boolean().optional(),
32731
34300
  info: record(string(), unknown()).optional(),
32732
34301
  settings: record(string(), unknown()).optional(),
34302
+ /** Keys of `settings` the form's schema declares secret (by type) — kept in
34303
+ * the keychain, not the table (D787). */
34304
+ secretKeys: array(string()).optional(),
32733
34305
  skipRestart: boolean().optional()
32734
34306
  });
32735
34307
  var UpdateIntegrationInputSchema = object({
@@ -32753,7 +34325,9 @@ method(_void(), array(IntegrationWithStateSchema)), method(object({ id: string()
32753
34325
  auth: "admin"
32754
34326
  }), method(object({ id: string() }), record(string(), unknown()), { auth: "admin" }), method(object({
32755
34327
  id: string(),
32756
- settings: record(string(), unknown())
34328
+ settings: record(string(), unknown()),
34329
+ /** Keys the form's schema declares secret (by type) — keychain-stored (D787). */
34330
+ secretKeys: array(string()).optional()
32757
34331
  }), object({ success: boolean() }), {
32758
34332
  kind: "mutation",
32759
34333
  auth: "admin"
@@ -41378,7 +42952,8 @@ var BaseDevice = class {
41378
42952
  this.role = options.role;
41379
42953
  this.parentDeviceId = ctx.parentDeviceId;
41380
42954
  const seedData = ctx.persistedConfig ?? {};
41381
- this.config = DeviceConfig.fromSchema(schema, (data) => ctx.persistConfig(data), seedData, ({ droppedKeys, issues }) => {
42955
+ const declaredSecretPaths = collectZodSecretPaths(schema);
42956
+ this.config = DeviceConfig.fromSchema(schema, (data) => ctx.persistConfig(data, { secretConfigPaths: declaredSecretPaths }), seedData, ({ droppedKeys, issues }) => {
41382
42957
  ctx.logger.warn("Device config recovery: dropping invalid persisted fields", {
41383
42958
  tags: {
41384
42959
  deviceId: ctx.id,
@@ -45067,6 +46642,90 @@ Object.freeze({
45067
46642
  addonId: null,
45068
46643
  access: "create"
45069
46644
  },
46645
+ "keychain.delete": {
46646
+ capName: "keychain",
46647
+ capScope: "system",
46648
+ addonId: null,
46649
+ access: "delete"
46650
+ },
46651
+ "keychain.getState": {
46652
+ capName: "keychain",
46653
+ capScope: "system",
46654
+ addonId: null,
46655
+ access: "view"
46656
+ },
46657
+ "keychain.listMeta": {
46658
+ capName: "keychain",
46659
+ capScope: "system",
46660
+ addonId: null,
46661
+ access: "view"
46662
+ },
46663
+ "keychain.put": {
46664
+ capName: "keychain",
46665
+ capScope: "system",
46666
+ addonId: null,
46667
+ access: "create"
46668
+ },
46669
+ "keychain.resolve": {
46670
+ capName: "keychain",
46671
+ capScope: "system",
46672
+ addonId: null,
46673
+ access: "view"
46674
+ },
46675
+ "keychainAdmin.deleteOrphans": {
46676
+ capName: "keychain-admin",
46677
+ capScope: "system",
46678
+ addonId: null,
46679
+ access: "delete"
46680
+ },
46681
+ "keychainAdmin.downloadRecoveryKey": {
46682
+ capName: "keychain-admin",
46683
+ capScope: "system",
46684
+ addonId: null,
46685
+ access: "create"
46686
+ },
46687
+ "keychainAdmin.listAudit": {
46688
+ capName: "keychain-admin",
46689
+ capScope: "system",
46690
+ addonId: null,
46691
+ access: "view"
46692
+ },
46693
+ "keychainAdmin.listSecrets": {
46694
+ capName: "keychain-admin",
46695
+ capScope: "system",
46696
+ addonId: null,
46697
+ access: "view"
46698
+ },
46699
+ "keychainAdmin.purgeRetiredKeys": {
46700
+ capName: "keychain-admin",
46701
+ capScope: "system",
46702
+ addonId: null,
46703
+ access: "delete"
46704
+ },
46705
+ "keychainAdmin.resetKeychain": {
46706
+ capName: "keychain-admin",
46707
+ capScope: "system",
46708
+ addonId: null,
46709
+ access: "delete"
46710
+ },
46711
+ "keychainAdmin.reveal": {
46712
+ capName: "keychain-admin",
46713
+ capScope: "system",
46714
+ addonId: null,
46715
+ access: "create"
46716
+ },
46717
+ "keychainAdmin.rotateMasterKey": {
46718
+ capName: "keychain-admin",
46719
+ capScope: "system",
46720
+ addonId: null,
46721
+ access: "create"
46722
+ },
46723
+ "keychainAdmin.status": {
46724
+ capName: "keychain-admin",
46725
+ capScope: "system",
46726
+ addonId: null,
46727
+ access: "view"
46728
+ },
45070
46729
  "lawnMowerControl.dock": {
45071
46730
  capName: "lawn-mower-control",
45072
46731
  capScope: "device",
@@ -46441,6 +48100,18 @@ Object.freeze({
46441
48100
  addonId: null,
46442
48101
  access: "create"
46443
48102
  },
48103
+ "pipelineAnalytics.addRetrainFrameFromRecording": {
48104
+ capName: "pipeline-analytics",
48105
+ capScope: "device",
48106
+ addonId: null,
48107
+ access: "create"
48108
+ },
48109
+ "pipelineAnalytics.addRetrainFramesToCollection": {
48110
+ capName: "pipeline-analytics",
48111
+ capScope: "device",
48112
+ addonId: null,
48113
+ access: "create"
48114
+ },
46444
48115
  "pipelineAnalytics.applyDeviceSettingsPatch": {
46445
48116
  capName: "pipeline-analytics",
46446
48117
  capScope: "device",
@@ -46489,12 +48160,24 @@ Object.freeze({
46489
48160
  addonId: null,
46490
48161
  access: "view"
46491
48162
  },
48163
+ "pipelineAnalytics.createRetrainCollection": {
48164
+ capName: "pipeline-analytics",
48165
+ capScope: "device",
48166
+ addonId: null,
48167
+ access: "create"
48168
+ },
46492
48169
  "pipelineAnalytics.deleteDeviceEvents": {
46493
48170
  capName: "pipeline-analytics",
46494
48171
  capScope: "device",
46495
48172
  addonId: null,
46496
48173
  access: "delete"
46497
48174
  },
48175
+ "pipelineAnalytics.deleteRetrainCollection": {
48176
+ capName: "pipeline-analytics",
48177
+ capScope: "device",
48178
+ addonId: null,
48179
+ access: "delete"
48180
+ },
46498
48181
  "pipelineAnalytics.deleteTracks": {
46499
48182
  capName: "pipeline-analytics",
46500
48183
  capScope: "device",
@@ -46699,6 +48382,24 @@ Object.freeze({
46699
48382
  addonId: null,
46700
48383
  access: "view"
46701
48384
  },
48385
+ "pipelineAnalytics.listRetrainAssistProfiles": {
48386
+ capName: "pipeline-analytics",
48387
+ capScope: "device",
48388
+ addonId: null,
48389
+ access: "view"
48390
+ },
48391
+ "pipelineAnalytics.listRetrainCollectionFrames": {
48392
+ capName: "pipeline-analytics",
48393
+ capScope: "device",
48394
+ addonId: null,
48395
+ access: "view"
48396
+ },
48397
+ "pipelineAnalytics.listRetrainCollections": {
48398
+ capName: "pipeline-analytics",
48399
+ capScope: "device",
48400
+ addonId: null,
48401
+ access: "view"
48402
+ },
46702
48403
  "pipelineAnalytics.listRetrainFrames": {
46703
48404
  capName: "pipeline-analytics",
46704
48405
  capScope: "device",
@@ -46747,6 +48448,12 @@ Object.freeze({
46747
48448
  addonId: null,
46748
48449
  access: "create"
46749
48450
  },
48451
+ "pipelineAnalytics.proposeRetrainAnnotationsWithLlm": {
48452
+ capName: "pipeline-analytics",
48453
+ capScope: "device",
48454
+ addonId: null,
48455
+ access: "create"
48456
+ },
46750
48457
  "pipelineAnalytics.pruneEvents": {
46751
48458
  capName: "pipeline-analytics",
46752
48459
  capScope: "device",
@@ -46801,6 +48508,18 @@ Object.freeze({
46801
48508
  addonId: null,
46802
48509
  access: "create"
46803
48510
  },
48511
+ "pipelineAnalytics.removeRetrainFrameFromCollection": {
48512
+ capName: "pipeline-analytics",
48513
+ capScope: "device",
48514
+ addonId: null,
48515
+ access: "delete"
48516
+ },
48517
+ "pipelineAnalytics.renameRetrainCollection": {
48518
+ capName: "pipeline-analytics",
48519
+ capScope: "device",
48520
+ addonId: null,
48521
+ access: "create"
48522
+ },
46804
48523
  "pipelineAnalytics.restageRetrainTrack": {
46805
48524
  capName: "pipeline-analytics",
46806
48525
  capScope: "device",
@@ -47089,6 +48808,12 @@ Object.freeze({
47089
48808
  addonId: null,
47090
48809
  access: "view"
47091
48810
  },
48811
+ "pipelineOrchestrator.abortNodeBenchmark": {
48812
+ capName: "pipeline-orchestrator",
48813
+ capScope: "system",
48814
+ addonId: null,
48815
+ access: "create"
48816
+ },
47092
48817
  "pipelineOrchestrator.applyAutoTune": {
47093
48818
  capName: "pipeline-orchestrator",
47094
48819
  capScope: "system",
@@ -47113,6 +48838,12 @@ Object.freeze({
47113
48838
  addonId: null,
47114
48839
  access: "create"
47115
48840
  },
48841
+ "pipelineOrchestrator.deleteNodeBenchmarkResult": {
48842
+ capName: "pipeline-orchestrator",
48843
+ capScope: "system",
48844
+ addonId: null,
48845
+ access: "delete"
48846
+ },
47116
48847
  "pipelineOrchestrator.getAgentLoad": {
47117
48848
  capName: "pipeline-orchestrator",
47118
48849
  capScope: "system",
@@ -47221,6 +48952,24 @@ Object.freeze({
47221
48952
  addonId: null,
47222
48953
  access: "view"
47223
48954
  },
48955
+ "pipelineOrchestrator.getNodeBenchmarkCandidates": {
48956
+ capName: "pipeline-orchestrator",
48957
+ capScope: "system",
48958
+ addonId: null,
48959
+ access: "view"
48960
+ },
48961
+ "pipelineOrchestrator.getNodeBenchmarkPreflight": {
48962
+ capName: "pipeline-orchestrator",
48963
+ capScope: "system",
48964
+ addonId: null,
48965
+ access: "view"
48966
+ },
48967
+ "pipelineOrchestrator.getNodeBenchmarkStatus": {
48968
+ capName: "pipeline-orchestrator",
48969
+ capScope: "system",
48970
+ addonId: null,
48971
+ access: "view"
48972
+ },
47224
48973
  "pipelineOrchestrator.getNodeInferenceDevices": {
47225
48974
  capName: "pipeline-orchestrator",
47226
48975
  capScope: "system",
@@ -47263,6 +49012,12 @@ Object.freeze({
47263
49012
  addonId: null,
47264
49013
  access: "view"
47265
49014
  },
49015
+ "pipelineOrchestrator.listNodeBenchmarkResults": {
49016
+ capName: "pipeline-orchestrator",
49017
+ capScope: "system",
49018
+ addonId: null,
49019
+ access: "view"
49020
+ },
47266
49021
  "pipelineOrchestrator.pauseForStorageMigration": {
47267
49022
  capName: "pipeline-orchestrator",
47268
49023
  capScope: "system",
@@ -47407,6 +49162,12 @@ Object.freeze({
47407
49162
  addonId: null,
47408
49163
  access: "create"
47409
49164
  },
49165
+ "pipelineOrchestrator.startNodeBenchmark": {
49166
+ capName: "pipeline-orchestrator",
49167
+ capScope: "system",
49168
+ addonId: null,
49169
+ access: "create"
49170
+ },
47410
49171
  "pipelineOrchestrator.suggestShares": {
47411
49172
  capName: "pipeline-orchestrator",
47412
49173
  capScope: "system",
@@ -47425,6 +49186,12 @@ Object.freeze({
47425
49186
  addonId: null,
47426
49187
  access: "create"
47427
49188
  },
49189
+ "pipelineRunner.abortNodeBench": {
49190
+ capName: "pipeline-runner",
49191
+ capScope: "system",
49192
+ addonId: null,
49193
+ access: "create"
49194
+ },
47428
49195
  "pipelineRunner.attachCamera": {
47429
49196
  capName: "pipeline-runner",
47430
49197
  capScope: "system",
@@ -47473,6 +49240,12 @@ Object.freeze({
47473
49240
  addonId: null,
47474
49241
  access: "view"
47475
49242
  },
49243
+ "pipelineRunner.getNodeBenchStatus": {
49244
+ capName: "pipeline-runner",
49245
+ capScope: "system",
49246
+ addonId: null,
49247
+ access: "view"
49248
+ },
47476
49249
  "pipelineRunner.getParkedTrackFrame": {
47477
49250
  capName: "pipeline-runner",
47478
49251
  capScope: "system",
@@ -47515,6 +49288,12 @@ Object.freeze({
47515
49288
  addonId: null,
47516
49289
  access: "create"
47517
49290
  },
49291
+ "pipelineRunner.startNodeBench": {
49292
+ capName: "pipeline-runner",
49293
+ capScope: "system",
49294
+ addonId: null,
49295
+ access: "create"
49296
+ },
47518
49297
  "plateGallery.assignPlate": {
47519
49298
  capName: "plate-gallery",
47520
49299
  capScope: "system",
@@ -52650,6 +54429,11 @@ Object.freeze({
52650
54429
  form: "single",
52651
54430
  optional: false
52652
54431
  }],
54432
+ "pipelineAnalytics.addRetrainFrameFromRecording": [{
54433
+ name: "deviceId",
54434
+ form: "single",
54435
+ optional: false
54436
+ }],
52653
54437
  "pipelineAnalytics.applyDeviceSettingsPatch": [{
52654
54438
  name: "deviceId",
52655
54439
  form: "single",
@@ -52840,6 +54624,11 @@ Object.freeze({
52840
54624
  form: "single",
52841
54625
  optional: false
52842
54626
  }],
54627
+ "pipelineAnalytics.proposeRetrainAnnotationsWithLlm": [{
54628
+ name: "deviceId",
54629
+ form: "single",
54630
+ optional: false
54631
+ }],
52843
54632
  "pipelineAnalytics.pruneEventsBefore": [{
52844
54633
  name: "deviceId",
52845
54634
  form: "single",