@camstack/addon-export-hap 1.2.154 → 1.2.156

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.
@@ -38,7 +38,7 @@ var __copyProps = (to, from, except, desc) => {
38
38
  var __toCommonJS = (mod) => __hasOwnProp.call(mod, "module.exports") ? mod["module.exports"] : __copyProps(__defProp({}, "__esModule", { value: true }), mod);
39
39
  var __require = /* @__PURE__ */ createRequire(import.meta.url);
40
40
  //#endregion
41
- //#region ../types/dist/event-category-B_0XEcLF.mjs
41
+ //#region ../types/dist/event-category-DaIZi00R.mjs
42
42
  var EventCategory = /* @__PURE__ */ function(EventCategory) {
43
43
  EventCategory["SystemBoot"] = "system.boot";
44
44
  EventCategory["SystemAddonsReady"] = "system.addons-ready";
@@ -117,6 +117,13 @@ var EventCategory = /* @__PURE__ */ function(EventCategory) {
117
117
  */
118
118
  EventCategory["AddonLoadFailed"] = "addon.load-failed";
119
119
  /**
120
+ * A keychain value was stored or removed (D787). Carries the ref, its
121
+ * owner and the new version — NEVER the value. A process holding the ref
122
+ * drops its cached copy and the owning `BaseAddon` re-resolves its config.
123
+ * Telemetry (D8): a process that misses it still revalidates by version.
124
+ */
125
+ EventCategory["KeychainChanged"] = "keychain.changed";
126
+ /**
120
127
  * Addon recovered from a previous failure. Emitted when an addon
121
128
  * transitions from `failed` back to `healthy` (typically via the
122
129
  * monitor's auto-retry loop, or after manual `addons.retryLoad`).
@@ -5409,7 +5416,7 @@ var ZodIssueCode = {
5409
5416
  var ZodFirstPartyTypeKind;
5410
5417
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
5411
5418
  //#endregion
5412
- //#region ../types/dist/sleep-B0JG7-_F.mjs
5419
+ //#region ../types/dist/sleep-r3RWkGVx.mjs
5413
5420
  /**
5414
5421
  * The audio chunk plane's byte format, and the ONE expansion from a coded
5415
5422
  * window to float samples (D455).
@@ -5488,6 +5495,97 @@ function buildAlawTable() {
5488
5495
  }
5489
5496
  buildUlawTable();
5490
5497
  buildAlawTable();
5498
+ /** Is this field's stored value a credential? */
5499
+ function isSecretConfigField(field) {
5500
+ if (field.type === "password") return true;
5501
+ return "secret" in field && field.secret === true;
5502
+ }
5503
+ /**
5504
+ * Is this field's value stored in the KEYCHAIN (D787)? Every secret field is,
5505
+ * by its TYPE, unless it opts out with `storage: 'inline'` — never by its name.
5506
+ */
5507
+ function isKeychainStoredField(field) {
5508
+ if (!isSecretConfigField(field)) return false;
5509
+ if (field.type === "textarea" && field.isJson === true) return false;
5510
+ return !("storage" in field && field.storage === "inline");
5511
+ }
5512
+ /**
5513
+ * What a settings blob holds where a secret used to be.
5514
+ *
5515
+ * A keychain-stored field never holds its value. It holds a self-describing
5516
+ * MARKER, `{"$secret":"secret://…","v":1}` — an object, never a string, so no
5517
+ * code can mistake it for a credential and no form can send it to a camera as
5518
+ * a password. The empty state is `null` / absent, never `''`.
5519
+ *
5520
+ * The same shapes travel to and from the admin UI:
5521
+ *
5522
+ * - read: `hydrateSchema` hands a secret field a {@link SecretFieldView}
5523
+ * (`{ $secret, v, set: true }`) or `null` — the browser learns whether a
5524
+ * value is set, never the value.
5525
+ * - write: an untouched field submits the view back unchanged (KEEP); a typed
5526
+ * value is a plain non-empty string (CHANGE); the Clear button submits
5527
+ * {@link SECRET_CLEAR} (CLEAR). `''`, `null` and the legacy redaction tokens
5528
+ * are KEEP — an empty string is what a defaults-fallback pushes back, and
5529
+ * treating it as "clear" is how a save destroyed a stored credential before.
5530
+ *
5531
+ * Pure and browser-safe.
5532
+ */
5533
+ var SECRET_CLEAR = { $secretClear: true };
5534
+ /** The `'***'` token D634 redaction writes for non-admins. */
5535
+ var LEGACY_DEVICE_REDACTION = "***";
5536
+ function isRecord$2(value) {
5537
+ return typeof value === "object" && value !== null && !Array.isArray(value);
5538
+ }
5539
+ function makeSecretMarker(ref) {
5540
+ return {
5541
+ $secret: ref,
5542
+ v: 1
5543
+ };
5544
+ }
5545
+ /** A stored marker: an object whose `$secret` is a non-empty string. */
5546
+ function isSecretMarker(value) {
5547
+ if (!isRecord$2(value)) return false;
5548
+ const ref = value["$secret"];
5549
+ return typeof ref === "string" && ref.length > 0;
5550
+ }
5551
+ function isSecretClear(value) {
5552
+ return isRecord$2(value) && value["$secretClear"] === true;
5553
+ }
5554
+ /**
5555
+ * The UI view of a stored secret field value: a marker becomes "set", inline
5556
+ * plaintext becomes "set (inline)", nothing becomes `null`. A value never
5557
+ * survives this function.
5558
+ */
5559
+ function toSecretFieldView(stored) {
5560
+ if (isSecretMarker(stored)) return {
5561
+ $secret: stored.$secret,
5562
+ v: 1,
5563
+ set: true
5564
+ };
5565
+ if (typeof stored === "string" && stored.length > 0) return {
5566
+ $secret: null,
5567
+ v: 1,
5568
+ set: true,
5569
+ inline: true
5570
+ };
5571
+ return null;
5572
+ }
5573
+ /**
5574
+ * Classify an incoming value for a secret path. Only a non-empty string that is
5575
+ * not a redaction token sets a value; only {@link SECRET_CLEAR} clears.
5576
+ * Everything else — a marker (ours or anyone's), a UI view, `''`, `null`,
5577
+ * `undefined`, a redaction token, a non-string — keeps what is stored.
5578
+ */
5579
+ function classifySecretWrite(incoming) {
5580
+ if (isSecretClear(incoming)) return { kind: "clear" };
5581
+ if (typeof incoming !== "string") return { kind: "keep" };
5582
+ if (incoming.length === 0) return { kind: "keep" };
5583
+ if (incoming === "__camstack_redacted__" || incoming === LEGACY_DEVICE_REDACTION) return { kind: "keep" };
5584
+ return {
5585
+ kind: "set",
5586
+ value: incoming
5587
+ };
5588
+ }
5491
5589
  Object.fromEntries([
5492
5590
  {
5493
5591
  id: "overview",
@@ -5659,33 +5757,19 @@ Object.fromEntries([
5659
5757
  function isValuelessField(field) {
5660
5758
  return field.type === "separator" || field.type === "info" || field.type === "qr-code" || field.type === "button" || field.type === "object-array" || field.type === "widget" || field.type === "addon-action-button" || field.type === "device-action-button";
5661
5759
  }
5662
- /**
5663
- * Merge a `ConfigUISchema` with a raw `values` record into a
5664
- * `ConfigUISchemaWithValues`. Used by every `get*Settings` backend endpoint
5665
- * before returning to the admin UI. Groups are walked recursively.
5666
- *
5667
- * For each leaf field:
5668
- * - structural fields (`separator`, `info`, `button`) pass through unchanged
5669
- * - other fields get `value = values[key] ?? field.default ?? null`
5670
- *
5671
- * Unknown keys in `values` (keys not declared in the schema) are silently
5672
- * ignored — they don't contribute to the output. Missing keys fall back to
5673
- * the schema default or `null`. This mirrors the old backend behaviour where
5674
- * `FormBuilder` rendered `values[key] ?? field.default`.
5675
- */
5676
- function hydrateSchema(schema, values) {
5760
+ function hydrateSchema(schema, values, options = {}) {
5677
5761
  return {
5678
5762
  ...schema.tabs ? { tabs: [...schema.tabs] } : {},
5679
5763
  sections: schema.sections.map((section) => ({
5680
5764
  ...section,
5681
- fields: section.fields.map((field) => hydrateField(field, values))
5765
+ fields: section.fields.map((field) => hydrateField(field, values, options))
5682
5766
  }))
5683
5767
  };
5684
5768
  }
5685
- function hydrateField(field, values) {
5769
+ function hydrateField(field, values, options) {
5686
5770
  if (isValuelessField(field)) return field;
5687
5771
  if (field.type === "group") {
5688
- const hydratedChildren = field.fields.map((child) => hydrateField(child, values));
5772
+ const hydratedChildren = field.fields.map((child) => hydrateField(child, values, options));
5689
5773
  return {
5690
5774
  ...field,
5691
5775
  fields: hydratedChildren
@@ -5694,7 +5778,7 @@ function hydrateField(field, values) {
5694
5778
  if (field.type === "sub-tabs") {
5695
5779
  const hydratedTabs = field.tabs.map((tab) => ({
5696
5780
  ...tab,
5697
- fields: tab.fields.map((child) => hydrateField(child, values))
5781
+ fields: tab.fields.map((child) => hydrateField(child, values, options))
5698
5782
  }));
5699
5783
  return {
5700
5784
  ...field,
@@ -5704,6 +5788,33 @@ function hydrateField(field, values) {
5704
5788
  const key = field.key;
5705
5789
  const storedValue = Object.prototype.hasOwnProperty.call(values, key) ? values[key] : void 0;
5706
5790
  const defaultValue = field.default;
5791
+ const asView = (v) => isSecretMarker(v) || options.inlineSecretsAsViews === true && v !== void 0;
5792
+ if (isKeychainStoredField(field) && asView(storedValue)) return {
5793
+ ...field,
5794
+ value: toSecretFieldView(storedValue)
5795
+ };
5796
+ if (isKeychainStoredField(field) && options.inlineSecretsAsViews === true) return {
5797
+ ...field,
5798
+ value: null
5799
+ };
5800
+ if (field.type === "editable-array" && Array.isArray(storedValue)) {
5801
+ const secretItemKeys = field.itemFields.filter((item) => "key" in item && isKeychainStoredField(item)).map((item) => "key" in item ? item.key : "");
5802
+ if (secretItemKeys.length > 0) {
5803
+ const rows = storedValue.map((row) => {
5804
+ if (row === null || typeof row !== "object" || Array.isArray(row)) return row;
5805
+ const out = { ...row };
5806
+ for (const k of secretItemKeys) {
5807
+ const v = Reflect.get(row, k);
5808
+ if (asView(v)) out[k] = toSecretFieldView(v);
5809
+ }
5810
+ return out;
5811
+ });
5812
+ return {
5813
+ ...field,
5814
+ value: rows
5815
+ };
5816
+ }
5817
+ }
5707
5818
  if (field.multiple) {
5708
5819
  const stored = Array.isArray(storedValue) ? storedValue : storedValue !== void 0 && storedValue !== null ? [storedValue] : [];
5709
5820
  const itemFallback = field.multiple.itemDefault !== void 0 ? field.multiple.itemDefault : defaultValue !== void 0 ? defaultValue : typeOf(field) === "string" ? "" : null;
@@ -5946,6 +6057,778 @@ function projectStore(store, perNodeKeys, nodeId) {
5946
6057
  }
5947
6058
  return out;
5948
6059
  }
6060
+ var GLOBAL_SCOPE = { kind: "global" };
6061
+ /** The scope every addon-wide (not per-node, not per-device) setting lives in. */
6062
+ function globalSecretScope() {
6063
+ return GLOBAL_SCOPE;
6064
+ }
6065
+ function encodeSegment(value) {
6066
+ return encodeURIComponent(value);
6067
+ }
6068
+ function decodeSegment(value) {
6069
+ try {
6070
+ return decodeURIComponent(value);
6071
+ } catch {
6072
+ return null;
6073
+ }
6074
+ }
6075
+ /**
6076
+ * The field path of a value inside an array item, addressed by the item's id:
6077
+ * `arrayItemFieldPath('providers', 'authentik', 'clientSecret')` →
6078
+ * `providers[authentik].clientSecret`.
6079
+ */
6080
+ function arrayItemFieldPath(arrayKey, itemId, fieldKey) {
6081
+ return `${arrayKey}[${encodeSegment(itemId)}].${fieldKey}`;
6082
+ }
6083
+ function parseScope(segments) {
6084
+ switch (segments[0]) {
6085
+ case "global": return {
6086
+ scope: GLOBAL_SCOPE,
6087
+ used: 1
6088
+ };
6089
+ case "node": {
6090
+ const nodeId = segments[1] !== void 0 ? decodeSegment(segments[1]) : null;
6091
+ return nodeId === null || nodeId.length === 0 ? null : {
6092
+ scope: {
6093
+ kind: "node",
6094
+ nodeId
6095
+ },
6096
+ used: 2
6097
+ };
6098
+ }
6099
+ case "device": {
6100
+ const raw = segments[1];
6101
+ if (raw === void 0 || !/^\d+$/.test(raw)) return null;
6102
+ return {
6103
+ scope: {
6104
+ kind: "device",
6105
+ deviceId: Number(raw)
6106
+ },
6107
+ used: 2
6108
+ };
6109
+ }
6110
+ case "integration": {
6111
+ const id = segments[1] !== void 0 ? decodeSegment(segments[1]) : null;
6112
+ return id === null || id.length === 0 ? null : {
6113
+ scope: {
6114
+ kind: "integration",
6115
+ integrationId: id
6116
+ },
6117
+ used: 2
6118
+ };
6119
+ }
6120
+ case "row": {
6121
+ const collection = segments[1] !== void 0 ? decodeSegment(segments[1]) : null;
6122
+ const rowId = segments[2] !== void 0 ? decodeSegment(segments[2]) : null;
6123
+ if (collection === null || rowId === null || collection.length === 0 || rowId.length === 0) return null;
6124
+ return {
6125
+ scope: {
6126
+ kind: "row",
6127
+ collection,
6128
+ rowId
6129
+ },
6130
+ used: 3
6131
+ };
6132
+ }
6133
+ default: return null;
6134
+ }
6135
+ }
6136
+ /** Take a ref apart; `null` when it is not a well-formed ref. */
6137
+ function parseSecretRef(ref) {
6138
+ if (!ref.startsWith("secret://")) return null;
6139
+ const segments = ref.slice(9).split("/");
6140
+ const owner = segments[0] !== void 0 ? decodeSegment(segments[0]) : null;
6141
+ if (owner === null || owner.length === 0) return null;
6142
+ const parsed = parseScope(segments.slice(1));
6143
+ if (parsed === null) return null;
6144
+ const fieldPath = segments.slice(1 + parsed.used).join("/");
6145
+ if (fieldPath.length === 0) return null;
6146
+ return {
6147
+ owner,
6148
+ scope: parsed.scope,
6149
+ fieldPath
6150
+ };
6151
+ }
6152
+ /** A write to a secret path could not be stored in the keychain, so it was refused. */
6153
+ var KeychainWriteRefusedError = class extends Error {
6154
+ fieldPath;
6155
+ constructor(fieldPath, cause) {
6156
+ super(`secret "${fieldPath}" was not saved: the keychain could not store it (${cause instanceof Error ? cause.message : String(cause)}). Nothing was written.`);
6157
+ this.fieldPath = fieldPath;
6158
+ this.name = "KeychainWriteRefusedError";
6159
+ }
6160
+ };
6161
+ var KEEP = { kind: "keep" };
6162
+ function isRecord$1$1(value) {
6163
+ return typeof value === "object" && value !== null && !Array.isArray(value);
6164
+ }
6165
+ function defaultMintId() {
6166
+ return globalThis.crypto.randomUUID();
6167
+ }
6168
+ /** Every marker ref anywhere under `value`. */
6169
+ function collectSecretMarkerRefs(value, out = []) {
6170
+ if (isSecretMarker(value)) {
6171
+ out.push(value.$secret);
6172
+ return out;
6173
+ }
6174
+ if (Array.isArray(value)) for (const item of value) collectSecretMarkerRefs(item, out);
6175
+ else if (isRecord$1$1(value)) for (const child of Object.values(value)) collectSecretMarkerRefs(child, out);
6176
+ return out;
6177
+ }
6178
+ async function storedValueEquals(secrets, marker, candidate) {
6179
+ const resolved = (await secrets.resolve([marker.$secret]))[marker.$secret];
6180
+ return resolved?.kind === "value" && resolved.value === candidate;
6181
+ }
6182
+ async function writeLeaf(ctx, incoming, stored, fieldPath) {
6183
+ const intent = classifySecretWrite(incoming);
6184
+ const ref = ctx.secrets.ref(ctx.scope, fieldPath);
6185
+ const storedIsOurs = isSecretMarker(stored) && stored.$secret === ref;
6186
+ if (intent.kind === "keep") return KEEP;
6187
+ if (intent.kind === "set" && !ctx.operatorWrite && typeof stored === "string" && stored === intent.value) return KEEP;
6188
+ if (intent.kind === "clear") {
6189
+ if (storedIsOurs) ctx.deletes.push(ref);
6190
+ return {
6191
+ kind: "value",
6192
+ value: null
6193
+ };
6194
+ }
6195
+ if (storedIsOurs && await storedValueEquals(ctx.secrets, stored, intent.value)) return {
6196
+ kind: "value",
6197
+ value: stored
6198
+ };
6199
+ try {
6200
+ await ctx.secrets.put(ref, intent.value);
6201
+ } catch (err) {
6202
+ throw new KeychainWriteRefusedError(fieldPath, err);
6203
+ }
6204
+ return {
6205
+ kind: "value",
6206
+ value: makeSecretMarker(ref)
6207
+ };
6208
+ }
6209
+ /** Apply a member result onto `out`: KEEP restores the stored member, or removes it. */
6210
+ function applyMember(out, key, result, storedParent) {
6211
+ if (result.kind === "value") {
6212
+ out[key] = result.value;
6213
+ return;
6214
+ }
6215
+ if (Object.prototype.hasOwnProperty.call(storedParent, key)) out[key] = storedParent[key];
6216
+ else delete out[key];
6217
+ }
6218
+ async function writeMembers(ctx, children, incoming, stored, pathOf) {
6219
+ const out = { ...incoming };
6220
+ for (const [member, node] of children) applyMember(out, member, await writeNode(ctx, node, incoming[member], stored[member], pathOf(member)), stored);
6221
+ return out;
6222
+ }
6223
+ function rowId(row, idKey) {
6224
+ const raw = row[idKey];
6225
+ if (typeof raw === "string" && raw.length > 0) return raw;
6226
+ if (typeof raw === "number" && Number.isFinite(raw)) return String(raw);
6227
+ return null;
6228
+ }
6229
+ async function writeArray(ctx, node, incoming, stored, fieldPath) {
6230
+ const storedRows = Array.isArray(stored) ? stored.filter(isRecord$1$1) : [];
6231
+ if (!Array.isArray(incoming)) {
6232
+ ctx.deletes.push(...collectSecretMarkerRefs(storedRows));
6233
+ return {
6234
+ kind: "value",
6235
+ value: incoming
6236
+ };
6237
+ }
6238
+ const storedById = /* @__PURE__ */ new Map();
6239
+ for (const row of storedRows) {
6240
+ const id = rowId(row, node.idKey);
6241
+ if (id !== null) storedById.set(id, row);
6242
+ }
6243
+ const kept = /* @__PURE__ */ new Set();
6244
+ const rows = [];
6245
+ for (const row of incoming) {
6246
+ if (!isRecord$1$1(row)) {
6247
+ rows.push(row);
6248
+ continue;
6249
+ }
6250
+ const id = rowId(row, node.idKey) ?? ctx.mintId();
6251
+ kept.add(id);
6252
+ const withId = {
6253
+ ...row,
6254
+ [node.idKey]: row[node.idKey] ?? id
6255
+ };
6256
+ if (rowId(withId, node.idKey) === null) withId[node.idKey] = id;
6257
+ const storedRow = storedById.get(id) ?? {};
6258
+ rows.push(await writeMembers(ctx, node.item, withId, storedRow, (member) => arrayItemFieldPath(fieldPath, id, member)));
6259
+ }
6260
+ for (const [id, row] of storedById) if (!kept.has(id)) ctx.deletes.push(...collectSecretMarkerRefs(row));
6261
+ return {
6262
+ kind: "value",
6263
+ value: rows
6264
+ };
6265
+ }
6266
+ async function writeNode(ctx, node, incoming, stored, fieldPath) {
6267
+ switch (node.kind) {
6268
+ case "leaf": return writeLeaf(ctx, incoming, stored, fieldPath);
6269
+ case "array": return writeArray(ctx, node, incoming, stored, fieldPath);
6270
+ case "object": {
6271
+ if (!isRecord$1$1(incoming)) {
6272
+ if (incoming === void 0) return KEEP;
6273
+ ctx.deletes.push(...collectSecretMarkerRefs(stored));
6274
+ return {
6275
+ kind: "value",
6276
+ value: incoming
6277
+ };
6278
+ }
6279
+ const storedObj = isRecord$1$1(stored) ? stored : {};
6280
+ return {
6281
+ kind: "value",
6282
+ value: await writeMembers(ctx, node.children, incoming, storedObj, (m) => `${fieldPath}.${m}`)
6283
+ };
6284
+ }
6285
+ }
6286
+ }
6287
+ /** Split a perNode-scoped key (`key@nodeId`). */
6288
+ function splitNodeKey(key) {
6289
+ const at = key.indexOf("@");
6290
+ return at <= 0 ? {
6291
+ base: key,
6292
+ nodeId: null
6293
+ } : {
6294
+ base: key.slice(0, at),
6295
+ nodeId: key.slice(at + 1)
6296
+ };
6297
+ }
6298
+ /** Rewrite a settings patch so no secret value reaches the blob. See the file doc. */
6299
+ async function transformSecretWrite(input) {
6300
+ const deletes = [];
6301
+ const base = {
6302
+ secrets: input.secrets,
6303
+ mintId: input.mintId ?? defaultMintId,
6304
+ deletes,
6305
+ operatorWrite: input.operatorWrite === true
6306
+ };
6307
+ const out = {};
6308
+ for (const [key, incoming] of Object.entries(input.patch)) {
6309
+ const { base: baseKey, nodeId } = splitNodeKey(key);
6310
+ const node = input.tree.get(baseKey);
6311
+ if (node === void 0) {
6312
+ out[key] = incoming;
6313
+ continue;
6314
+ }
6315
+ const scope = nodeId !== null && nodeId.length > 0 ? {
6316
+ kind: "node",
6317
+ nodeId
6318
+ } : input.scope ?? globalSecretScope();
6319
+ const result = await writeNode({
6320
+ ...base,
6321
+ scope
6322
+ }, node, incoming, input.stored[key], baseKey);
6323
+ if (result.kind === "value") out[key] = result.value;
6324
+ }
6325
+ return {
6326
+ patch: out,
6327
+ afterWrite: async () => {
6328
+ if (deletes.length === 0) return { orphaned: [] };
6329
+ try {
6330
+ await input.secrets.delete([...new Set(deletes)]);
6331
+ return { orphaned: [] };
6332
+ } catch {
6333
+ return { orphaned: [...new Set(deletes)] };
6334
+ }
6335
+ }
6336
+ };
6337
+ }
6338
+ /** Is `ref` one of `owner`'s refs? */
6339
+ function isSecretRefOwnedBy(ref, owner) {
6340
+ return parseSecretRef(ref)?.owner === owner;
6341
+ }
6342
+ /**
6343
+ * Replace every marker in `value` with its keychain value. Returns the SAME
6344
+ * reference when there is no marker (no allocation, no keychain call).
6345
+ */
6346
+ async function resolveSecretMarkers(value, secrets, options = {}) {
6347
+ const keepMarker = options.unresolved === "keep-marker";
6348
+ const owner = options.ownedBy;
6349
+ const inScope = (ref) => owner === void 0 || isSecretRefOwnedBy(ref, owner);
6350
+ const refs = collectSecretMarkerRefs(value).filter(inScope);
6351
+ if (refs.length === 0) return {
6352
+ value,
6353
+ unresolved: []
6354
+ };
6355
+ const answers = await secrets.resolve(refs);
6356
+ const unresolved = [];
6357
+ for (const ref of new Set(refs)) {
6358
+ const answer = answers[ref];
6359
+ if (answer === void 0) unresolved.push({
6360
+ ref,
6361
+ reason: "not-initialized"
6362
+ });
6363
+ else if (answer.kind === "unavailable") unresolved.push({
6364
+ ref,
6365
+ reason: answer.reason
6366
+ });
6367
+ else if (answer.kind === "missing" || answer.kind === "forbidden") unresolved.push({
6368
+ ref,
6369
+ reason: answer.kind
6370
+ });
6371
+ }
6372
+ const substitute = (v) => {
6373
+ if (isSecretMarker(v)) {
6374
+ if (!inScope(v.$secret)) return {
6375
+ keep: true,
6376
+ value: v
6377
+ };
6378
+ const answer = answers[v.$secret];
6379
+ if (answer?.kind === "value") return {
6380
+ keep: true,
6381
+ value: answer.value
6382
+ };
6383
+ return keepMarker ? {
6384
+ keep: true,
6385
+ value: v
6386
+ } : {
6387
+ keep: false,
6388
+ value: void 0
6389
+ };
6390
+ }
6391
+ if (Array.isArray(v)) {
6392
+ const items = [];
6393
+ for (const item of v) {
6394
+ const s = substitute(item);
6395
+ if (s.keep) items.push(s.value);
6396
+ }
6397
+ return {
6398
+ keep: true,
6399
+ value: items
6400
+ };
6401
+ }
6402
+ if (isRecord$1$1(v)) {
6403
+ const out = {};
6404
+ for (const [k, child] of Object.entries(v)) {
6405
+ const s = substitute(child);
6406
+ if (s.keep) out[k] = s.value;
6407
+ }
6408
+ return {
6409
+ keep: true,
6410
+ value: out
6411
+ };
6412
+ }
6413
+ return {
6414
+ keep: true,
6415
+ value: v
6416
+ };
6417
+ };
6418
+ return {
6419
+ value: substitute(value).value,
6420
+ unresolved
6421
+ };
6422
+ }
6423
+ /** An addon tried to replace a stored secret it could not read. Nothing was written. */
6424
+ var SecretOverwriteRefusedError = class extends Error {
6425
+ ref;
6426
+ reason;
6427
+ constructor(ref, reason) {
6428
+ 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.`);
6429
+ this.ref = ref;
6430
+ this.reason = reason;
6431
+ this.name = "SecretOverwriteRefusedError";
6432
+ }
6433
+ };
6434
+ function isRecord$3(value) {
6435
+ return typeof value === "object" && value !== null && !Array.isArray(value);
6436
+ }
6437
+ function resolvedValue(pass, marker) {
6438
+ const answer = pass.answers[marker.$secret];
6439
+ return answer?.kind === "value" ? answer.value : null;
6440
+ }
6441
+ async function atMarker(pass, incoming, stored) {
6442
+ if (incoming === null) return stored;
6443
+ if (typeof incoming !== "string") return incoming;
6444
+ if (incoming === resolvedValue(pass, stored)) return stored;
6445
+ const intent = classifySecretWrite(incoming);
6446
+ if (intent.kind !== "set") return stored;
6447
+ const ref = stored.$secret;
6448
+ if (!isSecretRefOwnedBy(ref, pass.secrets.owner)) return incoming;
6449
+ const answer = pass.answers[ref];
6450
+ 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);
6451
+ try {
6452
+ await pass.secrets.put(ref, intent.value);
6453
+ } catch (err) {
6454
+ throw new KeychainWriteRefusedError(ref, err);
6455
+ }
6456
+ pass.changedRefs.push(ref);
6457
+ return stored;
6458
+ }
6459
+ function inArray(pass, incoming, stored) {
6460
+ return incoming.map((item, index) => {
6461
+ const twin = stored[index];
6462
+ if (isSecretMarker(twin)) return typeof item === "string" && item === resolvedValue(pass, twin) ? twin : item;
6463
+ if (isRecord$3(item) && isRecord$3(twin)) return inArrayRow(pass, item, twin);
6464
+ if (Array.isArray(item) && Array.isArray(twin)) return inArray(pass, item, twin);
6465
+ return item;
6466
+ });
6467
+ }
6468
+ function inArrayRow(pass, incoming, stored) {
6469
+ const out = { ...incoming };
6470
+ for (const [key, value] of Object.entries(incoming)) {
6471
+ const twin = stored[key];
6472
+ if (isSecretMarker(twin)) {
6473
+ if (typeof value === "string" && value === resolvedValue(pass, twin)) out[key] = twin;
6474
+ } else if (isRecord$3(value) && isRecord$3(twin)) out[key] = inArrayRow(pass, value, twin);
6475
+ else if (Array.isArray(value) && Array.isArray(twin)) out[key] = inArray(pass, value, twin);
6476
+ }
6477
+ return out;
6478
+ }
6479
+ async function walk(pass, incoming, stored) {
6480
+ if (isSecretMarker(stored)) return atMarker(pass, incoming, stored);
6481
+ if (Array.isArray(incoming) && Array.isArray(stored)) return inArray(pass, incoming, stored);
6482
+ if (!isRecord$3(incoming) || !isRecord$3(stored)) return incoming;
6483
+ const out = { ...incoming };
6484
+ for (const [key, value] of Object.entries(incoming)) out[key] = await walk(pass, value, stored[key]);
6485
+ return out;
6486
+ }
6487
+ /** Restore markers a write-back carries as values. See the file doc. */
6488
+ async function restoreUnchangedSecrets(input) {
6489
+ const refs = [];
6490
+ for (const key of Object.keys(input.patch)) collectSecretMarkerRefs(input.stored[key], refs);
6491
+ const owned = refs.filter((ref) => isSecretRefOwnedBy(ref, input.secrets.owner));
6492
+ if (owned.length === 0) return {
6493
+ patch: input.patch,
6494
+ changedRefs: []
6495
+ };
6496
+ const pass = {
6497
+ secrets: input.secrets,
6498
+ answers: await input.secrets.resolve([...new Set(owned)]),
6499
+ operatorWrite: input.operatorWrite,
6500
+ changedRefs: []
6501
+ };
6502
+ const out = {};
6503
+ for (const [key, value] of Object.entries(input.patch)) out[key] = await walk(pass, value, input.stored[key]);
6504
+ return {
6505
+ patch: out,
6506
+ changedRefs: pass.changedRefs
6507
+ };
6508
+ }
6509
+ /** Structural equality over JSON-shaped values (key order does not matter). */
6510
+ function isJsonEqual(a, b) {
6511
+ if (Object.is(a, b)) return true;
6512
+ if (Array.isArray(a)) return Array.isArray(b) && a.length === b.length && a.every((v, i) => isJsonEqual(v, b[i]));
6513
+ if (isRecord$3(a) && isRecord$3(b)) {
6514
+ const keys = Object.keys(a);
6515
+ if (keys.length !== Object.keys(b).length) return false;
6516
+ return keys.every((k) => Object.prototype.hasOwnProperty.call(b, k) && isJsonEqual(a[k], b[k]));
6517
+ }
6518
+ return false;
6519
+ }
6520
+ /** The patch without the keys whose value already equals the stored one. */
6521
+ function dropUnchangedKeys(patch, stored) {
6522
+ const out = {};
6523
+ for (const [key, value] of Object.entries(patch)) {
6524
+ if (Object.prototype.hasOwnProperty.call(stored, key) && isJsonEqual(value, stored[key])) continue;
6525
+ out[key] = value;
6526
+ }
6527
+ return out;
6528
+ }
6529
+ /** The top-level keys of a blob that hold at least one of `owner`'s markers. */
6530
+ function markerKeysOf(blob, owner) {
6531
+ const keys = /* @__PURE__ */ new Set();
6532
+ for (const [key, value] of Object.entries(blob)) if (collectSecretMarkerRefs(value).some((ref) => isSecretRefOwnedBy(ref, owner))) keys.add(key);
6533
+ return keys;
6534
+ }
6535
+ function nodeFromStored(value, owner) {
6536
+ if (isSecretMarker(value)) return isSecretRefOwnedBy(value.$secret, owner) ? { kind: "leaf" } : null;
6537
+ if (!isRecord$3(value)) return null;
6538
+ const children = /* @__PURE__ */ new Map();
6539
+ for (const [key, child] of Object.entries(value)) {
6540
+ const node = nodeFromStored(child, owner);
6541
+ if (node !== null) children.set(key, node);
6542
+ }
6543
+ return children.size > 0 ? {
6544
+ kind: "object",
6545
+ children
6546
+ } : null;
6547
+ }
6548
+ /**
6549
+ * The declared secret tree, widened by every place the STORED blob holds a
6550
+ * marker under one of `keys` — so a marker the schema no longer declares (or
6551
+ * never declared: Wyze before b4906cec6) still gets the save path's
6552
+ * KEEP / SET / CLEAR semantics instead of being overwritten by whatever the
6553
+ * addon writes. Markers inside arrays are not added: a row has no id field to
6554
+ * match by unless the schema declares one. Only `owner`'s markers count: a
6555
+ * builtin that keeps another addon's marker (device-manager) never takes it
6556
+ * over.
6557
+ */
6558
+ function widenTreeWithStoredMarkers(declared, stored, keys, owner) {
6559
+ const added = /* @__PURE__ */ new Map();
6560
+ for (const key of keys) {
6561
+ const at = key.indexOf("@");
6562
+ const base = at > 0 ? key.slice(0, at) : key;
6563
+ if (declared.has(base) || added.has(base)) continue;
6564
+ const node = nodeFromStored(stored[key], owner);
6565
+ if (node !== null) added.set(base, node);
6566
+ }
6567
+ return added.size === 0 ? declared : new Map([...declared, ...added]);
6568
+ }
6569
+ /** The blob as stored now; a failed read REFUSES the write instead of guessing. */
6570
+ async function readStoredAddonBlob(raw) {
6571
+ const threeWay = raw.readAddonStoreResult;
6572
+ if (threeWay === void 0) return raw.readAddonStore();
6573
+ const result = await threeWay.call(raw);
6574
+ if (result.kind === "failed") throw new Error(`settings write refused: the stored blob could not be read (${result.error})`);
6575
+ return result.kind === "missing" ? {} : result.value;
6576
+ }
6577
+ function touchesTree(tree, patch) {
6578
+ if (tree.size === 0) return false;
6579
+ for (const key of Object.keys(patch)) {
6580
+ const at = key.indexOf("@");
6581
+ if (tree.has(at > 0 ? key.slice(0, at) : key)) return true;
6582
+ }
6583
+ return false;
6584
+ }
6585
+ /**
6586
+ * Which top-level keys of each store held markers when last seen. `undefined`
6587
+ * for a store not seen yet: its first write reads it, to be safe.
6588
+ */
6589
+ var MarkerKeyIndex = class {
6590
+ owner;
6591
+ byStore = /* @__PURE__ */ new Map();
6592
+ constructor(owner) {
6593
+ this.owner = owner;
6594
+ }
6595
+ seen(store, blob) {
6596
+ this.byStore.set(store, markerKeysOf(blob, this.owner));
6597
+ }
6598
+ wrote(store, patch) {
6599
+ const keys = this.byStore.get(store);
6600
+ if (keys === void 0) return;
6601
+ const now = markerKeysOf(patch, this.owner);
6602
+ for (const key of Object.keys(patch)) if (now.has(key)) keys.add(key);
6603
+ else keys.delete(key);
6604
+ }
6605
+ mayHoldMarkers(store, patch) {
6606
+ const keys = this.byStore.get(store);
6607
+ if (keys === void 0) return true;
6608
+ return Object.keys(patch).some((key) => keys.has(key));
6609
+ }
6610
+ };
6611
+ function createHandle(raw, opts) {
6612
+ const chains = /* @__PURE__ */ new Map();
6613
+ const serialize = (key, fn) => {
6614
+ const next = (chains.get(key) ?? Promise.resolve()).then(fn, fn);
6615
+ const tail = next.catch(() => void 0);
6616
+ chains.set(key, tail);
6617
+ tail.then(() => {
6618
+ if (chains.get(key) === tail) chains.delete(key);
6619
+ });
6620
+ return next;
6621
+ };
6622
+ const index = new MarkerKeyIndex(opts.secrets.owner);
6623
+ const resolveRead = async (store, blob) => {
6624
+ index.seen(store, blob);
6625
+ const { value, unresolved } = await resolveSecretMarkers(blob, opts.secrets, {
6626
+ unresolved: "keep-marker",
6627
+ ownedBy: opts.secrets.owner
6628
+ });
6629
+ if (unresolved.length > 0) opts.onUnresolved?.(unresolved);
6630
+ return value;
6631
+ };
6632
+ const write = async (store, declared, scope, patch, readStored, rawWrite) => {
6633
+ if (!touchesTree(declared, patch) && !index.mayHoldMarkers(store, patch)) {
6634
+ await rawWrite(patch);
6635
+ index.wrote(store, patch);
6636
+ return { changed: true };
6637
+ }
6638
+ return serialize(store, async () => {
6639
+ const stored = await readStored();
6640
+ index.seen(store, stored);
6641
+ const operatorWrite = opts.isOperatorWrite?.() === true;
6642
+ const restored = await restoreUnchangedSecrets({
6643
+ patch,
6644
+ stored,
6645
+ secrets: opts.secrets,
6646
+ operatorWrite
6647
+ });
6648
+ const result = await transformSecretWrite({
6649
+ tree: widenTreeWithStoredMarkers(declared, stored, Object.keys(restored.patch), opts.secrets.owner),
6650
+ secrets: opts.secrets,
6651
+ patch: restored.patch,
6652
+ stored,
6653
+ ...scope !== void 0 ? { scope } : {},
6654
+ operatorWrite
6655
+ });
6656
+ const effective = dropUnchangedKeys(result.patch, stored);
6657
+ const wroteBlob = Object.keys(effective).length > 0;
6658
+ if (wroteBlob) {
6659
+ await rawWrite(effective);
6660
+ index.wrote(store, effective);
6661
+ }
6662
+ const { orphaned } = await result.afterWrite();
6663
+ if (orphaned.length > 0) opts.onOrphaned(orphaned);
6664
+ return { changed: wroteBlob || restored.changedRefs.length > 0 };
6665
+ });
6666
+ };
6667
+ const writeAddon = (patch) => write("addon", opts.addonTree(), void 0, patch, () => readStoredAddonBlob(raw), (p) => raw.writeAddonStore(p));
6668
+ const readAddonStoreResult = raw.readAddonStoreResult;
6669
+ const readAddonStoreKeyResult = raw.readAddonStoreKeyResult;
6670
+ const readDeviceStoreBatch = raw.readDeviceStoreBatch;
6671
+ const overrides = {
6672
+ readAddonStore: async () => resolveRead("addon", await raw.readAddonStore()),
6673
+ ...readAddonStoreResult !== void 0 ? { readAddonStoreResult: async () => {
6674
+ const result = await readAddonStoreResult.call(raw);
6675
+ return result.kind === "value" ? {
6676
+ kind: "value",
6677
+ value: await resolveRead("addon", result.value)
6678
+ } : result;
6679
+ } } : {},
6680
+ ...readAddonStoreKeyResult !== void 0 ? { readAddonStoreKeyResult: async (key) => {
6681
+ const result = await readAddonStoreKeyResult.call(raw, key);
6682
+ if (result.kind !== "present") return result;
6683
+ const { value, unresolved } = await resolveSecretMarkers({ [key]: result.value }, opts.secrets, {
6684
+ unresolved: "keep-marker",
6685
+ ownedBy: opts.secrets.owner
6686
+ });
6687
+ if (unresolved.length > 0) opts.onUnresolved?.(unresolved);
6688
+ return {
6689
+ kind: "present",
6690
+ value: value[key]
6691
+ };
6692
+ } } : {},
6693
+ readDeviceStore: async (deviceId) => resolveRead(`device:${deviceId}`, await raw.readDeviceStore(deviceId)),
6694
+ ...readDeviceStoreBatch !== void 0 ? { readDeviceStoreBatch: async (deviceIds) => {
6695
+ const rows = await readDeviceStoreBatch.call(raw, deviceIds);
6696
+ const out = /* @__PURE__ */ new Map();
6697
+ for (const [deviceId, blob] of rows) out.set(deviceId, await resolveRead(`device:${deviceId}`, blob));
6698
+ return out;
6699
+ } } : {},
6700
+ writeAddonStore: async (patch) => {
6701
+ await writeAddon(patch);
6702
+ },
6703
+ writeDeviceStore: async (deviceId, patch) => {
6704
+ await write(`device:${deviceId}`, opts.deviceTree(), {
6705
+ kind: "device",
6706
+ deviceId
6707
+ }, patch, () => raw.readDeviceStore(deviceId), (p) => raw.writeDeviceStore(deviceId, p));
6708
+ }
6709
+ };
6710
+ return {
6711
+ settings: new Proxy(raw, { get(target, prop, receiver) {
6712
+ if (typeof prop === "string" && Object.prototype.hasOwnProperty.call(overrides, prop)) return Reflect.get(overrides, prop);
6713
+ const value = Reflect.get(target, prop, receiver);
6714
+ return typeof value === "function" ? value.bind(target) : value;
6715
+ } }),
6716
+ raw: {
6717
+ readAddonStore: async () => {
6718
+ const blob = await raw.readAddonStore();
6719
+ index.seen("addon", blob);
6720
+ return blob;
6721
+ },
6722
+ readDeviceStore: async (deviceId) => {
6723
+ const blob = await raw.readDeviceStore(deviceId);
6724
+ index.seen(`device:${deviceId}`, blob);
6725
+ return blob;
6726
+ }
6727
+ },
6728
+ writeAddonStore: writeAddon
6729
+ };
6730
+ }
6731
+ /** The context the addon sees, plus the private raw view and write outcome. */
6732
+ function createSecretAwareContext(context, opts) {
6733
+ const raw = context.settings;
6734
+ if (raw === void 0) return {
6735
+ context,
6736
+ handle: null
6737
+ };
6738
+ const handle = createHandle(raw, opts);
6739
+ return {
6740
+ context: new Proxy(context, { get(target, prop, receiver) {
6741
+ if (prop === "settings") return handle.settings;
6742
+ return Reflect.get(target, prop, receiver);
6743
+ } }),
6744
+ handle
6745
+ };
6746
+ }
6747
+ var LEAF = { kind: "leaf" };
6748
+ var DEFAULT_ITEM_ID_KEY = "id";
6749
+ function collectFields(fields, out) {
6750
+ for (const field of fields) {
6751
+ if (field.type === "group") {
6752
+ collectFields(field.fields, out);
6753
+ continue;
6754
+ }
6755
+ if (field.type === "sub-tabs") {
6756
+ for (const tab of field.tabs) collectFields(tab.fields, out);
6757
+ continue;
6758
+ }
6759
+ if (field.type === "editable-array") {
6760
+ const item = /* @__PURE__ */ new Map();
6761
+ for (const itemField of field.itemFields) if ("key" in itemField && isKeychainStoredField(itemField)) item.set(itemField.key, LEAF);
6762
+ if (item.size > 0) out.set(field.key, {
6763
+ kind: "array",
6764
+ idKey: field.itemIdKey ?? DEFAULT_ITEM_ID_KEY,
6765
+ item
6766
+ });
6767
+ continue;
6768
+ }
6769
+ if (!("key" in field) || typeof field.key !== "string") continue;
6770
+ if (isKeychainStoredField(field)) out.set(field.key, LEAF);
6771
+ }
6772
+ }
6773
+ /** The secret tree a settings schema declares. */
6774
+ function secretTreeFromSchema(schema) {
6775
+ const out = /* @__PURE__ */ new Map();
6776
+ if (schema === null) return out;
6777
+ for (const section of schema.sections) collectFields(section.fields, out);
6778
+ return out;
6779
+ }
6780
+ /** Parse `a.b[id].c` into segments; throws on a malformed path (a declaration bug). */
6781
+ function parseSecretStatePath(path) {
6782
+ const segments = [];
6783
+ for (const raw of path.split(".")) {
6784
+ const m = /^([^[\]]+)(?:\[([^[\]]+)\])?$/.exec(raw);
6785
+ if (m === null || m[1] === void 0) throw new Error(`secretStatePaths: malformed path "${path}"`);
6786
+ segments.push(m[2] !== void 0 ? {
6787
+ key: m[1],
6788
+ idKey: m[2]
6789
+ } : { key: m[1] });
6790
+ }
6791
+ if (segments.length === 0) throw new Error(`secretStatePaths: empty path`);
6792
+ if (segments[segments.length - 1]?.idKey !== void 0) throw new Error(`secretStatePaths: "${path}" ends on an array — name the member that is secret`);
6793
+ return segments;
6794
+ }
6795
+ function insert(into, segments) {
6796
+ const [head, ...rest] = segments;
6797
+ if (head === void 0) return;
6798
+ if (rest.length === 0) {
6799
+ into.set(head.key, LEAF);
6800
+ return;
6801
+ }
6802
+ const existing = into.get(head.key);
6803
+ if (head.idKey !== void 0) {
6804
+ const item = new Map(existing?.kind === "array" ? existing.item : []);
6805
+ insert(item, rest);
6806
+ into.set(head.key, {
6807
+ kind: "array",
6808
+ idKey: head.idKey,
6809
+ item
6810
+ });
6811
+ return;
6812
+ }
6813
+ const children = new Map(existing?.kind === "object" ? existing.children : []);
6814
+ insert(children, rest);
6815
+ into.set(head.key, {
6816
+ kind: "object",
6817
+ children
6818
+ });
6819
+ }
6820
+ /** Add hidden-state paths (`secretStatePaths`) to a schema-derived tree. */
6821
+ function mergeSecretStatePaths(tree, paths) {
6822
+ if (paths.length === 0) return tree;
6823
+ const out = new Map(tree);
6824
+ for (const path of paths) insert(out, parseSecretStatePath(path));
6825
+ return out;
6826
+ }
6827
+ /** First retry of a secret the keychain could not serve; doubles to {@link SECRET_RETRY_MAX_MS}. */
6828
+ var SECRET_RETRY_FIRST_MS = 5e3;
6829
+ var SECRET_RETRY_MAX_MS = 5 * 6e4;
6830
+ /** Coalesces a burst of `keychain.changed` events into one re-resolve. */
6831
+ var SECRET_CHANGE_DEBOUNCE_MS = 250;
5949
6832
  /**
5950
6833
  * Base class for CamStack addons. Eliminates settings boilerplate:
5951
6834
  *
@@ -6015,6 +6898,33 @@ var BaseAddon = class {
6015
6898
  settingsStoreReady = false;
6016
6899
  /** Default config values. Provided via constructor. */
6017
6900
  defaults;
6901
+ /**
6902
+ * Hidden-state paths that hold secrets (D787) — values the addon writes
6903
+ * itself (`updateGlobalSettings`, `state()`) that no form field declares.
6904
+ * Stored in the keychain exactly like a `password` field. Syntax:
6905
+ * `'snapshotSigningKey'`, `'identity.pincode'`, `'tokens[userId].accessToken'`
6906
+ * (`key[<id field>]` addresses array items by id, never by index).
6907
+ */
6908
+ secretStatePaths = [];
6909
+ _addonSecretTree = null;
6910
+ _deviceSecretTree = null;
6911
+ /** Refs the last resolved config pointed at — a change to one re-resolves. */
6912
+ _configSecretRefs = /* @__PURE__ */ new Set();
6913
+ _unresolvedSecrets = [];
6914
+ _secretRetryTimer = null;
6915
+ _secretRetryDelayMs = SECRET_RETRY_FIRST_MS;
6916
+ _secretChangeTimer = null;
6917
+ _secretChangeUnsub = null;
6918
+ /** >0 while an OPERATOR's settings write is being applied. */
6919
+ _operatorWriteDepth = 0;
6920
+ /**
6921
+ * The keychain-aware settings handle (D798). Its `raw` view is the ONLY way
6922
+ * to the marker-bearing blobs and stays private to this class: the form
6923
+ * hydrate and config resolution need markers, addon code never does.
6924
+ */
6925
+ _secretSettings = null;
6926
+ /** Refs an addon-facing read could not resolve — each is logged once per process. */
6927
+ _loggedUnresolvedReads = /* @__PURE__ */ new Set();
6018
6928
  constructor(defaults) {
6019
6929
  this.defaults = defaults;
6020
6930
  this._config = { ...defaults };
@@ -6050,8 +6960,26 @@ var BaseAddon = class {
6050
6960
  return this._config;
6051
6961
  }
6052
6962
  async initialize(context) {
6053
- this._ctx = context;
6963
+ const secrets = context.secrets;
6964
+ if (secrets !== void 0) {
6965
+ const { context: wrapped, handle } = createSecretAwareContext(context, {
6966
+ secrets,
6967
+ addonTree: () => this.addonSecretTree(),
6968
+ deviceTree: () => this.deviceSecretTree(),
6969
+ onOrphaned: (refs) => context.logger.warn("keychain refs dropped by a settings write could not be deleted", { meta: { refs: [...refs] } }),
6970
+ isOperatorWrite: () => this._operatorWriteDepth > 0,
6971
+ onUnresolved: (unresolved) => this.logUnresolvedRead(unresolved)
6972
+ });
6973
+ this._ctx = wrapped;
6974
+ this._secretSettings = handle;
6975
+ } else {
6976
+ this._ctx = context;
6977
+ this._secretSettings = null;
6978
+ }
6054
6979
  await this.resolveConfig();
6980
+ if (secrets !== void 0) this._secretChangeUnsub = secrets.onChange((ref) => {
6981
+ if (this._configSecretRefs.has(ref)) this.scheduleSecretReresolve(SECRET_CHANGE_DEBOUNCE_MS);
6982
+ });
6055
6983
  const result = await this.onInitialize();
6056
6984
  this.emitLifecycle(EventCategory.AddonStarted);
6057
6985
  const normalized = normalizeAddonInitResult(result);
@@ -6084,6 +7012,12 @@ var BaseAddon = class {
6084
7012
  */
6085
7013
  async onHubReachable() {}
6086
7014
  async shutdown() {
7015
+ this._secretChangeUnsub?.();
7016
+ this._secretChangeUnsub = null;
7017
+ if (this._secretRetryTimer !== null) clearTimeout(this._secretRetryTimer);
7018
+ if (this._secretChangeTimer !== null) clearTimeout(this._secretChangeTimer);
7019
+ this._secretRetryTimer = null;
7020
+ this._secretChangeTimer = null;
6087
7021
  this.emitLifecycle(EventCategory.AddonStopped);
6088
7022
  if (this.autoEmitReadiness) this.emitReadinessForProviders("down");
6089
7023
  await this.onShutdown();
@@ -6158,11 +7092,8 @@ var BaseAddon = class {
6158
7092
  async getGlobalSettings(overlay, cap, nodeId) {
6159
7093
  const schema = this.globalSettingsSchema(cap);
6160
7094
  if (!schema) return { sections: [] };
6161
- const projected = await this.resolveGlobalStore(nodeId, cap);
6162
- return hydrateSchema(schema, overlay ? {
6163
- ...projected,
6164
- ...overlay
6165
- } : projected);
7095
+ const projected = await this.readRawProjectedStore(nodeId, cap);
7096
+ return hydrateSchema(schema, overlay ? await this.overlayKeepingMarkers(projected, overlay) : projected, { inlineSecretsAsViews: true });
6166
7097
  }
6167
7098
  /**
6168
7099
  * The integration-level view of this addon's settings: exactly the sections
@@ -6207,11 +7138,11 @@ var BaseAddon = class {
6207
7138
  });
6208
7139
  }
6209
7140
  if (sections.length === 0) return null;
6210
- const projected = await this.resolveGlobalStore(nodeId);
7141
+ const projected = await this.readRawProjectedStore(nodeId);
6211
7142
  return hydrateSchema({
6212
7143
  ...schema,
6213
7144
  sections
6214
- }, projected);
7145
+ }, projected, { inlineSecretsAsViews: true });
6215
7146
  }
6216
7147
  /**
6217
7148
  * The raw addon store PROJECTED onto the target node's bare per-node keys:
@@ -6224,12 +7155,50 @@ var BaseAddon = class {
6224
7155
  * the store for custom option logic (option narrowing, value snapping) to
6225
7156
  * read it per-node — never `ctx.settings.readAddonStore()` directly.
6226
7157
  * `nodeId` omitted ⇒ the local node (node-blind injection from ctx).
7158
+ *
7159
+ * Keychain values come back RESOLVED (D798): a secret reads as its value,
7160
+ * never as a `{ $secret }` marker. One the keychain cannot serve right now
7161
+ * stays a marker — "stored, unavailable" (`isSecretMarker()` is true, and it
7162
+ * is listed in {@link unresolvedSecrets}) — never `''` and never absent, so
7163
+ * it cannot be mistaken for "nothing stored, mint a new one". Writing the
7164
+ * resolved blob back is a no-op for every unchanged secret.
6227
7165
  */
6228
7166
  async resolveGlobalStore(nodeId, cap) {
6229
7167
  const raw = await this._ctx?.settings?.readAddonStore() ?? {};
7168
+ return this.projectForNode(raw, nodeId, cap);
7169
+ }
7170
+ projectForNode(store, nodeId, cap) {
6230
7171
  const keys = this.perNodeKeys(cap);
6231
7172
  const node = normalizeNodeId(nodeId ?? this._ctx?.kernel?.localNodeId);
6232
- return keys.size > 0 ? projectStore(raw, keys, node) : raw;
7173
+ return keys.size > 0 ? projectStore(store, keys, node) : store;
7174
+ }
7175
+ /** The PROJECTED store with its markers — the form hydrate only (D798). */
7176
+ async readRawProjectedStore(nodeId, cap) {
7177
+ const raw = await this.rawSettings()?.readAddonStore() ?? {};
7178
+ return this.projectForNode(raw, nodeId, cap);
7179
+ }
7180
+ /**
7181
+ * `{ ...stored, ...overlay }`, except that an overlay member equal to the
7182
+ * RESOLVED stored one keeps the stored (marker-bearing) member — so a form
7183
+ * hydrated from a resolved overlay still shows a secret as "set", never as
7184
+ * its value.
7185
+ */
7186
+ async overlayKeepingMarkers(stored, overlay) {
7187
+ const secrets = this._ctx?.secrets;
7188
+ const merged = {
7189
+ ...stored,
7190
+ ...overlay
7191
+ };
7192
+ if (secrets === void 0 || collectSecretMarkerRefs(stored).length === 0) return merged;
7193
+ const { value: resolved } = await resolveSecretMarkers(stored, secrets, {
7194
+ unresolved: "keep-marker",
7195
+ ownedBy: secrets.owner
7196
+ });
7197
+ for (const key of Object.keys(overlay)) {
7198
+ if (collectSecretMarkerRefs(stored[key]).length === 0) continue;
7199
+ if (isJsonEqual(overlay[key], resolved[key])) merged[key] = stored[key];
7200
+ }
7201
+ return merged;
6233
7202
  }
6234
7203
  /**
6235
7204
  * Whether ONE global key of this addon's store was written, read three-way
@@ -6265,18 +7234,58 @@ var BaseAddon = class {
6265
7234
  value: result.value[key]
6266
7235
  };
6267
7236
  }
7237
+ /**
7238
+ * The OPERATOR's write — a settings form or an admin API call, dispatched by
7239
+ * the kernel. Identical to {@link updateGlobalSettings}, except that a secret
7240
+ * the operator sends is stored as sent even when it equals a pre-keychain
7241
+ * inline value: the operator re-entering a password is a change, an addon
7242
+ * writing back what it read is not (D787).
7243
+ */
7244
+ async updateGlobalSettingsAsOperator(patch, nodeId) {
7245
+ this._operatorWriteDepth++;
7246
+ try {
7247
+ await this.applyGlobalPatch(patch, nodeId);
7248
+ } finally {
7249
+ this._operatorWriteDepth--;
7250
+ }
7251
+ }
6268
7252
  async updateGlobalSettings(patch, nodeId) {
7253
+ await this.applyGlobalPatch(patch, nodeId);
7254
+ }
7255
+ /**
7256
+ * REMOVE stored secrets — their keychain values and their markers (D787).
7257
+ *
7258
+ * Writing `''` to a secret field KEEPS what is stored (an empty string is
7259
+ * what a defaults fallback writes back, and it must never destroy a
7260
+ * credential), so code that means "forget this token" says so here. Without
7261
+ * a keychain (an older kernel) it writes `''`, as such code always did.
7262
+ */
7263
+ async clearSecrets(keys, nodeId) {
7264
+ const tree = this.addonSecretTree();
7265
+ const keychain = this._ctx?.secrets !== void 0;
7266
+ const stored = keychain ? await this.readAddonStoreWithRetry() : {};
7267
+ const patch = {};
7268
+ for (const key of keys) {
7269
+ const keychainStored = tree.has(key) || collectSecretMarkerRefs(stored[key]).length > 0;
7270
+ patch[key] = keychain && keychainStored ? SECRET_CLEAR : "";
7271
+ }
7272
+ await this.applyGlobalPatch(patch, nodeId);
7273
+ }
7274
+ async applyGlobalPatch(barePatch, nodeId) {
6269
7275
  const keys = this.perNodeKeys();
6270
7276
  const localNode = normalizeNodeId(this._ctx?.kernel?.localNodeId);
6271
7277
  const target = normalizeNodeId(nodeId ?? this._ctx?.kernel?.localNodeId);
6272
- const barePatch = patch;
6273
7278
  const scoped = keys.size > 0 ? scopePatch(barePatch, keys, target) : barePatch;
6274
- await this._ctx?.settings?.writeAddonStore(scoped);
7279
+ const handle = this._secretSettings;
7280
+ if (handle !== null) {
7281
+ const { changed } = await handle.writeAddonStore(scoped);
7282
+ if (!changed) return;
7283
+ } else await this._ctx?.settings?.writeAddonStore(scoped);
6275
7284
  if (target !== localNode) return;
6276
7285
  await this.resolveConfig();
6277
7286
  await this.onConfigChanged();
6278
7287
  this.emitLifecycle(EventCategory.AddonUpdated, { level: "global" });
6279
- this.maybeAutoRestart(patch, this.globalSettingsSchema());
7288
+ this.maybeAutoRestart(Object.keys(barePatch), this.globalSettingsSchema());
6280
7289
  }
6281
7290
  /**
6282
7291
  * The set of field keys the global settings schema declares `perNode: true`
@@ -6301,7 +7310,7 @@ var BaseAddon = class {
6301
7310
  * time to return its response before the addon is torn down and
6302
7311
  * re-initialised by `AddonRegistryService.restartAddon`.
6303
7312
  */
6304
- maybeAutoRestart(patch, schema) {
7313
+ maybeAutoRestart(patchKeys, schema) {
6305
7314
  if (!schema) return;
6306
7315
  const restartKeys = /* @__PURE__ */ new Set();
6307
7316
  for (const section of schema.sections) for (const field of section.fields) {
@@ -6309,13 +7318,13 @@ var BaseAddon = class {
6309
7318
  if (field.requiresRestart) restartKeys.add(field.key);
6310
7319
  }
6311
7320
  if (restartKeys.size === 0) return;
6312
- if (!Object.keys(patch).some((k) => restartKeys.has(k))) return;
7321
+ if (!patchKeys.some((k) => restartKeys.has(k))) return;
6313
7322
  const ctx = this._ctx;
6314
7323
  if (!ctx) return;
6315
7324
  const addonId = ctx.id;
6316
7325
  setImmediate(() => {
6317
7326
  ctx.api.addons?.restartAddon?.mutate({ addonId }).then(() => {
6318
- ctx.logger.info("addon auto-restart triggered by restart-required setting change", { meta: { changedFields: Object.keys(patch).filter((k) => restartKeys.has(k)) } });
7327
+ ctx.logger.info("addon auto-restart triggered by restart-required setting change", { meta: { changedFields: patchKeys.filter((k) => restartKeys.has(k)) } });
6319
7328
  }).catch((err) => {
6320
7329
  ctx.logger.error("addon auto-restart failed", { meta: { error: err instanceof Error ? err.message : String(err) } });
6321
7330
  });
@@ -6324,7 +7333,7 @@ var BaseAddon = class {
6324
7333
  async getDeviceSettings(deviceId) {
6325
7334
  const schema = this.deviceSettingsSchema();
6326
7335
  if (!schema) return { sections: [] };
6327
- return hydrateSchema(schema, await this._ctx?.settings?.readDeviceStore(deviceId) ?? {});
7336
+ return hydrateSchema(schema, await this.rawSettings()?.readDeviceStore(deviceId) ?? {}, { inlineSecretsAsViews: true });
6328
7337
  }
6329
7338
  async updateDeviceSettings(deviceId, patch) {
6330
7339
  await this._ctx?.settings?.writeDeviceStore(deviceId, patch);
@@ -6454,7 +7463,7 @@ var BaseAddon = class {
6454
7463
  * selection at boot (absent scoped key ⇒ the constructor default wins).
6455
7464
  */
6456
7465
  async resolveConfig() {
6457
- const stored = await this.readAddonStoreWithRetry();
7466
+ const stored = await this.resolveStoredSecrets(await this.readAddonStoreWithRetry());
6458
7467
  const perNode = this.perNodeKeys();
6459
7468
  const localNode = normalizeNodeId(this._ctx?.kernel?.localNodeId);
6460
7469
  const resolved = { ...this.defaults };
@@ -6479,7 +7488,7 @@ var BaseAddon = class {
6479
7488
  key,
6480
7489
  schema,
6481
7490
  fallback,
6482
- read: () => this.readAddonStoreWithRetry(),
7491
+ read: async () => this.resolveStoredSecrets(await this.readAddonStoreWithRetry()),
6483
7492
  write: async (patch) => {
6484
7493
  await this._ctx?.settings?.writeAddonStore(patch);
6485
7494
  },
@@ -6496,7 +7505,7 @@ var BaseAddon = class {
6496
7505
  key,
6497
7506
  schema,
6498
7507
  fallback,
6499
- read: async () => await this._ctx?.settings?.readDeviceStore(deviceId) ?? {},
7508
+ read: async () => this.resolveStoredSecrets(await this.rawSettings()?.readDeviceStore(deviceId) ?? {}, false),
6500
7509
  write: async (patch) => {
6501
7510
  await this._ctx?.settings?.writeDeviceStore(deviceId, patch);
6502
7511
  },
@@ -6508,6 +7517,87 @@ var BaseAddon = class {
6508
7517
  } })
6509
7518
  });
6510
7519
  }
7520
+ /** The addon store's secret tree: schema fields by TYPE, plus `secretStatePaths`. */
7521
+ addonSecretTree() {
7522
+ this._addonSecretTree ??= mergeSecretStatePaths(secretTreeFromSchema(this.globalSettingsSchema()), this.secretStatePaths);
7523
+ return this._addonSecretTree;
7524
+ }
7525
+ deviceSecretTree() {
7526
+ this._deviceSecretTree ??= secretTreeFromSchema(this.deviceSettingsSchema());
7527
+ return this._deviceSecretTree;
7528
+ }
7529
+ /**
7530
+ * Secrets of this addon's stored config that could not be resolved on the
7531
+ * last read, with why. Non-empty means the addon is running WITHOUT them —
7532
+ * an addon whose function needs one should report itself degraded rather
7533
+ * than start on an empty credential.
7534
+ */
7535
+ get unresolvedSecrets() {
7536
+ return this._unresolvedSecrets;
7537
+ }
7538
+ /**
7539
+ * Substitute every keychain marker in a stored blob with its value. With no
7540
+ * keychain (no `ctx.secrets`) or no marker, the blob comes back unchanged.
7541
+ * An unresolvable value is LEFT OUT (never `''`), logged by ref — never by
7542
+ * value — and, when the cause can pass, retried with backoff. Nothing is
7543
+ * ever written back from here.
7544
+ */
7545
+ async resolveStoredSecrets(blob, trackForConfig = true) {
7546
+ const secrets = this._ctx?.secrets;
7547
+ if (secrets === void 0) return blob;
7548
+ const refs = collectSecretMarkerRefs(blob);
7549
+ if (trackForConfig) this._configSecretRefs = new Set(refs);
7550
+ if (refs.length === 0) {
7551
+ if (trackForConfig) this._unresolvedSecrets = [];
7552
+ return blob;
7553
+ }
7554
+ const { value, unresolved } = await resolveSecretMarkers(blob, secrets);
7555
+ if (trackForConfig) {
7556
+ this._unresolvedSecrets = unresolved;
7557
+ if (unresolved.length > 0) {
7558
+ this._ctx?.logger?.error?.("secret unavailable — running without it, will retry", { meta: { secrets: unresolved.map((u) => ({
7559
+ ref: u.ref,
7560
+ reason: u.reason
7561
+ })) } });
7562
+ if (unresolved.some((u) => u.reason !== "missing" && u.reason !== "forbidden")) {
7563
+ this.scheduleSecretReresolve(this._secretRetryDelayMs);
7564
+ this._secretRetryDelayMs = Math.min(this._secretRetryDelayMs * 2, SECRET_RETRY_MAX_MS);
7565
+ }
7566
+ } else this._secretRetryDelayMs = SECRET_RETRY_FIRST_MS;
7567
+ }
7568
+ return value;
7569
+ }
7570
+ /**
7571
+ * The marker-bearing settings reads (D798) — private on purpose. Without a
7572
+ * keychain the context's own view is already raw.
7573
+ */
7574
+ rawSettings() {
7575
+ return this._secretSettings?.raw ?? this._ctx?.settings;
7576
+ }
7577
+ /** An addon-facing read met markers it could not resolve: say so once per ref. */
7578
+ logUnresolvedRead(unresolved) {
7579
+ const fresh = unresolved.filter((u) => !this._loggedUnresolvedReads.has(u.ref));
7580
+ if (fresh.length === 0) return;
7581
+ for (const u of fresh) this._loggedUnresolvedReads.add(u.ref);
7582
+ 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) => ({
7583
+ ref: u.ref,
7584
+ reason: u.reason
7585
+ })) } });
7586
+ }
7587
+ /** Re-resolve the config (a keychain-only change, or a retry) and apply it. */
7588
+ scheduleSecretReresolve(delayMs) {
7589
+ const timerOf = delayMs === SECRET_CHANGE_DEBOUNCE_MS ? "_secretChangeTimer" : "_secretRetryTimer";
7590
+ if (this[timerOf] !== null) return;
7591
+ const timer = setTimeout(() => {
7592
+ this[timerOf] = null;
7593
+ if (this._ctx === null) return;
7594
+ this.resolveConfig().then(() => this.onConfigChanged()).catch((err) => {
7595
+ this._ctx?.logger?.error?.("re-resolving secrets failed", { meta: { error: err instanceof Error ? err.message : String(err) } });
7596
+ });
7597
+ }, delayMs);
7598
+ timer.unref?.();
7599
+ this[timerOf] = timer;
7600
+ }
6511
7601
  /**
6512
7602
  * Wrap `ctx.settings.readAddonStore()` with a short retry budget so a
6513
7603
  * transient settings-store outage (mid-restart of sqlite-settings, tsx-watch
@@ -6520,7 +7610,7 @@ var BaseAddon = class {
6520
7610
  * `{}` (defaults) — the addon's first successful patch will rehydrate.
6521
7611
  */
6522
7612
  async readAddonStoreWithRetry() {
6523
- const settings = this._ctx?.settings;
7613
+ const settings = this.rawSettings();
6524
7614
  if (!settings) return {};
6525
7615
  const delaysMs = [
6526
7616
  150,
@@ -9480,6 +10570,278 @@ var CameraSwitchGroupSchema = object({
9480
10570
  fetchedAt: number()
9481
10571
  });
9482
10572
  /**
10573
+ * The trainer contract — what the hub hands the cloud trainer and what it
10574
+ * gets back (cloud training, D805+).
10575
+ *
10576
+ * The trainer (`hf/camstack-trainer`, published as the Hugging Face repo
10577
+ * `camstack/camstack-trainer`) is a separate AGPL program the hub never
10578
+ * imports: `job.json` goes in, files come out, and progress is `CAMSTACK_EVENT`
10579
+ * lines on stdout. These schemas are the hub's half of that boundary; the
10580
+ * trainer's pydantic models (and the JSON Schemas generated from them under
10581
+ * `hf/camstack-trainer/schemas/`) are the other half. A change here is a
10582
+ * change there, in the same piece of work.
10583
+ *
10584
+ * No `.default()` anywhere: defaults do not run on the addon cap path, so the
10585
+ * orchestrator fills every field of a job spec explicitly.
10586
+ */
10587
+ var TRAINING_JOB_SCHEMA = "camstack.training/v1";
10588
+ var TRAINING_RESULT_SCHEMA = "camstack.training-result/v1";
10589
+ /** What the trainer can export. Edge TPU is a later, separate image. */
10590
+ var TrainingExportSchema = _enum([
10591
+ "onnx",
10592
+ "openvino-fp16",
10593
+ "openvino-int8",
10594
+ "coreml-fp16"
10595
+ ]);
10596
+ var FloorsSchema = record(string(), number().min(0).max(1));
10597
+ object({
10598
+ schema: literal(TRAINING_JOB_SCHEMA),
10599
+ jobKey: string().uuid(),
10600
+ target: object({
10601
+ kind: literal("detector"),
10602
+ step: literal("object-detection")
10603
+ }),
10604
+ base: object({
10605
+ modelId: string().min(1),
10606
+ /** Ultralytics weights id, e.g. `yolov9m.pt`. */
10607
+ weights: string().min(1),
10608
+ imgsz: number().int().positive()
10609
+ }),
10610
+ baseline: object({
10611
+ modelId: string().min(1),
10612
+ /** The baseline ONNX the holdout comparison runs; public mirror URL. */
10613
+ onnxUrl: string().url(),
10614
+ imgsz: number().int().positive(),
10615
+ floors: FloorsSchema
10616
+ }),
10617
+ dataset: object({
10618
+ versionId: string().min(1),
10619
+ annotationHash: string(),
10620
+ /** sha256 of the uploaded archive; the trainer refuses a mismatch (exit 65). */
10621
+ sha256: string().regex(/^[0-9a-f]{64}$/)
10622
+ }),
10623
+ split: object({
10624
+ holdoutCameras: array(number().int()),
10625
+ /** When no camera is held out: the last N days of every camera. */
10626
+ holdoutLastDays: number().int().nonnegative(),
10627
+ valFraction: number().min(0).max(.5),
10628
+ seed: number().int()
10629
+ }),
10630
+ hyper: object({
10631
+ epochs: number().int().positive(),
10632
+ batch: number().int().positive(),
10633
+ lr0: number().positive(),
10634
+ /** Layers frozen from the start of the backbone; 0 = none. */
10635
+ freeze: number().int().nonnegative(),
10636
+ patience: number().int().nonnegative(),
10637
+ seed: number().int()
10638
+ }),
10639
+ replay: object({
10640
+ source: literal("coco2017"),
10641
+ count: number().int().nonnegative()
10642
+ }),
10643
+ exports: array(TrainingExportSchema).min(1),
10644
+ calibration: object({ maxFrames: number().int().positive() }),
10645
+ floors: object({
10646
+ minSupport: number().int().positive(),
10647
+ clamp: number().min(0).max(1)
10648
+ }),
10649
+ int8Gate: object({ maxMap50Drop: number().min(0).max(1) }),
10650
+ catalog: object({
10651
+ id: string().regex(/^[a-z0-9][a-z0-9-]{2,80}$/),
10652
+ name: string().min(1).max(160)
10653
+ })
10654
+ });
10655
+ /** One regular file of the bundle. An mlpackage contributes one row per member. */
10656
+ var TrainingResultFileSchema = object({
10657
+ path: string().min(1),
10658
+ bytes: number().int().nonnegative(),
10659
+ sha256: string().regex(/^[0-9a-f]{64}$/),
10660
+ format: _enum([
10661
+ "onnx",
10662
+ "openvino",
10663
+ "coreml",
10664
+ "pt"
10665
+ ]),
10666
+ variant: _enum(["base", "int8"])
10667
+ });
10668
+ var DraftFormatSchema = object({
10669
+ /** RELATIVE path inside the bundle; the hub rewrites it to `camstack-local://`. */
10670
+ url: string().min(1),
10671
+ sizeMB: number().nonnegative(),
10672
+ isDirectory: boolean().optional(),
10673
+ files: array(string()).optional(),
10674
+ runtimes: array(literal("python")).optional(),
10675
+ revision: string().min(1)
10676
+ });
10677
+ /** The trainer's half of a catalog entry; the hub completes it (labels, licence, group). */
10678
+ var TrainingCatalogDraftSchema = object({
10679
+ id: string().min(1),
10680
+ name: string().min(1),
10681
+ description: string(),
10682
+ labels: array(unknown()),
10683
+ inputSize: object({
10684
+ width: number().int().positive(),
10685
+ height: number().int().positive()
10686
+ }),
10687
+ preprocessMode: literal("letterbox"),
10688
+ defaultClassFloors: FloorsSchema,
10689
+ formats: object({
10690
+ onnx: DraftFormatSchema.optional(),
10691
+ openvino: DraftFormatSchema.optional(),
10692
+ coreml: DraftFormatSchema.optional()
10693
+ })
10694
+ });
10695
+ /** One class of one model's holdout report (the eval harness's summary). */
10696
+ var TrainingEvalClassSchema = object({
10697
+ positives: number().int(),
10698
+ floor: number().nullable(),
10699
+ tp: number().int(),
10700
+ fp: number().int(),
10701
+ fn: number().int(),
10702
+ precision: number().nullable(),
10703
+ recall: number().nullable(),
10704
+ ap50: number().nullable(),
10705
+ recallByCamera: record(string(), number().nullable()).optional(),
10706
+ recallByLight: record(string(), number().nullable()).optional(),
10707
+ fpByCamera: record(string(), number()).optional(),
10708
+ smallFound: number().int().optional(),
10709
+ smallTotal: number().int().optional()
10710
+ }).passthrough();
10711
+ var TrainingEvalReportSchema = object({
10712
+ frames: number().int(),
10713
+ classes: record(string(), TrainingEvalClassSchema)
10714
+ }).passthrough();
10715
+ /**
10716
+ * A succeeded result carries every block; a failed one carries the error and
10717
+ * whatever was known by then — the other blocks are ABSENT, not null. The
10718
+ * orchestrator checks the blocks it needs before it trusts a success.
10719
+ */
10720
+ var TrainingResultSchema = object({
10721
+ schema: literal(TRAINING_RESULT_SCHEMA),
10722
+ jobKey: string(),
10723
+ status: _enum(["succeeded", "failed"]),
10724
+ error: object({
10725
+ stage: string(),
10726
+ code: string(),
10727
+ message: string()
10728
+ }).nullable(),
10729
+ trainer: object({
10730
+ version: string(),
10731
+ revision: string()
10732
+ }),
10733
+ toolchain: record(string(), string().nullable()),
10734
+ dataset: object({
10735
+ versionId: string(),
10736
+ annotationHash: string(),
10737
+ sha256: string(),
10738
+ frames: object({
10739
+ train: number().int(),
10740
+ val: number().int(),
10741
+ holdout: number().int()
10742
+ }),
10743
+ holdoutCameras: array(number().int()),
10744
+ replayImages: number().int()
10745
+ }).optional(),
10746
+ training: object({
10747
+ epochsRun: number().int(),
10748
+ bestEpoch: number().int(),
10749
+ bestMap50: number(),
10750
+ bestMap50_95: number(),
10751
+ seconds: number()
10752
+ }).optional(),
10753
+ evaluation: object({
10754
+ holdoutFrames: number().int(),
10755
+ baseline: TrainingEvalReportSchema.nullable(),
10756
+ candidate: TrainingEvalReportSchema.nullable(),
10757
+ candidateInt8: TrainingEvalReportSchema.nullable(),
10758
+ recallDeltaByCamera: record(string(), record(string(), number())).nullable(),
10759
+ map50: record(string(), number().nullable())
10760
+ }).optional(),
10761
+ floors: object({
10762
+ baseline: FloorsSchema,
10763
+ candidate: FloorsSchema,
10764
+ candidateInt8: FloorsSchema.nullable(),
10765
+ notes: array(string())
10766
+ }).optional(),
10767
+ int8: object({
10768
+ kept: boolean(),
10769
+ map50Fp16: number().nullable(),
10770
+ map50Int8: number().nullable(),
10771
+ reason: string().nullable()
10772
+ }).optional(),
10773
+ exportsDropped: array(object({
10774
+ export: string(),
10775
+ reason: string()
10776
+ })).optional(),
10777
+ files: array(TrainingResultFileSchema).optional(),
10778
+ bundle: object({
10779
+ path: literal("bundle.tar"),
10780
+ bytes: number().int().nonnegative(),
10781
+ sha256: string().regex(/^[0-9a-f]{64}$/)
10782
+ }).nullable().optional(),
10783
+ catalogDraft: object({
10784
+ base: TrainingCatalogDraftSchema,
10785
+ int8: TrainingCatalogDraftSchema.nullable()
10786
+ }).nullable().optional(),
10787
+ licence: string()
10788
+ });
10789
+ var TrainingStageSchema = _enum([
10790
+ "prepare",
10791
+ "replay",
10792
+ "train",
10793
+ "eval",
10794
+ "export",
10795
+ "package"
10796
+ ]);
10797
+ var EventBase = {
10798
+ v: literal(1),
10799
+ ts: number()
10800
+ };
10801
+ discriminatedUnion("type", [
10802
+ object({
10803
+ ...EventBase,
10804
+ type: literal("stage"),
10805
+ stage: TrainingStageSchema
10806
+ }),
10807
+ object({
10808
+ ...EventBase,
10809
+ type: literal("epoch"),
10810
+ epoch: number().int(),
10811
+ epochs: number().int(),
10812
+ boxLoss: number().nullable().optional(),
10813
+ map50: number().nullable().optional(),
10814
+ map50_95: number().nullable().optional(),
10815
+ etaSec: number().nullable().optional()
10816
+ }),
10817
+ object({
10818
+ ...EventBase,
10819
+ type: literal("metric"),
10820
+ name: string(),
10821
+ value: number()
10822
+ }),
10823
+ object({
10824
+ ...EventBase,
10825
+ type: literal("artifact"),
10826
+ path: string(),
10827
+ bytes: number(),
10828
+ sha256: string()
10829
+ }),
10830
+ object({
10831
+ ...EventBase,
10832
+ type: literal("done"),
10833
+ status: _enum(["succeeded", "failed"]),
10834
+ resultSha256: string().nullable().optional()
10835
+ }),
10836
+ object({
10837
+ ...EventBase,
10838
+ type: literal("error"),
10839
+ stage: string(),
10840
+ code: string(),
10841
+ message: string()
10842
+ })
10843
+ ]);
10844
+ /**
9483
10845
  * What the gate decided about a birth, from the CALLER's point of view.
9484
10846
  *
9485
10847
  * Deliberately not `ConfirmationVerdict`: `undecided` is not a birth decision
@@ -11961,7 +13323,9 @@ var AddonHttpRouteSchema = object({
11961
13323
  "authenticated",
11962
13324
  "admin"
11963
13325
  ]).optional(),
11964
- description: string().optional()
13326
+ description: string().optional(),
13327
+ /** The hub limits this route per client address before the handler runs. */
13328
+ rateLimit: _enum(["auth"]).optional()
11965
13329
  });
11966
13330
  /**
11967
13331
  * Cross-process route invocation envelope. The hub captures the
@@ -12666,6 +14030,37 @@ var BackupDestinationInfoSchema = object({
12666
14030
  lastError: string().optional()
12667
14031
  });
12668
14032
  /**
14033
+ * How an archive is encrypted (operator decision 2026-10-09): to a backup
14034
+ * PUBLIC key the hub holds, so only the operator's secret key opens it.
14035
+ * Absent on a plain `.tar.gz` — every archive made before encryption, or
14036
+ * with it off — which restores without a key.
14037
+ */
14038
+ var BackupArchiveEncryptionSchema = object({
14039
+ /** `x25519-hkdf-aes256gcm-stream-v1`. */
14040
+ scheme: string(),
14041
+ /** 16 hex — the backup key whose secret restores this archive. */
14042
+ keyId: string()
14043
+ });
14044
+ /**
14045
+ * The backup encryption setting. The hub keeps PUBLIC keys only: the active
14046
+ * one new archives are encrypted to, and the retired ones older archives
14047
+ * still need. The secret key is shown once, at `setupEncryption`.
14048
+ */
14049
+ var BackupEncryptionStatusSchema = object({
14050
+ enabled: boolean(),
14051
+ active: object({
14052
+ keyId: string(),
14053
+ publicKey: string(),
14054
+ createdAt: number()
14055
+ }).nullable(),
14056
+ /** Every key ever set up, newest first. */
14057
+ keys: array(object({
14058
+ keyId: string(),
14059
+ createdAt: number(),
14060
+ retiredAt: number().nullable()
14061
+ })).readonly()
14062
+ });
14063
+ /**
12669
14064
  * Per-archive entry returned by `backup.listArchives({ destinationId })`.
12670
14065
  * Same shape the destination drill-in renders. Sourced from the per-
12671
14066
  * location `manifests.json` (no per-archive tarball read required).
@@ -12677,7 +14072,9 @@ var BackupArchiveEntrySchema = object({
12677
14072
  sizeBytes: number(),
12678
14073
  label: string().optional(),
12679
14074
  /** Top-level locations included in the archive (db, addons, tls, …). */
12680
- locations: array(string()).readonly()
14075
+ locations: array(string()).readonly(),
14076
+ /** Present when the archive is encrypted; restore then needs that key. */
14077
+ encryption: BackupArchiveEncryptionSchema.optional()
12681
14078
  });
12682
14079
  var BackupEntrySchema = object({
12683
14080
  id: string(),
@@ -12686,7 +14083,8 @@ var BackupEntrySchema = object({
12686
14083
  label: string().optional(),
12687
14084
  createdAt: number(),
12688
14085
  sizeBytes: number(),
12689
- locations: array(string()).optional()
14086
+ locations: array(string()).optional(),
14087
+ encryption: BackupArchiveEncryptionSchema.optional()
12690
14088
  });
12691
14089
  var ArchiveEntrySchema = object({
12692
14090
  path: string(),
@@ -12875,10 +14273,40 @@ method(_void(), array(BackupDestinationInfoSchema).readonly(), { auth: "admin" }
12875
14273
  * this list and skips entries whose path doesn't start with
12876
14274
  * any of them.
12877
14275
  */
12878
- locations: array(string()).optional()
14276
+ locations: array(string()).optional(),
14277
+ /**
14278
+ * The backup SECRET key, for an encrypted archive (ignored for a plain
14279
+ * one). The archive is decrypted into the hub's private staging
14280
+ * before the restart; the key is not stored. A wrong or missing key
14281
+ * is refused before the archive is downloaded.
14282
+ */
14283
+ backupSecretKey: string().optional()
12879
14284
  }), _void(), {
12880
14285
  kind: "mutation",
12881
14286
  auth: "admin"
14287
+ }), method(_void(), BackupEncryptionStatusSchema, { auth: "admin" }), method(object({}), object({
14288
+ keyId: string(),
14289
+ secretKey: string(),
14290
+ publicKey: string(),
14291
+ createdAt: number(),
14292
+ replacedKeyId: string().nullable()
14293
+ }), {
14294
+ kind: "mutation",
14295
+ auth: "admin"
14296
+ }), method(object({}), object({ disabledKeyId: string().nullable() }), {
14297
+ kind: "mutation",
14298
+ auth: "admin"
14299
+ }), method(object({ backupSecretKey: string() }), object({
14300
+ valid: boolean(),
14301
+ keyId: string().nullable(),
14302
+ /** The hub knows this key (active or retired). */
14303
+ known: boolean(),
14304
+ /** It is the key new archives are encrypted to. */
14305
+ active: boolean(),
14306
+ error: string().optional()
14307
+ }), {
14308
+ kind: "mutation",
14309
+ auth: "admin"
12882
14310
  }), method(object({
12883
14311
  destinationId: string(),
12884
14312
  backupId: string()
@@ -14502,7 +15930,60 @@ var CustomModelDescriptorSchema = object({
14502
15930
  stepId: string(),
14503
15931
  entry: ModelCatalogEntrySchema
14504
15932
  });
14505
- method(_void(), array(CustomModelDescriptorSchema).readonly(), { auth: "admin" });
15933
+ /** One regular file of an imported bundle, as the producer measured it. */
15934
+ var ModelBundleFileSchema = object({
15935
+ /** Relative path inside the bundle tar; an mlpackage member is `<x>.mlpackage/<member>`. */
15936
+ path: string().min(1),
15937
+ bytes: number().int().nonnegative(),
15938
+ sha256: string().regex(/^[0-9a-f]{64}$/)
15939
+ });
15940
+ var ImportModelBundleInputSchema = object({
15941
+ /** The registry provider that keeps the model (Model Studio). */
15942
+ addonId: string(),
15943
+ stepId: string().min(1),
15944
+ /**
15945
+ * The catalog rows to register, complete, every format URL already
15946
+ * `camstack-local://<modelId>/<file>` naming a file of the bundle. One
15947
+ * bundle may carry several rows (a base and its INT8 variant).
15948
+ */
15949
+ entries: array(ModelCatalogEntrySchema).min(1).max(4),
15950
+ /** The bundle tar, offered by the producer over `ctx.peerBytes` (same host). */
15951
+ bundle: object({
15952
+ ticket: PeerBytesTicketSchema,
15953
+ bytes: number().int().positive(),
15954
+ sha256: string().regex(/^[0-9a-f]{64}$/)
15955
+ }),
15956
+ /** Every file the tar must hold; anything missing, extra or different is refused. */
15957
+ files: array(ModelBundleFileSchema).min(1).max(64),
15958
+ /** Convert missing engine formats and push the model to every agent afterwards. */
15959
+ distribute: boolean()
15960
+ });
15961
+ var ImportModelBundleResultSchema = discriminatedUnion("kind", [object({
15962
+ kind: literal("imported"),
15963
+ modelIds: array(string()).readonly(),
15964
+ distributed: array(object({
15965
+ modelId: string(),
15966
+ nodeId: string(),
15967
+ format: _enum(MODEL_FORMATS),
15968
+ ok: boolean(),
15969
+ error: string().optional()
15970
+ })).readonly()
15971
+ }), object({
15972
+ kind: literal("refused"),
15973
+ reason: _enum([
15974
+ "transfer-failed",
15975
+ "checksum-mismatch",
15976
+ "bundle-mismatch",
15977
+ "invalid-entry",
15978
+ "id-taken"
15979
+ ]),
15980
+ detail: string()
15981
+ })]);
15982
+ method(_void(), array(CustomModelDescriptorSchema).readonly(), { auth: "admin" }), method(ImportModelBundleInputSchema, ImportModelBundleResultSchema, {
15983
+ kind: "mutation",
15984
+ auth: "admin",
15985
+ timeoutMs: 30 * 6e4
15986
+ });
14506
15987
  /**
14507
15988
  * Query filter for settings-store collections.
14508
15989
  */
@@ -14886,6 +16367,253 @@ id: union([string(), number()]) }), {
14886
16367
  auth: "admin"
14887
16368
  });
14888
16369
  /**
16370
+ * `keychain` — the hub's encrypted store of secret values (D787).
16371
+ *
16372
+ * Settings blobs never hold a secret: they hold a marker
16373
+ * `{"$secret":"secret://<owner>/<scope>/<fieldPath>","v":1}` and the value
16374
+ * lives here, AES-256-GCM under a data key that a master key wraps. This cap
16375
+ * is the OWNER's door to its own values: every method is owner-checked
16376
+ * against the CALLER, never against anything the caller claims.
16377
+ *
16378
+ * Who the caller is: the transport stamps `callerAddonId` into the args of a
16379
+ * call that crossed a process (the parent `LocalChildRegistry` from the UDS
16380
+ * connection, the agent from its child's connection carried in
16381
+ * `$hub-cap-fwd`'s envelope). A stamp always overwrites; a wire call with no
16382
+ * stamp has its claim stripped. Only a hub in-process caller may state its own
16383
+ * identity — `ctx.secrets` does that with the addon id closed over. This is
16384
+ * identity against BUGS and misrouting, not against a malicious addon (every
16385
+ * runner is the same OS user): see the threat model in
16386
+ * `docs/design/2026-10-08-secrets-keychain.md`.
16387
+ *
16388
+ * `callerAddonId` is deliberately NOT in any input schema: the tRPC router
16389
+ * parses the input, so a session can never supply it, and the internal mount
16390
+ * floors every method to admin anyway (D240).
16391
+ *
16392
+ * Internal: addons reach it through `ctx.secrets`, never directly.
16393
+ */
16394
+ /** Why a value cannot be served right now. Never folded into "missing". */
16395
+ var KeychainUnavailableReasonSchema = _enum([
16396
+ "key-missing",
16397
+ "wrong-key",
16398
+ "key-file-unreadable",
16399
+ "store-unavailable",
16400
+ "not-initialized",
16401
+ "decrypt-failed"
16402
+ ]);
16403
+ var KeychainStateSchema = discriminatedUnion("state", [object({ state: literal("ready") }), object({
16404
+ state: literal("locked"),
16405
+ reason: KeychainUnavailableReasonSchema
16406
+ })]);
16407
+ var KeychainResolveEntrySchema = discriminatedUnion("kind", [
16408
+ object({
16409
+ kind: literal("value"),
16410
+ value: string(),
16411
+ version: number().int()
16412
+ }),
16413
+ object({ kind: literal("missing") }),
16414
+ object({
16415
+ kind: literal("unavailable"),
16416
+ reason: KeychainUnavailableReasonSchema
16417
+ }),
16418
+ object({ kind: literal("forbidden") })
16419
+ ]);
16420
+ var KeychainResolveResultSchema = record(string(), KeychainResolveEntrySchema);
16421
+ /** Metadata of one stored value — never the value. */
16422
+ var KeychainSecretMetaSchema = object({
16423
+ ref: string(),
16424
+ owner: string(),
16425
+ /** Formatted scope (`global`, `node/<id>`, `device/<id>`, …). */
16426
+ scope: string(),
16427
+ fieldPath: string(),
16428
+ version: number().int(),
16429
+ createdAt: number(),
16430
+ updatedAt: number(),
16431
+ /** `addon:<id>` | `user:<id>` | `system`. */
16432
+ updatedBy: string(),
16433
+ /** Coarse — written at most once an hour per ref. `null` = never read. */
16434
+ lastReadAt: number().nullable()
16435
+ });
16436
+ var RefListSchema = array(string().min(1)).max(512);
16437
+ method(object({
16438
+ ref: string().min(1),
16439
+ value: string().min(1)
16440
+ }), object({
16441
+ ref: string(),
16442
+ version: number().int()
16443
+ }), {
16444
+ kind: "mutation",
16445
+ auth: "admin"
16446
+ }), method(object({ refs: RefListSchema }), KeychainResolveResultSchema, { auth: "admin" }), method(object({ refs: RefListSchema }), object({ deleted: number().int() }), {
16447
+ kind: "mutation",
16448
+ auth: "admin"
16449
+ }), method(object({}), array(KeychainSecretMetaSchema).readonly(), { auth: "admin" }), method(object({}), KeychainStateSchema, { auth: "admin" });
16450
+ var KeychainKeySourceSchema = object({
16451
+ kind: _enum([
16452
+ "config-file",
16453
+ "previous-config-file",
16454
+ "platform",
16455
+ "default-file"
16456
+ ]),
16457
+ /** File sources only — a path is not a secret. */
16458
+ path: string().optional(),
16459
+ /**
16460
+ * True when a whole-volume backup of the data directory carries this key
16461
+ * next to the database it protects (the default file). The page warns.
16462
+ */
16463
+ sharesBackupWithDatabase: boolean()
16464
+ });
16465
+ /**
16466
+ * One keychain reset, as the Secrets page reports it until the operator
16467
+ * acknowledges it. Never a value: refs, counts and table names only.
16468
+ */
16469
+ var KeychainResetRecordSchema = object({
16470
+ id: string(),
16471
+ at: number(),
16472
+ /** `user:<id>` or {@link KEYCHAIN_RESET_TRIGGER_ACTOR}. */
16473
+ actor: string(),
16474
+ /** Why the keychain was locked when it was reset; `null` when it was not locked. */
16475
+ lockedReason: string().nullable(),
16476
+ /** Values moved into the archive table (ciphertext under the lost key). */
16477
+ archived: number().int(),
16478
+ /** `keychain:secrets-orphaned-<ts>`, or `null` when nothing was stored. */
16479
+ archivedCollection: string().nullable(),
16480
+ /**
16481
+ * `keychain:keys-orphaned-<ts>`: the wrapped data keys of the archive, kept
16482
+ * so the archive can still be opened if the lost master key turns up.
16483
+ */
16484
+ archivedKeysCollection: string().nullable(),
16485
+ /**
16486
+ * `system-settings` keys whose marker the reset cleared — the cluster
16487
+ * secret's: a marker left pointing at an archived value would refuse every
16488
+ * agent forever (D797).
16489
+ */
16490
+ clearedSettingsKeys: array(string()).readonly(),
16491
+ /** When an operator dismissed the notice on the Secrets page; `null` until then. */
16492
+ acknowledgedAt: number().nullable()
16493
+ });
16494
+ var KeychainStatusSchema = object({
16495
+ keychain: KeychainStateSchema,
16496
+ /** The source of the master key in use; `null` while locked. */
16497
+ keySource: KeychainKeySourceSchema.nullable(),
16498
+ /** The source configured to be primary — differs from `keySource` while a rotation is pending. */
16499
+ configuredSource: KeychainKeySourceSchema,
16500
+ /** Short fingerprint of the master key in use (`HMAC(KEK, label)`, 16 hex). */
16501
+ fingerprint: string().nullable(),
16502
+ activeKeyId: string().nullable(),
16503
+ /**
16504
+ * The keychain unlocked with a NON-primary source: the configured primary
16505
+ * key is not the one that wraps the data key yet. `rotateMasterKey` moves it.
16506
+ */
16507
+ rotationPending: boolean(),
16508
+ /** Wrapped copies of the data key under a previous master key, kept until purged. */
16509
+ retiredWraps: number().int(),
16510
+ recoveryKeyDownloadedAt: number().nullable(),
16511
+ secretCount: number().int(),
16512
+ /** The most recent reset, acknowledged or not; `null` when the keychain was never reset. */
16513
+ lastReset: KeychainResetRecordSchema.nullable()
16514
+ });
16515
+ /**
16516
+ * Whether a stored value is still pointed at by its owner's settings.
16517
+ * `unknown` is a first-class answer: a scope whose blob could not be read is
16518
+ * never reported as an orphan (and never deleted as one).
16519
+ */
16520
+ var KeychainSecretUsageSchema = _enum([
16521
+ "in-use",
16522
+ "orphan",
16523
+ "unknown"
16524
+ ]);
16525
+ var KeychainAdminSecretSchema = KeychainSecretMetaSchema.extend({ usage: KeychainSecretUsageSchema });
16526
+ var KeychainAuditActionSchema = _enum([
16527
+ "put",
16528
+ "delete",
16529
+ "reveal",
16530
+ "rotate-master-key",
16531
+ "purge-retired-keys",
16532
+ "download-recovery-key",
16533
+ "delete-orphans",
16534
+ "reset",
16535
+ "acknowledge-reset",
16536
+ "initialize"
16537
+ ]);
16538
+ var KeychainAuditEntrySchema = object({
16539
+ id: string(),
16540
+ at: number(),
16541
+ action: KeychainAuditActionSchema,
16542
+ /** `addon:<id>` | `user:<id>` | `system` | `trigger-file`. */
16543
+ actor: string(),
16544
+ ref: string().nullable(),
16545
+ detail: string().nullable()
16546
+ });
16547
+ var KEYCHAIN_RESET_CONFIRMATION = "RESET KEYCHAIN";
16548
+ /**
16549
+ * Secrets the HUB itself holds (owner `system`) that no settings form shows:
16550
+ * `jwt-signing-key` — the session signing key (D797). It is always "in use",
16551
+ * never an orphan; it is generated on a fresh hub and replaced only through
16552
+ * {@link keychainAdminCapability.methods.setSystemSecret}.
16553
+ */
16554
+ var SystemHeldSecretNameSchema = _enum(["jwt-signing-key"]);
16555
+ 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({
16556
+ value: string(),
16557
+ version: number().int()
16558
+ }), {
16559
+ kind: "mutation",
16560
+ auth: "admin",
16561
+ caller: "required"
16562
+ }), method(object({
16563
+ name: SystemHeldSecretNameSchema,
16564
+ value: string().min(16)
16565
+ }), object({
16566
+ ref: string(),
16567
+ version: number().int()
16568
+ }), {
16569
+ kind: "mutation",
16570
+ auth: "admin",
16571
+ caller: "required"
16572
+ }), method(object({ refs: array(string().min(1)).max(1e3) }), object({
16573
+ deleted: array(string()).readonly(),
16574
+ kept: array(object({
16575
+ ref: string(),
16576
+ usage: KeychainSecretUsageSchema
16577
+ })).readonly()
16578
+ }), {
16579
+ kind: "mutation",
16580
+ auth: "admin",
16581
+ caller: "required"
16582
+ }), method(object({}), object({
16583
+ fingerprint: string(),
16584
+ keySource: KeychainKeySourceSchema
16585
+ }), {
16586
+ kind: "mutation",
16587
+ auth: "admin",
16588
+ caller: "required"
16589
+ }), method(object({}), object({ purged: number().int() }), {
16590
+ kind: "mutation",
16591
+ auth: "admin",
16592
+ caller: "required"
16593
+ }), method(object({}), object({
16594
+ key: string(),
16595
+ fingerprint: string(),
16596
+ keySource: KeychainKeySourceSchema
16597
+ }), {
16598
+ kind: "mutation",
16599
+ auth: "admin",
16600
+ caller: "required"
16601
+ }), method(object({ confirm: literal(KEYCHAIN_RESET_CONFIRMATION) }), object({
16602
+ archivedCollection: string().nullable(),
16603
+ archived: number().int()
16604
+ }), {
16605
+ kind: "mutation",
16606
+ auth: "admin",
16607
+ caller: "required"
16608
+ }), method(object({}), object({
16609
+ reset: KeychainResetRecordSchema.nullable(),
16610
+ pendingReentry: array(KeychainSecretMetaSchema).readonly()
16611
+ }), { auth: "admin" }), method(object({}), object({ acknowledged: boolean() }), {
16612
+ kind: "mutation",
16613
+ auth: "admin",
16614
+ caller: "required"
16615
+ });
16616
+ /**
14889
16617
  * Stable UI option list for the `hwaccel` setting. Decoder addons
14890
16618
  * reuse this for `globalSettingsSchema()` so the dropdown is
14891
16619
  * identical everywhere. Order: auto → off → common backends by
@@ -16003,7 +17731,11 @@ var DeviceRegisterPayloadSchema = object({
16003
17731
  var DeviceRemovePayloadSchema = object({ deviceId: number() });
16004
17732
  var DevicePersistConfigPayloadSchema = object({
16005
17733
  deviceId: number(),
16006
- data: record(string(), unknown())
17734
+ data: record(string(), unknown()),
17735
+ /** The paths the device's schema declares secret (D783), when the caller
17736
+ * knows them — those values are kept in the keychain, not the blob (D787).
17737
+ * Absent: the paths the device last reported at `registerDevice` apply. */
17738
+ secretConfigPaths: array(string()).optional()
16007
17739
  });
16008
17740
  /** What a migration actually did, per switch. `unreachable` is a first-class
16009
17741
  * answer: a camera that could not be asked is not a camera that was silenced. */
@@ -17606,7 +19338,7 @@ method(LogEntrySchema, _void(), { kind: "mutation" }), method(object({
17606
19338
  * `login-method` — collection cap through which auth addons contribute
17607
19339
  * their pre-auth login surfaces to the login page. This is the SINGLE,
17608
19340
  * generic mechanism that supersedes the dead `auth.listProviders` reader:
17609
- * every auth addon (OIDC, magic-link, WebAuthn/passkey) registers a
19341
+ * every auth addon (OIDC, WebAuthn/passkey) registers a
17610
19342
  * `login-method` provider and the PUBLIC `auth.listLoginMethods`
17611
19343
  * procedure aggregates them for the unauthenticated login page.
17612
19344
  *
@@ -17614,8 +19346,7 @@ method(LogEntrySchema, _void(), { kind: "mutation" }), method(object({
17614
19346
  *
17615
19347
  * - `redirect` — a declarative button. The login page renders a generic
17616
19348
  * button that navigates to `startUrl` (an addon-owned HTTP route).
17617
- * Covers OIDC (`/addon/auth-oidc/<id>/start`) and magic-link with
17618
- * ZERO shell-side JS. A future SSO addon plugs in the same way — the
19349
+ * Covers OIDC (`/addon/auth-oidc/<id>/start`) with ZERO shell-side JS. A future SSO addon plugs in the same way — the
17619
19350
  * login page needs NO change.
17620
19351
  *
17621
19352
  * - `widget` — a Module-Federation widget the login page mounts (via
@@ -17634,8 +19365,8 @@ method(LogEntrySchema, _void(), { kind: "mutation" }), method(object({
17634
19365
  * decision.
17635
19366
  *
17636
19367
  * Every contribution carries a `stage`:
17637
- * - `primary` — shown on the first credentials screen (OIDC /
17638
- * magic-link buttons; a future usernameless passkey).
19368
+ * - `primary` — shown on the first credentials screen (OIDC
19369
+ * buttons; a usernameless passkey).
17639
19370
  * - `second-factor` — shown AFTER the password leg, gated on the
17640
19371
  * returned `factors` (passkey-as-2FA today).
17641
19372
  *
@@ -17662,7 +19393,7 @@ var LoginMethodContributionSchema = discriminatedUnion("kind", [
17662
19393
  * The provider names an external identity a signed-in user can link to
17663
19394
  * their own account (D782): `auth.listLinkableProviders` /
17664
19395
  * `beginExternalLink` offer exactly the redirect methods that set this,
17665
- * whatever their id. Absent / false — a login button only (magic-link).
19396
+ * whatever their id. Absent / false — a login button only.
17666
19397
  */
17667
19398
  linkable: boolean().optional()
17668
19399
  }),
@@ -21479,8 +23210,7 @@ method(object({}), object({ rules: array(NcRuleSchema) }), { auth: "admin" }), m
21479
23210
  * `super_admin` — collapsed onto the single boolean because every
21480
23211
  * non-admin caller is governed by the same scope-check rules; the
21481
23212
  * distinction was only ever used to route role-specific procedures
21482
- * which we no longer have. Agents are admin sessions issued via
21483
- * `createServiceToken`; CLI / webhook integrations are `cst_*` tokens
23213
+ * which we no longer have. CLI / webhook integrations are `cst_*` tokens
21484
23214
  * with `isAdmin: false` + an explicit scope list.
21485
23215
  */
21486
23216
  /** Per-method access flavour. Materialised on every cap method via codegen. */
@@ -22982,8 +24712,23 @@ var RetrainMacroClassSchema = _enum([
22982
24712
  ]);
22983
24713
  /** A subject to learn, or a phantom to unlearn (taught by OMISSION). */
22984
24714
  var RetrainAnnotationKindSchema = _enum(["subject", "model_error"]);
22985
- /** Did a human draw this box, or did the assist propose it? */
22986
- var RetrainAnnotationSourceSchema = _enum(["operator", "assist"]);
24715
+ /**
24716
+ * Where a box came from. A machine-sourced box is a DRAFT on the page until
24717
+ * the operator confirms it; once saved it keeps its source as provenance.
24718
+ *
24719
+ * - `operator` — drawn by hand.
24720
+ * - `assist` — proposed by a detector run on the copy (the camera's own
24721
+ * model, or a larger teacher model).
24722
+ * - `pipeline` — the box the live pipeline actually drew on that frame, read
24723
+ * back from the track store (never a re-run).
24724
+ * - `llm` — proposed by a vision-capable LLM profile.
24725
+ */
24726
+ var RetrainAnnotationSourceSchema = _enum([
24727
+ "operator",
24728
+ "assist",
24729
+ "pipeline",
24730
+ "llm"
24731
+ ]);
22987
24732
  /** Normalised `[0,1]` rectangle against the FULL frame — the canonical form. */
22988
24733
  var RetrainBboxSchema = object({
22989
24734
  x: number(),
@@ -23001,7 +24746,8 @@ var RetrainBboxSchema = object({
23001
24746
  */
23002
24747
  var RetrainAnnotationSchema = object({
23003
24748
  id: string(),
23004
- trackId: string(),
24749
+ /** The frame's track. Absent on a recording still, which has none. */
24750
+ trackId: string().optional(),
23005
24751
  deviceId: number(),
23006
24752
  /** The COPY in retrain storage — never the source track's media key. */
23007
24753
  mediaKey: string(),
@@ -23050,13 +24796,47 @@ var RetrainFrameCandidateSchema = object({
23050
24796
  * fail, whatever became of the original. */
23051
24797
  copied: boolean()
23052
24798
  });
24799
+ /**
24800
+ * One box the live pipeline drew on a copied frame — what a correction starts
24801
+ * from. Derived when the frame is listed, from the track store: the subject
24802
+ * box recorded on the source media row when there is one, else the track
24803
+ * position nearest the frame's capture time. Never stored as an annotation
24804
+ * until the operator confirms it.
24805
+ */
24806
+ var RetrainPipelineBoxSchema = object({
24807
+ /** Normalised `[0,1]` against the full frame. */
24808
+ bbox: RetrainBboxSchema,
24809
+ macroClass: RetrainMacroClassSchema,
24810
+ label: string().optional(),
24811
+ subLabel: string().optional(),
24812
+ /** The detection score of the position used, when it was recorded. */
24813
+ score: number().optional(),
24814
+ /** The root model that produced the track, when it was recorded. */
24815
+ modelId: string().optional(),
24816
+ trackId: string(),
24817
+ /** `subject-box`: recorded on this very frame. `position`: the track's
24818
+ * position nearest the capture time, `deltaMs` away. */
24819
+ basis: _enum(["subject-box", "position"]),
24820
+ deltaMs: number()
24821
+ });
24822
+ /**
24823
+ * Where a retrain frame came from: a TRACK's stored media (copy-on-select),
24824
+ * or the RECORDING at an instant — the frame a model saw nothing in has no
24825
+ * track at all.
24826
+ */
24827
+ var RetrainFrameOriginSchema = _enum(["track", "recording"]);
23053
24828
  /** A frame the dataset OWNS: bytes copied at selection time. */
23054
24829
  var RetrainFrameSchema = object({
23055
24830
  frameId: string(),
23056
24831
  deviceId: number(),
23057
- trackId: string(),
23058
- /** Provenance only. It may already point at nothing — that is expected. */
23059
- sourceMediaId: number().int(),
24832
+ origin: RetrainFrameOriginSchema,
24833
+ /** The track it was copied from. Absent on a recording still. */
24834
+ trackId: string().optional(),
24835
+ /** Provenance only. It may already point at nothing — that is expected.
24836
+ * Absent on a recording still. */
24837
+ sourceMediaId: number().int().optional(),
24838
+ /** A recording still: the playhead instant it was taken at. */
24839
+ epochMs: number().optional(),
23060
24840
  sourceKind: MediaFileKindEnum,
23061
24841
  sizeBytes: number().int(),
23062
24842
  width: number().int(),
@@ -23067,7 +24847,12 @@ var RetrainFrameSchema = object({
23067
24847
  /** The operator's "every subject in this frame is boxed". Detector
23068
24848
  * evaluation keeps only complete frames: an unboxed subject would count as
23069
24849
  * a false positive. */
23070
- complete: boolean()
24850
+ complete: boolean(),
24851
+ /** The boxes the pipeline drew on this frame. Present on list answers;
24852
+ * empty when nothing the track store holds can be placed on it. */
24853
+ pipelineBoxes: array(RetrainPipelineBoxSchema).readonly().optional(),
24854
+ /** The named collections this frame belongs to. Present on list answers. */
24855
+ collectionIds: array(string()).readonly().optional()
23071
24856
  });
23072
24857
  /** Why a copy-on-select could not be honoured — named, never a silent skip. */
23073
24858
  var RetrainCopyRefusalSchema = _enum([
@@ -23098,6 +24883,11 @@ var RetrainFrameListSchema = object({
23098
24883
  var RetrainExportFilterSchema = object({
23099
24884
  deviceIds: array(number()).optional(),
23100
24885
  frameIds: array(string()).max(2e4).optional(),
24886
+ /** Only frames in at least one of these named collections. */
24887
+ collectionIds: array(string()).max(200).optional(),
24888
+ /** Exactly the frames of this dataset version (and its completeOnly). An
24889
+ * unknown id selects nothing. */
24890
+ datasetVersionId: string().optional(),
23101
24891
  batchId: string().optional(),
23102
24892
  /** Only frames the operator marked complete (all subjects boxed). */
23103
24893
  completeOnly: boolean().optional()
@@ -23162,6 +24952,170 @@ var RetrainAssistResultSchema = discriminatedUnion("kind", [object({
23162
24952
  reason: string(),
23163
24953
  detail: string().optional()
23164
24954
  })]);
24955
+ /** A named set over the retrain corpus — membership only, it owns no pixels. */
24956
+ var RetrainCollectionSchema = object({
24957
+ id: string(),
24958
+ name: string(),
24959
+ createdAt: number(),
24960
+ frameCount: number().int()
24961
+ });
24962
+ var RetrainCollectionCreateResultSchema = discriminatedUnion("kind", [object({
24963
+ kind: literal("created"),
24964
+ collection: RetrainCollectionSchema
24965
+ }), object({
24966
+ kind: literal("refused"),
24967
+ reason: _enum(["empty-name", "duplicate-name"])
24968
+ })]);
24969
+ var RetrainCollectionRenameResultSchema = discriminatedUnion("kind", [object({
24970
+ kind: literal("renamed"),
24971
+ collection: RetrainCollectionSchema
24972
+ }), object({
24973
+ kind: literal("refused"),
24974
+ reason: _enum([
24975
+ "empty-name",
24976
+ "duplicate-name",
24977
+ "unknown-collection"
24978
+ ])
24979
+ })]);
24980
+ /**
24981
+ * The outcome of adding the frame at a recording instant. Every refusal is
24982
+ * named: `still-unavailable` (not recording, a gap, or an undecodable frame —
24983
+ * `detail` says which), `still-busy` (the recorder is at its decode bound; try
24984
+ * again), `unreadable-image`, `write-failed`, `unknown-collection`.
24985
+ */
24986
+ var AddRetrainFrameFromRecordingResultSchema = discriminatedUnion("kind", [object({
24987
+ kind: literal("added"),
24988
+ collectionId: string(),
24989
+ frame: RetrainFrameSchema,
24990
+ /** The moment was already in the dataset; nothing was decoded. */
24991
+ reused: boolean()
24992
+ }), object({
24993
+ kind: literal("refused"),
24994
+ reason: _enum([
24995
+ "unknown-collection",
24996
+ "still-unavailable",
24997
+ "still-busy",
24998
+ "unreadable-image",
24999
+ "write-failed"
25000
+ ]),
25001
+ detail: string().optional()
25002
+ })]);
25003
+ /** A vision LLM profile the AI assist may use, and where it sends the frame. */
25004
+ var RetrainAssistProfileSchema = object({
25005
+ id: string(),
25006
+ name: string(),
25007
+ model: string(),
25008
+ kind: string(),
25009
+ /** `true` when the frame would leave the house (a cloud vendor, or an
25010
+ * endpoint that is not on the local network). The page confirms each such
25011
+ * run, and the provider refuses one without `allowCloud`. */
25012
+ leavesHouse: boolean()
25013
+ });
25014
+ /** A box the AI assist proposed: a draft, plus the model's own reason. */
25015
+ var RetrainLlmProposalSchema = RetrainAnnotationDraftSchema.extend({ reason: string() });
25016
+ /** What the AI assist said about a box that was already on the canvas. */
25017
+ var RetrainLlmReviewSchema = object({
25018
+ /** The `ref` the page sent the box under. */
25019
+ ref: string(),
25020
+ verdict: _enum([
25021
+ "confirmed",
25022
+ "wrong-class",
25023
+ "not-an-object",
25024
+ "uncertain"
25025
+ ]),
25026
+ suggestedClass: RetrainMacroClassSchema.optional(),
25027
+ reason: string()
25028
+ });
25029
+ /**
25030
+ * The AI assist's answer. `proposed` carries drafts (`source: 'llm'`, the
25031
+ * model and its confidence) and reviews; items the model got wrong (a box off
25032
+ * the frame, an unasked class, an unknown ref) are dropped and counted in
25033
+ * `rejected`. A whole answer that is not the schema is `malformed-answer`.
25034
+ */
25035
+ var RetrainLlmAssistResultSchema = discriminatedUnion("kind", [object({
25036
+ kind: literal("proposed"),
25037
+ profileId: string(),
25038
+ model: string(),
25039
+ /** The frame was sent outside the house for this answer. */
25040
+ leftHouse: boolean(),
25041
+ proposals: array(RetrainLlmProposalSchema).readonly(),
25042
+ reviews: array(RetrainLlmReviewSchema).readonly(),
25043
+ rejected: number().int()
25044
+ }), object({
25045
+ kind: literal("refused"),
25046
+ reason: _enum([
25047
+ "unknown-frame",
25048
+ "unreadable-frame",
25049
+ "unknown-profile",
25050
+ "profile-disabled",
25051
+ "no-vision",
25052
+ "cloud-not-confirmed",
25053
+ "llm-error",
25054
+ "malformed-answer"
25055
+ ]),
25056
+ detail: string().optional()
25057
+ })]);
25058
+ /** What a dataset version is cut from. Every field narrows. */
25059
+ var RetrainDatasetSelectionSchema = object({
25060
+ deviceIds: array(number()).readonly().optional(),
25061
+ collectionIds: array(string()).max(200).readonly().optional(),
25062
+ frameIds: array(string()).max(2e4).readonly().optional()
25063
+ });
25064
+ /** The counts a dataset is judged by. */
25065
+ var RetrainDatasetStatsSchema = object({
25066
+ frames: number().int(),
25067
+ completeFrames: number().int(),
25068
+ /** `completeFrames / frames`, 0..1. */
25069
+ completeness: number(),
25070
+ /** Boxes to learn (model errors excluded). */
25071
+ subjects: number().int(),
25072
+ modelErrors: number().int(),
25073
+ /** Complete frames with no subject. */
25074
+ hardNegatives: number().int(),
25075
+ /** Subjects per class × camera × day/night. */
25076
+ cells: array(object({
25077
+ macroClass: string(),
25078
+ deviceId: number(),
25079
+ lighting: _enum([
25080
+ "day",
25081
+ "night",
25082
+ "unknown"
25083
+ ]),
25084
+ subjects: number().int(),
25085
+ frames: number().int()
25086
+ })).readonly(),
25087
+ cameras: array(object({
25088
+ deviceId: number(),
25089
+ frames: number().int(),
25090
+ completeFrames: number().int()
25091
+ })).readonly()
25092
+ });
25093
+ /** An immutable dataset version, without its frame list. */
25094
+ var RetrainDatasetVersionSchema = object({
25095
+ id: string(),
25096
+ name: string(),
25097
+ createdAt: number(),
25098
+ selection: RetrainDatasetSelectionSchema,
25099
+ layout: RetrainExportLayoutSchema,
25100
+ completeOnly: boolean(),
25101
+ frameCount: number().int(),
25102
+ /** sha256 of what the frames taught when the version was frozen. */
25103
+ annotationHash: string(),
25104
+ /** The export manifest schema the version was cut under. */
25105
+ manifestSchema: string(),
25106
+ stats: RetrainDatasetStatsSchema
25107
+ });
25108
+ var CreateRetrainDatasetVersionResultSchema = discriminatedUnion("kind", [object({
25109
+ kind: literal("created"),
25110
+ version: RetrainDatasetVersionSchema
25111
+ }), object({
25112
+ kind: literal("refused"),
25113
+ reason: _enum([
25114
+ "empty-name",
25115
+ "duplicate-name",
25116
+ "no-frames"
25117
+ ])
25118
+ })]);
23165
25119
  /** The outcome of a lifecycle move owned by the retrain page. */
23166
25120
  var RetrainTransitionResultSchema = object({
23167
25121
  trackId: string(),
@@ -23879,7 +25833,7 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
23879
25833
  auth: "admin"
23880
25834
  }), method(object({
23881
25835
  deviceId: number(),
23882
- trackId: string(),
25836
+ trackId: string().optional(),
23883
25837
  frameId: string()
23884
25838
  }), object({
23885
25839
  removed: boolean(),
@@ -23896,7 +25850,8 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
23896
25850
  auth: "admin"
23897
25851
  }), method(object({
23898
25852
  deviceId: number(),
23899
- trackId: string(),
25853
+ /** The frame's track, when it has one — checked against the frame. */
25854
+ trackId: string().optional(),
23900
25855
  frameId: string(),
23901
25856
  subject: RetrainAssistSubjectSchema,
23902
25857
  /** Which node runs it. Absent ⇒ wherever an unowned call lands. */
@@ -23904,12 +25859,16 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
23904
25859
  }), RetrainAssistResultSchema, {
23905
25860
  kind: "mutation",
23906
25861
  auth: "admin"
23907
- }), method(object({ trackId: string() }), array(RetrainAnnotationSchema).readonly(), {
25862
+ }), method(object({
25863
+ trackId: string().optional(),
25864
+ frameIds: array(string()).max(2e3).optional()
25865
+ }), array(RetrainAnnotationSchema).readonly(), {
23908
25866
  kind: "query",
23909
25867
  auth: "admin"
23910
25868
  }), method(object({
23911
25869
  deviceId: number(),
23912
- trackId: string(),
25870
+ /** The frame's track, when it has one — checked against the frame. */
25871
+ trackId: string().optional(),
23913
25872
  frameId: string(),
23914
25873
  annotations: array(RetrainAnnotationDraftSchema)
23915
25874
  }), array(RetrainAnnotationSchema).readonly(), {
@@ -23932,7 +25891,7 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
23932
25891
  auth: "admin"
23933
25892
  }), method(object({
23934
25893
  deviceId: number(),
23935
- trackId: string(),
25894
+ trackId: string().optional(),
23936
25895
  frameId: string(),
23937
25896
  complete: boolean()
23938
25897
  }), RetrainFrameSchema, {
@@ -23946,6 +25905,115 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
23946
25905
  kind: "mutation",
23947
25906
  auth: "admin",
23948
25907
  timeoutMs: 60 * 6e4
25908
+ }), method(object({
25909
+ filter: RetrainExportFilterSchema,
25910
+ layout: RetrainExportLayoutSchema
25911
+ }), object({
25912
+ ticket: PeerBytesTicketSchema,
25913
+ frames: number().int(),
25914
+ annotations: number().int()
25915
+ }), {
25916
+ kind: "mutation",
25917
+ auth: "admin",
25918
+ timeoutMs: 12e4
25919
+ }), method(object({
25920
+ selection: RetrainDatasetSelectionSchema,
25921
+ completeOnly: boolean().optional()
25922
+ }), RetrainDatasetStatsSchema, {
25923
+ kind: "query",
25924
+ auth: "admin"
25925
+ }), method(object({
25926
+ name: string().max(120),
25927
+ selection: RetrainDatasetSelectionSchema,
25928
+ layout: RetrainExportLayoutSchema,
25929
+ completeOnly: boolean()
25930
+ }), CreateRetrainDatasetVersionResultSchema, {
25931
+ kind: "mutation",
25932
+ auth: "admin",
25933
+ timeoutMs: 12e4
25934
+ }), method(object({}), array(RetrainDatasetVersionSchema).readonly(), {
25935
+ kind: "query",
25936
+ auth: "admin"
25937
+ }), method(object({ id: string() }), object({ deleted: boolean() }), {
25938
+ kind: "mutation",
25939
+ auth: "admin"
25940
+ }), method(object({ id: string() }), object({
25941
+ found: boolean(),
25942
+ annotationHash: string(),
25943
+ matches: boolean(),
25944
+ missingFrames: number().int()
25945
+ }), {
25946
+ kind: "query",
25947
+ auth: "admin",
25948
+ timeoutMs: 12e4
25949
+ }), method(object({}), array(RetrainAssistProfileSchema).readonly(), {
25950
+ kind: "query",
25951
+ auth: "admin"
25952
+ }), method(object({
25953
+ deviceId: number(),
25954
+ trackId: string().optional(),
25955
+ frameId: string(),
25956
+ profileId: string(),
25957
+ classes: array(RetrainMacroClassSchema).min(1),
25958
+ boxes: array(object({
25959
+ ref: string(),
25960
+ bbox: RetrainBboxSchema,
25961
+ macroClass: RetrainMacroClassSchema,
25962
+ label: string().optional()
25963
+ })).max(50),
25964
+ allowCloud: boolean()
25965
+ }), RetrainLlmAssistResultSchema, {
25966
+ kind: "mutation",
25967
+ auth: "admin",
25968
+ timeoutMs: 18e4
25969
+ }), method(object({ name: string().max(120) }), RetrainCollectionCreateResultSchema, {
25970
+ kind: "mutation",
25971
+ auth: "admin"
25972
+ }), method(object({}), array(RetrainCollectionSchema).readonly(), {
25973
+ kind: "query",
25974
+ auth: "admin"
25975
+ }), method(object({
25976
+ id: string(),
25977
+ name: string().max(120)
25978
+ }), RetrainCollectionRenameResultSchema, {
25979
+ kind: "mutation",
25980
+ auth: "admin"
25981
+ }), method(object({ id: string() }), object({
25982
+ deleted: boolean(),
25983
+ removedFrames: number().int()
25984
+ }), {
25985
+ kind: "mutation",
25986
+ auth: "admin"
25987
+ }), method(object({
25988
+ collectionId: string(),
25989
+ deviceId: number(),
25990
+ epochMs: number()
25991
+ }), AddRetrainFrameFromRecordingResultSchema, {
25992
+ kind: "mutation",
25993
+ auth: "admin",
25994
+ timeoutMs: 6e4
25995
+ }), method(object({
25996
+ collectionId: string(),
25997
+ frameIds: array(string()).min(1).max(500)
25998
+ }), object({
25999
+ added: number().int(),
26000
+ alreadyMember: number().int(),
26001
+ unknownFrameIds: array(string()).readonly()
26002
+ }), {
26003
+ kind: "mutation",
26004
+ auth: "admin"
26005
+ }), method(object({
26006
+ collectionId: string(),
26007
+ frameId: string()
26008
+ }), object({
26009
+ removed: boolean(),
26010
+ deletedFrame: boolean()
26011
+ }), {
26012
+ kind: "mutation",
26013
+ auth: "admin"
26014
+ }), method(object({ collectionId: string() }), array(RetrainFrameSchema).readonly(), {
26015
+ kind: "query",
26016
+ auth: "admin"
23949
26017
  }), method(object({
23950
26018
  /** Which of the three event tables owns the row. */
23951
26019
  ownerType: EventOwnerTypeSchema,
@@ -24569,13 +26637,31 @@ var RecommendationReasonSchema = discriminatedUnion("kind", [
24569
26637
  object({
24570
26638
  kind: literal("no-family-build"),
24571
26639
  format: ModelFormatSchema$1
26640
+ }),
26641
+ object({
26642
+ kind: literal("kept-custom-pin"),
26643
+ modelId: string(),
26644
+ deviceKey: string()
24572
26645
  })
24573
26646
  ]);
26647
+ /** Why a device is left exactly as it is, whatever the plan would pick (D786). */
26648
+ var KeptReasonSchema = _enum(["custom-pin"]);
26649
+ /**
26650
+ * Where a choice's latency came from (D791): this node's own benchmark
26651
+ * result, or the hardware-class table. Measured on the node beats the table.
26652
+ */
26653
+ var LatencySourceSchema = discriminatedUnion("kind", [object({ kind: literal("table") }), object({
26654
+ kind: literal("node-benchmark"),
26655
+ resultId: string(),
26656
+ measuredAtMs: number()
26657
+ })]);
24574
26658
  var DeviceModelChoiceSchema = object({
24575
26659
  modelId: string(),
24576
26660
  p50Ms: number(),
24577
26661
  fps: number(),
24578
26662
  measured: boolean(),
26663
+ /** Absent on a plan from before D791 — read as the table. */
26664
+ source: LatencySourceSchema.optional(),
24579
26665
  /** Parallel sessions at the camera rate with the headroom kept free: ⌊fps × (1 − headroom) / camera fps⌋. */
24580
26666
  capacitySessions: number(),
24581
26667
  personRecall: number()
@@ -24586,6 +26672,8 @@ var DeviceRecommendationSchema = object({
24586
26672
  enabled: boolean(),
24587
26673
  available: boolean(),
24588
26674
  chosen: DeviceModelChoiceSchema.nullable(),
26675
+ /** Present when the device is kept as is: Apply writes nothing on it. */
26676
+ kept: KeptReasonSchema.optional(),
24589
26677
  reasons: array(RecommendationReasonSchema).readonly()
24590
26678
  });
24591
26679
  var NodeRecommendationSchema = object({
@@ -24639,6 +26727,17 @@ var AutoTuneWarningSchema = discriminatedUnion("kind", [
24639
26727
  kind: literal("coral-enabled"),
24640
26728
  nodeId: string(),
24641
26729
  deviceKey: string()
26730
+ }),
26731
+ object({
26732
+ kind: literal("custom-pin-kept"),
26733
+ nodeId: string(),
26734
+ deviceKey: string().nullable(),
26735
+ deviceId: number().nullable(),
26736
+ modelId: string()
26737
+ }),
26738
+ object({
26739
+ kind: literal("custom-registry-unreadable"),
26740
+ error: string()
24642
26741
  })
24643
26742
  ]);
24644
26743
  var AutoTuneOptionsSchema = object({
@@ -24817,13 +26916,14 @@ var SuggestSharesResultSchema = object({
24817
26916
  nodes: array(SuggestedNodeShareSchema).readonly()
24818
26917
  });
24819
26918
  /**
24820
- * Where the node and device shares come from (D750, D755).
24821
- * - `hardware` (default) — computed by the system from each node's static
24822
- * capacity (its accelerators at their Auto tune models, from the measured
24823
- * latency table), recomputed whenever a node or device joins, leaves, is
24824
- * switched on or off, or changes model. No load input.
24825
- * - `benchmark` — the same, from each node's measured capacity (node
24826
- * benchmark results); a node without results falls back to `hardware`.
26919
+ * Where the node and device shares come from (D750, D755, D791).
26920
+ * - `benchmark` (default since D791) — each node's capacity as its own node
26921
+ * benchmark measured it; a node without fresh results is sized from
26922
+ * `hardware` and says so. Measured on the node beats the table.
26923
+ * - `hardware` — computed from each node's static capacity only (its
26924
+ * accelerators at their Auto tune models, from the latency table).
26925
+ * Both are recomputed whenever a node or device joins, leaves, is switched
26926
+ * on or off, changes model, or a benchmark result is written. No load input.
24827
26927
  * - `manual` — the operator's stored sliders.
24828
26928
  * Either way a node or device that cannot take sessions gives its share to
24829
26929
  * the others in proportion; the stored values are never rewritten for that.
@@ -24872,6 +26972,362 @@ var EffectiveSharesSchema = object({
24872
26972
  nodeWeights: record(string(), number()),
24873
26973
  deviceWeights: record(string(), record(string(), number()))
24874
26974
  });
26975
+ /**
26976
+ * Wire shapes of the node benchmark (D791): the operator's plan, the
26977
+ * preflight the confirmation shows, the run the orchestrator owns, what the
26978
+ * measuring runner reports, and the result rows Auto tune and the automatic
26979
+ * shares read.
26980
+ *
26981
+ * ONE node at a time, owned by the pipeline orchestrator. While a run is
26982
+ * active the cluster is in BENCHMARK MODE for that node: it is not a
26983
+ * detection candidate, camera pins naming it are ignored so its sessions move
26984
+ * elsewhere, and both come back when the mode ends — after a crash or a hub
26985
+ * restart too (a persisted manifest, reconciled against the registry).
26986
+ *
26987
+ * Two measurements, both on the node, driven by its own runner (frames never
26988
+ * cross a process at frame rate, D9):
26989
+ * - `device` — one accelerator × one candidate detector, root only, open
26990
+ * loop: how many streams at the camera rate it carries inside the frame
26991
+ * interval;
26992
+ * - `pipeline` — the chosen detector plus the operator's detail steps
26993
+ * (faces, plates, classifiers, CLIP…), on varied frames from the bench
26994
+ * clip: how many parallel sessions the node carries before latency, drops,
26995
+ * CPU, RAM or the event loop give out.
26996
+ */
26997
+ /** Defaults and bounds, one place. */
26998
+ var NODE_BENCHMARK_DEFAULTS = {
26999
+ fpsPerStream: 10,
27000
+ budgetMinutes: 45,
27001
+ minBudgetMinutes: 10,
27002
+ maxBudgetMinutes: 120,
27003
+ /** A result older than this no longer beats the table. */
27004
+ staleAfterDays: 30,
27005
+ /** Warm-in per ramp step (not accounted). */
27006
+ settleSec: 5,
27007
+ /** Accounted window per ramp step. */
27008
+ measureSec: 20,
27009
+ /** Longest the drain may take before the run is refused. */
27010
+ drainTimeoutSec: 120,
27011
+ /** Candidate models per device in one run. */
27012
+ maxModelsPerDevice: 6
27013
+ };
27014
+ /** The two measurements a run can make. */
27015
+ var NodeBenchmarkPhaseSchema = _enum(["device", "pipeline"]);
27016
+ var NodeBenchmarkDevicePlanSchema = object({
27017
+ /** `<backend>:<device>` — `openvino:npu`, `coreml:all`, `cpu`. */
27018
+ deviceKey: string().min(1),
27019
+ /**
27020
+ * Root detector candidates for the `device` measurement, in the order
27021
+ * measured. The FIRST is the one the `pipeline` measurement runs.
27022
+ */
27023
+ modelIds: array(string().min(1)).min(1).max(NODE_BENCHMARK_DEFAULTS.maxModelsPerDevice)
27024
+ });
27025
+ /** What the operator confirmed. */
27026
+ var NodeBenchmarkPlanSchema = object({
27027
+ nodeId: string().min(1),
27028
+ devices: array(NodeBenchmarkDevicePlanSchema).min(1),
27029
+ /** Which measurements run. At least one. */
27030
+ phases: array(NodeBenchmarkPhaseSchema).min(1).default(["device", "pipeline"]),
27031
+ /**
27032
+ * Detail steps (catalog step ids under the root: faces, plates,
27033
+ * classifiers, CLIP…) the `pipeline` measurement enables. The root
27034
+ * detector always runs.
27035
+ */
27036
+ steps: array(string().min(1)).default([]),
27037
+ /** Offered rate of one stream / session. */
27038
+ fpsPerStream: number().int().min(1).max(30).default(NODE_BENCHMARK_DEFAULTS.fpsPerStream),
27039
+ /** Hard deadline: the mode ends and the cluster is restored when it passes. */
27040
+ budgetMinutes: number().int().min(NODE_BENCHMARK_DEFAULTS.minBudgetMinutes).max(NODE_BENCHMARK_DEFAULTS.maxBudgetMinutes).default(NODE_BENCHMARK_DEFAULTS.budgetMinutes),
27041
+ /** Keep the models the run downloaded (default: delete what was not installed before). */
27042
+ keepDownloadedModels: boolean().default(false),
27043
+ /** Start although the other nodes' capacity does not cover the sessions running now. */
27044
+ acceptInsufficientHeadroom: boolean().default(false)
27045
+ });
27046
+ var NodeBenchmarkRefusalSchema = object({
27047
+ kind: _enum([
27048
+ "benchmark-active",
27049
+ "node-offline",
27050
+ "unknown-device",
27051
+ "no-phase",
27052
+ "insufficient-headroom"
27053
+ ]),
27054
+ detail: string(),
27055
+ overridable: boolean()
27056
+ });
27057
+ /** A camera whose detection leaves the node for the run. */
27058
+ var NodeBenchmarkMovingCameraSchema = object({
27059
+ deviceId: number(),
27060
+ /** Placed on the node now (a standing attach or a running session). */
27061
+ placedOnNode: boolean(),
27062
+ /** A node pin naming this node, ignored for the run. */
27063
+ pinnedToNode: boolean()
27064
+ });
27065
+ /** A camera that cannot leave: no other node can obtain its frames. */
27066
+ var NodeBenchmarkStayingCameraSchema = object({
27067
+ deviceId: number(),
27068
+ reason: literal("only-frame-source")
27069
+ });
27070
+ var NodeBenchmarkPreflightSchema = object({
27071
+ nodeId: string(),
27072
+ online: boolean(),
27073
+ moving: array(NodeBenchmarkMovingCameraSchema).readonly(),
27074
+ /** Keep running on the node during the run; the result is flagged contaminated. */
27075
+ staying: array(NodeBenchmarkStayingCameraSchema).readonly(),
27076
+ estimatedDurationMs: number(),
27077
+ /** The run ends and the cluster is restored at the latest after this long. */
27078
+ budgetMs: number(),
27079
+ phases: array(NodeBenchmarkPhaseSchema).readonly(),
27080
+ steps: array(string()).readonly(),
27081
+ devices: array(NodeBenchmarkDevicePlanSchema).readonly(),
27082
+ /** Parallel sessions the cluster runs now, and what the other nodes can carry. */
27083
+ headroom: object({
27084
+ sessionsNow: number(),
27085
+ otherNodesCapacitySessions: number().nullable()
27086
+ }),
27087
+ refusals: array(NodeBenchmarkRefusalSchema).readonly(),
27088
+ canStart: boolean()
27089
+ });
27090
+ /** Where the measuring runner is. */
27091
+ var NodeBenchProgressSchema = object({
27092
+ phase: _enum([
27093
+ "preparing",
27094
+ "device",
27095
+ "pipeline",
27096
+ "cleanup"
27097
+ ]),
27098
+ deviceKey: string().nullable(),
27099
+ modelId: string().nullable(),
27100
+ /** Streams (device) or sessions (pipeline) of the step running now. */
27101
+ load: number().nullable(),
27102
+ cellsDone: number(),
27103
+ cellsTotal: number(),
27104
+ message: string()
27105
+ });
27106
+ /** What limited a ramp. `none` = the ramp ran out of steps still passing. */
27107
+ var NodeBenchLimitSchema = _enum([
27108
+ "p95",
27109
+ "drops",
27110
+ "errors",
27111
+ "stall",
27112
+ "cpu",
27113
+ "ram",
27114
+ "none"
27115
+ ]);
27116
+ var NodeBenchRampStepSchema = object({
27117
+ load: number(),
27118
+ pass: boolean(),
27119
+ p95Ms: number(),
27120
+ dropRatio: number(),
27121
+ /** Completed frames per second over the accounted window. */
27122
+ fps: number(),
27123
+ cpuPct: number().nullable(),
27124
+ ramFreePct: number().nullable(),
27125
+ failReasons: array(string()).readonly()
27126
+ });
27127
+ var NodeBenchCellSchema = discriminatedUnion("phase", [object({
27128
+ phase: literal("device"),
27129
+ deviceKey: string(),
27130
+ modelId: string(),
27131
+ /** Single-stream latency (the K = 1 step). */
27132
+ p50Ms: number(),
27133
+ p95Ms: number(),
27134
+ p99Ms: number(),
27135
+ /** Frames per second sustained at the last passing step. */
27136
+ fps: number(),
27137
+ /** Streams at the camera rate the device carried inside the frame interval; 0 = not even one. */
27138
+ kMax: number(),
27139
+ limitedBy: NodeBenchLimitSchema,
27140
+ /** First call (model load + warm-up). */
27141
+ warmupMs: number(),
27142
+ ramp: array(NodeBenchRampStepSchema).readonly()
27143
+ }), object({
27144
+ phase: literal("pipeline"),
27145
+ deviceKey: string(),
27146
+ modelId: string(),
27147
+ steps: array(string()).readonly(),
27148
+ /** Parallel sessions at the camera rate the node carried; 0 = not even one. */
27149
+ maxSessions: number(),
27150
+ limitedBy: NodeBenchLimitSchema,
27151
+ /** Detail steps that produced at least one result on the clip — a step that never fired measured nothing. */
27152
+ stepsFired: array(string()).readonly(),
27153
+ warmupMs: number(),
27154
+ ramp: array(NodeBenchRampStepSchema).readonly()
27155
+ })]);
27156
+ /**
27157
+ * What a result was measured ON. A result whose fingerprint no longer matches
27158
+ * the node no longer beats the table.
27159
+ */
27160
+ var NodeBenchFingerprintSchema = object({
27161
+ pipelineVersion: string().nullable(),
27162
+ cpuModel: string().nullable(),
27163
+ ramGb: number().nullable(),
27164
+ os: string().nullable(),
27165
+ /** Per device: the pool the cells ran on (runtime + tuning). */
27166
+ pools: record(string(), object({
27167
+ runtime: string(),
27168
+ numWorkers: number(),
27169
+ concurrency: number(),
27170
+ batchMode: string()
27171
+ })).default({})
27172
+ });
27173
+ /** The frames the run used. */
27174
+ var NodeBenchClipSchema = object({
27175
+ /** `camstack-bench-v1` or `reference-images` (the fallback when the clip is not reachable). */
27176
+ id: string(),
27177
+ revision: string().nullable(),
27178
+ frames: number(),
27179
+ width: number(),
27180
+ height: number()
27181
+ });
27182
+ var NodeBenchRunnerInputSchema = object({
27183
+ runId: string().min(1),
27184
+ devices: array(NodeBenchmarkDevicePlanSchema).min(1),
27185
+ phases: array(NodeBenchmarkPhaseSchema).min(1),
27186
+ /** The full detail step tree root for the `pipeline` measurement is built on the node from these ids. */
27187
+ steps: array(string()).default([]),
27188
+ fpsPerStream: number().int().min(1).max(30),
27189
+ /** The runner stops on its own past this instant, whatever the hub does. */
27190
+ deadlineAtMs: number(),
27191
+ settleSec: number().min(0).max(60).default(NODE_BENCHMARK_DEFAULTS.settleSec),
27192
+ measureSec: number().min(2).max(300).default(NODE_BENCHMARK_DEFAULTS.measureSec),
27193
+ keepDownloadedModels: boolean().default(false)
27194
+ });
27195
+ var NodeBenchRunnerStateSchema = _enum([
27196
+ "running",
27197
+ "done",
27198
+ "failed",
27199
+ "aborted"
27200
+ ]);
27201
+ var NodeBenchRunnerStatusSchema = object({
27202
+ runId: string(),
27203
+ nodeId: string(),
27204
+ state: NodeBenchRunnerStateSchema,
27205
+ progress: NodeBenchProgressSchema.nullable(),
27206
+ /** Every finished cell so far — a run stopped half way keeps what it measured. */
27207
+ cells: array(NodeBenchCellSchema).readonly(),
27208
+ fingerprint: NodeBenchFingerprintSchema.nullable(),
27209
+ clip: NodeBenchClipSchema.nullable(),
27210
+ /** Cameras seen running on the node during the run (they share its pools). */
27211
+ activeCameraIds: array(number()).readonly(),
27212
+ /** Models the run downloaded and then deleted (not installed before). */
27213
+ deletedModels: array(string()).readonly(),
27214
+ error: string().nullable(),
27215
+ startedAtMs: number(),
27216
+ finishedAtMs: number().nullable()
27217
+ });
27218
+ var NodeBenchmarkStateSchema = _enum([
27219
+ "draining",
27220
+ "measuring",
27221
+ "restoring",
27222
+ "done",
27223
+ "failed",
27224
+ "aborted"
27225
+ ]);
27226
+ /** Why a run ended. */
27227
+ var NodeBenchmarkEndReasonSchema = _enum([
27228
+ "completed",
27229
+ "operator-abort",
27230
+ "deadline",
27231
+ "node-lost",
27232
+ "runner-lost",
27233
+ "hub-restart",
27234
+ "drain-timeout",
27235
+ "failed"
27236
+ ]);
27237
+ var NodeBenchmarkRunSchema = object({
27238
+ runId: string(),
27239
+ nodeId: string(),
27240
+ state: NodeBenchmarkStateSchema,
27241
+ plan: NodeBenchmarkPlanSchema,
27242
+ startedAtMs: number(),
27243
+ deadlineAtMs: number(),
27244
+ finishedAtMs: number().nullable(),
27245
+ endReason: NodeBenchmarkEndReasonSchema.nullable(),
27246
+ error: string().nullable(),
27247
+ /** Cameras moved off the node for the run. */
27248
+ moved: array(number()).readonly(),
27249
+ /** Cameras that stayed (their only frame source is the node). */
27250
+ staying: array(number()).readonly(),
27251
+ /** Something else ran on the node's pools during the run. */
27252
+ contaminated: boolean(),
27253
+ progress: NodeBenchProgressSchema.nullable(),
27254
+ resultIds: array(string()).readonly()
27255
+ });
27256
+ /** `getNodeBenchmarkStatus`: the active run (or the last one), and whether benchmark mode is on. */
27257
+ var NodeBenchmarkStatusSchema = object({
27258
+ /** The node the cluster is in benchmark mode for; null = none. */
27259
+ modeNodeId: string().nullable(),
27260
+ run: NodeBenchmarkRunSchema.nullable()
27261
+ });
27262
+ /**
27263
+ * One stored measurement — the only authority Auto tune and the automatic
27264
+ * shares read measured capacity from. Written by the orchestrator when a run
27265
+ * ends, never by anyone else.
27266
+ */
27267
+ var NodeBenchmarkResultSchema = object({
27268
+ id: string(),
27269
+ runId: string(),
27270
+ nodeId: string(),
27271
+ cell: NodeBenchCellSchema,
27272
+ fpsPerStream: number(),
27273
+ fingerprint: NodeBenchFingerprintSchema.nullable(),
27274
+ clip: NodeBenchClipSchema.nullable(),
27275
+ /** Other work shared the node's pools (a camera that could not move, or the hub's own duties). */
27276
+ contaminated: boolean(),
27277
+ stayingCameras: array(number()).readonly(),
27278
+ /** The run ended early; the cell itself completed. */
27279
+ partialRun: boolean(),
27280
+ measuredAtMs: number()
27281
+ });
27282
+ var ListNodeBenchmarkResultsInputSchema = object({
27283
+ nodeId: string().optional(),
27284
+ deviceKey: string().optional()
27285
+ });
27286
+ /** A result with its standing today: does it still beat the table? */
27287
+ var NodeBenchmarkResultViewSchema = NodeBenchmarkResultSchema.extend({
27288
+ /** `fresh` beats the table; `stale` falls back to it; `superseded` = a newer row covers the same cell. */
27289
+ standing: _enum([
27290
+ "fresh",
27291
+ "stale",
27292
+ "superseded"
27293
+ ]),
27294
+ staleWhy: _enum([
27295
+ "age",
27296
+ "runtime",
27297
+ "pool-tuning"
27298
+ ]).nullable()
27299
+ });
27300
+ object({
27301
+ runId: string(),
27302
+ nodeId: string(),
27303
+ startedAtMs: number(),
27304
+ deadlineAtMs: number(),
27305
+ plan: NodeBenchmarkPlanSchema,
27306
+ moved: array(number()).readonly(),
27307
+ staying: array(number()).readonly()
27308
+ });
27309
+ /** Candidate detectors per device, for the plan editor. */
27310
+ var NodeBenchmarkCandidatesSchema = object({
27311
+ nodeId: string(),
27312
+ reachable: boolean(),
27313
+ devices: array(object({
27314
+ deviceKey: string(),
27315
+ enabled: boolean(),
27316
+ available: boolean(),
27317
+ /** Ordered: what Auto tune would pick first, then the rest of the family by accuracy. */
27318
+ suggested: array(string()).readonly(),
27319
+ /** Every root detector the device has a build for. */
27320
+ all: array(string()).readonly(),
27321
+ /** The model the device runs now, when pinned. */
27322
+ currentModelId: string().nullable()
27323
+ })).readonly(),
27324
+ /** Detail steps the node's catalog offers under the root (for the `pipeline` measurement). */
27325
+ steps: array(object({
27326
+ id: string(),
27327
+ name: string(),
27328
+ slot: string()
27329
+ })).readonly()
27330
+ });
24875
27331
  object({
24876
27332
  activeCameras: number(),
24877
27333
  throttledCameras: number(),
@@ -25960,7 +28416,16 @@ method(RunnerCameraConfigSchema, object({ success: literal(true) }), { kind: "mu
25960
28416
  }), ParkedTrackFrameSchema.nullable()), method(object({
25961
28417
  deviceId: number(),
25962
28418
  trackId: string()
25963
- }), object({ released: number().int().nonnegative() }), { kind: "mutation" });
28419
+ }), object({ released: number().int().nonnegative() }), { kind: "mutation" }), method(NodeBenchRunnerInputSchema, object({
28420
+ accepted: literal(true),
28421
+ runId: string()
28422
+ }), {
28423
+ kind: "mutation",
28424
+ auth: "admin"
28425
+ }), method(object({ runId: string() }), NodeBenchRunnerStatusSchema.nullable(), { auth: "admin" }), method(object({ runId: string() }), object({ aborted: boolean() }), {
28426
+ kind: "mutation",
28427
+ auth: "admin"
28428
+ });
25964
28429
  var CameraPipelineConfigSchema = object({
25965
28430
  engine: PipelineEngineChoiceSchema.optional(),
25966
28431
  steps: array(PipelineStepInputSchema).readonly(),
@@ -26599,6 +29064,21 @@ method(object({
26599
29064
  }), method(PlacementStatsInputSchema, PlacementStatsSchema, { auth: "admin" }), method(SuggestSharesInputSchema, SuggestSharesResultSchema, { auth: "admin" }), method(_void(), EffectiveSharesSchema, { auth: "admin" }), method(SetShareSourceInputSchema, object({ success: literal(true) }), {
26600
29065
  kind: "mutation",
26601
29066
  auth: "admin"
29067
+ }), method(NodeBenchmarkPlanSchema, NodeBenchmarkPreflightSchema, { auth: "admin" }), method(NodeBenchmarkPlanSchema, discriminatedUnion("kind", [object({
29068
+ kind: literal("started"),
29069
+ runId: string()
29070
+ }), object({
29071
+ kind: literal("refused"),
29072
+ preflight: NodeBenchmarkPreflightSchema
29073
+ })]), {
29074
+ kind: "mutation",
29075
+ auth: "admin"
29076
+ }), method(_void(), NodeBenchmarkStatusSchema, { auth: "admin" }), method(object({ runId: string() }), object({ aborted: boolean() }), {
29077
+ kind: "mutation",
29078
+ auth: "admin"
29079
+ }), method(object({ nodeId: string() }), NodeBenchmarkCandidatesSchema, { auth: "admin" }), method(ListNodeBenchmarkResultsInputSchema, array(NodeBenchmarkResultViewSchema).readonly(), { auth: "admin" }), method(object({ id: string() }), object({ deleted: boolean() }), {
29080
+ kind: "mutation",
29081
+ auth: "admin"
26602
29082
  }), method(object({ deviceId: number() }), CameraPipelineSettingsSchema.nullable()), method(object({
26603
29083
  deviceId: number(),
26604
29084
  addonId: string(),
@@ -27004,8 +29484,8 @@ version: string().optional() }), ServerUpdateActionResultSchema, {
27004
29484
  * `smtp-provider` — pluggable email delivery surface.
27005
29485
  *
27006
29486
  * Collection cap: a deployment may install multiple SMTP relays (e.g.
27007
- * one for transactional / one for notifications). Consumers (magic-link,
27008
- * notifier addons, …) walk the collection and pick the first
29487
+ * one for transactional / one for notifications). Consumers (notifier
29488
+ * addons, …) walk the collection and pick the first
27009
29489
  * ready provider OR target a specific addonId.
27010
29490
  *
27011
29491
  * The shape stays small on purpose — `sendEmail` is enough for the
@@ -27184,7 +29664,7 @@ targets: array(object({
27184
29664
  })));
27185
29665
  /**
27186
29666
  * `sso-bridge` — internal hub-only cap that lets SSO-style auth
27187
- * providers (OIDC, SAML, magic-link, …) mint an HMAC-signed token
29667
+ * providers (OIDC, SAML, …) mint an HMAC-signed token
27188
29668
  * carrying the post-callback claims before redirecting back to
27189
29669
  * `/api/auth/sso/finish`.
27190
29670
  *
@@ -27247,7 +29727,14 @@ var SsoBridgeClaimsSchema = object({
27247
29727
  * Verified `iss` of the id_token behind an OIDC login bridge (D782). A
27248
29728
  * subject is unique only per issuer, so a link is bound to it.
27249
29729
  */
27250
- issuer: string().optional()
29730
+ issuer: string().optional(),
29731
+ /**
29732
+ * SHA-256 (hex) of the `camstack_sso_state` cookie the IdP `/start` set in
29733
+ * the browser that began this sign-in. `/api/auth/sso/finish` requires the
29734
+ * request to present the matching cookie — a login bridge is useless in
29735
+ * any other browser.
29736
+ */
29737
+ browserBinding: string().optional()
27251
29738
  });
27252
29739
  method(object({
27253
29740
  claims: SsoBridgeClaimsSchema,
@@ -31909,6 +34396,9 @@ var CreateIntegrationInputSchema = object({
31909
34396
  enabled: boolean().optional(),
31910
34397
  info: record(string(), unknown()).optional(),
31911
34398
  settings: record(string(), unknown()).optional(),
34399
+ /** Keys of `settings` the form's schema declares secret (by type) — kept in
34400
+ * the keychain, not the table (D787). */
34401
+ secretKeys: array(string()).optional(),
31912
34402
  skipRestart: boolean().optional()
31913
34403
  });
31914
34404
  var UpdateIntegrationInputSchema = object({
@@ -31932,7 +34422,9 @@ method(_void(), array(IntegrationWithStateSchema)), method(object({ id: string()
31932
34422
  auth: "admin"
31933
34423
  }), method(object({ id: string() }), record(string(), unknown()), { auth: "admin" }), method(object({
31934
34424
  id: string(),
31935
- settings: record(string(), unknown())
34425
+ settings: record(string(), unknown()),
34426
+ /** Keys the form's schema declares secret (by type) — keychain-stored (D787). */
34427
+ secretKeys: array(string()).optional()
31936
34428
  }), object({ success: boolean() }), {
31937
34429
  kind: "mutation",
31938
34430
  auth: "admin"
@@ -37416,16 +39908,6 @@ var ApiKeySummarySchema = object({
37416
39908
  createdAt: number(),
37417
39909
  lastUsedAt: number().optional()
37418
39910
  });
37419
- var CreateApiKeyInputSchema = object({
37420
- label: string(),
37421
- isAdmin: boolean().default(false),
37422
- allowedProviders: union([array(string()), literal("*")]).optional(),
37423
- allowedDevices: record(string(), union([array(string()), literal("*")])).optional()
37424
- });
37425
- var CreateApiKeyResultSchema = object({
37426
- token: string(),
37427
- record: ApiKeySummarySchema
37428
- });
37429
39911
  var ScopedTokenSummarySchema = object({
37430
39912
  id: string(),
37431
39913
  userId: string(),
@@ -37524,17 +40006,10 @@ method(_void(), array(UserSummarySchema), { auth: "admin" }), method(CreateUserI
37524
40006
  }), UserSummarySchema.extend({ passwordHash: string() }).nullable(), {
37525
40007
  kind: "mutation",
37526
40008
  access: "view"
37527
- }), method(_void(), array(ApiKeySummarySchema), { auth: "admin" }), method(CreateApiKeyInputSchema, CreateApiKeyResultSchema, {
37528
- kind: "mutation",
37529
- auth: "admin",
37530
- access: "create"
37531
- }), method(object({ id: string() }), object({ success: literal(true) }), {
40009
+ }), method(_void(), array(ApiKeySummarySchema), { auth: "admin" }), method(object({ id: string() }), object({ success: literal(true) }), {
37532
40010
  kind: "mutation",
37533
40011
  auth: "admin",
37534
40012
  access: "delete"
37535
- }), method(object({ token: string() }), ApiKeySummarySchema.nullable(), {
37536
- kind: "mutation",
37537
- access: "view"
37538
40013
  }), method(CreateScopedTokenInputSchema, CreateScopedTokenResultSchema, {
37539
40014
  kind: "mutation",
37540
40015
  auth: "admin",
@@ -37608,15 +40083,7 @@ method(_void(), array(UserSummarySchema), { auth: "admin" }), method(CreateUserI
37608
40083
  }).nullable(), { access: "view" }), method(object({ userId: string() }), array(ExternalIdentitySchema), { auth: "admin" }), method(ExternalIdentityKeySchema, object({
37609
40084
  userId: string(),
37610
40085
  issuer: string()
37611
- }).nullable(), { auth: "admin" }), method(ExternalIdentityKeySchema.extend({
37612
- userId: string(),
37613
- issuer: string().min(1),
37614
- label: string().optional()
37615
- }), object({ success: literal(true) }), {
37616
- kind: "mutation",
37617
- auth: "admin",
37618
- access: "create"
37619
- }), method(ExternalIdentityKeySchema.extend({ userId: string() }), object({ success: boolean() }), {
40086
+ }).nullable(), { auth: "admin" }), method(ExternalIdentityKeySchema.extend({ userId: string() }), object({ success: boolean() }), {
37620
40087
  kind: "mutation",
37621
40088
  auth: "admin",
37622
40089
  access: "delete"
@@ -38011,6 +40478,451 @@ DeviceType.Camera, method(object({
38011
40478
  detection: array(ZoneRuleSchema).readonly(),
38012
40479
  package: array(ZoneRuleSchema).readonly()
38013
40480
  });
40481
+ /**
40482
+ * `training-provider` — ONE cloud that can run the CamStack trainer.
40483
+ *
40484
+ * A thin, mockable translation layer: it knows how to run a container with a
40485
+ * GPU, move a dataset in, read the job's stdout and hand artefacts back. It
40486
+ * knows nothing about datasets, splits, floors, cost policy or Model Studio —
40487
+ * those are the `training` orchestrator's (D805). Every rule written there
40488
+ * once is what makes a second provider (RunPod, a local NVIDIA node) a new
40489
+ * manifest entry and nothing else.
40490
+ *
40491
+ * Collection, routed by the `addonId` in every single-row input (the `llm` /
40492
+ * `notification-output` posture); `describe` concat-fans across providers.
40493
+ * Every method is `admin`: these spend money.
40494
+ *
40495
+ * Every cloud object a provider creates is tagged with the orchestrator's
40496
+ * `jobKey`, so a retried submit finds the job it already started instead of
40497
+ * starting a second GPU, and `listJobs` can find orphans.
40498
+ *
40499
+ * Bytes never ride a cap field: the dataset arrives as a `ctx.peerBytes`
40500
+ * ticket the producer (pipeline-analytics) minted, and artefacts leave as a
40501
+ * ticket the provider mints (D613).
40502
+ */
40503
+ var TrainingGpuOptionSchema = object({
40504
+ id: string(),
40505
+ label: string(),
40506
+ /** List price, USD per GPU-hour, before any region multiplier. */
40507
+ usdPerHour: number().nonnegative(),
40508
+ vramGb: number().nonnegative()
40509
+ });
40510
+ var TrainingRegionOptionSchema = object({
40511
+ /** `''` = any region (the provider's choice). */
40512
+ id: string(),
40513
+ label: string(),
40514
+ priceMultiplier: number().positive()
40515
+ });
40516
+ /**
40517
+ * The provider's per-account settings, as the orchestrator reads them. They
40518
+ * live in the PROVIDER addon's settings (operator decision 2026-10-08: they
40519
+ * depend on the user's account), never hard-coded in the orchestrator.
40520
+ */
40521
+ var TrainingProviderDefaultsSchema = object({
40522
+ gpuType: string(),
40523
+ region: string(),
40524
+ costCapUsd: number().nonnegative(),
40525
+ maxRuntimeSec: number().int().positive(),
40526
+ /** Hours a FAILED job's cloud dataset is kept for debugging; 0 = delete at once. */
40527
+ failedDatasetGraceHours: number().nonnegative()
40528
+ });
40529
+ var TrainingProviderDescriptorSchema = object({
40530
+ addonId: string(),
40531
+ /** `modal`, `runpod`, `fake`, … */
40532
+ kind: string(),
40533
+ label: string(),
40534
+ gpuTypes: array(TrainingGpuOptionSchema).readonly(),
40535
+ regions: array(TrainingRegionOptionSchema).readonly(),
40536
+ maxDatasetBytes: number().int().positive(),
40537
+ maxRuntimeSec: number().int().positive(),
40538
+ freeTierNote: string().optional(),
40539
+ /** Where the data goes, in one sentence the confirm dialog repeats. */
40540
+ dataResidencyNote: string(),
40541
+ /** Credentials are present — never the values. */
40542
+ configured: boolean(),
40543
+ defaults: TrainingProviderDefaultsSchema
40544
+ });
40545
+ var TrainingCredentialCheckSchema = object({
40546
+ ok: boolean(),
40547
+ /** Workspace / account name, when the provider says. */
40548
+ account: string().optional(),
40549
+ reason: _enum([
40550
+ "missing",
40551
+ "invalid",
40552
+ "forbidden",
40553
+ "network",
40554
+ "quota"
40555
+ ]).optional(),
40556
+ detail: string().optional()
40557
+ });
40558
+ var ProviderJobStateSchema = _enum([
40559
+ "pending",
40560
+ "starting",
40561
+ "running",
40562
+ "succeeded",
40563
+ "failed",
40564
+ "cancelled",
40565
+ "lost"
40566
+ ]);
40567
+ var ProviderJobStatusSchema = object({
40568
+ jobKey: string(),
40569
+ providerJobId: string().optional(),
40570
+ state: ProviderJobStateSchema,
40571
+ startedAt: number().optional(),
40572
+ endedAt: number().optional(),
40573
+ exitCode: number().int().optional(),
40574
+ failureReason: string().optional(),
40575
+ gpuType: string(),
40576
+ region: string().optional(),
40577
+ billedSeconds: number().nonnegative(),
40578
+ costUsd: number().nonnegative(),
40579
+ /** True when `costUsd` is runtime × list price, not a billing answer. */
40580
+ costIsEstimate: boolean(),
40581
+ lastFetchedAt: number()
40582
+ });
40583
+ /**
40584
+ * The trainer the job runs, by SOURCE revision: the provider turns it into an
40585
+ * image its own way (Modal builds the published Dockerfile at that revision;
40586
+ * a registry-pull provider maps it to a tag). Recorded on the job and echoed
40587
+ * in `result.json`.
40588
+ */
40589
+ var TrainerSourceRefSchema = object({
40590
+ /** Hugging Face repo id, e.g. `camstack/camstack-trainer`. */
40591
+ repo: string().min(1),
40592
+ /** A commit sha (never a branch) — the job must be reproducible. */
40593
+ revision: string().regex(/^[0-9a-f]{7,64}$/)
40594
+ });
40595
+ var JobRef = {
40596
+ addonId: string(),
40597
+ jobKey: string().uuid()
40598
+ };
40599
+ var TrainingLogLineSchema = object({
40600
+ ts: number(),
40601
+ text: string()
40602
+ });
40603
+ method(object({}), array(TrainingProviderDescriptorSchema).readonly(), { auth: "admin" }), method(object({ addonId: string() }), TrainingCredentialCheckSchema, {
40604
+ kind: "mutation",
40605
+ auth: "admin",
40606
+ timeoutMs: 3e4
40607
+ }), method(object({
40608
+ addonId: string(),
40609
+ gpuType: string(),
40610
+ region: string(),
40611
+ datasetBytes: number().int().nonnegative(),
40612
+ gpuSecondsLow: number().nonnegative(),
40613
+ gpuSecondsHigh: number().nonnegative()
40614
+ }), object({
40615
+ usdLow: number().nonnegative(),
40616
+ usdHigh: number().nonnegative(),
40617
+ notes: array(string()).readonly()
40618
+ }), { auth: "admin" }), method(object({
40619
+ ...JobRef,
40620
+ ticket: PeerBytesTicketSchema
40621
+ }), object({
40622
+ bytes: number().int().nonnegative(),
40623
+ sha256: string()
40624
+ }), {
40625
+ kind: "mutation",
40626
+ auth: "admin",
40627
+ timeoutMs: 120 * 6e4
40628
+ }), method(object({
40629
+ ...JobRef,
40630
+ trainer: TrainerSourceRefSchema,
40631
+ jobSpecJson: string().min(2).max(64e3),
40632
+ gpuType: string(),
40633
+ region: string(),
40634
+ maxRuntimeSec: number().int().positive()
40635
+ }), ProviderJobStatusSchema, {
40636
+ kind: "mutation",
40637
+ auth: "admin",
40638
+ timeoutMs: 30 * 6e4
40639
+ }), method(object(JobRef), ProviderJobStatusSchema, {
40640
+ auth: "admin",
40641
+ timeoutMs: 6e4
40642
+ }), method(object({
40643
+ ...JobRef,
40644
+ cursor: string().optional(),
40645
+ max: number().int().min(1).max(500)
40646
+ }), object({
40647
+ lines: array(TrainingLogLineSchema).readonly(),
40648
+ cursor: string()
40649
+ }), {
40650
+ auth: "admin",
40651
+ timeoutMs: 6e4
40652
+ }), method(object(JobRef), object({ ok: literal(true) }), {
40653
+ kind: "mutation",
40654
+ auth: "admin",
40655
+ timeoutMs: 6e4
40656
+ }), method(object(JobRef), object({
40657
+ found: boolean(),
40658
+ text: string().optional()
40659
+ }), {
40660
+ kind: "mutation",
40661
+ auth: "admin",
40662
+ timeoutMs: 5 * 6e4
40663
+ }), method(object({
40664
+ ...JobRef,
40665
+ path: _enum(["bundle.tar"])
40666
+ }), object({ ticket: PeerBytesTicketSchema }), {
40667
+ kind: "mutation",
40668
+ auth: "admin",
40669
+ timeoutMs: 5 * 6e4
40670
+ }), method(object(JobRef), object({ deleted: array(string()).readonly() }), {
40671
+ kind: "mutation",
40672
+ auth: "admin",
40673
+ timeoutMs: 5 * 6e4
40674
+ }), method(object({ addonId: string() }), array(ProviderJobStatusSchema).readonly(), {
40675
+ auth: "admin",
40676
+ timeoutMs: 2 * 6e4
40677
+ });
40678
+ /**
40679
+ * `training` — the cloud-training orchestrator (D805). Hub-only singleton,
40680
+ * provided by `addon-training`.
40681
+ *
40682
+ * It owns what every provider must agree on, written once:
40683
+ *
40684
+ * - **Dataset versions.** Taken over from pipeline-analytics (D796): the rows
40685
+ * live here (D808); pipeline-analytics still CUTS a version (it owns the corpus and
40686
+ * the export plan) and reaches this store through the five row methods
40687
+ * below, so the Retrain page and the export did not change.
40688
+ * - **Jobs.** A persisted state machine, a reconcile loop against the
40689
+ * provider, a cost guard, a daily orphan sweep and the retention rules.
40690
+ * - **The return flow.** Verified artefacts → Model Studio
40691
+ * (`custom-model-registry.importModelBundle`) → canary on cameras →
40692
+ * rollback. Nothing is ever registered automatically.
40693
+ *
40694
+ * Every method is `admin`.
40695
+ */
40696
+ /** A version WITH its frame list — what the export and a job read. */
40697
+ var TrainingDatasetVersionRowSchema = RetrainDatasetVersionSchema.omit({ frameCount: true }).extend({ frameIds: array(string()).max(2e4).readonly() });
40698
+ /** A base model a detector job can fine-tune, and the baseline it is judged against. */
40699
+ var TrainingBaseModelSchema = object({
40700
+ modelId: string(),
40701
+ label: string(),
40702
+ weights: string(),
40703
+ imgsz: number().int(),
40704
+ baselineOnnxUrl: string(),
40705
+ baselineFloors: record(string(), number()),
40706
+ /** The base the fleet runs most — the UI's default. */
40707
+ recommended: boolean()
40708
+ });
40709
+ var TrainingPresetSchema = _enum([
40710
+ "quick",
40711
+ "standard",
40712
+ "thorough"
40713
+ ]);
40714
+ var TrainingJobRequestSchema = object({
40715
+ datasetVersionId: string().min(1),
40716
+ /** The `training-provider` addon that runs it. */
40717
+ addonId: string().min(1),
40718
+ gpuType: string().min(1),
40719
+ region: string(),
40720
+ baseModelId: string().min(1),
40721
+ preset: TrainingPresetSchema,
40722
+ /** Freeze the backbone's first N layers; `null` = the preset's choice. */
40723
+ freeze: number().int().nonnegative().nullable(),
40724
+ /** Cameras held out whole for evaluation; `null` = the orchestrator's default. */
40725
+ holdoutCameras: array(number().int()).nullable()
40726
+ });
40727
+ var TrainingSplitPlanSchema = object({
40728
+ holdoutCameras: array(number().int()).readonly(),
40729
+ /** Used when no camera is held out: the last N days of every camera. */
40730
+ holdoutLastDays: number().int().nonnegative(),
40731
+ /** Holdout subjects per class (camera holdout only; `null` = known only after the split). */
40732
+ holdoutSupport: record(string(), number().int()).nullable(),
40733
+ trainSubjects: number().int()
40734
+ });
40735
+ var TrainingRefusalReasonSchema = _enum([
40736
+ "unknown-dataset",
40737
+ "unknown-provider",
40738
+ "provider-not-configured",
40739
+ "unknown-base-model",
40740
+ "unknown-gpu",
40741
+ "dataset-too-large",
40742
+ "no-training-subjects",
40743
+ "job-already-running"
40744
+ ]);
40745
+ var TrainingJobPlanSchema = object({
40746
+ refusal: object({
40747
+ reason: TrainingRefusalReasonSchema,
40748
+ detail: string()
40749
+ }).nullable(),
40750
+ warnings: array(string()).readonly(),
40751
+ split: TrainingSplitPlanSchema.nullable(),
40752
+ estimate: object({
40753
+ datasetBytes: number().int(),
40754
+ uploadMinutesAt20Mbps: number(),
40755
+ gpuSecondsLow: number(),
40756
+ gpuSecondsHigh: number(),
40757
+ usdLow: number(),
40758
+ usdHigh: number(),
40759
+ notes: array(string()).readonly()
40760
+ }).nullable(),
40761
+ /** Pre-filled from the provider's settings; the operator may lower or raise them. */
40762
+ defaults: object({
40763
+ maxCostUsd: number(),
40764
+ maxRuntimeSec: number().int()
40765
+ }).nullable(),
40766
+ /** The sentence the confirm dialog repeats: where the frames go and when they are deleted. */
40767
+ dataNotice: string()
40768
+ });
40769
+ /**
40770
+ * Orchestrator-owned states, persisted. `uploading` covers exporting the
40771
+ * archive (it is streamed, never staged). Terminal: `failed`, `cancelled`,
40772
+ * `lost`, `expired`, `discarded`. `registered` and `canary` are where a
40773
+ * result lives after the operator acted on it.
40774
+ */
40775
+ var TrainingJobStateSchema = _enum([
40776
+ "uploading",
40777
+ "submitted",
40778
+ "starting",
40779
+ "running",
40780
+ "collecting",
40781
+ "ready",
40782
+ "registered",
40783
+ "canary",
40784
+ "failed",
40785
+ "cancelling",
40786
+ "cancelled",
40787
+ "lost",
40788
+ "expired",
40789
+ "discarded"
40790
+ ]);
40791
+ var TrainingFailureReasonSchema = _enum([
40792
+ "cost-cap",
40793
+ "runtime-cap",
40794
+ "upload-failed",
40795
+ "submit-failed",
40796
+ "trainer-failed",
40797
+ "result-invalid",
40798
+ "checksum-mismatch",
40799
+ "fetch-failed",
40800
+ "provider-error",
40801
+ "hub-restart-during-upload"
40802
+ ]);
40803
+ var TrainingProgressPointSchema = object({
40804
+ epoch: number().int(),
40805
+ map50: number().nullable(),
40806
+ map50_95: number().nullable()
40807
+ });
40808
+ var TrainingCanarySchema = object({
40809
+ deviceIds: array(number().int()).readonly(),
40810
+ since: number(),
40811
+ /** Every override the canary replaced, exactly, so rollback restores it. */
40812
+ previous: array(object({
40813
+ deviceId: number().int(),
40814
+ nodeId: string(),
40815
+ deviceKey: string(),
40816
+ patch: object({
40817
+ modelId: string().optional(),
40818
+ settings: record(string(), unknown()).readonly().optional()
40819
+ }).nullable()
40820
+ })).readonly()
40821
+ });
40822
+ var TrainingJobSchema = object({
40823
+ id: string(),
40824
+ idempotencyKey: string(),
40825
+ name: string(),
40826
+ createdAt: number(),
40827
+ updatedAt: number(),
40828
+ state: TrainingJobStateSchema,
40829
+ stage: TrainingStageSchema.nullable(),
40830
+ failure: object({
40831
+ reason: TrainingFailureReasonSchema,
40832
+ stage: string().nullable(),
40833
+ detail: string()
40834
+ }).nullable(),
40835
+ request: TrainingJobRequestSchema,
40836
+ maxCostUsd: number().nonnegative(),
40837
+ maxRuntimeSec: number().int().positive(),
40838
+ trainer: TrainerSourceRefSchema,
40839
+ datasetLayout: RetrainExportLayoutSchema,
40840
+ dataset: object({
40841
+ bytes: number().int(),
40842
+ sha256: string(),
40843
+ uploadedAt: number()
40844
+ }).nullable(),
40845
+ split: TrainingSplitPlanSchema,
40846
+ provider: object({
40847
+ state: ProviderJobStateSchema.nullable(),
40848
+ providerJobId: string().nullable(),
40849
+ startedAt: number().nullable(),
40850
+ endedAt: number().nullable(),
40851
+ billedSeconds: number(),
40852
+ costUsd: number(),
40853
+ costIsEstimate: boolean(),
40854
+ lastPolledAt: number().nullable()
40855
+ }),
40856
+ progress: object({
40857
+ epoch: number().int().nullable(),
40858
+ epochs: number().int().nullable(),
40859
+ etaSec: number().nullable(),
40860
+ series: array(TrainingProgressPointSchema).readonly()
40861
+ }),
40862
+ /** The last lines of the job's output (≤ 200), newest last. Never frame paths. */
40863
+ logTail: array(string()).readonly(),
40864
+ logCursor: string().nullable(),
40865
+ artifacts: object({
40866
+ bundleBytes: number().int(),
40867
+ bundleSha256: string(),
40868
+ fetchedAt: number(),
40869
+ /** When the staged artefacts are deleted from the hub. */
40870
+ expiresAt: number()
40871
+ }).nullable(),
40872
+ /** When the provider-side copy of the frames was deleted; null while it exists. */
40873
+ cloudDatasetDeletedAt: number().nullable(),
40874
+ /** A failed job's dataset is kept until then (the provider's grace), then deleted. */
40875
+ cloudCleanupDueAt: number().nullable(),
40876
+ /** Model ids registered from this job (base, and int8 when kept). */
40877
+ registeredModelIds: array(string()).readonly(),
40878
+ canary: TrainingCanarySchema.nullable()
40879
+ });
40880
+ var IdInput = object({ id: string().min(1) });
40881
+ method(TrainingDatasetVersionRowSchema, object({ stored: boolean() }), {
40882
+ kind: "mutation",
40883
+ auth: "admin"
40884
+ }), 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() }), {
40885
+ kind: "mutation",
40886
+ auth: "admin"
40887
+ }), method(object({}), array(TrainingBaseModelSchema).readonly(), { auth: "admin" }), method(TrainingJobRequestSchema, TrainingJobPlanSchema, {
40888
+ auth: "admin",
40889
+ timeoutMs: 6e4
40890
+ }), method(TrainingJobRequestSchema.extend({
40891
+ name: string().min(1).max(120),
40892
+ maxCostUsd: number().positive(),
40893
+ maxRuntimeSec: number().int().positive(),
40894
+ idempotencyKey: string().min(8).max(80)
40895
+ }), discriminatedUnion("kind", [object({
40896
+ kind: literal("started"),
40897
+ job: TrainingJobSchema
40898
+ }), object({
40899
+ kind: literal("refused"),
40900
+ reason: TrainingRefusalReasonSchema,
40901
+ detail: string()
40902
+ })]), {
40903
+ kind: "mutation",
40904
+ auth: "admin",
40905
+ timeoutMs: 12e4
40906
+ }), method(object({}), array(TrainingJobSchema).readonly(), { auth: "admin" }), method(IdInput, TrainingJobSchema.nullable(), { auth: "admin" }), method(IdInput, TrainingJobSchema, {
40907
+ kind: "mutation",
40908
+ auth: "admin",
40909
+ timeoutMs: 12e4
40910
+ }), method(IdInput, TrainingResultSchema.nullable(), { auth: "admin" }), method(IdInput.extend({ canaryDeviceIds: array(number().int()).readonly() }), TrainingJobSchema, {
40911
+ kind: "mutation",
40912
+ auth: "admin",
40913
+ timeoutMs: 30 * 6e4
40914
+ }), method(IdInput.extend({ deviceIds: array(number().int()).min(1).readonly() }), TrainingJobSchema, {
40915
+ kind: "mutation",
40916
+ auth: "admin",
40917
+ timeoutMs: 12e4
40918
+ }), method(IdInput, TrainingJobSchema, {
40919
+ kind: "mutation",
40920
+ auth: "admin",
40921
+ timeoutMs: 12e4
40922
+ }), method(IdInput, TrainingJobSchema, {
40923
+ kind: "mutation",
40924
+ auth: "admin"
40925
+ });
38014
40926
  SOURCE_CAPS.filter((cap) => cap !== "switch" && cap !== "motion");
38015
40927
  Object.freeze({
38016
40928
  person: .5,
@@ -38634,6 +41546,12 @@ Object.freeze({
38634
41546
  addonId: null,
38635
41547
  access: "create"
38636
41548
  },
41549
+ "backup.checkBackupKey": {
41550
+ capName: "backup",
41551
+ capScope: "system",
41552
+ addonId: null,
41553
+ access: "create"
41554
+ },
38637
41555
  "backup.delete": {
38638
41556
  capName: "backup",
38639
41557
  capScope: "system",
@@ -38646,6 +41564,18 @@ Object.freeze({
38646
41564
  addonId: null,
38647
41565
  access: "delete"
38648
41566
  },
41567
+ "backup.disableEncryption": {
41568
+ capName: "backup",
41569
+ capScope: "system",
41570
+ addonId: null,
41571
+ access: "create"
41572
+ },
41573
+ "backup.getEncryption": {
41574
+ capName: "backup",
41575
+ capScope: "system",
41576
+ addonId: null,
41577
+ access: "view"
41578
+ },
38649
41579
  "backup.getEntries": {
38650
41580
  capName: "backup",
38651
41581
  capScope: "system",
@@ -38700,6 +41630,12 @@ Object.freeze({
38700
41630
  addonId: null,
38701
41631
  access: "create"
38702
41632
  },
41633
+ "backup.setupEncryption": {
41634
+ capName: "backup",
41635
+ capScope: "system",
41636
+ addonId: null,
41637
+ access: "create"
41638
+ },
38703
41639
  "backup.trigger": {
38704
41640
  capName: "backup",
38705
41641
  capScope: "system",
@@ -39252,6 +42188,12 @@ Object.freeze({
39252
42188
  addonId: null,
39253
42189
  access: "create"
39254
42190
  },
42191
+ "customModelRegistry.importModelBundle": {
42192
+ capName: "custom-model-registry",
42193
+ capScope: "system",
42194
+ addonId: null,
42195
+ access: "create"
42196
+ },
39255
42197
  "customModelRegistry.listModels": {
39256
42198
  capName: "custom-model-registry",
39257
42199
  capScope: "system",
@@ -40662,6 +43604,108 @@ Object.freeze({
40662
43604
  addonId: null,
40663
43605
  access: "create"
40664
43606
  },
43607
+ "keychain.delete": {
43608
+ capName: "keychain",
43609
+ capScope: "system",
43610
+ addonId: null,
43611
+ access: "delete"
43612
+ },
43613
+ "keychain.getState": {
43614
+ capName: "keychain",
43615
+ capScope: "system",
43616
+ addonId: null,
43617
+ access: "view"
43618
+ },
43619
+ "keychain.listMeta": {
43620
+ capName: "keychain",
43621
+ capScope: "system",
43622
+ addonId: null,
43623
+ access: "view"
43624
+ },
43625
+ "keychain.put": {
43626
+ capName: "keychain",
43627
+ capScope: "system",
43628
+ addonId: null,
43629
+ access: "create"
43630
+ },
43631
+ "keychain.resolve": {
43632
+ capName: "keychain",
43633
+ capScope: "system",
43634
+ addonId: null,
43635
+ access: "view"
43636
+ },
43637
+ "keychainAdmin.acknowledgeReset": {
43638
+ capName: "keychain-admin",
43639
+ capScope: "system",
43640
+ addonId: null,
43641
+ access: "create"
43642
+ },
43643
+ "keychainAdmin.deleteOrphans": {
43644
+ capName: "keychain-admin",
43645
+ capScope: "system",
43646
+ addonId: null,
43647
+ access: "delete"
43648
+ },
43649
+ "keychainAdmin.downloadRecoveryKey": {
43650
+ capName: "keychain-admin",
43651
+ capScope: "system",
43652
+ addonId: null,
43653
+ access: "create"
43654
+ },
43655
+ "keychainAdmin.listAudit": {
43656
+ capName: "keychain-admin",
43657
+ capScope: "system",
43658
+ addonId: null,
43659
+ access: "view"
43660
+ },
43661
+ "keychainAdmin.listSecrets": {
43662
+ capName: "keychain-admin",
43663
+ capScope: "system",
43664
+ addonId: null,
43665
+ access: "view"
43666
+ },
43667
+ "keychainAdmin.purgeRetiredKeys": {
43668
+ capName: "keychain-admin",
43669
+ capScope: "system",
43670
+ addonId: null,
43671
+ access: "delete"
43672
+ },
43673
+ "keychainAdmin.resetKeychain": {
43674
+ capName: "keychain-admin",
43675
+ capScope: "system",
43676
+ addonId: null,
43677
+ access: "delete"
43678
+ },
43679
+ "keychainAdmin.resetReport": {
43680
+ capName: "keychain-admin",
43681
+ capScope: "system",
43682
+ addonId: null,
43683
+ access: "delete"
43684
+ },
43685
+ "keychainAdmin.reveal": {
43686
+ capName: "keychain-admin",
43687
+ capScope: "system",
43688
+ addonId: null,
43689
+ access: "create"
43690
+ },
43691
+ "keychainAdmin.rotateMasterKey": {
43692
+ capName: "keychain-admin",
43693
+ capScope: "system",
43694
+ addonId: null,
43695
+ access: "create"
43696
+ },
43697
+ "keychainAdmin.setSystemSecret": {
43698
+ capName: "keychain-admin",
43699
+ capScope: "system",
43700
+ addonId: null,
43701
+ access: "create"
43702
+ },
43703
+ "keychainAdmin.status": {
43704
+ capName: "keychain-admin",
43705
+ capScope: "system",
43706
+ addonId: null,
43707
+ access: "view"
43708
+ },
40665
43709
  "lawnMowerControl.dock": {
40666
43710
  capName: "lawn-mower-control",
40667
43711
  capScope: "device",
@@ -42036,6 +45080,18 @@ Object.freeze({
42036
45080
  addonId: null,
42037
45081
  access: "create"
42038
45082
  },
45083
+ "pipelineAnalytics.addRetrainFrameFromRecording": {
45084
+ capName: "pipeline-analytics",
45085
+ capScope: "device",
45086
+ addonId: null,
45087
+ access: "create"
45088
+ },
45089
+ "pipelineAnalytics.addRetrainFramesToCollection": {
45090
+ capName: "pipeline-analytics",
45091
+ capScope: "device",
45092
+ addonId: null,
45093
+ access: "create"
45094
+ },
42039
45095
  "pipelineAnalytics.applyDeviceSettingsPatch": {
42040
45096
  capName: "pipeline-analytics",
42041
45097
  capScope: "device",
@@ -42084,12 +45140,36 @@ Object.freeze({
42084
45140
  addonId: null,
42085
45141
  access: "view"
42086
45142
  },
45143
+ "pipelineAnalytics.createRetrainCollection": {
45144
+ capName: "pipeline-analytics",
45145
+ capScope: "device",
45146
+ addonId: null,
45147
+ access: "create"
45148
+ },
45149
+ "pipelineAnalytics.createRetrainDatasetVersion": {
45150
+ capName: "pipeline-analytics",
45151
+ capScope: "device",
45152
+ addonId: null,
45153
+ access: "create"
45154
+ },
42087
45155
  "pipelineAnalytics.deleteDeviceEvents": {
42088
45156
  capName: "pipeline-analytics",
42089
45157
  capScope: "device",
42090
45158
  addonId: null,
42091
45159
  access: "delete"
42092
45160
  },
45161
+ "pipelineAnalytics.deleteRetrainCollection": {
45162
+ capName: "pipeline-analytics",
45163
+ capScope: "device",
45164
+ addonId: null,
45165
+ access: "delete"
45166
+ },
45167
+ "pipelineAnalytics.deleteRetrainDatasetVersion": {
45168
+ capName: "pipeline-analytics",
45169
+ capScope: "device",
45170
+ addonId: null,
45171
+ access: "delete"
45172
+ },
42093
45173
  "pipelineAnalytics.deleteTracks": {
42094
45174
  capName: "pipeline-analytics",
42095
45175
  capScope: "device",
@@ -42294,6 +45374,30 @@ Object.freeze({
42294
45374
  addonId: null,
42295
45375
  access: "view"
42296
45376
  },
45377
+ "pipelineAnalytics.listRetrainAssistProfiles": {
45378
+ capName: "pipeline-analytics",
45379
+ capScope: "device",
45380
+ addonId: null,
45381
+ access: "view"
45382
+ },
45383
+ "pipelineAnalytics.listRetrainCollectionFrames": {
45384
+ capName: "pipeline-analytics",
45385
+ capScope: "device",
45386
+ addonId: null,
45387
+ access: "view"
45388
+ },
45389
+ "pipelineAnalytics.listRetrainCollections": {
45390
+ capName: "pipeline-analytics",
45391
+ capScope: "device",
45392
+ addonId: null,
45393
+ access: "view"
45394
+ },
45395
+ "pipelineAnalytics.listRetrainDatasetVersions": {
45396
+ capName: "pipeline-analytics",
45397
+ capScope: "device",
45398
+ addonId: null,
45399
+ access: "view"
45400
+ },
42297
45401
  "pipelineAnalytics.listRetrainFrames": {
42298
45402
  capName: "pipeline-analytics",
42299
45403
  capScope: "device",
@@ -42324,6 +45428,12 @@ Object.freeze({
42324
45428
  addonId: null,
42325
45429
  access: "view"
42326
45430
  },
45431
+ "pipelineAnalytics.offerRetrainArchive": {
45432
+ capName: "pipeline-analytics",
45433
+ capScope: "device",
45434
+ addonId: null,
45435
+ access: "create"
45436
+ },
42327
45437
  "pipelineAnalytics.ownersWithMedia": {
42328
45438
  capName: "pipeline-analytics",
42329
45439
  capScope: "device",
@@ -42336,12 +45446,24 @@ Object.freeze({
42336
45446
  addonId: null,
42337
45447
  access: "create"
42338
45448
  },
45449
+ "pipelineAnalytics.previewRetrainDataset": {
45450
+ capName: "pipeline-analytics",
45451
+ capScope: "device",
45452
+ addonId: null,
45453
+ access: "view"
45454
+ },
42339
45455
  "pipelineAnalytics.proposeRetrainAnnotations": {
42340
45456
  capName: "pipeline-analytics",
42341
45457
  capScope: "device",
42342
45458
  addonId: null,
42343
45459
  access: "create"
42344
45460
  },
45461
+ "pipelineAnalytics.proposeRetrainAnnotationsWithLlm": {
45462
+ capName: "pipeline-analytics",
45463
+ capScope: "device",
45464
+ addonId: null,
45465
+ access: "create"
45466
+ },
42345
45467
  "pipelineAnalytics.pruneEvents": {
42346
45468
  capName: "pipeline-analytics",
42347
45469
  capScope: "device",
@@ -42396,6 +45518,18 @@ Object.freeze({
42396
45518
  addonId: null,
42397
45519
  access: "create"
42398
45520
  },
45521
+ "pipelineAnalytics.removeRetrainFrameFromCollection": {
45522
+ capName: "pipeline-analytics",
45523
+ capScope: "device",
45524
+ addonId: null,
45525
+ access: "delete"
45526
+ },
45527
+ "pipelineAnalytics.renameRetrainCollection": {
45528
+ capName: "pipeline-analytics",
45529
+ capScope: "device",
45530
+ addonId: null,
45531
+ access: "create"
45532
+ },
42399
45533
  "pipelineAnalytics.restageRetrainTrack": {
42400
45534
  capName: "pipeline-analytics",
42401
45535
  capScope: "device",
@@ -42456,6 +45590,12 @@ Object.freeze({
42456
45590
  addonId: null,
42457
45591
  access: "create"
42458
45592
  },
45593
+ "pipelineAnalytics.verifyRetrainDatasetVersion": {
45594
+ capName: "pipeline-analytics",
45595
+ capScope: "device",
45596
+ addonId: null,
45597
+ access: "view"
45598
+ },
42459
45599
  "pipelineAnalytics.wipeAllAnalytics": {
42460
45600
  capName: "pipeline-analytics",
42461
45601
  capScope: "device",
@@ -42684,6 +45824,12 @@ Object.freeze({
42684
45824
  addonId: null,
42685
45825
  access: "view"
42686
45826
  },
45827
+ "pipelineOrchestrator.abortNodeBenchmark": {
45828
+ capName: "pipeline-orchestrator",
45829
+ capScope: "system",
45830
+ addonId: null,
45831
+ access: "create"
45832
+ },
42687
45833
  "pipelineOrchestrator.applyAutoTune": {
42688
45834
  capName: "pipeline-orchestrator",
42689
45835
  capScope: "system",
@@ -42708,6 +45854,12 @@ Object.freeze({
42708
45854
  addonId: null,
42709
45855
  access: "create"
42710
45856
  },
45857
+ "pipelineOrchestrator.deleteNodeBenchmarkResult": {
45858
+ capName: "pipeline-orchestrator",
45859
+ capScope: "system",
45860
+ addonId: null,
45861
+ access: "delete"
45862
+ },
42711
45863
  "pipelineOrchestrator.getAgentLoad": {
42712
45864
  capName: "pipeline-orchestrator",
42713
45865
  capScope: "system",
@@ -42816,6 +45968,24 @@ Object.freeze({
42816
45968
  addonId: null,
42817
45969
  access: "view"
42818
45970
  },
45971
+ "pipelineOrchestrator.getNodeBenchmarkCandidates": {
45972
+ capName: "pipeline-orchestrator",
45973
+ capScope: "system",
45974
+ addonId: null,
45975
+ access: "view"
45976
+ },
45977
+ "pipelineOrchestrator.getNodeBenchmarkPreflight": {
45978
+ capName: "pipeline-orchestrator",
45979
+ capScope: "system",
45980
+ addonId: null,
45981
+ access: "view"
45982
+ },
45983
+ "pipelineOrchestrator.getNodeBenchmarkStatus": {
45984
+ capName: "pipeline-orchestrator",
45985
+ capScope: "system",
45986
+ addonId: null,
45987
+ access: "view"
45988
+ },
42819
45989
  "pipelineOrchestrator.getNodeInferenceDevices": {
42820
45990
  capName: "pipeline-orchestrator",
42821
45991
  capScope: "system",
@@ -42858,6 +46028,12 @@ Object.freeze({
42858
46028
  addonId: null,
42859
46029
  access: "view"
42860
46030
  },
46031
+ "pipelineOrchestrator.listNodeBenchmarkResults": {
46032
+ capName: "pipeline-orchestrator",
46033
+ capScope: "system",
46034
+ addonId: null,
46035
+ access: "view"
46036
+ },
42861
46037
  "pipelineOrchestrator.pauseForStorageMigration": {
42862
46038
  capName: "pipeline-orchestrator",
42863
46039
  capScope: "system",
@@ -43002,6 +46178,12 @@ Object.freeze({
43002
46178
  addonId: null,
43003
46179
  access: "create"
43004
46180
  },
46181
+ "pipelineOrchestrator.startNodeBenchmark": {
46182
+ capName: "pipeline-orchestrator",
46183
+ capScope: "system",
46184
+ addonId: null,
46185
+ access: "create"
46186
+ },
43005
46187
  "pipelineOrchestrator.suggestShares": {
43006
46188
  capName: "pipeline-orchestrator",
43007
46189
  capScope: "system",
@@ -43020,6 +46202,12 @@ Object.freeze({
43020
46202
  addonId: null,
43021
46203
  access: "create"
43022
46204
  },
46205
+ "pipelineRunner.abortNodeBench": {
46206
+ capName: "pipeline-runner",
46207
+ capScope: "system",
46208
+ addonId: null,
46209
+ access: "create"
46210
+ },
43023
46211
  "pipelineRunner.attachCamera": {
43024
46212
  capName: "pipeline-runner",
43025
46213
  capScope: "system",
@@ -43068,6 +46256,12 @@ Object.freeze({
43068
46256
  addonId: null,
43069
46257
  access: "view"
43070
46258
  },
46259
+ "pipelineRunner.getNodeBenchStatus": {
46260
+ capName: "pipeline-runner",
46261
+ capScope: "system",
46262
+ addonId: null,
46263
+ access: "view"
46264
+ },
43071
46265
  "pipelineRunner.getParkedTrackFrame": {
43072
46266
  capName: "pipeline-runner",
43073
46267
  capScope: "system",
@@ -43110,6 +46304,12 @@ Object.freeze({
43110
46304
  addonId: null,
43111
46305
  access: "create"
43112
46306
  },
46307
+ "pipelineRunner.startNodeBench": {
46308
+ capName: "pipeline-runner",
46309
+ capScope: "system",
46310
+ addonId: null,
46311
+ access: "create"
46312
+ },
43113
46313
  "plateGallery.assignPlate": {
43114
46314
  capName: "plate-gallery",
43115
46315
  capScope: "system",
@@ -44772,6 +47972,174 @@ Object.freeze({
44772
47972
  addonId: null,
44773
47973
  access: "view"
44774
47974
  },
47975
+ "training.canaryResult": {
47976
+ capName: "training",
47977
+ capScope: "system",
47978
+ addonId: null,
47979
+ access: "create"
47980
+ },
47981
+ "training.cancelJob": {
47982
+ capName: "training",
47983
+ capScope: "system",
47984
+ addonId: null,
47985
+ access: "create"
47986
+ },
47987
+ "training.discardResult": {
47988
+ capName: "training",
47989
+ capScope: "system",
47990
+ addonId: null,
47991
+ access: "create"
47992
+ },
47993
+ "training.findDatasetVersionIdByName": {
47994
+ capName: "training",
47995
+ capScope: "system",
47996
+ addonId: null,
47997
+ access: "view"
47998
+ },
47999
+ "training.getDatasetVersion": {
48000
+ capName: "training",
48001
+ capScope: "system",
48002
+ addonId: null,
48003
+ access: "view"
48004
+ },
48005
+ "training.getJob": {
48006
+ capName: "training",
48007
+ capScope: "system",
48008
+ addonId: null,
48009
+ access: "view"
48010
+ },
48011
+ "training.getJobResult": {
48012
+ capName: "training",
48013
+ capScope: "system",
48014
+ addonId: null,
48015
+ access: "view"
48016
+ },
48017
+ "training.listBaseModels": {
48018
+ capName: "training",
48019
+ capScope: "system",
48020
+ addonId: null,
48021
+ access: "view"
48022
+ },
48023
+ "training.listDatasetVersions": {
48024
+ capName: "training",
48025
+ capScope: "system",
48026
+ addonId: null,
48027
+ access: "view"
48028
+ },
48029
+ "training.listJobs": {
48030
+ capName: "training",
48031
+ capScope: "system",
48032
+ addonId: null,
48033
+ access: "view"
48034
+ },
48035
+ "training.planJob": {
48036
+ capName: "training",
48037
+ capScope: "system",
48038
+ addonId: null,
48039
+ access: "view"
48040
+ },
48041
+ "training.putDatasetVersion": {
48042
+ capName: "training",
48043
+ capScope: "system",
48044
+ addonId: null,
48045
+ access: "create"
48046
+ },
48047
+ "training.registerResult": {
48048
+ capName: "training",
48049
+ capScope: "system",
48050
+ addonId: null,
48051
+ access: "create"
48052
+ },
48053
+ "training.removeDatasetVersion": {
48054
+ capName: "training",
48055
+ capScope: "system",
48056
+ addonId: null,
48057
+ access: "delete"
48058
+ },
48059
+ "training.rollbackCanary": {
48060
+ capName: "training",
48061
+ capScope: "system",
48062
+ addonId: null,
48063
+ access: "create"
48064
+ },
48065
+ "training.startJob": {
48066
+ capName: "training",
48067
+ capScope: "system",
48068
+ addonId: null,
48069
+ access: "create"
48070
+ },
48071
+ "trainingProvider.cancelJob": {
48072
+ capName: "training-provider",
48073
+ capScope: "system",
48074
+ addonId: null,
48075
+ access: "create"
48076
+ },
48077
+ "trainingProvider.cleanupJob": {
48078
+ capName: "training-provider",
48079
+ capScope: "system",
48080
+ addonId: null,
48081
+ access: "create"
48082
+ },
48083
+ "trainingProvider.describe": {
48084
+ capName: "training-provider",
48085
+ capScope: "system",
48086
+ addonId: null,
48087
+ access: "view"
48088
+ },
48089
+ "trainingProvider.estimateJob": {
48090
+ capName: "training-provider",
48091
+ capScope: "system",
48092
+ addonId: null,
48093
+ access: "view"
48094
+ },
48095
+ "trainingProvider.getJob": {
48096
+ capName: "training-provider",
48097
+ capScope: "system",
48098
+ addonId: null,
48099
+ access: "view"
48100
+ },
48101
+ "trainingProvider.listJobEvents": {
48102
+ capName: "training-provider",
48103
+ capScope: "system",
48104
+ addonId: null,
48105
+ access: "view"
48106
+ },
48107
+ "trainingProvider.listJobs": {
48108
+ capName: "training-provider",
48109
+ capScope: "system",
48110
+ addonId: null,
48111
+ access: "view"
48112
+ },
48113
+ "trainingProvider.offerArtifact": {
48114
+ capName: "training-provider",
48115
+ capScope: "system",
48116
+ addonId: null,
48117
+ access: "create"
48118
+ },
48119
+ "trainingProvider.readResult": {
48120
+ capName: "training-provider",
48121
+ capScope: "system",
48122
+ addonId: null,
48123
+ access: "create"
48124
+ },
48125
+ "trainingProvider.submitJob": {
48126
+ capName: "training-provider",
48127
+ capScope: "system",
48128
+ addonId: null,
48129
+ access: "create"
48130
+ },
48131
+ "trainingProvider.uploadDataset": {
48132
+ capName: "training-provider",
48133
+ capScope: "system",
48134
+ addonId: null,
48135
+ access: "create"
48136
+ },
48137
+ "trainingProvider.validateCredentials": {
48138
+ capName: "training-provider",
48139
+ capScope: "system",
48140
+ addonId: null,
48141
+ access: "create"
48142
+ },
44775
48143
  "turnProvider.getTurnServers": {
44776
48144
  capName: "turn-provider",
44777
48145
  capScope: "system",
@@ -44796,12 +48164,6 @@ Object.freeze({
44796
48164
  addonId: null,
44797
48165
  access: "create"
44798
48166
  },
44799
- "userManagement.createApiKey": {
44800
- capName: "user-management",
44801
- capScope: "system",
44802
- addonId: null,
44803
- access: "create"
44804
- },
44805
48167
  "userManagement.createScopedToken": {
44806
48168
  capName: "user-management",
44807
48169
  capScope: "system",
@@ -44838,12 +48200,6 @@ Object.freeze({
44838
48200
  addonId: null,
44839
48201
  access: "view"
44840
48202
  },
44841
- "userManagement.linkExternalIdentity": {
44842
- capName: "user-management",
44843
- capScope: "system",
44844
- addonId: null,
44845
- access: "create"
44846
- },
44847
48203
  "userManagement.listApiKeys": {
44848
48204
  capName: "user-management",
44849
48205
  capScope: "system",
@@ -44946,12 +48302,6 @@ Object.freeze({
44946
48302
  addonId: null,
44947
48303
  access: "create"
44948
48304
  },
44949
- "userManagement.validateApiKey": {
44950
- capName: "user-management",
44951
- capScope: "system",
44952
- addonId: null,
44953
- access: "view"
44954
- },
44955
48305
  "userManagement.validateCredentials": {
44956
48306
  capName: "user-management",
44957
48307
  capScope: "system",
@@ -48039,6 +51389,11 @@ Object.freeze({
48039
51389
  form: "single",
48040
51390
  optional: false
48041
51391
  }],
51392
+ "pipelineAnalytics.addRetrainFrameFromRecording": [{
51393
+ name: "deviceId",
51394
+ form: "single",
51395
+ optional: false
51396
+ }],
48042
51397
  "pipelineAnalytics.applyDeviceSettingsPatch": [{
48043
51398
  name: "deviceId",
48044
51399
  form: "single",
@@ -48229,6 +51584,11 @@ Object.freeze({
48229
51584
  form: "single",
48230
51585
  optional: false
48231
51586
  }],
51587
+ "pipelineAnalytics.proposeRetrainAnnotationsWithLlm": [{
51588
+ name: "deviceId",
51589
+ form: "single",
51590
+ optional: false
51591
+ }],
48232
51592
  "pipelineAnalytics.pruneEventsBefore": [{
48233
51593
  name: "deviceId",
48234
51594
  form: "single",
@@ -49055,6 +52415,11 @@ Object.freeze({
49055
52415
  form: "single",
49056
52416
  optional: false
49057
52417
  }],
52418
+ "training.canaryResult": [{
52419
+ name: "deviceIds",
52420
+ form: "array",
52421
+ optional: false
52422
+ }],
49058
52423
  "update.getStatus": [{
49059
52424
  name: "deviceId",
49060
52425
  form: "single",
@@ -113908,8 +117273,10 @@ function ptzPresetLabel(presetName) {
113908
117273
  * `proxy.ptz.getPresets({})`. Toggling ON calls
113909
117274
  * `proxy.ptz.goToPreset({presetId})` and auto-resets to OFF after 1s.
113910
117275
  * - Four directional momentary switches ("Pan Left", "Pan Right",
113911
- * "Tilt Up", "Tilt Down") that issue a `continuousMove` for
113912
- * `ptzPulseMs` then a `stop`. Auto-reset to OFF on completion.
117276
+ * "Tilt Up", "Tilt Down") that issue ONE `ptz.move` — the PTZ cap's
117277
+ * self-terminating burst, whose duration the DRIVER owns and reports as
117278
+ * `getOptions().moveImpulseMs` (ptz.cap.ts). The exporter carries no
117279
+ * duration of its own. Auto-reset to OFF once the pulse is over.
113913
117280
  * - One stateful switch "Autotrack" when the proxy has the
113914
117281
  * `ptz-autotrack` cap bound. Toggling sets
113915
117282
  * `proxy.ptzAutotrack.setEnabled({enabled})`. Initial value is
@@ -113925,7 +117292,7 @@ function ptzPresetLabel(presetName) {
113925
117292
  */
113926
117293
  var MOMENTARY_RESET_MS = 1e3;
113927
117294
  async function buildPtz(bctx) {
113928
- const { ctx, accessory, proxy, numericDeviceId, options } = bctx;
117295
+ const { ctx, accessory, proxy, numericDeviceId } = bctx;
113929
117296
  const log = ctx.logger.withTags({ deviceId: numericDeviceId });
113930
117297
  const timers = /* @__PURE__ */ new Set();
113931
117298
  const armReset = (cb, delay) => {
@@ -113954,30 +117321,29 @@ async function buildPtz(bctx) {
113954
117321
  armReset(() => service.updateCharacteristic(import_dist.Characteristic.On, false), MOMENTARY_RESET_MS);
113955
117322
  });
113956
117323
  }
113957
- if (proxy.ptz) for (const dir of PTZ_DIRECTIONS) {
113958
- const label = ptzServiceName(dir.label);
113959
- const service = accessory.addService(import_dist.Service.Switch, label, dir.subtype);
113960
- applyServiceLabel(service, label);
113961
- service.getCharacteristic(import_dist.Characteristic.On).onSet(async (value) => {
113962
- if (value !== true) return;
113963
- try {
113964
- await proxy.ptz?.continuousMove({ ...dir.cmd });
113965
- armReset(async () => {
113966
- try {
113967
- await proxy.ptz?.stop({});
113968
- } catch (err) {
113969
- log.debug("export-hap: ptz.stop failed (non-fatal)", { meta: { error: errMsg$4(err) } });
113970
- }
113971
- service.updateCharacteristic(import_dist.Characteristic.On, false);
113972
- }, options.ptzPulseMs);
113973
- } catch (err) {
113974
- log.warn("export-hap: ptz.continuousMove failed", { meta: {
113975
- dir: dir.label,
113976
- error: errMsg$4(err)
113977
- } });
113978
- service.updateCharacteristic(import_dist.Characteristic.On, false);
113979
- }
113980
- });
117324
+ if (proxy.ptz) {
117325
+ const impulse = createImpulseReader(bctx);
117326
+ for (const dir of PTZ_DIRECTIONS) {
117327
+ const label = ptzServiceName(dir.label);
117328
+ const service = accessory.addService(import_dist.Service.Switch, label, dir.subtype);
117329
+ applyServiceLabel(service, label);
117330
+ const reset = (delayMs) => armReset(() => service.updateCharacteristic(import_dist.Characteristic.On, false), delayMs);
117331
+ service.getCharacteristic(import_dist.Characteristic.On).onSet(async (value) => {
117332
+ if (value !== true) return;
117333
+ const startedAt = Date.now();
117334
+ try {
117335
+ await proxy.ptz?.move({ ...dir.cmd });
117336
+ } catch (err) {
117337
+ log.warn("export-hap: ptz.move failed", { meta: {
117338
+ dir: dir.label,
117339
+ error: errMsg$4(err)
117340
+ } });
117341
+ reset(0);
117342
+ return;
117343
+ }
117344
+ reset(remainingPulseMs(await impulse.read(), Date.now() - startedAt));
117345
+ });
117346
+ }
113981
117347
  }
113982
117348
  const autotrackHandle = await tryBuildAutotrack(bctx);
113983
117349
  return { async dispose() {
@@ -114035,6 +117401,38 @@ async function tryBuildAutotrack(bctx) {
114035
117401
  });
114036
117402
  return { async dispose() {} };
114037
117403
  }
117404
+ /**
117405
+ * How long the switch should still read ON after `move` resolved.
117406
+ *
117407
+ * Drivers differ in WHEN `move` returns: hikvision awaits its own pulse before
117408
+ * resolving, while reolink (`autoStopMs`), amcrest (background stop) and onvif
117409
+ * (`timeout`) return as soon as the burst has started. Subtracting the time the
117410
+ * call took covers both: the switch stays ON for the pulse, never longer. An
117411
+ * unknown impulse (`null`) resets at once — the head still stops on its own.
117412
+ */
117413
+ function remainingPulseMs(moveImpulseMs, elapsedMs) {
117414
+ if (moveImpulseMs === null) return 0;
117415
+ return Math.max(0, moveImpulseMs - elapsedMs);
117416
+ }
117417
+ /**
117418
+ * Reads `ptz.getOptions().moveImpulseMs` once and keeps it. A failed or
117419
+ * unreported read is NOT cached, so a camera that was offline at the first
117420
+ * press answers on a later one.
117421
+ */
117422
+ function createImpulseReader(bctx) {
117423
+ const { ctx, proxy, numericDeviceId } = bctx;
117424
+ let known = null;
117425
+ return { async read() {
117426
+ if (known !== null) return known;
117427
+ try {
117428
+ const ms = (await proxy.ptz?.getOptions({}))?.moveImpulseMs;
117429
+ known = typeof ms === "number" && ms > 0 ? ms : null;
117430
+ } catch (err) {
117431
+ ctx.logger.withTags({ deviceId: numericDeviceId }).debug("export-hap: ptz.getOptions failed (non-fatal)", { meta: { error: errMsg$4(err) } });
117432
+ }
117433
+ return known;
117434
+ } };
117435
+ }
114038
117436
  function errMsg$4(err) {
114039
117437
  return err instanceof Error ? err.message : String(err);
114040
117438
  }
@@ -116672,7 +120070,6 @@ var DEFAULT_CONFIG = {
116672
120070
  bridgeName: "CamStack Bridge",
116673
120071
  fixedPin: "",
116674
120072
  interfaceName: "",
116675
- ptzPulseMs: 400,
116676
120073
  clipRetentionDays: 14,
116677
120074
  identity: {
116678
120075
  username: "",
@@ -116718,6 +120115,8 @@ function buildBridgeUuid(bridgeName) {
116718
120115
  return import_dist.uuid.generate(`camstack:bridge:${bridgeName}:${Date.now()}`);
116719
120116
  }
116720
120117
  var ExportHapAddon = class extends BaseAddon {
120118
+ /** The bridge setup code pairs a controller: a credential, kept in the keychain (D787). */
120119
+ secretStatePaths = ["identity.pincode"];
116721
120120
  exposed = /* @__PURE__ */ new Map();
116722
120121
  lastError;
116723
120122
  /** Shared HAP setup code applied to every published accessory. */
@@ -117017,7 +120416,6 @@ var ExportHapAddon = class extends BaseAddon {
117017
120416
  deviceId: entry.deviceId,
117018
120417
  displayName: entry.displayName,
117019
120418
  options: {
117020
- ptzPulseMs: this.config.ptzPulseMs,
117021
120419
  decodeMemos: this.decodeMemos,
117022
120420
  resolveFfmpeg: this.pinnedFfmpeg,
117023
120421
  hksvClipStore: this.hksvClipStore,
@@ -117377,14 +120775,6 @@ var ExportHapAddon = class extends BaseAddon {
117377
120775
  description: "CamStack keeps its own copy of every clip it sends to HomeKit Secure Video — HomeKit itself never gives one back. This is the fleet default; each camera can override it, and each can switch the copies off entirely. Clips are also capped at 200 per camera, 512 MB per camera and 4 GB overall — whichever limit is reached first wins, and the log names which one.",
117378
120776
  default: DEFAULT_CONFIG.clipRetentionDays,
117379
120777
  placement: { tab: "advanced" }
117380
- }),
117381
- this.field({
117382
- type: "number",
117383
- key: "ptzPulseMs",
117384
- label: "PTZ pulse duration (ms)",
117385
- description: "Duration of a single pan/tilt momentary command issued by the PTZ direction switches in Apple Home. Lower = finer steps; higher = bigger sweeps per tap. Defaults to 400ms.",
117386
- default: DEFAULT_CONFIG.ptzPulseMs,
117387
- placement: { tab: "advanced" }
117388
120778
  })
117389
120779
  ]
117390
120780
  }] });