@camstack/addon-post-analysis 1.2.285 → 1.2.287

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 (18) hide show
  1. package/THIRD_PARTY_MODELS.md +8 -0
  2. package/dist/{dist-D2tXUMfE.mjs → clip-model-registry-BRHeTbFV.mjs} +1405 -427
  3. package/dist/{dist-ITESpHou.js → clip-model-registry-Cq1X8kTo.js} +1514 -440
  4. package/dist/embedding-encoder/index.js +962 -428
  5. package/dist/embedding-encoder/index.mjs +952 -418
  6. package/dist/pipeline-analytics/_stub.js +2 -2
  7. package/dist/pipeline-analytics/{_virtual_mf-localSharedImportMap___mfe_internal__addon_pipeline_analytics_widgets-7oasHfhD.mjs → _virtual_mf-localSharedImportMap___mfe_internal__addon_pipeline_analytics_widgets-BpJC8P0K.mjs} +2 -2
  8. package/dist/pipeline-analytics/_virtual_mf___mfe_internal__addon_pipeline_analytics_widgets__loadShare___mf_0_camstack_mf_1_types__loadShare__.js-3dZf67Z7.mjs +26 -0
  9. package/dist/pipeline-analytics/_virtual_mf___mfe_internal__addon_pipeline_analytics_widgets__loadShare___mf_0_camstack_mf_1_ui_mf_2_library__loadShare__.js-r4OU_ahc.mjs +26 -0
  10. package/dist/pipeline-analytics/{hostInit-B6m75Rnz.mjs → hostInit-BIUCfS5T.mjs} +2 -2
  11. package/dist/pipeline-analytics/index.js +6449 -5096
  12. package/dist/pipeline-analytics/index.mjs +5109 -3756
  13. package/dist/pipeline-analytics/remoteEntry.js +1 -1
  14. package/package.json +1 -1
  15. package/python/test_text_encoder.py +49 -2
  16. package/python/text_encoder_inference.py +31 -14
  17. package/dist/pipeline-analytics/_virtual_mf___mfe_internal__addon_pipeline_analytics_widgets__loadShare___mf_0_camstack_mf_1_types__loadShare__.js-CjeM5Bph.mjs +0 -26
  18. package/dist/pipeline-analytics/_virtual_mf___mfe_internal__addon_pipeline_analytics_widgets__loadShare___mf_0_camstack_mf_1_ui_mf_2_library__loadShare__.js-BidXbeas.mjs +0 -26
@@ -5391,7 +5391,7 @@ var ZodIssueCode = {
5391
5391
  var ZodFirstPartyTypeKind;
5392
5392
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
5393
5393
  //#endregion
5394
- //#region ../types/dist/sleep-BaRu0bS5.mjs
5394
+ //#region ../types/dist/sleep-DC-wdyeS.mjs
5395
5395
  /**
5396
5396
  * The audio chunk plane's byte format, and the ONE expansion from a coded
5397
5397
  * window to float samples (D455).
@@ -6176,6 +6176,40 @@ var BaseAddon = class {
6176
6176
  const node = normalizeNodeId(nodeId ?? this._ctx?.kernel?.localNodeId);
6177
6177
  return keys.size > 0 ? projectStore(raw, keys, node) : raw;
6178
6178
  }
6179
+ /**
6180
+ * Whether ONE global key of this addon's store was written, read three-way
6181
+ * (D651). For a question a hydrated view cannot answer: `getGlobalSettings`
6182
+ * reports `value ?? default`, so "the operator chose the default" and "nobody
6183
+ * chose" look the same, and a failed read looks like both. A `perNode` key is
6184
+ * not supported here: its stored name is scoped.
6185
+ */
6186
+ async readStoredGlobalKey(key) {
6187
+ const read = this._ctx?.settings?.readAddonStoreResult;
6188
+ if (read === void 0) return {
6189
+ kind: "unreadable",
6190
+ reason: "three-way-read-unavailable"
6191
+ };
6192
+ let result;
6193
+ try {
6194
+ result = await read.call(this._ctx?.settings);
6195
+ } catch (err) {
6196
+ return {
6197
+ kind: "unreadable",
6198
+ reason: "store-read-failed",
6199
+ error: err instanceof Error ? err.message : String(err)
6200
+ };
6201
+ }
6202
+ if (result.kind === "failed") return {
6203
+ kind: "unreadable",
6204
+ reason: "store-read-failed",
6205
+ error: result.error
6206
+ };
6207
+ if (result.kind === "missing" || !Object.prototype.hasOwnProperty.call(result.value, key)) return { kind: "absent" };
6208
+ return {
6209
+ kind: "present",
6210
+ value: result.value[key]
6211
+ };
6212
+ }
6179
6213
  async updateGlobalSettings(patch, nodeId) {
6180
6214
  const keys = this.perNodeKeys();
6181
6215
  const localNode = normalizeNodeId(this._ctx?.kernel?.localNodeId);
@@ -7471,7 +7505,7 @@ method(object({ deviceId: number() }), array(StreamSourceEntrySchema)), method(o
7471
7505
  * can answer "may a rule actuate this?" without importing the schema barrel
7472
7506
  * (~144MB RSS per runner, D28).
7473
7507
  *
7474
- * Coverage: 87 device-scoped capabilities.
7508
+ * Coverage: 88 device-scoped capabilities.
7475
7509
  */
7476
7510
  var DEVICE_SCOPED_CAPS = new Set([
7477
7511
  "accessories",
@@ -7501,6 +7535,7 @@ var DEVICE_SCOPED_CAPS = new Set([
7501
7535
  "detection-pipeline",
7502
7536
  "device-admin-link",
7503
7537
  "device-discovery",
7538
+ "device-extension",
7504
7539
  "device-ops",
7505
7540
  "device-status",
7506
7541
  "doorbell",
@@ -10027,6 +10062,60 @@ var FailureCounters = class {
10027
10062
  this.counters.clear();
10028
10063
  }
10029
10064
  };
10065
+ var ClipModelMetaSchema = object({
10066
+ /** The paired text encoder's catalog id (the embedding-encoder's text catalog). */
10067
+ textModelId: string().min(1),
10068
+ /** Output dimension of BOTH towers. A vector of any other length is refused. */
10069
+ embeddingDim: number().int().positive(),
10070
+ /**
10071
+ * The `vector-store` index this model's vectors live in. ONE feature space
10072
+ * per index: two models share an index only when their vectors are ranked
10073
+ * against each other, which for CLIP means never across families. MobileCLIP
10074
+ * S1 and S2 share `object-clip` for history (separated by the row's
10075
+ * `modelId`); any other model gets its own.
10076
+ */
10077
+ vectorIndex: string().regex(/^object-clip(-[a-z0-9][a-z0-9-]*)?$/),
10078
+ /**
10079
+ * The text encoder's tokenizer, a declared SIBLING file of its onnx. The name
10080
+ * must be unique per tokenizer: every model's siblings land in ONE flat
10081
+ * models directory, so two different tokenizers under the same name would
10082
+ * silently overwrite each other (whichever model downloaded last wins, and
10083
+ * the other one tokenises with the wrong vocabulary).
10084
+ */
10085
+ tokenizerFile: string().min(1),
10086
+ /** Token window the text graph takes (SigLIP2: 64; CLIP BPE: 77). */
10087
+ contextLength: number().int().positive(),
10088
+ /** Id the tokenizer pads with. */
10089
+ padId: number().int().nonnegative(),
10090
+ /**
10091
+ * The search cosine floor at `strictness: 'loose'` — calibrated per model,
10092
+ * because cosine bands are a property of the model: 0.2 keeps 96% of matched
10093
+ * COCO caption-image pairs on MobileCLIP S1 and 2.7% on SigLIP2.
10094
+ */
10095
+ searchMinScore: number().min(0).max(1)
10096
+ });
10097
+ var ClipSearchStrictnessSchema = _enum([
10098
+ "loose",
10099
+ "balanced",
10100
+ "strict"
10101
+ ]);
10102
+ var CLIP_STRICTNESS_FACTOR = {
10103
+ loose: 1,
10104
+ balanced: 1.25,
10105
+ strict: 1.5
10106
+ };
10107
+ /**
10108
+ * The cosine floor a search runs with.
10109
+ *
10110
+ * An explicit `minScore` is honoured verbatim: it is a number a caller chose,
10111
+ * and silently rescaling it would make the same URL mean different things on
10112
+ * two installs. Everything else is relative to the model.
10113
+ */
10114
+ function resolveClipSearchMinScore(meta, request) {
10115
+ if (request.minScore !== void 0) return request.minScore;
10116
+ const factor = CLIP_STRICTNESS_FACTOR[request.strictness ?? "loose"];
10117
+ return Math.min(1, Math.round(meta.searchMinScore * factor * 1e3) / 1e3);
10118
+ }
10030
10119
  var MODEL_FORMATS = [
10031
10120
  "onnx",
10032
10121
  "coreml",
@@ -10230,7 +10319,14 @@ var ModelCatalogEntrySchema = object({
10230
10319
  * applies (Frigate / COCO public catalog). Set on a custom model whose raw
10231
10320
  * labels already ARE the CamStack macros (Scrypted identity map).
10232
10321
  */
10233
- classMap: DetectionCatalogClassMapSchema.optional()
10322
+ classMap: DetectionCatalogClassMapSchema.optional(),
10323
+ /**
10324
+ * The model's CLIP feature-space contract (text encoder, dimension, vector
10325
+ * index, token window, search floor) — see `clip-model.ts`. Present ONLY on a
10326
+ * CLIP image encoder; its absence is what "not a CLIP model" means to the
10327
+ * embedding encoder and the semantic-search store (D649).
10328
+ */
10329
+ clip: ClipModelMetaSchema.optional()
10234
10330
  });
10235
10331
  var ConvertTargetSchema = discriminatedUnion("format", [object({
10236
10332
  format: literal("openvino"),
@@ -14680,6 +14776,27 @@ var LinkedDeviceSchema = object({
14680
14776
  features: array(string()),
14681
14777
  producesTrackedEvents: boolean().optional()
14682
14778
  });
14779
+ /**
14780
+ * The `linked-devices` extension slot's editable value (D648): the operator's
14781
+ * pick list, exactly what `_linkedDeviceIds` persists. Tree children are NOT
14782
+ * in it — they are always linked and are not a pick.
14783
+ *
14784
+ * `trackedDeviceIds` (D655) is the tracked-event opt-in, exactly what
14785
+ * `_linkedDeviceTrackedIds` persists: which linked devices materialize a
14786
+ * synthetic tracked event on the camera. A read always carries it AS STORED
14787
+ * (an absent key reads as `[]`, which is what the resolver makes of it —
14788
+ * NONE). On a write it is optional: absent leaves the opt-in untouched, so a
14789
+ * card built before D655 cannot erase it by saving the pick list. A present
14790
+ * list REPLACES the opt-in; each id must be a pick, a device the camera links
14791
+ * by structure (the row's `impliedSources`: tree children, a picked
14792
+ * container's child) or already stored — so what was read can always be
14793
+ * written back unchanged, and a NEW opt-in outside the linked set is refused.
14794
+ */
14795
+ var LinkedDevicesSlotValueSchema = object({
14796
+ deviceIds: array(number().int().positive()),
14797
+ trackedDeviceIds: array(number().int().positive()).optional()
14798
+ });
14799
+ DeviceType.Camera;
14683
14800
  /** One camera's resolved linked set, tagged with the camera it belongs to.
14684
14801
  * The batch answer needs the tag; the single-device answer already has it
14685
14802
  * from the input, which is why `getLinkedDevices` keeps the untagged shape. */
@@ -15205,11 +15322,128 @@ var EmbeddingResultSchema = object({
15205
15322
  embedding: array(number()),
15206
15323
  inferenceMs: number()
15207
15324
  });
15325
+ /** The two CLIP towers the encoder runs; a crash budget is kept per tower. */
15326
+ var EmbeddingTowerSchema = _enum(["image", "text"]);
15327
+ /**
15328
+ * A tower in the terminal `failed` state (D649, D6): it crashed or failed to
15329
+ * load `crashes` times within `windowMs`, and is refused by name until an
15330
+ * operator `resetFailedModels` or a model change — never on a timer.
15331
+ *
15332
+ * `nodeId` is the node whose tower failed. The state lives in THAT node's
15333
+ * encoder process (in memory — a runner respawn clears it), and one node's
15334
+ * answer says nothing about another's.
15335
+ */
15336
+ var EmbeddingFailedModelSchema = object({
15337
+ modelId: string(),
15338
+ tower: EmbeddingTowerSchema,
15339
+ nodeId: string(),
15340
+ crashes: number(),
15341
+ windowMs: number(),
15342
+ sinceMs: number(),
15343
+ lastReason: string()
15344
+ });
15345
+ /**
15346
+ * A model whose REQUIREMENTS can never be met on this node (D649 round 5):
15347
+ * an id the catalog does not know, a model URL answering 404/410, a declared
15348
+ * sibling (the tokenizer) that is not there. After `attempts` failed builds
15349
+ * it is terminally `requirements-failed`, refused by name until an operator
15350
+ * `resetFailedModels` or a model change — the same exits as a crashed tower.
15351
+ */
15352
+ var EmbeddingFailedRequirementSchema = object({
15353
+ modelId: string(),
15354
+ tower: EmbeddingTowerSchema,
15355
+ nodeId: string(),
15356
+ attempts: number(),
15357
+ sinceMs: number(),
15358
+ lastReason: string()
15359
+ });
15208
15360
  var EmbeddingInfoSchema = object({
15209
15361
  modelId: string(),
15210
15362
  embeddingDim: number(),
15211
- ready: boolean()
15212
- });
15363
+ ready: boolean(),
15364
+ /**
15365
+ * The node that answered. Absent only from an encoder older than D649's
15366
+ * crash budget — whose `failedModels` is then UNKNOWN (D315), never "none".
15367
+ */
15368
+ nodeId: string().optional(),
15369
+ /**
15370
+ * Towers in `failed` on the answering node, each row naming it. `undefined`
15371
+ * means the node could not say (pre-budget encoder); a node that has the
15372
+ * budget always answers an array, empty included.
15373
+ */
15374
+ failedModels: array(EmbeddingFailedModelSchema).optional(),
15375
+ /** Models terminally `requirements-failed` on the answering node; same reading as above. */
15376
+ failedRequirements: array(EmbeddingFailedRequirementSchema).optional()
15377
+ });
15378
+ /**
15379
+ * The THREE codes an encoder refusal can carry (D649, D6). Same shape as
15380
+ * `VECTOR_INDEX_DIM_CONFLICT`: the code rides in the MESSAGE, because an
15381
+ * Error's own properties do not survive the UDS/tRPC hop and its message does,
15382
+ * and both sides go through the helpers below — the encoder builds the
15383
+ * refusal, the live detail plane classifies on it to count refusals per
15384
+ * camera instead of logging one warning per track. The bracketed token
15385
+ * carries the code, the model, the tower and the node so a consumer never
15386
+ * parses prose.
15387
+ *
15388
+ * - `EMBEDDING_MODEL_FAILED`: the tower crashed / failed to load past the crash
15389
+ * budget — terminal until `resetFailedModels` or a model change.
15390
+ * - `EMBEDDING_REQUIREMENTS_UNAVAILABLE`: files or runtime not there right now
15391
+ * (a download or Python that failed, or the cooldown after one) — the next
15392
+ * request past the cooldown tries again.
15393
+ * - `EMBEDDING_REQUIREMENTS_FAILED`: the requirements can never be met (unknown
15394
+ * id, 404/410, missing sibling) and the bounded attempts are spent —
15395
+ * terminal, same exits as a crashed tower.
15396
+ */
15397
+ var EMBEDDING_MODEL_FAILED = "embedding-model-failed";
15398
+ var EMBEDDING_REQUIREMENTS_UNAVAILABLE = "embedding-requirements-unavailable";
15399
+ var EMBEDDING_REQUIREMENTS_FAILED = "embedding-requirements-failed";
15400
+ var EmbeddingRefusalCodeSchema = _enum([
15401
+ EMBEDDING_MODEL_FAILED,
15402
+ EMBEDDING_REQUIREMENTS_UNAVAILABLE,
15403
+ EMBEDDING_REQUIREMENTS_FAILED
15404
+ ]);
15405
+ function embeddingRefusalToken(code, on) {
15406
+ return `[${code} model=${on.modelId} tower=${on.tower} node=${on.nodeId}]`;
15407
+ }
15408
+ /** The encoder's refusal for a crashed tower, carrying {@link EMBEDDING_MODEL_FAILED}. */
15409
+ function embeddingModelFailedError(row) {
15410
+ return /* @__PURE__ */ new Error(`${embeddingRefusalToken(EMBEDDING_MODEL_FAILED, row)} ${row.modelId} (${row.tower} tower) crashed ${String(row.crashes)} times in ${String(Math.round(row.windowMs / 1e3))}s on ${row.nodeId} — ${row.lastReason}. Cleared by embeddingEncoder.resetFailedModels({ modelId: "${row.modelId}", nodeId: "${row.nodeId}" }) or a model change.`);
15411
+ }
15412
+ /** The requirements refusal for THIS request, carrying {@link EMBEDDING_REQUIREMENTS_UNAVAILABLE}. */
15413
+ function embeddingRequirementsUnavailableError(on, reason) {
15414
+ return /* @__PURE__ */ new Error(`${embeddingRefusalToken(EMBEDDING_REQUIREMENTS_UNAVAILABLE, on)} ${on.modelId} (${on.tower} tower) on ${on.nodeId}: ${reason}`);
15415
+ }
15416
+ /** The terminal requirements refusal, carrying {@link EMBEDDING_REQUIREMENTS_FAILED}. */
15417
+ function embeddingRequirementsFailedError(row) {
15418
+ return /* @__PURE__ */ new Error(`${embeddingRefusalToken(EMBEDDING_REQUIREMENTS_FAILED, row)} ${row.modelId} (${row.tower} tower) on ${row.nodeId}: requirements can never be met — ${String(row.attempts)} attempts, last: ${row.lastReason}. Cleared by embeddingEncoder.resetFailedModels({ modelId: "${row.modelId}", nodeId: "${row.nodeId}" }) or a model change.`);
15419
+ }
15420
+ var EMBEDDING_REFUSAL_TOKEN = new RegExp(`\\[(${EMBEDDING_MODEL_FAILED}|${EMBEDDING_REQUIREMENTS_UNAVAILABLE}|${EMBEDDING_REQUIREMENTS_FAILED}) model=([^\\s\\]]+) tower=(image|text) node=([^\\s\\]]+)\\]`);
15421
+ /** The refusal `err` (possibly re-wrapped by a transport) carries, or `null` for any other error. */
15422
+ function embeddingRefusalOf(err) {
15423
+ const message = err instanceof Error ? err.message : String(err);
15424
+ const match = EMBEDDING_REFUSAL_TOKEN.exec(message);
15425
+ if (match === null) return null;
15426
+ const code = EmbeddingRefusalCodeSchema.safeParse(match[1]);
15427
+ const tower = EmbeddingTowerSchema.safeParse(match[3]);
15428
+ if (!code.success || !tower.success || match[2] === void 0 || match[4] === void 0) return null;
15429
+ return {
15430
+ code: code.data,
15431
+ modelId: match[2],
15432
+ tower: tower.data,
15433
+ nodeId: match[4]
15434
+ };
15435
+ }
15436
+ /**
15437
+ * ONE provider per node (`placement: any-node`), addressed like every global
15438
+ * collection: the codegen injects a `{ nodeId?, addonId? }` selector on the
15439
+ * void methods and lifts a top-level `nodeId` off the object ones. A call
15440
+ * that names no node is answered by the HUB's provider — never by a merge
15441
+ * across nodes, because no global collection fans out across nodes (only the
15442
+ * providers of one node are `concatCollection`-fanned). So a fleet view of
15443
+ * `failedModels` is one `getInfo({ nodeId })` per node, and every answer
15444
+ * names the node it came from (D649 round 4); a node that cannot be asked is
15445
+ * UNKNOWN to the reader, never "no failures" (D315).
15446
+ */
15213
15447
  var embeddingEncoderCapability = {
15214
15448
  name: "embedding-encoder",
15215
15449
  scope: "system",
@@ -15228,8 +15462,30 @@ var embeddingEncoderCapability = {
15228
15462
  width: number(),
15229
15463
  height: number()
15230
15464
  }), EmbeddingResultSchema, { auth: "admin" }),
15231
- encodeText: method(object({ text: string() }), EmbeddingResultSchema, { auth: "admin" }),
15232
- getInfo: method(_void(), EmbeddingInfoSchema, { auth: "admin" })
15465
+ /**
15466
+ * `modelId` (a CLIP IMAGE model id, whose catalog `clip.textModelId` names
15467
+ * the text tower) encodes in that model's space; absent, the cluster row's
15468
+ * `clip-embedding` model — the space every writer is in (D649).
15469
+ */
15470
+ encodeText: method(object({
15471
+ text: string(),
15472
+ modelId: string().min(1).optional()
15473
+ }), EmbeddingResultSchema, { auth: "admin" }),
15474
+ /** Answers for ONE node — the `nodeId` selector's, else the hub's. */
15475
+ getInfo: method(_void(), EmbeddingInfoSchema, { auth: "admin" }),
15476
+ /**
15477
+ * The operator's explicit clear of the `failed` state (one model, or all)
15478
+ * on ONE node — pass `nodeId` for an agent; the result names the node it
15479
+ * cleared. The only way out besides a model change: a crashing tower is
15480
+ * not retried on a timer.
15481
+ */
15482
+ resetFailedModels: method(object({ modelId: string().min(1).optional() }), object({
15483
+ cleared: array(string()),
15484
+ nodeId: string()
15485
+ }), {
15486
+ kind: "mutation",
15487
+ auth: "admin"
15488
+ })
15233
15489
  }
15234
15490
  };
15235
15491
  /**
@@ -18758,7 +19014,12 @@ var NcMediaPolicySchema = object({
18758
19014
  * the degrade engine, which drops the video and keeps the still.
18759
19015
  */
18760
19016
  clip: boolean().optional(),
18761
- /** Seconds of footage BEFORE / AFTER the event instant. Defaults 3 / 7. */
19017
+ /**
19018
+ * Seconds of footage BEFORE / AFTER the event instant. Absent =
19019
+ * {@link NC_CLIP_PRE_ROLL_DEFAULT_SEC} / {@link NC_CLIP_POST_ROLL_DEFAULT_SEC}
19020
+ * (4 / 6), resolved by the Notification Center at dispatch — deliberately not
19021
+ * a Zod default, so a rule that never chose keeps following the hub's.
19022
+ */
18762
19023
  clipPreRollSec: number().int().min(0).max(30).optional(),
18763
19024
  clipPostRollSec: number().int().min(0).max(30).optional(),
18764
19025
  /**
@@ -20841,6 +21102,202 @@ var OauthIntegrationDescriptorSchema = object({
20841
21102
  });
20842
21103
  method(_void(), OauthIntegrationDescriptorSchema, { auth: "admin" });
20843
21104
  /**
21105
+ * A model choice has a SCOPE, and a scope change has a workflow.
21106
+ *
21107
+ * ## The two scopes
21108
+ *
21109
+ * Almost every pipeline step's model is a **node** question: which build runs
21110
+ * fastest on THIS accelerator. Two nodes may legitimately answer differently —
21111
+ * a Coral runs the tflite SSD, a Mac runs the coreml YOLO — because the answers
21112
+ * are compared against nothing. They produce boxes, and a box is a box.
21113
+ *
21114
+ * Two steps are not like that. `face-embedding` and `clip-embedding` produce
21115
+ * **vectors that land in ONE shared index** (`identity_samples`,
21116
+ * `vec_object_clip`) and are ranked against each other by cosine similarity.
21117
+ * Cosine similarity between two encoders is not a weak signal, it is a
21118
+ * meaningless number — and nothing inside a vector can tell you it happened.
21119
+ * So for those two steps the model is a **cluster** question with exactly one
21120
+ * answer, stored in exactly one row.
21121
+ *
21122
+ * That is the same argument [D52](../../../../docs/decisions/adr-0052.md) makes
21123
+ * for the crop convention (`detail-crop.ts`), one level up: the crop decides
21124
+ * WHAT pixels the encoder sees, this decides WHICH encoder sees them. Both are
21125
+ * cluster-wide for the same reason and neither may become per-node.
21126
+ *
21127
+ * ## Why the registry lives here and not in the step catalog
21128
+ *
21129
+ * The scope itself is declared on the step, in
21130
+ * `detection-pipeline/registry/step-definitions.ts` (`StepDefinition.modelScope`)
21131
+ * — that is where a new step declares what kind of choice its model is. But the
21132
+ * catalog lives inside `addon-pipeline`, and three packages that must NOT
21133
+ * import an addon need to know the set: the orchestrator (which renders and
21134
+ * stores the row), post-analysis (which pins the row for a re-embed pass) and
21135
+ * admin-ui (which mirrors it). So the set is mirrored here, and
21136
+ * `scripts/check-cluster-model-scope.ts` fails the build when the two disagree.
21137
+ * A hand-copied key that stops matching is exactly how a setting silently stops
21138
+ * arriving while both sides still look correct.
21139
+ *
21140
+ * ## The defaults ARE today's behaviour
21141
+ *
21142
+ * {@link DEFAULT_CLUSTER_STEP_MODELS} reproduces the catalog `defaultModelId`
21143
+ * of both steps. Declaring the scope therefore changes nothing on the day it
21144
+ * ships: the cluster row starts out saying what every node was already doing.
21145
+ * Changing it is legitimate — that is what the knob is for — but it invalidates
21146
+ * the stored vectors of that surface, and must be followed by a re-embed pass
21147
+ * (`face-reembed-pass.ts`, `embedding-rebuild.ts`).
21148
+ */
21149
+ /**
21150
+ * Why the orchestrator cannot say which model the operator chose for a
21151
+ * cluster-scoped step (D651).
21152
+ */
21153
+ var CLUSTER_MODEL_CHOICE_UNREADABLE_REASONS = [
21154
+ "owner-not-ready",
21155
+ "store-read-failed",
21156
+ "three-way-read-unavailable",
21157
+ "invalid-stored",
21158
+ "not-cluster-scoped"
21159
+ ];
21160
+ /**
21161
+ * The cluster-scoped steps. Mirrored from the catalog's `modelScope: 'cluster'`
21162
+ * declarations and guarded by `scripts/check-cluster-model-scope.ts`.
21163
+ */
21164
+ var CLUSTER_MODEL_SCOPED_STEPS = [{
21165
+ stepId: "face-embedding",
21166
+ label: "Face recognition model",
21167
+ defaultModelId: "auraface-r100",
21168
+ indexName: "the enrolled face gallery",
21169
+ options: [
21170
+ {
21171
+ id: "auraface-r100",
21172
+ label: "AuraFace R100"
21173
+ },
21174
+ {
21175
+ id: "arcface-r100",
21176
+ label: "ArcFace (ResNet34)"
21177
+ },
21178
+ {
21179
+ id: "inception-resnet-v1",
21180
+ label: "Inception ResNet V1"
21181
+ }
21182
+ ]
21183
+ }, {
21184
+ stepId: "clip-embedding",
21185
+ label: "Semantic search model",
21186
+ defaultModelId: "mobileclip-s1",
21187
+ indexName: "the object semantic-search index",
21188
+ options: [
21189
+ {
21190
+ id: "mobileclip-s1",
21191
+ label: "MobileCLIP S1"
21192
+ },
21193
+ {
21194
+ id: "mobileclip-s2",
21195
+ label: "MobileCLIP S2"
21196
+ },
21197
+ {
21198
+ id: "siglip2-b16-224",
21199
+ label: "SigLIP2 B/16 (Apache-2.0)"
21200
+ }
21201
+ ]
21202
+ }];
21203
+ /**
21204
+ * The settings key holding one step's cluster model choice.
21205
+ *
21206
+ * Step-qualified so the keys stay unique across the addon's whole schema, which
21207
+ * is what lets {@link pickClusterStepModels} walk every section instead of
21208
+ * trusting the section id.
21209
+ */
21210
+ function clusterModelSettingKey(stepId) {
21211
+ return `clusterModel:${stepId}`;
21212
+ }
21213
+ /** The cluster row when nobody has configured one — today's catalog defaults. */
21214
+ var DEFAULT_CLUSTER_STEP_MODELS = Object.freeze(Object.fromEntries(CLUSTER_MODEL_SCOPED_STEPS.map((s) => [s.stepId, s.defaultModelId])));
21215
+ function interpretStoredClusterModel(raw) {
21216
+ if (raw === void 0 || raw === null || raw === "") return { kind: "absent" };
21217
+ if (typeof raw === "string") return {
21218
+ kind: "chosen",
21219
+ modelId: raw
21220
+ };
21221
+ return {
21222
+ kind: "invalid",
21223
+ value: raw
21224
+ };
21225
+ }
21226
+ /**
21227
+ * Narrow a FLAT settings record to the cluster row.
21228
+ *
21229
+ * Per-FIELD fallback, deliberately (same rule as `readDetailCropConvention`): a
21230
+ * junk face model must not also discard a valid clip model. An `absent` or
21231
+ * `invalid` value ({@link interpretStoredClusterModel}) resolves to the step's
21232
+ * catalog default — never to a blank id, because a blank id downstream becomes
21233
+ * "substitute the format default", which is precisely the substitution this
21234
+ * scope exists to forbid.
21235
+ */
21236
+ function readClusterStepModels(config) {
21237
+ const out = {};
21238
+ for (const step of CLUSTER_MODEL_SCOPED_STEPS) {
21239
+ const read = interpretStoredClusterModel(config[clusterModelSettingKey(step.stepId)]);
21240
+ out[step.stepId] = read.kind === "chosen" ? read.modelId : step.defaultModelId;
21241
+ }
21242
+ return out;
21243
+ }
21244
+ function isHydratedField$2(entry) {
21245
+ return typeof entry === "object" && entry !== null && "key" in entry;
21246
+ }
21247
+ /**
21248
+ * Extract the cluster row from an `addon-settings.getGlobalSettings` payload.
21249
+ *
21250
+ * Walks EVERY section rather than looking inside {@link CLUSTER_MODEL_SECTION_ID}
21251
+ * alone: the keys are unique across the addon's schema, and a section rename
21252
+ * must not silently revert the whole cluster to the defaults. A `null` payload
21253
+ * (addon mid-boot) is the defaults.
21254
+ */
21255
+ function pickClusterStepModels(view) {
21256
+ if (view === null) return DEFAULT_CLUSTER_STEP_MODELS;
21257
+ return readClusterStepModels(flattenHydratedView(view, clusterModelKeys()));
21258
+ }
21259
+ function clusterModelKeys() {
21260
+ return new Set(CLUSTER_MODEL_SCOPED_STEPS.map((s) => clusterModelSettingKey(s.stepId)));
21261
+ }
21262
+ /** The `wanted` keys of a hydrated view as one flat record, every section walked. */
21263
+ function flattenHydratedView(view, wanted) {
21264
+ const flat = {};
21265
+ for (const section of view.sections) for (const entry of section.fields) {
21266
+ if (!isHydratedField$2(entry) || typeof entry.key !== "string") continue;
21267
+ if (wanted.has(entry.key)) flat[entry.key] = entry.value;
21268
+ }
21269
+ return flat;
21270
+ }
21271
+ var CLUSTER_STEP_SETTING_FIELDS = [{
21272
+ stepId: "face-embedding",
21273
+ key: "minLandmarkFaceSize",
21274
+ label: "Min face size for recognition (detection px)",
21275
+ description: "Refuse to embed a face smaller than this IN THE DETECTION FRAME. Applies to every node — the enrolled gallery is one index, and two admission floors would fill it from two policies. 0 disables the gate.",
21276
+ type: "slider",
21277
+ min: 0,
21278
+ max: 64,
21279
+ step: 2,
21280
+ default: 24
21281
+ }];
21282
+ function clusterStepSettingKey(stepId, fieldKey) {
21283
+ return `clusterStepSetting:${stepId}:${fieldKey}`;
21284
+ }
21285
+ var ClusterSettingNumberSchema = number().finite();
21286
+ function readClusterStepSettings(config) {
21287
+ const out = {};
21288
+ for (const field of CLUSTER_STEP_SETTING_FIELDS) {
21289
+ const parsed = ClusterSettingNumberSchema.safeParse(config[clusterStepSettingKey(field.stepId, field.key)]);
21290
+ const value = parsed.success ? parsed.data : field.default;
21291
+ const existing = out[field.stepId] ?? {};
21292
+ out[field.stepId] = {
21293
+ ...existing,
21294
+ [field.key]: value
21295
+ };
21296
+ }
21297
+ return out;
21298
+ }
21299
+ readClusterStepSettings({});
21300
+ /**
20844
21301
  * pipeline-analytics — device-scoped wrapper cap. Refines raw
20845
21302
  * per-frame detections emitted by the pipeline runner into tracked
20846
21303
  * objects, per-kind event collections (motion / object / audio), and
@@ -21656,7 +22113,8 @@ var MediaFileKindEnum = _enum([
21656
22113
  "thumbnailSmall",
21657
22114
  "confirmationCrop",
21658
22115
  "debugCrop",
21659
- "sceneFrame"
22116
+ "sceneFrame",
22117
+ "lastSceneFrame"
21660
22118
  ]);
21661
22119
  /**
21662
22120
  * One media row ON THE WIRE: what it is, how big it is, and WHERE ITS BYTES
@@ -22208,7 +22666,23 @@ var SearchObjectEventsInput = object({
22208
22666
  until: number().optional(),
22209
22667
  classFilter: string().optional(),
22210
22668
  limit: number().default(50),
22211
- minScore: number().min(0).max(1).default(.2)
22669
+ /**
22670
+ * An ABSOLUTE cosine floor. Optional since D649: a floor is a property of the
22671
+ * model (0.2 kept 96% of matched pairs on MobileCLIP S1 and 2.7% on SigLIP2),
22672
+ * so an absent one resolves to the searched model's own `searchMinScore`
22673
+ * scaled by `strictness`. A number sent here is honoured verbatim.
22674
+ */
22675
+ minScore: number().min(0).max(1).optional(),
22676
+ /** Model-relative floor — see `resolveClipSearchMinScore`. Default `loose`. */
22677
+ strictness: ClipSearchStrictnessSchema.optional(),
22678
+ /**
22679
+ * Search THIS CLIP model's index instead of the cluster row's. Every index a
22680
+ * model ever wrote stays searchable until it is wiped (the MobileCLIP index
22681
+ * through a SigLIP2 cutover and its rollback window). An id with no CLIP
22682
+ * metadata is refused; an id other than the cluster row's is ADMIN-only
22683
+ * (`model-override-requires-admin`).
22684
+ */
22685
+ modelId: string().min(1).optional()
22212
22686
  });
22213
22687
  var TrackCascadeCountsSchema = object({
22214
22688
  /** Persisted track roots deleted (authoritative). */
@@ -22343,7 +22817,41 @@ var RebuildObjectEmbeddingsInput = object({
22343
22817
  * comparable, so wiping and rebuilding is the only way to be sure every vector
22344
22818
  * means the same thing.
22345
22819
  */
22346
- var WipeObjectEmbeddingsResultSchema = object({ deleted: number() });
22820
+ var WipeObjectEmbeddingsResultSchema = object({
22821
+ deleted: number(),
22822
+ /**
22823
+ * CLIP indexes that could NOT be emptied (unreachable, or refused at their
22824
+ * dimension) — not a clean slate. Additive and optional (D649).
22825
+ */
22826
+ failedIndexes: array(string()).optional()
22827
+ });
22828
+ /**
22829
+ * Why a rebuild did not start, BY NAME — ONE vocabulary for both gates in front
22830
+ * of a pass (D649 over D651). A bare `started: false` read the same for "the
22831
+ * stores are booting" and "the cluster row names a model with no CLIP
22832
+ * metadata", which need different fixes.
22833
+ * - `stores-unavailable` — the analytics stores or the API are not up yet.
22834
+ * - the owner's confirmation of the cluster model (D651, `ClusterPinConfirmer`):
22835
+ * a pass that rewrites an index needs two agreeing reads of the OWNER's
22836
+ * answer (`pipelineOrchestrator.getClusterModelChoice`) — a pass that cannot
22837
+ * name its model does not run (D54):
22838
+ * - the owner's own `unreadable` reasons (`owner-not-ready`,
22839
+ * `store-read-failed`, `three-way-read-unavailable`, `invalid-stored`,
22840
+ * `not-cluster-scoped`);
22841
+ * - `method-unavailable` — the orchestrator predates the method;
22842
+ * - `read-failed` — the call failed or answered something unparseable;
22843
+ * - `reads-disagree` — the two reads named different choices.
22844
+ * - `not-a-clip-model` — the CONFIRMED id has no CLIP metadata, so there is no
22845
+ * index to fill and no dimension to check against (D649).
22846
+ */
22847
+ var RebuildObjectEmbeddingsRefusalSchema = _enum([
22848
+ "stores-unavailable",
22849
+ ...CLUSTER_MODEL_CHOICE_UNREADABLE_REASONS,
22850
+ "method-unavailable",
22851
+ "read-failed",
22852
+ "reads-disagree",
22853
+ "not-a-clip-model"
22854
+ ]);
22347
22855
  /**
22348
22856
  * Acknowledgement that a rebuild STARTED.
22349
22857
  *
@@ -22356,7 +22864,12 @@ var WipeObjectEmbeddingsResultSchema = object({ deleted: number() });
22356
22864
  var RebuildObjectEmbeddingsResultSchema = object({
22357
22865
  started: boolean(),
22358
22866
  /** True when a pass was already running; the new request is ignored. */
22359
- alreadyRunning: boolean()
22867
+ alreadyRunning: boolean(),
22868
+ /** Present when the pass refused to start — see `RebuildObjectEmbeddingsRefusalSchema`. */
22869
+ refusal: RebuildObjectEmbeddingsRefusalSchema.optional(),
22870
+ /** The CLIP model the pass pinned, and the index it fills (when it started). */
22871
+ modelId: string().optional(),
22872
+ index: string().optional()
22360
22873
  });
22361
22874
  var RebuildStatusSchema = object({
22362
22875
  running: boolean(),
@@ -22390,7 +22903,11 @@ var RebuildStatusSchema = object({
22390
22903
  startedAtMs: number().nullable(),
22391
22904
  finishedAtMs: number().nullable(),
22392
22905
  /** Present when the pass ended by throwing. */
22393
- error: string().nullable()
22906
+ error: string().nullable(),
22907
+ /** The CLIP model the current / last pass pinned (D54), `null` before any. */
22908
+ modelId: string().nullable(),
22909
+ /** The index that pass fills — `ClipModelMeta.vectorIndex` of `modelId` (D649). */
22910
+ index: string().nullable()
22394
22911
  });
22395
22912
  /**
22396
22913
  * Acknowledgement that a debug-media reclaim STARTED.
@@ -23349,7 +23866,7 @@ var pipelineAnalyticsCapability = {
23349
23866
  * ObjectEvents by trackId. Returns up to `limit` events scored ≥
23350
23867
  * `minScore`, sorted descending by score.
23351
23868
  */
23352
- searchObjectEvents: method(SearchObjectEventsInput, array(ScoredObjectEventSchema).readonly()),
23869
+ searchObjectEvents: method(SearchObjectEventsInput, array(ScoredObjectEventSchema).readonly(), { caller: "required" }),
23353
23870
  wipeObjectEmbeddings: method(object({}), WipeObjectEmbeddingsResultSchema, {
23354
23871
  kind: "mutation",
23355
23872
  auth: "admin"
@@ -23829,7 +24346,14 @@ method(_void(), array(PipelineEngineChoiceSchema)), method(_void(), PipelineEngi
23829
24346
  height: number()
23830
24347
  }), { kind: "mutation" }), method(object({
23831
24348
  stepId: string(),
23832
- frameId: number().int()
24349
+ frameId: number().int(),
24350
+ /**
24351
+ * The model to time — REQUIRED (D658). Without it the pool answered the
24352
+ * step's ACTIVE variant (the first loaded after boot), so a benchmark
24353
+ * of model B silently timed model A. Callers pass the `rootModelId`
24354
+ * their warmup `runPipeline` reported: the model that actually ran.
24355
+ */
24356
+ modelId: string().min(1)
23833
24357
  }), record(string(), unknown()), { kind: "mutation" }), method(object({ frameId: number().int() }), _void(), { kind: "mutation" }), method(object({ deviceKey: string().optional() }), EffectiveTuningSchema), method(_void(), array(object({
23834
24358
  engineKey: string(),
23835
24359
  engine: PipelineEngineChoiceSchema,
@@ -24446,6 +24970,17 @@ var RunnerFrameSourceSchema = discriminatedUnion("kind", [object({ kind: literal
24446
24970
  hubHostnameOverride: string().optional()
24447
24971
  })]).describe("Per-camera frame-source mode for the runner (P2c)");
24448
24972
  /**
24973
+ * What ONE step runs with on ONE roster device for THIS camera (D650): the
24974
+ * device's per-(node,device) base with the camera's override for that device
24975
+ * on top — the same `override ?? base` merge the orchestrator applies to the
24976
+ * elected device (`applyDeviceProvisioning`). Absent `modelId` ⇒ the executor
24977
+ * resolves the device format's default, exactly as on the elected device.
24978
+ */
24979
+ var RunnerJumpStepProvisioningSchema = object({
24980
+ modelId: string().optional(),
24981
+ settings: record(string(), unknown()).optional()
24982
+ });
24983
+ /**
24449
24984
  * One ENABLED inference device on the runner's node, as the step-tree
24450
24985
  * device-jump resolver sees it (phase 1). The orchestrator populates this
24451
24986
  * roster on the attach payload whenever the camera is elected onto a specific
@@ -24457,7 +24992,16 @@ var RunnerFrameSourceSchema = discriminatedUnion("kind", [object({ kind: literal
24457
24992
  var RunnerInferenceDeviceSchema = object({
24458
24993
  deviceKey: string(),
24459
24994
  weight: number().positive().default(1),
24460
- maxSessions: number().int().positive().nullable().default(null)
24995
+ maxSessions: number().int().positive().nullable().default(null),
24996
+ /**
24997
+ * Per-step provisioning for this camera on THIS device (D650), keyed by step
24998
+ * id. A step the runner jumps here runs with these fields, never with the
24999
+ * elected device's: `modelId` / `settings` are REPLACED on the jumped subtree
25000
+ * (a step absent from the map runs with neither — the target format default).
25001
+ * Absent field ⇒ an orchestrator that predates D650: the jumped step keeps
25002
+ * the elected device's provisioning, as before.
25003
+ */
25004
+ steps: record(string(), RunnerJumpStepProvisioningSchema).optional()
24461
25005
  });
24462
25006
  /**
24463
25007
  * Camera assignment payload sent by `addon-pipeline-orchestrator` to a
@@ -25332,6 +25876,28 @@ var NodeInferenceDeviceSchema = object({
25332
25876
  */
25333
25877
  exclusion: InferenceDeviceExclusionReasonSchema.nullable()
25334
25878
  });
25879
+ /**
25880
+ * The operator's model choice for one cluster-scoped step, answered by the
25881
+ * addon that OWNS the `clusterModel:*` settings (D651). Three answers, never
25882
+ * folded: a written choice, a key nobody wrote (the cluster runs the default
25883
+ * BY ABSENCE), or no answer. A caller that rewrites an index acts only on the
25884
+ * first two, read twice and agreeing.
25885
+ */
25886
+ var ClusterModelChoiceSchema = discriminatedUnion("kind", [
25887
+ object({
25888
+ kind: literal("stored"),
25889
+ modelId: string()
25890
+ }),
25891
+ object({
25892
+ kind: literal("absent"),
25893
+ defaultModelId: string()
25894
+ }),
25895
+ object({
25896
+ kind: literal("unreadable"),
25897
+ reason: _enum(CLUSTER_MODEL_CHOICE_UNREADABLE_REASONS),
25898
+ error: string().optional()
25899
+ })
25900
+ ]);
25335
25901
  var NodeInferenceDevicesSchema = object({
25336
25902
  nodeId: string(),
25337
25903
  /** False when the node's platform-probe was unreachable (no live device set). */
@@ -25359,10 +25925,17 @@ method(StorageMigrationLeaseInputSchema, object({ paused: literal(true) }), {
25359
25925
  }), object({ success: literal(true) }), {
25360
25926
  kind: "mutation",
25361
25927
  auth: "admin"
25362
- }), method(object({ deviceId: number() }), object({ deviceKey: string().nullable() })), method(_void(), object({ migrated: number() }), {
25928
+ }), method(object({ deviceId: number() }), object({ deviceKey: string().nullable() })), method(_void(), object({
25929
+ migrated: number(),
25930
+ skipped: array(object({
25931
+ deviceId: number(),
25932
+ targetNodeId: string(),
25933
+ reason: string()
25934
+ })).default([])
25935
+ }), {
25363
25936
  kind: "mutation",
25364
25937
  auth: "admin"
25365
- }), method(_void(), array(PipelineAssignmentSchema).readonly()), method(object({ deviceId: number() }), PipelineAssignmentSchema.nullable()), method(_void(), array(AgentLoadSummarySchema).readonly()), method(_void(), GlobalMetricsSchema), method(object({ deviceId: number() }), CameraMetricsSchema.nullable()), method(object({ nodeId: string() }), CapabilityBindingsSchema), method(object({
25938
+ }), method(_void(), array(PipelineAssignmentSchema).readonly()), method(object({ deviceId: number() }), PipelineAssignmentSchema.nullable()), method(_void(), array(AgentLoadSummarySchema).readonly()), method(object({ stepId: string() }), ClusterModelChoiceSchema), method(_void(), GlobalMetricsSchema), method(object({ deviceId: number() }), CameraMetricsSchema.nullable()), method(object({ nodeId: string() }), CapabilityBindingsSchema), method(object({
25366
25939
  nodeId: string(),
25367
25940
  capName: string(),
25368
25941
  addonId: string()
@@ -27078,6 +27651,20 @@ var VectorScanResultSchema = object({
27078
27651
  */
27079
27652
  nextCursor: number().int().nonnegative().nullable()
27080
27653
  });
27654
+ /**
27655
+ * The ONE error code for "this index exists at another dimension; refusing to
27656
+ * redeclare it" (D649). It rides in the MESSAGE — an Error's own properties do
27657
+ * not survive the UDS/tRPC hop, its message does — and both sides go through
27658
+ * the helpers below, never a copied phrase: a consumer that must tell "this
27659
+ * index can never hold my vectors" from "the provider is unreachable" (a
27660
+ * delete counts the first as nothing-to-delete and the second as still
27661
+ * present) otherwise breaks silently the day the wording changes.
27662
+ */
27663
+ var VECTOR_INDEX_DIM_CONFLICT = "vector-index-dim-conflict";
27664
+ /** True when `err` (possibly re-wrapped by a transport) is that refusal. */
27665
+ function isVectorIndexDimConflict(err) {
27666
+ return (err instanceof Error ? err.message : String(err)).includes(`[${VECTOR_INDEX_DIM_CONFLICT}]`);
27667
+ }
27081
27668
  var VectorStatsInputSchema = object({ index: string() });
27082
27669
  var VectorStatsResultSchema = object({
27083
27670
  /** Provider id, so an operator can tell brute force from an ANN index. */
@@ -27737,6 +28324,358 @@ DeviceType.Camera, method(object({
27737
28324
  auth: "protected"
27738
28325
  });
27739
28326
  /**
28327
+ * LA tabella "quale booleano di questo tipo di device conta come ALTO", e il
28328
+ * valutatore puro del suo FRONTE.
28329
+ *
28330
+ * Viveva dentro il builtin virtual-doorbell
28331
+ * (`@camstack/system` — `builtins/doorbell/trigger-engine.ts`) e i suoi
28332
+ * predicati erano privati al modulo. Il recorder ne ha bisogno per il trigger
28333
+ * `RecordingTriggers.sensorDeviceIds`: copiarla avrebbe creato la SECONDA
28334
+ * tabella, che diverge alla prima cap aggiunta e il cui sintomo — "il sensore
28335
+ * fa suonare il campanello ma non registra" — è esattamente D62. Quindi si
28336
+ * SPOSTA qui e il doorbell la ri-esporta.
28337
+ *
28338
+ * ⚠ NON è `DEVICE_STATE_READERS` (`catalogs/device-state-vocabulary.ts`), e le
28339
+ * due non vanno unificate: quella risponde a "qual è la PAROLA di stato per una
28340
+ * regola" (e include `presence`, `cover`, `alarm-panel`), questa a "qual è il
28341
+ * booleano il cui FRONTE conta". Vocabolari deliberatamente diversi.
28342
+ */
28343
+ /**
28344
+ * Known binary / switch source caps → the boolean slice field whose
28345
+ * false→true rise counts as ACTIVE. Every entry is "fire on active".
28346
+ * Sensors whose "active" reading is not a plain boolean (presence's string
28347
+ * state, connectivity's connected flag) are deliberately excluded — a
28348
+ * reconnect is not a doorbell press, and it is not a recording either.
28349
+ */
28350
+ var SOURCE_CAP_ACTIVE_FIELD = {
28351
+ contact: "entryOpen",
28352
+ binary: "on",
28353
+ switch: "on",
28354
+ motion: "detected",
28355
+ flood: "flooded",
28356
+ gas: "detected",
28357
+ smoke: "detected",
28358
+ "carbon-monoxide": "detected",
28359
+ vibration: "detected",
28360
+ tamper: "tampered"
28361
+ };
28362
+ /**
28363
+ * The same caps → the slice field carrying the ms-epoch timestamp of the
28364
+ * last transition. Every source cap MUST appear here (guarded by a spec):
28365
+ * without a transition timestamp the evaluator cannot tell a genuine rise
28366
+ * from a boot-time hydration when the FIRST slice it ever sees is already
28367
+ * active, and errs towards silence — swallowing the rise.
28368
+ *
28369
+ * These timestamps are UPSTREAM ones, not ingest ones: the Home Assistant
28370
+ * provider derives them from `state.last_changed`, so they survive our own
28371
+ * restarts and correctly read as "hours ago" for a state that has been
28372
+ * active for hours. `motion` names its rise timestamp `lastDetectedAt`.
28373
+ */
28374
+ var SOURCE_CAP_CHANGED_AT_FIELD = {
28375
+ contact: "lastChangedAt",
28376
+ binary: "lastChangedAt",
28377
+ switch: "lastChangedAt",
28378
+ motion: "lastDetectedAt",
28379
+ flood: "lastChangedAt",
28380
+ gas: "lastChangedAt",
28381
+ smoke: "lastChangedAt",
28382
+ "carbon-monoxide": "lastChangedAt",
28383
+ vibration: "lastChangedAt",
28384
+ tamper: "lastChangedAt"
28385
+ };
28386
+ /** Cap names whose presence in a device's bindings qualify it as a source. */
28387
+ var SOURCE_CAPS = Object.keys(SOURCE_CAP_ACTIVE_FIELD);
28388
+ /** True when a cap is a recognised binary/switch source. */
28389
+ function isSourceCap(capName) {
28390
+ return Object.prototype.hasOwnProperty.call(SOURCE_CAP_ACTIVE_FIELD, capName);
28391
+ }
28392
+ /** Extract the "active" boolean a source cap's slice carries, or null when
28393
+ * the cap is unknown or the field is missing / non-boolean. */
28394
+ function sliceActiveValue(capName, slice) {
28395
+ const field = SOURCE_CAP_ACTIVE_FIELD[capName];
28396
+ if (field === void 0) return null;
28397
+ const raw = slice[field];
28398
+ return typeof raw === "boolean" ? raw : null;
28399
+ }
28400
+ /** Ms-epoch transition timestamp a source cap's slice carries, or null when
28401
+ * it is absent, non-numeric or the zero "never observed" sentinel. */
28402
+ function sliceChangedAt(capName, slice) {
28403
+ const field = SOURCE_CAP_CHANGED_AT_FIELD[capName];
28404
+ if (field === void 0) return null;
28405
+ const raw = slice[field];
28406
+ if (typeof raw !== "number" || !Number.isFinite(raw) || raw <= 0) return null;
28407
+ return raw;
28408
+ }
28409
+ /**
28410
+ * How recent a source's own transition timestamp must be for a FIRST
28411
+ * sighting that is already active to count as a genuine rise rather than a
28412
+ * hydration of long-standing state.
28413
+ */
28414
+ var DEFAULT_FIRST_SIGHTING_FRESHNESS_MS = 3e4;
28415
+ /**
28416
+ * IL fronte. Puro: nessun orologio proprio, nessuna memoria — il chiamante
28417
+ * porta `prior`, `nowMs` e il proprio `startedAtMs`.
28418
+ *
28419
+ * Il caso della PRIMA slice già attiva è trattato esplicitamente e vale come
28420
+ * fronte solo se il timestamp UPSTREAM della transizione è posteriore a
28421
+ * `startedAtMs` **e** entro `firstSightingFreshnessMs`. Entrambe le metà
28422
+ * servono: la sola freschezza scatterebbe su un'idratazione al boot di uno
28423
+ * stato flippato pochi secondi prima del riavvio, e il solo "dopo che abbiamo
28424
+ * iniziato" scatterebbe, su un processo di lunga vita, per una sorgente
28425
+ * adottata oggi il cui stato è cambiato ieri. Il caso ambiguo ERRA VERSO IL
28426
+ * SILENZIO e lo dichiara (`baseline-seeded-stale-active`).
28427
+ */
28428
+ function evaluateSensorEdge(input) {
28429
+ const value = sliceActiveValue(input.capName, input.slice);
28430
+ if (value === null) return {
28431
+ edge: "none",
28432
+ value: null,
28433
+ reason: isSourceCap(input.capName) ? "non-boolean-value" : "unknown-cap"
28434
+ };
28435
+ if (input.prior === void 0) {
28436
+ if (!value) return {
28437
+ edge: "none",
28438
+ value,
28439
+ reason: "baseline-seeded-inactive"
28440
+ };
28441
+ const changedAt = sliceChangedAt(input.capName, input.slice);
28442
+ const floor = Math.max(input.startedAtMs, input.nowMs - input.firstSightingFreshnessMs);
28443
+ if (changedAt === null || changedAt < floor) return {
28444
+ edge: "none",
28445
+ value,
28446
+ reason: "baseline-seeded-stale-active"
28447
+ };
28448
+ return {
28449
+ edge: "rising",
28450
+ value: true
28451
+ };
28452
+ }
28453
+ if (input.prior === value) return {
28454
+ edge: "none",
28455
+ value,
28456
+ reason: "no-change"
28457
+ };
28458
+ if (!value) return {
28459
+ edge: "none",
28460
+ value,
28461
+ reason: "falling-edge"
28462
+ };
28463
+ return {
28464
+ edge: "rising",
28465
+ value: true
28466
+ };
28467
+ }
28468
+ /**
28469
+ * Doorbell button cap. Two kinds of providers coexist behind this cap
28470
+ * name (same pattern as `snapshot`):
28471
+ *
28472
+ * - **Native** providers: registered per-device by device-driver
28473
+ * addons via `ctx.registerNativeCap` — either on a
28474
+ * `DeviceType.Button` accessory with `role: DeviceRole.Doorbell`,
28475
+ * or directly on the camera (Reolink registers at camera level).
28476
+ * Emits an `onPressed` event every time the firmware pushes a
28477
+ * ring; status tracks the last press and a pressCount since start
28478
+ * (diagnostic).
28479
+ *
28480
+ * - **Wrapper** provider: the `virtual-doorbell` system builtin
28481
+ * (`@camstack/system/builtins/doorbell`). Turns ANY binary-ish
28482
+ * device (contact / switch / event-emitter …) into a doorbell for
28483
+ * a camera. `defaultActive: false` — the operator explicitly binds
28484
+ * it per camera in the device-bindings UI, then picks the source
28485
+ * device + trigger in the per-device settings.
28486
+ *
28487
+ * The DeviceEventPropagator re-emits `onPressed` on the camera parent
28488
+ * — subscribers listening at the camera level receive ring events
28489
+ * with `via[]` populated. No code on the parent needed.
28490
+ */
28491
+ var DoorbellStatusSchema = object({
28492
+ /** Ms epoch of the last press. null = never observed since this provider started. */
28493
+ lastPressedAt: number().nullable(),
28494
+ /** Counter since provider start. Resets on reboot. Useful for metrics/debug. */
28495
+ pressCountSinceStart: number()
28496
+ });
28497
+ var DoorbellPressEventSchema = object({
28498
+ deviceId: number(),
28499
+ timestamp: number()
28500
+ });
28501
+ /**
28502
+ * The `doorbell-source` extension slot's editable value (D648): the camera's
28503
+ * virtual-doorbell trigger devices, exactly what the wrapper's
28504
+ * `doorbellSources` persists (as `{ deviceId }` records).
28505
+ */
28506
+ var DoorbellSourceSlotValueSchema = object({ deviceIds: array(number().int().positive()) });
28507
+ /**
28508
+ * The `doorbell-source` slot — which devices ring this camera's VIRTUAL
28509
+ * doorbell, owned by the `virtual-doorbell` wrapper over its
28510
+ * `doorbellSources` store (D648). A source rings when one of its
28511
+ * `SOURCE_CAPS` rises. Whether the wrapper is bound to the camera at all is a
28512
+ * different authority (`deviceManager.setWrapperActive`, D62) — the slot
28513
+ * reports it, it never writes it.
28514
+ */
28515
+ var DOORBELL_SOURCE_SLOT = {
28516
+ id: "doorbell-source",
28517
+ label: "Doorbell trigger devices",
28518
+ description: "Any of these becoming active rings this camera's virtual doorbell: a binary sensor when it goes active, a switch when it turns on.",
28519
+ shape: "association",
28520
+ hostDeviceTypes: [DeviceType.Camera],
28521
+ sourceCaps: SOURCE_CAPS,
28522
+ cardinality: "many",
28523
+ value: DoorbellSourceSlotValueSchema
28524
+ };
28525
+ var doorbellCapability = {
28526
+ name: "doorbell",
28527
+ scope: "device",
28528
+ deviceNative: true,
28529
+ mode: "singleton",
28530
+ kind: "wrapper",
28531
+ defaultActive: false,
28532
+ deviceTypes: [DeviceType.Button, DeviceType.Camera],
28533
+ extensionSlots: [DOORBELL_SOURCE_SLOT],
28534
+ methods: {},
28535
+ events: {
28536
+ /**
28537
+ * Fires once per physical press. Reolink delivers via Baichuan
28538
+ * push (`ReolinkSimpleEvent.type === 'doorbell'`). There is no
28539
+ * release/duration — it's a pulse.
28540
+ */
28541
+ onPressed: { data: DoorbellPressEventSchema } },
28542
+ status: {
28543
+ schema: DoorbellStatusSchema,
28544
+ kind: "push"
28545
+ },
28546
+ /**
28547
+ * Runtime-state slice — last press timestamp + lifetime press count.
28548
+ * Mirrored by the kernel and readable via
28549
+ * `device.state.doorbell.value`. UIs can show "last ring 5m ago"
28550
+ * without subscribing.
28551
+ */
28552
+ runtimeState: DoorbellStatusSchema,
28553
+ /**
28554
+ * Runtime-state durability: **restored** — a monotonic accumulator: the slice IS the record. `lastPressedAt` is content here, not a clock, so it is deliberately NOT volatile.
28555
+ *
28556
+ * See `RuntimeStateDurability`. Enforced by
28557
+ * `scripts/check-runtime-state-durability.ts`.
28558
+ */
28559
+ durability: "restored"
28560
+ };
28561
+ var ExtensionSlotIdSchema = _enum(["doorbell-source", "linked-devices"]);
28562
+ DeviceType.Camera, DeviceType.Camera;
28563
+ /** A slot's editable value, discriminated on `slot`. */
28564
+ var ExtensionSlotValueSchema = discriminatedUnion("slot", [DoorbellSourceSlotValueSchema.extend({ slot: literal("doorbell-source") }), LinkedDevicesSlotValueSchema.extend({ slot: literal("linked-devices") })]);
28565
+ DeviceType.Camera;
28566
+ var ExtensionSourceAvailabilitySchema = discriminatedUnion("state", [object({ state: literal("ok") }), object({
28567
+ state: literal("unreachable"),
28568
+ reason: string()
28569
+ })]);
28570
+ /** One provider of slots — the D554 source-listing row. */
28571
+ var ExtensionSourceSchema = object({
28572
+ /** The routing prefix of every `slotRef` this provider serves. */
28573
+ source: string(),
28574
+ label: string(),
28575
+ /** Stamped by the dispatcher from the registry (D557). */
28576
+ addonId: string().optional(),
28577
+ availability: ExtensionSourceAvailabilitySchema
28578
+ });
28579
+ /**
28580
+ * How one picked source stands. `missing` — no such device (deleted, or an id
28581
+ * that never existed); `foreign` — a device the slot's owner cannot read from
28582
+ * (slice 2's cross-owner graft source); `unavailable` — it exists but is not a
28583
+ * valid source now (a container, which is never a pick). A source in any of
28584
+ * these states is SHOWN, never silently dropped or re-pointed.
28585
+ */
28586
+ var ExtensionSourceHealthSchema = _enum([
28587
+ "ok",
28588
+ "missing",
28589
+ "foreign",
28590
+ "unavailable"
28591
+ ]);
28592
+ var ExtensionSlotSourceSchema = object({
28593
+ deviceId: number().int(),
28594
+ /** The device's name, or null when it could not be resolved (`missing`). */
28595
+ name: string().nullable(),
28596
+ health: ExtensionSourceHealthSchema,
28597
+ detail: string().optional()
28598
+ });
28599
+ /**
28600
+ * A DIFFERENT authority that gates whether the slot's sources do anything —
28601
+ * reported read-only, named, never written through this contract (D62). The
28602
+ * virtual doorbell's sources ring only while the wrapper is bound to the
28603
+ * camera, and that binding belongs to `deviceManager.setWrapperActive`.
28604
+ * `unknown` means the gate could not be read; it is not "inactive" (D315).
28605
+ */
28606
+ var ExtensionSlotActivationSchema = object({
28607
+ state: _enum([
28608
+ "active",
28609
+ "inactive",
28610
+ "unknown"
28611
+ ]),
28612
+ authority: string(),
28613
+ detail: string().optional()
28614
+ });
28615
+ var ExtensionSlotRowSchema = discriminatedUnion("state", [object({
28616
+ state: literal("ok"),
28617
+ /** `<source>:<slotId>` — the routing key for `listCandidates` / `setSlot`. */
28618
+ slotRef: string(),
28619
+ slot: ExtensionSlotIdSchema,
28620
+ /** Names the store written (D62), e.g. `virtual-doorbell:doorbellSources`. */
28621
+ authority: string(),
28622
+ /** graft: its switch. association: null — removing every source is "off". */
28623
+ enabled: boolean().nullable(),
28624
+ /** graft: the cap registered on the host. association: null. */
28625
+ projects: string().nullable(),
28626
+ activation: ExtensionSlotActivationSchema.nullable(),
28627
+ value: ExtensionSlotValueSchema,
28628
+ sources: array(ExtensionSlotSourceSchema),
28629
+ /**
28630
+ * Devices the owner links to the host ON ITS OWN, by structure, and that
28631
+ * are therefore not in `value` (D655): a camera's device-tree children, and
28632
+ * the child a picked container stands for (D356 — a container is never a
28633
+ * pick, its children are). Read-only; the editor shows them and may offer
28634
+ * per-device options on them (the linked-devices tracked-event opt-in).
28635
+ * Absent when the owner links nothing beyond the picks, and from an owner
28636
+ * older than D655.
28637
+ */
28638
+ impliedSources: array(ExtensionSlotSourceSchema).optional()
28639
+ }), object({
28640
+ state: literal("unreachable"),
28641
+ addonId: string(),
28642
+ reason: string()
28643
+ })]);
28644
+ var ExtensionCandidatesSchema = object({ candidates: array(object({
28645
+ deviceId: number().int(),
28646
+ name: string(),
28647
+ type: string(),
28648
+ location: string().nullable(),
28649
+ /** The container a child belongs to — "Spotlight 2" alone does not say which. */
28650
+ parentName: string().nullable(),
28651
+ /** Pre-marked by the owner's suggestion rule. NEVER saved on its own (D356). */
28652
+ suggested: boolean(),
28653
+ /** Why it is suggested ("same location"), null when it is not. */
28654
+ reason: string().nullable()
28655
+ })) });
28656
+ /**
28657
+ * What a write did. `none` — applied in place. `host` / `parent` — the owner
28658
+ * reloaded the host (or, for an accessory child, its parent) because the
28659
+ * write changed what the host REGISTERS (a graft switched on or off, slice 2).
28660
+ */
28661
+ var ExtensionSetResultSchema = object({
28662
+ applied: literal(true),
28663
+ reload: _enum([
28664
+ "none",
28665
+ "host",
28666
+ "parent"
28667
+ ])
28668
+ });
28669
+ var ExtensionSlotRefInputSchema = object({
28670
+ deviceId: number().int(),
28671
+ slotRef: string().min(1)
28672
+ });
28673
+ var ExtensionSetSlotInputSchema = ExtensionSlotRefInputSchema.extend({ value: ExtensionSlotValueSchema });
28674
+ method(object({ deviceId: number().int() }), array(ExtensionSourceSchema)), method(object({ deviceId: number().int() }), array(ExtensionSlotRowSchema)), method(ExtensionSlotRefInputSchema, ExtensionCandidatesSchema), method(ExtensionSetSlotInputSchema, ExtensionSetResultSchema, {
28675
+ kind: "mutation",
28676
+ auth: "admin"
28677
+ });
28678
+ /**
27740
28679
  * Optional client-side hints sent at session creation to help the provider
27741
28680
  * pick the best native source. All fields optional — a viewer that knows
27742
28681
  * nothing still gets a sane default. (Relocated from the retired `webrtc`
@@ -30186,75 +31125,6 @@ onStatusChanged: { data: object({
30186
31125
  volatileStateFields: ["lastChangedAt"]
30187
31126
  };
30188
31127
  /**
30189
- * Doorbell button cap. Two kinds of providers coexist behind this cap
30190
- * name (same pattern as `snapshot`):
30191
- *
30192
- * - **Native** providers: registered per-device by device-driver
30193
- * addons via `ctx.registerNativeCap` — either on a
30194
- * `DeviceType.Button` accessory with `role: DeviceRole.Doorbell`,
30195
- * or directly on the camera (Reolink registers at camera level).
30196
- * Emits an `onPressed` event every time the firmware pushes a
30197
- * ring; status tracks the last press and a pressCount since start
30198
- * (diagnostic).
30199
- *
30200
- * - **Wrapper** provider: the `virtual-doorbell` system builtin
30201
- * (`@camstack/system/builtins/doorbell`). Turns ANY binary-ish
30202
- * device (contact / switch / event-emitter …) into a doorbell for
30203
- * a camera. `defaultActive: false` — the operator explicitly binds
30204
- * it per camera in the device-bindings UI, then picks the source
30205
- * device + trigger in the per-device settings.
30206
- *
30207
- * The DeviceEventPropagator re-emits `onPressed` on the camera parent
30208
- * — subscribers listening at the camera level receive ring events
30209
- * with `via[]` populated. No code on the parent needed.
30210
- */
30211
- var DoorbellStatusSchema = object({
30212
- /** Ms epoch of the last press. null = never observed since this provider started. */
30213
- lastPressedAt: number().nullable(),
30214
- /** Counter since provider start. Resets on reboot. Useful for metrics/debug. */
30215
- pressCountSinceStart: number()
30216
- });
30217
- var DoorbellPressEventSchema = object({
30218
- deviceId: number(),
30219
- timestamp: number()
30220
- });
30221
- var doorbellCapability = {
30222
- name: "doorbell",
30223
- scope: "device",
30224
- deviceNative: true,
30225
- mode: "singleton",
30226
- kind: "wrapper",
30227
- defaultActive: false,
30228
- deviceTypes: [DeviceType.Button, DeviceType.Camera],
30229
- exposesDeviceSettings: true,
30230
- methods: {},
30231
- events: {
30232
- /**
30233
- * Fires once per physical press. Reolink delivers via Baichuan
30234
- * push (`ReolinkSimpleEvent.type === 'doorbell'`). There is no
30235
- * release/duration — it's a pulse.
30236
- */
30237
- onPressed: { data: DoorbellPressEventSchema } },
30238
- status: {
30239
- schema: DoorbellStatusSchema,
30240
- kind: "push"
30241
- },
30242
- /**
30243
- * Runtime-state slice — last press timestamp + lifetime press count.
30244
- * Mirrored by the kernel and readable via
30245
- * `device.state.doorbell.value`. UIs can show "last ring 5m ago"
30246
- * without subscribing.
30247
- */
30248
- runtimeState: DoorbellStatusSchema,
30249
- /**
30250
- * Runtime-state durability: **restored** — a monotonic accumulator: the slice IS the record. `lastPressedAt` is content here, not a clock, so it is deliberately NOT volatile.
30251
- *
30252
- * See `RuntimeStateDurability`. Enforced by
30253
- * `scripts/check-runtime-state-durability.ts`.
30254
- */
30255
- durability: "restored"
30256
- };
30257
- /**
30258
31128
  * Enum-state sensor — a string value picked from a finite option set.
30259
31129
  * Drives HA `sensor` entries with `state_class: enum` (HVAC action
30260
31130
  * states, weather conditions, contact-source channels, mode strings).
@@ -39142,146 +40012,6 @@ function readDeviceStateFrom(runtimeState) {
39142
40012
  }
39143
40013
  }
39144
40014
  /**
39145
- * LA tabella "quale booleano di questo tipo di device conta come ALTO", e il
39146
- * valutatore puro del suo FRONTE.
39147
- *
39148
- * Viveva dentro il builtin virtual-doorbell
39149
- * (`@camstack/system` — `builtins/doorbell/trigger-engine.ts`) e i suoi
39150
- * predicati erano privati al modulo. Il recorder ne ha bisogno per il trigger
39151
- * `RecordingTriggers.sensorDeviceIds`: copiarla avrebbe creato la SECONDA
39152
- * tabella, che diverge alla prima cap aggiunta e il cui sintomo — "il sensore
39153
- * fa suonare il campanello ma non registra" — è esattamente D62. Quindi si
39154
- * SPOSTA qui e il doorbell la ri-esporta.
39155
- *
39156
- * ⚠ NON è `DEVICE_STATE_READERS` (`catalogs/device-state-vocabulary.ts`), e le
39157
- * due non vanno unificate: quella risponde a "qual è la PAROLA di stato per una
39158
- * regola" (e include `presence`, `cover`, `alarm-panel`), questa a "qual è il
39159
- * booleano il cui FRONTE conta". Vocabolari deliberatamente diversi.
39160
- */
39161
- /**
39162
- * Known binary / switch source caps → the boolean slice field whose
39163
- * false→true rise counts as ACTIVE. Every entry is "fire on active".
39164
- * Sensors whose "active" reading is not a plain boolean (presence's string
39165
- * state, connectivity's connected flag) are deliberately excluded — a
39166
- * reconnect is not a doorbell press, and it is not a recording either.
39167
- */
39168
- var SOURCE_CAP_ACTIVE_FIELD = {
39169
- contact: "entryOpen",
39170
- binary: "on",
39171
- switch: "on",
39172
- motion: "detected",
39173
- flood: "flooded",
39174
- gas: "detected",
39175
- smoke: "detected",
39176
- "carbon-monoxide": "detected",
39177
- vibration: "detected",
39178
- tamper: "tampered"
39179
- };
39180
- /**
39181
- * The same caps → the slice field carrying the ms-epoch timestamp of the
39182
- * last transition. Every source cap MUST appear here (guarded by a spec):
39183
- * without a transition timestamp the evaluator cannot tell a genuine rise
39184
- * from a boot-time hydration when the FIRST slice it ever sees is already
39185
- * active, and errs towards silence — swallowing the rise.
39186
- *
39187
- * These timestamps are UPSTREAM ones, not ingest ones: the Home Assistant
39188
- * provider derives them from `state.last_changed`, so they survive our own
39189
- * restarts and correctly read as "hours ago" for a state that has been
39190
- * active for hours. `motion` names its rise timestamp `lastDetectedAt`.
39191
- */
39192
- var SOURCE_CAP_CHANGED_AT_FIELD = {
39193
- contact: "lastChangedAt",
39194
- binary: "lastChangedAt",
39195
- switch: "lastChangedAt",
39196
- motion: "lastDetectedAt",
39197
- flood: "lastChangedAt",
39198
- gas: "lastChangedAt",
39199
- smoke: "lastChangedAt",
39200
- "carbon-monoxide": "lastChangedAt",
39201
- vibration: "lastChangedAt",
39202
- tamper: "lastChangedAt"
39203
- };
39204
- /** True when a cap is a recognised binary/switch source. */
39205
- function isSourceCap(capName) {
39206
- return Object.prototype.hasOwnProperty.call(SOURCE_CAP_ACTIVE_FIELD, capName);
39207
- }
39208
- /** Extract the "active" boolean a source cap's slice carries, or null when
39209
- * the cap is unknown or the field is missing / non-boolean. */
39210
- function sliceActiveValue(capName, slice) {
39211
- const field = SOURCE_CAP_ACTIVE_FIELD[capName];
39212
- if (field === void 0) return null;
39213
- const raw = slice[field];
39214
- return typeof raw === "boolean" ? raw : null;
39215
- }
39216
- /** Ms-epoch transition timestamp a source cap's slice carries, or null when
39217
- * it is absent, non-numeric or the zero "never observed" sentinel. */
39218
- function sliceChangedAt(capName, slice) {
39219
- const field = SOURCE_CAP_CHANGED_AT_FIELD[capName];
39220
- if (field === void 0) return null;
39221
- const raw = slice[field];
39222
- if (typeof raw !== "number" || !Number.isFinite(raw) || raw <= 0) return null;
39223
- return raw;
39224
- }
39225
- /**
39226
- * How recent a source's own transition timestamp must be for a FIRST
39227
- * sighting that is already active to count as a genuine rise rather than a
39228
- * hydration of long-standing state.
39229
- */
39230
- var DEFAULT_FIRST_SIGHTING_FRESHNESS_MS = 3e4;
39231
- /**
39232
- * IL fronte. Puro: nessun orologio proprio, nessuna memoria — il chiamante
39233
- * porta `prior`, `nowMs` e il proprio `startedAtMs`.
39234
- *
39235
- * Il caso della PRIMA slice già attiva è trattato esplicitamente e vale come
39236
- * fronte solo se il timestamp UPSTREAM della transizione è posteriore a
39237
- * `startedAtMs` **e** entro `firstSightingFreshnessMs`. Entrambe le metà
39238
- * servono: la sola freschezza scatterebbe su un'idratazione al boot di uno
39239
- * stato flippato pochi secondi prima del riavvio, e il solo "dopo che abbiamo
39240
- * iniziato" scatterebbe, su un processo di lunga vita, per una sorgente
39241
- * adottata oggi il cui stato è cambiato ieri. Il caso ambiguo ERRA VERSO IL
39242
- * SILENZIO e lo dichiara (`baseline-seeded-stale-active`).
39243
- */
39244
- function evaluateSensorEdge(input) {
39245
- const value = sliceActiveValue(input.capName, input.slice);
39246
- if (value === null) return {
39247
- edge: "none",
39248
- value: null,
39249
- reason: isSourceCap(input.capName) ? "non-boolean-value" : "unknown-cap"
39250
- };
39251
- if (input.prior === void 0) {
39252
- if (!value) return {
39253
- edge: "none",
39254
- value,
39255
- reason: "baseline-seeded-inactive"
39256
- };
39257
- const changedAt = sliceChangedAt(input.capName, input.slice);
39258
- const floor = Math.max(input.startedAtMs, input.nowMs - input.firstSightingFreshnessMs);
39259
- if (changedAt === null || changedAt < floor) return {
39260
- edge: "none",
39261
- value,
39262
- reason: "baseline-seeded-stale-active"
39263
- };
39264
- return {
39265
- edge: "rising",
39266
- value: true
39267
- };
39268
- }
39269
- if (input.prior === value) return {
39270
- edge: "none",
39271
- value,
39272
- reason: "no-change"
39273
- };
39274
- if (!value) return {
39275
- edge: "none",
39276
- value,
39277
- reason: "falling-edge"
39278
- };
39279
- return {
39280
- edge: "rising",
39281
- value: true
39282
- };
39283
- }
39284
- /**
39285
40015
  * Accessory device helpers — shared across drivers.
39286
40016
  *
39287
40017
  * Many vendor-specific drivers register accessory child devices on
@@ -43121,6 +43851,30 @@ Object.freeze({
43121
43851
  addonId: null,
43122
43852
  access: "create"
43123
43853
  },
43854
+ "deviceExtension.listCandidates": {
43855
+ capName: "device-extension",
43856
+ capScope: "device",
43857
+ addonId: null,
43858
+ access: "view"
43859
+ },
43860
+ "deviceExtension.listSlots": {
43861
+ capName: "device-extension",
43862
+ capScope: "device",
43863
+ addonId: null,
43864
+ access: "view"
43865
+ },
43866
+ "deviceExtension.listSources": {
43867
+ capName: "device-extension",
43868
+ capScope: "device",
43869
+ addonId: null,
43870
+ access: "view"
43871
+ },
43872
+ "deviceExtension.setSlot": {
43873
+ capName: "device-extension",
43874
+ capScope: "device",
43875
+ addonId: null,
43876
+ access: "create"
43877
+ },
43124
43878
  "deviceManager.addLocation": {
43125
43879
  capName: "device-manager",
43126
43880
  capScope: "system",
@@ -43193,12 +43947,6 @@ Object.freeze({
43193
43947
  addonId: null,
43194
43948
  access: "create"
43195
43949
  },
43196
- "deviceManager.applyDeviceSettingsPatch": {
43197
- capName: "device-manager",
43198
- capScope: "system",
43199
- addonId: null,
43200
- access: "create"
43201
- },
43202
43950
  "deviceManager.applyInitialMeta": {
43203
43951
  capName: "device-manager",
43204
43952
  capScope: "system",
@@ -43301,12 +44049,6 @@ Object.freeze({
43301
44049
  addonId: null,
43302
44050
  access: "view"
43303
44051
  },
43304
- "deviceManager.getDeviceLiveContribution": {
43305
- capName: "device-manager",
43306
- capScope: "system",
43307
- addonId: null,
43308
- access: "view"
43309
- },
43310
44052
  "deviceManager.getDeviceLiveInfoAggregate": {
43311
44053
  capName: "device-manager",
43312
44054
  capScope: "system",
@@ -43319,12 +44061,6 @@ Object.freeze({
43319
44061
  addonId: null,
43320
44062
  access: "view"
43321
44063
  },
43322
- "deviceManager.getDeviceSettingsContribution": {
43323
- capName: "device-manager",
43324
- capScope: "system",
43325
- addonId: null,
43326
- access: "view"
43327
- },
43328
44064
  "deviceManager.getDeviceStatusAggregate": {
43329
44065
  capName: "device-manager",
43330
44066
  capScope: "system",
@@ -43829,24 +44565,6 @@ Object.freeze({
43829
44565
  addonId: null,
43830
44566
  access: "view"
43831
44567
  },
43832
- "doorbell.applyDeviceSettingsPatch": {
43833
- capName: "doorbell",
43834
- capScope: "device",
43835
- addonId: null,
43836
- access: "create"
43837
- },
43838
- "doorbell.getDeviceLiveContribution": {
43839
- capName: "doorbell",
43840
- capScope: "device",
43841
- addonId: null,
43842
- access: "view"
43843
- },
43844
- "doorbell.getDeviceSettingsContribution": {
43845
- capName: "doorbell",
43846
- capScope: "device",
43847
- addonId: null,
43848
- access: "view"
43849
- },
43850
44568
  "doorbell.getStatus": {
43851
44569
  capName: "doorbell",
43852
44570
  capScope: "device",
@@ -43871,6 +44589,12 @@ Object.freeze({
43871
44589
  addonId: null,
43872
44590
  access: "view"
43873
44591
  },
44592
+ "embeddingEncoder.resetFailedModels": {
44593
+ capName: "embedding-encoder",
44594
+ capScope: "system",
44595
+ addonId: null,
44596
+ access: "delete"
44597
+ },
43874
44598
  "enumSensor.getStatus": {
43875
44599
  capName: "enum-sensor",
43876
44600
  capScope: "device",
@@ -46205,6 +46929,12 @@ Object.freeze({
46205
46929
  addonId: null,
46206
46930
  access: "view"
46207
46931
  },
46932
+ "pipelineOrchestrator.getClusterModelChoice": {
46933
+ capName: "pipeline-orchestrator",
46934
+ capScope: "system",
46935
+ addonId: null,
46936
+ access: "view"
46937
+ },
46208
46938
  "pipelineOrchestrator.getDeviceLiveContribution": {
46209
46939
  capName: "pipeline-orchestrator",
46210
46940
  capScope: "system",
@@ -49030,6 +49760,26 @@ Object.freeze({
49030
49760
  form: "single",
49031
49761
  optional: false
49032
49762
  }],
49763
+ "deviceExtension.listCandidates": [{
49764
+ name: "deviceId",
49765
+ form: "single",
49766
+ optional: false
49767
+ }],
49768
+ "deviceExtension.listSlots": [{
49769
+ name: "deviceId",
49770
+ form: "single",
49771
+ optional: false
49772
+ }],
49773
+ "deviceExtension.listSources": [{
49774
+ name: "deviceId",
49775
+ form: "single",
49776
+ optional: false
49777
+ }],
49778
+ "deviceExtension.setSlot": [{
49779
+ name: "deviceId",
49780
+ form: "single",
49781
+ optional: false
49782
+ }],
49033
49783
  "deviceManager.adoptionRelease": [{
49034
49784
  name: "camDeviceId",
49035
49785
  form: "single",
@@ -52652,169 +53402,6 @@ function readTimelapseGeneratedAt(rule, deviceId) {
52652
53402
  if (map !== void 0) return map[String(deviceId)] ?? 0;
52653
53403
  return rule.lastGeneratedAt ?? 0;
52654
53404
  }
52655
- /**
52656
- * A model choice has a SCOPE, and a scope change has a workflow.
52657
- *
52658
- * ## The two scopes
52659
- *
52660
- * Almost every pipeline step's model is a **node** question: which build runs
52661
- * fastest on THIS accelerator. Two nodes may legitimately answer differently —
52662
- * a Coral runs the tflite SSD, a Mac runs the coreml YOLO — because the answers
52663
- * are compared against nothing. They produce boxes, and a box is a box.
52664
- *
52665
- * Two steps are not like that. `face-embedding` and `clip-embedding` produce
52666
- * **vectors that land in ONE shared index** (`identity_samples`,
52667
- * `vec_object_clip`) and are ranked against each other by cosine similarity.
52668
- * Cosine similarity between two encoders is not a weak signal, it is a
52669
- * meaningless number — and nothing inside a vector can tell you it happened.
52670
- * So for those two steps the model is a **cluster** question with exactly one
52671
- * answer, stored in exactly one row.
52672
- *
52673
- * That is the same argument [D52](../../../../docs/decisions/adr-0052.md) makes
52674
- * for the crop convention (`detail-crop.ts`), one level up: the crop decides
52675
- * WHAT pixels the encoder sees, this decides WHICH encoder sees them. Both are
52676
- * cluster-wide for the same reason and neither may become per-node.
52677
- *
52678
- * ## Why the registry lives here and not in the step catalog
52679
- *
52680
- * The scope itself is declared on the step, in
52681
- * `detection-pipeline/registry/step-definitions.ts` (`StepDefinition.modelScope`)
52682
- * — that is where a new step declares what kind of choice its model is. But the
52683
- * catalog lives inside `addon-pipeline`, and three packages that must NOT
52684
- * import an addon need to know the set: the orchestrator (which renders and
52685
- * stores the row), post-analysis (which pins the row for a re-embed pass) and
52686
- * admin-ui (which mirrors it). So the set is mirrored here, and
52687
- * `scripts/check-cluster-model-scope.ts` fails the build when the two disagree.
52688
- * A hand-copied key that stops matching is exactly how a setting silently stops
52689
- * arriving while both sides still look correct.
52690
- *
52691
- * ## The defaults ARE today's behaviour
52692
- *
52693
- * {@link DEFAULT_CLUSTER_STEP_MODELS} reproduces the catalog `defaultModelId`
52694
- * of both steps. Declaring the scope therefore changes nothing on the day it
52695
- * ships: the cluster row starts out saying what every node was already doing.
52696
- * Changing it is legitimate — that is what the knob is for — but it invalidates
52697
- * the stored vectors of that surface, and must be followed by a re-embed pass
52698
- * (`face-reembed-pass.ts`, `embedding-rebuild.ts`).
52699
- */
52700
- /**
52701
- * The cluster-scoped steps. Mirrored from the catalog's `modelScope: 'cluster'`
52702
- * declarations and guarded by `scripts/check-cluster-model-scope.ts`.
52703
- */
52704
- var CLUSTER_MODEL_SCOPED_STEPS = [{
52705
- stepId: "face-embedding",
52706
- label: "Face recognition model",
52707
- defaultModelId: "arcface-r100",
52708
- indexName: "the enrolled face gallery",
52709
- options: [
52710
- {
52711
- id: "arcface-r100",
52712
- label: "ArcFace (ResNet34)"
52713
- },
52714
- {
52715
- id: "auraface-r100",
52716
- label: "AuraFace R100"
52717
- },
52718
- {
52719
- id: "inception-resnet-v1",
52720
- label: "Inception ResNet V1"
52721
- }
52722
- ]
52723
- }, {
52724
- stepId: "clip-embedding",
52725
- label: "Semantic search model",
52726
- defaultModelId: "mobileclip-s1",
52727
- indexName: "the object semantic-search index",
52728
- options: [{
52729
- id: "mobileclip-s1",
52730
- label: "MobileCLIP S1"
52731
- }, {
52732
- id: "mobileclip-s2",
52733
- label: "MobileCLIP S2"
52734
- }]
52735
- }];
52736
- /**
52737
- * The settings key holding one step's cluster model choice.
52738
- *
52739
- * Step-qualified so the keys stay unique across the addon's whole schema, which
52740
- * is what lets {@link pickClusterStepModels} walk every section instead of
52741
- * trusting the section id.
52742
- */
52743
- function clusterModelSettingKey(stepId) {
52744
- return `clusterModel:${stepId}`;
52745
- }
52746
- /** The cluster row when nobody has configured one — today's catalog defaults. */
52747
- var DEFAULT_CLUSTER_STEP_MODELS = Object.freeze(Object.fromEntries(CLUSTER_MODEL_SCOPED_STEPS.map((s) => [s.stepId, s.defaultModelId])));
52748
- /** A stored choice is a non-empty model id, or it is not a choice. */
52749
- var ChosenModelIdSchema = string().min(1);
52750
- /**
52751
- * Narrow a FLAT settings record to the cluster row.
52752
- *
52753
- * Per-FIELD fallback, deliberately (same rule as `readDetailCropConvention`): a
52754
- * junk face model must not also discard a valid clip model. An absent, empty or
52755
- * non-string value resolves to the step's catalog default — the historical
52756
- * behaviour — never to a blank id, because a blank id downstream becomes
52757
- * "substitute the format default", which is precisely the substitution this
52758
- * scope exists to forbid.
52759
- */
52760
- function readClusterStepModels(config) {
52761
- const out = {};
52762
- for (const step of CLUSTER_MODEL_SCOPED_STEPS) {
52763
- const parsed = ChosenModelIdSchema.safeParse(config[clusterModelSettingKey(step.stepId)]);
52764
- out[step.stepId] = parsed.success ? parsed.data : step.defaultModelId;
52765
- }
52766
- return out;
52767
- }
52768
- function isHydratedField$2(entry) {
52769
- return typeof entry === "object" && entry !== null && "key" in entry;
52770
- }
52771
- /**
52772
- * Extract the cluster row from an `addon-settings.getGlobalSettings` payload.
52773
- *
52774
- * Walks EVERY section rather than looking inside {@link CLUSTER_MODEL_SECTION_ID}
52775
- * alone: the keys are unique across the addon's schema, and a section rename
52776
- * must not silently revert the whole cluster to the defaults. A `null` payload
52777
- * (addon mid-boot) is the defaults.
52778
- */
52779
- function pickClusterStepModels(view) {
52780
- if (view === null) return DEFAULT_CLUSTER_STEP_MODELS;
52781
- const flat = {};
52782
- const wanted = new Set(CLUSTER_MODEL_SCOPED_STEPS.map((s) => clusterModelSettingKey(s.stepId)));
52783
- for (const section of view.sections) for (const entry of section.fields) {
52784
- if (!isHydratedField$2(entry) || typeof entry.key !== "string") continue;
52785
- if (wanted.has(entry.key)) flat[entry.key] = entry.value;
52786
- }
52787
- return readClusterStepModels(flat);
52788
- }
52789
- var CLUSTER_STEP_SETTING_FIELDS = [{
52790
- stepId: "face-embedding",
52791
- key: "minLandmarkFaceSize",
52792
- label: "Min face size for recognition (detection px)",
52793
- description: "Refuse to embed a face smaller than this IN THE DETECTION FRAME. Applies to every node — the enrolled gallery is one index, and two admission floors would fill it from two policies. 0 disables the gate.",
52794
- type: "slider",
52795
- min: 0,
52796
- max: 64,
52797
- step: 2,
52798
- default: 24
52799
- }];
52800
- function clusterStepSettingKey(stepId, fieldKey) {
52801
- return `clusterStepSetting:${stepId}:${fieldKey}`;
52802
- }
52803
- var ClusterSettingNumberSchema = number().finite();
52804
- function readClusterStepSettings(config) {
52805
- const out = {};
52806
- for (const field of CLUSTER_STEP_SETTING_FIELDS) {
52807
- const parsed = ClusterSettingNumberSchema.safeParse(config[clusterStepSettingKey(field.stepId, field.key)]);
52808
- const value = parsed.success ? parsed.data : field.default;
52809
- const existing = out[field.stepId] ?? {};
52810
- out[field.stepId] = {
52811
- ...existing,
52812
- [field.key]: value
52813
- };
52814
- }
52815
- return out;
52816
- }
52817
- readClusterStepSettings({});
52818
53405
  object({
52819
53406
  /**
52820
53407
  * Fraction of the box's own size added on EACH side before cutting.
@@ -53356,6 +53943,397 @@ function vectorDimFromBase64(encoded) {
53356
53943
  return Math.floor(Buffer.from(encoded, "base64").byteLength / 4);
53357
53944
  }
53358
53945
  //#endregion
53946
+ //#region src/pipeline-analytics/cluster-model-pin.ts
53947
+ /**
53948
+ * Where a re-embed pass gets the model it pins.
53949
+ *
53950
+ * ## Why not `embeddingEncoder.getInfo`
53951
+ *
53952
+ * That is what the CLIP rebuild used, and it answers a subtly different
53953
+ * question: "which model is the encoder addon currently holding", not "which
53954
+ * model has the operator chosen for the cluster". The two agree until they do
53955
+ * not — an encoder mid-reload, a node that never picked up a change — and when
53956
+ * they disagree the pass writes a whole index in the wrong space with a status
53957
+ * line that looks fine. Since `face-embedding` and `clip-embedding` declare
53958
+ * `modelScope: 'cluster'`, there is now exactly one authority for each, and it
53959
+ * is a stored row rather than a live process's opinion.
53960
+ *
53961
+ * ## Why the read is not cached here
53962
+ *
53963
+ * A pass reads it ONCE, at the start, and pins that value for its whole run
53964
+ * (D54). A cache would only matter for a caller that re-read it mid-pass, which
53965
+ * is precisely the thing the pin exists to prevent — so there is nothing to
53966
+ * cache and the absence is deliberate.
53967
+ *
53968
+ * ## Why a failed read refuses instead of defaulting
53969
+ *
53970
+ * A pass that cannot name its model must not run. The previous CLIP path's
53971
+ * `?? 'unknown'` is the shipped version of the alternative: rows stamped with an
53972
+ * id nothing ran, in an index whose same-model gate then has nothing to reason
53973
+ * about.
53974
+ */
53975
+ /** The addon whose GLOBAL settings hold the cluster row. */
53976
+ var CLUSTER_MODEL_OWNER_ADDON_ID = "pipeline-orchestrator";
53977
+ /** The step ids this module can pin — the same two the catalog declares. */
53978
+ var FACE_EMBEDDING_STEP_ID = "face-embedding";
53979
+ var CLIP_EMBEDDING_STEP_ID = "clip-embedding";
53980
+ /**
53981
+ * The cluster row, or `null` when it could not be read.
53982
+ *
53983
+ * `null` and not "the defaults": a caller that cannot distinguish "the operator
53984
+ * chose arcface" from "I could not ask" will run a pass on a guess. The one
53985
+ * production caller turns `null` into a refusal to start.
53986
+ */
53987
+ async function readClusterModelRow(api, logger) {
53988
+ try {
53989
+ return pickClusterStepModels(await api.addonSettings.getGlobalSettings.query({ addonId: CLUSTER_MODEL_OWNER_ADDON_ID }));
53990
+ } catch (err) {
53991
+ logger.warn("cluster model row unreadable — a re-embed pass must not guess which encoder the operator chose", { meta: {
53992
+ owner: CLUSTER_MODEL_OWNER_ADDON_ID,
53993
+ error: err instanceof Error ? err.message : String(err)
53994
+ } });
53995
+ return null;
53996
+ }
53997
+ }
53998
+ /**
53999
+ * Pin one cluster-scoped step's model for a whole pass.
54000
+ *
54001
+ * Returns `null` on an unreadable row OR an unknown step id — both mean the
54002
+ * caller must not start, and folding them together is safe because the caller's
54003
+ * move is identical: refuse, loudly.
54004
+ */
54005
+ async function resolveClusterModelPin(api, stepId, logger) {
54006
+ if (!CLUSTER_MODEL_SCOPED_STEPS.some((s) => s.stepId === stepId)) {
54007
+ logger.warn("cluster model pin requested for a step that is not cluster-scoped", { meta: {
54008
+ stepId,
54009
+ clusterScoped: CLUSTER_MODEL_SCOPED_STEPS.map((s) => s.stepId)
54010
+ } });
54011
+ return null;
54012
+ }
54013
+ const row = await readClusterModelRow(api, logger);
54014
+ if (row === null) return null;
54015
+ const modelId = row[stepId];
54016
+ return modelId !== void 0 && modelId !== "" ? modelId : null;
54017
+ }
54018
+ /**
54019
+ * The error texts a cap call carries when the provider or the router has no
54020
+ * such method: the kernel's `Capability "…" has no method "…"`, tRPC's
54021
+ * `No procedure found on path`, and the forked-child hop's
54022
+ * `method '…' not found on provider '…'` (child-cap-dispatch.ts). NOT `is not a function`: that is any
54023
+ * `TypeError` thrown INSIDE the owner while it answers, and reading it as
54024
+ * "the owner predates the method" would file a bug in the owner under a
54025
+ * rolling-release reason nobody investigates.
54026
+ */
54027
+ var METHOD_UNAVAILABLE_FINGERPRINTS = [
54028
+ /has no method/i,
54029
+ /no procedure found/i,
54030
+ /method not found/i,
54031
+ /method '[^']*' not found on provider/i
54032
+ ];
54033
+ /**
54034
+ * The pin read for a pass that REWRITES an index (D651 fix rounds 1–3).
54035
+ *
54036
+ * Asks the OWNER. The orchestrator owns `clusterModel:*` and answers from a
54037
+ * three-way read of its own store, once its boot has settled
54038
+ * (`pipelineOrchestrator.getClusterModelChoice`). Never the hydrated view,
54039
+ * which answers `value ?? default`, and never the owner's private store
54040
+ * layout. Silent on purpose: the callers log state CHANGES.
54041
+ */
54042
+ async function readClusterModelPinStrict(api, stepId) {
54043
+ const method = api.pipelineOrchestrator?.getClusterModelChoice;
54044
+ if (method === void 0) return {
54045
+ kind: "unknown",
54046
+ reason: "method-unavailable"
54047
+ };
54048
+ let raw;
54049
+ try {
54050
+ raw = await method.query({ stepId });
54051
+ } catch (err) {
54052
+ const error = err instanceof Error ? err.message : String(err);
54053
+ return METHOD_UNAVAILABLE_FINGERPRINTS.some((re) => re.test(error)) ? {
54054
+ kind: "unknown",
54055
+ reason: "method-unavailable",
54056
+ error
54057
+ } : {
54058
+ kind: "unknown",
54059
+ reason: "read-failed",
54060
+ error
54061
+ };
54062
+ }
54063
+ if (raw === void 0) return {
54064
+ kind: "unknown",
54065
+ reason: "method-unavailable"
54066
+ };
54067
+ const parsed = ClusterModelChoiceSchema.safeParse(raw);
54068
+ if (!parsed.success) return {
54069
+ kind: "unknown",
54070
+ reason: "read-failed",
54071
+ error: "unparseable owner answer"
54072
+ };
54073
+ const choice = parsed.data;
54074
+ if (choice.kind === "stored") return {
54075
+ kind: "known",
54076
+ modelId: choice.modelId
54077
+ };
54078
+ if (choice.kind === "absent") return {
54079
+ kind: "not-stored",
54080
+ defaultModelId: choice.defaultModelId
54081
+ };
54082
+ return choice.error !== void 0 ? {
54083
+ kind: "unknown",
54084
+ reason: choice.reason,
54085
+ error: choice.error
54086
+ } : {
54087
+ kind: "unknown",
54088
+ reason: choice.reason
54089
+ };
54090
+ }
54091
+ //#endregion
54092
+ //#region src/embedding-encoder/catalogs/embedding-models.ts
54093
+ var HF_REPO = "camstack/camstack-models";
54094
+ var hf = (path) => hfModelUrl(HF_REPO, path);
54095
+ /**
54096
+ * The text tower's tokenizer, in HF `tokenizers` format, hosted next to every
54097
+ * text-encoder onnx (`.../onnx/tokenizer.json`) and fetched as a sibling file so
54098
+ * it lands beside the model. Each model folder hosts ITS OWN (MobileCLIP: the
54099
+ * CLIP BPE, vocab 49408; SigLIP2: Gemma SentencePiece, 256k, lower-casing).
54100
+ */
54101
+ var TOKENIZER_FILE = "tokenizer.json";
54102
+ /** SigLIP2's tokenizer — a DIFFERENT file name on purpose: see `ClipModelMeta.tokenizerFile`. */
54103
+ var SIGLIP2_TOKENIZER_FILE = "camstack-siglip2-b16-224-tokenizer.json";
54104
+ var ovFormat = (url, sizeMB) => {
54105
+ const base = url.split("/").pop() ?? "";
54106
+ const files = base.endsWith(".xml") ? [base.replace(/\.xml$/, ".bin")] : void 0;
54107
+ return {
54108
+ url,
54109
+ sizeMB,
54110
+ runtimes: ["python"],
54111
+ ...files ? { files } : {}
54112
+ };
54113
+ };
54114
+ /**
54115
+ * Files inside an .mlpackage directory bundle.
54116
+ * Must be fetched alongside the package root when isDirectory is true.
54117
+ */
54118
+ var MLPACKAGE_FILES = [
54119
+ "Manifest.json",
54120
+ "Data/com.apple.CoreML/model.mlmodel",
54121
+ "Data/com.apple.CoreML/weights/weight.bin"
54122
+ ];
54123
+ /**
54124
+ * The MobileCLIP feature-space contract (D649 — see `clip-model.ts` in
54125
+ * `@camstack/types`). S1 and S2 share the historical 512-d `object-clip` index,
54126
+ * separated by each row's `modelId`; the CLIP BPE window is 77 tokens padded
54127
+ * with 0; 0.2 is the floor the search always shipped with, measured to keep 96%
54128
+ * of matched COCO caption-image pairs on S1.
54129
+ */
54130
+ var mobileclipMeta = (textModelId) => ({
54131
+ textModelId,
54132
+ embeddingDim: 512,
54133
+ vectorIndex: "object-clip",
54134
+ tokenizerFile: TOKENIZER_FILE,
54135
+ contextLength: 77,
54136
+ padId: 0,
54137
+ searchMinScore: .2
54138
+ });
54139
+ /**
54140
+ * SigLIP2 B/16-224 (D649). 768-d, so its OWN index; a 64-token Gemma
54141
+ * SentencePiece window padded with 0 (the hosted `tokenizer.json` lower-cases,
54142
+ * see `scripts/build-siglip2-model.py`). The floor is SIGLIP2_SEARCH_MIN_SCORE.
54143
+ */
54144
+ var SIGLIP2_META = {
54145
+ textModelId: "siglip2-b16-224-text",
54146
+ embeddingDim: 768,
54147
+ vectorIndex: "object-clip-siglip2-b16-224",
54148
+ tokenizerFile: SIGLIP2_TOKENIZER_FILE,
54149
+ contextLength: 64,
54150
+ padId: 0,
54151
+ searchMinScore: .1
54152
+ };
54153
+ /**
54154
+ * NO onnx vision builds, deliberately (2026-08-21). The int8 ONNX vision
54155
+ * exports were measured misaligned with the text encoders (matched image↔text
54156
+ * cosine ≈ 0.01 vs ≈ 0.22 for the fp16 openvino/coreml builds) — see the
54157
+ * catalog note in `addon-pipeline/.../model-catalogs.ts`. The image-encode leg
54158
+ * that consumed them here (`embeddingEncoder.encode` → PythonRawTensorEngine)
54159
+ * is retired with them: its only caller discarded the vector, and its
54160
+ * `preprocessForClip` applied OpenAI mean/std that MobileCLIP never used.
54161
+ * S0 was retired the same day (measured worst of the family on fleet crops).
54162
+ */
54163
+ var CLIP_IMAGE_MODELS = [
54164
+ {
54165
+ id: "mobileclip-s1",
54166
+ name: "MobileCLIP S1",
54167
+ description: "Apple MobileCLIP S1 — balanced vision encoder, 512-dim, 256×256 (fp16 OpenVINO/CoreML)",
54168
+ inputSize: {
54169
+ width: 256,
54170
+ height: 256
54171
+ },
54172
+ labels: [],
54173
+ inputNormalization: "none",
54174
+ clip: mobileclipMeta("mobileclip-s1-text"),
54175
+ formats: {
54176
+ openvino: ovFormat(hf("clip/mobileclip-s1/openvino/camstack-mobileclip-s1-vision.xml"), 55),
54177
+ coreml: {
54178
+ url: hf("clip/mobileclip-s1/coreml/camstack-mobileclip-s1-vision.mlpackage"),
54179
+ sizeMB: 65,
54180
+ isDirectory: true,
54181
+ files: [...MLPACKAGE_FILES],
54182
+ runtimes: ["python"]
54183
+ }
54184
+ }
54185
+ },
54186
+ {
54187
+ id: "mobileclip-s2",
54188
+ name: "MobileCLIP S2",
54189
+ description: "Apple MobileCLIP S2 — high-accuracy vision encoder, 512-dim, 256×256 (fp16 OpenVINO/CoreML)",
54190
+ inputSize: {
54191
+ width: 256,
54192
+ height: 256
54193
+ },
54194
+ labels: [],
54195
+ inputNormalization: "none",
54196
+ clip: mobileclipMeta("mobileclip-s2-text"),
54197
+ formats: {
54198
+ openvino: ovFormat(hf("clip/mobileclip-s2/openvino/camstack-mobileclip-s2-vision.xml"), 90),
54199
+ coreml: {
54200
+ url: hf("clip/mobileclip-s2/coreml/camstack-mobileclip-s2-vision.mlpackage"),
54201
+ sizeMB: 110,
54202
+ isDirectory: true,
54203
+ files: [...MLPACKAGE_FILES],
54204
+ runtimes: ["python"]
54205
+ }
54206
+ }
54207
+ },
54208
+ {
54209
+ id: "siglip2-b16-224",
54210
+ name: "SigLIP2 B/16",
54211
+ description: "Google SigLIP2 base, patch 16, 224×224 — Apache-2.0 vision encoder, 768-dim (fp16 OpenVINO/CoreML)",
54212
+ inputSize: {
54213
+ width: 224,
54214
+ height: 224
54215
+ },
54216
+ labels: [],
54217
+ inputNormalization: "none",
54218
+ license: "Apache-2.0",
54219
+ clip: SIGLIP2_META,
54220
+ formats: {
54221
+ openvino: ovFormat(hf("clip/siglip2/openvino/camstack-siglip2-b16-224-vision.xml"), 186),
54222
+ coreml: {
54223
+ url: hf("clip/siglip2/coreml/camstack-siglip2-b16-224-vision.mlpackage"),
54224
+ sizeMB: 185,
54225
+ isDirectory: true,
54226
+ files: [...MLPACKAGE_FILES],
54227
+ runtimes: ["python"]
54228
+ }
54229
+ }
54230
+ }
54231
+ ];
54232
+ /**
54233
+ * The int8 TEXT onnx encoders are healthy — unlike the retired int8 vision
54234
+ * exports. Verified 2026-08-21: the live search path (fp16 openvino vision
54235
+ * vectors ⋅ int8 onnx text queries) ranks correctly on the real index, and the
54236
+ * local cross-check aligns them with the fp16 vision space (cos ≈ 0.22 on
54237
+ * matched pairs).
54238
+ */
54239
+ var CLIP_TEXT_MODELS = [
54240
+ {
54241
+ id: "mobileclip-s1-text",
54242
+ name: "MobileCLIP S1 Text Encoder",
54243
+ description: "Text encoder for MobileCLIP S1, 512-dim, int8 quantized (61 MB)",
54244
+ inputSize: {
54245
+ width: 0,
54246
+ height: 0
54247
+ },
54248
+ labels: [],
54249
+ formats: {
54250
+ onnx: {
54251
+ url: hf("clip/mobileclip-s1/onnx/camstack-mobileclip-s1-text.onnx"),
54252
+ sizeMB: 61,
54253
+ files: [TOKENIZER_FILE]
54254
+ },
54255
+ openvino: ovFormat(hf("clip/mobileclip-s1/openvino/camstack-mobileclip-s1-text.xml"), 121)
54256
+ }
54257
+ },
54258
+ {
54259
+ id: "mobileclip-s2-text",
54260
+ name: "MobileCLIP S2 Text Encoder",
54261
+ description: "Text encoder for MobileCLIP S2, 512-dim, int8 quantized (61 MB)",
54262
+ inputSize: {
54263
+ width: 0,
54264
+ height: 0
54265
+ },
54266
+ labels: [],
54267
+ formats: {
54268
+ onnx: {
54269
+ url: hf("clip/mobileclip-s2/onnx/camstack-mobileclip-s2-text.onnx"),
54270
+ sizeMB: 61,
54271
+ files: [TOKENIZER_FILE]
54272
+ },
54273
+ openvino: ovFormat(hf("clip/mobileclip-s2/openvino/camstack-mobileclip-s2-text.xml"), 121)
54274
+ }
54275
+ },
54276
+ {
54277
+ id: "siglip2-b16-224-text",
54278
+ name: "SigLIP2 B/16 Text Encoder",
54279
+ description: "Text encoder for SigLIP2 B/16, 768-dim, fp16 (565 MB)",
54280
+ inputSize: {
54281
+ width: 0,
54282
+ height: 0
54283
+ },
54284
+ labels: [],
54285
+ license: "Apache-2.0",
54286
+ formats: {
54287
+ onnx: {
54288
+ url: hf("clip/siglip2/onnx/camstack-siglip2-b16-224-text.onnx"),
54289
+ sizeMB: 565,
54290
+ files: [SIGLIP2_TOKENIZER_FILE]
54291
+ },
54292
+ openvino: ovFormat(hf("clip/siglip2/openvino/camstack-siglip2-b16-224-text.xml"), 565)
54293
+ }
54294
+ }
54295
+ ];
54296
+ //#endregion
54297
+ //#region src/shared/clip/clip-model-registry.ts
54298
+ /** The model in force when nobody has chosen — the cluster row's default. */
54299
+ var DEFAULT_CLIP_MODEL = "mobileclip-s1";
54300
+ /**
54301
+ * Build a registry from catalog entries. Throws when two models share an index
54302
+ * at different dimensions: that is a catalog defect, and the vector store would
54303
+ * refuse the second model's writes one at a time, forever, at runtime.
54304
+ */
54305
+ function buildClipModelRegistry(entries) {
54306
+ const models = /* @__PURE__ */ new Map();
54307
+ const spaces = /* @__PURE__ */ new Map();
54308
+ for (const entry of entries) {
54309
+ const meta = entry.clip;
54310
+ if (meta === void 0) continue;
54311
+ models.set(entry.id, {
54312
+ modelId: entry.id,
54313
+ inputSize: entry.inputSize.width,
54314
+ meta
54315
+ });
54316
+ const existing = spaces.get(meta.vectorIndex);
54317
+ if (existing !== void 0 && existing.dim !== meta.embeddingDim) throw new Error(`CLIP index "${meta.vectorIndex}" declared at ${String(existing.dim)} dims by ${existing.modelIds.join(", ")} and at ${String(meta.embeddingDim)} by ${entry.id}`);
54318
+ spaces.set(meta.vectorIndex, {
54319
+ index: meta.vectorIndex,
54320
+ dim: meta.embeddingDim,
54321
+ modelIds: [...existing?.modelIds ?? [], entry.id]
54322
+ });
54323
+ }
54324
+ const all = [...spaces.values()];
54325
+ return {
54326
+ resolve: (modelId) => models.get(modelId) ?? null,
54327
+ spaceFor: (modelId) => {
54328
+ const model = models.get(modelId);
54329
+ return model === void 0 ? null : spaces.get(model.meta.vectorIndex) ?? null;
54330
+ },
54331
+ spaces: () => all
54332
+ };
54333
+ }
54334
+ /** The built-in catalog's registry. */
54335
+ var BUILTIN_CLIP_MODELS = buildClipModelRegistry(CLIP_IMAGE_MODELS);
54336
+ //#endregion
53359
54337
  Object.defineProperty(exports, "AUDIO_MACRO_LABELS", {
53360
54338
  enumerable: true,
53361
54339
  get: function() {
@@ -53374,6 +54352,12 @@ Object.defineProperty(exports, "ArchivedDebugNoteSchema", {
53374
54352
  return ArchivedDebugNoteSchema;
53375
54353
  }
53376
54354
  });
54355
+ Object.defineProperty(exports, "BUILTIN_CLIP_MODELS", {
54356
+ enumerable: true,
54357
+ get: function() {
54358
+ return BUILTIN_CLIP_MODELS;
54359
+ }
54360
+ });
53377
54361
  Object.defineProperty(exports, "BaseAddon", {
53378
54362
  enumerable: true,
53379
54363
  get: function() {
@@ -53392,10 +54376,22 @@ Object.defineProperty(exports, "BirthDecisionRecordSchema", {
53392
54376
  return BirthDecisionRecordSchema;
53393
54377
  }
53394
54378
  });
53395
- Object.defineProperty(exports, "CLUSTER_MODEL_SCOPED_STEPS", {
54379
+ Object.defineProperty(exports, "CLIP_EMBEDDING_STEP_ID", {
54380
+ enumerable: true,
54381
+ get: function() {
54382
+ return CLIP_EMBEDDING_STEP_ID;
54383
+ }
54384
+ });
54385
+ Object.defineProperty(exports, "CLIP_IMAGE_MODELS", {
54386
+ enumerable: true,
54387
+ get: function() {
54388
+ return CLIP_IMAGE_MODELS;
54389
+ }
54390
+ });
54391
+ Object.defineProperty(exports, "CLIP_TEXT_MODELS", {
53396
54392
  enumerable: true,
53397
54393
  get: function() {
53398
- return CLUSTER_MODEL_SCOPED_STEPS;
54394
+ return CLIP_TEXT_MODELS;
53399
54395
  }
53400
54396
  });
53401
54397
  Object.defineProperty(exports, "COCO_TO_MACRO", {
@@ -53416,6 +54412,12 @@ Object.defineProperty(exports, "CoverStateSchema", {
53416
54412
  return CoverStateSchema;
53417
54413
  }
53418
54414
  });
54415
+ Object.defineProperty(exports, "DEFAULT_CLIP_MODEL", {
54416
+ enumerable: true,
54417
+ get: function() {
54418
+ return DEFAULT_CLIP_MODEL;
54419
+ }
54420
+ });
53419
54421
  Object.defineProperty(exports, "DEFAULT_EVENT_COLOR", {
53420
54422
  enumerable: true,
53421
54423
  get: function() {
@@ -53458,6 +54460,24 @@ Object.defineProperty(exports, "DeviceType", {
53458
54460
  return DeviceType;
53459
54461
  }
53460
54462
  });
54463
+ Object.defineProperty(exports, "EMBEDDING_MODEL_FAILED", {
54464
+ enumerable: true,
54465
+ get: function() {
54466
+ return EMBEDDING_MODEL_FAILED;
54467
+ }
54468
+ });
54469
+ Object.defineProperty(exports, "EMBEDDING_REQUIREMENTS_FAILED", {
54470
+ enumerable: true,
54471
+ get: function() {
54472
+ return EMBEDDING_REQUIREMENTS_FAILED;
54473
+ }
54474
+ });
54475
+ Object.defineProperty(exports, "EMBEDDING_REQUIREMENTS_UNAVAILABLE", {
54476
+ enumerable: true,
54477
+ get: function() {
54478
+ return EMBEDDING_REQUIREMENTS_UNAVAILABLE;
54479
+ }
54480
+ });
53461
54481
  Object.defineProperty(exports, "EVENT_KIND_BY_CAP", {
53462
54482
  enumerable: true,
53463
54483
  get: function() {
@@ -53476,6 +54496,12 @@ Object.defineProperty(exports, "EventCategory", {
53476
54496
  return EventCategory;
53477
54497
  }
53478
54498
  });
54499
+ Object.defineProperty(exports, "FACE_EMBEDDING_STEP_ID", {
54500
+ enumerable: true,
54501
+ get: function() {
54502
+ return FACE_EMBEDDING_STEP_ID;
54503
+ }
54504
+ });
53479
54505
  Object.defineProperty(exports, "FIRST_LEVEL_MACRO_CLASSES", {
53480
54506
  enumerable: true,
53481
54507
  get: function() {
@@ -53728,6 +54754,12 @@ Object.defineProperty(exports, "RECORDING_SOURCE_CAMSTACK_ADDON", {
53728
54754
  return RECORDING_SOURCE_CAMSTACK_ADDON;
53729
54755
  }
53730
54756
  });
54757
+ Object.defineProperty(exports, "RebuildObjectEmbeddingsRefusalSchema", {
54758
+ enumerable: true,
54759
+ get: function() {
54760
+ return RebuildObjectEmbeddingsRefusalSchema;
54761
+ }
54762
+ });
53731
54763
  Object.defineProperty(exports, "RetrainStatusSchema", {
53732
54764
  enumerable: true,
53733
54765
  get: function() {
@@ -53926,6 +54958,30 @@ Object.defineProperty(exports, "embeddingEncoderCapability", {
53926
54958
  return embeddingEncoderCapability;
53927
54959
  }
53928
54960
  });
54961
+ Object.defineProperty(exports, "embeddingModelFailedError", {
54962
+ enumerable: true,
54963
+ get: function() {
54964
+ return embeddingModelFailedError;
54965
+ }
54966
+ });
54967
+ Object.defineProperty(exports, "embeddingRefusalOf", {
54968
+ enumerable: true,
54969
+ get: function() {
54970
+ return embeddingRefusalOf;
54971
+ }
54972
+ });
54973
+ Object.defineProperty(exports, "embeddingRequirementsFailedError", {
54974
+ enumerable: true,
54975
+ get: function() {
54976
+ return embeddingRequirementsFailedError;
54977
+ }
54978
+ });
54979
+ Object.defineProperty(exports, "embeddingRequirementsUnavailableError", {
54980
+ enumerable: true,
54981
+ get: function() {
54982
+ return embeddingRequirementsUnavailableError;
54983
+ }
54984
+ });
53929
54985
  Object.defineProperty(exports, "encodeVectorBase64", {
53930
54986
  enumerable: true,
53931
54987
  get: function() {
@@ -53962,12 +55018,6 @@ Object.defineProperty(exports, "failureContributionCapability", {
53962
55018
  return failureContributionCapability;
53963
55019
  }
53964
55020
  });
53965
- Object.defineProperty(exports, "hfModelUrl", {
53966
- enumerable: true,
53967
- get: function() {
53968
- return hfModelUrl;
53969
- }
53970
- });
53971
55021
  Object.defineProperty(exports, "hydrateSchema", {
53972
55022
  enumerable: true,
53973
55023
  get: function() {
@@ -54028,6 +55078,12 @@ Object.defineProperty(exports, "isSystemEventSummaryRule", {
54028
55078
  return isSystemEventSummaryRule;
54029
55079
  }
54030
55080
  });
55081
+ Object.defineProperty(exports, "isVectorIndexDimConflict", {
55082
+ enumerable: true,
55083
+ get: function() {
55084
+ return isVectorIndexDimConflict;
55085
+ }
55086
+ });
54031
55087
  Object.defineProperty(exports, "kebabToCamel", {
54032
55088
  enumerable: true,
54033
55089
  get: function() {
@@ -54052,6 +55108,12 @@ Object.defineProperty(exports, "nodePin", {
54052
55108
  return nodePin;
54053
55109
  }
54054
55110
  });
55111
+ Object.defineProperty(exports, "normalizeNodeId", {
55112
+ enumerable: true,
55113
+ get: function() {
55114
+ return normalizeNodeId;
55115
+ }
55116
+ });
54055
55117
  Object.defineProperty(exports, "notificationRulesCapability", {
54056
55118
  enumerable: true,
54057
55119
  get: function() {
@@ -54088,12 +55150,6 @@ Object.defineProperty(exports, "partialRecord", {
54088
55150
  return partialRecord;
54089
55151
  }
54090
55152
  });
54091
- Object.defineProperty(exports, "pickClusterStepModels", {
54092
- enumerable: true,
54093
- get: function() {
54094
- return pickClusterStepModels;
54095
- }
54096
- });
54097
55153
  Object.defineProperty(exports, "pipelineAnalyticsCapability", {
54098
55154
  enumerable: true,
54099
55155
  get: function() {
@@ -54106,6 +55162,12 @@ Object.defineProperty(exports, "plateGalleryCapability", {
54106
55162
  return plateGalleryCapability;
54107
55163
  }
54108
55164
  });
55165
+ Object.defineProperty(exports, "readClusterModelPinStrict", {
55166
+ enumerable: true,
55167
+ get: function() {
55168
+ return readClusterModelPinStrict;
55169
+ }
55170
+ });
54109
55171
  Object.defineProperty(exports, "readDeviceStateFrom", {
54110
55172
  enumerable: true,
54111
55173
  get: function() {
@@ -54124,6 +55186,18 @@ Object.defineProperty(exports, "record", {
54124
55186
  return record;
54125
55187
  }
54126
55188
  });
55189
+ Object.defineProperty(exports, "resolveClipSearchMinScore", {
55190
+ enumerable: true,
55191
+ get: function() {
55192
+ return resolveClipSearchMinScore;
55193
+ }
55194
+ });
55195
+ Object.defineProperty(exports, "resolveClusterModelPin", {
55196
+ enumerable: true,
55197
+ get: function() {
55198
+ return resolveClusterModelPin;
55199
+ }
55200
+ });
54127
55201
  Object.defineProperty(exports, "resolveLocationMode", {
54128
55202
  enumerable: true,
54129
55203
  get: function() {