@camstack/addon-provider-homematic 1.2.129 → 1.2.130

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/addon.js +1845 -56
  2. package/dist/addon.mjs +1845 -56
  3. package/package.json +1 -1
package/dist/addon.mjs CHANGED
@@ -9,7 +9,7 @@ import { join } from "path";
9
9
  var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
10
10
  var __require = /* @__PURE__ */ createRequire(import.meta.url);
11
11
  //#endregion
12
- //#region ../types/dist/event-category-B_0XEcLF.mjs
12
+ //#region ../types/dist/event-category-DaIZi00R.mjs
13
13
  var EventCategory = /* @__PURE__ */ function(EventCategory) {
14
14
  EventCategory["SystemBoot"] = "system.boot";
15
15
  EventCategory["SystemAddonsReady"] = "system.addons-ready";
@@ -88,6 +88,13 @@ var EventCategory = /* @__PURE__ */ function(EventCategory) {
88
88
  */
89
89
  EventCategory["AddonLoadFailed"] = "addon.load-failed";
90
90
  /**
91
+ * A keychain value was stored or removed (D787). Carries the ref, its
92
+ * owner and the new version — NEVER the value. A process holding the ref
93
+ * drops its cached copy and the owning `BaseAddon` re-resolves its config.
94
+ * Telemetry (D8): a process that misses it still revalidates by version.
95
+ */
96
+ EventCategory["KeychainChanged"] = "keychain.changed";
97
+ /**
91
98
  * Addon recovered from a previous failure. Emitted when an addon
92
99
  * transitions from `failed` back to `healthy` (typically via the
93
100
  * monitor's auto-retry loop, or after manual `addons.retryLoad`).
@@ -5380,7 +5387,7 @@ var ZodIssueCode = {
5380
5387
  var ZodFirstPartyTypeKind;
5381
5388
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
5382
5389
  //#endregion
5383
- //#region ../types/dist/sleep-B0JG7-_F.mjs
5390
+ //#region ../types/dist/sleep-Cr5YOk3m.mjs
5384
5391
  /**
5385
5392
  * The audio chunk plane's byte format, and the ONE expansion from a coded
5386
5393
  * window to float samples (D455).
@@ -5459,6 +5466,97 @@ function buildAlawTable() {
5459
5466
  }
5460
5467
  buildUlawTable();
5461
5468
  buildAlawTable();
5469
+ /** Is this field's stored value a credential? */
5470
+ function isSecretConfigField(field) {
5471
+ if (field.type === "password") return true;
5472
+ return "secret" in field && field.secret === true;
5473
+ }
5474
+ /**
5475
+ * Is this field's value stored in the KEYCHAIN (D787)? Every secret field is,
5476
+ * by its TYPE, unless it opts out with `storage: 'inline'` — never by its name.
5477
+ */
5478
+ function isKeychainStoredField(field) {
5479
+ if (!isSecretConfigField(field)) return false;
5480
+ if (field.type === "textarea" && field.isJson === true) return false;
5481
+ return !("storage" in field && field.storage === "inline");
5482
+ }
5483
+ /**
5484
+ * What a settings blob holds where a secret used to be.
5485
+ *
5486
+ * A keychain-stored field never holds its value. It holds a self-describing
5487
+ * MARKER, `{"$secret":"secret://…","v":1}` — an object, never a string, so no
5488
+ * code can mistake it for a credential and no form can send it to a camera as
5489
+ * a password. The empty state is `null` / absent, never `''`.
5490
+ *
5491
+ * The same shapes travel to and from the admin UI:
5492
+ *
5493
+ * - read: `hydrateSchema` hands a secret field a {@link SecretFieldView}
5494
+ * (`{ $secret, v, set: true }`) or `null` — the browser learns whether a
5495
+ * value is set, never the value.
5496
+ * - write: an untouched field submits the view back unchanged (KEEP); a typed
5497
+ * value is a plain non-empty string (CHANGE); the Clear button submits
5498
+ * {@link SECRET_CLEAR} (CLEAR). `''`, `null` and the legacy redaction tokens
5499
+ * are KEEP — an empty string is what a defaults-fallback pushes back, and
5500
+ * treating it as "clear" is how a save destroyed a stored credential before.
5501
+ *
5502
+ * Pure and browser-safe.
5503
+ */
5504
+ var SECRET_CLEAR = { $secretClear: true };
5505
+ /** The `'***'` token D634 redaction writes for non-admins. */
5506
+ var LEGACY_DEVICE_REDACTION = "***";
5507
+ function isRecord$1(value) {
5508
+ return typeof value === "object" && value !== null && !Array.isArray(value);
5509
+ }
5510
+ function makeSecretMarker(ref) {
5511
+ return {
5512
+ $secret: ref,
5513
+ v: 1
5514
+ };
5515
+ }
5516
+ /** A stored marker: an object whose `$secret` is a non-empty string. */
5517
+ function isSecretMarker(value) {
5518
+ if (!isRecord$1(value)) return false;
5519
+ const ref = value["$secret"];
5520
+ return typeof ref === "string" && ref.length > 0;
5521
+ }
5522
+ function isSecretClear(value) {
5523
+ return isRecord$1(value) && value["$secretClear"] === true;
5524
+ }
5525
+ /**
5526
+ * The UI view of a stored secret field value: a marker becomes "set", inline
5527
+ * plaintext becomes "set (inline)", nothing becomes `null`. A value never
5528
+ * survives this function.
5529
+ */
5530
+ function toSecretFieldView(stored) {
5531
+ if (isSecretMarker(stored)) return {
5532
+ $secret: stored.$secret,
5533
+ v: 1,
5534
+ set: true
5535
+ };
5536
+ if (typeof stored === "string" && stored.length > 0) return {
5537
+ $secret: null,
5538
+ v: 1,
5539
+ set: true,
5540
+ inline: true
5541
+ };
5542
+ return null;
5543
+ }
5544
+ /**
5545
+ * Classify an incoming value for a secret path. Only a non-empty string that is
5546
+ * not a redaction token sets a value; only {@link SECRET_CLEAR} clears.
5547
+ * Everything else — a marker (ours or anyone's), a UI view, `''`, `null`,
5548
+ * `undefined`, a redaction token, a non-string — keeps what is stored.
5549
+ */
5550
+ function classifySecretWrite(incoming) {
5551
+ if (isSecretClear(incoming)) return { kind: "clear" };
5552
+ if (typeof incoming !== "string") return { kind: "keep" };
5553
+ if (incoming.length === 0) return { kind: "keep" };
5554
+ if (incoming === "__camstack_redacted__" || incoming === LEGACY_DEVICE_REDACTION) return { kind: "keep" };
5555
+ return {
5556
+ kind: "set",
5557
+ value: incoming
5558
+ };
5559
+ }
5462
5560
  Object.fromEntries([
5463
5561
  {
5464
5562
  id: "overview",
@@ -5630,33 +5728,19 @@ Object.fromEntries([
5630
5728
  function isValuelessField(field) {
5631
5729
  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";
5632
5730
  }
5633
- /**
5634
- * Merge a `ConfigUISchema` with a raw `values` record into a
5635
- * `ConfigUISchemaWithValues`. Used by every `get*Settings` backend endpoint
5636
- * before returning to the admin UI. Groups are walked recursively.
5637
- *
5638
- * For each leaf field:
5639
- * - structural fields (`separator`, `info`, `button`) pass through unchanged
5640
- * - other fields get `value = values[key] ?? field.default ?? null`
5641
- *
5642
- * Unknown keys in `values` (keys not declared in the schema) are silently
5643
- * ignored — they don't contribute to the output. Missing keys fall back to
5644
- * the schema default or `null`. This mirrors the old backend behaviour where
5645
- * `FormBuilder` rendered `values[key] ?? field.default`.
5646
- */
5647
- function hydrateSchema(schema, values) {
5731
+ function hydrateSchema(schema, values, options = {}) {
5648
5732
  return {
5649
5733
  ...schema.tabs ? { tabs: [...schema.tabs] } : {},
5650
5734
  sections: schema.sections.map((section) => ({
5651
5735
  ...section,
5652
- fields: section.fields.map((field) => hydrateField(field, values))
5736
+ fields: section.fields.map((field) => hydrateField(field, values, options))
5653
5737
  }))
5654
5738
  };
5655
5739
  }
5656
- function hydrateField(field, values) {
5740
+ function hydrateField(field, values, options) {
5657
5741
  if (isValuelessField(field)) return field;
5658
5742
  if (field.type === "group") {
5659
- const hydratedChildren = field.fields.map((child) => hydrateField(child, values));
5743
+ const hydratedChildren = field.fields.map((child) => hydrateField(child, values, options));
5660
5744
  return {
5661
5745
  ...field,
5662
5746
  fields: hydratedChildren
@@ -5665,7 +5749,7 @@ function hydrateField(field, values) {
5665
5749
  if (field.type === "sub-tabs") {
5666
5750
  const hydratedTabs = field.tabs.map((tab) => ({
5667
5751
  ...tab,
5668
- fields: tab.fields.map((child) => hydrateField(child, values))
5752
+ fields: tab.fields.map((child) => hydrateField(child, values, options))
5669
5753
  }));
5670
5754
  return {
5671
5755
  ...field,
@@ -5675,6 +5759,33 @@ function hydrateField(field, values) {
5675
5759
  const key = field.key;
5676
5760
  const storedValue = Object.prototype.hasOwnProperty.call(values, key) ? values[key] : void 0;
5677
5761
  const defaultValue = field.default;
5762
+ const asView = (v) => isSecretMarker(v) || options.inlineSecretsAsViews === true && v !== void 0;
5763
+ if (isKeychainStoredField(field) && asView(storedValue)) return {
5764
+ ...field,
5765
+ value: toSecretFieldView(storedValue)
5766
+ };
5767
+ if (isKeychainStoredField(field) && options.inlineSecretsAsViews === true) return {
5768
+ ...field,
5769
+ value: null
5770
+ };
5771
+ if (field.type === "editable-array" && Array.isArray(storedValue)) {
5772
+ const secretItemKeys = field.itemFields.filter((item) => "key" in item && isKeychainStoredField(item)).map((item) => "key" in item ? item.key : "");
5773
+ if (secretItemKeys.length > 0) {
5774
+ const rows = storedValue.map((row) => {
5775
+ if (row === null || typeof row !== "object" || Array.isArray(row)) return row;
5776
+ const out = { ...row };
5777
+ for (const k of secretItemKeys) {
5778
+ const v = Reflect.get(row, k);
5779
+ if (asView(v)) out[k] = toSecretFieldView(v);
5780
+ }
5781
+ return out;
5782
+ });
5783
+ return {
5784
+ ...field,
5785
+ value: rows
5786
+ };
5787
+ }
5788
+ }
5678
5789
  if (field.multiple) {
5679
5790
  const stored = Array.isArray(storedValue) ? storedValue : storedValue !== void 0 && storedValue !== null ? [storedValue] : [];
5680
5791
  const itemFallback = field.multiple.itemDefault !== void 0 ? field.multiple.itemDefault : defaultValue !== void 0 ? defaultValue : typeOf(field) === "string" ? "" : null;
@@ -5917,6 +6028,431 @@ function projectStore(store, perNodeKeys, nodeId) {
5917
6028
  }
5918
6029
  return out;
5919
6030
  }
6031
+ var GLOBAL_SCOPE = { kind: "global" };
6032
+ /** The scope every addon-wide (not per-node, not per-device) setting lives in. */
6033
+ function globalSecretScope() {
6034
+ return GLOBAL_SCOPE;
6035
+ }
6036
+ function encodeSegment(value) {
6037
+ return encodeURIComponent(value);
6038
+ }
6039
+ /**
6040
+ * The field path of a value inside an array item, addressed by the item's id:
6041
+ * `arrayItemFieldPath('providers', 'authentik', 'clientSecret')` →
6042
+ * `providers[authentik].clientSecret`.
6043
+ */
6044
+ function arrayItemFieldPath(arrayKey, itemId, fieldKey) {
6045
+ return `${arrayKey}[${encodeSegment(itemId)}].${fieldKey}`;
6046
+ }
6047
+ /** A write to a secret path could not be stored in the keychain, so it was refused. */
6048
+ var KeychainWriteRefusedError = class extends Error {
6049
+ fieldPath;
6050
+ constructor(fieldPath, cause) {
6051
+ super(`secret "${fieldPath}" was not saved: the keychain could not store it (${cause instanceof Error ? cause.message : String(cause)}). Nothing was written.`);
6052
+ this.fieldPath = fieldPath;
6053
+ this.name = "KeychainWriteRefusedError";
6054
+ }
6055
+ };
6056
+ var KEEP = { kind: "keep" };
6057
+ function isRecord$2(value) {
6058
+ return typeof value === "object" && value !== null && !Array.isArray(value);
6059
+ }
6060
+ function defaultMintId() {
6061
+ return globalThis.crypto.randomUUID();
6062
+ }
6063
+ /** Every marker ref anywhere under `value`. */
6064
+ function collectSecretMarkerRefs(value, out = []) {
6065
+ if (isSecretMarker(value)) {
6066
+ out.push(value.$secret);
6067
+ return out;
6068
+ }
6069
+ if (Array.isArray(value)) for (const item of value) collectSecretMarkerRefs(item, out);
6070
+ else if (isRecord$2(value)) for (const child of Object.values(value)) collectSecretMarkerRefs(child, out);
6071
+ return out;
6072
+ }
6073
+ async function storedValueEquals(secrets, marker, candidate) {
6074
+ const resolved = (await secrets.resolve([marker.$secret]))[marker.$secret];
6075
+ return resolved?.kind === "value" && resolved.value === candidate;
6076
+ }
6077
+ async function writeLeaf(ctx, incoming, stored, fieldPath) {
6078
+ const intent = classifySecretWrite(incoming);
6079
+ const ref = ctx.secrets.ref(ctx.scope, fieldPath);
6080
+ const storedIsOurs = isSecretMarker(stored) && stored.$secret === ref;
6081
+ if (intent.kind === "keep") return KEEP;
6082
+ if (intent.kind === "set" && !ctx.operatorWrite && typeof stored === "string" && stored === intent.value) return KEEP;
6083
+ if (intent.kind === "clear") {
6084
+ if (storedIsOurs) ctx.deletes.push(ref);
6085
+ return {
6086
+ kind: "value",
6087
+ value: null
6088
+ };
6089
+ }
6090
+ if (storedIsOurs && await storedValueEquals(ctx.secrets, stored, intent.value)) return {
6091
+ kind: "value",
6092
+ value: stored
6093
+ };
6094
+ try {
6095
+ await ctx.secrets.put(ref, intent.value);
6096
+ } catch (err) {
6097
+ throw new KeychainWriteRefusedError(fieldPath, err);
6098
+ }
6099
+ return {
6100
+ kind: "value",
6101
+ value: makeSecretMarker(ref)
6102
+ };
6103
+ }
6104
+ /** Apply a member result onto `out`: KEEP restores the stored member, or removes it. */
6105
+ function applyMember(out, key, result, storedParent) {
6106
+ if (result.kind === "value") {
6107
+ out[key] = result.value;
6108
+ return;
6109
+ }
6110
+ if (Object.prototype.hasOwnProperty.call(storedParent, key)) out[key] = storedParent[key];
6111
+ else delete out[key];
6112
+ }
6113
+ async function writeMembers(ctx, children, incoming, stored, pathOf) {
6114
+ const out = { ...incoming };
6115
+ for (const [member, node] of children) applyMember(out, member, await writeNode(ctx, node, incoming[member], stored[member], pathOf(member)), stored);
6116
+ return out;
6117
+ }
6118
+ function rowId(row, idKey) {
6119
+ const raw = row[idKey];
6120
+ if (typeof raw === "string" && raw.length > 0) return raw;
6121
+ if (typeof raw === "number" && Number.isFinite(raw)) return String(raw);
6122
+ return null;
6123
+ }
6124
+ async function writeArray(ctx, node, incoming, stored, fieldPath) {
6125
+ const storedRows = Array.isArray(stored) ? stored.filter(isRecord$2) : [];
6126
+ if (!Array.isArray(incoming)) {
6127
+ ctx.deletes.push(...collectSecretMarkerRefs(storedRows));
6128
+ return {
6129
+ kind: "value",
6130
+ value: incoming
6131
+ };
6132
+ }
6133
+ const storedById = /* @__PURE__ */ new Map();
6134
+ for (const row of storedRows) {
6135
+ const id = rowId(row, node.idKey);
6136
+ if (id !== null) storedById.set(id, row);
6137
+ }
6138
+ const kept = /* @__PURE__ */ new Set();
6139
+ const rows = [];
6140
+ for (const row of incoming) {
6141
+ if (!isRecord$2(row)) {
6142
+ rows.push(row);
6143
+ continue;
6144
+ }
6145
+ const id = rowId(row, node.idKey) ?? ctx.mintId();
6146
+ kept.add(id);
6147
+ const withId = {
6148
+ ...row,
6149
+ [node.idKey]: row[node.idKey] ?? id
6150
+ };
6151
+ if (rowId(withId, node.idKey) === null) withId[node.idKey] = id;
6152
+ const storedRow = storedById.get(id) ?? {};
6153
+ rows.push(await writeMembers(ctx, node.item, withId, storedRow, (member) => arrayItemFieldPath(fieldPath, id, member)));
6154
+ }
6155
+ for (const [id, row] of storedById) if (!kept.has(id)) ctx.deletes.push(...collectSecretMarkerRefs(row));
6156
+ return {
6157
+ kind: "value",
6158
+ value: rows
6159
+ };
6160
+ }
6161
+ async function writeNode(ctx, node, incoming, stored, fieldPath) {
6162
+ switch (node.kind) {
6163
+ case "leaf": return writeLeaf(ctx, incoming, stored, fieldPath);
6164
+ case "array": return writeArray(ctx, node, incoming, stored, fieldPath);
6165
+ case "object": {
6166
+ if (!isRecord$2(incoming)) {
6167
+ if (incoming === void 0) return KEEP;
6168
+ ctx.deletes.push(...collectSecretMarkerRefs(stored));
6169
+ return {
6170
+ kind: "value",
6171
+ value: incoming
6172
+ };
6173
+ }
6174
+ const storedObj = isRecord$2(stored) ? stored : {};
6175
+ return {
6176
+ kind: "value",
6177
+ value: await writeMembers(ctx, node.children, incoming, storedObj, (m) => `${fieldPath}.${m}`)
6178
+ };
6179
+ }
6180
+ }
6181
+ }
6182
+ /** Split a perNode-scoped key (`key@nodeId`). */
6183
+ function splitNodeKey(key) {
6184
+ const at = key.indexOf("@");
6185
+ return at <= 0 ? {
6186
+ base: key,
6187
+ nodeId: null
6188
+ } : {
6189
+ base: key.slice(0, at),
6190
+ nodeId: key.slice(at + 1)
6191
+ };
6192
+ }
6193
+ /** Rewrite a settings patch so no secret value reaches the blob. See the file doc. */
6194
+ async function transformSecretWrite(input) {
6195
+ const deletes = [];
6196
+ const base = {
6197
+ secrets: input.secrets,
6198
+ mintId: input.mintId ?? defaultMintId,
6199
+ deletes,
6200
+ operatorWrite: input.operatorWrite === true
6201
+ };
6202
+ const out = {};
6203
+ for (const [key, incoming] of Object.entries(input.patch)) {
6204
+ const { base: baseKey, nodeId } = splitNodeKey(key);
6205
+ const node = input.tree.get(baseKey);
6206
+ if (node === void 0) {
6207
+ out[key] = incoming;
6208
+ continue;
6209
+ }
6210
+ const scope = nodeId !== null && nodeId.length > 0 ? {
6211
+ kind: "node",
6212
+ nodeId
6213
+ } : input.scope ?? globalSecretScope();
6214
+ const result = await writeNode({
6215
+ ...base,
6216
+ scope
6217
+ }, node, incoming, input.stored[key], baseKey);
6218
+ if (result.kind === "value") out[key] = result.value;
6219
+ }
6220
+ return {
6221
+ patch: out,
6222
+ afterWrite: async () => {
6223
+ if (deletes.length === 0) return { orphaned: [] };
6224
+ try {
6225
+ await input.secrets.delete([...new Set(deletes)]);
6226
+ return { orphaned: [] };
6227
+ } catch {
6228
+ return { orphaned: [...new Set(deletes)] };
6229
+ }
6230
+ }
6231
+ };
6232
+ }
6233
+ /**
6234
+ * Replace every marker in `value` with its keychain value. Returns the SAME
6235
+ * reference when there is no marker (no allocation, no keychain call).
6236
+ */
6237
+ async function resolveSecretMarkers(value, secrets) {
6238
+ const refs = collectSecretMarkerRefs(value);
6239
+ if (refs.length === 0) return {
6240
+ value,
6241
+ unresolved: []
6242
+ };
6243
+ const answers = await secrets.resolve(refs);
6244
+ const unresolved = [];
6245
+ for (const ref of new Set(refs)) {
6246
+ const answer = answers[ref];
6247
+ if (answer === void 0) unresolved.push({
6248
+ ref,
6249
+ reason: "not-initialized"
6250
+ });
6251
+ else if (answer.kind === "unavailable") unresolved.push({
6252
+ ref,
6253
+ reason: answer.reason
6254
+ });
6255
+ else if (answer.kind === "missing" || answer.kind === "forbidden") unresolved.push({
6256
+ ref,
6257
+ reason: answer.kind
6258
+ });
6259
+ }
6260
+ const substitute = (v) => {
6261
+ if (isSecretMarker(v)) {
6262
+ const answer = answers[v.$secret];
6263
+ return answer?.kind === "value" ? {
6264
+ keep: true,
6265
+ value: answer.value
6266
+ } : {
6267
+ keep: false,
6268
+ value: void 0
6269
+ };
6270
+ }
6271
+ if (Array.isArray(v)) {
6272
+ const items = [];
6273
+ for (const item of v) {
6274
+ const s = substitute(item);
6275
+ if (s.keep) items.push(s.value);
6276
+ }
6277
+ return {
6278
+ keep: true,
6279
+ value: items
6280
+ };
6281
+ }
6282
+ if (isRecord$2(v)) {
6283
+ const out = {};
6284
+ for (const [k, child] of Object.entries(v)) {
6285
+ const s = substitute(child);
6286
+ if (s.keep) out[k] = s.value;
6287
+ }
6288
+ return {
6289
+ keep: true,
6290
+ value: out
6291
+ };
6292
+ }
6293
+ return {
6294
+ keep: true,
6295
+ value: v
6296
+ };
6297
+ };
6298
+ return {
6299
+ value: substitute(value).value,
6300
+ unresolved
6301
+ };
6302
+ }
6303
+ function touchesTree(tree, patch) {
6304
+ if (tree.size === 0) return false;
6305
+ for (const key of Object.keys(patch)) {
6306
+ const at = key.indexOf("@");
6307
+ if (tree.has(at > 0 ? key.slice(0, at) : key)) return true;
6308
+ }
6309
+ return false;
6310
+ }
6311
+ /** The blob as stored now; a failed read REFUSES the write instead of guessing. */
6312
+ async function readStoredAddonBlob(raw) {
6313
+ const threeWay = raw.readAddonStoreResult;
6314
+ if (threeWay === void 0) return raw.readAddonStore();
6315
+ const result = await threeWay.call(raw);
6316
+ if (result.kind === "failed") throw new Error(`settings write refused: the stored blob could not be read (${result.error})`);
6317
+ return result.kind === "missing" ? {} : result.value;
6318
+ }
6319
+ function createSecretAwareSettings(raw, opts) {
6320
+ const chains = /* @__PURE__ */ new Map();
6321
+ const serialize = (key, fn) => {
6322
+ const next = (chains.get(key) ?? Promise.resolve()).then(fn, fn);
6323
+ const tail = next.catch(() => void 0);
6324
+ chains.set(key, tail);
6325
+ tail.then(() => {
6326
+ if (chains.get(key) === tail) chains.delete(key);
6327
+ });
6328
+ return next;
6329
+ };
6330
+ const write = async (chainKey, tree, scope, patch, readStored, rawWrite) => {
6331
+ if (!touchesTree(tree, patch)) return rawWrite(patch);
6332
+ return serialize(chainKey, async () => {
6333
+ const stored = await readStored();
6334
+ const result = await transformSecretWrite({
6335
+ tree,
6336
+ secrets: opts.secrets,
6337
+ patch,
6338
+ stored,
6339
+ ...scope !== void 0 ? { scope } : {},
6340
+ operatorWrite: opts.isOperatorWrite?.() === true
6341
+ });
6342
+ if (Object.keys(result.patch).length > 0) await rawWrite(result.patch);
6343
+ const { orphaned } = await result.afterWrite();
6344
+ if (orphaned.length > 0) opts.onOrphaned(orphaned);
6345
+ });
6346
+ };
6347
+ const wrapped = {
6348
+ writeAddonStore: (patch) => write("addon", opts.addonTree(), void 0, patch, () => readStoredAddonBlob(raw), (p) => raw.writeAddonStore(p)),
6349
+ writeDeviceStore: (deviceId, patch) => write(`device:${deviceId}`, opts.deviceTree(), {
6350
+ kind: "device",
6351
+ deviceId
6352
+ }, patch, () => raw.readDeviceStore(deviceId), (p) => raw.writeDeviceStore(deviceId, p))
6353
+ };
6354
+ return new Proxy(raw, { get(target, prop, receiver) {
6355
+ if (prop === "writeAddonStore") return wrapped.writeAddonStore;
6356
+ if (prop === "writeDeviceStore") return wrapped.writeDeviceStore;
6357
+ const value = Reflect.get(target, prop, receiver);
6358
+ return typeof value === "function" ? value.bind(target) : value;
6359
+ } });
6360
+ }
6361
+ /** The context the addon sees: identical, except that its settings writes are secret-aware. */
6362
+ function withSecretAwareSettings(context, opts) {
6363
+ const raw = context.settings;
6364
+ if (raw === void 0) return context;
6365
+ const settings = createSecretAwareSettings(raw, opts);
6366
+ return new Proxy(context, { get(target, prop, receiver) {
6367
+ if (prop === "settings") return settings;
6368
+ return Reflect.get(target, prop, receiver);
6369
+ } });
6370
+ }
6371
+ var LEAF = { kind: "leaf" };
6372
+ var DEFAULT_ITEM_ID_KEY = "id";
6373
+ function collectFields(fields, out) {
6374
+ for (const field of fields) {
6375
+ if (field.type === "group") {
6376
+ collectFields(field.fields, out);
6377
+ continue;
6378
+ }
6379
+ if (field.type === "sub-tabs") {
6380
+ for (const tab of field.tabs) collectFields(tab.fields, out);
6381
+ continue;
6382
+ }
6383
+ if (field.type === "editable-array") {
6384
+ const item = /* @__PURE__ */ new Map();
6385
+ for (const itemField of field.itemFields) if ("key" in itemField && isKeychainStoredField(itemField)) item.set(itemField.key, LEAF);
6386
+ if (item.size > 0) out.set(field.key, {
6387
+ kind: "array",
6388
+ idKey: field.itemIdKey ?? DEFAULT_ITEM_ID_KEY,
6389
+ item
6390
+ });
6391
+ continue;
6392
+ }
6393
+ if (!("key" in field) || typeof field.key !== "string") continue;
6394
+ if (isKeychainStoredField(field)) out.set(field.key, LEAF);
6395
+ }
6396
+ }
6397
+ /** The secret tree a settings schema declares. */
6398
+ function secretTreeFromSchema(schema) {
6399
+ const out = /* @__PURE__ */ new Map();
6400
+ if (schema === null) return out;
6401
+ for (const section of schema.sections) collectFields(section.fields, out);
6402
+ return out;
6403
+ }
6404
+ /** Parse `a.b[id].c` into segments; throws on a malformed path (a declaration bug). */
6405
+ function parseSecretStatePath(path) {
6406
+ const segments = [];
6407
+ for (const raw of path.split(".")) {
6408
+ const m = /^([^[\]]+)(?:\[([^[\]]+)\])?$/.exec(raw);
6409
+ if (m === null || m[1] === void 0) throw new Error(`secretStatePaths: malformed path "${path}"`);
6410
+ segments.push(m[2] !== void 0 ? {
6411
+ key: m[1],
6412
+ idKey: m[2]
6413
+ } : { key: m[1] });
6414
+ }
6415
+ if (segments.length === 0) throw new Error(`secretStatePaths: empty path`);
6416
+ if (segments[segments.length - 1]?.idKey !== void 0) throw new Error(`secretStatePaths: "${path}" ends on an array — name the member that is secret`);
6417
+ return segments;
6418
+ }
6419
+ function insert(into, segments) {
6420
+ const [head, ...rest] = segments;
6421
+ if (head === void 0) return;
6422
+ if (rest.length === 0) {
6423
+ into.set(head.key, LEAF);
6424
+ return;
6425
+ }
6426
+ const existing = into.get(head.key);
6427
+ if (head.idKey !== void 0) {
6428
+ const item = new Map(existing?.kind === "array" ? existing.item : []);
6429
+ insert(item, rest);
6430
+ into.set(head.key, {
6431
+ kind: "array",
6432
+ idKey: head.idKey,
6433
+ item
6434
+ });
6435
+ return;
6436
+ }
6437
+ const children = new Map(existing?.kind === "object" ? existing.children : []);
6438
+ insert(children, rest);
6439
+ into.set(head.key, {
6440
+ kind: "object",
6441
+ children
6442
+ });
6443
+ }
6444
+ /** Add hidden-state paths (`secretStatePaths`) to a schema-derived tree. */
6445
+ function mergeSecretStatePaths(tree, paths) {
6446
+ if (paths.length === 0) return tree;
6447
+ const out = new Map(tree);
6448
+ for (const path of paths) insert(out, parseSecretStatePath(path));
6449
+ return out;
6450
+ }
6451
+ /** First retry of a secret the keychain could not serve; doubles to {@link SECRET_RETRY_MAX_MS}. */
6452
+ var SECRET_RETRY_FIRST_MS = 5e3;
6453
+ var SECRET_RETRY_MAX_MS = 5 * 6e4;
6454
+ /** Coalesces a burst of `keychain.changed` events into one re-resolve. */
6455
+ var SECRET_CHANGE_DEBOUNCE_MS = 250;
5920
6456
  /**
5921
6457
  * Base class for CamStack addons. Eliminates settings boilerplate:
5922
6458
  *
@@ -5986,6 +6522,25 @@ var BaseAddon = class {
5986
6522
  settingsStoreReady = false;
5987
6523
  /** Default config values. Provided via constructor. */
5988
6524
  defaults;
6525
+ /**
6526
+ * Hidden-state paths that hold secrets (D787) — values the addon writes
6527
+ * itself (`updateGlobalSettings`, `state()`) that no form field declares.
6528
+ * Stored in the keychain exactly like a `password` field. Syntax:
6529
+ * `'snapshotSigningKey'`, `'identity.pincode'`, `'tokens[userId].accessToken'`
6530
+ * (`key[<id field>]` addresses array items by id, never by index).
6531
+ */
6532
+ secretStatePaths = [];
6533
+ _addonSecretTree = null;
6534
+ _deviceSecretTree = null;
6535
+ /** Refs the last resolved config pointed at — a change to one re-resolves. */
6536
+ _configSecretRefs = /* @__PURE__ */ new Set();
6537
+ _unresolvedSecrets = [];
6538
+ _secretRetryTimer = null;
6539
+ _secretRetryDelayMs = SECRET_RETRY_FIRST_MS;
6540
+ _secretChangeTimer = null;
6541
+ _secretChangeUnsub = null;
6542
+ /** >0 while an OPERATOR's settings write is being applied. */
6543
+ _operatorWriteDepth = 0;
5989
6544
  constructor(defaults) {
5990
6545
  this.defaults = defaults;
5991
6546
  this._config = { ...defaults };
@@ -6021,8 +6576,18 @@ var BaseAddon = class {
6021
6576
  return this._config;
6022
6577
  }
6023
6578
  async initialize(context) {
6024
- this._ctx = context;
6579
+ const secrets = context.secrets;
6580
+ this._ctx = secrets !== void 0 ? withSecretAwareSettings(context, {
6581
+ secrets,
6582
+ addonTree: () => this.addonSecretTree(),
6583
+ deviceTree: () => this.deviceSecretTree(),
6584
+ onOrphaned: (refs) => context.logger.warn("keychain refs dropped by a settings write could not be deleted", { meta: { refs: [...refs] } }),
6585
+ isOperatorWrite: () => this._operatorWriteDepth > 0
6586
+ }) : context;
6025
6587
  await this.resolveConfig();
6588
+ if (secrets !== void 0) this._secretChangeUnsub = secrets.onChange((ref) => {
6589
+ if (this._configSecretRefs.has(ref)) this.scheduleSecretReresolve(SECRET_CHANGE_DEBOUNCE_MS);
6590
+ });
6026
6591
  const result = await this.onInitialize();
6027
6592
  this.emitLifecycle(EventCategory.AddonStarted);
6028
6593
  const normalized = normalizeAddonInitResult(result);
@@ -6055,6 +6620,12 @@ var BaseAddon = class {
6055
6620
  */
6056
6621
  async onHubReachable() {}
6057
6622
  async shutdown() {
6623
+ this._secretChangeUnsub?.();
6624
+ this._secretChangeUnsub = null;
6625
+ if (this._secretRetryTimer !== null) clearTimeout(this._secretRetryTimer);
6626
+ if (this._secretChangeTimer !== null) clearTimeout(this._secretChangeTimer);
6627
+ this._secretRetryTimer = null;
6628
+ this._secretChangeTimer = null;
6058
6629
  this.emitLifecycle(EventCategory.AddonStopped);
6059
6630
  if (this.autoEmitReadiness) this.emitReadinessForProviders("down");
6060
6631
  await this.onShutdown();
@@ -6133,7 +6704,7 @@ var BaseAddon = class {
6133
6704
  return hydrateSchema(schema, overlay ? {
6134
6705
  ...projected,
6135
6706
  ...overlay
6136
- } : projected);
6707
+ } : projected, { inlineSecretsAsViews: true });
6137
6708
  }
6138
6709
  /**
6139
6710
  * The integration-level view of this addon's settings: exactly the sections
@@ -6182,7 +6753,7 @@ var BaseAddon = class {
6182
6753
  return hydrateSchema({
6183
6754
  ...schema,
6184
6755
  sections
6185
- }, projected);
6756
+ }, projected, { inlineSecretsAsViews: true });
6186
6757
  }
6187
6758
  /**
6188
6759
  * The raw addon store PROJECTED onto the target node's bare per-node keys:
@@ -6236,18 +6807,50 @@ var BaseAddon = class {
6236
6807
  value: result.value[key]
6237
6808
  };
6238
6809
  }
6810
+ /**
6811
+ * The OPERATOR's write — a settings form or an admin API call, dispatched by
6812
+ * the kernel. Identical to {@link updateGlobalSettings}, except that a secret
6813
+ * the operator sends is stored as sent even when it equals a pre-keychain
6814
+ * inline value: the operator re-entering a password is a change, an addon
6815
+ * writing back what it read is not (D787).
6816
+ */
6817
+ async updateGlobalSettingsAsOperator(patch, nodeId) {
6818
+ this._operatorWriteDepth++;
6819
+ try {
6820
+ await this.applyGlobalPatch(patch, nodeId);
6821
+ } finally {
6822
+ this._operatorWriteDepth--;
6823
+ }
6824
+ }
6239
6825
  async updateGlobalSettings(patch, nodeId) {
6826
+ await this.applyGlobalPatch(patch, nodeId);
6827
+ }
6828
+ /**
6829
+ * REMOVE stored secrets — their keychain values and their markers (D787).
6830
+ *
6831
+ * Writing `''` to a secret field KEEPS what is stored (an empty string is
6832
+ * what a defaults fallback writes back, and it must never destroy a
6833
+ * credential), so code that means "forget this token" says so here. Without
6834
+ * a keychain (an older kernel) it writes `''`, as such code always did.
6835
+ */
6836
+ async clearSecrets(keys, nodeId) {
6837
+ const tree = this.addonSecretTree();
6838
+ const keychain = this._ctx?.secrets !== void 0;
6839
+ const patch = {};
6840
+ for (const key of keys) patch[key] = keychain && tree.has(key) ? SECRET_CLEAR : "";
6841
+ await this.applyGlobalPatch(patch, nodeId);
6842
+ }
6843
+ async applyGlobalPatch(barePatch, nodeId) {
6240
6844
  const keys = this.perNodeKeys();
6241
6845
  const localNode = normalizeNodeId(this._ctx?.kernel?.localNodeId);
6242
6846
  const target = normalizeNodeId(nodeId ?? this._ctx?.kernel?.localNodeId);
6243
- const barePatch = patch;
6244
6847
  const scoped = keys.size > 0 ? scopePatch(barePatch, keys, target) : barePatch;
6245
6848
  await this._ctx?.settings?.writeAddonStore(scoped);
6246
6849
  if (target !== localNode) return;
6247
6850
  await this.resolveConfig();
6248
6851
  await this.onConfigChanged();
6249
6852
  this.emitLifecycle(EventCategory.AddonUpdated, { level: "global" });
6250
- this.maybeAutoRestart(patch, this.globalSettingsSchema());
6853
+ this.maybeAutoRestart(Object.keys(barePatch), this.globalSettingsSchema());
6251
6854
  }
6252
6855
  /**
6253
6856
  * The set of field keys the global settings schema declares `perNode: true`
@@ -6272,7 +6875,7 @@ var BaseAddon = class {
6272
6875
  * time to return its response before the addon is torn down and
6273
6876
  * re-initialised by `AddonRegistryService.restartAddon`.
6274
6877
  */
6275
- maybeAutoRestart(patch, schema) {
6878
+ maybeAutoRestart(patchKeys, schema) {
6276
6879
  if (!schema) return;
6277
6880
  const restartKeys = /* @__PURE__ */ new Set();
6278
6881
  for (const section of schema.sections) for (const field of section.fields) {
@@ -6280,13 +6883,13 @@ var BaseAddon = class {
6280
6883
  if (field.requiresRestart) restartKeys.add(field.key);
6281
6884
  }
6282
6885
  if (restartKeys.size === 0) return;
6283
- if (!Object.keys(patch).some((k) => restartKeys.has(k))) return;
6886
+ if (!patchKeys.some((k) => restartKeys.has(k))) return;
6284
6887
  const ctx = this._ctx;
6285
6888
  if (!ctx) return;
6286
6889
  const addonId = ctx.id;
6287
6890
  setImmediate(() => {
6288
6891
  ctx.api.addons?.restartAddon?.mutate({ addonId }).then(() => {
6289
- ctx.logger.info("addon auto-restart triggered by restart-required setting change", { meta: { changedFields: Object.keys(patch).filter((k) => restartKeys.has(k)) } });
6892
+ ctx.logger.info("addon auto-restart triggered by restart-required setting change", { meta: { changedFields: patchKeys.filter((k) => restartKeys.has(k)) } });
6290
6893
  }).catch((err) => {
6291
6894
  ctx.logger.error("addon auto-restart failed", { meta: { error: err instanceof Error ? err.message : String(err) } });
6292
6895
  });
@@ -6295,7 +6898,7 @@ var BaseAddon = class {
6295
6898
  async getDeviceSettings(deviceId) {
6296
6899
  const schema = this.deviceSettingsSchema();
6297
6900
  if (!schema) return { sections: [] };
6298
- return hydrateSchema(schema, await this._ctx?.settings?.readDeviceStore(deviceId) ?? {});
6901
+ return hydrateSchema(schema, await this._ctx?.settings?.readDeviceStore(deviceId) ?? {}, { inlineSecretsAsViews: true });
6299
6902
  }
6300
6903
  async updateDeviceSettings(deviceId, patch) {
6301
6904
  await this._ctx?.settings?.writeDeviceStore(deviceId, patch);
@@ -6425,7 +7028,7 @@ var BaseAddon = class {
6425
7028
  * selection at boot (absent scoped key ⇒ the constructor default wins).
6426
7029
  */
6427
7030
  async resolveConfig() {
6428
- const stored = await this.readAddonStoreWithRetry();
7031
+ const stored = await this.resolveStoredSecrets(await this.readAddonStoreWithRetry());
6429
7032
  const perNode = this.perNodeKeys();
6430
7033
  const localNode = normalizeNodeId(this._ctx?.kernel?.localNodeId);
6431
7034
  const resolved = { ...this.defaults };
@@ -6450,7 +7053,7 @@ var BaseAddon = class {
6450
7053
  key,
6451
7054
  schema,
6452
7055
  fallback,
6453
- read: () => this.readAddonStoreWithRetry(),
7056
+ read: async () => this.resolveStoredSecrets(await this.readAddonStoreWithRetry()),
6454
7057
  write: async (patch) => {
6455
7058
  await this._ctx?.settings?.writeAddonStore(patch);
6456
7059
  },
@@ -6467,7 +7070,7 @@ var BaseAddon = class {
6467
7070
  key,
6468
7071
  schema,
6469
7072
  fallback,
6470
- read: async () => await this._ctx?.settings?.readDeviceStore(deviceId) ?? {},
7073
+ read: async () => this.resolveStoredSecrets(await this._ctx?.settings?.readDeviceStore(deviceId) ?? {}, false),
6471
7074
  write: async (patch) => {
6472
7075
  await this._ctx?.settings?.writeDeviceStore(deviceId, patch);
6473
7076
  },
@@ -6479,6 +7082,70 @@ var BaseAddon = class {
6479
7082
  } })
6480
7083
  });
6481
7084
  }
7085
+ /** The addon store's secret tree: schema fields by TYPE, plus `secretStatePaths`. */
7086
+ addonSecretTree() {
7087
+ this._addonSecretTree ??= mergeSecretStatePaths(secretTreeFromSchema(this.globalSettingsSchema()), this.secretStatePaths);
7088
+ return this._addonSecretTree;
7089
+ }
7090
+ deviceSecretTree() {
7091
+ this._deviceSecretTree ??= secretTreeFromSchema(this.deviceSettingsSchema());
7092
+ return this._deviceSecretTree;
7093
+ }
7094
+ /**
7095
+ * Secrets of this addon's stored config that could not be resolved on the
7096
+ * last read, with why. Non-empty means the addon is running WITHOUT them —
7097
+ * an addon whose function needs one should report itself degraded rather
7098
+ * than start on an empty credential.
7099
+ */
7100
+ get unresolvedSecrets() {
7101
+ return this._unresolvedSecrets;
7102
+ }
7103
+ /**
7104
+ * Substitute every keychain marker in a stored blob with its value. With no
7105
+ * keychain (no `ctx.secrets`) or no marker, the blob comes back unchanged.
7106
+ * An unresolvable value is LEFT OUT (never `''`), logged by ref — never by
7107
+ * value — and, when the cause can pass, retried with backoff. Nothing is
7108
+ * ever written back from here.
7109
+ */
7110
+ async resolveStoredSecrets(blob, trackForConfig = true) {
7111
+ const secrets = this._ctx?.secrets;
7112
+ if (secrets === void 0) return blob;
7113
+ const refs = collectSecretMarkerRefs(blob);
7114
+ if (trackForConfig) this._configSecretRefs = new Set(refs);
7115
+ if (refs.length === 0) {
7116
+ if (trackForConfig) this._unresolvedSecrets = [];
7117
+ return blob;
7118
+ }
7119
+ const { value, unresolved } = await resolveSecretMarkers(blob, secrets);
7120
+ if (trackForConfig) {
7121
+ this._unresolvedSecrets = unresolved;
7122
+ if (unresolved.length > 0) {
7123
+ this._ctx?.logger?.error?.("secret unavailable — running without it, will retry", { meta: { secrets: unresolved.map((u) => ({
7124
+ ref: u.ref,
7125
+ reason: u.reason
7126
+ })) } });
7127
+ if (unresolved.some((u) => u.reason !== "missing" && u.reason !== "forbidden")) {
7128
+ this.scheduleSecretReresolve(this._secretRetryDelayMs);
7129
+ this._secretRetryDelayMs = Math.min(this._secretRetryDelayMs * 2, SECRET_RETRY_MAX_MS);
7130
+ }
7131
+ } else this._secretRetryDelayMs = SECRET_RETRY_FIRST_MS;
7132
+ }
7133
+ return value;
7134
+ }
7135
+ /** Re-resolve the config (a keychain-only change, or a retry) and apply it. */
7136
+ scheduleSecretReresolve(delayMs) {
7137
+ const timerOf = delayMs === SECRET_CHANGE_DEBOUNCE_MS ? "_secretChangeTimer" : "_secretRetryTimer";
7138
+ if (this[timerOf] !== null) return;
7139
+ const timer = setTimeout(() => {
7140
+ this[timerOf] = null;
7141
+ if (this._ctx === null) return;
7142
+ this.resolveConfig().then(() => this.onConfigChanged()).catch((err) => {
7143
+ this._ctx?.logger?.error?.("re-resolving secrets failed", { meta: { error: err instanceof Error ? err.message : String(err) } });
7144
+ });
7145
+ }, delayMs);
7146
+ timer.unref?.();
7147
+ this[timerOf] = timer;
7148
+ }
6482
7149
  /**
6483
7150
  * Wrap `ctx.settings.readAddonStore()` with a short retry budget so a
6484
7151
  * transient settings-store outage (mid-restart of sqlite-settings, tsx-watch
@@ -7054,6 +7721,69 @@ method(object({ deviceId: number() }), array(StreamSourceEntrySchema)), method(o
7054
7721
  kind: "mutation",
7055
7722
  auth: "admin"
7056
7723
  }), method(object({ deviceId: number() }), unknown().nullable()), method(object({ deviceId: number() }), RawStateResultSchema.nullable(), { auth: "protected" });
7724
+ function defOf(schema) {
7725
+ return schema._zod?.def ?? {};
7726
+ }
7727
+ function declaredHere(schema) {
7728
+ return globalRegistry.get(schema)?.secret === true;
7729
+ }
7730
+ /** Wrapper kinds whose `innerType` is the field itself. */
7731
+ var WRAPPERS = new Set([
7732
+ "optional",
7733
+ "nullable",
7734
+ "default",
7735
+ "prefault",
7736
+ "catch",
7737
+ "readonly",
7738
+ "nonoptional"
7739
+ ]);
7740
+ /**
7741
+ * The schema layers that make up ONE field: the schema itself and every
7742
+ * wrapper below it (optional / default / nullable / readonly / catch), plus
7743
+ * both sides of a pipe (`z.preprocess` puts the real schema on `out`,
7744
+ * `.transform` on `in`).
7745
+ */
7746
+ function layersOf(schema) {
7747
+ const out = [];
7748
+ const queue = [schema];
7749
+ while (queue.length > 0) {
7750
+ const s = queue.shift();
7751
+ if (!s || out.includes(s)) continue;
7752
+ out.push(s);
7753
+ const def = defOf(s);
7754
+ if (def.type !== void 0 && WRAPPERS.has(def.type) && def.innerType) queue.push(def.innerType);
7755
+ if (def.type === "pipe") {
7756
+ if (def.in) queue.push(def.in);
7757
+ if (def.out) queue.push(def.out);
7758
+ }
7759
+ }
7760
+ return out;
7761
+ }
7762
+ /** True when any layer of this field declares `.meta({ secret: true })`. */
7763
+ function isZodSecret(schema) {
7764
+ return layersOf(schema).some(declaredHere);
7765
+ }
7766
+ /**
7767
+ * Every declared secret path in a config schema: dotted keys, `[]` for "each
7768
+ * element of this array" (`connection.password`, `rows[].token`). A declared
7769
+ * object or array is reported as one path and not descended into — everything
7770
+ * under it is secret.
7771
+ */
7772
+ function collectZodSecretPaths(schema, prefix = "") {
7773
+ if (isZodSecret(schema)) return prefix.length > 0 ? [prefix] : [];
7774
+ const paths = [];
7775
+ for (const layer of layersOf(schema)) {
7776
+ const def = defOf(layer);
7777
+ if (def.type === "object" && def.shape) for (const [key, child] of Object.entries(def.shape)) paths.push(...collectZodSecretPaths(child, prefix ? `${prefix}.${key}` : key));
7778
+ else if (def.type === "array" && def.element) paths.push(...collectZodSecretPaths(def.element, `${prefix}[]`));
7779
+ else if (def.type === "union" && def.options) for (const option of def.options) paths.push(...collectZodSecretPaths(option, prefix));
7780
+ else if (def.type === "intersection") {
7781
+ if (def.left) paths.push(...collectZodSecretPaths(def.left, prefix));
7782
+ if (def.right) paths.push(...collectZodSecretPaths(def.right, prefix));
7783
+ }
7784
+ }
7785
+ return [...new Set(paths)];
7786
+ }
7057
7787
  //#endregion
7058
7788
  //#region ../types/dist/err-msg-DX6i_MY4.mjs
7059
7789
  var DeviceType = /* @__PURE__ */ function(DeviceType) {
@@ -14133,6 +14863,196 @@ id: union([string(), number()]) }), {
14133
14863
  kind: "mutation",
14134
14864
  auth: "admin"
14135
14865
  });
14866
+ /**
14867
+ * `keychain` — the hub's encrypted store of secret values (D787).
14868
+ *
14869
+ * Settings blobs never hold a secret: they hold a marker
14870
+ * `{"$secret":"secret://<owner>/<scope>/<fieldPath>","v":1}` and the value
14871
+ * lives here, AES-256-GCM under a data key that a master key wraps. This cap
14872
+ * is the OWNER's door to its own values: every method is owner-checked
14873
+ * against the CALLER, never against anything the caller claims.
14874
+ *
14875
+ * Who the caller is: the transport stamps `callerAddonId` into the args of a
14876
+ * call that crossed a process (the parent `LocalChildRegistry` from the UDS
14877
+ * connection, the agent from its child's connection carried in
14878
+ * `$hub-cap-fwd`'s envelope). A stamp always overwrites; a wire call with no
14879
+ * stamp has its claim stripped. Only a hub in-process caller may state its own
14880
+ * identity — `ctx.secrets` does that with the addon id closed over. This is
14881
+ * identity against BUGS and misrouting, not against a malicious addon (every
14882
+ * runner is the same OS user): see the threat model in
14883
+ * `docs/design/2026-10-08-secrets-keychain.md`.
14884
+ *
14885
+ * `callerAddonId` is deliberately NOT in any input schema: the tRPC router
14886
+ * parses the input, so a session can never supply it, and the internal mount
14887
+ * floors every method to admin anyway (D240).
14888
+ *
14889
+ * Internal: addons reach it through `ctx.secrets`, never directly.
14890
+ */
14891
+ /** Why a value cannot be served right now. Never folded into "missing". */
14892
+ var KeychainUnavailableReasonSchema = _enum([
14893
+ "key-missing",
14894
+ "wrong-key",
14895
+ "key-file-unreadable",
14896
+ "store-unavailable",
14897
+ "not-initialized",
14898
+ "decrypt-failed"
14899
+ ]);
14900
+ var KeychainStateSchema = discriminatedUnion("state", [object({ state: literal("ready") }), object({
14901
+ state: literal("locked"),
14902
+ reason: KeychainUnavailableReasonSchema
14903
+ })]);
14904
+ var KeychainResolveEntrySchema = discriminatedUnion("kind", [
14905
+ object({
14906
+ kind: literal("value"),
14907
+ value: string(),
14908
+ version: number().int()
14909
+ }),
14910
+ object({ kind: literal("missing") }),
14911
+ object({
14912
+ kind: literal("unavailable"),
14913
+ reason: KeychainUnavailableReasonSchema
14914
+ }),
14915
+ object({ kind: literal("forbidden") })
14916
+ ]);
14917
+ var KeychainResolveResultSchema = record(string(), KeychainResolveEntrySchema);
14918
+ /** Metadata of one stored value — never the value. */
14919
+ var KeychainSecretMetaSchema = object({
14920
+ ref: string(),
14921
+ owner: string(),
14922
+ /** Formatted scope (`global`, `node/<id>`, `device/<id>`, …). */
14923
+ scope: string(),
14924
+ fieldPath: string(),
14925
+ version: number().int(),
14926
+ createdAt: number(),
14927
+ updatedAt: number(),
14928
+ /** `addon:<id>` | `user:<id>` | `system`. */
14929
+ updatedBy: string(),
14930
+ /** Coarse — written at most once an hour per ref. `null` = never read. */
14931
+ lastReadAt: number().nullable()
14932
+ });
14933
+ var RefListSchema = array(string().min(1)).max(512);
14934
+ method(object({
14935
+ ref: string().min(1),
14936
+ value: string().min(1)
14937
+ }), object({
14938
+ ref: string(),
14939
+ version: number().int()
14940
+ }), {
14941
+ kind: "mutation",
14942
+ auth: "admin"
14943
+ }), method(object({ refs: RefListSchema }), KeychainResolveResultSchema, { auth: "admin" }), method(object({ refs: RefListSchema }), object({ deleted: number().int() }), {
14944
+ kind: "mutation",
14945
+ auth: "admin"
14946
+ }), method(object({}), array(KeychainSecretMetaSchema).readonly(), { auth: "admin" }), method(object({}), KeychainStateSchema, { auth: "admin" });
14947
+ var KeychainKeySourceSchema = object({
14948
+ kind: _enum([
14949
+ "config-file",
14950
+ "previous-config-file",
14951
+ "platform",
14952
+ "default-file"
14953
+ ]),
14954
+ /** File sources only — a path is not a secret. */
14955
+ path: string().optional(),
14956
+ /**
14957
+ * True when a whole-volume backup of the data directory carries this key
14958
+ * next to the database it protects (the default file). The page warns.
14959
+ */
14960
+ sharesBackupWithDatabase: boolean()
14961
+ });
14962
+ var KeychainStatusSchema = object({
14963
+ keychain: KeychainStateSchema,
14964
+ /** The source of the master key in use; `null` while locked. */
14965
+ keySource: KeychainKeySourceSchema.nullable(),
14966
+ /** The source configured to be primary — differs from `keySource` while a rotation is pending. */
14967
+ configuredSource: KeychainKeySourceSchema,
14968
+ /** Short fingerprint of the master key in use (`HMAC(KEK, label)`, 16 hex). */
14969
+ fingerprint: string().nullable(),
14970
+ activeKeyId: string().nullable(),
14971
+ /**
14972
+ * The keychain unlocked with a NON-primary source: the configured primary
14973
+ * key is not the one that wraps the data key yet. `rotateMasterKey` moves it.
14974
+ */
14975
+ rotationPending: boolean(),
14976
+ /** Wrapped copies of the data key under a previous master key, kept until purged. */
14977
+ retiredWraps: number().int(),
14978
+ recoveryKeyDownloadedAt: number().nullable(),
14979
+ secretCount: number().int()
14980
+ });
14981
+ /**
14982
+ * Whether a stored value is still pointed at by its owner's settings.
14983
+ * `unknown` is a first-class answer: a scope whose blob could not be read is
14984
+ * never reported as an orphan (and never deleted as one).
14985
+ */
14986
+ var KeychainSecretUsageSchema = _enum([
14987
+ "in-use",
14988
+ "orphan",
14989
+ "unknown"
14990
+ ]);
14991
+ var KeychainAdminSecretSchema = KeychainSecretMetaSchema.extend({ usage: KeychainSecretUsageSchema });
14992
+ var KeychainAuditActionSchema = _enum([
14993
+ "put",
14994
+ "delete",
14995
+ "reveal",
14996
+ "rotate-master-key",
14997
+ "purge-retired-keys",
14998
+ "download-recovery-key",
14999
+ "delete-orphans",
15000
+ "reset",
15001
+ "initialize"
15002
+ ]);
15003
+ var KeychainAuditEntrySchema = object({
15004
+ id: string(),
15005
+ at: number(),
15006
+ action: KeychainAuditActionSchema,
15007
+ /** `addon:<id>` | `user:<id>` | `system`. */
15008
+ actor: string(),
15009
+ ref: string().nullable(),
15010
+ detail: string().nullable()
15011
+ });
15012
+ 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({
15013
+ value: string(),
15014
+ version: number().int()
15015
+ }), {
15016
+ kind: "mutation",
15017
+ auth: "admin",
15018
+ caller: "required"
15019
+ }), method(object({ refs: array(string().min(1)).max(1e3) }), object({
15020
+ deleted: array(string()).readonly(),
15021
+ kept: array(object({
15022
+ ref: string(),
15023
+ usage: KeychainSecretUsageSchema
15024
+ })).readonly()
15025
+ }), {
15026
+ kind: "mutation",
15027
+ auth: "admin",
15028
+ caller: "required"
15029
+ }), method(object({}), object({
15030
+ fingerprint: string(),
15031
+ keySource: KeychainKeySourceSchema
15032
+ }), {
15033
+ kind: "mutation",
15034
+ auth: "admin",
15035
+ caller: "required"
15036
+ }), method(object({}), object({ purged: number().int() }), {
15037
+ kind: "mutation",
15038
+ auth: "admin",
15039
+ caller: "required"
15040
+ }), method(object({}), object({
15041
+ key: string(),
15042
+ fingerprint: string(),
15043
+ keySource: KeychainKeySourceSchema
15044
+ }), {
15045
+ kind: "mutation",
15046
+ auth: "admin",
15047
+ caller: "required"
15048
+ }), method(object({ confirm: literal("RESET KEYCHAIN") }), object({
15049
+ archivedCollection: string().nullable(),
15050
+ archived: number().int()
15051
+ }), {
15052
+ kind: "mutation",
15053
+ auth: "admin",
15054
+ caller: "required"
15055
+ });
14136
15056
  method(_void(), object({
14137
15057
  id: string(),
14138
15058
  name: string(),
@@ -15488,7 +16408,11 @@ var DeviceRegisterPayloadSchema = object({
15488
16408
  var DeviceRemovePayloadSchema = object({ deviceId: number() });
15489
16409
  var DevicePersistConfigPayloadSchema = object({
15490
16410
  deviceId: number(),
15491
- data: record(string(), unknown())
16411
+ data: record(string(), unknown()),
16412
+ /** The paths the device's schema declares secret (D783), when the caller
16413
+ * knows them — those values are kept in the keychain, not the blob (D787).
16414
+ * Absent: the paths the device last reported at `registerDevice` apply. */
16415
+ secretConfigPaths: array(string()).optional()
15492
16416
  });
15493
16417
  /** What a migration actually did, per switch. `unreachable` is a first-class
15494
16418
  * answer: a camera that could not be asked is not a camera that was silenced. */
@@ -22505,8 +23429,23 @@ var RetrainMacroClassSchema = _enum([
22505
23429
  ]);
22506
23430
  /** A subject to learn, or a phantom to unlearn (taught by OMISSION). */
22507
23431
  var RetrainAnnotationKindSchema = _enum(["subject", "model_error"]);
22508
- /** Did a human draw this box, or did the assist propose it? */
22509
- var RetrainAnnotationSourceSchema = _enum(["operator", "assist"]);
23432
+ /**
23433
+ * Where a box came from. A machine-sourced box is a DRAFT on the page until
23434
+ * the operator confirms it; once saved it keeps its source as provenance.
23435
+ *
23436
+ * - `operator` — drawn by hand.
23437
+ * - `assist` — proposed by a detector run on the copy (the camera's own
23438
+ * model, or a larger teacher model).
23439
+ * - `pipeline` — the box the live pipeline actually drew on that frame, read
23440
+ * back from the track store (never a re-run).
23441
+ * - `llm` — proposed by a vision-capable LLM profile.
23442
+ */
23443
+ var RetrainAnnotationSourceSchema = _enum([
23444
+ "operator",
23445
+ "assist",
23446
+ "pipeline",
23447
+ "llm"
23448
+ ]);
22510
23449
  /** Normalised `[0,1]` rectangle against the FULL frame — the canonical form. */
22511
23450
  var RetrainBboxSchema = object({
22512
23451
  x: number(),
@@ -22524,7 +23463,8 @@ var RetrainBboxSchema = object({
22524
23463
  */
22525
23464
  var RetrainAnnotationSchema = object({
22526
23465
  id: string(),
22527
- trackId: string(),
23466
+ /** The frame's track. Absent on a recording still, which has none. */
23467
+ trackId: string().optional(),
22528
23468
  deviceId: number(),
22529
23469
  /** The COPY in retrain storage — never the source track's media key. */
22530
23470
  mediaKey: string(),
@@ -22573,13 +23513,47 @@ var RetrainFrameCandidateSchema = object({
22573
23513
  * fail, whatever became of the original. */
22574
23514
  copied: boolean()
22575
23515
  });
23516
+ /**
23517
+ * One box the live pipeline drew on a copied frame — what a correction starts
23518
+ * from. Derived when the frame is listed, from the track store: the subject
23519
+ * box recorded on the source media row when there is one, else the track
23520
+ * position nearest the frame's capture time. Never stored as an annotation
23521
+ * until the operator confirms it.
23522
+ */
23523
+ var RetrainPipelineBoxSchema = object({
23524
+ /** Normalised `[0,1]` against the full frame. */
23525
+ bbox: RetrainBboxSchema,
23526
+ macroClass: RetrainMacroClassSchema,
23527
+ label: string().optional(),
23528
+ subLabel: string().optional(),
23529
+ /** The detection score of the position used, when it was recorded. */
23530
+ score: number().optional(),
23531
+ /** The root model that produced the track, when it was recorded. */
23532
+ modelId: string().optional(),
23533
+ trackId: string(),
23534
+ /** `subject-box`: recorded on this very frame. `position`: the track's
23535
+ * position nearest the capture time, `deltaMs` away. */
23536
+ basis: _enum(["subject-box", "position"]),
23537
+ deltaMs: number()
23538
+ });
23539
+ /**
23540
+ * Where a retrain frame came from: a TRACK's stored media (copy-on-select),
23541
+ * or the RECORDING at an instant — the frame a model saw nothing in has no
23542
+ * track at all.
23543
+ */
23544
+ var RetrainFrameOriginSchema = _enum(["track", "recording"]);
22576
23545
  /** A frame the dataset OWNS: bytes copied at selection time. */
22577
23546
  var RetrainFrameSchema = object({
22578
23547
  frameId: string(),
22579
23548
  deviceId: number(),
22580
- trackId: string(),
22581
- /** Provenance only. It may already point at nothing — that is expected. */
22582
- sourceMediaId: number().int(),
23549
+ origin: RetrainFrameOriginSchema,
23550
+ /** The track it was copied from. Absent on a recording still. */
23551
+ trackId: string().optional(),
23552
+ /** Provenance only. It may already point at nothing — that is expected.
23553
+ * Absent on a recording still. */
23554
+ sourceMediaId: number().int().optional(),
23555
+ /** A recording still: the playhead instant it was taken at. */
23556
+ epochMs: number().optional(),
22583
23557
  sourceKind: MediaFileKindEnum,
22584
23558
  sizeBytes: number().int(),
22585
23559
  width: number().int(),
@@ -22590,7 +23564,12 @@ var RetrainFrameSchema = object({
22590
23564
  /** The operator's "every subject in this frame is boxed". Detector
22591
23565
  * evaluation keeps only complete frames: an unboxed subject would count as
22592
23566
  * a false positive. */
22593
- complete: boolean()
23567
+ complete: boolean(),
23568
+ /** The boxes the pipeline drew on this frame. Present on list answers;
23569
+ * empty when nothing the track store holds can be placed on it. */
23570
+ pipelineBoxes: array(RetrainPipelineBoxSchema).readonly().optional(),
23571
+ /** The named collections this frame belongs to. Present on list answers. */
23572
+ collectionIds: array(string()).readonly().optional()
22594
23573
  });
22595
23574
  /** Why a copy-on-select could not be honoured — named, never a silent skip. */
22596
23575
  var RetrainCopyRefusalSchema = _enum([
@@ -22621,6 +23600,8 @@ var RetrainFrameListSchema = object({
22621
23600
  var RetrainExportFilterSchema = object({
22622
23601
  deviceIds: array(number()).optional(),
22623
23602
  frameIds: array(string()).max(2e4).optional(),
23603
+ /** Only frames in at least one of these named collections. */
23604
+ collectionIds: array(string()).max(200).optional(),
22624
23605
  batchId: string().optional(),
22625
23606
  /** Only frames the operator marked complete (all subjects boxed). */
22626
23607
  completeOnly: boolean().optional()
@@ -22685,6 +23666,109 @@ var RetrainAssistResultSchema = discriminatedUnion("kind", [object({
22685
23666
  reason: string(),
22686
23667
  detail: string().optional()
22687
23668
  })]);
23669
+ /** A named set over the retrain corpus — membership only, it owns no pixels. */
23670
+ var RetrainCollectionSchema = object({
23671
+ id: string(),
23672
+ name: string(),
23673
+ createdAt: number(),
23674
+ frameCount: number().int()
23675
+ });
23676
+ var RetrainCollectionCreateResultSchema = discriminatedUnion("kind", [object({
23677
+ kind: literal("created"),
23678
+ collection: RetrainCollectionSchema
23679
+ }), object({
23680
+ kind: literal("refused"),
23681
+ reason: _enum(["empty-name", "duplicate-name"])
23682
+ })]);
23683
+ var RetrainCollectionRenameResultSchema = discriminatedUnion("kind", [object({
23684
+ kind: literal("renamed"),
23685
+ collection: RetrainCollectionSchema
23686
+ }), object({
23687
+ kind: literal("refused"),
23688
+ reason: _enum([
23689
+ "empty-name",
23690
+ "duplicate-name",
23691
+ "unknown-collection"
23692
+ ])
23693
+ })]);
23694
+ /**
23695
+ * The outcome of adding the frame at a recording instant. Every refusal is
23696
+ * named: `still-unavailable` (not recording, a gap, or an undecodable frame —
23697
+ * `detail` says which), `still-busy` (the recorder is at its decode bound; try
23698
+ * again), `unreadable-image`, `write-failed`, `unknown-collection`.
23699
+ */
23700
+ var AddRetrainFrameFromRecordingResultSchema = discriminatedUnion("kind", [object({
23701
+ kind: literal("added"),
23702
+ collectionId: string(),
23703
+ frame: RetrainFrameSchema,
23704
+ /** The moment was already in the dataset; nothing was decoded. */
23705
+ reused: boolean()
23706
+ }), object({
23707
+ kind: literal("refused"),
23708
+ reason: _enum([
23709
+ "unknown-collection",
23710
+ "still-unavailable",
23711
+ "still-busy",
23712
+ "unreadable-image",
23713
+ "write-failed"
23714
+ ]),
23715
+ detail: string().optional()
23716
+ })]);
23717
+ /** A vision LLM profile the AI assist may use, and where it sends the frame. */
23718
+ var RetrainAssistProfileSchema = object({
23719
+ id: string(),
23720
+ name: string(),
23721
+ model: string(),
23722
+ kind: string(),
23723
+ /** `true` when the frame would leave the house (a cloud vendor, or an
23724
+ * endpoint that is not on the local network). The page confirms each such
23725
+ * run, and the provider refuses one without `allowCloud`. */
23726
+ leavesHouse: boolean()
23727
+ });
23728
+ /** A box the AI assist proposed: a draft, plus the model's own reason. */
23729
+ var RetrainLlmProposalSchema = RetrainAnnotationDraftSchema.extend({ reason: string() });
23730
+ /** What the AI assist said about a box that was already on the canvas. */
23731
+ var RetrainLlmReviewSchema = object({
23732
+ /** The `ref` the page sent the box under. */
23733
+ ref: string(),
23734
+ verdict: _enum([
23735
+ "confirmed",
23736
+ "wrong-class",
23737
+ "not-an-object",
23738
+ "uncertain"
23739
+ ]),
23740
+ suggestedClass: RetrainMacroClassSchema.optional(),
23741
+ reason: string()
23742
+ });
23743
+ /**
23744
+ * The AI assist's answer. `proposed` carries drafts (`source: 'llm'`, the
23745
+ * model and its confidence) and reviews; items the model got wrong (a box off
23746
+ * the frame, an unasked class, an unknown ref) are dropped and counted in
23747
+ * `rejected`. A whole answer that is not the schema is `malformed-answer`.
23748
+ */
23749
+ var RetrainLlmAssistResultSchema = discriminatedUnion("kind", [object({
23750
+ kind: literal("proposed"),
23751
+ profileId: string(),
23752
+ model: string(),
23753
+ /** The frame was sent outside the house for this answer. */
23754
+ leftHouse: boolean(),
23755
+ proposals: array(RetrainLlmProposalSchema).readonly(),
23756
+ reviews: array(RetrainLlmReviewSchema).readonly(),
23757
+ rejected: number().int()
23758
+ }), object({
23759
+ kind: literal("refused"),
23760
+ reason: _enum([
23761
+ "unknown-frame",
23762
+ "unreadable-frame",
23763
+ "unknown-profile",
23764
+ "profile-disabled",
23765
+ "no-vision",
23766
+ "cloud-not-confirmed",
23767
+ "llm-error",
23768
+ "malformed-answer"
23769
+ ]),
23770
+ detail: string().optional()
23771
+ })]);
22688
23772
  /** The outcome of a lifecycle move owned by the retrain page. */
22689
23773
  var RetrainTransitionResultSchema = object({
22690
23774
  trackId: string(),
@@ -23402,7 +24486,7 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
23402
24486
  auth: "admin"
23403
24487
  }), method(object({
23404
24488
  deviceId: number(),
23405
- trackId: string(),
24489
+ trackId: string().optional(),
23406
24490
  frameId: string()
23407
24491
  }), object({
23408
24492
  removed: boolean(),
@@ -23419,7 +24503,8 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
23419
24503
  auth: "admin"
23420
24504
  }), method(object({
23421
24505
  deviceId: number(),
23422
- trackId: string(),
24506
+ /** The frame's track, when it has one — checked against the frame. */
24507
+ trackId: string().optional(),
23423
24508
  frameId: string(),
23424
24509
  subject: RetrainAssistSubjectSchema,
23425
24510
  /** Which node runs it. Absent ⇒ wherever an unowned call lands. */
@@ -23427,12 +24512,16 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
23427
24512
  }), RetrainAssistResultSchema, {
23428
24513
  kind: "mutation",
23429
24514
  auth: "admin"
23430
- }), method(object({ trackId: string() }), array(RetrainAnnotationSchema).readonly(), {
24515
+ }), method(object({
24516
+ trackId: string().optional(),
24517
+ frameIds: array(string()).max(2e3).optional()
24518
+ }), array(RetrainAnnotationSchema).readonly(), {
23431
24519
  kind: "query",
23432
24520
  auth: "admin"
23433
24521
  }), method(object({
23434
24522
  deviceId: number(),
23435
- trackId: string(),
24523
+ /** The frame's track, when it has one — checked against the frame. */
24524
+ trackId: string().optional(),
23436
24525
  frameId: string(),
23437
24526
  annotations: array(RetrainAnnotationDraftSchema)
23438
24527
  }), array(RetrainAnnotationSchema).readonly(), {
@@ -23455,7 +24544,7 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
23455
24544
  auth: "admin"
23456
24545
  }), method(object({
23457
24546
  deviceId: number(),
23458
- trackId: string(),
24547
+ trackId: string().optional(),
23459
24548
  frameId: string(),
23460
24549
  complete: boolean()
23461
24550
  }), RetrainFrameSchema, {
@@ -23469,6 +24558,74 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
23469
24558
  kind: "mutation",
23470
24559
  auth: "admin",
23471
24560
  timeoutMs: 60 * 6e4
24561
+ }), method(object({}), array(RetrainAssistProfileSchema).readonly(), {
24562
+ kind: "query",
24563
+ auth: "admin"
24564
+ }), method(object({
24565
+ deviceId: number(),
24566
+ trackId: string().optional(),
24567
+ frameId: string(),
24568
+ profileId: string(),
24569
+ classes: array(RetrainMacroClassSchema).min(1),
24570
+ boxes: array(object({
24571
+ ref: string(),
24572
+ bbox: RetrainBboxSchema,
24573
+ macroClass: RetrainMacroClassSchema,
24574
+ label: string().optional()
24575
+ })).max(50),
24576
+ allowCloud: boolean()
24577
+ }), RetrainLlmAssistResultSchema, {
24578
+ kind: "mutation",
24579
+ auth: "admin",
24580
+ timeoutMs: 18e4
24581
+ }), method(object({ name: string().max(120) }), RetrainCollectionCreateResultSchema, {
24582
+ kind: "mutation",
24583
+ auth: "admin"
24584
+ }), method(object({}), array(RetrainCollectionSchema).readonly(), {
24585
+ kind: "query",
24586
+ auth: "admin"
24587
+ }), method(object({
24588
+ id: string(),
24589
+ name: string().max(120)
24590
+ }), RetrainCollectionRenameResultSchema, {
24591
+ kind: "mutation",
24592
+ auth: "admin"
24593
+ }), method(object({ id: string() }), object({
24594
+ deleted: boolean(),
24595
+ removedFrames: number().int()
24596
+ }), {
24597
+ kind: "mutation",
24598
+ auth: "admin"
24599
+ }), method(object({
24600
+ collectionId: string(),
24601
+ deviceId: number(),
24602
+ epochMs: number()
24603
+ }), AddRetrainFrameFromRecordingResultSchema, {
24604
+ kind: "mutation",
24605
+ auth: "admin",
24606
+ timeoutMs: 6e4
24607
+ }), method(object({
24608
+ collectionId: string(),
24609
+ frameIds: array(string()).min(1).max(500)
24610
+ }), object({
24611
+ added: number().int(),
24612
+ alreadyMember: number().int(),
24613
+ unknownFrameIds: array(string()).readonly()
24614
+ }), {
24615
+ kind: "mutation",
24616
+ auth: "admin"
24617
+ }), method(object({
24618
+ collectionId: string(),
24619
+ frameId: string()
24620
+ }), object({
24621
+ removed: boolean(),
24622
+ deletedFrame: boolean()
24623
+ }), {
24624
+ kind: "mutation",
24625
+ auth: "admin"
24626
+ }), method(object({ collectionId: string() }), array(RetrainFrameSchema).readonly(), {
24627
+ kind: "query",
24628
+ auth: "admin"
23472
24629
  }), method(object({
23473
24630
  /** Which of the three event tables owns the row. */
23474
24631
  ownerType: EventOwnerTypeSchema,
@@ -24092,13 +25249,31 @@ var RecommendationReasonSchema = discriminatedUnion("kind", [
24092
25249
  object({
24093
25250
  kind: literal("no-family-build"),
24094
25251
  format: ModelFormatSchema$1
25252
+ }),
25253
+ object({
25254
+ kind: literal("kept-custom-pin"),
25255
+ modelId: string(),
25256
+ deviceKey: string()
24095
25257
  })
24096
25258
  ]);
25259
+ /** Why a device is left exactly as it is, whatever the plan would pick (D786). */
25260
+ var KeptReasonSchema = _enum(["custom-pin"]);
25261
+ /**
25262
+ * Where a choice's latency came from (D791): this node's own benchmark
25263
+ * result, or the hardware-class table. Measured on the node beats the table.
25264
+ */
25265
+ var LatencySourceSchema = discriminatedUnion("kind", [object({ kind: literal("table") }), object({
25266
+ kind: literal("node-benchmark"),
25267
+ resultId: string(),
25268
+ measuredAtMs: number()
25269
+ })]);
24097
25270
  var DeviceModelChoiceSchema = object({
24098
25271
  modelId: string(),
24099
25272
  p50Ms: number(),
24100
25273
  fps: number(),
24101
25274
  measured: boolean(),
25275
+ /** Absent on a plan from before D791 — read as the table. */
25276
+ source: LatencySourceSchema.optional(),
24102
25277
  /** Parallel sessions at the camera rate with the headroom kept free: ⌊fps × (1 − headroom) / camera fps⌋. */
24103
25278
  capacitySessions: number(),
24104
25279
  personRecall: number()
@@ -24109,6 +25284,8 @@ var DeviceRecommendationSchema = object({
24109
25284
  enabled: boolean(),
24110
25285
  available: boolean(),
24111
25286
  chosen: DeviceModelChoiceSchema.nullable(),
25287
+ /** Present when the device is kept as is: Apply writes nothing on it. */
25288
+ kept: KeptReasonSchema.optional(),
24112
25289
  reasons: array(RecommendationReasonSchema).readonly()
24113
25290
  });
24114
25291
  var NodeRecommendationSchema = object({
@@ -24162,6 +25339,17 @@ var AutoTuneWarningSchema = discriminatedUnion("kind", [
24162
25339
  kind: literal("coral-enabled"),
24163
25340
  nodeId: string(),
24164
25341
  deviceKey: string()
25342
+ }),
25343
+ object({
25344
+ kind: literal("custom-pin-kept"),
25345
+ nodeId: string(),
25346
+ deviceKey: string().nullable(),
25347
+ deviceId: number().nullable(),
25348
+ modelId: string()
25349
+ }),
25350
+ object({
25351
+ kind: literal("custom-registry-unreadable"),
25352
+ error: string()
24165
25353
  })
24166
25354
  ]);
24167
25355
  var AutoTuneOptionsSchema = object({
@@ -24340,13 +25528,14 @@ var SuggestSharesResultSchema = object({
24340
25528
  nodes: array(SuggestedNodeShareSchema).readonly()
24341
25529
  });
24342
25530
  /**
24343
- * Where the node and device shares come from (D750, D755).
24344
- * - `hardware` (default) — computed by the system from each node's static
24345
- * capacity (its accelerators at their Auto tune models, from the measured
24346
- * latency table), recomputed whenever a node or device joins, leaves, is
24347
- * switched on or off, or changes model. No load input.
24348
- * - `benchmark` — the same, from each node's measured capacity (node
24349
- * benchmark results); a node without results falls back to `hardware`.
25531
+ * Where the node and device shares come from (D750, D755, D791).
25532
+ * - `benchmark` (default since D791) — each node's capacity as its own node
25533
+ * benchmark measured it; a node without fresh results is sized from
25534
+ * `hardware` and says so. Measured on the node beats the table.
25535
+ * - `hardware` — computed from each node's static capacity only (its
25536
+ * accelerators at their Auto tune models, from the latency table).
25537
+ * Both are recomputed whenever a node or device joins, leaves, is switched
25538
+ * on or off, changes model, or a benchmark result is written. No load input.
24350
25539
  * - `manual` — the operator's stored sliders.
24351
25540
  * Either way a node or device that cannot take sessions gives its share to
24352
25541
  * the others in proportion; the stored values are never rewritten for that.
@@ -24395,6 +25584,362 @@ var EffectiveSharesSchema = object({
24395
25584
  nodeWeights: record(string(), number()),
24396
25585
  deviceWeights: record(string(), record(string(), number()))
24397
25586
  });
25587
+ /**
25588
+ * Wire shapes of the node benchmark (D791): the operator's plan, the
25589
+ * preflight the confirmation shows, the run the orchestrator owns, what the
25590
+ * measuring runner reports, and the result rows Auto tune and the automatic
25591
+ * shares read.
25592
+ *
25593
+ * ONE node at a time, owned by the pipeline orchestrator. While a run is
25594
+ * active the cluster is in BENCHMARK MODE for that node: it is not a
25595
+ * detection candidate, camera pins naming it are ignored so its sessions move
25596
+ * elsewhere, and both come back when the mode ends — after a crash or a hub
25597
+ * restart too (a persisted manifest, reconciled against the registry).
25598
+ *
25599
+ * Two measurements, both on the node, driven by its own runner (frames never
25600
+ * cross a process at frame rate, D9):
25601
+ * - `device` — one accelerator × one candidate detector, root only, open
25602
+ * loop: how many streams at the camera rate it carries inside the frame
25603
+ * interval;
25604
+ * - `pipeline` — the chosen detector plus the operator's detail steps
25605
+ * (faces, plates, classifiers, CLIP…), on varied frames from the bench
25606
+ * clip: how many parallel sessions the node carries before latency, drops,
25607
+ * CPU, RAM or the event loop give out.
25608
+ */
25609
+ /** Defaults and bounds, one place. */
25610
+ var NODE_BENCHMARK_DEFAULTS = {
25611
+ fpsPerStream: 10,
25612
+ budgetMinutes: 45,
25613
+ minBudgetMinutes: 10,
25614
+ maxBudgetMinutes: 120,
25615
+ /** A result older than this no longer beats the table. */
25616
+ staleAfterDays: 30,
25617
+ /** Warm-in per ramp step (not accounted). */
25618
+ settleSec: 5,
25619
+ /** Accounted window per ramp step. */
25620
+ measureSec: 20,
25621
+ /** Longest the drain may take before the run is refused. */
25622
+ drainTimeoutSec: 120,
25623
+ /** Candidate models per device in one run. */
25624
+ maxModelsPerDevice: 6
25625
+ };
25626
+ /** The two measurements a run can make. */
25627
+ var NodeBenchmarkPhaseSchema = _enum(["device", "pipeline"]);
25628
+ var NodeBenchmarkDevicePlanSchema = object({
25629
+ /** `<backend>:<device>` — `openvino:npu`, `coreml:all`, `cpu`. */
25630
+ deviceKey: string().min(1),
25631
+ /**
25632
+ * Root detector candidates for the `device` measurement, in the order
25633
+ * measured. The FIRST is the one the `pipeline` measurement runs.
25634
+ */
25635
+ modelIds: array(string().min(1)).min(1).max(NODE_BENCHMARK_DEFAULTS.maxModelsPerDevice)
25636
+ });
25637
+ /** What the operator confirmed. */
25638
+ var NodeBenchmarkPlanSchema = object({
25639
+ nodeId: string().min(1),
25640
+ devices: array(NodeBenchmarkDevicePlanSchema).min(1),
25641
+ /** Which measurements run. At least one. */
25642
+ phases: array(NodeBenchmarkPhaseSchema).min(1).default(["device", "pipeline"]),
25643
+ /**
25644
+ * Detail steps (catalog step ids under the root: faces, plates,
25645
+ * classifiers, CLIP…) the `pipeline` measurement enables. The root
25646
+ * detector always runs.
25647
+ */
25648
+ steps: array(string().min(1)).default([]),
25649
+ /** Offered rate of one stream / session. */
25650
+ fpsPerStream: number().int().min(1).max(30).default(NODE_BENCHMARK_DEFAULTS.fpsPerStream),
25651
+ /** Hard deadline: the mode ends and the cluster is restored when it passes. */
25652
+ budgetMinutes: number().int().min(NODE_BENCHMARK_DEFAULTS.minBudgetMinutes).max(NODE_BENCHMARK_DEFAULTS.maxBudgetMinutes).default(NODE_BENCHMARK_DEFAULTS.budgetMinutes),
25653
+ /** Keep the models the run downloaded (default: delete what was not installed before). */
25654
+ keepDownloadedModels: boolean().default(false),
25655
+ /** Start although the other nodes' capacity does not cover the sessions running now. */
25656
+ acceptInsufficientHeadroom: boolean().default(false)
25657
+ });
25658
+ var NodeBenchmarkRefusalSchema = object({
25659
+ kind: _enum([
25660
+ "benchmark-active",
25661
+ "node-offline",
25662
+ "unknown-device",
25663
+ "no-phase",
25664
+ "insufficient-headroom"
25665
+ ]),
25666
+ detail: string(),
25667
+ overridable: boolean()
25668
+ });
25669
+ /** A camera whose detection leaves the node for the run. */
25670
+ var NodeBenchmarkMovingCameraSchema = object({
25671
+ deviceId: number(),
25672
+ /** Placed on the node now (a standing attach or a running session). */
25673
+ placedOnNode: boolean(),
25674
+ /** A node pin naming this node, ignored for the run. */
25675
+ pinnedToNode: boolean()
25676
+ });
25677
+ /** A camera that cannot leave: no other node can obtain its frames. */
25678
+ var NodeBenchmarkStayingCameraSchema = object({
25679
+ deviceId: number(),
25680
+ reason: literal("only-frame-source")
25681
+ });
25682
+ var NodeBenchmarkPreflightSchema = object({
25683
+ nodeId: string(),
25684
+ online: boolean(),
25685
+ moving: array(NodeBenchmarkMovingCameraSchema).readonly(),
25686
+ /** Keep running on the node during the run; the result is flagged contaminated. */
25687
+ staying: array(NodeBenchmarkStayingCameraSchema).readonly(),
25688
+ estimatedDurationMs: number(),
25689
+ /** The run ends and the cluster is restored at the latest after this long. */
25690
+ budgetMs: number(),
25691
+ phases: array(NodeBenchmarkPhaseSchema).readonly(),
25692
+ steps: array(string()).readonly(),
25693
+ devices: array(NodeBenchmarkDevicePlanSchema).readonly(),
25694
+ /** Parallel sessions the cluster runs now, and what the other nodes can carry. */
25695
+ headroom: object({
25696
+ sessionsNow: number(),
25697
+ otherNodesCapacitySessions: number().nullable()
25698
+ }),
25699
+ refusals: array(NodeBenchmarkRefusalSchema).readonly(),
25700
+ canStart: boolean()
25701
+ });
25702
+ /** Where the measuring runner is. */
25703
+ var NodeBenchProgressSchema = object({
25704
+ phase: _enum([
25705
+ "preparing",
25706
+ "device",
25707
+ "pipeline",
25708
+ "cleanup"
25709
+ ]),
25710
+ deviceKey: string().nullable(),
25711
+ modelId: string().nullable(),
25712
+ /** Streams (device) or sessions (pipeline) of the step running now. */
25713
+ load: number().nullable(),
25714
+ cellsDone: number(),
25715
+ cellsTotal: number(),
25716
+ message: string()
25717
+ });
25718
+ /** What limited a ramp. `none` = the ramp ran out of steps still passing. */
25719
+ var NodeBenchLimitSchema = _enum([
25720
+ "p95",
25721
+ "drops",
25722
+ "errors",
25723
+ "stall",
25724
+ "cpu",
25725
+ "ram",
25726
+ "none"
25727
+ ]);
25728
+ var NodeBenchRampStepSchema = object({
25729
+ load: number(),
25730
+ pass: boolean(),
25731
+ p95Ms: number(),
25732
+ dropRatio: number(),
25733
+ /** Completed frames per second over the accounted window. */
25734
+ fps: number(),
25735
+ cpuPct: number().nullable(),
25736
+ ramFreePct: number().nullable(),
25737
+ failReasons: array(string()).readonly()
25738
+ });
25739
+ var NodeBenchCellSchema = discriminatedUnion("phase", [object({
25740
+ phase: literal("device"),
25741
+ deviceKey: string(),
25742
+ modelId: string(),
25743
+ /** Single-stream latency (the K = 1 step). */
25744
+ p50Ms: number(),
25745
+ p95Ms: number(),
25746
+ p99Ms: number(),
25747
+ /** Frames per second sustained at the last passing step. */
25748
+ fps: number(),
25749
+ /** Streams at the camera rate the device carried inside the frame interval; 0 = not even one. */
25750
+ kMax: number(),
25751
+ limitedBy: NodeBenchLimitSchema,
25752
+ /** First call (model load + warm-up). */
25753
+ warmupMs: number(),
25754
+ ramp: array(NodeBenchRampStepSchema).readonly()
25755
+ }), object({
25756
+ phase: literal("pipeline"),
25757
+ deviceKey: string(),
25758
+ modelId: string(),
25759
+ steps: array(string()).readonly(),
25760
+ /** Parallel sessions at the camera rate the node carried; 0 = not even one. */
25761
+ maxSessions: number(),
25762
+ limitedBy: NodeBenchLimitSchema,
25763
+ /** Detail steps that produced at least one result on the clip — a step that never fired measured nothing. */
25764
+ stepsFired: array(string()).readonly(),
25765
+ warmupMs: number(),
25766
+ ramp: array(NodeBenchRampStepSchema).readonly()
25767
+ })]);
25768
+ /**
25769
+ * What a result was measured ON. A result whose fingerprint no longer matches
25770
+ * the node no longer beats the table.
25771
+ */
25772
+ var NodeBenchFingerprintSchema = object({
25773
+ pipelineVersion: string().nullable(),
25774
+ cpuModel: string().nullable(),
25775
+ ramGb: number().nullable(),
25776
+ os: string().nullable(),
25777
+ /** Per device: the pool the cells ran on (runtime + tuning). */
25778
+ pools: record(string(), object({
25779
+ runtime: string(),
25780
+ numWorkers: number(),
25781
+ concurrency: number(),
25782
+ batchMode: string()
25783
+ })).default({})
25784
+ });
25785
+ /** The frames the run used. */
25786
+ var NodeBenchClipSchema = object({
25787
+ /** `camstack-bench-v1` or `reference-images` (the fallback when the clip is not reachable). */
25788
+ id: string(),
25789
+ revision: string().nullable(),
25790
+ frames: number(),
25791
+ width: number(),
25792
+ height: number()
25793
+ });
25794
+ var NodeBenchRunnerInputSchema = object({
25795
+ runId: string().min(1),
25796
+ devices: array(NodeBenchmarkDevicePlanSchema).min(1),
25797
+ phases: array(NodeBenchmarkPhaseSchema).min(1),
25798
+ /** The full detail step tree root for the `pipeline` measurement is built on the node from these ids. */
25799
+ steps: array(string()).default([]),
25800
+ fpsPerStream: number().int().min(1).max(30),
25801
+ /** The runner stops on its own past this instant, whatever the hub does. */
25802
+ deadlineAtMs: number(),
25803
+ settleSec: number().min(0).max(60).default(NODE_BENCHMARK_DEFAULTS.settleSec),
25804
+ measureSec: number().min(2).max(300).default(NODE_BENCHMARK_DEFAULTS.measureSec),
25805
+ keepDownloadedModels: boolean().default(false)
25806
+ });
25807
+ var NodeBenchRunnerStateSchema = _enum([
25808
+ "running",
25809
+ "done",
25810
+ "failed",
25811
+ "aborted"
25812
+ ]);
25813
+ var NodeBenchRunnerStatusSchema = object({
25814
+ runId: string(),
25815
+ nodeId: string(),
25816
+ state: NodeBenchRunnerStateSchema,
25817
+ progress: NodeBenchProgressSchema.nullable(),
25818
+ /** Every finished cell so far — a run stopped half way keeps what it measured. */
25819
+ cells: array(NodeBenchCellSchema).readonly(),
25820
+ fingerprint: NodeBenchFingerprintSchema.nullable(),
25821
+ clip: NodeBenchClipSchema.nullable(),
25822
+ /** Cameras seen running on the node during the run (they share its pools). */
25823
+ activeCameraIds: array(number()).readonly(),
25824
+ /** Models the run downloaded and then deleted (not installed before). */
25825
+ deletedModels: array(string()).readonly(),
25826
+ error: string().nullable(),
25827
+ startedAtMs: number(),
25828
+ finishedAtMs: number().nullable()
25829
+ });
25830
+ var NodeBenchmarkStateSchema = _enum([
25831
+ "draining",
25832
+ "measuring",
25833
+ "restoring",
25834
+ "done",
25835
+ "failed",
25836
+ "aborted"
25837
+ ]);
25838
+ /** Why a run ended. */
25839
+ var NodeBenchmarkEndReasonSchema = _enum([
25840
+ "completed",
25841
+ "operator-abort",
25842
+ "deadline",
25843
+ "node-lost",
25844
+ "runner-lost",
25845
+ "hub-restart",
25846
+ "drain-timeout",
25847
+ "failed"
25848
+ ]);
25849
+ var NodeBenchmarkRunSchema = object({
25850
+ runId: string(),
25851
+ nodeId: string(),
25852
+ state: NodeBenchmarkStateSchema,
25853
+ plan: NodeBenchmarkPlanSchema,
25854
+ startedAtMs: number(),
25855
+ deadlineAtMs: number(),
25856
+ finishedAtMs: number().nullable(),
25857
+ endReason: NodeBenchmarkEndReasonSchema.nullable(),
25858
+ error: string().nullable(),
25859
+ /** Cameras moved off the node for the run. */
25860
+ moved: array(number()).readonly(),
25861
+ /** Cameras that stayed (their only frame source is the node). */
25862
+ staying: array(number()).readonly(),
25863
+ /** Something else ran on the node's pools during the run. */
25864
+ contaminated: boolean(),
25865
+ progress: NodeBenchProgressSchema.nullable(),
25866
+ resultIds: array(string()).readonly()
25867
+ });
25868
+ /** `getNodeBenchmarkStatus`: the active run (or the last one), and whether benchmark mode is on. */
25869
+ var NodeBenchmarkStatusSchema = object({
25870
+ /** The node the cluster is in benchmark mode for; null = none. */
25871
+ modeNodeId: string().nullable(),
25872
+ run: NodeBenchmarkRunSchema.nullable()
25873
+ });
25874
+ /**
25875
+ * One stored measurement — the only authority Auto tune and the automatic
25876
+ * shares read measured capacity from. Written by the orchestrator when a run
25877
+ * ends, never by anyone else.
25878
+ */
25879
+ var NodeBenchmarkResultSchema = object({
25880
+ id: string(),
25881
+ runId: string(),
25882
+ nodeId: string(),
25883
+ cell: NodeBenchCellSchema,
25884
+ fpsPerStream: number(),
25885
+ fingerprint: NodeBenchFingerprintSchema.nullable(),
25886
+ clip: NodeBenchClipSchema.nullable(),
25887
+ /** Other work shared the node's pools (a camera that could not move, or the hub's own duties). */
25888
+ contaminated: boolean(),
25889
+ stayingCameras: array(number()).readonly(),
25890
+ /** The run ended early; the cell itself completed. */
25891
+ partialRun: boolean(),
25892
+ measuredAtMs: number()
25893
+ });
25894
+ var ListNodeBenchmarkResultsInputSchema = object({
25895
+ nodeId: string().optional(),
25896
+ deviceKey: string().optional()
25897
+ });
25898
+ /** A result with its standing today: does it still beat the table? */
25899
+ var NodeBenchmarkResultViewSchema = NodeBenchmarkResultSchema.extend({
25900
+ /** `fresh` beats the table; `stale` falls back to it; `superseded` = a newer row covers the same cell. */
25901
+ standing: _enum([
25902
+ "fresh",
25903
+ "stale",
25904
+ "superseded"
25905
+ ]),
25906
+ staleWhy: _enum([
25907
+ "age",
25908
+ "runtime",
25909
+ "pool-tuning"
25910
+ ]).nullable()
25911
+ });
25912
+ object({
25913
+ runId: string(),
25914
+ nodeId: string(),
25915
+ startedAtMs: number(),
25916
+ deadlineAtMs: number(),
25917
+ plan: NodeBenchmarkPlanSchema,
25918
+ moved: array(number()).readonly(),
25919
+ staying: array(number()).readonly()
25920
+ });
25921
+ /** Candidate detectors per device, for the plan editor. */
25922
+ var NodeBenchmarkCandidatesSchema = object({
25923
+ nodeId: string(),
25924
+ reachable: boolean(),
25925
+ devices: array(object({
25926
+ deviceKey: string(),
25927
+ enabled: boolean(),
25928
+ available: boolean(),
25929
+ /** Ordered: what Auto tune would pick first, then the rest of the family by accuracy. */
25930
+ suggested: array(string()).readonly(),
25931
+ /** Every root detector the device has a build for. */
25932
+ all: array(string()).readonly(),
25933
+ /** The model the device runs now, when pinned. */
25934
+ currentModelId: string().nullable()
25935
+ })).readonly(),
25936
+ /** Detail steps the node's catalog offers under the root (for the `pipeline` measurement). */
25937
+ steps: array(object({
25938
+ id: string(),
25939
+ name: string(),
25940
+ slot: string()
25941
+ })).readonly()
25942
+ });
24398
25943
  object({
24399
25944
  activeCameras: number(),
24400
25945
  throttledCameras: number(),
@@ -25523,7 +27068,16 @@ method(RunnerCameraConfigSchema, object({ success: literal(true) }), { kind: "mu
25523
27068
  }), ParkedTrackFrameSchema.nullable()), method(object({
25524
27069
  deviceId: number(),
25525
27070
  trackId: string()
25526
- }), object({ released: number().int().nonnegative() }), { kind: "mutation" });
27071
+ }), object({ released: number().int().nonnegative() }), { kind: "mutation" }), method(NodeBenchRunnerInputSchema, object({
27072
+ accepted: literal(true),
27073
+ runId: string()
27074
+ }), {
27075
+ kind: "mutation",
27076
+ auth: "admin"
27077
+ }), method(object({ runId: string() }), NodeBenchRunnerStatusSchema.nullable(), { auth: "admin" }), method(object({ runId: string() }), object({ aborted: boolean() }), {
27078
+ kind: "mutation",
27079
+ auth: "admin"
27080
+ });
25527
27081
  var CameraPipelineConfigSchema = object({
25528
27082
  engine: PipelineEngineChoiceSchema.optional(),
25529
27083
  steps: array(PipelineStepInputSchema).readonly(),
@@ -26162,6 +27716,21 @@ method(object({
26162
27716
  }), method(PlacementStatsInputSchema, PlacementStatsSchema, { auth: "admin" }), method(SuggestSharesInputSchema, SuggestSharesResultSchema, { auth: "admin" }), method(_void(), EffectiveSharesSchema, { auth: "admin" }), method(SetShareSourceInputSchema, object({ success: literal(true) }), {
26163
27717
  kind: "mutation",
26164
27718
  auth: "admin"
27719
+ }), method(NodeBenchmarkPlanSchema, NodeBenchmarkPreflightSchema, { auth: "admin" }), method(NodeBenchmarkPlanSchema, discriminatedUnion("kind", [object({
27720
+ kind: literal("started"),
27721
+ runId: string()
27722
+ }), object({
27723
+ kind: literal("refused"),
27724
+ preflight: NodeBenchmarkPreflightSchema
27725
+ })]), {
27726
+ kind: "mutation",
27727
+ auth: "admin"
27728
+ }), method(_void(), NodeBenchmarkStatusSchema, { auth: "admin" }), method(object({ runId: string() }), object({ aborted: boolean() }), {
27729
+ kind: "mutation",
27730
+ auth: "admin"
27731
+ }), method(object({ nodeId: string() }), NodeBenchmarkCandidatesSchema, { auth: "admin" }), method(ListNodeBenchmarkResultsInputSchema, array(NodeBenchmarkResultViewSchema).readonly(), { auth: "admin" }), method(object({ id: string() }), object({ deleted: boolean() }), {
27732
+ kind: "mutation",
27733
+ auth: "admin"
26165
27734
  }), method(object({ deviceId: number() }), CameraPipelineSettingsSchema.nullable()), method(object({
26166
27735
  deviceId: number(),
26167
27736
  addonId: string(),
@@ -32269,6 +33838,9 @@ var CreateIntegrationInputSchema = object({
32269
33838
  enabled: boolean().optional(),
32270
33839
  info: record(string(), unknown()).optional(),
32271
33840
  settings: record(string(), unknown()).optional(),
33841
+ /** Keys of `settings` the form's schema declares secret (by type) — kept in
33842
+ * the keychain, not the table (D787). */
33843
+ secretKeys: array(string()).optional(),
32272
33844
  skipRestart: boolean().optional()
32273
33845
  });
32274
33846
  var UpdateIntegrationInputSchema = object({
@@ -32292,7 +33864,9 @@ method(_void(), array(IntegrationWithStateSchema)), method(object({ id: string()
32292
33864
  auth: "admin"
32293
33865
  }), method(object({ id: string() }), record(string(), unknown()), { auth: "admin" }), method(object({
32294
33866
  id: string(),
32295
- settings: record(string(), unknown())
33867
+ settings: record(string(), unknown()),
33868
+ /** Keys the form's schema declares secret (by type) — keychain-stored (D787). */
33869
+ secretKeys: array(string()).optional()
32296
33870
  }), object({ success: boolean() }), {
32297
33871
  kind: "mutation",
32298
33872
  auth: "admin"
@@ -40455,7 +42029,8 @@ var BaseDevice = class {
40455
42029
  this.role = options.role;
40456
42030
  this.parentDeviceId = ctx.parentDeviceId;
40457
42031
  const seedData = ctx.persistedConfig ?? {};
40458
- this.config = DeviceConfig.fromSchema(schema, (data) => ctx.persistConfig(data), seedData, ({ droppedKeys, issues }) => {
42032
+ const declaredSecretPaths = collectZodSecretPaths(schema);
42033
+ this.config = DeviceConfig.fromSchema(schema, (data) => ctx.persistConfig(data, { secretConfigPaths: declaredSecretPaths }), seedData, ({ droppedKeys, issues }) => {
40459
42034
  ctx.logger.warn("Device config recovery: dropping invalid persisted fields", {
40460
42035
  tags: {
40461
42036
  deviceId: ctx.id,
@@ -44144,6 +45719,90 @@ Object.freeze({
44144
45719
  addonId: null,
44145
45720
  access: "create"
44146
45721
  },
45722
+ "keychain.delete": {
45723
+ capName: "keychain",
45724
+ capScope: "system",
45725
+ addonId: null,
45726
+ access: "delete"
45727
+ },
45728
+ "keychain.getState": {
45729
+ capName: "keychain",
45730
+ capScope: "system",
45731
+ addonId: null,
45732
+ access: "view"
45733
+ },
45734
+ "keychain.listMeta": {
45735
+ capName: "keychain",
45736
+ capScope: "system",
45737
+ addonId: null,
45738
+ access: "view"
45739
+ },
45740
+ "keychain.put": {
45741
+ capName: "keychain",
45742
+ capScope: "system",
45743
+ addonId: null,
45744
+ access: "create"
45745
+ },
45746
+ "keychain.resolve": {
45747
+ capName: "keychain",
45748
+ capScope: "system",
45749
+ addonId: null,
45750
+ access: "view"
45751
+ },
45752
+ "keychainAdmin.deleteOrphans": {
45753
+ capName: "keychain-admin",
45754
+ capScope: "system",
45755
+ addonId: null,
45756
+ access: "delete"
45757
+ },
45758
+ "keychainAdmin.downloadRecoveryKey": {
45759
+ capName: "keychain-admin",
45760
+ capScope: "system",
45761
+ addonId: null,
45762
+ access: "create"
45763
+ },
45764
+ "keychainAdmin.listAudit": {
45765
+ capName: "keychain-admin",
45766
+ capScope: "system",
45767
+ addonId: null,
45768
+ access: "view"
45769
+ },
45770
+ "keychainAdmin.listSecrets": {
45771
+ capName: "keychain-admin",
45772
+ capScope: "system",
45773
+ addonId: null,
45774
+ access: "view"
45775
+ },
45776
+ "keychainAdmin.purgeRetiredKeys": {
45777
+ capName: "keychain-admin",
45778
+ capScope: "system",
45779
+ addonId: null,
45780
+ access: "delete"
45781
+ },
45782
+ "keychainAdmin.resetKeychain": {
45783
+ capName: "keychain-admin",
45784
+ capScope: "system",
45785
+ addonId: null,
45786
+ access: "delete"
45787
+ },
45788
+ "keychainAdmin.reveal": {
45789
+ capName: "keychain-admin",
45790
+ capScope: "system",
45791
+ addonId: null,
45792
+ access: "create"
45793
+ },
45794
+ "keychainAdmin.rotateMasterKey": {
45795
+ capName: "keychain-admin",
45796
+ capScope: "system",
45797
+ addonId: null,
45798
+ access: "create"
45799
+ },
45800
+ "keychainAdmin.status": {
45801
+ capName: "keychain-admin",
45802
+ capScope: "system",
45803
+ addonId: null,
45804
+ access: "view"
45805
+ },
44147
45806
  "lawnMowerControl.dock": {
44148
45807
  capName: "lawn-mower-control",
44149
45808
  capScope: "device",
@@ -45518,6 +47177,18 @@ Object.freeze({
45518
47177
  addonId: null,
45519
47178
  access: "create"
45520
47179
  },
47180
+ "pipelineAnalytics.addRetrainFrameFromRecording": {
47181
+ capName: "pipeline-analytics",
47182
+ capScope: "device",
47183
+ addonId: null,
47184
+ access: "create"
47185
+ },
47186
+ "pipelineAnalytics.addRetrainFramesToCollection": {
47187
+ capName: "pipeline-analytics",
47188
+ capScope: "device",
47189
+ addonId: null,
47190
+ access: "create"
47191
+ },
45521
47192
  "pipelineAnalytics.applyDeviceSettingsPatch": {
45522
47193
  capName: "pipeline-analytics",
45523
47194
  capScope: "device",
@@ -45566,12 +47237,24 @@ Object.freeze({
45566
47237
  addonId: null,
45567
47238
  access: "view"
45568
47239
  },
47240
+ "pipelineAnalytics.createRetrainCollection": {
47241
+ capName: "pipeline-analytics",
47242
+ capScope: "device",
47243
+ addonId: null,
47244
+ access: "create"
47245
+ },
45569
47246
  "pipelineAnalytics.deleteDeviceEvents": {
45570
47247
  capName: "pipeline-analytics",
45571
47248
  capScope: "device",
45572
47249
  addonId: null,
45573
47250
  access: "delete"
45574
47251
  },
47252
+ "pipelineAnalytics.deleteRetrainCollection": {
47253
+ capName: "pipeline-analytics",
47254
+ capScope: "device",
47255
+ addonId: null,
47256
+ access: "delete"
47257
+ },
45575
47258
  "pipelineAnalytics.deleteTracks": {
45576
47259
  capName: "pipeline-analytics",
45577
47260
  capScope: "device",
@@ -45776,6 +47459,24 @@ Object.freeze({
45776
47459
  addonId: null,
45777
47460
  access: "view"
45778
47461
  },
47462
+ "pipelineAnalytics.listRetrainAssistProfiles": {
47463
+ capName: "pipeline-analytics",
47464
+ capScope: "device",
47465
+ addonId: null,
47466
+ access: "view"
47467
+ },
47468
+ "pipelineAnalytics.listRetrainCollectionFrames": {
47469
+ capName: "pipeline-analytics",
47470
+ capScope: "device",
47471
+ addonId: null,
47472
+ access: "view"
47473
+ },
47474
+ "pipelineAnalytics.listRetrainCollections": {
47475
+ capName: "pipeline-analytics",
47476
+ capScope: "device",
47477
+ addonId: null,
47478
+ access: "view"
47479
+ },
45779
47480
  "pipelineAnalytics.listRetrainFrames": {
45780
47481
  capName: "pipeline-analytics",
45781
47482
  capScope: "device",
@@ -45824,6 +47525,12 @@ Object.freeze({
45824
47525
  addonId: null,
45825
47526
  access: "create"
45826
47527
  },
47528
+ "pipelineAnalytics.proposeRetrainAnnotationsWithLlm": {
47529
+ capName: "pipeline-analytics",
47530
+ capScope: "device",
47531
+ addonId: null,
47532
+ access: "create"
47533
+ },
45827
47534
  "pipelineAnalytics.pruneEvents": {
45828
47535
  capName: "pipeline-analytics",
45829
47536
  capScope: "device",
@@ -45878,6 +47585,18 @@ Object.freeze({
45878
47585
  addonId: null,
45879
47586
  access: "create"
45880
47587
  },
47588
+ "pipelineAnalytics.removeRetrainFrameFromCollection": {
47589
+ capName: "pipeline-analytics",
47590
+ capScope: "device",
47591
+ addonId: null,
47592
+ access: "delete"
47593
+ },
47594
+ "pipelineAnalytics.renameRetrainCollection": {
47595
+ capName: "pipeline-analytics",
47596
+ capScope: "device",
47597
+ addonId: null,
47598
+ access: "create"
47599
+ },
45881
47600
  "pipelineAnalytics.restageRetrainTrack": {
45882
47601
  capName: "pipeline-analytics",
45883
47602
  capScope: "device",
@@ -46166,6 +47885,12 @@ Object.freeze({
46166
47885
  addonId: null,
46167
47886
  access: "view"
46168
47887
  },
47888
+ "pipelineOrchestrator.abortNodeBenchmark": {
47889
+ capName: "pipeline-orchestrator",
47890
+ capScope: "system",
47891
+ addonId: null,
47892
+ access: "create"
47893
+ },
46169
47894
  "pipelineOrchestrator.applyAutoTune": {
46170
47895
  capName: "pipeline-orchestrator",
46171
47896
  capScope: "system",
@@ -46190,6 +47915,12 @@ Object.freeze({
46190
47915
  addonId: null,
46191
47916
  access: "create"
46192
47917
  },
47918
+ "pipelineOrchestrator.deleteNodeBenchmarkResult": {
47919
+ capName: "pipeline-orchestrator",
47920
+ capScope: "system",
47921
+ addonId: null,
47922
+ access: "delete"
47923
+ },
46193
47924
  "pipelineOrchestrator.getAgentLoad": {
46194
47925
  capName: "pipeline-orchestrator",
46195
47926
  capScope: "system",
@@ -46298,6 +48029,24 @@ Object.freeze({
46298
48029
  addonId: null,
46299
48030
  access: "view"
46300
48031
  },
48032
+ "pipelineOrchestrator.getNodeBenchmarkCandidates": {
48033
+ capName: "pipeline-orchestrator",
48034
+ capScope: "system",
48035
+ addonId: null,
48036
+ access: "view"
48037
+ },
48038
+ "pipelineOrchestrator.getNodeBenchmarkPreflight": {
48039
+ capName: "pipeline-orchestrator",
48040
+ capScope: "system",
48041
+ addonId: null,
48042
+ access: "view"
48043
+ },
48044
+ "pipelineOrchestrator.getNodeBenchmarkStatus": {
48045
+ capName: "pipeline-orchestrator",
48046
+ capScope: "system",
48047
+ addonId: null,
48048
+ access: "view"
48049
+ },
46301
48050
  "pipelineOrchestrator.getNodeInferenceDevices": {
46302
48051
  capName: "pipeline-orchestrator",
46303
48052
  capScope: "system",
@@ -46340,6 +48089,12 @@ Object.freeze({
46340
48089
  addonId: null,
46341
48090
  access: "view"
46342
48091
  },
48092
+ "pipelineOrchestrator.listNodeBenchmarkResults": {
48093
+ capName: "pipeline-orchestrator",
48094
+ capScope: "system",
48095
+ addonId: null,
48096
+ access: "view"
48097
+ },
46343
48098
  "pipelineOrchestrator.pauseForStorageMigration": {
46344
48099
  capName: "pipeline-orchestrator",
46345
48100
  capScope: "system",
@@ -46484,6 +48239,12 @@ Object.freeze({
46484
48239
  addonId: null,
46485
48240
  access: "create"
46486
48241
  },
48242
+ "pipelineOrchestrator.startNodeBenchmark": {
48243
+ capName: "pipeline-orchestrator",
48244
+ capScope: "system",
48245
+ addonId: null,
48246
+ access: "create"
48247
+ },
46487
48248
  "pipelineOrchestrator.suggestShares": {
46488
48249
  capName: "pipeline-orchestrator",
46489
48250
  capScope: "system",
@@ -46502,6 +48263,12 @@ Object.freeze({
46502
48263
  addonId: null,
46503
48264
  access: "create"
46504
48265
  },
48266
+ "pipelineRunner.abortNodeBench": {
48267
+ capName: "pipeline-runner",
48268
+ capScope: "system",
48269
+ addonId: null,
48270
+ access: "create"
48271
+ },
46505
48272
  "pipelineRunner.attachCamera": {
46506
48273
  capName: "pipeline-runner",
46507
48274
  capScope: "system",
@@ -46550,6 +48317,12 @@ Object.freeze({
46550
48317
  addonId: null,
46551
48318
  access: "view"
46552
48319
  },
48320
+ "pipelineRunner.getNodeBenchStatus": {
48321
+ capName: "pipeline-runner",
48322
+ capScope: "system",
48323
+ addonId: null,
48324
+ access: "view"
48325
+ },
46553
48326
  "pipelineRunner.getParkedTrackFrame": {
46554
48327
  capName: "pipeline-runner",
46555
48328
  capScope: "system",
@@ -46592,6 +48365,12 @@ Object.freeze({
46592
48365
  addonId: null,
46593
48366
  access: "create"
46594
48367
  },
48368
+ "pipelineRunner.startNodeBench": {
48369
+ capName: "pipeline-runner",
48370
+ capScope: "system",
48371
+ addonId: null,
48372
+ access: "create"
48373
+ },
46595
48374
  "plateGallery.assignPlate": {
46596
48375
  capName: "plate-gallery",
46597
48376
  capScope: "system",
@@ -51521,6 +53300,11 @@ Object.freeze({
51521
53300
  form: "single",
51522
53301
  optional: false
51523
53302
  }],
53303
+ "pipelineAnalytics.addRetrainFrameFromRecording": [{
53304
+ name: "deviceId",
53305
+ form: "single",
53306
+ optional: false
53307
+ }],
51524
53308
  "pipelineAnalytics.applyDeviceSettingsPatch": [{
51525
53309
  name: "deviceId",
51526
53310
  form: "single",
@@ -51711,6 +53495,11 @@ Object.freeze({
51711
53495
  form: "single",
51712
53496
  optional: false
51713
53497
  }],
53498
+ "pipelineAnalytics.proposeRetrainAnnotationsWithLlm": [{
53499
+ name: "deviceId",
53500
+ form: "single",
53501
+ optional: false
53502
+ }],
51714
53503
  "pipelineAnalytics.pruneEventsBefore": [{
51715
53504
  name: "deviceId",
51716
53505
  form: "single",