@camstack/addon-provider-reolink 1.2.179 → 1.2.181

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/addon.js +1823 -135
  2. package/dist/addon.mjs +1823 -135
  3. package/package.json +1 -1
package/dist/addon.js CHANGED
@@ -5413,7 +5413,7 @@ var ZodIssueCode = {
5413
5413
  var ZodFirstPartyTypeKind;
5414
5414
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
5415
5415
  //#endregion
5416
- //#region ../types/dist/sleep-Cr5YOk3m.mjs
5416
+ //#region ../types/dist/sleep-r3RWkGVx.mjs
5417
5417
  /**
5418
5418
  * The audio chunk plane's byte format, and the ONE expansion from a coded
5419
5419
  * window to float samples (D455).
@@ -5530,7 +5530,7 @@ function isKeychainStoredField(field) {
5530
5530
  var SECRET_CLEAR = { $secretClear: true };
5531
5531
  /** The `'***'` token D634 redaction writes for non-admins. */
5532
5532
  var LEGACY_DEVICE_REDACTION = "***";
5533
- function isRecord$1(value) {
5533
+ function isRecord$2(value) {
5534
5534
  return typeof value === "object" && value !== null && !Array.isArray(value);
5535
5535
  }
5536
5536
  function makeSecretMarker(ref) {
@@ -5541,12 +5541,16 @@ function makeSecretMarker(ref) {
5541
5541
  }
5542
5542
  /** A stored marker: an object whose `$secret` is a non-empty string. */
5543
5543
  function isSecretMarker(value) {
5544
- if (!isRecord$1(value)) return false;
5544
+ if (!isRecord$2(value)) return false;
5545
5545
  const ref = value["$secret"];
5546
5546
  return typeof ref === "string" && ref.length > 0;
5547
5547
  }
5548
+ /** Anything carrying a `$secret` key — a stored marker or a UI view of one. */
5549
+ function isSecretMarkerLike(value) {
5550
+ return isRecord$2(value) && Object.prototype.hasOwnProperty.call(value, "$secret");
5551
+ }
5548
5552
  function isSecretClear(value) {
5549
- return isRecord$1(value) && value["$secretClear"] === true;
5553
+ return isRecord$2(value) && value["$secretClear"] === true;
5550
5554
  }
5551
5555
  /**
5552
5556
  * The UI view of a stored secret field value: a marker becomes "set", inline
@@ -6062,6 +6066,13 @@ function globalSecretScope() {
6062
6066
  function encodeSegment(value) {
6063
6067
  return encodeURIComponent(value);
6064
6068
  }
6069
+ function decodeSegment(value) {
6070
+ try {
6071
+ return decodeURIComponent(value);
6072
+ } catch {
6073
+ return null;
6074
+ }
6075
+ }
6065
6076
  /**
6066
6077
  * The field path of a value inside an array item, addressed by the item's id:
6067
6078
  * `arrayItemFieldPath('providers', 'authentik', 'clientSecret')` →
@@ -6070,6 +6081,75 @@ function encodeSegment(value) {
6070
6081
  function arrayItemFieldPath(arrayKey, itemId, fieldKey) {
6071
6082
  return `${arrayKey}[${encodeSegment(itemId)}].${fieldKey}`;
6072
6083
  }
6084
+ function parseScope(segments) {
6085
+ switch (segments[0]) {
6086
+ case "global": return {
6087
+ scope: GLOBAL_SCOPE,
6088
+ used: 1
6089
+ };
6090
+ case "node": {
6091
+ const nodeId = segments[1] !== void 0 ? decodeSegment(segments[1]) : null;
6092
+ return nodeId === null || nodeId.length === 0 ? null : {
6093
+ scope: {
6094
+ kind: "node",
6095
+ nodeId
6096
+ },
6097
+ used: 2
6098
+ };
6099
+ }
6100
+ case "device": {
6101
+ const raw = segments[1];
6102
+ if (raw === void 0 || !/^\d+$/.test(raw)) return null;
6103
+ return {
6104
+ scope: {
6105
+ kind: "device",
6106
+ deviceId: Number(raw)
6107
+ },
6108
+ used: 2
6109
+ };
6110
+ }
6111
+ case "integration": {
6112
+ const id = segments[1] !== void 0 ? decodeSegment(segments[1]) : null;
6113
+ return id === null || id.length === 0 ? null : {
6114
+ scope: {
6115
+ kind: "integration",
6116
+ integrationId: id
6117
+ },
6118
+ used: 2
6119
+ };
6120
+ }
6121
+ case "row": {
6122
+ const collection = segments[1] !== void 0 ? decodeSegment(segments[1]) : null;
6123
+ const rowId = segments[2] !== void 0 ? decodeSegment(segments[2]) : null;
6124
+ if (collection === null || rowId === null || collection.length === 0 || rowId.length === 0) return null;
6125
+ return {
6126
+ scope: {
6127
+ kind: "row",
6128
+ collection,
6129
+ rowId
6130
+ },
6131
+ used: 3
6132
+ };
6133
+ }
6134
+ default: return null;
6135
+ }
6136
+ }
6137
+ /** Take a ref apart; `null` when it is not a well-formed ref. */
6138
+ function parseSecretRef(ref) {
6139
+ if (!ref.startsWith("secret://")) return null;
6140
+ const segments = ref.slice(9).split("/");
6141
+ const owner = segments[0] !== void 0 ? decodeSegment(segments[0]) : null;
6142
+ if (owner === null || owner.length === 0) return null;
6143
+ const parsed = parseScope(segments.slice(1));
6144
+ if (parsed === null) return null;
6145
+ const fieldPath = segments.slice(1 + parsed.used).join("/");
6146
+ if (fieldPath.length === 0) return null;
6147
+ return {
6148
+ owner,
6149
+ scope: parsed.scope,
6150
+ fieldPath
6151
+ };
6152
+ }
6073
6153
  /** A write to a secret path could not be stored in the keychain, so it was refused. */
6074
6154
  var KeychainWriteRefusedError = class extends Error {
6075
6155
  fieldPath;
@@ -6080,7 +6160,7 @@ var KeychainWriteRefusedError = class extends Error {
6080
6160
  }
6081
6161
  };
6082
6162
  var KEEP = { kind: "keep" };
6083
- function isRecord$2(value) {
6163
+ function isRecord$1(value) {
6084
6164
  return typeof value === "object" && value !== null && !Array.isArray(value);
6085
6165
  }
6086
6166
  function defaultMintId() {
@@ -6093,7 +6173,7 @@ function collectSecretMarkerRefs(value, out = []) {
6093
6173
  return out;
6094
6174
  }
6095
6175
  if (Array.isArray(value)) for (const item of value) collectSecretMarkerRefs(item, out);
6096
- else if (isRecord$2(value)) for (const child of Object.values(value)) collectSecretMarkerRefs(child, out);
6176
+ else if (isRecord$1(value)) for (const child of Object.values(value)) collectSecretMarkerRefs(child, out);
6097
6177
  return out;
6098
6178
  }
6099
6179
  async function storedValueEquals(secrets, marker, candidate) {
@@ -6148,7 +6228,7 @@ function rowId(row, idKey) {
6148
6228
  return null;
6149
6229
  }
6150
6230
  async function writeArray(ctx, node, incoming, stored, fieldPath) {
6151
- const storedRows = Array.isArray(stored) ? stored.filter(isRecord$2) : [];
6231
+ const storedRows = Array.isArray(stored) ? stored.filter(isRecord$1) : [];
6152
6232
  if (!Array.isArray(incoming)) {
6153
6233
  ctx.deletes.push(...collectSecretMarkerRefs(storedRows));
6154
6234
  return {
@@ -6164,7 +6244,7 @@ async function writeArray(ctx, node, incoming, stored, fieldPath) {
6164
6244
  const kept = /* @__PURE__ */ new Set();
6165
6245
  const rows = [];
6166
6246
  for (const row of incoming) {
6167
- if (!isRecord$2(row)) {
6247
+ if (!isRecord$1(row)) {
6168
6248
  rows.push(row);
6169
6249
  continue;
6170
6250
  }
@@ -6189,7 +6269,7 @@ async function writeNode(ctx, node, incoming, stored, fieldPath) {
6189
6269
  case "leaf": return writeLeaf(ctx, incoming, stored, fieldPath);
6190
6270
  case "array": return writeArray(ctx, node, incoming, stored, fieldPath);
6191
6271
  case "object": {
6192
- if (!isRecord$2(incoming)) {
6272
+ if (!isRecord$1(incoming)) {
6193
6273
  if (incoming === void 0) return KEEP;
6194
6274
  ctx.deletes.push(...collectSecretMarkerRefs(stored));
6195
6275
  return {
@@ -6197,7 +6277,7 @@ async function writeNode(ctx, node, incoming, stored, fieldPath) {
6197
6277
  value: incoming
6198
6278
  };
6199
6279
  }
6200
- const storedObj = isRecord$2(stored) ? stored : {};
6280
+ const storedObj = isRecord$1(stored) ? stored : {};
6201
6281
  return {
6202
6282
  kind: "value",
6203
6283
  value: await writeMembers(ctx, node.children, incoming, storedObj, (m) => `${fieldPath}.${m}`)
@@ -6256,12 +6336,19 @@ async function transformSecretWrite(input) {
6256
6336
  }
6257
6337
  };
6258
6338
  }
6339
+ /** Is `ref` one of `owner`'s refs? */
6340
+ function isSecretRefOwnedBy(ref, owner) {
6341
+ return parseSecretRef(ref)?.owner === owner;
6342
+ }
6259
6343
  /**
6260
6344
  * Replace every marker in `value` with its keychain value. Returns the SAME
6261
6345
  * reference when there is no marker (no allocation, no keychain call).
6262
6346
  */
6263
- async function resolveSecretMarkers(value, secrets) {
6264
- const refs = collectSecretMarkerRefs(value);
6347
+ async function resolveSecretMarkers(value, secrets, options = {}) {
6348
+ const keepMarker = options.unresolved === "keep-marker";
6349
+ const owner = options.ownedBy;
6350
+ const inScope = (ref) => owner === void 0 || isSecretRefOwnedBy(ref, owner);
6351
+ const refs = collectSecretMarkerRefs(value).filter(inScope);
6265
6352
  if (refs.length === 0) return {
6266
6353
  value,
6267
6354
  unresolved: []
@@ -6285,10 +6372,18 @@ async function resolveSecretMarkers(value, secrets) {
6285
6372
  }
6286
6373
  const substitute = (v) => {
6287
6374
  if (isSecretMarker(v)) {
6375
+ if (!inScope(v.$secret)) return {
6376
+ keep: true,
6377
+ value: v
6378
+ };
6288
6379
  const answer = answers[v.$secret];
6289
- return answer?.kind === "value" ? {
6380
+ if (answer?.kind === "value") return {
6290
6381
  keep: true,
6291
6382
  value: answer.value
6383
+ };
6384
+ return keepMarker ? {
6385
+ keep: true,
6386
+ value: v
6292
6387
  } : {
6293
6388
  keep: false,
6294
6389
  value: void 0
@@ -6305,7 +6400,7 @@ async function resolveSecretMarkers(value, secrets) {
6305
6400
  value: items
6306
6401
  };
6307
6402
  }
6308
- if (isRecord$2(v)) {
6403
+ if (isRecord$1(v)) {
6309
6404
  const out = {};
6310
6405
  for (const [k, child] of Object.entries(v)) {
6311
6406
  const s = substitute(child);
@@ -6326,14 +6421,152 @@ async function resolveSecretMarkers(value, secrets) {
6326
6421
  unresolved
6327
6422
  };
6328
6423
  }
6329
- function touchesTree(tree, patch) {
6330
- if (tree.size === 0) return false;
6331
- for (const key of Object.keys(patch)) {
6332
- const at = key.indexOf("@");
6333
- if (tree.has(at > 0 ? key.slice(0, at) : key)) return true;
6424
+ /** An addon tried to replace a stored secret it could not read. Nothing was written. */
6425
+ var SecretOverwriteRefusedError = class extends Error {
6426
+ ref;
6427
+ reason;
6428
+ constructor(ref, reason) {
6429
+ 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.`);
6430
+ this.ref = ref;
6431
+ this.reason = reason;
6432
+ this.name = "SecretOverwriteRefusedError";
6433
+ }
6434
+ };
6435
+ function isRecord$3(value) {
6436
+ return typeof value === "object" && value !== null && !Array.isArray(value);
6437
+ }
6438
+ function resolvedValue(pass, marker) {
6439
+ const answer = pass.answers[marker.$secret];
6440
+ return answer?.kind === "value" ? answer.value : null;
6441
+ }
6442
+ async function atMarker(pass, incoming, stored) {
6443
+ if (incoming === null) return stored;
6444
+ if (typeof incoming !== "string") return incoming;
6445
+ if (incoming === resolvedValue(pass, stored)) return stored;
6446
+ const intent = classifySecretWrite(incoming);
6447
+ if (intent.kind !== "set") return stored;
6448
+ const ref = stored.$secret;
6449
+ if (!isSecretRefOwnedBy(ref, pass.secrets.owner)) return incoming;
6450
+ const answer = pass.answers[ref];
6451
+ 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);
6452
+ try {
6453
+ await pass.secrets.put(ref, intent.value);
6454
+ } catch (err) {
6455
+ throw new KeychainWriteRefusedError(ref, err);
6456
+ }
6457
+ pass.changedRefs.push(ref);
6458
+ return stored;
6459
+ }
6460
+ function inArray(pass, incoming, stored) {
6461
+ return incoming.map((item, index) => {
6462
+ const twin = stored[index];
6463
+ if (isSecretMarker(twin)) return typeof item === "string" && item === resolvedValue(pass, twin) ? twin : item;
6464
+ if (isRecord$3(item) && isRecord$3(twin)) return inArrayRow(pass, item, twin);
6465
+ if (Array.isArray(item) && Array.isArray(twin)) return inArray(pass, item, twin);
6466
+ return item;
6467
+ });
6468
+ }
6469
+ function inArrayRow(pass, incoming, stored) {
6470
+ const out = { ...incoming };
6471
+ for (const [key, value] of Object.entries(incoming)) {
6472
+ const twin = stored[key];
6473
+ if (isSecretMarker(twin)) {
6474
+ if (typeof value === "string" && value === resolvedValue(pass, twin)) out[key] = twin;
6475
+ } else if (isRecord$3(value) && isRecord$3(twin)) out[key] = inArrayRow(pass, value, twin);
6476
+ else if (Array.isArray(value) && Array.isArray(twin)) out[key] = inArray(pass, value, twin);
6477
+ }
6478
+ return out;
6479
+ }
6480
+ async function walk(pass, incoming, stored) {
6481
+ if (isSecretMarker(stored)) return atMarker(pass, incoming, stored);
6482
+ if (Array.isArray(incoming) && Array.isArray(stored)) return inArray(pass, incoming, stored);
6483
+ if (!isRecord$3(incoming) || !isRecord$3(stored)) return incoming;
6484
+ const out = { ...incoming };
6485
+ for (const [key, value] of Object.entries(incoming)) out[key] = await walk(pass, value, stored[key]);
6486
+ return out;
6487
+ }
6488
+ /** Restore markers a write-back carries as values. See the file doc. */
6489
+ async function restoreUnchangedSecrets(input) {
6490
+ const refs = [];
6491
+ for (const key of Object.keys(input.patch)) collectSecretMarkerRefs(input.stored[key], refs);
6492
+ const owned = refs.filter((ref) => isSecretRefOwnedBy(ref, input.secrets.owner));
6493
+ if (owned.length === 0) return {
6494
+ patch: input.patch,
6495
+ changedRefs: []
6496
+ };
6497
+ const pass = {
6498
+ secrets: input.secrets,
6499
+ answers: await input.secrets.resolve([...new Set(owned)]),
6500
+ operatorWrite: input.operatorWrite,
6501
+ changedRefs: []
6502
+ };
6503
+ const out = {};
6504
+ for (const [key, value] of Object.entries(input.patch)) out[key] = await walk(pass, value, input.stored[key]);
6505
+ return {
6506
+ patch: out,
6507
+ changedRefs: pass.changedRefs
6508
+ };
6509
+ }
6510
+ /** Structural equality over JSON-shaped values (key order does not matter). */
6511
+ function isJsonEqual(a, b) {
6512
+ if (Object.is(a, b)) return true;
6513
+ if (Array.isArray(a)) return Array.isArray(b) && a.length === b.length && a.every((v, i) => isJsonEqual(v, b[i]));
6514
+ if (isRecord$3(a) && isRecord$3(b)) {
6515
+ const keys = Object.keys(a);
6516
+ if (keys.length !== Object.keys(b).length) return false;
6517
+ return keys.every((k) => Object.prototype.hasOwnProperty.call(b, k) && isJsonEqual(a[k], b[k]));
6334
6518
  }
6335
6519
  return false;
6336
6520
  }
6521
+ /** The patch without the keys whose value already equals the stored one. */
6522
+ function dropUnchangedKeys(patch, stored) {
6523
+ const out = {};
6524
+ for (const [key, value] of Object.entries(patch)) {
6525
+ if (Object.prototype.hasOwnProperty.call(stored, key) && isJsonEqual(value, stored[key])) continue;
6526
+ out[key] = value;
6527
+ }
6528
+ return out;
6529
+ }
6530
+ /** The top-level keys of a blob that hold at least one of `owner`'s markers. */
6531
+ function markerKeysOf(blob, owner) {
6532
+ const keys = /* @__PURE__ */ new Set();
6533
+ for (const [key, value] of Object.entries(blob)) if (collectSecretMarkerRefs(value).some((ref) => isSecretRefOwnedBy(ref, owner))) keys.add(key);
6534
+ return keys;
6535
+ }
6536
+ function nodeFromStored(value, owner) {
6537
+ if (isSecretMarker(value)) return isSecretRefOwnedBy(value.$secret, owner) ? { kind: "leaf" } : null;
6538
+ if (!isRecord$3(value)) return null;
6539
+ const children = /* @__PURE__ */ new Map();
6540
+ for (const [key, child] of Object.entries(value)) {
6541
+ const node = nodeFromStored(child, owner);
6542
+ if (node !== null) children.set(key, node);
6543
+ }
6544
+ return children.size > 0 ? {
6545
+ kind: "object",
6546
+ children
6547
+ } : null;
6548
+ }
6549
+ /**
6550
+ * The declared secret tree, widened by every place the STORED blob holds a
6551
+ * marker under one of `keys` — so a marker the schema no longer declares (or
6552
+ * never declared: Wyze before b4906cec6) still gets the save path's
6553
+ * KEEP / SET / CLEAR semantics instead of being overwritten by whatever the
6554
+ * addon writes. Markers inside arrays are not added: a row has no id field to
6555
+ * match by unless the schema declares one. Only `owner`'s markers count: a
6556
+ * builtin that keeps another addon's marker (device-manager) never takes it
6557
+ * over.
6558
+ */
6559
+ function widenTreeWithStoredMarkers(declared, stored, keys, owner) {
6560
+ const added = /* @__PURE__ */ new Map();
6561
+ for (const key of keys) {
6562
+ const at = key.indexOf("@");
6563
+ const base = at > 0 ? key.slice(0, at) : key;
6564
+ if (declared.has(base) || added.has(base)) continue;
6565
+ const node = nodeFromStored(stored[key], owner);
6566
+ if (node !== null) added.set(base, node);
6567
+ }
6568
+ return added.size === 0 ? declared : new Map([...declared, ...added]);
6569
+ }
6337
6570
  /** The blob as stored now; a failed read REFUSES the write instead of guessing. */
6338
6571
  async function readStoredAddonBlob(raw) {
6339
6572
  const threeWay = raw.readAddonStoreResult;
@@ -6342,7 +6575,41 @@ async function readStoredAddonBlob(raw) {
6342
6575
  if (result.kind === "failed") throw new Error(`settings write refused: the stored blob could not be read (${result.error})`);
6343
6576
  return result.kind === "missing" ? {} : result.value;
6344
6577
  }
6345
- function createSecretAwareSettings(raw, opts) {
6578
+ function touchesTree(tree, patch) {
6579
+ if (tree.size === 0) return false;
6580
+ for (const key of Object.keys(patch)) {
6581
+ const at = key.indexOf("@");
6582
+ if (tree.has(at > 0 ? key.slice(0, at) : key)) return true;
6583
+ }
6584
+ return false;
6585
+ }
6586
+ /**
6587
+ * Which top-level keys of each store held markers when last seen. `undefined`
6588
+ * for a store not seen yet: its first write reads it, to be safe.
6589
+ */
6590
+ var MarkerKeyIndex = class {
6591
+ owner;
6592
+ byStore = /* @__PURE__ */ new Map();
6593
+ constructor(owner) {
6594
+ this.owner = owner;
6595
+ }
6596
+ seen(store, blob) {
6597
+ this.byStore.set(store, markerKeysOf(blob, this.owner));
6598
+ }
6599
+ wrote(store, patch) {
6600
+ const keys = this.byStore.get(store);
6601
+ if (keys === void 0) return;
6602
+ const now = markerKeysOf(patch, this.owner);
6603
+ for (const key of Object.keys(patch)) if (now.has(key)) keys.add(key);
6604
+ else keys.delete(key);
6605
+ }
6606
+ mayHoldMarkers(store, patch) {
6607
+ const keys = this.byStore.get(store);
6608
+ if (keys === void 0) return true;
6609
+ return Object.keys(patch).some((key) => keys.has(key));
6610
+ }
6611
+ };
6612
+ function createHandle(raw, opts) {
6346
6613
  const chains = /* @__PURE__ */ new Map();
6347
6614
  const serialize = (key, fn) => {
6348
6615
  const next = (chains.get(key) ?? Promise.resolve()).then(fn, fn);
@@ -6353,46 +6620,130 @@ function createSecretAwareSettings(raw, opts) {
6353
6620
  });
6354
6621
  return next;
6355
6622
  };
6356
- const write = async (chainKey, tree, scope, patch, readStored, rawWrite) => {
6357
- if (!touchesTree(tree, patch)) return rawWrite(patch);
6358
- return serialize(chainKey, async () => {
6623
+ const index = new MarkerKeyIndex(opts.secrets.owner);
6624
+ const resolveRead = async (store, blob) => {
6625
+ index.seen(store, blob);
6626
+ const { value, unresolved } = await resolveSecretMarkers(blob, opts.secrets, {
6627
+ unresolved: "keep-marker",
6628
+ ownedBy: opts.secrets.owner
6629
+ });
6630
+ if (unresolved.length > 0) opts.onUnresolved?.(unresolved);
6631
+ return value;
6632
+ };
6633
+ const write = async (store, declared, scope, patch, readStored, rawWrite) => {
6634
+ if (!touchesTree(declared, patch) && !index.mayHoldMarkers(store, patch)) {
6635
+ await rawWrite(patch);
6636
+ index.wrote(store, patch);
6637
+ return { changed: true };
6638
+ }
6639
+ return serialize(store, async () => {
6359
6640
  const stored = await readStored();
6641
+ index.seen(store, stored);
6642
+ const operatorWrite = opts.isOperatorWrite?.() === true;
6643
+ const restored = await restoreUnchangedSecrets({
6644
+ patch,
6645
+ stored,
6646
+ secrets: opts.secrets,
6647
+ operatorWrite
6648
+ });
6360
6649
  const result = await transformSecretWrite({
6361
- tree,
6650
+ tree: widenTreeWithStoredMarkers(declared, stored, Object.keys(restored.patch), opts.secrets.owner),
6362
6651
  secrets: opts.secrets,
6363
- patch,
6652
+ patch: restored.patch,
6364
6653
  stored,
6365
6654
  ...scope !== void 0 ? { scope } : {},
6366
- operatorWrite: opts.isOperatorWrite?.() === true
6655
+ operatorWrite
6367
6656
  });
6368
- if (Object.keys(result.patch).length > 0) await rawWrite(result.patch);
6657
+ const effective = dropUnchangedKeys(result.patch, stored);
6658
+ const wroteBlob = Object.keys(effective).length > 0;
6659
+ if (wroteBlob) {
6660
+ await rawWrite(effective);
6661
+ index.wrote(store, effective);
6662
+ }
6369
6663
  const { orphaned } = await result.afterWrite();
6370
6664
  if (orphaned.length > 0) opts.onOrphaned(orphaned);
6371
- });
6665
+ return { changed: wroteBlob || restored.changedRefs.length > 0 };
6666
+ });
6667
+ };
6668
+ const writeAddon = (patch) => write("addon", opts.addonTree(), void 0, patch, () => readStoredAddonBlob(raw), (p) => raw.writeAddonStore(p));
6669
+ const readAddonStoreResult = raw.readAddonStoreResult;
6670
+ const readAddonStoreKeyResult = raw.readAddonStoreKeyResult;
6671
+ const readDeviceStoreBatch = raw.readDeviceStoreBatch;
6672
+ const overrides = {
6673
+ readAddonStore: async () => resolveRead("addon", await raw.readAddonStore()),
6674
+ ...readAddonStoreResult !== void 0 ? { readAddonStoreResult: async () => {
6675
+ const result = await readAddonStoreResult.call(raw);
6676
+ return result.kind === "value" ? {
6677
+ kind: "value",
6678
+ value: await resolveRead("addon", result.value)
6679
+ } : result;
6680
+ } } : {},
6681
+ ...readAddonStoreKeyResult !== void 0 ? { readAddonStoreKeyResult: async (key) => {
6682
+ const result = await readAddonStoreKeyResult.call(raw, key);
6683
+ if (result.kind !== "present") return result;
6684
+ const { value, unresolved } = await resolveSecretMarkers({ [key]: result.value }, opts.secrets, {
6685
+ unresolved: "keep-marker",
6686
+ ownedBy: opts.secrets.owner
6687
+ });
6688
+ if (unresolved.length > 0) opts.onUnresolved?.(unresolved);
6689
+ return {
6690
+ kind: "present",
6691
+ value: value[key]
6692
+ };
6693
+ } } : {},
6694
+ readDeviceStore: async (deviceId) => resolveRead(`device:${deviceId}`, await raw.readDeviceStore(deviceId)),
6695
+ ...readDeviceStoreBatch !== void 0 ? { readDeviceStoreBatch: async (deviceIds) => {
6696
+ const rows = await readDeviceStoreBatch.call(raw, deviceIds);
6697
+ const out = /* @__PURE__ */ new Map();
6698
+ for (const [deviceId, blob] of rows) out.set(deviceId, await resolveRead(`device:${deviceId}`, blob));
6699
+ return out;
6700
+ } } : {},
6701
+ writeAddonStore: async (patch) => {
6702
+ await writeAddon(patch);
6703
+ },
6704
+ writeDeviceStore: async (deviceId, patch) => {
6705
+ await write(`device:${deviceId}`, opts.deviceTree(), {
6706
+ kind: "device",
6707
+ deviceId
6708
+ }, patch, () => raw.readDeviceStore(deviceId), (p) => raw.writeDeviceStore(deviceId, p));
6709
+ }
6710
+ };
6711
+ return {
6712
+ settings: new Proxy(raw, { get(target, prop, receiver) {
6713
+ if (typeof prop === "string" && Object.prototype.hasOwnProperty.call(overrides, prop)) return Reflect.get(overrides, prop);
6714
+ const value = Reflect.get(target, prop, receiver);
6715
+ return typeof value === "function" ? value.bind(target) : value;
6716
+ } }),
6717
+ raw: {
6718
+ readAddonStore: async () => {
6719
+ const blob = await raw.readAddonStore();
6720
+ index.seen("addon", blob);
6721
+ return blob;
6722
+ },
6723
+ readDeviceStore: async (deviceId) => {
6724
+ const blob = await raw.readDeviceStore(deviceId);
6725
+ index.seen(`device:${deviceId}`, blob);
6726
+ return blob;
6727
+ }
6728
+ },
6729
+ writeAddonStore: writeAddon
6372
6730
  };
6373
- const wrapped = {
6374
- writeAddonStore: (patch) => write("addon", opts.addonTree(), void 0, patch, () => readStoredAddonBlob(raw), (p) => raw.writeAddonStore(p)),
6375
- writeDeviceStore: (deviceId, patch) => write(`device:${deviceId}`, opts.deviceTree(), {
6376
- kind: "device",
6377
- deviceId
6378
- }, patch, () => raw.readDeviceStore(deviceId), (p) => raw.writeDeviceStore(deviceId, p))
6379
- };
6380
- return new Proxy(raw, { get(target, prop, receiver) {
6381
- if (prop === "writeAddonStore") return wrapped.writeAddonStore;
6382
- if (prop === "writeDeviceStore") return wrapped.writeDeviceStore;
6383
- const value = Reflect.get(target, prop, receiver);
6384
- return typeof value === "function" ? value.bind(target) : value;
6385
- } });
6386
6731
  }
6387
- /** The context the addon sees: identical, except that its settings writes are secret-aware. */
6388
- function withSecretAwareSettings(context, opts) {
6732
+ /** The context the addon sees, plus the private raw view and write outcome. */
6733
+ function createSecretAwareContext(context, opts) {
6389
6734
  const raw = context.settings;
6390
- if (raw === void 0) return context;
6391
- const settings = createSecretAwareSettings(raw, opts);
6392
- return new Proxy(context, { get(target, prop, receiver) {
6393
- if (prop === "settings") return settings;
6394
- return Reflect.get(target, prop, receiver);
6395
- } });
6735
+ if (raw === void 0) return {
6736
+ context,
6737
+ handle: null
6738
+ };
6739
+ const handle = createHandle(raw, opts);
6740
+ return {
6741
+ context: new Proxy(context, { get(target, prop, receiver) {
6742
+ if (prop === "settings") return handle.settings;
6743
+ return Reflect.get(target, prop, receiver);
6744
+ } }),
6745
+ handle
6746
+ };
6396
6747
  }
6397
6748
  var LEAF = { kind: "leaf" };
6398
6749
  var DEFAULT_ITEM_ID_KEY = "id";
@@ -6567,6 +6918,14 @@ var BaseAddon = class {
6567
6918
  _secretChangeUnsub = null;
6568
6919
  /** >0 while an OPERATOR's settings write is being applied. */
6569
6920
  _operatorWriteDepth = 0;
6921
+ /**
6922
+ * The keychain-aware settings handle (D798). Its `raw` view is the ONLY way
6923
+ * to the marker-bearing blobs and stays private to this class: the form
6924
+ * hydrate and config resolution need markers, addon code never does.
6925
+ */
6926
+ _secretSettings = null;
6927
+ /** Refs an addon-facing read could not resolve — each is logged once per process. */
6928
+ _loggedUnresolvedReads = /* @__PURE__ */ new Set();
6570
6929
  constructor(defaults) {
6571
6930
  this.defaults = defaults;
6572
6931
  this._config = { ...defaults };
@@ -6603,13 +6962,21 @@ var BaseAddon = class {
6603
6962
  }
6604
6963
  async initialize(context) {
6605
6964
  const secrets = context.secrets;
6606
- this._ctx = secrets !== void 0 ? withSecretAwareSettings(context, {
6607
- secrets,
6608
- addonTree: () => this.addonSecretTree(),
6609
- deviceTree: () => this.deviceSecretTree(),
6610
- onOrphaned: (refs) => context.logger.warn("keychain refs dropped by a settings write could not be deleted", { meta: { refs: [...refs] } }),
6611
- isOperatorWrite: () => this._operatorWriteDepth > 0
6612
- }) : context;
6965
+ if (secrets !== void 0) {
6966
+ const { context: wrapped, handle } = createSecretAwareContext(context, {
6967
+ secrets,
6968
+ addonTree: () => this.addonSecretTree(),
6969
+ deviceTree: () => this.deviceSecretTree(),
6970
+ onOrphaned: (refs) => context.logger.warn("keychain refs dropped by a settings write could not be deleted", { meta: { refs: [...refs] } }),
6971
+ isOperatorWrite: () => this._operatorWriteDepth > 0,
6972
+ onUnresolved: (unresolved) => this.logUnresolvedRead(unresolved)
6973
+ });
6974
+ this._ctx = wrapped;
6975
+ this._secretSettings = handle;
6976
+ } else {
6977
+ this._ctx = context;
6978
+ this._secretSettings = null;
6979
+ }
6613
6980
  await this.resolveConfig();
6614
6981
  if (secrets !== void 0) this._secretChangeUnsub = secrets.onChange((ref) => {
6615
6982
  if (this._configSecretRefs.has(ref)) this.scheduleSecretReresolve(SECRET_CHANGE_DEBOUNCE_MS);
@@ -6726,11 +7093,8 @@ var BaseAddon = class {
6726
7093
  async getGlobalSettings(overlay, cap, nodeId) {
6727
7094
  const schema = this.globalSettingsSchema(cap);
6728
7095
  if (!schema) return { sections: [] };
6729
- const projected = await this.resolveGlobalStore(nodeId, cap);
6730
- return hydrateSchema(schema, overlay ? {
6731
- ...projected,
6732
- ...overlay
6733
- } : projected, { inlineSecretsAsViews: true });
7096
+ const projected = await this.readRawProjectedStore(nodeId, cap);
7097
+ return hydrateSchema(schema, overlay ? await this.overlayKeepingMarkers(projected, overlay) : projected, { inlineSecretsAsViews: true });
6734
7098
  }
6735
7099
  /**
6736
7100
  * The integration-level view of this addon's settings: exactly the sections
@@ -6775,7 +7139,7 @@ var BaseAddon = class {
6775
7139
  });
6776
7140
  }
6777
7141
  if (sections.length === 0) return null;
6778
- const projected = await this.resolveGlobalStore(nodeId);
7142
+ const projected = await this.readRawProjectedStore(nodeId);
6779
7143
  return hydrateSchema({
6780
7144
  ...schema,
6781
7145
  sections
@@ -6792,12 +7156,50 @@ var BaseAddon = class {
6792
7156
  * the store for custom option logic (option narrowing, value snapping) to
6793
7157
  * read it per-node — never `ctx.settings.readAddonStore()` directly.
6794
7158
  * `nodeId` omitted ⇒ the local node (node-blind injection from ctx).
7159
+ *
7160
+ * Keychain values come back RESOLVED (D798): a secret reads as its value,
7161
+ * never as a `{ $secret }` marker. One the keychain cannot serve right now
7162
+ * stays a marker — "stored, unavailable" (`isSecretMarker()` is true, and it
7163
+ * is listed in {@link unresolvedSecrets}) — never `''` and never absent, so
7164
+ * it cannot be mistaken for "nothing stored, mint a new one". Writing the
7165
+ * resolved blob back is a no-op for every unchanged secret.
6795
7166
  */
6796
7167
  async resolveGlobalStore(nodeId, cap) {
6797
7168
  const raw = await this._ctx?.settings?.readAddonStore() ?? {};
7169
+ return this.projectForNode(raw, nodeId, cap);
7170
+ }
7171
+ projectForNode(store, nodeId, cap) {
6798
7172
  const keys = this.perNodeKeys(cap);
6799
7173
  const node = normalizeNodeId(nodeId ?? this._ctx?.kernel?.localNodeId);
6800
- return keys.size > 0 ? projectStore(raw, keys, node) : raw;
7174
+ return keys.size > 0 ? projectStore(store, keys, node) : store;
7175
+ }
7176
+ /** The PROJECTED store with its markers — the form hydrate only (D798). */
7177
+ async readRawProjectedStore(nodeId, cap) {
7178
+ const raw = await this.rawSettings()?.readAddonStore() ?? {};
7179
+ return this.projectForNode(raw, nodeId, cap);
7180
+ }
7181
+ /**
7182
+ * `{ ...stored, ...overlay }`, except that an overlay member equal to the
7183
+ * RESOLVED stored one keeps the stored (marker-bearing) member — so a form
7184
+ * hydrated from a resolved overlay still shows a secret as "set", never as
7185
+ * its value.
7186
+ */
7187
+ async overlayKeepingMarkers(stored, overlay) {
7188
+ const secrets = this._ctx?.secrets;
7189
+ const merged = {
7190
+ ...stored,
7191
+ ...overlay
7192
+ };
7193
+ if (secrets === void 0 || collectSecretMarkerRefs(stored).length === 0) return merged;
7194
+ const { value: resolved } = await resolveSecretMarkers(stored, secrets, {
7195
+ unresolved: "keep-marker",
7196
+ ownedBy: secrets.owner
7197
+ });
7198
+ for (const key of Object.keys(overlay)) {
7199
+ if (collectSecretMarkerRefs(stored[key]).length === 0) continue;
7200
+ if (isJsonEqual(overlay[key], resolved[key])) merged[key] = stored[key];
7201
+ }
7202
+ return merged;
6801
7203
  }
6802
7204
  /**
6803
7205
  * Whether ONE global key of this addon's store was written, read three-way
@@ -6862,8 +7264,12 @@ var BaseAddon = class {
6862
7264
  async clearSecrets(keys, nodeId) {
6863
7265
  const tree = this.addonSecretTree();
6864
7266
  const keychain = this._ctx?.secrets !== void 0;
7267
+ const stored = keychain ? await this.readAddonStoreWithRetry() : {};
6865
7268
  const patch = {};
6866
- for (const key of keys) patch[key] = keychain && tree.has(key) ? SECRET_CLEAR : "";
7269
+ for (const key of keys) {
7270
+ const keychainStored = tree.has(key) || collectSecretMarkerRefs(stored[key]).length > 0;
7271
+ patch[key] = keychain && keychainStored ? SECRET_CLEAR : "";
7272
+ }
6867
7273
  await this.applyGlobalPatch(patch, nodeId);
6868
7274
  }
6869
7275
  async applyGlobalPatch(barePatch, nodeId) {
@@ -6871,7 +7277,11 @@ var BaseAddon = class {
6871
7277
  const localNode = normalizeNodeId(this._ctx?.kernel?.localNodeId);
6872
7278
  const target = normalizeNodeId(nodeId ?? this._ctx?.kernel?.localNodeId);
6873
7279
  const scoped = keys.size > 0 ? scopePatch(barePatch, keys, target) : barePatch;
6874
- await this._ctx?.settings?.writeAddonStore(scoped);
7280
+ const handle = this._secretSettings;
7281
+ if (handle !== null) {
7282
+ const { changed } = await handle.writeAddonStore(scoped);
7283
+ if (!changed) return;
7284
+ } else await this._ctx?.settings?.writeAddonStore(scoped);
6875
7285
  if (target !== localNode) return;
6876
7286
  await this.resolveConfig();
6877
7287
  await this.onConfigChanged();
@@ -6924,7 +7334,7 @@ var BaseAddon = class {
6924
7334
  async getDeviceSettings(deviceId) {
6925
7335
  const schema = this.deviceSettingsSchema();
6926
7336
  if (!schema) return { sections: [] };
6927
- return hydrateSchema(schema, await this._ctx?.settings?.readDeviceStore(deviceId) ?? {}, { inlineSecretsAsViews: true });
7337
+ return hydrateSchema(schema, await this.rawSettings()?.readDeviceStore(deviceId) ?? {}, { inlineSecretsAsViews: true });
6928
7338
  }
6929
7339
  async updateDeviceSettings(deviceId, patch) {
6930
7340
  await this._ctx?.settings?.writeDeviceStore(deviceId, patch);
@@ -7096,7 +7506,7 @@ var BaseAddon = class {
7096
7506
  key,
7097
7507
  schema,
7098
7508
  fallback,
7099
- read: async () => this.resolveStoredSecrets(await this._ctx?.settings?.readDeviceStore(deviceId) ?? {}, false),
7509
+ read: async () => this.resolveStoredSecrets(await this.rawSettings()?.readDeviceStore(deviceId) ?? {}, false),
7100
7510
  write: async (patch) => {
7101
7511
  await this._ctx?.settings?.writeDeviceStore(deviceId, patch);
7102
7512
  },
@@ -7158,6 +7568,23 @@ var BaseAddon = class {
7158
7568
  }
7159
7569
  return value;
7160
7570
  }
7571
+ /**
7572
+ * The marker-bearing settings reads (D798) — private on purpose. Without a
7573
+ * keychain the context's own view is already raw.
7574
+ */
7575
+ rawSettings() {
7576
+ return this._secretSettings?.raw ?? this._ctx?.settings;
7577
+ }
7578
+ /** An addon-facing read met markers it could not resolve: say so once per ref. */
7579
+ logUnresolvedRead(unresolved) {
7580
+ const fresh = unresolved.filter((u) => !this._loggedUnresolvedReads.has(u.ref));
7581
+ if (fresh.length === 0) return;
7582
+ for (const u of fresh) this._loggedUnresolvedReads.add(u.ref);
7583
+ 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) => ({
7584
+ ref: u.ref,
7585
+ reason: u.reason
7586
+ })) } });
7587
+ }
7161
7588
  /** Re-resolve the config (a keychain-only change, or a retry) and apply it. */
7162
7589
  scheduleSecretReresolve(delayMs) {
7163
7590
  const timerOf = delayMs === SECRET_CHANGE_DEBOUNCE_MS ? "_secretChangeTimer" : "_secretRetryTimer";
@@ -7184,7 +7611,7 @@ var BaseAddon = class {
7184
7611
  * `{}` (defaults) — the addon's first successful patch will rehydrate.
7185
7612
  */
7186
7613
  async readAddonStoreWithRetry() {
7187
- const settings = this._ctx?.settings;
7614
+ const settings = this.rawSettings();
7188
7615
  if (!settings) return {};
7189
7616
  const delaysMs = [
7190
7617
  150,
@@ -9555,6 +9982,278 @@ var CameraSwitchGroupSchema = object({
9555
9982
  fetchedAt: number()
9556
9983
  });
9557
9984
  /**
9985
+ * The trainer contract — what the hub hands the cloud trainer and what it
9986
+ * gets back (cloud training, D805+).
9987
+ *
9988
+ * The trainer (`hf/camstack-trainer`, published as the Hugging Face repo
9989
+ * `camstack/camstack-trainer`) is a separate AGPL program the hub never
9990
+ * imports: `job.json` goes in, files come out, and progress is `CAMSTACK_EVENT`
9991
+ * lines on stdout. These schemas are the hub's half of that boundary; the
9992
+ * trainer's pydantic models (and the JSON Schemas generated from them under
9993
+ * `hf/camstack-trainer/schemas/`) are the other half. A change here is a
9994
+ * change there, in the same piece of work.
9995
+ *
9996
+ * No `.default()` anywhere: defaults do not run on the addon cap path, so the
9997
+ * orchestrator fills every field of a job spec explicitly.
9998
+ */
9999
+ var TRAINING_JOB_SCHEMA = "camstack.training/v1";
10000
+ var TRAINING_RESULT_SCHEMA = "camstack.training-result/v1";
10001
+ /** What the trainer can export. Edge TPU is a later, separate image. */
10002
+ var TrainingExportSchema = _enum([
10003
+ "onnx",
10004
+ "openvino-fp16",
10005
+ "openvino-int8",
10006
+ "coreml-fp16"
10007
+ ]);
10008
+ var FloorsSchema = record(string(), number().min(0).max(1));
10009
+ object({
10010
+ schema: literal(TRAINING_JOB_SCHEMA),
10011
+ jobKey: string().uuid(),
10012
+ target: object({
10013
+ kind: literal("detector"),
10014
+ step: literal("object-detection")
10015
+ }),
10016
+ base: object({
10017
+ modelId: string().min(1),
10018
+ /** Ultralytics weights id, e.g. `yolov9m.pt`. */
10019
+ weights: string().min(1),
10020
+ imgsz: number().int().positive()
10021
+ }),
10022
+ baseline: object({
10023
+ modelId: string().min(1),
10024
+ /** The baseline ONNX the holdout comparison runs; public mirror URL. */
10025
+ onnxUrl: string().url(),
10026
+ imgsz: number().int().positive(),
10027
+ floors: FloorsSchema
10028
+ }),
10029
+ dataset: object({
10030
+ versionId: string().min(1),
10031
+ annotationHash: string(),
10032
+ /** sha256 of the uploaded archive; the trainer refuses a mismatch (exit 65). */
10033
+ sha256: string().regex(/^[0-9a-f]{64}$/)
10034
+ }),
10035
+ split: object({
10036
+ holdoutCameras: array(number().int()),
10037
+ /** When no camera is held out: the last N days of every camera. */
10038
+ holdoutLastDays: number().int().nonnegative(),
10039
+ valFraction: number().min(0).max(.5),
10040
+ seed: number().int()
10041
+ }),
10042
+ hyper: object({
10043
+ epochs: number().int().positive(),
10044
+ batch: number().int().positive(),
10045
+ lr0: number().positive(),
10046
+ /** Layers frozen from the start of the backbone; 0 = none. */
10047
+ freeze: number().int().nonnegative(),
10048
+ patience: number().int().nonnegative(),
10049
+ seed: number().int()
10050
+ }),
10051
+ replay: object({
10052
+ source: literal("coco2017"),
10053
+ count: number().int().nonnegative()
10054
+ }),
10055
+ exports: array(TrainingExportSchema).min(1),
10056
+ calibration: object({ maxFrames: number().int().positive() }),
10057
+ floors: object({
10058
+ minSupport: number().int().positive(),
10059
+ clamp: number().min(0).max(1)
10060
+ }),
10061
+ int8Gate: object({ maxMap50Drop: number().min(0).max(1) }),
10062
+ catalog: object({
10063
+ id: string().regex(/^[a-z0-9][a-z0-9-]{2,80}$/),
10064
+ name: string().min(1).max(160)
10065
+ })
10066
+ });
10067
+ /** One regular file of the bundle. An mlpackage contributes one row per member. */
10068
+ var TrainingResultFileSchema = object({
10069
+ path: string().min(1),
10070
+ bytes: number().int().nonnegative(),
10071
+ sha256: string().regex(/^[0-9a-f]{64}$/),
10072
+ format: _enum([
10073
+ "onnx",
10074
+ "openvino",
10075
+ "coreml",
10076
+ "pt"
10077
+ ]),
10078
+ variant: _enum(["base", "int8"])
10079
+ });
10080
+ var DraftFormatSchema = object({
10081
+ /** RELATIVE path inside the bundle; the hub rewrites it to `camstack-local://`. */
10082
+ url: string().min(1),
10083
+ sizeMB: number().nonnegative(),
10084
+ isDirectory: boolean().optional(),
10085
+ files: array(string()).optional(),
10086
+ runtimes: array(literal("python")).optional(),
10087
+ revision: string().min(1)
10088
+ });
10089
+ /** The trainer's half of a catalog entry; the hub completes it (labels, licence, group). */
10090
+ var TrainingCatalogDraftSchema = object({
10091
+ id: string().min(1),
10092
+ name: string().min(1),
10093
+ description: string(),
10094
+ labels: array(unknown()),
10095
+ inputSize: object({
10096
+ width: number().int().positive(),
10097
+ height: number().int().positive()
10098
+ }),
10099
+ preprocessMode: literal("letterbox"),
10100
+ defaultClassFloors: FloorsSchema,
10101
+ formats: object({
10102
+ onnx: DraftFormatSchema.optional(),
10103
+ openvino: DraftFormatSchema.optional(),
10104
+ coreml: DraftFormatSchema.optional()
10105
+ })
10106
+ });
10107
+ /** One class of one model's holdout report (the eval harness's summary). */
10108
+ var TrainingEvalClassSchema = object({
10109
+ positives: number().int(),
10110
+ floor: number().nullable(),
10111
+ tp: number().int(),
10112
+ fp: number().int(),
10113
+ fn: number().int(),
10114
+ precision: number().nullable(),
10115
+ recall: number().nullable(),
10116
+ ap50: number().nullable(),
10117
+ recallByCamera: record(string(), number().nullable()).optional(),
10118
+ recallByLight: record(string(), number().nullable()).optional(),
10119
+ fpByCamera: record(string(), number()).optional(),
10120
+ smallFound: number().int().optional(),
10121
+ smallTotal: number().int().optional()
10122
+ }).passthrough();
10123
+ var TrainingEvalReportSchema = object({
10124
+ frames: number().int(),
10125
+ classes: record(string(), TrainingEvalClassSchema)
10126
+ }).passthrough();
10127
+ /**
10128
+ * A succeeded result carries every block; a failed one carries the error and
10129
+ * whatever was known by then — the other blocks are ABSENT, not null. The
10130
+ * orchestrator checks the blocks it needs before it trusts a success.
10131
+ */
10132
+ var TrainingResultSchema = object({
10133
+ schema: literal(TRAINING_RESULT_SCHEMA),
10134
+ jobKey: string(),
10135
+ status: _enum(["succeeded", "failed"]),
10136
+ error: object({
10137
+ stage: string(),
10138
+ code: string(),
10139
+ message: string()
10140
+ }).nullable(),
10141
+ trainer: object({
10142
+ version: string(),
10143
+ revision: string()
10144
+ }),
10145
+ toolchain: record(string(), string().nullable()),
10146
+ dataset: object({
10147
+ versionId: string(),
10148
+ annotationHash: string(),
10149
+ sha256: string(),
10150
+ frames: object({
10151
+ train: number().int(),
10152
+ val: number().int(),
10153
+ holdout: number().int()
10154
+ }),
10155
+ holdoutCameras: array(number().int()),
10156
+ replayImages: number().int()
10157
+ }).optional(),
10158
+ training: object({
10159
+ epochsRun: number().int(),
10160
+ bestEpoch: number().int(),
10161
+ bestMap50: number(),
10162
+ bestMap50_95: number(),
10163
+ seconds: number()
10164
+ }).optional(),
10165
+ evaluation: object({
10166
+ holdoutFrames: number().int(),
10167
+ baseline: TrainingEvalReportSchema.nullable(),
10168
+ candidate: TrainingEvalReportSchema.nullable(),
10169
+ candidateInt8: TrainingEvalReportSchema.nullable(),
10170
+ recallDeltaByCamera: record(string(), record(string(), number())).nullable(),
10171
+ map50: record(string(), number().nullable())
10172
+ }).optional(),
10173
+ floors: object({
10174
+ baseline: FloorsSchema,
10175
+ candidate: FloorsSchema,
10176
+ candidateInt8: FloorsSchema.nullable(),
10177
+ notes: array(string())
10178
+ }).optional(),
10179
+ int8: object({
10180
+ kept: boolean(),
10181
+ map50Fp16: number().nullable(),
10182
+ map50Int8: number().nullable(),
10183
+ reason: string().nullable()
10184
+ }).optional(),
10185
+ exportsDropped: array(object({
10186
+ export: string(),
10187
+ reason: string()
10188
+ })).optional(),
10189
+ files: array(TrainingResultFileSchema).optional(),
10190
+ bundle: object({
10191
+ path: literal("bundle.tar"),
10192
+ bytes: number().int().nonnegative(),
10193
+ sha256: string().regex(/^[0-9a-f]{64}$/)
10194
+ }).nullable().optional(),
10195
+ catalogDraft: object({
10196
+ base: TrainingCatalogDraftSchema,
10197
+ int8: TrainingCatalogDraftSchema.nullable()
10198
+ }).nullable().optional(),
10199
+ licence: string()
10200
+ });
10201
+ var TrainingStageSchema = _enum([
10202
+ "prepare",
10203
+ "replay",
10204
+ "train",
10205
+ "eval",
10206
+ "export",
10207
+ "package"
10208
+ ]);
10209
+ var EventBase = {
10210
+ v: literal(1),
10211
+ ts: number()
10212
+ };
10213
+ discriminatedUnion("type", [
10214
+ object({
10215
+ ...EventBase,
10216
+ type: literal("stage"),
10217
+ stage: TrainingStageSchema
10218
+ }),
10219
+ object({
10220
+ ...EventBase,
10221
+ type: literal("epoch"),
10222
+ epoch: number().int(),
10223
+ epochs: number().int(),
10224
+ boxLoss: number().nullable().optional(),
10225
+ map50: number().nullable().optional(),
10226
+ map50_95: number().nullable().optional(),
10227
+ etaSec: number().nullable().optional()
10228
+ }),
10229
+ object({
10230
+ ...EventBase,
10231
+ type: literal("metric"),
10232
+ name: string(),
10233
+ value: number()
10234
+ }),
10235
+ object({
10236
+ ...EventBase,
10237
+ type: literal("artifact"),
10238
+ path: string(),
10239
+ bytes: number(),
10240
+ sha256: string()
10241
+ }),
10242
+ object({
10243
+ ...EventBase,
10244
+ type: literal("done"),
10245
+ status: _enum(["succeeded", "failed"]),
10246
+ resultSha256: string().nullable().optional()
10247
+ }),
10248
+ object({
10249
+ ...EventBase,
10250
+ type: literal("error"),
10251
+ stage: string(),
10252
+ code: string(),
10253
+ message: string()
10254
+ })
10255
+ ]);
10256
+ /**
9558
10257
  * What the gate decided about a birth, from the CALLER's point of view.
9559
10258
  *
9560
10259
  * Deliberately not `ConfirmationVerdict`: `undecided` is not a birth decision
@@ -12414,7 +13113,9 @@ var AddonHttpRouteSchema = object({
12414
13113
  "authenticated",
12415
13114
  "admin"
12416
13115
  ]).optional(),
12417
- description: string().optional()
13116
+ description: string().optional(),
13117
+ /** The hub limits this route per client address before the handler runs. */
13118
+ rateLimit: _enum(["auth"]).optional()
12418
13119
  });
12419
13120
  /**
12420
13121
  * Cross-process route invocation envelope. The hub captures the
@@ -13119,6 +13820,37 @@ var BackupDestinationInfoSchema = object({
13119
13820
  lastError: string().optional()
13120
13821
  });
13121
13822
  /**
13823
+ * How an archive is encrypted (operator decision 2026-10-09): to a backup
13824
+ * PUBLIC key the hub holds, so only the operator's secret key opens it.
13825
+ * Absent on a plain `.tar.gz` — every archive made before encryption, or
13826
+ * with it off — which restores without a key.
13827
+ */
13828
+ var BackupArchiveEncryptionSchema = object({
13829
+ /** `x25519-hkdf-aes256gcm-stream-v1`. */
13830
+ scheme: string(),
13831
+ /** 16 hex — the backup key whose secret restores this archive. */
13832
+ keyId: string()
13833
+ });
13834
+ /**
13835
+ * The backup encryption setting. The hub keeps PUBLIC keys only: the active
13836
+ * one new archives are encrypted to, and the retired ones older archives
13837
+ * still need. The secret key is shown once, at `setupEncryption`.
13838
+ */
13839
+ var BackupEncryptionStatusSchema = object({
13840
+ enabled: boolean(),
13841
+ active: object({
13842
+ keyId: string(),
13843
+ publicKey: string(),
13844
+ createdAt: number()
13845
+ }).nullable(),
13846
+ /** Every key ever set up, newest first. */
13847
+ keys: array(object({
13848
+ keyId: string(),
13849
+ createdAt: number(),
13850
+ retiredAt: number().nullable()
13851
+ })).readonly()
13852
+ });
13853
+ /**
13122
13854
  * Per-archive entry returned by `backup.listArchives({ destinationId })`.
13123
13855
  * Same shape the destination drill-in renders. Sourced from the per-
13124
13856
  * location `manifests.json` (no per-archive tarball read required).
@@ -13130,7 +13862,9 @@ var BackupArchiveEntrySchema = object({
13130
13862
  sizeBytes: number(),
13131
13863
  label: string().optional(),
13132
13864
  /** Top-level locations included in the archive (db, addons, tls, …). */
13133
- locations: array(string()).readonly()
13865
+ locations: array(string()).readonly(),
13866
+ /** Present when the archive is encrypted; restore then needs that key. */
13867
+ encryption: BackupArchiveEncryptionSchema.optional()
13134
13868
  });
13135
13869
  var BackupEntrySchema = object({
13136
13870
  id: string(),
@@ -13139,7 +13873,8 @@ var BackupEntrySchema = object({
13139
13873
  label: string().optional(),
13140
13874
  createdAt: number(),
13141
13875
  sizeBytes: number(),
13142
- locations: array(string()).optional()
13876
+ locations: array(string()).optional(),
13877
+ encryption: BackupArchiveEncryptionSchema.optional()
13143
13878
  });
13144
13879
  var ArchiveEntrySchema = object({
13145
13880
  path: string(),
@@ -13328,10 +14063,40 @@ method(_void(), array(BackupDestinationInfoSchema).readonly(), { auth: "admin" }
13328
14063
  * this list and skips entries whose path doesn't start with
13329
14064
  * any of them.
13330
14065
  */
13331
- locations: array(string()).optional()
14066
+ locations: array(string()).optional(),
14067
+ /**
14068
+ * The backup SECRET key, for an encrypted archive (ignored for a plain
14069
+ * one). The archive is decrypted into the hub's private staging
14070
+ * before the restart; the key is not stored. A wrong or missing key
14071
+ * is refused before the archive is downloaded.
14072
+ */
14073
+ backupSecretKey: string().optional()
13332
14074
  }), _void(), {
13333
14075
  kind: "mutation",
13334
14076
  auth: "admin"
14077
+ }), method(_void(), BackupEncryptionStatusSchema, { auth: "admin" }), method(object({}), object({
14078
+ keyId: string(),
14079
+ secretKey: string(),
14080
+ publicKey: string(),
14081
+ createdAt: number(),
14082
+ replacedKeyId: string().nullable()
14083
+ }), {
14084
+ kind: "mutation",
14085
+ auth: "admin"
14086
+ }), method(object({}), object({ disabledKeyId: string().nullable() }), {
14087
+ kind: "mutation",
14088
+ auth: "admin"
14089
+ }), method(object({ backupSecretKey: string() }), object({
14090
+ valid: boolean(),
14091
+ keyId: string().nullable(),
14092
+ /** The hub knows this key (active or retired). */
14093
+ known: boolean(),
14094
+ /** It is the key new archives are encrypted to. */
14095
+ active: boolean(),
14096
+ error: string().optional()
14097
+ }), {
14098
+ kind: "mutation",
14099
+ auth: "admin"
13335
14100
  }), method(object({
13336
14101
  destinationId: string(),
13337
14102
  backupId: string()
@@ -15057,7 +15822,60 @@ var CustomModelDescriptorSchema = object({
15057
15822
  stepId: string(),
15058
15823
  entry: ModelCatalogEntrySchema
15059
15824
  });
15060
- method(_void(), array(CustomModelDescriptorSchema).readonly(), { auth: "admin" });
15825
+ /** One regular file of an imported bundle, as the producer measured it. */
15826
+ var ModelBundleFileSchema = object({
15827
+ /** Relative path inside the bundle tar; an mlpackage member is `<x>.mlpackage/<member>`. */
15828
+ path: string().min(1),
15829
+ bytes: number().int().nonnegative(),
15830
+ sha256: string().regex(/^[0-9a-f]{64}$/)
15831
+ });
15832
+ var ImportModelBundleInputSchema = object({
15833
+ /** The registry provider that keeps the model (Model Studio). */
15834
+ addonId: string(),
15835
+ stepId: string().min(1),
15836
+ /**
15837
+ * The catalog rows to register, complete, every format URL already
15838
+ * `camstack-local://<modelId>/<file>` naming a file of the bundle. One
15839
+ * bundle may carry several rows (a base and its INT8 variant).
15840
+ */
15841
+ entries: array(ModelCatalogEntrySchema).min(1).max(4),
15842
+ /** The bundle tar, offered by the producer over `ctx.peerBytes` (same host). */
15843
+ bundle: object({
15844
+ ticket: PeerBytesTicketSchema,
15845
+ bytes: number().int().positive(),
15846
+ sha256: string().regex(/^[0-9a-f]{64}$/)
15847
+ }),
15848
+ /** Every file the tar must hold; anything missing, extra or different is refused. */
15849
+ files: array(ModelBundleFileSchema).min(1).max(64),
15850
+ /** Convert missing engine formats and push the model to every agent afterwards. */
15851
+ distribute: boolean()
15852
+ });
15853
+ var ImportModelBundleResultSchema = discriminatedUnion("kind", [object({
15854
+ kind: literal("imported"),
15855
+ modelIds: array(string()).readonly(),
15856
+ distributed: array(object({
15857
+ modelId: string(),
15858
+ nodeId: string(),
15859
+ format: _enum(MODEL_FORMATS),
15860
+ ok: boolean(),
15861
+ error: string().optional()
15862
+ })).readonly()
15863
+ }), object({
15864
+ kind: literal("refused"),
15865
+ reason: _enum([
15866
+ "transfer-failed",
15867
+ "checksum-mismatch",
15868
+ "bundle-mismatch",
15869
+ "invalid-entry",
15870
+ "id-taken"
15871
+ ]),
15872
+ detail: string()
15873
+ })]);
15874
+ method(_void(), array(CustomModelDescriptorSchema).readonly(), { auth: "admin" }), method(ImportModelBundleInputSchema, ImportModelBundleResultSchema, {
15875
+ kind: "mutation",
15876
+ auth: "admin",
15877
+ timeoutMs: 30 * 6e4
15878
+ });
15061
15879
  /**
15062
15880
  * Query filter for settings-store collections.
15063
15881
  */
@@ -15536,6 +16354,35 @@ var KeychainKeySourceSchema = object({
15536
16354
  */
15537
16355
  sharesBackupWithDatabase: boolean()
15538
16356
  });
16357
+ /**
16358
+ * One keychain reset, as the Secrets page reports it until the operator
16359
+ * acknowledges it. Never a value: refs, counts and table names only.
16360
+ */
16361
+ var KeychainResetRecordSchema = object({
16362
+ id: string(),
16363
+ at: number(),
16364
+ /** `user:<id>` or {@link KEYCHAIN_RESET_TRIGGER_ACTOR}. */
16365
+ actor: string(),
16366
+ /** Why the keychain was locked when it was reset; `null` when it was not locked. */
16367
+ lockedReason: string().nullable(),
16368
+ /** Values moved into the archive table (ciphertext under the lost key). */
16369
+ archived: number().int(),
16370
+ /** `keychain:secrets-orphaned-<ts>`, or `null` when nothing was stored. */
16371
+ archivedCollection: string().nullable(),
16372
+ /**
16373
+ * `keychain:keys-orphaned-<ts>`: the wrapped data keys of the archive, kept
16374
+ * so the archive can still be opened if the lost master key turns up.
16375
+ */
16376
+ archivedKeysCollection: string().nullable(),
16377
+ /**
16378
+ * `system-settings` keys whose marker the reset cleared — the cluster
16379
+ * secret's: a marker left pointing at an archived value would refuse every
16380
+ * agent forever (D797).
16381
+ */
16382
+ clearedSettingsKeys: array(string()).readonly(),
16383
+ /** When an operator dismissed the notice on the Secrets page; `null` until then. */
16384
+ acknowledgedAt: number().nullable()
16385
+ });
15539
16386
  var KeychainStatusSchema = object({
15540
16387
  keychain: KeychainStateSchema,
15541
16388
  /** The source of the master key in use; `null` while locked. */
@@ -15553,7 +16400,9 @@ var KeychainStatusSchema = object({
15553
16400
  /** Wrapped copies of the data key under a previous master key, kept until purged. */
15554
16401
  retiredWraps: number().int(),
15555
16402
  recoveryKeyDownloadedAt: number().nullable(),
15556
- secretCount: number().int()
16403
+ secretCount: number().int(),
16404
+ /** The most recent reset, acknowledged or not; `null` when the keychain was never reset. */
16405
+ lastReset: KeychainResetRecordSchema.nullable()
15557
16406
  });
15558
16407
  /**
15559
16408
  * Whether a stored value is still pointed at by its owner's settings.
@@ -15575,17 +16424,26 @@ var KeychainAuditActionSchema = _enum([
15575
16424
  "download-recovery-key",
15576
16425
  "delete-orphans",
15577
16426
  "reset",
16427
+ "acknowledge-reset",
15578
16428
  "initialize"
15579
16429
  ]);
15580
16430
  var KeychainAuditEntrySchema = object({
15581
16431
  id: string(),
15582
16432
  at: number(),
15583
16433
  action: KeychainAuditActionSchema,
15584
- /** `addon:<id>` | `user:<id>` | `system`. */
16434
+ /** `addon:<id>` | `user:<id>` | `system` | `trigger-file`. */
15585
16435
  actor: string(),
15586
16436
  ref: string().nullable(),
15587
16437
  detail: string().nullable()
15588
16438
  });
16439
+ var KEYCHAIN_RESET_CONFIRMATION = "RESET KEYCHAIN";
16440
+ /**
16441
+ * Secrets the HUB itself holds (owner `system`) that no settings form shows:
16442
+ * `jwt-signing-key` — the session signing key (D797). It is always "in use",
16443
+ * never an orphan; it is generated on a fresh hub and replaced only through
16444
+ * {@link keychainAdminCapability.methods.setSystemSecret}.
16445
+ */
16446
+ var SystemHeldSecretNameSchema = _enum(["jwt-signing-key"]);
15589
16447
  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({
15590
16448
  value: string(),
15591
16449
  version: number().int()
@@ -15593,6 +16451,16 @@ method(object({}), KeychainStatusSchema, { auth: "admin" }), method(object({}),
15593
16451
  kind: "mutation",
15594
16452
  auth: "admin",
15595
16453
  caller: "required"
16454
+ }), method(object({
16455
+ name: SystemHeldSecretNameSchema,
16456
+ value: string().min(16)
16457
+ }), object({
16458
+ ref: string(),
16459
+ version: number().int()
16460
+ }), {
16461
+ kind: "mutation",
16462
+ auth: "admin",
16463
+ caller: "required"
15596
16464
  }), method(object({ refs: array(string().min(1)).max(1e3) }), object({
15597
16465
  deleted: array(string()).readonly(),
15598
16466
  kept: array(object({
@@ -15622,13 +16490,20 @@ method(object({}), KeychainStatusSchema, { auth: "admin" }), method(object({}),
15622
16490
  kind: "mutation",
15623
16491
  auth: "admin",
15624
16492
  caller: "required"
15625
- }), method(object({ confirm: literal("RESET KEYCHAIN") }), object({
16493
+ }), method(object({ confirm: literal(KEYCHAIN_RESET_CONFIRMATION) }), object({
15626
16494
  archivedCollection: string().nullable(),
15627
16495
  archived: number().int()
15628
16496
  }), {
15629
16497
  kind: "mutation",
15630
16498
  auth: "admin",
15631
16499
  caller: "required"
16500
+ }), method(object({}), object({
16501
+ reset: KeychainResetRecordSchema.nullable(),
16502
+ pendingReentry: array(KeychainSecretMetaSchema).readonly()
16503
+ }), { auth: "admin" }), method(object({}), object({ acknowledged: boolean() }), {
16504
+ kind: "mutation",
16505
+ auth: "admin",
16506
+ caller: "required"
15632
16507
  });
15633
16508
  method(_void(), object({
15634
16509
  id: string(),
@@ -18615,7 +19490,7 @@ method(LogEntrySchema, _void(), { kind: "mutation" }), method(object({
18615
19490
  * `login-method` — collection cap through which auth addons contribute
18616
19491
  * their pre-auth login surfaces to the login page. This is the SINGLE,
18617
19492
  * generic mechanism that supersedes the dead `auth.listProviders` reader:
18618
- * every auth addon (OIDC, magic-link, WebAuthn/passkey) registers a
19493
+ * every auth addon (OIDC, WebAuthn/passkey) registers a
18619
19494
  * `login-method` provider and the PUBLIC `auth.listLoginMethods`
18620
19495
  * procedure aggregates them for the unauthenticated login page.
18621
19496
  *
@@ -18623,8 +19498,7 @@ method(LogEntrySchema, _void(), { kind: "mutation" }), method(object({
18623
19498
  *
18624
19499
  * - `redirect` — a declarative button. The login page renders a generic
18625
19500
  * button that navigates to `startUrl` (an addon-owned HTTP route).
18626
- * Covers OIDC (`/addon/auth-oidc/<id>/start`) and magic-link with
18627
- * ZERO shell-side JS. A future SSO addon plugs in the same way — the
19501
+ * Covers OIDC (`/addon/auth-oidc/<id>/start`) with ZERO shell-side JS. A future SSO addon plugs in the same way — the
18628
19502
  * login page needs NO change.
18629
19503
  *
18630
19504
  * - `widget` — a Module-Federation widget the login page mounts (via
@@ -18643,8 +19517,8 @@ method(LogEntrySchema, _void(), { kind: "mutation" }), method(object({
18643
19517
  * decision.
18644
19518
  *
18645
19519
  * Every contribution carries a `stage`:
18646
- * - `primary` — shown on the first credentials screen (OIDC /
18647
- * magic-link buttons; a future usernameless passkey).
19520
+ * - `primary` — shown on the first credentials screen (OIDC
19521
+ * buttons; a usernameless passkey).
18648
19522
  * - `second-factor` — shown AFTER the password leg, gated on the
18649
19523
  * returned `factors` (passkey-as-2FA today).
18650
19524
  *
@@ -18671,7 +19545,7 @@ var LoginMethodContributionSchema = discriminatedUnion("kind", [
18671
19545
  * The provider names an external identity a signed-in user can link to
18672
19546
  * their own account (D782): `auth.listLinkableProviders` /
18673
19547
  * `beginExternalLink` offer exactly the redirect methods that set this,
18674
- * whatever their id. Absent / false — a login button only (magic-link).
19548
+ * whatever their id. Absent / false — a login button only.
18675
19549
  */
18676
19550
  linkable: boolean().optional()
18677
19551
  }),
@@ -22526,8 +23400,7 @@ method(object({}), object({ rules: array(NcRuleSchema) }), { auth: "admin" }), m
22526
23400
  * `super_admin` — collapsed onto the single boolean because every
22527
23401
  * non-admin caller is governed by the same scope-check rules; the
22528
23402
  * distinction was only ever used to route role-specific procedures
22529
- * which we no longer have. Agents are admin sessions issued via
22530
- * `createServiceToken`; CLI / webhook integrations are `cst_*` tokens
23403
+ * which we no longer have. CLI / webhook integrations are `cst_*` tokens
22531
23404
  * with `isAdmin: false` + an explicit scope list.
22532
23405
  */
22533
23406
  /** Per-method access flavour. Materialised on every cap method via codegen. */
@@ -24202,6 +25075,9 @@ var RetrainExportFilterSchema = object({
24202
25075
  frameIds: array(string()).max(2e4).optional(),
24203
25076
  /** Only frames in at least one of these named collections. */
24204
25077
  collectionIds: array(string()).max(200).optional(),
25078
+ /** Exactly the frames of this dataset version (and its completeOnly). An
25079
+ * unknown id selects nothing. */
25080
+ datasetVersionId: string().optional(),
24205
25081
  batchId: string().optional(),
24206
25082
  /** Only frames the operator marked complete (all subjects boxed). */
24207
25083
  completeOnly: boolean().optional()
@@ -24369,6 +25245,67 @@ var RetrainLlmAssistResultSchema = discriminatedUnion("kind", [object({
24369
25245
  ]),
24370
25246
  detail: string().optional()
24371
25247
  })]);
25248
+ /** What a dataset version is cut from. Every field narrows. */
25249
+ var RetrainDatasetSelectionSchema = object({
25250
+ deviceIds: array(number()).readonly().optional(),
25251
+ collectionIds: array(string()).max(200).readonly().optional(),
25252
+ frameIds: array(string()).max(2e4).readonly().optional()
25253
+ });
25254
+ /** The counts a dataset is judged by. */
25255
+ var RetrainDatasetStatsSchema = object({
25256
+ frames: number().int(),
25257
+ completeFrames: number().int(),
25258
+ /** `completeFrames / frames`, 0..1. */
25259
+ completeness: number(),
25260
+ /** Boxes to learn (model errors excluded). */
25261
+ subjects: number().int(),
25262
+ modelErrors: number().int(),
25263
+ /** Complete frames with no subject. */
25264
+ hardNegatives: number().int(),
25265
+ /** Subjects per class × camera × day/night. */
25266
+ cells: array(object({
25267
+ macroClass: string(),
25268
+ deviceId: number(),
25269
+ lighting: _enum([
25270
+ "day",
25271
+ "night",
25272
+ "unknown"
25273
+ ]),
25274
+ subjects: number().int(),
25275
+ frames: number().int()
25276
+ })).readonly(),
25277
+ cameras: array(object({
25278
+ deviceId: number(),
25279
+ frames: number().int(),
25280
+ completeFrames: number().int()
25281
+ })).readonly()
25282
+ });
25283
+ /** An immutable dataset version, without its frame list. */
25284
+ var RetrainDatasetVersionSchema = object({
25285
+ id: string(),
25286
+ name: string(),
25287
+ createdAt: number(),
25288
+ selection: RetrainDatasetSelectionSchema,
25289
+ layout: RetrainExportLayoutSchema,
25290
+ completeOnly: boolean(),
25291
+ frameCount: number().int(),
25292
+ /** sha256 of what the frames taught when the version was frozen. */
25293
+ annotationHash: string(),
25294
+ /** The export manifest schema the version was cut under. */
25295
+ manifestSchema: string(),
25296
+ stats: RetrainDatasetStatsSchema
25297
+ });
25298
+ var CreateRetrainDatasetVersionResultSchema = discriminatedUnion("kind", [object({
25299
+ kind: literal("created"),
25300
+ version: RetrainDatasetVersionSchema
25301
+ }), object({
25302
+ kind: literal("refused"),
25303
+ reason: _enum([
25304
+ "empty-name",
25305
+ "duplicate-name",
25306
+ "no-frames"
25307
+ ])
25308
+ })]);
24372
25309
  /** The outcome of a lifecycle move owned by the retrain page. */
24373
25310
  var RetrainTransitionResultSchema = object({
24374
25311
  trackId: string(),
@@ -25158,6 +26095,47 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
25158
26095
  kind: "mutation",
25159
26096
  auth: "admin",
25160
26097
  timeoutMs: 60 * 6e4
26098
+ }), method(object({
26099
+ filter: RetrainExportFilterSchema,
26100
+ layout: RetrainExportLayoutSchema
26101
+ }), object({
26102
+ ticket: PeerBytesTicketSchema,
26103
+ frames: number().int(),
26104
+ annotations: number().int()
26105
+ }), {
26106
+ kind: "mutation",
26107
+ auth: "admin",
26108
+ timeoutMs: 12e4
26109
+ }), method(object({
26110
+ selection: RetrainDatasetSelectionSchema,
26111
+ completeOnly: boolean().optional()
26112
+ }), RetrainDatasetStatsSchema, {
26113
+ kind: "query",
26114
+ auth: "admin"
26115
+ }), method(object({
26116
+ name: string().max(120),
26117
+ selection: RetrainDatasetSelectionSchema,
26118
+ layout: RetrainExportLayoutSchema,
26119
+ completeOnly: boolean()
26120
+ }), CreateRetrainDatasetVersionResultSchema, {
26121
+ kind: "mutation",
26122
+ auth: "admin",
26123
+ timeoutMs: 12e4
26124
+ }), method(object({}), array(RetrainDatasetVersionSchema).readonly(), {
26125
+ kind: "query",
26126
+ auth: "admin"
26127
+ }), method(object({ id: string() }), object({ deleted: boolean() }), {
26128
+ kind: "mutation",
26129
+ auth: "admin"
26130
+ }), method(object({ id: string() }), object({
26131
+ found: boolean(),
26132
+ annotationHash: string(),
26133
+ matches: boolean(),
26134
+ missingFrames: number().int()
26135
+ }), {
26136
+ kind: "query",
26137
+ auth: "admin",
26138
+ timeoutMs: 12e4
25161
26139
  }), method(object({}), array(RetrainAssistProfileSchema).readonly(), {
25162
26140
  kind: "query",
25163
26141
  auth: "admin"
@@ -28736,8 +29714,8 @@ version: string().optional() }), ServerUpdateActionResultSchema, {
28736
29714
  * `smtp-provider` — pluggable email delivery surface.
28737
29715
  *
28738
29716
  * Collection cap: a deployment may install multiple SMTP relays (e.g.
28739
- * one for transactional / one for notifications). Consumers (magic-link,
28740
- * notifier addons, …) walk the collection and pick the first
29717
+ * one for transactional / one for notifications). Consumers (notifier
29718
+ * addons, …) walk the collection and pick the first
28741
29719
  * ready provider OR target a specific addonId.
28742
29720
  *
28743
29721
  * The shape stays small on purpose — `sendEmail` is enough for the
@@ -29020,7 +29998,7 @@ targets: array(object({
29020
29998
  };
29021
29999
  /**
29022
30000
  * `sso-bridge` — internal hub-only cap that lets SSO-style auth
29023
- * providers (OIDC, SAML, magic-link, …) mint an HMAC-signed token
30001
+ * providers (OIDC, SAML, …) mint an HMAC-signed token
29024
30002
  * carrying the post-callback claims before redirecting back to
29025
30003
  * `/api/auth/sso/finish`.
29026
30004
  *
@@ -29083,7 +30061,14 @@ var SsoBridgeClaimsSchema = object({
29083
30061
  * Verified `iss` of the id_token behind an OIDC login bridge (D782). A
29084
30062
  * subject is unique only per issuer, so a link is bound to it.
29085
30063
  */
29086
- issuer: string().optional()
30064
+ issuer: string().optional(),
30065
+ /**
30066
+ * SHA-256 (hex) of the `camstack_sso_state` cookie the IdP `/start` set in
30067
+ * the browser that began this sign-in. `/api/auth/sso/finish` requires the
30068
+ * request to present the matching cookie — a login bridge is useless in
30069
+ * any other browser.
30070
+ */
30071
+ browserBinding: string().optional()
29087
30072
  });
29088
30073
  method(object({
29089
30074
  claims: SsoBridgeClaimsSchema,
@@ -42330,16 +43315,6 @@ var ApiKeySummarySchema = object({
42330
43315
  createdAt: number(),
42331
43316
  lastUsedAt: number().optional()
42332
43317
  });
42333
- var CreateApiKeyInputSchema = object({
42334
- label: string(),
42335
- isAdmin: boolean().default(false),
42336
- allowedProviders: union([array(string()), literal("*")]).optional(),
42337
- allowedDevices: record(string(), union([array(string()), literal("*")])).optional()
42338
- });
42339
- var CreateApiKeyResultSchema = object({
42340
- token: string(),
42341
- record: ApiKeySummarySchema
42342
- });
42343
43318
  var ScopedTokenSummarySchema = object({
42344
43319
  id: string(),
42345
43320
  userId: string(),
@@ -42438,17 +43413,10 @@ method(_void(), array(UserSummarySchema), { auth: "admin" }), method(CreateUserI
42438
43413
  }), UserSummarySchema.extend({ passwordHash: string() }).nullable(), {
42439
43414
  kind: "mutation",
42440
43415
  access: "view"
42441
- }), method(_void(), array(ApiKeySummarySchema), { auth: "admin" }), method(CreateApiKeyInputSchema, CreateApiKeyResultSchema, {
42442
- kind: "mutation",
42443
- auth: "admin",
42444
- access: "create"
42445
- }), method(object({ id: string() }), object({ success: literal(true) }), {
43416
+ }), method(_void(), array(ApiKeySummarySchema), { auth: "admin" }), method(object({ id: string() }), object({ success: literal(true) }), {
42446
43417
  kind: "mutation",
42447
43418
  auth: "admin",
42448
43419
  access: "delete"
42449
- }), method(object({ token: string() }), ApiKeySummarySchema.nullable(), {
42450
- kind: "mutation",
42451
- access: "view"
42452
43420
  }), method(CreateScopedTokenInputSchema, CreateScopedTokenResultSchema, {
42453
43421
  kind: "mutation",
42454
43422
  auth: "admin",
@@ -42522,15 +43490,7 @@ method(_void(), array(UserSummarySchema), { auth: "admin" }), method(CreateUserI
42522
43490
  }).nullable(), { access: "view" }), method(object({ userId: string() }), array(ExternalIdentitySchema), { auth: "admin" }), method(ExternalIdentityKeySchema, object({
42523
43491
  userId: string(),
42524
43492
  issuer: string()
42525
- }).nullable(), { auth: "admin" }), method(ExternalIdentityKeySchema.extend({
42526
- userId: string(),
42527
- issuer: string().min(1),
42528
- label: string().optional()
42529
- }), object({ success: literal(true) }), {
42530
- kind: "mutation",
42531
- auth: "admin",
42532
- access: "create"
42533
- }), method(ExternalIdentityKeySchema.extend({ userId: string() }), object({ success: boolean() }), {
43493
+ }).nullable(), { auth: "admin" }), method(ExternalIdentityKeySchema.extend({ userId: string() }), object({ success: boolean() }), {
42534
43494
  kind: "mutation",
42535
43495
  auth: "admin",
42536
43496
  access: "delete"
@@ -43235,6 +44195,451 @@ var zoneRulesCapability = {
43235
44195
  */
43236
44196
  durability: "restored"
43237
44197
  };
44198
+ /**
44199
+ * `training-provider` — ONE cloud that can run the CamStack trainer.
44200
+ *
44201
+ * A thin, mockable translation layer: it knows how to run a container with a
44202
+ * GPU, move a dataset in, read the job's stdout and hand artefacts back. It
44203
+ * knows nothing about datasets, splits, floors, cost policy or Model Studio —
44204
+ * those are the `training` orchestrator's (D805). Every rule written there
44205
+ * once is what makes a second provider (RunPod, a local NVIDIA node) a new
44206
+ * manifest entry and nothing else.
44207
+ *
44208
+ * Collection, routed by the `addonId` in every single-row input (the `llm` /
44209
+ * `notification-output` posture); `describe` concat-fans across providers.
44210
+ * Every method is `admin`: these spend money.
44211
+ *
44212
+ * Every cloud object a provider creates is tagged with the orchestrator's
44213
+ * `jobKey`, so a retried submit finds the job it already started instead of
44214
+ * starting a second GPU, and `listJobs` can find orphans.
44215
+ *
44216
+ * Bytes never ride a cap field: the dataset arrives as a `ctx.peerBytes`
44217
+ * ticket the producer (pipeline-analytics) minted, and artefacts leave as a
44218
+ * ticket the provider mints (D613).
44219
+ */
44220
+ var TrainingGpuOptionSchema = object({
44221
+ id: string(),
44222
+ label: string(),
44223
+ /** List price, USD per GPU-hour, before any region multiplier. */
44224
+ usdPerHour: number().nonnegative(),
44225
+ vramGb: number().nonnegative()
44226
+ });
44227
+ var TrainingRegionOptionSchema = object({
44228
+ /** `''` = any region (the provider's choice). */
44229
+ id: string(),
44230
+ label: string(),
44231
+ priceMultiplier: number().positive()
44232
+ });
44233
+ /**
44234
+ * The provider's per-account settings, as the orchestrator reads them. They
44235
+ * live in the PROVIDER addon's settings (operator decision 2026-10-08: they
44236
+ * depend on the user's account), never hard-coded in the orchestrator.
44237
+ */
44238
+ var TrainingProviderDefaultsSchema = object({
44239
+ gpuType: string(),
44240
+ region: string(),
44241
+ costCapUsd: number().nonnegative(),
44242
+ maxRuntimeSec: number().int().positive(),
44243
+ /** Hours a FAILED job's cloud dataset is kept for debugging; 0 = delete at once. */
44244
+ failedDatasetGraceHours: number().nonnegative()
44245
+ });
44246
+ var TrainingProviderDescriptorSchema = object({
44247
+ addonId: string(),
44248
+ /** `modal`, `runpod`, `fake`, … */
44249
+ kind: string(),
44250
+ label: string(),
44251
+ gpuTypes: array(TrainingGpuOptionSchema).readonly(),
44252
+ regions: array(TrainingRegionOptionSchema).readonly(),
44253
+ maxDatasetBytes: number().int().positive(),
44254
+ maxRuntimeSec: number().int().positive(),
44255
+ freeTierNote: string().optional(),
44256
+ /** Where the data goes, in one sentence the confirm dialog repeats. */
44257
+ dataResidencyNote: string(),
44258
+ /** Credentials are present — never the values. */
44259
+ configured: boolean(),
44260
+ defaults: TrainingProviderDefaultsSchema
44261
+ });
44262
+ var TrainingCredentialCheckSchema = object({
44263
+ ok: boolean(),
44264
+ /** Workspace / account name, when the provider says. */
44265
+ account: string().optional(),
44266
+ reason: _enum([
44267
+ "missing",
44268
+ "invalid",
44269
+ "forbidden",
44270
+ "network",
44271
+ "quota"
44272
+ ]).optional(),
44273
+ detail: string().optional()
44274
+ });
44275
+ var ProviderJobStateSchema = _enum([
44276
+ "pending",
44277
+ "starting",
44278
+ "running",
44279
+ "succeeded",
44280
+ "failed",
44281
+ "cancelled",
44282
+ "lost"
44283
+ ]);
44284
+ var ProviderJobStatusSchema = object({
44285
+ jobKey: string(),
44286
+ providerJobId: string().optional(),
44287
+ state: ProviderJobStateSchema,
44288
+ startedAt: number().optional(),
44289
+ endedAt: number().optional(),
44290
+ exitCode: number().int().optional(),
44291
+ failureReason: string().optional(),
44292
+ gpuType: string(),
44293
+ region: string().optional(),
44294
+ billedSeconds: number().nonnegative(),
44295
+ costUsd: number().nonnegative(),
44296
+ /** True when `costUsd` is runtime × list price, not a billing answer. */
44297
+ costIsEstimate: boolean(),
44298
+ lastFetchedAt: number()
44299
+ });
44300
+ /**
44301
+ * The trainer the job runs, by SOURCE revision: the provider turns it into an
44302
+ * image its own way (Modal builds the published Dockerfile at that revision;
44303
+ * a registry-pull provider maps it to a tag). Recorded on the job and echoed
44304
+ * in `result.json`.
44305
+ */
44306
+ var TrainerSourceRefSchema = object({
44307
+ /** Hugging Face repo id, e.g. `camstack/camstack-trainer`. */
44308
+ repo: string().min(1),
44309
+ /** A commit sha (never a branch) — the job must be reproducible. */
44310
+ revision: string().regex(/^[0-9a-f]{7,64}$/)
44311
+ });
44312
+ var JobRef = {
44313
+ addonId: string(),
44314
+ jobKey: string().uuid()
44315
+ };
44316
+ var TrainingLogLineSchema = object({
44317
+ ts: number(),
44318
+ text: string()
44319
+ });
44320
+ method(object({}), array(TrainingProviderDescriptorSchema).readonly(), { auth: "admin" }), method(object({ addonId: string() }), TrainingCredentialCheckSchema, {
44321
+ kind: "mutation",
44322
+ auth: "admin",
44323
+ timeoutMs: 3e4
44324
+ }), method(object({
44325
+ addonId: string(),
44326
+ gpuType: string(),
44327
+ region: string(),
44328
+ datasetBytes: number().int().nonnegative(),
44329
+ gpuSecondsLow: number().nonnegative(),
44330
+ gpuSecondsHigh: number().nonnegative()
44331
+ }), object({
44332
+ usdLow: number().nonnegative(),
44333
+ usdHigh: number().nonnegative(),
44334
+ notes: array(string()).readonly()
44335
+ }), { auth: "admin" }), method(object({
44336
+ ...JobRef,
44337
+ ticket: PeerBytesTicketSchema
44338
+ }), object({
44339
+ bytes: number().int().nonnegative(),
44340
+ sha256: string()
44341
+ }), {
44342
+ kind: "mutation",
44343
+ auth: "admin",
44344
+ timeoutMs: 120 * 6e4
44345
+ }), method(object({
44346
+ ...JobRef,
44347
+ trainer: TrainerSourceRefSchema,
44348
+ jobSpecJson: string().min(2).max(64e3),
44349
+ gpuType: string(),
44350
+ region: string(),
44351
+ maxRuntimeSec: number().int().positive()
44352
+ }), ProviderJobStatusSchema, {
44353
+ kind: "mutation",
44354
+ auth: "admin",
44355
+ timeoutMs: 30 * 6e4
44356
+ }), method(object(JobRef), ProviderJobStatusSchema, {
44357
+ auth: "admin",
44358
+ timeoutMs: 6e4
44359
+ }), method(object({
44360
+ ...JobRef,
44361
+ cursor: string().optional(),
44362
+ max: number().int().min(1).max(500)
44363
+ }), object({
44364
+ lines: array(TrainingLogLineSchema).readonly(),
44365
+ cursor: string()
44366
+ }), {
44367
+ auth: "admin",
44368
+ timeoutMs: 6e4
44369
+ }), method(object(JobRef), object({ ok: literal(true) }), {
44370
+ kind: "mutation",
44371
+ auth: "admin",
44372
+ timeoutMs: 6e4
44373
+ }), method(object(JobRef), object({
44374
+ found: boolean(),
44375
+ text: string().optional()
44376
+ }), {
44377
+ kind: "mutation",
44378
+ auth: "admin",
44379
+ timeoutMs: 5 * 6e4
44380
+ }), method(object({
44381
+ ...JobRef,
44382
+ path: _enum(["bundle.tar"])
44383
+ }), object({ ticket: PeerBytesTicketSchema }), {
44384
+ kind: "mutation",
44385
+ auth: "admin",
44386
+ timeoutMs: 5 * 6e4
44387
+ }), method(object(JobRef), object({ deleted: array(string()).readonly() }), {
44388
+ kind: "mutation",
44389
+ auth: "admin",
44390
+ timeoutMs: 5 * 6e4
44391
+ }), method(object({ addonId: string() }), array(ProviderJobStatusSchema).readonly(), {
44392
+ auth: "admin",
44393
+ timeoutMs: 2 * 6e4
44394
+ });
44395
+ /**
44396
+ * `training` — the cloud-training orchestrator (D805). Hub-only singleton,
44397
+ * provided by `addon-training`.
44398
+ *
44399
+ * It owns what every provider must agree on, written once:
44400
+ *
44401
+ * - **Dataset versions.** Taken over from pipeline-analytics (D796): the rows
44402
+ * live here (D808); pipeline-analytics still CUTS a version (it owns the corpus and
44403
+ * the export plan) and reaches this store through the five row methods
44404
+ * below, so the Retrain page and the export did not change.
44405
+ * - **Jobs.** A persisted state machine, a reconcile loop against the
44406
+ * provider, a cost guard, a daily orphan sweep and the retention rules.
44407
+ * - **The return flow.** Verified artefacts → Model Studio
44408
+ * (`custom-model-registry.importModelBundle`) → canary on cameras →
44409
+ * rollback. Nothing is ever registered automatically.
44410
+ *
44411
+ * Every method is `admin`.
44412
+ */
44413
+ /** A version WITH its frame list — what the export and a job read. */
44414
+ var TrainingDatasetVersionRowSchema = RetrainDatasetVersionSchema.omit({ frameCount: true }).extend({ frameIds: array(string()).max(2e4).readonly() });
44415
+ /** A base model a detector job can fine-tune, and the baseline it is judged against. */
44416
+ var TrainingBaseModelSchema = object({
44417
+ modelId: string(),
44418
+ label: string(),
44419
+ weights: string(),
44420
+ imgsz: number().int(),
44421
+ baselineOnnxUrl: string(),
44422
+ baselineFloors: record(string(), number()),
44423
+ /** The base the fleet runs most — the UI's default. */
44424
+ recommended: boolean()
44425
+ });
44426
+ var TrainingPresetSchema = _enum([
44427
+ "quick",
44428
+ "standard",
44429
+ "thorough"
44430
+ ]);
44431
+ var TrainingJobRequestSchema = object({
44432
+ datasetVersionId: string().min(1),
44433
+ /** The `training-provider` addon that runs it. */
44434
+ addonId: string().min(1),
44435
+ gpuType: string().min(1),
44436
+ region: string(),
44437
+ baseModelId: string().min(1),
44438
+ preset: TrainingPresetSchema,
44439
+ /** Freeze the backbone's first N layers; `null` = the preset's choice. */
44440
+ freeze: number().int().nonnegative().nullable(),
44441
+ /** Cameras held out whole for evaluation; `null` = the orchestrator's default. */
44442
+ holdoutCameras: array(number().int()).nullable()
44443
+ });
44444
+ var TrainingSplitPlanSchema = object({
44445
+ holdoutCameras: array(number().int()).readonly(),
44446
+ /** Used when no camera is held out: the last N days of every camera. */
44447
+ holdoutLastDays: number().int().nonnegative(),
44448
+ /** Holdout subjects per class (camera holdout only; `null` = known only after the split). */
44449
+ holdoutSupport: record(string(), number().int()).nullable(),
44450
+ trainSubjects: number().int()
44451
+ });
44452
+ var TrainingRefusalReasonSchema = _enum([
44453
+ "unknown-dataset",
44454
+ "unknown-provider",
44455
+ "provider-not-configured",
44456
+ "unknown-base-model",
44457
+ "unknown-gpu",
44458
+ "dataset-too-large",
44459
+ "no-training-subjects",
44460
+ "job-already-running"
44461
+ ]);
44462
+ var TrainingJobPlanSchema = object({
44463
+ refusal: object({
44464
+ reason: TrainingRefusalReasonSchema,
44465
+ detail: string()
44466
+ }).nullable(),
44467
+ warnings: array(string()).readonly(),
44468
+ split: TrainingSplitPlanSchema.nullable(),
44469
+ estimate: object({
44470
+ datasetBytes: number().int(),
44471
+ uploadMinutesAt20Mbps: number(),
44472
+ gpuSecondsLow: number(),
44473
+ gpuSecondsHigh: number(),
44474
+ usdLow: number(),
44475
+ usdHigh: number(),
44476
+ notes: array(string()).readonly()
44477
+ }).nullable(),
44478
+ /** Pre-filled from the provider's settings; the operator may lower or raise them. */
44479
+ defaults: object({
44480
+ maxCostUsd: number(),
44481
+ maxRuntimeSec: number().int()
44482
+ }).nullable(),
44483
+ /** The sentence the confirm dialog repeats: where the frames go and when they are deleted. */
44484
+ dataNotice: string()
44485
+ });
44486
+ /**
44487
+ * Orchestrator-owned states, persisted. `uploading` covers exporting the
44488
+ * archive (it is streamed, never staged). Terminal: `failed`, `cancelled`,
44489
+ * `lost`, `expired`, `discarded`. `registered` and `canary` are where a
44490
+ * result lives after the operator acted on it.
44491
+ */
44492
+ var TrainingJobStateSchema = _enum([
44493
+ "uploading",
44494
+ "submitted",
44495
+ "starting",
44496
+ "running",
44497
+ "collecting",
44498
+ "ready",
44499
+ "registered",
44500
+ "canary",
44501
+ "failed",
44502
+ "cancelling",
44503
+ "cancelled",
44504
+ "lost",
44505
+ "expired",
44506
+ "discarded"
44507
+ ]);
44508
+ var TrainingFailureReasonSchema = _enum([
44509
+ "cost-cap",
44510
+ "runtime-cap",
44511
+ "upload-failed",
44512
+ "submit-failed",
44513
+ "trainer-failed",
44514
+ "result-invalid",
44515
+ "checksum-mismatch",
44516
+ "fetch-failed",
44517
+ "provider-error",
44518
+ "hub-restart-during-upload"
44519
+ ]);
44520
+ var TrainingProgressPointSchema = object({
44521
+ epoch: number().int(),
44522
+ map50: number().nullable(),
44523
+ map50_95: number().nullable()
44524
+ });
44525
+ var TrainingCanarySchema = object({
44526
+ deviceIds: array(number().int()).readonly(),
44527
+ since: number(),
44528
+ /** Every override the canary replaced, exactly, so rollback restores it. */
44529
+ previous: array(object({
44530
+ deviceId: number().int(),
44531
+ nodeId: string(),
44532
+ deviceKey: string(),
44533
+ patch: object({
44534
+ modelId: string().optional(),
44535
+ settings: record(string(), unknown()).readonly().optional()
44536
+ }).nullable()
44537
+ })).readonly()
44538
+ });
44539
+ var TrainingJobSchema = object({
44540
+ id: string(),
44541
+ idempotencyKey: string(),
44542
+ name: string(),
44543
+ createdAt: number(),
44544
+ updatedAt: number(),
44545
+ state: TrainingJobStateSchema,
44546
+ stage: TrainingStageSchema.nullable(),
44547
+ failure: object({
44548
+ reason: TrainingFailureReasonSchema,
44549
+ stage: string().nullable(),
44550
+ detail: string()
44551
+ }).nullable(),
44552
+ request: TrainingJobRequestSchema,
44553
+ maxCostUsd: number().nonnegative(),
44554
+ maxRuntimeSec: number().int().positive(),
44555
+ trainer: TrainerSourceRefSchema,
44556
+ datasetLayout: RetrainExportLayoutSchema,
44557
+ dataset: object({
44558
+ bytes: number().int(),
44559
+ sha256: string(),
44560
+ uploadedAt: number()
44561
+ }).nullable(),
44562
+ split: TrainingSplitPlanSchema,
44563
+ provider: object({
44564
+ state: ProviderJobStateSchema.nullable(),
44565
+ providerJobId: string().nullable(),
44566
+ startedAt: number().nullable(),
44567
+ endedAt: number().nullable(),
44568
+ billedSeconds: number(),
44569
+ costUsd: number(),
44570
+ costIsEstimate: boolean(),
44571
+ lastPolledAt: number().nullable()
44572
+ }),
44573
+ progress: object({
44574
+ epoch: number().int().nullable(),
44575
+ epochs: number().int().nullable(),
44576
+ etaSec: number().nullable(),
44577
+ series: array(TrainingProgressPointSchema).readonly()
44578
+ }),
44579
+ /** The last lines of the job's output (≤ 200), newest last. Never frame paths. */
44580
+ logTail: array(string()).readonly(),
44581
+ logCursor: string().nullable(),
44582
+ artifacts: object({
44583
+ bundleBytes: number().int(),
44584
+ bundleSha256: string(),
44585
+ fetchedAt: number(),
44586
+ /** When the staged artefacts are deleted from the hub. */
44587
+ expiresAt: number()
44588
+ }).nullable(),
44589
+ /** When the provider-side copy of the frames was deleted; null while it exists. */
44590
+ cloudDatasetDeletedAt: number().nullable(),
44591
+ /** A failed job's dataset is kept until then (the provider's grace), then deleted. */
44592
+ cloudCleanupDueAt: number().nullable(),
44593
+ /** Model ids registered from this job (base, and int8 when kept). */
44594
+ registeredModelIds: array(string()).readonly(),
44595
+ canary: TrainingCanarySchema.nullable()
44596
+ });
44597
+ var IdInput = object({ id: string().min(1) });
44598
+ method(TrainingDatasetVersionRowSchema, object({ stored: boolean() }), {
44599
+ kind: "mutation",
44600
+ auth: "admin"
44601
+ }), 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() }), {
44602
+ kind: "mutation",
44603
+ auth: "admin"
44604
+ }), method(object({}), array(TrainingBaseModelSchema).readonly(), { auth: "admin" }), method(TrainingJobRequestSchema, TrainingJobPlanSchema, {
44605
+ auth: "admin",
44606
+ timeoutMs: 6e4
44607
+ }), method(TrainingJobRequestSchema.extend({
44608
+ name: string().min(1).max(120),
44609
+ maxCostUsd: number().positive(),
44610
+ maxRuntimeSec: number().int().positive(),
44611
+ idempotencyKey: string().min(8).max(80)
44612
+ }), discriminatedUnion("kind", [object({
44613
+ kind: literal("started"),
44614
+ job: TrainingJobSchema
44615
+ }), object({
44616
+ kind: literal("refused"),
44617
+ reason: TrainingRefusalReasonSchema,
44618
+ detail: string()
44619
+ })]), {
44620
+ kind: "mutation",
44621
+ auth: "admin",
44622
+ timeoutMs: 12e4
44623
+ }), method(object({}), array(TrainingJobSchema).readonly(), { auth: "admin" }), method(IdInput, TrainingJobSchema.nullable(), { auth: "admin" }), method(IdInput, TrainingJobSchema, {
44624
+ kind: "mutation",
44625
+ auth: "admin",
44626
+ timeoutMs: 12e4
44627
+ }), method(IdInput, TrainingResultSchema.nullable(), { auth: "admin" }), method(IdInput.extend({ canaryDeviceIds: array(number().int()).readonly() }), TrainingJobSchema, {
44628
+ kind: "mutation",
44629
+ auth: "admin",
44630
+ timeoutMs: 30 * 6e4
44631
+ }), method(IdInput.extend({ deviceIds: array(number().int()).min(1).readonly() }), TrainingJobSchema, {
44632
+ kind: "mutation",
44633
+ auth: "admin",
44634
+ timeoutMs: 12e4
44635
+ }), method(IdInput, TrainingJobSchema, {
44636
+ kind: "mutation",
44637
+ auth: "admin",
44638
+ timeoutMs: 12e4
44639
+ }), method(IdInput, TrainingJobSchema, {
44640
+ kind: "mutation",
44641
+ auth: "admin"
44642
+ });
43238
44643
  SOURCE_CAPS.filter((cap) => cap !== "switch" && cap !== "motion");
43239
44644
  Object.freeze({
43240
44645
  person: .5,
@@ -45409,6 +46814,12 @@ Object.freeze({
45409
46814
  addonId: null,
45410
46815
  access: "create"
45411
46816
  },
46817
+ "backup.checkBackupKey": {
46818
+ capName: "backup",
46819
+ capScope: "system",
46820
+ addonId: null,
46821
+ access: "create"
46822
+ },
45412
46823
  "backup.delete": {
45413
46824
  capName: "backup",
45414
46825
  capScope: "system",
@@ -45421,6 +46832,18 @@ Object.freeze({
45421
46832
  addonId: null,
45422
46833
  access: "delete"
45423
46834
  },
46835
+ "backup.disableEncryption": {
46836
+ capName: "backup",
46837
+ capScope: "system",
46838
+ addonId: null,
46839
+ access: "create"
46840
+ },
46841
+ "backup.getEncryption": {
46842
+ capName: "backup",
46843
+ capScope: "system",
46844
+ addonId: null,
46845
+ access: "view"
46846
+ },
45424
46847
  "backup.getEntries": {
45425
46848
  capName: "backup",
45426
46849
  capScope: "system",
@@ -45475,6 +46898,12 @@ Object.freeze({
45475
46898
  addonId: null,
45476
46899
  access: "create"
45477
46900
  },
46901
+ "backup.setupEncryption": {
46902
+ capName: "backup",
46903
+ capScope: "system",
46904
+ addonId: null,
46905
+ access: "create"
46906
+ },
45478
46907
  "backup.trigger": {
45479
46908
  capName: "backup",
45480
46909
  capScope: "system",
@@ -46027,6 +47456,12 @@ Object.freeze({
46027
47456
  addonId: null,
46028
47457
  access: "create"
46029
47458
  },
47459
+ "customModelRegistry.importModelBundle": {
47460
+ capName: "custom-model-registry",
47461
+ capScope: "system",
47462
+ addonId: null,
47463
+ access: "create"
47464
+ },
46030
47465
  "customModelRegistry.listModels": {
46031
47466
  capName: "custom-model-registry",
46032
47467
  capScope: "system",
@@ -47467,6 +48902,12 @@ Object.freeze({
47467
48902
  addonId: null,
47468
48903
  access: "view"
47469
48904
  },
48905
+ "keychainAdmin.acknowledgeReset": {
48906
+ capName: "keychain-admin",
48907
+ capScope: "system",
48908
+ addonId: null,
48909
+ access: "create"
48910
+ },
47470
48911
  "keychainAdmin.deleteOrphans": {
47471
48912
  capName: "keychain-admin",
47472
48913
  capScope: "system",
@@ -47503,6 +48944,12 @@ Object.freeze({
47503
48944
  addonId: null,
47504
48945
  access: "delete"
47505
48946
  },
48947
+ "keychainAdmin.resetReport": {
48948
+ capName: "keychain-admin",
48949
+ capScope: "system",
48950
+ addonId: null,
48951
+ access: "delete"
48952
+ },
47506
48953
  "keychainAdmin.reveal": {
47507
48954
  capName: "keychain-admin",
47508
48955
  capScope: "system",
@@ -47515,6 +48962,12 @@ Object.freeze({
47515
48962
  addonId: null,
47516
48963
  access: "create"
47517
48964
  },
48965
+ "keychainAdmin.setSystemSecret": {
48966
+ capName: "keychain-admin",
48967
+ capScope: "system",
48968
+ addonId: null,
48969
+ access: "create"
48970
+ },
47518
48971
  "keychainAdmin.status": {
47519
48972
  capName: "keychain-admin",
47520
48973
  capScope: "system",
@@ -48961,6 +50414,12 @@ Object.freeze({
48961
50414
  addonId: null,
48962
50415
  access: "create"
48963
50416
  },
50417
+ "pipelineAnalytics.createRetrainDatasetVersion": {
50418
+ capName: "pipeline-analytics",
50419
+ capScope: "device",
50420
+ addonId: null,
50421
+ access: "create"
50422
+ },
48964
50423
  "pipelineAnalytics.deleteDeviceEvents": {
48965
50424
  capName: "pipeline-analytics",
48966
50425
  capScope: "device",
@@ -48973,6 +50432,12 @@ Object.freeze({
48973
50432
  addonId: null,
48974
50433
  access: "delete"
48975
50434
  },
50435
+ "pipelineAnalytics.deleteRetrainDatasetVersion": {
50436
+ capName: "pipeline-analytics",
50437
+ capScope: "device",
50438
+ addonId: null,
50439
+ access: "delete"
50440
+ },
48976
50441
  "pipelineAnalytics.deleteTracks": {
48977
50442
  capName: "pipeline-analytics",
48978
50443
  capScope: "device",
@@ -49195,6 +50660,12 @@ Object.freeze({
49195
50660
  addonId: null,
49196
50661
  access: "view"
49197
50662
  },
50663
+ "pipelineAnalytics.listRetrainDatasetVersions": {
50664
+ capName: "pipeline-analytics",
50665
+ capScope: "device",
50666
+ addonId: null,
50667
+ access: "view"
50668
+ },
49198
50669
  "pipelineAnalytics.listRetrainFrames": {
49199
50670
  capName: "pipeline-analytics",
49200
50671
  capScope: "device",
@@ -49225,6 +50696,12 @@ Object.freeze({
49225
50696
  addonId: null,
49226
50697
  access: "view"
49227
50698
  },
50699
+ "pipelineAnalytics.offerRetrainArchive": {
50700
+ capName: "pipeline-analytics",
50701
+ capScope: "device",
50702
+ addonId: null,
50703
+ access: "create"
50704
+ },
49228
50705
  "pipelineAnalytics.ownersWithMedia": {
49229
50706
  capName: "pipeline-analytics",
49230
50707
  capScope: "device",
@@ -49237,6 +50714,12 @@ Object.freeze({
49237
50714
  addonId: null,
49238
50715
  access: "create"
49239
50716
  },
50717
+ "pipelineAnalytics.previewRetrainDataset": {
50718
+ capName: "pipeline-analytics",
50719
+ capScope: "device",
50720
+ addonId: null,
50721
+ access: "view"
50722
+ },
49240
50723
  "pipelineAnalytics.proposeRetrainAnnotations": {
49241
50724
  capName: "pipeline-analytics",
49242
50725
  capScope: "device",
@@ -49375,6 +50858,12 @@ Object.freeze({
49375
50858
  addonId: null,
49376
50859
  access: "create"
49377
50860
  },
50861
+ "pipelineAnalytics.verifyRetrainDatasetVersion": {
50862
+ capName: "pipeline-analytics",
50863
+ capScope: "device",
50864
+ addonId: null,
50865
+ access: "view"
50866
+ },
49378
50867
  "pipelineAnalytics.wipeAllAnalytics": {
49379
50868
  capName: "pipeline-analytics",
49380
50869
  capScope: "device",
@@ -51751,6 +53240,174 @@ Object.freeze({
51751
53240
  addonId: null,
51752
53241
  access: "view"
51753
53242
  },
53243
+ "training.canaryResult": {
53244
+ capName: "training",
53245
+ capScope: "system",
53246
+ addonId: null,
53247
+ access: "create"
53248
+ },
53249
+ "training.cancelJob": {
53250
+ capName: "training",
53251
+ capScope: "system",
53252
+ addonId: null,
53253
+ access: "create"
53254
+ },
53255
+ "training.discardResult": {
53256
+ capName: "training",
53257
+ capScope: "system",
53258
+ addonId: null,
53259
+ access: "create"
53260
+ },
53261
+ "training.findDatasetVersionIdByName": {
53262
+ capName: "training",
53263
+ capScope: "system",
53264
+ addonId: null,
53265
+ access: "view"
53266
+ },
53267
+ "training.getDatasetVersion": {
53268
+ capName: "training",
53269
+ capScope: "system",
53270
+ addonId: null,
53271
+ access: "view"
53272
+ },
53273
+ "training.getJob": {
53274
+ capName: "training",
53275
+ capScope: "system",
53276
+ addonId: null,
53277
+ access: "view"
53278
+ },
53279
+ "training.getJobResult": {
53280
+ capName: "training",
53281
+ capScope: "system",
53282
+ addonId: null,
53283
+ access: "view"
53284
+ },
53285
+ "training.listBaseModels": {
53286
+ capName: "training",
53287
+ capScope: "system",
53288
+ addonId: null,
53289
+ access: "view"
53290
+ },
53291
+ "training.listDatasetVersions": {
53292
+ capName: "training",
53293
+ capScope: "system",
53294
+ addonId: null,
53295
+ access: "view"
53296
+ },
53297
+ "training.listJobs": {
53298
+ capName: "training",
53299
+ capScope: "system",
53300
+ addonId: null,
53301
+ access: "view"
53302
+ },
53303
+ "training.planJob": {
53304
+ capName: "training",
53305
+ capScope: "system",
53306
+ addonId: null,
53307
+ access: "view"
53308
+ },
53309
+ "training.putDatasetVersion": {
53310
+ capName: "training",
53311
+ capScope: "system",
53312
+ addonId: null,
53313
+ access: "create"
53314
+ },
53315
+ "training.registerResult": {
53316
+ capName: "training",
53317
+ capScope: "system",
53318
+ addonId: null,
53319
+ access: "create"
53320
+ },
53321
+ "training.removeDatasetVersion": {
53322
+ capName: "training",
53323
+ capScope: "system",
53324
+ addonId: null,
53325
+ access: "delete"
53326
+ },
53327
+ "training.rollbackCanary": {
53328
+ capName: "training",
53329
+ capScope: "system",
53330
+ addonId: null,
53331
+ access: "create"
53332
+ },
53333
+ "training.startJob": {
53334
+ capName: "training",
53335
+ capScope: "system",
53336
+ addonId: null,
53337
+ access: "create"
53338
+ },
53339
+ "trainingProvider.cancelJob": {
53340
+ capName: "training-provider",
53341
+ capScope: "system",
53342
+ addonId: null,
53343
+ access: "create"
53344
+ },
53345
+ "trainingProvider.cleanupJob": {
53346
+ capName: "training-provider",
53347
+ capScope: "system",
53348
+ addonId: null,
53349
+ access: "create"
53350
+ },
53351
+ "trainingProvider.describe": {
53352
+ capName: "training-provider",
53353
+ capScope: "system",
53354
+ addonId: null,
53355
+ access: "view"
53356
+ },
53357
+ "trainingProvider.estimateJob": {
53358
+ capName: "training-provider",
53359
+ capScope: "system",
53360
+ addonId: null,
53361
+ access: "view"
53362
+ },
53363
+ "trainingProvider.getJob": {
53364
+ capName: "training-provider",
53365
+ capScope: "system",
53366
+ addonId: null,
53367
+ access: "view"
53368
+ },
53369
+ "trainingProvider.listJobEvents": {
53370
+ capName: "training-provider",
53371
+ capScope: "system",
53372
+ addonId: null,
53373
+ access: "view"
53374
+ },
53375
+ "trainingProvider.listJobs": {
53376
+ capName: "training-provider",
53377
+ capScope: "system",
53378
+ addonId: null,
53379
+ access: "view"
53380
+ },
53381
+ "trainingProvider.offerArtifact": {
53382
+ capName: "training-provider",
53383
+ capScope: "system",
53384
+ addonId: null,
53385
+ access: "create"
53386
+ },
53387
+ "trainingProvider.readResult": {
53388
+ capName: "training-provider",
53389
+ capScope: "system",
53390
+ addonId: null,
53391
+ access: "create"
53392
+ },
53393
+ "trainingProvider.submitJob": {
53394
+ capName: "training-provider",
53395
+ capScope: "system",
53396
+ addonId: null,
53397
+ access: "create"
53398
+ },
53399
+ "trainingProvider.uploadDataset": {
53400
+ capName: "training-provider",
53401
+ capScope: "system",
53402
+ addonId: null,
53403
+ access: "create"
53404
+ },
53405
+ "trainingProvider.validateCredentials": {
53406
+ capName: "training-provider",
53407
+ capScope: "system",
53408
+ addonId: null,
53409
+ access: "create"
53410
+ },
51754
53411
  "turnProvider.getTurnServers": {
51755
53412
  capName: "turn-provider",
51756
53413
  capScope: "system",
@@ -51775,12 +53432,6 @@ Object.freeze({
51775
53432
  addonId: null,
51776
53433
  access: "create"
51777
53434
  },
51778
- "userManagement.createApiKey": {
51779
- capName: "user-management",
51780
- capScope: "system",
51781
- addonId: null,
51782
- access: "create"
51783
- },
51784
53435
  "userManagement.createScopedToken": {
51785
53436
  capName: "user-management",
51786
53437
  capScope: "system",
@@ -51817,12 +53468,6 @@ Object.freeze({
51817
53468
  addonId: null,
51818
53469
  access: "view"
51819
53470
  },
51820
- "userManagement.linkExternalIdentity": {
51821
- capName: "user-management",
51822
- capScope: "system",
51823
- addonId: null,
51824
- access: "create"
51825
- },
51826
53471
  "userManagement.listApiKeys": {
51827
53472
  capName: "user-management",
51828
53473
  capScope: "system",
@@ -51925,12 +53570,6 @@ Object.freeze({
51925
53570
  addonId: null,
51926
53571
  access: "create"
51927
53572
  },
51928
- "userManagement.validateApiKey": {
51929
- capName: "user-management",
51930
- capScope: "system",
51931
- addonId: null,
51932
- access: "view"
51933
- },
51934
53573
  "userManagement.validateCredentials": {
51935
53574
  capName: "user-management",
51936
53575
  capScope: "system",
@@ -56196,6 +57835,11 @@ Object.freeze({
56196
57835
  form: "single",
56197
57836
  optional: false
56198
57837
  }],
57838
+ "training.canaryResult": [{
57839
+ name: "deviceIds",
57840
+ form: "array",
57841
+ optional: false
57842
+ }],
56199
57843
  "update.getStatus": [{
56200
57844
  name: "deviceId",
56201
57845
  form: "single",
@@ -167229,6 +168873,22 @@ function accessoryKindsFor(sliceProbed, sliceFlags, deviceCache) {
167229
168873
  const flags = resolveAccessoryProbeFlags(sliceProbed, sliceFlags, deviceCache);
167230
168874
  return ACCESSORY_FLAGS.filter(([flag]) => flags[flag] === true).map(([, kind]) => kind);
167231
168875
  }
168876
+ /**
168877
+ * The probe flags every probe-gated decision should read (PTZ, intercom,
168878
+ * doorbell, autotrack caps, the device features, accessory children):
168879
+ * the live slice once this session has probed; otherwise the slice
168880
+ * overlaid with the flags persisted by the last successful probe. A
168881
+ * battery camera asleep at boot skips its probe, so without the overlay
168882
+ * its probe-gated caps vanish across every provider restart. With no
168883
+ * persisted probe stamp, the slice is returned unchanged.
168884
+ */
168885
+ function effectiveProbeFlags(sliceProbed, sliceFlags, deviceCache) {
168886
+ if (sliceProbed || deviceCache?.probedAt === void 0) return sliceFlags;
168887
+ return {
168888
+ ...sliceFlags,
168889
+ ...resolveAccessoryProbeFlags(false, {}, deviceCache)
168890
+ };
168891
+ }
167232
168892
  //#endregion
167233
168893
  //#region src/metadata-populator.ts
167234
168894
  var EXTENDED_INFO_TAGS = [
@@ -169180,6 +170840,19 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
169180
170840
  * underlying state. The set is small (≤6 entries) so allocation cost
169181
170841
  * is negligible vs the staleness of caching.
169182
170842
  */
170843
+ /**
170844
+ * Probe flags with the persisted fallback: until this session has probed
170845
+ * (a battery camera asleep at boot skips `onProbe`), the flags of the last
170846
+ * successful probe stored in `deviceCache` stand in for the empty
170847
+ * `feature-probe` slice. Every probe-gated read — PTZ / intercom /
170848
+ * doorbell / autotrack registration, `features`, accessory children —
170849
+ * goes through here, so a sleeping camera keeps those caps across a
170850
+ * provider restart. `config` is read defensively: the base constructor
170851
+ * may read flags before this class's fields exist.
170852
+ */
170853
+ getProbeFlags() {
170854
+ return effectiveProbeFlags(this.hasProbed(), super.getProbeFlags(), this.config?.get("deviceCache"));
170855
+ }
169183
170856
  get features() {
169184
170857
  return deriveReolinkCameraFeatures({
169185
170858
  probe: this.getProbeFlags(),
@@ -178452,6 +180125,7 @@ var ReolinkEmailPushServer = class {
178452
180125
  const raw = await this.deps.readStore();
178453
180126
  let authUsername = readString$1(raw, "emailPushAuthUsername", "");
178454
180127
  let authPassword = readString$1(raw, "emailPushAuthPassword", "");
180128
+ const passwordUnresolved = isSecretMarkerLike(raw["emailPushAuthPassword"]);
178455
180129
  const bootstrapped = {};
178456
180130
  if (!authUsername) {
178457
180131
  authUsername = `camstack-${(0, node_crypto.randomBytes)(4).toString("hex")}`;
@@ -178459,7 +180133,8 @@ var ReolinkEmailPushServer = class {
178459
180133
  }
178460
180134
  if (!authPassword) {
178461
180135
  authPassword = (0, node_crypto.randomBytes)(18).toString("base64url");
178462
- bootstrapped.emailPushAuthPassword = authPassword;
180136
+ if (passwordUnresolved) this.deps.logger.error("email-push: the SMTP password is in the keychain but could not be read — running on a temporary password that is NOT saved; camera mail will fail AUTH until it resolves");
180137
+ else bootstrapped.emailPushAuthPassword = authPassword;
178463
180138
  }
178464
180139
  if (Object.keys(bootstrapped).length > 0) try {
178465
180140
  await this.deps.writeStore(bootstrapped);
@@ -178619,6 +180294,16 @@ var ReolinkEmailPushServer = class {
178619
180294
  }
178620
180295
  };
178621
180296
  //#endregion
180297
+ //#region src/email-push-store.ts
180298
+ async function readEmailPushStore(deps) {
180299
+ const raw = await deps.readRaw();
180300
+ const password = await deps.readPassword();
180301
+ return password.length > 0 ? {
180302
+ ...raw,
180303
+ emailPushAuthPassword: password
180304
+ } : raw;
180305
+ }
180306
+ //#endregion
178622
180307
  //#region src/email-push-schema.ts
178623
180308
  /**
178624
180309
  * The ids of the sections above, in render order — the value the addon hands
@@ -179218,7 +180903,10 @@ var ReolinkProviderAddon = class extends BaseDeviceProvider {
179218
180903
  if (!this.emailPushServer) this.emailPushServer = new ReolinkEmailPushServer({
179219
180904
  logger: this.ctx.logger.child("email-push"),
179220
180905
  listCameras: () => this.listReolinkCameras(),
179221
- readStore: async () => await this.resolveGlobalStore(),
180906
+ readStore: () => readEmailPushStore({
180907
+ readRaw: () => this.resolveGlobalStore(),
180908
+ readPassword: () => this.emailPushAuthPasswordState.get()
180909
+ }),
179222
180910
  writeStore: async (patch) => {
179223
180911
  const username = patch["emailPushAuthUsername"];
179224
180912
  if (typeof username === "string") await this.emailPushAuthUsernameState.set(username);