@camstack/addon-provider-homematic 1.2.130 → 1.2.132

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 +1938 -136
  2. package/dist/addon.mjs +1938 -136
  3. package/package.json +1 -1
package/dist/addon.js CHANGED
@@ -5386,7 +5386,7 @@ var ZodIssueCode = {
5386
5386
  var ZodFirstPartyTypeKind;
5387
5387
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
5388
5388
  //#endregion
5389
- //#region ../types/dist/sleep-Cr5YOk3m.mjs
5389
+ //#region ../types/dist/sleep-r3RWkGVx.mjs
5390
5390
  /**
5391
5391
  * The audio chunk plane's byte format, and the ONE expansion from a coded
5392
5392
  * window to float samples (D455).
@@ -5503,7 +5503,7 @@ function isKeychainStoredField(field) {
5503
5503
  var SECRET_CLEAR = { $secretClear: true };
5504
5504
  /** The `'***'` token D634 redaction writes for non-admins. */
5505
5505
  var LEGACY_DEVICE_REDACTION = "***";
5506
- function isRecord$1(value) {
5506
+ function isRecord$2(value) {
5507
5507
  return typeof value === "object" && value !== null && !Array.isArray(value);
5508
5508
  }
5509
5509
  function makeSecretMarker(ref) {
@@ -5514,12 +5514,12 @@ function makeSecretMarker(ref) {
5514
5514
  }
5515
5515
  /** A stored marker: an object whose `$secret` is a non-empty string. */
5516
5516
  function isSecretMarker(value) {
5517
- if (!isRecord$1(value)) return false;
5517
+ if (!isRecord$2(value)) return false;
5518
5518
  const ref = value["$secret"];
5519
5519
  return typeof ref === "string" && ref.length > 0;
5520
5520
  }
5521
5521
  function isSecretClear(value) {
5522
- return isRecord$1(value) && value["$secretClear"] === true;
5522
+ return isRecord$2(value) && value["$secretClear"] === true;
5523
5523
  }
5524
5524
  /**
5525
5525
  * The UI view of a stored secret field value: a marker becomes "set", inline
@@ -6035,6 +6035,13 @@ function globalSecretScope() {
6035
6035
  function encodeSegment(value) {
6036
6036
  return encodeURIComponent(value);
6037
6037
  }
6038
+ function decodeSegment(value) {
6039
+ try {
6040
+ return decodeURIComponent(value);
6041
+ } catch {
6042
+ return null;
6043
+ }
6044
+ }
6038
6045
  /**
6039
6046
  * The field path of a value inside an array item, addressed by the item's id:
6040
6047
  * `arrayItemFieldPath('providers', 'authentik', 'clientSecret')` →
@@ -6043,6 +6050,75 @@ function encodeSegment(value) {
6043
6050
  function arrayItemFieldPath(arrayKey, itemId, fieldKey) {
6044
6051
  return `${arrayKey}[${encodeSegment(itemId)}].${fieldKey}`;
6045
6052
  }
6053
+ function parseScope(segments) {
6054
+ switch (segments[0]) {
6055
+ case "global": return {
6056
+ scope: GLOBAL_SCOPE,
6057
+ used: 1
6058
+ };
6059
+ case "node": {
6060
+ const nodeId = segments[1] !== void 0 ? decodeSegment(segments[1]) : null;
6061
+ return nodeId === null || nodeId.length === 0 ? null : {
6062
+ scope: {
6063
+ kind: "node",
6064
+ nodeId
6065
+ },
6066
+ used: 2
6067
+ };
6068
+ }
6069
+ case "device": {
6070
+ const raw = segments[1];
6071
+ if (raw === void 0 || !/^\d+$/.test(raw)) return null;
6072
+ return {
6073
+ scope: {
6074
+ kind: "device",
6075
+ deviceId: Number(raw)
6076
+ },
6077
+ used: 2
6078
+ };
6079
+ }
6080
+ case "integration": {
6081
+ const id = segments[1] !== void 0 ? decodeSegment(segments[1]) : null;
6082
+ return id === null || id.length === 0 ? null : {
6083
+ scope: {
6084
+ kind: "integration",
6085
+ integrationId: id
6086
+ },
6087
+ used: 2
6088
+ };
6089
+ }
6090
+ case "row": {
6091
+ const collection = segments[1] !== void 0 ? decodeSegment(segments[1]) : null;
6092
+ const rowId = segments[2] !== void 0 ? decodeSegment(segments[2]) : null;
6093
+ if (collection === null || rowId === null || collection.length === 0 || rowId.length === 0) return null;
6094
+ return {
6095
+ scope: {
6096
+ kind: "row",
6097
+ collection,
6098
+ rowId
6099
+ },
6100
+ used: 3
6101
+ };
6102
+ }
6103
+ default: return null;
6104
+ }
6105
+ }
6106
+ /** Take a ref apart; `null` when it is not a well-formed ref. */
6107
+ function parseSecretRef(ref) {
6108
+ if (!ref.startsWith("secret://")) return null;
6109
+ const segments = ref.slice(9).split("/");
6110
+ const owner = segments[0] !== void 0 ? decodeSegment(segments[0]) : null;
6111
+ if (owner === null || owner.length === 0) return null;
6112
+ const parsed = parseScope(segments.slice(1));
6113
+ if (parsed === null) return null;
6114
+ const fieldPath = segments.slice(1 + parsed.used).join("/");
6115
+ if (fieldPath.length === 0) return null;
6116
+ return {
6117
+ owner,
6118
+ scope: parsed.scope,
6119
+ fieldPath
6120
+ };
6121
+ }
6046
6122
  /** A write to a secret path could not be stored in the keychain, so it was refused. */
6047
6123
  var KeychainWriteRefusedError = class extends Error {
6048
6124
  fieldPath;
@@ -6053,7 +6129,7 @@ var KeychainWriteRefusedError = class extends Error {
6053
6129
  }
6054
6130
  };
6055
6131
  var KEEP = { kind: "keep" };
6056
- function isRecord$2(value) {
6132
+ function isRecord$1(value) {
6057
6133
  return typeof value === "object" && value !== null && !Array.isArray(value);
6058
6134
  }
6059
6135
  function defaultMintId() {
@@ -6066,7 +6142,7 @@ function collectSecretMarkerRefs(value, out = []) {
6066
6142
  return out;
6067
6143
  }
6068
6144
  if (Array.isArray(value)) for (const item of value) collectSecretMarkerRefs(item, out);
6069
- else if (isRecord$2(value)) for (const child of Object.values(value)) collectSecretMarkerRefs(child, out);
6145
+ else if (isRecord$1(value)) for (const child of Object.values(value)) collectSecretMarkerRefs(child, out);
6070
6146
  return out;
6071
6147
  }
6072
6148
  async function storedValueEquals(secrets, marker, candidate) {
@@ -6121,7 +6197,7 @@ function rowId(row, idKey) {
6121
6197
  return null;
6122
6198
  }
6123
6199
  async function writeArray(ctx, node, incoming, stored, fieldPath) {
6124
- const storedRows = Array.isArray(stored) ? stored.filter(isRecord$2) : [];
6200
+ const storedRows = Array.isArray(stored) ? stored.filter(isRecord$1) : [];
6125
6201
  if (!Array.isArray(incoming)) {
6126
6202
  ctx.deletes.push(...collectSecretMarkerRefs(storedRows));
6127
6203
  return {
@@ -6137,7 +6213,7 @@ async function writeArray(ctx, node, incoming, stored, fieldPath) {
6137
6213
  const kept = /* @__PURE__ */ new Set();
6138
6214
  const rows = [];
6139
6215
  for (const row of incoming) {
6140
- if (!isRecord$2(row)) {
6216
+ if (!isRecord$1(row)) {
6141
6217
  rows.push(row);
6142
6218
  continue;
6143
6219
  }
@@ -6162,7 +6238,7 @@ async function writeNode(ctx, node, incoming, stored, fieldPath) {
6162
6238
  case "leaf": return writeLeaf(ctx, incoming, stored, fieldPath);
6163
6239
  case "array": return writeArray(ctx, node, incoming, stored, fieldPath);
6164
6240
  case "object": {
6165
- if (!isRecord$2(incoming)) {
6241
+ if (!isRecord$1(incoming)) {
6166
6242
  if (incoming === void 0) return KEEP;
6167
6243
  ctx.deletes.push(...collectSecretMarkerRefs(stored));
6168
6244
  return {
@@ -6170,7 +6246,7 @@ async function writeNode(ctx, node, incoming, stored, fieldPath) {
6170
6246
  value: incoming
6171
6247
  };
6172
6248
  }
6173
- const storedObj = isRecord$2(stored) ? stored : {};
6249
+ const storedObj = isRecord$1(stored) ? stored : {};
6174
6250
  return {
6175
6251
  kind: "value",
6176
6252
  value: await writeMembers(ctx, node.children, incoming, storedObj, (m) => `${fieldPath}.${m}`)
@@ -6229,12 +6305,19 @@ async function transformSecretWrite(input) {
6229
6305
  }
6230
6306
  };
6231
6307
  }
6308
+ /** Is `ref` one of `owner`'s refs? */
6309
+ function isSecretRefOwnedBy(ref, owner) {
6310
+ return parseSecretRef(ref)?.owner === owner;
6311
+ }
6232
6312
  /**
6233
6313
  * Replace every marker in `value` with its keychain value. Returns the SAME
6234
6314
  * reference when there is no marker (no allocation, no keychain call).
6235
6315
  */
6236
- async function resolveSecretMarkers(value, secrets) {
6237
- const refs = collectSecretMarkerRefs(value);
6316
+ async function resolveSecretMarkers(value, secrets, options = {}) {
6317
+ const keepMarker = options.unresolved === "keep-marker";
6318
+ const owner = options.ownedBy;
6319
+ const inScope = (ref) => owner === void 0 || isSecretRefOwnedBy(ref, owner);
6320
+ const refs = collectSecretMarkerRefs(value).filter(inScope);
6238
6321
  if (refs.length === 0) return {
6239
6322
  value,
6240
6323
  unresolved: []
@@ -6258,10 +6341,18 @@ async function resolveSecretMarkers(value, secrets) {
6258
6341
  }
6259
6342
  const substitute = (v) => {
6260
6343
  if (isSecretMarker(v)) {
6344
+ if (!inScope(v.$secret)) return {
6345
+ keep: true,
6346
+ value: v
6347
+ };
6261
6348
  const answer = answers[v.$secret];
6262
- return answer?.kind === "value" ? {
6349
+ if (answer?.kind === "value") return {
6263
6350
  keep: true,
6264
6351
  value: answer.value
6352
+ };
6353
+ return keepMarker ? {
6354
+ keep: true,
6355
+ value: v
6265
6356
  } : {
6266
6357
  keep: false,
6267
6358
  value: void 0
@@ -6278,7 +6369,7 @@ async function resolveSecretMarkers(value, secrets) {
6278
6369
  value: items
6279
6370
  };
6280
6371
  }
6281
- if (isRecord$2(v)) {
6372
+ if (isRecord$1(v)) {
6282
6373
  const out = {};
6283
6374
  for (const [k, child] of Object.entries(v)) {
6284
6375
  const s = substitute(child);
@@ -6299,14 +6390,152 @@ async function resolveSecretMarkers(value, secrets) {
6299
6390
  unresolved
6300
6391
  };
6301
6392
  }
6302
- function touchesTree(tree, patch) {
6303
- if (tree.size === 0) return false;
6304
- for (const key of Object.keys(patch)) {
6305
- const at = key.indexOf("@");
6306
- if (tree.has(at > 0 ? key.slice(0, at) : key)) return true;
6393
+ /** An addon tried to replace a stored secret it could not read. Nothing was written. */
6394
+ var SecretOverwriteRefusedError = class extends Error {
6395
+ ref;
6396
+ reason;
6397
+ constructor(ref, reason) {
6398
+ 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.`);
6399
+ this.ref = ref;
6400
+ this.reason = reason;
6401
+ this.name = "SecretOverwriteRefusedError";
6402
+ }
6403
+ };
6404
+ function isRecord$3(value) {
6405
+ return typeof value === "object" && value !== null && !Array.isArray(value);
6406
+ }
6407
+ function resolvedValue(pass, marker) {
6408
+ const answer = pass.answers[marker.$secret];
6409
+ return answer?.kind === "value" ? answer.value : null;
6410
+ }
6411
+ async function atMarker(pass, incoming, stored) {
6412
+ if (incoming === null) return stored;
6413
+ if (typeof incoming !== "string") return incoming;
6414
+ if (incoming === resolvedValue(pass, stored)) return stored;
6415
+ const intent = classifySecretWrite(incoming);
6416
+ if (intent.kind !== "set") return stored;
6417
+ const ref = stored.$secret;
6418
+ if (!isSecretRefOwnedBy(ref, pass.secrets.owner)) return incoming;
6419
+ const answer = pass.answers[ref];
6420
+ 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);
6421
+ try {
6422
+ await pass.secrets.put(ref, intent.value);
6423
+ } catch (err) {
6424
+ throw new KeychainWriteRefusedError(ref, err);
6425
+ }
6426
+ pass.changedRefs.push(ref);
6427
+ return stored;
6428
+ }
6429
+ function inArray(pass, incoming, stored) {
6430
+ return incoming.map((item, index) => {
6431
+ const twin = stored[index];
6432
+ if (isSecretMarker(twin)) return typeof item === "string" && item === resolvedValue(pass, twin) ? twin : item;
6433
+ if (isRecord$3(item) && isRecord$3(twin)) return inArrayRow(pass, item, twin);
6434
+ if (Array.isArray(item) && Array.isArray(twin)) return inArray(pass, item, twin);
6435
+ return item;
6436
+ });
6437
+ }
6438
+ function inArrayRow(pass, incoming, stored) {
6439
+ const out = { ...incoming };
6440
+ for (const [key, value] of Object.entries(incoming)) {
6441
+ const twin = stored[key];
6442
+ if (isSecretMarker(twin)) {
6443
+ if (typeof value === "string" && value === resolvedValue(pass, twin)) out[key] = twin;
6444
+ } else if (isRecord$3(value) && isRecord$3(twin)) out[key] = inArrayRow(pass, value, twin);
6445
+ else if (Array.isArray(value) && Array.isArray(twin)) out[key] = inArray(pass, value, twin);
6446
+ }
6447
+ return out;
6448
+ }
6449
+ async function walk(pass, incoming, stored) {
6450
+ if (isSecretMarker(stored)) return atMarker(pass, incoming, stored);
6451
+ if (Array.isArray(incoming) && Array.isArray(stored)) return inArray(pass, incoming, stored);
6452
+ if (!isRecord$3(incoming) || !isRecord$3(stored)) return incoming;
6453
+ const out = { ...incoming };
6454
+ for (const [key, value] of Object.entries(incoming)) out[key] = await walk(pass, value, stored[key]);
6455
+ return out;
6456
+ }
6457
+ /** Restore markers a write-back carries as values. See the file doc. */
6458
+ async function restoreUnchangedSecrets(input) {
6459
+ const refs = [];
6460
+ for (const key of Object.keys(input.patch)) collectSecretMarkerRefs(input.stored[key], refs);
6461
+ const owned = refs.filter((ref) => isSecretRefOwnedBy(ref, input.secrets.owner));
6462
+ if (owned.length === 0) return {
6463
+ patch: input.patch,
6464
+ changedRefs: []
6465
+ };
6466
+ const pass = {
6467
+ secrets: input.secrets,
6468
+ answers: await input.secrets.resolve([...new Set(owned)]),
6469
+ operatorWrite: input.operatorWrite,
6470
+ changedRefs: []
6471
+ };
6472
+ const out = {};
6473
+ for (const [key, value] of Object.entries(input.patch)) out[key] = await walk(pass, value, input.stored[key]);
6474
+ return {
6475
+ patch: out,
6476
+ changedRefs: pass.changedRefs
6477
+ };
6478
+ }
6479
+ /** Structural equality over JSON-shaped values (key order does not matter). */
6480
+ function isJsonEqual(a, b) {
6481
+ if (Object.is(a, b)) return true;
6482
+ if (Array.isArray(a)) return Array.isArray(b) && a.length === b.length && a.every((v, i) => isJsonEqual(v, b[i]));
6483
+ if (isRecord$3(a) && isRecord$3(b)) {
6484
+ const keys = Object.keys(a);
6485
+ if (keys.length !== Object.keys(b).length) return false;
6486
+ return keys.every((k) => Object.prototype.hasOwnProperty.call(b, k) && isJsonEqual(a[k], b[k]));
6307
6487
  }
6308
6488
  return false;
6309
6489
  }
6490
+ /** The patch without the keys whose value already equals the stored one. */
6491
+ function dropUnchangedKeys(patch, stored) {
6492
+ const out = {};
6493
+ for (const [key, value] of Object.entries(patch)) {
6494
+ if (Object.prototype.hasOwnProperty.call(stored, key) && isJsonEqual(value, stored[key])) continue;
6495
+ out[key] = value;
6496
+ }
6497
+ return out;
6498
+ }
6499
+ /** The top-level keys of a blob that hold at least one of `owner`'s markers. */
6500
+ function markerKeysOf(blob, owner) {
6501
+ const keys = /* @__PURE__ */ new Set();
6502
+ for (const [key, value] of Object.entries(blob)) if (collectSecretMarkerRefs(value).some((ref) => isSecretRefOwnedBy(ref, owner))) keys.add(key);
6503
+ return keys;
6504
+ }
6505
+ function nodeFromStored(value, owner) {
6506
+ if (isSecretMarker(value)) return isSecretRefOwnedBy(value.$secret, owner) ? { kind: "leaf" } : null;
6507
+ if (!isRecord$3(value)) return null;
6508
+ const children = /* @__PURE__ */ new Map();
6509
+ for (const [key, child] of Object.entries(value)) {
6510
+ const node = nodeFromStored(child, owner);
6511
+ if (node !== null) children.set(key, node);
6512
+ }
6513
+ return children.size > 0 ? {
6514
+ kind: "object",
6515
+ children
6516
+ } : null;
6517
+ }
6518
+ /**
6519
+ * The declared secret tree, widened by every place the STORED blob holds a
6520
+ * marker under one of `keys` — so a marker the schema no longer declares (or
6521
+ * never declared: Wyze before b4906cec6) still gets the save path's
6522
+ * KEEP / SET / CLEAR semantics instead of being overwritten by whatever the
6523
+ * addon writes. Markers inside arrays are not added: a row has no id field to
6524
+ * match by unless the schema declares one. Only `owner`'s markers count: a
6525
+ * builtin that keeps another addon's marker (device-manager) never takes it
6526
+ * over.
6527
+ */
6528
+ function widenTreeWithStoredMarkers(declared, stored, keys, owner) {
6529
+ const added = /* @__PURE__ */ new Map();
6530
+ for (const key of keys) {
6531
+ const at = key.indexOf("@");
6532
+ const base = at > 0 ? key.slice(0, at) : key;
6533
+ if (declared.has(base) || added.has(base)) continue;
6534
+ const node = nodeFromStored(stored[key], owner);
6535
+ if (node !== null) added.set(base, node);
6536
+ }
6537
+ return added.size === 0 ? declared : new Map([...declared, ...added]);
6538
+ }
6310
6539
  /** The blob as stored now; a failed read REFUSES the write instead of guessing. */
6311
6540
  async function readStoredAddonBlob(raw) {
6312
6541
  const threeWay = raw.readAddonStoreResult;
@@ -6315,7 +6544,41 @@ async function readStoredAddonBlob(raw) {
6315
6544
  if (result.kind === "failed") throw new Error(`settings write refused: the stored blob could not be read (${result.error})`);
6316
6545
  return result.kind === "missing" ? {} : result.value;
6317
6546
  }
6318
- function createSecretAwareSettings(raw, opts) {
6547
+ function touchesTree(tree, patch) {
6548
+ if (tree.size === 0) return false;
6549
+ for (const key of Object.keys(patch)) {
6550
+ const at = key.indexOf("@");
6551
+ if (tree.has(at > 0 ? key.slice(0, at) : key)) return true;
6552
+ }
6553
+ return false;
6554
+ }
6555
+ /**
6556
+ * Which top-level keys of each store held markers when last seen. `undefined`
6557
+ * for a store not seen yet: its first write reads it, to be safe.
6558
+ */
6559
+ var MarkerKeyIndex = class {
6560
+ owner;
6561
+ byStore = /* @__PURE__ */ new Map();
6562
+ constructor(owner) {
6563
+ this.owner = owner;
6564
+ }
6565
+ seen(store, blob) {
6566
+ this.byStore.set(store, markerKeysOf(blob, this.owner));
6567
+ }
6568
+ wrote(store, patch) {
6569
+ const keys = this.byStore.get(store);
6570
+ if (keys === void 0) return;
6571
+ const now = markerKeysOf(patch, this.owner);
6572
+ for (const key of Object.keys(patch)) if (now.has(key)) keys.add(key);
6573
+ else keys.delete(key);
6574
+ }
6575
+ mayHoldMarkers(store, patch) {
6576
+ const keys = this.byStore.get(store);
6577
+ if (keys === void 0) return true;
6578
+ return Object.keys(patch).some((key) => keys.has(key));
6579
+ }
6580
+ };
6581
+ function createHandle(raw, opts) {
6319
6582
  const chains = /* @__PURE__ */ new Map();
6320
6583
  const serialize = (key, fn) => {
6321
6584
  const next = (chains.get(key) ?? Promise.resolve()).then(fn, fn);
@@ -6326,46 +6589,130 @@ function createSecretAwareSettings(raw, opts) {
6326
6589
  });
6327
6590
  return next;
6328
6591
  };
6329
- const write = async (chainKey, tree, scope, patch, readStored, rawWrite) => {
6330
- if (!touchesTree(tree, patch)) return rawWrite(patch);
6331
- return serialize(chainKey, async () => {
6592
+ const index = new MarkerKeyIndex(opts.secrets.owner);
6593
+ const resolveRead = async (store, blob) => {
6594
+ index.seen(store, blob);
6595
+ const { value, unresolved } = await resolveSecretMarkers(blob, opts.secrets, {
6596
+ unresolved: "keep-marker",
6597
+ ownedBy: opts.secrets.owner
6598
+ });
6599
+ if (unresolved.length > 0) opts.onUnresolved?.(unresolved);
6600
+ return value;
6601
+ };
6602
+ const write = async (store, declared, scope, patch, readStored, rawWrite) => {
6603
+ if (!touchesTree(declared, patch) && !index.mayHoldMarkers(store, patch)) {
6604
+ await rawWrite(patch);
6605
+ index.wrote(store, patch);
6606
+ return { changed: true };
6607
+ }
6608
+ return serialize(store, async () => {
6332
6609
  const stored = await readStored();
6610
+ index.seen(store, stored);
6611
+ const operatorWrite = opts.isOperatorWrite?.() === true;
6612
+ const restored = await restoreUnchangedSecrets({
6613
+ patch,
6614
+ stored,
6615
+ secrets: opts.secrets,
6616
+ operatorWrite
6617
+ });
6333
6618
  const result = await transformSecretWrite({
6334
- tree,
6619
+ tree: widenTreeWithStoredMarkers(declared, stored, Object.keys(restored.patch), opts.secrets.owner),
6335
6620
  secrets: opts.secrets,
6336
- patch,
6621
+ patch: restored.patch,
6337
6622
  stored,
6338
6623
  ...scope !== void 0 ? { scope } : {},
6339
- operatorWrite: opts.isOperatorWrite?.() === true
6624
+ operatorWrite
6340
6625
  });
6341
- if (Object.keys(result.patch).length > 0) await rawWrite(result.patch);
6626
+ const effective = dropUnchangedKeys(result.patch, stored);
6627
+ const wroteBlob = Object.keys(effective).length > 0;
6628
+ if (wroteBlob) {
6629
+ await rawWrite(effective);
6630
+ index.wrote(store, effective);
6631
+ }
6342
6632
  const { orphaned } = await result.afterWrite();
6343
6633
  if (orphaned.length > 0) opts.onOrphaned(orphaned);
6634
+ return { changed: wroteBlob || restored.changedRefs.length > 0 };
6344
6635
  });
6345
6636
  };
6346
- const wrapped = {
6347
- writeAddonStore: (patch) => write("addon", opts.addonTree(), void 0, patch, () => readStoredAddonBlob(raw), (p) => raw.writeAddonStore(p)),
6348
- writeDeviceStore: (deviceId, patch) => write(`device:${deviceId}`, opts.deviceTree(), {
6349
- kind: "device",
6350
- deviceId
6351
- }, patch, () => raw.readDeviceStore(deviceId), (p) => raw.writeDeviceStore(deviceId, p))
6637
+ const writeAddon = (patch) => write("addon", opts.addonTree(), void 0, patch, () => readStoredAddonBlob(raw), (p) => raw.writeAddonStore(p));
6638
+ const readAddonStoreResult = raw.readAddonStoreResult;
6639
+ const readAddonStoreKeyResult = raw.readAddonStoreKeyResult;
6640
+ const readDeviceStoreBatch = raw.readDeviceStoreBatch;
6641
+ const overrides = {
6642
+ readAddonStore: async () => resolveRead("addon", await raw.readAddonStore()),
6643
+ ...readAddonStoreResult !== void 0 ? { readAddonStoreResult: async () => {
6644
+ const result = await readAddonStoreResult.call(raw);
6645
+ return result.kind === "value" ? {
6646
+ kind: "value",
6647
+ value: await resolveRead("addon", result.value)
6648
+ } : result;
6649
+ } } : {},
6650
+ ...readAddonStoreKeyResult !== void 0 ? { readAddonStoreKeyResult: async (key) => {
6651
+ const result = await readAddonStoreKeyResult.call(raw, key);
6652
+ if (result.kind !== "present") return result;
6653
+ const { value, unresolved } = await resolveSecretMarkers({ [key]: result.value }, opts.secrets, {
6654
+ unresolved: "keep-marker",
6655
+ ownedBy: opts.secrets.owner
6656
+ });
6657
+ if (unresolved.length > 0) opts.onUnresolved?.(unresolved);
6658
+ return {
6659
+ kind: "present",
6660
+ value: value[key]
6661
+ };
6662
+ } } : {},
6663
+ readDeviceStore: async (deviceId) => resolveRead(`device:${deviceId}`, await raw.readDeviceStore(deviceId)),
6664
+ ...readDeviceStoreBatch !== void 0 ? { readDeviceStoreBatch: async (deviceIds) => {
6665
+ const rows = await readDeviceStoreBatch.call(raw, deviceIds);
6666
+ const out = /* @__PURE__ */ new Map();
6667
+ for (const [deviceId, blob] of rows) out.set(deviceId, await resolveRead(`device:${deviceId}`, blob));
6668
+ return out;
6669
+ } } : {},
6670
+ writeAddonStore: async (patch) => {
6671
+ await writeAddon(patch);
6672
+ },
6673
+ writeDeviceStore: async (deviceId, patch) => {
6674
+ await write(`device:${deviceId}`, opts.deviceTree(), {
6675
+ kind: "device",
6676
+ deviceId
6677
+ }, patch, () => raw.readDeviceStore(deviceId), (p) => raw.writeDeviceStore(deviceId, p));
6678
+ }
6679
+ };
6680
+ return {
6681
+ settings: new Proxy(raw, { get(target, prop, receiver) {
6682
+ if (typeof prop === "string" && Object.prototype.hasOwnProperty.call(overrides, prop)) return Reflect.get(overrides, prop);
6683
+ const value = Reflect.get(target, prop, receiver);
6684
+ return typeof value === "function" ? value.bind(target) : value;
6685
+ } }),
6686
+ raw: {
6687
+ readAddonStore: async () => {
6688
+ const blob = await raw.readAddonStore();
6689
+ index.seen("addon", blob);
6690
+ return blob;
6691
+ },
6692
+ readDeviceStore: async (deviceId) => {
6693
+ const blob = await raw.readDeviceStore(deviceId);
6694
+ index.seen(`device:${deviceId}`, blob);
6695
+ return blob;
6696
+ }
6697
+ },
6698
+ writeAddonStore: writeAddon
6352
6699
  };
6353
- return new Proxy(raw, { get(target, prop, receiver) {
6354
- if (prop === "writeAddonStore") return wrapped.writeAddonStore;
6355
- if (prop === "writeDeviceStore") return wrapped.writeDeviceStore;
6356
- const value = Reflect.get(target, prop, receiver);
6357
- return typeof value === "function" ? value.bind(target) : value;
6358
- } });
6359
6700
  }
6360
- /** The context the addon sees: identical, except that its settings writes are secret-aware. */
6361
- function withSecretAwareSettings(context, opts) {
6701
+ /** The context the addon sees, plus the private raw view and write outcome. */
6702
+ function createSecretAwareContext(context, opts) {
6362
6703
  const raw = context.settings;
6363
- if (raw === void 0) return context;
6364
- const settings = createSecretAwareSettings(raw, opts);
6365
- return new Proxy(context, { get(target, prop, receiver) {
6366
- if (prop === "settings") return settings;
6367
- return Reflect.get(target, prop, receiver);
6368
- } });
6704
+ if (raw === void 0) return {
6705
+ context,
6706
+ handle: null
6707
+ };
6708
+ const handle = createHandle(raw, opts);
6709
+ return {
6710
+ context: new Proxy(context, { get(target, prop, receiver) {
6711
+ if (prop === "settings") return handle.settings;
6712
+ return Reflect.get(target, prop, receiver);
6713
+ } }),
6714
+ handle
6715
+ };
6369
6716
  }
6370
6717
  var LEAF = { kind: "leaf" };
6371
6718
  var DEFAULT_ITEM_ID_KEY = "id";
@@ -6540,6 +6887,14 @@ var BaseAddon = class {
6540
6887
  _secretChangeUnsub = null;
6541
6888
  /** >0 while an OPERATOR's settings write is being applied. */
6542
6889
  _operatorWriteDepth = 0;
6890
+ /**
6891
+ * The keychain-aware settings handle (D798). Its `raw` view is the ONLY way
6892
+ * to the marker-bearing blobs and stays private to this class: the form
6893
+ * hydrate and config resolution need markers, addon code never does.
6894
+ */
6895
+ _secretSettings = null;
6896
+ /** Refs an addon-facing read could not resolve — each is logged once per process. */
6897
+ _loggedUnresolvedReads = /* @__PURE__ */ new Set();
6543
6898
  constructor(defaults) {
6544
6899
  this.defaults = defaults;
6545
6900
  this._config = { ...defaults };
@@ -6576,13 +6931,21 @@ var BaseAddon = class {
6576
6931
  }
6577
6932
  async initialize(context) {
6578
6933
  const secrets = context.secrets;
6579
- this._ctx = secrets !== void 0 ? withSecretAwareSettings(context, {
6580
- secrets,
6581
- addonTree: () => this.addonSecretTree(),
6582
- deviceTree: () => this.deviceSecretTree(),
6583
- onOrphaned: (refs) => context.logger.warn("keychain refs dropped by a settings write could not be deleted", { meta: { refs: [...refs] } }),
6584
- isOperatorWrite: () => this._operatorWriteDepth > 0
6585
- }) : context;
6934
+ if (secrets !== void 0) {
6935
+ const { context: wrapped, handle } = createSecretAwareContext(context, {
6936
+ secrets,
6937
+ addonTree: () => this.addonSecretTree(),
6938
+ deviceTree: () => this.deviceSecretTree(),
6939
+ onOrphaned: (refs) => context.logger.warn("keychain refs dropped by a settings write could not be deleted", { meta: { refs: [...refs] } }),
6940
+ isOperatorWrite: () => this._operatorWriteDepth > 0,
6941
+ onUnresolved: (unresolved) => this.logUnresolvedRead(unresolved)
6942
+ });
6943
+ this._ctx = wrapped;
6944
+ this._secretSettings = handle;
6945
+ } else {
6946
+ this._ctx = context;
6947
+ this._secretSettings = null;
6948
+ }
6586
6949
  await this.resolveConfig();
6587
6950
  if (secrets !== void 0) this._secretChangeUnsub = secrets.onChange((ref) => {
6588
6951
  if (this._configSecretRefs.has(ref)) this.scheduleSecretReresolve(SECRET_CHANGE_DEBOUNCE_MS);
@@ -6699,11 +7062,8 @@ var BaseAddon = class {
6699
7062
  async getGlobalSettings(overlay, cap, nodeId) {
6700
7063
  const schema = this.globalSettingsSchema(cap);
6701
7064
  if (!schema) return { sections: [] };
6702
- const projected = await this.resolveGlobalStore(nodeId, cap);
6703
- return hydrateSchema(schema, overlay ? {
6704
- ...projected,
6705
- ...overlay
6706
- } : projected, { inlineSecretsAsViews: true });
7065
+ const projected = await this.readRawProjectedStore(nodeId, cap);
7066
+ return hydrateSchema(schema, overlay ? await this.overlayKeepingMarkers(projected, overlay) : projected, { inlineSecretsAsViews: true });
6707
7067
  }
6708
7068
  /**
6709
7069
  * The integration-level view of this addon's settings: exactly the sections
@@ -6748,7 +7108,7 @@ var BaseAddon = class {
6748
7108
  });
6749
7109
  }
6750
7110
  if (sections.length === 0) return null;
6751
- const projected = await this.resolveGlobalStore(nodeId);
7111
+ const projected = await this.readRawProjectedStore(nodeId);
6752
7112
  return hydrateSchema({
6753
7113
  ...schema,
6754
7114
  sections
@@ -6765,12 +7125,50 @@ var BaseAddon = class {
6765
7125
  * the store for custom option logic (option narrowing, value snapping) to
6766
7126
  * read it per-node — never `ctx.settings.readAddonStore()` directly.
6767
7127
  * `nodeId` omitted ⇒ the local node (node-blind injection from ctx).
7128
+ *
7129
+ * Keychain values come back RESOLVED (D798): a secret reads as its value,
7130
+ * never as a `{ $secret }` marker. One the keychain cannot serve right now
7131
+ * stays a marker — "stored, unavailable" (`isSecretMarker()` is true, and it
7132
+ * is listed in {@link unresolvedSecrets}) — never `''` and never absent, so
7133
+ * it cannot be mistaken for "nothing stored, mint a new one". Writing the
7134
+ * resolved blob back is a no-op for every unchanged secret.
6768
7135
  */
6769
7136
  async resolveGlobalStore(nodeId, cap) {
6770
7137
  const raw = await this._ctx?.settings?.readAddonStore() ?? {};
7138
+ return this.projectForNode(raw, nodeId, cap);
7139
+ }
7140
+ projectForNode(store, nodeId, cap) {
6771
7141
  const keys = this.perNodeKeys(cap);
6772
7142
  const node = normalizeNodeId(nodeId ?? this._ctx?.kernel?.localNodeId);
6773
- return keys.size > 0 ? projectStore(raw, keys, node) : raw;
7143
+ return keys.size > 0 ? projectStore(store, keys, node) : store;
7144
+ }
7145
+ /** The PROJECTED store with its markers — the form hydrate only (D798). */
7146
+ async readRawProjectedStore(nodeId, cap) {
7147
+ const raw = await this.rawSettings()?.readAddonStore() ?? {};
7148
+ return this.projectForNode(raw, nodeId, cap);
7149
+ }
7150
+ /**
7151
+ * `{ ...stored, ...overlay }`, except that an overlay member equal to the
7152
+ * RESOLVED stored one keeps the stored (marker-bearing) member — so a form
7153
+ * hydrated from a resolved overlay still shows a secret as "set", never as
7154
+ * its value.
7155
+ */
7156
+ async overlayKeepingMarkers(stored, overlay) {
7157
+ const secrets = this._ctx?.secrets;
7158
+ const merged = {
7159
+ ...stored,
7160
+ ...overlay
7161
+ };
7162
+ if (secrets === void 0 || collectSecretMarkerRefs(stored).length === 0) return merged;
7163
+ const { value: resolved } = await resolveSecretMarkers(stored, secrets, {
7164
+ unresolved: "keep-marker",
7165
+ ownedBy: secrets.owner
7166
+ });
7167
+ for (const key of Object.keys(overlay)) {
7168
+ if (collectSecretMarkerRefs(stored[key]).length === 0) continue;
7169
+ if (isJsonEqual(overlay[key], resolved[key])) merged[key] = stored[key];
7170
+ }
7171
+ return merged;
6774
7172
  }
6775
7173
  /**
6776
7174
  * Whether ONE global key of this addon's store was written, read three-way
@@ -6835,8 +7233,12 @@ var BaseAddon = class {
6835
7233
  async clearSecrets(keys, nodeId) {
6836
7234
  const tree = this.addonSecretTree();
6837
7235
  const keychain = this._ctx?.secrets !== void 0;
7236
+ const stored = keychain ? await this.readAddonStoreWithRetry() : {};
6838
7237
  const patch = {};
6839
- for (const key of keys) patch[key] = keychain && tree.has(key) ? SECRET_CLEAR : "";
7238
+ for (const key of keys) {
7239
+ const keychainStored = tree.has(key) || collectSecretMarkerRefs(stored[key]).length > 0;
7240
+ patch[key] = keychain && keychainStored ? SECRET_CLEAR : "";
7241
+ }
6840
7242
  await this.applyGlobalPatch(patch, nodeId);
6841
7243
  }
6842
7244
  async applyGlobalPatch(barePatch, nodeId) {
@@ -6844,7 +7246,11 @@ var BaseAddon = class {
6844
7246
  const localNode = normalizeNodeId(this._ctx?.kernel?.localNodeId);
6845
7247
  const target = normalizeNodeId(nodeId ?? this._ctx?.kernel?.localNodeId);
6846
7248
  const scoped = keys.size > 0 ? scopePatch(barePatch, keys, target) : barePatch;
6847
- await this._ctx?.settings?.writeAddonStore(scoped);
7249
+ const handle = this._secretSettings;
7250
+ if (handle !== null) {
7251
+ const { changed } = await handle.writeAddonStore(scoped);
7252
+ if (!changed) return;
7253
+ } else await this._ctx?.settings?.writeAddonStore(scoped);
6848
7254
  if (target !== localNode) return;
6849
7255
  await this.resolveConfig();
6850
7256
  await this.onConfigChanged();
@@ -6897,7 +7303,7 @@ var BaseAddon = class {
6897
7303
  async getDeviceSettings(deviceId) {
6898
7304
  const schema = this.deviceSettingsSchema();
6899
7305
  if (!schema) return { sections: [] };
6900
- return hydrateSchema(schema, await this._ctx?.settings?.readDeviceStore(deviceId) ?? {}, { inlineSecretsAsViews: true });
7306
+ return hydrateSchema(schema, await this.rawSettings()?.readDeviceStore(deviceId) ?? {}, { inlineSecretsAsViews: true });
6901
7307
  }
6902
7308
  async updateDeviceSettings(deviceId, patch) {
6903
7309
  await this._ctx?.settings?.writeDeviceStore(deviceId, patch);
@@ -7069,7 +7475,7 @@ var BaseAddon = class {
7069
7475
  key,
7070
7476
  schema,
7071
7477
  fallback,
7072
- read: async () => this.resolveStoredSecrets(await this._ctx?.settings?.readDeviceStore(deviceId) ?? {}, false),
7478
+ read: async () => this.resolveStoredSecrets(await this.rawSettings()?.readDeviceStore(deviceId) ?? {}, false),
7073
7479
  write: async (patch) => {
7074
7480
  await this._ctx?.settings?.writeDeviceStore(deviceId, patch);
7075
7481
  },
@@ -7131,6 +7537,23 @@ var BaseAddon = class {
7131
7537
  }
7132
7538
  return value;
7133
7539
  }
7540
+ /**
7541
+ * The marker-bearing settings reads (D798) — private on purpose. Without a
7542
+ * keychain the context's own view is already raw.
7543
+ */
7544
+ rawSettings() {
7545
+ return this._secretSettings?.raw ?? this._ctx?.settings;
7546
+ }
7547
+ /** An addon-facing read met markers it could not resolve: say so once per ref. */
7548
+ logUnresolvedRead(unresolved) {
7549
+ const fresh = unresolved.filter((u) => !this._loggedUnresolvedReads.has(u.ref));
7550
+ if (fresh.length === 0) return;
7551
+ for (const u of fresh) this._loggedUnresolvedReads.add(u.ref);
7552
+ 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) => ({
7553
+ ref: u.ref,
7554
+ reason: u.reason
7555
+ })) } });
7556
+ }
7134
7557
  /** Re-resolve the config (a keychain-only change, or a retry) and apply it. */
7135
7558
  scheduleSecretReresolve(delayMs) {
7136
7559
  const timerOf = delayMs === SECRET_CHANGE_DEBOUNCE_MS ? "_secretChangeTimer" : "_secretRetryTimer";
@@ -7157,7 +7580,7 @@ var BaseAddon = class {
7157
7580
  * `{}` (defaults) — the addon's first successful patch will rehydrate.
7158
7581
  */
7159
7582
  async readAddonStoreWithRetry() {
7160
- const settings = this._ctx?.settings;
7583
+ const settings = this.rawSettings();
7161
7584
  if (!settings) return {};
7162
7585
  const delaysMs = [
7163
7586
  150,
@@ -9460,6 +9883,278 @@ var CameraSwitchGroupSchema = object({
9460
9883
  fetchedAt: number()
9461
9884
  });
9462
9885
  /**
9886
+ * The trainer contract — what the hub hands the cloud trainer and what it
9887
+ * gets back (cloud training, D805+).
9888
+ *
9889
+ * The trainer (`hf/camstack-trainer`, published as the Hugging Face repo
9890
+ * `camstack/camstack-trainer`) is a separate AGPL program the hub never
9891
+ * imports: `job.json` goes in, files come out, and progress is `CAMSTACK_EVENT`
9892
+ * lines on stdout. These schemas are the hub's half of that boundary; the
9893
+ * trainer's pydantic models (and the JSON Schemas generated from them under
9894
+ * `hf/camstack-trainer/schemas/`) are the other half. A change here is a
9895
+ * change there, in the same piece of work.
9896
+ *
9897
+ * No `.default()` anywhere: defaults do not run on the addon cap path, so the
9898
+ * orchestrator fills every field of a job spec explicitly.
9899
+ */
9900
+ var TRAINING_JOB_SCHEMA = "camstack.training/v1";
9901
+ var TRAINING_RESULT_SCHEMA = "camstack.training-result/v1";
9902
+ /** What the trainer can export. Edge TPU is a later, separate image. */
9903
+ var TrainingExportSchema = _enum([
9904
+ "onnx",
9905
+ "openvino-fp16",
9906
+ "openvino-int8",
9907
+ "coreml-fp16"
9908
+ ]);
9909
+ var FloorsSchema = record(string(), number().min(0).max(1));
9910
+ object({
9911
+ schema: literal(TRAINING_JOB_SCHEMA),
9912
+ jobKey: string().uuid(),
9913
+ target: object({
9914
+ kind: literal("detector"),
9915
+ step: literal("object-detection")
9916
+ }),
9917
+ base: object({
9918
+ modelId: string().min(1),
9919
+ /** Ultralytics weights id, e.g. `yolov9m.pt`. */
9920
+ weights: string().min(1),
9921
+ imgsz: number().int().positive()
9922
+ }),
9923
+ baseline: object({
9924
+ modelId: string().min(1),
9925
+ /** The baseline ONNX the holdout comparison runs; public mirror URL. */
9926
+ onnxUrl: string().url(),
9927
+ imgsz: number().int().positive(),
9928
+ floors: FloorsSchema
9929
+ }),
9930
+ dataset: object({
9931
+ versionId: string().min(1),
9932
+ annotationHash: string(),
9933
+ /** sha256 of the uploaded archive; the trainer refuses a mismatch (exit 65). */
9934
+ sha256: string().regex(/^[0-9a-f]{64}$/)
9935
+ }),
9936
+ split: object({
9937
+ holdoutCameras: array(number().int()),
9938
+ /** When no camera is held out: the last N days of every camera. */
9939
+ holdoutLastDays: number().int().nonnegative(),
9940
+ valFraction: number().min(0).max(.5),
9941
+ seed: number().int()
9942
+ }),
9943
+ hyper: object({
9944
+ epochs: number().int().positive(),
9945
+ batch: number().int().positive(),
9946
+ lr0: number().positive(),
9947
+ /** Layers frozen from the start of the backbone; 0 = none. */
9948
+ freeze: number().int().nonnegative(),
9949
+ patience: number().int().nonnegative(),
9950
+ seed: number().int()
9951
+ }),
9952
+ replay: object({
9953
+ source: literal("coco2017"),
9954
+ count: number().int().nonnegative()
9955
+ }),
9956
+ exports: array(TrainingExportSchema).min(1),
9957
+ calibration: object({ maxFrames: number().int().positive() }),
9958
+ floors: object({
9959
+ minSupport: number().int().positive(),
9960
+ clamp: number().min(0).max(1)
9961
+ }),
9962
+ int8Gate: object({ maxMap50Drop: number().min(0).max(1) }),
9963
+ catalog: object({
9964
+ id: string().regex(/^[a-z0-9][a-z0-9-]{2,80}$/),
9965
+ name: string().min(1).max(160)
9966
+ })
9967
+ });
9968
+ /** One regular file of the bundle. An mlpackage contributes one row per member. */
9969
+ var TrainingResultFileSchema = object({
9970
+ path: string().min(1),
9971
+ bytes: number().int().nonnegative(),
9972
+ sha256: string().regex(/^[0-9a-f]{64}$/),
9973
+ format: _enum([
9974
+ "onnx",
9975
+ "openvino",
9976
+ "coreml",
9977
+ "pt"
9978
+ ]),
9979
+ variant: _enum(["base", "int8"])
9980
+ });
9981
+ var DraftFormatSchema = object({
9982
+ /** RELATIVE path inside the bundle; the hub rewrites it to `camstack-local://`. */
9983
+ url: string().min(1),
9984
+ sizeMB: number().nonnegative(),
9985
+ isDirectory: boolean().optional(),
9986
+ files: array(string()).optional(),
9987
+ runtimes: array(literal("python")).optional(),
9988
+ revision: string().min(1)
9989
+ });
9990
+ /** The trainer's half of a catalog entry; the hub completes it (labels, licence, group). */
9991
+ var TrainingCatalogDraftSchema = object({
9992
+ id: string().min(1),
9993
+ name: string().min(1),
9994
+ description: string(),
9995
+ labels: array(unknown()),
9996
+ inputSize: object({
9997
+ width: number().int().positive(),
9998
+ height: number().int().positive()
9999
+ }),
10000
+ preprocessMode: literal("letterbox"),
10001
+ defaultClassFloors: FloorsSchema,
10002
+ formats: object({
10003
+ onnx: DraftFormatSchema.optional(),
10004
+ openvino: DraftFormatSchema.optional(),
10005
+ coreml: DraftFormatSchema.optional()
10006
+ })
10007
+ });
10008
+ /** One class of one model's holdout report (the eval harness's summary). */
10009
+ var TrainingEvalClassSchema = object({
10010
+ positives: number().int(),
10011
+ floor: number().nullable(),
10012
+ tp: number().int(),
10013
+ fp: number().int(),
10014
+ fn: number().int(),
10015
+ precision: number().nullable(),
10016
+ recall: number().nullable(),
10017
+ ap50: number().nullable(),
10018
+ recallByCamera: record(string(), number().nullable()).optional(),
10019
+ recallByLight: record(string(), number().nullable()).optional(),
10020
+ fpByCamera: record(string(), number()).optional(),
10021
+ smallFound: number().int().optional(),
10022
+ smallTotal: number().int().optional()
10023
+ }).passthrough();
10024
+ var TrainingEvalReportSchema = object({
10025
+ frames: number().int(),
10026
+ classes: record(string(), TrainingEvalClassSchema)
10027
+ }).passthrough();
10028
+ /**
10029
+ * A succeeded result carries every block; a failed one carries the error and
10030
+ * whatever was known by then — the other blocks are ABSENT, not null. The
10031
+ * orchestrator checks the blocks it needs before it trusts a success.
10032
+ */
10033
+ var TrainingResultSchema = object({
10034
+ schema: literal(TRAINING_RESULT_SCHEMA),
10035
+ jobKey: string(),
10036
+ status: _enum(["succeeded", "failed"]),
10037
+ error: object({
10038
+ stage: string(),
10039
+ code: string(),
10040
+ message: string()
10041
+ }).nullable(),
10042
+ trainer: object({
10043
+ version: string(),
10044
+ revision: string()
10045
+ }),
10046
+ toolchain: record(string(), string().nullable()),
10047
+ dataset: object({
10048
+ versionId: string(),
10049
+ annotationHash: string(),
10050
+ sha256: string(),
10051
+ frames: object({
10052
+ train: number().int(),
10053
+ val: number().int(),
10054
+ holdout: number().int()
10055
+ }),
10056
+ holdoutCameras: array(number().int()),
10057
+ replayImages: number().int()
10058
+ }).optional(),
10059
+ training: object({
10060
+ epochsRun: number().int(),
10061
+ bestEpoch: number().int(),
10062
+ bestMap50: number(),
10063
+ bestMap50_95: number(),
10064
+ seconds: number()
10065
+ }).optional(),
10066
+ evaluation: object({
10067
+ holdoutFrames: number().int(),
10068
+ baseline: TrainingEvalReportSchema.nullable(),
10069
+ candidate: TrainingEvalReportSchema.nullable(),
10070
+ candidateInt8: TrainingEvalReportSchema.nullable(),
10071
+ recallDeltaByCamera: record(string(), record(string(), number())).nullable(),
10072
+ map50: record(string(), number().nullable())
10073
+ }).optional(),
10074
+ floors: object({
10075
+ baseline: FloorsSchema,
10076
+ candidate: FloorsSchema,
10077
+ candidateInt8: FloorsSchema.nullable(),
10078
+ notes: array(string())
10079
+ }).optional(),
10080
+ int8: object({
10081
+ kept: boolean(),
10082
+ map50Fp16: number().nullable(),
10083
+ map50Int8: number().nullable(),
10084
+ reason: string().nullable()
10085
+ }).optional(),
10086
+ exportsDropped: array(object({
10087
+ export: string(),
10088
+ reason: string()
10089
+ })).optional(),
10090
+ files: array(TrainingResultFileSchema).optional(),
10091
+ bundle: object({
10092
+ path: literal("bundle.tar"),
10093
+ bytes: number().int().nonnegative(),
10094
+ sha256: string().regex(/^[0-9a-f]{64}$/)
10095
+ }).nullable().optional(),
10096
+ catalogDraft: object({
10097
+ base: TrainingCatalogDraftSchema,
10098
+ int8: TrainingCatalogDraftSchema.nullable()
10099
+ }).nullable().optional(),
10100
+ licence: string()
10101
+ });
10102
+ var TrainingStageSchema = _enum([
10103
+ "prepare",
10104
+ "replay",
10105
+ "train",
10106
+ "eval",
10107
+ "export",
10108
+ "package"
10109
+ ]);
10110
+ var EventBase = {
10111
+ v: literal(1),
10112
+ ts: number()
10113
+ };
10114
+ discriminatedUnion("type", [
10115
+ object({
10116
+ ...EventBase,
10117
+ type: literal("stage"),
10118
+ stage: TrainingStageSchema
10119
+ }),
10120
+ object({
10121
+ ...EventBase,
10122
+ type: literal("epoch"),
10123
+ epoch: number().int(),
10124
+ epochs: number().int(),
10125
+ boxLoss: number().nullable().optional(),
10126
+ map50: number().nullable().optional(),
10127
+ map50_95: number().nullable().optional(),
10128
+ etaSec: number().nullable().optional()
10129
+ }),
10130
+ object({
10131
+ ...EventBase,
10132
+ type: literal("metric"),
10133
+ name: string(),
10134
+ value: number()
10135
+ }),
10136
+ object({
10137
+ ...EventBase,
10138
+ type: literal("artifact"),
10139
+ path: string(),
10140
+ bytes: number(),
10141
+ sha256: string()
10142
+ }),
10143
+ object({
10144
+ ...EventBase,
10145
+ type: literal("done"),
10146
+ status: _enum(["succeeded", "failed"]),
10147
+ resultSha256: string().nullable().optional()
10148
+ }),
10149
+ object({
10150
+ ...EventBase,
10151
+ type: literal("error"),
10152
+ stage: string(),
10153
+ code: string(),
10154
+ message: string()
10155
+ })
10156
+ ]);
10157
+ /**
9463
10158
  * What the gate decided about a birth, from the CALLER's point of view.
9464
10159
  *
9465
10160
  * Deliberately not `ConfirmationVerdict`: `undecided` is not a birth decision
@@ -11787,7 +12482,9 @@ var AddonHttpRouteSchema = object({
11787
12482
  "authenticated",
11788
12483
  "admin"
11789
12484
  ]).optional(),
11790
- description: string().optional()
12485
+ description: string().optional(),
12486
+ /** The hub limits this route per client address before the handler runs. */
12487
+ rateLimit: _enum(["auth"]).optional()
11791
12488
  });
11792
12489
  /**
11793
12490
  * Cross-process route invocation envelope. The hub captures the
@@ -12492,6 +13189,37 @@ var BackupDestinationInfoSchema = object({
12492
13189
  lastError: string().optional()
12493
13190
  });
12494
13191
  /**
13192
+ * How an archive is encrypted (operator decision 2026-10-09): to a backup
13193
+ * PUBLIC key the hub holds, so only the operator's secret key opens it.
13194
+ * Absent on a plain `.tar.gz` — every archive made before encryption, or
13195
+ * with it off — which restores without a key.
13196
+ */
13197
+ var BackupArchiveEncryptionSchema = object({
13198
+ /** `x25519-hkdf-aes256gcm-stream-v1`. */
13199
+ scheme: string(),
13200
+ /** 16 hex — the backup key whose secret restores this archive. */
13201
+ keyId: string()
13202
+ });
13203
+ /**
13204
+ * The backup encryption setting. The hub keeps PUBLIC keys only: the active
13205
+ * one new archives are encrypted to, and the retired ones older archives
13206
+ * still need. The secret key is shown once, at `setupEncryption`.
13207
+ */
13208
+ var BackupEncryptionStatusSchema = object({
13209
+ enabled: boolean(),
13210
+ active: object({
13211
+ keyId: string(),
13212
+ publicKey: string(),
13213
+ createdAt: number()
13214
+ }).nullable(),
13215
+ /** Every key ever set up, newest first. */
13216
+ keys: array(object({
13217
+ keyId: string(),
13218
+ createdAt: number(),
13219
+ retiredAt: number().nullable()
13220
+ })).readonly()
13221
+ });
13222
+ /**
12495
13223
  * Per-archive entry returned by `backup.listArchives({ destinationId })`.
12496
13224
  * Same shape the destination drill-in renders. Sourced from the per-
12497
13225
  * location `manifests.json` (no per-archive tarball read required).
@@ -12503,7 +13231,9 @@ var BackupArchiveEntrySchema = object({
12503
13231
  sizeBytes: number(),
12504
13232
  label: string().optional(),
12505
13233
  /** Top-level locations included in the archive (db, addons, tls, …). */
12506
- locations: array(string()).readonly()
13234
+ locations: array(string()).readonly(),
13235
+ /** Present when the archive is encrypted; restore then needs that key. */
13236
+ encryption: BackupArchiveEncryptionSchema.optional()
12507
13237
  });
12508
13238
  var BackupEntrySchema = object({
12509
13239
  id: string(),
@@ -12512,7 +13242,8 @@ var BackupEntrySchema = object({
12512
13242
  label: string().optional(),
12513
13243
  createdAt: number(),
12514
13244
  sizeBytes: number(),
12515
- locations: array(string()).optional()
13245
+ locations: array(string()).optional(),
13246
+ encryption: BackupArchiveEncryptionSchema.optional()
12516
13247
  });
12517
13248
  var ArchiveEntrySchema = object({
12518
13249
  path: string(),
@@ -12701,10 +13432,40 @@ method(_void(), array(BackupDestinationInfoSchema).readonly(), { auth: "admin" }
12701
13432
  * this list and skips entries whose path doesn't start with
12702
13433
  * any of them.
12703
13434
  */
12704
- locations: array(string()).optional()
13435
+ locations: array(string()).optional(),
13436
+ /**
13437
+ * The backup SECRET key, for an encrypted archive (ignored for a plain
13438
+ * one). The archive is decrypted into the hub's private staging
13439
+ * before the restart; the key is not stored. A wrong or missing key
13440
+ * is refused before the archive is downloaded.
13441
+ */
13442
+ backupSecretKey: string().optional()
12705
13443
  }), _void(), {
12706
13444
  kind: "mutation",
12707
13445
  auth: "admin"
13446
+ }), method(_void(), BackupEncryptionStatusSchema, { auth: "admin" }), method(object({}), object({
13447
+ keyId: string(),
13448
+ secretKey: string(),
13449
+ publicKey: string(),
13450
+ createdAt: number(),
13451
+ replacedKeyId: string().nullable()
13452
+ }), {
13453
+ kind: "mutation",
13454
+ auth: "admin"
13455
+ }), method(object({}), object({ disabledKeyId: string().nullable() }), {
13456
+ kind: "mutation",
13457
+ auth: "admin"
13458
+ }), method(object({ backupSecretKey: string() }), object({
13459
+ valid: boolean(),
13460
+ keyId: string().nullable(),
13461
+ /** The hub knows this key (active or retired). */
13462
+ known: boolean(),
13463
+ /** It is the key new archives are encrypted to. */
13464
+ active: boolean(),
13465
+ error: string().optional()
13466
+ }), {
13467
+ kind: "mutation",
13468
+ auth: "admin"
12708
13469
  }), method(object({
12709
13470
  destinationId: string(),
12710
13471
  backupId: string()
@@ -14479,7 +15240,60 @@ var CustomModelDescriptorSchema = object({
14479
15240
  stepId: string(),
14480
15241
  entry: ModelCatalogEntrySchema
14481
15242
  });
14482
- method(_void(), array(CustomModelDescriptorSchema).readonly(), { auth: "admin" });
15243
+ /** One regular file of an imported bundle, as the producer measured it. */
15244
+ var ModelBundleFileSchema = object({
15245
+ /** Relative path inside the bundle tar; an mlpackage member is `<x>.mlpackage/<member>`. */
15246
+ path: string().min(1),
15247
+ bytes: number().int().nonnegative(),
15248
+ sha256: string().regex(/^[0-9a-f]{64}$/)
15249
+ });
15250
+ var ImportModelBundleInputSchema = object({
15251
+ /** The registry provider that keeps the model (Model Studio). */
15252
+ addonId: string(),
15253
+ stepId: string().min(1),
15254
+ /**
15255
+ * The catalog rows to register, complete, every format URL already
15256
+ * `camstack-local://<modelId>/<file>` naming a file of the bundle. One
15257
+ * bundle may carry several rows (a base and its INT8 variant).
15258
+ */
15259
+ entries: array(ModelCatalogEntrySchema).min(1).max(4),
15260
+ /** The bundle tar, offered by the producer over `ctx.peerBytes` (same host). */
15261
+ bundle: object({
15262
+ ticket: PeerBytesTicketSchema,
15263
+ bytes: number().int().positive(),
15264
+ sha256: string().regex(/^[0-9a-f]{64}$/)
15265
+ }),
15266
+ /** Every file the tar must hold; anything missing, extra or different is refused. */
15267
+ files: array(ModelBundleFileSchema).min(1).max(64),
15268
+ /** Convert missing engine formats and push the model to every agent afterwards. */
15269
+ distribute: boolean()
15270
+ });
15271
+ var ImportModelBundleResultSchema = discriminatedUnion("kind", [object({
15272
+ kind: literal("imported"),
15273
+ modelIds: array(string()).readonly(),
15274
+ distributed: array(object({
15275
+ modelId: string(),
15276
+ nodeId: string(),
15277
+ format: _enum(MODEL_FORMATS),
15278
+ ok: boolean(),
15279
+ error: string().optional()
15280
+ })).readonly()
15281
+ }), object({
15282
+ kind: literal("refused"),
15283
+ reason: _enum([
15284
+ "transfer-failed",
15285
+ "checksum-mismatch",
15286
+ "bundle-mismatch",
15287
+ "invalid-entry",
15288
+ "id-taken"
15289
+ ]),
15290
+ detail: string()
15291
+ })]);
15292
+ method(_void(), array(CustomModelDescriptorSchema).readonly(), { auth: "admin" }), method(ImportModelBundleInputSchema, ImportModelBundleResultSchema, {
15293
+ kind: "mutation",
15294
+ auth: "admin",
15295
+ timeoutMs: 30 * 6e4
15296
+ });
14483
15297
  /**
14484
15298
  * Query filter for settings-store collections.
14485
15299
  */
@@ -14958,6 +15772,35 @@ var KeychainKeySourceSchema = object({
14958
15772
  */
14959
15773
  sharesBackupWithDatabase: boolean()
14960
15774
  });
15775
+ /**
15776
+ * One keychain reset, as the Secrets page reports it until the operator
15777
+ * acknowledges it. Never a value: refs, counts and table names only.
15778
+ */
15779
+ var KeychainResetRecordSchema = object({
15780
+ id: string(),
15781
+ at: number(),
15782
+ /** `user:<id>` or {@link KEYCHAIN_RESET_TRIGGER_ACTOR}. */
15783
+ actor: string(),
15784
+ /** Why the keychain was locked when it was reset; `null` when it was not locked. */
15785
+ lockedReason: string().nullable(),
15786
+ /** Values moved into the archive table (ciphertext under the lost key). */
15787
+ archived: number().int(),
15788
+ /** `keychain:secrets-orphaned-<ts>`, or `null` when nothing was stored. */
15789
+ archivedCollection: string().nullable(),
15790
+ /**
15791
+ * `keychain:keys-orphaned-<ts>`: the wrapped data keys of the archive, kept
15792
+ * so the archive can still be opened if the lost master key turns up.
15793
+ */
15794
+ archivedKeysCollection: string().nullable(),
15795
+ /**
15796
+ * `system-settings` keys whose marker the reset cleared — the cluster
15797
+ * secret's: a marker left pointing at an archived value would refuse every
15798
+ * agent forever (D797).
15799
+ */
15800
+ clearedSettingsKeys: array(string()).readonly(),
15801
+ /** When an operator dismissed the notice on the Secrets page; `null` until then. */
15802
+ acknowledgedAt: number().nullable()
15803
+ });
14961
15804
  var KeychainStatusSchema = object({
14962
15805
  keychain: KeychainStateSchema,
14963
15806
  /** The source of the master key in use; `null` while locked. */
@@ -14975,7 +15818,9 @@ var KeychainStatusSchema = object({
14975
15818
  /** Wrapped copies of the data key under a previous master key, kept until purged. */
14976
15819
  retiredWraps: number().int(),
14977
15820
  recoveryKeyDownloadedAt: number().nullable(),
14978
- secretCount: number().int()
15821
+ secretCount: number().int(),
15822
+ /** The most recent reset, acknowledged or not; `null` when the keychain was never reset. */
15823
+ lastReset: KeychainResetRecordSchema.nullable()
14979
15824
  });
14980
15825
  /**
14981
15826
  * Whether a stored value is still pointed at by its owner's settings.
@@ -14997,17 +15842,26 @@ var KeychainAuditActionSchema = _enum([
14997
15842
  "download-recovery-key",
14998
15843
  "delete-orphans",
14999
15844
  "reset",
15845
+ "acknowledge-reset",
15000
15846
  "initialize"
15001
15847
  ]);
15002
15848
  var KeychainAuditEntrySchema = object({
15003
15849
  id: string(),
15004
15850
  at: number(),
15005
15851
  action: KeychainAuditActionSchema,
15006
- /** `addon:<id>` | `user:<id>` | `system`. */
15852
+ /** `addon:<id>` | `user:<id>` | `system` | `trigger-file`. */
15007
15853
  actor: string(),
15008
15854
  ref: string().nullable(),
15009
15855
  detail: string().nullable()
15010
15856
  });
15857
+ var KEYCHAIN_RESET_CONFIRMATION = "RESET KEYCHAIN";
15858
+ /**
15859
+ * Secrets the HUB itself holds (owner `system`) that no settings form shows:
15860
+ * `jwt-signing-key` — the session signing key (D797). It is always "in use",
15861
+ * never an orphan; it is generated on a fresh hub and replaced only through
15862
+ * {@link keychainAdminCapability.methods.setSystemSecret}.
15863
+ */
15864
+ var SystemHeldSecretNameSchema = _enum(["jwt-signing-key"]);
15011
15865
  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({
15012
15866
  value: string(),
15013
15867
  version: number().int()
@@ -15015,6 +15869,16 @@ method(object({}), KeychainStatusSchema, { auth: "admin" }), method(object({}),
15015
15869
  kind: "mutation",
15016
15870
  auth: "admin",
15017
15871
  caller: "required"
15872
+ }), method(object({
15873
+ name: SystemHeldSecretNameSchema,
15874
+ value: string().min(16)
15875
+ }), object({
15876
+ ref: string(),
15877
+ version: number().int()
15878
+ }), {
15879
+ kind: "mutation",
15880
+ auth: "admin",
15881
+ caller: "required"
15018
15882
  }), method(object({ refs: array(string().min(1)).max(1e3) }), object({
15019
15883
  deleted: array(string()).readonly(),
15020
15884
  kept: array(object({
@@ -15044,13 +15908,20 @@ method(object({}), KeychainStatusSchema, { auth: "admin" }), method(object({}),
15044
15908
  kind: "mutation",
15045
15909
  auth: "admin",
15046
15910
  caller: "required"
15047
- }), method(object({ confirm: literal("RESET KEYCHAIN") }), object({
15911
+ }), method(object({ confirm: literal(KEYCHAIN_RESET_CONFIRMATION) }), object({
15048
15912
  archivedCollection: string().nullable(),
15049
15913
  archived: number().int()
15050
15914
  }), {
15051
15915
  kind: "mutation",
15052
15916
  auth: "admin",
15053
15917
  caller: "required"
15918
+ }), method(object({}), object({
15919
+ reset: KeychainResetRecordSchema.nullable(),
15920
+ pendingReentry: array(KeychainSecretMetaSchema).readonly()
15921
+ }), { auth: "admin" }), method(object({}), object({ acknowledged: boolean() }), {
15922
+ kind: "mutation",
15923
+ auth: "admin",
15924
+ caller: "required"
15054
15925
  });
15055
15926
  method(_void(), object({
15056
15927
  id: string(),
@@ -18014,7 +18885,7 @@ method(LogEntrySchema, _void(), { kind: "mutation" }), method(object({
18014
18885
  * `login-method` — collection cap through which auth addons contribute
18015
18886
  * their pre-auth login surfaces to the login page. This is the SINGLE,
18016
18887
  * generic mechanism that supersedes the dead `auth.listProviders` reader:
18017
- * every auth addon (OIDC, magic-link, WebAuthn/passkey) registers a
18888
+ * every auth addon (OIDC, WebAuthn/passkey) registers a
18018
18889
  * `login-method` provider and the PUBLIC `auth.listLoginMethods`
18019
18890
  * procedure aggregates them for the unauthenticated login page.
18020
18891
  *
@@ -18022,8 +18893,7 @@ method(LogEntrySchema, _void(), { kind: "mutation" }), method(object({
18022
18893
  *
18023
18894
  * - `redirect` — a declarative button. The login page renders a generic
18024
18895
  * button that navigates to `startUrl` (an addon-owned HTTP route).
18025
- * Covers OIDC (`/addon/auth-oidc/<id>/start`) and magic-link with
18026
- * ZERO shell-side JS. A future SSO addon plugs in the same way — the
18896
+ * Covers OIDC (`/addon/auth-oidc/<id>/start`) with ZERO shell-side JS. A future SSO addon plugs in the same way — the
18027
18897
  * login page needs NO change.
18028
18898
  *
18029
18899
  * - `widget` — a Module-Federation widget the login page mounts (via
@@ -18042,8 +18912,8 @@ method(LogEntrySchema, _void(), { kind: "mutation" }), method(object({
18042
18912
  * decision.
18043
18913
  *
18044
18914
  * Every contribution carries a `stage`:
18045
- * - `primary` — shown on the first credentials screen (OIDC /
18046
- * magic-link buttons; a future usernameless passkey).
18915
+ * - `primary` — shown on the first credentials screen (OIDC
18916
+ * buttons; a usernameless passkey).
18047
18917
  * - `second-factor` — shown AFTER the password leg, gated on the
18048
18918
  * returned `factors` (passkey-as-2FA today).
18049
18919
  *
@@ -18070,7 +18940,7 @@ var LoginMethodContributionSchema = discriminatedUnion("kind", [
18070
18940
  * The provider names an external identity a signed-in user can link to
18071
18941
  * their own account (D782): `auth.listLinkableProviders` /
18072
18942
  * `beginExternalLink` offer exactly the redirect methods that set this,
18073
- * whatever their id. Absent / false — a login button only (magic-link).
18943
+ * whatever their id. Absent / false — a login button only.
18074
18944
  */
18075
18945
  linkable: boolean().optional()
18076
18946
  }),
@@ -21925,8 +22795,7 @@ method(object({}), object({ rules: array(NcRuleSchema) }), { auth: "admin" }), m
21925
22795
  * `super_admin` — collapsed onto the single boolean because every
21926
22796
  * non-admin caller is governed by the same scope-check rules; the
21927
22797
  * distinction was only ever used to route role-specific procedures
21928
- * which we no longer have. Agents are admin sessions issued via
21929
- * `createServiceToken`; CLI / webhook integrations are `cst_*` tokens
22798
+ * which we no longer have. CLI / webhook integrations are `cst_*` tokens
21930
22799
  * with `isAdmin: false` + an explicit scope list.
21931
22800
  */
21932
22801
  /** Per-method access flavour. Materialised on every cap method via codegen. */
@@ -23601,6 +24470,9 @@ var RetrainExportFilterSchema = object({
23601
24470
  frameIds: array(string()).max(2e4).optional(),
23602
24471
  /** Only frames in at least one of these named collections. */
23603
24472
  collectionIds: array(string()).max(200).optional(),
24473
+ /** Exactly the frames of this dataset version (and its completeOnly). An
24474
+ * unknown id selects nothing. */
24475
+ datasetVersionId: string().optional(),
23604
24476
  batchId: string().optional(),
23605
24477
  /** Only frames the operator marked complete (all subjects boxed). */
23606
24478
  completeOnly: boolean().optional()
@@ -23768,6 +24640,67 @@ var RetrainLlmAssistResultSchema = discriminatedUnion("kind", [object({
23768
24640
  ]),
23769
24641
  detail: string().optional()
23770
24642
  })]);
24643
+ /** What a dataset version is cut from. Every field narrows. */
24644
+ var RetrainDatasetSelectionSchema = object({
24645
+ deviceIds: array(number()).readonly().optional(),
24646
+ collectionIds: array(string()).max(200).readonly().optional(),
24647
+ frameIds: array(string()).max(2e4).readonly().optional()
24648
+ });
24649
+ /** The counts a dataset is judged by. */
24650
+ var RetrainDatasetStatsSchema = object({
24651
+ frames: number().int(),
24652
+ completeFrames: number().int(),
24653
+ /** `completeFrames / frames`, 0..1. */
24654
+ completeness: number(),
24655
+ /** Boxes to learn (model errors excluded). */
24656
+ subjects: number().int(),
24657
+ modelErrors: number().int(),
24658
+ /** Complete frames with no subject. */
24659
+ hardNegatives: number().int(),
24660
+ /** Subjects per class × camera × day/night. */
24661
+ cells: array(object({
24662
+ macroClass: string(),
24663
+ deviceId: number(),
24664
+ lighting: _enum([
24665
+ "day",
24666
+ "night",
24667
+ "unknown"
24668
+ ]),
24669
+ subjects: number().int(),
24670
+ frames: number().int()
24671
+ })).readonly(),
24672
+ cameras: array(object({
24673
+ deviceId: number(),
24674
+ frames: number().int(),
24675
+ completeFrames: number().int()
24676
+ })).readonly()
24677
+ });
24678
+ /** An immutable dataset version, without its frame list. */
24679
+ var RetrainDatasetVersionSchema = object({
24680
+ id: string(),
24681
+ name: string(),
24682
+ createdAt: number(),
24683
+ selection: RetrainDatasetSelectionSchema,
24684
+ layout: RetrainExportLayoutSchema,
24685
+ completeOnly: boolean(),
24686
+ frameCount: number().int(),
24687
+ /** sha256 of what the frames taught when the version was frozen. */
24688
+ annotationHash: string(),
24689
+ /** The export manifest schema the version was cut under. */
24690
+ manifestSchema: string(),
24691
+ stats: RetrainDatasetStatsSchema
24692
+ });
24693
+ var CreateRetrainDatasetVersionResultSchema = discriminatedUnion("kind", [object({
24694
+ kind: literal("created"),
24695
+ version: RetrainDatasetVersionSchema
24696
+ }), object({
24697
+ kind: literal("refused"),
24698
+ reason: _enum([
24699
+ "empty-name",
24700
+ "duplicate-name",
24701
+ "no-frames"
24702
+ ])
24703
+ })]);
23771
24704
  /** The outcome of a lifecycle move owned by the retrain page. */
23772
24705
  var RetrainTransitionResultSchema = object({
23773
24706
  trackId: string(),
@@ -24557,6 +25490,47 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
24557
25490
  kind: "mutation",
24558
25491
  auth: "admin",
24559
25492
  timeoutMs: 60 * 6e4
25493
+ }), method(object({
25494
+ filter: RetrainExportFilterSchema,
25495
+ layout: RetrainExportLayoutSchema
25496
+ }), object({
25497
+ ticket: PeerBytesTicketSchema,
25498
+ frames: number().int(),
25499
+ annotations: number().int()
25500
+ }), {
25501
+ kind: "mutation",
25502
+ auth: "admin",
25503
+ timeoutMs: 12e4
25504
+ }), method(object({
25505
+ selection: RetrainDatasetSelectionSchema,
25506
+ completeOnly: boolean().optional()
25507
+ }), RetrainDatasetStatsSchema, {
25508
+ kind: "query",
25509
+ auth: "admin"
25510
+ }), method(object({
25511
+ name: string().max(120),
25512
+ selection: RetrainDatasetSelectionSchema,
25513
+ layout: RetrainExportLayoutSchema,
25514
+ completeOnly: boolean()
25515
+ }), CreateRetrainDatasetVersionResultSchema, {
25516
+ kind: "mutation",
25517
+ auth: "admin",
25518
+ timeoutMs: 12e4
25519
+ }), method(object({}), array(RetrainDatasetVersionSchema).readonly(), {
25520
+ kind: "query",
25521
+ auth: "admin"
25522
+ }), method(object({ id: string() }), object({ deleted: boolean() }), {
25523
+ kind: "mutation",
25524
+ auth: "admin"
25525
+ }), method(object({ id: string() }), object({
25526
+ found: boolean(),
25527
+ annotationHash: string(),
25528
+ matches: boolean(),
25529
+ missingFrames: number().int()
25530
+ }), {
25531
+ kind: "query",
25532
+ auth: "admin",
25533
+ timeoutMs: 12e4
24560
25534
  }), method(object({}), array(RetrainAssistProfileSchema).readonly(), {
24561
25535
  kind: "query",
24562
25536
  auth: "admin"
@@ -25199,11 +26173,14 @@ var HardwareClassIdSchema = _enum([
25199
26173
  "intel-n-series",
25200
26174
  "apple-m-base",
25201
26175
  "apple-m-pro",
26176
+ "amd-phoenix",
25202
26177
  "unknown"
25203
26178
  ]);
25204
26179
  var AcceleratorKindSchema = _enum([
25205
26180
  "intel-npu",
25206
26181
  "intel-igpu",
26182
+ "amd-igpu",
26183
+ "amd-npu",
25207
26184
  "x86-cpu",
25208
26185
  "arm-cpu",
25209
26186
  "apple-ane",
@@ -28135,8 +29112,8 @@ version: string().optional() }), ServerUpdateActionResultSchema, {
28135
29112
  * `smtp-provider` — pluggable email delivery surface.
28136
29113
  *
28137
29114
  * Collection cap: a deployment may install multiple SMTP relays (e.g.
28138
- * one for transactional / one for notifications). Consumers (magic-link,
28139
- * notifier addons, …) walk the collection and pick the first
29115
+ * one for transactional / one for notifications). Consumers (notifier
29116
+ * addons, …) walk the collection and pick the first
28140
29117
  * ready provider OR target a specific addonId.
28141
29118
  *
28142
29119
  * The shape stays small on purpose — `sendEmail` is enough for the
@@ -28315,7 +29292,7 @@ targets: array(object({
28315
29292
  })));
28316
29293
  /**
28317
29294
  * `sso-bridge` — internal hub-only cap that lets SSO-style auth
28318
- * providers (OIDC, SAML, magic-link, …) mint an HMAC-signed token
29295
+ * providers (OIDC, SAML, …) mint an HMAC-signed token
28319
29296
  * carrying the post-callback claims before redirecting back to
28320
29297
  * `/api/auth/sso/finish`.
28321
29298
  *
@@ -28378,7 +29355,14 @@ var SsoBridgeClaimsSchema = object({
28378
29355
  * Verified `iss` of the id_token behind an OIDC login bridge (D782). A
28379
29356
  * subject is unique only per issuer, so a link is bound to it.
28380
29357
  */
28381
- issuer: string().optional()
29358
+ issuer: string().optional(),
29359
+ /**
29360
+ * SHA-256 (hex) of the `camstack_sso_state` cookie the IdP `/start` set in
29361
+ * the browser that began this sign-in. `/api/auth/sso/finish` requires the
29362
+ * request to present the matching cookie — a login bridge is useless in
29363
+ * any other browser.
29364
+ */
29365
+ browserBinding: string().optional()
28382
29366
  });
28383
29367
  method(object({
28384
29368
  claims: SsoBridgeClaimsSchema,
@@ -35814,7 +36798,13 @@ var TopologyNodeSchema = object({
35814
36798
  })).readonly(),
35815
36799
  processes: array(TopologyProcessSchema).readonly(),
35816
36800
  categories: array(TopologyCategorySchema).readonly(),
35817
- rootPackage: TopologyRootPackageSchema.nullable()
36801
+ rootPackage: TopologyRootPackageSchema.nullable(),
36802
+ /**
36803
+ * How an online AGENT reaches the hub (mesh mTLS Release A): `tls` once it has
36804
+ * completed a mutual-TLS handshake, `clear` otherwise. Absent for the hub,
36805
+ * for offline rows and when the hub cannot tell.
36806
+ */
36807
+ meshTransport: _enum(["tls", "clear"]).optional()
35818
36808
  });
35819
36809
  var CapUsageEdgeSchema = object({
35820
36810
  callerAddonId: string(),
@@ -36784,7 +37774,15 @@ var GpuInfoSchema = object({
36784
37774
  name: string(),
36785
37775
  memoryMB: number().optional()
36786
37776
  });
36787
- var NpuInfoSchema = object({ type: _enum(["apple-ane", "intel-npu"]) });
37777
+ var NpuInfoSchema = object({
37778
+ type: _enum([
37779
+ "apple-ane",
37780
+ "intel-npu",
37781
+ "amd-xdna"
37782
+ ]),
37783
+ name: string().optional(),
37784
+ generation: _enum(["xdna1", "xdna2"]).optional()
37785
+ });
36788
37786
  var CoralInfoSchema = object({
36789
37787
  type: literal("coral-edgetpu"),
36790
37788
  bus: string().optional()
@@ -40637,16 +41635,6 @@ var ApiKeySummarySchema = object({
40637
41635
  createdAt: number(),
40638
41636
  lastUsedAt: number().optional()
40639
41637
  });
40640
- var CreateApiKeyInputSchema = object({
40641
- label: string(),
40642
- isAdmin: boolean().default(false),
40643
- allowedProviders: union([array(string()), literal("*")]).optional(),
40644
- allowedDevices: record(string(), union([array(string()), literal("*")])).optional()
40645
- });
40646
- var CreateApiKeyResultSchema = object({
40647
- token: string(),
40648
- record: ApiKeySummarySchema
40649
- });
40650
41638
  var ScopedTokenSummarySchema = object({
40651
41639
  id: string(),
40652
41640
  userId: string(),
@@ -40745,17 +41733,10 @@ method(_void(), array(UserSummarySchema), { auth: "admin" }), method(CreateUserI
40745
41733
  }), UserSummarySchema.extend({ passwordHash: string() }).nullable(), {
40746
41734
  kind: "mutation",
40747
41735
  access: "view"
40748
- }), method(_void(), array(ApiKeySummarySchema), { auth: "admin" }), method(CreateApiKeyInputSchema, CreateApiKeyResultSchema, {
40749
- kind: "mutation",
40750
- auth: "admin",
40751
- access: "create"
40752
- }), method(object({ id: string() }), object({ success: literal(true) }), {
41736
+ }), method(_void(), array(ApiKeySummarySchema), { auth: "admin" }), method(object({ id: string() }), object({ success: literal(true) }), {
40753
41737
  kind: "mutation",
40754
41738
  auth: "admin",
40755
41739
  access: "delete"
40756
- }), method(object({ token: string() }), ApiKeySummarySchema.nullable(), {
40757
- kind: "mutation",
40758
- access: "view"
40759
41740
  }), method(CreateScopedTokenInputSchema, CreateScopedTokenResultSchema, {
40760
41741
  kind: "mutation",
40761
41742
  auth: "admin",
@@ -40829,15 +41810,7 @@ method(_void(), array(UserSummarySchema), { auth: "admin" }), method(CreateUserI
40829
41810
  }).nullable(), { access: "view" }), method(object({ userId: string() }), array(ExternalIdentitySchema), { auth: "admin" }), method(ExternalIdentityKeySchema, object({
40830
41811
  userId: string(),
40831
41812
  issuer: string()
40832
- }).nullable(), { auth: "admin" }), method(ExternalIdentityKeySchema.extend({
40833
- userId: string(),
40834
- issuer: string().min(1),
40835
- label: string().optional()
40836
- }), object({ success: literal(true) }), {
40837
- kind: "mutation",
40838
- auth: "admin",
40839
- access: "create"
40840
- }), method(ExternalIdentityKeySchema.extend({ userId: string() }), object({ success: boolean() }), {
41813
+ }).nullable(), { auth: "admin" }), method(ExternalIdentityKeySchema.extend({ userId: string() }), object({ success: boolean() }), {
40841
41814
  kind: "mutation",
40842
41815
  auth: "admin",
40843
41816
  access: "delete"
@@ -41542,6 +42515,451 @@ var zoneRulesCapability = {
41542
42515
  */
41543
42516
  durability: "restored"
41544
42517
  };
42518
+ /**
42519
+ * `training-provider` — ONE cloud that can run the CamStack trainer.
42520
+ *
42521
+ * A thin, mockable translation layer: it knows how to run a container with a
42522
+ * GPU, move a dataset in, read the job's stdout and hand artefacts back. It
42523
+ * knows nothing about datasets, splits, floors, cost policy or Model Studio —
42524
+ * those are the `training` orchestrator's (D805). Every rule written there
42525
+ * once is what makes a second provider (RunPod, a local NVIDIA node) a new
42526
+ * manifest entry and nothing else.
42527
+ *
42528
+ * Collection, routed by the `addonId` in every single-row input (the `llm` /
42529
+ * `notification-output` posture); `describe` concat-fans across providers.
42530
+ * Every method is `admin`: these spend money.
42531
+ *
42532
+ * Every cloud object a provider creates is tagged with the orchestrator's
42533
+ * `jobKey`, so a retried submit finds the job it already started instead of
42534
+ * starting a second GPU, and `listJobs` can find orphans.
42535
+ *
42536
+ * Bytes never ride a cap field: the dataset arrives as a `ctx.peerBytes`
42537
+ * ticket the producer (pipeline-analytics) minted, and artefacts leave as a
42538
+ * ticket the provider mints (D613).
42539
+ */
42540
+ var TrainingGpuOptionSchema = object({
42541
+ id: string(),
42542
+ label: string(),
42543
+ /** List price, USD per GPU-hour, before any region multiplier. */
42544
+ usdPerHour: number().nonnegative(),
42545
+ vramGb: number().nonnegative()
42546
+ });
42547
+ var TrainingRegionOptionSchema = object({
42548
+ /** `''` = any region (the provider's choice). */
42549
+ id: string(),
42550
+ label: string(),
42551
+ priceMultiplier: number().positive()
42552
+ });
42553
+ /**
42554
+ * The provider's per-account settings, as the orchestrator reads them. They
42555
+ * live in the PROVIDER addon's settings (operator decision 2026-10-08: they
42556
+ * depend on the user's account), never hard-coded in the orchestrator.
42557
+ */
42558
+ var TrainingProviderDefaultsSchema = object({
42559
+ gpuType: string(),
42560
+ region: string(),
42561
+ costCapUsd: number().nonnegative(),
42562
+ maxRuntimeSec: number().int().positive(),
42563
+ /** Hours a FAILED job's cloud dataset is kept for debugging; 0 = delete at once. */
42564
+ failedDatasetGraceHours: number().nonnegative()
42565
+ });
42566
+ var TrainingProviderDescriptorSchema = object({
42567
+ addonId: string(),
42568
+ /** `modal`, `runpod`, `fake`, … */
42569
+ kind: string(),
42570
+ label: string(),
42571
+ gpuTypes: array(TrainingGpuOptionSchema).readonly(),
42572
+ regions: array(TrainingRegionOptionSchema).readonly(),
42573
+ maxDatasetBytes: number().int().positive(),
42574
+ maxRuntimeSec: number().int().positive(),
42575
+ freeTierNote: string().optional(),
42576
+ /** Where the data goes, in one sentence the confirm dialog repeats. */
42577
+ dataResidencyNote: string(),
42578
+ /** Credentials are present — never the values. */
42579
+ configured: boolean(),
42580
+ defaults: TrainingProviderDefaultsSchema
42581
+ });
42582
+ var TrainingCredentialCheckSchema = object({
42583
+ ok: boolean(),
42584
+ /** Workspace / account name, when the provider says. */
42585
+ account: string().optional(),
42586
+ reason: _enum([
42587
+ "missing",
42588
+ "invalid",
42589
+ "forbidden",
42590
+ "network",
42591
+ "quota"
42592
+ ]).optional(),
42593
+ detail: string().optional()
42594
+ });
42595
+ var ProviderJobStateSchema = _enum([
42596
+ "pending",
42597
+ "starting",
42598
+ "running",
42599
+ "succeeded",
42600
+ "failed",
42601
+ "cancelled",
42602
+ "lost"
42603
+ ]);
42604
+ var ProviderJobStatusSchema = object({
42605
+ jobKey: string(),
42606
+ providerJobId: string().optional(),
42607
+ state: ProviderJobStateSchema,
42608
+ startedAt: number().optional(),
42609
+ endedAt: number().optional(),
42610
+ exitCode: number().int().optional(),
42611
+ failureReason: string().optional(),
42612
+ gpuType: string(),
42613
+ region: string().optional(),
42614
+ billedSeconds: number().nonnegative(),
42615
+ costUsd: number().nonnegative(),
42616
+ /** True when `costUsd` is runtime × list price, not a billing answer. */
42617
+ costIsEstimate: boolean(),
42618
+ lastFetchedAt: number()
42619
+ });
42620
+ /**
42621
+ * The trainer the job runs, by SOURCE revision: the provider turns it into an
42622
+ * image its own way (Modal builds the published Dockerfile at that revision;
42623
+ * a registry-pull provider maps it to a tag). Recorded on the job and echoed
42624
+ * in `result.json`.
42625
+ */
42626
+ var TrainerSourceRefSchema = object({
42627
+ /** Hugging Face repo id, e.g. `camstack/camstack-trainer`. */
42628
+ repo: string().min(1),
42629
+ /** A commit sha (never a branch) — the job must be reproducible. */
42630
+ revision: string().regex(/^[0-9a-f]{7,64}$/)
42631
+ });
42632
+ var JobRef = {
42633
+ addonId: string(),
42634
+ jobKey: string().uuid()
42635
+ };
42636
+ var TrainingLogLineSchema = object({
42637
+ ts: number(),
42638
+ text: string()
42639
+ });
42640
+ method(object({}), array(TrainingProviderDescriptorSchema).readonly(), { auth: "admin" }), method(object({ addonId: string() }), TrainingCredentialCheckSchema, {
42641
+ kind: "mutation",
42642
+ auth: "admin",
42643
+ timeoutMs: 3e4
42644
+ }), method(object({
42645
+ addonId: string(),
42646
+ gpuType: string(),
42647
+ region: string(),
42648
+ datasetBytes: number().int().nonnegative(),
42649
+ gpuSecondsLow: number().nonnegative(),
42650
+ gpuSecondsHigh: number().nonnegative()
42651
+ }), object({
42652
+ usdLow: number().nonnegative(),
42653
+ usdHigh: number().nonnegative(),
42654
+ notes: array(string()).readonly()
42655
+ }), { auth: "admin" }), method(object({
42656
+ ...JobRef,
42657
+ ticket: PeerBytesTicketSchema
42658
+ }), object({
42659
+ bytes: number().int().nonnegative(),
42660
+ sha256: string()
42661
+ }), {
42662
+ kind: "mutation",
42663
+ auth: "admin",
42664
+ timeoutMs: 120 * 6e4
42665
+ }), method(object({
42666
+ ...JobRef,
42667
+ trainer: TrainerSourceRefSchema,
42668
+ jobSpecJson: string().min(2).max(64e3),
42669
+ gpuType: string(),
42670
+ region: string(),
42671
+ maxRuntimeSec: number().int().positive()
42672
+ }), ProviderJobStatusSchema, {
42673
+ kind: "mutation",
42674
+ auth: "admin",
42675
+ timeoutMs: 30 * 6e4
42676
+ }), method(object(JobRef), ProviderJobStatusSchema, {
42677
+ auth: "admin",
42678
+ timeoutMs: 6e4
42679
+ }), method(object({
42680
+ ...JobRef,
42681
+ cursor: string().optional(),
42682
+ max: number().int().min(1).max(500)
42683
+ }), object({
42684
+ lines: array(TrainingLogLineSchema).readonly(),
42685
+ cursor: string()
42686
+ }), {
42687
+ auth: "admin",
42688
+ timeoutMs: 6e4
42689
+ }), method(object(JobRef), object({ ok: literal(true) }), {
42690
+ kind: "mutation",
42691
+ auth: "admin",
42692
+ timeoutMs: 6e4
42693
+ }), method(object(JobRef), object({
42694
+ found: boolean(),
42695
+ text: string().optional()
42696
+ }), {
42697
+ kind: "mutation",
42698
+ auth: "admin",
42699
+ timeoutMs: 5 * 6e4
42700
+ }), method(object({
42701
+ ...JobRef,
42702
+ path: _enum(["bundle.tar"])
42703
+ }), object({ ticket: PeerBytesTicketSchema }), {
42704
+ kind: "mutation",
42705
+ auth: "admin",
42706
+ timeoutMs: 5 * 6e4
42707
+ }), method(object(JobRef), object({ deleted: array(string()).readonly() }), {
42708
+ kind: "mutation",
42709
+ auth: "admin",
42710
+ timeoutMs: 5 * 6e4
42711
+ }), method(object({ addonId: string() }), array(ProviderJobStatusSchema).readonly(), {
42712
+ auth: "admin",
42713
+ timeoutMs: 2 * 6e4
42714
+ });
42715
+ /**
42716
+ * `training` — the cloud-training orchestrator (D805). Hub-only singleton,
42717
+ * provided by `addon-training`.
42718
+ *
42719
+ * It owns what every provider must agree on, written once:
42720
+ *
42721
+ * - **Dataset versions.** Taken over from pipeline-analytics (D796): the rows
42722
+ * live here (D808); pipeline-analytics still CUTS a version (it owns the corpus and
42723
+ * the export plan) and reaches this store through the five row methods
42724
+ * below, so the Retrain page and the export did not change.
42725
+ * - **Jobs.** A persisted state machine, a reconcile loop against the
42726
+ * provider, a cost guard, a daily orphan sweep and the retention rules.
42727
+ * - **The return flow.** Verified artefacts → Model Studio
42728
+ * (`custom-model-registry.importModelBundle`) → canary on cameras →
42729
+ * rollback. Nothing is ever registered automatically.
42730
+ *
42731
+ * Every method is `admin`.
42732
+ */
42733
+ /** A version WITH its frame list — what the export and a job read. */
42734
+ var TrainingDatasetVersionRowSchema = RetrainDatasetVersionSchema.omit({ frameCount: true }).extend({ frameIds: array(string()).max(2e4).readonly() });
42735
+ /** A base model a detector job can fine-tune, and the baseline it is judged against. */
42736
+ var TrainingBaseModelSchema = object({
42737
+ modelId: string(),
42738
+ label: string(),
42739
+ weights: string(),
42740
+ imgsz: number().int(),
42741
+ baselineOnnxUrl: string(),
42742
+ baselineFloors: record(string(), number()),
42743
+ /** The base the fleet runs most — the UI's default. */
42744
+ recommended: boolean()
42745
+ });
42746
+ var TrainingPresetSchema = _enum([
42747
+ "quick",
42748
+ "standard",
42749
+ "thorough"
42750
+ ]);
42751
+ var TrainingJobRequestSchema = object({
42752
+ datasetVersionId: string().min(1),
42753
+ /** The `training-provider` addon that runs it. */
42754
+ addonId: string().min(1),
42755
+ gpuType: string().min(1),
42756
+ region: string(),
42757
+ baseModelId: string().min(1),
42758
+ preset: TrainingPresetSchema,
42759
+ /** Freeze the backbone's first N layers; `null` = the preset's choice. */
42760
+ freeze: number().int().nonnegative().nullable(),
42761
+ /** Cameras held out whole for evaluation; `null` = the orchestrator's default. */
42762
+ holdoutCameras: array(number().int()).nullable()
42763
+ });
42764
+ var TrainingSplitPlanSchema = object({
42765
+ holdoutCameras: array(number().int()).readonly(),
42766
+ /** Used when no camera is held out: the last N days of every camera. */
42767
+ holdoutLastDays: number().int().nonnegative(),
42768
+ /** Holdout subjects per class (camera holdout only; `null` = known only after the split). */
42769
+ holdoutSupport: record(string(), number().int()).nullable(),
42770
+ trainSubjects: number().int()
42771
+ });
42772
+ var TrainingRefusalReasonSchema = _enum([
42773
+ "unknown-dataset",
42774
+ "unknown-provider",
42775
+ "provider-not-configured",
42776
+ "unknown-base-model",
42777
+ "unknown-gpu",
42778
+ "dataset-too-large",
42779
+ "no-training-subjects",
42780
+ "job-already-running"
42781
+ ]);
42782
+ var TrainingJobPlanSchema = object({
42783
+ refusal: object({
42784
+ reason: TrainingRefusalReasonSchema,
42785
+ detail: string()
42786
+ }).nullable(),
42787
+ warnings: array(string()).readonly(),
42788
+ split: TrainingSplitPlanSchema.nullable(),
42789
+ estimate: object({
42790
+ datasetBytes: number().int(),
42791
+ uploadMinutesAt20Mbps: number(),
42792
+ gpuSecondsLow: number(),
42793
+ gpuSecondsHigh: number(),
42794
+ usdLow: number(),
42795
+ usdHigh: number(),
42796
+ notes: array(string()).readonly()
42797
+ }).nullable(),
42798
+ /** Pre-filled from the provider's settings; the operator may lower or raise them. */
42799
+ defaults: object({
42800
+ maxCostUsd: number(),
42801
+ maxRuntimeSec: number().int()
42802
+ }).nullable(),
42803
+ /** The sentence the confirm dialog repeats: where the frames go and when they are deleted. */
42804
+ dataNotice: string()
42805
+ });
42806
+ /**
42807
+ * Orchestrator-owned states, persisted. `uploading` covers exporting the
42808
+ * archive (it is streamed, never staged). Terminal: `failed`, `cancelled`,
42809
+ * `lost`, `expired`, `discarded`. `registered` and `canary` are where a
42810
+ * result lives after the operator acted on it.
42811
+ */
42812
+ var TrainingJobStateSchema = _enum([
42813
+ "uploading",
42814
+ "submitted",
42815
+ "starting",
42816
+ "running",
42817
+ "collecting",
42818
+ "ready",
42819
+ "registered",
42820
+ "canary",
42821
+ "failed",
42822
+ "cancelling",
42823
+ "cancelled",
42824
+ "lost",
42825
+ "expired",
42826
+ "discarded"
42827
+ ]);
42828
+ var TrainingFailureReasonSchema = _enum([
42829
+ "cost-cap",
42830
+ "runtime-cap",
42831
+ "upload-failed",
42832
+ "submit-failed",
42833
+ "trainer-failed",
42834
+ "result-invalid",
42835
+ "checksum-mismatch",
42836
+ "fetch-failed",
42837
+ "provider-error",
42838
+ "hub-restart-during-upload"
42839
+ ]);
42840
+ var TrainingProgressPointSchema = object({
42841
+ epoch: number().int(),
42842
+ map50: number().nullable(),
42843
+ map50_95: number().nullable()
42844
+ });
42845
+ var TrainingCanarySchema = object({
42846
+ deviceIds: array(number().int()).readonly(),
42847
+ since: number(),
42848
+ /** Every override the canary replaced, exactly, so rollback restores it. */
42849
+ previous: array(object({
42850
+ deviceId: number().int(),
42851
+ nodeId: string(),
42852
+ deviceKey: string(),
42853
+ patch: object({
42854
+ modelId: string().optional(),
42855
+ settings: record(string(), unknown()).readonly().optional()
42856
+ }).nullable()
42857
+ })).readonly()
42858
+ });
42859
+ var TrainingJobSchema = object({
42860
+ id: string(),
42861
+ idempotencyKey: string(),
42862
+ name: string(),
42863
+ createdAt: number(),
42864
+ updatedAt: number(),
42865
+ state: TrainingJobStateSchema,
42866
+ stage: TrainingStageSchema.nullable(),
42867
+ failure: object({
42868
+ reason: TrainingFailureReasonSchema,
42869
+ stage: string().nullable(),
42870
+ detail: string()
42871
+ }).nullable(),
42872
+ request: TrainingJobRequestSchema,
42873
+ maxCostUsd: number().nonnegative(),
42874
+ maxRuntimeSec: number().int().positive(),
42875
+ trainer: TrainerSourceRefSchema,
42876
+ datasetLayout: RetrainExportLayoutSchema,
42877
+ dataset: object({
42878
+ bytes: number().int(),
42879
+ sha256: string(),
42880
+ uploadedAt: number()
42881
+ }).nullable(),
42882
+ split: TrainingSplitPlanSchema,
42883
+ provider: object({
42884
+ state: ProviderJobStateSchema.nullable(),
42885
+ providerJobId: string().nullable(),
42886
+ startedAt: number().nullable(),
42887
+ endedAt: number().nullable(),
42888
+ billedSeconds: number(),
42889
+ costUsd: number(),
42890
+ costIsEstimate: boolean(),
42891
+ lastPolledAt: number().nullable()
42892
+ }),
42893
+ progress: object({
42894
+ epoch: number().int().nullable(),
42895
+ epochs: number().int().nullable(),
42896
+ etaSec: number().nullable(),
42897
+ series: array(TrainingProgressPointSchema).readonly()
42898
+ }),
42899
+ /** The last lines of the job's output (≤ 200), newest last. Never frame paths. */
42900
+ logTail: array(string()).readonly(),
42901
+ logCursor: string().nullable(),
42902
+ artifacts: object({
42903
+ bundleBytes: number().int(),
42904
+ bundleSha256: string(),
42905
+ fetchedAt: number(),
42906
+ /** When the staged artefacts are deleted from the hub. */
42907
+ expiresAt: number()
42908
+ }).nullable(),
42909
+ /** When the provider-side copy of the frames was deleted; null while it exists. */
42910
+ cloudDatasetDeletedAt: number().nullable(),
42911
+ /** A failed job's dataset is kept until then (the provider's grace), then deleted. */
42912
+ cloudCleanupDueAt: number().nullable(),
42913
+ /** Model ids registered from this job (base, and int8 when kept). */
42914
+ registeredModelIds: array(string()).readonly(),
42915
+ canary: TrainingCanarySchema.nullable()
42916
+ });
42917
+ var IdInput = object({ id: string().min(1) });
42918
+ method(TrainingDatasetVersionRowSchema, object({ stored: boolean() }), {
42919
+ kind: "mutation",
42920
+ auth: "admin"
42921
+ }), 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() }), {
42922
+ kind: "mutation",
42923
+ auth: "admin"
42924
+ }), method(object({}), array(TrainingBaseModelSchema).readonly(), { auth: "admin" }), method(TrainingJobRequestSchema, TrainingJobPlanSchema, {
42925
+ auth: "admin",
42926
+ timeoutMs: 6e4
42927
+ }), method(TrainingJobRequestSchema.extend({
42928
+ name: string().min(1).max(120),
42929
+ maxCostUsd: number().positive(),
42930
+ maxRuntimeSec: number().int().positive(),
42931
+ idempotencyKey: string().min(8).max(80)
42932
+ }), discriminatedUnion("kind", [object({
42933
+ kind: literal("started"),
42934
+ job: TrainingJobSchema
42935
+ }), object({
42936
+ kind: literal("refused"),
42937
+ reason: TrainingRefusalReasonSchema,
42938
+ detail: string()
42939
+ })]), {
42940
+ kind: "mutation",
42941
+ auth: "admin",
42942
+ timeoutMs: 12e4
42943
+ }), method(object({}), array(TrainingJobSchema).readonly(), { auth: "admin" }), method(IdInput, TrainingJobSchema.nullable(), { auth: "admin" }), method(IdInput, TrainingJobSchema, {
42944
+ kind: "mutation",
42945
+ auth: "admin",
42946
+ timeoutMs: 12e4
42947
+ }), method(IdInput, TrainingResultSchema.nullable(), { auth: "admin" }), method(IdInput.extend({ canaryDeviceIds: array(number().int()).readonly() }), TrainingJobSchema, {
42948
+ kind: "mutation",
42949
+ auth: "admin",
42950
+ timeoutMs: 30 * 6e4
42951
+ }), method(IdInput.extend({ deviceIds: array(number().int()).min(1).readonly() }), TrainingJobSchema, {
42952
+ kind: "mutation",
42953
+ auth: "admin",
42954
+ timeoutMs: 12e4
42955
+ }), method(IdInput, TrainingJobSchema, {
42956
+ kind: "mutation",
42957
+ auth: "admin",
42958
+ timeoutMs: 12e4
42959
+ }), method(IdInput, TrainingJobSchema, {
42960
+ kind: "mutation",
42961
+ auth: "admin"
42962
+ });
41545
42963
  SOURCE_CAPS.filter((cap) => cap !== "switch" && cap !== "motion");
41546
42964
  Object.freeze({
41547
42965
  person: .5,
@@ -43690,6 +45108,12 @@ Object.freeze({
43690
45108
  addonId: null,
43691
45109
  access: "create"
43692
45110
  },
45111
+ "backup.checkBackupKey": {
45112
+ capName: "backup",
45113
+ capScope: "system",
45114
+ addonId: null,
45115
+ access: "create"
45116
+ },
43693
45117
  "backup.delete": {
43694
45118
  capName: "backup",
43695
45119
  capScope: "system",
@@ -43702,6 +45126,18 @@ Object.freeze({
43702
45126
  addonId: null,
43703
45127
  access: "delete"
43704
45128
  },
45129
+ "backup.disableEncryption": {
45130
+ capName: "backup",
45131
+ capScope: "system",
45132
+ addonId: null,
45133
+ access: "create"
45134
+ },
45135
+ "backup.getEncryption": {
45136
+ capName: "backup",
45137
+ capScope: "system",
45138
+ addonId: null,
45139
+ access: "view"
45140
+ },
43705
45141
  "backup.getEntries": {
43706
45142
  capName: "backup",
43707
45143
  capScope: "system",
@@ -43756,6 +45192,12 @@ Object.freeze({
43756
45192
  addonId: null,
43757
45193
  access: "create"
43758
45194
  },
45195
+ "backup.setupEncryption": {
45196
+ capName: "backup",
45197
+ capScope: "system",
45198
+ addonId: null,
45199
+ access: "create"
45200
+ },
43759
45201
  "backup.trigger": {
43760
45202
  capName: "backup",
43761
45203
  capScope: "system",
@@ -44308,6 +45750,12 @@ Object.freeze({
44308
45750
  addonId: null,
44309
45751
  access: "create"
44310
45752
  },
45753
+ "customModelRegistry.importModelBundle": {
45754
+ capName: "custom-model-registry",
45755
+ capScope: "system",
45756
+ addonId: null,
45757
+ access: "create"
45758
+ },
44311
45759
  "customModelRegistry.listModels": {
44312
45760
  capName: "custom-model-registry",
44313
45761
  capScope: "system",
@@ -45748,6 +47196,12 @@ Object.freeze({
45748
47196
  addonId: null,
45749
47197
  access: "view"
45750
47198
  },
47199
+ "keychainAdmin.acknowledgeReset": {
47200
+ capName: "keychain-admin",
47201
+ capScope: "system",
47202
+ addonId: null,
47203
+ access: "create"
47204
+ },
45751
47205
  "keychainAdmin.deleteOrphans": {
45752
47206
  capName: "keychain-admin",
45753
47207
  capScope: "system",
@@ -45784,6 +47238,12 @@ Object.freeze({
45784
47238
  addonId: null,
45785
47239
  access: "delete"
45786
47240
  },
47241
+ "keychainAdmin.resetReport": {
47242
+ capName: "keychain-admin",
47243
+ capScope: "system",
47244
+ addonId: null,
47245
+ access: "delete"
47246
+ },
45787
47247
  "keychainAdmin.reveal": {
45788
47248
  capName: "keychain-admin",
45789
47249
  capScope: "system",
@@ -45796,6 +47256,12 @@ Object.freeze({
45796
47256
  addonId: null,
45797
47257
  access: "create"
45798
47258
  },
47259
+ "keychainAdmin.setSystemSecret": {
47260
+ capName: "keychain-admin",
47261
+ capScope: "system",
47262
+ addonId: null,
47263
+ access: "create"
47264
+ },
45799
47265
  "keychainAdmin.status": {
45800
47266
  capName: "keychain-admin",
45801
47267
  capScope: "system",
@@ -47242,6 +48708,12 @@ Object.freeze({
47242
48708
  addonId: null,
47243
48709
  access: "create"
47244
48710
  },
48711
+ "pipelineAnalytics.createRetrainDatasetVersion": {
48712
+ capName: "pipeline-analytics",
48713
+ capScope: "device",
48714
+ addonId: null,
48715
+ access: "create"
48716
+ },
47245
48717
  "pipelineAnalytics.deleteDeviceEvents": {
47246
48718
  capName: "pipeline-analytics",
47247
48719
  capScope: "device",
@@ -47254,6 +48726,12 @@ Object.freeze({
47254
48726
  addonId: null,
47255
48727
  access: "delete"
47256
48728
  },
48729
+ "pipelineAnalytics.deleteRetrainDatasetVersion": {
48730
+ capName: "pipeline-analytics",
48731
+ capScope: "device",
48732
+ addonId: null,
48733
+ access: "delete"
48734
+ },
47257
48735
  "pipelineAnalytics.deleteTracks": {
47258
48736
  capName: "pipeline-analytics",
47259
48737
  capScope: "device",
@@ -47476,6 +48954,12 @@ Object.freeze({
47476
48954
  addonId: null,
47477
48955
  access: "view"
47478
48956
  },
48957
+ "pipelineAnalytics.listRetrainDatasetVersions": {
48958
+ capName: "pipeline-analytics",
48959
+ capScope: "device",
48960
+ addonId: null,
48961
+ access: "view"
48962
+ },
47479
48963
  "pipelineAnalytics.listRetrainFrames": {
47480
48964
  capName: "pipeline-analytics",
47481
48965
  capScope: "device",
@@ -47506,6 +48990,12 @@ Object.freeze({
47506
48990
  addonId: null,
47507
48991
  access: "view"
47508
48992
  },
48993
+ "pipelineAnalytics.offerRetrainArchive": {
48994
+ capName: "pipeline-analytics",
48995
+ capScope: "device",
48996
+ addonId: null,
48997
+ access: "create"
48998
+ },
47509
48999
  "pipelineAnalytics.ownersWithMedia": {
47510
49000
  capName: "pipeline-analytics",
47511
49001
  capScope: "device",
@@ -47518,6 +49008,12 @@ Object.freeze({
47518
49008
  addonId: null,
47519
49009
  access: "create"
47520
49010
  },
49011
+ "pipelineAnalytics.previewRetrainDataset": {
49012
+ capName: "pipeline-analytics",
49013
+ capScope: "device",
49014
+ addonId: null,
49015
+ access: "view"
49016
+ },
47521
49017
  "pipelineAnalytics.proposeRetrainAnnotations": {
47522
49018
  capName: "pipeline-analytics",
47523
49019
  capScope: "device",
@@ -47656,6 +49152,12 @@ Object.freeze({
47656
49152
  addonId: null,
47657
49153
  access: "create"
47658
49154
  },
49155
+ "pipelineAnalytics.verifyRetrainDatasetVersion": {
49156
+ capName: "pipeline-analytics",
49157
+ capScope: "device",
49158
+ addonId: null,
49159
+ access: "view"
49160
+ },
47659
49161
  "pipelineAnalytics.wipeAllAnalytics": {
47660
49162
  capName: "pipeline-analytics",
47661
49163
  capScope: "device",
@@ -50032,6 +51534,174 @@ Object.freeze({
50032
51534
  addonId: null,
50033
51535
  access: "view"
50034
51536
  },
51537
+ "training.canaryResult": {
51538
+ capName: "training",
51539
+ capScope: "system",
51540
+ addonId: null,
51541
+ access: "create"
51542
+ },
51543
+ "training.cancelJob": {
51544
+ capName: "training",
51545
+ capScope: "system",
51546
+ addonId: null,
51547
+ access: "create"
51548
+ },
51549
+ "training.discardResult": {
51550
+ capName: "training",
51551
+ capScope: "system",
51552
+ addonId: null,
51553
+ access: "create"
51554
+ },
51555
+ "training.findDatasetVersionIdByName": {
51556
+ capName: "training",
51557
+ capScope: "system",
51558
+ addonId: null,
51559
+ access: "view"
51560
+ },
51561
+ "training.getDatasetVersion": {
51562
+ capName: "training",
51563
+ capScope: "system",
51564
+ addonId: null,
51565
+ access: "view"
51566
+ },
51567
+ "training.getJob": {
51568
+ capName: "training",
51569
+ capScope: "system",
51570
+ addonId: null,
51571
+ access: "view"
51572
+ },
51573
+ "training.getJobResult": {
51574
+ capName: "training",
51575
+ capScope: "system",
51576
+ addonId: null,
51577
+ access: "view"
51578
+ },
51579
+ "training.listBaseModels": {
51580
+ capName: "training",
51581
+ capScope: "system",
51582
+ addonId: null,
51583
+ access: "view"
51584
+ },
51585
+ "training.listDatasetVersions": {
51586
+ capName: "training",
51587
+ capScope: "system",
51588
+ addonId: null,
51589
+ access: "view"
51590
+ },
51591
+ "training.listJobs": {
51592
+ capName: "training",
51593
+ capScope: "system",
51594
+ addonId: null,
51595
+ access: "view"
51596
+ },
51597
+ "training.planJob": {
51598
+ capName: "training",
51599
+ capScope: "system",
51600
+ addonId: null,
51601
+ access: "view"
51602
+ },
51603
+ "training.putDatasetVersion": {
51604
+ capName: "training",
51605
+ capScope: "system",
51606
+ addonId: null,
51607
+ access: "create"
51608
+ },
51609
+ "training.registerResult": {
51610
+ capName: "training",
51611
+ capScope: "system",
51612
+ addonId: null,
51613
+ access: "create"
51614
+ },
51615
+ "training.removeDatasetVersion": {
51616
+ capName: "training",
51617
+ capScope: "system",
51618
+ addonId: null,
51619
+ access: "delete"
51620
+ },
51621
+ "training.rollbackCanary": {
51622
+ capName: "training",
51623
+ capScope: "system",
51624
+ addonId: null,
51625
+ access: "create"
51626
+ },
51627
+ "training.startJob": {
51628
+ capName: "training",
51629
+ capScope: "system",
51630
+ addonId: null,
51631
+ access: "create"
51632
+ },
51633
+ "trainingProvider.cancelJob": {
51634
+ capName: "training-provider",
51635
+ capScope: "system",
51636
+ addonId: null,
51637
+ access: "create"
51638
+ },
51639
+ "trainingProvider.cleanupJob": {
51640
+ capName: "training-provider",
51641
+ capScope: "system",
51642
+ addonId: null,
51643
+ access: "create"
51644
+ },
51645
+ "trainingProvider.describe": {
51646
+ capName: "training-provider",
51647
+ capScope: "system",
51648
+ addonId: null,
51649
+ access: "view"
51650
+ },
51651
+ "trainingProvider.estimateJob": {
51652
+ capName: "training-provider",
51653
+ capScope: "system",
51654
+ addonId: null,
51655
+ access: "view"
51656
+ },
51657
+ "trainingProvider.getJob": {
51658
+ capName: "training-provider",
51659
+ capScope: "system",
51660
+ addonId: null,
51661
+ access: "view"
51662
+ },
51663
+ "trainingProvider.listJobEvents": {
51664
+ capName: "training-provider",
51665
+ capScope: "system",
51666
+ addonId: null,
51667
+ access: "view"
51668
+ },
51669
+ "trainingProvider.listJobs": {
51670
+ capName: "training-provider",
51671
+ capScope: "system",
51672
+ addonId: null,
51673
+ access: "view"
51674
+ },
51675
+ "trainingProvider.offerArtifact": {
51676
+ capName: "training-provider",
51677
+ capScope: "system",
51678
+ addonId: null,
51679
+ access: "create"
51680
+ },
51681
+ "trainingProvider.readResult": {
51682
+ capName: "training-provider",
51683
+ capScope: "system",
51684
+ addonId: null,
51685
+ access: "create"
51686
+ },
51687
+ "trainingProvider.submitJob": {
51688
+ capName: "training-provider",
51689
+ capScope: "system",
51690
+ addonId: null,
51691
+ access: "create"
51692
+ },
51693
+ "trainingProvider.uploadDataset": {
51694
+ capName: "training-provider",
51695
+ capScope: "system",
51696
+ addonId: null,
51697
+ access: "create"
51698
+ },
51699
+ "trainingProvider.validateCredentials": {
51700
+ capName: "training-provider",
51701
+ capScope: "system",
51702
+ addonId: null,
51703
+ access: "create"
51704
+ },
50035
51705
  "turnProvider.getTurnServers": {
50036
51706
  capName: "turn-provider",
50037
51707
  capScope: "system",
@@ -50056,12 +51726,6 @@ Object.freeze({
50056
51726
  addonId: null,
50057
51727
  access: "create"
50058
51728
  },
50059
- "userManagement.createApiKey": {
50060
- capName: "user-management",
50061
- capScope: "system",
50062
- addonId: null,
50063
- access: "create"
50064
- },
50065
51729
  "userManagement.createScopedToken": {
50066
51730
  capName: "user-management",
50067
51731
  capScope: "system",
@@ -50098,12 +51762,6 @@ Object.freeze({
50098
51762
  addonId: null,
50099
51763
  access: "view"
50100
51764
  },
50101
- "userManagement.linkExternalIdentity": {
50102
- capName: "user-management",
50103
- capScope: "system",
50104
- addonId: null,
50105
- access: "create"
50106
- },
50107
51765
  "userManagement.listApiKeys": {
50108
51766
  capName: "user-management",
50109
51767
  capScope: "system",
@@ -50206,12 +51864,6 @@ Object.freeze({
50206
51864
  addonId: null,
50207
51865
  access: "create"
50208
51866
  },
50209
- "userManagement.validateApiKey": {
50210
- capName: "user-management",
50211
- capScope: "system",
50212
- addonId: null,
50213
- access: "view"
50214
- },
50215
51867
  "userManagement.validateCredentials": {
50216
51868
  capName: "user-management",
50217
51869
  capScope: "system",
@@ -54325,6 +55977,11 @@ Object.freeze({
54325
55977
  form: "single",
54326
55978
  optional: false
54327
55979
  }],
55980
+ "training.canaryResult": [{
55981
+ name: "deviceIds",
55982
+ form: "array",
55983
+ optional: false
55984
+ }],
54328
55985
  "update.getStatus": [{
54329
55986
  name: "deviceId",
54330
55987
  form: "single",
@@ -55053,6 +56710,8 @@ var STATE_SUMMARY_VARS = [
55053
56710
  [...RULE_TEXT],
55054
56711
  [...RULE_TEXT],
55055
56712
  [...RULE_TEXT],
56713
+ [...RULE_TEXT],
56714
+ [...RULE_TEXT],
55056
56715
  ([...RULE_TEXT], [...UPDATES]),
55057
56716
  ([...RULE_TEXT], [...PACKAGE_UPDATES]),
55058
56717
  ([...RULE_TEXT], [...PACKAGE_UPDATES]),
@@ -78611,6 +80270,19 @@ function sameConnection(a, b) {
78611
80270
  return a.host === b.host && a.enableHmipRf === b.enableHmipRf && a.enableBidcosRf === b.enableBidcosRf && a.enableGroups === b.enableGroups && a.enableBidcosWired === b.enableBidcosWired && a.callbackHost === b.callbackHost && a.callbackPort === b.callbackPort && a.username === b.username && a.password === b.password && a.tls === b.tls;
78612
80271
  }
78613
80272
  /**
80273
+ * Delays (ms) between background restore retries after a failed
80274
+ * `facade.start()` (e.g. CCU `ECONNREFUSED`). Six attempts ≈ 2+5+10+20+30+60 s.
80275
+ * Exported for specs that drive the schedule with fake timers.
80276
+ */
80277
+ var RESTORE_RETRY_DELAYS_MS = [
80278
+ 2e3,
80279
+ 5e3,
80280
+ 1e4,
80281
+ 2e4,
80282
+ 3e4,
80283
+ 6e4
80284
+ ];
80285
+ /**
78614
80286
  * Manages N live CCU connections ("brokers"), each backed by an
78615
80287
  * {@link HmIntegrationManager}. Replaces the old single-CCU
78616
80288
  * `homematic-gateway.ts` singleton.
@@ -78656,6 +80328,10 @@ var HmBrokerRegistry = class {
78656
80328
  * typically in tests) facade creation is skipped.
78657
80329
  */
78658
80330
  #useDefaultFactory;
80331
+ /** Pending restore-retry timers — cleared on {@link shutdown}. */
80332
+ #retryTimers = /* @__PURE__ */ new Map();
80333
+ /** True after {@link shutdown} — blocks further restore retries. */
80334
+ #shuttingDown = false;
78659
80335
  constructor(logger, deps = {}) {
78660
80336
  this.#logger = logger;
78661
80337
  this.#onBrokerConnected = deps.onBrokerConnected ?? (() => void 0);
@@ -78680,10 +80356,13 @@ var HmBrokerRegistry = class {
78680
80356
  * Restore previously-persisted broker entries on addon boot.
78681
80357
  *
78682
80358
  * Seeds the id counter from existing ids so future allocations never
78683
- * collide. Starts each manager best-effort: a failed start is logged as a
78684
- * warning and the manager is still tracked (it can be retried later).
80359
+ * collide. Starts each manager best-effort: a failed start is rolled back
80360
+ * out of `#managers` (so a later attempt can rebuild) and scheduled for a
80361
+ * bounded background retry — a transient CCU `ECONNREFUSED` must not leave
80362
+ * the broker dead until an operator restarts the addon.
78685
80363
  */
78686
80364
  async restore(entries) {
80365
+ this.#shuttingDown = false;
78687
80366
  for (const entry of entries) this.#seedCounter(entry.id);
78688
80367
  for (const entry of entries) try {
78689
80368
  await this.#startManager(entry);
@@ -78693,6 +80372,7 @@ var HmBrokerRegistry = class {
78693
80372
  tags: { brokerId: entry.id },
78694
80373
  meta: { error: msg }
78695
80374
  });
80375
+ this.#scheduleRestoreRetry(entry, 0);
78696
80376
  }
78697
80377
  }
78698
80378
  /**
@@ -78700,6 +80380,9 @@ var HmBrokerRegistry = class {
78700
80380
  * shutdown.
78701
80381
  */
78702
80382
  async shutdown() {
80383
+ this.#shuttingDown = true;
80384
+ for (const timer of this.#retryTimers.values()) clearTimeout(timer);
80385
+ this.#retryTimers.clear();
78703
80386
  const ids = Array.from(this.#managers.keys());
78704
80387
  await Promise.all(ids.map(async (id) => {
78705
80388
  const mgr = this.#managers.get(id);
@@ -78891,6 +80574,10 @@ var HmBrokerRegistry = class {
78891
80574
  * Build (via the factory), register, and start the manager for one entry.
78892
80575
  * If a manager for the same id already exists (e.g. a duplicate restore
78893
80576
  * call), skip construction and only re-index the integration FK.
80577
+ *
80578
+ * On `start()` failure the half-built manager is abandoned so a retry can
80579
+ * construct a fresh one — leaving it in `#managers` used to make every
80580
+ * subsequent `#startManager` a no-op.
78894
80581
  */
78895
80582
  async #startManager(entry) {
78896
80583
  if (this.#managers.has(entry.id)) {
@@ -78907,13 +80594,92 @@ var HmBrokerRegistry = class {
78907
80594
  });
78908
80595
  this.#managers.set(entry.id, mgr);
78909
80596
  if (entry.integrationId !== void 0) this.#integrationToBroker.set(entry.integrationId, entry.id);
78910
- await mgr.start();
80597
+ try {
80598
+ await mgr.start();
80599
+ } catch (err) {
80600
+ await this.#abandonFailedStart(entry.id, mgr);
80601
+ throw err;
80602
+ }
80603
+ const pending = this.#retryTimers.get(entry.id);
80604
+ if (pending !== void 0) {
80605
+ clearTimeout(pending);
80606
+ this.#retryTimers.delete(entry.id);
80607
+ }
78911
80608
  this.#logger.info("HmBrokerRegistry: manager started", {
78912
80609
  tags: { brokerId: entry.id },
78913
80610
  meta: { name: entry.name }
78914
80611
  });
78915
80612
  }
78916
80613
  /**
80614
+ * Drop a manager that never reached `connected` so a later attempt can
80615
+ * rebuild it. Best-effort `stop()`; never throws.
80616
+ */
80617
+ async #abandonFailedStart(id, mgr) {
80618
+ this.#managers.delete(id);
80619
+ this.#facades.delete(id);
80620
+ homematicFacades.set(id, null);
80621
+ try {
80622
+ await mgr.stop();
80623
+ } catch (err) {
80624
+ const msg = err instanceof Error ? err.message : String(err);
80625
+ this.#logger.debug("HmBrokerRegistry: abandon stop failed", {
80626
+ tags: { brokerId: id },
80627
+ meta: { error: msg }
80628
+ });
80629
+ }
80630
+ }
80631
+ /**
80632
+ * Schedule attempt `attemptIndex` of {@link RESTORE_RETRY_DELAYS_MS} for
80633
+ * `entry`. No-ops when the registry is shutting down or the schedule is
80634
+ * exhausted (warns once at the end).
80635
+ */
80636
+ #scheduleRestoreRetry(entry, attemptIndex) {
80637
+ if (this.#shuttingDown) return;
80638
+ const delay = RESTORE_RETRY_DELAYS_MS[attemptIndex];
80639
+ if (delay === void 0) {
80640
+ this.#logger.warn("HmBrokerRegistry: restore retries exhausted", {
80641
+ tags: { brokerId: entry.id },
80642
+ meta: { attempts: RESTORE_RETRY_DELAYS_MS.length }
80643
+ });
80644
+ return;
80645
+ }
80646
+ const existing = this.#retryTimers.get(entry.id);
80647
+ if (existing !== void 0) clearTimeout(existing);
80648
+ const timer = setTimeout(() => {
80649
+ this.#retryTimers.delete(entry.id);
80650
+ this.#runRestoreRetry(entry, attemptIndex);
80651
+ }, delay);
80652
+ this.#retryTimers.set(entry.id, timer);
80653
+ this.#logger.info("HmBrokerRegistry: scheduling restore retry", {
80654
+ tags: { brokerId: entry.id },
80655
+ meta: {
80656
+ attempt: attemptIndex + 1,
80657
+ delayMs: delay
80658
+ }
80659
+ });
80660
+ }
80661
+ async #runRestoreRetry(entry, attemptIndex) {
80662
+ if (this.#shuttingDown) return;
80663
+ if (this.#managers.has(entry.id)) return;
80664
+ try {
80665
+ await this.#startManager(entry);
80666
+ this.#logger.info("HmBrokerRegistry: restore retry succeeded", {
80667
+ tags: { brokerId: entry.id },
80668
+ meta: { attempt: attemptIndex + 1 }
80669
+ });
80670
+ } catch (err) {
80671
+ const msg = err instanceof Error ? err.message : String(err);
80672
+ this.#logger.warn("HmBrokerRegistry: restore retry failed", {
80673
+ tags: { brokerId: entry.id },
80674
+ meta: {
80675
+ attempt: attemptIndex + 1,
80676
+ error: msg
80677
+ }
80678
+ });
80679
+ this.#scheduleRestoreRetry(entry, attemptIndex + 1);
80680
+ }
80681
+ }
80682
+ /**
78917
80683
  * Allocate the next monotonic id in the `hm_NNN` sequence and advance
78918
80684
  * the counter.
78919
80685
  */
@@ -81370,6 +83136,19 @@ var HmContainerDevice = class HmContainerDevice extends BaseDevice {
81370
83136
  }
81371
83137
  }
81372
83138
  /**
83139
+ * Stamp `feature-probe.lastProbedAt` only when the CCU device is on the
83140
+ * facade. An empty accessory-spec list + a stamped probe is how the kernel
83141
+ * orphan-prunes linked children (`device-cap-proxy` safety gate): a restore
83142
+ * that races a CCU `ECONNREFUSED` used to delete every accessory and fence
83143
+ * their identities for 5 minutes. Leaving `lastProbedAt === 0` until the
83144
+ * device is present keeps the gate closed; `reprobe()` on broker connect
83145
+ * completes the probe and spawns/reconciles children for real.
83146
+ */
83147
+ async onProbe() {
83148
+ if (this.resolveHmDevice() === null) return;
83149
+ await super.onProbe();
83150
+ }
83151
+ /**
81373
83152
  * Derive the accessory children LIVE from the facade descriptor. Each child
81374
83153
  * is a {@link HmEntitySpec} (the shared per-entity decomposition) wrapped into
81375
83154
  * an `AccessoryChildSpec`: the `stableIdSuffix` IS the spec `key`, the broker
@@ -81509,6 +83288,7 @@ var HomematicProviderAddon = class extends BaseDeviceProvider {
81509
83288
  this.registry.setOnBrokerConnected((brokerId) => {
81510
83289
  this.ctx.logger.info("Homematic: broker connected", { meta: { brokerId } });
81511
83290
  this.setBrokerDevicesOnline(brokerId, true);
83291
+ this.reprobeBrokerContainers(brokerId);
81512
83292
  });
81513
83293
  this.registry.setOnBrokerDisconnected((brokerId) => {
81514
83294
  this.setBrokerDevicesOnline(brokerId, false);
@@ -81903,6 +83683,28 @@ var HomematicProviderAddon = class extends BaseDeviceProvider {
81903
83683
  count: n
81904
83684
  } });
81905
83685
  }
83686
+ /**
83687
+ * Reprobe every adopted {@link HmContainerDevice} for `brokerId` so the
83688
+ * kernel re-runs accessory reconcile against the live facade. Best-effort:
83689
+ * one container's failure must not block the rest (same discipline as HA's
83690
+ * post-connect reconcile).
83691
+ */
83692
+ async reprobeBrokerContainers(brokerId) {
83693
+ const reg = this.ctx.kernel.deviceRegistry;
83694
+ if (!reg) return;
83695
+ const containers = reg.getAllForAddon(this.addonId).filter((d) => d instanceof HmContainerDevice && d.config.get("brokerId") === brokerId);
83696
+ for (const container of containers) try {
83697
+ await container.reprobe();
83698
+ } catch (err) {
83699
+ this.ctx.logger.warn("Homematic: container reprobe failed", {
83700
+ tags: { deviceId: container.id },
83701
+ meta: {
83702
+ brokerId,
83703
+ error: errMsg(err)
83704
+ }
83705
+ });
83706
+ }
83707
+ }
81906
83708
  /** Return the live registry or throw if the addon is not initialised. */
81907
83709
  requireRegistry() {
81908
83710
  if (!this.registry) throw new Error("Homematic provider not initialised");