@camstack/addon-auth 1.2.131 → 1.2.133

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.
@@ -1,5 +1,5 @@
1
1
  require("node:crypto");
2
- //#region ../types/dist/event-category-B_0XEcLF.mjs
2
+ //#region ../types/dist/event-category-DaIZi00R.mjs
3
3
  var EventCategory = /* @__PURE__ */ function(EventCategory) {
4
4
  EventCategory["SystemBoot"] = "system.boot";
5
5
  EventCategory["SystemAddonsReady"] = "system.addons-ready";
@@ -78,6 +78,13 @@ var EventCategory = /* @__PURE__ */ function(EventCategory) {
78
78
  */
79
79
  EventCategory["AddonLoadFailed"] = "addon.load-failed";
80
80
  /**
81
+ * A keychain value was stored or removed (D787). Carries the ref, its
82
+ * owner and the new version — NEVER the value. A process holding the ref
83
+ * drops its cached copy and the owning `BaseAddon` re-resolves its config.
84
+ * Telemetry (D8): a process that misses it still revalidates by version.
85
+ */
86
+ EventCategory["KeychainChanged"] = "keychain.changed";
87
+ /**
81
88
  * Addon recovered from a previous failure. Emitted when an addon
82
89
  * transitions from `failed` back to `healthy` (typically via the
83
90
  * monitor's auto-retry loop, or after manual `addons.retryLoad`).
@@ -5370,7 +5377,7 @@ var ZodIssueCode = {
5370
5377
  var ZodFirstPartyTypeKind;
5371
5378
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
5372
5379
  //#endregion
5373
- //#region ../types/dist/sleep-B0JG7-_F.mjs
5380
+ //#region ../types/dist/sleep-DujUvOcb.mjs
5374
5381
  /**
5375
5382
  * The audio chunk plane's byte format, and the ONE expansion from a coded
5376
5383
  * window to float samples (D455).
@@ -5449,6 +5456,97 @@ function buildAlawTable() {
5449
5456
  }
5450
5457
  buildUlawTable();
5451
5458
  buildAlawTable();
5459
+ /** Is this field's stored value a credential? */
5460
+ function isSecretConfigField(field) {
5461
+ if (field.type === "password") return true;
5462
+ return "secret" in field && field.secret === true;
5463
+ }
5464
+ /**
5465
+ * Is this field's value stored in the KEYCHAIN (D787)? Every secret field is,
5466
+ * by its TYPE, unless it opts out with `storage: 'inline'` — never by its name.
5467
+ */
5468
+ function isKeychainStoredField(field) {
5469
+ if (!isSecretConfigField(field)) return false;
5470
+ if (field.type === "textarea" && field.isJson === true) return false;
5471
+ return !("storage" in field && field.storage === "inline");
5472
+ }
5473
+ /**
5474
+ * What a settings blob holds where a secret used to be.
5475
+ *
5476
+ * A keychain-stored field never holds its value. It holds a self-describing
5477
+ * MARKER, `{"$secret":"secret://…","v":1}` — an object, never a string, so no
5478
+ * code can mistake it for a credential and no form can send it to a camera as
5479
+ * a password. The empty state is `null` / absent, never `''`.
5480
+ *
5481
+ * The same shapes travel to and from the admin UI:
5482
+ *
5483
+ * - read: `hydrateSchema` hands a secret field a {@link SecretFieldView}
5484
+ * (`{ $secret, v, set: true }`) or `null` — the browser learns whether a
5485
+ * value is set, never the value.
5486
+ * - write: an untouched field submits the view back unchanged (KEEP); a typed
5487
+ * value is a plain non-empty string (CHANGE); the Clear button submits
5488
+ * {@link SECRET_CLEAR} (CLEAR). `''`, `null` and the legacy redaction tokens
5489
+ * are KEEP — an empty string is what a defaults-fallback pushes back, and
5490
+ * treating it as "clear" is how a save destroyed a stored credential before.
5491
+ *
5492
+ * Pure and browser-safe.
5493
+ */
5494
+ var SECRET_CLEAR = { $secretClear: true };
5495
+ /** The `'***'` token D634 redaction writes for non-admins. */
5496
+ var LEGACY_DEVICE_REDACTION = "***";
5497
+ function isRecord$1(value) {
5498
+ return typeof value === "object" && value !== null && !Array.isArray(value);
5499
+ }
5500
+ function makeSecretMarker(ref) {
5501
+ return {
5502
+ $secret: ref,
5503
+ v: 1
5504
+ };
5505
+ }
5506
+ /** A stored marker: an object whose `$secret` is a non-empty string. */
5507
+ function isSecretMarker(value) {
5508
+ if (!isRecord$1(value)) return false;
5509
+ const ref = value["$secret"];
5510
+ return typeof ref === "string" && ref.length > 0;
5511
+ }
5512
+ function isSecretClear(value) {
5513
+ return isRecord$1(value) && value["$secretClear"] === true;
5514
+ }
5515
+ /**
5516
+ * The UI view of a stored secret field value: a marker becomes "set", inline
5517
+ * plaintext becomes "set (inline)", nothing becomes `null`. A value never
5518
+ * survives this function.
5519
+ */
5520
+ function toSecretFieldView(stored) {
5521
+ if (isSecretMarker(stored)) return {
5522
+ $secret: stored.$secret,
5523
+ v: 1,
5524
+ set: true
5525
+ };
5526
+ if (typeof stored === "string" && stored.length > 0) return {
5527
+ $secret: null,
5528
+ v: 1,
5529
+ set: true,
5530
+ inline: true
5531
+ };
5532
+ return null;
5533
+ }
5534
+ /**
5535
+ * Classify an incoming value for a secret path. Only a non-empty string that is
5536
+ * not a redaction token sets a value; only {@link SECRET_CLEAR} clears.
5537
+ * Everything else — a marker (ours or anyone's), a UI view, `''`, `null`,
5538
+ * `undefined`, a redaction token, a non-string — keeps what is stored.
5539
+ */
5540
+ function classifySecretWrite(incoming) {
5541
+ if (isSecretClear(incoming)) return { kind: "clear" };
5542
+ if (typeof incoming !== "string") return { kind: "keep" };
5543
+ if (incoming.length === 0) return { kind: "keep" };
5544
+ if (incoming === "__camstack_redacted__" || incoming === LEGACY_DEVICE_REDACTION) return { kind: "keep" };
5545
+ return {
5546
+ kind: "set",
5547
+ value: incoming
5548
+ };
5549
+ }
5452
5550
  Object.fromEntries([
5453
5551
  {
5454
5552
  id: "overview",
@@ -5620,33 +5718,19 @@ Object.fromEntries([
5620
5718
  function isValuelessField(field) {
5621
5719
  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";
5622
5720
  }
5623
- /**
5624
- * Merge a `ConfigUISchema` with a raw `values` record into a
5625
- * `ConfigUISchemaWithValues`. Used by every `get*Settings` backend endpoint
5626
- * before returning to the admin UI. Groups are walked recursively.
5627
- *
5628
- * For each leaf field:
5629
- * - structural fields (`separator`, `info`, `button`) pass through unchanged
5630
- * - other fields get `value = values[key] ?? field.default ?? null`
5631
- *
5632
- * Unknown keys in `values` (keys not declared in the schema) are silently
5633
- * ignored — they don't contribute to the output. Missing keys fall back to
5634
- * the schema default or `null`. This mirrors the old backend behaviour where
5635
- * `FormBuilder` rendered `values[key] ?? field.default`.
5636
- */
5637
- function hydrateSchema(schema, values) {
5721
+ function hydrateSchema(schema, values, options = {}) {
5638
5722
  return {
5639
5723
  ...schema.tabs ? { tabs: [...schema.tabs] } : {},
5640
5724
  sections: schema.sections.map((section) => ({
5641
5725
  ...section,
5642
- fields: section.fields.map((field) => hydrateField(field, values))
5726
+ fields: section.fields.map((field) => hydrateField(field, values, options))
5643
5727
  }))
5644
5728
  };
5645
5729
  }
5646
- function hydrateField(field, values) {
5730
+ function hydrateField(field, values, options) {
5647
5731
  if (isValuelessField(field)) return field;
5648
5732
  if (field.type === "group") {
5649
- const hydratedChildren = field.fields.map((child) => hydrateField(child, values));
5733
+ const hydratedChildren = field.fields.map((child) => hydrateField(child, values, options));
5650
5734
  return {
5651
5735
  ...field,
5652
5736
  fields: hydratedChildren
@@ -5655,7 +5739,7 @@ function hydrateField(field, values) {
5655
5739
  if (field.type === "sub-tabs") {
5656
5740
  const hydratedTabs = field.tabs.map((tab) => ({
5657
5741
  ...tab,
5658
- fields: tab.fields.map((child) => hydrateField(child, values))
5742
+ fields: tab.fields.map((child) => hydrateField(child, values, options))
5659
5743
  }));
5660
5744
  return {
5661
5745
  ...field,
@@ -5665,6 +5749,33 @@ function hydrateField(field, values) {
5665
5749
  const key = field.key;
5666
5750
  const storedValue = Object.prototype.hasOwnProperty.call(values, key) ? values[key] : void 0;
5667
5751
  const defaultValue = field.default;
5752
+ const asView = (v) => isSecretMarker(v) || options.inlineSecretsAsViews === true && v !== void 0;
5753
+ if (isKeychainStoredField(field) && asView(storedValue)) return {
5754
+ ...field,
5755
+ value: toSecretFieldView(storedValue)
5756
+ };
5757
+ if (isKeychainStoredField(field) && options.inlineSecretsAsViews === true) return {
5758
+ ...field,
5759
+ value: null
5760
+ };
5761
+ if (field.type === "editable-array" && Array.isArray(storedValue)) {
5762
+ const secretItemKeys = field.itemFields.filter((item) => "key" in item && isKeychainStoredField(item)).map((item) => "key" in item ? item.key : "");
5763
+ if (secretItemKeys.length > 0) {
5764
+ const rows = storedValue.map((row) => {
5765
+ if (row === null || typeof row !== "object" || Array.isArray(row)) return row;
5766
+ const out = { ...row };
5767
+ for (const k of secretItemKeys) {
5768
+ const v = Reflect.get(row, k);
5769
+ if (asView(v)) out[k] = toSecretFieldView(v);
5770
+ }
5771
+ return out;
5772
+ });
5773
+ return {
5774
+ ...field,
5775
+ value: rows
5776
+ };
5777
+ }
5778
+ }
5668
5779
  if (field.multiple) {
5669
5780
  const stored = Array.isArray(storedValue) ? storedValue : storedValue !== void 0 && storedValue !== null ? [storedValue] : [];
5670
5781
  const itemFallback = field.multiple.itemDefault !== void 0 ? field.multiple.itemDefault : defaultValue !== void 0 ? defaultValue : typeOf(field) === "string" ? "" : null;
@@ -5907,6 +6018,431 @@ function projectStore(store, perNodeKeys, nodeId) {
5907
6018
  }
5908
6019
  return out;
5909
6020
  }
6021
+ var GLOBAL_SCOPE = { kind: "global" };
6022
+ /** The scope every addon-wide (not per-node, not per-device) setting lives in. */
6023
+ function globalSecretScope() {
6024
+ return GLOBAL_SCOPE;
6025
+ }
6026
+ function encodeSegment(value) {
6027
+ return encodeURIComponent(value);
6028
+ }
6029
+ /**
6030
+ * The field path of a value inside an array item, addressed by the item's id:
6031
+ * `arrayItemFieldPath('providers', 'authentik', 'clientSecret')` →
6032
+ * `providers[authentik].clientSecret`.
6033
+ */
6034
+ function arrayItemFieldPath(arrayKey, itemId, fieldKey) {
6035
+ return `${arrayKey}[${encodeSegment(itemId)}].${fieldKey}`;
6036
+ }
6037
+ /** A write to a secret path could not be stored in the keychain, so it was refused. */
6038
+ var KeychainWriteRefusedError = class extends Error {
6039
+ fieldPath;
6040
+ constructor(fieldPath, cause) {
6041
+ super(`secret "${fieldPath}" was not saved: the keychain could not store it (${cause instanceof Error ? cause.message : String(cause)}). Nothing was written.`);
6042
+ this.fieldPath = fieldPath;
6043
+ this.name = "KeychainWriteRefusedError";
6044
+ }
6045
+ };
6046
+ var KEEP = { kind: "keep" };
6047
+ function isRecord(value) {
6048
+ return typeof value === "object" && value !== null && !Array.isArray(value);
6049
+ }
6050
+ function defaultMintId() {
6051
+ return globalThis.crypto.randomUUID();
6052
+ }
6053
+ /** Every marker ref anywhere under `value`. */
6054
+ function collectSecretMarkerRefs(value, out = []) {
6055
+ if (isSecretMarker(value)) {
6056
+ out.push(value.$secret);
6057
+ return out;
6058
+ }
6059
+ if (Array.isArray(value)) for (const item of value) collectSecretMarkerRefs(item, out);
6060
+ else if (isRecord(value)) for (const child of Object.values(value)) collectSecretMarkerRefs(child, out);
6061
+ return out;
6062
+ }
6063
+ async function storedValueEquals(secrets, marker, candidate) {
6064
+ const resolved = (await secrets.resolve([marker.$secret]))[marker.$secret];
6065
+ return resolved?.kind === "value" && resolved.value === candidate;
6066
+ }
6067
+ async function writeLeaf(ctx, incoming, stored, fieldPath) {
6068
+ const intent = classifySecretWrite(incoming);
6069
+ const ref = ctx.secrets.ref(ctx.scope, fieldPath);
6070
+ const storedIsOurs = isSecretMarker(stored) && stored.$secret === ref;
6071
+ if (intent.kind === "keep") return KEEP;
6072
+ if (intent.kind === "set" && !ctx.operatorWrite && typeof stored === "string" && stored === intent.value) return KEEP;
6073
+ if (intent.kind === "clear") {
6074
+ if (storedIsOurs) ctx.deletes.push(ref);
6075
+ return {
6076
+ kind: "value",
6077
+ value: null
6078
+ };
6079
+ }
6080
+ if (storedIsOurs && await storedValueEquals(ctx.secrets, stored, intent.value)) return {
6081
+ kind: "value",
6082
+ value: stored
6083
+ };
6084
+ try {
6085
+ await ctx.secrets.put(ref, intent.value);
6086
+ } catch (err) {
6087
+ throw new KeychainWriteRefusedError(fieldPath, err);
6088
+ }
6089
+ return {
6090
+ kind: "value",
6091
+ value: makeSecretMarker(ref)
6092
+ };
6093
+ }
6094
+ /** Apply a member result onto `out`: KEEP restores the stored member, or removes it. */
6095
+ function applyMember(out, key, result, storedParent) {
6096
+ if (result.kind === "value") {
6097
+ out[key] = result.value;
6098
+ return;
6099
+ }
6100
+ if (Object.prototype.hasOwnProperty.call(storedParent, key)) out[key] = storedParent[key];
6101
+ else delete out[key];
6102
+ }
6103
+ async function writeMembers(ctx, children, incoming, stored, pathOf) {
6104
+ const out = { ...incoming };
6105
+ for (const [member, node] of children) applyMember(out, member, await writeNode(ctx, node, incoming[member], stored[member], pathOf(member)), stored);
6106
+ return out;
6107
+ }
6108
+ function rowId(row, idKey) {
6109
+ const raw = row[idKey];
6110
+ if (typeof raw === "string" && raw.length > 0) return raw;
6111
+ if (typeof raw === "number" && Number.isFinite(raw)) return String(raw);
6112
+ return null;
6113
+ }
6114
+ async function writeArray(ctx, node, incoming, stored, fieldPath) {
6115
+ const storedRows = Array.isArray(stored) ? stored.filter(isRecord) : [];
6116
+ if (!Array.isArray(incoming)) {
6117
+ ctx.deletes.push(...collectSecretMarkerRefs(storedRows));
6118
+ return {
6119
+ kind: "value",
6120
+ value: incoming
6121
+ };
6122
+ }
6123
+ const storedById = /* @__PURE__ */ new Map();
6124
+ for (const row of storedRows) {
6125
+ const id = rowId(row, node.idKey);
6126
+ if (id !== null) storedById.set(id, row);
6127
+ }
6128
+ const kept = /* @__PURE__ */ new Set();
6129
+ const rows = [];
6130
+ for (const row of incoming) {
6131
+ if (!isRecord(row)) {
6132
+ rows.push(row);
6133
+ continue;
6134
+ }
6135
+ const id = rowId(row, node.idKey) ?? ctx.mintId();
6136
+ kept.add(id);
6137
+ const withId = {
6138
+ ...row,
6139
+ [node.idKey]: row[node.idKey] ?? id
6140
+ };
6141
+ if (rowId(withId, node.idKey) === null) withId[node.idKey] = id;
6142
+ const storedRow = storedById.get(id) ?? {};
6143
+ rows.push(await writeMembers(ctx, node.item, withId, storedRow, (member) => arrayItemFieldPath(fieldPath, id, member)));
6144
+ }
6145
+ for (const [id, row] of storedById) if (!kept.has(id)) ctx.deletes.push(...collectSecretMarkerRefs(row));
6146
+ return {
6147
+ kind: "value",
6148
+ value: rows
6149
+ };
6150
+ }
6151
+ async function writeNode(ctx, node, incoming, stored, fieldPath) {
6152
+ switch (node.kind) {
6153
+ case "leaf": return writeLeaf(ctx, incoming, stored, fieldPath);
6154
+ case "array": return writeArray(ctx, node, incoming, stored, fieldPath);
6155
+ case "object": {
6156
+ if (!isRecord(incoming)) {
6157
+ if (incoming === void 0) return KEEP;
6158
+ ctx.deletes.push(...collectSecretMarkerRefs(stored));
6159
+ return {
6160
+ kind: "value",
6161
+ value: incoming
6162
+ };
6163
+ }
6164
+ const storedObj = isRecord(stored) ? stored : {};
6165
+ return {
6166
+ kind: "value",
6167
+ value: await writeMembers(ctx, node.children, incoming, storedObj, (m) => `${fieldPath}.${m}`)
6168
+ };
6169
+ }
6170
+ }
6171
+ }
6172
+ /** Split a perNode-scoped key (`key@nodeId`). */
6173
+ function splitNodeKey(key) {
6174
+ const at = key.indexOf("@");
6175
+ return at <= 0 ? {
6176
+ base: key,
6177
+ nodeId: null
6178
+ } : {
6179
+ base: key.slice(0, at),
6180
+ nodeId: key.slice(at + 1)
6181
+ };
6182
+ }
6183
+ /** Rewrite a settings patch so no secret value reaches the blob. See the file doc. */
6184
+ async function transformSecretWrite(input) {
6185
+ const deletes = [];
6186
+ const base = {
6187
+ secrets: input.secrets,
6188
+ mintId: input.mintId ?? defaultMintId,
6189
+ deletes,
6190
+ operatorWrite: input.operatorWrite === true
6191
+ };
6192
+ const out = {};
6193
+ for (const [key, incoming] of Object.entries(input.patch)) {
6194
+ const { base: baseKey, nodeId } = splitNodeKey(key);
6195
+ const node = input.tree.get(baseKey);
6196
+ if (node === void 0) {
6197
+ out[key] = incoming;
6198
+ continue;
6199
+ }
6200
+ const scope = nodeId !== null && nodeId.length > 0 ? {
6201
+ kind: "node",
6202
+ nodeId
6203
+ } : input.scope ?? globalSecretScope();
6204
+ const result = await writeNode({
6205
+ ...base,
6206
+ scope
6207
+ }, node, incoming, input.stored[key], baseKey);
6208
+ if (result.kind === "value") out[key] = result.value;
6209
+ }
6210
+ return {
6211
+ patch: out,
6212
+ afterWrite: async () => {
6213
+ if (deletes.length === 0) return { orphaned: [] };
6214
+ try {
6215
+ await input.secrets.delete([...new Set(deletes)]);
6216
+ return { orphaned: [] };
6217
+ } catch {
6218
+ return { orphaned: [...new Set(deletes)] };
6219
+ }
6220
+ }
6221
+ };
6222
+ }
6223
+ /**
6224
+ * Replace every marker in `value` with its keychain value. Returns the SAME
6225
+ * reference when there is no marker (no allocation, no keychain call).
6226
+ */
6227
+ async function resolveSecretMarkers(value, secrets) {
6228
+ const refs = collectSecretMarkerRefs(value);
6229
+ if (refs.length === 0) return {
6230
+ value,
6231
+ unresolved: []
6232
+ };
6233
+ const answers = await secrets.resolve(refs);
6234
+ const unresolved = [];
6235
+ for (const ref of new Set(refs)) {
6236
+ const answer = answers[ref];
6237
+ if (answer === void 0) unresolved.push({
6238
+ ref,
6239
+ reason: "not-initialized"
6240
+ });
6241
+ else if (answer.kind === "unavailable") unresolved.push({
6242
+ ref,
6243
+ reason: answer.reason
6244
+ });
6245
+ else if (answer.kind === "missing" || answer.kind === "forbidden") unresolved.push({
6246
+ ref,
6247
+ reason: answer.kind
6248
+ });
6249
+ }
6250
+ const substitute = (v) => {
6251
+ if (isSecretMarker(v)) {
6252
+ const answer = answers[v.$secret];
6253
+ return answer?.kind === "value" ? {
6254
+ keep: true,
6255
+ value: answer.value
6256
+ } : {
6257
+ keep: false,
6258
+ value: void 0
6259
+ };
6260
+ }
6261
+ if (Array.isArray(v)) {
6262
+ const items = [];
6263
+ for (const item of v) {
6264
+ const s = substitute(item);
6265
+ if (s.keep) items.push(s.value);
6266
+ }
6267
+ return {
6268
+ keep: true,
6269
+ value: items
6270
+ };
6271
+ }
6272
+ if (isRecord(v)) {
6273
+ const out = {};
6274
+ for (const [k, child] of Object.entries(v)) {
6275
+ const s = substitute(child);
6276
+ if (s.keep) out[k] = s.value;
6277
+ }
6278
+ return {
6279
+ keep: true,
6280
+ value: out
6281
+ };
6282
+ }
6283
+ return {
6284
+ keep: true,
6285
+ value: v
6286
+ };
6287
+ };
6288
+ return {
6289
+ value: substitute(value).value,
6290
+ unresolved
6291
+ };
6292
+ }
6293
+ function touchesTree(tree, patch) {
6294
+ if (tree.size === 0) return false;
6295
+ for (const key of Object.keys(patch)) {
6296
+ const at = key.indexOf("@");
6297
+ if (tree.has(at > 0 ? key.slice(0, at) : key)) return true;
6298
+ }
6299
+ return false;
6300
+ }
6301
+ /** The blob as stored now; a failed read REFUSES the write instead of guessing. */
6302
+ async function readStoredAddonBlob(raw) {
6303
+ const threeWay = raw.readAddonStoreResult;
6304
+ if (threeWay === void 0) return raw.readAddonStore();
6305
+ const result = await threeWay.call(raw);
6306
+ if (result.kind === "failed") throw new Error(`settings write refused: the stored blob could not be read (${result.error})`);
6307
+ return result.kind === "missing" ? {} : result.value;
6308
+ }
6309
+ function createSecretAwareSettings(raw, opts) {
6310
+ const chains = /* @__PURE__ */ new Map();
6311
+ const serialize = (key, fn) => {
6312
+ const next = (chains.get(key) ?? Promise.resolve()).then(fn, fn);
6313
+ const tail = next.catch(() => void 0);
6314
+ chains.set(key, tail);
6315
+ tail.then(() => {
6316
+ if (chains.get(key) === tail) chains.delete(key);
6317
+ });
6318
+ return next;
6319
+ };
6320
+ const write = async (chainKey, tree, scope, patch, readStored, rawWrite) => {
6321
+ if (!touchesTree(tree, patch)) return rawWrite(patch);
6322
+ return serialize(chainKey, async () => {
6323
+ const stored = await readStored();
6324
+ const result = await transformSecretWrite({
6325
+ tree,
6326
+ secrets: opts.secrets,
6327
+ patch,
6328
+ stored,
6329
+ ...scope !== void 0 ? { scope } : {},
6330
+ operatorWrite: opts.isOperatorWrite?.() === true
6331
+ });
6332
+ if (Object.keys(result.patch).length > 0) await rawWrite(result.patch);
6333
+ const { orphaned } = await result.afterWrite();
6334
+ if (orphaned.length > 0) opts.onOrphaned(orphaned);
6335
+ });
6336
+ };
6337
+ const wrapped = {
6338
+ writeAddonStore: (patch) => write("addon", opts.addonTree(), void 0, patch, () => readStoredAddonBlob(raw), (p) => raw.writeAddonStore(p)),
6339
+ writeDeviceStore: (deviceId, patch) => write(`device:${deviceId}`, opts.deviceTree(), {
6340
+ kind: "device",
6341
+ deviceId
6342
+ }, patch, () => raw.readDeviceStore(deviceId), (p) => raw.writeDeviceStore(deviceId, p))
6343
+ };
6344
+ return new Proxy(raw, { get(target, prop, receiver) {
6345
+ if (prop === "writeAddonStore") return wrapped.writeAddonStore;
6346
+ if (prop === "writeDeviceStore") return wrapped.writeDeviceStore;
6347
+ const value = Reflect.get(target, prop, receiver);
6348
+ return typeof value === "function" ? value.bind(target) : value;
6349
+ } });
6350
+ }
6351
+ /** The context the addon sees: identical, except that its settings writes are secret-aware. */
6352
+ function withSecretAwareSettings(context, opts) {
6353
+ const raw = context.settings;
6354
+ if (raw === void 0) return context;
6355
+ const settings = createSecretAwareSettings(raw, opts);
6356
+ return new Proxy(context, { get(target, prop, receiver) {
6357
+ if (prop === "settings") return settings;
6358
+ return Reflect.get(target, prop, receiver);
6359
+ } });
6360
+ }
6361
+ var LEAF = { kind: "leaf" };
6362
+ var DEFAULT_ITEM_ID_KEY = "id";
6363
+ function collectFields(fields, out) {
6364
+ for (const field of fields) {
6365
+ if (field.type === "group") {
6366
+ collectFields(field.fields, out);
6367
+ continue;
6368
+ }
6369
+ if (field.type === "sub-tabs") {
6370
+ for (const tab of field.tabs) collectFields(tab.fields, out);
6371
+ continue;
6372
+ }
6373
+ if (field.type === "editable-array") {
6374
+ const item = /* @__PURE__ */ new Map();
6375
+ for (const itemField of field.itemFields) if ("key" in itemField && isKeychainStoredField(itemField)) item.set(itemField.key, LEAF);
6376
+ if (item.size > 0) out.set(field.key, {
6377
+ kind: "array",
6378
+ idKey: field.itemIdKey ?? DEFAULT_ITEM_ID_KEY,
6379
+ item
6380
+ });
6381
+ continue;
6382
+ }
6383
+ if (!("key" in field) || typeof field.key !== "string") continue;
6384
+ if (isKeychainStoredField(field)) out.set(field.key, LEAF);
6385
+ }
6386
+ }
6387
+ /** The secret tree a settings schema declares. */
6388
+ function secretTreeFromSchema(schema) {
6389
+ const out = /* @__PURE__ */ new Map();
6390
+ if (schema === null) return out;
6391
+ for (const section of schema.sections) collectFields(section.fields, out);
6392
+ return out;
6393
+ }
6394
+ /** Parse `a.b[id].c` into segments; throws on a malformed path (a declaration bug). */
6395
+ function parseSecretStatePath(path) {
6396
+ const segments = [];
6397
+ for (const raw of path.split(".")) {
6398
+ const m = /^([^[\]]+)(?:\[([^[\]]+)\])?$/.exec(raw);
6399
+ if (m === null || m[1] === void 0) throw new Error(`secretStatePaths: malformed path "${path}"`);
6400
+ segments.push(m[2] !== void 0 ? {
6401
+ key: m[1],
6402
+ idKey: m[2]
6403
+ } : { key: m[1] });
6404
+ }
6405
+ if (segments.length === 0) throw new Error(`secretStatePaths: empty path`);
6406
+ if (segments[segments.length - 1]?.idKey !== void 0) throw new Error(`secretStatePaths: "${path}" ends on an array — name the member that is secret`);
6407
+ return segments;
6408
+ }
6409
+ function insert(into, segments) {
6410
+ const [head, ...rest] = segments;
6411
+ if (head === void 0) return;
6412
+ if (rest.length === 0) {
6413
+ into.set(head.key, LEAF);
6414
+ return;
6415
+ }
6416
+ const existing = into.get(head.key);
6417
+ if (head.idKey !== void 0) {
6418
+ const item = new Map(existing?.kind === "array" ? existing.item : []);
6419
+ insert(item, rest);
6420
+ into.set(head.key, {
6421
+ kind: "array",
6422
+ idKey: head.idKey,
6423
+ item
6424
+ });
6425
+ return;
6426
+ }
6427
+ const children = new Map(existing?.kind === "object" ? existing.children : []);
6428
+ insert(children, rest);
6429
+ into.set(head.key, {
6430
+ kind: "object",
6431
+ children
6432
+ });
6433
+ }
6434
+ /** Add hidden-state paths (`secretStatePaths`) to a schema-derived tree. */
6435
+ function mergeSecretStatePaths(tree, paths) {
6436
+ if (paths.length === 0) return tree;
6437
+ const out = new Map(tree);
6438
+ for (const path of paths) insert(out, parseSecretStatePath(path));
6439
+ return out;
6440
+ }
6441
+ /** First retry of a secret the keychain could not serve; doubles to {@link SECRET_RETRY_MAX_MS}. */
6442
+ var SECRET_RETRY_FIRST_MS = 5e3;
6443
+ var SECRET_RETRY_MAX_MS = 5 * 6e4;
6444
+ /** Coalesces a burst of `keychain.changed` events into one re-resolve. */
6445
+ var SECRET_CHANGE_DEBOUNCE_MS = 250;
5910
6446
  /**
5911
6447
  * Base class for CamStack addons. Eliminates settings boilerplate:
5912
6448
  *
@@ -5976,6 +6512,25 @@ var BaseAddon = class {
5976
6512
  settingsStoreReady = false;
5977
6513
  /** Default config values. Provided via constructor. */
5978
6514
  defaults;
6515
+ /**
6516
+ * Hidden-state paths that hold secrets (D787) — values the addon writes
6517
+ * itself (`updateGlobalSettings`, `state()`) that no form field declares.
6518
+ * Stored in the keychain exactly like a `password` field. Syntax:
6519
+ * `'snapshotSigningKey'`, `'identity.pincode'`, `'tokens[userId].accessToken'`
6520
+ * (`key[<id field>]` addresses array items by id, never by index).
6521
+ */
6522
+ secretStatePaths = [];
6523
+ _addonSecretTree = null;
6524
+ _deviceSecretTree = null;
6525
+ /** Refs the last resolved config pointed at — a change to one re-resolves. */
6526
+ _configSecretRefs = /* @__PURE__ */ new Set();
6527
+ _unresolvedSecrets = [];
6528
+ _secretRetryTimer = null;
6529
+ _secretRetryDelayMs = SECRET_RETRY_FIRST_MS;
6530
+ _secretChangeTimer = null;
6531
+ _secretChangeUnsub = null;
6532
+ /** >0 while an OPERATOR's settings write is being applied. */
6533
+ _operatorWriteDepth = 0;
5979
6534
  constructor(defaults) {
5980
6535
  this.defaults = defaults;
5981
6536
  this._config = { ...defaults };
@@ -6011,8 +6566,18 @@ var BaseAddon = class {
6011
6566
  return this._config;
6012
6567
  }
6013
6568
  async initialize(context) {
6014
- this._ctx = context;
6569
+ const secrets = context.secrets;
6570
+ this._ctx = secrets !== void 0 ? withSecretAwareSettings(context, {
6571
+ secrets,
6572
+ addonTree: () => this.addonSecretTree(),
6573
+ deviceTree: () => this.deviceSecretTree(),
6574
+ onOrphaned: (refs) => context.logger.warn("keychain refs dropped by a settings write could not be deleted", { meta: { refs: [...refs] } }),
6575
+ isOperatorWrite: () => this._operatorWriteDepth > 0
6576
+ }) : context;
6015
6577
  await this.resolveConfig();
6578
+ if (secrets !== void 0) this._secretChangeUnsub = secrets.onChange((ref) => {
6579
+ if (this._configSecretRefs.has(ref)) this.scheduleSecretReresolve(SECRET_CHANGE_DEBOUNCE_MS);
6580
+ });
6016
6581
  const result = await this.onInitialize();
6017
6582
  this.emitLifecycle(EventCategory.AddonStarted);
6018
6583
  const normalized = normalizeAddonInitResult(result);
@@ -6045,6 +6610,12 @@ var BaseAddon = class {
6045
6610
  */
6046
6611
  async onHubReachable() {}
6047
6612
  async shutdown() {
6613
+ this._secretChangeUnsub?.();
6614
+ this._secretChangeUnsub = null;
6615
+ if (this._secretRetryTimer !== null) clearTimeout(this._secretRetryTimer);
6616
+ if (this._secretChangeTimer !== null) clearTimeout(this._secretChangeTimer);
6617
+ this._secretRetryTimer = null;
6618
+ this._secretChangeTimer = null;
6048
6619
  this.emitLifecycle(EventCategory.AddonStopped);
6049
6620
  if (this.autoEmitReadiness) this.emitReadinessForProviders("down");
6050
6621
  await this.onShutdown();
@@ -6123,7 +6694,7 @@ var BaseAddon = class {
6123
6694
  return hydrateSchema(schema, overlay ? {
6124
6695
  ...projected,
6125
6696
  ...overlay
6126
- } : projected);
6697
+ } : projected, { inlineSecretsAsViews: true });
6127
6698
  }
6128
6699
  /**
6129
6700
  * The integration-level view of this addon's settings: exactly the sections
@@ -6172,7 +6743,7 @@ var BaseAddon = class {
6172
6743
  return hydrateSchema({
6173
6744
  ...schema,
6174
6745
  sections
6175
- }, projected);
6746
+ }, projected, { inlineSecretsAsViews: true });
6176
6747
  }
6177
6748
  /**
6178
6749
  * The raw addon store PROJECTED onto the target node's bare per-node keys:
@@ -6226,18 +6797,50 @@ var BaseAddon = class {
6226
6797
  value: result.value[key]
6227
6798
  };
6228
6799
  }
6800
+ /**
6801
+ * The OPERATOR's write — a settings form or an admin API call, dispatched by
6802
+ * the kernel. Identical to {@link updateGlobalSettings}, except that a secret
6803
+ * the operator sends is stored as sent even when it equals a pre-keychain
6804
+ * inline value: the operator re-entering a password is a change, an addon
6805
+ * writing back what it read is not (D787).
6806
+ */
6807
+ async updateGlobalSettingsAsOperator(patch, nodeId) {
6808
+ this._operatorWriteDepth++;
6809
+ try {
6810
+ await this.applyGlobalPatch(patch, nodeId);
6811
+ } finally {
6812
+ this._operatorWriteDepth--;
6813
+ }
6814
+ }
6229
6815
  async updateGlobalSettings(patch, nodeId) {
6816
+ await this.applyGlobalPatch(patch, nodeId);
6817
+ }
6818
+ /**
6819
+ * REMOVE stored secrets — their keychain values and their markers (D787).
6820
+ *
6821
+ * Writing `''` to a secret field KEEPS what is stored (an empty string is
6822
+ * what a defaults fallback writes back, and it must never destroy a
6823
+ * credential), so code that means "forget this token" says so here. Without
6824
+ * a keychain (an older kernel) it writes `''`, as such code always did.
6825
+ */
6826
+ async clearSecrets(keys, nodeId) {
6827
+ const tree = this.addonSecretTree();
6828
+ const keychain = this._ctx?.secrets !== void 0;
6829
+ const patch = {};
6830
+ for (const key of keys) patch[key] = keychain && tree.has(key) ? SECRET_CLEAR : "";
6831
+ await this.applyGlobalPatch(patch, nodeId);
6832
+ }
6833
+ async applyGlobalPatch(barePatch, nodeId) {
6230
6834
  const keys = this.perNodeKeys();
6231
6835
  const localNode = normalizeNodeId(this._ctx?.kernel?.localNodeId);
6232
6836
  const target = normalizeNodeId(nodeId ?? this._ctx?.kernel?.localNodeId);
6233
- const barePatch = patch;
6234
6837
  const scoped = keys.size > 0 ? scopePatch(barePatch, keys, target) : barePatch;
6235
6838
  await this._ctx?.settings?.writeAddonStore(scoped);
6236
6839
  if (target !== localNode) return;
6237
6840
  await this.resolveConfig();
6238
6841
  await this.onConfigChanged();
6239
6842
  this.emitLifecycle(EventCategory.AddonUpdated, { level: "global" });
6240
- this.maybeAutoRestart(patch, this.globalSettingsSchema());
6843
+ this.maybeAutoRestart(Object.keys(barePatch), this.globalSettingsSchema());
6241
6844
  }
6242
6845
  /**
6243
6846
  * The set of field keys the global settings schema declares `perNode: true`
@@ -6262,7 +6865,7 @@ var BaseAddon = class {
6262
6865
  * time to return its response before the addon is torn down and
6263
6866
  * re-initialised by `AddonRegistryService.restartAddon`.
6264
6867
  */
6265
- maybeAutoRestart(patch, schema) {
6868
+ maybeAutoRestart(patchKeys, schema) {
6266
6869
  if (!schema) return;
6267
6870
  const restartKeys = /* @__PURE__ */ new Set();
6268
6871
  for (const section of schema.sections) for (const field of section.fields) {
@@ -6270,13 +6873,13 @@ var BaseAddon = class {
6270
6873
  if (field.requiresRestart) restartKeys.add(field.key);
6271
6874
  }
6272
6875
  if (restartKeys.size === 0) return;
6273
- if (!Object.keys(patch).some((k) => restartKeys.has(k))) return;
6876
+ if (!patchKeys.some((k) => restartKeys.has(k))) return;
6274
6877
  const ctx = this._ctx;
6275
6878
  if (!ctx) return;
6276
6879
  const addonId = ctx.id;
6277
6880
  setImmediate(() => {
6278
6881
  ctx.api.addons?.restartAddon?.mutate({ addonId }).then(() => {
6279
- ctx.logger.info("addon auto-restart triggered by restart-required setting change", { meta: { changedFields: Object.keys(patch).filter((k) => restartKeys.has(k)) } });
6882
+ ctx.logger.info("addon auto-restart triggered by restart-required setting change", { meta: { changedFields: patchKeys.filter((k) => restartKeys.has(k)) } });
6280
6883
  }).catch((err) => {
6281
6884
  ctx.logger.error("addon auto-restart failed", { meta: { error: err instanceof Error ? err.message : String(err) } });
6282
6885
  });
@@ -6285,7 +6888,7 @@ var BaseAddon = class {
6285
6888
  async getDeviceSettings(deviceId) {
6286
6889
  const schema = this.deviceSettingsSchema();
6287
6890
  if (!schema) return { sections: [] };
6288
- return hydrateSchema(schema, await this._ctx?.settings?.readDeviceStore(deviceId) ?? {});
6891
+ return hydrateSchema(schema, await this._ctx?.settings?.readDeviceStore(deviceId) ?? {}, { inlineSecretsAsViews: true });
6289
6892
  }
6290
6893
  async updateDeviceSettings(deviceId, patch) {
6291
6894
  await this._ctx?.settings?.writeDeviceStore(deviceId, patch);
@@ -6415,7 +7018,7 @@ var BaseAddon = class {
6415
7018
  * selection at boot (absent scoped key ⇒ the constructor default wins).
6416
7019
  */
6417
7020
  async resolveConfig() {
6418
- const stored = await this.readAddonStoreWithRetry();
7021
+ const stored = await this.resolveStoredSecrets(await this.readAddonStoreWithRetry());
6419
7022
  const perNode = this.perNodeKeys();
6420
7023
  const localNode = normalizeNodeId(this._ctx?.kernel?.localNodeId);
6421
7024
  const resolved = { ...this.defaults };
@@ -6440,7 +7043,7 @@ var BaseAddon = class {
6440
7043
  key,
6441
7044
  schema,
6442
7045
  fallback,
6443
- read: () => this.readAddonStoreWithRetry(),
7046
+ read: async () => this.resolveStoredSecrets(await this.readAddonStoreWithRetry()),
6444
7047
  write: async (patch) => {
6445
7048
  await this._ctx?.settings?.writeAddonStore(patch);
6446
7049
  },
@@ -6457,7 +7060,7 @@ var BaseAddon = class {
6457
7060
  key,
6458
7061
  schema,
6459
7062
  fallback,
6460
- read: async () => await this._ctx?.settings?.readDeviceStore(deviceId) ?? {},
7063
+ read: async () => this.resolveStoredSecrets(await this._ctx?.settings?.readDeviceStore(deviceId) ?? {}, false),
6461
7064
  write: async (patch) => {
6462
7065
  await this._ctx?.settings?.writeDeviceStore(deviceId, patch);
6463
7066
  },
@@ -6469,6 +7072,70 @@ var BaseAddon = class {
6469
7072
  } })
6470
7073
  });
6471
7074
  }
7075
+ /** The addon store's secret tree: schema fields by TYPE, plus `secretStatePaths`. */
7076
+ addonSecretTree() {
7077
+ this._addonSecretTree ??= mergeSecretStatePaths(secretTreeFromSchema(this.globalSettingsSchema()), this.secretStatePaths);
7078
+ return this._addonSecretTree;
7079
+ }
7080
+ deviceSecretTree() {
7081
+ this._deviceSecretTree ??= secretTreeFromSchema(this.deviceSettingsSchema());
7082
+ return this._deviceSecretTree;
7083
+ }
7084
+ /**
7085
+ * Secrets of this addon's stored config that could not be resolved on the
7086
+ * last read, with why. Non-empty means the addon is running WITHOUT them —
7087
+ * an addon whose function needs one should report itself degraded rather
7088
+ * than start on an empty credential.
7089
+ */
7090
+ get unresolvedSecrets() {
7091
+ return this._unresolvedSecrets;
7092
+ }
7093
+ /**
7094
+ * Substitute every keychain marker in a stored blob with its value. With no
7095
+ * keychain (no `ctx.secrets`) or no marker, the blob comes back unchanged.
7096
+ * An unresolvable value is LEFT OUT (never `''`), logged by ref — never by
7097
+ * value — and, when the cause can pass, retried with backoff. Nothing is
7098
+ * ever written back from here.
7099
+ */
7100
+ async resolveStoredSecrets(blob, trackForConfig = true) {
7101
+ const secrets = this._ctx?.secrets;
7102
+ if (secrets === void 0) return blob;
7103
+ const refs = collectSecretMarkerRefs(blob);
7104
+ if (trackForConfig) this._configSecretRefs = new Set(refs);
7105
+ if (refs.length === 0) {
7106
+ if (trackForConfig) this._unresolvedSecrets = [];
7107
+ return blob;
7108
+ }
7109
+ const { value, unresolved } = await resolveSecretMarkers(blob, secrets);
7110
+ if (trackForConfig) {
7111
+ this._unresolvedSecrets = unresolved;
7112
+ if (unresolved.length > 0) {
7113
+ this._ctx?.logger?.error?.("secret unavailable — running without it, will retry", { meta: { secrets: unresolved.map((u) => ({
7114
+ ref: u.ref,
7115
+ reason: u.reason
7116
+ })) } });
7117
+ if (unresolved.some((u) => u.reason !== "missing" && u.reason !== "forbidden")) {
7118
+ this.scheduleSecretReresolve(this._secretRetryDelayMs);
7119
+ this._secretRetryDelayMs = Math.min(this._secretRetryDelayMs * 2, SECRET_RETRY_MAX_MS);
7120
+ }
7121
+ } else this._secretRetryDelayMs = SECRET_RETRY_FIRST_MS;
7122
+ }
7123
+ return value;
7124
+ }
7125
+ /** Re-resolve the config (a keychain-only change, or a retry) and apply it. */
7126
+ scheduleSecretReresolve(delayMs) {
7127
+ const timerOf = delayMs === SECRET_CHANGE_DEBOUNCE_MS ? "_secretChangeTimer" : "_secretRetryTimer";
7128
+ if (this[timerOf] !== null) return;
7129
+ const timer = setTimeout(() => {
7130
+ this[timerOf] = null;
7131
+ if (this._ctx === null) return;
7132
+ this.resolveConfig().then(() => this.onConfigChanged()).catch((err) => {
7133
+ this._ctx?.logger?.error?.("re-resolving secrets failed", { meta: { error: err instanceof Error ? err.message : String(err) } });
7134
+ });
7135
+ }, delayMs);
7136
+ timer.unref?.();
7137
+ this[timerOf] = timer;
7138
+ }
6472
7139
  /**
6473
7140
  * Wrap `ctx.settings.readAddonStore()` with a short retry budget so a
6474
7141
  * transient settings-store outage (mid-restart of sqlite-settings, tsx-watch
@@ -14136,6 +14803,214 @@ id: union([string(), number()]) }), {
14136
14803
  kind: "mutation",
14137
14804
  auth: "admin"
14138
14805
  });
14806
+ /**
14807
+ * `keychain` — the hub's encrypted store of secret values (D787).
14808
+ *
14809
+ * Settings blobs never hold a secret: they hold a marker
14810
+ * `{"$secret":"secret://<owner>/<scope>/<fieldPath>","v":1}` and the value
14811
+ * lives here, AES-256-GCM under a data key that a master key wraps. This cap
14812
+ * is the OWNER's door to its own values: every method is owner-checked
14813
+ * against the CALLER, never against anything the caller claims.
14814
+ *
14815
+ * Who the caller is: the transport stamps `callerAddonId` into the args of a
14816
+ * call that crossed a process (the parent `LocalChildRegistry` from the UDS
14817
+ * connection, the agent from its child's connection carried in
14818
+ * `$hub-cap-fwd`'s envelope). A stamp always overwrites; a wire call with no
14819
+ * stamp has its claim stripped. Only a hub in-process caller may state its own
14820
+ * identity — `ctx.secrets` does that with the addon id closed over. This is
14821
+ * identity against BUGS and misrouting, not against a malicious addon (every
14822
+ * runner is the same OS user): see the threat model in
14823
+ * `docs/design/2026-10-08-secrets-keychain.md`.
14824
+ *
14825
+ * `callerAddonId` is deliberately NOT in any input schema: the tRPC router
14826
+ * parses the input, so a session can never supply it, and the internal mount
14827
+ * floors every method to admin anyway (D240).
14828
+ *
14829
+ * Internal: addons reach it through `ctx.secrets`, never directly.
14830
+ */
14831
+ /** Why a value cannot be served right now. Never folded into "missing". */
14832
+ var KeychainUnavailableReasonSchema = _enum([
14833
+ "key-missing",
14834
+ "wrong-key",
14835
+ "key-file-unreadable",
14836
+ "store-unavailable",
14837
+ "not-initialized",
14838
+ "decrypt-failed"
14839
+ ]);
14840
+ var KeychainStateSchema = discriminatedUnion("state", [object({ state: literal("ready") }), object({
14841
+ state: literal("locked"),
14842
+ reason: KeychainUnavailableReasonSchema
14843
+ })]);
14844
+ var KeychainResolveEntrySchema = discriminatedUnion("kind", [
14845
+ object({
14846
+ kind: literal("value"),
14847
+ value: string(),
14848
+ version: number().int()
14849
+ }),
14850
+ object({ kind: literal("missing") }),
14851
+ object({
14852
+ kind: literal("unavailable"),
14853
+ reason: KeychainUnavailableReasonSchema
14854
+ }),
14855
+ object({ kind: literal("forbidden") })
14856
+ ]);
14857
+ var KeychainResolveResultSchema = record(string(), KeychainResolveEntrySchema);
14858
+ /** Metadata of one stored value — never the value. */
14859
+ var KeychainSecretMetaSchema = object({
14860
+ ref: string(),
14861
+ owner: string(),
14862
+ /** Formatted scope (`global`, `node/<id>`, `device/<id>`, …). */
14863
+ scope: string(),
14864
+ fieldPath: string(),
14865
+ version: number().int(),
14866
+ createdAt: number(),
14867
+ updatedAt: number(),
14868
+ /** `addon:<id>` | `user:<id>` | `system`. */
14869
+ updatedBy: string(),
14870
+ /** Coarse — written at most once an hour per ref. `null` = never read. */
14871
+ lastReadAt: number().nullable()
14872
+ });
14873
+ var RefListSchema = array(string().min(1)).max(512);
14874
+ method(object({
14875
+ ref: string().min(1),
14876
+ value: string().min(1)
14877
+ }), object({
14878
+ ref: string(),
14879
+ version: number().int()
14880
+ }), {
14881
+ kind: "mutation",
14882
+ auth: "admin"
14883
+ }), method(object({ refs: RefListSchema }), KeychainResolveResultSchema, { auth: "admin" }), method(object({ refs: RefListSchema }), object({ deleted: number().int() }), {
14884
+ kind: "mutation",
14885
+ auth: "admin"
14886
+ }), method(object({}), array(KeychainSecretMetaSchema).readonly(), { auth: "admin" }), method(object({}), KeychainStateSchema, { auth: "admin" });
14887
+ var KeychainKeySourceSchema = object({
14888
+ kind: _enum([
14889
+ "config-file",
14890
+ "previous-config-file",
14891
+ "platform",
14892
+ "default-file"
14893
+ ]),
14894
+ /** File sources only — a path is not a secret. */
14895
+ path: string().optional(),
14896
+ /**
14897
+ * True when a whole-volume backup of the data directory carries this key
14898
+ * next to the database it protects (the default file). The page warns.
14899
+ */
14900
+ sharesBackupWithDatabase: boolean()
14901
+ });
14902
+ var KeychainStatusSchema = object({
14903
+ keychain: KeychainStateSchema,
14904
+ /** The source of the master key in use; `null` while locked. */
14905
+ keySource: KeychainKeySourceSchema.nullable(),
14906
+ /** The source configured to be primary — differs from `keySource` while a rotation is pending. */
14907
+ configuredSource: KeychainKeySourceSchema,
14908
+ /** Short fingerprint of the master key in use (`HMAC(KEK, label)`, 16 hex). */
14909
+ fingerprint: string().nullable(),
14910
+ activeKeyId: string().nullable(),
14911
+ /**
14912
+ * The keychain unlocked with a NON-primary source: the configured primary
14913
+ * key is not the one that wraps the data key yet. `rotateMasterKey` moves it.
14914
+ */
14915
+ rotationPending: boolean(),
14916
+ /** Wrapped copies of the data key under a previous master key, kept until purged. */
14917
+ retiredWraps: number().int(),
14918
+ recoveryKeyDownloadedAt: number().nullable(),
14919
+ secretCount: number().int()
14920
+ });
14921
+ /**
14922
+ * Whether a stored value is still pointed at by its owner's settings.
14923
+ * `unknown` is a first-class answer: a scope whose blob could not be read is
14924
+ * never reported as an orphan (and never deleted as one).
14925
+ */
14926
+ var KeychainSecretUsageSchema = _enum([
14927
+ "in-use",
14928
+ "orphan",
14929
+ "unknown"
14930
+ ]);
14931
+ var KeychainAdminSecretSchema = KeychainSecretMetaSchema.extend({ usage: KeychainSecretUsageSchema });
14932
+ var KeychainAuditActionSchema = _enum([
14933
+ "put",
14934
+ "delete",
14935
+ "reveal",
14936
+ "rotate-master-key",
14937
+ "purge-retired-keys",
14938
+ "download-recovery-key",
14939
+ "delete-orphans",
14940
+ "reset",
14941
+ "initialize"
14942
+ ]);
14943
+ var KeychainAuditEntrySchema = object({
14944
+ id: string(),
14945
+ at: number(),
14946
+ action: KeychainAuditActionSchema,
14947
+ /** `addon:<id>` | `user:<id>` | `system`. */
14948
+ actor: string(),
14949
+ ref: string().nullable(),
14950
+ detail: string().nullable()
14951
+ });
14952
+ var KEYCHAIN_RESET_CONFIRMATION = "RESET KEYCHAIN";
14953
+ /**
14954
+ * Secrets the HUB itself holds (owner `system`) that no settings form shows:
14955
+ * `jwt-signing-key` — the session signing key (D797). It is always "in use",
14956
+ * never an orphan; it is generated on a fresh hub and replaced only through
14957
+ * {@link keychainAdminCapability.methods.setSystemSecret}.
14958
+ */
14959
+ var SystemHeldSecretNameSchema = _enum(["jwt-signing-key"]);
14960
+ 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({
14961
+ value: string(),
14962
+ version: number().int()
14963
+ }), {
14964
+ kind: "mutation",
14965
+ auth: "admin",
14966
+ caller: "required"
14967
+ }), method(object({
14968
+ name: SystemHeldSecretNameSchema,
14969
+ value: string().min(16)
14970
+ }), object({
14971
+ ref: string(),
14972
+ version: number().int()
14973
+ }), {
14974
+ kind: "mutation",
14975
+ auth: "admin",
14976
+ caller: "required"
14977
+ }), method(object({ refs: array(string().min(1)).max(1e3) }), object({
14978
+ deleted: array(string()).readonly(),
14979
+ kept: array(object({
14980
+ ref: string(),
14981
+ usage: KeychainSecretUsageSchema
14982
+ })).readonly()
14983
+ }), {
14984
+ kind: "mutation",
14985
+ auth: "admin",
14986
+ caller: "required"
14987
+ }), method(object({}), object({
14988
+ fingerprint: string(),
14989
+ keySource: KeychainKeySourceSchema
14990
+ }), {
14991
+ kind: "mutation",
14992
+ auth: "admin",
14993
+ caller: "required"
14994
+ }), method(object({}), object({ purged: number().int() }), {
14995
+ kind: "mutation",
14996
+ auth: "admin",
14997
+ caller: "required"
14998
+ }), method(object({}), object({
14999
+ key: string(),
15000
+ fingerprint: string(),
15001
+ keySource: KeychainKeySourceSchema
15002
+ }), {
15003
+ kind: "mutation",
15004
+ auth: "admin",
15005
+ caller: "required"
15006
+ }), method(object({ confirm: literal(KEYCHAIN_RESET_CONFIRMATION) }), object({
15007
+ archivedCollection: string().nullable(),
15008
+ archived: number().int()
15009
+ }), {
15010
+ kind: "mutation",
15011
+ auth: "admin",
15012
+ caller: "required"
15013
+ });
14139
15014
  method(_void(), object({
14140
15015
  id: string(),
14141
15016
  name: string(),
@@ -15173,7 +16048,11 @@ var DeviceRegisterPayloadSchema = object({
15173
16048
  var DeviceRemovePayloadSchema = object({ deviceId: number() });
15174
16049
  var DevicePersistConfigPayloadSchema = object({
15175
16050
  deviceId: number(),
15176
- data: record(string(), unknown())
16051
+ data: record(string(), unknown()),
16052
+ /** The paths the device's schema declares secret (D783), when the caller
16053
+ * knows them — those values are kept in the keychain, not the blob (D787).
16054
+ * Absent: the paths the device last reported at `registerDevice` apply. */
16055
+ secretConfigPaths: array(string()).optional()
15177
16056
  });
15178
16057
  /** What a migration actually did, per switch. `unreachable` is a first-class
15179
16058
  * answer: a camera that could not be asked is not a camera that was silenced. */
@@ -22160,8 +23039,23 @@ var RetrainMacroClassSchema = _enum([
22160
23039
  ]);
22161
23040
  /** A subject to learn, or a phantom to unlearn (taught by OMISSION). */
22162
23041
  var RetrainAnnotationKindSchema = _enum(["subject", "model_error"]);
22163
- /** Did a human draw this box, or did the assist propose it? */
22164
- var RetrainAnnotationSourceSchema = _enum(["operator", "assist"]);
23042
+ /**
23043
+ * Where a box came from. A machine-sourced box is a DRAFT on the page until
23044
+ * the operator confirms it; once saved it keeps its source as provenance.
23045
+ *
23046
+ * - `operator` — drawn by hand.
23047
+ * - `assist` — proposed by a detector run on the copy (the camera's own
23048
+ * model, or a larger teacher model).
23049
+ * - `pipeline` — the box the live pipeline actually drew on that frame, read
23050
+ * back from the track store (never a re-run).
23051
+ * - `llm` — proposed by a vision-capable LLM profile.
23052
+ */
23053
+ var RetrainAnnotationSourceSchema = _enum([
23054
+ "operator",
23055
+ "assist",
23056
+ "pipeline",
23057
+ "llm"
23058
+ ]);
22165
23059
  /** Normalised `[0,1]` rectangle against the FULL frame — the canonical form. */
22166
23060
  var RetrainBboxSchema = object({
22167
23061
  x: number(),
@@ -22179,7 +23073,8 @@ var RetrainBboxSchema = object({
22179
23073
  */
22180
23074
  var RetrainAnnotationSchema = object({
22181
23075
  id: string(),
22182
- trackId: string(),
23076
+ /** The frame's track. Absent on a recording still, which has none. */
23077
+ trackId: string().optional(),
22183
23078
  deviceId: number(),
22184
23079
  /** The COPY in retrain storage — never the source track's media key. */
22185
23080
  mediaKey: string(),
@@ -22228,13 +23123,47 @@ var RetrainFrameCandidateSchema = object({
22228
23123
  * fail, whatever became of the original. */
22229
23124
  copied: boolean()
22230
23125
  });
23126
+ /**
23127
+ * One box the live pipeline drew on a copied frame — what a correction starts
23128
+ * from. Derived when the frame is listed, from the track store: the subject
23129
+ * box recorded on the source media row when there is one, else the track
23130
+ * position nearest the frame's capture time. Never stored as an annotation
23131
+ * until the operator confirms it.
23132
+ */
23133
+ var RetrainPipelineBoxSchema = object({
23134
+ /** Normalised `[0,1]` against the full frame. */
23135
+ bbox: RetrainBboxSchema,
23136
+ macroClass: RetrainMacroClassSchema,
23137
+ label: string().optional(),
23138
+ subLabel: string().optional(),
23139
+ /** The detection score of the position used, when it was recorded. */
23140
+ score: number().optional(),
23141
+ /** The root model that produced the track, when it was recorded. */
23142
+ modelId: string().optional(),
23143
+ trackId: string(),
23144
+ /** `subject-box`: recorded on this very frame. `position`: the track's
23145
+ * position nearest the capture time, `deltaMs` away. */
23146
+ basis: _enum(["subject-box", "position"]),
23147
+ deltaMs: number()
23148
+ });
23149
+ /**
23150
+ * Where a retrain frame came from: a TRACK's stored media (copy-on-select),
23151
+ * or the RECORDING at an instant — the frame a model saw nothing in has no
23152
+ * track at all.
23153
+ */
23154
+ var RetrainFrameOriginSchema = _enum(["track", "recording"]);
22231
23155
  /** A frame the dataset OWNS: bytes copied at selection time. */
22232
23156
  var RetrainFrameSchema = object({
22233
23157
  frameId: string(),
22234
23158
  deviceId: number(),
22235
- trackId: string(),
22236
- /** Provenance only. It may already point at nothing — that is expected. */
22237
- sourceMediaId: number().int(),
23159
+ origin: RetrainFrameOriginSchema,
23160
+ /** The track it was copied from. Absent on a recording still. */
23161
+ trackId: string().optional(),
23162
+ /** Provenance only. It may already point at nothing — that is expected.
23163
+ * Absent on a recording still. */
23164
+ sourceMediaId: number().int().optional(),
23165
+ /** A recording still: the playhead instant it was taken at. */
23166
+ epochMs: number().optional(),
22238
23167
  sourceKind: MediaFileKindEnum,
22239
23168
  sizeBytes: number().int(),
22240
23169
  width: number().int(),
@@ -22245,7 +23174,12 @@ var RetrainFrameSchema = object({
22245
23174
  /** The operator's "every subject in this frame is boxed". Detector
22246
23175
  * evaluation keeps only complete frames: an unboxed subject would count as
22247
23176
  * a false positive. */
22248
- complete: boolean()
23177
+ complete: boolean(),
23178
+ /** The boxes the pipeline drew on this frame. Present on list answers;
23179
+ * empty when nothing the track store holds can be placed on it. */
23180
+ pipelineBoxes: array(RetrainPipelineBoxSchema).readonly().optional(),
23181
+ /** The named collections this frame belongs to. Present on list answers. */
23182
+ collectionIds: array(string()).readonly().optional()
22249
23183
  });
22250
23184
  /** Why a copy-on-select could not be honoured — named, never a silent skip. */
22251
23185
  var RetrainCopyRefusalSchema = _enum([
@@ -22276,6 +23210,11 @@ var RetrainFrameListSchema = object({
22276
23210
  var RetrainExportFilterSchema = object({
22277
23211
  deviceIds: array(number()).optional(),
22278
23212
  frameIds: array(string()).max(2e4).optional(),
23213
+ /** Only frames in at least one of these named collections. */
23214
+ collectionIds: array(string()).max(200).optional(),
23215
+ /** Exactly the frames of this dataset version (and its completeOnly). An
23216
+ * unknown id selects nothing. */
23217
+ datasetVersionId: string().optional(),
22279
23218
  batchId: string().optional(),
22280
23219
  /** Only frames the operator marked complete (all subjects boxed). */
22281
23220
  completeOnly: boolean().optional()
@@ -22340,6 +23279,170 @@ var RetrainAssistResultSchema = discriminatedUnion("kind", [object({
22340
23279
  reason: string(),
22341
23280
  detail: string().optional()
22342
23281
  })]);
23282
+ /** A named set over the retrain corpus — membership only, it owns no pixels. */
23283
+ var RetrainCollectionSchema = object({
23284
+ id: string(),
23285
+ name: string(),
23286
+ createdAt: number(),
23287
+ frameCount: number().int()
23288
+ });
23289
+ var RetrainCollectionCreateResultSchema = discriminatedUnion("kind", [object({
23290
+ kind: literal("created"),
23291
+ collection: RetrainCollectionSchema
23292
+ }), object({
23293
+ kind: literal("refused"),
23294
+ reason: _enum(["empty-name", "duplicate-name"])
23295
+ })]);
23296
+ var RetrainCollectionRenameResultSchema = discriminatedUnion("kind", [object({
23297
+ kind: literal("renamed"),
23298
+ collection: RetrainCollectionSchema
23299
+ }), object({
23300
+ kind: literal("refused"),
23301
+ reason: _enum([
23302
+ "empty-name",
23303
+ "duplicate-name",
23304
+ "unknown-collection"
23305
+ ])
23306
+ })]);
23307
+ /**
23308
+ * The outcome of adding the frame at a recording instant. Every refusal is
23309
+ * named: `still-unavailable` (not recording, a gap, or an undecodable frame —
23310
+ * `detail` says which), `still-busy` (the recorder is at its decode bound; try
23311
+ * again), `unreadable-image`, `write-failed`, `unknown-collection`.
23312
+ */
23313
+ var AddRetrainFrameFromRecordingResultSchema = discriminatedUnion("kind", [object({
23314
+ kind: literal("added"),
23315
+ collectionId: string(),
23316
+ frame: RetrainFrameSchema,
23317
+ /** The moment was already in the dataset; nothing was decoded. */
23318
+ reused: boolean()
23319
+ }), object({
23320
+ kind: literal("refused"),
23321
+ reason: _enum([
23322
+ "unknown-collection",
23323
+ "still-unavailable",
23324
+ "still-busy",
23325
+ "unreadable-image",
23326
+ "write-failed"
23327
+ ]),
23328
+ detail: string().optional()
23329
+ })]);
23330
+ /** A vision LLM profile the AI assist may use, and where it sends the frame. */
23331
+ var RetrainAssistProfileSchema = object({
23332
+ id: string(),
23333
+ name: string(),
23334
+ model: string(),
23335
+ kind: string(),
23336
+ /** `true` when the frame would leave the house (a cloud vendor, or an
23337
+ * endpoint that is not on the local network). The page confirms each such
23338
+ * run, and the provider refuses one without `allowCloud`. */
23339
+ leavesHouse: boolean()
23340
+ });
23341
+ /** A box the AI assist proposed: a draft, plus the model's own reason. */
23342
+ var RetrainLlmProposalSchema = RetrainAnnotationDraftSchema.extend({ reason: string() });
23343
+ /** What the AI assist said about a box that was already on the canvas. */
23344
+ var RetrainLlmReviewSchema = object({
23345
+ /** The `ref` the page sent the box under. */
23346
+ ref: string(),
23347
+ verdict: _enum([
23348
+ "confirmed",
23349
+ "wrong-class",
23350
+ "not-an-object",
23351
+ "uncertain"
23352
+ ]),
23353
+ suggestedClass: RetrainMacroClassSchema.optional(),
23354
+ reason: string()
23355
+ });
23356
+ /**
23357
+ * The AI assist's answer. `proposed` carries drafts (`source: 'llm'`, the
23358
+ * model and its confidence) and reviews; items the model got wrong (a box off
23359
+ * the frame, an unasked class, an unknown ref) are dropped and counted in
23360
+ * `rejected`. A whole answer that is not the schema is `malformed-answer`.
23361
+ */
23362
+ var RetrainLlmAssistResultSchema = discriminatedUnion("kind", [object({
23363
+ kind: literal("proposed"),
23364
+ profileId: string(),
23365
+ model: string(),
23366
+ /** The frame was sent outside the house for this answer. */
23367
+ leftHouse: boolean(),
23368
+ proposals: array(RetrainLlmProposalSchema).readonly(),
23369
+ reviews: array(RetrainLlmReviewSchema).readonly(),
23370
+ rejected: number().int()
23371
+ }), object({
23372
+ kind: literal("refused"),
23373
+ reason: _enum([
23374
+ "unknown-frame",
23375
+ "unreadable-frame",
23376
+ "unknown-profile",
23377
+ "profile-disabled",
23378
+ "no-vision",
23379
+ "cloud-not-confirmed",
23380
+ "llm-error",
23381
+ "malformed-answer"
23382
+ ]),
23383
+ detail: string().optional()
23384
+ })]);
23385
+ /** What a dataset version is cut from. Every field narrows. */
23386
+ var RetrainDatasetSelectionSchema = object({
23387
+ deviceIds: array(number()).readonly().optional(),
23388
+ collectionIds: array(string()).max(200).readonly().optional(),
23389
+ frameIds: array(string()).max(2e4).readonly().optional()
23390
+ });
23391
+ /** The counts a dataset is judged by. */
23392
+ var RetrainDatasetStatsSchema = object({
23393
+ frames: number().int(),
23394
+ completeFrames: number().int(),
23395
+ /** `completeFrames / frames`, 0..1. */
23396
+ completeness: number(),
23397
+ /** Boxes to learn (model errors excluded). */
23398
+ subjects: number().int(),
23399
+ modelErrors: number().int(),
23400
+ /** Complete frames with no subject. */
23401
+ hardNegatives: number().int(),
23402
+ /** Subjects per class × camera × day/night. */
23403
+ cells: array(object({
23404
+ macroClass: string(),
23405
+ deviceId: number(),
23406
+ lighting: _enum([
23407
+ "day",
23408
+ "night",
23409
+ "unknown"
23410
+ ]),
23411
+ subjects: number().int(),
23412
+ frames: number().int()
23413
+ })).readonly(),
23414
+ cameras: array(object({
23415
+ deviceId: number(),
23416
+ frames: number().int(),
23417
+ completeFrames: number().int()
23418
+ })).readonly()
23419
+ });
23420
+ /** An immutable dataset version, without its frame list. */
23421
+ var RetrainDatasetVersionSchema = object({
23422
+ id: string(),
23423
+ name: string(),
23424
+ createdAt: number(),
23425
+ selection: RetrainDatasetSelectionSchema,
23426
+ layout: RetrainExportLayoutSchema,
23427
+ completeOnly: boolean(),
23428
+ frameCount: number().int(),
23429
+ /** sha256 of what the frames taught when the version was frozen. */
23430
+ annotationHash: string(),
23431
+ /** The export manifest schema the version was cut under. */
23432
+ manifestSchema: string(),
23433
+ stats: RetrainDatasetStatsSchema
23434
+ });
23435
+ var CreateRetrainDatasetVersionResultSchema = discriminatedUnion("kind", [object({
23436
+ kind: literal("created"),
23437
+ version: RetrainDatasetVersionSchema
23438
+ }), object({
23439
+ kind: literal("refused"),
23440
+ reason: _enum([
23441
+ "empty-name",
23442
+ "duplicate-name",
23443
+ "no-frames"
23444
+ ])
23445
+ })]);
22343
23446
  /** The outcome of a lifecycle move owned by the retrain page. */
22344
23447
  var RetrainTransitionResultSchema = object({
22345
23448
  trackId: string(),
@@ -23057,7 +24160,7 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
23057
24160
  auth: "admin"
23058
24161
  }), method(object({
23059
24162
  deviceId: number(),
23060
- trackId: string(),
24163
+ trackId: string().optional(),
23061
24164
  frameId: string()
23062
24165
  }), object({
23063
24166
  removed: boolean(),
@@ -23074,7 +24177,8 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
23074
24177
  auth: "admin"
23075
24178
  }), method(object({
23076
24179
  deviceId: number(),
23077
- trackId: string(),
24180
+ /** The frame's track, when it has one — checked against the frame. */
24181
+ trackId: string().optional(),
23078
24182
  frameId: string(),
23079
24183
  subject: RetrainAssistSubjectSchema,
23080
24184
  /** Which node runs it. Absent ⇒ wherever an unowned call lands. */
@@ -23082,12 +24186,16 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
23082
24186
  }), RetrainAssistResultSchema, {
23083
24187
  kind: "mutation",
23084
24188
  auth: "admin"
23085
- }), method(object({ trackId: string() }), array(RetrainAnnotationSchema).readonly(), {
24189
+ }), method(object({
24190
+ trackId: string().optional(),
24191
+ frameIds: array(string()).max(2e3).optional()
24192
+ }), array(RetrainAnnotationSchema).readonly(), {
23086
24193
  kind: "query",
23087
24194
  auth: "admin"
23088
24195
  }), method(object({
23089
24196
  deviceId: number(),
23090
- trackId: string(),
24197
+ /** The frame's track, when it has one — checked against the frame. */
24198
+ trackId: string().optional(),
23091
24199
  frameId: string(),
23092
24200
  annotations: array(RetrainAnnotationDraftSchema)
23093
24201
  }), array(RetrainAnnotationSchema).readonly(), {
@@ -23110,7 +24218,7 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
23110
24218
  auth: "admin"
23111
24219
  }), method(object({
23112
24220
  deviceId: number(),
23113
- trackId: string(),
24221
+ trackId: string().optional(),
23114
24222
  frameId: string(),
23115
24223
  complete: boolean()
23116
24224
  }), RetrainFrameSchema, {
@@ -23124,6 +24232,104 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
23124
24232
  kind: "mutation",
23125
24233
  auth: "admin",
23126
24234
  timeoutMs: 60 * 6e4
24235
+ }), method(object({
24236
+ selection: RetrainDatasetSelectionSchema,
24237
+ completeOnly: boolean().optional()
24238
+ }), RetrainDatasetStatsSchema, {
24239
+ kind: "query",
24240
+ auth: "admin"
24241
+ }), method(object({
24242
+ name: string().max(120),
24243
+ selection: RetrainDatasetSelectionSchema,
24244
+ layout: RetrainExportLayoutSchema,
24245
+ completeOnly: boolean()
24246
+ }), CreateRetrainDatasetVersionResultSchema, {
24247
+ kind: "mutation",
24248
+ auth: "admin",
24249
+ timeoutMs: 12e4
24250
+ }), method(object({}), array(RetrainDatasetVersionSchema).readonly(), {
24251
+ kind: "query",
24252
+ auth: "admin"
24253
+ }), method(object({ id: string() }), object({ deleted: boolean() }), {
24254
+ kind: "mutation",
24255
+ auth: "admin"
24256
+ }), method(object({ id: string() }), object({
24257
+ found: boolean(),
24258
+ annotationHash: string(),
24259
+ matches: boolean(),
24260
+ missingFrames: number().int()
24261
+ }), {
24262
+ kind: "query",
24263
+ auth: "admin",
24264
+ timeoutMs: 12e4
24265
+ }), method(object({}), array(RetrainAssistProfileSchema).readonly(), {
24266
+ kind: "query",
24267
+ auth: "admin"
24268
+ }), method(object({
24269
+ deviceId: number(),
24270
+ trackId: string().optional(),
24271
+ frameId: string(),
24272
+ profileId: string(),
24273
+ classes: array(RetrainMacroClassSchema).min(1),
24274
+ boxes: array(object({
24275
+ ref: string(),
24276
+ bbox: RetrainBboxSchema,
24277
+ macroClass: RetrainMacroClassSchema,
24278
+ label: string().optional()
24279
+ })).max(50),
24280
+ allowCloud: boolean()
24281
+ }), RetrainLlmAssistResultSchema, {
24282
+ kind: "mutation",
24283
+ auth: "admin",
24284
+ timeoutMs: 18e4
24285
+ }), method(object({ name: string().max(120) }), RetrainCollectionCreateResultSchema, {
24286
+ kind: "mutation",
24287
+ auth: "admin"
24288
+ }), method(object({}), array(RetrainCollectionSchema).readonly(), {
24289
+ kind: "query",
24290
+ auth: "admin"
24291
+ }), method(object({
24292
+ id: string(),
24293
+ name: string().max(120)
24294
+ }), RetrainCollectionRenameResultSchema, {
24295
+ kind: "mutation",
24296
+ auth: "admin"
24297
+ }), method(object({ id: string() }), object({
24298
+ deleted: boolean(),
24299
+ removedFrames: number().int()
24300
+ }), {
24301
+ kind: "mutation",
24302
+ auth: "admin"
24303
+ }), method(object({
24304
+ collectionId: string(),
24305
+ deviceId: number(),
24306
+ epochMs: number()
24307
+ }), AddRetrainFrameFromRecordingResultSchema, {
24308
+ kind: "mutation",
24309
+ auth: "admin",
24310
+ timeoutMs: 6e4
24311
+ }), method(object({
24312
+ collectionId: string(),
24313
+ frameIds: array(string()).min(1).max(500)
24314
+ }), object({
24315
+ added: number().int(),
24316
+ alreadyMember: number().int(),
24317
+ unknownFrameIds: array(string()).readonly()
24318
+ }), {
24319
+ kind: "mutation",
24320
+ auth: "admin"
24321
+ }), method(object({
24322
+ collectionId: string(),
24323
+ frameId: string()
24324
+ }), object({
24325
+ removed: boolean(),
24326
+ deletedFrame: boolean()
24327
+ }), {
24328
+ kind: "mutation",
24329
+ auth: "admin"
24330
+ }), method(object({ collectionId: string() }), array(RetrainFrameSchema).readonly(), {
24331
+ kind: "query",
24332
+ auth: "admin"
23127
24333
  }), method(object({
23128
24334
  /** Which of the three event tables owns the row. */
23129
24335
  ownerType: EventOwnerTypeSchema,
@@ -23747,13 +24953,31 @@ var RecommendationReasonSchema = discriminatedUnion("kind", [
23747
24953
  object({
23748
24954
  kind: literal("no-family-build"),
23749
24955
  format: ModelFormatSchema$1
24956
+ }),
24957
+ object({
24958
+ kind: literal("kept-custom-pin"),
24959
+ modelId: string(),
24960
+ deviceKey: string()
23750
24961
  })
23751
24962
  ]);
24963
+ /** Why a device is left exactly as it is, whatever the plan would pick (D786). */
24964
+ var KeptReasonSchema = _enum(["custom-pin"]);
24965
+ /**
24966
+ * Where a choice's latency came from (D791): this node's own benchmark
24967
+ * result, or the hardware-class table. Measured on the node beats the table.
24968
+ */
24969
+ var LatencySourceSchema = discriminatedUnion("kind", [object({ kind: literal("table") }), object({
24970
+ kind: literal("node-benchmark"),
24971
+ resultId: string(),
24972
+ measuredAtMs: number()
24973
+ })]);
23752
24974
  var DeviceModelChoiceSchema = object({
23753
24975
  modelId: string(),
23754
24976
  p50Ms: number(),
23755
24977
  fps: number(),
23756
24978
  measured: boolean(),
24979
+ /** Absent on a plan from before D791 — read as the table. */
24980
+ source: LatencySourceSchema.optional(),
23757
24981
  /** Parallel sessions at the camera rate with the headroom kept free: ⌊fps × (1 − headroom) / camera fps⌋. */
23758
24982
  capacitySessions: number(),
23759
24983
  personRecall: number()
@@ -23764,6 +24988,8 @@ var DeviceRecommendationSchema = object({
23764
24988
  enabled: boolean(),
23765
24989
  available: boolean(),
23766
24990
  chosen: DeviceModelChoiceSchema.nullable(),
24991
+ /** Present when the device is kept as is: Apply writes nothing on it. */
24992
+ kept: KeptReasonSchema.optional(),
23767
24993
  reasons: array(RecommendationReasonSchema).readonly()
23768
24994
  });
23769
24995
  var NodeRecommendationSchema = object({
@@ -23817,6 +25043,17 @@ var AutoTuneWarningSchema = discriminatedUnion("kind", [
23817
25043
  kind: literal("coral-enabled"),
23818
25044
  nodeId: string(),
23819
25045
  deviceKey: string()
25046
+ }),
25047
+ object({
25048
+ kind: literal("custom-pin-kept"),
25049
+ nodeId: string(),
25050
+ deviceKey: string().nullable(),
25051
+ deviceId: number().nullable(),
25052
+ modelId: string()
25053
+ }),
25054
+ object({
25055
+ kind: literal("custom-registry-unreadable"),
25056
+ error: string()
23820
25057
  })
23821
25058
  ]);
23822
25059
  var AutoTuneOptionsSchema = object({
@@ -23995,13 +25232,14 @@ var SuggestSharesResultSchema = object({
23995
25232
  nodes: array(SuggestedNodeShareSchema).readonly()
23996
25233
  });
23997
25234
  /**
23998
- * Where the node and device shares come from (D750, D755).
23999
- * - `hardware` (default) — computed by the system from each node's static
24000
- * capacity (its accelerators at their Auto tune models, from the measured
24001
- * latency table), recomputed whenever a node or device joins, leaves, is
24002
- * switched on or off, or changes model. No load input.
24003
- * - `benchmark` — the same, from each node's measured capacity (node
24004
- * benchmark results); a node without results falls back to `hardware`.
25235
+ * Where the node and device shares come from (D750, D755, D791).
25236
+ * - `benchmark` (default since D791) — each node's capacity as its own node
25237
+ * benchmark measured it; a node without fresh results is sized from
25238
+ * `hardware` and says so. Measured on the node beats the table.
25239
+ * - `hardware` — computed from each node's static capacity only (its
25240
+ * accelerators at their Auto tune models, from the latency table).
25241
+ * Both are recomputed whenever a node or device joins, leaves, is switched
25242
+ * on or off, changes model, or a benchmark result is written. No load input.
24005
25243
  * - `manual` — the operator's stored sliders.
24006
25244
  * Either way a node or device that cannot take sessions gives its share to
24007
25245
  * the others in proportion; the stored values are never rewritten for that.
@@ -24050,6 +25288,362 @@ var EffectiveSharesSchema = object({
24050
25288
  nodeWeights: record(string(), number()),
24051
25289
  deviceWeights: record(string(), record(string(), number()))
24052
25290
  });
25291
+ /**
25292
+ * Wire shapes of the node benchmark (D791): the operator's plan, the
25293
+ * preflight the confirmation shows, the run the orchestrator owns, what the
25294
+ * measuring runner reports, and the result rows Auto tune and the automatic
25295
+ * shares read.
25296
+ *
25297
+ * ONE node at a time, owned by the pipeline orchestrator. While a run is
25298
+ * active the cluster is in BENCHMARK MODE for that node: it is not a
25299
+ * detection candidate, camera pins naming it are ignored so its sessions move
25300
+ * elsewhere, and both come back when the mode ends — after a crash or a hub
25301
+ * restart too (a persisted manifest, reconciled against the registry).
25302
+ *
25303
+ * Two measurements, both on the node, driven by its own runner (frames never
25304
+ * cross a process at frame rate, D9):
25305
+ * - `device` — one accelerator × one candidate detector, root only, open
25306
+ * loop: how many streams at the camera rate it carries inside the frame
25307
+ * interval;
25308
+ * - `pipeline` — the chosen detector plus the operator's detail steps
25309
+ * (faces, plates, classifiers, CLIP…), on varied frames from the bench
25310
+ * clip: how many parallel sessions the node carries before latency, drops,
25311
+ * CPU, RAM or the event loop give out.
25312
+ */
25313
+ /** Defaults and bounds, one place. */
25314
+ var NODE_BENCHMARK_DEFAULTS = {
25315
+ fpsPerStream: 10,
25316
+ budgetMinutes: 45,
25317
+ minBudgetMinutes: 10,
25318
+ maxBudgetMinutes: 120,
25319
+ /** A result older than this no longer beats the table. */
25320
+ staleAfterDays: 30,
25321
+ /** Warm-in per ramp step (not accounted). */
25322
+ settleSec: 5,
25323
+ /** Accounted window per ramp step. */
25324
+ measureSec: 20,
25325
+ /** Longest the drain may take before the run is refused. */
25326
+ drainTimeoutSec: 120,
25327
+ /** Candidate models per device in one run. */
25328
+ maxModelsPerDevice: 6
25329
+ };
25330
+ /** The two measurements a run can make. */
25331
+ var NodeBenchmarkPhaseSchema = _enum(["device", "pipeline"]);
25332
+ var NodeBenchmarkDevicePlanSchema = object({
25333
+ /** `<backend>:<device>` — `openvino:npu`, `coreml:all`, `cpu`. */
25334
+ deviceKey: string().min(1),
25335
+ /**
25336
+ * Root detector candidates for the `device` measurement, in the order
25337
+ * measured. The FIRST is the one the `pipeline` measurement runs.
25338
+ */
25339
+ modelIds: array(string().min(1)).min(1).max(NODE_BENCHMARK_DEFAULTS.maxModelsPerDevice)
25340
+ });
25341
+ /** What the operator confirmed. */
25342
+ var NodeBenchmarkPlanSchema = object({
25343
+ nodeId: string().min(1),
25344
+ devices: array(NodeBenchmarkDevicePlanSchema).min(1),
25345
+ /** Which measurements run. At least one. */
25346
+ phases: array(NodeBenchmarkPhaseSchema).min(1).default(["device", "pipeline"]),
25347
+ /**
25348
+ * Detail steps (catalog step ids under the root: faces, plates,
25349
+ * classifiers, CLIP…) the `pipeline` measurement enables. The root
25350
+ * detector always runs.
25351
+ */
25352
+ steps: array(string().min(1)).default([]),
25353
+ /** Offered rate of one stream / session. */
25354
+ fpsPerStream: number().int().min(1).max(30).default(NODE_BENCHMARK_DEFAULTS.fpsPerStream),
25355
+ /** Hard deadline: the mode ends and the cluster is restored when it passes. */
25356
+ budgetMinutes: number().int().min(NODE_BENCHMARK_DEFAULTS.minBudgetMinutes).max(NODE_BENCHMARK_DEFAULTS.maxBudgetMinutes).default(NODE_BENCHMARK_DEFAULTS.budgetMinutes),
25357
+ /** Keep the models the run downloaded (default: delete what was not installed before). */
25358
+ keepDownloadedModels: boolean().default(false),
25359
+ /** Start although the other nodes' capacity does not cover the sessions running now. */
25360
+ acceptInsufficientHeadroom: boolean().default(false)
25361
+ });
25362
+ var NodeBenchmarkRefusalSchema = object({
25363
+ kind: _enum([
25364
+ "benchmark-active",
25365
+ "node-offline",
25366
+ "unknown-device",
25367
+ "no-phase",
25368
+ "insufficient-headroom"
25369
+ ]),
25370
+ detail: string(),
25371
+ overridable: boolean()
25372
+ });
25373
+ /** A camera whose detection leaves the node for the run. */
25374
+ var NodeBenchmarkMovingCameraSchema = object({
25375
+ deviceId: number(),
25376
+ /** Placed on the node now (a standing attach or a running session). */
25377
+ placedOnNode: boolean(),
25378
+ /** A node pin naming this node, ignored for the run. */
25379
+ pinnedToNode: boolean()
25380
+ });
25381
+ /** A camera that cannot leave: no other node can obtain its frames. */
25382
+ var NodeBenchmarkStayingCameraSchema = object({
25383
+ deviceId: number(),
25384
+ reason: literal("only-frame-source")
25385
+ });
25386
+ var NodeBenchmarkPreflightSchema = object({
25387
+ nodeId: string(),
25388
+ online: boolean(),
25389
+ moving: array(NodeBenchmarkMovingCameraSchema).readonly(),
25390
+ /** Keep running on the node during the run; the result is flagged contaminated. */
25391
+ staying: array(NodeBenchmarkStayingCameraSchema).readonly(),
25392
+ estimatedDurationMs: number(),
25393
+ /** The run ends and the cluster is restored at the latest after this long. */
25394
+ budgetMs: number(),
25395
+ phases: array(NodeBenchmarkPhaseSchema).readonly(),
25396
+ steps: array(string()).readonly(),
25397
+ devices: array(NodeBenchmarkDevicePlanSchema).readonly(),
25398
+ /** Parallel sessions the cluster runs now, and what the other nodes can carry. */
25399
+ headroom: object({
25400
+ sessionsNow: number(),
25401
+ otherNodesCapacitySessions: number().nullable()
25402
+ }),
25403
+ refusals: array(NodeBenchmarkRefusalSchema).readonly(),
25404
+ canStart: boolean()
25405
+ });
25406
+ /** Where the measuring runner is. */
25407
+ var NodeBenchProgressSchema = object({
25408
+ phase: _enum([
25409
+ "preparing",
25410
+ "device",
25411
+ "pipeline",
25412
+ "cleanup"
25413
+ ]),
25414
+ deviceKey: string().nullable(),
25415
+ modelId: string().nullable(),
25416
+ /** Streams (device) or sessions (pipeline) of the step running now. */
25417
+ load: number().nullable(),
25418
+ cellsDone: number(),
25419
+ cellsTotal: number(),
25420
+ message: string()
25421
+ });
25422
+ /** What limited a ramp. `none` = the ramp ran out of steps still passing. */
25423
+ var NodeBenchLimitSchema = _enum([
25424
+ "p95",
25425
+ "drops",
25426
+ "errors",
25427
+ "stall",
25428
+ "cpu",
25429
+ "ram",
25430
+ "none"
25431
+ ]);
25432
+ var NodeBenchRampStepSchema = object({
25433
+ load: number(),
25434
+ pass: boolean(),
25435
+ p95Ms: number(),
25436
+ dropRatio: number(),
25437
+ /** Completed frames per second over the accounted window. */
25438
+ fps: number(),
25439
+ cpuPct: number().nullable(),
25440
+ ramFreePct: number().nullable(),
25441
+ failReasons: array(string()).readonly()
25442
+ });
25443
+ var NodeBenchCellSchema = discriminatedUnion("phase", [object({
25444
+ phase: literal("device"),
25445
+ deviceKey: string(),
25446
+ modelId: string(),
25447
+ /** Single-stream latency (the K = 1 step). */
25448
+ p50Ms: number(),
25449
+ p95Ms: number(),
25450
+ p99Ms: number(),
25451
+ /** Frames per second sustained at the last passing step. */
25452
+ fps: number(),
25453
+ /** Streams at the camera rate the device carried inside the frame interval; 0 = not even one. */
25454
+ kMax: number(),
25455
+ limitedBy: NodeBenchLimitSchema,
25456
+ /** First call (model load + warm-up). */
25457
+ warmupMs: number(),
25458
+ ramp: array(NodeBenchRampStepSchema).readonly()
25459
+ }), object({
25460
+ phase: literal("pipeline"),
25461
+ deviceKey: string(),
25462
+ modelId: string(),
25463
+ steps: array(string()).readonly(),
25464
+ /** Parallel sessions at the camera rate the node carried; 0 = not even one. */
25465
+ maxSessions: number(),
25466
+ limitedBy: NodeBenchLimitSchema,
25467
+ /** Detail steps that produced at least one result on the clip — a step that never fired measured nothing. */
25468
+ stepsFired: array(string()).readonly(),
25469
+ warmupMs: number(),
25470
+ ramp: array(NodeBenchRampStepSchema).readonly()
25471
+ })]);
25472
+ /**
25473
+ * What a result was measured ON. A result whose fingerprint no longer matches
25474
+ * the node no longer beats the table.
25475
+ */
25476
+ var NodeBenchFingerprintSchema = object({
25477
+ pipelineVersion: string().nullable(),
25478
+ cpuModel: string().nullable(),
25479
+ ramGb: number().nullable(),
25480
+ os: string().nullable(),
25481
+ /** Per device: the pool the cells ran on (runtime + tuning). */
25482
+ pools: record(string(), object({
25483
+ runtime: string(),
25484
+ numWorkers: number(),
25485
+ concurrency: number(),
25486
+ batchMode: string()
25487
+ })).default({})
25488
+ });
25489
+ /** The frames the run used. */
25490
+ var NodeBenchClipSchema = object({
25491
+ /** `camstack-bench-v1` or `reference-images` (the fallback when the clip is not reachable). */
25492
+ id: string(),
25493
+ revision: string().nullable(),
25494
+ frames: number(),
25495
+ width: number(),
25496
+ height: number()
25497
+ });
25498
+ var NodeBenchRunnerInputSchema = object({
25499
+ runId: string().min(1),
25500
+ devices: array(NodeBenchmarkDevicePlanSchema).min(1),
25501
+ phases: array(NodeBenchmarkPhaseSchema).min(1),
25502
+ /** The full detail step tree root for the `pipeline` measurement is built on the node from these ids. */
25503
+ steps: array(string()).default([]),
25504
+ fpsPerStream: number().int().min(1).max(30),
25505
+ /** The runner stops on its own past this instant, whatever the hub does. */
25506
+ deadlineAtMs: number(),
25507
+ settleSec: number().min(0).max(60).default(NODE_BENCHMARK_DEFAULTS.settleSec),
25508
+ measureSec: number().min(2).max(300).default(NODE_BENCHMARK_DEFAULTS.measureSec),
25509
+ keepDownloadedModels: boolean().default(false)
25510
+ });
25511
+ var NodeBenchRunnerStateSchema = _enum([
25512
+ "running",
25513
+ "done",
25514
+ "failed",
25515
+ "aborted"
25516
+ ]);
25517
+ var NodeBenchRunnerStatusSchema = object({
25518
+ runId: string(),
25519
+ nodeId: string(),
25520
+ state: NodeBenchRunnerStateSchema,
25521
+ progress: NodeBenchProgressSchema.nullable(),
25522
+ /** Every finished cell so far — a run stopped half way keeps what it measured. */
25523
+ cells: array(NodeBenchCellSchema).readonly(),
25524
+ fingerprint: NodeBenchFingerprintSchema.nullable(),
25525
+ clip: NodeBenchClipSchema.nullable(),
25526
+ /** Cameras seen running on the node during the run (they share its pools). */
25527
+ activeCameraIds: array(number()).readonly(),
25528
+ /** Models the run downloaded and then deleted (not installed before). */
25529
+ deletedModels: array(string()).readonly(),
25530
+ error: string().nullable(),
25531
+ startedAtMs: number(),
25532
+ finishedAtMs: number().nullable()
25533
+ });
25534
+ var NodeBenchmarkStateSchema = _enum([
25535
+ "draining",
25536
+ "measuring",
25537
+ "restoring",
25538
+ "done",
25539
+ "failed",
25540
+ "aborted"
25541
+ ]);
25542
+ /** Why a run ended. */
25543
+ var NodeBenchmarkEndReasonSchema = _enum([
25544
+ "completed",
25545
+ "operator-abort",
25546
+ "deadline",
25547
+ "node-lost",
25548
+ "runner-lost",
25549
+ "hub-restart",
25550
+ "drain-timeout",
25551
+ "failed"
25552
+ ]);
25553
+ var NodeBenchmarkRunSchema = object({
25554
+ runId: string(),
25555
+ nodeId: string(),
25556
+ state: NodeBenchmarkStateSchema,
25557
+ plan: NodeBenchmarkPlanSchema,
25558
+ startedAtMs: number(),
25559
+ deadlineAtMs: number(),
25560
+ finishedAtMs: number().nullable(),
25561
+ endReason: NodeBenchmarkEndReasonSchema.nullable(),
25562
+ error: string().nullable(),
25563
+ /** Cameras moved off the node for the run. */
25564
+ moved: array(number()).readonly(),
25565
+ /** Cameras that stayed (their only frame source is the node). */
25566
+ staying: array(number()).readonly(),
25567
+ /** Something else ran on the node's pools during the run. */
25568
+ contaminated: boolean(),
25569
+ progress: NodeBenchProgressSchema.nullable(),
25570
+ resultIds: array(string()).readonly()
25571
+ });
25572
+ /** `getNodeBenchmarkStatus`: the active run (or the last one), and whether benchmark mode is on. */
25573
+ var NodeBenchmarkStatusSchema = object({
25574
+ /** The node the cluster is in benchmark mode for; null = none. */
25575
+ modeNodeId: string().nullable(),
25576
+ run: NodeBenchmarkRunSchema.nullable()
25577
+ });
25578
+ /**
25579
+ * One stored measurement — the only authority Auto tune and the automatic
25580
+ * shares read measured capacity from. Written by the orchestrator when a run
25581
+ * ends, never by anyone else.
25582
+ */
25583
+ var NodeBenchmarkResultSchema = object({
25584
+ id: string(),
25585
+ runId: string(),
25586
+ nodeId: string(),
25587
+ cell: NodeBenchCellSchema,
25588
+ fpsPerStream: number(),
25589
+ fingerprint: NodeBenchFingerprintSchema.nullable(),
25590
+ clip: NodeBenchClipSchema.nullable(),
25591
+ /** Other work shared the node's pools (a camera that could not move, or the hub's own duties). */
25592
+ contaminated: boolean(),
25593
+ stayingCameras: array(number()).readonly(),
25594
+ /** The run ended early; the cell itself completed. */
25595
+ partialRun: boolean(),
25596
+ measuredAtMs: number()
25597
+ });
25598
+ var ListNodeBenchmarkResultsInputSchema = object({
25599
+ nodeId: string().optional(),
25600
+ deviceKey: string().optional()
25601
+ });
25602
+ /** A result with its standing today: does it still beat the table? */
25603
+ var NodeBenchmarkResultViewSchema = NodeBenchmarkResultSchema.extend({
25604
+ /** `fresh` beats the table; `stale` falls back to it; `superseded` = a newer row covers the same cell. */
25605
+ standing: _enum([
25606
+ "fresh",
25607
+ "stale",
25608
+ "superseded"
25609
+ ]),
25610
+ staleWhy: _enum([
25611
+ "age",
25612
+ "runtime",
25613
+ "pool-tuning"
25614
+ ]).nullable()
25615
+ });
25616
+ object({
25617
+ runId: string(),
25618
+ nodeId: string(),
25619
+ startedAtMs: number(),
25620
+ deadlineAtMs: number(),
25621
+ plan: NodeBenchmarkPlanSchema,
25622
+ moved: array(number()).readonly(),
25623
+ staying: array(number()).readonly()
25624
+ });
25625
+ /** Candidate detectors per device, for the plan editor. */
25626
+ var NodeBenchmarkCandidatesSchema = object({
25627
+ nodeId: string(),
25628
+ reachable: boolean(),
25629
+ devices: array(object({
25630
+ deviceKey: string(),
25631
+ enabled: boolean(),
25632
+ available: boolean(),
25633
+ /** Ordered: what Auto tune would pick first, then the rest of the family by accuracy. */
25634
+ suggested: array(string()).readonly(),
25635
+ /** Every root detector the device has a build for. */
25636
+ all: array(string()).readonly(),
25637
+ /** The model the device runs now, when pinned. */
25638
+ currentModelId: string().nullable()
25639
+ })).readonly(),
25640
+ /** Detail steps the node's catalog offers under the root (for the `pipeline` measurement). */
25641
+ steps: array(object({
25642
+ id: string(),
25643
+ name: string(),
25644
+ slot: string()
25645
+ })).readonly()
25646
+ });
24053
25647
  object({
24054
25648
  activeCameras: number(),
24055
25649
  throttledCameras: number(),
@@ -25138,7 +26732,16 @@ method(RunnerCameraConfigSchema, object({ success: literal(true) }), { kind: "mu
25138
26732
  }), ParkedTrackFrameSchema.nullable()), method(object({
25139
26733
  deviceId: number(),
25140
26734
  trackId: string()
25141
- }), object({ released: number().int().nonnegative() }), { kind: "mutation" });
26735
+ }), object({ released: number().int().nonnegative() }), { kind: "mutation" }), method(NodeBenchRunnerInputSchema, object({
26736
+ accepted: literal(true),
26737
+ runId: string()
26738
+ }), {
26739
+ kind: "mutation",
26740
+ auth: "admin"
26741
+ }), method(object({ runId: string() }), NodeBenchRunnerStatusSchema.nullable(), { auth: "admin" }), method(object({ runId: string() }), object({ aborted: boolean() }), {
26742
+ kind: "mutation",
26743
+ auth: "admin"
26744
+ });
25142
26745
  var CameraPipelineConfigSchema = object({
25143
26746
  engine: PipelineEngineChoiceSchema.optional(),
25144
26747
  steps: array(PipelineStepInputSchema).readonly(),
@@ -25777,6 +27380,21 @@ method(object({
25777
27380
  }), method(PlacementStatsInputSchema, PlacementStatsSchema, { auth: "admin" }), method(SuggestSharesInputSchema, SuggestSharesResultSchema, { auth: "admin" }), method(_void(), EffectiveSharesSchema, { auth: "admin" }), method(SetShareSourceInputSchema, object({ success: literal(true) }), {
25778
27381
  kind: "mutation",
25779
27382
  auth: "admin"
27383
+ }), method(NodeBenchmarkPlanSchema, NodeBenchmarkPreflightSchema, { auth: "admin" }), method(NodeBenchmarkPlanSchema, discriminatedUnion("kind", [object({
27384
+ kind: literal("started"),
27385
+ runId: string()
27386
+ }), object({
27387
+ kind: literal("refused"),
27388
+ preflight: NodeBenchmarkPreflightSchema
27389
+ })]), {
27390
+ kind: "mutation",
27391
+ auth: "admin"
27392
+ }), method(_void(), NodeBenchmarkStatusSchema, { auth: "admin" }), method(object({ runId: string() }), object({ aborted: boolean() }), {
27393
+ kind: "mutation",
27394
+ auth: "admin"
27395
+ }), method(object({ nodeId: string() }), NodeBenchmarkCandidatesSchema, { auth: "admin" }), method(ListNodeBenchmarkResultsInputSchema, array(NodeBenchmarkResultViewSchema).readonly(), { auth: "admin" }), method(object({ id: string() }), object({ deleted: boolean() }), {
27396
+ kind: "mutation",
27397
+ auth: "admin"
25780
27398
  }), method(object({ deviceId: number() }), CameraPipelineSettingsSchema.nullable()), method(object({
25781
27399
  deviceId: number(),
25782
27400
  addonId: string(),
@@ -30893,6 +32511,9 @@ var CreateIntegrationInputSchema = object({
30893
32511
  enabled: boolean().optional(),
30894
32512
  info: record(string(), unknown()).optional(),
30895
32513
  settings: record(string(), unknown()).optional(),
32514
+ /** Keys of `settings` the form's schema declares secret (by type) — kept in
32515
+ * the keychain, not the table (D787). */
32516
+ secretKeys: array(string()).optional(),
30896
32517
  skipRestart: boolean().optional()
30897
32518
  });
30898
32519
  var UpdateIntegrationInputSchema = object({
@@ -30916,7 +32537,9 @@ method(_void(), array(IntegrationWithStateSchema)), method(object({ id: string()
30916
32537
  auth: "admin"
30917
32538
  }), method(object({ id: string() }), record(string(), unknown()), { auth: "admin" }), method(object({
30918
32539
  id: string(),
30919
- settings: record(string(), unknown())
32540
+ settings: record(string(), unknown()),
32541
+ /** Keys the form's schema declares secret (by type) — keychain-stored (D787). */
32542
+ secretKeys: array(string()).optional()
30920
32543
  }), object({ success: boolean() }), {
30921
32544
  kind: "mutation",
30922
32545
  auth: "admin"
@@ -39621,6 +41244,96 @@ Object.freeze({
39621
41244
  addonId: null,
39622
41245
  access: "create"
39623
41246
  },
41247
+ "keychain.delete": {
41248
+ capName: "keychain",
41249
+ capScope: "system",
41250
+ addonId: null,
41251
+ access: "delete"
41252
+ },
41253
+ "keychain.getState": {
41254
+ capName: "keychain",
41255
+ capScope: "system",
41256
+ addonId: null,
41257
+ access: "view"
41258
+ },
41259
+ "keychain.listMeta": {
41260
+ capName: "keychain",
41261
+ capScope: "system",
41262
+ addonId: null,
41263
+ access: "view"
41264
+ },
41265
+ "keychain.put": {
41266
+ capName: "keychain",
41267
+ capScope: "system",
41268
+ addonId: null,
41269
+ access: "create"
41270
+ },
41271
+ "keychain.resolve": {
41272
+ capName: "keychain",
41273
+ capScope: "system",
41274
+ addonId: null,
41275
+ access: "view"
41276
+ },
41277
+ "keychainAdmin.deleteOrphans": {
41278
+ capName: "keychain-admin",
41279
+ capScope: "system",
41280
+ addonId: null,
41281
+ access: "delete"
41282
+ },
41283
+ "keychainAdmin.downloadRecoveryKey": {
41284
+ capName: "keychain-admin",
41285
+ capScope: "system",
41286
+ addonId: null,
41287
+ access: "create"
41288
+ },
41289
+ "keychainAdmin.listAudit": {
41290
+ capName: "keychain-admin",
41291
+ capScope: "system",
41292
+ addonId: null,
41293
+ access: "view"
41294
+ },
41295
+ "keychainAdmin.listSecrets": {
41296
+ capName: "keychain-admin",
41297
+ capScope: "system",
41298
+ addonId: null,
41299
+ access: "view"
41300
+ },
41301
+ "keychainAdmin.purgeRetiredKeys": {
41302
+ capName: "keychain-admin",
41303
+ capScope: "system",
41304
+ addonId: null,
41305
+ access: "delete"
41306
+ },
41307
+ "keychainAdmin.resetKeychain": {
41308
+ capName: "keychain-admin",
41309
+ capScope: "system",
41310
+ addonId: null,
41311
+ access: "delete"
41312
+ },
41313
+ "keychainAdmin.reveal": {
41314
+ capName: "keychain-admin",
41315
+ capScope: "system",
41316
+ addonId: null,
41317
+ access: "create"
41318
+ },
41319
+ "keychainAdmin.rotateMasterKey": {
41320
+ capName: "keychain-admin",
41321
+ capScope: "system",
41322
+ addonId: null,
41323
+ access: "create"
41324
+ },
41325
+ "keychainAdmin.setSystemSecret": {
41326
+ capName: "keychain-admin",
41327
+ capScope: "system",
41328
+ addonId: null,
41329
+ access: "create"
41330
+ },
41331
+ "keychainAdmin.status": {
41332
+ capName: "keychain-admin",
41333
+ capScope: "system",
41334
+ addonId: null,
41335
+ access: "view"
41336
+ },
39624
41337
  "lawnMowerControl.dock": {
39625
41338
  capName: "lawn-mower-control",
39626
41339
  capScope: "device",
@@ -40995,6 +42708,18 @@ Object.freeze({
40995
42708
  addonId: null,
40996
42709
  access: "create"
40997
42710
  },
42711
+ "pipelineAnalytics.addRetrainFrameFromRecording": {
42712
+ capName: "pipeline-analytics",
42713
+ capScope: "device",
42714
+ addonId: null,
42715
+ access: "create"
42716
+ },
42717
+ "pipelineAnalytics.addRetrainFramesToCollection": {
42718
+ capName: "pipeline-analytics",
42719
+ capScope: "device",
42720
+ addonId: null,
42721
+ access: "create"
42722
+ },
40998
42723
  "pipelineAnalytics.applyDeviceSettingsPatch": {
40999
42724
  capName: "pipeline-analytics",
41000
42725
  capScope: "device",
@@ -41043,12 +42768,36 @@ Object.freeze({
41043
42768
  addonId: null,
41044
42769
  access: "view"
41045
42770
  },
42771
+ "pipelineAnalytics.createRetrainCollection": {
42772
+ capName: "pipeline-analytics",
42773
+ capScope: "device",
42774
+ addonId: null,
42775
+ access: "create"
42776
+ },
42777
+ "pipelineAnalytics.createRetrainDatasetVersion": {
42778
+ capName: "pipeline-analytics",
42779
+ capScope: "device",
42780
+ addonId: null,
42781
+ access: "create"
42782
+ },
41046
42783
  "pipelineAnalytics.deleteDeviceEvents": {
41047
42784
  capName: "pipeline-analytics",
41048
42785
  capScope: "device",
41049
42786
  addonId: null,
41050
42787
  access: "delete"
41051
42788
  },
42789
+ "pipelineAnalytics.deleteRetrainCollection": {
42790
+ capName: "pipeline-analytics",
42791
+ capScope: "device",
42792
+ addonId: null,
42793
+ access: "delete"
42794
+ },
42795
+ "pipelineAnalytics.deleteRetrainDatasetVersion": {
42796
+ capName: "pipeline-analytics",
42797
+ capScope: "device",
42798
+ addonId: null,
42799
+ access: "delete"
42800
+ },
41052
42801
  "pipelineAnalytics.deleteTracks": {
41053
42802
  capName: "pipeline-analytics",
41054
42803
  capScope: "device",
@@ -41253,6 +43002,30 @@ Object.freeze({
41253
43002
  addonId: null,
41254
43003
  access: "view"
41255
43004
  },
43005
+ "pipelineAnalytics.listRetrainAssistProfiles": {
43006
+ capName: "pipeline-analytics",
43007
+ capScope: "device",
43008
+ addonId: null,
43009
+ access: "view"
43010
+ },
43011
+ "pipelineAnalytics.listRetrainCollectionFrames": {
43012
+ capName: "pipeline-analytics",
43013
+ capScope: "device",
43014
+ addonId: null,
43015
+ access: "view"
43016
+ },
43017
+ "pipelineAnalytics.listRetrainCollections": {
43018
+ capName: "pipeline-analytics",
43019
+ capScope: "device",
43020
+ addonId: null,
43021
+ access: "view"
43022
+ },
43023
+ "pipelineAnalytics.listRetrainDatasetVersions": {
43024
+ capName: "pipeline-analytics",
43025
+ capScope: "device",
43026
+ addonId: null,
43027
+ access: "view"
43028
+ },
41256
43029
  "pipelineAnalytics.listRetrainFrames": {
41257
43030
  capName: "pipeline-analytics",
41258
43031
  capScope: "device",
@@ -41295,12 +43068,24 @@ Object.freeze({
41295
43068
  addonId: null,
41296
43069
  access: "create"
41297
43070
  },
43071
+ "pipelineAnalytics.previewRetrainDataset": {
43072
+ capName: "pipeline-analytics",
43073
+ capScope: "device",
43074
+ addonId: null,
43075
+ access: "view"
43076
+ },
41298
43077
  "pipelineAnalytics.proposeRetrainAnnotations": {
41299
43078
  capName: "pipeline-analytics",
41300
43079
  capScope: "device",
41301
43080
  addonId: null,
41302
43081
  access: "create"
41303
43082
  },
43083
+ "pipelineAnalytics.proposeRetrainAnnotationsWithLlm": {
43084
+ capName: "pipeline-analytics",
43085
+ capScope: "device",
43086
+ addonId: null,
43087
+ access: "create"
43088
+ },
41304
43089
  "pipelineAnalytics.pruneEvents": {
41305
43090
  capName: "pipeline-analytics",
41306
43091
  capScope: "device",
@@ -41355,6 +43140,18 @@ Object.freeze({
41355
43140
  addonId: null,
41356
43141
  access: "create"
41357
43142
  },
43143
+ "pipelineAnalytics.removeRetrainFrameFromCollection": {
43144
+ capName: "pipeline-analytics",
43145
+ capScope: "device",
43146
+ addonId: null,
43147
+ access: "delete"
43148
+ },
43149
+ "pipelineAnalytics.renameRetrainCollection": {
43150
+ capName: "pipeline-analytics",
43151
+ capScope: "device",
43152
+ addonId: null,
43153
+ access: "create"
43154
+ },
41358
43155
  "pipelineAnalytics.restageRetrainTrack": {
41359
43156
  capName: "pipeline-analytics",
41360
43157
  capScope: "device",
@@ -41415,6 +43212,12 @@ Object.freeze({
41415
43212
  addonId: null,
41416
43213
  access: "create"
41417
43214
  },
43215
+ "pipelineAnalytics.verifyRetrainDatasetVersion": {
43216
+ capName: "pipeline-analytics",
43217
+ capScope: "device",
43218
+ addonId: null,
43219
+ access: "view"
43220
+ },
41418
43221
  "pipelineAnalytics.wipeAllAnalytics": {
41419
43222
  capName: "pipeline-analytics",
41420
43223
  capScope: "device",
@@ -41643,6 +43446,12 @@ Object.freeze({
41643
43446
  addonId: null,
41644
43447
  access: "view"
41645
43448
  },
43449
+ "pipelineOrchestrator.abortNodeBenchmark": {
43450
+ capName: "pipeline-orchestrator",
43451
+ capScope: "system",
43452
+ addonId: null,
43453
+ access: "create"
43454
+ },
41646
43455
  "pipelineOrchestrator.applyAutoTune": {
41647
43456
  capName: "pipeline-orchestrator",
41648
43457
  capScope: "system",
@@ -41667,6 +43476,12 @@ Object.freeze({
41667
43476
  addonId: null,
41668
43477
  access: "create"
41669
43478
  },
43479
+ "pipelineOrchestrator.deleteNodeBenchmarkResult": {
43480
+ capName: "pipeline-orchestrator",
43481
+ capScope: "system",
43482
+ addonId: null,
43483
+ access: "delete"
43484
+ },
41670
43485
  "pipelineOrchestrator.getAgentLoad": {
41671
43486
  capName: "pipeline-orchestrator",
41672
43487
  capScope: "system",
@@ -41775,6 +43590,24 @@ Object.freeze({
41775
43590
  addonId: null,
41776
43591
  access: "view"
41777
43592
  },
43593
+ "pipelineOrchestrator.getNodeBenchmarkCandidates": {
43594
+ capName: "pipeline-orchestrator",
43595
+ capScope: "system",
43596
+ addonId: null,
43597
+ access: "view"
43598
+ },
43599
+ "pipelineOrchestrator.getNodeBenchmarkPreflight": {
43600
+ capName: "pipeline-orchestrator",
43601
+ capScope: "system",
43602
+ addonId: null,
43603
+ access: "view"
43604
+ },
43605
+ "pipelineOrchestrator.getNodeBenchmarkStatus": {
43606
+ capName: "pipeline-orchestrator",
43607
+ capScope: "system",
43608
+ addonId: null,
43609
+ access: "view"
43610
+ },
41778
43611
  "pipelineOrchestrator.getNodeInferenceDevices": {
41779
43612
  capName: "pipeline-orchestrator",
41780
43613
  capScope: "system",
@@ -41817,6 +43650,12 @@ Object.freeze({
41817
43650
  addonId: null,
41818
43651
  access: "view"
41819
43652
  },
43653
+ "pipelineOrchestrator.listNodeBenchmarkResults": {
43654
+ capName: "pipeline-orchestrator",
43655
+ capScope: "system",
43656
+ addonId: null,
43657
+ access: "view"
43658
+ },
41820
43659
  "pipelineOrchestrator.pauseForStorageMigration": {
41821
43660
  capName: "pipeline-orchestrator",
41822
43661
  capScope: "system",
@@ -41961,6 +43800,12 @@ Object.freeze({
41961
43800
  addonId: null,
41962
43801
  access: "create"
41963
43802
  },
43803
+ "pipelineOrchestrator.startNodeBenchmark": {
43804
+ capName: "pipeline-orchestrator",
43805
+ capScope: "system",
43806
+ addonId: null,
43807
+ access: "create"
43808
+ },
41964
43809
  "pipelineOrchestrator.suggestShares": {
41965
43810
  capName: "pipeline-orchestrator",
41966
43811
  capScope: "system",
@@ -41979,6 +43824,12 @@ Object.freeze({
41979
43824
  addonId: null,
41980
43825
  access: "create"
41981
43826
  },
43827
+ "pipelineRunner.abortNodeBench": {
43828
+ capName: "pipeline-runner",
43829
+ capScope: "system",
43830
+ addonId: null,
43831
+ access: "create"
43832
+ },
41982
43833
  "pipelineRunner.attachCamera": {
41983
43834
  capName: "pipeline-runner",
41984
43835
  capScope: "system",
@@ -42027,6 +43878,12 @@ Object.freeze({
42027
43878
  addonId: null,
42028
43879
  access: "view"
42029
43880
  },
43881
+ "pipelineRunner.getNodeBenchStatus": {
43882
+ capName: "pipeline-runner",
43883
+ capScope: "system",
43884
+ addonId: null,
43885
+ access: "view"
43886
+ },
42030
43887
  "pipelineRunner.getParkedTrackFrame": {
42031
43888
  capName: "pipeline-runner",
42032
43889
  capScope: "system",
@@ -42069,6 +43926,12 @@ Object.freeze({
42069
43926
  addonId: null,
42070
43927
  access: "create"
42071
43928
  },
43929
+ "pipelineRunner.startNodeBench": {
43930
+ capName: "pipeline-runner",
43931
+ capScope: "system",
43932
+ addonId: null,
43933
+ access: "create"
43934
+ },
42072
43935
  "plateGallery.assignPlate": {
42073
43936
  capName: "plate-gallery",
42074
43937
  capScope: "system",
@@ -47002,6 +48865,11 @@ Object.freeze({
47002
48865
  form: "single",
47003
48866
  optional: false
47004
48867
  }],
48868
+ "pipelineAnalytics.addRetrainFrameFromRecording": [{
48869
+ name: "deviceId",
48870
+ form: "single",
48871
+ optional: false
48872
+ }],
47005
48873
  "pipelineAnalytics.applyDeviceSettingsPatch": [{
47006
48874
  name: "deviceId",
47007
48875
  form: "single",
@@ -47192,6 +49060,11 @@ Object.freeze({
47192
49060
  form: "single",
47193
49061
  optional: false
47194
49062
  }],
49063
+ "pipelineAnalytics.proposeRetrainAnnotationsWithLlm": [{
49064
+ name: "deviceId",
49065
+ form: "single",
49066
+ optional: false
49067
+ }],
47195
49068
  "pipelineAnalytics.pruneEventsBefore": [{
47196
49069
  name: "deviceId",
47197
49070
  form: "single",
@@ -49298,16 +51171,6 @@ DEFAULT_NATIVE_LEASE_SETTINGS.admission;
49298
51171
  var MB = 1024 * 1024;
49299
51172
  1024 * MB, 3072 * MB;
49300
51173
  //#endregion
49301
- //#region src/hub-browser-origin.ts
49302
- async function hubBrowserOrigin(localNetwork, logger) {
49303
- try {
49304
- return (await localNetwork.getAddresses.query()).roles.publicEndpoint.resolved;
49305
- } catch (err) {
49306
- logger.warn("hub address unavailable from local-network — using the localhost default", { meta: { error: err instanceof Error ? err.message : String(err) } });
49307
- return null;
49308
- }
49309
- }
49310
- //#endregion
49311
51174
  Object.defineProperty(exports, "BaseAddon", {
49312
51175
  enumerable: true,
49313
51176
  get: function() {
@@ -49356,12 +51219,6 @@ Object.defineProperty(exports, "errMsg", {
49356
51219
  return errMsg;
49357
51220
  }
49358
51221
  });
49359
- Object.defineProperty(exports, "hubBrowserOrigin", {
49360
- enumerable: true,
49361
- get: function() {
49362
- return hubBrowserOrigin;
49363
- }
49364
- });
49365
51222
  Object.defineProperty(exports, "isDisplayIconKey", {
49366
51223
  enumerable: true,
49367
51224
  get: function() {