@camstack/addon-provider-homeassistant 1.2.163 → 1.2.164

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.
@@ -1,4 +1,4 @@
1
- //#region ../types/dist/event-category-B_0XEcLF.mjs
1
+ //#region ../types/dist/event-category-DaIZi00R.mjs
2
2
  var EventCategory = /* @__PURE__ */ function(EventCategory) {
3
3
  EventCategory["SystemBoot"] = "system.boot";
4
4
  EventCategory["SystemAddonsReady"] = "system.addons-ready";
@@ -77,6 +77,13 @@ var EventCategory = /* @__PURE__ */ function(EventCategory) {
77
77
  */
78
78
  EventCategory["AddonLoadFailed"] = "addon.load-failed";
79
79
  /**
80
+ * A keychain value was stored or removed (D787). Carries the ref, its
81
+ * owner and the new version — NEVER the value. A process holding the ref
82
+ * drops its cached copy and the owning `BaseAddon` re-resolves its config.
83
+ * Telemetry (D8): a process that misses it still revalidates by version.
84
+ */
85
+ EventCategory["KeychainChanged"] = "keychain.changed";
86
+ /**
80
87
  * Addon recovered from a previous failure. Emitted when an addon
81
88
  * transitions from `failed` back to `healthy` (typically via the
82
89
  * monitor's auto-retry loop, or after manual `addons.retryLoad`).
@@ -5369,7 +5376,7 @@ var ZodIssueCode = {
5369
5376
  var ZodFirstPartyTypeKind;
5370
5377
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
5371
5378
  //#endregion
5372
- //#region ../types/dist/sleep-B0JG7-_F.mjs
5379
+ //#region ../types/dist/sleep-Cr5YOk3m.mjs
5373
5380
  /**
5374
5381
  * The audio chunk plane's byte format, and the ONE expansion from a coded
5375
5382
  * window to float samples (D455).
@@ -5448,6 +5455,97 @@ function buildAlawTable() {
5448
5455
  }
5449
5456
  buildUlawTable();
5450
5457
  buildAlawTable();
5458
+ /** Is this field's stored value a credential? */
5459
+ function isSecretConfigField(field) {
5460
+ if (field.type === "password") return true;
5461
+ return "secret" in field && field.secret === true;
5462
+ }
5463
+ /**
5464
+ * Is this field's value stored in the KEYCHAIN (D787)? Every secret field is,
5465
+ * by its TYPE, unless it opts out with `storage: 'inline'` — never by its name.
5466
+ */
5467
+ function isKeychainStoredField(field) {
5468
+ if (!isSecretConfigField(field)) return false;
5469
+ if (field.type === "textarea" && field.isJson === true) return false;
5470
+ return !("storage" in field && field.storage === "inline");
5471
+ }
5472
+ /**
5473
+ * What a settings blob holds where a secret used to be.
5474
+ *
5475
+ * A keychain-stored field never holds its value. It holds a self-describing
5476
+ * MARKER, `{"$secret":"secret://…","v":1}` — an object, never a string, so no
5477
+ * code can mistake it for a credential and no form can send it to a camera as
5478
+ * a password. The empty state is `null` / absent, never `''`.
5479
+ *
5480
+ * The same shapes travel to and from the admin UI:
5481
+ *
5482
+ * - read: `hydrateSchema` hands a secret field a {@link SecretFieldView}
5483
+ * (`{ $secret, v, set: true }`) or `null` — the browser learns whether a
5484
+ * value is set, never the value.
5485
+ * - write: an untouched field submits the view back unchanged (KEEP); a typed
5486
+ * value is a plain non-empty string (CHANGE); the Clear button submits
5487
+ * {@link SECRET_CLEAR} (CLEAR). `''`, `null` and the legacy redaction tokens
5488
+ * are KEEP — an empty string is what a defaults-fallback pushes back, and
5489
+ * treating it as "clear" is how a save destroyed a stored credential before.
5490
+ *
5491
+ * Pure and browser-safe.
5492
+ */
5493
+ var SECRET_CLEAR = { $secretClear: true };
5494
+ /** The `'***'` token D634 redaction writes for non-admins. */
5495
+ var LEGACY_DEVICE_REDACTION = "***";
5496
+ function isRecord$1(value) {
5497
+ return typeof value === "object" && value !== null && !Array.isArray(value);
5498
+ }
5499
+ function makeSecretMarker(ref) {
5500
+ return {
5501
+ $secret: ref,
5502
+ v: 1
5503
+ };
5504
+ }
5505
+ /** A stored marker: an object whose `$secret` is a non-empty string. */
5506
+ function isSecretMarker(value) {
5507
+ if (!isRecord$1(value)) return false;
5508
+ const ref = value["$secret"];
5509
+ return typeof ref === "string" && ref.length > 0;
5510
+ }
5511
+ function isSecretClear(value) {
5512
+ return isRecord$1(value) && value["$secretClear"] === true;
5513
+ }
5514
+ /**
5515
+ * The UI view of a stored secret field value: a marker becomes "set", inline
5516
+ * plaintext becomes "set (inline)", nothing becomes `null`. A value never
5517
+ * survives this function.
5518
+ */
5519
+ function toSecretFieldView(stored) {
5520
+ if (isSecretMarker(stored)) return {
5521
+ $secret: stored.$secret,
5522
+ v: 1,
5523
+ set: true
5524
+ };
5525
+ if (typeof stored === "string" && stored.length > 0) return {
5526
+ $secret: null,
5527
+ v: 1,
5528
+ set: true,
5529
+ inline: true
5530
+ };
5531
+ return null;
5532
+ }
5533
+ /**
5534
+ * Classify an incoming value for a secret path. Only a non-empty string that is
5535
+ * not a redaction token sets a value; only {@link SECRET_CLEAR} clears.
5536
+ * Everything else — a marker (ours or anyone's), a UI view, `''`, `null`,
5537
+ * `undefined`, a redaction token, a non-string — keeps what is stored.
5538
+ */
5539
+ function classifySecretWrite(incoming) {
5540
+ if (isSecretClear(incoming)) return { kind: "clear" };
5541
+ if (typeof incoming !== "string") return { kind: "keep" };
5542
+ if (incoming.length === 0) return { kind: "keep" };
5543
+ if (incoming === "__camstack_redacted__" || incoming === LEGACY_DEVICE_REDACTION) return { kind: "keep" };
5544
+ return {
5545
+ kind: "set",
5546
+ value: incoming
5547
+ };
5548
+ }
5451
5549
  Object.fromEntries([
5452
5550
  {
5453
5551
  id: "overview",
@@ -5619,33 +5717,19 @@ Object.fromEntries([
5619
5717
  function isValuelessField(field) {
5620
5718
  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";
5621
5719
  }
5622
- /**
5623
- * Merge a `ConfigUISchema` with a raw `values` record into a
5624
- * `ConfigUISchemaWithValues`. Used by every `get*Settings` backend endpoint
5625
- * before returning to the admin UI. Groups are walked recursively.
5626
- *
5627
- * For each leaf field:
5628
- * - structural fields (`separator`, `info`, `button`) pass through unchanged
5629
- * - other fields get `value = values[key] ?? field.default ?? null`
5630
- *
5631
- * Unknown keys in `values` (keys not declared in the schema) are silently
5632
- * ignored — they don't contribute to the output. Missing keys fall back to
5633
- * the schema default or `null`. This mirrors the old backend behaviour where
5634
- * `FormBuilder` rendered `values[key] ?? field.default`.
5635
- */
5636
- function hydrateSchema(schema, values) {
5720
+ function hydrateSchema(schema, values, options = {}) {
5637
5721
  return {
5638
5722
  ...schema.tabs ? { tabs: [...schema.tabs] } : {},
5639
5723
  sections: schema.sections.map((section) => ({
5640
5724
  ...section,
5641
- fields: section.fields.map((field) => hydrateField(field, values))
5725
+ fields: section.fields.map((field) => hydrateField(field, values, options))
5642
5726
  }))
5643
5727
  };
5644
5728
  }
5645
- function hydrateField(field, values) {
5729
+ function hydrateField(field, values, options) {
5646
5730
  if (isValuelessField(field)) return field;
5647
5731
  if (field.type === "group") {
5648
- const hydratedChildren = field.fields.map((child) => hydrateField(child, values));
5732
+ const hydratedChildren = field.fields.map((child) => hydrateField(child, values, options));
5649
5733
  return {
5650
5734
  ...field,
5651
5735
  fields: hydratedChildren
@@ -5654,7 +5738,7 @@ function hydrateField(field, values) {
5654
5738
  if (field.type === "sub-tabs") {
5655
5739
  const hydratedTabs = field.tabs.map((tab) => ({
5656
5740
  ...tab,
5657
- fields: tab.fields.map((child) => hydrateField(child, values))
5741
+ fields: tab.fields.map((child) => hydrateField(child, values, options))
5658
5742
  }));
5659
5743
  return {
5660
5744
  ...field,
@@ -5664,6 +5748,33 @@ function hydrateField(field, values) {
5664
5748
  const key = field.key;
5665
5749
  const storedValue = Object.prototype.hasOwnProperty.call(values, key) ? values[key] : void 0;
5666
5750
  const defaultValue = field.default;
5751
+ const asView = (v) => isSecretMarker(v) || options.inlineSecretsAsViews === true && v !== void 0;
5752
+ if (isKeychainStoredField(field) && asView(storedValue)) return {
5753
+ ...field,
5754
+ value: toSecretFieldView(storedValue)
5755
+ };
5756
+ if (isKeychainStoredField(field) && options.inlineSecretsAsViews === true) return {
5757
+ ...field,
5758
+ value: null
5759
+ };
5760
+ if (field.type === "editable-array" && Array.isArray(storedValue)) {
5761
+ const secretItemKeys = field.itemFields.filter((item) => "key" in item && isKeychainStoredField(item)).map((item) => "key" in item ? item.key : "");
5762
+ if (secretItemKeys.length > 0) {
5763
+ const rows = storedValue.map((row) => {
5764
+ if (row === null || typeof row !== "object" || Array.isArray(row)) return row;
5765
+ const out = { ...row };
5766
+ for (const k of secretItemKeys) {
5767
+ const v = Reflect.get(row, k);
5768
+ if (asView(v)) out[k] = toSecretFieldView(v);
5769
+ }
5770
+ return out;
5771
+ });
5772
+ return {
5773
+ ...field,
5774
+ value: rows
5775
+ };
5776
+ }
5777
+ }
5667
5778
  if (field.multiple) {
5668
5779
  const stored = Array.isArray(storedValue) ? storedValue : storedValue !== void 0 && storedValue !== null ? [storedValue] : [];
5669
5780
  const itemFallback = field.multiple.itemDefault !== void 0 ? field.multiple.itemDefault : defaultValue !== void 0 ? defaultValue : typeOf(field) === "string" ? "" : null;
@@ -5906,6 +6017,431 @@ function projectStore(store, perNodeKeys, nodeId) {
5906
6017
  }
5907
6018
  return out;
5908
6019
  }
6020
+ var GLOBAL_SCOPE = { kind: "global" };
6021
+ /** The scope every addon-wide (not per-node, not per-device) setting lives in. */
6022
+ function globalSecretScope() {
6023
+ return GLOBAL_SCOPE;
6024
+ }
6025
+ function encodeSegment(value) {
6026
+ return encodeURIComponent(value);
6027
+ }
6028
+ /**
6029
+ * The field path of a value inside an array item, addressed by the item's id:
6030
+ * `arrayItemFieldPath('providers', 'authentik', 'clientSecret')` →
6031
+ * `providers[authentik].clientSecret`.
6032
+ */
6033
+ function arrayItemFieldPath(arrayKey, itemId, fieldKey) {
6034
+ return `${arrayKey}[${encodeSegment(itemId)}].${fieldKey}`;
6035
+ }
6036
+ /** A write to a secret path could not be stored in the keychain, so it was refused. */
6037
+ var KeychainWriteRefusedError = class extends Error {
6038
+ fieldPath;
6039
+ constructor(fieldPath, cause) {
6040
+ super(`secret "${fieldPath}" was not saved: the keychain could not store it (${cause instanceof Error ? cause.message : String(cause)}). Nothing was written.`);
6041
+ this.fieldPath = fieldPath;
6042
+ this.name = "KeychainWriteRefusedError";
6043
+ }
6044
+ };
6045
+ var KEEP = { kind: "keep" };
6046
+ function isRecord(value) {
6047
+ return typeof value === "object" && value !== null && !Array.isArray(value);
6048
+ }
6049
+ function defaultMintId() {
6050
+ return globalThis.crypto.randomUUID();
6051
+ }
6052
+ /** Every marker ref anywhere under `value`. */
6053
+ function collectSecretMarkerRefs(value, out = []) {
6054
+ if (isSecretMarker(value)) {
6055
+ out.push(value.$secret);
6056
+ return out;
6057
+ }
6058
+ if (Array.isArray(value)) for (const item of value) collectSecretMarkerRefs(item, out);
6059
+ else if (isRecord(value)) for (const child of Object.values(value)) collectSecretMarkerRefs(child, out);
6060
+ return out;
6061
+ }
6062
+ async function storedValueEquals(secrets, marker, candidate) {
6063
+ const resolved = (await secrets.resolve([marker.$secret]))[marker.$secret];
6064
+ return resolved?.kind === "value" && resolved.value === candidate;
6065
+ }
6066
+ async function writeLeaf(ctx, incoming, stored, fieldPath) {
6067
+ const intent = classifySecretWrite(incoming);
6068
+ const ref = ctx.secrets.ref(ctx.scope, fieldPath);
6069
+ const storedIsOurs = isSecretMarker(stored) && stored.$secret === ref;
6070
+ if (intent.kind === "keep") return KEEP;
6071
+ if (intent.kind === "set" && !ctx.operatorWrite && typeof stored === "string" && stored === intent.value) return KEEP;
6072
+ if (intent.kind === "clear") {
6073
+ if (storedIsOurs) ctx.deletes.push(ref);
6074
+ return {
6075
+ kind: "value",
6076
+ value: null
6077
+ };
6078
+ }
6079
+ if (storedIsOurs && await storedValueEquals(ctx.secrets, stored, intent.value)) return {
6080
+ kind: "value",
6081
+ value: stored
6082
+ };
6083
+ try {
6084
+ await ctx.secrets.put(ref, intent.value);
6085
+ } catch (err) {
6086
+ throw new KeychainWriteRefusedError(fieldPath, err);
6087
+ }
6088
+ return {
6089
+ kind: "value",
6090
+ value: makeSecretMarker(ref)
6091
+ };
6092
+ }
6093
+ /** Apply a member result onto `out`: KEEP restores the stored member, or removes it. */
6094
+ function applyMember(out, key, result, storedParent) {
6095
+ if (result.kind === "value") {
6096
+ out[key] = result.value;
6097
+ return;
6098
+ }
6099
+ if (Object.prototype.hasOwnProperty.call(storedParent, key)) out[key] = storedParent[key];
6100
+ else delete out[key];
6101
+ }
6102
+ async function writeMembers(ctx, children, incoming, stored, pathOf) {
6103
+ const out = { ...incoming };
6104
+ for (const [member, node] of children) applyMember(out, member, await writeNode(ctx, node, incoming[member], stored[member], pathOf(member)), stored);
6105
+ return out;
6106
+ }
6107
+ function rowId(row, idKey) {
6108
+ const raw = row[idKey];
6109
+ if (typeof raw === "string" && raw.length > 0) return raw;
6110
+ if (typeof raw === "number" && Number.isFinite(raw)) return String(raw);
6111
+ return null;
6112
+ }
6113
+ async function writeArray(ctx, node, incoming, stored, fieldPath) {
6114
+ const storedRows = Array.isArray(stored) ? stored.filter(isRecord) : [];
6115
+ if (!Array.isArray(incoming)) {
6116
+ ctx.deletes.push(...collectSecretMarkerRefs(storedRows));
6117
+ return {
6118
+ kind: "value",
6119
+ value: incoming
6120
+ };
6121
+ }
6122
+ const storedById = /* @__PURE__ */ new Map();
6123
+ for (const row of storedRows) {
6124
+ const id = rowId(row, node.idKey);
6125
+ if (id !== null) storedById.set(id, row);
6126
+ }
6127
+ const kept = /* @__PURE__ */ new Set();
6128
+ const rows = [];
6129
+ for (const row of incoming) {
6130
+ if (!isRecord(row)) {
6131
+ rows.push(row);
6132
+ continue;
6133
+ }
6134
+ const id = rowId(row, node.idKey) ?? ctx.mintId();
6135
+ kept.add(id);
6136
+ const withId = {
6137
+ ...row,
6138
+ [node.idKey]: row[node.idKey] ?? id
6139
+ };
6140
+ if (rowId(withId, node.idKey) === null) withId[node.idKey] = id;
6141
+ const storedRow = storedById.get(id) ?? {};
6142
+ rows.push(await writeMembers(ctx, node.item, withId, storedRow, (member) => arrayItemFieldPath(fieldPath, id, member)));
6143
+ }
6144
+ for (const [id, row] of storedById) if (!kept.has(id)) ctx.deletes.push(...collectSecretMarkerRefs(row));
6145
+ return {
6146
+ kind: "value",
6147
+ value: rows
6148
+ };
6149
+ }
6150
+ async function writeNode(ctx, node, incoming, stored, fieldPath) {
6151
+ switch (node.kind) {
6152
+ case "leaf": return writeLeaf(ctx, incoming, stored, fieldPath);
6153
+ case "array": return writeArray(ctx, node, incoming, stored, fieldPath);
6154
+ case "object": {
6155
+ if (!isRecord(incoming)) {
6156
+ if (incoming === void 0) return KEEP;
6157
+ ctx.deletes.push(...collectSecretMarkerRefs(stored));
6158
+ return {
6159
+ kind: "value",
6160
+ value: incoming
6161
+ };
6162
+ }
6163
+ const storedObj = isRecord(stored) ? stored : {};
6164
+ return {
6165
+ kind: "value",
6166
+ value: await writeMembers(ctx, node.children, incoming, storedObj, (m) => `${fieldPath}.${m}`)
6167
+ };
6168
+ }
6169
+ }
6170
+ }
6171
+ /** Split a perNode-scoped key (`key@nodeId`). */
6172
+ function splitNodeKey(key) {
6173
+ const at = key.indexOf("@");
6174
+ return at <= 0 ? {
6175
+ base: key,
6176
+ nodeId: null
6177
+ } : {
6178
+ base: key.slice(0, at),
6179
+ nodeId: key.slice(at + 1)
6180
+ };
6181
+ }
6182
+ /** Rewrite a settings patch so no secret value reaches the blob. See the file doc. */
6183
+ async function transformSecretWrite(input) {
6184
+ const deletes = [];
6185
+ const base = {
6186
+ secrets: input.secrets,
6187
+ mintId: input.mintId ?? defaultMintId,
6188
+ deletes,
6189
+ operatorWrite: input.operatorWrite === true
6190
+ };
6191
+ const out = {};
6192
+ for (const [key, incoming] of Object.entries(input.patch)) {
6193
+ const { base: baseKey, nodeId } = splitNodeKey(key);
6194
+ const node = input.tree.get(baseKey);
6195
+ if (node === void 0) {
6196
+ out[key] = incoming;
6197
+ continue;
6198
+ }
6199
+ const scope = nodeId !== null && nodeId.length > 0 ? {
6200
+ kind: "node",
6201
+ nodeId
6202
+ } : input.scope ?? globalSecretScope();
6203
+ const result = await writeNode({
6204
+ ...base,
6205
+ scope
6206
+ }, node, incoming, input.stored[key], baseKey);
6207
+ if (result.kind === "value") out[key] = result.value;
6208
+ }
6209
+ return {
6210
+ patch: out,
6211
+ afterWrite: async () => {
6212
+ if (deletes.length === 0) return { orphaned: [] };
6213
+ try {
6214
+ await input.secrets.delete([...new Set(deletes)]);
6215
+ return { orphaned: [] };
6216
+ } catch {
6217
+ return { orphaned: [...new Set(deletes)] };
6218
+ }
6219
+ }
6220
+ };
6221
+ }
6222
+ /**
6223
+ * Replace every marker in `value` with its keychain value. Returns the SAME
6224
+ * reference when there is no marker (no allocation, no keychain call).
6225
+ */
6226
+ async function resolveSecretMarkers(value, secrets) {
6227
+ const refs = collectSecretMarkerRefs(value);
6228
+ if (refs.length === 0) return {
6229
+ value,
6230
+ unresolved: []
6231
+ };
6232
+ const answers = await secrets.resolve(refs);
6233
+ const unresolved = [];
6234
+ for (const ref of new Set(refs)) {
6235
+ const answer = answers[ref];
6236
+ if (answer === void 0) unresolved.push({
6237
+ ref,
6238
+ reason: "not-initialized"
6239
+ });
6240
+ else if (answer.kind === "unavailable") unresolved.push({
6241
+ ref,
6242
+ reason: answer.reason
6243
+ });
6244
+ else if (answer.kind === "missing" || answer.kind === "forbidden") unresolved.push({
6245
+ ref,
6246
+ reason: answer.kind
6247
+ });
6248
+ }
6249
+ const substitute = (v) => {
6250
+ if (isSecretMarker(v)) {
6251
+ const answer = answers[v.$secret];
6252
+ return answer?.kind === "value" ? {
6253
+ keep: true,
6254
+ value: answer.value
6255
+ } : {
6256
+ keep: false,
6257
+ value: void 0
6258
+ };
6259
+ }
6260
+ if (Array.isArray(v)) {
6261
+ const items = [];
6262
+ for (const item of v) {
6263
+ const s = substitute(item);
6264
+ if (s.keep) items.push(s.value);
6265
+ }
6266
+ return {
6267
+ keep: true,
6268
+ value: items
6269
+ };
6270
+ }
6271
+ if (isRecord(v)) {
6272
+ const out = {};
6273
+ for (const [k, child] of Object.entries(v)) {
6274
+ const s = substitute(child);
6275
+ if (s.keep) out[k] = s.value;
6276
+ }
6277
+ return {
6278
+ keep: true,
6279
+ value: out
6280
+ };
6281
+ }
6282
+ return {
6283
+ keep: true,
6284
+ value: v
6285
+ };
6286
+ };
6287
+ return {
6288
+ value: substitute(value).value,
6289
+ unresolved
6290
+ };
6291
+ }
6292
+ function touchesTree(tree, patch) {
6293
+ if (tree.size === 0) return false;
6294
+ for (const key of Object.keys(patch)) {
6295
+ const at = key.indexOf("@");
6296
+ if (tree.has(at > 0 ? key.slice(0, at) : key)) return true;
6297
+ }
6298
+ return false;
6299
+ }
6300
+ /** The blob as stored now; a failed read REFUSES the write instead of guessing. */
6301
+ async function readStoredAddonBlob(raw) {
6302
+ const threeWay = raw.readAddonStoreResult;
6303
+ if (threeWay === void 0) return raw.readAddonStore();
6304
+ const result = await threeWay.call(raw);
6305
+ if (result.kind === "failed") throw new Error(`settings write refused: the stored blob could not be read (${result.error})`);
6306
+ return result.kind === "missing" ? {} : result.value;
6307
+ }
6308
+ function createSecretAwareSettings(raw, opts) {
6309
+ const chains = /* @__PURE__ */ new Map();
6310
+ const serialize = (key, fn) => {
6311
+ const next = (chains.get(key) ?? Promise.resolve()).then(fn, fn);
6312
+ const tail = next.catch(() => void 0);
6313
+ chains.set(key, tail);
6314
+ tail.then(() => {
6315
+ if (chains.get(key) === tail) chains.delete(key);
6316
+ });
6317
+ return next;
6318
+ };
6319
+ const write = async (chainKey, tree, scope, patch, readStored, rawWrite) => {
6320
+ if (!touchesTree(tree, patch)) return rawWrite(patch);
6321
+ return serialize(chainKey, async () => {
6322
+ const stored = await readStored();
6323
+ const result = await transformSecretWrite({
6324
+ tree,
6325
+ secrets: opts.secrets,
6326
+ patch,
6327
+ stored,
6328
+ ...scope !== void 0 ? { scope } : {},
6329
+ operatorWrite: opts.isOperatorWrite?.() === true
6330
+ });
6331
+ if (Object.keys(result.patch).length > 0) await rawWrite(result.patch);
6332
+ const { orphaned } = await result.afterWrite();
6333
+ if (orphaned.length > 0) opts.onOrphaned(orphaned);
6334
+ });
6335
+ };
6336
+ const wrapped = {
6337
+ writeAddonStore: (patch) => write("addon", opts.addonTree(), void 0, patch, () => readStoredAddonBlob(raw), (p) => raw.writeAddonStore(p)),
6338
+ writeDeviceStore: (deviceId, patch) => write(`device:${deviceId}`, opts.deviceTree(), {
6339
+ kind: "device",
6340
+ deviceId
6341
+ }, patch, () => raw.readDeviceStore(deviceId), (p) => raw.writeDeviceStore(deviceId, p))
6342
+ };
6343
+ return new Proxy(raw, { get(target, prop, receiver) {
6344
+ if (prop === "writeAddonStore") return wrapped.writeAddonStore;
6345
+ if (prop === "writeDeviceStore") return wrapped.writeDeviceStore;
6346
+ const value = Reflect.get(target, prop, receiver);
6347
+ return typeof value === "function" ? value.bind(target) : value;
6348
+ } });
6349
+ }
6350
+ /** The context the addon sees: identical, except that its settings writes are secret-aware. */
6351
+ function withSecretAwareSettings(context, opts) {
6352
+ const raw = context.settings;
6353
+ if (raw === void 0) return context;
6354
+ const settings = createSecretAwareSettings(raw, opts);
6355
+ return new Proxy(context, { get(target, prop, receiver) {
6356
+ if (prop === "settings") return settings;
6357
+ return Reflect.get(target, prop, receiver);
6358
+ } });
6359
+ }
6360
+ var LEAF = { kind: "leaf" };
6361
+ var DEFAULT_ITEM_ID_KEY = "id";
6362
+ function collectFields(fields, out) {
6363
+ for (const field of fields) {
6364
+ if (field.type === "group") {
6365
+ collectFields(field.fields, out);
6366
+ continue;
6367
+ }
6368
+ if (field.type === "sub-tabs") {
6369
+ for (const tab of field.tabs) collectFields(tab.fields, out);
6370
+ continue;
6371
+ }
6372
+ if (field.type === "editable-array") {
6373
+ const item = /* @__PURE__ */ new Map();
6374
+ for (const itemField of field.itemFields) if ("key" in itemField && isKeychainStoredField(itemField)) item.set(itemField.key, LEAF);
6375
+ if (item.size > 0) out.set(field.key, {
6376
+ kind: "array",
6377
+ idKey: field.itemIdKey ?? DEFAULT_ITEM_ID_KEY,
6378
+ item
6379
+ });
6380
+ continue;
6381
+ }
6382
+ if (!("key" in field) || typeof field.key !== "string") continue;
6383
+ if (isKeychainStoredField(field)) out.set(field.key, LEAF);
6384
+ }
6385
+ }
6386
+ /** The secret tree a settings schema declares. */
6387
+ function secretTreeFromSchema(schema) {
6388
+ const out = /* @__PURE__ */ new Map();
6389
+ if (schema === null) return out;
6390
+ for (const section of schema.sections) collectFields(section.fields, out);
6391
+ return out;
6392
+ }
6393
+ /** Parse `a.b[id].c` into segments; throws on a malformed path (a declaration bug). */
6394
+ function parseSecretStatePath(path) {
6395
+ const segments = [];
6396
+ for (const raw of path.split(".")) {
6397
+ const m = /^([^[\]]+)(?:\[([^[\]]+)\])?$/.exec(raw);
6398
+ if (m === null || m[1] === void 0) throw new Error(`secretStatePaths: malformed path "${path}"`);
6399
+ segments.push(m[2] !== void 0 ? {
6400
+ key: m[1],
6401
+ idKey: m[2]
6402
+ } : { key: m[1] });
6403
+ }
6404
+ if (segments.length === 0) throw new Error(`secretStatePaths: empty path`);
6405
+ if (segments[segments.length - 1]?.idKey !== void 0) throw new Error(`secretStatePaths: "${path}" ends on an array — name the member that is secret`);
6406
+ return segments;
6407
+ }
6408
+ function insert(into, segments) {
6409
+ const [head, ...rest] = segments;
6410
+ if (head === void 0) return;
6411
+ if (rest.length === 0) {
6412
+ into.set(head.key, LEAF);
6413
+ return;
6414
+ }
6415
+ const existing = into.get(head.key);
6416
+ if (head.idKey !== void 0) {
6417
+ const item = new Map(existing?.kind === "array" ? existing.item : []);
6418
+ insert(item, rest);
6419
+ into.set(head.key, {
6420
+ kind: "array",
6421
+ idKey: head.idKey,
6422
+ item
6423
+ });
6424
+ return;
6425
+ }
6426
+ const children = new Map(existing?.kind === "object" ? existing.children : []);
6427
+ insert(children, rest);
6428
+ into.set(head.key, {
6429
+ kind: "object",
6430
+ children
6431
+ });
6432
+ }
6433
+ /** Add hidden-state paths (`secretStatePaths`) to a schema-derived tree. */
6434
+ function mergeSecretStatePaths(tree, paths) {
6435
+ if (paths.length === 0) return tree;
6436
+ const out = new Map(tree);
6437
+ for (const path of paths) insert(out, parseSecretStatePath(path));
6438
+ return out;
6439
+ }
6440
+ /** First retry of a secret the keychain could not serve; doubles to {@link SECRET_RETRY_MAX_MS}. */
6441
+ var SECRET_RETRY_FIRST_MS = 5e3;
6442
+ var SECRET_RETRY_MAX_MS = 5 * 6e4;
6443
+ /** Coalesces a burst of `keychain.changed` events into one re-resolve. */
6444
+ var SECRET_CHANGE_DEBOUNCE_MS = 250;
5909
6445
  /**
5910
6446
  * Base class for CamStack addons. Eliminates settings boilerplate:
5911
6447
  *
@@ -5975,6 +6511,25 @@ var BaseAddon = class {
5975
6511
  settingsStoreReady = false;
5976
6512
  /** Default config values. Provided via constructor. */
5977
6513
  defaults;
6514
+ /**
6515
+ * Hidden-state paths that hold secrets (D787) — values the addon writes
6516
+ * itself (`updateGlobalSettings`, `state()`) that no form field declares.
6517
+ * Stored in the keychain exactly like a `password` field. Syntax:
6518
+ * `'snapshotSigningKey'`, `'identity.pincode'`, `'tokens[userId].accessToken'`
6519
+ * (`key[<id field>]` addresses array items by id, never by index).
6520
+ */
6521
+ secretStatePaths = [];
6522
+ _addonSecretTree = null;
6523
+ _deviceSecretTree = null;
6524
+ /** Refs the last resolved config pointed at — a change to one re-resolves. */
6525
+ _configSecretRefs = /* @__PURE__ */ new Set();
6526
+ _unresolvedSecrets = [];
6527
+ _secretRetryTimer = null;
6528
+ _secretRetryDelayMs = SECRET_RETRY_FIRST_MS;
6529
+ _secretChangeTimer = null;
6530
+ _secretChangeUnsub = null;
6531
+ /** >0 while an OPERATOR's settings write is being applied. */
6532
+ _operatorWriteDepth = 0;
5978
6533
  constructor(defaults) {
5979
6534
  this.defaults = defaults;
5980
6535
  this._config = { ...defaults };
@@ -6010,8 +6565,18 @@ var BaseAddon = class {
6010
6565
  return this._config;
6011
6566
  }
6012
6567
  async initialize(context) {
6013
- this._ctx = context;
6568
+ const secrets = context.secrets;
6569
+ this._ctx = secrets !== void 0 ? withSecretAwareSettings(context, {
6570
+ secrets,
6571
+ addonTree: () => this.addonSecretTree(),
6572
+ deviceTree: () => this.deviceSecretTree(),
6573
+ onOrphaned: (refs) => context.logger.warn("keychain refs dropped by a settings write could not be deleted", { meta: { refs: [...refs] } }),
6574
+ isOperatorWrite: () => this._operatorWriteDepth > 0
6575
+ }) : context;
6014
6576
  await this.resolveConfig();
6577
+ if (secrets !== void 0) this._secretChangeUnsub = secrets.onChange((ref) => {
6578
+ if (this._configSecretRefs.has(ref)) this.scheduleSecretReresolve(SECRET_CHANGE_DEBOUNCE_MS);
6579
+ });
6015
6580
  const result = await this.onInitialize();
6016
6581
  this.emitLifecycle(EventCategory.AddonStarted);
6017
6582
  const normalized = normalizeAddonInitResult(result);
@@ -6044,6 +6609,12 @@ var BaseAddon = class {
6044
6609
  */
6045
6610
  async onHubReachable() {}
6046
6611
  async shutdown() {
6612
+ this._secretChangeUnsub?.();
6613
+ this._secretChangeUnsub = null;
6614
+ if (this._secretRetryTimer !== null) clearTimeout(this._secretRetryTimer);
6615
+ if (this._secretChangeTimer !== null) clearTimeout(this._secretChangeTimer);
6616
+ this._secretRetryTimer = null;
6617
+ this._secretChangeTimer = null;
6047
6618
  this.emitLifecycle(EventCategory.AddonStopped);
6048
6619
  if (this.autoEmitReadiness) this.emitReadinessForProviders("down");
6049
6620
  await this.onShutdown();
@@ -6122,7 +6693,7 @@ var BaseAddon = class {
6122
6693
  return hydrateSchema(schema, overlay ? {
6123
6694
  ...projected,
6124
6695
  ...overlay
6125
- } : projected);
6696
+ } : projected, { inlineSecretsAsViews: true });
6126
6697
  }
6127
6698
  /**
6128
6699
  * The integration-level view of this addon's settings: exactly the sections
@@ -6171,7 +6742,7 @@ var BaseAddon = class {
6171
6742
  return hydrateSchema({
6172
6743
  ...schema,
6173
6744
  sections
6174
- }, projected);
6745
+ }, projected, { inlineSecretsAsViews: true });
6175
6746
  }
6176
6747
  /**
6177
6748
  * The raw addon store PROJECTED onto the target node's bare per-node keys:
@@ -6225,18 +6796,50 @@ var BaseAddon = class {
6225
6796
  value: result.value[key]
6226
6797
  };
6227
6798
  }
6799
+ /**
6800
+ * The OPERATOR's write — a settings form or an admin API call, dispatched by
6801
+ * the kernel. Identical to {@link updateGlobalSettings}, except that a secret
6802
+ * the operator sends is stored as sent even when it equals a pre-keychain
6803
+ * inline value: the operator re-entering a password is a change, an addon
6804
+ * writing back what it read is not (D787).
6805
+ */
6806
+ async updateGlobalSettingsAsOperator(patch, nodeId) {
6807
+ this._operatorWriteDepth++;
6808
+ try {
6809
+ await this.applyGlobalPatch(patch, nodeId);
6810
+ } finally {
6811
+ this._operatorWriteDepth--;
6812
+ }
6813
+ }
6228
6814
  async updateGlobalSettings(patch, nodeId) {
6815
+ await this.applyGlobalPatch(patch, nodeId);
6816
+ }
6817
+ /**
6818
+ * REMOVE stored secrets — their keychain values and their markers (D787).
6819
+ *
6820
+ * Writing `''` to a secret field KEEPS what is stored (an empty string is
6821
+ * what a defaults fallback writes back, and it must never destroy a
6822
+ * credential), so code that means "forget this token" says so here. Without
6823
+ * a keychain (an older kernel) it writes `''`, as such code always did.
6824
+ */
6825
+ async clearSecrets(keys, nodeId) {
6826
+ const tree = this.addonSecretTree();
6827
+ const keychain = this._ctx?.secrets !== void 0;
6828
+ const patch = {};
6829
+ for (const key of keys) patch[key] = keychain && tree.has(key) ? SECRET_CLEAR : "";
6830
+ await this.applyGlobalPatch(patch, nodeId);
6831
+ }
6832
+ async applyGlobalPatch(barePatch, nodeId) {
6229
6833
  const keys = this.perNodeKeys();
6230
6834
  const localNode = normalizeNodeId(this._ctx?.kernel?.localNodeId);
6231
6835
  const target = normalizeNodeId(nodeId ?? this._ctx?.kernel?.localNodeId);
6232
- const barePatch = patch;
6233
6836
  const scoped = keys.size > 0 ? scopePatch(barePatch, keys, target) : barePatch;
6234
6837
  await this._ctx?.settings?.writeAddonStore(scoped);
6235
6838
  if (target !== localNode) return;
6236
6839
  await this.resolveConfig();
6237
6840
  await this.onConfigChanged();
6238
6841
  this.emitLifecycle(EventCategory.AddonUpdated, { level: "global" });
6239
- this.maybeAutoRestart(patch, this.globalSettingsSchema());
6842
+ this.maybeAutoRestart(Object.keys(barePatch), this.globalSettingsSchema());
6240
6843
  }
6241
6844
  /**
6242
6845
  * The set of field keys the global settings schema declares `perNode: true`
@@ -6261,7 +6864,7 @@ var BaseAddon = class {
6261
6864
  * time to return its response before the addon is torn down and
6262
6865
  * re-initialised by `AddonRegistryService.restartAddon`.
6263
6866
  */
6264
- maybeAutoRestart(patch, schema) {
6867
+ maybeAutoRestart(patchKeys, schema) {
6265
6868
  if (!schema) return;
6266
6869
  const restartKeys = /* @__PURE__ */ new Set();
6267
6870
  for (const section of schema.sections) for (const field of section.fields) {
@@ -6269,13 +6872,13 @@ var BaseAddon = class {
6269
6872
  if (field.requiresRestart) restartKeys.add(field.key);
6270
6873
  }
6271
6874
  if (restartKeys.size === 0) return;
6272
- if (!Object.keys(patch).some((k) => restartKeys.has(k))) return;
6875
+ if (!patchKeys.some((k) => restartKeys.has(k))) return;
6273
6876
  const ctx = this._ctx;
6274
6877
  if (!ctx) return;
6275
6878
  const addonId = ctx.id;
6276
6879
  setImmediate(() => {
6277
6880
  ctx.api.addons?.restartAddon?.mutate({ addonId }).then(() => {
6278
- ctx.logger.info("addon auto-restart triggered by restart-required setting change", { meta: { changedFields: Object.keys(patch).filter((k) => restartKeys.has(k)) } });
6881
+ ctx.logger.info("addon auto-restart triggered by restart-required setting change", { meta: { changedFields: patchKeys.filter((k) => restartKeys.has(k)) } });
6279
6882
  }).catch((err) => {
6280
6883
  ctx.logger.error("addon auto-restart failed", { meta: { error: err instanceof Error ? err.message : String(err) } });
6281
6884
  });
@@ -6284,7 +6887,7 @@ var BaseAddon = class {
6284
6887
  async getDeviceSettings(deviceId) {
6285
6888
  const schema = this.deviceSettingsSchema();
6286
6889
  if (!schema) return { sections: [] };
6287
- return hydrateSchema(schema, await this._ctx?.settings?.readDeviceStore(deviceId) ?? {});
6890
+ return hydrateSchema(schema, await this._ctx?.settings?.readDeviceStore(deviceId) ?? {}, { inlineSecretsAsViews: true });
6288
6891
  }
6289
6892
  async updateDeviceSettings(deviceId, patch) {
6290
6893
  await this._ctx?.settings?.writeDeviceStore(deviceId, patch);
@@ -6414,7 +7017,7 @@ var BaseAddon = class {
6414
7017
  * selection at boot (absent scoped key ⇒ the constructor default wins).
6415
7018
  */
6416
7019
  async resolveConfig() {
6417
- const stored = await this.readAddonStoreWithRetry();
7020
+ const stored = await this.resolveStoredSecrets(await this.readAddonStoreWithRetry());
6418
7021
  const perNode = this.perNodeKeys();
6419
7022
  const localNode = normalizeNodeId(this._ctx?.kernel?.localNodeId);
6420
7023
  const resolved = { ...this.defaults };
@@ -6439,7 +7042,7 @@ var BaseAddon = class {
6439
7042
  key,
6440
7043
  schema,
6441
7044
  fallback,
6442
- read: () => this.readAddonStoreWithRetry(),
7045
+ read: async () => this.resolveStoredSecrets(await this.readAddonStoreWithRetry()),
6443
7046
  write: async (patch) => {
6444
7047
  await this._ctx?.settings?.writeAddonStore(patch);
6445
7048
  },
@@ -6456,7 +7059,7 @@ var BaseAddon = class {
6456
7059
  key,
6457
7060
  schema,
6458
7061
  fallback,
6459
- read: async () => await this._ctx?.settings?.readDeviceStore(deviceId) ?? {},
7062
+ read: async () => this.resolveStoredSecrets(await this._ctx?.settings?.readDeviceStore(deviceId) ?? {}, false),
6460
7063
  write: async (patch) => {
6461
7064
  await this._ctx?.settings?.writeDeviceStore(deviceId, patch);
6462
7065
  },
@@ -6468,6 +7071,70 @@ var BaseAddon = class {
6468
7071
  } })
6469
7072
  });
6470
7073
  }
7074
+ /** The addon store's secret tree: schema fields by TYPE, plus `secretStatePaths`. */
7075
+ addonSecretTree() {
7076
+ this._addonSecretTree ??= mergeSecretStatePaths(secretTreeFromSchema(this.globalSettingsSchema()), this.secretStatePaths);
7077
+ return this._addonSecretTree;
7078
+ }
7079
+ deviceSecretTree() {
7080
+ this._deviceSecretTree ??= secretTreeFromSchema(this.deviceSettingsSchema());
7081
+ return this._deviceSecretTree;
7082
+ }
7083
+ /**
7084
+ * Secrets of this addon's stored config that could not be resolved on the
7085
+ * last read, with why. Non-empty means the addon is running WITHOUT them —
7086
+ * an addon whose function needs one should report itself degraded rather
7087
+ * than start on an empty credential.
7088
+ */
7089
+ get unresolvedSecrets() {
7090
+ return this._unresolvedSecrets;
7091
+ }
7092
+ /**
7093
+ * Substitute every keychain marker in a stored blob with its value. With no
7094
+ * keychain (no `ctx.secrets`) or no marker, the blob comes back unchanged.
7095
+ * An unresolvable value is LEFT OUT (never `''`), logged by ref — never by
7096
+ * value — and, when the cause can pass, retried with backoff. Nothing is
7097
+ * ever written back from here.
7098
+ */
7099
+ async resolveStoredSecrets(blob, trackForConfig = true) {
7100
+ const secrets = this._ctx?.secrets;
7101
+ if (secrets === void 0) return blob;
7102
+ const refs = collectSecretMarkerRefs(blob);
7103
+ if (trackForConfig) this._configSecretRefs = new Set(refs);
7104
+ if (refs.length === 0) {
7105
+ if (trackForConfig) this._unresolvedSecrets = [];
7106
+ return blob;
7107
+ }
7108
+ const { value, unresolved } = await resolveSecretMarkers(blob, secrets);
7109
+ if (trackForConfig) {
7110
+ this._unresolvedSecrets = unresolved;
7111
+ if (unresolved.length > 0) {
7112
+ this._ctx?.logger?.error?.("secret unavailable — running without it, will retry", { meta: { secrets: unresolved.map((u) => ({
7113
+ ref: u.ref,
7114
+ reason: u.reason
7115
+ })) } });
7116
+ if (unresolved.some((u) => u.reason !== "missing" && u.reason !== "forbidden")) {
7117
+ this.scheduleSecretReresolve(this._secretRetryDelayMs);
7118
+ this._secretRetryDelayMs = Math.min(this._secretRetryDelayMs * 2, SECRET_RETRY_MAX_MS);
7119
+ }
7120
+ } else this._secretRetryDelayMs = SECRET_RETRY_FIRST_MS;
7121
+ }
7122
+ return value;
7123
+ }
7124
+ /** Re-resolve the config (a keychain-only change, or a retry) and apply it. */
7125
+ scheduleSecretReresolve(delayMs) {
7126
+ const timerOf = delayMs === SECRET_CHANGE_DEBOUNCE_MS ? "_secretChangeTimer" : "_secretRetryTimer";
7127
+ if (this[timerOf] !== null) return;
7128
+ const timer = setTimeout(() => {
7129
+ this[timerOf] = null;
7130
+ if (this._ctx === null) return;
7131
+ this.resolveConfig().then(() => this.onConfigChanged()).catch((err) => {
7132
+ this._ctx?.logger?.error?.("re-resolving secrets failed", { meta: { error: err instanceof Error ? err.message : String(err) } });
7133
+ });
7134
+ }, delayMs);
7135
+ timer.unref?.();
7136
+ this[timerOf] = timer;
7137
+ }
6471
7138
  /**
6472
7139
  * Wrap `ctx.settings.readAddonStore()` with a short retry budget so a
6473
7140
  * transient settings-store outage (mid-restart of sqlite-settings, tsx-watch
@@ -7102,6 +7769,69 @@ method(object({ deviceId: number() }), array(StreamSourceEntrySchema)), method(o
7102
7769
  kind: "mutation",
7103
7770
  auth: "admin"
7104
7771
  }), method(object({ deviceId: number() }), unknown().nullable()), method(object({ deviceId: number() }), RawStateResultSchema.nullable(), { auth: "protected" });
7772
+ function defOf(schema) {
7773
+ return schema._zod?.def ?? {};
7774
+ }
7775
+ function declaredHere(schema) {
7776
+ return globalRegistry.get(schema)?.secret === true;
7777
+ }
7778
+ /** Wrapper kinds whose `innerType` is the field itself. */
7779
+ var WRAPPERS = new Set([
7780
+ "optional",
7781
+ "nullable",
7782
+ "default",
7783
+ "prefault",
7784
+ "catch",
7785
+ "readonly",
7786
+ "nonoptional"
7787
+ ]);
7788
+ /**
7789
+ * The schema layers that make up ONE field: the schema itself and every
7790
+ * wrapper below it (optional / default / nullable / readonly / catch), plus
7791
+ * both sides of a pipe (`z.preprocess` puts the real schema on `out`,
7792
+ * `.transform` on `in`).
7793
+ */
7794
+ function layersOf(schema) {
7795
+ const out = [];
7796
+ const queue = [schema];
7797
+ while (queue.length > 0) {
7798
+ const s = queue.shift();
7799
+ if (!s || out.includes(s)) continue;
7800
+ out.push(s);
7801
+ const def = defOf(s);
7802
+ if (def.type !== void 0 && WRAPPERS.has(def.type) && def.innerType) queue.push(def.innerType);
7803
+ if (def.type === "pipe") {
7804
+ if (def.in) queue.push(def.in);
7805
+ if (def.out) queue.push(def.out);
7806
+ }
7807
+ }
7808
+ return out;
7809
+ }
7810
+ /** True when any layer of this field declares `.meta({ secret: true })`. */
7811
+ function isZodSecret(schema) {
7812
+ return layersOf(schema).some(declaredHere);
7813
+ }
7814
+ /**
7815
+ * Every declared secret path in a config schema: dotted keys, `[]` for "each
7816
+ * element of this array" (`connection.password`, `rows[].token`). A declared
7817
+ * object or array is reported as one path and not descended into — everything
7818
+ * under it is secret.
7819
+ */
7820
+ function collectZodSecretPaths(schema, prefix = "") {
7821
+ if (isZodSecret(schema)) return prefix.length > 0 ? [prefix] : [];
7822
+ const paths = [];
7823
+ for (const layer of layersOf(schema)) {
7824
+ const def = defOf(layer);
7825
+ if (def.type === "object" && def.shape) for (const [key, child] of Object.entries(def.shape)) paths.push(...collectZodSecretPaths(child, prefix ? `${prefix}.${key}` : key));
7826
+ else if (def.type === "array" && def.element) paths.push(...collectZodSecretPaths(def.element, `${prefix}[]`));
7827
+ else if (def.type === "union" && def.options) for (const option of def.options) paths.push(...collectZodSecretPaths(option, prefix));
7828
+ else if (def.type === "intersection") {
7829
+ if (def.left) paths.push(...collectZodSecretPaths(def.left, prefix));
7830
+ if (def.right) paths.push(...collectZodSecretPaths(def.right, prefix));
7831
+ }
7832
+ }
7833
+ return [...new Set(paths)];
7834
+ }
7105
7835
  //#endregion
7106
7836
  //#region ../types/dist/err-msg-DX6i_MY4.mjs
7107
7837
  var DeviceType = /* @__PURE__ */ function(DeviceType) {
@@ -14344,6 +15074,196 @@ id: union([string(), number()]) }), {
14344
15074
  kind: "mutation",
14345
15075
  auth: "admin"
14346
15076
  });
15077
+ /**
15078
+ * `keychain` — the hub's encrypted store of secret values (D787).
15079
+ *
15080
+ * Settings blobs never hold a secret: they hold a marker
15081
+ * `{"$secret":"secret://<owner>/<scope>/<fieldPath>","v":1}` and the value
15082
+ * lives here, AES-256-GCM under a data key that a master key wraps. This cap
15083
+ * is the OWNER's door to its own values: every method is owner-checked
15084
+ * against the CALLER, never against anything the caller claims.
15085
+ *
15086
+ * Who the caller is: the transport stamps `callerAddonId` into the args of a
15087
+ * call that crossed a process (the parent `LocalChildRegistry` from the UDS
15088
+ * connection, the agent from its child's connection carried in
15089
+ * `$hub-cap-fwd`'s envelope). A stamp always overwrites; a wire call with no
15090
+ * stamp has its claim stripped. Only a hub in-process caller may state its own
15091
+ * identity — `ctx.secrets` does that with the addon id closed over. This is
15092
+ * identity against BUGS and misrouting, not against a malicious addon (every
15093
+ * runner is the same OS user): see the threat model in
15094
+ * `docs/design/2026-10-08-secrets-keychain.md`.
15095
+ *
15096
+ * `callerAddonId` is deliberately NOT in any input schema: the tRPC router
15097
+ * parses the input, so a session can never supply it, and the internal mount
15098
+ * floors every method to admin anyway (D240).
15099
+ *
15100
+ * Internal: addons reach it through `ctx.secrets`, never directly.
15101
+ */
15102
+ /** Why a value cannot be served right now. Never folded into "missing". */
15103
+ var KeychainUnavailableReasonSchema = _enum([
15104
+ "key-missing",
15105
+ "wrong-key",
15106
+ "key-file-unreadable",
15107
+ "store-unavailable",
15108
+ "not-initialized",
15109
+ "decrypt-failed"
15110
+ ]);
15111
+ var KeychainStateSchema = discriminatedUnion("state", [object({ state: literal("ready") }), object({
15112
+ state: literal("locked"),
15113
+ reason: KeychainUnavailableReasonSchema
15114
+ })]);
15115
+ var KeychainResolveEntrySchema = discriminatedUnion("kind", [
15116
+ object({
15117
+ kind: literal("value"),
15118
+ value: string(),
15119
+ version: number().int()
15120
+ }),
15121
+ object({ kind: literal("missing") }),
15122
+ object({
15123
+ kind: literal("unavailable"),
15124
+ reason: KeychainUnavailableReasonSchema
15125
+ }),
15126
+ object({ kind: literal("forbidden") })
15127
+ ]);
15128
+ var KeychainResolveResultSchema = record(string(), KeychainResolveEntrySchema);
15129
+ /** Metadata of one stored value — never the value. */
15130
+ var KeychainSecretMetaSchema = object({
15131
+ ref: string(),
15132
+ owner: string(),
15133
+ /** Formatted scope (`global`, `node/<id>`, `device/<id>`, …). */
15134
+ scope: string(),
15135
+ fieldPath: string(),
15136
+ version: number().int(),
15137
+ createdAt: number(),
15138
+ updatedAt: number(),
15139
+ /** `addon:<id>` | `user:<id>` | `system`. */
15140
+ updatedBy: string(),
15141
+ /** Coarse — written at most once an hour per ref. `null` = never read. */
15142
+ lastReadAt: number().nullable()
15143
+ });
15144
+ var RefListSchema = array(string().min(1)).max(512);
15145
+ method(object({
15146
+ ref: string().min(1),
15147
+ value: string().min(1)
15148
+ }), object({
15149
+ ref: string(),
15150
+ version: number().int()
15151
+ }), {
15152
+ kind: "mutation",
15153
+ auth: "admin"
15154
+ }), method(object({ refs: RefListSchema }), KeychainResolveResultSchema, { auth: "admin" }), method(object({ refs: RefListSchema }), object({ deleted: number().int() }), {
15155
+ kind: "mutation",
15156
+ auth: "admin"
15157
+ }), method(object({}), array(KeychainSecretMetaSchema).readonly(), { auth: "admin" }), method(object({}), KeychainStateSchema, { auth: "admin" });
15158
+ var KeychainKeySourceSchema = object({
15159
+ kind: _enum([
15160
+ "config-file",
15161
+ "previous-config-file",
15162
+ "platform",
15163
+ "default-file"
15164
+ ]),
15165
+ /** File sources only — a path is not a secret. */
15166
+ path: string().optional(),
15167
+ /**
15168
+ * True when a whole-volume backup of the data directory carries this key
15169
+ * next to the database it protects (the default file). The page warns.
15170
+ */
15171
+ sharesBackupWithDatabase: boolean()
15172
+ });
15173
+ var KeychainStatusSchema = object({
15174
+ keychain: KeychainStateSchema,
15175
+ /** The source of the master key in use; `null` while locked. */
15176
+ keySource: KeychainKeySourceSchema.nullable(),
15177
+ /** The source configured to be primary — differs from `keySource` while a rotation is pending. */
15178
+ configuredSource: KeychainKeySourceSchema,
15179
+ /** Short fingerprint of the master key in use (`HMAC(KEK, label)`, 16 hex). */
15180
+ fingerprint: string().nullable(),
15181
+ activeKeyId: string().nullable(),
15182
+ /**
15183
+ * The keychain unlocked with a NON-primary source: the configured primary
15184
+ * key is not the one that wraps the data key yet. `rotateMasterKey` moves it.
15185
+ */
15186
+ rotationPending: boolean(),
15187
+ /** Wrapped copies of the data key under a previous master key, kept until purged. */
15188
+ retiredWraps: number().int(),
15189
+ recoveryKeyDownloadedAt: number().nullable(),
15190
+ secretCount: number().int()
15191
+ });
15192
+ /**
15193
+ * Whether a stored value is still pointed at by its owner's settings.
15194
+ * `unknown` is a first-class answer: a scope whose blob could not be read is
15195
+ * never reported as an orphan (and never deleted as one).
15196
+ */
15197
+ var KeychainSecretUsageSchema = _enum([
15198
+ "in-use",
15199
+ "orphan",
15200
+ "unknown"
15201
+ ]);
15202
+ var KeychainAdminSecretSchema = KeychainSecretMetaSchema.extend({ usage: KeychainSecretUsageSchema });
15203
+ var KeychainAuditActionSchema = _enum([
15204
+ "put",
15205
+ "delete",
15206
+ "reveal",
15207
+ "rotate-master-key",
15208
+ "purge-retired-keys",
15209
+ "download-recovery-key",
15210
+ "delete-orphans",
15211
+ "reset",
15212
+ "initialize"
15213
+ ]);
15214
+ var KeychainAuditEntrySchema = object({
15215
+ id: string(),
15216
+ at: number(),
15217
+ action: KeychainAuditActionSchema,
15218
+ /** `addon:<id>` | `user:<id>` | `system`. */
15219
+ actor: string(),
15220
+ ref: string().nullable(),
15221
+ detail: string().nullable()
15222
+ });
15223
+ 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({
15224
+ value: string(),
15225
+ version: number().int()
15226
+ }), {
15227
+ kind: "mutation",
15228
+ auth: "admin",
15229
+ caller: "required"
15230
+ }), method(object({ refs: array(string().min(1)).max(1e3) }), object({
15231
+ deleted: array(string()).readonly(),
15232
+ kept: array(object({
15233
+ ref: string(),
15234
+ usage: KeychainSecretUsageSchema
15235
+ })).readonly()
15236
+ }), {
15237
+ kind: "mutation",
15238
+ auth: "admin",
15239
+ caller: "required"
15240
+ }), method(object({}), object({
15241
+ fingerprint: string(),
15242
+ keySource: KeychainKeySourceSchema
15243
+ }), {
15244
+ kind: "mutation",
15245
+ auth: "admin",
15246
+ caller: "required"
15247
+ }), method(object({}), object({ purged: number().int() }), {
15248
+ kind: "mutation",
15249
+ auth: "admin",
15250
+ caller: "required"
15251
+ }), method(object({}), object({
15252
+ key: string(),
15253
+ fingerprint: string(),
15254
+ keySource: KeychainKeySourceSchema
15255
+ }), {
15256
+ kind: "mutation",
15257
+ auth: "admin",
15258
+ caller: "required"
15259
+ }), method(object({ confirm: literal("RESET KEYCHAIN") }), object({
15260
+ archivedCollection: string().nullable(),
15261
+ archived: number().int()
15262
+ }), {
15263
+ kind: "mutation",
15264
+ auth: "admin",
15265
+ caller: "required"
15266
+ });
14347
15267
  method(_void(), object({
14348
15268
  id: string(),
14349
15269
  name: string(),
@@ -15803,7 +16723,11 @@ var DeviceRegisterPayloadSchema = object({
15803
16723
  var DeviceRemovePayloadSchema = object({ deviceId: number() });
15804
16724
  var DevicePersistConfigPayloadSchema = object({
15805
16725
  deviceId: number(),
15806
- data: record(string(), unknown())
16726
+ data: record(string(), unknown()),
16727
+ /** The paths the device's schema declares secret (D783), when the caller
16728
+ * knows them — those values are kept in the keychain, not the blob (D787).
16729
+ * Absent: the paths the device last reported at `registerDevice` apply. */
16730
+ secretConfigPaths: array(string()).optional()
15807
16731
  });
15808
16732
  /** What a migration actually did, per switch. `unreachable` is a first-class
15809
16733
  * answer: a camera that could not be asked is not a camera that was silenced. */
@@ -22858,8 +23782,23 @@ var RetrainMacroClassSchema = _enum([
22858
23782
  ]);
22859
23783
  /** A subject to learn, or a phantom to unlearn (taught by OMISSION). */
22860
23784
  var RetrainAnnotationKindSchema = _enum(["subject", "model_error"]);
22861
- /** Did a human draw this box, or did the assist propose it? */
22862
- var RetrainAnnotationSourceSchema = _enum(["operator", "assist"]);
23785
+ /**
23786
+ * Where a box came from. A machine-sourced box is a DRAFT on the page until
23787
+ * the operator confirms it; once saved it keeps its source as provenance.
23788
+ *
23789
+ * - `operator` — drawn by hand.
23790
+ * - `assist` — proposed by a detector run on the copy (the camera's own
23791
+ * model, or a larger teacher model).
23792
+ * - `pipeline` — the box the live pipeline actually drew on that frame, read
23793
+ * back from the track store (never a re-run).
23794
+ * - `llm` — proposed by a vision-capable LLM profile.
23795
+ */
23796
+ var RetrainAnnotationSourceSchema = _enum([
23797
+ "operator",
23798
+ "assist",
23799
+ "pipeline",
23800
+ "llm"
23801
+ ]);
22863
23802
  /** Normalised `[0,1]` rectangle against the FULL frame — the canonical form. */
22864
23803
  var RetrainBboxSchema = object({
22865
23804
  x: number(),
@@ -22877,7 +23816,8 @@ var RetrainBboxSchema = object({
22877
23816
  */
22878
23817
  var RetrainAnnotationSchema = object({
22879
23818
  id: string(),
22880
- trackId: string(),
23819
+ /** The frame's track. Absent on a recording still, which has none. */
23820
+ trackId: string().optional(),
22881
23821
  deviceId: number(),
22882
23822
  /** The COPY in retrain storage — never the source track's media key. */
22883
23823
  mediaKey: string(),
@@ -22926,13 +23866,47 @@ var RetrainFrameCandidateSchema = object({
22926
23866
  * fail, whatever became of the original. */
22927
23867
  copied: boolean()
22928
23868
  });
23869
+ /**
23870
+ * One box the live pipeline drew on a copied frame — what a correction starts
23871
+ * from. Derived when the frame is listed, from the track store: the subject
23872
+ * box recorded on the source media row when there is one, else the track
23873
+ * position nearest the frame's capture time. Never stored as an annotation
23874
+ * until the operator confirms it.
23875
+ */
23876
+ var RetrainPipelineBoxSchema = object({
23877
+ /** Normalised `[0,1]` against the full frame. */
23878
+ bbox: RetrainBboxSchema,
23879
+ macroClass: RetrainMacroClassSchema,
23880
+ label: string().optional(),
23881
+ subLabel: string().optional(),
23882
+ /** The detection score of the position used, when it was recorded. */
23883
+ score: number().optional(),
23884
+ /** The root model that produced the track, when it was recorded. */
23885
+ modelId: string().optional(),
23886
+ trackId: string(),
23887
+ /** `subject-box`: recorded on this very frame. `position`: the track's
23888
+ * position nearest the capture time, `deltaMs` away. */
23889
+ basis: _enum(["subject-box", "position"]),
23890
+ deltaMs: number()
23891
+ });
23892
+ /**
23893
+ * Where a retrain frame came from: a TRACK's stored media (copy-on-select),
23894
+ * or the RECORDING at an instant — the frame a model saw nothing in has no
23895
+ * track at all.
23896
+ */
23897
+ var RetrainFrameOriginSchema = _enum(["track", "recording"]);
22929
23898
  /** A frame the dataset OWNS: bytes copied at selection time. */
22930
23899
  var RetrainFrameSchema = object({
22931
23900
  frameId: string(),
22932
23901
  deviceId: number(),
22933
- trackId: string(),
22934
- /** Provenance only. It may already point at nothing — that is expected. */
22935
- sourceMediaId: number().int(),
23902
+ origin: RetrainFrameOriginSchema,
23903
+ /** The track it was copied from. Absent on a recording still. */
23904
+ trackId: string().optional(),
23905
+ /** Provenance only. It may already point at nothing — that is expected.
23906
+ * Absent on a recording still. */
23907
+ sourceMediaId: number().int().optional(),
23908
+ /** A recording still: the playhead instant it was taken at. */
23909
+ epochMs: number().optional(),
22936
23910
  sourceKind: MediaFileKindEnum,
22937
23911
  sizeBytes: number().int(),
22938
23912
  width: number().int(),
@@ -22943,7 +23917,12 @@ var RetrainFrameSchema = object({
22943
23917
  /** The operator's "every subject in this frame is boxed". Detector
22944
23918
  * evaluation keeps only complete frames: an unboxed subject would count as
22945
23919
  * a false positive. */
22946
- complete: boolean()
23920
+ complete: boolean(),
23921
+ /** The boxes the pipeline drew on this frame. Present on list answers;
23922
+ * empty when nothing the track store holds can be placed on it. */
23923
+ pipelineBoxes: array(RetrainPipelineBoxSchema).readonly().optional(),
23924
+ /** The named collections this frame belongs to. Present on list answers. */
23925
+ collectionIds: array(string()).readonly().optional()
22947
23926
  });
22948
23927
  /** Why a copy-on-select could not be honoured — named, never a silent skip. */
22949
23928
  var RetrainCopyRefusalSchema = _enum([
@@ -22974,6 +23953,8 @@ var RetrainFrameListSchema = object({
22974
23953
  var RetrainExportFilterSchema = object({
22975
23954
  deviceIds: array(number()).optional(),
22976
23955
  frameIds: array(string()).max(2e4).optional(),
23956
+ /** Only frames in at least one of these named collections. */
23957
+ collectionIds: array(string()).max(200).optional(),
22977
23958
  batchId: string().optional(),
22978
23959
  /** Only frames the operator marked complete (all subjects boxed). */
22979
23960
  completeOnly: boolean().optional()
@@ -23038,6 +24019,109 @@ var RetrainAssistResultSchema = discriminatedUnion("kind", [object({
23038
24019
  reason: string(),
23039
24020
  detail: string().optional()
23040
24021
  })]);
24022
+ /** A named set over the retrain corpus — membership only, it owns no pixels. */
24023
+ var RetrainCollectionSchema = object({
24024
+ id: string(),
24025
+ name: string(),
24026
+ createdAt: number(),
24027
+ frameCount: number().int()
24028
+ });
24029
+ var RetrainCollectionCreateResultSchema = discriminatedUnion("kind", [object({
24030
+ kind: literal("created"),
24031
+ collection: RetrainCollectionSchema
24032
+ }), object({
24033
+ kind: literal("refused"),
24034
+ reason: _enum(["empty-name", "duplicate-name"])
24035
+ })]);
24036
+ var RetrainCollectionRenameResultSchema = discriminatedUnion("kind", [object({
24037
+ kind: literal("renamed"),
24038
+ collection: RetrainCollectionSchema
24039
+ }), object({
24040
+ kind: literal("refused"),
24041
+ reason: _enum([
24042
+ "empty-name",
24043
+ "duplicate-name",
24044
+ "unknown-collection"
24045
+ ])
24046
+ })]);
24047
+ /**
24048
+ * The outcome of adding the frame at a recording instant. Every refusal is
24049
+ * named: `still-unavailable` (not recording, a gap, or an undecodable frame —
24050
+ * `detail` says which), `still-busy` (the recorder is at its decode bound; try
24051
+ * again), `unreadable-image`, `write-failed`, `unknown-collection`.
24052
+ */
24053
+ var AddRetrainFrameFromRecordingResultSchema = discriminatedUnion("kind", [object({
24054
+ kind: literal("added"),
24055
+ collectionId: string(),
24056
+ frame: RetrainFrameSchema,
24057
+ /** The moment was already in the dataset; nothing was decoded. */
24058
+ reused: boolean()
24059
+ }), object({
24060
+ kind: literal("refused"),
24061
+ reason: _enum([
24062
+ "unknown-collection",
24063
+ "still-unavailable",
24064
+ "still-busy",
24065
+ "unreadable-image",
24066
+ "write-failed"
24067
+ ]),
24068
+ detail: string().optional()
24069
+ })]);
24070
+ /** A vision LLM profile the AI assist may use, and where it sends the frame. */
24071
+ var RetrainAssistProfileSchema = object({
24072
+ id: string(),
24073
+ name: string(),
24074
+ model: string(),
24075
+ kind: string(),
24076
+ /** `true` when the frame would leave the house (a cloud vendor, or an
24077
+ * endpoint that is not on the local network). The page confirms each such
24078
+ * run, and the provider refuses one without `allowCloud`. */
24079
+ leavesHouse: boolean()
24080
+ });
24081
+ /** A box the AI assist proposed: a draft, plus the model's own reason. */
24082
+ var RetrainLlmProposalSchema = RetrainAnnotationDraftSchema.extend({ reason: string() });
24083
+ /** What the AI assist said about a box that was already on the canvas. */
24084
+ var RetrainLlmReviewSchema = object({
24085
+ /** The `ref` the page sent the box under. */
24086
+ ref: string(),
24087
+ verdict: _enum([
24088
+ "confirmed",
24089
+ "wrong-class",
24090
+ "not-an-object",
24091
+ "uncertain"
24092
+ ]),
24093
+ suggestedClass: RetrainMacroClassSchema.optional(),
24094
+ reason: string()
24095
+ });
24096
+ /**
24097
+ * The AI assist's answer. `proposed` carries drafts (`source: 'llm'`, the
24098
+ * model and its confidence) and reviews; items the model got wrong (a box off
24099
+ * the frame, an unasked class, an unknown ref) are dropped and counted in
24100
+ * `rejected`. A whole answer that is not the schema is `malformed-answer`.
24101
+ */
24102
+ var RetrainLlmAssistResultSchema = discriminatedUnion("kind", [object({
24103
+ kind: literal("proposed"),
24104
+ profileId: string(),
24105
+ model: string(),
24106
+ /** The frame was sent outside the house for this answer. */
24107
+ leftHouse: boolean(),
24108
+ proposals: array(RetrainLlmProposalSchema).readonly(),
24109
+ reviews: array(RetrainLlmReviewSchema).readonly(),
24110
+ rejected: number().int()
24111
+ }), object({
24112
+ kind: literal("refused"),
24113
+ reason: _enum([
24114
+ "unknown-frame",
24115
+ "unreadable-frame",
24116
+ "unknown-profile",
24117
+ "profile-disabled",
24118
+ "no-vision",
24119
+ "cloud-not-confirmed",
24120
+ "llm-error",
24121
+ "malformed-answer"
24122
+ ]),
24123
+ detail: string().optional()
24124
+ })]);
23041
24125
  /** The outcome of a lifecycle move owned by the retrain page. */
23042
24126
  var RetrainTransitionResultSchema = object({
23043
24127
  trackId: string(),
@@ -23755,7 +24839,7 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
23755
24839
  auth: "admin"
23756
24840
  }), method(object({
23757
24841
  deviceId: number(),
23758
- trackId: string(),
24842
+ trackId: string().optional(),
23759
24843
  frameId: string()
23760
24844
  }), object({
23761
24845
  removed: boolean(),
@@ -23772,7 +24856,8 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
23772
24856
  auth: "admin"
23773
24857
  }), method(object({
23774
24858
  deviceId: number(),
23775
- trackId: string(),
24859
+ /** The frame's track, when it has one — checked against the frame. */
24860
+ trackId: string().optional(),
23776
24861
  frameId: string(),
23777
24862
  subject: RetrainAssistSubjectSchema,
23778
24863
  /** Which node runs it. Absent ⇒ wherever an unowned call lands. */
@@ -23780,12 +24865,16 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
23780
24865
  }), RetrainAssistResultSchema, {
23781
24866
  kind: "mutation",
23782
24867
  auth: "admin"
23783
- }), method(object({ trackId: string() }), array(RetrainAnnotationSchema).readonly(), {
24868
+ }), method(object({
24869
+ trackId: string().optional(),
24870
+ frameIds: array(string()).max(2e3).optional()
24871
+ }), array(RetrainAnnotationSchema).readonly(), {
23784
24872
  kind: "query",
23785
24873
  auth: "admin"
23786
24874
  }), method(object({
23787
24875
  deviceId: number(),
23788
- trackId: string(),
24876
+ /** The frame's track, when it has one — checked against the frame. */
24877
+ trackId: string().optional(),
23789
24878
  frameId: string(),
23790
24879
  annotations: array(RetrainAnnotationDraftSchema)
23791
24880
  }), array(RetrainAnnotationSchema).readonly(), {
@@ -23808,7 +24897,7 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
23808
24897
  auth: "admin"
23809
24898
  }), method(object({
23810
24899
  deviceId: number(),
23811
- trackId: string(),
24900
+ trackId: string().optional(),
23812
24901
  frameId: string(),
23813
24902
  complete: boolean()
23814
24903
  }), RetrainFrameSchema, {
@@ -23822,6 +24911,74 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
23822
24911
  kind: "mutation",
23823
24912
  auth: "admin",
23824
24913
  timeoutMs: 60 * 6e4
24914
+ }), method(object({}), array(RetrainAssistProfileSchema).readonly(), {
24915
+ kind: "query",
24916
+ auth: "admin"
24917
+ }), method(object({
24918
+ deviceId: number(),
24919
+ trackId: string().optional(),
24920
+ frameId: string(),
24921
+ profileId: string(),
24922
+ classes: array(RetrainMacroClassSchema).min(1),
24923
+ boxes: array(object({
24924
+ ref: string(),
24925
+ bbox: RetrainBboxSchema,
24926
+ macroClass: RetrainMacroClassSchema,
24927
+ label: string().optional()
24928
+ })).max(50),
24929
+ allowCloud: boolean()
24930
+ }), RetrainLlmAssistResultSchema, {
24931
+ kind: "mutation",
24932
+ auth: "admin",
24933
+ timeoutMs: 18e4
24934
+ }), method(object({ name: string().max(120) }), RetrainCollectionCreateResultSchema, {
24935
+ kind: "mutation",
24936
+ auth: "admin"
24937
+ }), method(object({}), array(RetrainCollectionSchema).readonly(), {
24938
+ kind: "query",
24939
+ auth: "admin"
24940
+ }), method(object({
24941
+ id: string(),
24942
+ name: string().max(120)
24943
+ }), RetrainCollectionRenameResultSchema, {
24944
+ kind: "mutation",
24945
+ auth: "admin"
24946
+ }), method(object({ id: string() }), object({
24947
+ deleted: boolean(),
24948
+ removedFrames: number().int()
24949
+ }), {
24950
+ kind: "mutation",
24951
+ auth: "admin"
24952
+ }), method(object({
24953
+ collectionId: string(),
24954
+ deviceId: number(),
24955
+ epochMs: number()
24956
+ }), AddRetrainFrameFromRecordingResultSchema, {
24957
+ kind: "mutation",
24958
+ auth: "admin",
24959
+ timeoutMs: 6e4
24960
+ }), method(object({
24961
+ collectionId: string(),
24962
+ frameIds: array(string()).min(1).max(500)
24963
+ }), object({
24964
+ added: number().int(),
24965
+ alreadyMember: number().int(),
24966
+ unknownFrameIds: array(string()).readonly()
24967
+ }), {
24968
+ kind: "mutation",
24969
+ auth: "admin"
24970
+ }), method(object({
24971
+ collectionId: string(),
24972
+ frameId: string()
24973
+ }), object({
24974
+ removed: boolean(),
24975
+ deletedFrame: boolean()
24976
+ }), {
24977
+ kind: "mutation",
24978
+ auth: "admin"
24979
+ }), method(object({ collectionId: string() }), array(RetrainFrameSchema).readonly(), {
24980
+ kind: "query",
24981
+ auth: "admin"
23825
24982
  }), method(object({
23826
24983
  /** Which of the three event tables owns the row. */
23827
24984
  ownerType: EventOwnerTypeSchema,
@@ -24445,13 +25602,31 @@ var RecommendationReasonSchema = discriminatedUnion("kind", [
24445
25602
  object({
24446
25603
  kind: literal("no-family-build"),
24447
25604
  format: ModelFormatSchema$1
25605
+ }),
25606
+ object({
25607
+ kind: literal("kept-custom-pin"),
25608
+ modelId: string(),
25609
+ deviceKey: string()
24448
25610
  })
24449
25611
  ]);
25612
+ /** Why a device is left exactly as it is, whatever the plan would pick (D786). */
25613
+ var KeptReasonSchema = _enum(["custom-pin"]);
25614
+ /**
25615
+ * Where a choice's latency came from (D791): this node's own benchmark
25616
+ * result, or the hardware-class table. Measured on the node beats the table.
25617
+ */
25618
+ var LatencySourceSchema = discriminatedUnion("kind", [object({ kind: literal("table") }), object({
25619
+ kind: literal("node-benchmark"),
25620
+ resultId: string(),
25621
+ measuredAtMs: number()
25622
+ })]);
24450
25623
  var DeviceModelChoiceSchema = object({
24451
25624
  modelId: string(),
24452
25625
  p50Ms: number(),
24453
25626
  fps: number(),
24454
25627
  measured: boolean(),
25628
+ /** Absent on a plan from before D791 — read as the table. */
25629
+ source: LatencySourceSchema.optional(),
24455
25630
  /** Parallel sessions at the camera rate with the headroom kept free: ⌊fps × (1 − headroom) / camera fps⌋. */
24456
25631
  capacitySessions: number(),
24457
25632
  personRecall: number()
@@ -24462,6 +25637,8 @@ var DeviceRecommendationSchema = object({
24462
25637
  enabled: boolean(),
24463
25638
  available: boolean(),
24464
25639
  chosen: DeviceModelChoiceSchema.nullable(),
25640
+ /** Present when the device is kept as is: Apply writes nothing on it. */
25641
+ kept: KeptReasonSchema.optional(),
24465
25642
  reasons: array(RecommendationReasonSchema).readonly()
24466
25643
  });
24467
25644
  var NodeRecommendationSchema = object({
@@ -24515,6 +25692,17 @@ var AutoTuneWarningSchema = discriminatedUnion("kind", [
24515
25692
  kind: literal("coral-enabled"),
24516
25693
  nodeId: string(),
24517
25694
  deviceKey: string()
25695
+ }),
25696
+ object({
25697
+ kind: literal("custom-pin-kept"),
25698
+ nodeId: string(),
25699
+ deviceKey: string().nullable(),
25700
+ deviceId: number().nullable(),
25701
+ modelId: string()
25702
+ }),
25703
+ object({
25704
+ kind: literal("custom-registry-unreadable"),
25705
+ error: string()
24518
25706
  })
24519
25707
  ]);
24520
25708
  var AutoTuneOptionsSchema = object({
@@ -24693,13 +25881,14 @@ var SuggestSharesResultSchema = object({
24693
25881
  nodes: array(SuggestedNodeShareSchema).readonly()
24694
25882
  });
24695
25883
  /**
24696
- * Where the node and device shares come from (D750, D755).
24697
- * - `hardware` (default) — computed by the system from each node's static
24698
- * capacity (its accelerators at their Auto tune models, from the measured
24699
- * latency table), recomputed whenever a node or device joins, leaves, is
24700
- * switched on or off, or changes model. No load input.
24701
- * - `benchmark` — the same, from each node's measured capacity (node
24702
- * benchmark results); a node without results falls back to `hardware`.
25884
+ * Where the node and device shares come from (D750, D755, D791).
25885
+ * - `benchmark` (default since D791) — each node's capacity as its own node
25886
+ * benchmark measured it; a node without fresh results is sized from
25887
+ * `hardware` and says so. Measured on the node beats the table.
25888
+ * - `hardware` — computed from each node's static capacity only (its
25889
+ * accelerators at their Auto tune models, from the latency table).
25890
+ * Both are recomputed whenever a node or device joins, leaves, is switched
25891
+ * on or off, changes model, or a benchmark result is written. No load input.
24703
25892
  * - `manual` — the operator's stored sliders.
24704
25893
  * Either way a node or device that cannot take sessions gives its share to
24705
25894
  * the others in proportion; the stored values are never rewritten for that.
@@ -24748,6 +25937,362 @@ var EffectiveSharesSchema = object({
24748
25937
  nodeWeights: record(string(), number()),
24749
25938
  deviceWeights: record(string(), record(string(), number()))
24750
25939
  });
25940
+ /**
25941
+ * Wire shapes of the node benchmark (D791): the operator's plan, the
25942
+ * preflight the confirmation shows, the run the orchestrator owns, what the
25943
+ * measuring runner reports, and the result rows Auto tune and the automatic
25944
+ * shares read.
25945
+ *
25946
+ * ONE node at a time, owned by the pipeline orchestrator. While a run is
25947
+ * active the cluster is in BENCHMARK MODE for that node: it is not a
25948
+ * detection candidate, camera pins naming it are ignored so its sessions move
25949
+ * elsewhere, and both come back when the mode ends — after a crash or a hub
25950
+ * restart too (a persisted manifest, reconciled against the registry).
25951
+ *
25952
+ * Two measurements, both on the node, driven by its own runner (frames never
25953
+ * cross a process at frame rate, D9):
25954
+ * - `device` — one accelerator × one candidate detector, root only, open
25955
+ * loop: how many streams at the camera rate it carries inside the frame
25956
+ * interval;
25957
+ * - `pipeline` — the chosen detector plus the operator's detail steps
25958
+ * (faces, plates, classifiers, CLIP…), on varied frames from the bench
25959
+ * clip: how many parallel sessions the node carries before latency, drops,
25960
+ * CPU, RAM or the event loop give out.
25961
+ */
25962
+ /** Defaults and bounds, one place. */
25963
+ var NODE_BENCHMARK_DEFAULTS = {
25964
+ fpsPerStream: 10,
25965
+ budgetMinutes: 45,
25966
+ minBudgetMinutes: 10,
25967
+ maxBudgetMinutes: 120,
25968
+ /** A result older than this no longer beats the table. */
25969
+ staleAfterDays: 30,
25970
+ /** Warm-in per ramp step (not accounted). */
25971
+ settleSec: 5,
25972
+ /** Accounted window per ramp step. */
25973
+ measureSec: 20,
25974
+ /** Longest the drain may take before the run is refused. */
25975
+ drainTimeoutSec: 120,
25976
+ /** Candidate models per device in one run. */
25977
+ maxModelsPerDevice: 6
25978
+ };
25979
+ /** The two measurements a run can make. */
25980
+ var NodeBenchmarkPhaseSchema = _enum(["device", "pipeline"]);
25981
+ var NodeBenchmarkDevicePlanSchema = object({
25982
+ /** `<backend>:<device>` — `openvino:npu`, `coreml:all`, `cpu`. */
25983
+ deviceKey: string().min(1),
25984
+ /**
25985
+ * Root detector candidates for the `device` measurement, in the order
25986
+ * measured. The FIRST is the one the `pipeline` measurement runs.
25987
+ */
25988
+ modelIds: array(string().min(1)).min(1).max(NODE_BENCHMARK_DEFAULTS.maxModelsPerDevice)
25989
+ });
25990
+ /** What the operator confirmed. */
25991
+ var NodeBenchmarkPlanSchema = object({
25992
+ nodeId: string().min(1),
25993
+ devices: array(NodeBenchmarkDevicePlanSchema).min(1),
25994
+ /** Which measurements run. At least one. */
25995
+ phases: array(NodeBenchmarkPhaseSchema).min(1).default(["device", "pipeline"]),
25996
+ /**
25997
+ * Detail steps (catalog step ids under the root: faces, plates,
25998
+ * classifiers, CLIP…) the `pipeline` measurement enables. The root
25999
+ * detector always runs.
26000
+ */
26001
+ steps: array(string().min(1)).default([]),
26002
+ /** Offered rate of one stream / session. */
26003
+ fpsPerStream: number().int().min(1).max(30).default(NODE_BENCHMARK_DEFAULTS.fpsPerStream),
26004
+ /** Hard deadline: the mode ends and the cluster is restored when it passes. */
26005
+ budgetMinutes: number().int().min(NODE_BENCHMARK_DEFAULTS.minBudgetMinutes).max(NODE_BENCHMARK_DEFAULTS.maxBudgetMinutes).default(NODE_BENCHMARK_DEFAULTS.budgetMinutes),
26006
+ /** Keep the models the run downloaded (default: delete what was not installed before). */
26007
+ keepDownloadedModels: boolean().default(false),
26008
+ /** Start although the other nodes' capacity does not cover the sessions running now. */
26009
+ acceptInsufficientHeadroom: boolean().default(false)
26010
+ });
26011
+ var NodeBenchmarkRefusalSchema = object({
26012
+ kind: _enum([
26013
+ "benchmark-active",
26014
+ "node-offline",
26015
+ "unknown-device",
26016
+ "no-phase",
26017
+ "insufficient-headroom"
26018
+ ]),
26019
+ detail: string(),
26020
+ overridable: boolean()
26021
+ });
26022
+ /** A camera whose detection leaves the node for the run. */
26023
+ var NodeBenchmarkMovingCameraSchema = object({
26024
+ deviceId: number(),
26025
+ /** Placed on the node now (a standing attach or a running session). */
26026
+ placedOnNode: boolean(),
26027
+ /** A node pin naming this node, ignored for the run. */
26028
+ pinnedToNode: boolean()
26029
+ });
26030
+ /** A camera that cannot leave: no other node can obtain its frames. */
26031
+ var NodeBenchmarkStayingCameraSchema = object({
26032
+ deviceId: number(),
26033
+ reason: literal("only-frame-source")
26034
+ });
26035
+ var NodeBenchmarkPreflightSchema = object({
26036
+ nodeId: string(),
26037
+ online: boolean(),
26038
+ moving: array(NodeBenchmarkMovingCameraSchema).readonly(),
26039
+ /** Keep running on the node during the run; the result is flagged contaminated. */
26040
+ staying: array(NodeBenchmarkStayingCameraSchema).readonly(),
26041
+ estimatedDurationMs: number(),
26042
+ /** The run ends and the cluster is restored at the latest after this long. */
26043
+ budgetMs: number(),
26044
+ phases: array(NodeBenchmarkPhaseSchema).readonly(),
26045
+ steps: array(string()).readonly(),
26046
+ devices: array(NodeBenchmarkDevicePlanSchema).readonly(),
26047
+ /** Parallel sessions the cluster runs now, and what the other nodes can carry. */
26048
+ headroom: object({
26049
+ sessionsNow: number(),
26050
+ otherNodesCapacitySessions: number().nullable()
26051
+ }),
26052
+ refusals: array(NodeBenchmarkRefusalSchema).readonly(),
26053
+ canStart: boolean()
26054
+ });
26055
+ /** Where the measuring runner is. */
26056
+ var NodeBenchProgressSchema = object({
26057
+ phase: _enum([
26058
+ "preparing",
26059
+ "device",
26060
+ "pipeline",
26061
+ "cleanup"
26062
+ ]),
26063
+ deviceKey: string().nullable(),
26064
+ modelId: string().nullable(),
26065
+ /** Streams (device) or sessions (pipeline) of the step running now. */
26066
+ load: number().nullable(),
26067
+ cellsDone: number(),
26068
+ cellsTotal: number(),
26069
+ message: string()
26070
+ });
26071
+ /** What limited a ramp. `none` = the ramp ran out of steps still passing. */
26072
+ var NodeBenchLimitSchema = _enum([
26073
+ "p95",
26074
+ "drops",
26075
+ "errors",
26076
+ "stall",
26077
+ "cpu",
26078
+ "ram",
26079
+ "none"
26080
+ ]);
26081
+ var NodeBenchRampStepSchema = object({
26082
+ load: number(),
26083
+ pass: boolean(),
26084
+ p95Ms: number(),
26085
+ dropRatio: number(),
26086
+ /** Completed frames per second over the accounted window. */
26087
+ fps: number(),
26088
+ cpuPct: number().nullable(),
26089
+ ramFreePct: number().nullable(),
26090
+ failReasons: array(string()).readonly()
26091
+ });
26092
+ var NodeBenchCellSchema = discriminatedUnion("phase", [object({
26093
+ phase: literal("device"),
26094
+ deviceKey: string(),
26095
+ modelId: string(),
26096
+ /** Single-stream latency (the K = 1 step). */
26097
+ p50Ms: number(),
26098
+ p95Ms: number(),
26099
+ p99Ms: number(),
26100
+ /** Frames per second sustained at the last passing step. */
26101
+ fps: number(),
26102
+ /** Streams at the camera rate the device carried inside the frame interval; 0 = not even one. */
26103
+ kMax: number(),
26104
+ limitedBy: NodeBenchLimitSchema,
26105
+ /** First call (model load + warm-up). */
26106
+ warmupMs: number(),
26107
+ ramp: array(NodeBenchRampStepSchema).readonly()
26108
+ }), object({
26109
+ phase: literal("pipeline"),
26110
+ deviceKey: string(),
26111
+ modelId: string(),
26112
+ steps: array(string()).readonly(),
26113
+ /** Parallel sessions at the camera rate the node carried; 0 = not even one. */
26114
+ maxSessions: number(),
26115
+ limitedBy: NodeBenchLimitSchema,
26116
+ /** Detail steps that produced at least one result on the clip — a step that never fired measured nothing. */
26117
+ stepsFired: array(string()).readonly(),
26118
+ warmupMs: number(),
26119
+ ramp: array(NodeBenchRampStepSchema).readonly()
26120
+ })]);
26121
+ /**
26122
+ * What a result was measured ON. A result whose fingerprint no longer matches
26123
+ * the node no longer beats the table.
26124
+ */
26125
+ var NodeBenchFingerprintSchema = object({
26126
+ pipelineVersion: string().nullable(),
26127
+ cpuModel: string().nullable(),
26128
+ ramGb: number().nullable(),
26129
+ os: string().nullable(),
26130
+ /** Per device: the pool the cells ran on (runtime + tuning). */
26131
+ pools: record(string(), object({
26132
+ runtime: string(),
26133
+ numWorkers: number(),
26134
+ concurrency: number(),
26135
+ batchMode: string()
26136
+ })).default({})
26137
+ });
26138
+ /** The frames the run used. */
26139
+ var NodeBenchClipSchema = object({
26140
+ /** `camstack-bench-v1` or `reference-images` (the fallback when the clip is not reachable). */
26141
+ id: string(),
26142
+ revision: string().nullable(),
26143
+ frames: number(),
26144
+ width: number(),
26145
+ height: number()
26146
+ });
26147
+ var NodeBenchRunnerInputSchema = object({
26148
+ runId: string().min(1),
26149
+ devices: array(NodeBenchmarkDevicePlanSchema).min(1),
26150
+ phases: array(NodeBenchmarkPhaseSchema).min(1),
26151
+ /** The full detail step tree root for the `pipeline` measurement is built on the node from these ids. */
26152
+ steps: array(string()).default([]),
26153
+ fpsPerStream: number().int().min(1).max(30),
26154
+ /** The runner stops on its own past this instant, whatever the hub does. */
26155
+ deadlineAtMs: number(),
26156
+ settleSec: number().min(0).max(60).default(NODE_BENCHMARK_DEFAULTS.settleSec),
26157
+ measureSec: number().min(2).max(300).default(NODE_BENCHMARK_DEFAULTS.measureSec),
26158
+ keepDownloadedModels: boolean().default(false)
26159
+ });
26160
+ var NodeBenchRunnerStateSchema = _enum([
26161
+ "running",
26162
+ "done",
26163
+ "failed",
26164
+ "aborted"
26165
+ ]);
26166
+ var NodeBenchRunnerStatusSchema = object({
26167
+ runId: string(),
26168
+ nodeId: string(),
26169
+ state: NodeBenchRunnerStateSchema,
26170
+ progress: NodeBenchProgressSchema.nullable(),
26171
+ /** Every finished cell so far — a run stopped half way keeps what it measured. */
26172
+ cells: array(NodeBenchCellSchema).readonly(),
26173
+ fingerprint: NodeBenchFingerprintSchema.nullable(),
26174
+ clip: NodeBenchClipSchema.nullable(),
26175
+ /** Cameras seen running on the node during the run (they share its pools). */
26176
+ activeCameraIds: array(number()).readonly(),
26177
+ /** Models the run downloaded and then deleted (not installed before). */
26178
+ deletedModels: array(string()).readonly(),
26179
+ error: string().nullable(),
26180
+ startedAtMs: number(),
26181
+ finishedAtMs: number().nullable()
26182
+ });
26183
+ var NodeBenchmarkStateSchema = _enum([
26184
+ "draining",
26185
+ "measuring",
26186
+ "restoring",
26187
+ "done",
26188
+ "failed",
26189
+ "aborted"
26190
+ ]);
26191
+ /** Why a run ended. */
26192
+ var NodeBenchmarkEndReasonSchema = _enum([
26193
+ "completed",
26194
+ "operator-abort",
26195
+ "deadline",
26196
+ "node-lost",
26197
+ "runner-lost",
26198
+ "hub-restart",
26199
+ "drain-timeout",
26200
+ "failed"
26201
+ ]);
26202
+ var NodeBenchmarkRunSchema = object({
26203
+ runId: string(),
26204
+ nodeId: string(),
26205
+ state: NodeBenchmarkStateSchema,
26206
+ plan: NodeBenchmarkPlanSchema,
26207
+ startedAtMs: number(),
26208
+ deadlineAtMs: number(),
26209
+ finishedAtMs: number().nullable(),
26210
+ endReason: NodeBenchmarkEndReasonSchema.nullable(),
26211
+ error: string().nullable(),
26212
+ /** Cameras moved off the node for the run. */
26213
+ moved: array(number()).readonly(),
26214
+ /** Cameras that stayed (their only frame source is the node). */
26215
+ staying: array(number()).readonly(),
26216
+ /** Something else ran on the node's pools during the run. */
26217
+ contaminated: boolean(),
26218
+ progress: NodeBenchProgressSchema.nullable(),
26219
+ resultIds: array(string()).readonly()
26220
+ });
26221
+ /** `getNodeBenchmarkStatus`: the active run (or the last one), and whether benchmark mode is on. */
26222
+ var NodeBenchmarkStatusSchema = object({
26223
+ /** The node the cluster is in benchmark mode for; null = none. */
26224
+ modeNodeId: string().nullable(),
26225
+ run: NodeBenchmarkRunSchema.nullable()
26226
+ });
26227
+ /**
26228
+ * One stored measurement — the only authority Auto tune and the automatic
26229
+ * shares read measured capacity from. Written by the orchestrator when a run
26230
+ * ends, never by anyone else.
26231
+ */
26232
+ var NodeBenchmarkResultSchema = object({
26233
+ id: string(),
26234
+ runId: string(),
26235
+ nodeId: string(),
26236
+ cell: NodeBenchCellSchema,
26237
+ fpsPerStream: number(),
26238
+ fingerprint: NodeBenchFingerprintSchema.nullable(),
26239
+ clip: NodeBenchClipSchema.nullable(),
26240
+ /** Other work shared the node's pools (a camera that could not move, or the hub's own duties). */
26241
+ contaminated: boolean(),
26242
+ stayingCameras: array(number()).readonly(),
26243
+ /** The run ended early; the cell itself completed. */
26244
+ partialRun: boolean(),
26245
+ measuredAtMs: number()
26246
+ });
26247
+ var ListNodeBenchmarkResultsInputSchema = object({
26248
+ nodeId: string().optional(),
26249
+ deviceKey: string().optional()
26250
+ });
26251
+ /** A result with its standing today: does it still beat the table? */
26252
+ var NodeBenchmarkResultViewSchema = NodeBenchmarkResultSchema.extend({
26253
+ /** `fresh` beats the table; `stale` falls back to it; `superseded` = a newer row covers the same cell. */
26254
+ standing: _enum([
26255
+ "fresh",
26256
+ "stale",
26257
+ "superseded"
26258
+ ]),
26259
+ staleWhy: _enum([
26260
+ "age",
26261
+ "runtime",
26262
+ "pool-tuning"
26263
+ ]).nullable()
26264
+ });
26265
+ object({
26266
+ runId: string(),
26267
+ nodeId: string(),
26268
+ startedAtMs: number(),
26269
+ deadlineAtMs: number(),
26270
+ plan: NodeBenchmarkPlanSchema,
26271
+ moved: array(number()).readonly(),
26272
+ staying: array(number()).readonly()
26273
+ });
26274
+ /** Candidate detectors per device, for the plan editor. */
26275
+ var NodeBenchmarkCandidatesSchema = object({
26276
+ nodeId: string(),
26277
+ reachable: boolean(),
26278
+ devices: array(object({
26279
+ deviceKey: string(),
26280
+ enabled: boolean(),
26281
+ available: boolean(),
26282
+ /** Ordered: what Auto tune would pick first, then the rest of the family by accuracy. */
26283
+ suggested: array(string()).readonly(),
26284
+ /** Every root detector the device has a build for. */
26285
+ all: array(string()).readonly(),
26286
+ /** The model the device runs now, when pinned. */
26287
+ currentModelId: string().nullable()
26288
+ })).readonly(),
26289
+ /** Detail steps the node's catalog offers under the root (for the `pipeline` measurement). */
26290
+ steps: array(object({
26291
+ id: string(),
26292
+ name: string(),
26293
+ slot: string()
26294
+ })).readonly()
26295
+ });
24751
26296
  object({
24752
26297
  activeCameras: number(),
24753
26298
  throttledCameras: number(),
@@ -25876,7 +27421,16 @@ method(RunnerCameraConfigSchema, object({ success: literal(true) }), { kind: "mu
25876
27421
  }), ParkedTrackFrameSchema.nullable()), method(object({
25877
27422
  deviceId: number(),
25878
27423
  trackId: string()
25879
- }), object({ released: number().int().nonnegative() }), { kind: "mutation" });
27424
+ }), object({ released: number().int().nonnegative() }), { kind: "mutation" }), method(NodeBenchRunnerInputSchema, object({
27425
+ accepted: literal(true),
27426
+ runId: string()
27427
+ }), {
27428
+ kind: "mutation",
27429
+ auth: "admin"
27430
+ }), method(object({ runId: string() }), NodeBenchRunnerStatusSchema.nullable(), { auth: "admin" }), method(object({ runId: string() }), object({ aborted: boolean() }), {
27431
+ kind: "mutation",
27432
+ auth: "admin"
27433
+ });
25880
27434
  var CameraPipelineConfigSchema = object({
25881
27435
  engine: PipelineEngineChoiceSchema.optional(),
25882
27436
  steps: array(PipelineStepInputSchema).readonly(),
@@ -26515,6 +28069,21 @@ method(object({
26515
28069
  }), method(PlacementStatsInputSchema, PlacementStatsSchema, { auth: "admin" }), method(SuggestSharesInputSchema, SuggestSharesResultSchema, { auth: "admin" }), method(_void(), EffectiveSharesSchema, { auth: "admin" }), method(SetShareSourceInputSchema, object({ success: literal(true) }), {
26516
28070
  kind: "mutation",
26517
28071
  auth: "admin"
28072
+ }), method(NodeBenchmarkPlanSchema, NodeBenchmarkPreflightSchema, { auth: "admin" }), method(NodeBenchmarkPlanSchema, discriminatedUnion("kind", [object({
28073
+ kind: literal("started"),
28074
+ runId: string()
28075
+ }), object({
28076
+ kind: literal("refused"),
28077
+ preflight: NodeBenchmarkPreflightSchema
28078
+ })]), {
28079
+ kind: "mutation",
28080
+ auth: "admin"
28081
+ }), method(_void(), NodeBenchmarkStatusSchema, { auth: "admin" }), method(object({ runId: string() }), object({ aborted: boolean() }), {
28082
+ kind: "mutation",
28083
+ auth: "admin"
28084
+ }), method(object({ nodeId: string() }), NodeBenchmarkCandidatesSchema, { auth: "admin" }), method(ListNodeBenchmarkResultsInputSchema, array(NodeBenchmarkResultViewSchema).readonly(), { auth: "admin" }), method(object({ id: string() }), object({ deleted: boolean() }), {
28085
+ kind: "mutation",
28086
+ auth: "admin"
26518
28087
  }), method(object({ deviceId: number() }), CameraPipelineSettingsSchema.nullable()), method(object({
26519
28088
  deviceId: number(),
26520
28089
  addonId: string(),
@@ -32720,6 +34289,9 @@ var CreateIntegrationInputSchema = object({
32720
34289
  enabled: boolean().optional(),
32721
34290
  info: record(string(), unknown()).optional(),
32722
34291
  settings: record(string(), unknown()).optional(),
34292
+ /** Keys of `settings` the form's schema declares secret (by type) — kept in
34293
+ * the keychain, not the table (D787). */
34294
+ secretKeys: array(string()).optional(),
32723
34295
  skipRestart: boolean().optional()
32724
34296
  });
32725
34297
  var UpdateIntegrationInputSchema = object({
@@ -32743,7 +34315,9 @@ method(_void(), array(IntegrationWithStateSchema)), method(object({ id: string()
32743
34315
  auth: "admin"
32744
34316
  }), method(object({ id: string() }), record(string(), unknown()), { auth: "admin" }), method(object({
32745
34317
  id: string(),
32746
- settings: record(string(), unknown())
34318
+ settings: record(string(), unknown()),
34319
+ /** Keys the form's schema declares secret (by type) — keychain-stored (D787). */
34320
+ secretKeys: array(string()).optional()
32747
34321
  }), object({ success: boolean() }), {
32748
34322
  kind: "mutation",
32749
34323
  auth: "admin"
@@ -40906,7 +42480,8 @@ var BaseDevice = class {
40906
42480
  this.role = options.role;
40907
42481
  this.parentDeviceId = ctx.parentDeviceId;
40908
42482
  const seedData = ctx.persistedConfig ?? {};
40909
- this.config = DeviceConfig.fromSchema(schema, (data) => ctx.persistConfig(data), seedData, ({ droppedKeys, issues }) => {
42483
+ const declaredSecretPaths = collectZodSecretPaths(schema);
42484
+ this.config = DeviceConfig.fromSchema(schema, (data) => ctx.persistConfig(data, { secretConfigPaths: declaredSecretPaths }), seedData, ({ droppedKeys, issues }) => {
40910
42485
  ctx.logger.warn("Device config recovery: dropping invalid persisted fields", {
40911
42486
  tags: {
40912
42487
  deviceId: ctx.id,
@@ -44595,6 +46170,90 @@ Object.freeze({
44595
46170
  addonId: null,
44596
46171
  access: "create"
44597
46172
  },
46173
+ "keychain.delete": {
46174
+ capName: "keychain",
46175
+ capScope: "system",
46176
+ addonId: null,
46177
+ access: "delete"
46178
+ },
46179
+ "keychain.getState": {
46180
+ capName: "keychain",
46181
+ capScope: "system",
46182
+ addonId: null,
46183
+ access: "view"
46184
+ },
46185
+ "keychain.listMeta": {
46186
+ capName: "keychain",
46187
+ capScope: "system",
46188
+ addonId: null,
46189
+ access: "view"
46190
+ },
46191
+ "keychain.put": {
46192
+ capName: "keychain",
46193
+ capScope: "system",
46194
+ addonId: null,
46195
+ access: "create"
46196
+ },
46197
+ "keychain.resolve": {
46198
+ capName: "keychain",
46199
+ capScope: "system",
46200
+ addonId: null,
46201
+ access: "view"
46202
+ },
46203
+ "keychainAdmin.deleteOrphans": {
46204
+ capName: "keychain-admin",
46205
+ capScope: "system",
46206
+ addonId: null,
46207
+ access: "delete"
46208
+ },
46209
+ "keychainAdmin.downloadRecoveryKey": {
46210
+ capName: "keychain-admin",
46211
+ capScope: "system",
46212
+ addonId: null,
46213
+ access: "create"
46214
+ },
46215
+ "keychainAdmin.listAudit": {
46216
+ capName: "keychain-admin",
46217
+ capScope: "system",
46218
+ addonId: null,
46219
+ access: "view"
46220
+ },
46221
+ "keychainAdmin.listSecrets": {
46222
+ capName: "keychain-admin",
46223
+ capScope: "system",
46224
+ addonId: null,
46225
+ access: "view"
46226
+ },
46227
+ "keychainAdmin.purgeRetiredKeys": {
46228
+ capName: "keychain-admin",
46229
+ capScope: "system",
46230
+ addonId: null,
46231
+ access: "delete"
46232
+ },
46233
+ "keychainAdmin.resetKeychain": {
46234
+ capName: "keychain-admin",
46235
+ capScope: "system",
46236
+ addonId: null,
46237
+ access: "delete"
46238
+ },
46239
+ "keychainAdmin.reveal": {
46240
+ capName: "keychain-admin",
46241
+ capScope: "system",
46242
+ addonId: null,
46243
+ access: "create"
46244
+ },
46245
+ "keychainAdmin.rotateMasterKey": {
46246
+ capName: "keychain-admin",
46247
+ capScope: "system",
46248
+ addonId: null,
46249
+ access: "create"
46250
+ },
46251
+ "keychainAdmin.status": {
46252
+ capName: "keychain-admin",
46253
+ capScope: "system",
46254
+ addonId: null,
46255
+ access: "view"
46256
+ },
44598
46257
  "lawnMowerControl.dock": {
44599
46258
  capName: "lawn-mower-control",
44600
46259
  capScope: "device",
@@ -45969,6 +47628,18 @@ Object.freeze({
45969
47628
  addonId: null,
45970
47629
  access: "create"
45971
47630
  },
47631
+ "pipelineAnalytics.addRetrainFrameFromRecording": {
47632
+ capName: "pipeline-analytics",
47633
+ capScope: "device",
47634
+ addonId: null,
47635
+ access: "create"
47636
+ },
47637
+ "pipelineAnalytics.addRetrainFramesToCollection": {
47638
+ capName: "pipeline-analytics",
47639
+ capScope: "device",
47640
+ addonId: null,
47641
+ access: "create"
47642
+ },
45972
47643
  "pipelineAnalytics.applyDeviceSettingsPatch": {
45973
47644
  capName: "pipeline-analytics",
45974
47645
  capScope: "device",
@@ -46017,12 +47688,24 @@ Object.freeze({
46017
47688
  addonId: null,
46018
47689
  access: "view"
46019
47690
  },
47691
+ "pipelineAnalytics.createRetrainCollection": {
47692
+ capName: "pipeline-analytics",
47693
+ capScope: "device",
47694
+ addonId: null,
47695
+ access: "create"
47696
+ },
46020
47697
  "pipelineAnalytics.deleteDeviceEvents": {
46021
47698
  capName: "pipeline-analytics",
46022
47699
  capScope: "device",
46023
47700
  addonId: null,
46024
47701
  access: "delete"
46025
47702
  },
47703
+ "pipelineAnalytics.deleteRetrainCollection": {
47704
+ capName: "pipeline-analytics",
47705
+ capScope: "device",
47706
+ addonId: null,
47707
+ access: "delete"
47708
+ },
46026
47709
  "pipelineAnalytics.deleteTracks": {
46027
47710
  capName: "pipeline-analytics",
46028
47711
  capScope: "device",
@@ -46227,6 +47910,24 @@ Object.freeze({
46227
47910
  addonId: null,
46228
47911
  access: "view"
46229
47912
  },
47913
+ "pipelineAnalytics.listRetrainAssistProfiles": {
47914
+ capName: "pipeline-analytics",
47915
+ capScope: "device",
47916
+ addonId: null,
47917
+ access: "view"
47918
+ },
47919
+ "pipelineAnalytics.listRetrainCollectionFrames": {
47920
+ capName: "pipeline-analytics",
47921
+ capScope: "device",
47922
+ addonId: null,
47923
+ access: "view"
47924
+ },
47925
+ "pipelineAnalytics.listRetrainCollections": {
47926
+ capName: "pipeline-analytics",
47927
+ capScope: "device",
47928
+ addonId: null,
47929
+ access: "view"
47930
+ },
46230
47931
  "pipelineAnalytics.listRetrainFrames": {
46231
47932
  capName: "pipeline-analytics",
46232
47933
  capScope: "device",
@@ -46275,6 +47976,12 @@ Object.freeze({
46275
47976
  addonId: null,
46276
47977
  access: "create"
46277
47978
  },
47979
+ "pipelineAnalytics.proposeRetrainAnnotationsWithLlm": {
47980
+ capName: "pipeline-analytics",
47981
+ capScope: "device",
47982
+ addonId: null,
47983
+ access: "create"
47984
+ },
46278
47985
  "pipelineAnalytics.pruneEvents": {
46279
47986
  capName: "pipeline-analytics",
46280
47987
  capScope: "device",
@@ -46329,6 +48036,18 @@ Object.freeze({
46329
48036
  addonId: null,
46330
48037
  access: "create"
46331
48038
  },
48039
+ "pipelineAnalytics.removeRetrainFrameFromCollection": {
48040
+ capName: "pipeline-analytics",
48041
+ capScope: "device",
48042
+ addonId: null,
48043
+ access: "delete"
48044
+ },
48045
+ "pipelineAnalytics.renameRetrainCollection": {
48046
+ capName: "pipeline-analytics",
48047
+ capScope: "device",
48048
+ addonId: null,
48049
+ access: "create"
48050
+ },
46332
48051
  "pipelineAnalytics.restageRetrainTrack": {
46333
48052
  capName: "pipeline-analytics",
46334
48053
  capScope: "device",
@@ -46617,6 +48336,12 @@ Object.freeze({
46617
48336
  addonId: null,
46618
48337
  access: "view"
46619
48338
  },
48339
+ "pipelineOrchestrator.abortNodeBenchmark": {
48340
+ capName: "pipeline-orchestrator",
48341
+ capScope: "system",
48342
+ addonId: null,
48343
+ access: "create"
48344
+ },
46620
48345
  "pipelineOrchestrator.applyAutoTune": {
46621
48346
  capName: "pipeline-orchestrator",
46622
48347
  capScope: "system",
@@ -46641,6 +48366,12 @@ Object.freeze({
46641
48366
  addonId: null,
46642
48367
  access: "create"
46643
48368
  },
48369
+ "pipelineOrchestrator.deleteNodeBenchmarkResult": {
48370
+ capName: "pipeline-orchestrator",
48371
+ capScope: "system",
48372
+ addonId: null,
48373
+ access: "delete"
48374
+ },
46644
48375
  "pipelineOrchestrator.getAgentLoad": {
46645
48376
  capName: "pipeline-orchestrator",
46646
48377
  capScope: "system",
@@ -46749,6 +48480,24 @@ Object.freeze({
46749
48480
  addonId: null,
46750
48481
  access: "view"
46751
48482
  },
48483
+ "pipelineOrchestrator.getNodeBenchmarkCandidates": {
48484
+ capName: "pipeline-orchestrator",
48485
+ capScope: "system",
48486
+ addonId: null,
48487
+ access: "view"
48488
+ },
48489
+ "pipelineOrchestrator.getNodeBenchmarkPreflight": {
48490
+ capName: "pipeline-orchestrator",
48491
+ capScope: "system",
48492
+ addonId: null,
48493
+ access: "view"
48494
+ },
48495
+ "pipelineOrchestrator.getNodeBenchmarkStatus": {
48496
+ capName: "pipeline-orchestrator",
48497
+ capScope: "system",
48498
+ addonId: null,
48499
+ access: "view"
48500
+ },
46752
48501
  "pipelineOrchestrator.getNodeInferenceDevices": {
46753
48502
  capName: "pipeline-orchestrator",
46754
48503
  capScope: "system",
@@ -46791,6 +48540,12 @@ Object.freeze({
46791
48540
  addonId: null,
46792
48541
  access: "view"
46793
48542
  },
48543
+ "pipelineOrchestrator.listNodeBenchmarkResults": {
48544
+ capName: "pipeline-orchestrator",
48545
+ capScope: "system",
48546
+ addonId: null,
48547
+ access: "view"
48548
+ },
46794
48549
  "pipelineOrchestrator.pauseForStorageMigration": {
46795
48550
  capName: "pipeline-orchestrator",
46796
48551
  capScope: "system",
@@ -46935,6 +48690,12 @@ Object.freeze({
46935
48690
  addonId: null,
46936
48691
  access: "create"
46937
48692
  },
48693
+ "pipelineOrchestrator.startNodeBenchmark": {
48694
+ capName: "pipeline-orchestrator",
48695
+ capScope: "system",
48696
+ addonId: null,
48697
+ access: "create"
48698
+ },
46938
48699
  "pipelineOrchestrator.suggestShares": {
46939
48700
  capName: "pipeline-orchestrator",
46940
48701
  capScope: "system",
@@ -46953,6 +48714,12 @@ Object.freeze({
46953
48714
  addonId: null,
46954
48715
  access: "create"
46955
48716
  },
48717
+ "pipelineRunner.abortNodeBench": {
48718
+ capName: "pipeline-runner",
48719
+ capScope: "system",
48720
+ addonId: null,
48721
+ access: "create"
48722
+ },
46956
48723
  "pipelineRunner.attachCamera": {
46957
48724
  capName: "pipeline-runner",
46958
48725
  capScope: "system",
@@ -47001,6 +48768,12 @@ Object.freeze({
47001
48768
  addonId: null,
47002
48769
  access: "view"
47003
48770
  },
48771
+ "pipelineRunner.getNodeBenchStatus": {
48772
+ capName: "pipeline-runner",
48773
+ capScope: "system",
48774
+ addonId: null,
48775
+ access: "view"
48776
+ },
47004
48777
  "pipelineRunner.getParkedTrackFrame": {
47005
48778
  capName: "pipeline-runner",
47006
48779
  capScope: "system",
@@ -47043,6 +48816,12 @@ Object.freeze({
47043
48816
  addonId: null,
47044
48817
  access: "create"
47045
48818
  },
48819
+ "pipelineRunner.startNodeBench": {
48820
+ capName: "pipeline-runner",
48821
+ capScope: "system",
48822
+ addonId: null,
48823
+ access: "create"
48824
+ },
47046
48825
  "plateGallery.assignPlate": {
47047
48826
  capName: "plate-gallery",
47048
48827
  capScope: "system",
@@ -51972,6 +53751,11 @@ Object.freeze({
51972
53751
  form: "single",
51973
53752
  optional: false
51974
53753
  }],
53754
+ "pipelineAnalytics.addRetrainFrameFromRecording": [{
53755
+ name: "deviceId",
53756
+ form: "single",
53757
+ optional: false
53758
+ }],
51975
53759
  "pipelineAnalytics.applyDeviceSettingsPatch": [{
51976
53760
  name: "deviceId",
51977
53761
  form: "single",
@@ -52162,6 +53946,11 @@ Object.freeze({
52162
53946
  form: "single",
52163
53947
  optional: false
52164
53948
  }],
53949
+ "pipelineAnalytics.proposeRetrainAnnotationsWithLlm": [{
53950
+ name: "deviceId",
53951
+ form: "single",
53952
+ optional: false
53953
+ }],
52165
53954
  "pipelineAnalytics.pruneEventsBefore": [{
52166
53955
  name: "deviceId",
52167
53956
  form: "single",