@camstack/addon-post-analysis 1.2.343 → 1.2.344

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (15) hide show
  1. package/dist/{clip-model-registry-DZz3e781.mjs → clip-model-registry-C44gfwjm.mjs} +1992 -57
  2. package/dist/{clip-model-registry-Cd_y9S4U.js → clip-model-registry-Ca_IbZyD.js} +1992 -57
  3. package/dist/embedding-encoder/index.js +1 -1
  4. package/dist/embedding-encoder/index.mjs +1 -1
  5. package/dist/pipeline-analytics/_stub.js +2 -2
  6. package/dist/pipeline-analytics/{_virtual_mf-localSharedImportMap___mfe_internal__addon_pipeline_analytics_widgets-DrdO3Pxp.mjs → _virtual_mf-localSharedImportMap___mfe_internal__addon_pipeline_analytics_widgets-D73dyYqt.mjs} +2 -2
  7. package/dist/pipeline-analytics/_virtual_mf___mfe_internal__addon_pipeline_analytics_widgets__loadShare___mf_0_camstack_mf_1_types__loadShare__.js-C-2BbuN4.mjs +26 -0
  8. package/dist/pipeline-analytics/_virtual_mf___mfe_internal__addon_pipeline_analytics_widgets__loadShare___mf_0_camstack_mf_1_ui_mf_2_library__loadShare__.js-ZZJLA-YE.mjs +26 -0
  9. package/dist/pipeline-analytics/{hostInit-DPNnWr-m.mjs → hostInit-h_8fvfFv.mjs} +2 -2
  10. package/dist/pipeline-analytics/index.js +1562 -138
  11. package/dist/pipeline-analytics/index.mjs +1562 -138
  12. package/dist/pipeline-analytics/remoteEntry.js +1 -1
  13. package/package.json +1 -1
  14. package/dist/pipeline-analytics/_virtual_mf___mfe_internal__addon_pipeline_analytics_widgets__loadShare___mf_0_camstack_mf_1_types__loadShare__.js-DEq-B6oq.mjs +0 -26
  15. package/dist/pipeline-analytics/_virtual_mf___mfe_internal__addon_pipeline_analytics_widgets__loadShare___mf_0_camstack_mf_1_ui_mf_2_library__loadShare__.js-CiTUMvVf.mjs +0 -26
@@ -1,5 +1,5 @@
1
1
  import { createHash } from "node:crypto";
2
- //#region ../types/dist/event-category-B_0XEcLF.mjs
2
+ //#region ../types/dist/event-category-DaIZi00R.mjs
3
3
  var EventCategory = /* @__PURE__ */ function(EventCategory) {
4
4
  EventCategory["SystemBoot"] = "system.boot";
5
5
  EventCategory["SystemAddonsReady"] = "system.addons-ready";
@@ -78,6 +78,13 @@ var EventCategory = /* @__PURE__ */ function(EventCategory) {
78
78
  */
79
79
  EventCategory["AddonLoadFailed"] = "addon.load-failed";
80
80
  /**
81
+ * A keychain value was stored or removed (D787). Carries the ref, its
82
+ * owner and the new version — NEVER the value. A process holding the ref
83
+ * drops its cached copy and the owning `BaseAddon` re-resolves its config.
84
+ * Telemetry (D8): a process that misses it still revalidates by version.
85
+ */
86
+ EventCategory["KeychainChanged"] = "keychain.changed";
87
+ /**
81
88
  * Addon recovered from a previous failure. Emitted when an addon
82
89
  * transitions from `failed` back to `healthy` (typically via the
83
90
  * monitor's auto-retry loop, or after manual `addons.retryLoad`).
@@ -5442,7 +5449,7 @@ var ZodIssueCode = {
5442
5449
  var ZodFirstPartyTypeKind;
5443
5450
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
5444
5451
  //#endregion
5445
- //#region ../types/dist/sleep-B0JG7-_F.mjs
5452
+ //#region ../types/dist/sleep-Cr5YOk3m.mjs
5446
5453
  /**
5447
5454
  * The audio chunk plane's byte format, and the ONE expansion from a coded
5448
5455
  * window to float samples (D455).
@@ -5521,6 +5528,97 @@ function buildAlawTable() {
5521
5528
  }
5522
5529
  buildUlawTable();
5523
5530
  buildAlawTable();
5531
+ /** Is this field's stored value a credential? */
5532
+ function isSecretConfigField(field) {
5533
+ if (field.type === "password") return true;
5534
+ return "secret" in field && field.secret === true;
5535
+ }
5536
+ /**
5537
+ * Is this field's value stored in the KEYCHAIN (D787)? Every secret field is,
5538
+ * by its TYPE, unless it opts out with `storage: 'inline'` — never by its name.
5539
+ */
5540
+ function isKeychainStoredField(field) {
5541
+ if (!isSecretConfigField(field)) return false;
5542
+ if (field.type === "textarea" && field.isJson === true) return false;
5543
+ return !("storage" in field && field.storage === "inline");
5544
+ }
5545
+ /**
5546
+ * What a settings blob holds where a secret used to be.
5547
+ *
5548
+ * A keychain-stored field never holds its value. It holds a self-describing
5549
+ * MARKER, `{"$secret":"secret://…","v":1}` — an object, never a string, so no
5550
+ * code can mistake it for a credential and no form can send it to a camera as
5551
+ * a password. The empty state is `null` / absent, never `''`.
5552
+ *
5553
+ * The same shapes travel to and from the admin UI:
5554
+ *
5555
+ * - read: `hydrateSchema` hands a secret field a {@link SecretFieldView}
5556
+ * (`{ $secret, v, set: true }`) or `null` — the browser learns whether a
5557
+ * value is set, never the value.
5558
+ * - write: an untouched field submits the view back unchanged (KEEP); a typed
5559
+ * value is a plain non-empty string (CHANGE); the Clear button submits
5560
+ * {@link SECRET_CLEAR} (CLEAR). `''`, `null` and the legacy redaction tokens
5561
+ * are KEEP — an empty string is what a defaults-fallback pushes back, and
5562
+ * treating it as "clear" is how a save destroyed a stored credential before.
5563
+ *
5564
+ * Pure and browser-safe.
5565
+ */
5566
+ var SECRET_CLEAR = { $secretClear: true };
5567
+ /** The `'***'` token D634 redaction writes for non-admins. */
5568
+ var LEGACY_DEVICE_REDACTION = "***";
5569
+ function isRecord$1(value) {
5570
+ return typeof value === "object" && value !== null && !Array.isArray(value);
5571
+ }
5572
+ function makeSecretMarker(ref) {
5573
+ return {
5574
+ $secret: ref,
5575
+ v: 1
5576
+ };
5577
+ }
5578
+ /** A stored marker: an object whose `$secret` is a non-empty string. */
5579
+ function isSecretMarker(value) {
5580
+ if (!isRecord$1(value)) return false;
5581
+ const ref = value["$secret"];
5582
+ return typeof ref === "string" && ref.length > 0;
5583
+ }
5584
+ function isSecretClear(value) {
5585
+ return isRecord$1(value) && value["$secretClear"] === true;
5586
+ }
5587
+ /**
5588
+ * The UI view of a stored secret field value: a marker becomes "set", inline
5589
+ * plaintext becomes "set (inline)", nothing becomes `null`. A value never
5590
+ * survives this function.
5591
+ */
5592
+ function toSecretFieldView(stored) {
5593
+ if (isSecretMarker(stored)) return {
5594
+ $secret: stored.$secret,
5595
+ v: 1,
5596
+ set: true
5597
+ };
5598
+ if (typeof stored === "string" && stored.length > 0) return {
5599
+ $secret: null,
5600
+ v: 1,
5601
+ set: true,
5602
+ inline: true
5603
+ };
5604
+ return null;
5605
+ }
5606
+ /**
5607
+ * Classify an incoming value for a secret path. Only a non-empty string that is
5608
+ * not a redaction token sets a value; only {@link SECRET_CLEAR} clears.
5609
+ * Everything else — a marker (ours or anyone's), a UI view, `''`, `null`,
5610
+ * `undefined`, a redaction token, a non-string — keeps what is stored.
5611
+ */
5612
+ function classifySecretWrite(incoming) {
5613
+ if (isSecretClear(incoming)) return { kind: "clear" };
5614
+ if (typeof incoming !== "string") return { kind: "keep" };
5615
+ if (incoming.length === 0) return { kind: "keep" };
5616
+ if (incoming === "__camstack_redacted__" || incoming === LEGACY_DEVICE_REDACTION) return { kind: "keep" };
5617
+ return {
5618
+ kind: "set",
5619
+ value: incoming
5620
+ };
5621
+ }
5524
5622
  Object.fromEntries([
5525
5623
  {
5526
5624
  id: "overview",
@@ -5692,33 +5790,19 @@ Object.fromEntries([
5692
5790
  function isValuelessField(field) {
5693
5791
  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";
5694
5792
  }
5695
- /**
5696
- * Merge a `ConfigUISchema` with a raw `values` record into a
5697
- * `ConfigUISchemaWithValues`. Used by every `get*Settings` backend endpoint
5698
- * before returning to the admin UI. Groups are walked recursively.
5699
- *
5700
- * For each leaf field:
5701
- * - structural fields (`separator`, `info`, `button`) pass through unchanged
5702
- * - other fields get `value = values[key] ?? field.default ?? null`
5703
- *
5704
- * Unknown keys in `values` (keys not declared in the schema) are silently
5705
- * ignored — they don't contribute to the output. Missing keys fall back to
5706
- * the schema default or `null`. This mirrors the old backend behaviour where
5707
- * `FormBuilder` rendered `values[key] ?? field.default`.
5708
- */
5709
- function hydrateSchema(schema, values) {
5793
+ function hydrateSchema(schema, values, options = {}) {
5710
5794
  return {
5711
5795
  ...schema.tabs ? { tabs: [...schema.tabs] } : {},
5712
5796
  sections: schema.sections.map((section) => ({
5713
5797
  ...section,
5714
- fields: section.fields.map((field) => hydrateField(field, values))
5798
+ fields: section.fields.map((field) => hydrateField(field, values, options))
5715
5799
  }))
5716
5800
  };
5717
5801
  }
5718
- function hydrateField(field, values) {
5802
+ function hydrateField(field, values, options) {
5719
5803
  if (isValuelessField(field)) return field;
5720
5804
  if (field.type === "group") {
5721
- const hydratedChildren = field.fields.map((child) => hydrateField(child, values));
5805
+ const hydratedChildren = field.fields.map((child) => hydrateField(child, values, options));
5722
5806
  return {
5723
5807
  ...field,
5724
5808
  fields: hydratedChildren
@@ -5727,7 +5811,7 @@ function hydrateField(field, values) {
5727
5811
  if (field.type === "sub-tabs") {
5728
5812
  const hydratedTabs = field.tabs.map((tab) => ({
5729
5813
  ...tab,
5730
- fields: tab.fields.map((child) => hydrateField(child, values))
5814
+ fields: tab.fields.map((child) => hydrateField(child, values, options))
5731
5815
  }));
5732
5816
  return {
5733
5817
  ...field,
@@ -5737,6 +5821,33 @@ function hydrateField(field, values) {
5737
5821
  const key = field.key;
5738
5822
  const storedValue = Object.prototype.hasOwnProperty.call(values, key) ? values[key] : void 0;
5739
5823
  const defaultValue = field.default;
5824
+ const asView = (v) => isSecretMarker(v) || options.inlineSecretsAsViews === true && v !== void 0;
5825
+ if (isKeychainStoredField(field) && asView(storedValue)) return {
5826
+ ...field,
5827
+ value: toSecretFieldView(storedValue)
5828
+ };
5829
+ if (isKeychainStoredField(field) && options.inlineSecretsAsViews === true) return {
5830
+ ...field,
5831
+ value: null
5832
+ };
5833
+ if (field.type === "editable-array" && Array.isArray(storedValue)) {
5834
+ const secretItemKeys = field.itemFields.filter((item) => "key" in item && isKeychainStoredField(item)).map((item) => "key" in item ? item.key : "");
5835
+ if (secretItemKeys.length > 0) {
5836
+ const rows = storedValue.map((row) => {
5837
+ if (row === null || typeof row !== "object" || Array.isArray(row)) return row;
5838
+ const out = { ...row };
5839
+ for (const k of secretItemKeys) {
5840
+ const v = Reflect.get(row, k);
5841
+ if (asView(v)) out[k] = toSecretFieldView(v);
5842
+ }
5843
+ return out;
5844
+ });
5845
+ return {
5846
+ ...field,
5847
+ value: rows
5848
+ };
5849
+ }
5850
+ }
5740
5851
  if (field.multiple) {
5741
5852
  const stored = Array.isArray(storedValue) ? storedValue : storedValue !== void 0 && storedValue !== null ? [storedValue] : [];
5742
5853
  const itemFallback = field.multiple.itemDefault !== void 0 ? field.multiple.itemDefault : defaultValue !== void 0 ? defaultValue : typeOf(field) === "string" ? "" : null;
@@ -5979,6 +6090,431 @@ function projectStore(store, perNodeKeys, nodeId) {
5979
6090
  }
5980
6091
  return out;
5981
6092
  }
6093
+ var GLOBAL_SCOPE = { kind: "global" };
6094
+ /** The scope every addon-wide (not per-node, not per-device) setting lives in. */
6095
+ function globalSecretScope() {
6096
+ return GLOBAL_SCOPE;
6097
+ }
6098
+ function encodeSegment(value) {
6099
+ return encodeURIComponent(value);
6100
+ }
6101
+ /**
6102
+ * The field path of a value inside an array item, addressed by the item's id:
6103
+ * `arrayItemFieldPath('providers', 'authentik', 'clientSecret')` →
6104
+ * `providers[authentik].clientSecret`.
6105
+ */
6106
+ function arrayItemFieldPath(arrayKey, itemId, fieldKey) {
6107
+ return `${arrayKey}[${encodeSegment(itemId)}].${fieldKey}`;
6108
+ }
6109
+ /** A write to a secret path could not be stored in the keychain, so it was refused. */
6110
+ var KeychainWriteRefusedError = class extends Error {
6111
+ fieldPath;
6112
+ constructor(fieldPath, cause) {
6113
+ super(`secret "${fieldPath}" was not saved: the keychain could not store it (${cause instanceof Error ? cause.message : String(cause)}). Nothing was written.`);
6114
+ this.fieldPath = fieldPath;
6115
+ this.name = "KeychainWriteRefusedError";
6116
+ }
6117
+ };
6118
+ var KEEP = { kind: "keep" };
6119
+ function isRecord(value) {
6120
+ return typeof value === "object" && value !== null && !Array.isArray(value);
6121
+ }
6122
+ function defaultMintId() {
6123
+ return globalThis.crypto.randomUUID();
6124
+ }
6125
+ /** Every marker ref anywhere under `value`. */
6126
+ function collectSecretMarkerRefs(value, out = []) {
6127
+ if (isSecretMarker(value)) {
6128
+ out.push(value.$secret);
6129
+ return out;
6130
+ }
6131
+ if (Array.isArray(value)) for (const item of value) collectSecretMarkerRefs(item, out);
6132
+ else if (isRecord(value)) for (const child of Object.values(value)) collectSecretMarkerRefs(child, out);
6133
+ return out;
6134
+ }
6135
+ async function storedValueEquals(secrets, marker, candidate) {
6136
+ const resolved = (await secrets.resolve([marker.$secret]))[marker.$secret];
6137
+ return resolved?.kind === "value" && resolved.value === candidate;
6138
+ }
6139
+ async function writeLeaf(ctx, incoming, stored, fieldPath) {
6140
+ const intent = classifySecretWrite(incoming);
6141
+ const ref = ctx.secrets.ref(ctx.scope, fieldPath);
6142
+ const storedIsOurs = isSecretMarker(stored) && stored.$secret === ref;
6143
+ if (intent.kind === "keep") return KEEP;
6144
+ if (intent.kind === "set" && !ctx.operatorWrite && typeof stored === "string" && stored === intent.value) return KEEP;
6145
+ if (intent.kind === "clear") {
6146
+ if (storedIsOurs) ctx.deletes.push(ref);
6147
+ return {
6148
+ kind: "value",
6149
+ value: null
6150
+ };
6151
+ }
6152
+ if (storedIsOurs && await storedValueEquals(ctx.secrets, stored, intent.value)) return {
6153
+ kind: "value",
6154
+ value: stored
6155
+ };
6156
+ try {
6157
+ await ctx.secrets.put(ref, intent.value);
6158
+ } catch (err) {
6159
+ throw new KeychainWriteRefusedError(fieldPath, err);
6160
+ }
6161
+ return {
6162
+ kind: "value",
6163
+ value: makeSecretMarker(ref)
6164
+ };
6165
+ }
6166
+ /** Apply a member result onto `out`: KEEP restores the stored member, or removes it. */
6167
+ function applyMember(out, key, result, storedParent) {
6168
+ if (result.kind === "value") {
6169
+ out[key] = result.value;
6170
+ return;
6171
+ }
6172
+ if (Object.prototype.hasOwnProperty.call(storedParent, key)) out[key] = storedParent[key];
6173
+ else delete out[key];
6174
+ }
6175
+ async function writeMembers(ctx, children, incoming, stored, pathOf) {
6176
+ const out = { ...incoming };
6177
+ for (const [member, node] of children) applyMember(out, member, await writeNode(ctx, node, incoming[member], stored[member], pathOf(member)), stored);
6178
+ return out;
6179
+ }
6180
+ function rowId(row, idKey) {
6181
+ const raw = row[idKey];
6182
+ if (typeof raw === "string" && raw.length > 0) return raw;
6183
+ if (typeof raw === "number" && Number.isFinite(raw)) return String(raw);
6184
+ return null;
6185
+ }
6186
+ async function writeArray(ctx, node, incoming, stored, fieldPath) {
6187
+ const storedRows = Array.isArray(stored) ? stored.filter(isRecord) : [];
6188
+ if (!Array.isArray(incoming)) {
6189
+ ctx.deletes.push(...collectSecretMarkerRefs(storedRows));
6190
+ return {
6191
+ kind: "value",
6192
+ value: incoming
6193
+ };
6194
+ }
6195
+ const storedById = /* @__PURE__ */ new Map();
6196
+ for (const row of storedRows) {
6197
+ const id = rowId(row, node.idKey);
6198
+ if (id !== null) storedById.set(id, row);
6199
+ }
6200
+ const kept = /* @__PURE__ */ new Set();
6201
+ const rows = [];
6202
+ for (const row of incoming) {
6203
+ if (!isRecord(row)) {
6204
+ rows.push(row);
6205
+ continue;
6206
+ }
6207
+ const id = rowId(row, node.idKey) ?? ctx.mintId();
6208
+ kept.add(id);
6209
+ const withId = {
6210
+ ...row,
6211
+ [node.idKey]: row[node.idKey] ?? id
6212
+ };
6213
+ if (rowId(withId, node.idKey) === null) withId[node.idKey] = id;
6214
+ const storedRow = storedById.get(id) ?? {};
6215
+ rows.push(await writeMembers(ctx, node.item, withId, storedRow, (member) => arrayItemFieldPath(fieldPath, id, member)));
6216
+ }
6217
+ for (const [id, row] of storedById) if (!kept.has(id)) ctx.deletes.push(...collectSecretMarkerRefs(row));
6218
+ return {
6219
+ kind: "value",
6220
+ value: rows
6221
+ };
6222
+ }
6223
+ async function writeNode(ctx, node, incoming, stored, fieldPath) {
6224
+ switch (node.kind) {
6225
+ case "leaf": return writeLeaf(ctx, incoming, stored, fieldPath);
6226
+ case "array": return writeArray(ctx, node, incoming, stored, fieldPath);
6227
+ case "object": {
6228
+ if (!isRecord(incoming)) {
6229
+ if (incoming === void 0) return KEEP;
6230
+ ctx.deletes.push(...collectSecretMarkerRefs(stored));
6231
+ return {
6232
+ kind: "value",
6233
+ value: incoming
6234
+ };
6235
+ }
6236
+ const storedObj = isRecord(stored) ? stored : {};
6237
+ return {
6238
+ kind: "value",
6239
+ value: await writeMembers(ctx, node.children, incoming, storedObj, (m) => `${fieldPath}.${m}`)
6240
+ };
6241
+ }
6242
+ }
6243
+ }
6244
+ /** Split a perNode-scoped key (`key@nodeId`). */
6245
+ function splitNodeKey(key) {
6246
+ const at = key.indexOf("@");
6247
+ return at <= 0 ? {
6248
+ base: key,
6249
+ nodeId: null
6250
+ } : {
6251
+ base: key.slice(0, at),
6252
+ nodeId: key.slice(at + 1)
6253
+ };
6254
+ }
6255
+ /** Rewrite a settings patch so no secret value reaches the blob. See the file doc. */
6256
+ async function transformSecretWrite(input) {
6257
+ const deletes = [];
6258
+ const base = {
6259
+ secrets: input.secrets,
6260
+ mintId: input.mintId ?? defaultMintId,
6261
+ deletes,
6262
+ operatorWrite: input.operatorWrite === true
6263
+ };
6264
+ const out = {};
6265
+ for (const [key, incoming] of Object.entries(input.patch)) {
6266
+ const { base: baseKey, nodeId } = splitNodeKey(key);
6267
+ const node = input.tree.get(baseKey);
6268
+ if (node === void 0) {
6269
+ out[key] = incoming;
6270
+ continue;
6271
+ }
6272
+ const scope = nodeId !== null && nodeId.length > 0 ? {
6273
+ kind: "node",
6274
+ nodeId
6275
+ } : input.scope ?? globalSecretScope();
6276
+ const result = await writeNode({
6277
+ ...base,
6278
+ scope
6279
+ }, node, incoming, input.stored[key], baseKey);
6280
+ if (result.kind === "value") out[key] = result.value;
6281
+ }
6282
+ return {
6283
+ patch: out,
6284
+ afterWrite: async () => {
6285
+ if (deletes.length === 0) return { orphaned: [] };
6286
+ try {
6287
+ await input.secrets.delete([...new Set(deletes)]);
6288
+ return { orphaned: [] };
6289
+ } catch {
6290
+ return { orphaned: [...new Set(deletes)] };
6291
+ }
6292
+ }
6293
+ };
6294
+ }
6295
+ /**
6296
+ * Replace every marker in `value` with its keychain value. Returns the SAME
6297
+ * reference when there is no marker (no allocation, no keychain call).
6298
+ */
6299
+ async function resolveSecretMarkers(value, secrets) {
6300
+ const refs = collectSecretMarkerRefs(value);
6301
+ if (refs.length === 0) return {
6302
+ value,
6303
+ unresolved: []
6304
+ };
6305
+ const answers = await secrets.resolve(refs);
6306
+ const unresolved = [];
6307
+ for (const ref of new Set(refs)) {
6308
+ const answer = answers[ref];
6309
+ if (answer === void 0) unresolved.push({
6310
+ ref,
6311
+ reason: "not-initialized"
6312
+ });
6313
+ else if (answer.kind === "unavailable") unresolved.push({
6314
+ ref,
6315
+ reason: answer.reason
6316
+ });
6317
+ else if (answer.kind === "missing" || answer.kind === "forbidden") unresolved.push({
6318
+ ref,
6319
+ reason: answer.kind
6320
+ });
6321
+ }
6322
+ const substitute = (v) => {
6323
+ if (isSecretMarker(v)) {
6324
+ const answer = answers[v.$secret];
6325
+ return answer?.kind === "value" ? {
6326
+ keep: true,
6327
+ value: answer.value
6328
+ } : {
6329
+ keep: false,
6330
+ value: void 0
6331
+ };
6332
+ }
6333
+ if (Array.isArray(v)) {
6334
+ const items = [];
6335
+ for (const item of v) {
6336
+ const s = substitute(item);
6337
+ if (s.keep) items.push(s.value);
6338
+ }
6339
+ return {
6340
+ keep: true,
6341
+ value: items
6342
+ };
6343
+ }
6344
+ if (isRecord(v)) {
6345
+ const out = {};
6346
+ for (const [k, child] of Object.entries(v)) {
6347
+ const s = substitute(child);
6348
+ if (s.keep) out[k] = s.value;
6349
+ }
6350
+ return {
6351
+ keep: true,
6352
+ value: out
6353
+ };
6354
+ }
6355
+ return {
6356
+ keep: true,
6357
+ value: v
6358
+ };
6359
+ };
6360
+ return {
6361
+ value: substitute(value).value,
6362
+ unresolved
6363
+ };
6364
+ }
6365
+ function touchesTree(tree, patch) {
6366
+ if (tree.size === 0) return false;
6367
+ for (const key of Object.keys(patch)) {
6368
+ const at = key.indexOf("@");
6369
+ if (tree.has(at > 0 ? key.slice(0, at) : key)) return true;
6370
+ }
6371
+ return false;
6372
+ }
6373
+ /** The blob as stored now; a failed read REFUSES the write instead of guessing. */
6374
+ async function readStoredAddonBlob(raw) {
6375
+ const threeWay = raw.readAddonStoreResult;
6376
+ if (threeWay === void 0) return raw.readAddonStore();
6377
+ const result = await threeWay.call(raw);
6378
+ if (result.kind === "failed") throw new Error(`settings write refused: the stored blob could not be read (${result.error})`);
6379
+ return result.kind === "missing" ? {} : result.value;
6380
+ }
6381
+ function createSecretAwareSettings(raw, opts) {
6382
+ const chains = /* @__PURE__ */ new Map();
6383
+ const serialize = (key, fn) => {
6384
+ const next = (chains.get(key) ?? Promise.resolve()).then(fn, fn);
6385
+ const tail = next.catch(() => void 0);
6386
+ chains.set(key, tail);
6387
+ tail.then(() => {
6388
+ if (chains.get(key) === tail) chains.delete(key);
6389
+ });
6390
+ return next;
6391
+ };
6392
+ const write = async (chainKey, tree, scope, patch, readStored, rawWrite) => {
6393
+ if (!touchesTree(tree, patch)) return rawWrite(patch);
6394
+ return serialize(chainKey, async () => {
6395
+ const stored = await readStored();
6396
+ const result = await transformSecretWrite({
6397
+ tree,
6398
+ secrets: opts.secrets,
6399
+ patch,
6400
+ stored,
6401
+ ...scope !== void 0 ? { scope } : {},
6402
+ operatorWrite: opts.isOperatorWrite?.() === true
6403
+ });
6404
+ if (Object.keys(result.patch).length > 0) await rawWrite(result.patch);
6405
+ const { orphaned } = await result.afterWrite();
6406
+ if (orphaned.length > 0) opts.onOrphaned(orphaned);
6407
+ });
6408
+ };
6409
+ const wrapped = {
6410
+ writeAddonStore: (patch) => write("addon", opts.addonTree(), void 0, patch, () => readStoredAddonBlob(raw), (p) => raw.writeAddonStore(p)),
6411
+ writeDeviceStore: (deviceId, patch) => write(`device:${deviceId}`, opts.deviceTree(), {
6412
+ kind: "device",
6413
+ deviceId
6414
+ }, patch, () => raw.readDeviceStore(deviceId), (p) => raw.writeDeviceStore(deviceId, p))
6415
+ };
6416
+ return new Proxy(raw, { get(target, prop, receiver) {
6417
+ if (prop === "writeAddonStore") return wrapped.writeAddonStore;
6418
+ if (prop === "writeDeviceStore") return wrapped.writeDeviceStore;
6419
+ const value = Reflect.get(target, prop, receiver);
6420
+ return typeof value === "function" ? value.bind(target) : value;
6421
+ } });
6422
+ }
6423
+ /** The context the addon sees: identical, except that its settings writes are secret-aware. */
6424
+ function withSecretAwareSettings(context, opts) {
6425
+ const raw = context.settings;
6426
+ if (raw === void 0) return context;
6427
+ const settings = createSecretAwareSettings(raw, opts);
6428
+ return new Proxy(context, { get(target, prop, receiver) {
6429
+ if (prop === "settings") return settings;
6430
+ return Reflect.get(target, prop, receiver);
6431
+ } });
6432
+ }
6433
+ var LEAF = { kind: "leaf" };
6434
+ var DEFAULT_ITEM_ID_KEY = "id";
6435
+ function collectFields(fields, out) {
6436
+ for (const field of fields) {
6437
+ if (field.type === "group") {
6438
+ collectFields(field.fields, out);
6439
+ continue;
6440
+ }
6441
+ if (field.type === "sub-tabs") {
6442
+ for (const tab of field.tabs) collectFields(tab.fields, out);
6443
+ continue;
6444
+ }
6445
+ if (field.type === "editable-array") {
6446
+ const item = /* @__PURE__ */ new Map();
6447
+ for (const itemField of field.itemFields) if ("key" in itemField && isKeychainStoredField(itemField)) item.set(itemField.key, LEAF);
6448
+ if (item.size > 0) out.set(field.key, {
6449
+ kind: "array",
6450
+ idKey: field.itemIdKey ?? DEFAULT_ITEM_ID_KEY,
6451
+ item
6452
+ });
6453
+ continue;
6454
+ }
6455
+ if (!("key" in field) || typeof field.key !== "string") continue;
6456
+ if (isKeychainStoredField(field)) out.set(field.key, LEAF);
6457
+ }
6458
+ }
6459
+ /** The secret tree a settings schema declares. */
6460
+ function secretTreeFromSchema(schema) {
6461
+ const out = /* @__PURE__ */ new Map();
6462
+ if (schema === null) return out;
6463
+ for (const section of schema.sections) collectFields(section.fields, out);
6464
+ return out;
6465
+ }
6466
+ /** Parse `a.b[id].c` into segments; throws on a malformed path (a declaration bug). */
6467
+ function parseSecretStatePath(path) {
6468
+ const segments = [];
6469
+ for (const raw of path.split(".")) {
6470
+ const m = /^([^[\]]+)(?:\[([^[\]]+)\])?$/.exec(raw);
6471
+ if (m === null || m[1] === void 0) throw new Error(`secretStatePaths: malformed path "${path}"`);
6472
+ segments.push(m[2] !== void 0 ? {
6473
+ key: m[1],
6474
+ idKey: m[2]
6475
+ } : { key: m[1] });
6476
+ }
6477
+ if (segments.length === 0) throw new Error(`secretStatePaths: empty path`);
6478
+ if (segments[segments.length - 1]?.idKey !== void 0) throw new Error(`secretStatePaths: "${path}" ends on an array — name the member that is secret`);
6479
+ return segments;
6480
+ }
6481
+ function insert(into, segments) {
6482
+ const [head, ...rest] = segments;
6483
+ if (head === void 0) return;
6484
+ if (rest.length === 0) {
6485
+ into.set(head.key, LEAF);
6486
+ return;
6487
+ }
6488
+ const existing = into.get(head.key);
6489
+ if (head.idKey !== void 0) {
6490
+ const item = new Map(existing?.kind === "array" ? existing.item : []);
6491
+ insert(item, rest);
6492
+ into.set(head.key, {
6493
+ kind: "array",
6494
+ idKey: head.idKey,
6495
+ item
6496
+ });
6497
+ return;
6498
+ }
6499
+ const children = new Map(existing?.kind === "object" ? existing.children : []);
6500
+ insert(children, rest);
6501
+ into.set(head.key, {
6502
+ kind: "object",
6503
+ children
6504
+ });
6505
+ }
6506
+ /** Add hidden-state paths (`secretStatePaths`) to a schema-derived tree. */
6507
+ function mergeSecretStatePaths(tree, paths) {
6508
+ if (paths.length === 0) return tree;
6509
+ const out = new Map(tree);
6510
+ for (const path of paths) insert(out, parseSecretStatePath(path));
6511
+ return out;
6512
+ }
6513
+ /** First retry of a secret the keychain could not serve; doubles to {@link SECRET_RETRY_MAX_MS}. */
6514
+ var SECRET_RETRY_FIRST_MS = 5e3;
6515
+ var SECRET_RETRY_MAX_MS = 5 * 6e4;
6516
+ /** Coalesces a burst of `keychain.changed` events into one re-resolve. */
6517
+ var SECRET_CHANGE_DEBOUNCE_MS = 250;
5982
6518
  /**
5983
6519
  * Base class for CamStack addons. Eliminates settings boilerplate:
5984
6520
  *
@@ -6048,6 +6584,25 @@ var BaseAddon = class {
6048
6584
  settingsStoreReady = false;
6049
6585
  /** Default config values. Provided via constructor. */
6050
6586
  defaults;
6587
+ /**
6588
+ * Hidden-state paths that hold secrets (D787) — values the addon writes
6589
+ * itself (`updateGlobalSettings`, `state()`) that no form field declares.
6590
+ * Stored in the keychain exactly like a `password` field. Syntax:
6591
+ * `'snapshotSigningKey'`, `'identity.pincode'`, `'tokens[userId].accessToken'`
6592
+ * (`key[<id field>]` addresses array items by id, never by index).
6593
+ */
6594
+ secretStatePaths = [];
6595
+ _addonSecretTree = null;
6596
+ _deviceSecretTree = null;
6597
+ /** Refs the last resolved config pointed at — a change to one re-resolves. */
6598
+ _configSecretRefs = /* @__PURE__ */ new Set();
6599
+ _unresolvedSecrets = [];
6600
+ _secretRetryTimer = null;
6601
+ _secretRetryDelayMs = SECRET_RETRY_FIRST_MS;
6602
+ _secretChangeTimer = null;
6603
+ _secretChangeUnsub = null;
6604
+ /** >0 while an OPERATOR's settings write is being applied. */
6605
+ _operatorWriteDepth = 0;
6051
6606
  constructor(defaults) {
6052
6607
  this.defaults = defaults;
6053
6608
  this._config = { ...defaults };
@@ -6083,8 +6638,18 @@ var BaseAddon = class {
6083
6638
  return this._config;
6084
6639
  }
6085
6640
  async initialize(context) {
6086
- this._ctx = context;
6641
+ const secrets = context.secrets;
6642
+ this._ctx = secrets !== void 0 ? withSecretAwareSettings(context, {
6643
+ secrets,
6644
+ addonTree: () => this.addonSecretTree(),
6645
+ deviceTree: () => this.deviceSecretTree(),
6646
+ onOrphaned: (refs) => context.logger.warn("keychain refs dropped by a settings write could not be deleted", { meta: { refs: [...refs] } }),
6647
+ isOperatorWrite: () => this._operatorWriteDepth > 0
6648
+ }) : context;
6087
6649
  await this.resolveConfig();
6650
+ if (secrets !== void 0) this._secretChangeUnsub = secrets.onChange((ref) => {
6651
+ if (this._configSecretRefs.has(ref)) this.scheduleSecretReresolve(SECRET_CHANGE_DEBOUNCE_MS);
6652
+ });
6088
6653
  const result = await this.onInitialize();
6089
6654
  this.emitLifecycle(EventCategory.AddonStarted);
6090
6655
  const normalized = normalizeAddonInitResult(result);
@@ -6117,6 +6682,12 @@ var BaseAddon = class {
6117
6682
  */
6118
6683
  async onHubReachable() {}
6119
6684
  async shutdown() {
6685
+ this._secretChangeUnsub?.();
6686
+ this._secretChangeUnsub = null;
6687
+ if (this._secretRetryTimer !== null) clearTimeout(this._secretRetryTimer);
6688
+ if (this._secretChangeTimer !== null) clearTimeout(this._secretChangeTimer);
6689
+ this._secretRetryTimer = null;
6690
+ this._secretChangeTimer = null;
6120
6691
  this.emitLifecycle(EventCategory.AddonStopped);
6121
6692
  if (this.autoEmitReadiness) this.emitReadinessForProviders("down");
6122
6693
  await this.onShutdown();
@@ -6195,7 +6766,7 @@ var BaseAddon = class {
6195
6766
  return hydrateSchema(schema, overlay ? {
6196
6767
  ...projected,
6197
6768
  ...overlay
6198
- } : projected);
6769
+ } : projected, { inlineSecretsAsViews: true });
6199
6770
  }
6200
6771
  /**
6201
6772
  * The integration-level view of this addon's settings: exactly the sections
@@ -6244,7 +6815,7 @@ var BaseAddon = class {
6244
6815
  return hydrateSchema({
6245
6816
  ...schema,
6246
6817
  sections
6247
- }, projected);
6818
+ }, projected, { inlineSecretsAsViews: true });
6248
6819
  }
6249
6820
  /**
6250
6821
  * The raw addon store PROJECTED onto the target node's bare per-node keys:
@@ -6298,18 +6869,50 @@ var BaseAddon = class {
6298
6869
  value: result.value[key]
6299
6870
  };
6300
6871
  }
6872
+ /**
6873
+ * The OPERATOR's write — a settings form or an admin API call, dispatched by
6874
+ * the kernel. Identical to {@link updateGlobalSettings}, except that a secret
6875
+ * the operator sends is stored as sent even when it equals a pre-keychain
6876
+ * inline value: the operator re-entering a password is a change, an addon
6877
+ * writing back what it read is not (D787).
6878
+ */
6879
+ async updateGlobalSettingsAsOperator(patch, nodeId) {
6880
+ this._operatorWriteDepth++;
6881
+ try {
6882
+ await this.applyGlobalPatch(patch, nodeId);
6883
+ } finally {
6884
+ this._operatorWriteDepth--;
6885
+ }
6886
+ }
6301
6887
  async updateGlobalSettings(patch, nodeId) {
6888
+ await this.applyGlobalPatch(patch, nodeId);
6889
+ }
6890
+ /**
6891
+ * REMOVE stored secrets — their keychain values and their markers (D787).
6892
+ *
6893
+ * Writing `''` to a secret field KEEPS what is stored (an empty string is
6894
+ * what a defaults fallback writes back, and it must never destroy a
6895
+ * credential), so code that means "forget this token" says so here. Without
6896
+ * a keychain (an older kernel) it writes `''`, as such code always did.
6897
+ */
6898
+ async clearSecrets(keys, nodeId) {
6899
+ const tree = this.addonSecretTree();
6900
+ const keychain = this._ctx?.secrets !== void 0;
6901
+ const patch = {};
6902
+ for (const key of keys) patch[key] = keychain && tree.has(key) ? SECRET_CLEAR : "";
6903
+ await this.applyGlobalPatch(patch, nodeId);
6904
+ }
6905
+ async applyGlobalPatch(barePatch, nodeId) {
6302
6906
  const keys = this.perNodeKeys();
6303
6907
  const localNode = normalizeNodeId(this._ctx?.kernel?.localNodeId);
6304
6908
  const target = normalizeNodeId(nodeId ?? this._ctx?.kernel?.localNodeId);
6305
- const barePatch = patch;
6306
6909
  const scoped = keys.size > 0 ? scopePatch(barePatch, keys, target) : barePatch;
6307
6910
  await this._ctx?.settings?.writeAddonStore(scoped);
6308
6911
  if (target !== localNode) return;
6309
6912
  await this.resolveConfig();
6310
6913
  await this.onConfigChanged();
6311
6914
  this.emitLifecycle(EventCategory.AddonUpdated, { level: "global" });
6312
- this.maybeAutoRestart(patch, this.globalSettingsSchema());
6915
+ this.maybeAutoRestart(Object.keys(barePatch), this.globalSettingsSchema());
6313
6916
  }
6314
6917
  /**
6315
6918
  * The set of field keys the global settings schema declares `perNode: true`
@@ -6334,7 +6937,7 @@ var BaseAddon = class {
6334
6937
  * time to return its response before the addon is torn down and
6335
6938
  * re-initialised by `AddonRegistryService.restartAddon`.
6336
6939
  */
6337
- maybeAutoRestart(patch, schema) {
6940
+ maybeAutoRestart(patchKeys, schema) {
6338
6941
  if (!schema) return;
6339
6942
  const restartKeys = /* @__PURE__ */ new Set();
6340
6943
  for (const section of schema.sections) for (const field of section.fields) {
@@ -6342,13 +6945,13 @@ var BaseAddon = class {
6342
6945
  if (field.requiresRestart) restartKeys.add(field.key);
6343
6946
  }
6344
6947
  if (restartKeys.size === 0) return;
6345
- if (!Object.keys(patch).some((k) => restartKeys.has(k))) return;
6948
+ if (!patchKeys.some((k) => restartKeys.has(k))) return;
6346
6949
  const ctx = this._ctx;
6347
6950
  if (!ctx) return;
6348
6951
  const addonId = ctx.id;
6349
6952
  setImmediate(() => {
6350
6953
  ctx.api.addons?.restartAddon?.mutate({ addonId }).then(() => {
6351
- ctx.logger.info("addon auto-restart triggered by restart-required setting change", { meta: { changedFields: Object.keys(patch).filter((k) => restartKeys.has(k)) } });
6954
+ ctx.logger.info("addon auto-restart triggered by restart-required setting change", { meta: { changedFields: patchKeys.filter((k) => restartKeys.has(k)) } });
6352
6955
  }).catch((err) => {
6353
6956
  ctx.logger.error("addon auto-restart failed", { meta: { error: err instanceof Error ? err.message : String(err) } });
6354
6957
  });
@@ -6357,7 +6960,7 @@ var BaseAddon = class {
6357
6960
  async getDeviceSettings(deviceId) {
6358
6961
  const schema = this.deviceSettingsSchema();
6359
6962
  if (!schema) return { sections: [] };
6360
- return hydrateSchema(schema, await this._ctx?.settings?.readDeviceStore(deviceId) ?? {});
6963
+ return hydrateSchema(schema, await this._ctx?.settings?.readDeviceStore(deviceId) ?? {}, { inlineSecretsAsViews: true });
6361
6964
  }
6362
6965
  async updateDeviceSettings(deviceId, patch) {
6363
6966
  await this._ctx?.settings?.writeDeviceStore(deviceId, patch);
@@ -6487,7 +7090,7 @@ var BaseAddon = class {
6487
7090
  * selection at boot (absent scoped key ⇒ the constructor default wins).
6488
7091
  */
6489
7092
  async resolveConfig() {
6490
- const stored = await this.readAddonStoreWithRetry();
7093
+ const stored = await this.resolveStoredSecrets(await this.readAddonStoreWithRetry());
6491
7094
  const perNode = this.perNodeKeys();
6492
7095
  const localNode = normalizeNodeId(this._ctx?.kernel?.localNodeId);
6493
7096
  const resolved = { ...this.defaults };
@@ -6512,7 +7115,7 @@ var BaseAddon = class {
6512
7115
  key,
6513
7116
  schema,
6514
7117
  fallback,
6515
- read: () => this.readAddonStoreWithRetry(),
7118
+ read: async () => this.resolveStoredSecrets(await this.readAddonStoreWithRetry()),
6516
7119
  write: async (patch) => {
6517
7120
  await this._ctx?.settings?.writeAddonStore(patch);
6518
7121
  },
@@ -6529,7 +7132,7 @@ var BaseAddon = class {
6529
7132
  key,
6530
7133
  schema,
6531
7134
  fallback,
6532
- read: async () => await this._ctx?.settings?.readDeviceStore(deviceId) ?? {},
7135
+ read: async () => this.resolveStoredSecrets(await this._ctx?.settings?.readDeviceStore(deviceId) ?? {}, false),
6533
7136
  write: async (patch) => {
6534
7137
  await this._ctx?.settings?.writeDeviceStore(deviceId, patch);
6535
7138
  },
@@ -6541,6 +7144,70 @@ var BaseAddon = class {
6541
7144
  } })
6542
7145
  });
6543
7146
  }
7147
+ /** The addon store's secret tree: schema fields by TYPE, plus `secretStatePaths`. */
7148
+ addonSecretTree() {
7149
+ this._addonSecretTree ??= mergeSecretStatePaths(secretTreeFromSchema(this.globalSettingsSchema()), this.secretStatePaths);
7150
+ return this._addonSecretTree;
7151
+ }
7152
+ deviceSecretTree() {
7153
+ this._deviceSecretTree ??= secretTreeFromSchema(this.deviceSettingsSchema());
7154
+ return this._deviceSecretTree;
7155
+ }
7156
+ /**
7157
+ * Secrets of this addon's stored config that could not be resolved on the
7158
+ * last read, with why. Non-empty means the addon is running WITHOUT them —
7159
+ * an addon whose function needs one should report itself degraded rather
7160
+ * than start on an empty credential.
7161
+ */
7162
+ get unresolvedSecrets() {
7163
+ return this._unresolvedSecrets;
7164
+ }
7165
+ /**
7166
+ * Substitute every keychain marker in a stored blob with its value. With no
7167
+ * keychain (no `ctx.secrets`) or no marker, the blob comes back unchanged.
7168
+ * An unresolvable value is LEFT OUT (never `''`), logged by ref — never by
7169
+ * value — and, when the cause can pass, retried with backoff. Nothing is
7170
+ * ever written back from here.
7171
+ */
7172
+ async resolveStoredSecrets(blob, trackForConfig = true) {
7173
+ const secrets = this._ctx?.secrets;
7174
+ if (secrets === void 0) return blob;
7175
+ const refs = collectSecretMarkerRefs(blob);
7176
+ if (trackForConfig) this._configSecretRefs = new Set(refs);
7177
+ if (refs.length === 0) {
7178
+ if (trackForConfig) this._unresolvedSecrets = [];
7179
+ return blob;
7180
+ }
7181
+ const { value, unresolved } = await resolveSecretMarkers(blob, secrets);
7182
+ if (trackForConfig) {
7183
+ this._unresolvedSecrets = unresolved;
7184
+ if (unresolved.length > 0) {
7185
+ this._ctx?.logger?.error?.("secret unavailable — running without it, will retry", { meta: { secrets: unresolved.map((u) => ({
7186
+ ref: u.ref,
7187
+ reason: u.reason
7188
+ })) } });
7189
+ if (unresolved.some((u) => u.reason !== "missing" && u.reason !== "forbidden")) {
7190
+ this.scheduleSecretReresolve(this._secretRetryDelayMs);
7191
+ this._secretRetryDelayMs = Math.min(this._secretRetryDelayMs * 2, SECRET_RETRY_MAX_MS);
7192
+ }
7193
+ } else this._secretRetryDelayMs = SECRET_RETRY_FIRST_MS;
7194
+ }
7195
+ return value;
7196
+ }
7197
+ /** Re-resolve the config (a keychain-only change, or a retry) and apply it. */
7198
+ scheduleSecretReresolve(delayMs) {
7199
+ const timerOf = delayMs === SECRET_CHANGE_DEBOUNCE_MS ? "_secretChangeTimer" : "_secretRetryTimer";
7200
+ if (this[timerOf] !== null) return;
7201
+ const timer = setTimeout(() => {
7202
+ this[timerOf] = null;
7203
+ if (this._ctx === null) return;
7204
+ this.resolveConfig().then(() => this.onConfigChanged()).catch((err) => {
7205
+ this._ctx?.logger?.error?.("re-resolving secrets failed", { meta: { error: err instanceof Error ? err.message : String(err) } });
7206
+ });
7207
+ }, delayMs);
7208
+ timer.unref?.();
7209
+ this[timerOf] = timer;
7210
+ }
6544
7211
  /**
6545
7212
  * Wrap `ctx.settings.readAddonStore()` with a short retry budget so a
6546
7213
  * transient settings-store outage (mid-restart of sqlite-settings, tsx-watch
@@ -7305,6 +7972,69 @@ var deviceOpsCapability = {
7305
7972
  getRawState: method(object({ deviceId: number() }), RawStateResultSchema.nullable(), { auth: "protected" })
7306
7973
  }
7307
7974
  };
7975
+ function defOf(schema) {
7976
+ return schema._zod?.def ?? {};
7977
+ }
7978
+ function declaredHere(schema) {
7979
+ return globalRegistry.get(schema)?.secret === true;
7980
+ }
7981
+ /** Wrapper kinds whose `innerType` is the field itself. */
7982
+ var WRAPPERS = new Set([
7983
+ "optional",
7984
+ "nullable",
7985
+ "default",
7986
+ "prefault",
7987
+ "catch",
7988
+ "readonly",
7989
+ "nonoptional"
7990
+ ]);
7991
+ /**
7992
+ * The schema layers that make up ONE field: the schema itself and every
7993
+ * wrapper below it (optional / default / nullable / readonly / catch), plus
7994
+ * both sides of a pipe (`z.preprocess` puts the real schema on `out`,
7995
+ * `.transform` on `in`).
7996
+ */
7997
+ function layersOf(schema) {
7998
+ const out = [];
7999
+ const queue = [schema];
8000
+ while (queue.length > 0) {
8001
+ const s = queue.shift();
8002
+ if (!s || out.includes(s)) continue;
8003
+ out.push(s);
8004
+ const def = defOf(s);
8005
+ if (def.type !== void 0 && WRAPPERS.has(def.type) && def.innerType) queue.push(def.innerType);
8006
+ if (def.type === "pipe") {
8007
+ if (def.in) queue.push(def.in);
8008
+ if (def.out) queue.push(def.out);
8009
+ }
8010
+ }
8011
+ return out;
8012
+ }
8013
+ /** True when any layer of this field declares `.meta({ secret: true })`. */
8014
+ function isZodSecret(schema) {
8015
+ return layersOf(schema).some(declaredHere);
8016
+ }
8017
+ /**
8018
+ * Every declared secret path in a config schema: dotted keys, `[]` for "each
8019
+ * element of this array" (`connection.password`, `rows[].token`). A declared
8020
+ * object or array is reported as one path and not descended into — everything
8021
+ * under it is secret.
8022
+ */
8023
+ function collectZodSecretPaths(schema, prefix = "") {
8024
+ if (isZodSecret(schema)) return prefix.length > 0 ? [prefix] : [];
8025
+ const paths = [];
8026
+ for (const layer of layersOf(schema)) {
8027
+ const def = defOf(layer);
8028
+ if (def.type === "object" && def.shape) for (const [key, child] of Object.entries(def.shape)) paths.push(...collectZodSecretPaths(child, prefix ? `${prefix}.${key}` : key));
8029
+ else if (def.type === "array" && def.element) paths.push(...collectZodSecretPaths(def.element, `${prefix}[]`));
8030
+ else if (def.type === "union" && def.options) for (const option of def.options) paths.push(...collectZodSecretPaths(option, prefix));
8031
+ else if (def.type === "intersection") {
8032
+ if (def.left) paths.push(...collectZodSecretPaths(def.left, prefix));
8033
+ if (def.right) paths.push(...collectZodSecretPaths(def.right, prefix));
8034
+ }
8035
+ }
8036
+ return [...new Set(paths)];
8037
+ }
7308
8038
  /**
7309
8039
  * AUTO-GENERATED by scripts/generate-device-scoped-caps.ts — DO NOT EDIT.
7310
8040
  *
@@ -16286,6 +17016,254 @@ id: union([string(), number()]) }), {
16286
17016
  })
16287
17017
  }
16288
17018
  };
17019
+ /**
17020
+ * `keychain` — the hub's encrypted store of secret values (D787).
17021
+ *
17022
+ * Settings blobs never hold a secret: they hold a marker
17023
+ * `{"$secret":"secret://<owner>/<scope>/<fieldPath>","v":1}` and the value
17024
+ * lives here, AES-256-GCM under a data key that a master key wraps. This cap
17025
+ * is the OWNER's door to its own values: every method is owner-checked
17026
+ * against the CALLER, never against anything the caller claims.
17027
+ *
17028
+ * Who the caller is: the transport stamps `callerAddonId` into the args of a
17029
+ * call that crossed a process (the parent `LocalChildRegistry` from the UDS
17030
+ * connection, the agent from its child's connection carried in
17031
+ * `$hub-cap-fwd`'s envelope). A stamp always overwrites; a wire call with no
17032
+ * stamp has its claim stripped. Only a hub in-process caller may state its own
17033
+ * identity — `ctx.secrets` does that with the addon id closed over. This is
17034
+ * identity against BUGS and misrouting, not against a malicious addon (every
17035
+ * runner is the same OS user): see the threat model in
17036
+ * `docs/design/2026-10-08-secrets-keychain.md`.
17037
+ *
17038
+ * `callerAddonId` is deliberately NOT in any input schema: the tRPC router
17039
+ * parses the input, so a session can never supply it, and the internal mount
17040
+ * floors every method to admin anyway (D240).
17041
+ *
17042
+ * Internal: addons reach it through `ctx.secrets`, never directly.
17043
+ */
17044
+ /** Why a value cannot be served right now. Never folded into "missing". */
17045
+ var KeychainUnavailableReasonSchema = _enum([
17046
+ "key-missing",
17047
+ "wrong-key",
17048
+ "key-file-unreadable",
17049
+ "store-unavailable",
17050
+ "not-initialized",
17051
+ "decrypt-failed"
17052
+ ]);
17053
+ var KeychainStateSchema = discriminatedUnion("state", [object({ state: literal("ready") }), object({
17054
+ state: literal("locked"),
17055
+ reason: KeychainUnavailableReasonSchema
17056
+ })]);
17057
+ var KeychainResolveEntrySchema = discriminatedUnion("kind", [
17058
+ object({
17059
+ kind: literal("value"),
17060
+ value: string(),
17061
+ version: number().int()
17062
+ }),
17063
+ object({ kind: literal("missing") }),
17064
+ object({
17065
+ kind: literal("unavailable"),
17066
+ reason: KeychainUnavailableReasonSchema
17067
+ }),
17068
+ object({ kind: literal("forbidden") })
17069
+ ]);
17070
+ var KeychainResolveResultSchema = record(string(), KeychainResolveEntrySchema);
17071
+ /** Metadata of one stored value — never the value. */
17072
+ var KeychainSecretMetaSchema = object({
17073
+ ref: string(),
17074
+ owner: string(),
17075
+ /** Formatted scope (`global`, `node/<id>`, `device/<id>`, …). */
17076
+ scope: string(),
17077
+ fieldPath: string(),
17078
+ version: number().int(),
17079
+ createdAt: number(),
17080
+ updatedAt: number(),
17081
+ /** `addon:<id>` | `user:<id>` | `system`. */
17082
+ updatedBy: string(),
17083
+ /** Coarse — written at most once an hour per ref. `null` = never read. */
17084
+ lastReadAt: number().nullable()
17085
+ });
17086
+ var RefListSchema = array(string().min(1)).max(512);
17087
+ var keychainCapability = {
17088
+ name: "keychain",
17089
+ scope: "system",
17090
+ mode: "singleton",
17091
+ internal: true,
17092
+ methods: {
17093
+ /** Store (or replace) the caller's value at `ref`. Refused while locked. */
17094
+ put: method(object({
17095
+ ref: string().min(1),
17096
+ value: string().min(1)
17097
+ }), object({
17098
+ ref: string(),
17099
+ version: number().int()
17100
+ }), {
17101
+ kind: "mutation",
17102
+ auth: "admin"
17103
+ }),
17104
+ /**
17105
+ * Resolve the caller's refs in one round-trip. A locked keychain answers
17106
+ * `unavailable` per ref — never `missing`, never an empty value.
17107
+ */
17108
+ resolve: method(object({ refs: RefListSchema }), KeychainResolveResultSchema, { auth: "admin" }),
17109
+ /** Remove the caller's refs. Unknown refs are ignored. */
17110
+ delete: method(object({ refs: RefListSchema }), object({ deleted: number().int() }), {
17111
+ kind: "mutation",
17112
+ auth: "admin"
17113
+ }),
17114
+ /** The caller's own refs, metadata only. */
17115
+ listMeta: method(object({}), array(KeychainSecretMetaSchema).readonly(), { auth: "admin" }),
17116
+ /** Whether values can be served — the save path refuses a write while locked. */
17117
+ getState: method(object({}), KeychainStateSchema, { auth: "admin" })
17118
+ }
17119
+ };
17120
+ var KeychainKeySourceSchema = object({
17121
+ kind: _enum([
17122
+ "config-file",
17123
+ "previous-config-file",
17124
+ "platform",
17125
+ "default-file"
17126
+ ]),
17127
+ /** File sources only — a path is not a secret. */
17128
+ path: string().optional(),
17129
+ /**
17130
+ * True when a whole-volume backup of the data directory carries this key
17131
+ * next to the database it protects (the default file). The page warns.
17132
+ */
17133
+ sharesBackupWithDatabase: boolean()
17134
+ });
17135
+ var KeychainStatusSchema = object({
17136
+ keychain: KeychainStateSchema,
17137
+ /** The source of the master key in use; `null` while locked. */
17138
+ keySource: KeychainKeySourceSchema.nullable(),
17139
+ /** The source configured to be primary — differs from `keySource` while a rotation is pending. */
17140
+ configuredSource: KeychainKeySourceSchema,
17141
+ /** Short fingerprint of the master key in use (`HMAC(KEK, label)`, 16 hex). */
17142
+ fingerprint: string().nullable(),
17143
+ activeKeyId: string().nullable(),
17144
+ /**
17145
+ * The keychain unlocked with a NON-primary source: the configured primary
17146
+ * key is not the one that wraps the data key yet. `rotateMasterKey` moves it.
17147
+ */
17148
+ rotationPending: boolean(),
17149
+ /** Wrapped copies of the data key under a previous master key, kept until purged. */
17150
+ retiredWraps: number().int(),
17151
+ recoveryKeyDownloadedAt: number().nullable(),
17152
+ secretCount: number().int()
17153
+ });
17154
+ /**
17155
+ * Whether a stored value is still pointed at by its owner's settings.
17156
+ * `unknown` is a first-class answer: a scope whose blob could not be read is
17157
+ * never reported as an orphan (and never deleted as one).
17158
+ */
17159
+ var KeychainSecretUsageSchema = _enum([
17160
+ "in-use",
17161
+ "orphan",
17162
+ "unknown"
17163
+ ]);
17164
+ var KeychainAdminSecretSchema = KeychainSecretMetaSchema.extend({ usage: KeychainSecretUsageSchema });
17165
+ var KeychainAuditActionSchema = _enum([
17166
+ "put",
17167
+ "delete",
17168
+ "reveal",
17169
+ "rotate-master-key",
17170
+ "purge-retired-keys",
17171
+ "download-recovery-key",
17172
+ "delete-orphans",
17173
+ "reset",
17174
+ "initialize"
17175
+ ]);
17176
+ var KeychainAuditEntrySchema = object({
17177
+ id: string(),
17178
+ at: number(),
17179
+ action: KeychainAuditActionSchema,
17180
+ /** `addon:<id>` | `user:<id>` | `system`. */
17181
+ actor: string(),
17182
+ ref: string().nullable(),
17183
+ detail: string().nullable()
17184
+ });
17185
+ var keychainAdminCapability = {
17186
+ name: "keychain-admin",
17187
+ scope: "system",
17188
+ mode: "singleton",
17189
+ methods: {
17190
+ status: method(object({}), KeychainStatusSchema, { auth: "admin" }),
17191
+ listSecrets: method(object({}), array(KeychainAdminSecretSchema).readonly(), { auth: "admin" }),
17192
+ listAudit: method(object({ limit: number().int().min(1).max(500).optional() }), array(KeychainAuditEntrySchema).readonly(), { auth: "admin" }),
17193
+ /**
17194
+ * Show one value to the operator. Audited. The UI hides it again after a
17195
+ * few seconds; nothing caches it.
17196
+ */
17197
+ reveal: method(object({ ref: string().min(1) }), object({
17198
+ value: string(),
17199
+ version: number().int()
17200
+ }), {
17201
+ kind: "mutation",
17202
+ auth: "admin",
17203
+ caller: "required"
17204
+ }),
17205
+ /** Delete refs no owner points at any more. Re-checked here; `unknown` is kept. */
17206
+ deleteOrphans: method(object({ refs: array(string().min(1)).max(1e3) }), object({
17207
+ deleted: array(string()).readonly(),
17208
+ kept: array(object({
17209
+ ref: string(),
17210
+ usage: KeychainSecretUsageSchema
17211
+ })).readonly()
17212
+ }), {
17213
+ kind: "mutation",
17214
+ auth: "admin",
17215
+ caller: "required"
17216
+ }),
17217
+ /**
17218
+ * Wrap the data key under the configured primary master key.
17219
+ *
17220
+ * Pending rotation (the keychain unlocked with a previous source): re-wrap
17221
+ * under the primary. Otherwise, with the default file as primary: generate
17222
+ * a new master key, write it there, re-wrap. A file or OS-keychain primary
17223
+ * that is already in use cannot be replaced from here — put the new key at
17224
+ * the source, keep the old one as `keychain.previousKeyFile`, restart, and
17225
+ * rotate. No value is re-encrypted either way; the previous wrap is kept
17226
+ * (retired) until purged.
17227
+ */
17228
+ rotateMasterKey: method(object({}), object({
17229
+ fingerprint: string(),
17230
+ keySource: KeychainKeySourceSchema
17231
+ }), {
17232
+ kind: "mutation",
17233
+ auth: "admin",
17234
+ caller: "required"
17235
+ }),
17236
+ purgeRetiredKeys: method(object({}), object({ purged: number().int() }), {
17237
+ kind: "mutation",
17238
+ auth: "admin",
17239
+ caller: "required"
17240
+ }),
17241
+ /** The master key, base64. Audited; marks the recovery copy as taken. */
17242
+ downloadRecoveryKey: method(object({}), object({
17243
+ key: string(),
17244
+ fingerprint: string(),
17245
+ keySource: KeychainKeySourceSchema
17246
+ }), {
17247
+ kind: "mutation",
17248
+ auth: "admin",
17249
+ caller: "required"
17250
+ }),
17251
+ /**
17252
+ * Lost-key recovery: archive every stored value into a
17253
+ * `keychain:secrets-orphaned-<ts>` table and start over with a new data
17254
+ * key. Every secret field then reads "not set". Requires the typed
17255
+ * confirmation {@link KEYCHAIN_RESET_CONFIRMATION}.
17256
+ */
17257
+ resetKeychain: method(object({ confirm: literal("RESET KEYCHAIN") }), object({
17258
+ archivedCollection: string().nullable(),
17259
+ archived: number().int()
17260
+ }), {
17261
+ kind: "mutation",
17262
+ auth: "admin",
17263
+ caller: "required"
17264
+ })
17265
+ }
17266
+ };
16289
17267
  var decoderCapability = {
16290
17268
  name: "decoder",
16291
17269
  scope: "system",
@@ -17641,7 +18619,11 @@ var DeviceRegisterPayloadSchema = object({
17641
18619
  var DeviceRemovePayloadSchema = object({ deviceId: number() });
17642
18620
  var DevicePersistConfigPayloadSchema = object({
17643
18621
  deviceId: number(),
17644
- data: record(string(), unknown())
18622
+ data: record(string(), unknown()),
18623
+ /** The paths the device's schema declares secret (D783), when the caller
18624
+ * knows them — those values are kept in the keychain, not the blob (D787).
18625
+ * Absent: the paths the device last reported at `registerDevice` apply. */
18626
+ secretConfigPaths: array(string()).optional()
17645
18627
  });
17646
18628
  /** What a migration actually did, per switch. `unreachable` is a first-class
17647
18629
  * answer: a camera that could not be asked is not a camera that was silenced. */
@@ -26893,8 +27875,23 @@ var RetrainMacroClassSchema = _enum([
26893
27875
  ]);
26894
27876
  /** A subject to learn, or a phantom to unlearn (taught by OMISSION). */
26895
27877
  var RetrainAnnotationKindSchema = _enum(["subject", "model_error"]);
26896
- /** Did a human draw this box, or did the assist propose it? */
26897
- var RetrainAnnotationSourceSchema = _enum(["operator", "assist"]);
27878
+ /**
27879
+ * Where a box came from. A machine-sourced box is a DRAFT on the page until
27880
+ * the operator confirms it; once saved it keeps its source as provenance.
27881
+ *
27882
+ * - `operator` — drawn by hand.
27883
+ * - `assist` — proposed by a detector run on the copy (the camera's own
27884
+ * model, or a larger teacher model).
27885
+ * - `pipeline` — the box the live pipeline actually drew on that frame, read
27886
+ * back from the track store (never a re-run).
27887
+ * - `llm` — proposed by a vision-capable LLM profile.
27888
+ */
27889
+ var RetrainAnnotationSourceSchema = _enum([
27890
+ "operator",
27891
+ "assist",
27892
+ "pipeline",
27893
+ "llm"
27894
+ ]);
26898
27895
  /** Normalised `[0,1]` rectangle against the FULL frame — the canonical form. */
26899
27896
  var RetrainBboxSchema = object({
26900
27897
  x: number(),
@@ -26912,7 +27909,8 @@ var RetrainBboxSchema = object({
26912
27909
  */
26913
27910
  var RetrainAnnotationSchema = object({
26914
27911
  id: string(),
26915
- trackId: string(),
27912
+ /** The frame's track. Absent on a recording still, which has none. */
27913
+ trackId: string().optional(),
26916
27914
  deviceId: number(),
26917
27915
  /** The COPY in retrain storage — never the source track's media key. */
26918
27916
  mediaKey: string(),
@@ -26961,13 +27959,47 @@ var RetrainFrameCandidateSchema = object({
26961
27959
  * fail, whatever became of the original. */
26962
27960
  copied: boolean()
26963
27961
  });
27962
+ /**
27963
+ * One box the live pipeline drew on a copied frame — what a correction starts
27964
+ * from. Derived when the frame is listed, from the track store: the subject
27965
+ * box recorded on the source media row when there is one, else the track
27966
+ * position nearest the frame's capture time. Never stored as an annotation
27967
+ * until the operator confirms it.
27968
+ */
27969
+ var RetrainPipelineBoxSchema = object({
27970
+ /** Normalised `[0,1]` against the full frame. */
27971
+ bbox: RetrainBboxSchema,
27972
+ macroClass: RetrainMacroClassSchema,
27973
+ label: string().optional(),
27974
+ subLabel: string().optional(),
27975
+ /** The detection score of the position used, when it was recorded. */
27976
+ score: number().optional(),
27977
+ /** The root model that produced the track, when it was recorded. */
27978
+ modelId: string().optional(),
27979
+ trackId: string(),
27980
+ /** `subject-box`: recorded on this very frame. `position`: the track's
27981
+ * position nearest the capture time, `deltaMs` away. */
27982
+ basis: _enum(["subject-box", "position"]),
27983
+ deltaMs: number()
27984
+ });
27985
+ /**
27986
+ * Where a retrain frame came from: a TRACK's stored media (copy-on-select),
27987
+ * or the RECORDING at an instant — the frame a model saw nothing in has no
27988
+ * track at all.
27989
+ */
27990
+ var RetrainFrameOriginSchema = _enum(["track", "recording"]);
26964
27991
  /** A frame the dataset OWNS: bytes copied at selection time. */
26965
27992
  var RetrainFrameSchema = object({
26966
27993
  frameId: string(),
26967
27994
  deviceId: number(),
26968
- trackId: string(),
26969
- /** Provenance only. It may already point at nothing — that is expected. */
26970
- sourceMediaId: number().int(),
27995
+ origin: RetrainFrameOriginSchema,
27996
+ /** The track it was copied from. Absent on a recording still. */
27997
+ trackId: string().optional(),
27998
+ /** Provenance only. It may already point at nothing — that is expected.
27999
+ * Absent on a recording still. */
28000
+ sourceMediaId: number().int().optional(),
28001
+ /** A recording still: the playhead instant it was taken at. */
28002
+ epochMs: number().optional(),
26971
28003
  sourceKind: MediaFileKindEnum,
26972
28004
  sizeBytes: number().int(),
26973
28005
  width: number().int(),
@@ -26978,7 +28010,12 @@ var RetrainFrameSchema = object({
26978
28010
  /** The operator's "every subject in this frame is boxed". Detector
26979
28011
  * evaluation keeps only complete frames: an unboxed subject would count as
26980
28012
  * a false positive. */
26981
- complete: boolean()
28013
+ complete: boolean(),
28014
+ /** The boxes the pipeline drew on this frame. Present on list answers;
28015
+ * empty when nothing the track store holds can be placed on it. */
28016
+ pipelineBoxes: array(RetrainPipelineBoxSchema).readonly().optional(),
28017
+ /** The named collections this frame belongs to. Present on list answers. */
28018
+ collectionIds: array(string()).readonly().optional()
26982
28019
  });
26983
28020
  /** Why a copy-on-select could not be honoured — named, never a silent skip. */
26984
28021
  var RetrainCopyRefusalSchema = _enum([
@@ -27009,6 +28046,8 @@ var RetrainFrameListSchema = object({
27009
28046
  var RetrainExportFilterSchema = object({
27010
28047
  deviceIds: array(number()).optional(),
27011
28048
  frameIds: array(string()).max(2e4).optional(),
28049
+ /** Only frames in at least one of these named collections. */
28050
+ collectionIds: array(string()).max(200).optional(),
27012
28051
  batchId: string().optional(),
27013
28052
  /** Only frames the operator marked complete (all subjects boxed). */
27014
28053
  completeOnly: boolean().optional()
@@ -27073,6 +28112,109 @@ var RetrainAssistResultSchema = discriminatedUnion("kind", [object({
27073
28112
  reason: string(),
27074
28113
  detail: string().optional()
27075
28114
  })]);
28115
+ /** A named set over the retrain corpus — membership only, it owns no pixels. */
28116
+ var RetrainCollectionSchema = object({
28117
+ id: string(),
28118
+ name: string(),
28119
+ createdAt: number(),
28120
+ frameCount: number().int()
28121
+ });
28122
+ var RetrainCollectionCreateResultSchema = discriminatedUnion("kind", [object({
28123
+ kind: literal("created"),
28124
+ collection: RetrainCollectionSchema
28125
+ }), object({
28126
+ kind: literal("refused"),
28127
+ reason: _enum(["empty-name", "duplicate-name"])
28128
+ })]);
28129
+ var RetrainCollectionRenameResultSchema = discriminatedUnion("kind", [object({
28130
+ kind: literal("renamed"),
28131
+ collection: RetrainCollectionSchema
28132
+ }), object({
28133
+ kind: literal("refused"),
28134
+ reason: _enum([
28135
+ "empty-name",
28136
+ "duplicate-name",
28137
+ "unknown-collection"
28138
+ ])
28139
+ })]);
28140
+ /**
28141
+ * The outcome of adding the frame at a recording instant. Every refusal is
28142
+ * named: `still-unavailable` (not recording, a gap, or an undecodable frame —
28143
+ * `detail` says which), `still-busy` (the recorder is at its decode bound; try
28144
+ * again), `unreadable-image`, `write-failed`, `unknown-collection`.
28145
+ */
28146
+ var AddRetrainFrameFromRecordingResultSchema = discriminatedUnion("kind", [object({
28147
+ kind: literal("added"),
28148
+ collectionId: string(),
28149
+ frame: RetrainFrameSchema,
28150
+ /** The moment was already in the dataset; nothing was decoded. */
28151
+ reused: boolean()
28152
+ }), object({
28153
+ kind: literal("refused"),
28154
+ reason: _enum([
28155
+ "unknown-collection",
28156
+ "still-unavailable",
28157
+ "still-busy",
28158
+ "unreadable-image",
28159
+ "write-failed"
28160
+ ]),
28161
+ detail: string().optional()
28162
+ })]);
28163
+ /** A vision LLM profile the AI assist may use, and where it sends the frame. */
28164
+ var RetrainAssistProfileSchema = object({
28165
+ id: string(),
28166
+ name: string(),
28167
+ model: string(),
28168
+ kind: string(),
28169
+ /** `true` when the frame would leave the house (a cloud vendor, or an
28170
+ * endpoint that is not on the local network). The page confirms each such
28171
+ * run, and the provider refuses one without `allowCloud`. */
28172
+ leavesHouse: boolean()
28173
+ });
28174
+ /** A box the AI assist proposed: a draft, plus the model's own reason. */
28175
+ var RetrainLlmProposalSchema = RetrainAnnotationDraftSchema.extend({ reason: string() });
28176
+ /** What the AI assist said about a box that was already on the canvas. */
28177
+ var RetrainLlmReviewSchema = object({
28178
+ /** The `ref` the page sent the box under. */
28179
+ ref: string(),
28180
+ verdict: _enum([
28181
+ "confirmed",
28182
+ "wrong-class",
28183
+ "not-an-object",
28184
+ "uncertain"
28185
+ ]),
28186
+ suggestedClass: RetrainMacroClassSchema.optional(),
28187
+ reason: string()
28188
+ });
28189
+ /**
28190
+ * The AI assist's answer. `proposed` carries drafts (`source: 'llm'`, the
28191
+ * model and its confidence) and reviews; items the model got wrong (a box off
28192
+ * the frame, an unasked class, an unknown ref) are dropped and counted in
28193
+ * `rejected`. A whole answer that is not the schema is `malformed-answer`.
28194
+ */
28195
+ var RetrainLlmAssistResultSchema = discriminatedUnion("kind", [object({
28196
+ kind: literal("proposed"),
28197
+ profileId: string(),
28198
+ model: string(),
28199
+ /** The frame was sent outside the house for this answer. */
28200
+ leftHouse: boolean(),
28201
+ proposals: array(RetrainLlmProposalSchema).readonly(),
28202
+ reviews: array(RetrainLlmReviewSchema).readonly(),
28203
+ rejected: number().int()
28204
+ }), object({
28205
+ kind: literal("refused"),
28206
+ reason: _enum([
28207
+ "unknown-frame",
28208
+ "unreadable-frame",
28209
+ "unknown-profile",
28210
+ "profile-disabled",
28211
+ "no-vision",
28212
+ "cloud-not-confirmed",
28213
+ "llm-error",
28214
+ "malformed-answer"
28215
+ ]),
28216
+ detail: string().optional()
28217
+ })]);
27076
28218
  /** The outcome of a lifecycle move owned by the retrain page. */
27077
28219
  var RetrainTransitionResultSchema = object({
27078
28220
  trackId: string(),
@@ -28289,7 +29431,7 @@ var pipelineAnalyticsCapability = {
28289
29431
  * a frame leaves the dataset before export. */
28290
29432
  deselectRetrainFrame: method(object({
28291
29433
  deviceId: number(),
28292
- trackId: string(),
29434
+ trackId: string().optional(),
28293
29435
  frameId: string()
28294
29436
  }), object({
28295
29437
  removed: boolean(),
@@ -28332,7 +29474,8 @@ var pipelineAnalyticsCapability = {
28332
29474
  */
28333
29475
  proposeRetrainAnnotations: method(object({
28334
29476
  deviceId: number(),
28335
- trackId: string(),
29477
+ /** The frame's track, when it has one — checked against the frame. */
29478
+ trackId: string().optional(),
28336
29479
  frameId: string(),
28337
29480
  subject: RetrainAssistSubjectSchema,
28338
29481
  /** Which node runs it. Absent ⇒ wherever an unowned call lands. */
@@ -28341,8 +29484,12 @@ var pipelineAnalyticsCapability = {
28341
29484
  kind: "mutation",
28342
29485
  auth: "admin"
28343
29486
  }),
28344
- /** Every annotation on a track, oldest first. */
28345
- listRetrainAnnotations: method(object({ trackId: string() }), array(RetrainAnnotationSchema).readonly(), {
29487
+ /** Every annotation on a track, or on named frames (a recording still has
29488
+ * no track), oldest first. One of the two is required. */
29489
+ listRetrainAnnotations: method(object({
29490
+ trackId: string().optional(),
29491
+ frameIds: array(string()).max(2e3).optional()
29492
+ }), array(RetrainAnnotationSchema).readonly(), {
28346
29493
  kind: "query",
28347
29494
  auth: "admin"
28348
29495
  }),
@@ -28361,7 +29508,8 @@ var pipelineAnalyticsCapability = {
28361
29508
  */
28362
29509
  saveRetrainAnnotations: method(object({
28363
29510
  deviceId: number(),
28364
- trackId: string(),
29511
+ /** The frame's track, when it has one — checked against the frame. */
29512
+ trackId: string().optional(),
28365
29513
  frameId: string(),
28366
29514
  annotations: array(RetrainAnnotationDraftSchema)
28367
29515
  }), array(RetrainAnnotationSchema).readonly(), {
@@ -28424,7 +29572,7 @@ var pipelineAnalyticsCapability = {
28424
29572
  */
28425
29573
  setRetrainFrameComplete: method(object({
28426
29574
  deviceId: number(),
28427
- trackId: string(),
29575
+ trackId: string().optional(),
28428
29576
  frameId: string(),
28429
29577
  complete: boolean()
28430
29578
  }), RetrainFrameSchema, {
@@ -28447,6 +29595,115 @@ var pipelineAnalyticsCapability = {
28447
29595
  auth: "admin",
28448
29596
  timeoutMs: 60 * 6e4
28449
29597
  }),
29598
+ /** The enabled, vision-capable LLM profiles, each saying whether a frame
29599
+ * sent to it leaves the house. */
29600
+ listRetrainAssistProfiles: method(object({}), array(RetrainAssistProfileSchema).readonly(), {
29601
+ kind: "query",
29602
+ auth: "admin"
29603
+ }),
29604
+ /**
29605
+ * Ask a vision LLM (the `llm` capability) about ONE copied frame: list the
29606
+ * objects of `classes` with boxes, and review the boxes already on the
29607
+ * canvas (sent by `ref`). Answers drafts (`source: 'llm'`) and reviews —
29608
+ * nothing is stored, nothing is accepted. A profile that sends the frame
29609
+ * outside the house is refused unless `allowCloud` says the operator
29610
+ * confirmed this run.
29611
+ */
29612
+ proposeRetrainAnnotationsWithLlm: method(object({
29613
+ deviceId: number(),
29614
+ trackId: string().optional(),
29615
+ frameId: string(),
29616
+ profileId: string(),
29617
+ classes: array(RetrainMacroClassSchema).min(1),
29618
+ boxes: array(object({
29619
+ ref: string(),
29620
+ bbox: RetrainBboxSchema,
29621
+ macroClass: RetrainMacroClassSchema,
29622
+ label: string().optional()
29623
+ })).max(50),
29624
+ allowCloud: boolean()
29625
+ }), RetrainLlmAssistResultSchema, {
29626
+ kind: "mutation",
29627
+ auth: "admin",
29628
+ timeoutMs: 18e4
29629
+ }),
29630
+ /**
29631
+ * Create a named collection — a set over the retrain corpus ("packages
29632
+ * porch night"). Names are unique case-insensitively and never empty;
29633
+ * both refusals are named.
29634
+ */
29635
+ createRetrainCollection: method(object({ name: string().max(120) }), RetrainCollectionCreateResultSchema, {
29636
+ kind: "mutation",
29637
+ auth: "admin"
29638
+ }),
29639
+ /** Every collection, newest first, with its frame count. */
29640
+ listRetrainCollections: method(object({}), array(RetrainCollectionSchema).readonly(), {
29641
+ kind: "query",
29642
+ auth: "admin"
29643
+ }),
29644
+ renameRetrainCollection: method(object({
29645
+ id: string(),
29646
+ name: string().max(120)
29647
+ }), RetrainCollectionRenameResultSchema, {
29648
+ kind: "mutation",
29649
+ auth: "admin"
29650
+ }),
29651
+ /**
29652
+ * Delete a collection. Its recording stills that no other collection
29653
+ * holds are deleted with their annotations (nothing else reaches them);
29654
+ * frames copied from tracks always stay in the dataset.
29655
+ */
29656
+ deleteRetrainCollection: method(object({ id: string() }), object({
29657
+ deleted: boolean(),
29658
+ removedFrames: number().int()
29659
+ }), {
29660
+ kind: "mutation",
29661
+ auth: "admin"
29662
+ }),
29663
+ /**
29664
+ * Add the frame at a recording instant to a collection — the frame the
29665
+ * model may have seen NOTHING in. The recorder re-decodes the native
29666
+ * frame at `epochMs`; the dataset copies it (trackless, durable). The same
29667
+ * moment twice is one copy. Every refusal is named.
29668
+ */
29669
+ addRetrainFrameFromRecording: method(object({
29670
+ collectionId: string(),
29671
+ deviceId: number(),
29672
+ epochMs: number()
29673
+ }), AddRetrainFrameFromRecordingResultSchema, {
29674
+ kind: "mutation",
29675
+ auth: "admin",
29676
+ timeoutMs: 6e4
29677
+ }),
29678
+ /** Add frames already in the dataset to a collection. */
29679
+ addRetrainFramesToCollection: method(object({
29680
+ collectionId: string(),
29681
+ frameIds: array(string()).min(1).max(500)
29682
+ }), object({
29683
+ added: number().int(),
29684
+ alreadyMember: number().int(),
29685
+ unknownFrameIds: array(string()).readonly()
29686
+ }), {
29687
+ kind: "mutation",
29688
+ auth: "admin"
29689
+ }),
29690
+ /** Remove a frame from a collection. A recording still left in no
29691
+ * collection is deleted with its annotations (`deletedFrame`). */
29692
+ removeRetrainFrameFromCollection: method(object({
29693
+ collectionId: string(),
29694
+ frameId: string()
29695
+ }), object({
29696
+ removed: boolean(),
29697
+ deletedFrame: boolean()
29698
+ }), {
29699
+ kind: "mutation",
29700
+ auth: "admin"
29701
+ }),
29702
+ /** The frames of a collection, with their pipeline boxes. */
29703
+ listRetrainCollectionFrames: method(object({ collectionId: string() }), array(RetrainFrameSchema).readonly(), {
29704
+ kind: "query",
29705
+ auth: "admin"
29706
+ }),
28450
29707
  /**
28451
29708
  * The media an EVENT owns.
28452
29709
  *
@@ -29386,13 +30643,31 @@ var RecommendationReasonSchema = discriminatedUnion("kind", [
29386
30643
  object({
29387
30644
  kind: literal("no-family-build"),
29388
30645
  format: ModelFormatSchema$1
30646
+ }),
30647
+ object({
30648
+ kind: literal("kept-custom-pin"),
30649
+ modelId: string(),
30650
+ deviceKey: string()
29389
30651
  })
29390
30652
  ]);
30653
+ /** Why a device is left exactly as it is, whatever the plan would pick (D786). */
30654
+ var KeptReasonSchema = _enum(["custom-pin"]);
30655
+ /**
30656
+ * Where a choice's latency came from (D791): this node's own benchmark
30657
+ * result, or the hardware-class table. Measured on the node beats the table.
30658
+ */
30659
+ var LatencySourceSchema = discriminatedUnion("kind", [object({ kind: literal("table") }), object({
30660
+ kind: literal("node-benchmark"),
30661
+ resultId: string(),
30662
+ measuredAtMs: number()
30663
+ })]);
29391
30664
  var DeviceModelChoiceSchema = object({
29392
30665
  modelId: string(),
29393
30666
  p50Ms: number(),
29394
30667
  fps: number(),
29395
30668
  measured: boolean(),
30669
+ /** Absent on a plan from before D791 — read as the table. */
30670
+ source: LatencySourceSchema.optional(),
29396
30671
  /** Parallel sessions at the camera rate with the headroom kept free: ⌊fps × (1 − headroom) / camera fps⌋. */
29397
30672
  capacitySessions: number(),
29398
30673
  personRecall: number()
@@ -29403,6 +30678,8 @@ var DeviceRecommendationSchema = object({
29403
30678
  enabled: boolean(),
29404
30679
  available: boolean(),
29405
30680
  chosen: DeviceModelChoiceSchema.nullable(),
30681
+ /** Present when the device is kept as is: Apply writes nothing on it. */
30682
+ kept: KeptReasonSchema.optional(),
29406
30683
  reasons: array(RecommendationReasonSchema).readonly()
29407
30684
  });
29408
30685
  var NodeRecommendationSchema = object({
@@ -29456,6 +30733,17 @@ var AutoTuneWarningSchema = discriminatedUnion("kind", [
29456
30733
  kind: literal("coral-enabled"),
29457
30734
  nodeId: string(),
29458
30735
  deviceKey: string()
30736
+ }),
30737
+ object({
30738
+ kind: literal("custom-pin-kept"),
30739
+ nodeId: string(),
30740
+ deviceKey: string().nullable(),
30741
+ deviceId: number().nullable(),
30742
+ modelId: string()
30743
+ }),
30744
+ object({
30745
+ kind: literal("custom-registry-unreadable"),
30746
+ error: string()
29459
30747
  })
29460
30748
  ]);
29461
30749
  var AutoTuneOptionsSchema = object({
@@ -29634,13 +30922,14 @@ var SuggestSharesResultSchema = object({
29634
30922
  nodes: array(SuggestedNodeShareSchema).readonly()
29635
30923
  });
29636
30924
  /**
29637
- * Where the node and device shares come from (D750, D755).
29638
- * - `hardware` (default) — computed by the system from each node's static
29639
- * capacity (its accelerators at their Auto tune models, from the measured
29640
- * latency table), recomputed whenever a node or device joins, leaves, is
29641
- * switched on or off, or changes model. No load input.
29642
- * - `benchmark` — the same, from each node's measured capacity (node
29643
- * benchmark results); a node without results falls back to `hardware`.
30925
+ * Where the node and device shares come from (D750, D755, D791).
30926
+ * - `benchmark` (default since D791) — each node's capacity as its own node
30927
+ * benchmark measured it; a node without fresh results is sized from
30928
+ * `hardware` and says so. Measured on the node beats the table.
30929
+ * - `hardware` — computed from each node's static capacity only (its
30930
+ * accelerators at their Auto tune models, from the latency table).
30931
+ * Both are recomputed whenever a node or device joins, leaves, is switched
30932
+ * on or off, changes model, or a benchmark result is written. No load input.
29644
30933
  * - `manual` — the operator's stored sliders.
29645
30934
  * Either way a node or device that cannot take sessions gives its share to
29646
30935
  * the others in proportion; the stored values are never rewritten for that.
@@ -29689,6 +30978,362 @@ var EffectiveSharesSchema = object({
29689
30978
  nodeWeights: record(string(), number()),
29690
30979
  deviceWeights: record(string(), record(string(), number()))
29691
30980
  });
30981
+ /**
30982
+ * Wire shapes of the node benchmark (D791): the operator's plan, the
30983
+ * preflight the confirmation shows, the run the orchestrator owns, what the
30984
+ * measuring runner reports, and the result rows Auto tune and the automatic
30985
+ * shares read.
30986
+ *
30987
+ * ONE node at a time, owned by the pipeline orchestrator. While a run is
30988
+ * active the cluster is in BENCHMARK MODE for that node: it is not a
30989
+ * detection candidate, camera pins naming it are ignored so its sessions move
30990
+ * elsewhere, and both come back when the mode ends — after a crash or a hub
30991
+ * restart too (a persisted manifest, reconciled against the registry).
30992
+ *
30993
+ * Two measurements, both on the node, driven by its own runner (frames never
30994
+ * cross a process at frame rate, D9):
30995
+ * - `device` — one accelerator × one candidate detector, root only, open
30996
+ * loop: how many streams at the camera rate it carries inside the frame
30997
+ * interval;
30998
+ * - `pipeline` — the chosen detector plus the operator's detail steps
30999
+ * (faces, plates, classifiers, CLIP…), on varied frames from the bench
31000
+ * clip: how many parallel sessions the node carries before latency, drops,
31001
+ * CPU, RAM or the event loop give out.
31002
+ */
31003
+ /** Defaults and bounds, one place. */
31004
+ var NODE_BENCHMARK_DEFAULTS = {
31005
+ fpsPerStream: 10,
31006
+ budgetMinutes: 45,
31007
+ minBudgetMinutes: 10,
31008
+ maxBudgetMinutes: 120,
31009
+ /** A result older than this no longer beats the table. */
31010
+ staleAfterDays: 30,
31011
+ /** Warm-in per ramp step (not accounted). */
31012
+ settleSec: 5,
31013
+ /** Accounted window per ramp step. */
31014
+ measureSec: 20,
31015
+ /** Longest the drain may take before the run is refused. */
31016
+ drainTimeoutSec: 120,
31017
+ /** Candidate models per device in one run. */
31018
+ maxModelsPerDevice: 6
31019
+ };
31020
+ /** The two measurements a run can make. */
31021
+ var NodeBenchmarkPhaseSchema = _enum(["device", "pipeline"]);
31022
+ var NodeBenchmarkDevicePlanSchema = object({
31023
+ /** `<backend>:<device>` — `openvino:npu`, `coreml:all`, `cpu`. */
31024
+ deviceKey: string().min(1),
31025
+ /**
31026
+ * Root detector candidates for the `device` measurement, in the order
31027
+ * measured. The FIRST is the one the `pipeline` measurement runs.
31028
+ */
31029
+ modelIds: array(string().min(1)).min(1).max(NODE_BENCHMARK_DEFAULTS.maxModelsPerDevice)
31030
+ });
31031
+ /** What the operator confirmed. */
31032
+ var NodeBenchmarkPlanSchema = object({
31033
+ nodeId: string().min(1),
31034
+ devices: array(NodeBenchmarkDevicePlanSchema).min(1),
31035
+ /** Which measurements run. At least one. */
31036
+ phases: array(NodeBenchmarkPhaseSchema).min(1).default(["device", "pipeline"]),
31037
+ /**
31038
+ * Detail steps (catalog step ids under the root: faces, plates,
31039
+ * classifiers, CLIP…) the `pipeline` measurement enables. The root
31040
+ * detector always runs.
31041
+ */
31042
+ steps: array(string().min(1)).default([]),
31043
+ /** Offered rate of one stream / session. */
31044
+ fpsPerStream: number().int().min(1).max(30).default(NODE_BENCHMARK_DEFAULTS.fpsPerStream),
31045
+ /** Hard deadline: the mode ends and the cluster is restored when it passes. */
31046
+ budgetMinutes: number().int().min(NODE_BENCHMARK_DEFAULTS.minBudgetMinutes).max(NODE_BENCHMARK_DEFAULTS.maxBudgetMinutes).default(NODE_BENCHMARK_DEFAULTS.budgetMinutes),
31047
+ /** Keep the models the run downloaded (default: delete what was not installed before). */
31048
+ keepDownloadedModels: boolean().default(false),
31049
+ /** Start although the other nodes' capacity does not cover the sessions running now. */
31050
+ acceptInsufficientHeadroom: boolean().default(false)
31051
+ });
31052
+ var NodeBenchmarkRefusalSchema = object({
31053
+ kind: _enum([
31054
+ "benchmark-active",
31055
+ "node-offline",
31056
+ "unknown-device",
31057
+ "no-phase",
31058
+ "insufficient-headroom"
31059
+ ]),
31060
+ detail: string(),
31061
+ overridable: boolean()
31062
+ });
31063
+ /** A camera whose detection leaves the node for the run. */
31064
+ var NodeBenchmarkMovingCameraSchema = object({
31065
+ deviceId: number(),
31066
+ /** Placed on the node now (a standing attach or a running session). */
31067
+ placedOnNode: boolean(),
31068
+ /** A node pin naming this node, ignored for the run. */
31069
+ pinnedToNode: boolean()
31070
+ });
31071
+ /** A camera that cannot leave: no other node can obtain its frames. */
31072
+ var NodeBenchmarkStayingCameraSchema = object({
31073
+ deviceId: number(),
31074
+ reason: literal("only-frame-source")
31075
+ });
31076
+ var NodeBenchmarkPreflightSchema = object({
31077
+ nodeId: string(),
31078
+ online: boolean(),
31079
+ moving: array(NodeBenchmarkMovingCameraSchema).readonly(),
31080
+ /** Keep running on the node during the run; the result is flagged contaminated. */
31081
+ staying: array(NodeBenchmarkStayingCameraSchema).readonly(),
31082
+ estimatedDurationMs: number(),
31083
+ /** The run ends and the cluster is restored at the latest after this long. */
31084
+ budgetMs: number(),
31085
+ phases: array(NodeBenchmarkPhaseSchema).readonly(),
31086
+ steps: array(string()).readonly(),
31087
+ devices: array(NodeBenchmarkDevicePlanSchema).readonly(),
31088
+ /** Parallel sessions the cluster runs now, and what the other nodes can carry. */
31089
+ headroom: object({
31090
+ sessionsNow: number(),
31091
+ otherNodesCapacitySessions: number().nullable()
31092
+ }),
31093
+ refusals: array(NodeBenchmarkRefusalSchema).readonly(),
31094
+ canStart: boolean()
31095
+ });
31096
+ /** Where the measuring runner is. */
31097
+ var NodeBenchProgressSchema = object({
31098
+ phase: _enum([
31099
+ "preparing",
31100
+ "device",
31101
+ "pipeline",
31102
+ "cleanup"
31103
+ ]),
31104
+ deviceKey: string().nullable(),
31105
+ modelId: string().nullable(),
31106
+ /** Streams (device) or sessions (pipeline) of the step running now. */
31107
+ load: number().nullable(),
31108
+ cellsDone: number(),
31109
+ cellsTotal: number(),
31110
+ message: string()
31111
+ });
31112
+ /** What limited a ramp. `none` = the ramp ran out of steps still passing. */
31113
+ var NodeBenchLimitSchema = _enum([
31114
+ "p95",
31115
+ "drops",
31116
+ "errors",
31117
+ "stall",
31118
+ "cpu",
31119
+ "ram",
31120
+ "none"
31121
+ ]);
31122
+ var NodeBenchRampStepSchema = object({
31123
+ load: number(),
31124
+ pass: boolean(),
31125
+ p95Ms: number(),
31126
+ dropRatio: number(),
31127
+ /** Completed frames per second over the accounted window. */
31128
+ fps: number(),
31129
+ cpuPct: number().nullable(),
31130
+ ramFreePct: number().nullable(),
31131
+ failReasons: array(string()).readonly()
31132
+ });
31133
+ var NodeBenchCellSchema = discriminatedUnion("phase", [object({
31134
+ phase: literal("device"),
31135
+ deviceKey: string(),
31136
+ modelId: string(),
31137
+ /** Single-stream latency (the K = 1 step). */
31138
+ p50Ms: number(),
31139
+ p95Ms: number(),
31140
+ p99Ms: number(),
31141
+ /** Frames per second sustained at the last passing step. */
31142
+ fps: number(),
31143
+ /** Streams at the camera rate the device carried inside the frame interval; 0 = not even one. */
31144
+ kMax: number(),
31145
+ limitedBy: NodeBenchLimitSchema,
31146
+ /** First call (model load + warm-up). */
31147
+ warmupMs: number(),
31148
+ ramp: array(NodeBenchRampStepSchema).readonly()
31149
+ }), object({
31150
+ phase: literal("pipeline"),
31151
+ deviceKey: string(),
31152
+ modelId: string(),
31153
+ steps: array(string()).readonly(),
31154
+ /** Parallel sessions at the camera rate the node carried; 0 = not even one. */
31155
+ maxSessions: number(),
31156
+ limitedBy: NodeBenchLimitSchema,
31157
+ /** Detail steps that produced at least one result on the clip — a step that never fired measured nothing. */
31158
+ stepsFired: array(string()).readonly(),
31159
+ warmupMs: number(),
31160
+ ramp: array(NodeBenchRampStepSchema).readonly()
31161
+ })]);
31162
+ /**
31163
+ * What a result was measured ON. A result whose fingerprint no longer matches
31164
+ * the node no longer beats the table.
31165
+ */
31166
+ var NodeBenchFingerprintSchema = object({
31167
+ pipelineVersion: string().nullable(),
31168
+ cpuModel: string().nullable(),
31169
+ ramGb: number().nullable(),
31170
+ os: string().nullable(),
31171
+ /** Per device: the pool the cells ran on (runtime + tuning). */
31172
+ pools: record(string(), object({
31173
+ runtime: string(),
31174
+ numWorkers: number(),
31175
+ concurrency: number(),
31176
+ batchMode: string()
31177
+ })).default({})
31178
+ });
31179
+ /** The frames the run used. */
31180
+ var NodeBenchClipSchema = object({
31181
+ /** `camstack-bench-v1` or `reference-images` (the fallback when the clip is not reachable). */
31182
+ id: string(),
31183
+ revision: string().nullable(),
31184
+ frames: number(),
31185
+ width: number(),
31186
+ height: number()
31187
+ });
31188
+ var NodeBenchRunnerInputSchema = object({
31189
+ runId: string().min(1),
31190
+ devices: array(NodeBenchmarkDevicePlanSchema).min(1),
31191
+ phases: array(NodeBenchmarkPhaseSchema).min(1),
31192
+ /** The full detail step tree root for the `pipeline` measurement is built on the node from these ids. */
31193
+ steps: array(string()).default([]),
31194
+ fpsPerStream: number().int().min(1).max(30),
31195
+ /** The runner stops on its own past this instant, whatever the hub does. */
31196
+ deadlineAtMs: number(),
31197
+ settleSec: number().min(0).max(60).default(NODE_BENCHMARK_DEFAULTS.settleSec),
31198
+ measureSec: number().min(2).max(300).default(NODE_BENCHMARK_DEFAULTS.measureSec),
31199
+ keepDownloadedModels: boolean().default(false)
31200
+ });
31201
+ var NodeBenchRunnerStateSchema = _enum([
31202
+ "running",
31203
+ "done",
31204
+ "failed",
31205
+ "aborted"
31206
+ ]);
31207
+ var NodeBenchRunnerStatusSchema = object({
31208
+ runId: string(),
31209
+ nodeId: string(),
31210
+ state: NodeBenchRunnerStateSchema,
31211
+ progress: NodeBenchProgressSchema.nullable(),
31212
+ /** Every finished cell so far — a run stopped half way keeps what it measured. */
31213
+ cells: array(NodeBenchCellSchema).readonly(),
31214
+ fingerprint: NodeBenchFingerprintSchema.nullable(),
31215
+ clip: NodeBenchClipSchema.nullable(),
31216
+ /** Cameras seen running on the node during the run (they share its pools). */
31217
+ activeCameraIds: array(number()).readonly(),
31218
+ /** Models the run downloaded and then deleted (not installed before). */
31219
+ deletedModels: array(string()).readonly(),
31220
+ error: string().nullable(),
31221
+ startedAtMs: number(),
31222
+ finishedAtMs: number().nullable()
31223
+ });
31224
+ var NodeBenchmarkStateSchema = _enum([
31225
+ "draining",
31226
+ "measuring",
31227
+ "restoring",
31228
+ "done",
31229
+ "failed",
31230
+ "aborted"
31231
+ ]);
31232
+ /** Why a run ended. */
31233
+ var NodeBenchmarkEndReasonSchema = _enum([
31234
+ "completed",
31235
+ "operator-abort",
31236
+ "deadline",
31237
+ "node-lost",
31238
+ "runner-lost",
31239
+ "hub-restart",
31240
+ "drain-timeout",
31241
+ "failed"
31242
+ ]);
31243
+ var NodeBenchmarkRunSchema = object({
31244
+ runId: string(),
31245
+ nodeId: string(),
31246
+ state: NodeBenchmarkStateSchema,
31247
+ plan: NodeBenchmarkPlanSchema,
31248
+ startedAtMs: number(),
31249
+ deadlineAtMs: number(),
31250
+ finishedAtMs: number().nullable(),
31251
+ endReason: NodeBenchmarkEndReasonSchema.nullable(),
31252
+ error: string().nullable(),
31253
+ /** Cameras moved off the node for the run. */
31254
+ moved: array(number()).readonly(),
31255
+ /** Cameras that stayed (their only frame source is the node). */
31256
+ staying: array(number()).readonly(),
31257
+ /** Something else ran on the node's pools during the run. */
31258
+ contaminated: boolean(),
31259
+ progress: NodeBenchProgressSchema.nullable(),
31260
+ resultIds: array(string()).readonly()
31261
+ });
31262
+ /** `getNodeBenchmarkStatus`: the active run (or the last one), and whether benchmark mode is on. */
31263
+ var NodeBenchmarkStatusSchema = object({
31264
+ /** The node the cluster is in benchmark mode for; null = none. */
31265
+ modeNodeId: string().nullable(),
31266
+ run: NodeBenchmarkRunSchema.nullable()
31267
+ });
31268
+ /**
31269
+ * One stored measurement — the only authority Auto tune and the automatic
31270
+ * shares read measured capacity from. Written by the orchestrator when a run
31271
+ * ends, never by anyone else.
31272
+ */
31273
+ var NodeBenchmarkResultSchema = object({
31274
+ id: string(),
31275
+ runId: string(),
31276
+ nodeId: string(),
31277
+ cell: NodeBenchCellSchema,
31278
+ fpsPerStream: number(),
31279
+ fingerprint: NodeBenchFingerprintSchema.nullable(),
31280
+ clip: NodeBenchClipSchema.nullable(),
31281
+ /** Other work shared the node's pools (a camera that could not move, or the hub's own duties). */
31282
+ contaminated: boolean(),
31283
+ stayingCameras: array(number()).readonly(),
31284
+ /** The run ended early; the cell itself completed. */
31285
+ partialRun: boolean(),
31286
+ measuredAtMs: number()
31287
+ });
31288
+ var ListNodeBenchmarkResultsInputSchema = object({
31289
+ nodeId: string().optional(),
31290
+ deviceKey: string().optional()
31291
+ });
31292
+ /** A result with its standing today: does it still beat the table? */
31293
+ var NodeBenchmarkResultViewSchema = NodeBenchmarkResultSchema.extend({
31294
+ /** `fresh` beats the table; `stale` falls back to it; `superseded` = a newer row covers the same cell. */
31295
+ standing: _enum([
31296
+ "fresh",
31297
+ "stale",
31298
+ "superseded"
31299
+ ]),
31300
+ staleWhy: _enum([
31301
+ "age",
31302
+ "runtime",
31303
+ "pool-tuning"
31304
+ ]).nullable()
31305
+ });
31306
+ object({
31307
+ runId: string(),
31308
+ nodeId: string(),
31309
+ startedAtMs: number(),
31310
+ deadlineAtMs: number(),
31311
+ plan: NodeBenchmarkPlanSchema,
31312
+ moved: array(number()).readonly(),
31313
+ staying: array(number()).readonly()
31314
+ });
31315
+ /** Candidate detectors per device, for the plan editor. */
31316
+ var NodeBenchmarkCandidatesSchema = object({
31317
+ nodeId: string(),
31318
+ reachable: boolean(),
31319
+ devices: array(object({
31320
+ deviceKey: string(),
31321
+ enabled: boolean(),
31322
+ available: boolean(),
31323
+ /** Ordered: what Auto tune would pick first, then the rest of the family by accuracy. */
31324
+ suggested: array(string()).readonly(),
31325
+ /** Every root detector the device has a build for. */
31326
+ all: array(string()).readonly(),
31327
+ /** The model the device runs now, when pinned. */
31328
+ currentModelId: string().nullable()
31329
+ })).readonly(),
31330
+ /** Detail steps the node's catalog offers under the root (for the `pipeline` measurement). */
31331
+ steps: array(object({
31332
+ id: string(),
31333
+ name: string(),
31334
+ slot: string()
31335
+ })).readonly()
31336
+ });
29692
31337
  object({
29693
31338
  activeCameras: number(),
29694
31339
  throttledCameras: number(),
@@ -31007,7 +32652,30 @@ var pipelineRunnerCapability = {
31007
32652
  releaseParkedTrackFrames: method(object({
31008
32653
  deviceId: number(),
31009
32654
  trackId: string()
31010
- }), object({ released: number().int().nonnegative() }), { kind: "mutation" })
32655
+ }), object({ released: number().int().nonnegative() }), { kind: "mutation" }),
32656
+ /**
32657
+ * Start measuring THIS node for the orchestrator's node benchmark: the
32658
+ * bench clip decoded once into RAM, each device × candidate detector on an
32659
+ * open-loop ramp (`device`), then the chosen pipeline with the requested
32660
+ * detail steps (`pipeline`). Everything runs in-process with the executor
32661
+ * — no frame crosses a node (D9) — and writes nothing: no track, event,
32662
+ * media or notification. Reached by `nodePin(nodeId)`. Answers at once;
32663
+ * one run per node; the run stops itself at `deadlineAtMs`.
32664
+ */
32665
+ startNodeBench: method(NodeBenchRunnerInputSchema, object({
32666
+ accepted: literal(true),
32667
+ runId: string()
32668
+ }), {
32669
+ kind: "mutation",
32670
+ auth: "admin"
32671
+ }),
32672
+ /** The run's progress and every finished cell; null when this runner does not know `runId`. */
32673
+ getNodeBenchStatus: method(object({ runId: string() }), NodeBenchRunnerStatusSchema.nullable(), { auth: "admin" }),
32674
+ /** Stop the run; what it finished is kept. */
32675
+ abortNodeBench: method(object({ runId: string() }), object({ aborted: boolean() }), {
32676
+ kind: "mutation",
32677
+ auth: "admin"
32678
+ })
31011
32679
  }
31012
32680
  };
31013
32681
  var CameraPipelineConfigSchema = object({
@@ -31935,6 +33603,51 @@ var pipelineOrchestratorCapability = {
31935
33603
  kind: "mutation",
31936
33604
  auth: "admin"
31937
33605
  }),
33606
+ /**
33607
+ * Node benchmark — what a run of this plan would do, without doing it:
33608
+ * the cameras that leave the node, those that cannot (the node is their
33609
+ * only frame source; they stay and flag the run), the estimated duration
33610
+ * and every reason it may not start. The confirmation shows this.
33611
+ */
33612
+ getNodeBenchmarkPreflight: method(NodeBenchmarkPlanSchema, NodeBenchmarkPreflightSchema, { auth: "admin" }),
33613
+ /**
33614
+ * Node benchmark — start ONE run (cluster-wide lock). The orchestrator
33615
+ * persists a restore manifest, enters benchmark mode for the node (out of
33616
+ * placement, its camera pins ignored, nothing rewritten), drains it, drives
33617
+ * the node's own runner, then restores — always, including after an
33618
+ * abort, a lost node or a hub restart. Answers at once; poll
33619
+ * `getNodeBenchmarkStatus`. Refused runs carry the preflight.
33620
+ */
33621
+ startNodeBenchmark: method(NodeBenchmarkPlanSchema, discriminatedUnion("kind", [object({
33622
+ kind: literal("started"),
33623
+ runId: string()
33624
+ }), object({
33625
+ kind: literal("refused"),
33626
+ preflight: NodeBenchmarkPreflightSchema
33627
+ })]), {
33628
+ kind: "mutation",
33629
+ auth: "admin"
33630
+ }),
33631
+ /** Node benchmark — the active run (or the last one) and the node in benchmark mode. */
33632
+ getNodeBenchmarkStatus: method(_void(), NodeBenchmarkStatusSchema, { auth: "admin" }),
33633
+ /** Node benchmark — stop the active run; the cluster is restored as it was. */
33634
+ abortNodeBenchmark: method(object({ runId: string() }), object({ aborted: boolean() }), {
33635
+ kind: "mutation",
33636
+ auth: "admin"
33637
+ }),
33638
+ /**
33639
+ * Node benchmark — root detector candidates per device (what Auto tune
33640
+ * would pick first, then the family) and the detail steps the node's
33641
+ * catalog offers, for the plan editor.
33642
+ */
33643
+ getNodeBenchmarkCandidates: method(object({ nodeId: string() }), NodeBenchmarkCandidatesSchema, { auth: "admin" }),
33644
+ /** Node benchmark — stored results, newest first, each with its standing today. */
33645
+ listNodeBenchmarkResults: method(ListNodeBenchmarkResultsInputSchema, array(NodeBenchmarkResultViewSchema).readonly(), { auth: "admin" }),
33646
+ /** Node benchmark — delete one result; Auto tune and the shares stop reading it. */
33647
+ deleteNodeBenchmarkResult: method(object({ id: string() }), object({ deleted: boolean() }), {
33648
+ kind: "mutation",
33649
+ auth: "admin"
33650
+ }),
31938
33651
  /** Read one camera's settings. Null when never touched (inherits agent defaults fully). */
31939
33652
  getCameraSettings: method(object({ deviceId: number() }), CameraPipelineSettingsSchema.nullable()),
31940
33653
  /** Set or clear the 3-state toggle for one (camera, addonId). Pass `enabled: null` to clear and revert to agent default. */
@@ -39415,6 +41128,9 @@ var CreateIntegrationInputSchema = object({
39415
41128
  enabled: boolean().optional(),
39416
41129
  info: record(string(), unknown()).optional(),
39417
41130
  settings: record(string(), unknown()).optional(),
41131
+ /** Keys of `settings` the form's schema declares secret (by type) — kept in
41132
+ * the keychain, not the table (D787). */
41133
+ secretKeys: array(string()).optional(),
39418
41134
  skipRestart: boolean().optional()
39419
41135
  });
39420
41136
  var UpdateIntegrationInputSchema = object({
@@ -39450,7 +41166,9 @@ var integrationsCapability = {
39450
41166
  getSettings: method(object({ id: string() }), record(string(), unknown()), { auth: "admin" }),
39451
41167
  setSettings: method(object({
39452
41168
  id: string(),
39453
- settings: record(string(), unknown())
41169
+ settings: record(string(), unknown()),
41170
+ /** Keys the form's schema declares secret (by type) — keychain-stored (D787). */
41171
+ secretKeys: array(string()).optional()
39454
41172
  }), object({ success: boolean() }), {
39455
41173
  kind: "mutation",
39456
41174
  auth: "admin"
@@ -48773,7 +50491,8 @@ var BaseDevice = class {
48773
50491
  this.role = options.role;
48774
50492
  this.parentDeviceId = ctx.parentDeviceId;
48775
50493
  const seedData = ctx.persistedConfig ?? {};
48776
- this.config = DeviceConfig.fromSchema(schema, (data) => ctx.persistConfig(data), seedData, ({ droppedKeys, issues }) => {
50494
+ const declaredSecretPaths = collectZodSecretPaths(schema);
50495
+ this.config = DeviceConfig.fromSchema(schema, (data) => ctx.persistConfig(data, { secretConfigPaths: declaredSecretPaths }), seedData, ({ droppedKeys, issues }) => {
48777
50496
  ctx.logger.warn("Device config recovery: dropping invalid persisted fields", {
48778
50497
  tags: {
48779
50498
  deviceId: ctx.id,
@@ -51985,6 +53704,90 @@ Object.freeze({
51985
53704
  addonId: null,
51986
53705
  access: "create"
51987
53706
  },
53707
+ "keychain.delete": {
53708
+ capName: "keychain",
53709
+ capScope: "system",
53710
+ addonId: null,
53711
+ access: "delete"
53712
+ },
53713
+ "keychain.getState": {
53714
+ capName: "keychain",
53715
+ capScope: "system",
53716
+ addonId: null,
53717
+ access: "view"
53718
+ },
53719
+ "keychain.listMeta": {
53720
+ capName: "keychain",
53721
+ capScope: "system",
53722
+ addonId: null,
53723
+ access: "view"
53724
+ },
53725
+ "keychain.put": {
53726
+ capName: "keychain",
53727
+ capScope: "system",
53728
+ addonId: null,
53729
+ access: "create"
53730
+ },
53731
+ "keychain.resolve": {
53732
+ capName: "keychain",
53733
+ capScope: "system",
53734
+ addonId: null,
53735
+ access: "view"
53736
+ },
53737
+ "keychainAdmin.deleteOrphans": {
53738
+ capName: "keychain-admin",
53739
+ capScope: "system",
53740
+ addonId: null,
53741
+ access: "delete"
53742
+ },
53743
+ "keychainAdmin.downloadRecoveryKey": {
53744
+ capName: "keychain-admin",
53745
+ capScope: "system",
53746
+ addonId: null,
53747
+ access: "create"
53748
+ },
53749
+ "keychainAdmin.listAudit": {
53750
+ capName: "keychain-admin",
53751
+ capScope: "system",
53752
+ addonId: null,
53753
+ access: "view"
53754
+ },
53755
+ "keychainAdmin.listSecrets": {
53756
+ capName: "keychain-admin",
53757
+ capScope: "system",
53758
+ addonId: null,
53759
+ access: "view"
53760
+ },
53761
+ "keychainAdmin.purgeRetiredKeys": {
53762
+ capName: "keychain-admin",
53763
+ capScope: "system",
53764
+ addonId: null,
53765
+ access: "delete"
53766
+ },
53767
+ "keychainAdmin.resetKeychain": {
53768
+ capName: "keychain-admin",
53769
+ capScope: "system",
53770
+ addonId: null,
53771
+ access: "delete"
53772
+ },
53773
+ "keychainAdmin.reveal": {
53774
+ capName: "keychain-admin",
53775
+ capScope: "system",
53776
+ addonId: null,
53777
+ access: "create"
53778
+ },
53779
+ "keychainAdmin.rotateMasterKey": {
53780
+ capName: "keychain-admin",
53781
+ capScope: "system",
53782
+ addonId: null,
53783
+ access: "create"
53784
+ },
53785
+ "keychainAdmin.status": {
53786
+ capName: "keychain-admin",
53787
+ capScope: "system",
53788
+ addonId: null,
53789
+ access: "view"
53790
+ },
51988
53791
  "lawnMowerControl.dock": {
51989
53792
  capName: "lawn-mower-control",
51990
53793
  capScope: "device",
@@ -53359,6 +55162,18 @@ Object.freeze({
53359
55162
  addonId: null,
53360
55163
  access: "create"
53361
55164
  },
55165
+ "pipelineAnalytics.addRetrainFrameFromRecording": {
55166
+ capName: "pipeline-analytics",
55167
+ capScope: "device",
55168
+ addonId: null,
55169
+ access: "create"
55170
+ },
55171
+ "pipelineAnalytics.addRetrainFramesToCollection": {
55172
+ capName: "pipeline-analytics",
55173
+ capScope: "device",
55174
+ addonId: null,
55175
+ access: "create"
55176
+ },
53362
55177
  "pipelineAnalytics.applyDeviceSettingsPatch": {
53363
55178
  capName: "pipeline-analytics",
53364
55179
  capScope: "device",
@@ -53407,12 +55222,24 @@ Object.freeze({
53407
55222
  addonId: null,
53408
55223
  access: "view"
53409
55224
  },
55225
+ "pipelineAnalytics.createRetrainCollection": {
55226
+ capName: "pipeline-analytics",
55227
+ capScope: "device",
55228
+ addonId: null,
55229
+ access: "create"
55230
+ },
53410
55231
  "pipelineAnalytics.deleteDeviceEvents": {
53411
55232
  capName: "pipeline-analytics",
53412
55233
  capScope: "device",
53413
55234
  addonId: null,
53414
55235
  access: "delete"
53415
55236
  },
55237
+ "pipelineAnalytics.deleteRetrainCollection": {
55238
+ capName: "pipeline-analytics",
55239
+ capScope: "device",
55240
+ addonId: null,
55241
+ access: "delete"
55242
+ },
53416
55243
  "pipelineAnalytics.deleteTracks": {
53417
55244
  capName: "pipeline-analytics",
53418
55245
  capScope: "device",
@@ -53617,6 +55444,24 @@ Object.freeze({
53617
55444
  addonId: null,
53618
55445
  access: "view"
53619
55446
  },
55447
+ "pipelineAnalytics.listRetrainAssistProfiles": {
55448
+ capName: "pipeline-analytics",
55449
+ capScope: "device",
55450
+ addonId: null,
55451
+ access: "view"
55452
+ },
55453
+ "pipelineAnalytics.listRetrainCollectionFrames": {
55454
+ capName: "pipeline-analytics",
55455
+ capScope: "device",
55456
+ addonId: null,
55457
+ access: "view"
55458
+ },
55459
+ "pipelineAnalytics.listRetrainCollections": {
55460
+ capName: "pipeline-analytics",
55461
+ capScope: "device",
55462
+ addonId: null,
55463
+ access: "view"
55464
+ },
53620
55465
  "pipelineAnalytics.listRetrainFrames": {
53621
55466
  capName: "pipeline-analytics",
53622
55467
  capScope: "device",
@@ -53665,6 +55510,12 @@ Object.freeze({
53665
55510
  addonId: null,
53666
55511
  access: "create"
53667
55512
  },
55513
+ "pipelineAnalytics.proposeRetrainAnnotationsWithLlm": {
55514
+ capName: "pipeline-analytics",
55515
+ capScope: "device",
55516
+ addonId: null,
55517
+ access: "create"
55518
+ },
53668
55519
  "pipelineAnalytics.pruneEvents": {
53669
55520
  capName: "pipeline-analytics",
53670
55521
  capScope: "device",
@@ -53719,6 +55570,18 @@ Object.freeze({
53719
55570
  addonId: null,
53720
55571
  access: "create"
53721
55572
  },
55573
+ "pipelineAnalytics.removeRetrainFrameFromCollection": {
55574
+ capName: "pipeline-analytics",
55575
+ capScope: "device",
55576
+ addonId: null,
55577
+ access: "delete"
55578
+ },
55579
+ "pipelineAnalytics.renameRetrainCollection": {
55580
+ capName: "pipeline-analytics",
55581
+ capScope: "device",
55582
+ addonId: null,
55583
+ access: "create"
55584
+ },
53722
55585
  "pipelineAnalytics.restageRetrainTrack": {
53723
55586
  capName: "pipeline-analytics",
53724
55587
  capScope: "device",
@@ -54007,6 +55870,12 @@ Object.freeze({
54007
55870
  addonId: null,
54008
55871
  access: "view"
54009
55872
  },
55873
+ "pipelineOrchestrator.abortNodeBenchmark": {
55874
+ capName: "pipeline-orchestrator",
55875
+ capScope: "system",
55876
+ addonId: null,
55877
+ access: "create"
55878
+ },
54010
55879
  "pipelineOrchestrator.applyAutoTune": {
54011
55880
  capName: "pipeline-orchestrator",
54012
55881
  capScope: "system",
@@ -54031,6 +55900,12 @@ Object.freeze({
54031
55900
  addonId: null,
54032
55901
  access: "create"
54033
55902
  },
55903
+ "pipelineOrchestrator.deleteNodeBenchmarkResult": {
55904
+ capName: "pipeline-orchestrator",
55905
+ capScope: "system",
55906
+ addonId: null,
55907
+ access: "delete"
55908
+ },
54034
55909
  "pipelineOrchestrator.getAgentLoad": {
54035
55910
  capName: "pipeline-orchestrator",
54036
55911
  capScope: "system",
@@ -54139,6 +56014,24 @@ Object.freeze({
54139
56014
  addonId: null,
54140
56015
  access: "view"
54141
56016
  },
56017
+ "pipelineOrchestrator.getNodeBenchmarkCandidates": {
56018
+ capName: "pipeline-orchestrator",
56019
+ capScope: "system",
56020
+ addonId: null,
56021
+ access: "view"
56022
+ },
56023
+ "pipelineOrchestrator.getNodeBenchmarkPreflight": {
56024
+ capName: "pipeline-orchestrator",
56025
+ capScope: "system",
56026
+ addonId: null,
56027
+ access: "view"
56028
+ },
56029
+ "pipelineOrchestrator.getNodeBenchmarkStatus": {
56030
+ capName: "pipeline-orchestrator",
56031
+ capScope: "system",
56032
+ addonId: null,
56033
+ access: "view"
56034
+ },
54142
56035
  "pipelineOrchestrator.getNodeInferenceDevices": {
54143
56036
  capName: "pipeline-orchestrator",
54144
56037
  capScope: "system",
@@ -54181,6 +56074,12 @@ Object.freeze({
54181
56074
  addonId: null,
54182
56075
  access: "view"
54183
56076
  },
56077
+ "pipelineOrchestrator.listNodeBenchmarkResults": {
56078
+ capName: "pipeline-orchestrator",
56079
+ capScope: "system",
56080
+ addonId: null,
56081
+ access: "view"
56082
+ },
54184
56083
  "pipelineOrchestrator.pauseForStorageMigration": {
54185
56084
  capName: "pipeline-orchestrator",
54186
56085
  capScope: "system",
@@ -54325,6 +56224,12 @@ Object.freeze({
54325
56224
  addonId: null,
54326
56225
  access: "create"
54327
56226
  },
56227
+ "pipelineOrchestrator.startNodeBenchmark": {
56228
+ capName: "pipeline-orchestrator",
56229
+ capScope: "system",
56230
+ addonId: null,
56231
+ access: "create"
56232
+ },
54328
56233
  "pipelineOrchestrator.suggestShares": {
54329
56234
  capName: "pipeline-orchestrator",
54330
56235
  capScope: "system",
@@ -54343,6 +56248,12 @@ Object.freeze({
54343
56248
  addonId: null,
54344
56249
  access: "create"
54345
56250
  },
56251
+ "pipelineRunner.abortNodeBench": {
56252
+ capName: "pipeline-runner",
56253
+ capScope: "system",
56254
+ addonId: null,
56255
+ access: "create"
56256
+ },
54346
56257
  "pipelineRunner.attachCamera": {
54347
56258
  capName: "pipeline-runner",
54348
56259
  capScope: "system",
@@ -54391,6 +56302,12 @@ Object.freeze({
54391
56302
  addonId: null,
54392
56303
  access: "view"
54393
56304
  },
56305
+ "pipelineRunner.getNodeBenchStatus": {
56306
+ capName: "pipeline-runner",
56307
+ capScope: "system",
56308
+ addonId: null,
56309
+ access: "view"
56310
+ },
54394
56311
  "pipelineRunner.getParkedTrackFrame": {
54395
56312
  capName: "pipeline-runner",
54396
56313
  capScope: "system",
@@ -54433,6 +56350,12 @@ Object.freeze({
54433
56350
  addonId: null,
54434
56351
  access: "create"
54435
56352
  },
56353
+ "pipelineRunner.startNodeBench": {
56354
+ capName: "pipeline-runner",
56355
+ capScope: "system",
56356
+ addonId: null,
56357
+ access: "create"
56358
+ },
54436
56359
  "plateGallery.assignPlate": {
54437
56360
  capName: "plate-gallery",
54438
56361
  capScope: "system",
@@ -58112,6 +60035,8 @@ var ALL_CAPABILITY_DEFINITIONS = [
58112
60035
  imageSettingsCapability,
58113
60036
  integrationsCapability,
58114
60037
  intercomCapability,
60038
+ keychainCapability,
60039
+ keychainAdminCapability,
58115
60040
  lawnMowerControlCapability,
58116
60041
  llmCapability,
58117
60042
  llmRuntimeCapability,
@@ -59538,6 +61463,11 @@ Object.freeze({
59538
61463
  form: "single",
59539
61464
  optional: false
59540
61465
  }],
61466
+ "pipelineAnalytics.addRetrainFrameFromRecording": [{
61467
+ name: "deviceId",
61468
+ form: "single",
61469
+ optional: false
61470
+ }],
59541
61471
  "pipelineAnalytics.applyDeviceSettingsPatch": [{
59542
61472
  name: "deviceId",
59543
61473
  form: "single",
@@ -59728,6 +61658,11 @@ Object.freeze({
59728
61658
  form: "single",
59729
61659
  optional: false
59730
61660
  }],
61661
+ "pipelineAnalytics.proposeRetrainAnnotationsWithLlm": [{
61662
+ name: "deviceId",
61663
+ form: "single",
61664
+ optional: false
61665
+ }],
59731
61666
  "pipelineAnalytics.pruneEventsBefore": [{
59732
61667
  name: "deviceId",
59733
61668
  form: "single",