@camstack/addon-pipeline 1.2.345 → 1.2.347

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 (35) hide show
  1. package/dist/audio-analyzer/index.js +3 -3
  2. package/dist/audio-analyzer/index.mjs +3 -3
  3. package/dist/{custom-model-catalog-C7zLb7ze.mjs → custom-model-catalog-B_3TaGyS.mjs} +2 -2
  4. package/dist/{custom-model-catalog-CrEsRBe_.js → custom-model-catalog-VPiA2VLl.js} +2 -2
  5. package/dist/detection-pipeline/index.js +4 -4
  6. package/dist/detection-pipeline/index.mjs +8 -8
  7. package/dist/{dist-_I6JkuJ8.js → dist-BK74zWWV.js} +3774 -111
  8. package/dist/{dist-cT7hhXh9.mjs → dist-mCRj-pzB.mjs} +3745 -112
  9. package/dist/{model-catalogs-BrKLOMBe.js → model-catalogs-0h3q8aik.js} +15 -4
  10. package/dist/{model-catalogs-CPAmiLRa.mjs → model-catalogs-CwzQMyNC.mjs} +15 -4
  11. package/dist/motion-wasm/index.js +1 -1
  12. package/dist/motion-wasm/index.mjs +1 -1
  13. package/dist/{node-Dmga8QNL.mjs → node-BbmYK6W-.mjs} +1 -1
  14. package/dist/{node-6zL5ddry.js → node-BdTn3tlc.js} +1 -1
  15. package/dist/pipeline-runner/index.js +733 -6
  16. package/dist/pipeline-runner/index.mjs +739 -12
  17. package/dist/{process-memory-CstCtC3A.js → process-memory-CnZ_X4eQ.js} +1 -1
  18. package/dist/{process-memory-DZcnBnb1.mjs → process-memory-bOQf34ya.mjs} +1 -1
  19. package/dist/recorder/index.js +27 -7
  20. package/dist/recorder/index.mjs +27 -7
  21. package/dist/{segment-demux-js-qzo-pQK7.mjs → segment-demux-js-5MO-ia8o.mjs} +1 -1
  22. package/dist/{segment-demux-js-DPtDBph6.js → segment-demux-js-C4jnKQoX.js} +1 -1
  23. package/dist/stream-broker/_stub.js +2 -2
  24. package/dist/stream-broker/{_virtual_mf-localSharedImportMap___mfe_internal__addon_stream_broker_widgets-Drg8iwTA.mjs → _virtual_mf-localSharedImportMap___mfe_internal__addon_stream_broker_widgets-C8GBSIhY.mjs} +3 -3
  25. package/dist/stream-broker/_virtual_mf___mfe_internal__addon_stream_broker_widgets__loadShare___mf_0_camstack_mf_1_types__loadShare__.js-CNhTe1NS.mjs +26 -0
  26. package/dist/stream-broker/_virtual_mf___mfe_internal__addon_stream_broker_widgets__loadShare___mf_0_camstack_mf_1_ui_mf_2_library__loadShare__.js-uvybMzaE.mjs +26 -0
  27. package/dist/stream-broker/demux-worker-child.js +1 -1
  28. package/dist/stream-broker/demux-worker-child.mjs +1 -1
  29. package/dist/stream-broker/{hostInit-Bz5eB0VL.mjs → hostInit-IWX_cy7U.mjs} +3 -3
  30. package/dist/stream-broker/index.js +3 -3
  31. package/dist/stream-broker/index.mjs +5 -5
  32. package/dist/stream-broker/remoteEntry.js +1 -1
  33. package/package.json +1 -1
  34. package/dist/stream-broker/_virtual_mf___mfe_internal__addon_stream_broker_widgets__loadShare___mf_0_camstack_mf_1_types__loadShare__.js-C2VoXjqc.mjs +0 -26
  35. package/dist/stream-broker/_virtual_mf___mfe_internal__addon_stream_broker_widgets__loadShare___mf_0_camstack_mf_1_ui_mf_2_library__loadShare__.js-DATpA6mb.mjs +0 -26
@@ -1,5 +1,5 @@
1
1
  let node_crypto = require("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`).
@@ -5370,7 +5377,7 @@ var ZodIssueCode = {
5370
5377
  var ZodFirstPartyTypeKind;
5371
5378
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
5372
5379
  //#endregion
5373
- //#region ../types/dist/sleep-BNeXenvr.mjs
5380
+ //#region ../types/dist/sleep-r3RWkGVx.mjs
5374
5381
  /**
5375
5382
  * The audio chunk plane's byte format, and the ONE expansion from a coded
5376
5383
  * window to float samples (D455).
@@ -5481,6 +5488,97 @@ function buildAlawTable() {
5481
5488
  }
5482
5489
  var ULAW_TABLE = buildUlawTable();
5483
5490
  var ALAW_TABLE = buildAlawTable();
5491
+ /** Is this field's stored value a credential? */
5492
+ function isSecretConfigField(field) {
5493
+ if (field.type === "password") return true;
5494
+ return "secret" in field && field.secret === true;
5495
+ }
5496
+ /**
5497
+ * Is this field's value stored in the KEYCHAIN (D787)? Every secret field is,
5498
+ * by its TYPE, unless it opts out with `storage: 'inline'` — never by its name.
5499
+ */
5500
+ function isKeychainStoredField(field) {
5501
+ if (!isSecretConfigField(field)) return false;
5502
+ if (field.type === "textarea" && field.isJson === true) return false;
5503
+ return !("storage" in field && field.storage === "inline");
5504
+ }
5505
+ /**
5506
+ * What a settings blob holds where a secret used to be.
5507
+ *
5508
+ * A keychain-stored field never holds its value. It holds a self-describing
5509
+ * MARKER, `{"$secret":"secret://…","v":1}` — an object, never a string, so no
5510
+ * code can mistake it for a credential and no form can send it to a camera as
5511
+ * a password. The empty state is `null` / absent, never `''`.
5512
+ *
5513
+ * The same shapes travel to and from the admin UI:
5514
+ *
5515
+ * - read: `hydrateSchema` hands a secret field a {@link SecretFieldView}
5516
+ * (`{ $secret, v, set: true }`) or `null` — the browser learns whether a
5517
+ * value is set, never the value.
5518
+ * - write: an untouched field submits the view back unchanged (KEEP); a typed
5519
+ * value is a plain non-empty string (CHANGE); the Clear button submits
5520
+ * {@link SECRET_CLEAR} (CLEAR). `''`, `null` and the legacy redaction tokens
5521
+ * are KEEP — an empty string is what a defaults-fallback pushes back, and
5522
+ * treating it as "clear" is how a save destroyed a stored credential before.
5523
+ *
5524
+ * Pure and browser-safe.
5525
+ */
5526
+ var SECRET_CLEAR = { $secretClear: true };
5527
+ /** The `'***'` token D634 redaction writes for non-admins. */
5528
+ var LEGACY_DEVICE_REDACTION = "***";
5529
+ function isRecord$2(value) {
5530
+ return typeof value === "object" && value !== null && !Array.isArray(value);
5531
+ }
5532
+ function makeSecretMarker(ref) {
5533
+ return {
5534
+ $secret: ref,
5535
+ v: 1
5536
+ };
5537
+ }
5538
+ /** A stored marker: an object whose `$secret` is a non-empty string. */
5539
+ function isSecretMarker(value) {
5540
+ if (!isRecord$2(value)) return false;
5541
+ const ref = value["$secret"];
5542
+ return typeof ref === "string" && ref.length > 0;
5543
+ }
5544
+ function isSecretClear(value) {
5545
+ return isRecord$2(value) && value["$secretClear"] === true;
5546
+ }
5547
+ /**
5548
+ * The UI view of a stored secret field value: a marker becomes "set", inline
5549
+ * plaintext becomes "set (inline)", nothing becomes `null`. A value never
5550
+ * survives this function.
5551
+ */
5552
+ function toSecretFieldView(stored) {
5553
+ if (isSecretMarker(stored)) return {
5554
+ $secret: stored.$secret,
5555
+ v: 1,
5556
+ set: true
5557
+ };
5558
+ if (typeof stored === "string" && stored.length > 0) return {
5559
+ $secret: null,
5560
+ v: 1,
5561
+ set: true,
5562
+ inline: true
5563
+ };
5564
+ return null;
5565
+ }
5566
+ /**
5567
+ * Classify an incoming value for a secret path. Only a non-empty string that is
5568
+ * not a redaction token sets a value; only {@link SECRET_CLEAR} clears.
5569
+ * Everything else — a marker (ours or anyone's), a UI view, `''`, `null`,
5570
+ * `undefined`, a redaction token, a non-string — keeps what is stored.
5571
+ */
5572
+ function classifySecretWrite(incoming) {
5573
+ if (isSecretClear(incoming)) return { kind: "clear" };
5574
+ if (typeof incoming !== "string") return { kind: "keep" };
5575
+ if (incoming.length === 0) return { kind: "keep" };
5576
+ if (incoming === "__camstack_redacted__" || incoming === LEGACY_DEVICE_REDACTION) return { kind: "keep" };
5577
+ return {
5578
+ kind: "set",
5579
+ value: incoming
5580
+ };
5581
+ }
5484
5582
  Object.fromEntries([
5485
5583
  {
5486
5584
  id: "overview",
@@ -5652,33 +5750,19 @@ Object.fromEntries([
5652
5750
  function isValuelessField(field) {
5653
5751
  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";
5654
5752
  }
5655
- /**
5656
- * Merge a `ConfigUISchema` with a raw `values` record into a
5657
- * `ConfigUISchemaWithValues`. Used by every `get*Settings` backend endpoint
5658
- * before returning to the admin UI. Groups are walked recursively.
5659
- *
5660
- * For each leaf field:
5661
- * - structural fields (`separator`, `info`, `button`) pass through unchanged
5662
- * - other fields get `value = values[key] ?? field.default ?? null`
5663
- *
5664
- * Unknown keys in `values` (keys not declared in the schema) are silently
5665
- * ignored — they don't contribute to the output. Missing keys fall back to
5666
- * the schema default or `null`. This mirrors the old backend behaviour where
5667
- * `FormBuilder` rendered `values[key] ?? field.default`.
5668
- */
5669
- function hydrateSchema(schema, values) {
5753
+ function hydrateSchema(schema, values, options = {}) {
5670
5754
  return {
5671
5755
  ...schema.tabs ? { tabs: [...schema.tabs] } : {},
5672
5756
  sections: schema.sections.map((section) => ({
5673
5757
  ...section,
5674
- fields: section.fields.map((field) => hydrateField(field, values))
5758
+ fields: section.fields.map((field) => hydrateField(field, values, options))
5675
5759
  }))
5676
5760
  };
5677
5761
  }
5678
- function hydrateField(field, values) {
5762
+ function hydrateField(field, values, options) {
5679
5763
  if (isValuelessField(field)) return field;
5680
5764
  if (field.type === "group") {
5681
- const hydratedChildren = field.fields.map((child) => hydrateField(child, values));
5765
+ const hydratedChildren = field.fields.map((child) => hydrateField(child, values, options));
5682
5766
  return {
5683
5767
  ...field,
5684
5768
  fields: hydratedChildren
@@ -5687,7 +5771,7 @@ function hydrateField(field, values) {
5687
5771
  if (field.type === "sub-tabs") {
5688
5772
  const hydratedTabs = field.tabs.map((tab) => ({
5689
5773
  ...tab,
5690
- fields: tab.fields.map((child) => hydrateField(child, values))
5774
+ fields: tab.fields.map((child) => hydrateField(child, values, options))
5691
5775
  }));
5692
5776
  return {
5693
5777
  ...field,
@@ -5697,6 +5781,33 @@ function hydrateField(field, values) {
5697
5781
  const key = field.key;
5698
5782
  const storedValue = Object.prototype.hasOwnProperty.call(values, key) ? values[key] : void 0;
5699
5783
  const defaultValue = field.default;
5784
+ const asView = (v) => isSecretMarker(v) || options.inlineSecretsAsViews === true && v !== void 0;
5785
+ if (isKeychainStoredField(field) && asView(storedValue)) return {
5786
+ ...field,
5787
+ value: toSecretFieldView(storedValue)
5788
+ };
5789
+ if (isKeychainStoredField(field) && options.inlineSecretsAsViews === true) return {
5790
+ ...field,
5791
+ value: null
5792
+ };
5793
+ if (field.type === "editable-array" && Array.isArray(storedValue)) {
5794
+ const secretItemKeys = field.itemFields.filter((item) => "key" in item && isKeychainStoredField(item)).map((item) => "key" in item ? item.key : "");
5795
+ if (secretItemKeys.length > 0) {
5796
+ const rows = storedValue.map((row) => {
5797
+ if (row === null || typeof row !== "object" || Array.isArray(row)) return row;
5798
+ const out = { ...row };
5799
+ for (const k of secretItemKeys) {
5800
+ const v = Reflect.get(row, k);
5801
+ if (asView(v)) out[k] = toSecretFieldView(v);
5802
+ }
5803
+ return out;
5804
+ });
5805
+ return {
5806
+ ...field,
5807
+ value: rows
5808
+ };
5809
+ }
5810
+ }
5700
5811
  if (field.multiple) {
5701
5812
  const stored = Array.isArray(storedValue) ? storedValue : storedValue !== void 0 && storedValue !== null ? [storedValue] : [];
5702
5813
  const itemFallback = field.multiple.itemDefault !== void 0 ? field.multiple.itemDefault : defaultValue !== void 0 ? defaultValue : typeOf(field) === "string" ? "" : null;
@@ -5955,6 +6066,778 @@ function projectStore(store, perNodeKeys, nodeId) {
5955
6066
  }
5956
6067
  return out;
5957
6068
  }
6069
+ var GLOBAL_SCOPE = { kind: "global" };
6070
+ /** The scope every addon-wide (not per-node, not per-device) setting lives in. */
6071
+ function globalSecretScope() {
6072
+ return GLOBAL_SCOPE;
6073
+ }
6074
+ function encodeSegment(value) {
6075
+ return encodeURIComponent(value);
6076
+ }
6077
+ function decodeSegment(value) {
6078
+ try {
6079
+ return decodeURIComponent(value);
6080
+ } catch {
6081
+ return null;
6082
+ }
6083
+ }
6084
+ /**
6085
+ * The field path of a value inside an array item, addressed by the item's id:
6086
+ * `arrayItemFieldPath('providers', 'authentik', 'clientSecret')` →
6087
+ * `providers[authentik].clientSecret`.
6088
+ */
6089
+ function arrayItemFieldPath(arrayKey, itemId, fieldKey) {
6090
+ return `${arrayKey}[${encodeSegment(itemId)}].${fieldKey}`;
6091
+ }
6092
+ function parseScope(segments) {
6093
+ switch (segments[0]) {
6094
+ case "global": return {
6095
+ scope: GLOBAL_SCOPE,
6096
+ used: 1
6097
+ };
6098
+ case "node": {
6099
+ const nodeId = segments[1] !== void 0 ? decodeSegment(segments[1]) : null;
6100
+ return nodeId === null || nodeId.length === 0 ? null : {
6101
+ scope: {
6102
+ kind: "node",
6103
+ nodeId
6104
+ },
6105
+ used: 2
6106
+ };
6107
+ }
6108
+ case "device": {
6109
+ const raw = segments[1];
6110
+ if (raw === void 0 || !/^\d+$/.test(raw)) return null;
6111
+ return {
6112
+ scope: {
6113
+ kind: "device",
6114
+ deviceId: Number(raw)
6115
+ },
6116
+ used: 2
6117
+ };
6118
+ }
6119
+ case "integration": {
6120
+ const id = segments[1] !== void 0 ? decodeSegment(segments[1]) : null;
6121
+ return id === null || id.length === 0 ? null : {
6122
+ scope: {
6123
+ kind: "integration",
6124
+ integrationId: id
6125
+ },
6126
+ used: 2
6127
+ };
6128
+ }
6129
+ case "row": {
6130
+ const collection = segments[1] !== void 0 ? decodeSegment(segments[1]) : null;
6131
+ const rowId = segments[2] !== void 0 ? decodeSegment(segments[2]) : null;
6132
+ if (collection === null || rowId === null || collection.length === 0 || rowId.length === 0) return null;
6133
+ return {
6134
+ scope: {
6135
+ kind: "row",
6136
+ collection,
6137
+ rowId
6138
+ },
6139
+ used: 3
6140
+ };
6141
+ }
6142
+ default: return null;
6143
+ }
6144
+ }
6145
+ /** Take a ref apart; `null` when it is not a well-formed ref. */
6146
+ function parseSecretRef(ref) {
6147
+ if (!ref.startsWith("secret://")) return null;
6148
+ const segments = ref.slice(9).split("/");
6149
+ const owner = segments[0] !== void 0 ? decodeSegment(segments[0]) : null;
6150
+ if (owner === null || owner.length === 0) return null;
6151
+ const parsed = parseScope(segments.slice(1));
6152
+ if (parsed === null) return null;
6153
+ const fieldPath = segments.slice(1 + parsed.used).join("/");
6154
+ if (fieldPath.length === 0) return null;
6155
+ return {
6156
+ owner,
6157
+ scope: parsed.scope,
6158
+ fieldPath
6159
+ };
6160
+ }
6161
+ /** A write to a secret path could not be stored in the keychain, so it was refused. */
6162
+ var KeychainWriteRefusedError = class extends Error {
6163
+ fieldPath;
6164
+ constructor(fieldPath, cause) {
6165
+ super(`secret "${fieldPath}" was not saved: the keychain could not store it (${cause instanceof Error ? cause.message : String(cause)}). Nothing was written.`);
6166
+ this.fieldPath = fieldPath;
6167
+ this.name = "KeychainWriteRefusedError";
6168
+ }
6169
+ };
6170
+ var KEEP = { kind: "keep" };
6171
+ function isRecord$1$1(value) {
6172
+ return typeof value === "object" && value !== null && !Array.isArray(value);
6173
+ }
6174
+ function defaultMintId() {
6175
+ return globalThis.crypto.randomUUID();
6176
+ }
6177
+ /** Every marker ref anywhere under `value`. */
6178
+ function collectSecretMarkerRefs(value, out = []) {
6179
+ if (isSecretMarker(value)) {
6180
+ out.push(value.$secret);
6181
+ return out;
6182
+ }
6183
+ if (Array.isArray(value)) for (const item of value) collectSecretMarkerRefs(item, out);
6184
+ else if (isRecord$1$1(value)) for (const child of Object.values(value)) collectSecretMarkerRefs(child, out);
6185
+ return out;
6186
+ }
6187
+ async function storedValueEquals(secrets, marker, candidate) {
6188
+ const resolved = (await secrets.resolve([marker.$secret]))[marker.$secret];
6189
+ return resolved?.kind === "value" && resolved.value === candidate;
6190
+ }
6191
+ async function writeLeaf(ctx, incoming, stored, fieldPath) {
6192
+ const intent = classifySecretWrite(incoming);
6193
+ const ref = ctx.secrets.ref(ctx.scope, fieldPath);
6194
+ const storedIsOurs = isSecretMarker(stored) && stored.$secret === ref;
6195
+ if (intent.kind === "keep") return KEEP;
6196
+ if (intent.kind === "set" && !ctx.operatorWrite && typeof stored === "string" && stored === intent.value) return KEEP;
6197
+ if (intent.kind === "clear") {
6198
+ if (storedIsOurs) ctx.deletes.push(ref);
6199
+ return {
6200
+ kind: "value",
6201
+ value: null
6202
+ };
6203
+ }
6204
+ if (storedIsOurs && await storedValueEquals(ctx.secrets, stored, intent.value)) return {
6205
+ kind: "value",
6206
+ value: stored
6207
+ };
6208
+ try {
6209
+ await ctx.secrets.put(ref, intent.value);
6210
+ } catch (err) {
6211
+ throw new KeychainWriteRefusedError(fieldPath, err);
6212
+ }
6213
+ return {
6214
+ kind: "value",
6215
+ value: makeSecretMarker(ref)
6216
+ };
6217
+ }
6218
+ /** Apply a member result onto `out`: KEEP restores the stored member, or removes it. */
6219
+ function applyMember(out, key, result, storedParent) {
6220
+ if (result.kind === "value") {
6221
+ out[key] = result.value;
6222
+ return;
6223
+ }
6224
+ if (Object.prototype.hasOwnProperty.call(storedParent, key)) out[key] = storedParent[key];
6225
+ else delete out[key];
6226
+ }
6227
+ async function writeMembers(ctx, children, incoming, stored, pathOf) {
6228
+ const out = { ...incoming };
6229
+ for (const [member, node] of children) applyMember(out, member, await writeNode(ctx, node, incoming[member], stored[member], pathOf(member)), stored);
6230
+ return out;
6231
+ }
6232
+ function rowId(row, idKey) {
6233
+ const raw = row[idKey];
6234
+ if (typeof raw === "string" && raw.length > 0) return raw;
6235
+ if (typeof raw === "number" && Number.isFinite(raw)) return String(raw);
6236
+ return null;
6237
+ }
6238
+ async function writeArray(ctx, node, incoming, stored, fieldPath) {
6239
+ const storedRows = Array.isArray(stored) ? stored.filter(isRecord$1$1) : [];
6240
+ if (!Array.isArray(incoming)) {
6241
+ ctx.deletes.push(...collectSecretMarkerRefs(storedRows));
6242
+ return {
6243
+ kind: "value",
6244
+ value: incoming
6245
+ };
6246
+ }
6247
+ const storedById = /* @__PURE__ */ new Map();
6248
+ for (const row of storedRows) {
6249
+ const id = rowId(row, node.idKey);
6250
+ if (id !== null) storedById.set(id, row);
6251
+ }
6252
+ const kept = /* @__PURE__ */ new Set();
6253
+ const rows = [];
6254
+ for (const row of incoming) {
6255
+ if (!isRecord$1$1(row)) {
6256
+ rows.push(row);
6257
+ continue;
6258
+ }
6259
+ const id = rowId(row, node.idKey) ?? ctx.mintId();
6260
+ kept.add(id);
6261
+ const withId = {
6262
+ ...row,
6263
+ [node.idKey]: row[node.idKey] ?? id
6264
+ };
6265
+ if (rowId(withId, node.idKey) === null) withId[node.idKey] = id;
6266
+ const storedRow = storedById.get(id) ?? {};
6267
+ rows.push(await writeMembers(ctx, node.item, withId, storedRow, (member) => arrayItemFieldPath(fieldPath, id, member)));
6268
+ }
6269
+ for (const [id, row] of storedById) if (!kept.has(id)) ctx.deletes.push(...collectSecretMarkerRefs(row));
6270
+ return {
6271
+ kind: "value",
6272
+ value: rows
6273
+ };
6274
+ }
6275
+ async function writeNode(ctx, node, incoming, stored, fieldPath) {
6276
+ switch (node.kind) {
6277
+ case "leaf": return writeLeaf(ctx, incoming, stored, fieldPath);
6278
+ case "array": return writeArray(ctx, node, incoming, stored, fieldPath);
6279
+ case "object": {
6280
+ if (!isRecord$1$1(incoming)) {
6281
+ if (incoming === void 0) return KEEP;
6282
+ ctx.deletes.push(...collectSecretMarkerRefs(stored));
6283
+ return {
6284
+ kind: "value",
6285
+ value: incoming
6286
+ };
6287
+ }
6288
+ const storedObj = isRecord$1$1(stored) ? stored : {};
6289
+ return {
6290
+ kind: "value",
6291
+ value: await writeMembers(ctx, node.children, incoming, storedObj, (m) => `${fieldPath}.${m}`)
6292
+ };
6293
+ }
6294
+ }
6295
+ }
6296
+ /** Split a perNode-scoped key (`key@nodeId`). */
6297
+ function splitNodeKey(key) {
6298
+ const at = key.indexOf("@");
6299
+ return at <= 0 ? {
6300
+ base: key,
6301
+ nodeId: null
6302
+ } : {
6303
+ base: key.slice(0, at),
6304
+ nodeId: key.slice(at + 1)
6305
+ };
6306
+ }
6307
+ /** Rewrite a settings patch so no secret value reaches the blob. See the file doc. */
6308
+ async function transformSecretWrite(input) {
6309
+ const deletes = [];
6310
+ const base = {
6311
+ secrets: input.secrets,
6312
+ mintId: input.mintId ?? defaultMintId,
6313
+ deletes,
6314
+ operatorWrite: input.operatorWrite === true
6315
+ };
6316
+ const out = {};
6317
+ for (const [key, incoming] of Object.entries(input.patch)) {
6318
+ const { base: baseKey, nodeId } = splitNodeKey(key);
6319
+ const node = input.tree.get(baseKey);
6320
+ if (node === void 0) {
6321
+ out[key] = incoming;
6322
+ continue;
6323
+ }
6324
+ const scope = nodeId !== null && nodeId.length > 0 ? {
6325
+ kind: "node",
6326
+ nodeId
6327
+ } : input.scope ?? globalSecretScope();
6328
+ const result = await writeNode({
6329
+ ...base,
6330
+ scope
6331
+ }, node, incoming, input.stored[key], baseKey);
6332
+ if (result.kind === "value") out[key] = result.value;
6333
+ }
6334
+ return {
6335
+ patch: out,
6336
+ afterWrite: async () => {
6337
+ if (deletes.length === 0) return { orphaned: [] };
6338
+ try {
6339
+ await input.secrets.delete([...new Set(deletes)]);
6340
+ return { orphaned: [] };
6341
+ } catch {
6342
+ return { orphaned: [...new Set(deletes)] };
6343
+ }
6344
+ }
6345
+ };
6346
+ }
6347
+ /** Is `ref` one of `owner`'s refs? */
6348
+ function isSecretRefOwnedBy(ref, owner) {
6349
+ return parseSecretRef(ref)?.owner === owner;
6350
+ }
6351
+ /**
6352
+ * Replace every marker in `value` with its keychain value. Returns the SAME
6353
+ * reference when there is no marker (no allocation, no keychain call).
6354
+ */
6355
+ async function resolveSecretMarkers(value, secrets, options = {}) {
6356
+ const keepMarker = options.unresolved === "keep-marker";
6357
+ const owner = options.ownedBy;
6358
+ const inScope = (ref) => owner === void 0 || isSecretRefOwnedBy(ref, owner);
6359
+ const refs = collectSecretMarkerRefs(value).filter(inScope);
6360
+ if (refs.length === 0) return {
6361
+ value,
6362
+ unresolved: []
6363
+ };
6364
+ const answers = await secrets.resolve(refs);
6365
+ const unresolved = [];
6366
+ for (const ref of new Set(refs)) {
6367
+ const answer = answers[ref];
6368
+ if (answer === void 0) unresolved.push({
6369
+ ref,
6370
+ reason: "not-initialized"
6371
+ });
6372
+ else if (answer.kind === "unavailable") unresolved.push({
6373
+ ref,
6374
+ reason: answer.reason
6375
+ });
6376
+ else if (answer.kind === "missing" || answer.kind === "forbidden") unresolved.push({
6377
+ ref,
6378
+ reason: answer.kind
6379
+ });
6380
+ }
6381
+ const substitute = (v) => {
6382
+ if (isSecretMarker(v)) {
6383
+ if (!inScope(v.$secret)) return {
6384
+ keep: true,
6385
+ value: v
6386
+ };
6387
+ const answer = answers[v.$secret];
6388
+ if (answer?.kind === "value") return {
6389
+ keep: true,
6390
+ value: answer.value
6391
+ };
6392
+ return keepMarker ? {
6393
+ keep: true,
6394
+ value: v
6395
+ } : {
6396
+ keep: false,
6397
+ value: void 0
6398
+ };
6399
+ }
6400
+ if (Array.isArray(v)) {
6401
+ const items = [];
6402
+ for (const item of v) {
6403
+ const s = substitute(item);
6404
+ if (s.keep) items.push(s.value);
6405
+ }
6406
+ return {
6407
+ keep: true,
6408
+ value: items
6409
+ };
6410
+ }
6411
+ if (isRecord$1$1(v)) {
6412
+ const out = {};
6413
+ for (const [k, child] of Object.entries(v)) {
6414
+ const s = substitute(child);
6415
+ if (s.keep) out[k] = s.value;
6416
+ }
6417
+ return {
6418
+ keep: true,
6419
+ value: out
6420
+ };
6421
+ }
6422
+ return {
6423
+ keep: true,
6424
+ value: v
6425
+ };
6426
+ };
6427
+ return {
6428
+ value: substitute(value).value,
6429
+ unresolved
6430
+ };
6431
+ }
6432
+ /** An addon tried to replace a stored secret it could not read. Nothing was written. */
6433
+ var SecretOverwriteRefusedError = class extends Error {
6434
+ ref;
6435
+ reason;
6436
+ constructor(ref, reason) {
6437
+ super(`secret ${ref} was not replaced: its stored value cannot be read right now (${reason}), and an addon may not overwrite a secret it cannot see. Nothing was written.`);
6438
+ this.ref = ref;
6439
+ this.reason = reason;
6440
+ this.name = "SecretOverwriteRefusedError";
6441
+ }
6442
+ };
6443
+ function isRecord(value) {
6444
+ return typeof value === "object" && value !== null && !Array.isArray(value);
6445
+ }
6446
+ function resolvedValue(pass, marker) {
6447
+ const answer = pass.answers[marker.$secret];
6448
+ return answer?.kind === "value" ? answer.value : null;
6449
+ }
6450
+ async function atMarker(pass, incoming, stored) {
6451
+ if (incoming === null) return stored;
6452
+ if (typeof incoming !== "string") return incoming;
6453
+ if (incoming === resolvedValue(pass, stored)) return stored;
6454
+ const intent = classifySecretWrite(incoming);
6455
+ if (intent.kind !== "set") return stored;
6456
+ const ref = stored.$secret;
6457
+ if (!isSecretRefOwnedBy(ref, pass.secrets.owner)) return incoming;
6458
+ const answer = pass.answers[ref];
6459
+ if ((answer === void 0 || answer.kind === "unavailable" || answer.kind === "forbidden") && !pass.operatorWrite) throw new SecretOverwriteRefusedError(ref, answer === void 0 ? "not-initialized" : answer.kind === "unavailable" ? answer.reason : answer.kind);
6460
+ try {
6461
+ await pass.secrets.put(ref, intent.value);
6462
+ } catch (err) {
6463
+ throw new KeychainWriteRefusedError(ref, err);
6464
+ }
6465
+ pass.changedRefs.push(ref);
6466
+ return stored;
6467
+ }
6468
+ function inArray(pass, incoming, stored) {
6469
+ return incoming.map((item, index) => {
6470
+ const twin = stored[index];
6471
+ if (isSecretMarker(twin)) return typeof item === "string" && item === resolvedValue(pass, twin) ? twin : item;
6472
+ if (isRecord(item) && isRecord(twin)) return inArrayRow(pass, item, twin);
6473
+ if (Array.isArray(item) && Array.isArray(twin)) return inArray(pass, item, twin);
6474
+ return item;
6475
+ });
6476
+ }
6477
+ function inArrayRow(pass, incoming, stored) {
6478
+ const out = { ...incoming };
6479
+ for (const [key, value] of Object.entries(incoming)) {
6480
+ const twin = stored[key];
6481
+ if (isSecretMarker(twin)) {
6482
+ if (typeof value === "string" && value === resolvedValue(pass, twin)) out[key] = twin;
6483
+ } else if (isRecord(value) && isRecord(twin)) out[key] = inArrayRow(pass, value, twin);
6484
+ else if (Array.isArray(value) && Array.isArray(twin)) out[key] = inArray(pass, value, twin);
6485
+ }
6486
+ return out;
6487
+ }
6488
+ async function walk(pass, incoming, stored) {
6489
+ if (isSecretMarker(stored)) return atMarker(pass, incoming, stored);
6490
+ if (Array.isArray(incoming) && Array.isArray(stored)) return inArray(pass, incoming, stored);
6491
+ if (!isRecord(incoming) || !isRecord(stored)) return incoming;
6492
+ const out = { ...incoming };
6493
+ for (const [key, value] of Object.entries(incoming)) out[key] = await walk(pass, value, stored[key]);
6494
+ return out;
6495
+ }
6496
+ /** Restore markers a write-back carries as values. See the file doc. */
6497
+ async function restoreUnchangedSecrets(input) {
6498
+ const refs = [];
6499
+ for (const key of Object.keys(input.patch)) collectSecretMarkerRefs(input.stored[key], refs);
6500
+ const owned = refs.filter((ref) => isSecretRefOwnedBy(ref, input.secrets.owner));
6501
+ if (owned.length === 0) return {
6502
+ patch: input.patch,
6503
+ changedRefs: []
6504
+ };
6505
+ const pass = {
6506
+ secrets: input.secrets,
6507
+ answers: await input.secrets.resolve([...new Set(owned)]),
6508
+ operatorWrite: input.operatorWrite,
6509
+ changedRefs: []
6510
+ };
6511
+ const out = {};
6512
+ for (const [key, value] of Object.entries(input.patch)) out[key] = await walk(pass, value, input.stored[key]);
6513
+ return {
6514
+ patch: out,
6515
+ changedRefs: pass.changedRefs
6516
+ };
6517
+ }
6518
+ /** Structural equality over JSON-shaped values (key order does not matter). */
6519
+ function isJsonEqual(a, b) {
6520
+ if (Object.is(a, b)) return true;
6521
+ if (Array.isArray(a)) return Array.isArray(b) && a.length === b.length && a.every((v, i) => isJsonEqual(v, b[i]));
6522
+ if (isRecord(a) && isRecord(b)) {
6523
+ const keys = Object.keys(a);
6524
+ if (keys.length !== Object.keys(b).length) return false;
6525
+ return keys.every((k) => Object.prototype.hasOwnProperty.call(b, k) && isJsonEqual(a[k], b[k]));
6526
+ }
6527
+ return false;
6528
+ }
6529
+ /** The patch without the keys whose value already equals the stored one. */
6530
+ function dropUnchangedKeys(patch, stored) {
6531
+ const out = {};
6532
+ for (const [key, value] of Object.entries(patch)) {
6533
+ if (Object.prototype.hasOwnProperty.call(stored, key) && isJsonEqual(value, stored[key])) continue;
6534
+ out[key] = value;
6535
+ }
6536
+ return out;
6537
+ }
6538
+ /** The top-level keys of a blob that hold at least one of `owner`'s markers. */
6539
+ function markerKeysOf(blob, owner) {
6540
+ const keys = /* @__PURE__ */ new Set();
6541
+ for (const [key, value] of Object.entries(blob)) if (collectSecretMarkerRefs(value).some((ref) => isSecretRefOwnedBy(ref, owner))) keys.add(key);
6542
+ return keys;
6543
+ }
6544
+ function nodeFromStored(value, owner) {
6545
+ if (isSecretMarker(value)) return isSecretRefOwnedBy(value.$secret, owner) ? { kind: "leaf" } : null;
6546
+ if (!isRecord(value)) return null;
6547
+ const children = /* @__PURE__ */ new Map();
6548
+ for (const [key, child] of Object.entries(value)) {
6549
+ const node = nodeFromStored(child, owner);
6550
+ if (node !== null) children.set(key, node);
6551
+ }
6552
+ return children.size > 0 ? {
6553
+ kind: "object",
6554
+ children
6555
+ } : null;
6556
+ }
6557
+ /**
6558
+ * The declared secret tree, widened by every place the STORED blob holds a
6559
+ * marker under one of `keys` — so a marker the schema no longer declares (or
6560
+ * never declared: Wyze before b4906cec6) still gets the save path's
6561
+ * KEEP / SET / CLEAR semantics instead of being overwritten by whatever the
6562
+ * addon writes. Markers inside arrays are not added: a row has no id field to
6563
+ * match by unless the schema declares one. Only `owner`'s markers count: a
6564
+ * builtin that keeps another addon's marker (device-manager) never takes it
6565
+ * over.
6566
+ */
6567
+ function widenTreeWithStoredMarkers(declared, stored, keys, owner) {
6568
+ const added = /* @__PURE__ */ new Map();
6569
+ for (const key of keys) {
6570
+ const at = key.indexOf("@");
6571
+ const base = at > 0 ? key.slice(0, at) : key;
6572
+ if (declared.has(base) || added.has(base)) continue;
6573
+ const node = nodeFromStored(stored[key], owner);
6574
+ if (node !== null) added.set(base, node);
6575
+ }
6576
+ return added.size === 0 ? declared : new Map([...declared, ...added]);
6577
+ }
6578
+ /** The blob as stored now; a failed read REFUSES the write instead of guessing. */
6579
+ async function readStoredAddonBlob(raw) {
6580
+ const threeWay = raw.readAddonStoreResult;
6581
+ if (threeWay === void 0) return raw.readAddonStore();
6582
+ const result = await threeWay.call(raw);
6583
+ if (result.kind === "failed") throw new Error(`settings write refused: the stored blob could not be read (${result.error})`);
6584
+ return result.kind === "missing" ? {} : result.value;
6585
+ }
6586
+ function touchesTree(tree, patch) {
6587
+ if (tree.size === 0) return false;
6588
+ for (const key of Object.keys(patch)) {
6589
+ const at = key.indexOf("@");
6590
+ if (tree.has(at > 0 ? key.slice(0, at) : key)) return true;
6591
+ }
6592
+ return false;
6593
+ }
6594
+ /**
6595
+ * Which top-level keys of each store held markers when last seen. `undefined`
6596
+ * for a store not seen yet: its first write reads it, to be safe.
6597
+ */
6598
+ var MarkerKeyIndex = class {
6599
+ owner;
6600
+ byStore = /* @__PURE__ */ new Map();
6601
+ constructor(owner) {
6602
+ this.owner = owner;
6603
+ }
6604
+ seen(store, blob) {
6605
+ this.byStore.set(store, markerKeysOf(blob, this.owner));
6606
+ }
6607
+ wrote(store, patch) {
6608
+ const keys = this.byStore.get(store);
6609
+ if (keys === void 0) return;
6610
+ const now = markerKeysOf(patch, this.owner);
6611
+ for (const key of Object.keys(patch)) if (now.has(key)) keys.add(key);
6612
+ else keys.delete(key);
6613
+ }
6614
+ mayHoldMarkers(store, patch) {
6615
+ const keys = this.byStore.get(store);
6616
+ if (keys === void 0) return true;
6617
+ return Object.keys(patch).some((key) => keys.has(key));
6618
+ }
6619
+ };
6620
+ function createHandle(raw, opts) {
6621
+ const chains = /* @__PURE__ */ new Map();
6622
+ const serialize = (key, fn) => {
6623
+ const next = (chains.get(key) ?? Promise.resolve()).then(fn, fn);
6624
+ const tail = next.catch(() => void 0);
6625
+ chains.set(key, tail);
6626
+ tail.then(() => {
6627
+ if (chains.get(key) === tail) chains.delete(key);
6628
+ });
6629
+ return next;
6630
+ };
6631
+ const index = new MarkerKeyIndex(opts.secrets.owner);
6632
+ const resolveRead = async (store, blob) => {
6633
+ index.seen(store, blob);
6634
+ const { value, unresolved } = await resolveSecretMarkers(blob, opts.secrets, {
6635
+ unresolved: "keep-marker",
6636
+ ownedBy: opts.secrets.owner
6637
+ });
6638
+ if (unresolved.length > 0) opts.onUnresolved?.(unresolved);
6639
+ return value;
6640
+ };
6641
+ const write = async (store, declared, scope, patch, readStored, rawWrite) => {
6642
+ if (!touchesTree(declared, patch) && !index.mayHoldMarkers(store, patch)) {
6643
+ await rawWrite(patch);
6644
+ index.wrote(store, patch);
6645
+ return { changed: true };
6646
+ }
6647
+ return serialize(store, async () => {
6648
+ const stored = await readStored();
6649
+ index.seen(store, stored);
6650
+ const operatorWrite = opts.isOperatorWrite?.() === true;
6651
+ const restored = await restoreUnchangedSecrets({
6652
+ patch,
6653
+ stored,
6654
+ secrets: opts.secrets,
6655
+ operatorWrite
6656
+ });
6657
+ const result = await transformSecretWrite({
6658
+ tree: widenTreeWithStoredMarkers(declared, stored, Object.keys(restored.patch), opts.secrets.owner),
6659
+ secrets: opts.secrets,
6660
+ patch: restored.patch,
6661
+ stored,
6662
+ ...scope !== void 0 ? { scope } : {},
6663
+ operatorWrite
6664
+ });
6665
+ const effective = dropUnchangedKeys(result.patch, stored);
6666
+ const wroteBlob = Object.keys(effective).length > 0;
6667
+ if (wroteBlob) {
6668
+ await rawWrite(effective);
6669
+ index.wrote(store, effective);
6670
+ }
6671
+ const { orphaned } = await result.afterWrite();
6672
+ if (orphaned.length > 0) opts.onOrphaned(orphaned);
6673
+ return { changed: wroteBlob || restored.changedRefs.length > 0 };
6674
+ });
6675
+ };
6676
+ const writeAddon = (patch) => write("addon", opts.addonTree(), void 0, patch, () => readStoredAddonBlob(raw), (p) => raw.writeAddonStore(p));
6677
+ const readAddonStoreResult = raw.readAddonStoreResult;
6678
+ const readAddonStoreKeyResult = raw.readAddonStoreKeyResult;
6679
+ const readDeviceStoreBatch = raw.readDeviceStoreBatch;
6680
+ const overrides = {
6681
+ readAddonStore: async () => resolveRead("addon", await raw.readAddonStore()),
6682
+ ...readAddonStoreResult !== void 0 ? { readAddonStoreResult: async () => {
6683
+ const result = await readAddonStoreResult.call(raw);
6684
+ return result.kind === "value" ? {
6685
+ kind: "value",
6686
+ value: await resolveRead("addon", result.value)
6687
+ } : result;
6688
+ } } : {},
6689
+ ...readAddonStoreKeyResult !== void 0 ? { readAddonStoreKeyResult: async (key) => {
6690
+ const result = await readAddonStoreKeyResult.call(raw, key);
6691
+ if (result.kind !== "present") return result;
6692
+ const { value, unresolved } = await resolveSecretMarkers({ [key]: result.value }, opts.secrets, {
6693
+ unresolved: "keep-marker",
6694
+ ownedBy: opts.secrets.owner
6695
+ });
6696
+ if (unresolved.length > 0) opts.onUnresolved?.(unresolved);
6697
+ return {
6698
+ kind: "present",
6699
+ value: value[key]
6700
+ };
6701
+ } } : {},
6702
+ readDeviceStore: async (deviceId) => resolveRead(`device:${deviceId}`, await raw.readDeviceStore(deviceId)),
6703
+ ...readDeviceStoreBatch !== void 0 ? { readDeviceStoreBatch: async (deviceIds) => {
6704
+ const rows = await readDeviceStoreBatch.call(raw, deviceIds);
6705
+ const out = /* @__PURE__ */ new Map();
6706
+ for (const [deviceId, blob] of rows) out.set(deviceId, await resolveRead(`device:${deviceId}`, blob));
6707
+ return out;
6708
+ } } : {},
6709
+ writeAddonStore: async (patch) => {
6710
+ await writeAddon(patch);
6711
+ },
6712
+ writeDeviceStore: async (deviceId, patch) => {
6713
+ await write(`device:${deviceId}`, opts.deviceTree(), {
6714
+ kind: "device",
6715
+ deviceId
6716
+ }, patch, () => raw.readDeviceStore(deviceId), (p) => raw.writeDeviceStore(deviceId, p));
6717
+ }
6718
+ };
6719
+ return {
6720
+ settings: new Proxy(raw, { get(target, prop, receiver) {
6721
+ if (typeof prop === "string" && Object.prototype.hasOwnProperty.call(overrides, prop)) return Reflect.get(overrides, prop);
6722
+ const value = Reflect.get(target, prop, receiver);
6723
+ return typeof value === "function" ? value.bind(target) : value;
6724
+ } }),
6725
+ raw: {
6726
+ readAddonStore: async () => {
6727
+ const blob = await raw.readAddonStore();
6728
+ index.seen("addon", blob);
6729
+ return blob;
6730
+ },
6731
+ readDeviceStore: async (deviceId) => {
6732
+ const blob = await raw.readDeviceStore(deviceId);
6733
+ index.seen(`device:${deviceId}`, blob);
6734
+ return blob;
6735
+ }
6736
+ },
6737
+ writeAddonStore: writeAddon
6738
+ };
6739
+ }
6740
+ /** The context the addon sees, plus the private raw view and write outcome. */
6741
+ function createSecretAwareContext(context, opts) {
6742
+ const raw = context.settings;
6743
+ if (raw === void 0) return {
6744
+ context,
6745
+ handle: null
6746
+ };
6747
+ const handle = createHandle(raw, opts);
6748
+ return {
6749
+ context: new Proxy(context, { get(target, prop, receiver) {
6750
+ if (prop === "settings") return handle.settings;
6751
+ return Reflect.get(target, prop, receiver);
6752
+ } }),
6753
+ handle
6754
+ };
6755
+ }
6756
+ var LEAF = { kind: "leaf" };
6757
+ var DEFAULT_ITEM_ID_KEY = "id";
6758
+ function collectFields(fields, out) {
6759
+ for (const field of fields) {
6760
+ if (field.type === "group") {
6761
+ collectFields(field.fields, out);
6762
+ continue;
6763
+ }
6764
+ if (field.type === "sub-tabs") {
6765
+ for (const tab of field.tabs) collectFields(tab.fields, out);
6766
+ continue;
6767
+ }
6768
+ if (field.type === "editable-array") {
6769
+ const item = /* @__PURE__ */ new Map();
6770
+ for (const itemField of field.itemFields) if ("key" in itemField && isKeychainStoredField(itemField)) item.set(itemField.key, LEAF);
6771
+ if (item.size > 0) out.set(field.key, {
6772
+ kind: "array",
6773
+ idKey: field.itemIdKey ?? DEFAULT_ITEM_ID_KEY,
6774
+ item
6775
+ });
6776
+ continue;
6777
+ }
6778
+ if (!("key" in field) || typeof field.key !== "string") continue;
6779
+ if (isKeychainStoredField(field)) out.set(field.key, LEAF);
6780
+ }
6781
+ }
6782
+ /** The secret tree a settings schema declares. */
6783
+ function secretTreeFromSchema(schema) {
6784
+ const out = /* @__PURE__ */ new Map();
6785
+ if (schema === null) return out;
6786
+ for (const section of schema.sections) collectFields(section.fields, out);
6787
+ return out;
6788
+ }
6789
+ /** Parse `a.b[id].c` into segments; throws on a malformed path (a declaration bug). */
6790
+ function parseSecretStatePath(path) {
6791
+ const segments = [];
6792
+ for (const raw of path.split(".")) {
6793
+ const m = /^([^[\]]+)(?:\[([^[\]]+)\])?$/.exec(raw);
6794
+ if (m === null || m[1] === void 0) throw new Error(`secretStatePaths: malformed path "${path}"`);
6795
+ segments.push(m[2] !== void 0 ? {
6796
+ key: m[1],
6797
+ idKey: m[2]
6798
+ } : { key: m[1] });
6799
+ }
6800
+ if (segments.length === 0) throw new Error(`secretStatePaths: empty path`);
6801
+ if (segments[segments.length - 1]?.idKey !== void 0) throw new Error(`secretStatePaths: "${path}" ends on an array — name the member that is secret`);
6802
+ return segments;
6803
+ }
6804
+ function insert(into, segments) {
6805
+ const [head, ...rest] = segments;
6806
+ if (head === void 0) return;
6807
+ if (rest.length === 0) {
6808
+ into.set(head.key, LEAF);
6809
+ return;
6810
+ }
6811
+ const existing = into.get(head.key);
6812
+ if (head.idKey !== void 0) {
6813
+ const item = new Map(existing?.kind === "array" ? existing.item : []);
6814
+ insert(item, rest);
6815
+ into.set(head.key, {
6816
+ kind: "array",
6817
+ idKey: head.idKey,
6818
+ item
6819
+ });
6820
+ return;
6821
+ }
6822
+ const children = new Map(existing?.kind === "object" ? existing.children : []);
6823
+ insert(children, rest);
6824
+ into.set(head.key, {
6825
+ kind: "object",
6826
+ children
6827
+ });
6828
+ }
6829
+ /** Add hidden-state paths (`secretStatePaths`) to a schema-derived tree. */
6830
+ function mergeSecretStatePaths(tree, paths) {
6831
+ if (paths.length === 0) return tree;
6832
+ const out = new Map(tree);
6833
+ for (const path of paths) insert(out, parseSecretStatePath(path));
6834
+ return out;
6835
+ }
6836
+ /** First retry of a secret the keychain could not serve; doubles to {@link SECRET_RETRY_MAX_MS}. */
6837
+ var SECRET_RETRY_FIRST_MS = 5e3;
6838
+ var SECRET_RETRY_MAX_MS = 5 * 6e4;
6839
+ /** Coalesces a burst of `keychain.changed` events into one re-resolve. */
6840
+ var SECRET_CHANGE_DEBOUNCE_MS = 250;
5958
6841
  /**
5959
6842
  * Base class for CamStack addons. Eliminates settings boilerplate:
5960
6843
  *
@@ -6024,6 +6907,33 @@ var BaseAddon = class {
6024
6907
  settingsStoreReady = false;
6025
6908
  /** Default config values. Provided via constructor. */
6026
6909
  defaults;
6910
+ /**
6911
+ * Hidden-state paths that hold secrets (D787) — values the addon writes
6912
+ * itself (`updateGlobalSettings`, `state()`) that no form field declares.
6913
+ * Stored in the keychain exactly like a `password` field. Syntax:
6914
+ * `'snapshotSigningKey'`, `'identity.pincode'`, `'tokens[userId].accessToken'`
6915
+ * (`key[<id field>]` addresses array items by id, never by index).
6916
+ */
6917
+ secretStatePaths = [];
6918
+ _addonSecretTree = null;
6919
+ _deviceSecretTree = null;
6920
+ /** Refs the last resolved config pointed at — a change to one re-resolves. */
6921
+ _configSecretRefs = /* @__PURE__ */ new Set();
6922
+ _unresolvedSecrets = [];
6923
+ _secretRetryTimer = null;
6924
+ _secretRetryDelayMs = SECRET_RETRY_FIRST_MS;
6925
+ _secretChangeTimer = null;
6926
+ _secretChangeUnsub = null;
6927
+ /** >0 while an OPERATOR's settings write is being applied. */
6928
+ _operatorWriteDepth = 0;
6929
+ /**
6930
+ * The keychain-aware settings handle (D798). Its `raw` view is the ONLY way
6931
+ * to the marker-bearing blobs and stays private to this class: the form
6932
+ * hydrate and config resolution need markers, addon code never does.
6933
+ */
6934
+ _secretSettings = null;
6935
+ /** Refs an addon-facing read could not resolve — each is logged once per process. */
6936
+ _loggedUnresolvedReads = /* @__PURE__ */ new Set();
6027
6937
  constructor(defaults) {
6028
6938
  this.defaults = defaults;
6029
6939
  this._config = { ...defaults };
@@ -6059,8 +6969,26 @@ var BaseAddon = class {
6059
6969
  return this._config;
6060
6970
  }
6061
6971
  async initialize(context) {
6062
- this._ctx = context;
6972
+ const secrets = context.secrets;
6973
+ if (secrets !== void 0) {
6974
+ const { context: wrapped, handle } = createSecretAwareContext(context, {
6975
+ secrets,
6976
+ addonTree: () => this.addonSecretTree(),
6977
+ deviceTree: () => this.deviceSecretTree(),
6978
+ onOrphaned: (refs) => context.logger.warn("keychain refs dropped by a settings write could not be deleted", { meta: { refs: [...refs] } }),
6979
+ isOperatorWrite: () => this._operatorWriteDepth > 0,
6980
+ onUnresolved: (unresolved) => this.logUnresolvedRead(unresolved)
6981
+ });
6982
+ this._ctx = wrapped;
6983
+ this._secretSettings = handle;
6984
+ } else {
6985
+ this._ctx = context;
6986
+ this._secretSettings = null;
6987
+ }
6063
6988
  await this.resolveConfig();
6989
+ if (secrets !== void 0) this._secretChangeUnsub = secrets.onChange((ref) => {
6990
+ if (this._configSecretRefs.has(ref)) this.scheduleSecretReresolve(SECRET_CHANGE_DEBOUNCE_MS);
6991
+ });
6064
6992
  const result = await this.onInitialize();
6065
6993
  this.emitLifecycle(EventCategory.AddonStarted);
6066
6994
  const normalized = normalizeAddonInitResult(result);
@@ -6093,6 +7021,12 @@ var BaseAddon = class {
6093
7021
  */
6094
7022
  async onHubReachable() {}
6095
7023
  async shutdown() {
7024
+ this._secretChangeUnsub?.();
7025
+ this._secretChangeUnsub = null;
7026
+ if (this._secretRetryTimer !== null) clearTimeout(this._secretRetryTimer);
7027
+ if (this._secretChangeTimer !== null) clearTimeout(this._secretChangeTimer);
7028
+ this._secretRetryTimer = null;
7029
+ this._secretChangeTimer = null;
6096
7030
  this.emitLifecycle(EventCategory.AddonStopped);
6097
7031
  if (this.autoEmitReadiness) this.emitReadinessForProviders("down");
6098
7032
  await this.onShutdown();
@@ -6167,11 +7101,8 @@ var BaseAddon = class {
6167
7101
  async getGlobalSettings(overlay, cap, nodeId) {
6168
7102
  const schema = this.globalSettingsSchema(cap);
6169
7103
  if (!schema) return { sections: [] };
6170
- const projected = await this.resolveGlobalStore(nodeId, cap);
6171
- return hydrateSchema(schema, overlay ? {
6172
- ...projected,
6173
- ...overlay
6174
- } : projected);
7104
+ const projected = await this.readRawProjectedStore(nodeId, cap);
7105
+ return hydrateSchema(schema, overlay ? await this.overlayKeepingMarkers(projected, overlay) : projected, { inlineSecretsAsViews: true });
6175
7106
  }
6176
7107
  /**
6177
7108
  * The integration-level view of this addon's settings: exactly the sections
@@ -6216,11 +7147,11 @@ var BaseAddon = class {
6216
7147
  });
6217
7148
  }
6218
7149
  if (sections.length === 0) return null;
6219
- const projected = await this.resolveGlobalStore(nodeId);
7150
+ const projected = await this.readRawProjectedStore(nodeId);
6220
7151
  return hydrateSchema({
6221
7152
  ...schema,
6222
7153
  sections
6223
- }, projected);
7154
+ }, projected, { inlineSecretsAsViews: true });
6224
7155
  }
6225
7156
  /**
6226
7157
  * The raw addon store PROJECTED onto the target node's bare per-node keys:
@@ -6233,12 +7164,50 @@ var BaseAddon = class {
6233
7164
  * the store for custom option logic (option narrowing, value snapping) to
6234
7165
  * read it per-node — never `ctx.settings.readAddonStore()` directly.
6235
7166
  * `nodeId` omitted ⇒ the local node (node-blind injection from ctx).
7167
+ *
7168
+ * Keychain values come back RESOLVED (D798): a secret reads as its value,
7169
+ * never as a `{ $secret }` marker. One the keychain cannot serve right now
7170
+ * stays a marker — "stored, unavailable" (`isSecretMarker()` is true, and it
7171
+ * is listed in {@link unresolvedSecrets}) — never `''` and never absent, so
7172
+ * it cannot be mistaken for "nothing stored, mint a new one". Writing the
7173
+ * resolved blob back is a no-op for every unchanged secret.
6236
7174
  */
6237
7175
  async resolveGlobalStore(nodeId, cap) {
6238
7176
  const raw = await this._ctx?.settings?.readAddonStore() ?? {};
7177
+ return this.projectForNode(raw, nodeId, cap);
7178
+ }
7179
+ projectForNode(store, nodeId, cap) {
6239
7180
  const keys = this.perNodeKeys(cap);
6240
7181
  const node = normalizeNodeId(nodeId ?? this._ctx?.kernel?.localNodeId);
6241
- return keys.size > 0 ? projectStore(raw, keys, node) : raw;
7182
+ return keys.size > 0 ? projectStore(store, keys, node) : store;
7183
+ }
7184
+ /** The PROJECTED store with its markers — the form hydrate only (D798). */
7185
+ async readRawProjectedStore(nodeId, cap) {
7186
+ const raw = await this.rawSettings()?.readAddonStore() ?? {};
7187
+ return this.projectForNode(raw, nodeId, cap);
7188
+ }
7189
+ /**
7190
+ * `{ ...stored, ...overlay }`, except that an overlay member equal to the
7191
+ * RESOLVED stored one keeps the stored (marker-bearing) member — so a form
7192
+ * hydrated from a resolved overlay still shows a secret as "set", never as
7193
+ * its value.
7194
+ */
7195
+ async overlayKeepingMarkers(stored, overlay) {
7196
+ const secrets = this._ctx?.secrets;
7197
+ const merged = {
7198
+ ...stored,
7199
+ ...overlay
7200
+ };
7201
+ if (secrets === void 0 || collectSecretMarkerRefs(stored).length === 0) return merged;
7202
+ const { value: resolved } = await resolveSecretMarkers(stored, secrets, {
7203
+ unresolved: "keep-marker",
7204
+ ownedBy: secrets.owner
7205
+ });
7206
+ for (const key of Object.keys(overlay)) {
7207
+ if (collectSecretMarkerRefs(stored[key]).length === 0) continue;
7208
+ if (isJsonEqual(overlay[key], resolved[key])) merged[key] = stored[key];
7209
+ }
7210
+ return merged;
6242
7211
  }
6243
7212
  /**
6244
7213
  * Whether ONE global key of this addon's store was written, read three-way
@@ -6274,18 +7243,58 @@ var BaseAddon = class {
6274
7243
  value: result.value[key]
6275
7244
  };
6276
7245
  }
7246
+ /**
7247
+ * The OPERATOR's write — a settings form or an admin API call, dispatched by
7248
+ * the kernel. Identical to {@link updateGlobalSettings}, except that a secret
7249
+ * the operator sends is stored as sent even when it equals a pre-keychain
7250
+ * inline value: the operator re-entering a password is a change, an addon
7251
+ * writing back what it read is not (D787).
7252
+ */
7253
+ async updateGlobalSettingsAsOperator(patch, nodeId) {
7254
+ this._operatorWriteDepth++;
7255
+ try {
7256
+ await this.applyGlobalPatch(patch, nodeId);
7257
+ } finally {
7258
+ this._operatorWriteDepth--;
7259
+ }
7260
+ }
6277
7261
  async updateGlobalSettings(patch, nodeId) {
7262
+ await this.applyGlobalPatch(patch, nodeId);
7263
+ }
7264
+ /**
7265
+ * REMOVE stored secrets — their keychain values and their markers (D787).
7266
+ *
7267
+ * Writing `''` to a secret field KEEPS what is stored (an empty string is
7268
+ * what a defaults fallback writes back, and it must never destroy a
7269
+ * credential), so code that means "forget this token" says so here. Without
7270
+ * a keychain (an older kernel) it writes `''`, as such code always did.
7271
+ */
7272
+ async clearSecrets(keys, nodeId) {
7273
+ const tree = this.addonSecretTree();
7274
+ const keychain = this._ctx?.secrets !== void 0;
7275
+ const stored = keychain ? await this.readAddonStoreWithRetry() : {};
7276
+ const patch = {};
7277
+ for (const key of keys) {
7278
+ const keychainStored = tree.has(key) || collectSecretMarkerRefs(stored[key]).length > 0;
7279
+ patch[key] = keychain && keychainStored ? SECRET_CLEAR : "";
7280
+ }
7281
+ await this.applyGlobalPatch(patch, nodeId);
7282
+ }
7283
+ async applyGlobalPatch(barePatch, nodeId) {
6278
7284
  const keys = this.perNodeKeys();
6279
7285
  const localNode = normalizeNodeId(this._ctx?.kernel?.localNodeId);
6280
7286
  const target = normalizeNodeId(nodeId ?? this._ctx?.kernel?.localNodeId);
6281
- const barePatch = patch;
6282
7287
  const scoped = keys.size > 0 ? scopePatch(barePatch, keys, target) : barePatch;
6283
- await this._ctx?.settings?.writeAddonStore(scoped);
7288
+ const handle = this._secretSettings;
7289
+ if (handle !== null) {
7290
+ const { changed } = await handle.writeAddonStore(scoped);
7291
+ if (!changed) return;
7292
+ } else await this._ctx?.settings?.writeAddonStore(scoped);
6284
7293
  if (target !== localNode) return;
6285
7294
  await this.resolveConfig();
6286
7295
  await this.onConfigChanged();
6287
7296
  this.emitLifecycle(EventCategory.AddonUpdated, { level: "global" });
6288
- this.maybeAutoRestart(patch, this.globalSettingsSchema());
7297
+ this.maybeAutoRestart(Object.keys(barePatch), this.globalSettingsSchema());
6289
7298
  }
6290
7299
  /**
6291
7300
  * The set of field keys the global settings schema declares `perNode: true`
@@ -6310,7 +7319,7 @@ var BaseAddon = class {
6310
7319
  * time to return its response before the addon is torn down and
6311
7320
  * re-initialised by `AddonRegistryService.restartAddon`.
6312
7321
  */
6313
- maybeAutoRestart(patch, schema) {
7322
+ maybeAutoRestart(patchKeys, schema) {
6314
7323
  if (!schema) return;
6315
7324
  const restartKeys = /* @__PURE__ */ new Set();
6316
7325
  for (const section of schema.sections) for (const field of section.fields) {
@@ -6318,13 +7327,13 @@ var BaseAddon = class {
6318
7327
  if (field.requiresRestart) restartKeys.add(field.key);
6319
7328
  }
6320
7329
  if (restartKeys.size === 0) return;
6321
- if (!Object.keys(patch).some((k) => restartKeys.has(k))) return;
7330
+ if (!patchKeys.some((k) => restartKeys.has(k))) return;
6322
7331
  const ctx = this._ctx;
6323
7332
  if (!ctx) return;
6324
7333
  const addonId = ctx.id;
6325
7334
  setImmediate(() => {
6326
7335
  ctx.api.addons?.restartAddon?.mutate({ addonId }).then(() => {
6327
- ctx.logger.info("addon auto-restart triggered by restart-required setting change", { meta: { changedFields: Object.keys(patch).filter((k) => restartKeys.has(k)) } });
7336
+ ctx.logger.info("addon auto-restart triggered by restart-required setting change", { meta: { changedFields: patchKeys.filter((k) => restartKeys.has(k)) } });
6328
7337
  }).catch((err) => {
6329
7338
  ctx.logger.error("addon auto-restart failed", { meta: { error: err instanceof Error ? err.message : String(err) } });
6330
7339
  });
@@ -6333,7 +7342,7 @@ var BaseAddon = class {
6333
7342
  async getDeviceSettings(deviceId) {
6334
7343
  const schema = this.deviceSettingsSchema();
6335
7344
  if (!schema) return { sections: [] };
6336
- return hydrateSchema(schema, await this._ctx?.settings?.readDeviceStore(deviceId) ?? {});
7345
+ return hydrateSchema(schema, await this.rawSettings()?.readDeviceStore(deviceId) ?? {}, { inlineSecretsAsViews: true });
6337
7346
  }
6338
7347
  async updateDeviceSettings(deviceId, patch) {
6339
7348
  await this._ctx?.settings?.writeDeviceStore(deviceId, patch);
@@ -6463,7 +7472,7 @@ var BaseAddon = class {
6463
7472
  * selection at boot (absent scoped key ⇒ the constructor default wins).
6464
7473
  */
6465
7474
  async resolveConfig() {
6466
- const stored = await this.readAddonStoreWithRetry();
7475
+ const stored = await this.resolveStoredSecrets(await this.readAddonStoreWithRetry());
6467
7476
  const perNode = this.perNodeKeys();
6468
7477
  const localNode = normalizeNodeId(this._ctx?.kernel?.localNodeId);
6469
7478
  const resolved = { ...this.defaults };
@@ -6488,7 +7497,7 @@ var BaseAddon = class {
6488
7497
  key,
6489
7498
  schema,
6490
7499
  fallback,
6491
- read: () => this.readAddonStoreWithRetry(),
7500
+ read: async () => this.resolveStoredSecrets(await this.readAddonStoreWithRetry()),
6492
7501
  write: async (patch) => {
6493
7502
  await this._ctx?.settings?.writeAddonStore(patch);
6494
7503
  },
@@ -6505,7 +7514,7 @@ var BaseAddon = class {
6505
7514
  key,
6506
7515
  schema,
6507
7516
  fallback,
6508
- read: async () => await this._ctx?.settings?.readDeviceStore(deviceId) ?? {},
7517
+ read: async () => this.resolveStoredSecrets(await this.rawSettings()?.readDeviceStore(deviceId) ?? {}, false),
6509
7518
  write: async (patch) => {
6510
7519
  await this._ctx?.settings?.writeDeviceStore(deviceId, patch);
6511
7520
  },
@@ -6517,6 +7526,87 @@ var BaseAddon = class {
6517
7526
  } })
6518
7527
  });
6519
7528
  }
7529
+ /** The addon store's secret tree: schema fields by TYPE, plus `secretStatePaths`. */
7530
+ addonSecretTree() {
7531
+ this._addonSecretTree ??= mergeSecretStatePaths(secretTreeFromSchema(this.globalSettingsSchema()), this.secretStatePaths);
7532
+ return this._addonSecretTree;
7533
+ }
7534
+ deviceSecretTree() {
7535
+ this._deviceSecretTree ??= secretTreeFromSchema(this.deviceSettingsSchema());
7536
+ return this._deviceSecretTree;
7537
+ }
7538
+ /**
7539
+ * Secrets of this addon's stored config that could not be resolved on the
7540
+ * last read, with why. Non-empty means the addon is running WITHOUT them —
7541
+ * an addon whose function needs one should report itself degraded rather
7542
+ * than start on an empty credential.
7543
+ */
7544
+ get unresolvedSecrets() {
7545
+ return this._unresolvedSecrets;
7546
+ }
7547
+ /**
7548
+ * Substitute every keychain marker in a stored blob with its value. With no
7549
+ * keychain (no `ctx.secrets`) or no marker, the blob comes back unchanged.
7550
+ * An unresolvable value is LEFT OUT (never `''`), logged by ref — never by
7551
+ * value — and, when the cause can pass, retried with backoff. Nothing is
7552
+ * ever written back from here.
7553
+ */
7554
+ async resolveStoredSecrets(blob, trackForConfig = true) {
7555
+ const secrets = this._ctx?.secrets;
7556
+ if (secrets === void 0) return blob;
7557
+ const refs = collectSecretMarkerRefs(blob);
7558
+ if (trackForConfig) this._configSecretRefs = new Set(refs);
7559
+ if (refs.length === 0) {
7560
+ if (trackForConfig) this._unresolvedSecrets = [];
7561
+ return blob;
7562
+ }
7563
+ const { value, unresolved } = await resolveSecretMarkers(blob, secrets);
7564
+ if (trackForConfig) {
7565
+ this._unresolvedSecrets = unresolved;
7566
+ if (unresolved.length > 0) {
7567
+ this._ctx?.logger?.error?.("secret unavailable — running without it, will retry", { meta: { secrets: unresolved.map((u) => ({
7568
+ ref: u.ref,
7569
+ reason: u.reason
7570
+ })) } });
7571
+ if (unresolved.some((u) => u.reason !== "missing" && u.reason !== "forbidden")) {
7572
+ this.scheduleSecretReresolve(this._secretRetryDelayMs);
7573
+ this._secretRetryDelayMs = Math.min(this._secretRetryDelayMs * 2, SECRET_RETRY_MAX_MS);
7574
+ }
7575
+ } else this._secretRetryDelayMs = SECRET_RETRY_FIRST_MS;
7576
+ }
7577
+ return value;
7578
+ }
7579
+ /**
7580
+ * The marker-bearing settings reads (D798) — private on purpose. Without a
7581
+ * keychain the context's own view is already raw.
7582
+ */
7583
+ rawSettings() {
7584
+ return this._secretSettings?.raw ?? this._ctx?.settings;
7585
+ }
7586
+ /** An addon-facing read met markers it could not resolve: say so once per ref. */
7587
+ logUnresolvedRead(unresolved) {
7588
+ const fresh = unresolved.filter((u) => !this._loggedUnresolvedReads.has(u.ref));
7589
+ if (fresh.length === 0) return;
7590
+ for (const u of fresh) this._loggedUnresolvedReads.add(u.ref);
7591
+ this._ctx?.logger?.warn?.("settings read: a stored secret is unavailable — it reads as its marker, not as a value", { meta: { secrets: fresh.map((u) => ({
7592
+ ref: u.ref,
7593
+ reason: u.reason
7594
+ })) } });
7595
+ }
7596
+ /** Re-resolve the config (a keychain-only change, or a retry) and apply it. */
7597
+ scheduleSecretReresolve(delayMs) {
7598
+ const timerOf = delayMs === SECRET_CHANGE_DEBOUNCE_MS ? "_secretChangeTimer" : "_secretRetryTimer";
7599
+ if (this[timerOf] !== null) return;
7600
+ const timer = setTimeout(() => {
7601
+ this[timerOf] = null;
7602
+ if (this._ctx === null) return;
7603
+ this.resolveConfig().then(() => this.onConfigChanged()).catch((err) => {
7604
+ this._ctx?.logger?.error?.("re-resolving secrets failed", { meta: { error: err instanceof Error ? err.message : String(err) } });
7605
+ });
7606
+ }, delayMs);
7607
+ timer.unref?.();
7608
+ this[timerOf] = timer;
7609
+ }
6520
7610
  /**
6521
7611
  * Wrap `ctx.settings.readAddonStore()` with a short retry budget so a
6522
7612
  * transient settings-store outage (mid-restart of sqlite-settings, tsx-watch
@@ -6529,7 +7619,7 @@ var BaseAddon = class {
6529
7619
  * `{}` (defaults) — the addon's first successful patch will rehydrate.
6530
7620
  */
6531
7621
  async readAddonStoreWithRetry() {
6532
- const settings = this._ctx?.settings;
7622
+ const settings = this.rawSettings();
6533
7623
  if (!settings) return {};
6534
7624
  const delaysMs = [
6535
7625
  150,
@@ -10142,6 +11232,278 @@ var CameraSwitchGroupSchema = object({
10142
11232
  fetchedAt: number()
10143
11233
  });
10144
11234
  /**
11235
+ * The trainer contract — what the hub hands the cloud trainer and what it
11236
+ * gets back (cloud training, D805+).
11237
+ *
11238
+ * The trainer (`hf/camstack-trainer`, published as the Hugging Face repo
11239
+ * `camstack/camstack-trainer`) is a separate AGPL program the hub never
11240
+ * imports: `job.json` goes in, files come out, and progress is `CAMSTACK_EVENT`
11241
+ * lines on stdout. These schemas are the hub's half of that boundary; the
11242
+ * trainer's pydantic models (and the JSON Schemas generated from them under
11243
+ * `hf/camstack-trainer/schemas/`) are the other half. A change here is a
11244
+ * change there, in the same piece of work.
11245
+ *
11246
+ * No `.default()` anywhere: defaults do not run on the addon cap path, so the
11247
+ * orchestrator fills every field of a job spec explicitly.
11248
+ */
11249
+ var TRAINING_JOB_SCHEMA = "camstack.training/v1";
11250
+ var TRAINING_RESULT_SCHEMA = "camstack.training-result/v1";
11251
+ /** What the trainer can export. Edge TPU is a later, separate image. */
11252
+ var TrainingExportSchema = _enum([
11253
+ "onnx",
11254
+ "openvino-fp16",
11255
+ "openvino-int8",
11256
+ "coreml-fp16"
11257
+ ]);
11258
+ var FloorsSchema = record(string(), number().min(0).max(1));
11259
+ object({
11260
+ schema: literal(TRAINING_JOB_SCHEMA),
11261
+ jobKey: string().uuid(),
11262
+ target: object({
11263
+ kind: literal("detector"),
11264
+ step: literal("object-detection")
11265
+ }),
11266
+ base: object({
11267
+ modelId: string().min(1),
11268
+ /** Ultralytics weights id, e.g. `yolov9m.pt`. */
11269
+ weights: string().min(1),
11270
+ imgsz: number().int().positive()
11271
+ }),
11272
+ baseline: object({
11273
+ modelId: string().min(1),
11274
+ /** The baseline ONNX the holdout comparison runs; public mirror URL. */
11275
+ onnxUrl: string().url(),
11276
+ imgsz: number().int().positive(),
11277
+ floors: FloorsSchema
11278
+ }),
11279
+ dataset: object({
11280
+ versionId: string().min(1),
11281
+ annotationHash: string(),
11282
+ /** sha256 of the uploaded archive; the trainer refuses a mismatch (exit 65). */
11283
+ sha256: string().regex(/^[0-9a-f]{64}$/)
11284
+ }),
11285
+ split: object({
11286
+ holdoutCameras: array(number().int()),
11287
+ /** When no camera is held out: the last N days of every camera. */
11288
+ holdoutLastDays: number().int().nonnegative(),
11289
+ valFraction: number().min(0).max(.5),
11290
+ seed: number().int()
11291
+ }),
11292
+ hyper: object({
11293
+ epochs: number().int().positive(),
11294
+ batch: number().int().positive(),
11295
+ lr0: number().positive(),
11296
+ /** Layers frozen from the start of the backbone; 0 = none. */
11297
+ freeze: number().int().nonnegative(),
11298
+ patience: number().int().nonnegative(),
11299
+ seed: number().int()
11300
+ }),
11301
+ replay: object({
11302
+ source: literal("coco2017"),
11303
+ count: number().int().nonnegative()
11304
+ }),
11305
+ exports: array(TrainingExportSchema).min(1),
11306
+ calibration: object({ maxFrames: number().int().positive() }),
11307
+ floors: object({
11308
+ minSupport: number().int().positive(),
11309
+ clamp: number().min(0).max(1)
11310
+ }),
11311
+ int8Gate: object({ maxMap50Drop: number().min(0).max(1) }),
11312
+ catalog: object({
11313
+ id: string().regex(/^[a-z0-9][a-z0-9-]{2,80}$/),
11314
+ name: string().min(1).max(160)
11315
+ })
11316
+ });
11317
+ /** One regular file of the bundle. An mlpackage contributes one row per member. */
11318
+ var TrainingResultFileSchema = object({
11319
+ path: string().min(1),
11320
+ bytes: number().int().nonnegative(),
11321
+ sha256: string().regex(/^[0-9a-f]{64}$/),
11322
+ format: _enum([
11323
+ "onnx",
11324
+ "openvino",
11325
+ "coreml",
11326
+ "pt"
11327
+ ]),
11328
+ variant: _enum(["base", "int8"])
11329
+ });
11330
+ var DraftFormatSchema = object({
11331
+ /** RELATIVE path inside the bundle; the hub rewrites it to `camstack-local://`. */
11332
+ url: string().min(1),
11333
+ sizeMB: number().nonnegative(),
11334
+ isDirectory: boolean().optional(),
11335
+ files: array(string()).optional(),
11336
+ runtimes: array(literal("python")).optional(),
11337
+ revision: string().min(1)
11338
+ });
11339
+ /** The trainer's half of a catalog entry; the hub completes it (labels, licence, group). */
11340
+ var TrainingCatalogDraftSchema = object({
11341
+ id: string().min(1),
11342
+ name: string().min(1),
11343
+ description: string(),
11344
+ labels: array(unknown()),
11345
+ inputSize: object({
11346
+ width: number().int().positive(),
11347
+ height: number().int().positive()
11348
+ }),
11349
+ preprocessMode: literal("letterbox"),
11350
+ defaultClassFloors: FloorsSchema,
11351
+ formats: object({
11352
+ onnx: DraftFormatSchema.optional(),
11353
+ openvino: DraftFormatSchema.optional(),
11354
+ coreml: DraftFormatSchema.optional()
11355
+ })
11356
+ });
11357
+ /** One class of one model's holdout report (the eval harness's summary). */
11358
+ var TrainingEvalClassSchema = object({
11359
+ positives: number().int(),
11360
+ floor: number().nullable(),
11361
+ tp: number().int(),
11362
+ fp: number().int(),
11363
+ fn: number().int(),
11364
+ precision: number().nullable(),
11365
+ recall: number().nullable(),
11366
+ ap50: number().nullable(),
11367
+ recallByCamera: record(string(), number().nullable()).optional(),
11368
+ recallByLight: record(string(), number().nullable()).optional(),
11369
+ fpByCamera: record(string(), number()).optional(),
11370
+ smallFound: number().int().optional(),
11371
+ smallTotal: number().int().optional()
11372
+ }).passthrough();
11373
+ var TrainingEvalReportSchema = object({
11374
+ frames: number().int(),
11375
+ classes: record(string(), TrainingEvalClassSchema)
11376
+ }).passthrough();
11377
+ /**
11378
+ * A succeeded result carries every block; a failed one carries the error and
11379
+ * whatever was known by then — the other blocks are ABSENT, not null. The
11380
+ * orchestrator checks the blocks it needs before it trusts a success.
11381
+ */
11382
+ var TrainingResultSchema = object({
11383
+ schema: literal(TRAINING_RESULT_SCHEMA),
11384
+ jobKey: string(),
11385
+ status: _enum(["succeeded", "failed"]),
11386
+ error: object({
11387
+ stage: string(),
11388
+ code: string(),
11389
+ message: string()
11390
+ }).nullable(),
11391
+ trainer: object({
11392
+ version: string(),
11393
+ revision: string()
11394
+ }),
11395
+ toolchain: record(string(), string().nullable()),
11396
+ dataset: object({
11397
+ versionId: string(),
11398
+ annotationHash: string(),
11399
+ sha256: string(),
11400
+ frames: object({
11401
+ train: number().int(),
11402
+ val: number().int(),
11403
+ holdout: number().int()
11404
+ }),
11405
+ holdoutCameras: array(number().int()),
11406
+ replayImages: number().int()
11407
+ }).optional(),
11408
+ training: object({
11409
+ epochsRun: number().int(),
11410
+ bestEpoch: number().int(),
11411
+ bestMap50: number(),
11412
+ bestMap50_95: number(),
11413
+ seconds: number()
11414
+ }).optional(),
11415
+ evaluation: object({
11416
+ holdoutFrames: number().int(),
11417
+ baseline: TrainingEvalReportSchema.nullable(),
11418
+ candidate: TrainingEvalReportSchema.nullable(),
11419
+ candidateInt8: TrainingEvalReportSchema.nullable(),
11420
+ recallDeltaByCamera: record(string(), record(string(), number())).nullable(),
11421
+ map50: record(string(), number().nullable())
11422
+ }).optional(),
11423
+ floors: object({
11424
+ baseline: FloorsSchema,
11425
+ candidate: FloorsSchema,
11426
+ candidateInt8: FloorsSchema.nullable(),
11427
+ notes: array(string())
11428
+ }).optional(),
11429
+ int8: object({
11430
+ kept: boolean(),
11431
+ map50Fp16: number().nullable(),
11432
+ map50Int8: number().nullable(),
11433
+ reason: string().nullable()
11434
+ }).optional(),
11435
+ exportsDropped: array(object({
11436
+ export: string(),
11437
+ reason: string()
11438
+ })).optional(),
11439
+ files: array(TrainingResultFileSchema).optional(),
11440
+ bundle: object({
11441
+ path: literal("bundle.tar"),
11442
+ bytes: number().int().nonnegative(),
11443
+ sha256: string().regex(/^[0-9a-f]{64}$/)
11444
+ }).nullable().optional(),
11445
+ catalogDraft: object({
11446
+ base: TrainingCatalogDraftSchema,
11447
+ int8: TrainingCatalogDraftSchema.nullable()
11448
+ }).nullable().optional(),
11449
+ licence: string()
11450
+ });
11451
+ var TrainingStageSchema = _enum([
11452
+ "prepare",
11453
+ "replay",
11454
+ "train",
11455
+ "eval",
11456
+ "export",
11457
+ "package"
11458
+ ]);
11459
+ var EventBase = {
11460
+ v: literal(1),
11461
+ ts: number()
11462
+ };
11463
+ discriminatedUnion("type", [
11464
+ object({
11465
+ ...EventBase,
11466
+ type: literal("stage"),
11467
+ stage: TrainingStageSchema
11468
+ }),
11469
+ object({
11470
+ ...EventBase,
11471
+ type: literal("epoch"),
11472
+ epoch: number().int(),
11473
+ epochs: number().int(),
11474
+ boxLoss: number().nullable().optional(),
11475
+ map50: number().nullable().optional(),
11476
+ map50_95: number().nullable().optional(),
11477
+ etaSec: number().nullable().optional()
11478
+ }),
11479
+ object({
11480
+ ...EventBase,
11481
+ type: literal("metric"),
11482
+ name: string(),
11483
+ value: number()
11484
+ }),
11485
+ object({
11486
+ ...EventBase,
11487
+ type: literal("artifact"),
11488
+ path: string(),
11489
+ bytes: number(),
11490
+ sha256: string()
11491
+ }),
11492
+ object({
11493
+ ...EventBase,
11494
+ type: literal("done"),
11495
+ status: _enum(["succeeded", "failed"]),
11496
+ resultSha256: string().nullable().optional()
11497
+ }),
11498
+ object({
11499
+ ...EventBase,
11500
+ type: literal("error"),
11501
+ stage: string(),
11502
+ code: string(),
11503
+ message: string()
11504
+ })
11505
+ ]);
11506
+ /**
10145
11507
  * What the gate decided about a birth, from the CALLER's point of view.
10146
11508
  *
10147
11509
  * Deliberately not `ConfirmationVerdict`: `undecided` is not a birth decision
@@ -13456,7 +14818,9 @@ var AddonHttpRouteSchema = object({
13456
14818
  "authenticated",
13457
14819
  "admin"
13458
14820
  ]).optional(),
13459
- description: string().optional()
14821
+ description: string().optional(),
14822
+ /** The hub limits this route per client address before the handler runs. */
14823
+ rateLimit: _enum(["auth"]).optional()
13460
14824
  });
13461
14825
  /**
13462
14826
  * Cross-process route invocation envelope. The hub captures the
@@ -14279,6 +15643,37 @@ var BackupDestinationInfoSchema = object({
14279
15643
  lastError: string().optional()
14280
15644
  });
14281
15645
  /**
15646
+ * How an archive is encrypted (operator decision 2026-10-09): to a backup
15647
+ * PUBLIC key the hub holds, so only the operator's secret key opens it.
15648
+ * Absent on a plain `.tar.gz` — every archive made before encryption, or
15649
+ * with it off — which restores without a key.
15650
+ */
15651
+ var BackupArchiveEncryptionSchema = object({
15652
+ /** `x25519-hkdf-aes256gcm-stream-v1`. */
15653
+ scheme: string(),
15654
+ /** 16 hex — the backup key whose secret restores this archive. */
15655
+ keyId: string()
15656
+ });
15657
+ /**
15658
+ * The backup encryption setting. The hub keeps PUBLIC keys only: the active
15659
+ * one new archives are encrypted to, and the retired ones older archives
15660
+ * still need. The secret key is shown once, at `setupEncryption`.
15661
+ */
15662
+ var BackupEncryptionStatusSchema = object({
15663
+ enabled: boolean(),
15664
+ active: object({
15665
+ keyId: string(),
15666
+ publicKey: string(),
15667
+ createdAt: number()
15668
+ }).nullable(),
15669
+ /** Every key ever set up, newest first. */
15670
+ keys: array(object({
15671
+ keyId: string(),
15672
+ createdAt: number(),
15673
+ retiredAt: number().nullable()
15674
+ })).readonly()
15675
+ });
15676
+ /**
14282
15677
  * Per-archive entry returned by `backup.listArchives({ destinationId })`.
14283
15678
  * Same shape the destination drill-in renders. Sourced from the per-
14284
15679
  * location `manifests.json` (no per-archive tarball read required).
@@ -14290,7 +15685,9 @@ var BackupArchiveEntrySchema = object({
14290
15685
  sizeBytes: number(),
14291
15686
  label: string().optional(),
14292
15687
  /** Top-level locations included in the archive (db, addons, tls, …). */
14293
- locations: array(string()).readonly()
15688
+ locations: array(string()).readonly(),
15689
+ /** Present when the archive is encrypted; restore then needs that key. */
15690
+ encryption: BackupArchiveEncryptionSchema.optional()
14294
15691
  });
14295
15692
  var BackupEntrySchema = object({
14296
15693
  id: string(),
@@ -14299,7 +15696,8 @@ var BackupEntrySchema = object({
14299
15696
  label: string().optional(),
14300
15697
  createdAt: number(),
14301
15698
  sizeBytes: number(),
14302
- locations: array(string()).optional()
15699
+ locations: array(string()).optional(),
15700
+ encryption: BackupArchiveEncryptionSchema.optional()
14303
15701
  });
14304
15702
  var ArchiveEntrySchema = object({
14305
15703
  path: string(),
@@ -14488,10 +15886,40 @@ method(_void(), array(BackupDestinationInfoSchema).readonly(), { auth: "admin" }
14488
15886
  * this list and skips entries whose path doesn't start with
14489
15887
  * any of them.
14490
15888
  */
14491
- locations: array(string()).optional()
15889
+ locations: array(string()).optional(),
15890
+ /**
15891
+ * The backup SECRET key, for an encrypted archive (ignored for a plain
15892
+ * one). The archive is decrypted into the hub's private staging
15893
+ * before the restart; the key is not stored. A wrong or missing key
15894
+ * is refused before the archive is downloaded.
15895
+ */
15896
+ backupSecretKey: string().optional()
14492
15897
  }), _void(), {
14493
15898
  kind: "mutation",
14494
15899
  auth: "admin"
15900
+ }), method(_void(), BackupEncryptionStatusSchema, { auth: "admin" }), method(object({}), object({
15901
+ keyId: string(),
15902
+ secretKey: string(),
15903
+ publicKey: string(),
15904
+ createdAt: number(),
15905
+ replacedKeyId: string().nullable()
15906
+ }), {
15907
+ kind: "mutation",
15908
+ auth: "admin"
15909
+ }), method(object({}), object({ disabledKeyId: string().nullable() }), {
15910
+ kind: "mutation",
15911
+ auth: "admin"
15912
+ }), method(object({ backupSecretKey: string() }), object({
15913
+ valid: boolean(),
15914
+ keyId: string().nullable(),
15915
+ /** The hub knows this key (active or retired). */
15916
+ known: boolean(),
15917
+ /** It is the key new archives are encrypted to. */
15918
+ active: boolean(),
15919
+ error: string().optional()
15920
+ }), {
15921
+ kind: "mutation",
15922
+ auth: "admin"
14495
15923
  }), method(object({
14496
15924
  destinationId: string(),
14497
15925
  backupId: string()
@@ -16447,7 +17875,60 @@ var CustomModelDescriptorSchema = object({
16447
17875
  stepId: string(),
16448
17876
  entry: ModelCatalogEntrySchema
16449
17877
  });
16450
- method(_void(), array(CustomModelDescriptorSchema).readonly(), { auth: "admin" });
17878
+ /** One regular file of an imported bundle, as the producer measured it. */
17879
+ var ModelBundleFileSchema = object({
17880
+ /** Relative path inside the bundle tar; an mlpackage member is `<x>.mlpackage/<member>`. */
17881
+ path: string().min(1),
17882
+ bytes: number().int().nonnegative(),
17883
+ sha256: string().regex(/^[0-9a-f]{64}$/)
17884
+ });
17885
+ var ImportModelBundleInputSchema = object({
17886
+ /** The registry provider that keeps the model (Model Studio). */
17887
+ addonId: string(),
17888
+ stepId: string().min(1),
17889
+ /**
17890
+ * The catalog rows to register, complete, every format URL already
17891
+ * `camstack-local://<modelId>/<file>` naming a file of the bundle. One
17892
+ * bundle may carry several rows (a base and its INT8 variant).
17893
+ */
17894
+ entries: array(ModelCatalogEntrySchema).min(1).max(4),
17895
+ /** The bundle tar, offered by the producer over `ctx.peerBytes` (same host). */
17896
+ bundle: object({
17897
+ ticket: PeerBytesTicketSchema,
17898
+ bytes: number().int().positive(),
17899
+ sha256: string().regex(/^[0-9a-f]{64}$/)
17900
+ }),
17901
+ /** Every file the tar must hold; anything missing, extra or different is refused. */
17902
+ files: array(ModelBundleFileSchema).min(1).max(64),
17903
+ /** Convert missing engine formats and push the model to every agent afterwards. */
17904
+ distribute: boolean()
17905
+ });
17906
+ var ImportModelBundleResultSchema = discriminatedUnion("kind", [object({
17907
+ kind: literal("imported"),
17908
+ modelIds: array(string()).readonly(),
17909
+ distributed: array(object({
17910
+ modelId: string(),
17911
+ nodeId: string(),
17912
+ format: _enum(MODEL_FORMATS),
17913
+ ok: boolean(),
17914
+ error: string().optional()
17915
+ })).readonly()
17916
+ }), object({
17917
+ kind: literal("refused"),
17918
+ reason: _enum([
17919
+ "transfer-failed",
17920
+ "checksum-mismatch",
17921
+ "bundle-mismatch",
17922
+ "invalid-entry",
17923
+ "id-taken"
17924
+ ]),
17925
+ detail: string()
17926
+ })]);
17927
+ method(_void(), array(CustomModelDescriptorSchema).readonly(), { auth: "admin" }), method(ImportModelBundleInputSchema, ImportModelBundleResultSchema, {
17928
+ kind: "mutation",
17929
+ auth: "admin",
17930
+ timeoutMs: 30 * 6e4
17931
+ });
16451
17932
  /**
16452
17933
  * Query filter for settings-store collections.
16453
17934
  */
@@ -16830,6 +18311,253 @@ id: union([string(), number()]) }), {
16830
18311
  kind: "mutation",
16831
18312
  auth: "admin"
16832
18313
  });
18314
+ /**
18315
+ * `keychain` — the hub's encrypted store of secret values (D787).
18316
+ *
18317
+ * Settings blobs never hold a secret: they hold a marker
18318
+ * `{"$secret":"secret://<owner>/<scope>/<fieldPath>","v":1}` and the value
18319
+ * lives here, AES-256-GCM under a data key that a master key wraps. This cap
18320
+ * is the OWNER's door to its own values: every method is owner-checked
18321
+ * against the CALLER, never against anything the caller claims.
18322
+ *
18323
+ * Who the caller is: the transport stamps `callerAddonId` into the args of a
18324
+ * call that crossed a process (the parent `LocalChildRegistry` from the UDS
18325
+ * connection, the agent from its child's connection carried in
18326
+ * `$hub-cap-fwd`'s envelope). A stamp always overwrites; a wire call with no
18327
+ * stamp has its claim stripped. Only a hub in-process caller may state its own
18328
+ * identity — `ctx.secrets` does that with the addon id closed over. This is
18329
+ * identity against BUGS and misrouting, not against a malicious addon (every
18330
+ * runner is the same OS user): see the threat model in
18331
+ * `docs/design/2026-10-08-secrets-keychain.md`.
18332
+ *
18333
+ * `callerAddonId` is deliberately NOT in any input schema: the tRPC router
18334
+ * parses the input, so a session can never supply it, and the internal mount
18335
+ * floors every method to admin anyway (D240).
18336
+ *
18337
+ * Internal: addons reach it through `ctx.secrets`, never directly.
18338
+ */
18339
+ /** Why a value cannot be served right now. Never folded into "missing". */
18340
+ var KeychainUnavailableReasonSchema = _enum([
18341
+ "key-missing",
18342
+ "wrong-key",
18343
+ "key-file-unreadable",
18344
+ "store-unavailable",
18345
+ "not-initialized",
18346
+ "decrypt-failed"
18347
+ ]);
18348
+ var KeychainStateSchema = discriminatedUnion("state", [object({ state: literal("ready") }), object({
18349
+ state: literal("locked"),
18350
+ reason: KeychainUnavailableReasonSchema
18351
+ })]);
18352
+ var KeychainResolveEntrySchema = discriminatedUnion("kind", [
18353
+ object({
18354
+ kind: literal("value"),
18355
+ value: string(),
18356
+ version: number().int()
18357
+ }),
18358
+ object({ kind: literal("missing") }),
18359
+ object({
18360
+ kind: literal("unavailable"),
18361
+ reason: KeychainUnavailableReasonSchema
18362
+ }),
18363
+ object({ kind: literal("forbidden") })
18364
+ ]);
18365
+ var KeychainResolveResultSchema = record(string(), KeychainResolveEntrySchema);
18366
+ /** Metadata of one stored value — never the value. */
18367
+ var KeychainSecretMetaSchema = object({
18368
+ ref: string(),
18369
+ owner: string(),
18370
+ /** Formatted scope (`global`, `node/<id>`, `device/<id>`, …). */
18371
+ scope: string(),
18372
+ fieldPath: string(),
18373
+ version: number().int(),
18374
+ createdAt: number(),
18375
+ updatedAt: number(),
18376
+ /** `addon:<id>` | `user:<id>` | `system`. */
18377
+ updatedBy: string(),
18378
+ /** Coarse — written at most once an hour per ref. `null` = never read. */
18379
+ lastReadAt: number().nullable()
18380
+ });
18381
+ var RefListSchema = array(string().min(1)).max(512);
18382
+ method(object({
18383
+ ref: string().min(1),
18384
+ value: string().min(1)
18385
+ }), object({
18386
+ ref: string(),
18387
+ version: number().int()
18388
+ }), {
18389
+ kind: "mutation",
18390
+ auth: "admin"
18391
+ }), method(object({ refs: RefListSchema }), KeychainResolveResultSchema, { auth: "admin" }), method(object({ refs: RefListSchema }), object({ deleted: number().int() }), {
18392
+ kind: "mutation",
18393
+ auth: "admin"
18394
+ }), method(object({}), array(KeychainSecretMetaSchema).readonly(), { auth: "admin" }), method(object({}), KeychainStateSchema, { auth: "admin" });
18395
+ var KeychainKeySourceSchema = object({
18396
+ kind: _enum([
18397
+ "config-file",
18398
+ "previous-config-file",
18399
+ "platform",
18400
+ "default-file"
18401
+ ]),
18402
+ /** File sources only — a path is not a secret. */
18403
+ path: string().optional(),
18404
+ /**
18405
+ * True when a whole-volume backup of the data directory carries this key
18406
+ * next to the database it protects (the default file). The page warns.
18407
+ */
18408
+ sharesBackupWithDatabase: boolean()
18409
+ });
18410
+ /**
18411
+ * One keychain reset, as the Secrets page reports it until the operator
18412
+ * acknowledges it. Never a value: refs, counts and table names only.
18413
+ */
18414
+ var KeychainResetRecordSchema = object({
18415
+ id: string(),
18416
+ at: number(),
18417
+ /** `user:<id>` or {@link KEYCHAIN_RESET_TRIGGER_ACTOR}. */
18418
+ actor: string(),
18419
+ /** Why the keychain was locked when it was reset; `null` when it was not locked. */
18420
+ lockedReason: string().nullable(),
18421
+ /** Values moved into the archive table (ciphertext under the lost key). */
18422
+ archived: number().int(),
18423
+ /** `keychain:secrets-orphaned-<ts>`, or `null` when nothing was stored. */
18424
+ archivedCollection: string().nullable(),
18425
+ /**
18426
+ * `keychain:keys-orphaned-<ts>`: the wrapped data keys of the archive, kept
18427
+ * so the archive can still be opened if the lost master key turns up.
18428
+ */
18429
+ archivedKeysCollection: string().nullable(),
18430
+ /**
18431
+ * `system-settings` keys whose marker the reset cleared — the cluster
18432
+ * secret's: a marker left pointing at an archived value would refuse every
18433
+ * agent forever (D797).
18434
+ */
18435
+ clearedSettingsKeys: array(string()).readonly(),
18436
+ /** When an operator dismissed the notice on the Secrets page; `null` until then. */
18437
+ acknowledgedAt: number().nullable()
18438
+ });
18439
+ var KeychainStatusSchema = object({
18440
+ keychain: KeychainStateSchema,
18441
+ /** The source of the master key in use; `null` while locked. */
18442
+ keySource: KeychainKeySourceSchema.nullable(),
18443
+ /** The source configured to be primary — differs from `keySource` while a rotation is pending. */
18444
+ configuredSource: KeychainKeySourceSchema,
18445
+ /** Short fingerprint of the master key in use (`HMAC(KEK, label)`, 16 hex). */
18446
+ fingerprint: string().nullable(),
18447
+ activeKeyId: string().nullable(),
18448
+ /**
18449
+ * The keychain unlocked with a NON-primary source: the configured primary
18450
+ * key is not the one that wraps the data key yet. `rotateMasterKey` moves it.
18451
+ */
18452
+ rotationPending: boolean(),
18453
+ /** Wrapped copies of the data key under a previous master key, kept until purged. */
18454
+ retiredWraps: number().int(),
18455
+ recoveryKeyDownloadedAt: number().nullable(),
18456
+ secretCount: number().int(),
18457
+ /** The most recent reset, acknowledged or not; `null` when the keychain was never reset. */
18458
+ lastReset: KeychainResetRecordSchema.nullable()
18459
+ });
18460
+ /**
18461
+ * Whether a stored value is still pointed at by its owner's settings.
18462
+ * `unknown` is a first-class answer: a scope whose blob could not be read is
18463
+ * never reported as an orphan (and never deleted as one).
18464
+ */
18465
+ var KeychainSecretUsageSchema = _enum([
18466
+ "in-use",
18467
+ "orphan",
18468
+ "unknown"
18469
+ ]);
18470
+ var KeychainAdminSecretSchema = KeychainSecretMetaSchema.extend({ usage: KeychainSecretUsageSchema });
18471
+ var KeychainAuditActionSchema = _enum([
18472
+ "put",
18473
+ "delete",
18474
+ "reveal",
18475
+ "rotate-master-key",
18476
+ "purge-retired-keys",
18477
+ "download-recovery-key",
18478
+ "delete-orphans",
18479
+ "reset",
18480
+ "acknowledge-reset",
18481
+ "initialize"
18482
+ ]);
18483
+ var KeychainAuditEntrySchema = object({
18484
+ id: string(),
18485
+ at: number(),
18486
+ action: KeychainAuditActionSchema,
18487
+ /** `addon:<id>` | `user:<id>` | `system` | `trigger-file`. */
18488
+ actor: string(),
18489
+ ref: string().nullable(),
18490
+ detail: string().nullable()
18491
+ });
18492
+ var KEYCHAIN_RESET_CONFIRMATION = "RESET KEYCHAIN";
18493
+ /**
18494
+ * Secrets the HUB itself holds (owner `system`) that no settings form shows:
18495
+ * `jwt-signing-key` — the session signing key (D797). It is always "in use",
18496
+ * never an orphan; it is generated on a fresh hub and replaced only through
18497
+ * {@link keychainAdminCapability.methods.setSystemSecret}.
18498
+ */
18499
+ var SystemHeldSecretNameSchema = _enum(["jwt-signing-key"]);
18500
+ method(object({}), KeychainStatusSchema, { auth: "admin" }), method(object({}), array(KeychainAdminSecretSchema).readonly(), { auth: "admin" }), method(object({ limit: number().int().min(1).max(500).optional() }), array(KeychainAuditEntrySchema).readonly(), { auth: "admin" }), method(object({ ref: string().min(1) }), object({
18501
+ value: string(),
18502
+ version: number().int()
18503
+ }), {
18504
+ kind: "mutation",
18505
+ auth: "admin",
18506
+ caller: "required"
18507
+ }), method(object({
18508
+ name: SystemHeldSecretNameSchema,
18509
+ value: string().min(16)
18510
+ }), object({
18511
+ ref: string(),
18512
+ version: number().int()
18513
+ }), {
18514
+ kind: "mutation",
18515
+ auth: "admin",
18516
+ caller: "required"
18517
+ }), method(object({ refs: array(string().min(1)).max(1e3) }), object({
18518
+ deleted: array(string()).readonly(),
18519
+ kept: array(object({
18520
+ ref: string(),
18521
+ usage: KeychainSecretUsageSchema
18522
+ })).readonly()
18523
+ }), {
18524
+ kind: "mutation",
18525
+ auth: "admin",
18526
+ caller: "required"
18527
+ }), method(object({}), object({
18528
+ fingerprint: string(),
18529
+ keySource: KeychainKeySourceSchema
18530
+ }), {
18531
+ kind: "mutation",
18532
+ auth: "admin",
18533
+ caller: "required"
18534
+ }), method(object({}), object({ purged: number().int() }), {
18535
+ kind: "mutation",
18536
+ auth: "admin",
18537
+ caller: "required"
18538
+ }), method(object({}), object({
18539
+ key: string(),
18540
+ fingerprint: string(),
18541
+ keySource: KeychainKeySourceSchema
18542
+ }), {
18543
+ kind: "mutation",
18544
+ auth: "admin",
18545
+ caller: "required"
18546
+ }), method(object({ confirm: literal(KEYCHAIN_RESET_CONFIRMATION) }), object({
18547
+ archivedCollection: string().nullable(),
18548
+ archived: number().int()
18549
+ }), {
18550
+ kind: "mutation",
18551
+ auth: "admin",
18552
+ caller: "required"
18553
+ }), method(object({}), object({
18554
+ reset: KeychainResetRecordSchema.nullable(),
18555
+ pendingReentry: array(KeychainSecretMetaSchema).readonly()
18556
+ }), { auth: "admin" }), method(object({}), object({ acknowledged: boolean() }), {
18557
+ kind: "mutation",
18558
+ auth: "admin",
18559
+ caller: "required"
18560
+ });
16833
18561
  method(_void(), object({
16834
18562
  id: string(),
16835
18563
  name: string(),
@@ -17678,6 +19406,10 @@ var DeviceInfoSchema = object({
17678
19406
  isCamera: boolean(),
17679
19407
  /** Current config values — serializable snapshot */
17680
19408
  config: record(string(), unknown()),
19409
+ /** Paths inside `config` the device's schema declares secret (D783) —
19410
+ * what the non-admin redaction withholds. Paths, never values. Absent
19411
+ * when the owning runner has not reported them. */
19412
+ secretConfigPaths: array(string()).optional(),
17681
19413
  /** Hardware + identity blob (manufacturer / model / firmware / sn /
17682
19414
  * uid / mac / …). Populated by drivers; editable via setMetadata. */
17683
19415
  metadata: record(string(), unknown()).nullable().optional(),
@@ -17883,12 +19615,22 @@ var DeviceRegisterPayloadSchema = object({
17883
19615
  * call (workers re-register on init), so probe-driven updates
17884
19616
  * (e.g. PTZ flag flipping after the abilities probe) propagate. */
17885
19617
  features: array(string()).optional(),
17886
- config: record(string(), unknown())
19618
+ config: record(string(), unknown()),
19619
+ /** Config paths the device's own schema DECLARES secret
19620
+ * (`.meta({ secret: true })` — dotted, `[]` for array items, e.g.
19621
+ * `connection.password`). Re-published on every register; the non-admin
19622
+ * redaction withholds them at any depth (D783). Optional: an older runner
19623
+ * omits it and the keyword backstop applies. */
19624
+ secretConfigPaths: array(string()).optional()
17887
19625
  });
17888
19626
  var DeviceRemovePayloadSchema = object({ deviceId: number() });
17889
19627
  var DevicePersistConfigPayloadSchema = object({
17890
19628
  deviceId: number(),
17891
- data: record(string(), unknown())
19629
+ data: record(string(), unknown()),
19630
+ /** The paths the device's schema declares secret (D783), when the caller
19631
+ * knows them — those values are kept in the keychain, not the blob (D787).
19632
+ * Absent: the paths the device last reported at `registerDevice` apply. */
19633
+ secretConfigPaths: array(string()).optional()
17892
19634
  });
17893
19635
  /** What a migration actually did, per switch. `unreachable` is a first-class
17894
19636
  * answer: a camera that could not be asked is not a camera that was silenced. */
@@ -19545,7 +21287,7 @@ method(LogEntrySchema, _void(), { kind: "mutation" }), method(object({
19545
21287
  * `login-method` — collection cap through which auth addons contribute
19546
21288
  * their pre-auth login surfaces to the login page. This is the SINGLE,
19547
21289
  * generic mechanism that supersedes the dead `auth.listProviders` reader:
19548
- * every auth addon (OIDC, magic-link, WebAuthn/passkey) registers a
21290
+ * every auth addon (OIDC, WebAuthn/passkey) registers a
19549
21291
  * `login-method` provider and the PUBLIC `auth.listLoginMethods`
19550
21292
  * procedure aggregates them for the unauthenticated login page.
19551
21293
  *
@@ -19553,8 +21295,7 @@ method(LogEntrySchema, _void(), { kind: "mutation" }), method(object({
19553
21295
  *
19554
21296
  * - `redirect` — a declarative button. The login page renders a generic
19555
21297
  * button that navigates to `startUrl` (an addon-owned HTTP route).
19556
- * Covers OIDC (`/addon/auth-oidc/<id>/start`) and magic-link with
19557
- * ZERO shell-side JS. A future SSO addon plugs in the same way — the
21298
+ * Covers OIDC (`/addon/auth-oidc/<id>/start`) with ZERO shell-side JS. A future SSO addon plugs in the same way — the
19558
21299
  * login page needs NO change.
19559
21300
  *
19560
21301
  * - `widget` — a Module-Federation widget the login page mounts (via
@@ -19573,8 +21314,8 @@ method(LogEntrySchema, _void(), { kind: "mutation" }), method(object({
19573
21314
  * decision.
19574
21315
  *
19575
21316
  * Every contribution carries a `stage`:
19576
- * - `primary` — shown on the first credentials screen (OIDC /
19577
- * magic-link buttons; a future usernameless passkey).
21317
+ * - `primary` — shown on the first credentials screen (OIDC
21318
+ * buttons; a usernameless passkey).
19578
21319
  * - `second-factor` — shown AFTER the password leg, gated on the
19579
21320
  * returned `factors` (passkey-as-2FA today).
19580
21321
  *
@@ -19596,7 +21337,14 @@ var LoginMethodContributionSchema = discriminatedUnion("kind", [
19596
21337
  icon: string().optional(),
19597
21338
  /** Addon-owned HTTP route the button navigates to (GET). */
19598
21339
  startUrl: string(),
19599
- stage: LoginStageEnum
21340
+ stage: LoginStageEnum,
21341
+ /**
21342
+ * The provider names an external identity a signed-in user can link to
21343
+ * their own account (D782): `auth.listLinkableProviders` /
21344
+ * `beginExternalLink` offer exactly the redirect methods that set this,
21345
+ * whatever their id. Absent / false — a login button only.
21346
+ */
21347
+ linkable: boolean().optional()
19600
21348
  }),
19601
21349
  object({
19602
21350
  kind: literal("widget"),
@@ -23754,8 +25502,7 @@ method(object({}), object({ rules: array(NcRuleSchema) }), { auth: "admin" }), m
23754
25502
  * `super_admin` — collapsed onto the single boolean because every
23755
25503
  * non-admin caller is governed by the same scope-check rules; the
23756
25504
  * distinction was only ever used to route role-specific procedures
23757
- * which we no longer have. Agents are admin sessions issued via
23758
- * `createServiceToken`; CLI / webhook integrations are `cst_*` tokens
25505
+ * which we no longer have. CLI / webhook integrations are `cst_*` tokens
23759
25506
  * with `isAdmin: false` + an explicit scope list.
23760
25507
  */
23761
25508
  /** Per-method access flavour. Materialised on every cap method via codegen. */
@@ -25304,8 +27051,23 @@ var RetrainMacroClassSchema = _enum([
25304
27051
  ]);
25305
27052
  /** A subject to learn, or a phantom to unlearn (taught by OMISSION). */
25306
27053
  var RetrainAnnotationKindSchema = _enum(["subject", "model_error"]);
25307
- /** Did a human draw this box, or did the assist propose it? */
25308
- var RetrainAnnotationSourceSchema = _enum(["operator", "assist"]);
27054
+ /**
27055
+ * Where a box came from. A machine-sourced box is a DRAFT on the page until
27056
+ * the operator confirms it; once saved it keeps its source as provenance.
27057
+ *
27058
+ * - `operator` — drawn by hand.
27059
+ * - `assist` — proposed by a detector run on the copy (the camera's own
27060
+ * model, or a larger teacher model).
27061
+ * - `pipeline` — the box the live pipeline actually drew on that frame, read
27062
+ * back from the track store (never a re-run).
27063
+ * - `llm` — proposed by a vision-capable LLM profile.
27064
+ */
27065
+ var RetrainAnnotationSourceSchema = _enum([
27066
+ "operator",
27067
+ "assist",
27068
+ "pipeline",
27069
+ "llm"
27070
+ ]);
25309
27071
  /** Normalised `[0,1]` rectangle against the FULL frame — the canonical form. */
25310
27072
  var RetrainBboxSchema = object({
25311
27073
  x: number(),
@@ -25323,7 +27085,8 @@ var RetrainBboxSchema = object({
25323
27085
  */
25324
27086
  var RetrainAnnotationSchema = object({
25325
27087
  id: string(),
25326
- trackId: string(),
27088
+ /** The frame's track. Absent on a recording still, which has none. */
27089
+ trackId: string().optional(),
25327
27090
  deviceId: number(),
25328
27091
  /** The COPY in retrain storage — never the source track's media key. */
25329
27092
  mediaKey: string(),
@@ -25372,18 +27135,63 @@ var RetrainFrameCandidateSchema = object({
25372
27135
  * fail, whatever became of the original. */
25373
27136
  copied: boolean()
25374
27137
  });
27138
+ /**
27139
+ * One box the live pipeline drew on a copied frame — what a correction starts
27140
+ * from. Derived when the frame is listed, from the track store: the subject
27141
+ * box recorded on the source media row when there is one, else the track
27142
+ * position nearest the frame's capture time. Never stored as an annotation
27143
+ * until the operator confirms it.
27144
+ */
27145
+ var RetrainPipelineBoxSchema = object({
27146
+ /** Normalised `[0,1]` against the full frame. */
27147
+ bbox: RetrainBboxSchema,
27148
+ macroClass: RetrainMacroClassSchema,
27149
+ label: string().optional(),
27150
+ subLabel: string().optional(),
27151
+ /** The detection score of the position used, when it was recorded. */
27152
+ score: number().optional(),
27153
+ /** The root model that produced the track, when it was recorded. */
27154
+ modelId: string().optional(),
27155
+ trackId: string(),
27156
+ /** `subject-box`: recorded on this very frame. `position`: the track's
27157
+ * position nearest the capture time, `deltaMs` away. */
27158
+ basis: _enum(["subject-box", "position"]),
27159
+ deltaMs: number()
27160
+ });
27161
+ /**
27162
+ * Where a retrain frame came from: a TRACK's stored media (copy-on-select),
27163
+ * or the RECORDING at an instant — the frame a model saw nothing in has no
27164
+ * track at all.
27165
+ */
27166
+ var RetrainFrameOriginSchema = _enum(["track", "recording"]);
25375
27167
  /** A frame the dataset OWNS: bytes copied at selection time. */
25376
27168
  var RetrainFrameSchema = object({
25377
27169
  frameId: string(),
25378
27170
  deviceId: number(),
25379
- trackId: string(),
25380
- /** Provenance only. It may already point at nothing — that is expected. */
25381
- sourceMediaId: number().int(),
27171
+ origin: RetrainFrameOriginSchema,
27172
+ /** The track it was copied from. Absent on a recording still. */
27173
+ trackId: string().optional(),
27174
+ /** Provenance only. It may already point at nothing — that is expected.
27175
+ * Absent on a recording still. */
27176
+ sourceMediaId: number().int().optional(),
27177
+ /** A recording still: the playhead instant it was taken at. */
27178
+ epochMs: number().optional(),
25382
27179
  sourceKind: MediaFileKindEnum,
25383
27180
  sizeBytes: number().int(),
25384
27181
  width: number().int(),
25385
27182
  height: number().int(),
25386
- copiedAt: number()
27183
+ copiedAt: number(),
27184
+ /** When the CAMERA captured the frame. Absent on a copy taken before D785. */
27185
+ capturedAt: number().optional(),
27186
+ /** The operator's "every subject in this frame is boxed". Detector
27187
+ * evaluation keeps only complete frames: an unboxed subject would count as
27188
+ * a false positive. */
27189
+ complete: boolean(),
27190
+ /** The boxes the pipeline drew on this frame. Present on list answers;
27191
+ * empty when nothing the track store holds can be placed on it. */
27192
+ pipelineBoxes: array(RetrainPipelineBoxSchema).readonly().optional(),
27193
+ /** The named collections this frame belongs to. Present on list answers. */
27194
+ collectionIds: array(string()).readonly().optional()
25387
27195
  });
25388
27196
  /** Why a copy-on-select could not be honoured — named, never a silent skip. */
25389
27197
  var RetrainCopyRefusalSchema = _enum([
@@ -25404,6 +27212,56 @@ var RetrainFrameListSchema = object({
25404
27212
  /** What the page pre-selects — the native key frame when one survives. */
25405
27213
  autoPickMediaId: number().int().optional()
25406
27214
  });
27215
+ /**
27216
+ * Which frames an annotated export carries. Every field narrows; an empty
27217
+ * filter is every annotated copy. A dataset VERSION is a frozen `frameIds`
27218
+ * list owned by whoever trains (the training orchestrator), so `frameIds` is
27219
+ * the primitive a version export uses; `batchId` re-selects what an earlier
27220
+ * export carried (`exportedInBatch`).
27221
+ */
27222
+ var RetrainExportFilterSchema = object({
27223
+ deviceIds: array(number()).optional(),
27224
+ frameIds: array(string()).max(2e4).optional(),
27225
+ /** Only frames in at least one of these named collections. */
27226
+ collectionIds: array(string()).max(200).optional(),
27227
+ /** Exactly the frames of this dataset version (and its completeOnly). An
27228
+ * unknown id selects nothing. */
27229
+ datasetVersionId: string().optional(),
27230
+ batchId: string().optional(),
27231
+ /** Only frames the operator marked complete (all subjects boxed). */
27232
+ completeOnly: boolean().optional()
27233
+ });
27234
+ /**
27235
+ * `frames`: the full frame copies, boxes in `annotations.json`.
27236
+ * `crops`: additionally one JPEG per subject, cut with the runtime detail-crop
27237
+ * convention — the classifier layout.
27238
+ */
27239
+ var RetrainExportLayoutSchema = _enum(["frames", "crops"]);
27240
+ /**
27241
+ * Where `writeRetrainArchive` streams the tar: one HTTP request whose body is
27242
+ * the archive, sent chunk by chunk. Covers a presigned PUT and a provider
27243
+ * addon's data-plane upload route alike. Headers are sent verbatim and never
27244
+ * logged.
27245
+ */
27246
+ var RetrainArchiveTargetSchema = object({
27247
+ kind: literal("http"),
27248
+ method: _enum(["PUT", "POST"]),
27249
+ url: string().url(),
27250
+ headers: record(string(), string()).optional()
27251
+ });
27252
+ var RetrainArchiveResultSchema = object({
27253
+ batchId: string(),
27254
+ frames: number().int(),
27255
+ crops: number().int(),
27256
+ annotations: number().int(),
27257
+ /** Frames planned but not shipped (unreadable copy, path too long). */
27258
+ missing: number().int(),
27259
+ bytes: number().int(),
27260
+ /** sha256 of the exact bytes sent. */
27261
+ sha256: string(),
27262
+ /** The target's HTTP status. */
27263
+ status: number().int()
27264
+ });
25407
27265
  /** What the operator asked the assist to look for. */
25408
27266
  var RetrainAssistSubjectSchema = discriminatedUnion("kind", [object({
25409
27267
  kind: literal("package"),
@@ -25433,6 +27291,170 @@ var RetrainAssistResultSchema = discriminatedUnion("kind", [object({
25433
27291
  reason: string(),
25434
27292
  detail: string().optional()
25435
27293
  })]);
27294
+ /** A named set over the retrain corpus — membership only, it owns no pixels. */
27295
+ var RetrainCollectionSchema = object({
27296
+ id: string(),
27297
+ name: string(),
27298
+ createdAt: number(),
27299
+ frameCount: number().int()
27300
+ });
27301
+ var RetrainCollectionCreateResultSchema = discriminatedUnion("kind", [object({
27302
+ kind: literal("created"),
27303
+ collection: RetrainCollectionSchema
27304
+ }), object({
27305
+ kind: literal("refused"),
27306
+ reason: _enum(["empty-name", "duplicate-name"])
27307
+ })]);
27308
+ var RetrainCollectionRenameResultSchema = discriminatedUnion("kind", [object({
27309
+ kind: literal("renamed"),
27310
+ collection: RetrainCollectionSchema
27311
+ }), object({
27312
+ kind: literal("refused"),
27313
+ reason: _enum([
27314
+ "empty-name",
27315
+ "duplicate-name",
27316
+ "unknown-collection"
27317
+ ])
27318
+ })]);
27319
+ /**
27320
+ * The outcome of adding the frame at a recording instant. Every refusal is
27321
+ * named: `still-unavailable` (not recording, a gap, or an undecodable frame —
27322
+ * `detail` says which), `still-busy` (the recorder is at its decode bound; try
27323
+ * again), `unreadable-image`, `write-failed`, `unknown-collection`.
27324
+ */
27325
+ var AddRetrainFrameFromRecordingResultSchema = discriminatedUnion("kind", [object({
27326
+ kind: literal("added"),
27327
+ collectionId: string(),
27328
+ frame: RetrainFrameSchema,
27329
+ /** The moment was already in the dataset; nothing was decoded. */
27330
+ reused: boolean()
27331
+ }), object({
27332
+ kind: literal("refused"),
27333
+ reason: _enum([
27334
+ "unknown-collection",
27335
+ "still-unavailable",
27336
+ "still-busy",
27337
+ "unreadable-image",
27338
+ "write-failed"
27339
+ ]),
27340
+ detail: string().optional()
27341
+ })]);
27342
+ /** A vision LLM profile the AI assist may use, and where it sends the frame. */
27343
+ var RetrainAssistProfileSchema = object({
27344
+ id: string(),
27345
+ name: string(),
27346
+ model: string(),
27347
+ kind: string(),
27348
+ /** `true` when the frame would leave the house (a cloud vendor, or an
27349
+ * endpoint that is not on the local network). The page confirms each such
27350
+ * run, and the provider refuses one without `allowCloud`. */
27351
+ leavesHouse: boolean()
27352
+ });
27353
+ /** A box the AI assist proposed: a draft, plus the model's own reason. */
27354
+ var RetrainLlmProposalSchema = RetrainAnnotationDraftSchema.extend({ reason: string() });
27355
+ /** What the AI assist said about a box that was already on the canvas. */
27356
+ var RetrainLlmReviewSchema = object({
27357
+ /** The `ref` the page sent the box under. */
27358
+ ref: string(),
27359
+ verdict: _enum([
27360
+ "confirmed",
27361
+ "wrong-class",
27362
+ "not-an-object",
27363
+ "uncertain"
27364
+ ]),
27365
+ suggestedClass: RetrainMacroClassSchema.optional(),
27366
+ reason: string()
27367
+ });
27368
+ /**
27369
+ * The AI assist's answer. `proposed` carries drafts (`source: 'llm'`, the
27370
+ * model and its confidence) and reviews; items the model got wrong (a box off
27371
+ * the frame, an unasked class, an unknown ref) are dropped and counted in
27372
+ * `rejected`. A whole answer that is not the schema is `malformed-answer`.
27373
+ */
27374
+ var RetrainLlmAssistResultSchema = discriminatedUnion("kind", [object({
27375
+ kind: literal("proposed"),
27376
+ profileId: string(),
27377
+ model: string(),
27378
+ /** The frame was sent outside the house for this answer. */
27379
+ leftHouse: boolean(),
27380
+ proposals: array(RetrainLlmProposalSchema).readonly(),
27381
+ reviews: array(RetrainLlmReviewSchema).readonly(),
27382
+ rejected: number().int()
27383
+ }), object({
27384
+ kind: literal("refused"),
27385
+ reason: _enum([
27386
+ "unknown-frame",
27387
+ "unreadable-frame",
27388
+ "unknown-profile",
27389
+ "profile-disabled",
27390
+ "no-vision",
27391
+ "cloud-not-confirmed",
27392
+ "llm-error",
27393
+ "malformed-answer"
27394
+ ]),
27395
+ detail: string().optional()
27396
+ })]);
27397
+ /** What a dataset version is cut from. Every field narrows. */
27398
+ var RetrainDatasetSelectionSchema = object({
27399
+ deviceIds: array(number()).readonly().optional(),
27400
+ collectionIds: array(string()).max(200).readonly().optional(),
27401
+ frameIds: array(string()).max(2e4).readonly().optional()
27402
+ });
27403
+ /** The counts a dataset is judged by. */
27404
+ var RetrainDatasetStatsSchema = object({
27405
+ frames: number().int(),
27406
+ completeFrames: number().int(),
27407
+ /** `completeFrames / frames`, 0..1. */
27408
+ completeness: number(),
27409
+ /** Boxes to learn (model errors excluded). */
27410
+ subjects: number().int(),
27411
+ modelErrors: number().int(),
27412
+ /** Complete frames with no subject. */
27413
+ hardNegatives: number().int(),
27414
+ /** Subjects per class × camera × day/night. */
27415
+ cells: array(object({
27416
+ macroClass: string(),
27417
+ deviceId: number(),
27418
+ lighting: _enum([
27419
+ "day",
27420
+ "night",
27421
+ "unknown"
27422
+ ]),
27423
+ subjects: number().int(),
27424
+ frames: number().int()
27425
+ })).readonly(),
27426
+ cameras: array(object({
27427
+ deviceId: number(),
27428
+ frames: number().int(),
27429
+ completeFrames: number().int()
27430
+ })).readonly()
27431
+ });
27432
+ /** An immutable dataset version, without its frame list. */
27433
+ var RetrainDatasetVersionSchema = object({
27434
+ id: string(),
27435
+ name: string(),
27436
+ createdAt: number(),
27437
+ selection: RetrainDatasetSelectionSchema,
27438
+ layout: RetrainExportLayoutSchema,
27439
+ completeOnly: boolean(),
27440
+ frameCount: number().int(),
27441
+ /** sha256 of what the frames taught when the version was frozen. */
27442
+ annotationHash: string(),
27443
+ /** The export manifest schema the version was cut under. */
27444
+ manifestSchema: string(),
27445
+ stats: RetrainDatasetStatsSchema
27446
+ });
27447
+ var CreateRetrainDatasetVersionResultSchema = discriminatedUnion("kind", [object({
27448
+ kind: literal("created"),
27449
+ version: RetrainDatasetVersionSchema
27450
+ }), object({
27451
+ kind: literal("refused"),
27452
+ reason: _enum([
27453
+ "empty-name",
27454
+ "duplicate-name",
27455
+ "no-frames"
27456
+ ])
27457
+ })]);
25436
27458
  /** The outcome of a lifecycle move owned by the retrain page. */
25437
27459
  var RetrainTransitionResultSchema = object({
25438
27460
  trackId: string(),
@@ -26150,7 +28172,7 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
26150
28172
  auth: "admin"
26151
28173
  }), method(object({
26152
28174
  deviceId: number(),
26153
- trackId: string(),
28175
+ trackId: string().optional(),
26154
28176
  frameId: string()
26155
28177
  }), object({
26156
28178
  removed: boolean(),
@@ -26167,7 +28189,8 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
26167
28189
  auth: "admin"
26168
28190
  }), method(object({
26169
28191
  deviceId: number(),
26170
- trackId: string(),
28192
+ /** The frame's track, when it has one — checked against the frame. */
28193
+ trackId: string().optional(),
26171
28194
  frameId: string(),
26172
28195
  subject: RetrainAssistSubjectSchema,
26173
28196
  /** Which node runs it. Absent ⇒ wherever an unowned call lands. */
@@ -26175,12 +28198,16 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
26175
28198
  }), RetrainAssistResultSchema, {
26176
28199
  kind: "mutation",
26177
28200
  auth: "admin"
26178
- }), method(object({ trackId: string() }), array(RetrainAnnotationSchema).readonly(), {
28201
+ }), method(object({
28202
+ trackId: string().optional(),
28203
+ frameIds: array(string()).max(2e3).optional()
28204
+ }), array(RetrainAnnotationSchema).readonly(), {
26179
28205
  kind: "query",
26180
28206
  auth: "admin"
26181
28207
  }), method(object({
26182
28208
  deviceId: number(),
26183
- trackId: string(),
28209
+ /** The frame's track, when it has one — checked against the frame. */
28210
+ trackId: string().optional(),
26184
28211
  frameId: string(),
26185
28212
  annotations: array(RetrainAnnotationDraftSchema)
26186
28213
  }), array(RetrainAnnotationSchema).readonly(), {
@@ -26198,7 +28225,132 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
26198
28225
  }), RetrainTransitionResultSchema, {
26199
28226
  kind: "mutation",
26200
28227
  auth: "admin"
26201
- }), method(object({ deviceIds: array(number()).optional() }), object({ url: string() }), {
28228
+ }), method(RetrainExportFilterSchema.extend({ layout: RetrainExportLayoutSchema.optional() }), object({ url: string() }), {
28229
+ kind: "query",
28230
+ auth: "admin"
28231
+ }), method(object({
28232
+ deviceId: number(),
28233
+ trackId: string().optional(),
28234
+ frameId: string(),
28235
+ complete: boolean()
28236
+ }), RetrainFrameSchema, {
28237
+ kind: "mutation",
28238
+ auth: "admin"
28239
+ }), method(object({
28240
+ filter: RetrainExportFilterSchema,
28241
+ layout: RetrainExportLayoutSchema,
28242
+ target: RetrainArchiveTargetSchema
28243
+ }), RetrainArchiveResultSchema, {
28244
+ kind: "mutation",
28245
+ auth: "admin",
28246
+ timeoutMs: 60 * 6e4
28247
+ }), method(object({
28248
+ filter: RetrainExportFilterSchema,
28249
+ layout: RetrainExportLayoutSchema
28250
+ }), object({
28251
+ ticket: PeerBytesTicketSchema,
28252
+ frames: number().int(),
28253
+ annotations: number().int()
28254
+ }), {
28255
+ kind: "mutation",
28256
+ auth: "admin",
28257
+ timeoutMs: 12e4
28258
+ }), method(object({
28259
+ selection: RetrainDatasetSelectionSchema,
28260
+ completeOnly: boolean().optional()
28261
+ }), RetrainDatasetStatsSchema, {
28262
+ kind: "query",
28263
+ auth: "admin"
28264
+ }), method(object({
28265
+ name: string().max(120),
28266
+ selection: RetrainDatasetSelectionSchema,
28267
+ layout: RetrainExportLayoutSchema,
28268
+ completeOnly: boolean()
28269
+ }), CreateRetrainDatasetVersionResultSchema, {
28270
+ kind: "mutation",
28271
+ auth: "admin",
28272
+ timeoutMs: 12e4
28273
+ }), method(object({}), array(RetrainDatasetVersionSchema).readonly(), {
28274
+ kind: "query",
28275
+ auth: "admin"
28276
+ }), method(object({ id: string() }), object({ deleted: boolean() }), {
28277
+ kind: "mutation",
28278
+ auth: "admin"
28279
+ }), method(object({ id: string() }), object({
28280
+ found: boolean(),
28281
+ annotationHash: string(),
28282
+ matches: boolean(),
28283
+ missingFrames: number().int()
28284
+ }), {
28285
+ kind: "query",
28286
+ auth: "admin",
28287
+ timeoutMs: 12e4
28288
+ }), method(object({}), array(RetrainAssistProfileSchema).readonly(), {
28289
+ kind: "query",
28290
+ auth: "admin"
28291
+ }), method(object({
28292
+ deviceId: number(),
28293
+ trackId: string().optional(),
28294
+ frameId: string(),
28295
+ profileId: string(),
28296
+ classes: array(RetrainMacroClassSchema).min(1),
28297
+ boxes: array(object({
28298
+ ref: string(),
28299
+ bbox: RetrainBboxSchema,
28300
+ macroClass: RetrainMacroClassSchema,
28301
+ label: string().optional()
28302
+ })).max(50),
28303
+ allowCloud: boolean()
28304
+ }), RetrainLlmAssistResultSchema, {
28305
+ kind: "mutation",
28306
+ auth: "admin",
28307
+ timeoutMs: 18e4
28308
+ }), method(object({ name: string().max(120) }), RetrainCollectionCreateResultSchema, {
28309
+ kind: "mutation",
28310
+ auth: "admin"
28311
+ }), method(object({}), array(RetrainCollectionSchema).readonly(), {
28312
+ kind: "query",
28313
+ auth: "admin"
28314
+ }), method(object({
28315
+ id: string(),
28316
+ name: string().max(120)
28317
+ }), RetrainCollectionRenameResultSchema, {
28318
+ kind: "mutation",
28319
+ auth: "admin"
28320
+ }), method(object({ id: string() }), object({
28321
+ deleted: boolean(),
28322
+ removedFrames: number().int()
28323
+ }), {
28324
+ kind: "mutation",
28325
+ auth: "admin"
28326
+ }), method(object({
28327
+ collectionId: string(),
28328
+ deviceId: number(),
28329
+ epochMs: number()
28330
+ }), AddRetrainFrameFromRecordingResultSchema, {
28331
+ kind: "mutation",
28332
+ auth: "admin",
28333
+ timeoutMs: 6e4
28334
+ }), method(object({
28335
+ collectionId: string(),
28336
+ frameIds: array(string()).min(1).max(500)
28337
+ }), object({
28338
+ added: number().int(),
28339
+ alreadyMember: number().int(),
28340
+ unknownFrameIds: array(string()).readonly()
28341
+ }), {
28342
+ kind: "mutation",
28343
+ auth: "admin"
28344
+ }), method(object({
28345
+ collectionId: string(),
28346
+ frameId: string()
28347
+ }), object({
28348
+ removed: boolean(),
28349
+ deletedFrame: boolean()
28350
+ }), {
28351
+ kind: "mutation",
28352
+ auth: "admin"
28353
+ }), method(object({ collectionId: string() }), array(RetrainFrameSchema).readonly(), {
26202
28354
  kind: "query",
26203
28355
  auth: "admin"
26204
28356
  }), method(object({
@@ -27026,13 +29178,31 @@ var RecommendationReasonSchema = discriminatedUnion("kind", [
27026
29178
  object({
27027
29179
  kind: literal("no-family-build"),
27028
29180
  format: ModelFormatSchema$1
29181
+ }),
29182
+ object({
29183
+ kind: literal("kept-custom-pin"),
29184
+ modelId: string(),
29185
+ deviceKey: string()
27029
29186
  })
27030
29187
  ]);
29188
+ /** Why a device is left exactly as it is, whatever the plan would pick (D786). */
29189
+ var KeptReasonSchema = _enum(["custom-pin"]);
29190
+ /**
29191
+ * Where a choice's latency came from (D791): this node's own benchmark
29192
+ * result, or the hardware-class table. Measured on the node beats the table.
29193
+ */
29194
+ var LatencySourceSchema = discriminatedUnion("kind", [object({ kind: literal("table") }), object({
29195
+ kind: literal("node-benchmark"),
29196
+ resultId: string(),
29197
+ measuredAtMs: number()
29198
+ })]);
27031
29199
  var DeviceModelChoiceSchema = object({
27032
29200
  modelId: string(),
27033
29201
  p50Ms: number(),
27034
29202
  fps: number(),
27035
29203
  measured: boolean(),
29204
+ /** Absent on a plan from before D791 — read as the table. */
29205
+ source: LatencySourceSchema.optional(),
27036
29206
  /** Parallel sessions at the camera rate with the headroom kept free: ⌊fps × (1 − headroom) / camera fps⌋. */
27037
29207
  capacitySessions: number(),
27038
29208
  personRecall: number()
@@ -27043,6 +29213,8 @@ var DeviceRecommendationSchema = object({
27043
29213
  enabled: boolean(),
27044
29214
  available: boolean(),
27045
29215
  chosen: DeviceModelChoiceSchema.nullable(),
29216
+ /** Present when the device is kept as is: Apply writes nothing on it. */
29217
+ kept: KeptReasonSchema.optional(),
27046
29218
  reasons: array(RecommendationReasonSchema).readonly()
27047
29219
  });
27048
29220
  var NodeRecommendationSchema = object({
@@ -27096,6 +29268,17 @@ var AutoTuneWarningSchema = discriminatedUnion("kind", [
27096
29268
  kind: literal("coral-enabled"),
27097
29269
  nodeId: string(),
27098
29270
  deviceKey: string()
29271
+ }),
29272
+ object({
29273
+ kind: literal("custom-pin-kept"),
29274
+ nodeId: string(),
29275
+ deviceKey: string().nullable(),
29276
+ deviceId: number().nullable(),
29277
+ modelId: string()
29278
+ }),
29279
+ object({
29280
+ kind: literal("custom-registry-unreadable"),
29281
+ error: string()
27099
29282
  })
27100
29283
  ]);
27101
29284
  var AutoTuneOptionsSchema = object({
@@ -27274,13 +29457,14 @@ var SuggestSharesResultSchema = object({
27274
29457
  nodes: array(SuggestedNodeShareSchema).readonly()
27275
29458
  });
27276
29459
  /**
27277
- * Where the node and device shares come from (D750, D755).
27278
- * - `hardware` (default) — computed by the system from each node's static
27279
- * capacity (its accelerators at their Auto tune models, from the measured
27280
- * latency table), recomputed whenever a node or device joins, leaves, is
27281
- * switched on or off, or changes model. No load input.
27282
- * - `benchmark` — the same, from each node's measured capacity (node
27283
- * benchmark results); a node without results falls back to `hardware`.
29460
+ * Where the node and device shares come from (D750, D755, D791).
29461
+ * - `benchmark` (default since D791) — each node's capacity as its own node
29462
+ * benchmark measured it; a node without fresh results is sized from
29463
+ * `hardware` and says so. Measured on the node beats the table.
29464
+ * - `hardware` — computed from each node's static capacity only (its
29465
+ * accelerators at their Auto tune models, from the latency table).
29466
+ * Both are recomputed whenever a node or device joins, leaves, is switched
29467
+ * on or off, changes model, or a benchmark result is written. No load input.
27284
29468
  * - `manual` — the operator's stored sliders.
27285
29469
  * Either way a node or device that cannot take sessions gives its share to
27286
29470
  * the others in proportion; the stored values are never rewritten for that.
@@ -27329,6 +29513,362 @@ var EffectiveSharesSchema = object({
27329
29513
  nodeWeights: record(string(), number()),
27330
29514
  deviceWeights: record(string(), record(string(), number()))
27331
29515
  });
29516
+ /**
29517
+ * Wire shapes of the node benchmark (D791): the operator's plan, the
29518
+ * preflight the confirmation shows, the run the orchestrator owns, what the
29519
+ * measuring runner reports, and the result rows Auto tune and the automatic
29520
+ * shares read.
29521
+ *
29522
+ * ONE node at a time, owned by the pipeline orchestrator. While a run is
29523
+ * active the cluster is in BENCHMARK MODE for that node: it is not a
29524
+ * detection candidate, camera pins naming it are ignored so its sessions move
29525
+ * elsewhere, and both come back when the mode ends — after a crash or a hub
29526
+ * restart too (a persisted manifest, reconciled against the registry).
29527
+ *
29528
+ * Two measurements, both on the node, driven by its own runner (frames never
29529
+ * cross a process at frame rate, D9):
29530
+ * - `device` — one accelerator × one candidate detector, root only, open
29531
+ * loop: how many streams at the camera rate it carries inside the frame
29532
+ * interval;
29533
+ * - `pipeline` — the chosen detector plus the operator's detail steps
29534
+ * (faces, plates, classifiers, CLIP…), on varied frames from the bench
29535
+ * clip: how many parallel sessions the node carries before latency, drops,
29536
+ * CPU, RAM or the event loop give out.
29537
+ */
29538
+ /** Defaults and bounds, one place. */
29539
+ var NODE_BENCHMARK_DEFAULTS = {
29540
+ fpsPerStream: 10,
29541
+ budgetMinutes: 45,
29542
+ minBudgetMinutes: 10,
29543
+ maxBudgetMinutes: 120,
29544
+ /** A result older than this no longer beats the table. */
29545
+ staleAfterDays: 30,
29546
+ /** Warm-in per ramp step (not accounted). */
29547
+ settleSec: 5,
29548
+ /** Accounted window per ramp step. */
29549
+ measureSec: 20,
29550
+ /** Longest the drain may take before the run is refused. */
29551
+ drainTimeoutSec: 120,
29552
+ /** Candidate models per device in one run. */
29553
+ maxModelsPerDevice: 6
29554
+ };
29555
+ /** The two measurements a run can make. */
29556
+ var NodeBenchmarkPhaseSchema = _enum(["device", "pipeline"]);
29557
+ var NodeBenchmarkDevicePlanSchema = object({
29558
+ /** `<backend>:<device>` — `openvino:npu`, `coreml:all`, `cpu`. */
29559
+ deviceKey: string().min(1),
29560
+ /**
29561
+ * Root detector candidates for the `device` measurement, in the order
29562
+ * measured. The FIRST is the one the `pipeline` measurement runs.
29563
+ */
29564
+ modelIds: array(string().min(1)).min(1).max(NODE_BENCHMARK_DEFAULTS.maxModelsPerDevice)
29565
+ });
29566
+ /** What the operator confirmed. */
29567
+ var NodeBenchmarkPlanSchema = object({
29568
+ nodeId: string().min(1),
29569
+ devices: array(NodeBenchmarkDevicePlanSchema).min(1),
29570
+ /** Which measurements run. At least one. */
29571
+ phases: array(NodeBenchmarkPhaseSchema).min(1).default(["device", "pipeline"]),
29572
+ /**
29573
+ * Detail steps (catalog step ids under the root: faces, plates,
29574
+ * classifiers, CLIP…) the `pipeline` measurement enables. The root
29575
+ * detector always runs.
29576
+ */
29577
+ steps: array(string().min(1)).default([]),
29578
+ /** Offered rate of one stream / session. */
29579
+ fpsPerStream: number().int().min(1).max(30).default(NODE_BENCHMARK_DEFAULTS.fpsPerStream),
29580
+ /** Hard deadline: the mode ends and the cluster is restored when it passes. */
29581
+ budgetMinutes: number().int().min(NODE_BENCHMARK_DEFAULTS.minBudgetMinutes).max(NODE_BENCHMARK_DEFAULTS.maxBudgetMinutes).default(NODE_BENCHMARK_DEFAULTS.budgetMinutes),
29582
+ /** Keep the models the run downloaded (default: delete what was not installed before). */
29583
+ keepDownloadedModels: boolean().default(false),
29584
+ /** Start although the other nodes' capacity does not cover the sessions running now. */
29585
+ acceptInsufficientHeadroom: boolean().default(false)
29586
+ });
29587
+ var NodeBenchmarkRefusalSchema = object({
29588
+ kind: _enum([
29589
+ "benchmark-active",
29590
+ "node-offline",
29591
+ "unknown-device",
29592
+ "no-phase",
29593
+ "insufficient-headroom"
29594
+ ]),
29595
+ detail: string(),
29596
+ overridable: boolean()
29597
+ });
29598
+ /** A camera whose detection leaves the node for the run. */
29599
+ var NodeBenchmarkMovingCameraSchema = object({
29600
+ deviceId: number(),
29601
+ /** Placed on the node now (a standing attach or a running session). */
29602
+ placedOnNode: boolean(),
29603
+ /** A node pin naming this node, ignored for the run. */
29604
+ pinnedToNode: boolean()
29605
+ });
29606
+ /** A camera that cannot leave: no other node can obtain its frames. */
29607
+ var NodeBenchmarkStayingCameraSchema = object({
29608
+ deviceId: number(),
29609
+ reason: literal("only-frame-source")
29610
+ });
29611
+ var NodeBenchmarkPreflightSchema = object({
29612
+ nodeId: string(),
29613
+ online: boolean(),
29614
+ moving: array(NodeBenchmarkMovingCameraSchema).readonly(),
29615
+ /** Keep running on the node during the run; the result is flagged contaminated. */
29616
+ staying: array(NodeBenchmarkStayingCameraSchema).readonly(),
29617
+ estimatedDurationMs: number(),
29618
+ /** The run ends and the cluster is restored at the latest after this long. */
29619
+ budgetMs: number(),
29620
+ phases: array(NodeBenchmarkPhaseSchema).readonly(),
29621
+ steps: array(string()).readonly(),
29622
+ devices: array(NodeBenchmarkDevicePlanSchema).readonly(),
29623
+ /** Parallel sessions the cluster runs now, and what the other nodes can carry. */
29624
+ headroom: object({
29625
+ sessionsNow: number(),
29626
+ otherNodesCapacitySessions: number().nullable()
29627
+ }),
29628
+ refusals: array(NodeBenchmarkRefusalSchema).readonly(),
29629
+ canStart: boolean()
29630
+ });
29631
+ /** Where the measuring runner is. */
29632
+ var NodeBenchProgressSchema = object({
29633
+ phase: _enum([
29634
+ "preparing",
29635
+ "device",
29636
+ "pipeline",
29637
+ "cleanup"
29638
+ ]),
29639
+ deviceKey: string().nullable(),
29640
+ modelId: string().nullable(),
29641
+ /** Streams (device) or sessions (pipeline) of the step running now. */
29642
+ load: number().nullable(),
29643
+ cellsDone: number(),
29644
+ cellsTotal: number(),
29645
+ message: string()
29646
+ });
29647
+ /** What limited a ramp. `none` = the ramp ran out of steps still passing. */
29648
+ var NodeBenchLimitSchema = _enum([
29649
+ "p95",
29650
+ "drops",
29651
+ "errors",
29652
+ "stall",
29653
+ "cpu",
29654
+ "ram",
29655
+ "none"
29656
+ ]);
29657
+ var NodeBenchRampStepSchema = object({
29658
+ load: number(),
29659
+ pass: boolean(),
29660
+ p95Ms: number(),
29661
+ dropRatio: number(),
29662
+ /** Completed frames per second over the accounted window. */
29663
+ fps: number(),
29664
+ cpuPct: number().nullable(),
29665
+ ramFreePct: number().nullable(),
29666
+ failReasons: array(string()).readonly()
29667
+ });
29668
+ var NodeBenchCellSchema = discriminatedUnion("phase", [object({
29669
+ phase: literal("device"),
29670
+ deviceKey: string(),
29671
+ modelId: string(),
29672
+ /** Single-stream latency (the K = 1 step). */
29673
+ p50Ms: number(),
29674
+ p95Ms: number(),
29675
+ p99Ms: number(),
29676
+ /** Frames per second sustained at the last passing step. */
29677
+ fps: number(),
29678
+ /** Streams at the camera rate the device carried inside the frame interval; 0 = not even one. */
29679
+ kMax: number(),
29680
+ limitedBy: NodeBenchLimitSchema,
29681
+ /** First call (model load + warm-up). */
29682
+ warmupMs: number(),
29683
+ ramp: array(NodeBenchRampStepSchema).readonly()
29684
+ }), object({
29685
+ phase: literal("pipeline"),
29686
+ deviceKey: string(),
29687
+ modelId: string(),
29688
+ steps: array(string()).readonly(),
29689
+ /** Parallel sessions at the camera rate the node carried; 0 = not even one. */
29690
+ maxSessions: number(),
29691
+ limitedBy: NodeBenchLimitSchema,
29692
+ /** Detail steps that produced at least one result on the clip — a step that never fired measured nothing. */
29693
+ stepsFired: array(string()).readonly(),
29694
+ warmupMs: number(),
29695
+ ramp: array(NodeBenchRampStepSchema).readonly()
29696
+ })]);
29697
+ /**
29698
+ * What a result was measured ON. A result whose fingerprint no longer matches
29699
+ * the node no longer beats the table.
29700
+ */
29701
+ var NodeBenchFingerprintSchema = object({
29702
+ pipelineVersion: string().nullable(),
29703
+ cpuModel: string().nullable(),
29704
+ ramGb: number().nullable(),
29705
+ os: string().nullable(),
29706
+ /** Per device: the pool the cells ran on (runtime + tuning). */
29707
+ pools: record(string(), object({
29708
+ runtime: string(),
29709
+ numWorkers: number(),
29710
+ concurrency: number(),
29711
+ batchMode: string()
29712
+ })).default({})
29713
+ });
29714
+ /** The frames the run used. */
29715
+ var NodeBenchClipSchema = object({
29716
+ /** `camstack-bench-v1` or `reference-images` (the fallback when the clip is not reachable). */
29717
+ id: string(),
29718
+ revision: string().nullable(),
29719
+ frames: number(),
29720
+ width: number(),
29721
+ height: number()
29722
+ });
29723
+ var NodeBenchRunnerInputSchema = object({
29724
+ runId: string().min(1),
29725
+ devices: array(NodeBenchmarkDevicePlanSchema).min(1),
29726
+ phases: array(NodeBenchmarkPhaseSchema).min(1),
29727
+ /** The full detail step tree root for the `pipeline` measurement is built on the node from these ids. */
29728
+ steps: array(string()).default([]),
29729
+ fpsPerStream: number().int().min(1).max(30),
29730
+ /** The runner stops on its own past this instant, whatever the hub does. */
29731
+ deadlineAtMs: number(),
29732
+ settleSec: number().min(0).max(60).default(NODE_BENCHMARK_DEFAULTS.settleSec),
29733
+ measureSec: number().min(2).max(300).default(NODE_BENCHMARK_DEFAULTS.measureSec),
29734
+ keepDownloadedModels: boolean().default(false)
29735
+ });
29736
+ var NodeBenchRunnerStateSchema = _enum([
29737
+ "running",
29738
+ "done",
29739
+ "failed",
29740
+ "aborted"
29741
+ ]);
29742
+ var NodeBenchRunnerStatusSchema = object({
29743
+ runId: string(),
29744
+ nodeId: string(),
29745
+ state: NodeBenchRunnerStateSchema,
29746
+ progress: NodeBenchProgressSchema.nullable(),
29747
+ /** Every finished cell so far — a run stopped half way keeps what it measured. */
29748
+ cells: array(NodeBenchCellSchema).readonly(),
29749
+ fingerprint: NodeBenchFingerprintSchema.nullable(),
29750
+ clip: NodeBenchClipSchema.nullable(),
29751
+ /** Cameras seen running on the node during the run (they share its pools). */
29752
+ activeCameraIds: array(number()).readonly(),
29753
+ /** Models the run downloaded and then deleted (not installed before). */
29754
+ deletedModels: array(string()).readonly(),
29755
+ error: string().nullable(),
29756
+ startedAtMs: number(),
29757
+ finishedAtMs: number().nullable()
29758
+ });
29759
+ var NodeBenchmarkStateSchema = _enum([
29760
+ "draining",
29761
+ "measuring",
29762
+ "restoring",
29763
+ "done",
29764
+ "failed",
29765
+ "aborted"
29766
+ ]);
29767
+ /** Why a run ended. */
29768
+ var NodeBenchmarkEndReasonSchema = _enum([
29769
+ "completed",
29770
+ "operator-abort",
29771
+ "deadline",
29772
+ "node-lost",
29773
+ "runner-lost",
29774
+ "hub-restart",
29775
+ "drain-timeout",
29776
+ "failed"
29777
+ ]);
29778
+ var NodeBenchmarkRunSchema = object({
29779
+ runId: string(),
29780
+ nodeId: string(),
29781
+ state: NodeBenchmarkStateSchema,
29782
+ plan: NodeBenchmarkPlanSchema,
29783
+ startedAtMs: number(),
29784
+ deadlineAtMs: number(),
29785
+ finishedAtMs: number().nullable(),
29786
+ endReason: NodeBenchmarkEndReasonSchema.nullable(),
29787
+ error: string().nullable(),
29788
+ /** Cameras moved off the node for the run. */
29789
+ moved: array(number()).readonly(),
29790
+ /** Cameras that stayed (their only frame source is the node). */
29791
+ staying: array(number()).readonly(),
29792
+ /** Something else ran on the node's pools during the run. */
29793
+ contaminated: boolean(),
29794
+ progress: NodeBenchProgressSchema.nullable(),
29795
+ resultIds: array(string()).readonly()
29796
+ });
29797
+ /** `getNodeBenchmarkStatus`: the active run (or the last one), and whether benchmark mode is on. */
29798
+ var NodeBenchmarkStatusSchema = object({
29799
+ /** The node the cluster is in benchmark mode for; null = none. */
29800
+ modeNodeId: string().nullable(),
29801
+ run: NodeBenchmarkRunSchema.nullable()
29802
+ });
29803
+ /**
29804
+ * One stored measurement — the only authority Auto tune and the automatic
29805
+ * shares read measured capacity from. Written by the orchestrator when a run
29806
+ * ends, never by anyone else.
29807
+ */
29808
+ var NodeBenchmarkResultSchema = object({
29809
+ id: string(),
29810
+ runId: string(),
29811
+ nodeId: string(),
29812
+ cell: NodeBenchCellSchema,
29813
+ fpsPerStream: number(),
29814
+ fingerprint: NodeBenchFingerprintSchema.nullable(),
29815
+ clip: NodeBenchClipSchema.nullable(),
29816
+ /** Other work shared the node's pools (a camera that could not move, or the hub's own duties). */
29817
+ contaminated: boolean(),
29818
+ stayingCameras: array(number()).readonly(),
29819
+ /** The run ended early; the cell itself completed. */
29820
+ partialRun: boolean(),
29821
+ measuredAtMs: number()
29822
+ });
29823
+ var ListNodeBenchmarkResultsInputSchema = object({
29824
+ nodeId: string().optional(),
29825
+ deviceKey: string().optional()
29826
+ });
29827
+ /** A result with its standing today: does it still beat the table? */
29828
+ var NodeBenchmarkResultViewSchema = NodeBenchmarkResultSchema.extend({
29829
+ /** `fresh` beats the table; `stale` falls back to it; `superseded` = a newer row covers the same cell. */
29830
+ standing: _enum([
29831
+ "fresh",
29832
+ "stale",
29833
+ "superseded"
29834
+ ]),
29835
+ staleWhy: _enum([
29836
+ "age",
29837
+ "runtime",
29838
+ "pool-tuning"
29839
+ ]).nullable()
29840
+ });
29841
+ object({
29842
+ runId: string(),
29843
+ nodeId: string(),
29844
+ startedAtMs: number(),
29845
+ deadlineAtMs: number(),
29846
+ plan: NodeBenchmarkPlanSchema,
29847
+ moved: array(number()).readonly(),
29848
+ staying: array(number()).readonly()
29849
+ });
29850
+ /** Candidate detectors per device, for the plan editor. */
29851
+ var NodeBenchmarkCandidatesSchema = object({
29852
+ nodeId: string(),
29853
+ reachable: boolean(),
29854
+ devices: array(object({
29855
+ deviceKey: string(),
29856
+ enabled: boolean(),
29857
+ available: boolean(),
29858
+ /** Ordered: what Auto tune would pick first, then the rest of the family by accuracy. */
29859
+ suggested: array(string()).readonly(),
29860
+ /** Every root detector the device has a build for. */
29861
+ all: array(string()).readonly(),
29862
+ /** The model the device runs now, when pinned. */
29863
+ currentModelId: string().nullable()
29864
+ })).readonly(),
29865
+ /** Detail steps the node's catalog offers under the root (for the `pipeline` measurement). */
29866
+ steps: array(object({
29867
+ id: string(),
29868
+ name: string(),
29869
+ slot: string()
29870
+ })).readonly()
29871
+ });
27332
29872
  object({
27333
29873
  activeCameras: number(),
27334
29874
  throttledCameras: number(),
@@ -28607,7 +31147,30 @@ var pipelineRunnerCapability = {
28607
31147
  releaseParkedTrackFrames: method(object({
28608
31148
  deviceId: number(),
28609
31149
  trackId: string()
28610
- }), object({ released: number().int().nonnegative() }), { kind: "mutation" })
31150
+ }), object({ released: number().int().nonnegative() }), { kind: "mutation" }),
31151
+ /**
31152
+ * Start measuring THIS node for the orchestrator's node benchmark: the
31153
+ * bench clip decoded once into RAM, each device × candidate detector on an
31154
+ * open-loop ramp (`device`), then the chosen pipeline with the requested
31155
+ * detail steps (`pipeline`). Everything runs in-process with the executor
31156
+ * — no frame crosses a node (D9) — and writes nothing: no track, event,
31157
+ * media or notification. Reached by `nodePin(nodeId)`. Answers at once;
31158
+ * one run per node; the run stops itself at `deadlineAtMs`.
31159
+ */
31160
+ startNodeBench: method(NodeBenchRunnerInputSchema, object({
31161
+ accepted: literal(true),
31162
+ runId: string()
31163
+ }), {
31164
+ kind: "mutation",
31165
+ auth: "admin"
31166
+ }),
31167
+ /** The run's progress and every finished cell; null when this runner does not know `runId`. */
31168
+ getNodeBenchStatus: method(object({ runId: string() }), NodeBenchRunnerStatusSchema.nullable(), { auth: "admin" }),
31169
+ /** Stop the run; what it finished is kept. */
31170
+ abortNodeBench: method(object({ runId: string() }), object({ aborted: boolean() }), {
31171
+ kind: "mutation",
31172
+ auth: "admin"
31173
+ })
28611
31174
  }
28612
31175
  };
28613
31176
  var CameraPipelineConfigSchema = object({
@@ -29248,6 +31811,21 @@ method(object({
29248
31811
  }), method(PlacementStatsInputSchema, PlacementStatsSchema, { auth: "admin" }), method(SuggestSharesInputSchema, SuggestSharesResultSchema, { auth: "admin" }), method(_void(), EffectiveSharesSchema, { auth: "admin" }), method(SetShareSourceInputSchema, object({ success: literal(true) }), {
29249
31812
  kind: "mutation",
29250
31813
  auth: "admin"
31814
+ }), method(NodeBenchmarkPlanSchema, NodeBenchmarkPreflightSchema, { auth: "admin" }), method(NodeBenchmarkPlanSchema, discriminatedUnion("kind", [object({
31815
+ kind: literal("started"),
31816
+ runId: string()
31817
+ }), object({
31818
+ kind: literal("refused"),
31819
+ preflight: NodeBenchmarkPreflightSchema
31820
+ })]), {
31821
+ kind: "mutation",
31822
+ auth: "admin"
31823
+ }), method(_void(), NodeBenchmarkStatusSchema, { auth: "admin" }), method(object({ runId: string() }), object({ aborted: boolean() }), {
31824
+ kind: "mutation",
31825
+ auth: "admin"
31826
+ }), method(object({ nodeId: string() }), NodeBenchmarkCandidatesSchema, { auth: "admin" }), method(ListNodeBenchmarkResultsInputSchema, array(NodeBenchmarkResultViewSchema).readonly(), { auth: "admin" }), method(object({ id: string() }), object({ deleted: boolean() }), {
31827
+ kind: "mutation",
31828
+ auth: "admin"
29251
31829
  }), method(object({ deviceId: number() }), CameraPipelineSettingsSchema.nullable()), method(object({
29252
31830
  deviceId: number(),
29253
31831
  addonId: string(),
@@ -29653,8 +32231,8 @@ version: string().optional() }), ServerUpdateActionResultSchema, {
29653
32231
  * `smtp-provider` — pluggable email delivery surface.
29654
32232
  *
29655
32233
  * Collection cap: a deployment may install multiple SMTP relays (e.g.
29656
- * one for transactional / one for notifications). Consumers (magic-link,
29657
- * notifier addons, …) walk the collection and pick the first
32234
+ * one for transactional / one for notifications). Consumers (notifier
32235
+ * addons, …) walk the collection and pick the first
29658
32236
  * ready provider OR target a specific addonId.
29659
32237
  *
29660
32238
  * The shape stays small on purpose — `sendEmail` is enough for the
@@ -29833,7 +32411,7 @@ targets: array(object({
29833
32411
  })));
29834
32412
  /**
29835
32413
  * `sso-bridge` — internal hub-only cap that lets SSO-style auth
29836
- * providers (OIDC, SAML, magic-link, …) mint an HMAC-signed token
32414
+ * providers (OIDC, SAML, …) mint an HMAC-signed token
29837
32415
  * carrying the post-callback claims before redirecting back to
29838
32416
  * `/api/auth/sso/finish`.
29839
32417
  *
@@ -29884,7 +32462,26 @@ var SsoBridgeClaimsSchema = object({
29884
32462
  * editing a descriptor must not retroactively extend or shorten a link the
29885
32463
  * operator already consented to.
29886
32464
  */
29887
- refreshTtl: union([number().int().positive(), literal("never")]).optional()
32465
+ refreshTtl: union([number().int().positive(), literal("never")]).optional(),
32466
+ /**
32467
+ * Opaque handle of a hub-side LINK intent (D782). Set by an OIDC callback
32468
+ * that was started from a signed-in user's "Link" button: the finish then
32469
+ * links this identity to the intent's user instead of signing anyone in.
32470
+ * The handle carries no user id — the hub resolves it, single-use.
32471
+ */
32472
+ linkIntent: string().optional(),
32473
+ /**
32474
+ * Verified `iss` of the id_token behind an OIDC login bridge (D782). A
32475
+ * subject is unique only per issuer, so a link is bound to it.
32476
+ */
32477
+ issuer: string().optional(),
32478
+ /**
32479
+ * SHA-256 (hex) of the `camstack_sso_state` cookie the IdP `/start` set in
32480
+ * the browser that began this sign-in. `/api/auth/sso/finish` requires the
32481
+ * request to present the matching cookie — a login bridge is useless in
32482
+ * any other browser.
32483
+ */
32484
+ browserBinding: string().optional()
29888
32485
  });
29889
32486
  method(object({
29890
32487
  claims: SsoBridgeClaimsSchema,
@@ -34813,6 +37410,9 @@ var CreateIntegrationInputSchema = object({
34813
37410
  enabled: boolean().optional(),
34814
37411
  info: record(string(), unknown()).optional(),
34815
37412
  settings: record(string(), unknown()).optional(),
37413
+ /** Keys of `settings` the form's schema declares secret (by type) — kept in
37414
+ * the keychain, not the table (D787). */
37415
+ secretKeys: array(string()).optional(),
34816
37416
  skipRestart: boolean().optional()
34817
37417
  });
34818
37418
  var UpdateIntegrationInputSchema = object({
@@ -34836,7 +37436,9 @@ method(_void(), array(IntegrationWithStateSchema)), method(object({ id: string()
34836
37436
  auth: "admin"
34837
37437
  }), method(object({ id: string() }), record(string(), unknown()), { auth: "admin" }), method(object({
34838
37438
  id: string(),
34839
- settings: record(string(), unknown())
37439
+ settings: record(string(), unknown()),
37440
+ /** Keys the form's schema declares secret (by type) — keychain-stored (D787). */
37441
+ secretKeys: array(string()).optional()
34840
37442
  }), object({ success: boolean() }), {
34841
37443
  kind: "mutation",
34842
37444
  auth: "admin"
@@ -40815,16 +43417,6 @@ var ApiKeySummarySchema = object({
40815
43417
  createdAt: number(),
40816
43418
  lastUsedAt: number().optional()
40817
43419
  });
40818
- var CreateApiKeyInputSchema = object({
40819
- label: string(),
40820
- isAdmin: boolean().default(false),
40821
- allowedProviders: union([array(string()), literal("*")]).optional(),
40822
- allowedDevices: record(string(), union([array(string()), literal("*")])).optional()
40823
- });
40824
- var CreateApiKeyResultSchema = object({
40825
- token: string(),
40826
- record: ApiKeySummarySchema
40827
- });
40828
43420
  var ScopedTokenSummarySchema = object({
40829
43421
  id: string(),
40830
43422
  userId: string(),
@@ -40865,6 +43457,32 @@ var TotpStatusSchema = object({
40865
43457
  /** Null when no row exists OR the row is still pending confirmation. */
40866
43458
  confirmedAt: number().nullable()
40867
43459
  });
43460
+ /**
43461
+ * user-management — singleton capability for user accounts, API keys,
43462
+ * and scoped tokens.
43463
+ *
43464
+ * v2 model: every method gated by `auth: 'admin'`. Admin-only delegation
43465
+ * — the subset check on `setUserScopes` / `createScopedToken` is moot
43466
+ * because non-admins never reach these. If/when we open non-admin
43467
+ * delegation, structural caller-scope subset check goes inside the
43468
+ * provider.
43469
+ */
43470
+ var ExternalIdentitySchema = object({
43471
+ /** Login-method id of the provider instance, e.g. `auth-oidc/authentik`. */
43472
+ provider: string(),
43473
+ /** The IdP's stable subject (`sub`) for this account. */
43474
+ subject: string(),
43475
+ /** The verified `iss` of the IdP the identity was linked under — `sub` is unique only per issuer. */
43476
+ issuer: string(),
43477
+ userId: string(),
43478
+ /** What the IdP called the account at link time (username / email) — display only. */
43479
+ label: string().optional(),
43480
+ linkedAt: number()
43481
+ });
43482
+ var ExternalIdentityKeySchema = object({
43483
+ provider: string().min(1),
43484
+ subject: string().min(1)
43485
+ });
40868
43486
  method(_void(), array(UserSummarySchema), { auth: "admin" }), method(CreateUserInputSchema, UserSummarySchema, {
40869
43487
  kind: "mutation",
40870
43488
  auth: "admin",
@@ -40897,17 +43515,10 @@ method(_void(), array(UserSummarySchema), { auth: "admin" }), method(CreateUserI
40897
43515
  }), UserSummarySchema.extend({ passwordHash: string() }).nullable(), {
40898
43516
  kind: "mutation",
40899
43517
  access: "view"
40900
- }), method(_void(), array(ApiKeySummarySchema), { auth: "admin" }), method(CreateApiKeyInputSchema, CreateApiKeyResultSchema, {
40901
- kind: "mutation",
40902
- auth: "admin",
40903
- access: "create"
40904
- }), method(object({ id: string() }), object({ success: literal(true) }), {
43518
+ }), method(_void(), array(ApiKeySummarySchema), { auth: "admin" }), method(object({ id: string() }), object({ success: literal(true) }), {
40905
43519
  kind: "mutation",
40906
43520
  auth: "admin",
40907
43521
  access: "delete"
40908
- }), method(object({ token: string() }), ApiKeySummarySchema.nullable(), {
40909
- kind: "mutation",
40910
- access: "view"
40911
43522
  }), method(CreateScopedTokenInputSchema, CreateScopedTokenResultSchema, {
40912
43523
  kind: "mutation",
40913
43524
  auth: "admin",
@@ -40978,7 +43589,14 @@ method(_void(), array(UserSummarySchema), { auth: "admin" }), method(CreateUserI
40978
43589
  userId: string(),
40979
43590
  username: string(),
40980
43591
  scopes: array(TokenScopeSchema)
40981
- }).nullable(), { access: "view" }), method(_void(), array(OauthSessionSummarySchema), { auth: "admin" }), method(object({ id: string() }), object({ success: boolean() }), {
43592
+ }).nullable(), { access: "view" }), method(object({ userId: string() }), array(ExternalIdentitySchema), { auth: "admin" }), method(ExternalIdentityKeySchema, object({
43593
+ userId: string(),
43594
+ issuer: string()
43595
+ }).nullable(), { auth: "admin" }), method(ExternalIdentityKeySchema.extend({ userId: string() }), object({ success: boolean() }), {
43596
+ kind: "mutation",
43597
+ auth: "admin",
43598
+ access: "delete"
43599
+ }), method(_void(), array(OauthSessionSummarySchema), { auth: "admin" }), method(object({ id: string() }), object({ success: boolean() }), {
40982
43600
  kind: "mutation",
40983
43601
  auth: "admin",
40984
43602
  access: "delete"
@@ -41369,6 +43987,451 @@ DeviceType.Camera, method(object({
41369
43987
  detection: array(ZoneRuleSchema).readonly(),
41370
43988
  package: array(ZoneRuleSchema).readonly()
41371
43989
  });
43990
+ /**
43991
+ * `training-provider` — ONE cloud that can run the CamStack trainer.
43992
+ *
43993
+ * A thin, mockable translation layer: it knows how to run a container with a
43994
+ * GPU, move a dataset in, read the job's stdout and hand artefacts back. It
43995
+ * knows nothing about datasets, splits, floors, cost policy or Model Studio —
43996
+ * those are the `training` orchestrator's (D805). Every rule written there
43997
+ * once is what makes a second provider (RunPod, a local NVIDIA node) a new
43998
+ * manifest entry and nothing else.
43999
+ *
44000
+ * Collection, routed by the `addonId` in every single-row input (the `llm` /
44001
+ * `notification-output` posture); `describe` concat-fans across providers.
44002
+ * Every method is `admin`: these spend money.
44003
+ *
44004
+ * Every cloud object a provider creates is tagged with the orchestrator's
44005
+ * `jobKey`, so a retried submit finds the job it already started instead of
44006
+ * starting a second GPU, and `listJobs` can find orphans.
44007
+ *
44008
+ * Bytes never ride a cap field: the dataset arrives as a `ctx.peerBytes`
44009
+ * ticket the producer (pipeline-analytics) minted, and artefacts leave as a
44010
+ * ticket the provider mints (D613).
44011
+ */
44012
+ var TrainingGpuOptionSchema = object({
44013
+ id: string(),
44014
+ label: string(),
44015
+ /** List price, USD per GPU-hour, before any region multiplier. */
44016
+ usdPerHour: number().nonnegative(),
44017
+ vramGb: number().nonnegative()
44018
+ });
44019
+ var TrainingRegionOptionSchema = object({
44020
+ /** `''` = any region (the provider's choice). */
44021
+ id: string(),
44022
+ label: string(),
44023
+ priceMultiplier: number().positive()
44024
+ });
44025
+ /**
44026
+ * The provider's per-account settings, as the orchestrator reads them. They
44027
+ * live in the PROVIDER addon's settings (operator decision 2026-10-08: they
44028
+ * depend on the user's account), never hard-coded in the orchestrator.
44029
+ */
44030
+ var TrainingProviderDefaultsSchema = object({
44031
+ gpuType: string(),
44032
+ region: string(),
44033
+ costCapUsd: number().nonnegative(),
44034
+ maxRuntimeSec: number().int().positive(),
44035
+ /** Hours a FAILED job's cloud dataset is kept for debugging; 0 = delete at once. */
44036
+ failedDatasetGraceHours: number().nonnegative()
44037
+ });
44038
+ var TrainingProviderDescriptorSchema = object({
44039
+ addonId: string(),
44040
+ /** `modal`, `runpod`, `fake`, … */
44041
+ kind: string(),
44042
+ label: string(),
44043
+ gpuTypes: array(TrainingGpuOptionSchema).readonly(),
44044
+ regions: array(TrainingRegionOptionSchema).readonly(),
44045
+ maxDatasetBytes: number().int().positive(),
44046
+ maxRuntimeSec: number().int().positive(),
44047
+ freeTierNote: string().optional(),
44048
+ /** Where the data goes, in one sentence the confirm dialog repeats. */
44049
+ dataResidencyNote: string(),
44050
+ /** Credentials are present — never the values. */
44051
+ configured: boolean(),
44052
+ defaults: TrainingProviderDefaultsSchema
44053
+ });
44054
+ var TrainingCredentialCheckSchema = object({
44055
+ ok: boolean(),
44056
+ /** Workspace / account name, when the provider says. */
44057
+ account: string().optional(),
44058
+ reason: _enum([
44059
+ "missing",
44060
+ "invalid",
44061
+ "forbidden",
44062
+ "network",
44063
+ "quota"
44064
+ ]).optional(),
44065
+ detail: string().optional()
44066
+ });
44067
+ var ProviderJobStateSchema = _enum([
44068
+ "pending",
44069
+ "starting",
44070
+ "running",
44071
+ "succeeded",
44072
+ "failed",
44073
+ "cancelled",
44074
+ "lost"
44075
+ ]);
44076
+ var ProviderJobStatusSchema = object({
44077
+ jobKey: string(),
44078
+ providerJobId: string().optional(),
44079
+ state: ProviderJobStateSchema,
44080
+ startedAt: number().optional(),
44081
+ endedAt: number().optional(),
44082
+ exitCode: number().int().optional(),
44083
+ failureReason: string().optional(),
44084
+ gpuType: string(),
44085
+ region: string().optional(),
44086
+ billedSeconds: number().nonnegative(),
44087
+ costUsd: number().nonnegative(),
44088
+ /** True when `costUsd` is runtime × list price, not a billing answer. */
44089
+ costIsEstimate: boolean(),
44090
+ lastFetchedAt: number()
44091
+ });
44092
+ /**
44093
+ * The trainer the job runs, by SOURCE revision: the provider turns it into an
44094
+ * image its own way (Modal builds the published Dockerfile at that revision;
44095
+ * a registry-pull provider maps it to a tag). Recorded on the job and echoed
44096
+ * in `result.json`.
44097
+ */
44098
+ var TrainerSourceRefSchema = object({
44099
+ /** Hugging Face repo id, e.g. `camstack/camstack-trainer`. */
44100
+ repo: string().min(1),
44101
+ /** A commit sha (never a branch) — the job must be reproducible. */
44102
+ revision: string().regex(/^[0-9a-f]{7,64}$/)
44103
+ });
44104
+ var JobRef = {
44105
+ addonId: string(),
44106
+ jobKey: string().uuid()
44107
+ };
44108
+ var TrainingLogLineSchema = object({
44109
+ ts: number(),
44110
+ text: string()
44111
+ });
44112
+ method(object({}), array(TrainingProviderDescriptorSchema).readonly(), { auth: "admin" }), method(object({ addonId: string() }), TrainingCredentialCheckSchema, {
44113
+ kind: "mutation",
44114
+ auth: "admin",
44115
+ timeoutMs: 3e4
44116
+ }), method(object({
44117
+ addonId: string(),
44118
+ gpuType: string(),
44119
+ region: string(),
44120
+ datasetBytes: number().int().nonnegative(),
44121
+ gpuSecondsLow: number().nonnegative(),
44122
+ gpuSecondsHigh: number().nonnegative()
44123
+ }), object({
44124
+ usdLow: number().nonnegative(),
44125
+ usdHigh: number().nonnegative(),
44126
+ notes: array(string()).readonly()
44127
+ }), { auth: "admin" }), method(object({
44128
+ ...JobRef,
44129
+ ticket: PeerBytesTicketSchema
44130
+ }), object({
44131
+ bytes: number().int().nonnegative(),
44132
+ sha256: string()
44133
+ }), {
44134
+ kind: "mutation",
44135
+ auth: "admin",
44136
+ timeoutMs: 120 * 6e4
44137
+ }), method(object({
44138
+ ...JobRef,
44139
+ trainer: TrainerSourceRefSchema,
44140
+ jobSpecJson: string().min(2).max(64e3),
44141
+ gpuType: string(),
44142
+ region: string(),
44143
+ maxRuntimeSec: number().int().positive()
44144
+ }), ProviderJobStatusSchema, {
44145
+ kind: "mutation",
44146
+ auth: "admin",
44147
+ timeoutMs: 30 * 6e4
44148
+ }), method(object(JobRef), ProviderJobStatusSchema, {
44149
+ auth: "admin",
44150
+ timeoutMs: 6e4
44151
+ }), method(object({
44152
+ ...JobRef,
44153
+ cursor: string().optional(),
44154
+ max: number().int().min(1).max(500)
44155
+ }), object({
44156
+ lines: array(TrainingLogLineSchema).readonly(),
44157
+ cursor: string()
44158
+ }), {
44159
+ auth: "admin",
44160
+ timeoutMs: 6e4
44161
+ }), method(object(JobRef), object({ ok: literal(true) }), {
44162
+ kind: "mutation",
44163
+ auth: "admin",
44164
+ timeoutMs: 6e4
44165
+ }), method(object(JobRef), object({
44166
+ found: boolean(),
44167
+ text: string().optional()
44168
+ }), {
44169
+ kind: "mutation",
44170
+ auth: "admin",
44171
+ timeoutMs: 5 * 6e4
44172
+ }), method(object({
44173
+ ...JobRef,
44174
+ path: _enum(["bundle.tar"])
44175
+ }), object({ ticket: PeerBytesTicketSchema }), {
44176
+ kind: "mutation",
44177
+ auth: "admin",
44178
+ timeoutMs: 5 * 6e4
44179
+ }), method(object(JobRef), object({ deleted: array(string()).readonly() }), {
44180
+ kind: "mutation",
44181
+ auth: "admin",
44182
+ timeoutMs: 5 * 6e4
44183
+ }), method(object({ addonId: string() }), array(ProviderJobStatusSchema).readonly(), {
44184
+ auth: "admin",
44185
+ timeoutMs: 2 * 6e4
44186
+ });
44187
+ /**
44188
+ * `training` — the cloud-training orchestrator (D805). Hub-only singleton,
44189
+ * provided by `addon-training`.
44190
+ *
44191
+ * It owns what every provider must agree on, written once:
44192
+ *
44193
+ * - **Dataset versions.** Taken over from pipeline-analytics (D796): the rows
44194
+ * live here (D808); pipeline-analytics still CUTS a version (it owns the corpus and
44195
+ * the export plan) and reaches this store through the five row methods
44196
+ * below, so the Retrain page and the export did not change.
44197
+ * - **Jobs.** A persisted state machine, a reconcile loop against the
44198
+ * provider, a cost guard, a daily orphan sweep and the retention rules.
44199
+ * - **The return flow.** Verified artefacts → Model Studio
44200
+ * (`custom-model-registry.importModelBundle`) → canary on cameras →
44201
+ * rollback. Nothing is ever registered automatically.
44202
+ *
44203
+ * Every method is `admin`.
44204
+ */
44205
+ /** A version WITH its frame list — what the export and a job read. */
44206
+ var TrainingDatasetVersionRowSchema = RetrainDatasetVersionSchema.omit({ frameCount: true }).extend({ frameIds: array(string()).max(2e4).readonly() });
44207
+ /** A base model a detector job can fine-tune, and the baseline it is judged against. */
44208
+ var TrainingBaseModelSchema = object({
44209
+ modelId: string(),
44210
+ label: string(),
44211
+ weights: string(),
44212
+ imgsz: number().int(),
44213
+ baselineOnnxUrl: string(),
44214
+ baselineFloors: record(string(), number()),
44215
+ /** The base the fleet runs most — the UI's default. */
44216
+ recommended: boolean()
44217
+ });
44218
+ var TrainingPresetSchema = _enum([
44219
+ "quick",
44220
+ "standard",
44221
+ "thorough"
44222
+ ]);
44223
+ var TrainingJobRequestSchema = object({
44224
+ datasetVersionId: string().min(1),
44225
+ /** The `training-provider` addon that runs it. */
44226
+ addonId: string().min(1),
44227
+ gpuType: string().min(1),
44228
+ region: string(),
44229
+ baseModelId: string().min(1),
44230
+ preset: TrainingPresetSchema,
44231
+ /** Freeze the backbone's first N layers; `null` = the preset's choice. */
44232
+ freeze: number().int().nonnegative().nullable(),
44233
+ /** Cameras held out whole for evaluation; `null` = the orchestrator's default. */
44234
+ holdoutCameras: array(number().int()).nullable()
44235
+ });
44236
+ var TrainingSplitPlanSchema = object({
44237
+ holdoutCameras: array(number().int()).readonly(),
44238
+ /** Used when no camera is held out: the last N days of every camera. */
44239
+ holdoutLastDays: number().int().nonnegative(),
44240
+ /** Holdout subjects per class (camera holdout only; `null` = known only after the split). */
44241
+ holdoutSupport: record(string(), number().int()).nullable(),
44242
+ trainSubjects: number().int()
44243
+ });
44244
+ var TrainingRefusalReasonSchema = _enum([
44245
+ "unknown-dataset",
44246
+ "unknown-provider",
44247
+ "provider-not-configured",
44248
+ "unknown-base-model",
44249
+ "unknown-gpu",
44250
+ "dataset-too-large",
44251
+ "no-training-subjects",
44252
+ "job-already-running"
44253
+ ]);
44254
+ var TrainingJobPlanSchema = object({
44255
+ refusal: object({
44256
+ reason: TrainingRefusalReasonSchema,
44257
+ detail: string()
44258
+ }).nullable(),
44259
+ warnings: array(string()).readonly(),
44260
+ split: TrainingSplitPlanSchema.nullable(),
44261
+ estimate: object({
44262
+ datasetBytes: number().int(),
44263
+ uploadMinutesAt20Mbps: number(),
44264
+ gpuSecondsLow: number(),
44265
+ gpuSecondsHigh: number(),
44266
+ usdLow: number(),
44267
+ usdHigh: number(),
44268
+ notes: array(string()).readonly()
44269
+ }).nullable(),
44270
+ /** Pre-filled from the provider's settings; the operator may lower or raise them. */
44271
+ defaults: object({
44272
+ maxCostUsd: number(),
44273
+ maxRuntimeSec: number().int()
44274
+ }).nullable(),
44275
+ /** The sentence the confirm dialog repeats: where the frames go and when they are deleted. */
44276
+ dataNotice: string()
44277
+ });
44278
+ /**
44279
+ * Orchestrator-owned states, persisted. `uploading` covers exporting the
44280
+ * archive (it is streamed, never staged). Terminal: `failed`, `cancelled`,
44281
+ * `lost`, `expired`, `discarded`. `registered` and `canary` are where a
44282
+ * result lives after the operator acted on it.
44283
+ */
44284
+ var TrainingJobStateSchema = _enum([
44285
+ "uploading",
44286
+ "submitted",
44287
+ "starting",
44288
+ "running",
44289
+ "collecting",
44290
+ "ready",
44291
+ "registered",
44292
+ "canary",
44293
+ "failed",
44294
+ "cancelling",
44295
+ "cancelled",
44296
+ "lost",
44297
+ "expired",
44298
+ "discarded"
44299
+ ]);
44300
+ var TrainingFailureReasonSchema = _enum([
44301
+ "cost-cap",
44302
+ "runtime-cap",
44303
+ "upload-failed",
44304
+ "submit-failed",
44305
+ "trainer-failed",
44306
+ "result-invalid",
44307
+ "checksum-mismatch",
44308
+ "fetch-failed",
44309
+ "provider-error",
44310
+ "hub-restart-during-upload"
44311
+ ]);
44312
+ var TrainingProgressPointSchema = object({
44313
+ epoch: number().int(),
44314
+ map50: number().nullable(),
44315
+ map50_95: number().nullable()
44316
+ });
44317
+ var TrainingCanarySchema = object({
44318
+ deviceIds: array(number().int()).readonly(),
44319
+ since: number(),
44320
+ /** Every override the canary replaced, exactly, so rollback restores it. */
44321
+ previous: array(object({
44322
+ deviceId: number().int(),
44323
+ nodeId: string(),
44324
+ deviceKey: string(),
44325
+ patch: object({
44326
+ modelId: string().optional(),
44327
+ settings: record(string(), unknown()).readonly().optional()
44328
+ }).nullable()
44329
+ })).readonly()
44330
+ });
44331
+ var TrainingJobSchema = object({
44332
+ id: string(),
44333
+ idempotencyKey: string(),
44334
+ name: string(),
44335
+ createdAt: number(),
44336
+ updatedAt: number(),
44337
+ state: TrainingJobStateSchema,
44338
+ stage: TrainingStageSchema.nullable(),
44339
+ failure: object({
44340
+ reason: TrainingFailureReasonSchema,
44341
+ stage: string().nullable(),
44342
+ detail: string()
44343
+ }).nullable(),
44344
+ request: TrainingJobRequestSchema,
44345
+ maxCostUsd: number().nonnegative(),
44346
+ maxRuntimeSec: number().int().positive(),
44347
+ trainer: TrainerSourceRefSchema,
44348
+ datasetLayout: RetrainExportLayoutSchema,
44349
+ dataset: object({
44350
+ bytes: number().int(),
44351
+ sha256: string(),
44352
+ uploadedAt: number()
44353
+ }).nullable(),
44354
+ split: TrainingSplitPlanSchema,
44355
+ provider: object({
44356
+ state: ProviderJobStateSchema.nullable(),
44357
+ providerJobId: string().nullable(),
44358
+ startedAt: number().nullable(),
44359
+ endedAt: number().nullable(),
44360
+ billedSeconds: number(),
44361
+ costUsd: number(),
44362
+ costIsEstimate: boolean(),
44363
+ lastPolledAt: number().nullable()
44364
+ }),
44365
+ progress: object({
44366
+ epoch: number().int().nullable(),
44367
+ epochs: number().int().nullable(),
44368
+ etaSec: number().nullable(),
44369
+ series: array(TrainingProgressPointSchema).readonly()
44370
+ }),
44371
+ /** The last lines of the job's output (≤ 200), newest last. Never frame paths. */
44372
+ logTail: array(string()).readonly(),
44373
+ logCursor: string().nullable(),
44374
+ artifacts: object({
44375
+ bundleBytes: number().int(),
44376
+ bundleSha256: string(),
44377
+ fetchedAt: number(),
44378
+ /** When the staged artefacts are deleted from the hub. */
44379
+ expiresAt: number()
44380
+ }).nullable(),
44381
+ /** When the provider-side copy of the frames was deleted; null while it exists. */
44382
+ cloudDatasetDeletedAt: number().nullable(),
44383
+ /** A failed job's dataset is kept until then (the provider's grace), then deleted. */
44384
+ cloudCleanupDueAt: number().nullable(),
44385
+ /** Model ids registered from this job (base, and int8 when kept). */
44386
+ registeredModelIds: array(string()).readonly(),
44387
+ canary: TrainingCanarySchema.nullable()
44388
+ });
44389
+ var IdInput = object({ id: string().min(1) });
44390
+ method(TrainingDatasetVersionRowSchema, object({ stored: boolean() }), {
44391
+ kind: "mutation",
44392
+ auth: "admin"
44393
+ }), method(IdInput, TrainingDatasetVersionRowSchema.nullable(), { auth: "admin" }), method(object({}), array(RetrainDatasetVersionSchema).readonly(), { auth: "admin" }), method(object({ name: string() }), object({ id: string().nullable() }), { auth: "admin" }), method(IdInput, object({ removed: boolean() }), {
44394
+ kind: "mutation",
44395
+ auth: "admin"
44396
+ }), method(object({}), array(TrainingBaseModelSchema).readonly(), { auth: "admin" }), method(TrainingJobRequestSchema, TrainingJobPlanSchema, {
44397
+ auth: "admin",
44398
+ timeoutMs: 6e4
44399
+ }), method(TrainingJobRequestSchema.extend({
44400
+ name: string().min(1).max(120),
44401
+ maxCostUsd: number().positive(),
44402
+ maxRuntimeSec: number().int().positive(),
44403
+ idempotencyKey: string().min(8).max(80)
44404
+ }), discriminatedUnion("kind", [object({
44405
+ kind: literal("started"),
44406
+ job: TrainingJobSchema
44407
+ }), object({
44408
+ kind: literal("refused"),
44409
+ reason: TrainingRefusalReasonSchema,
44410
+ detail: string()
44411
+ })]), {
44412
+ kind: "mutation",
44413
+ auth: "admin",
44414
+ timeoutMs: 12e4
44415
+ }), method(object({}), array(TrainingJobSchema).readonly(), { auth: "admin" }), method(IdInput, TrainingJobSchema.nullable(), { auth: "admin" }), method(IdInput, TrainingJobSchema, {
44416
+ kind: "mutation",
44417
+ auth: "admin",
44418
+ timeoutMs: 12e4
44419
+ }), method(IdInput, TrainingResultSchema.nullable(), { auth: "admin" }), method(IdInput.extend({ canaryDeviceIds: array(number().int()).readonly() }), TrainingJobSchema, {
44420
+ kind: "mutation",
44421
+ auth: "admin",
44422
+ timeoutMs: 30 * 6e4
44423
+ }), method(IdInput.extend({ deviceIds: array(number().int()).min(1).readonly() }), TrainingJobSchema, {
44424
+ kind: "mutation",
44425
+ auth: "admin",
44426
+ timeoutMs: 12e4
44427
+ }), method(IdInput, TrainingJobSchema, {
44428
+ kind: "mutation",
44429
+ auth: "admin",
44430
+ timeoutMs: 12e4
44431
+ }), method(IdInput, TrainingJobSchema, {
44432
+ kind: "mutation",
44433
+ auth: "admin"
44434
+ });
41372
44435
  SOURCE_CAPS.filter((cap) => cap !== "switch" && cap !== "motion");
41373
44436
  Object.freeze({
41374
44437
  person: .5,
@@ -42012,6 +45075,12 @@ Object.freeze({
42012
45075
  addonId: null,
42013
45076
  access: "create"
42014
45077
  },
45078
+ "backup.checkBackupKey": {
45079
+ capName: "backup",
45080
+ capScope: "system",
45081
+ addonId: null,
45082
+ access: "create"
45083
+ },
42015
45084
  "backup.delete": {
42016
45085
  capName: "backup",
42017
45086
  capScope: "system",
@@ -42024,6 +45093,18 @@ Object.freeze({
42024
45093
  addonId: null,
42025
45094
  access: "delete"
42026
45095
  },
45096
+ "backup.disableEncryption": {
45097
+ capName: "backup",
45098
+ capScope: "system",
45099
+ addonId: null,
45100
+ access: "create"
45101
+ },
45102
+ "backup.getEncryption": {
45103
+ capName: "backup",
45104
+ capScope: "system",
45105
+ addonId: null,
45106
+ access: "view"
45107
+ },
42027
45108
  "backup.getEntries": {
42028
45109
  capName: "backup",
42029
45110
  capScope: "system",
@@ -42078,6 +45159,12 @@ Object.freeze({
42078
45159
  addonId: null,
42079
45160
  access: "create"
42080
45161
  },
45162
+ "backup.setupEncryption": {
45163
+ capName: "backup",
45164
+ capScope: "system",
45165
+ addonId: null,
45166
+ access: "create"
45167
+ },
42081
45168
  "backup.trigger": {
42082
45169
  capName: "backup",
42083
45170
  capScope: "system",
@@ -42630,6 +45717,12 @@ Object.freeze({
42630
45717
  addonId: null,
42631
45718
  access: "create"
42632
45719
  },
45720
+ "customModelRegistry.importModelBundle": {
45721
+ capName: "custom-model-registry",
45722
+ capScope: "system",
45723
+ addonId: null,
45724
+ access: "create"
45725
+ },
42633
45726
  "customModelRegistry.listModels": {
42634
45727
  capName: "custom-model-registry",
42635
45728
  capScope: "system",
@@ -44040,6 +47133,108 @@ Object.freeze({
44040
47133
  addonId: null,
44041
47134
  access: "create"
44042
47135
  },
47136
+ "keychain.delete": {
47137
+ capName: "keychain",
47138
+ capScope: "system",
47139
+ addonId: null,
47140
+ access: "delete"
47141
+ },
47142
+ "keychain.getState": {
47143
+ capName: "keychain",
47144
+ capScope: "system",
47145
+ addonId: null,
47146
+ access: "view"
47147
+ },
47148
+ "keychain.listMeta": {
47149
+ capName: "keychain",
47150
+ capScope: "system",
47151
+ addonId: null,
47152
+ access: "view"
47153
+ },
47154
+ "keychain.put": {
47155
+ capName: "keychain",
47156
+ capScope: "system",
47157
+ addonId: null,
47158
+ access: "create"
47159
+ },
47160
+ "keychain.resolve": {
47161
+ capName: "keychain",
47162
+ capScope: "system",
47163
+ addonId: null,
47164
+ access: "view"
47165
+ },
47166
+ "keychainAdmin.acknowledgeReset": {
47167
+ capName: "keychain-admin",
47168
+ capScope: "system",
47169
+ addonId: null,
47170
+ access: "create"
47171
+ },
47172
+ "keychainAdmin.deleteOrphans": {
47173
+ capName: "keychain-admin",
47174
+ capScope: "system",
47175
+ addonId: null,
47176
+ access: "delete"
47177
+ },
47178
+ "keychainAdmin.downloadRecoveryKey": {
47179
+ capName: "keychain-admin",
47180
+ capScope: "system",
47181
+ addonId: null,
47182
+ access: "create"
47183
+ },
47184
+ "keychainAdmin.listAudit": {
47185
+ capName: "keychain-admin",
47186
+ capScope: "system",
47187
+ addonId: null,
47188
+ access: "view"
47189
+ },
47190
+ "keychainAdmin.listSecrets": {
47191
+ capName: "keychain-admin",
47192
+ capScope: "system",
47193
+ addonId: null,
47194
+ access: "view"
47195
+ },
47196
+ "keychainAdmin.purgeRetiredKeys": {
47197
+ capName: "keychain-admin",
47198
+ capScope: "system",
47199
+ addonId: null,
47200
+ access: "delete"
47201
+ },
47202
+ "keychainAdmin.resetKeychain": {
47203
+ capName: "keychain-admin",
47204
+ capScope: "system",
47205
+ addonId: null,
47206
+ access: "delete"
47207
+ },
47208
+ "keychainAdmin.resetReport": {
47209
+ capName: "keychain-admin",
47210
+ capScope: "system",
47211
+ addonId: null,
47212
+ access: "delete"
47213
+ },
47214
+ "keychainAdmin.reveal": {
47215
+ capName: "keychain-admin",
47216
+ capScope: "system",
47217
+ addonId: null,
47218
+ access: "create"
47219
+ },
47220
+ "keychainAdmin.rotateMasterKey": {
47221
+ capName: "keychain-admin",
47222
+ capScope: "system",
47223
+ addonId: null,
47224
+ access: "create"
47225
+ },
47226
+ "keychainAdmin.setSystemSecret": {
47227
+ capName: "keychain-admin",
47228
+ capScope: "system",
47229
+ addonId: null,
47230
+ access: "create"
47231
+ },
47232
+ "keychainAdmin.status": {
47233
+ capName: "keychain-admin",
47234
+ capScope: "system",
47235
+ addonId: null,
47236
+ access: "view"
47237
+ },
44043
47238
  "lawnMowerControl.dock": {
44044
47239
  capName: "lawn-mower-control",
44045
47240
  capScope: "device",
@@ -45414,6 +48609,18 @@ Object.freeze({
45414
48609
  addonId: null,
45415
48610
  access: "create"
45416
48611
  },
48612
+ "pipelineAnalytics.addRetrainFrameFromRecording": {
48613
+ capName: "pipeline-analytics",
48614
+ capScope: "device",
48615
+ addonId: null,
48616
+ access: "create"
48617
+ },
48618
+ "pipelineAnalytics.addRetrainFramesToCollection": {
48619
+ capName: "pipeline-analytics",
48620
+ capScope: "device",
48621
+ addonId: null,
48622
+ access: "create"
48623
+ },
45417
48624
  "pipelineAnalytics.applyDeviceSettingsPatch": {
45418
48625
  capName: "pipeline-analytics",
45419
48626
  capScope: "device",
@@ -45462,12 +48669,36 @@ Object.freeze({
45462
48669
  addonId: null,
45463
48670
  access: "view"
45464
48671
  },
48672
+ "pipelineAnalytics.createRetrainCollection": {
48673
+ capName: "pipeline-analytics",
48674
+ capScope: "device",
48675
+ addonId: null,
48676
+ access: "create"
48677
+ },
48678
+ "pipelineAnalytics.createRetrainDatasetVersion": {
48679
+ capName: "pipeline-analytics",
48680
+ capScope: "device",
48681
+ addonId: null,
48682
+ access: "create"
48683
+ },
45465
48684
  "pipelineAnalytics.deleteDeviceEvents": {
45466
48685
  capName: "pipeline-analytics",
45467
48686
  capScope: "device",
45468
48687
  addonId: null,
45469
48688
  access: "delete"
45470
48689
  },
48690
+ "pipelineAnalytics.deleteRetrainCollection": {
48691
+ capName: "pipeline-analytics",
48692
+ capScope: "device",
48693
+ addonId: null,
48694
+ access: "delete"
48695
+ },
48696
+ "pipelineAnalytics.deleteRetrainDatasetVersion": {
48697
+ capName: "pipeline-analytics",
48698
+ capScope: "device",
48699
+ addonId: null,
48700
+ access: "delete"
48701
+ },
45471
48702
  "pipelineAnalytics.deleteTracks": {
45472
48703
  capName: "pipeline-analytics",
45473
48704
  capScope: "device",
@@ -45672,6 +48903,30 @@ Object.freeze({
45672
48903
  addonId: null,
45673
48904
  access: "view"
45674
48905
  },
48906
+ "pipelineAnalytics.listRetrainAssistProfiles": {
48907
+ capName: "pipeline-analytics",
48908
+ capScope: "device",
48909
+ addonId: null,
48910
+ access: "view"
48911
+ },
48912
+ "pipelineAnalytics.listRetrainCollectionFrames": {
48913
+ capName: "pipeline-analytics",
48914
+ capScope: "device",
48915
+ addonId: null,
48916
+ access: "view"
48917
+ },
48918
+ "pipelineAnalytics.listRetrainCollections": {
48919
+ capName: "pipeline-analytics",
48920
+ capScope: "device",
48921
+ addonId: null,
48922
+ access: "view"
48923
+ },
48924
+ "pipelineAnalytics.listRetrainDatasetVersions": {
48925
+ capName: "pipeline-analytics",
48926
+ capScope: "device",
48927
+ addonId: null,
48928
+ access: "view"
48929
+ },
45675
48930
  "pipelineAnalytics.listRetrainFrames": {
45676
48931
  capName: "pipeline-analytics",
45677
48932
  capScope: "device",
@@ -45702,6 +48957,12 @@ Object.freeze({
45702
48957
  addonId: null,
45703
48958
  access: "view"
45704
48959
  },
48960
+ "pipelineAnalytics.offerRetrainArchive": {
48961
+ capName: "pipeline-analytics",
48962
+ capScope: "device",
48963
+ addonId: null,
48964
+ access: "create"
48965
+ },
45705
48966
  "pipelineAnalytics.ownersWithMedia": {
45706
48967
  capName: "pipeline-analytics",
45707
48968
  capScope: "device",
@@ -45714,12 +48975,24 @@ Object.freeze({
45714
48975
  addonId: null,
45715
48976
  access: "create"
45716
48977
  },
48978
+ "pipelineAnalytics.previewRetrainDataset": {
48979
+ capName: "pipeline-analytics",
48980
+ capScope: "device",
48981
+ addonId: null,
48982
+ access: "view"
48983
+ },
45717
48984
  "pipelineAnalytics.proposeRetrainAnnotations": {
45718
48985
  capName: "pipeline-analytics",
45719
48986
  capScope: "device",
45720
48987
  addonId: null,
45721
48988
  access: "create"
45722
48989
  },
48990
+ "pipelineAnalytics.proposeRetrainAnnotationsWithLlm": {
48991
+ capName: "pipeline-analytics",
48992
+ capScope: "device",
48993
+ addonId: null,
48994
+ access: "create"
48995
+ },
45723
48996
  "pipelineAnalytics.pruneEvents": {
45724
48997
  capName: "pipeline-analytics",
45725
48998
  capScope: "device",
@@ -45774,6 +49047,18 @@ Object.freeze({
45774
49047
  addonId: null,
45775
49048
  access: "create"
45776
49049
  },
49050
+ "pipelineAnalytics.removeRetrainFrameFromCollection": {
49051
+ capName: "pipeline-analytics",
49052
+ capScope: "device",
49053
+ addonId: null,
49054
+ access: "delete"
49055
+ },
49056
+ "pipelineAnalytics.renameRetrainCollection": {
49057
+ capName: "pipeline-analytics",
49058
+ capScope: "device",
49059
+ addonId: null,
49060
+ access: "create"
49061
+ },
45777
49062
  "pipelineAnalytics.restageRetrainTrack": {
45778
49063
  capName: "pipeline-analytics",
45779
49064
  capScope: "device",
@@ -45804,6 +49089,12 @@ Object.freeze({
45804
49089
  addonId: null,
45805
49090
  access: "create"
45806
49091
  },
49092
+ "pipelineAnalytics.setRetrainFrameComplete": {
49093
+ capName: "pipeline-analytics",
49094
+ capScope: "device",
49095
+ addonId: null,
49096
+ access: "create"
49097
+ },
45807
49098
  "pipelineAnalytics.setTrackFlags": {
45808
49099
  capName: "pipeline-analytics",
45809
49100
  capScope: "device",
@@ -45828,6 +49119,12 @@ Object.freeze({
45828
49119
  addonId: null,
45829
49120
  access: "create"
45830
49121
  },
49122
+ "pipelineAnalytics.verifyRetrainDatasetVersion": {
49123
+ capName: "pipeline-analytics",
49124
+ capScope: "device",
49125
+ addonId: null,
49126
+ access: "view"
49127
+ },
45831
49128
  "pipelineAnalytics.wipeAllAnalytics": {
45832
49129
  capName: "pipeline-analytics",
45833
49130
  capScope: "device",
@@ -45840,6 +49137,12 @@ Object.freeze({
45840
49137
  addonId: null,
45841
49138
  access: "delete"
45842
49139
  },
49140
+ "pipelineAnalytics.writeRetrainArchive": {
49141
+ capName: "pipeline-analytics",
49142
+ capScope: "device",
49143
+ addonId: null,
49144
+ access: "create"
49145
+ },
45843
49146
  "pipelineExecutor.cacheFrameInPool": {
45844
49147
  capName: "pipeline-executor",
45845
49148
  capScope: "system",
@@ -46050,6 +49353,12 @@ Object.freeze({
46050
49353
  addonId: null,
46051
49354
  access: "view"
46052
49355
  },
49356
+ "pipelineOrchestrator.abortNodeBenchmark": {
49357
+ capName: "pipeline-orchestrator",
49358
+ capScope: "system",
49359
+ addonId: null,
49360
+ access: "create"
49361
+ },
46053
49362
  "pipelineOrchestrator.applyAutoTune": {
46054
49363
  capName: "pipeline-orchestrator",
46055
49364
  capScope: "system",
@@ -46074,6 +49383,12 @@ Object.freeze({
46074
49383
  addonId: null,
46075
49384
  access: "create"
46076
49385
  },
49386
+ "pipelineOrchestrator.deleteNodeBenchmarkResult": {
49387
+ capName: "pipeline-orchestrator",
49388
+ capScope: "system",
49389
+ addonId: null,
49390
+ access: "delete"
49391
+ },
46077
49392
  "pipelineOrchestrator.getAgentLoad": {
46078
49393
  capName: "pipeline-orchestrator",
46079
49394
  capScope: "system",
@@ -46182,6 +49497,24 @@ Object.freeze({
46182
49497
  addonId: null,
46183
49498
  access: "view"
46184
49499
  },
49500
+ "pipelineOrchestrator.getNodeBenchmarkCandidates": {
49501
+ capName: "pipeline-orchestrator",
49502
+ capScope: "system",
49503
+ addonId: null,
49504
+ access: "view"
49505
+ },
49506
+ "pipelineOrchestrator.getNodeBenchmarkPreflight": {
49507
+ capName: "pipeline-orchestrator",
49508
+ capScope: "system",
49509
+ addonId: null,
49510
+ access: "view"
49511
+ },
49512
+ "pipelineOrchestrator.getNodeBenchmarkStatus": {
49513
+ capName: "pipeline-orchestrator",
49514
+ capScope: "system",
49515
+ addonId: null,
49516
+ access: "view"
49517
+ },
46185
49518
  "pipelineOrchestrator.getNodeInferenceDevices": {
46186
49519
  capName: "pipeline-orchestrator",
46187
49520
  capScope: "system",
@@ -46224,6 +49557,12 @@ Object.freeze({
46224
49557
  addonId: null,
46225
49558
  access: "view"
46226
49559
  },
49560
+ "pipelineOrchestrator.listNodeBenchmarkResults": {
49561
+ capName: "pipeline-orchestrator",
49562
+ capScope: "system",
49563
+ addonId: null,
49564
+ access: "view"
49565
+ },
46227
49566
  "pipelineOrchestrator.pauseForStorageMigration": {
46228
49567
  capName: "pipeline-orchestrator",
46229
49568
  capScope: "system",
@@ -46368,6 +49707,12 @@ Object.freeze({
46368
49707
  addonId: null,
46369
49708
  access: "create"
46370
49709
  },
49710
+ "pipelineOrchestrator.startNodeBenchmark": {
49711
+ capName: "pipeline-orchestrator",
49712
+ capScope: "system",
49713
+ addonId: null,
49714
+ access: "create"
49715
+ },
46371
49716
  "pipelineOrchestrator.suggestShares": {
46372
49717
  capName: "pipeline-orchestrator",
46373
49718
  capScope: "system",
@@ -46386,6 +49731,12 @@ Object.freeze({
46386
49731
  addonId: null,
46387
49732
  access: "create"
46388
49733
  },
49734
+ "pipelineRunner.abortNodeBench": {
49735
+ capName: "pipeline-runner",
49736
+ capScope: "system",
49737
+ addonId: null,
49738
+ access: "create"
49739
+ },
46389
49740
  "pipelineRunner.attachCamera": {
46390
49741
  capName: "pipeline-runner",
46391
49742
  capScope: "system",
@@ -46434,6 +49785,12 @@ Object.freeze({
46434
49785
  addonId: null,
46435
49786
  access: "view"
46436
49787
  },
49788
+ "pipelineRunner.getNodeBenchStatus": {
49789
+ capName: "pipeline-runner",
49790
+ capScope: "system",
49791
+ addonId: null,
49792
+ access: "view"
49793
+ },
46437
49794
  "pipelineRunner.getParkedTrackFrame": {
46438
49795
  capName: "pipeline-runner",
46439
49796
  capScope: "system",
@@ -46476,6 +49833,12 @@ Object.freeze({
46476
49833
  addonId: null,
46477
49834
  access: "create"
46478
49835
  },
49836
+ "pipelineRunner.startNodeBench": {
49837
+ capName: "pipeline-runner",
49838
+ capScope: "system",
49839
+ addonId: null,
49840
+ access: "create"
49841
+ },
46479
49842
  "plateGallery.assignPlate": {
46480
49843
  capName: "plate-gallery",
46481
49844
  capScope: "system",
@@ -48138,6 +51501,174 @@ Object.freeze({
48138
51501
  addonId: null,
48139
51502
  access: "view"
48140
51503
  },
51504
+ "training.canaryResult": {
51505
+ capName: "training",
51506
+ capScope: "system",
51507
+ addonId: null,
51508
+ access: "create"
51509
+ },
51510
+ "training.cancelJob": {
51511
+ capName: "training",
51512
+ capScope: "system",
51513
+ addonId: null,
51514
+ access: "create"
51515
+ },
51516
+ "training.discardResult": {
51517
+ capName: "training",
51518
+ capScope: "system",
51519
+ addonId: null,
51520
+ access: "create"
51521
+ },
51522
+ "training.findDatasetVersionIdByName": {
51523
+ capName: "training",
51524
+ capScope: "system",
51525
+ addonId: null,
51526
+ access: "view"
51527
+ },
51528
+ "training.getDatasetVersion": {
51529
+ capName: "training",
51530
+ capScope: "system",
51531
+ addonId: null,
51532
+ access: "view"
51533
+ },
51534
+ "training.getJob": {
51535
+ capName: "training",
51536
+ capScope: "system",
51537
+ addonId: null,
51538
+ access: "view"
51539
+ },
51540
+ "training.getJobResult": {
51541
+ capName: "training",
51542
+ capScope: "system",
51543
+ addonId: null,
51544
+ access: "view"
51545
+ },
51546
+ "training.listBaseModels": {
51547
+ capName: "training",
51548
+ capScope: "system",
51549
+ addonId: null,
51550
+ access: "view"
51551
+ },
51552
+ "training.listDatasetVersions": {
51553
+ capName: "training",
51554
+ capScope: "system",
51555
+ addonId: null,
51556
+ access: "view"
51557
+ },
51558
+ "training.listJobs": {
51559
+ capName: "training",
51560
+ capScope: "system",
51561
+ addonId: null,
51562
+ access: "view"
51563
+ },
51564
+ "training.planJob": {
51565
+ capName: "training",
51566
+ capScope: "system",
51567
+ addonId: null,
51568
+ access: "view"
51569
+ },
51570
+ "training.putDatasetVersion": {
51571
+ capName: "training",
51572
+ capScope: "system",
51573
+ addonId: null,
51574
+ access: "create"
51575
+ },
51576
+ "training.registerResult": {
51577
+ capName: "training",
51578
+ capScope: "system",
51579
+ addonId: null,
51580
+ access: "create"
51581
+ },
51582
+ "training.removeDatasetVersion": {
51583
+ capName: "training",
51584
+ capScope: "system",
51585
+ addonId: null,
51586
+ access: "delete"
51587
+ },
51588
+ "training.rollbackCanary": {
51589
+ capName: "training",
51590
+ capScope: "system",
51591
+ addonId: null,
51592
+ access: "create"
51593
+ },
51594
+ "training.startJob": {
51595
+ capName: "training",
51596
+ capScope: "system",
51597
+ addonId: null,
51598
+ access: "create"
51599
+ },
51600
+ "trainingProvider.cancelJob": {
51601
+ capName: "training-provider",
51602
+ capScope: "system",
51603
+ addonId: null,
51604
+ access: "create"
51605
+ },
51606
+ "trainingProvider.cleanupJob": {
51607
+ capName: "training-provider",
51608
+ capScope: "system",
51609
+ addonId: null,
51610
+ access: "create"
51611
+ },
51612
+ "trainingProvider.describe": {
51613
+ capName: "training-provider",
51614
+ capScope: "system",
51615
+ addonId: null,
51616
+ access: "view"
51617
+ },
51618
+ "trainingProvider.estimateJob": {
51619
+ capName: "training-provider",
51620
+ capScope: "system",
51621
+ addonId: null,
51622
+ access: "view"
51623
+ },
51624
+ "trainingProvider.getJob": {
51625
+ capName: "training-provider",
51626
+ capScope: "system",
51627
+ addonId: null,
51628
+ access: "view"
51629
+ },
51630
+ "trainingProvider.listJobEvents": {
51631
+ capName: "training-provider",
51632
+ capScope: "system",
51633
+ addonId: null,
51634
+ access: "view"
51635
+ },
51636
+ "trainingProvider.listJobs": {
51637
+ capName: "training-provider",
51638
+ capScope: "system",
51639
+ addonId: null,
51640
+ access: "view"
51641
+ },
51642
+ "trainingProvider.offerArtifact": {
51643
+ capName: "training-provider",
51644
+ capScope: "system",
51645
+ addonId: null,
51646
+ access: "create"
51647
+ },
51648
+ "trainingProvider.readResult": {
51649
+ capName: "training-provider",
51650
+ capScope: "system",
51651
+ addonId: null,
51652
+ access: "create"
51653
+ },
51654
+ "trainingProvider.submitJob": {
51655
+ capName: "training-provider",
51656
+ capScope: "system",
51657
+ addonId: null,
51658
+ access: "create"
51659
+ },
51660
+ "trainingProvider.uploadDataset": {
51661
+ capName: "training-provider",
51662
+ capScope: "system",
51663
+ addonId: null,
51664
+ access: "create"
51665
+ },
51666
+ "trainingProvider.validateCredentials": {
51667
+ capName: "training-provider",
51668
+ capScope: "system",
51669
+ addonId: null,
51670
+ access: "create"
51671
+ },
48141
51672
  "turnProvider.getTurnServers": {
48142
51673
  capName: "turn-provider",
48143
51674
  capScope: "system",
@@ -48162,12 +51693,6 @@ Object.freeze({
48162
51693
  addonId: null,
48163
51694
  access: "create"
48164
51695
  },
48165
- "userManagement.createApiKey": {
48166
- capName: "user-management",
48167
- capScope: "system",
48168
- addonId: null,
48169
- access: "create"
48170
- },
48171
51696
  "userManagement.createScopedToken": {
48172
51697
  capName: "user-management",
48173
51698
  capScope: "system",
@@ -48192,6 +51717,12 @@ Object.freeze({
48192
51717
  addonId: null,
48193
51718
  access: "delete"
48194
51719
  },
51720
+ "userManagement.findUserByExternalIdentity": {
51721
+ capName: "user-management",
51722
+ capScope: "system",
51723
+ addonId: null,
51724
+ access: "view"
51725
+ },
48195
51726
  "userManagement.getTotpStatus": {
48196
51727
  capName: "user-management",
48197
51728
  capScope: "system",
@@ -48204,6 +51735,12 @@ Object.freeze({
48204
51735
  addonId: null,
48205
51736
  access: "view"
48206
51737
  },
51738
+ "userManagement.listExternalIdentities": {
51739
+ capName: "user-management",
51740
+ capScope: "system",
51741
+ addonId: null,
51742
+ access: "view"
51743
+ },
48207
51744
  "userManagement.listOauthSessions": {
48208
51745
  capName: "user-management",
48209
51746
  capScope: "system",
@@ -48282,17 +51819,17 @@ Object.freeze({
48282
51819
  addonId: null,
48283
51820
  access: "create"
48284
51821
  },
48285
- "userManagement.updateUser": {
51822
+ "userManagement.unlinkExternalIdentity": {
48286
51823
  capName: "user-management",
48287
51824
  capScope: "system",
48288
51825
  addonId: null,
48289
- access: "create"
51826
+ access: "delete"
48290
51827
  },
48291
- "userManagement.validateApiKey": {
51828
+ "userManagement.updateUser": {
48292
51829
  capName: "user-management",
48293
51830
  capScope: "system",
48294
51831
  addonId: null,
48295
- access: "view"
51832
+ access: "create"
48296
51833
  },
48297
51834
  "userManagement.validateCredentials": {
48298
51835
  capName: "user-management",
@@ -51381,6 +54918,11 @@ Object.freeze({
51381
54918
  form: "single",
51382
54919
  optional: false
51383
54920
  }],
54921
+ "pipelineAnalytics.addRetrainFrameFromRecording": [{
54922
+ name: "deviceId",
54923
+ form: "single",
54924
+ optional: false
54925
+ }],
51384
54926
  "pipelineAnalytics.applyDeviceSettingsPatch": [{
51385
54927
  name: "deviceId",
51386
54928
  form: "single",
@@ -51571,6 +55113,11 @@ Object.freeze({
51571
55113
  form: "single",
51572
55114
  optional: false
51573
55115
  }],
55116
+ "pipelineAnalytics.proposeRetrainAnnotationsWithLlm": [{
55117
+ name: "deviceId",
55118
+ form: "single",
55119
+ optional: false
55120
+ }],
51574
55121
  "pipelineAnalytics.pruneEventsBefore": [{
51575
55122
  name: "deviceId",
51576
55123
  form: "single",
@@ -51621,6 +55168,11 @@ Object.freeze({
51621
55168
  form: "single",
51622
55169
  optional: false
51623
55170
  }],
55171
+ "pipelineAnalytics.setRetrainFrameComplete": [{
55172
+ name: "deviceId",
55173
+ form: "single",
55174
+ optional: false
55175
+ }],
51624
55176
  "pipelineAnalytics.setTrackFlags": [{
51625
55177
  name: "deviceId",
51626
55178
  form: "single",
@@ -52392,6 +55944,11 @@ Object.freeze({
52392
55944
  form: "single",
52393
55945
  optional: false
52394
55946
  }],
55947
+ "training.canaryResult": [{
55948
+ name: "deviceIds",
55949
+ form: "array",
55950
+ optional: false
55951
+ }],
52395
55952
  "update.getStatus": [{
52396
55953
  name: "deviceId",
52397
55954
  form: "single",
@@ -53627,6 +57184,73 @@ function collectModelBoundKeys(fields) {
53627
57184
  return "key" in field && "bindsToModel" in field && field.bindsToModel === true ? [field.key] : [];
53628
57185
  });
53629
57186
  }
57187
+ /** Ramp steps the runner tries per cell, at most. */
57188
+ var DEVICE_RAMP = [
57189
+ 1,
57190
+ 2,
57191
+ 4,
57192
+ 6,
57193
+ 8,
57194
+ 12,
57195
+ 16,
57196
+ 24,
57197
+ 32
57198
+ ];
57199
+ var PIPELINE_RAMP = [
57200
+ 1,
57201
+ 2,
57202
+ 3,
57203
+ 4,
57204
+ 6,
57205
+ 8,
57206
+ 10,
57207
+ 12,
57208
+ 16
57209
+ ];
57210
+ var BENCH_ROOT_STEP_ID = "object-detection";
57211
+ function slotAddons(schema, slot) {
57212
+ return schema.slots.find((s) => s.id === slot)?.addons ?? [];
57213
+ }
57214
+ var feeds = (from, to) => to.inputClasses.some((c) => from.outputClasses.includes(c));
57215
+ function layout(schema) {
57216
+ const root = slotAddons(schema, "detector").find((a) => a.id === BENCH_ROOT_STEP_ID);
57217
+ if (root === void 0) return null;
57218
+ const classifiers = slotAddons(schema, "classifier");
57219
+ const croppers = slotAddons(schema, "cropper").filter((c) => feeds(root, c)).map((cropper) => ({
57220
+ cropper,
57221
+ recognizers: classifiers.filter((k) => feeds(cropper, k))
57222
+ }));
57223
+ const underCropper = new Set(croppers.flatMap((c) => c.recognizers.map((r) => r.id)));
57224
+ return {
57225
+ root,
57226
+ croppers,
57227
+ classifiers: classifiers.filter((k) => feeds(root, k) && !underCropper.has(k.id)),
57228
+ refiners: slotAddons(schema, "refiner")
57229
+ };
57230
+ }
57231
+ /** Build the tree. Throws when the node's catalog has no object-detection root. */
57232
+ function buildBenchStepTree(schema, rootModelId, enabledStepIds) {
57233
+ const l = layout(schema);
57234
+ if (l === null) throw new Error(`the node's catalog has no ${BENCH_ROOT_STEP_ID} step`);
57235
+ const on = new Set(enabledStepIds);
57236
+ const step = (a, enabled) => ({
57237
+ addonId: a.id,
57238
+ enabled
57239
+ });
57240
+ return [{
57241
+ addonId: l.root.id,
57242
+ modelId: rootModelId,
57243
+ enabled: true,
57244
+ children: [
57245
+ ...l.croppers.map(({ cropper, recognizers }) => ({
57246
+ ...step(cropper, on.has(cropper.id) || recognizers.some((r) => on.has(r.id))),
57247
+ children: recognizers.map((r) => step(r, on.has(r.id)))
57248
+ })),
57249
+ ...l.classifiers.map((k) => step(k, on.has(k.id))),
57250
+ ...l.refiners.map((r) => step(r, on.has(r.id)))
57251
+ ]
57252
+ }];
57253
+ }
53630
57254
  /** Side of the square, as a multiple of the face box's longer side. */
53631
57255
  var ROOT_FACE_REFINE_SCALE = 1.6;
53632
57256
  /**
@@ -54172,7 +57796,12 @@ var CREDENTIAL_PARAM_PATTERNS = [
54172
57796
  /^bearer$/i,
54173
57797
  /^api[_-]?key$/i,
54174
57798
  /^access[_-]?token$/i,
54175
- /^refresh[_-]?token$/i
57799
+ /^refresh[_-]?token$/i,
57800
+ /^bridge$/i,
57801
+ /^code$/i,
57802
+ /^state$/i,
57803
+ /^challenge$/i,
57804
+ /^link$/i
54176
57805
  ];
54177
57806
  function isCredentialParam(name) {
54178
57807
  return CREDENTIAL_PARAM_PATTERNS.some((re) => re.test(name));
@@ -54194,6 +57823,10 @@ function isCredentialParam(name) {
54194
57823
  * are NOT masked (those are entity references, not credentials).
54195
57824
  */
54196
57825
  function maskUrlCredentials(rawUrl) {
57826
+ if (rawUrl.startsWith("/") && !rawUrl.startsWith("//")) {
57827
+ const masked = maskUrlCredentials(`http://relative.invalid${rawUrl}`);
57828
+ return masked.startsWith("http://relative.invalid") ? masked.slice(23) : rawUrl;
57829
+ }
54197
57830
  try {
54198
57831
  const u = new URL(rawUrl);
54199
57832
  let touched = false;
@@ -55001,6 +58634,12 @@ Object.defineProperty(exports, "DEVICE_BACKEND_TO_FORMAT", {
55001
58634
  return DEVICE_BACKEND_TO_FORMAT;
55002
58635
  }
55003
58636
  });
58637
+ Object.defineProperty(exports, "DEVICE_RAMP", {
58638
+ enumerable: true,
58639
+ get: function() {
58640
+ return DEVICE_RAMP;
58641
+ }
58642
+ });
55004
58643
  Object.defineProperty(exports, "DeviceFeature", {
55005
58644
  enumerable: true,
55006
58645
  get: function() {
@@ -55079,6 +58718,12 @@ Object.defineProperty(exports, "LABEL_SUPPLY_VOCABULARIES", {
55079
58718
  return LABEL_SUPPLY_VOCABULARIES;
55080
58719
  }
55081
58720
  });
58721
+ Object.defineProperty(exports, "MODEL_FORMATS", {
58722
+ enumerable: true,
58723
+ get: function() {
58724
+ return MODEL_FORMATS;
58725
+ }
58726
+ });
55082
58727
  Object.defineProperty(exports, "NativeLeaseAdmissionSchema", {
55083
58728
  enumerable: true,
55084
58729
  get: function() {
@@ -55091,12 +58736,24 @@ Object.defineProperty(exports, "NativeLeaseSettingsSchema", {
55091
58736
  return NativeLeaseSettingsSchema;
55092
58737
  }
55093
58738
  });
58739
+ Object.defineProperty(exports, "NodeBenchRunnerInputSchema", {
58740
+ enumerable: true,
58741
+ get: function() {
58742
+ return NodeBenchRunnerInputSchema;
58743
+ }
58744
+ });
55094
58745
  Object.defineProperty(exports, "OpsLogEntrySchema", {
55095
58746
  enumerable: true,
55096
58747
  get: function() {
55097
58748
  return OpsLogEntrySchema;
55098
58749
  }
55099
58750
  });
58751
+ Object.defineProperty(exports, "PIPELINE_RAMP", {
58752
+ enumerable: true,
58753
+ get: function() {
58754
+ return PIPELINE_RAMP;
58755
+ }
58756
+ });
55100
58757
  Object.defineProperty(exports, "PoolMemoryWatchdog", {
55101
58758
  enumerable: true,
55102
58759
  get: function() {
@@ -55241,6 +58898,12 @@ Object.defineProperty(exports, "boolean", {
55241
58898
  return boolean;
55242
58899
  }
55243
58900
  });
58901
+ Object.defineProperty(exports, "buildBenchStepTree", {
58902
+ enumerable: true,
58903
+ get: function() {
58904
+ return buildBenchStepTree;
58905
+ }
58906
+ });
55244
58907
  Object.defineProperty(exports, "buildFfmpegArgs", {
55245
58908
  enumerable: true,
55246
58909
  get: function() {