@camstack/addon-matter-broker 0.2.122 → 0.2.123

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
@@ -11,7 +11,7 @@ import { networkInterfaces, tmpdir, uptime } from "node:os";
11
11
  import { finished } from "node:stream/promises";
12
12
  import { createConnection, createServer as createServer$2 } from "node:net";
13
13
  import * as dgram from "node:dgram";
14
- //#region ../types/dist/event-category-B_0XEcLF.mjs
14
+ //#region ../types/dist/event-category-DaIZi00R.mjs
15
15
  var EventCategory = /* @__PURE__ */ function(EventCategory) {
16
16
  EventCategory["SystemBoot"] = "system.boot";
17
17
  EventCategory["SystemAddonsReady"] = "system.addons-ready";
@@ -90,6 +90,13 @@ var EventCategory = /* @__PURE__ */ function(EventCategory) {
90
90
  */
91
91
  EventCategory["AddonLoadFailed"] = "addon.load-failed";
92
92
  /**
93
+ * A keychain value was stored or removed (D787). Carries the ref, its
94
+ * owner and the new version — NEVER the value. A process holding the ref
95
+ * drops its cached copy and the owning `BaseAddon` re-resolves its config.
96
+ * Telemetry (D8): a process that misses it still revalidates by version.
97
+ */
98
+ EventCategory["KeychainChanged"] = "keychain.changed";
99
+ /**
93
100
  * Addon recovered from a previous failure. Emitted when an addon
94
101
  * transitions from `failed` back to `healthy` (typically via the
95
102
  * monitor's auto-retry loop, or after manual `addons.retryLoad`).
@@ -5382,7 +5389,7 @@ var ZodIssueCode = {
5382
5389
  var ZodFirstPartyTypeKind;
5383
5390
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
5384
5391
  //#endregion
5385
- //#region ../types/dist/sleep-B0JG7-_F.mjs
5392
+ //#region ../types/dist/sleep-Cr5YOk3m.mjs
5386
5393
  /**
5387
5394
  * The audio chunk plane's byte format, and the ONE expansion from a coded
5388
5395
  * window to float samples (D455).
@@ -5461,6 +5468,97 @@ function buildAlawTable() {
5461
5468
  }
5462
5469
  buildUlawTable();
5463
5470
  buildAlawTable();
5471
+ /** Is this field's stored value a credential? */
5472
+ function isSecretConfigField(field) {
5473
+ if (field.type === "password") return true;
5474
+ return "secret" in field && field.secret === true;
5475
+ }
5476
+ /**
5477
+ * Is this field's value stored in the KEYCHAIN (D787)? Every secret field is,
5478
+ * by its TYPE, unless it opts out with `storage: 'inline'` — never by its name.
5479
+ */
5480
+ function isKeychainStoredField(field) {
5481
+ if (!isSecretConfigField(field)) return false;
5482
+ if (field.type === "textarea" && field.isJson === true) return false;
5483
+ return !("storage" in field && field.storage === "inline");
5484
+ }
5485
+ /**
5486
+ * What a settings blob holds where a secret used to be.
5487
+ *
5488
+ * A keychain-stored field never holds its value. It holds a self-describing
5489
+ * MARKER, `{"$secret":"secret://…","v":1}` — an object, never a string, so no
5490
+ * code can mistake it for a credential and no form can send it to a camera as
5491
+ * a password. The empty state is `null` / absent, never `''`.
5492
+ *
5493
+ * The same shapes travel to and from the admin UI:
5494
+ *
5495
+ * - read: `hydrateSchema` hands a secret field a {@link SecretFieldView}
5496
+ * (`{ $secret, v, set: true }`) or `null` — the browser learns whether a
5497
+ * value is set, never the value.
5498
+ * - write: an untouched field submits the view back unchanged (KEEP); a typed
5499
+ * value is a plain non-empty string (CHANGE); the Clear button submits
5500
+ * {@link SECRET_CLEAR} (CLEAR). `''`, `null` and the legacy redaction tokens
5501
+ * are KEEP — an empty string is what a defaults-fallback pushes back, and
5502
+ * treating it as "clear" is how a save destroyed a stored credential before.
5503
+ *
5504
+ * Pure and browser-safe.
5505
+ */
5506
+ var SECRET_CLEAR = { $secretClear: true };
5507
+ /** The `'***'` token D634 redaction writes for non-admins. */
5508
+ var LEGACY_DEVICE_REDACTION = "***";
5509
+ function isRecord$1$1(value) {
5510
+ return typeof value === "object" && value !== null && !Array.isArray(value);
5511
+ }
5512
+ function makeSecretMarker(ref) {
5513
+ return {
5514
+ $secret: ref,
5515
+ v: 1
5516
+ };
5517
+ }
5518
+ /** A stored marker: an object whose `$secret` is a non-empty string. */
5519
+ function isSecretMarker(value) {
5520
+ if (!isRecord$1$1(value)) return false;
5521
+ const ref = value["$secret"];
5522
+ return typeof ref === "string" && ref.length > 0;
5523
+ }
5524
+ function isSecretClear(value) {
5525
+ return isRecord$1$1(value) && value["$secretClear"] === true;
5526
+ }
5527
+ /**
5528
+ * The UI view of a stored secret field value: a marker becomes "set", inline
5529
+ * plaintext becomes "set (inline)", nothing becomes `null`. A value never
5530
+ * survives this function.
5531
+ */
5532
+ function toSecretFieldView(stored) {
5533
+ if (isSecretMarker(stored)) return {
5534
+ $secret: stored.$secret,
5535
+ v: 1,
5536
+ set: true
5537
+ };
5538
+ if (typeof stored === "string" && stored.length > 0) return {
5539
+ $secret: null,
5540
+ v: 1,
5541
+ set: true,
5542
+ inline: true
5543
+ };
5544
+ return null;
5545
+ }
5546
+ /**
5547
+ * Classify an incoming value for a secret path. Only a non-empty string that is
5548
+ * not a redaction token sets a value; only {@link SECRET_CLEAR} clears.
5549
+ * Everything else — a marker (ours or anyone's), a UI view, `''`, `null`,
5550
+ * `undefined`, a redaction token, a non-string — keeps what is stored.
5551
+ */
5552
+ function classifySecretWrite(incoming) {
5553
+ if (isSecretClear(incoming)) return { kind: "clear" };
5554
+ if (typeof incoming !== "string") return { kind: "keep" };
5555
+ if (incoming.length === 0) return { kind: "keep" };
5556
+ if (incoming === "__camstack_redacted__" || incoming === LEGACY_DEVICE_REDACTION) return { kind: "keep" };
5557
+ return {
5558
+ kind: "set",
5559
+ value: incoming
5560
+ };
5561
+ }
5464
5562
  Object.fromEntries([
5465
5563
  {
5466
5564
  id: "overview",
@@ -5632,33 +5730,19 @@ Object.fromEntries([
5632
5730
  function isValuelessField(field) {
5633
5731
  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";
5634
5732
  }
5635
- /**
5636
- * Merge a `ConfigUISchema` with a raw `values` record into a
5637
- * `ConfigUISchemaWithValues`. Used by every `get*Settings` backend endpoint
5638
- * before returning to the admin UI. Groups are walked recursively.
5639
- *
5640
- * For each leaf field:
5641
- * - structural fields (`separator`, `info`, `button`) pass through unchanged
5642
- * - other fields get `value = values[key] ?? field.default ?? null`
5643
- *
5644
- * Unknown keys in `values` (keys not declared in the schema) are silently
5645
- * ignored — they don't contribute to the output. Missing keys fall back to
5646
- * the schema default or `null`. This mirrors the old backend behaviour where
5647
- * `FormBuilder` rendered `values[key] ?? field.default`.
5648
- */
5649
- function hydrateSchema(schema, values) {
5733
+ function hydrateSchema(schema, values, options = {}) {
5650
5734
  return {
5651
5735
  ...schema.tabs ? { tabs: [...schema.tabs] } : {},
5652
5736
  sections: schema.sections.map((section) => ({
5653
5737
  ...section,
5654
- fields: section.fields.map((field) => hydrateField(field, values))
5738
+ fields: section.fields.map((field) => hydrateField(field, values, options))
5655
5739
  }))
5656
5740
  };
5657
5741
  }
5658
- function hydrateField(field, values) {
5742
+ function hydrateField(field, values, options) {
5659
5743
  if (isValuelessField(field)) return field;
5660
5744
  if (field.type === "group") {
5661
- const hydratedChildren = field.fields.map((child) => hydrateField(child, values));
5745
+ const hydratedChildren = field.fields.map((child) => hydrateField(child, values, options));
5662
5746
  return {
5663
5747
  ...field,
5664
5748
  fields: hydratedChildren
@@ -5667,7 +5751,7 @@ function hydrateField(field, values) {
5667
5751
  if (field.type === "sub-tabs") {
5668
5752
  const hydratedTabs = field.tabs.map((tab) => ({
5669
5753
  ...tab,
5670
- fields: tab.fields.map((child) => hydrateField(child, values))
5754
+ fields: tab.fields.map((child) => hydrateField(child, values, options))
5671
5755
  }));
5672
5756
  return {
5673
5757
  ...field,
@@ -5677,6 +5761,33 @@ function hydrateField(field, values) {
5677
5761
  const key = field.key;
5678
5762
  const storedValue = Object.prototype.hasOwnProperty.call(values, key) ? values[key] : void 0;
5679
5763
  const defaultValue = field.default;
5764
+ const asView = (v) => isSecretMarker(v) || options.inlineSecretsAsViews === true && v !== void 0;
5765
+ if (isKeychainStoredField(field) && asView(storedValue)) return {
5766
+ ...field,
5767
+ value: toSecretFieldView(storedValue)
5768
+ };
5769
+ if (isKeychainStoredField(field) && options.inlineSecretsAsViews === true) return {
5770
+ ...field,
5771
+ value: null
5772
+ };
5773
+ if (field.type === "editable-array" && Array.isArray(storedValue)) {
5774
+ const secretItemKeys = field.itemFields.filter((item) => "key" in item && isKeychainStoredField(item)).map((item) => "key" in item ? item.key : "");
5775
+ if (secretItemKeys.length > 0) {
5776
+ const rows = storedValue.map((row) => {
5777
+ if (row === null || typeof row !== "object" || Array.isArray(row)) return row;
5778
+ const out = { ...row };
5779
+ for (const k of secretItemKeys) {
5780
+ const v = Reflect.get(row, k);
5781
+ if (asView(v)) out[k] = toSecretFieldView(v);
5782
+ }
5783
+ return out;
5784
+ });
5785
+ return {
5786
+ ...field,
5787
+ value: rows
5788
+ };
5789
+ }
5790
+ }
5680
5791
  if (field.multiple) {
5681
5792
  const stored = Array.isArray(storedValue) ? storedValue : storedValue !== void 0 && storedValue !== null ? [storedValue] : [];
5682
5793
  const itemFallback = field.multiple.itemDefault !== void 0 ? field.multiple.itemDefault : defaultValue !== void 0 ? defaultValue : typeOf(field) === "string" ? "" : null;
@@ -5919,6 +6030,431 @@ function projectStore(store, perNodeKeys, nodeId) {
5919
6030
  }
5920
6031
  return out;
5921
6032
  }
6033
+ var GLOBAL_SCOPE = { kind: "global" };
6034
+ /** The scope every addon-wide (not per-node, not per-device) setting lives in. */
6035
+ function globalSecretScope() {
6036
+ return GLOBAL_SCOPE;
6037
+ }
6038
+ function encodeSegment(value) {
6039
+ return encodeURIComponent(value);
6040
+ }
6041
+ /**
6042
+ * The field path of a value inside an array item, addressed by the item's id:
6043
+ * `arrayItemFieldPath('providers', 'authentik', 'clientSecret')` →
6044
+ * `providers[authentik].clientSecret`.
6045
+ */
6046
+ function arrayItemFieldPath(arrayKey, itemId, fieldKey) {
6047
+ return `${arrayKey}[${encodeSegment(itemId)}].${fieldKey}`;
6048
+ }
6049
+ /** A write to a secret path could not be stored in the keychain, so it was refused. */
6050
+ var KeychainWriteRefusedError = class extends Error {
6051
+ fieldPath;
6052
+ constructor(fieldPath, cause) {
6053
+ super(`secret "${fieldPath}" was not saved: the keychain could not store it (${cause instanceof Error ? cause.message : String(cause)}). Nothing was written.`);
6054
+ this.fieldPath = fieldPath;
6055
+ this.name = "KeychainWriteRefusedError";
6056
+ }
6057
+ };
6058
+ var KEEP = { kind: "keep" };
6059
+ function isRecord$2(value) {
6060
+ return typeof value === "object" && value !== null && !Array.isArray(value);
6061
+ }
6062
+ function defaultMintId() {
6063
+ return globalThis.crypto.randomUUID();
6064
+ }
6065
+ /** Every marker ref anywhere under `value`. */
6066
+ function collectSecretMarkerRefs(value, out = []) {
6067
+ if (isSecretMarker(value)) {
6068
+ out.push(value.$secret);
6069
+ return out;
6070
+ }
6071
+ if (Array.isArray(value)) for (const item of value) collectSecretMarkerRefs(item, out);
6072
+ else if (isRecord$2(value)) for (const child of Object.values(value)) collectSecretMarkerRefs(child, out);
6073
+ return out;
6074
+ }
6075
+ async function storedValueEquals(secrets, marker, candidate) {
6076
+ const resolved = (await secrets.resolve([marker.$secret]))[marker.$secret];
6077
+ return resolved?.kind === "value" && resolved.value === candidate;
6078
+ }
6079
+ async function writeLeaf(ctx, incoming, stored, fieldPath) {
6080
+ const intent = classifySecretWrite(incoming);
6081
+ const ref = ctx.secrets.ref(ctx.scope, fieldPath);
6082
+ const storedIsOurs = isSecretMarker(stored) && stored.$secret === ref;
6083
+ if (intent.kind === "keep") return KEEP;
6084
+ if (intent.kind === "set" && !ctx.operatorWrite && typeof stored === "string" && stored === intent.value) return KEEP;
6085
+ if (intent.kind === "clear") {
6086
+ if (storedIsOurs) ctx.deletes.push(ref);
6087
+ return {
6088
+ kind: "value",
6089
+ value: null
6090
+ };
6091
+ }
6092
+ if (storedIsOurs && await storedValueEquals(ctx.secrets, stored, intent.value)) return {
6093
+ kind: "value",
6094
+ value: stored
6095
+ };
6096
+ try {
6097
+ await ctx.secrets.put(ref, intent.value);
6098
+ } catch (err) {
6099
+ throw new KeychainWriteRefusedError(fieldPath, err);
6100
+ }
6101
+ return {
6102
+ kind: "value",
6103
+ value: makeSecretMarker(ref)
6104
+ };
6105
+ }
6106
+ /** Apply a member result onto `out`: KEEP restores the stored member, or removes it. */
6107
+ function applyMember(out, key, result, storedParent) {
6108
+ if (result.kind === "value") {
6109
+ out[key] = result.value;
6110
+ return;
6111
+ }
6112
+ if (Object.prototype.hasOwnProperty.call(storedParent, key)) out[key] = storedParent[key];
6113
+ else delete out[key];
6114
+ }
6115
+ async function writeMembers(ctx, children, incoming, stored, pathOf) {
6116
+ const out = { ...incoming };
6117
+ for (const [member, node] of children) applyMember(out, member, await writeNode(ctx, node, incoming[member], stored[member], pathOf(member)), stored);
6118
+ return out;
6119
+ }
6120
+ function rowId(row, idKey) {
6121
+ const raw = row[idKey];
6122
+ if (typeof raw === "string" && raw.length > 0) return raw;
6123
+ if (typeof raw === "number" && Number.isFinite(raw)) return String(raw);
6124
+ return null;
6125
+ }
6126
+ async function writeArray(ctx, node, incoming, stored, fieldPath) {
6127
+ const storedRows = Array.isArray(stored) ? stored.filter(isRecord$2) : [];
6128
+ if (!Array.isArray(incoming)) {
6129
+ ctx.deletes.push(...collectSecretMarkerRefs(storedRows));
6130
+ return {
6131
+ kind: "value",
6132
+ value: incoming
6133
+ };
6134
+ }
6135
+ const storedById = /* @__PURE__ */ new Map();
6136
+ for (const row of storedRows) {
6137
+ const id = rowId(row, node.idKey);
6138
+ if (id !== null) storedById.set(id, row);
6139
+ }
6140
+ const kept = /* @__PURE__ */ new Set();
6141
+ const rows = [];
6142
+ for (const row of incoming) {
6143
+ if (!isRecord$2(row)) {
6144
+ rows.push(row);
6145
+ continue;
6146
+ }
6147
+ const id = rowId(row, node.idKey) ?? ctx.mintId();
6148
+ kept.add(id);
6149
+ const withId = {
6150
+ ...row,
6151
+ [node.idKey]: row[node.idKey] ?? id
6152
+ };
6153
+ if (rowId(withId, node.idKey) === null) withId[node.idKey] = id;
6154
+ const storedRow = storedById.get(id) ?? {};
6155
+ rows.push(await writeMembers(ctx, node.item, withId, storedRow, (member) => arrayItemFieldPath(fieldPath, id, member)));
6156
+ }
6157
+ for (const [id, row] of storedById) if (!kept.has(id)) ctx.deletes.push(...collectSecretMarkerRefs(row));
6158
+ return {
6159
+ kind: "value",
6160
+ value: rows
6161
+ };
6162
+ }
6163
+ async function writeNode(ctx, node, incoming, stored, fieldPath) {
6164
+ switch (node.kind) {
6165
+ case "leaf": return writeLeaf(ctx, incoming, stored, fieldPath);
6166
+ case "array": return writeArray(ctx, node, incoming, stored, fieldPath);
6167
+ case "object": {
6168
+ if (!isRecord$2(incoming)) {
6169
+ if (incoming === void 0) return KEEP;
6170
+ ctx.deletes.push(...collectSecretMarkerRefs(stored));
6171
+ return {
6172
+ kind: "value",
6173
+ value: incoming
6174
+ };
6175
+ }
6176
+ const storedObj = isRecord$2(stored) ? stored : {};
6177
+ return {
6178
+ kind: "value",
6179
+ value: await writeMembers(ctx, node.children, incoming, storedObj, (m) => `${fieldPath}.${m}`)
6180
+ };
6181
+ }
6182
+ }
6183
+ }
6184
+ /** Split a perNode-scoped key (`key@nodeId`). */
6185
+ function splitNodeKey(key) {
6186
+ const at = key.indexOf("@");
6187
+ return at <= 0 ? {
6188
+ base: key,
6189
+ nodeId: null
6190
+ } : {
6191
+ base: key.slice(0, at),
6192
+ nodeId: key.slice(at + 1)
6193
+ };
6194
+ }
6195
+ /** Rewrite a settings patch so no secret value reaches the blob. See the file doc. */
6196
+ async function transformSecretWrite(input) {
6197
+ const deletes = [];
6198
+ const base = {
6199
+ secrets: input.secrets,
6200
+ mintId: input.mintId ?? defaultMintId,
6201
+ deletes,
6202
+ operatorWrite: input.operatorWrite === true
6203
+ };
6204
+ const out = {};
6205
+ for (const [key, incoming] of Object.entries(input.patch)) {
6206
+ const { base: baseKey, nodeId } = splitNodeKey(key);
6207
+ const node = input.tree.get(baseKey);
6208
+ if (node === void 0) {
6209
+ out[key] = incoming;
6210
+ continue;
6211
+ }
6212
+ const scope = nodeId !== null && nodeId.length > 0 ? {
6213
+ kind: "node",
6214
+ nodeId
6215
+ } : input.scope ?? globalSecretScope();
6216
+ const result = await writeNode({
6217
+ ...base,
6218
+ scope
6219
+ }, node, incoming, input.stored[key], baseKey);
6220
+ if (result.kind === "value") out[key] = result.value;
6221
+ }
6222
+ return {
6223
+ patch: out,
6224
+ afterWrite: async () => {
6225
+ if (deletes.length === 0) return { orphaned: [] };
6226
+ try {
6227
+ await input.secrets.delete([...new Set(deletes)]);
6228
+ return { orphaned: [] };
6229
+ } catch {
6230
+ return { orphaned: [...new Set(deletes)] };
6231
+ }
6232
+ }
6233
+ };
6234
+ }
6235
+ /**
6236
+ * Replace every marker in `value` with its keychain value. Returns the SAME
6237
+ * reference when there is no marker (no allocation, no keychain call).
6238
+ */
6239
+ async function resolveSecretMarkers(value, secrets) {
6240
+ const refs = collectSecretMarkerRefs(value);
6241
+ if (refs.length === 0) return {
6242
+ value,
6243
+ unresolved: []
6244
+ };
6245
+ const answers = await secrets.resolve(refs);
6246
+ const unresolved = [];
6247
+ for (const ref of new Set(refs)) {
6248
+ const answer = answers[ref];
6249
+ if (answer === void 0) unresolved.push({
6250
+ ref,
6251
+ reason: "not-initialized"
6252
+ });
6253
+ else if (answer.kind === "unavailable") unresolved.push({
6254
+ ref,
6255
+ reason: answer.reason
6256
+ });
6257
+ else if (answer.kind === "missing" || answer.kind === "forbidden") unresolved.push({
6258
+ ref,
6259
+ reason: answer.kind
6260
+ });
6261
+ }
6262
+ const substitute = (v) => {
6263
+ if (isSecretMarker(v)) {
6264
+ const answer = answers[v.$secret];
6265
+ return answer?.kind === "value" ? {
6266
+ keep: true,
6267
+ value: answer.value
6268
+ } : {
6269
+ keep: false,
6270
+ value: void 0
6271
+ };
6272
+ }
6273
+ if (Array.isArray(v)) {
6274
+ const items = [];
6275
+ for (const item of v) {
6276
+ const s = substitute(item);
6277
+ if (s.keep) items.push(s.value);
6278
+ }
6279
+ return {
6280
+ keep: true,
6281
+ value: items
6282
+ };
6283
+ }
6284
+ if (isRecord$2(v)) {
6285
+ const out = {};
6286
+ for (const [k, child] of Object.entries(v)) {
6287
+ const s = substitute(child);
6288
+ if (s.keep) out[k] = s.value;
6289
+ }
6290
+ return {
6291
+ keep: true,
6292
+ value: out
6293
+ };
6294
+ }
6295
+ return {
6296
+ keep: true,
6297
+ value: v
6298
+ };
6299
+ };
6300
+ return {
6301
+ value: substitute(value).value,
6302
+ unresolved
6303
+ };
6304
+ }
6305
+ function touchesTree(tree, patch) {
6306
+ if (tree.size === 0) return false;
6307
+ for (const key of Object.keys(patch)) {
6308
+ const at = key.indexOf("@");
6309
+ if (tree.has(at > 0 ? key.slice(0, at) : key)) return true;
6310
+ }
6311
+ return false;
6312
+ }
6313
+ /** The blob as stored now; a failed read REFUSES the write instead of guessing. */
6314
+ async function readStoredAddonBlob(raw) {
6315
+ const threeWay = raw.readAddonStoreResult;
6316
+ if (threeWay === void 0) return raw.readAddonStore();
6317
+ const result = await threeWay.call(raw);
6318
+ if (result.kind === "failed") throw new Error(`settings write refused: the stored blob could not be read (${result.error})`);
6319
+ return result.kind === "missing" ? {} : result.value;
6320
+ }
6321
+ function createSecretAwareSettings(raw, opts) {
6322
+ const chains = /* @__PURE__ */ new Map();
6323
+ const serialize = (key, fn) => {
6324
+ const next = (chains.get(key) ?? Promise.resolve()).then(fn, fn);
6325
+ const tail = next.catch(() => void 0);
6326
+ chains.set(key, tail);
6327
+ tail.then(() => {
6328
+ if (chains.get(key) === tail) chains.delete(key);
6329
+ });
6330
+ return next;
6331
+ };
6332
+ const write = async (chainKey, tree, scope, patch, readStored, rawWrite) => {
6333
+ if (!touchesTree(tree, patch)) return rawWrite(patch);
6334
+ return serialize(chainKey, async () => {
6335
+ const stored = await readStored();
6336
+ const result = await transformSecretWrite({
6337
+ tree,
6338
+ secrets: opts.secrets,
6339
+ patch,
6340
+ stored,
6341
+ ...scope !== void 0 ? { scope } : {},
6342
+ operatorWrite: opts.isOperatorWrite?.() === true
6343
+ });
6344
+ if (Object.keys(result.patch).length > 0) await rawWrite(result.patch);
6345
+ const { orphaned } = await result.afterWrite();
6346
+ if (orphaned.length > 0) opts.onOrphaned(orphaned);
6347
+ });
6348
+ };
6349
+ const wrapped = {
6350
+ writeAddonStore: (patch) => write("addon", opts.addonTree(), void 0, patch, () => readStoredAddonBlob(raw), (p) => raw.writeAddonStore(p)),
6351
+ writeDeviceStore: (deviceId, patch) => write(`device:${deviceId}`, opts.deviceTree(), {
6352
+ kind: "device",
6353
+ deviceId
6354
+ }, patch, () => raw.readDeviceStore(deviceId), (p) => raw.writeDeviceStore(deviceId, p))
6355
+ };
6356
+ return new Proxy(raw, { get(target, prop, receiver) {
6357
+ if (prop === "writeAddonStore") return wrapped.writeAddonStore;
6358
+ if (prop === "writeDeviceStore") return wrapped.writeDeviceStore;
6359
+ const value = Reflect.get(target, prop, receiver);
6360
+ return typeof value === "function" ? value.bind(target) : value;
6361
+ } });
6362
+ }
6363
+ /** The context the addon sees: identical, except that its settings writes are secret-aware. */
6364
+ function withSecretAwareSettings(context, opts) {
6365
+ const raw = context.settings;
6366
+ if (raw === void 0) return context;
6367
+ const settings = createSecretAwareSettings(raw, opts);
6368
+ return new Proxy(context, { get(target, prop, receiver) {
6369
+ if (prop === "settings") return settings;
6370
+ return Reflect.get(target, prop, receiver);
6371
+ } });
6372
+ }
6373
+ var LEAF = { kind: "leaf" };
6374
+ var DEFAULT_ITEM_ID_KEY = "id";
6375
+ function collectFields(fields, out) {
6376
+ for (const field of fields) {
6377
+ if (field.type === "group") {
6378
+ collectFields(field.fields, out);
6379
+ continue;
6380
+ }
6381
+ if (field.type === "sub-tabs") {
6382
+ for (const tab of field.tabs) collectFields(tab.fields, out);
6383
+ continue;
6384
+ }
6385
+ if (field.type === "editable-array") {
6386
+ const item = /* @__PURE__ */ new Map();
6387
+ for (const itemField of field.itemFields) if ("key" in itemField && isKeychainStoredField(itemField)) item.set(itemField.key, LEAF);
6388
+ if (item.size > 0) out.set(field.key, {
6389
+ kind: "array",
6390
+ idKey: field.itemIdKey ?? DEFAULT_ITEM_ID_KEY,
6391
+ item
6392
+ });
6393
+ continue;
6394
+ }
6395
+ if (!("key" in field) || typeof field.key !== "string") continue;
6396
+ if (isKeychainStoredField(field)) out.set(field.key, LEAF);
6397
+ }
6398
+ }
6399
+ /** The secret tree a settings schema declares. */
6400
+ function secretTreeFromSchema(schema) {
6401
+ const out = /* @__PURE__ */ new Map();
6402
+ if (schema === null) return out;
6403
+ for (const section of schema.sections) collectFields(section.fields, out);
6404
+ return out;
6405
+ }
6406
+ /** Parse `a.b[id].c` into segments; throws on a malformed path (a declaration bug). */
6407
+ function parseSecretStatePath(path) {
6408
+ const segments = [];
6409
+ for (const raw of path.split(".")) {
6410
+ const m = /^([^[\]]+)(?:\[([^[\]]+)\])?$/.exec(raw);
6411
+ if (m === null || m[1] === void 0) throw new Error(`secretStatePaths: malformed path "${path}"`);
6412
+ segments.push(m[2] !== void 0 ? {
6413
+ key: m[1],
6414
+ idKey: m[2]
6415
+ } : { key: m[1] });
6416
+ }
6417
+ if (segments.length === 0) throw new Error(`secretStatePaths: empty path`);
6418
+ if (segments[segments.length - 1]?.idKey !== void 0) throw new Error(`secretStatePaths: "${path}" ends on an array — name the member that is secret`);
6419
+ return segments;
6420
+ }
6421
+ function insert(into, segments) {
6422
+ const [head, ...rest] = segments;
6423
+ if (head === void 0) return;
6424
+ if (rest.length === 0) {
6425
+ into.set(head.key, LEAF);
6426
+ return;
6427
+ }
6428
+ const existing = into.get(head.key);
6429
+ if (head.idKey !== void 0) {
6430
+ const item = new Map(existing?.kind === "array" ? existing.item : []);
6431
+ insert(item, rest);
6432
+ into.set(head.key, {
6433
+ kind: "array",
6434
+ idKey: head.idKey,
6435
+ item
6436
+ });
6437
+ return;
6438
+ }
6439
+ const children = new Map(existing?.kind === "object" ? existing.children : []);
6440
+ insert(children, rest);
6441
+ into.set(head.key, {
6442
+ kind: "object",
6443
+ children
6444
+ });
6445
+ }
6446
+ /** Add hidden-state paths (`secretStatePaths`) to a schema-derived tree. */
6447
+ function mergeSecretStatePaths(tree, paths) {
6448
+ if (paths.length === 0) return tree;
6449
+ const out = new Map(tree);
6450
+ for (const path of paths) insert(out, parseSecretStatePath(path));
6451
+ return out;
6452
+ }
6453
+ /** First retry of a secret the keychain could not serve; doubles to {@link SECRET_RETRY_MAX_MS}. */
6454
+ var SECRET_RETRY_FIRST_MS = 5e3;
6455
+ var SECRET_RETRY_MAX_MS = 5 * 6e4;
6456
+ /** Coalesces a burst of `keychain.changed` events into one re-resolve. */
6457
+ var SECRET_CHANGE_DEBOUNCE_MS = 250;
5922
6458
  /**
5923
6459
  * Base class for CamStack addons. Eliminates settings boilerplate:
5924
6460
  *
@@ -5988,6 +6524,25 @@ var BaseAddon = class {
5988
6524
  settingsStoreReady = false;
5989
6525
  /** Default config values. Provided via constructor. */
5990
6526
  defaults;
6527
+ /**
6528
+ * Hidden-state paths that hold secrets (D787) — values the addon writes
6529
+ * itself (`updateGlobalSettings`, `state()`) that no form field declares.
6530
+ * Stored in the keychain exactly like a `password` field. Syntax:
6531
+ * `'snapshotSigningKey'`, `'identity.pincode'`, `'tokens[userId].accessToken'`
6532
+ * (`key[<id field>]` addresses array items by id, never by index).
6533
+ */
6534
+ secretStatePaths = [];
6535
+ _addonSecretTree = null;
6536
+ _deviceSecretTree = null;
6537
+ /** Refs the last resolved config pointed at — a change to one re-resolves. */
6538
+ _configSecretRefs = /* @__PURE__ */ new Set();
6539
+ _unresolvedSecrets = [];
6540
+ _secretRetryTimer = null;
6541
+ _secretRetryDelayMs = SECRET_RETRY_FIRST_MS;
6542
+ _secretChangeTimer = null;
6543
+ _secretChangeUnsub = null;
6544
+ /** >0 while an OPERATOR's settings write is being applied. */
6545
+ _operatorWriteDepth = 0;
5991
6546
  constructor(defaults) {
5992
6547
  this.defaults = defaults;
5993
6548
  this._config = { ...defaults };
@@ -6023,8 +6578,18 @@ var BaseAddon = class {
6023
6578
  return this._config;
6024
6579
  }
6025
6580
  async initialize(context) {
6026
- this._ctx = context;
6581
+ const secrets = context.secrets;
6582
+ this._ctx = secrets !== void 0 ? withSecretAwareSettings(context, {
6583
+ secrets,
6584
+ addonTree: () => this.addonSecretTree(),
6585
+ deviceTree: () => this.deviceSecretTree(),
6586
+ onOrphaned: (refs) => context.logger.warn("keychain refs dropped by a settings write could not be deleted", { meta: { refs: [...refs] } }),
6587
+ isOperatorWrite: () => this._operatorWriteDepth > 0
6588
+ }) : context;
6027
6589
  await this.resolveConfig();
6590
+ if (secrets !== void 0) this._secretChangeUnsub = secrets.onChange((ref) => {
6591
+ if (this._configSecretRefs.has(ref)) this.scheduleSecretReresolve(SECRET_CHANGE_DEBOUNCE_MS);
6592
+ });
6028
6593
  const result = await this.onInitialize();
6029
6594
  this.emitLifecycle(EventCategory.AddonStarted);
6030
6595
  const normalized = normalizeAddonInitResult(result);
@@ -6057,6 +6622,12 @@ var BaseAddon = class {
6057
6622
  */
6058
6623
  async onHubReachable() {}
6059
6624
  async shutdown() {
6625
+ this._secretChangeUnsub?.();
6626
+ this._secretChangeUnsub = null;
6627
+ if (this._secretRetryTimer !== null) clearTimeout(this._secretRetryTimer);
6628
+ if (this._secretChangeTimer !== null) clearTimeout(this._secretChangeTimer);
6629
+ this._secretRetryTimer = null;
6630
+ this._secretChangeTimer = null;
6060
6631
  this.emitLifecycle(EventCategory.AddonStopped);
6061
6632
  if (this.autoEmitReadiness) this.emitReadinessForProviders("down");
6062
6633
  await this.onShutdown();
@@ -6135,7 +6706,7 @@ var BaseAddon = class {
6135
6706
  return hydrateSchema(schema, overlay ? {
6136
6707
  ...projected,
6137
6708
  ...overlay
6138
- } : projected);
6709
+ } : projected, { inlineSecretsAsViews: true });
6139
6710
  }
6140
6711
  /**
6141
6712
  * The integration-level view of this addon's settings: exactly the sections
@@ -6184,7 +6755,7 @@ var BaseAddon = class {
6184
6755
  return hydrateSchema({
6185
6756
  ...schema,
6186
6757
  sections
6187
- }, projected);
6758
+ }, projected, { inlineSecretsAsViews: true });
6188
6759
  }
6189
6760
  /**
6190
6761
  * The raw addon store PROJECTED onto the target node's bare per-node keys:
@@ -6238,18 +6809,50 @@ var BaseAddon = class {
6238
6809
  value: result.value[key]
6239
6810
  };
6240
6811
  }
6812
+ /**
6813
+ * The OPERATOR's write — a settings form or an admin API call, dispatched by
6814
+ * the kernel. Identical to {@link updateGlobalSettings}, except that a secret
6815
+ * the operator sends is stored as sent even when it equals a pre-keychain
6816
+ * inline value: the operator re-entering a password is a change, an addon
6817
+ * writing back what it read is not (D787).
6818
+ */
6819
+ async updateGlobalSettingsAsOperator(patch, nodeId) {
6820
+ this._operatorWriteDepth++;
6821
+ try {
6822
+ await this.applyGlobalPatch(patch, nodeId);
6823
+ } finally {
6824
+ this._operatorWriteDepth--;
6825
+ }
6826
+ }
6241
6827
  async updateGlobalSettings(patch, nodeId) {
6828
+ await this.applyGlobalPatch(patch, nodeId);
6829
+ }
6830
+ /**
6831
+ * REMOVE stored secrets — their keychain values and their markers (D787).
6832
+ *
6833
+ * Writing `''` to a secret field KEEPS what is stored (an empty string is
6834
+ * what a defaults fallback writes back, and it must never destroy a
6835
+ * credential), so code that means "forget this token" says so here. Without
6836
+ * a keychain (an older kernel) it writes `''`, as such code always did.
6837
+ */
6838
+ async clearSecrets(keys, nodeId) {
6839
+ const tree = this.addonSecretTree();
6840
+ const keychain = this._ctx?.secrets !== void 0;
6841
+ const patch = {};
6842
+ for (const key of keys) patch[key] = keychain && tree.has(key) ? SECRET_CLEAR : "";
6843
+ await this.applyGlobalPatch(patch, nodeId);
6844
+ }
6845
+ async applyGlobalPatch(barePatch, nodeId) {
6242
6846
  const keys = this.perNodeKeys();
6243
6847
  const localNode = normalizeNodeId(this._ctx?.kernel?.localNodeId);
6244
6848
  const target = normalizeNodeId(nodeId ?? this._ctx?.kernel?.localNodeId);
6245
- const barePatch = patch;
6246
6849
  const scoped = keys.size > 0 ? scopePatch(barePatch, keys, target) : barePatch;
6247
6850
  await this._ctx?.settings?.writeAddonStore(scoped);
6248
6851
  if (target !== localNode) return;
6249
6852
  await this.resolveConfig();
6250
6853
  await this.onConfigChanged();
6251
6854
  this.emitLifecycle(EventCategory.AddonUpdated, { level: "global" });
6252
- this.maybeAutoRestart(patch, this.globalSettingsSchema());
6855
+ this.maybeAutoRestart(Object.keys(barePatch), this.globalSettingsSchema());
6253
6856
  }
6254
6857
  /**
6255
6858
  * The set of field keys the global settings schema declares `perNode: true`
@@ -6274,7 +6877,7 @@ var BaseAddon = class {
6274
6877
  * time to return its response before the addon is torn down and
6275
6878
  * re-initialised by `AddonRegistryService.restartAddon`.
6276
6879
  */
6277
- maybeAutoRestart(patch, schema) {
6880
+ maybeAutoRestart(patchKeys, schema) {
6278
6881
  if (!schema) return;
6279
6882
  const restartKeys = /* @__PURE__ */ new Set();
6280
6883
  for (const section of schema.sections) for (const field of section.fields) {
@@ -6282,13 +6885,13 @@ var BaseAddon = class {
6282
6885
  if (field.requiresRestart) restartKeys.add(field.key);
6283
6886
  }
6284
6887
  if (restartKeys.size === 0) return;
6285
- if (!Object.keys(patch).some((k) => restartKeys.has(k))) return;
6888
+ if (!patchKeys.some((k) => restartKeys.has(k))) return;
6286
6889
  const ctx = this._ctx;
6287
6890
  if (!ctx) return;
6288
6891
  const addonId = ctx.id;
6289
6892
  setImmediate(() => {
6290
6893
  ctx.api.addons?.restartAddon?.mutate({ addonId }).then(() => {
6291
- ctx.logger.info("addon auto-restart triggered by restart-required setting change", { meta: { changedFields: Object.keys(patch).filter((k) => restartKeys.has(k)) } });
6894
+ ctx.logger.info("addon auto-restart triggered by restart-required setting change", { meta: { changedFields: patchKeys.filter((k) => restartKeys.has(k)) } });
6292
6895
  }).catch((err) => {
6293
6896
  ctx.logger.error("addon auto-restart failed", { meta: { error: err instanceof Error ? err.message : String(err) } });
6294
6897
  });
@@ -6297,7 +6900,7 @@ var BaseAddon = class {
6297
6900
  async getDeviceSettings(deviceId) {
6298
6901
  const schema = this.deviceSettingsSchema();
6299
6902
  if (!schema) return { sections: [] };
6300
- return hydrateSchema(schema, await this._ctx?.settings?.readDeviceStore(deviceId) ?? {});
6903
+ return hydrateSchema(schema, await this._ctx?.settings?.readDeviceStore(deviceId) ?? {}, { inlineSecretsAsViews: true });
6301
6904
  }
6302
6905
  async updateDeviceSettings(deviceId, patch) {
6303
6906
  await this._ctx?.settings?.writeDeviceStore(deviceId, patch);
@@ -6427,7 +7030,7 @@ var BaseAddon = class {
6427
7030
  * selection at boot (absent scoped key ⇒ the constructor default wins).
6428
7031
  */
6429
7032
  async resolveConfig() {
6430
- const stored = await this.readAddonStoreWithRetry();
7033
+ const stored = await this.resolveStoredSecrets(await this.readAddonStoreWithRetry());
6431
7034
  const perNode = this.perNodeKeys();
6432
7035
  const localNode = normalizeNodeId(this._ctx?.kernel?.localNodeId);
6433
7036
  const resolved = { ...this.defaults };
@@ -6452,7 +7055,7 @@ var BaseAddon = class {
6452
7055
  key,
6453
7056
  schema,
6454
7057
  fallback,
6455
- read: () => this.readAddonStoreWithRetry(),
7058
+ read: async () => this.resolveStoredSecrets(await this.readAddonStoreWithRetry()),
6456
7059
  write: async (patch) => {
6457
7060
  await this._ctx?.settings?.writeAddonStore(patch);
6458
7061
  },
@@ -6469,7 +7072,7 @@ var BaseAddon = class {
6469
7072
  key,
6470
7073
  schema,
6471
7074
  fallback,
6472
- read: async () => await this._ctx?.settings?.readDeviceStore(deviceId) ?? {},
7075
+ read: async () => this.resolveStoredSecrets(await this._ctx?.settings?.readDeviceStore(deviceId) ?? {}, false),
6473
7076
  write: async (patch) => {
6474
7077
  await this._ctx?.settings?.writeDeviceStore(deviceId, patch);
6475
7078
  },
@@ -6481,6 +7084,70 @@ var BaseAddon = class {
6481
7084
  } })
6482
7085
  });
6483
7086
  }
7087
+ /** The addon store's secret tree: schema fields by TYPE, plus `secretStatePaths`. */
7088
+ addonSecretTree() {
7089
+ this._addonSecretTree ??= mergeSecretStatePaths(secretTreeFromSchema(this.globalSettingsSchema()), this.secretStatePaths);
7090
+ return this._addonSecretTree;
7091
+ }
7092
+ deviceSecretTree() {
7093
+ this._deviceSecretTree ??= secretTreeFromSchema(this.deviceSettingsSchema());
7094
+ return this._deviceSecretTree;
7095
+ }
7096
+ /**
7097
+ * Secrets of this addon's stored config that could not be resolved on the
7098
+ * last read, with why. Non-empty means the addon is running WITHOUT them —
7099
+ * an addon whose function needs one should report itself degraded rather
7100
+ * than start on an empty credential.
7101
+ */
7102
+ get unresolvedSecrets() {
7103
+ return this._unresolvedSecrets;
7104
+ }
7105
+ /**
7106
+ * Substitute every keychain marker in a stored blob with its value. With no
7107
+ * keychain (no `ctx.secrets`) or no marker, the blob comes back unchanged.
7108
+ * An unresolvable value is LEFT OUT (never `''`), logged by ref — never by
7109
+ * value — and, when the cause can pass, retried with backoff. Nothing is
7110
+ * ever written back from here.
7111
+ */
7112
+ async resolveStoredSecrets(blob, trackForConfig = true) {
7113
+ const secrets = this._ctx?.secrets;
7114
+ if (secrets === void 0) return blob;
7115
+ const refs = collectSecretMarkerRefs(blob);
7116
+ if (trackForConfig) this._configSecretRefs = new Set(refs);
7117
+ if (refs.length === 0) {
7118
+ if (trackForConfig) this._unresolvedSecrets = [];
7119
+ return blob;
7120
+ }
7121
+ const { value, unresolved } = await resolveSecretMarkers(blob, secrets);
7122
+ if (trackForConfig) {
7123
+ this._unresolvedSecrets = unresolved;
7124
+ if (unresolved.length > 0) {
7125
+ this._ctx?.logger?.error?.("secret unavailable — running without it, will retry", { meta: { secrets: unresolved.map((u) => ({
7126
+ ref: u.ref,
7127
+ reason: u.reason
7128
+ })) } });
7129
+ if (unresolved.some((u) => u.reason !== "missing" && u.reason !== "forbidden")) {
7130
+ this.scheduleSecretReresolve(this._secretRetryDelayMs);
7131
+ this._secretRetryDelayMs = Math.min(this._secretRetryDelayMs * 2, SECRET_RETRY_MAX_MS);
7132
+ }
7133
+ } else this._secretRetryDelayMs = SECRET_RETRY_FIRST_MS;
7134
+ }
7135
+ return value;
7136
+ }
7137
+ /** Re-resolve the config (a keychain-only change, or a retry) and apply it. */
7138
+ scheduleSecretReresolve(delayMs) {
7139
+ const timerOf = delayMs === SECRET_CHANGE_DEBOUNCE_MS ? "_secretChangeTimer" : "_secretRetryTimer";
7140
+ if (this[timerOf] !== null) return;
7141
+ const timer = setTimeout(() => {
7142
+ this[timerOf] = null;
7143
+ if (this._ctx === null) return;
7144
+ this.resolveConfig().then(() => this.onConfigChanged()).catch((err) => {
7145
+ this._ctx?.logger?.error?.("re-resolving secrets failed", { meta: { error: err instanceof Error ? err.message : String(err) } });
7146
+ });
7147
+ }, delayMs);
7148
+ timer.unref?.();
7149
+ this[timerOf] = timer;
7150
+ }
6484
7151
  /**
6485
7152
  * Wrap `ctx.settings.readAddonStore()` with a short retry budget so a
6486
7153
  * transient settings-store outage (mid-restart of sqlite-settings, tsx-watch
@@ -7056,6 +7723,69 @@ method(object({ deviceId: number() }), array(StreamSourceEntrySchema)), method(o
7056
7723
  kind: "mutation",
7057
7724
  auth: "admin"
7058
7725
  }), method(object({ deviceId: number() }), unknown().nullable()), method(object({ deviceId: number() }), RawStateResultSchema.nullable(), { auth: "protected" });
7726
+ function defOf(schema) {
7727
+ return schema._zod?.def ?? {};
7728
+ }
7729
+ function declaredHere(schema) {
7730
+ return globalRegistry.get(schema)?.secret === true;
7731
+ }
7732
+ /** Wrapper kinds whose `innerType` is the field itself. */
7733
+ var WRAPPERS = new Set([
7734
+ "optional",
7735
+ "nullable",
7736
+ "default",
7737
+ "prefault",
7738
+ "catch",
7739
+ "readonly",
7740
+ "nonoptional"
7741
+ ]);
7742
+ /**
7743
+ * The schema layers that make up ONE field: the schema itself and every
7744
+ * wrapper below it (optional / default / nullable / readonly / catch), plus
7745
+ * both sides of a pipe (`z.preprocess` puts the real schema on `out`,
7746
+ * `.transform` on `in`).
7747
+ */
7748
+ function layersOf(schema) {
7749
+ const out = [];
7750
+ const queue = [schema];
7751
+ while (queue.length > 0) {
7752
+ const s = queue.shift();
7753
+ if (!s || out.includes(s)) continue;
7754
+ out.push(s);
7755
+ const def = defOf(s);
7756
+ if (def.type !== void 0 && WRAPPERS.has(def.type) && def.innerType) queue.push(def.innerType);
7757
+ if (def.type === "pipe") {
7758
+ if (def.in) queue.push(def.in);
7759
+ if (def.out) queue.push(def.out);
7760
+ }
7761
+ }
7762
+ return out;
7763
+ }
7764
+ /** True when any layer of this field declares `.meta({ secret: true })`. */
7765
+ function isZodSecret(schema) {
7766
+ return layersOf(schema).some(declaredHere);
7767
+ }
7768
+ /**
7769
+ * Every declared secret path in a config schema: dotted keys, `[]` for "each
7770
+ * element of this array" (`connection.password`, `rows[].token`). A declared
7771
+ * object or array is reported as one path and not descended into — everything
7772
+ * under it is secret.
7773
+ */
7774
+ function collectZodSecretPaths(schema, prefix = "") {
7775
+ if (isZodSecret(schema)) return prefix.length > 0 ? [prefix] : [];
7776
+ const paths = [];
7777
+ for (const layer of layersOf(schema)) {
7778
+ const def = defOf(layer);
7779
+ if (def.type === "object" && def.shape) for (const [key, child] of Object.entries(def.shape)) paths.push(...collectZodSecretPaths(child, prefix ? `${prefix}.${key}` : key));
7780
+ else if (def.type === "array" && def.element) paths.push(...collectZodSecretPaths(def.element, `${prefix}[]`));
7781
+ else if (def.type === "union" && def.options) for (const option of def.options) paths.push(...collectZodSecretPaths(option, prefix));
7782
+ else if (def.type === "intersection") {
7783
+ if (def.left) paths.push(...collectZodSecretPaths(def.left, prefix));
7784
+ if (def.right) paths.push(...collectZodSecretPaths(def.right, prefix));
7785
+ }
7786
+ }
7787
+ return [...new Set(paths)];
7788
+ }
7059
7789
  //#endregion
7060
7790
  //#region ../types/dist/err-msg-DX6i_MY4.mjs
7061
7791
  var DeviceType = /* @__PURE__ */ function(DeviceType) {
@@ -14135,6 +14865,196 @@ id: union([string$2(), number()]) }), {
14135
14865
  kind: "mutation",
14136
14866
  auth: "admin"
14137
14867
  });
14868
+ /**
14869
+ * `keychain` — the hub's encrypted store of secret values (D787).
14870
+ *
14871
+ * Settings blobs never hold a secret: they hold a marker
14872
+ * `{"$secret":"secret://<owner>/<scope>/<fieldPath>","v":1}` and the value
14873
+ * lives here, AES-256-GCM under a data key that a master key wraps. This cap
14874
+ * is the OWNER's door to its own values: every method is owner-checked
14875
+ * against the CALLER, never against anything the caller claims.
14876
+ *
14877
+ * Who the caller is: the transport stamps `callerAddonId` into the args of a
14878
+ * call that crossed a process (the parent `LocalChildRegistry` from the UDS
14879
+ * connection, the agent from its child's connection carried in
14880
+ * `$hub-cap-fwd`'s envelope). A stamp always overwrites; a wire call with no
14881
+ * stamp has its claim stripped. Only a hub in-process caller may state its own
14882
+ * identity — `ctx.secrets` does that with the addon id closed over. This is
14883
+ * identity against BUGS and misrouting, not against a malicious addon (every
14884
+ * runner is the same OS user): see the threat model in
14885
+ * `docs/design/2026-10-08-secrets-keychain.md`.
14886
+ *
14887
+ * `callerAddonId` is deliberately NOT in any input schema: the tRPC router
14888
+ * parses the input, so a session can never supply it, and the internal mount
14889
+ * floors every method to admin anyway (D240).
14890
+ *
14891
+ * Internal: addons reach it through `ctx.secrets`, never directly.
14892
+ */
14893
+ /** Why a value cannot be served right now. Never folded into "missing". */
14894
+ var KeychainUnavailableReasonSchema = _enum([
14895
+ "key-missing",
14896
+ "wrong-key",
14897
+ "key-file-unreadable",
14898
+ "store-unavailable",
14899
+ "not-initialized",
14900
+ "decrypt-failed"
14901
+ ]);
14902
+ var KeychainStateSchema = discriminatedUnion("state", [object({ state: literal("ready") }), object({
14903
+ state: literal("locked"),
14904
+ reason: KeychainUnavailableReasonSchema
14905
+ })]);
14906
+ var KeychainResolveEntrySchema = discriminatedUnion("kind", [
14907
+ object({
14908
+ kind: literal("value"),
14909
+ value: string$2(),
14910
+ version: number().int()
14911
+ }),
14912
+ object({ kind: literal("missing") }),
14913
+ object({
14914
+ kind: literal("unavailable"),
14915
+ reason: KeychainUnavailableReasonSchema
14916
+ }),
14917
+ object({ kind: literal("forbidden") })
14918
+ ]);
14919
+ var KeychainResolveResultSchema = record(string$2(), KeychainResolveEntrySchema);
14920
+ /** Metadata of one stored value — never the value. */
14921
+ var KeychainSecretMetaSchema = object({
14922
+ ref: string$2(),
14923
+ owner: string$2(),
14924
+ /** Formatted scope (`global`, `node/<id>`, `device/<id>`, …). */
14925
+ scope: string$2(),
14926
+ fieldPath: string$2(),
14927
+ version: number().int(),
14928
+ createdAt: number(),
14929
+ updatedAt: number(),
14930
+ /** `addon:<id>` | `user:<id>` | `system`. */
14931
+ updatedBy: string$2(),
14932
+ /** Coarse — written at most once an hour per ref. `null` = never read. */
14933
+ lastReadAt: number().nullable()
14934
+ });
14935
+ var RefListSchema = array(string$2().min(1)).max(512);
14936
+ method(object({
14937
+ ref: string$2().min(1),
14938
+ value: string$2().min(1)
14939
+ }), object({
14940
+ ref: string$2(),
14941
+ version: number().int()
14942
+ }), {
14943
+ kind: "mutation",
14944
+ auth: "admin"
14945
+ }), method(object({ refs: RefListSchema }), KeychainResolveResultSchema, { auth: "admin" }), method(object({ refs: RefListSchema }), object({ deleted: number().int() }), {
14946
+ kind: "mutation",
14947
+ auth: "admin"
14948
+ }), method(object({}), array(KeychainSecretMetaSchema).readonly(), { auth: "admin" }), method(object({}), KeychainStateSchema, { auth: "admin" });
14949
+ var KeychainKeySourceSchema = object({
14950
+ kind: _enum([
14951
+ "config-file",
14952
+ "previous-config-file",
14953
+ "platform",
14954
+ "default-file"
14955
+ ]),
14956
+ /** File sources only — a path is not a secret. */
14957
+ path: string$2().optional(),
14958
+ /**
14959
+ * True when a whole-volume backup of the data directory carries this key
14960
+ * next to the database it protects (the default file). The page warns.
14961
+ */
14962
+ sharesBackupWithDatabase: boolean()
14963
+ });
14964
+ var KeychainStatusSchema = object({
14965
+ keychain: KeychainStateSchema,
14966
+ /** The source of the master key in use; `null` while locked. */
14967
+ keySource: KeychainKeySourceSchema.nullable(),
14968
+ /** The source configured to be primary — differs from `keySource` while a rotation is pending. */
14969
+ configuredSource: KeychainKeySourceSchema,
14970
+ /** Short fingerprint of the master key in use (`HMAC(KEK, label)`, 16 hex). */
14971
+ fingerprint: string$2().nullable(),
14972
+ activeKeyId: string$2().nullable(),
14973
+ /**
14974
+ * The keychain unlocked with a NON-primary source: the configured primary
14975
+ * key is not the one that wraps the data key yet. `rotateMasterKey` moves it.
14976
+ */
14977
+ rotationPending: boolean(),
14978
+ /** Wrapped copies of the data key under a previous master key, kept until purged. */
14979
+ retiredWraps: number().int(),
14980
+ recoveryKeyDownloadedAt: number().nullable(),
14981
+ secretCount: number().int()
14982
+ });
14983
+ /**
14984
+ * Whether a stored value is still pointed at by its owner's settings.
14985
+ * `unknown` is a first-class answer: a scope whose blob could not be read is
14986
+ * never reported as an orphan (and never deleted as one).
14987
+ */
14988
+ var KeychainSecretUsageSchema = _enum([
14989
+ "in-use",
14990
+ "orphan",
14991
+ "unknown"
14992
+ ]);
14993
+ var KeychainAdminSecretSchema = KeychainSecretMetaSchema.extend({ usage: KeychainSecretUsageSchema });
14994
+ var KeychainAuditActionSchema = _enum([
14995
+ "put",
14996
+ "delete",
14997
+ "reveal",
14998
+ "rotate-master-key",
14999
+ "purge-retired-keys",
15000
+ "download-recovery-key",
15001
+ "delete-orphans",
15002
+ "reset",
15003
+ "initialize"
15004
+ ]);
15005
+ var KeychainAuditEntrySchema = object({
15006
+ id: string$2(),
15007
+ at: number(),
15008
+ action: KeychainAuditActionSchema,
15009
+ /** `addon:<id>` | `user:<id>` | `system`. */
15010
+ actor: string$2(),
15011
+ ref: string$2().nullable(),
15012
+ detail: string$2().nullable()
15013
+ });
15014
+ 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$2().min(1) }), object({
15015
+ value: string$2(),
15016
+ version: number().int()
15017
+ }), {
15018
+ kind: "mutation",
15019
+ auth: "admin",
15020
+ caller: "required"
15021
+ }), method(object({ refs: array(string$2().min(1)).max(1e3) }), object({
15022
+ deleted: array(string$2()).readonly(),
15023
+ kept: array(object({
15024
+ ref: string$2(),
15025
+ usage: KeychainSecretUsageSchema
15026
+ })).readonly()
15027
+ }), {
15028
+ kind: "mutation",
15029
+ auth: "admin",
15030
+ caller: "required"
15031
+ }), method(object({}), object({
15032
+ fingerprint: string$2(),
15033
+ keySource: KeychainKeySourceSchema
15034
+ }), {
15035
+ kind: "mutation",
15036
+ auth: "admin",
15037
+ caller: "required"
15038
+ }), method(object({}), object({ purged: number().int() }), {
15039
+ kind: "mutation",
15040
+ auth: "admin",
15041
+ caller: "required"
15042
+ }), method(object({}), object({
15043
+ key: string$2(),
15044
+ fingerprint: string$2(),
15045
+ keySource: KeychainKeySourceSchema
15046
+ }), {
15047
+ kind: "mutation",
15048
+ auth: "admin",
15049
+ caller: "required"
15050
+ }), method(object({ confirm: literal("RESET KEYCHAIN") }), object({
15051
+ archivedCollection: string$2().nullable(),
15052
+ archived: number().int()
15053
+ }), {
15054
+ kind: "mutation",
15055
+ auth: "admin",
15056
+ caller: "required"
15057
+ });
14138
15058
  method(_void(), object({
14139
15059
  id: string$2(),
14140
15060
  name: string$2(),
@@ -15377,7 +16297,11 @@ var DeviceRegisterPayloadSchema = object({
15377
16297
  var DeviceRemovePayloadSchema = object({ deviceId: number() });
15378
16298
  var DevicePersistConfigPayloadSchema = object({
15379
16299
  deviceId: number(),
15380
- data: record(string$2(), unknown())
16300
+ data: record(string$2(), unknown()),
16301
+ /** The paths the device's schema declares secret (D783), when the caller
16302
+ * knows them — those values are kept in the keychain, not the blob (D787).
16303
+ * Absent: the paths the device last reported at `registerDevice` apply. */
16304
+ secretConfigPaths: array(string$2()).optional()
15381
16305
  });
15382
16306
  /** What a migration actually did, per switch. `unreachable` is a first-class
15383
16307
  * answer: a camera that could not be asked is not a camera that was silenced. */
@@ -22394,8 +23318,23 @@ var RetrainMacroClassSchema = _enum([
22394
23318
  ]);
22395
23319
  /** A subject to learn, or a phantom to unlearn (taught by OMISSION). */
22396
23320
  var RetrainAnnotationKindSchema = _enum(["subject", "model_error"]);
22397
- /** Did a human draw this box, or did the assist propose it? */
22398
- var RetrainAnnotationSourceSchema = _enum(["operator", "assist"]);
23321
+ /**
23322
+ * Where a box came from. A machine-sourced box is a DRAFT on the page until
23323
+ * the operator confirms it; once saved it keeps its source as provenance.
23324
+ *
23325
+ * - `operator` — drawn by hand.
23326
+ * - `assist` — proposed by a detector run on the copy (the camera's own
23327
+ * model, or a larger teacher model).
23328
+ * - `pipeline` — the box the live pipeline actually drew on that frame, read
23329
+ * back from the track store (never a re-run).
23330
+ * - `llm` — proposed by a vision-capable LLM profile.
23331
+ */
23332
+ var RetrainAnnotationSourceSchema = _enum([
23333
+ "operator",
23334
+ "assist",
23335
+ "pipeline",
23336
+ "llm"
23337
+ ]);
22399
23338
  /** Normalised `[0,1]` rectangle against the FULL frame — the canonical form. */
22400
23339
  var RetrainBboxSchema = object({
22401
23340
  x: number(),
@@ -22413,7 +23352,8 @@ var RetrainBboxSchema = object({
22413
23352
  */
22414
23353
  var RetrainAnnotationSchema = object({
22415
23354
  id: string$2(),
22416
- trackId: string$2(),
23355
+ /** The frame's track. Absent on a recording still, which has none. */
23356
+ trackId: string$2().optional(),
22417
23357
  deviceId: number(),
22418
23358
  /** The COPY in retrain storage — never the source track's media key. */
22419
23359
  mediaKey: string$2(),
@@ -22462,13 +23402,47 @@ var RetrainFrameCandidateSchema = object({
22462
23402
  * fail, whatever became of the original. */
22463
23403
  copied: boolean()
22464
23404
  });
23405
+ /**
23406
+ * One box the live pipeline drew on a copied frame — what a correction starts
23407
+ * from. Derived when the frame is listed, from the track store: the subject
23408
+ * box recorded on the source media row when there is one, else the track
23409
+ * position nearest the frame's capture time. Never stored as an annotation
23410
+ * until the operator confirms it.
23411
+ */
23412
+ var RetrainPipelineBoxSchema = object({
23413
+ /** Normalised `[0,1]` against the full frame. */
23414
+ bbox: RetrainBboxSchema,
23415
+ macroClass: RetrainMacroClassSchema,
23416
+ label: string$2().optional(),
23417
+ subLabel: string$2().optional(),
23418
+ /** The detection score of the position used, when it was recorded. */
23419
+ score: number().optional(),
23420
+ /** The root model that produced the track, when it was recorded. */
23421
+ modelId: string$2().optional(),
23422
+ trackId: string$2(),
23423
+ /** `subject-box`: recorded on this very frame. `position`: the track's
23424
+ * position nearest the capture time, `deltaMs` away. */
23425
+ basis: _enum(["subject-box", "position"]),
23426
+ deltaMs: number()
23427
+ });
23428
+ /**
23429
+ * Where a retrain frame came from: a TRACK's stored media (copy-on-select),
23430
+ * or the RECORDING at an instant — the frame a model saw nothing in has no
23431
+ * track at all.
23432
+ */
23433
+ var RetrainFrameOriginSchema = _enum(["track", "recording"]);
22465
23434
  /** A frame the dataset OWNS: bytes copied at selection time. */
22466
23435
  var RetrainFrameSchema = object({
22467
23436
  frameId: string$2(),
22468
23437
  deviceId: number(),
22469
- trackId: string$2(),
22470
- /** Provenance only. It may already point at nothing — that is expected. */
22471
- sourceMediaId: number().int(),
23438
+ origin: RetrainFrameOriginSchema,
23439
+ /** The track it was copied from. Absent on a recording still. */
23440
+ trackId: string$2().optional(),
23441
+ /** Provenance only. It may already point at nothing — that is expected.
23442
+ * Absent on a recording still. */
23443
+ sourceMediaId: number().int().optional(),
23444
+ /** A recording still: the playhead instant it was taken at. */
23445
+ epochMs: number().optional(),
22472
23446
  sourceKind: MediaFileKindEnum,
22473
23447
  sizeBytes: number().int(),
22474
23448
  width: number().int(),
@@ -22479,7 +23453,12 @@ var RetrainFrameSchema = object({
22479
23453
  /** The operator's "every subject in this frame is boxed". Detector
22480
23454
  * evaluation keeps only complete frames: an unboxed subject would count as
22481
23455
  * a false positive. */
22482
- complete: boolean()
23456
+ complete: boolean(),
23457
+ /** The boxes the pipeline drew on this frame. Present on list answers;
23458
+ * empty when nothing the track store holds can be placed on it. */
23459
+ pipelineBoxes: array(RetrainPipelineBoxSchema).readonly().optional(),
23460
+ /** The named collections this frame belongs to. Present on list answers. */
23461
+ collectionIds: array(string$2()).readonly().optional()
22483
23462
  });
22484
23463
  /** Why a copy-on-select could not be honoured — named, never a silent skip. */
22485
23464
  var RetrainCopyRefusalSchema = _enum([
@@ -22510,6 +23489,8 @@ var RetrainFrameListSchema = object({
22510
23489
  var RetrainExportFilterSchema = object({
22511
23490
  deviceIds: array(number()).optional(),
22512
23491
  frameIds: array(string$2()).max(2e4).optional(),
23492
+ /** Only frames in at least one of these named collections. */
23493
+ collectionIds: array(string$2()).max(200).optional(),
22513
23494
  batchId: string$2().optional(),
22514
23495
  /** Only frames the operator marked complete (all subjects boxed). */
22515
23496
  completeOnly: boolean().optional()
@@ -22574,6 +23555,109 @@ var RetrainAssistResultSchema = discriminatedUnion("kind", [object({
22574
23555
  reason: string$2(),
22575
23556
  detail: string$2().optional()
22576
23557
  })]);
23558
+ /** A named set over the retrain corpus — membership only, it owns no pixels. */
23559
+ var RetrainCollectionSchema = object({
23560
+ id: string$2(),
23561
+ name: string$2(),
23562
+ createdAt: number(),
23563
+ frameCount: number().int()
23564
+ });
23565
+ var RetrainCollectionCreateResultSchema = discriminatedUnion("kind", [object({
23566
+ kind: literal("created"),
23567
+ collection: RetrainCollectionSchema
23568
+ }), object({
23569
+ kind: literal("refused"),
23570
+ reason: _enum(["empty-name", "duplicate-name"])
23571
+ })]);
23572
+ var RetrainCollectionRenameResultSchema = discriminatedUnion("kind", [object({
23573
+ kind: literal("renamed"),
23574
+ collection: RetrainCollectionSchema
23575
+ }), object({
23576
+ kind: literal("refused"),
23577
+ reason: _enum([
23578
+ "empty-name",
23579
+ "duplicate-name",
23580
+ "unknown-collection"
23581
+ ])
23582
+ })]);
23583
+ /**
23584
+ * The outcome of adding the frame at a recording instant. Every refusal is
23585
+ * named: `still-unavailable` (not recording, a gap, or an undecodable frame —
23586
+ * `detail` says which), `still-busy` (the recorder is at its decode bound; try
23587
+ * again), `unreadable-image`, `write-failed`, `unknown-collection`.
23588
+ */
23589
+ var AddRetrainFrameFromRecordingResultSchema = discriminatedUnion("kind", [object({
23590
+ kind: literal("added"),
23591
+ collectionId: string$2(),
23592
+ frame: RetrainFrameSchema,
23593
+ /** The moment was already in the dataset; nothing was decoded. */
23594
+ reused: boolean()
23595
+ }), object({
23596
+ kind: literal("refused"),
23597
+ reason: _enum([
23598
+ "unknown-collection",
23599
+ "still-unavailable",
23600
+ "still-busy",
23601
+ "unreadable-image",
23602
+ "write-failed"
23603
+ ]),
23604
+ detail: string$2().optional()
23605
+ })]);
23606
+ /** A vision LLM profile the AI assist may use, and where it sends the frame. */
23607
+ var RetrainAssistProfileSchema = object({
23608
+ id: string$2(),
23609
+ name: string$2(),
23610
+ model: string$2(),
23611
+ kind: string$2(),
23612
+ /** `true` when the frame would leave the house (a cloud vendor, or an
23613
+ * endpoint that is not on the local network). The page confirms each such
23614
+ * run, and the provider refuses one without `allowCloud`. */
23615
+ leavesHouse: boolean()
23616
+ });
23617
+ /** A box the AI assist proposed: a draft, plus the model's own reason. */
23618
+ var RetrainLlmProposalSchema = RetrainAnnotationDraftSchema.extend({ reason: string$2() });
23619
+ /** What the AI assist said about a box that was already on the canvas. */
23620
+ var RetrainLlmReviewSchema = object({
23621
+ /** The `ref` the page sent the box under. */
23622
+ ref: string$2(),
23623
+ verdict: _enum([
23624
+ "confirmed",
23625
+ "wrong-class",
23626
+ "not-an-object",
23627
+ "uncertain"
23628
+ ]),
23629
+ suggestedClass: RetrainMacroClassSchema.optional(),
23630
+ reason: string$2()
23631
+ });
23632
+ /**
23633
+ * The AI assist's answer. `proposed` carries drafts (`source: 'llm'`, the
23634
+ * model and its confidence) and reviews; items the model got wrong (a box off
23635
+ * the frame, an unasked class, an unknown ref) are dropped and counted in
23636
+ * `rejected`. A whole answer that is not the schema is `malformed-answer`.
23637
+ */
23638
+ var RetrainLlmAssistResultSchema = discriminatedUnion("kind", [object({
23639
+ kind: literal("proposed"),
23640
+ profileId: string$2(),
23641
+ model: string$2(),
23642
+ /** The frame was sent outside the house for this answer. */
23643
+ leftHouse: boolean(),
23644
+ proposals: array(RetrainLlmProposalSchema).readonly(),
23645
+ reviews: array(RetrainLlmReviewSchema).readonly(),
23646
+ rejected: number().int()
23647
+ }), object({
23648
+ kind: literal("refused"),
23649
+ reason: _enum([
23650
+ "unknown-frame",
23651
+ "unreadable-frame",
23652
+ "unknown-profile",
23653
+ "profile-disabled",
23654
+ "no-vision",
23655
+ "cloud-not-confirmed",
23656
+ "llm-error",
23657
+ "malformed-answer"
23658
+ ]),
23659
+ detail: string$2().optional()
23660
+ })]);
22577
23661
  /** The outcome of a lifecycle move owned by the retrain page. */
22578
23662
  var RetrainTransitionResultSchema = object({
22579
23663
  trackId: string$2(),
@@ -23291,7 +24375,7 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
23291
24375
  auth: "admin"
23292
24376
  }), method(object({
23293
24377
  deviceId: number(),
23294
- trackId: string$2(),
24378
+ trackId: string$2().optional(),
23295
24379
  frameId: string$2()
23296
24380
  }), object({
23297
24381
  removed: boolean(),
@@ -23308,7 +24392,8 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
23308
24392
  auth: "admin"
23309
24393
  }), method(object({
23310
24394
  deviceId: number(),
23311
- trackId: string$2(),
24395
+ /** The frame's track, when it has one — checked against the frame. */
24396
+ trackId: string$2().optional(),
23312
24397
  frameId: string$2(),
23313
24398
  subject: RetrainAssistSubjectSchema,
23314
24399
  /** Which node runs it. Absent ⇒ wherever an unowned call lands. */
@@ -23316,12 +24401,16 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
23316
24401
  }), RetrainAssistResultSchema, {
23317
24402
  kind: "mutation",
23318
24403
  auth: "admin"
23319
- }), method(object({ trackId: string$2() }), array(RetrainAnnotationSchema).readonly(), {
24404
+ }), method(object({
24405
+ trackId: string$2().optional(),
24406
+ frameIds: array(string$2()).max(2e3).optional()
24407
+ }), array(RetrainAnnotationSchema).readonly(), {
23320
24408
  kind: "query",
23321
24409
  auth: "admin"
23322
24410
  }), method(object({
23323
24411
  deviceId: number(),
23324
- trackId: string$2(),
24412
+ /** The frame's track, when it has one — checked against the frame. */
24413
+ trackId: string$2().optional(),
23325
24414
  frameId: string$2(),
23326
24415
  annotations: array(RetrainAnnotationDraftSchema)
23327
24416
  }), array(RetrainAnnotationSchema).readonly(), {
@@ -23344,7 +24433,7 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
23344
24433
  auth: "admin"
23345
24434
  }), method(object({
23346
24435
  deviceId: number(),
23347
- trackId: string$2(),
24436
+ trackId: string$2().optional(),
23348
24437
  frameId: string$2(),
23349
24438
  complete: boolean()
23350
24439
  }), RetrainFrameSchema, {
@@ -23358,6 +24447,74 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
23358
24447
  kind: "mutation",
23359
24448
  auth: "admin",
23360
24449
  timeoutMs: 60 * 6e4
24450
+ }), method(object({}), array(RetrainAssistProfileSchema).readonly(), {
24451
+ kind: "query",
24452
+ auth: "admin"
24453
+ }), method(object({
24454
+ deviceId: number(),
24455
+ trackId: string$2().optional(),
24456
+ frameId: string$2(),
24457
+ profileId: string$2(),
24458
+ classes: array(RetrainMacroClassSchema).min(1),
24459
+ boxes: array(object({
24460
+ ref: string$2(),
24461
+ bbox: RetrainBboxSchema,
24462
+ macroClass: RetrainMacroClassSchema,
24463
+ label: string$2().optional()
24464
+ })).max(50),
24465
+ allowCloud: boolean()
24466
+ }), RetrainLlmAssistResultSchema, {
24467
+ kind: "mutation",
24468
+ auth: "admin",
24469
+ timeoutMs: 18e4
24470
+ }), method(object({ name: string$2().max(120) }), RetrainCollectionCreateResultSchema, {
24471
+ kind: "mutation",
24472
+ auth: "admin"
24473
+ }), method(object({}), array(RetrainCollectionSchema).readonly(), {
24474
+ kind: "query",
24475
+ auth: "admin"
24476
+ }), method(object({
24477
+ id: string$2(),
24478
+ name: string$2().max(120)
24479
+ }), RetrainCollectionRenameResultSchema, {
24480
+ kind: "mutation",
24481
+ auth: "admin"
24482
+ }), method(object({ id: string$2() }), object({
24483
+ deleted: boolean(),
24484
+ removedFrames: number().int()
24485
+ }), {
24486
+ kind: "mutation",
24487
+ auth: "admin"
24488
+ }), method(object({
24489
+ collectionId: string$2(),
24490
+ deviceId: number(),
24491
+ epochMs: number()
24492
+ }), AddRetrainFrameFromRecordingResultSchema, {
24493
+ kind: "mutation",
24494
+ auth: "admin",
24495
+ timeoutMs: 6e4
24496
+ }), method(object({
24497
+ collectionId: string$2(),
24498
+ frameIds: array(string$2()).min(1).max(500)
24499
+ }), object({
24500
+ added: number().int(),
24501
+ alreadyMember: number().int(),
24502
+ unknownFrameIds: array(string$2()).readonly()
24503
+ }), {
24504
+ kind: "mutation",
24505
+ auth: "admin"
24506
+ }), method(object({
24507
+ collectionId: string$2(),
24508
+ frameId: string$2()
24509
+ }), object({
24510
+ removed: boolean(),
24511
+ deletedFrame: boolean()
24512
+ }), {
24513
+ kind: "mutation",
24514
+ auth: "admin"
24515
+ }), method(object({ collectionId: string$2() }), array(RetrainFrameSchema).readonly(), {
24516
+ kind: "query",
24517
+ auth: "admin"
23361
24518
  }), method(object({
23362
24519
  /** Which of the three event tables owns the row. */
23363
24520
  ownerType: EventOwnerTypeSchema,
@@ -23981,13 +25138,31 @@ var RecommendationReasonSchema = discriminatedUnion("kind", [
23981
25138
  object({
23982
25139
  kind: literal("no-family-build"),
23983
25140
  format: ModelFormatSchema$1
25141
+ }),
25142
+ object({
25143
+ kind: literal("kept-custom-pin"),
25144
+ modelId: string$2(),
25145
+ deviceKey: string$2()
23984
25146
  })
23985
25147
  ]);
25148
+ /** Why a device is left exactly as it is, whatever the plan would pick (D786). */
25149
+ var KeptReasonSchema = _enum(["custom-pin"]);
25150
+ /**
25151
+ * Where a choice's latency came from (D791): this node's own benchmark
25152
+ * result, or the hardware-class table. Measured on the node beats the table.
25153
+ */
25154
+ var LatencySourceSchema = discriminatedUnion("kind", [object({ kind: literal("table") }), object({
25155
+ kind: literal("node-benchmark"),
25156
+ resultId: string$2(),
25157
+ measuredAtMs: number()
25158
+ })]);
23986
25159
  var DeviceModelChoiceSchema = object({
23987
25160
  modelId: string$2(),
23988
25161
  p50Ms: number(),
23989
25162
  fps: number(),
23990
25163
  measured: boolean(),
25164
+ /** Absent on a plan from before D791 — read as the table. */
25165
+ source: LatencySourceSchema.optional(),
23991
25166
  /** Parallel sessions at the camera rate with the headroom kept free: ⌊fps × (1 − headroom) / camera fps⌋. */
23992
25167
  capacitySessions: number(),
23993
25168
  personRecall: number()
@@ -23998,6 +25173,8 @@ var DeviceRecommendationSchema = object({
23998
25173
  enabled: boolean(),
23999
25174
  available: boolean(),
24000
25175
  chosen: DeviceModelChoiceSchema.nullable(),
25176
+ /** Present when the device is kept as is: Apply writes nothing on it. */
25177
+ kept: KeptReasonSchema.optional(),
24001
25178
  reasons: array(RecommendationReasonSchema).readonly()
24002
25179
  });
24003
25180
  var NodeRecommendationSchema = object({
@@ -24051,6 +25228,17 @@ var AutoTuneWarningSchema = discriminatedUnion("kind", [
24051
25228
  kind: literal("coral-enabled"),
24052
25229
  nodeId: string$2(),
24053
25230
  deviceKey: string$2()
25231
+ }),
25232
+ object({
25233
+ kind: literal("custom-pin-kept"),
25234
+ nodeId: string$2(),
25235
+ deviceKey: string$2().nullable(),
25236
+ deviceId: number().nullable(),
25237
+ modelId: string$2()
25238
+ }),
25239
+ object({
25240
+ kind: literal("custom-registry-unreadable"),
25241
+ error: string$2()
24054
25242
  })
24055
25243
  ]);
24056
25244
  var AutoTuneOptionsSchema = object({
@@ -24229,13 +25417,14 @@ var SuggestSharesResultSchema = object({
24229
25417
  nodes: array(SuggestedNodeShareSchema).readonly()
24230
25418
  });
24231
25419
  /**
24232
- * Where the node and device shares come from (D750, D755).
24233
- * - `hardware` (default) — computed by the system from each node's static
24234
- * capacity (its accelerators at their Auto tune models, from the measured
24235
- * latency table), recomputed whenever a node or device joins, leaves, is
24236
- * switched on or off, or changes model. No load input.
24237
- * - `benchmark` — the same, from each node's measured capacity (node
24238
- * benchmark results); a node without results falls back to `hardware`.
25420
+ * Where the node and device shares come from (D750, D755, D791).
25421
+ * - `benchmark` (default since D791) — each node's capacity as its own node
25422
+ * benchmark measured it; a node without fresh results is sized from
25423
+ * `hardware` and says so. Measured on the node beats the table.
25424
+ * - `hardware` — computed from each node's static capacity only (its
25425
+ * accelerators at their Auto tune models, from the latency table).
25426
+ * Both are recomputed whenever a node or device joins, leaves, is switched
25427
+ * on or off, changes model, or a benchmark result is written. No load input.
24239
25428
  * - `manual` — the operator's stored sliders.
24240
25429
  * Either way a node or device that cannot take sessions gives its share to
24241
25430
  * the others in proportion; the stored values are never rewritten for that.
@@ -24284,6 +25473,362 @@ var EffectiveSharesSchema = object({
24284
25473
  nodeWeights: record(string$2(), number()),
24285
25474
  deviceWeights: record(string$2(), record(string$2(), number()))
24286
25475
  });
25476
+ /**
25477
+ * Wire shapes of the node benchmark (D791): the operator's plan, the
25478
+ * preflight the confirmation shows, the run the orchestrator owns, what the
25479
+ * measuring runner reports, and the result rows Auto tune and the automatic
25480
+ * shares read.
25481
+ *
25482
+ * ONE node at a time, owned by the pipeline orchestrator. While a run is
25483
+ * active the cluster is in BENCHMARK MODE for that node: it is not a
25484
+ * detection candidate, camera pins naming it are ignored so its sessions move
25485
+ * elsewhere, and both come back when the mode ends — after a crash or a hub
25486
+ * restart too (a persisted manifest, reconciled against the registry).
25487
+ *
25488
+ * Two measurements, both on the node, driven by its own runner (frames never
25489
+ * cross a process at frame rate, D9):
25490
+ * - `device` — one accelerator × one candidate detector, root only, open
25491
+ * loop: how many streams at the camera rate it carries inside the frame
25492
+ * interval;
25493
+ * - `pipeline` — the chosen detector plus the operator's detail steps
25494
+ * (faces, plates, classifiers, CLIP…), on varied frames from the bench
25495
+ * clip: how many parallel sessions the node carries before latency, drops,
25496
+ * CPU, RAM or the event loop give out.
25497
+ */
25498
+ /** Defaults and bounds, one place. */
25499
+ var NODE_BENCHMARK_DEFAULTS = {
25500
+ fpsPerStream: 10,
25501
+ budgetMinutes: 45,
25502
+ minBudgetMinutes: 10,
25503
+ maxBudgetMinutes: 120,
25504
+ /** A result older than this no longer beats the table. */
25505
+ staleAfterDays: 30,
25506
+ /** Warm-in per ramp step (not accounted). */
25507
+ settleSec: 5,
25508
+ /** Accounted window per ramp step. */
25509
+ measureSec: 20,
25510
+ /** Longest the drain may take before the run is refused. */
25511
+ drainTimeoutSec: 120,
25512
+ /** Candidate models per device in one run. */
25513
+ maxModelsPerDevice: 6
25514
+ };
25515
+ /** The two measurements a run can make. */
25516
+ var NodeBenchmarkPhaseSchema = _enum(["device", "pipeline"]);
25517
+ var NodeBenchmarkDevicePlanSchema = object({
25518
+ /** `<backend>:<device>` — `openvino:npu`, `coreml:all`, `cpu`. */
25519
+ deviceKey: string$2().min(1),
25520
+ /**
25521
+ * Root detector candidates for the `device` measurement, in the order
25522
+ * measured. The FIRST is the one the `pipeline` measurement runs.
25523
+ */
25524
+ modelIds: array(string$2().min(1)).min(1).max(NODE_BENCHMARK_DEFAULTS.maxModelsPerDevice)
25525
+ });
25526
+ /** What the operator confirmed. */
25527
+ var NodeBenchmarkPlanSchema = object({
25528
+ nodeId: string$2().min(1),
25529
+ devices: array(NodeBenchmarkDevicePlanSchema).min(1),
25530
+ /** Which measurements run. At least one. */
25531
+ phases: array(NodeBenchmarkPhaseSchema).min(1).default(["device", "pipeline"]),
25532
+ /**
25533
+ * Detail steps (catalog step ids under the root: faces, plates,
25534
+ * classifiers, CLIP…) the `pipeline` measurement enables. The root
25535
+ * detector always runs.
25536
+ */
25537
+ steps: array(string$2().min(1)).default([]),
25538
+ /** Offered rate of one stream / session. */
25539
+ fpsPerStream: number().int().min(1).max(30).default(NODE_BENCHMARK_DEFAULTS.fpsPerStream),
25540
+ /** Hard deadline: the mode ends and the cluster is restored when it passes. */
25541
+ budgetMinutes: number().int().min(NODE_BENCHMARK_DEFAULTS.minBudgetMinutes).max(NODE_BENCHMARK_DEFAULTS.maxBudgetMinutes).default(NODE_BENCHMARK_DEFAULTS.budgetMinutes),
25542
+ /** Keep the models the run downloaded (default: delete what was not installed before). */
25543
+ keepDownloadedModels: boolean().default(false),
25544
+ /** Start although the other nodes' capacity does not cover the sessions running now. */
25545
+ acceptInsufficientHeadroom: boolean().default(false)
25546
+ });
25547
+ var NodeBenchmarkRefusalSchema = object({
25548
+ kind: _enum([
25549
+ "benchmark-active",
25550
+ "node-offline",
25551
+ "unknown-device",
25552
+ "no-phase",
25553
+ "insufficient-headroom"
25554
+ ]),
25555
+ detail: string$2(),
25556
+ overridable: boolean()
25557
+ });
25558
+ /** A camera whose detection leaves the node for the run. */
25559
+ var NodeBenchmarkMovingCameraSchema = object({
25560
+ deviceId: number(),
25561
+ /** Placed on the node now (a standing attach or a running session). */
25562
+ placedOnNode: boolean(),
25563
+ /** A node pin naming this node, ignored for the run. */
25564
+ pinnedToNode: boolean()
25565
+ });
25566
+ /** A camera that cannot leave: no other node can obtain its frames. */
25567
+ var NodeBenchmarkStayingCameraSchema = object({
25568
+ deviceId: number(),
25569
+ reason: literal("only-frame-source")
25570
+ });
25571
+ var NodeBenchmarkPreflightSchema = object({
25572
+ nodeId: string$2(),
25573
+ online: boolean(),
25574
+ moving: array(NodeBenchmarkMovingCameraSchema).readonly(),
25575
+ /** Keep running on the node during the run; the result is flagged contaminated. */
25576
+ staying: array(NodeBenchmarkStayingCameraSchema).readonly(),
25577
+ estimatedDurationMs: number(),
25578
+ /** The run ends and the cluster is restored at the latest after this long. */
25579
+ budgetMs: number(),
25580
+ phases: array(NodeBenchmarkPhaseSchema).readonly(),
25581
+ steps: array(string$2()).readonly(),
25582
+ devices: array(NodeBenchmarkDevicePlanSchema).readonly(),
25583
+ /** Parallel sessions the cluster runs now, and what the other nodes can carry. */
25584
+ headroom: object({
25585
+ sessionsNow: number(),
25586
+ otherNodesCapacitySessions: number().nullable()
25587
+ }),
25588
+ refusals: array(NodeBenchmarkRefusalSchema).readonly(),
25589
+ canStart: boolean()
25590
+ });
25591
+ /** Where the measuring runner is. */
25592
+ var NodeBenchProgressSchema = object({
25593
+ phase: _enum([
25594
+ "preparing",
25595
+ "device",
25596
+ "pipeline",
25597
+ "cleanup"
25598
+ ]),
25599
+ deviceKey: string$2().nullable(),
25600
+ modelId: string$2().nullable(),
25601
+ /** Streams (device) or sessions (pipeline) of the step running now. */
25602
+ load: number().nullable(),
25603
+ cellsDone: number(),
25604
+ cellsTotal: number(),
25605
+ message: string$2()
25606
+ });
25607
+ /** What limited a ramp. `none` = the ramp ran out of steps still passing. */
25608
+ var NodeBenchLimitSchema = _enum([
25609
+ "p95",
25610
+ "drops",
25611
+ "errors",
25612
+ "stall",
25613
+ "cpu",
25614
+ "ram",
25615
+ "none"
25616
+ ]);
25617
+ var NodeBenchRampStepSchema = object({
25618
+ load: number(),
25619
+ pass: boolean(),
25620
+ p95Ms: number(),
25621
+ dropRatio: number(),
25622
+ /** Completed frames per second over the accounted window. */
25623
+ fps: number(),
25624
+ cpuPct: number().nullable(),
25625
+ ramFreePct: number().nullable(),
25626
+ failReasons: array(string$2()).readonly()
25627
+ });
25628
+ var NodeBenchCellSchema = discriminatedUnion("phase", [object({
25629
+ phase: literal("device"),
25630
+ deviceKey: string$2(),
25631
+ modelId: string$2(),
25632
+ /** Single-stream latency (the K = 1 step). */
25633
+ p50Ms: number(),
25634
+ p95Ms: number(),
25635
+ p99Ms: number(),
25636
+ /** Frames per second sustained at the last passing step. */
25637
+ fps: number(),
25638
+ /** Streams at the camera rate the device carried inside the frame interval; 0 = not even one. */
25639
+ kMax: number(),
25640
+ limitedBy: NodeBenchLimitSchema,
25641
+ /** First call (model load + warm-up). */
25642
+ warmupMs: number(),
25643
+ ramp: array(NodeBenchRampStepSchema).readonly()
25644
+ }), object({
25645
+ phase: literal("pipeline"),
25646
+ deviceKey: string$2(),
25647
+ modelId: string$2(),
25648
+ steps: array(string$2()).readonly(),
25649
+ /** Parallel sessions at the camera rate the node carried; 0 = not even one. */
25650
+ maxSessions: number(),
25651
+ limitedBy: NodeBenchLimitSchema,
25652
+ /** Detail steps that produced at least one result on the clip — a step that never fired measured nothing. */
25653
+ stepsFired: array(string$2()).readonly(),
25654
+ warmupMs: number(),
25655
+ ramp: array(NodeBenchRampStepSchema).readonly()
25656
+ })]);
25657
+ /**
25658
+ * What a result was measured ON. A result whose fingerprint no longer matches
25659
+ * the node no longer beats the table.
25660
+ */
25661
+ var NodeBenchFingerprintSchema = object({
25662
+ pipelineVersion: string$2().nullable(),
25663
+ cpuModel: string$2().nullable(),
25664
+ ramGb: number().nullable(),
25665
+ os: string$2().nullable(),
25666
+ /** Per device: the pool the cells ran on (runtime + tuning). */
25667
+ pools: record(string$2(), object({
25668
+ runtime: string$2(),
25669
+ numWorkers: number(),
25670
+ concurrency: number(),
25671
+ batchMode: string$2()
25672
+ })).default({})
25673
+ });
25674
+ /** The frames the run used. */
25675
+ var NodeBenchClipSchema = object({
25676
+ /** `camstack-bench-v1` or `reference-images` (the fallback when the clip is not reachable). */
25677
+ id: string$2(),
25678
+ revision: string$2().nullable(),
25679
+ frames: number(),
25680
+ width: number(),
25681
+ height: number()
25682
+ });
25683
+ var NodeBenchRunnerInputSchema = object({
25684
+ runId: string$2().min(1),
25685
+ devices: array(NodeBenchmarkDevicePlanSchema).min(1),
25686
+ phases: array(NodeBenchmarkPhaseSchema).min(1),
25687
+ /** The full detail step tree root for the `pipeline` measurement is built on the node from these ids. */
25688
+ steps: array(string$2()).default([]),
25689
+ fpsPerStream: number().int().min(1).max(30),
25690
+ /** The runner stops on its own past this instant, whatever the hub does. */
25691
+ deadlineAtMs: number(),
25692
+ settleSec: number().min(0).max(60).default(NODE_BENCHMARK_DEFAULTS.settleSec),
25693
+ measureSec: number().min(2).max(300).default(NODE_BENCHMARK_DEFAULTS.measureSec),
25694
+ keepDownloadedModels: boolean().default(false)
25695
+ });
25696
+ var NodeBenchRunnerStateSchema = _enum([
25697
+ "running",
25698
+ "done",
25699
+ "failed",
25700
+ "aborted"
25701
+ ]);
25702
+ var NodeBenchRunnerStatusSchema = object({
25703
+ runId: string$2(),
25704
+ nodeId: string$2(),
25705
+ state: NodeBenchRunnerStateSchema,
25706
+ progress: NodeBenchProgressSchema.nullable(),
25707
+ /** Every finished cell so far — a run stopped half way keeps what it measured. */
25708
+ cells: array(NodeBenchCellSchema).readonly(),
25709
+ fingerprint: NodeBenchFingerprintSchema.nullable(),
25710
+ clip: NodeBenchClipSchema.nullable(),
25711
+ /** Cameras seen running on the node during the run (they share its pools). */
25712
+ activeCameraIds: array(number()).readonly(),
25713
+ /** Models the run downloaded and then deleted (not installed before). */
25714
+ deletedModels: array(string$2()).readonly(),
25715
+ error: string$2().nullable(),
25716
+ startedAtMs: number(),
25717
+ finishedAtMs: number().nullable()
25718
+ });
25719
+ var NodeBenchmarkStateSchema = _enum([
25720
+ "draining",
25721
+ "measuring",
25722
+ "restoring",
25723
+ "done",
25724
+ "failed",
25725
+ "aborted"
25726
+ ]);
25727
+ /** Why a run ended. */
25728
+ var NodeBenchmarkEndReasonSchema = _enum([
25729
+ "completed",
25730
+ "operator-abort",
25731
+ "deadline",
25732
+ "node-lost",
25733
+ "runner-lost",
25734
+ "hub-restart",
25735
+ "drain-timeout",
25736
+ "failed"
25737
+ ]);
25738
+ var NodeBenchmarkRunSchema = object({
25739
+ runId: string$2(),
25740
+ nodeId: string$2(),
25741
+ state: NodeBenchmarkStateSchema,
25742
+ plan: NodeBenchmarkPlanSchema,
25743
+ startedAtMs: number(),
25744
+ deadlineAtMs: number(),
25745
+ finishedAtMs: number().nullable(),
25746
+ endReason: NodeBenchmarkEndReasonSchema.nullable(),
25747
+ error: string$2().nullable(),
25748
+ /** Cameras moved off the node for the run. */
25749
+ moved: array(number()).readonly(),
25750
+ /** Cameras that stayed (their only frame source is the node). */
25751
+ staying: array(number()).readonly(),
25752
+ /** Something else ran on the node's pools during the run. */
25753
+ contaminated: boolean(),
25754
+ progress: NodeBenchProgressSchema.nullable(),
25755
+ resultIds: array(string$2()).readonly()
25756
+ });
25757
+ /** `getNodeBenchmarkStatus`: the active run (or the last one), and whether benchmark mode is on. */
25758
+ var NodeBenchmarkStatusSchema = object({
25759
+ /** The node the cluster is in benchmark mode for; null = none. */
25760
+ modeNodeId: string$2().nullable(),
25761
+ run: NodeBenchmarkRunSchema.nullable()
25762
+ });
25763
+ /**
25764
+ * One stored measurement — the only authority Auto tune and the automatic
25765
+ * shares read measured capacity from. Written by the orchestrator when a run
25766
+ * ends, never by anyone else.
25767
+ */
25768
+ var NodeBenchmarkResultSchema = object({
25769
+ id: string$2(),
25770
+ runId: string$2(),
25771
+ nodeId: string$2(),
25772
+ cell: NodeBenchCellSchema,
25773
+ fpsPerStream: number(),
25774
+ fingerprint: NodeBenchFingerprintSchema.nullable(),
25775
+ clip: NodeBenchClipSchema.nullable(),
25776
+ /** Other work shared the node's pools (a camera that could not move, or the hub's own duties). */
25777
+ contaminated: boolean(),
25778
+ stayingCameras: array(number()).readonly(),
25779
+ /** The run ended early; the cell itself completed. */
25780
+ partialRun: boolean(),
25781
+ measuredAtMs: number()
25782
+ });
25783
+ var ListNodeBenchmarkResultsInputSchema = object({
25784
+ nodeId: string$2().optional(),
25785
+ deviceKey: string$2().optional()
25786
+ });
25787
+ /** A result with its standing today: does it still beat the table? */
25788
+ var NodeBenchmarkResultViewSchema = NodeBenchmarkResultSchema.extend({
25789
+ /** `fresh` beats the table; `stale` falls back to it; `superseded` = a newer row covers the same cell. */
25790
+ standing: _enum([
25791
+ "fresh",
25792
+ "stale",
25793
+ "superseded"
25794
+ ]),
25795
+ staleWhy: _enum([
25796
+ "age",
25797
+ "runtime",
25798
+ "pool-tuning"
25799
+ ]).nullable()
25800
+ });
25801
+ object({
25802
+ runId: string$2(),
25803
+ nodeId: string$2(),
25804
+ startedAtMs: number(),
25805
+ deadlineAtMs: number(),
25806
+ plan: NodeBenchmarkPlanSchema,
25807
+ moved: array(number()).readonly(),
25808
+ staying: array(number()).readonly()
25809
+ });
25810
+ /** Candidate detectors per device, for the plan editor. */
25811
+ var NodeBenchmarkCandidatesSchema = object({
25812
+ nodeId: string$2(),
25813
+ reachable: boolean(),
25814
+ devices: array(object({
25815
+ deviceKey: string$2(),
25816
+ enabled: boolean(),
25817
+ available: boolean(),
25818
+ /** Ordered: what Auto tune would pick first, then the rest of the family by accuracy. */
25819
+ suggested: array(string$2()).readonly(),
25820
+ /** Every root detector the device has a build for. */
25821
+ all: array(string$2()).readonly(),
25822
+ /** The model the device runs now, when pinned. */
25823
+ currentModelId: string$2().nullable()
25824
+ })).readonly(),
25825
+ /** Detail steps the node's catalog offers under the root (for the `pipeline` measurement). */
25826
+ steps: array(object({
25827
+ id: string$2(),
25828
+ name: string$2(),
25829
+ slot: string$2()
25830
+ })).readonly()
25831
+ });
24287
25832
  object({
24288
25833
  activeCameras: number(),
24289
25834
  throttledCameras: number(),
@@ -25412,7 +26957,16 @@ method(RunnerCameraConfigSchema, object({ success: literal(true) }), { kind: "mu
25412
26957
  }), ParkedTrackFrameSchema.nullable()), method(object({
25413
26958
  deviceId: number(),
25414
26959
  trackId: string$2()
25415
- }), object({ released: number().int().nonnegative() }), { kind: "mutation" });
26960
+ }), object({ released: number().int().nonnegative() }), { kind: "mutation" }), method(NodeBenchRunnerInputSchema, object({
26961
+ accepted: literal(true),
26962
+ runId: string$2()
26963
+ }), {
26964
+ kind: "mutation",
26965
+ auth: "admin"
26966
+ }), method(object({ runId: string$2() }), NodeBenchRunnerStatusSchema.nullable(), { auth: "admin" }), method(object({ runId: string$2() }), object({ aborted: boolean() }), {
26967
+ kind: "mutation",
26968
+ auth: "admin"
26969
+ });
25416
26970
  var CameraPipelineConfigSchema = object({
25417
26971
  engine: PipelineEngineChoiceSchema.optional(),
25418
26972
  steps: array(PipelineStepInputSchema).readonly(),
@@ -26051,6 +27605,21 @@ method(object({
26051
27605
  }), method(PlacementStatsInputSchema, PlacementStatsSchema, { auth: "admin" }), method(SuggestSharesInputSchema, SuggestSharesResultSchema, { auth: "admin" }), method(_void(), EffectiveSharesSchema, { auth: "admin" }), method(SetShareSourceInputSchema, object({ success: literal(true) }), {
26052
27606
  kind: "mutation",
26053
27607
  auth: "admin"
27608
+ }), method(NodeBenchmarkPlanSchema, NodeBenchmarkPreflightSchema, { auth: "admin" }), method(NodeBenchmarkPlanSchema, discriminatedUnion("kind", [object({
27609
+ kind: literal("started"),
27610
+ runId: string$2()
27611
+ }), object({
27612
+ kind: literal("refused"),
27613
+ preflight: NodeBenchmarkPreflightSchema
27614
+ })]), {
27615
+ kind: "mutation",
27616
+ auth: "admin"
27617
+ }), method(_void(), NodeBenchmarkStatusSchema, { auth: "admin" }), method(object({ runId: string$2() }), object({ aborted: boolean() }), {
27618
+ kind: "mutation",
27619
+ auth: "admin"
27620
+ }), method(object({ nodeId: string$2() }), NodeBenchmarkCandidatesSchema, { auth: "admin" }), method(ListNodeBenchmarkResultsInputSchema, array(NodeBenchmarkResultViewSchema).readonly(), { auth: "admin" }), method(object({ id: string$2() }), object({ deleted: boolean() }), {
27621
+ kind: "mutation",
27622
+ auth: "admin"
26054
27623
  }), method(object({ deviceId: number() }), CameraPipelineSettingsSchema.nullable()), method(object({
26055
27624
  deviceId: number(),
26056
27625
  addonId: string$2(),
@@ -32175,6 +33744,9 @@ var CreateIntegrationInputSchema = object({
32175
33744
  enabled: boolean().optional(),
32176
33745
  info: record(string$2(), unknown()).optional(),
32177
33746
  settings: record(string$2(), unknown()).optional(),
33747
+ /** Keys of `settings` the form's schema declares secret (by type) — kept in
33748
+ * the keychain, not the table (D787). */
33749
+ secretKeys: array(string$2()).optional(),
32178
33750
  skipRestart: boolean().optional()
32179
33751
  });
32180
33752
  var UpdateIntegrationInputSchema = object({
@@ -32198,7 +33770,9 @@ method(_void(), array(IntegrationWithStateSchema)), method(object({ id: string$2
32198
33770
  auth: "admin"
32199
33771
  }), method(object({ id: string$2() }), record(string$2(), unknown()), { auth: "admin" }), method(object({
32200
33772
  id: string$2(),
32201
- settings: record(string$2(), unknown())
33773
+ settings: record(string$2(), unknown()),
33774
+ /** Keys the form's schema declares secret (by type) — keychain-stored (D787). */
33775
+ secretKeys: array(string$2()).optional()
32202
33776
  }), object({ success: boolean() }), {
32203
33777
  kind: "mutation",
32204
33778
  auth: "admin"
@@ -40361,7 +41935,8 @@ var BaseDevice = class {
40361
41935
  this.role = options.role;
40362
41936
  this.parentDeviceId = ctx.parentDeviceId;
40363
41937
  const seedData = ctx.persistedConfig ?? {};
40364
- this.config = DeviceConfig.fromSchema(schema, (data) => ctx.persistConfig(data), seedData, ({ droppedKeys, issues }) => {
41938
+ const declaredSecretPaths = collectZodSecretPaths(schema);
41939
+ this.config = DeviceConfig.fromSchema(schema, (data) => ctx.persistConfig(data, { secretConfigPaths: declaredSecretPaths }), seedData, ({ droppedKeys, issues }) => {
40365
41940
  ctx.logger.warn("Device config recovery: dropping invalid persisted fields", {
40366
41941
  tags: {
40367
41942
  deviceId: ctx.id,
@@ -44050,6 +45625,90 @@ Object.freeze({
44050
45625
  addonId: null,
44051
45626
  access: "create"
44052
45627
  },
45628
+ "keychain.delete": {
45629
+ capName: "keychain",
45630
+ capScope: "system",
45631
+ addonId: null,
45632
+ access: "delete"
45633
+ },
45634
+ "keychain.getState": {
45635
+ capName: "keychain",
45636
+ capScope: "system",
45637
+ addonId: null,
45638
+ access: "view"
45639
+ },
45640
+ "keychain.listMeta": {
45641
+ capName: "keychain",
45642
+ capScope: "system",
45643
+ addonId: null,
45644
+ access: "view"
45645
+ },
45646
+ "keychain.put": {
45647
+ capName: "keychain",
45648
+ capScope: "system",
45649
+ addonId: null,
45650
+ access: "create"
45651
+ },
45652
+ "keychain.resolve": {
45653
+ capName: "keychain",
45654
+ capScope: "system",
45655
+ addonId: null,
45656
+ access: "view"
45657
+ },
45658
+ "keychainAdmin.deleteOrphans": {
45659
+ capName: "keychain-admin",
45660
+ capScope: "system",
45661
+ addonId: null,
45662
+ access: "delete"
45663
+ },
45664
+ "keychainAdmin.downloadRecoveryKey": {
45665
+ capName: "keychain-admin",
45666
+ capScope: "system",
45667
+ addonId: null,
45668
+ access: "create"
45669
+ },
45670
+ "keychainAdmin.listAudit": {
45671
+ capName: "keychain-admin",
45672
+ capScope: "system",
45673
+ addonId: null,
45674
+ access: "view"
45675
+ },
45676
+ "keychainAdmin.listSecrets": {
45677
+ capName: "keychain-admin",
45678
+ capScope: "system",
45679
+ addonId: null,
45680
+ access: "view"
45681
+ },
45682
+ "keychainAdmin.purgeRetiredKeys": {
45683
+ capName: "keychain-admin",
45684
+ capScope: "system",
45685
+ addonId: null,
45686
+ access: "delete"
45687
+ },
45688
+ "keychainAdmin.resetKeychain": {
45689
+ capName: "keychain-admin",
45690
+ capScope: "system",
45691
+ addonId: null,
45692
+ access: "delete"
45693
+ },
45694
+ "keychainAdmin.reveal": {
45695
+ capName: "keychain-admin",
45696
+ capScope: "system",
45697
+ addonId: null,
45698
+ access: "create"
45699
+ },
45700
+ "keychainAdmin.rotateMasterKey": {
45701
+ capName: "keychain-admin",
45702
+ capScope: "system",
45703
+ addonId: null,
45704
+ access: "create"
45705
+ },
45706
+ "keychainAdmin.status": {
45707
+ capName: "keychain-admin",
45708
+ capScope: "system",
45709
+ addonId: null,
45710
+ access: "view"
45711
+ },
44053
45712
  "lawnMowerControl.dock": {
44054
45713
  capName: "lawn-mower-control",
44055
45714
  capScope: "device",
@@ -45424,6 +47083,18 @@ Object.freeze({
45424
47083
  addonId: null,
45425
47084
  access: "create"
45426
47085
  },
47086
+ "pipelineAnalytics.addRetrainFrameFromRecording": {
47087
+ capName: "pipeline-analytics",
47088
+ capScope: "device",
47089
+ addonId: null,
47090
+ access: "create"
47091
+ },
47092
+ "pipelineAnalytics.addRetrainFramesToCollection": {
47093
+ capName: "pipeline-analytics",
47094
+ capScope: "device",
47095
+ addonId: null,
47096
+ access: "create"
47097
+ },
45427
47098
  "pipelineAnalytics.applyDeviceSettingsPatch": {
45428
47099
  capName: "pipeline-analytics",
45429
47100
  capScope: "device",
@@ -45472,12 +47143,24 @@ Object.freeze({
45472
47143
  addonId: null,
45473
47144
  access: "view"
45474
47145
  },
47146
+ "pipelineAnalytics.createRetrainCollection": {
47147
+ capName: "pipeline-analytics",
47148
+ capScope: "device",
47149
+ addonId: null,
47150
+ access: "create"
47151
+ },
45475
47152
  "pipelineAnalytics.deleteDeviceEvents": {
45476
47153
  capName: "pipeline-analytics",
45477
47154
  capScope: "device",
45478
47155
  addonId: null,
45479
47156
  access: "delete"
45480
47157
  },
47158
+ "pipelineAnalytics.deleteRetrainCollection": {
47159
+ capName: "pipeline-analytics",
47160
+ capScope: "device",
47161
+ addonId: null,
47162
+ access: "delete"
47163
+ },
45481
47164
  "pipelineAnalytics.deleteTracks": {
45482
47165
  capName: "pipeline-analytics",
45483
47166
  capScope: "device",
@@ -45682,6 +47365,24 @@ Object.freeze({
45682
47365
  addonId: null,
45683
47366
  access: "view"
45684
47367
  },
47368
+ "pipelineAnalytics.listRetrainAssistProfiles": {
47369
+ capName: "pipeline-analytics",
47370
+ capScope: "device",
47371
+ addonId: null,
47372
+ access: "view"
47373
+ },
47374
+ "pipelineAnalytics.listRetrainCollectionFrames": {
47375
+ capName: "pipeline-analytics",
47376
+ capScope: "device",
47377
+ addonId: null,
47378
+ access: "view"
47379
+ },
47380
+ "pipelineAnalytics.listRetrainCollections": {
47381
+ capName: "pipeline-analytics",
47382
+ capScope: "device",
47383
+ addonId: null,
47384
+ access: "view"
47385
+ },
45685
47386
  "pipelineAnalytics.listRetrainFrames": {
45686
47387
  capName: "pipeline-analytics",
45687
47388
  capScope: "device",
@@ -45730,6 +47431,12 @@ Object.freeze({
45730
47431
  addonId: null,
45731
47432
  access: "create"
45732
47433
  },
47434
+ "pipelineAnalytics.proposeRetrainAnnotationsWithLlm": {
47435
+ capName: "pipeline-analytics",
47436
+ capScope: "device",
47437
+ addonId: null,
47438
+ access: "create"
47439
+ },
45733
47440
  "pipelineAnalytics.pruneEvents": {
45734
47441
  capName: "pipeline-analytics",
45735
47442
  capScope: "device",
@@ -45784,6 +47491,18 @@ Object.freeze({
45784
47491
  addonId: null,
45785
47492
  access: "create"
45786
47493
  },
47494
+ "pipelineAnalytics.removeRetrainFrameFromCollection": {
47495
+ capName: "pipeline-analytics",
47496
+ capScope: "device",
47497
+ addonId: null,
47498
+ access: "delete"
47499
+ },
47500
+ "pipelineAnalytics.renameRetrainCollection": {
47501
+ capName: "pipeline-analytics",
47502
+ capScope: "device",
47503
+ addonId: null,
47504
+ access: "create"
47505
+ },
45787
47506
  "pipelineAnalytics.restageRetrainTrack": {
45788
47507
  capName: "pipeline-analytics",
45789
47508
  capScope: "device",
@@ -46072,6 +47791,12 @@ Object.freeze({
46072
47791
  addonId: null,
46073
47792
  access: "view"
46074
47793
  },
47794
+ "pipelineOrchestrator.abortNodeBenchmark": {
47795
+ capName: "pipeline-orchestrator",
47796
+ capScope: "system",
47797
+ addonId: null,
47798
+ access: "create"
47799
+ },
46075
47800
  "pipelineOrchestrator.applyAutoTune": {
46076
47801
  capName: "pipeline-orchestrator",
46077
47802
  capScope: "system",
@@ -46096,6 +47821,12 @@ Object.freeze({
46096
47821
  addonId: null,
46097
47822
  access: "create"
46098
47823
  },
47824
+ "pipelineOrchestrator.deleteNodeBenchmarkResult": {
47825
+ capName: "pipeline-orchestrator",
47826
+ capScope: "system",
47827
+ addonId: null,
47828
+ access: "delete"
47829
+ },
46099
47830
  "pipelineOrchestrator.getAgentLoad": {
46100
47831
  capName: "pipeline-orchestrator",
46101
47832
  capScope: "system",
@@ -46204,6 +47935,24 @@ Object.freeze({
46204
47935
  addonId: null,
46205
47936
  access: "view"
46206
47937
  },
47938
+ "pipelineOrchestrator.getNodeBenchmarkCandidates": {
47939
+ capName: "pipeline-orchestrator",
47940
+ capScope: "system",
47941
+ addonId: null,
47942
+ access: "view"
47943
+ },
47944
+ "pipelineOrchestrator.getNodeBenchmarkPreflight": {
47945
+ capName: "pipeline-orchestrator",
47946
+ capScope: "system",
47947
+ addonId: null,
47948
+ access: "view"
47949
+ },
47950
+ "pipelineOrchestrator.getNodeBenchmarkStatus": {
47951
+ capName: "pipeline-orchestrator",
47952
+ capScope: "system",
47953
+ addonId: null,
47954
+ access: "view"
47955
+ },
46207
47956
  "pipelineOrchestrator.getNodeInferenceDevices": {
46208
47957
  capName: "pipeline-orchestrator",
46209
47958
  capScope: "system",
@@ -46246,6 +47995,12 @@ Object.freeze({
46246
47995
  addonId: null,
46247
47996
  access: "view"
46248
47997
  },
47998
+ "pipelineOrchestrator.listNodeBenchmarkResults": {
47999
+ capName: "pipeline-orchestrator",
48000
+ capScope: "system",
48001
+ addonId: null,
48002
+ access: "view"
48003
+ },
46249
48004
  "pipelineOrchestrator.pauseForStorageMigration": {
46250
48005
  capName: "pipeline-orchestrator",
46251
48006
  capScope: "system",
@@ -46390,6 +48145,12 @@ Object.freeze({
46390
48145
  addonId: null,
46391
48146
  access: "create"
46392
48147
  },
48148
+ "pipelineOrchestrator.startNodeBenchmark": {
48149
+ capName: "pipeline-orchestrator",
48150
+ capScope: "system",
48151
+ addonId: null,
48152
+ access: "create"
48153
+ },
46393
48154
  "pipelineOrchestrator.suggestShares": {
46394
48155
  capName: "pipeline-orchestrator",
46395
48156
  capScope: "system",
@@ -46408,6 +48169,12 @@ Object.freeze({
46408
48169
  addonId: null,
46409
48170
  access: "create"
46410
48171
  },
48172
+ "pipelineRunner.abortNodeBench": {
48173
+ capName: "pipeline-runner",
48174
+ capScope: "system",
48175
+ addonId: null,
48176
+ access: "create"
48177
+ },
46411
48178
  "pipelineRunner.attachCamera": {
46412
48179
  capName: "pipeline-runner",
46413
48180
  capScope: "system",
@@ -46456,6 +48223,12 @@ Object.freeze({
46456
48223
  addonId: null,
46457
48224
  access: "view"
46458
48225
  },
48226
+ "pipelineRunner.getNodeBenchStatus": {
48227
+ capName: "pipeline-runner",
48228
+ capScope: "system",
48229
+ addonId: null,
48230
+ access: "view"
48231
+ },
46459
48232
  "pipelineRunner.getParkedTrackFrame": {
46460
48233
  capName: "pipeline-runner",
46461
48234
  capScope: "system",
@@ -46498,6 +48271,12 @@ Object.freeze({
46498
48271
  addonId: null,
46499
48272
  access: "create"
46500
48273
  },
48274
+ "pipelineRunner.startNodeBench": {
48275
+ capName: "pipeline-runner",
48276
+ capScope: "system",
48277
+ addonId: null,
48278
+ access: "create"
48279
+ },
46501
48280
  "plateGallery.assignPlate": {
46502
48281
  capName: "plate-gallery",
46503
48282
  capScope: "system",
@@ -51427,6 +53206,11 @@ Object.freeze({
51427
53206
  form: "single",
51428
53207
  optional: false
51429
53208
  }],
53209
+ "pipelineAnalytics.addRetrainFrameFromRecording": [{
53210
+ name: "deviceId",
53211
+ form: "single",
53212
+ optional: false
53213
+ }],
51430
53214
  "pipelineAnalytics.applyDeviceSettingsPatch": [{
51431
53215
  name: "deviceId",
51432
53216
  form: "single",
@@ -51617,6 +53401,11 @@ Object.freeze({
51617
53401
  form: "single",
51618
53402
  optional: false
51619
53403
  }],
53404
+ "pipelineAnalytics.proposeRetrainAnnotationsWithLlm": [{
53405
+ name: "deviceId",
53406
+ form: "single",
53407
+ optional: false
53408
+ }],
51620
53409
  "pipelineAnalytics.pruneEventsBefore": [{
51621
53410
  name: "deviceId",
51622
53411
  form: "single",