@camstack/addon-post-analysis 1.2.285 → 1.2.286

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-ITESpHou.js → clip-model-registry-CY0FGcpQ.js} +1483 -403
  3. package/dist/{dist-D2tXUMfE.mjs → clip-model-registry-D4mC2M7F.mjs} +1374 -390
  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-CkfvSztj.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-NKbCrEkH.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-BAYoLHsN.mjs +26 -0
  10. package/dist/pipeline-analytics/{hostInit-B6m75Rnz.mjs → hostInit-CelYj4QN.mjs} +2 -2
  11. package/dist/pipeline-analytics/index.js +5863 -5053
  12. package/dist/pipeline-analytics/index.mjs +4510 -3700
  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
@@ -5360,7 +5360,7 @@ var ZodIssueCode = {
5360
5360
  var ZodFirstPartyTypeKind;
5361
5361
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
5362
5362
  //#endregion
5363
- //#region ../types/dist/sleep-BaRu0bS5.mjs
5363
+ //#region ../types/dist/sleep-BXv0ZcRa.mjs
5364
5364
  /**
5365
5365
  * The audio chunk plane's byte format, and the ONE expansion from a coded
5366
5366
  * window to float samples (D455).
@@ -6145,6 +6145,40 @@ var BaseAddon = class {
6145
6145
  const node = normalizeNodeId(nodeId ?? this._ctx?.kernel?.localNodeId);
6146
6146
  return keys.size > 0 ? projectStore(raw, keys, node) : raw;
6147
6147
  }
6148
+ /**
6149
+ * Whether ONE global key of this addon's store was written, read three-way
6150
+ * (D651). For a question a hydrated view cannot answer: `getGlobalSettings`
6151
+ * reports `value ?? default`, so "the operator chose the default" and "nobody
6152
+ * chose" look the same, and a failed read looks like both. A `perNode` key is
6153
+ * not supported here: its stored name is scoped.
6154
+ */
6155
+ async readStoredGlobalKey(key) {
6156
+ const read = this._ctx?.settings?.readAddonStoreResult;
6157
+ if (read === void 0) return {
6158
+ kind: "unreadable",
6159
+ reason: "three-way-read-unavailable"
6160
+ };
6161
+ let result;
6162
+ try {
6163
+ result = await read.call(this._ctx?.settings);
6164
+ } catch (err) {
6165
+ return {
6166
+ kind: "unreadable",
6167
+ reason: "store-read-failed",
6168
+ error: err instanceof Error ? err.message : String(err)
6169
+ };
6170
+ }
6171
+ if (result.kind === "failed") return {
6172
+ kind: "unreadable",
6173
+ reason: "store-read-failed",
6174
+ error: result.error
6175
+ };
6176
+ if (result.kind === "missing" || !Object.prototype.hasOwnProperty.call(result.value, key)) return { kind: "absent" };
6177
+ return {
6178
+ kind: "present",
6179
+ value: result.value[key]
6180
+ };
6181
+ }
6148
6182
  async updateGlobalSettings(patch, nodeId) {
6149
6183
  const keys = this.perNodeKeys();
6150
6184
  const localNode = normalizeNodeId(this._ctx?.kernel?.localNodeId);
@@ -7440,7 +7474,7 @@ method(object({ deviceId: number() }), array(StreamSourceEntrySchema)), method(o
7440
7474
  * can answer "may a rule actuate this?" without importing the schema barrel
7441
7475
  * (~144MB RSS per runner, D28).
7442
7476
  *
7443
- * Coverage: 87 device-scoped capabilities.
7477
+ * Coverage: 88 device-scoped capabilities.
7444
7478
  */
7445
7479
  var DEVICE_SCOPED_CAPS = new Set([
7446
7480
  "accessories",
@@ -7470,6 +7504,7 @@ var DEVICE_SCOPED_CAPS = new Set([
7470
7504
  "detection-pipeline",
7471
7505
  "device-admin-link",
7472
7506
  "device-discovery",
7507
+ "device-extension",
7473
7508
  "device-ops",
7474
7509
  "device-status",
7475
7510
  "doorbell",
@@ -9996,6 +10031,60 @@ var FailureCounters = class {
9996
10031
  this.counters.clear();
9997
10032
  }
9998
10033
  };
10034
+ var ClipModelMetaSchema = object({
10035
+ /** The paired text encoder's catalog id (the embedding-encoder's text catalog). */
10036
+ textModelId: string().min(1),
10037
+ /** Output dimension of BOTH towers. A vector of any other length is refused. */
10038
+ embeddingDim: number().int().positive(),
10039
+ /**
10040
+ * The `vector-store` index this model's vectors live in. ONE feature space
10041
+ * per index: two models share an index only when their vectors are ranked
10042
+ * against each other, which for CLIP means never across families. MobileCLIP
10043
+ * S1 and S2 share `object-clip` for history (separated by the row's
10044
+ * `modelId`); any other model gets its own.
10045
+ */
10046
+ vectorIndex: string().regex(/^object-clip(-[a-z0-9][a-z0-9-]*)?$/),
10047
+ /**
10048
+ * The text encoder's tokenizer, a declared SIBLING file of its onnx. The name
10049
+ * must be unique per tokenizer: every model's siblings land in ONE flat
10050
+ * models directory, so two different tokenizers under the same name would
10051
+ * silently overwrite each other (whichever model downloaded last wins, and
10052
+ * the other one tokenises with the wrong vocabulary).
10053
+ */
10054
+ tokenizerFile: string().min(1),
10055
+ /** Token window the text graph takes (SigLIP2: 64; CLIP BPE: 77). */
10056
+ contextLength: number().int().positive(),
10057
+ /** Id the tokenizer pads with. */
10058
+ padId: number().int().nonnegative(),
10059
+ /**
10060
+ * The search cosine floor at `strictness: 'loose'` — calibrated per model,
10061
+ * because cosine bands are a property of the model: 0.2 keeps 96% of matched
10062
+ * COCO caption-image pairs on MobileCLIP S1 and 2.7% on SigLIP2.
10063
+ */
10064
+ searchMinScore: number().min(0).max(1)
10065
+ });
10066
+ var ClipSearchStrictnessSchema = _enum([
10067
+ "loose",
10068
+ "balanced",
10069
+ "strict"
10070
+ ]);
10071
+ var CLIP_STRICTNESS_FACTOR = {
10072
+ loose: 1,
10073
+ balanced: 1.25,
10074
+ strict: 1.5
10075
+ };
10076
+ /**
10077
+ * The cosine floor a search runs with.
10078
+ *
10079
+ * An explicit `minScore` is honoured verbatim: it is a number a caller chose,
10080
+ * and silently rescaling it would make the same URL mean different things on
10081
+ * two installs. Everything else is relative to the model.
10082
+ */
10083
+ function resolveClipSearchMinScore(meta, request) {
10084
+ if (request.minScore !== void 0) return request.minScore;
10085
+ const factor = CLIP_STRICTNESS_FACTOR[request.strictness ?? "loose"];
10086
+ return Math.min(1, Math.round(meta.searchMinScore * factor * 1e3) / 1e3);
10087
+ }
9999
10088
  var MODEL_FORMATS = [
10000
10089
  "onnx",
10001
10090
  "coreml",
@@ -10199,7 +10288,14 @@ var ModelCatalogEntrySchema = object({
10199
10288
  * applies (Frigate / COCO public catalog). Set on a custom model whose raw
10200
10289
  * labels already ARE the CamStack macros (Scrypted identity map).
10201
10290
  */
10202
- classMap: DetectionCatalogClassMapSchema.optional()
10291
+ classMap: DetectionCatalogClassMapSchema.optional(),
10292
+ /**
10293
+ * The model's CLIP feature-space contract (text encoder, dimension, vector
10294
+ * index, token window, search floor) — see `clip-model.ts`. Present ONLY on a
10295
+ * CLIP image encoder; its absence is what "not a CLIP model" means to the
10296
+ * embedding encoder and the semantic-search store (D649).
10297
+ */
10298
+ clip: ClipModelMetaSchema.optional()
10203
10299
  });
10204
10300
  var ConvertTargetSchema = discriminatedUnion("format", [object({
10205
10301
  format: literal("openvino"),
@@ -14649,6 +14745,13 @@ var LinkedDeviceSchema = object({
14649
14745
  features: array(string()),
14650
14746
  producesTrackedEvents: boolean().optional()
14651
14747
  });
14748
+ /**
14749
+ * The `linked-devices` extension slot's editable value (D648): the operator's
14750
+ * pick list, exactly what `_linkedDeviceIds` persists. Tree children are NOT
14751
+ * in it — they are always linked and are not a pick.
14752
+ */
14753
+ var LinkedDevicesSlotValueSchema = object({ deviceIds: array(number().int().positive()) });
14754
+ DeviceType.Camera;
14652
14755
  /** One camera's resolved linked set, tagged with the camera it belongs to.
14653
14756
  * The batch answer needs the tag; the single-device answer already has it
14654
14757
  * from the input, which is why `getLinkedDevices` keeps the untagged shape. */
@@ -15174,11 +15277,128 @@ var EmbeddingResultSchema = object({
15174
15277
  embedding: array(number()),
15175
15278
  inferenceMs: number()
15176
15279
  });
15280
+ /** The two CLIP towers the encoder runs; a crash budget is kept per tower. */
15281
+ var EmbeddingTowerSchema = _enum(["image", "text"]);
15282
+ /**
15283
+ * A tower in the terminal `failed` state (D649, D6): it crashed or failed to
15284
+ * load `crashes` times within `windowMs`, and is refused by name until an
15285
+ * operator `resetFailedModels` or a model change — never on a timer.
15286
+ *
15287
+ * `nodeId` is the node whose tower failed. The state lives in THAT node's
15288
+ * encoder process (in memory — a runner respawn clears it), and one node's
15289
+ * answer says nothing about another's.
15290
+ */
15291
+ var EmbeddingFailedModelSchema = object({
15292
+ modelId: string(),
15293
+ tower: EmbeddingTowerSchema,
15294
+ nodeId: string(),
15295
+ crashes: number(),
15296
+ windowMs: number(),
15297
+ sinceMs: number(),
15298
+ lastReason: string()
15299
+ });
15300
+ /**
15301
+ * A model whose REQUIREMENTS can never be met on this node (D649 round 5):
15302
+ * an id the catalog does not know, a model URL answering 404/410, a declared
15303
+ * sibling (the tokenizer) that is not there. After `attempts` failed builds
15304
+ * it is terminally `requirements-failed`, refused by name until an operator
15305
+ * `resetFailedModels` or a model change — the same exits as a crashed tower.
15306
+ */
15307
+ var EmbeddingFailedRequirementSchema = object({
15308
+ modelId: string(),
15309
+ tower: EmbeddingTowerSchema,
15310
+ nodeId: string(),
15311
+ attempts: number(),
15312
+ sinceMs: number(),
15313
+ lastReason: string()
15314
+ });
15177
15315
  var EmbeddingInfoSchema = object({
15178
15316
  modelId: string(),
15179
15317
  embeddingDim: number(),
15180
- ready: boolean()
15181
- });
15318
+ ready: boolean(),
15319
+ /**
15320
+ * The node that answered. Absent only from an encoder older than D649's
15321
+ * crash budget — whose `failedModels` is then UNKNOWN (D315), never "none".
15322
+ */
15323
+ nodeId: string().optional(),
15324
+ /**
15325
+ * Towers in `failed` on the answering node, each row naming it. `undefined`
15326
+ * means the node could not say (pre-budget encoder); a node that has the
15327
+ * budget always answers an array, empty included.
15328
+ */
15329
+ failedModels: array(EmbeddingFailedModelSchema).optional(),
15330
+ /** Models terminally `requirements-failed` on the answering node; same reading as above. */
15331
+ failedRequirements: array(EmbeddingFailedRequirementSchema).optional()
15332
+ });
15333
+ /**
15334
+ * The THREE codes an encoder refusal can carry (D649, D6). Same shape as
15335
+ * `VECTOR_INDEX_DIM_CONFLICT`: the code rides in the MESSAGE, because an
15336
+ * Error's own properties do not survive the UDS/tRPC hop and its message does,
15337
+ * and both sides go through the helpers below — the encoder builds the
15338
+ * refusal, the live detail plane classifies on it to count refusals per
15339
+ * camera instead of logging one warning per track. The bracketed token
15340
+ * carries the code, the model, the tower and the node so a consumer never
15341
+ * parses prose.
15342
+ *
15343
+ * - `EMBEDDING_MODEL_FAILED`: the tower crashed / failed to load past the crash
15344
+ * budget — terminal until `resetFailedModels` or a model change.
15345
+ * - `EMBEDDING_REQUIREMENTS_UNAVAILABLE`: files or runtime not there right now
15346
+ * (a download or Python that failed, or the cooldown after one) — the next
15347
+ * request past the cooldown tries again.
15348
+ * - `EMBEDDING_REQUIREMENTS_FAILED`: the requirements can never be met (unknown
15349
+ * id, 404/410, missing sibling) and the bounded attempts are spent —
15350
+ * terminal, same exits as a crashed tower.
15351
+ */
15352
+ var EMBEDDING_MODEL_FAILED = "embedding-model-failed";
15353
+ var EMBEDDING_REQUIREMENTS_UNAVAILABLE = "embedding-requirements-unavailable";
15354
+ var EMBEDDING_REQUIREMENTS_FAILED = "embedding-requirements-failed";
15355
+ var EmbeddingRefusalCodeSchema = _enum([
15356
+ EMBEDDING_MODEL_FAILED,
15357
+ EMBEDDING_REQUIREMENTS_UNAVAILABLE,
15358
+ EMBEDDING_REQUIREMENTS_FAILED
15359
+ ]);
15360
+ function embeddingRefusalToken(code, on) {
15361
+ return `[${code} model=${on.modelId} tower=${on.tower} node=${on.nodeId}]`;
15362
+ }
15363
+ /** The encoder's refusal for a crashed tower, carrying {@link EMBEDDING_MODEL_FAILED}. */
15364
+ function embeddingModelFailedError(row) {
15365
+ 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.`);
15366
+ }
15367
+ /** The requirements refusal for THIS request, carrying {@link EMBEDDING_REQUIREMENTS_UNAVAILABLE}. */
15368
+ function embeddingRequirementsUnavailableError(on, reason) {
15369
+ return /* @__PURE__ */ new Error(`${embeddingRefusalToken(EMBEDDING_REQUIREMENTS_UNAVAILABLE, on)} ${on.modelId} (${on.tower} tower) on ${on.nodeId}: ${reason}`);
15370
+ }
15371
+ /** The terminal requirements refusal, carrying {@link EMBEDDING_REQUIREMENTS_FAILED}. */
15372
+ function embeddingRequirementsFailedError(row) {
15373
+ 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.`);
15374
+ }
15375
+ var EMBEDDING_REFUSAL_TOKEN = new RegExp(`\\[(${EMBEDDING_MODEL_FAILED}|${EMBEDDING_REQUIREMENTS_UNAVAILABLE}|${EMBEDDING_REQUIREMENTS_FAILED}) model=([^\\s\\]]+) tower=(image|text) node=([^\\s\\]]+)\\]`);
15376
+ /** The refusal `err` (possibly re-wrapped by a transport) carries, or `null` for any other error. */
15377
+ function embeddingRefusalOf(err) {
15378
+ const message = err instanceof Error ? err.message : String(err);
15379
+ const match = EMBEDDING_REFUSAL_TOKEN.exec(message);
15380
+ if (match === null) return null;
15381
+ const code = EmbeddingRefusalCodeSchema.safeParse(match[1]);
15382
+ const tower = EmbeddingTowerSchema.safeParse(match[3]);
15383
+ if (!code.success || !tower.success || match[2] === void 0 || match[4] === void 0) return null;
15384
+ return {
15385
+ code: code.data,
15386
+ modelId: match[2],
15387
+ tower: tower.data,
15388
+ nodeId: match[4]
15389
+ };
15390
+ }
15391
+ /**
15392
+ * ONE provider per node (`placement: any-node`), addressed like every global
15393
+ * collection: the codegen injects a `{ nodeId?, addonId? }` selector on the
15394
+ * void methods and lifts a top-level `nodeId` off the object ones. A call
15395
+ * that names no node is answered by the HUB's provider — never by a merge
15396
+ * across nodes, because no global collection fans out across nodes (only the
15397
+ * providers of one node are `concatCollection`-fanned). So a fleet view of
15398
+ * `failedModels` is one `getInfo({ nodeId })` per node, and every answer
15399
+ * names the node it came from (D649 round 4); a node that cannot be asked is
15400
+ * UNKNOWN to the reader, never "no failures" (D315).
15401
+ */
15182
15402
  var embeddingEncoderCapability = {
15183
15403
  name: "embedding-encoder",
15184
15404
  scope: "system",
@@ -15197,8 +15417,30 @@ var embeddingEncoderCapability = {
15197
15417
  width: number(),
15198
15418
  height: number()
15199
15419
  }), EmbeddingResultSchema, { auth: "admin" }),
15200
- encodeText: method(object({ text: string() }), EmbeddingResultSchema, { auth: "admin" }),
15201
- getInfo: method(_void(), EmbeddingInfoSchema, { auth: "admin" })
15420
+ /**
15421
+ * `modelId` (a CLIP IMAGE model id, whose catalog `clip.textModelId` names
15422
+ * the text tower) encodes in that model's space; absent, the cluster row's
15423
+ * `clip-embedding` model — the space every writer is in (D649).
15424
+ */
15425
+ encodeText: method(object({
15426
+ text: string(),
15427
+ modelId: string().min(1).optional()
15428
+ }), EmbeddingResultSchema, { auth: "admin" }),
15429
+ /** Answers for ONE node — the `nodeId` selector's, else the hub's. */
15430
+ getInfo: method(_void(), EmbeddingInfoSchema, { auth: "admin" }),
15431
+ /**
15432
+ * The operator's explicit clear of the `failed` state (one model, or all)
15433
+ * on ONE node — pass `nodeId` for an agent; the result names the node it
15434
+ * cleared. The only way out besides a model change: a crashing tower is
15435
+ * not retried on a timer.
15436
+ */
15437
+ resetFailedModels: method(object({ modelId: string().min(1).optional() }), object({
15438
+ cleared: array(string()),
15439
+ nodeId: string()
15440
+ }), {
15441
+ kind: "mutation",
15442
+ auth: "admin"
15443
+ })
15202
15444
  }
15203
15445
  };
15204
15446
  /**
@@ -18727,7 +18969,12 @@ var NcMediaPolicySchema = object({
18727
18969
  * the degrade engine, which drops the video and keeps the still.
18728
18970
  */
18729
18971
  clip: boolean().optional(),
18730
- /** Seconds of footage BEFORE / AFTER the event instant. Defaults 3 / 7. */
18972
+ /**
18973
+ * Seconds of footage BEFORE / AFTER the event instant. Absent =
18974
+ * {@link NC_CLIP_PRE_ROLL_DEFAULT_SEC} / {@link NC_CLIP_POST_ROLL_DEFAULT_SEC}
18975
+ * (4 / 6), resolved by the Notification Center at dispatch — deliberately not
18976
+ * a Zod default, so a rule that never chose keeps following the hub's.
18977
+ */
18731
18978
  clipPreRollSec: number().int().min(0).max(30).optional(),
18732
18979
  clipPostRollSec: number().int().min(0).max(30).optional(),
18733
18980
  /**
@@ -20810,6 +21057,202 @@ var OauthIntegrationDescriptorSchema = object({
20810
21057
  });
20811
21058
  method(_void(), OauthIntegrationDescriptorSchema, { auth: "admin" });
20812
21059
  /**
21060
+ * A model choice has a SCOPE, and a scope change has a workflow.
21061
+ *
21062
+ * ## The two scopes
21063
+ *
21064
+ * Almost every pipeline step's model is a **node** question: which build runs
21065
+ * fastest on THIS accelerator. Two nodes may legitimately answer differently —
21066
+ * a Coral runs the tflite SSD, a Mac runs the coreml YOLO — because the answers
21067
+ * are compared against nothing. They produce boxes, and a box is a box.
21068
+ *
21069
+ * Two steps are not like that. `face-embedding` and `clip-embedding` produce
21070
+ * **vectors that land in ONE shared index** (`identity_samples`,
21071
+ * `vec_object_clip`) and are ranked against each other by cosine similarity.
21072
+ * Cosine similarity between two encoders is not a weak signal, it is a
21073
+ * meaningless number — and nothing inside a vector can tell you it happened.
21074
+ * So for those two steps the model is a **cluster** question with exactly one
21075
+ * answer, stored in exactly one row.
21076
+ *
21077
+ * That is the same argument [D52](../../../../docs/decisions/adr-0052.md) makes
21078
+ * for the crop convention (`detail-crop.ts`), one level up: the crop decides
21079
+ * WHAT pixels the encoder sees, this decides WHICH encoder sees them. Both are
21080
+ * cluster-wide for the same reason and neither may become per-node.
21081
+ *
21082
+ * ## Why the registry lives here and not in the step catalog
21083
+ *
21084
+ * The scope itself is declared on the step, in
21085
+ * `detection-pipeline/registry/step-definitions.ts` (`StepDefinition.modelScope`)
21086
+ * — that is where a new step declares what kind of choice its model is. But the
21087
+ * catalog lives inside `addon-pipeline`, and three packages that must NOT
21088
+ * import an addon need to know the set: the orchestrator (which renders and
21089
+ * stores the row), post-analysis (which pins the row for a re-embed pass) and
21090
+ * admin-ui (which mirrors it). So the set is mirrored here, and
21091
+ * `scripts/check-cluster-model-scope.ts` fails the build when the two disagree.
21092
+ * A hand-copied key that stops matching is exactly how a setting silently stops
21093
+ * arriving while both sides still look correct.
21094
+ *
21095
+ * ## The defaults ARE today's behaviour
21096
+ *
21097
+ * {@link DEFAULT_CLUSTER_STEP_MODELS} reproduces the catalog `defaultModelId`
21098
+ * of both steps. Declaring the scope therefore changes nothing on the day it
21099
+ * ships: the cluster row starts out saying what every node was already doing.
21100
+ * Changing it is legitimate — that is what the knob is for — but it invalidates
21101
+ * the stored vectors of that surface, and must be followed by a re-embed pass
21102
+ * (`face-reembed-pass.ts`, `embedding-rebuild.ts`).
21103
+ */
21104
+ /**
21105
+ * Why the orchestrator cannot say which model the operator chose for a
21106
+ * cluster-scoped step (D651).
21107
+ */
21108
+ var CLUSTER_MODEL_CHOICE_UNREADABLE_REASONS = [
21109
+ "owner-not-ready",
21110
+ "store-read-failed",
21111
+ "three-way-read-unavailable",
21112
+ "invalid-stored",
21113
+ "not-cluster-scoped"
21114
+ ];
21115
+ /**
21116
+ * The cluster-scoped steps. Mirrored from the catalog's `modelScope: 'cluster'`
21117
+ * declarations and guarded by `scripts/check-cluster-model-scope.ts`.
21118
+ */
21119
+ var CLUSTER_MODEL_SCOPED_STEPS = [{
21120
+ stepId: "face-embedding",
21121
+ label: "Face recognition model",
21122
+ defaultModelId: "auraface-r100",
21123
+ indexName: "the enrolled face gallery",
21124
+ options: [
21125
+ {
21126
+ id: "auraface-r100",
21127
+ label: "AuraFace R100"
21128
+ },
21129
+ {
21130
+ id: "arcface-r100",
21131
+ label: "ArcFace (ResNet34)"
21132
+ },
21133
+ {
21134
+ id: "inception-resnet-v1",
21135
+ label: "Inception ResNet V1"
21136
+ }
21137
+ ]
21138
+ }, {
21139
+ stepId: "clip-embedding",
21140
+ label: "Semantic search model",
21141
+ defaultModelId: "mobileclip-s1",
21142
+ indexName: "the object semantic-search index",
21143
+ options: [
21144
+ {
21145
+ id: "mobileclip-s1",
21146
+ label: "MobileCLIP S1"
21147
+ },
21148
+ {
21149
+ id: "mobileclip-s2",
21150
+ label: "MobileCLIP S2"
21151
+ },
21152
+ {
21153
+ id: "siglip2-b16-224",
21154
+ label: "SigLIP2 B/16 (Apache-2.0)"
21155
+ }
21156
+ ]
21157
+ }];
21158
+ /**
21159
+ * The settings key holding one step's cluster model choice.
21160
+ *
21161
+ * Step-qualified so the keys stay unique across the addon's whole schema, which
21162
+ * is what lets {@link pickClusterStepModels} walk every section instead of
21163
+ * trusting the section id.
21164
+ */
21165
+ function clusterModelSettingKey(stepId) {
21166
+ return `clusterModel:${stepId}`;
21167
+ }
21168
+ /** The cluster row when nobody has configured one — today's catalog defaults. */
21169
+ var DEFAULT_CLUSTER_STEP_MODELS = Object.freeze(Object.fromEntries(CLUSTER_MODEL_SCOPED_STEPS.map((s) => [s.stepId, s.defaultModelId])));
21170
+ function interpretStoredClusterModel(raw) {
21171
+ if (raw === void 0 || raw === null || raw === "") return { kind: "absent" };
21172
+ if (typeof raw === "string") return {
21173
+ kind: "chosen",
21174
+ modelId: raw
21175
+ };
21176
+ return {
21177
+ kind: "invalid",
21178
+ value: raw
21179
+ };
21180
+ }
21181
+ /**
21182
+ * Narrow a FLAT settings record to the cluster row.
21183
+ *
21184
+ * Per-FIELD fallback, deliberately (same rule as `readDetailCropConvention`): a
21185
+ * junk face model must not also discard a valid clip model. An `absent` or
21186
+ * `invalid` value ({@link interpretStoredClusterModel}) resolves to the step's
21187
+ * catalog default — never to a blank id, because a blank id downstream becomes
21188
+ * "substitute the format default", which is precisely the substitution this
21189
+ * scope exists to forbid.
21190
+ */
21191
+ function readClusterStepModels(config) {
21192
+ const out = {};
21193
+ for (const step of CLUSTER_MODEL_SCOPED_STEPS) {
21194
+ const read = interpretStoredClusterModel(config[clusterModelSettingKey(step.stepId)]);
21195
+ out[step.stepId] = read.kind === "chosen" ? read.modelId : step.defaultModelId;
21196
+ }
21197
+ return out;
21198
+ }
21199
+ function isHydratedField$2(entry) {
21200
+ return typeof entry === "object" && entry !== null && "key" in entry;
21201
+ }
21202
+ /**
21203
+ * Extract the cluster row from an `addon-settings.getGlobalSettings` payload.
21204
+ *
21205
+ * Walks EVERY section rather than looking inside {@link CLUSTER_MODEL_SECTION_ID}
21206
+ * alone: the keys are unique across the addon's schema, and a section rename
21207
+ * must not silently revert the whole cluster to the defaults. A `null` payload
21208
+ * (addon mid-boot) is the defaults.
21209
+ */
21210
+ function pickClusterStepModels(view) {
21211
+ if (view === null) return DEFAULT_CLUSTER_STEP_MODELS;
21212
+ return readClusterStepModels(flattenHydratedView(view, clusterModelKeys()));
21213
+ }
21214
+ function clusterModelKeys() {
21215
+ return new Set(CLUSTER_MODEL_SCOPED_STEPS.map((s) => clusterModelSettingKey(s.stepId)));
21216
+ }
21217
+ /** The `wanted` keys of a hydrated view as one flat record, every section walked. */
21218
+ function flattenHydratedView(view, wanted) {
21219
+ const flat = {};
21220
+ for (const section of view.sections) for (const entry of section.fields) {
21221
+ if (!isHydratedField$2(entry) || typeof entry.key !== "string") continue;
21222
+ if (wanted.has(entry.key)) flat[entry.key] = entry.value;
21223
+ }
21224
+ return flat;
21225
+ }
21226
+ var CLUSTER_STEP_SETTING_FIELDS = [{
21227
+ stepId: "face-embedding",
21228
+ key: "minLandmarkFaceSize",
21229
+ label: "Min face size for recognition (detection px)",
21230
+ 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.",
21231
+ type: "slider",
21232
+ min: 0,
21233
+ max: 64,
21234
+ step: 2,
21235
+ default: 24
21236
+ }];
21237
+ function clusterStepSettingKey(stepId, fieldKey) {
21238
+ return `clusterStepSetting:${stepId}:${fieldKey}`;
21239
+ }
21240
+ var ClusterSettingNumberSchema = number().finite();
21241
+ function readClusterStepSettings(config) {
21242
+ const out = {};
21243
+ for (const field of CLUSTER_STEP_SETTING_FIELDS) {
21244
+ const parsed = ClusterSettingNumberSchema.safeParse(config[clusterStepSettingKey(field.stepId, field.key)]);
21245
+ const value = parsed.success ? parsed.data : field.default;
21246
+ const existing = out[field.stepId] ?? {};
21247
+ out[field.stepId] = {
21248
+ ...existing,
21249
+ [field.key]: value
21250
+ };
21251
+ }
21252
+ return out;
21253
+ }
21254
+ readClusterStepSettings({});
21255
+ /**
20813
21256
  * pipeline-analytics — device-scoped wrapper cap. Refines raw
20814
21257
  * per-frame detections emitted by the pipeline runner into tracked
20815
21258
  * objects, per-kind event collections (motion / object / audio), and
@@ -21625,7 +22068,8 @@ var MediaFileKindEnum = _enum([
21625
22068
  "thumbnailSmall",
21626
22069
  "confirmationCrop",
21627
22070
  "debugCrop",
21628
- "sceneFrame"
22071
+ "sceneFrame",
22072
+ "lastSceneFrame"
21629
22073
  ]);
21630
22074
  /**
21631
22075
  * One media row ON THE WIRE: what it is, how big it is, and WHERE ITS BYTES
@@ -22177,7 +22621,23 @@ var SearchObjectEventsInput = object({
22177
22621
  until: number().optional(),
22178
22622
  classFilter: string().optional(),
22179
22623
  limit: number().default(50),
22180
- minScore: number().min(0).max(1).default(.2)
22624
+ /**
22625
+ * An ABSOLUTE cosine floor. Optional since D649: a floor is a property of the
22626
+ * model (0.2 kept 96% of matched pairs on MobileCLIP S1 and 2.7% on SigLIP2),
22627
+ * so an absent one resolves to the searched model's own `searchMinScore`
22628
+ * scaled by `strictness`. A number sent here is honoured verbatim.
22629
+ */
22630
+ minScore: number().min(0).max(1).optional(),
22631
+ /** Model-relative floor — see `resolveClipSearchMinScore`. Default `loose`. */
22632
+ strictness: ClipSearchStrictnessSchema.optional(),
22633
+ /**
22634
+ * Search THIS CLIP model's index instead of the cluster row's. Every index a
22635
+ * model ever wrote stays searchable until it is wiped (the MobileCLIP index
22636
+ * through a SigLIP2 cutover and its rollback window). An id with no CLIP
22637
+ * metadata is refused; an id other than the cluster row's is ADMIN-only
22638
+ * (`model-override-requires-admin`).
22639
+ */
22640
+ modelId: string().min(1).optional()
22181
22641
  });
22182
22642
  var TrackCascadeCountsSchema = object({
22183
22643
  /** Persisted track roots deleted (authoritative). */
@@ -22312,7 +22772,41 @@ var RebuildObjectEmbeddingsInput = object({
22312
22772
  * comparable, so wiping and rebuilding is the only way to be sure every vector
22313
22773
  * means the same thing.
22314
22774
  */
22315
- var WipeObjectEmbeddingsResultSchema = object({ deleted: number() });
22775
+ var WipeObjectEmbeddingsResultSchema = object({
22776
+ deleted: number(),
22777
+ /**
22778
+ * CLIP indexes that could NOT be emptied (unreachable, or refused at their
22779
+ * dimension) — not a clean slate. Additive and optional (D649).
22780
+ */
22781
+ failedIndexes: array(string()).optional()
22782
+ });
22783
+ /**
22784
+ * Why a rebuild did not start, BY NAME — ONE vocabulary for both gates in front
22785
+ * of a pass (D649 over D651). A bare `started: false` read the same for "the
22786
+ * stores are booting" and "the cluster row names a model with no CLIP
22787
+ * metadata", which need different fixes.
22788
+ * - `stores-unavailable` — the analytics stores or the API are not up yet.
22789
+ * - the owner's confirmation of the cluster model (D651, `ClusterPinConfirmer`):
22790
+ * a pass that rewrites an index needs two agreeing reads of the OWNER's
22791
+ * answer (`pipelineOrchestrator.getClusterModelChoice`) — a pass that cannot
22792
+ * name its model does not run (D54):
22793
+ * - the owner's own `unreadable` reasons (`owner-not-ready`,
22794
+ * `store-read-failed`, `three-way-read-unavailable`, `invalid-stored`,
22795
+ * `not-cluster-scoped`);
22796
+ * - `method-unavailable` — the orchestrator predates the method;
22797
+ * - `read-failed` — the call failed or answered something unparseable;
22798
+ * - `reads-disagree` — the two reads named different choices.
22799
+ * - `not-a-clip-model` — the CONFIRMED id has no CLIP metadata, so there is no
22800
+ * index to fill and no dimension to check against (D649).
22801
+ */
22802
+ var RebuildObjectEmbeddingsRefusalSchema = _enum([
22803
+ "stores-unavailable",
22804
+ ...CLUSTER_MODEL_CHOICE_UNREADABLE_REASONS,
22805
+ "method-unavailable",
22806
+ "read-failed",
22807
+ "reads-disagree",
22808
+ "not-a-clip-model"
22809
+ ]);
22316
22810
  /**
22317
22811
  * Acknowledgement that a rebuild STARTED.
22318
22812
  *
@@ -22325,7 +22819,12 @@ var WipeObjectEmbeddingsResultSchema = object({ deleted: number() });
22325
22819
  var RebuildObjectEmbeddingsResultSchema = object({
22326
22820
  started: boolean(),
22327
22821
  /** True when a pass was already running; the new request is ignored. */
22328
- alreadyRunning: boolean()
22822
+ alreadyRunning: boolean(),
22823
+ /** Present when the pass refused to start — see `RebuildObjectEmbeddingsRefusalSchema`. */
22824
+ refusal: RebuildObjectEmbeddingsRefusalSchema.optional(),
22825
+ /** The CLIP model the pass pinned, and the index it fills (when it started). */
22826
+ modelId: string().optional(),
22827
+ index: string().optional()
22329
22828
  });
22330
22829
  var RebuildStatusSchema = object({
22331
22830
  running: boolean(),
@@ -22359,7 +22858,11 @@ var RebuildStatusSchema = object({
22359
22858
  startedAtMs: number().nullable(),
22360
22859
  finishedAtMs: number().nullable(),
22361
22860
  /** Present when the pass ended by throwing. */
22362
- error: string().nullable()
22861
+ error: string().nullable(),
22862
+ /** The CLIP model the current / last pass pinned (D54), `null` before any. */
22863
+ modelId: string().nullable(),
22864
+ /** The index that pass fills — `ClipModelMeta.vectorIndex` of `modelId` (D649). */
22865
+ index: string().nullable()
22363
22866
  });
22364
22867
  /**
22365
22868
  * Acknowledgement that a debug-media reclaim STARTED.
@@ -23318,7 +23821,7 @@ var pipelineAnalyticsCapability = {
23318
23821
  * ObjectEvents by trackId. Returns up to `limit` events scored ≥
23319
23822
  * `minScore`, sorted descending by score.
23320
23823
  */
23321
- searchObjectEvents: method(SearchObjectEventsInput, array(ScoredObjectEventSchema).readonly()),
23824
+ searchObjectEvents: method(SearchObjectEventsInput, array(ScoredObjectEventSchema).readonly(), { caller: "required" }),
23322
23825
  wipeObjectEmbeddings: method(object({}), WipeObjectEmbeddingsResultSchema, {
23323
23826
  kind: "mutation",
23324
23827
  auth: "admin"
@@ -24415,6 +24918,17 @@ var RunnerFrameSourceSchema = discriminatedUnion("kind", [object({ kind: literal
24415
24918
  hubHostnameOverride: string().optional()
24416
24919
  })]).describe("Per-camera frame-source mode for the runner (P2c)");
24417
24920
  /**
24921
+ * What ONE step runs with on ONE roster device for THIS camera (D650): the
24922
+ * device's per-(node,device) base with the camera's override for that device
24923
+ * on top — the same `override ?? base` merge the orchestrator applies to the
24924
+ * elected device (`applyDeviceProvisioning`). Absent `modelId` ⇒ the executor
24925
+ * resolves the device format's default, exactly as on the elected device.
24926
+ */
24927
+ var RunnerJumpStepProvisioningSchema = object({
24928
+ modelId: string().optional(),
24929
+ settings: record(string(), unknown()).optional()
24930
+ });
24931
+ /**
24418
24932
  * One ENABLED inference device on the runner's node, as the step-tree
24419
24933
  * device-jump resolver sees it (phase 1). The orchestrator populates this
24420
24934
  * roster on the attach payload whenever the camera is elected onto a specific
@@ -24426,7 +24940,16 @@ var RunnerFrameSourceSchema = discriminatedUnion("kind", [object({ kind: literal
24426
24940
  var RunnerInferenceDeviceSchema = object({
24427
24941
  deviceKey: string(),
24428
24942
  weight: number().positive().default(1),
24429
- maxSessions: number().int().positive().nullable().default(null)
24943
+ maxSessions: number().int().positive().nullable().default(null),
24944
+ /**
24945
+ * Per-step provisioning for this camera on THIS device (D650), keyed by step
24946
+ * id. A step the runner jumps here runs with these fields, never with the
24947
+ * elected device's: `modelId` / `settings` are REPLACED on the jumped subtree
24948
+ * (a step absent from the map runs with neither — the target format default).
24949
+ * Absent field ⇒ an orchestrator that predates D650: the jumped step keeps
24950
+ * the elected device's provisioning, as before.
24951
+ */
24952
+ steps: record(string(), RunnerJumpStepProvisioningSchema).optional()
24430
24953
  });
24431
24954
  /**
24432
24955
  * Camera assignment payload sent by `addon-pipeline-orchestrator` to a
@@ -25301,6 +25824,28 @@ var NodeInferenceDeviceSchema = object({
25301
25824
  */
25302
25825
  exclusion: InferenceDeviceExclusionReasonSchema.nullable()
25303
25826
  });
25827
+ /**
25828
+ * The operator's model choice for one cluster-scoped step, answered by the
25829
+ * addon that OWNS the `clusterModel:*` settings (D651). Three answers, never
25830
+ * folded: a written choice, a key nobody wrote (the cluster runs the default
25831
+ * BY ABSENCE), or no answer. A caller that rewrites an index acts only on the
25832
+ * first two, read twice and agreeing.
25833
+ */
25834
+ var ClusterModelChoiceSchema = discriminatedUnion("kind", [
25835
+ object({
25836
+ kind: literal("stored"),
25837
+ modelId: string()
25838
+ }),
25839
+ object({
25840
+ kind: literal("absent"),
25841
+ defaultModelId: string()
25842
+ }),
25843
+ object({
25844
+ kind: literal("unreadable"),
25845
+ reason: _enum(CLUSTER_MODEL_CHOICE_UNREADABLE_REASONS),
25846
+ error: string().optional()
25847
+ })
25848
+ ]);
25304
25849
  var NodeInferenceDevicesSchema = object({
25305
25850
  nodeId: string(),
25306
25851
  /** False when the node's platform-probe was unreachable (no live device set). */
@@ -25328,10 +25873,17 @@ method(StorageMigrationLeaseInputSchema, object({ paused: literal(true) }), {
25328
25873
  }), object({ success: literal(true) }), {
25329
25874
  kind: "mutation",
25330
25875
  auth: "admin"
25331
- }), method(object({ deviceId: number() }), object({ deviceKey: string().nullable() })), method(_void(), object({ migrated: number() }), {
25876
+ }), method(object({ deviceId: number() }), object({ deviceKey: string().nullable() })), method(_void(), object({
25877
+ migrated: number(),
25878
+ skipped: array(object({
25879
+ deviceId: number(),
25880
+ targetNodeId: string(),
25881
+ reason: string()
25882
+ })).default([])
25883
+ }), {
25332
25884
  kind: "mutation",
25333
25885
  auth: "admin"
25334
- }), 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({
25886
+ }), 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({
25335
25887
  nodeId: string(),
25336
25888
  capName: string(),
25337
25889
  addonId: string()
@@ -27047,6 +27599,20 @@ var VectorScanResultSchema = object({
27047
27599
  */
27048
27600
  nextCursor: number().int().nonnegative().nullable()
27049
27601
  });
27602
+ /**
27603
+ * The ONE error code for "this index exists at another dimension; refusing to
27604
+ * redeclare it" (D649). It rides in the MESSAGE — an Error's own properties do
27605
+ * not survive the UDS/tRPC hop, its message does — and both sides go through
27606
+ * the helpers below, never a copied phrase: a consumer that must tell "this
27607
+ * index can never hold my vectors" from "the provider is unreachable" (a
27608
+ * delete counts the first as nothing-to-delete and the second as still
27609
+ * present) otherwise breaks silently the day the wording changes.
27610
+ */
27611
+ var VECTOR_INDEX_DIM_CONFLICT = "vector-index-dim-conflict";
27612
+ /** True when `err` (possibly re-wrapped by a transport) is that refusal. */
27613
+ function isVectorIndexDimConflict(err) {
27614
+ return (err instanceof Error ? err.message : String(err)).includes(`[${VECTOR_INDEX_DIM_CONFLICT}]`);
27615
+ }
27050
27616
  var VectorStatsInputSchema = object({ index: string() });
27051
27617
  var VectorStatsResultSchema = object({
27052
27618
  /** Provider id, so an operator can tell brute force from an ANN index. */
@@ -27706,6 +28272,349 @@ DeviceType.Camera, method(object({
27706
28272
  auth: "protected"
27707
28273
  });
27708
28274
  /**
28275
+ * LA tabella "quale booleano di questo tipo di device conta come ALTO", e il
28276
+ * valutatore puro del suo FRONTE.
28277
+ *
28278
+ * Viveva dentro il builtin virtual-doorbell
28279
+ * (`@camstack/system` — `builtins/doorbell/trigger-engine.ts`) e i suoi
28280
+ * predicati erano privati al modulo. Il recorder ne ha bisogno per il trigger
28281
+ * `RecordingTriggers.sensorDeviceIds`: copiarla avrebbe creato la SECONDA
28282
+ * tabella, che diverge alla prima cap aggiunta e il cui sintomo — "il sensore
28283
+ * fa suonare il campanello ma non registra" — è esattamente D62. Quindi si
28284
+ * SPOSTA qui e il doorbell la ri-esporta.
28285
+ *
28286
+ * ⚠ NON è `DEVICE_STATE_READERS` (`catalogs/device-state-vocabulary.ts`), e le
28287
+ * due non vanno unificate: quella risponde a "qual è la PAROLA di stato per una
28288
+ * regola" (e include `presence`, `cover`, `alarm-panel`), questa a "qual è il
28289
+ * booleano il cui FRONTE conta". Vocabolari deliberatamente diversi.
28290
+ */
28291
+ /**
28292
+ * Known binary / switch source caps → the boolean slice field whose
28293
+ * false→true rise counts as ACTIVE. Every entry is "fire on active".
28294
+ * Sensors whose "active" reading is not a plain boolean (presence's string
28295
+ * state, connectivity's connected flag) are deliberately excluded — a
28296
+ * reconnect is not a doorbell press, and it is not a recording either.
28297
+ */
28298
+ var SOURCE_CAP_ACTIVE_FIELD = {
28299
+ contact: "entryOpen",
28300
+ binary: "on",
28301
+ switch: "on",
28302
+ motion: "detected",
28303
+ flood: "flooded",
28304
+ gas: "detected",
28305
+ smoke: "detected",
28306
+ "carbon-monoxide": "detected",
28307
+ vibration: "detected",
28308
+ tamper: "tampered"
28309
+ };
28310
+ /**
28311
+ * The same caps → the slice field carrying the ms-epoch timestamp of the
28312
+ * last transition. Every source cap MUST appear here (guarded by a spec):
28313
+ * without a transition timestamp the evaluator cannot tell a genuine rise
28314
+ * from a boot-time hydration when the FIRST slice it ever sees is already
28315
+ * active, and errs towards silence — swallowing the rise.
28316
+ *
28317
+ * These timestamps are UPSTREAM ones, not ingest ones: the Home Assistant
28318
+ * provider derives them from `state.last_changed`, so they survive our own
28319
+ * restarts and correctly read as "hours ago" for a state that has been
28320
+ * active for hours. `motion` names its rise timestamp `lastDetectedAt`.
28321
+ */
28322
+ var SOURCE_CAP_CHANGED_AT_FIELD = {
28323
+ contact: "lastChangedAt",
28324
+ binary: "lastChangedAt",
28325
+ switch: "lastChangedAt",
28326
+ motion: "lastDetectedAt",
28327
+ flood: "lastChangedAt",
28328
+ gas: "lastChangedAt",
28329
+ smoke: "lastChangedAt",
28330
+ "carbon-monoxide": "lastChangedAt",
28331
+ vibration: "lastChangedAt",
28332
+ tamper: "lastChangedAt"
28333
+ };
28334
+ /** Cap names whose presence in a device's bindings qualify it as a source. */
28335
+ var SOURCE_CAPS = Object.keys(SOURCE_CAP_ACTIVE_FIELD);
28336
+ /** True when a cap is a recognised binary/switch source. */
28337
+ function isSourceCap(capName) {
28338
+ return Object.prototype.hasOwnProperty.call(SOURCE_CAP_ACTIVE_FIELD, capName);
28339
+ }
28340
+ /** Extract the "active" boolean a source cap's slice carries, or null when
28341
+ * the cap is unknown or the field is missing / non-boolean. */
28342
+ function sliceActiveValue(capName, slice) {
28343
+ const field = SOURCE_CAP_ACTIVE_FIELD[capName];
28344
+ if (field === void 0) return null;
28345
+ const raw = slice[field];
28346
+ return typeof raw === "boolean" ? raw : null;
28347
+ }
28348
+ /** Ms-epoch transition timestamp a source cap's slice carries, or null when
28349
+ * it is absent, non-numeric or the zero "never observed" sentinel. */
28350
+ function sliceChangedAt(capName, slice) {
28351
+ const field = SOURCE_CAP_CHANGED_AT_FIELD[capName];
28352
+ if (field === void 0) return null;
28353
+ const raw = slice[field];
28354
+ if (typeof raw !== "number" || !Number.isFinite(raw) || raw <= 0) return null;
28355
+ return raw;
28356
+ }
28357
+ /**
28358
+ * How recent a source's own transition timestamp must be for a FIRST
28359
+ * sighting that is already active to count as a genuine rise rather than a
28360
+ * hydration of long-standing state.
28361
+ */
28362
+ var DEFAULT_FIRST_SIGHTING_FRESHNESS_MS = 3e4;
28363
+ /**
28364
+ * IL fronte. Puro: nessun orologio proprio, nessuna memoria — il chiamante
28365
+ * porta `prior`, `nowMs` e il proprio `startedAtMs`.
28366
+ *
28367
+ * Il caso della PRIMA slice già attiva è trattato esplicitamente e vale come
28368
+ * fronte solo se il timestamp UPSTREAM della transizione è posteriore a
28369
+ * `startedAtMs` **e** entro `firstSightingFreshnessMs`. Entrambe le metà
28370
+ * servono: la sola freschezza scatterebbe su un'idratazione al boot di uno
28371
+ * stato flippato pochi secondi prima del riavvio, e il solo "dopo che abbiamo
28372
+ * iniziato" scatterebbe, su un processo di lunga vita, per una sorgente
28373
+ * adottata oggi il cui stato è cambiato ieri. Il caso ambiguo ERRA VERSO IL
28374
+ * SILENZIO e lo dichiara (`baseline-seeded-stale-active`).
28375
+ */
28376
+ function evaluateSensorEdge(input) {
28377
+ const value = sliceActiveValue(input.capName, input.slice);
28378
+ if (value === null) return {
28379
+ edge: "none",
28380
+ value: null,
28381
+ reason: isSourceCap(input.capName) ? "non-boolean-value" : "unknown-cap"
28382
+ };
28383
+ if (input.prior === void 0) {
28384
+ if (!value) return {
28385
+ edge: "none",
28386
+ value,
28387
+ reason: "baseline-seeded-inactive"
28388
+ };
28389
+ const changedAt = sliceChangedAt(input.capName, input.slice);
28390
+ const floor = Math.max(input.startedAtMs, input.nowMs - input.firstSightingFreshnessMs);
28391
+ if (changedAt === null || changedAt < floor) return {
28392
+ edge: "none",
28393
+ value,
28394
+ reason: "baseline-seeded-stale-active"
28395
+ };
28396
+ return {
28397
+ edge: "rising",
28398
+ value: true
28399
+ };
28400
+ }
28401
+ if (input.prior === value) return {
28402
+ edge: "none",
28403
+ value,
28404
+ reason: "no-change"
28405
+ };
28406
+ if (!value) return {
28407
+ edge: "none",
28408
+ value,
28409
+ reason: "falling-edge"
28410
+ };
28411
+ return {
28412
+ edge: "rising",
28413
+ value: true
28414
+ };
28415
+ }
28416
+ /**
28417
+ * Doorbell button cap. Two kinds of providers coexist behind this cap
28418
+ * name (same pattern as `snapshot`):
28419
+ *
28420
+ * - **Native** providers: registered per-device by device-driver
28421
+ * addons via `ctx.registerNativeCap` — either on a
28422
+ * `DeviceType.Button` accessory with `role: DeviceRole.Doorbell`,
28423
+ * or directly on the camera (Reolink registers at camera level).
28424
+ * Emits an `onPressed` event every time the firmware pushes a
28425
+ * ring; status tracks the last press and a pressCount since start
28426
+ * (diagnostic).
28427
+ *
28428
+ * - **Wrapper** provider: the `virtual-doorbell` system builtin
28429
+ * (`@camstack/system/builtins/doorbell`). Turns ANY binary-ish
28430
+ * device (contact / switch / event-emitter …) into a doorbell for
28431
+ * a camera. `defaultActive: false` — the operator explicitly binds
28432
+ * it per camera in the device-bindings UI, then picks the source
28433
+ * device + trigger in the per-device settings.
28434
+ *
28435
+ * The DeviceEventPropagator re-emits `onPressed` on the camera parent
28436
+ * — subscribers listening at the camera level receive ring events
28437
+ * with `via[]` populated. No code on the parent needed.
28438
+ */
28439
+ var DoorbellStatusSchema = object({
28440
+ /** Ms epoch of the last press. null = never observed since this provider started. */
28441
+ lastPressedAt: number().nullable(),
28442
+ /** Counter since provider start. Resets on reboot. Useful for metrics/debug. */
28443
+ pressCountSinceStart: number()
28444
+ });
28445
+ var DoorbellPressEventSchema = object({
28446
+ deviceId: number(),
28447
+ timestamp: number()
28448
+ });
28449
+ /**
28450
+ * The `doorbell-source` extension slot's editable value (D648): the camera's
28451
+ * virtual-doorbell trigger devices, exactly what the wrapper's
28452
+ * `doorbellSources` persists (as `{ deviceId }` records).
28453
+ */
28454
+ var DoorbellSourceSlotValueSchema = object({ deviceIds: array(number().int().positive()) });
28455
+ /**
28456
+ * The `doorbell-source` slot — which devices ring this camera's VIRTUAL
28457
+ * doorbell, owned by the `virtual-doorbell` wrapper over its
28458
+ * `doorbellSources` store (D648). A source rings when one of its
28459
+ * `SOURCE_CAPS` rises. Whether the wrapper is bound to the camera at all is a
28460
+ * different authority (`deviceManager.setWrapperActive`, D62) — the slot
28461
+ * reports it, it never writes it.
28462
+ */
28463
+ var DOORBELL_SOURCE_SLOT = {
28464
+ id: "doorbell-source",
28465
+ label: "Doorbell trigger devices",
28466
+ 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.",
28467
+ shape: "association",
28468
+ hostDeviceTypes: [DeviceType.Camera],
28469
+ sourceCaps: SOURCE_CAPS,
28470
+ cardinality: "many",
28471
+ value: DoorbellSourceSlotValueSchema
28472
+ };
28473
+ var doorbellCapability = {
28474
+ name: "doorbell",
28475
+ scope: "device",
28476
+ deviceNative: true,
28477
+ mode: "singleton",
28478
+ kind: "wrapper",
28479
+ defaultActive: false,
28480
+ deviceTypes: [DeviceType.Button, DeviceType.Camera],
28481
+ exposesDeviceSettings: true,
28482
+ extensionSlots: [DOORBELL_SOURCE_SLOT],
28483
+ methods: {},
28484
+ events: {
28485
+ /**
28486
+ * Fires once per physical press. Reolink delivers via Baichuan
28487
+ * push (`ReolinkSimpleEvent.type === 'doorbell'`). There is no
28488
+ * release/duration — it's a pulse.
28489
+ */
28490
+ onPressed: { data: DoorbellPressEventSchema } },
28491
+ status: {
28492
+ schema: DoorbellStatusSchema,
28493
+ kind: "push"
28494
+ },
28495
+ /**
28496
+ * Runtime-state slice — last press timestamp + lifetime press count.
28497
+ * Mirrored by the kernel and readable via
28498
+ * `device.state.doorbell.value`. UIs can show "last ring 5m ago"
28499
+ * without subscribing.
28500
+ */
28501
+ runtimeState: DoorbellStatusSchema,
28502
+ /**
28503
+ * 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.
28504
+ *
28505
+ * See `RuntimeStateDurability`. Enforced by
28506
+ * `scripts/check-runtime-state-durability.ts`.
28507
+ */
28508
+ durability: "restored"
28509
+ };
28510
+ var ExtensionSlotIdSchema = _enum(["doorbell-source", "linked-devices"]);
28511
+ DeviceType.Camera, DeviceType.Camera;
28512
+ /** A slot's editable value, discriminated on `slot`. */
28513
+ var ExtensionSlotValueSchema = discriminatedUnion("slot", [DoorbellSourceSlotValueSchema.extend({ slot: literal("doorbell-source") }), LinkedDevicesSlotValueSchema.extend({ slot: literal("linked-devices") })]);
28514
+ DeviceType.Camera;
28515
+ var ExtensionSourceAvailabilitySchema = discriminatedUnion("state", [object({ state: literal("ok") }), object({
28516
+ state: literal("unreachable"),
28517
+ reason: string()
28518
+ })]);
28519
+ /** One provider of slots — the D554 source-listing row. */
28520
+ var ExtensionSourceSchema = object({
28521
+ /** The routing prefix of every `slotRef` this provider serves. */
28522
+ source: string(),
28523
+ label: string(),
28524
+ /** Stamped by the dispatcher from the registry (D557). */
28525
+ addonId: string().optional(),
28526
+ availability: ExtensionSourceAvailabilitySchema
28527
+ });
28528
+ /**
28529
+ * How one picked source stands. `missing` — no such device (deleted, or an id
28530
+ * that never existed); `foreign` — a device the slot's owner cannot read from
28531
+ * (slice 2's cross-owner graft source); `unavailable` — it exists but is not a
28532
+ * valid source now (a container, which is never a pick). A source in any of
28533
+ * these states is SHOWN, never silently dropped or re-pointed.
28534
+ */
28535
+ var ExtensionSourceHealthSchema = _enum([
28536
+ "ok",
28537
+ "missing",
28538
+ "foreign",
28539
+ "unavailable"
28540
+ ]);
28541
+ var ExtensionSlotSourceSchema = object({
28542
+ deviceId: number().int(),
28543
+ /** The device's name, or null when it could not be resolved (`missing`). */
28544
+ name: string().nullable(),
28545
+ health: ExtensionSourceHealthSchema,
28546
+ detail: string().optional()
28547
+ });
28548
+ /**
28549
+ * A DIFFERENT authority that gates whether the slot's sources do anything —
28550
+ * reported read-only, named, never written through this contract (D62). The
28551
+ * virtual doorbell's sources ring only while the wrapper is bound to the
28552
+ * camera, and that binding belongs to `deviceManager.setWrapperActive`.
28553
+ * `unknown` means the gate could not be read; it is not "inactive" (D315).
28554
+ */
28555
+ var ExtensionSlotActivationSchema = object({
28556
+ state: _enum([
28557
+ "active",
28558
+ "inactive",
28559
+ "unknown"
28560
+ ]),
28561
+ authority: string(),
28562
+ detail: string().optional()
28563
+ });
28564
+ var ExtensionSlotRowSchema = discriminatedUnion("state", [object({
28565
+ state: literal("ok"),
28566
+ /** `<source>:<slotId>` — the routing key for `listCandidates` / `setSlot`. */
28567
+ slotRef: string(),
28568
+ slot: ExtensionSlotIdSchema,
28569
+ /** Names the store written (D62), e.g. `virtual-doorbell:doorbellSources`. */
28570
+ authority: string(),
28571
+ /** graft: its switch. association: null — removing every source is "off". */
28572
+ enabled: boolean().nullable(),
28573
+ /** graft: the cap registered on the host. association: null. */
28574
+ projects: string().nullable(),
28575
+ activation: ExtensionSlotActivationSchema.nullable(),
28576
+ value: ExtensionSlotValueSchema,
28577
+ sources: array(ExtensionSlotSourceSchema)
28578
+ }), object({
28579
+ state: literal("unreachable"),
28580
+ addonId: string(),
28581
+ reason: string()
28582
+ })]);
28583
+ var ExtensionCandidatesSchema = object({ candidates: array(object({
28584
+ deviceId: number().int(),
28585
+ name: string(),
28586
+ type: string(),
28587
+ location: string().nullable(),
28588
+ /** The container a child belongs to — "Spotlight 2" alone does not say which. */
28589
+ parentName: string().nullable(),
28590
+ /** Pre-marked by the owner's suggestion rule. NEVER saved on its own (D356). */
28591
+ suggested: boolean(),
28592
+ /** Why it is suggested ("same location"), null when it is not. */
28593
+ reason: string().nullable()
28594
+ })) });
28595
+ /**
28596
+ * What a write did. `none` — applied in place. `host` / `parent` — the owner
28597
+ * reloaded the host (or, for an accessory child, its parent) because the
28598
+ * write changed what the host REGISTERS (a graft switched on or off, slice 2).
28599
+ */
28600
+ var ExtensionSetResultSchema = object({
28601
+ applied: literal(true),
28602
+ reload: _enum([
28603
+ "none",
28604
+ "host",
28605
+ "parent"
28606
+ ])
28607
+ });
28608
+ var ExtensionSlotRefInputSchema = object({
28609
+ deviceId: number().int(),
28610
+ slotRef: string().min(1)
28611
+ });
28612
+ var ExtensionSetSlotInputSchema = ExtensionSlotRefInputSchema.extend({ value: ExtensionSlotValueSchema });
28613
+ method(object({ deviceId: number().int() }), array(ExtensionSourceSchema)), method(object({ deviceId: number().int() }), array(ExtensionSlotRowSchema)), method(ExtensionSlotRefInputSchema, ExtensionCandidatesSchema), method(ExtensionSetSlotInputSchema, ExtensionSetResultSchema, {
28614
+ kind: "mutation",
28615
+ auth: "admin"
28616
+ });
28617
+ /**
27709
28618
  * Optional client-side hints sent at session creation to help the provider
27710
28619
  * pick the best native source. All fields optional — a viewer that knows
27711
28620
  * nothing still gets a sane default. (Relocated from the retired `webrtc`
@@ -30155,75 +31064,6 @@ onStatusChanged: { data: object({
30155
31064
  volatileStateFields: ["lastChangedAt"]
30156
31065
  };
30157
31066
  /**
30158
- * Doorbell button cap. Two kinds of providers coexist behind this cap
30159
- * name (same pattern as `snapshot`):
30160
- *
30161
- * - **Native** providers: registered per-device by device-driver
30162
- * addons via `ctx.registerNativeCap` — either on a
30163
- * `DeviceType.Button` accessory with `role: DeviceRole.Doorbell`,
30164
- * or directly on the camera (Reolink registers at camera level).
30165
- * Emits an `onPressed` event every time the firmware pushes a
30166
- * ring; status tracks the last press and a pressCount since start
30167
- * (diagnostic).
30168
- *
30169
- * - **Wrapper** provider: the `virtual-doorbell` system builtin
30170
- * (`@camstack/system/builtins/doorbell`). Turns ANY binary-ish
30171
- * device (contact / switch / event-emitter …) into a doorbell for
30172
- * a camera. `defaultActive: false` — the operator explicitly binds
30173
- * it per camera in the device-bindings UI, then picks the source
30174
- * device + trigger in the per-device settings.
30175
- *
30176
- * The DeviceEventPropagator re-emits `onPressed` on the camera parent
30177
- * — subscribers listening at the camera level receive ring events
30178
- * with `via[]` populated. No code on the parent needed.
30179
- */
30180
- var DoorbellStatusSchema = object({
30181
- /** Ms epoch of the last press. null = never observed since this provider started. */
30182
- lastPressedAt: number().nullable(),
30183
- /** Counter since provider start. Resets on reboot. Useful for metrics/debug. */
30184
- pressCountSinceStart: number()
30185
- });
30186
- var DoorbellPressEventSchema = object({
30187
- deviceId: number(),
30188
- timestamp: number()
30189
- });
30190
- var doorbellCapability = {
30191
- name: "doorbell",
30192
- scope: "device",
30193
- deviceNative: true,
30194
- mode: "singleton",
30195
- kind: "wrapper",
30196
- defaultActive: false,
30197
- deviceTypes: [DeviceType.Button, DeviceType.Camera],
30198
- exposesDeviceSettings: true,
30199
- methods: {},
30200
- events: {
30201
- /**
30202
- * Fires once per physical press. Reolink delivers via Baichuan
30203
- * push (`ReolinkSimpleEvent.type === 'doorbell'`). There is no
30204
- * release/duration — it's a pulse.
30205
- */
30206
- onPressed: { data: DoorbellPressEventSchema } },
30207
- status: {
30208
- schema: DoorbellStatusSchema,
30209
- kind: "push"
30210
- },
30211
- /**
30212
- * Runtime-state slice — last press timestamp + lifetime press count.
30213
- * Mirrored by the kernel and readable via
30214
- * `device.state.doorbell.value`. UIs can show "last ring 5m ago"
30215
- * without subscribing.
30216
- */
30217
- runtimeState: DoorbellStatusSchema,
30218
- /**
30219
- * 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.
30220
- *
30221
- * See `RuntimeStateDurability`. Enforced by
30222
- * `scripts/check-runtime-state-durability.ts`.
30223
- */
30224
- durability: "restored"
30225
- };
30226
- /**
30227
31067
  * Enum-state sensor — a string value picked from a finite option set.
30228
31068
  * Drives HA `sensor` entries with `state_class: enum` (HVAC action
30229
31069
  * states, weather conditions, contact-source channels, mode strings).
@@ -39111,146 +39951,6 @@ function readDeviceStateFrom(runtimeState) {
39111
39951
  }
39112
39952
  }
39113
39953
  /**
39114
- * LA tabella "quale booleano di questo tipo di device conta come ALTO", e il
39115
- * valutatore puro del suo FRONTE.
39116
- *
39117
- * Viveva dentro il builtin virtual-doorbell
39118
- * (`@camstack/system` — `builtins/doorbell/trigger-engine.ts`) e i suoi
39119
- * predicati erano privati al modulo. Il recorder ne ha bisogno per il trigger
39120
- * `RecordingTriggers.sensorDeviceIds`: copiarla avrebbe creato la SECONDA
39121
- * tabella, che diverge alla prima cap aggiunta e il cui sintomo — "il sensore
39122
- * fa suonare il campanello ma non registra" — è esattamente D62. Quindi si
39123
- * SPOSTA qui e il doorbell la ri-esporta.
39124
- *
39125
- * ⚠ NON è `DEVICE_STATE_READERS` (`catalogs/device-state-vocabulary.ts`), e le
39126
- * due non vanno unificate: quella risponde a "qual è la PAROLA di stato per una
39127
- * regola" (e include `presence`, `cover`, `alarm-panel`), questa a "qual è il
39128
- * booleano il cui FRONTE conta". Vocabolari deliberatamente diversi.
39129
- */
39130
- /**
39131
- * Known binary / switch source caps → the boolean slice field whose
39132
- * false→true rise counts as ACTIVE. Every entry is "fire on active".
39133
- * Sensors whose "active" reading is not a plain boolean (presence's string
39134
- * state, connectivity's connected flag) are deliberately excluded — a
39135
- * reconnect is not a doorbell press, and it is not a recording either.
39136
- */
39137
- var SOURCE_CAP_ACTIVE_FIELD = {
39138
- contact: "entryOpen",
39139
- binary: "on",
39140
- switch: "on",
39141
- motion: "detected",
39142
- flood: "flooded",
39143
- gas: "detected",
39144
- smoke: "detected",
39145
- "carbon-monoxide": "detected",
39146
- vibration: "detected",
39147
- tamper: "tampered"
39148
- };
39149
- /**
39150
- * The same caps → the slice field carrying the ms-epoch timestamp of the
39151
- * last transition. Every source cap MUST appear here (guarded by a spec):
39152
- * without a transition timestamp the evaluator cannot tell a genuine rise
39153
- * from a boot-time hydration when the FIRST slice it ever sees is already
39154
- * active, and errs towards silence — swallowing the rise.
39155
- *
39156
- * These timestamps are UPSTREAM ones, not ingest ones: the Home Assistant
39157
- * provider derives them from `state.last_changed`, so they survive our own
39158
- * restarts and correctly read as "hours ago" for a state that has been
39159
- * active for hours. `motion` names its rise timestamp `lastDetectedAt`.
39160
- */
39161
- var SOURCE_CAP_CHANGED_AT_FIELD = {
39162
- contact: "lastChangedAt",
39163
- binary: "lastChangedAt",
39164
- switch: "lastChangedAt",
39165
- motion: "lastDetectedAt",
39166
- flood: "lastChangedAt",
39167
- gas: "lastChangedAt",
39168
- smoke: "lastChangedAt",
39169
- "carbon-monoxide": "lastChangedAt",
39170
- vibration: "lastChangedAt",
39171
- tamper: "lastChangedAt"
39172
- };
39173
- /** True when a cap is a recognised binary/switch source. */
39174
- function isSourceCap(capName) {
39175
- return Object.prototype.hasOwnProperty.call(SOURCE_CAP_ACTIVE_FIELD, capName);
39176
- }
39177
- /** Extract the "active" boolean a source cap's slice carries, or null when
39178
- * the cap is unknown or the field is missing / non-boolean. */
39179
- function sliceActiveValue(capName, slice) {
39180
- const field = SOURCE_CAP_ACTIVE_FIELD[capName];
39181
- if (field === void 0) return null;
39182
- const raw = slice[field];
39183
- return typeof raw === "boolean" ? raw : null;
39184
- }
39185
- /** Ms-epoch transition timestamp a source cap's slice carries, or null when
39186
- * it is absent, non-numeric or the zero "never observed" sentinel. */
39187
- function sliceChangedAt(capName, slice) {
39188
- const field = SOURCE_CAP_CHANGED_AT_FIELD[capName];
39189
- if (field === void 0) return null;
39190
- const raw = slice[field];
39191
- if (typeof raw !== "number" || !Number.isFinite(raw) || raw <= 0) return null;
39192
- return raw;
39193
- }
39194
- /**
39195
- * How recent a source's own transition timestamp must be for a FIRST
39196
- * sighting that is already active to count as a genuine rise rather than a
39197
- * hydration of long-standing state.
39198
- */
39199
- var DEFAULT_FIRST_SIGHTING_FRESHNESS_MS = 3e4;
39200
- /**
39201
- * IL fronte. Puro: nessun orologio proprio, nessuna memoria — il chiamante
39202
- * porta `prior`, `nowMs` e il proprio `startedAtMs`.
39203
- *
39204
- * Il caso della PRIMA slice già attiva è trattato esplicitamente e vale come
39205
- * fronte solo se il timestamp UPSTREAM della transizione è posteriore a
39206
- * `startedAtMs` **e** entro `firstSightingFreshnessMs`. Entrambe le metà
39207
- * servono: la sola freschezza scatterebbe su un'idratazione al boot di uno
39208
- * stato flippato pochi secondi prima del riavvio, e il solo "dopo che abbiamo
39209
- * iniziato" scatterebbe, su un processo di lunga vita, per una sorgente
39210
- * adottata oggi il cui stato è cambiato ieri. Il caso ambiguo ERRA VERSO IL
39211
- * SILENZIO e lo dichiara (`baseline-seeded-stale-active`).
39212
- */
39213
- function evaluateSensorEdge(input) {
39214
- const value = sliceActiveValue(input.capName, input.slice);
39215
- if (value === null) return {
39216
- edge: "none",
39217
- value: null,
39218
- reason: isSourceCap(input.capName) ? "non-boolean-value" : "unknown-cap"
39219
- };
39220
- if (input.prior === void 0) {
39221
- if (!value) return {
39222
- edge: "none",
39223
- value,
39224
- reason: "baseline-seeded-inactive"
39225
- };
39226
- const changedAt = sliceChangedAt(input.capName, input.slice);
39227
- const floor = Math.max(input.startedAtMs, input.nowMs - input.firstSightingFreshnessMs);
39228
- if (changedAt === null || changedAt < floor) return {
39229
- edge: "none",
39230
- value,
39231
- reason: "baseline-seeded-stale-active"
39232
- };
39233
- return {
39234
- edge: "rising",
39235
- value: true
39236
- };
39237
- }
39238
- if (input.prior === value) return {
39239
- edge: "none",
39240
- value,
39241
- reason: "no-change"
39242
- };
39243
- if (!value) return {
39244
- edge: "none",
39245
- value,
39246
- reason: "falling-edge"
39247
- };
39248
- return {
39249
- edge: "rising",
39250
- value: true
39251
- };
39252
- }
39253
- /**
39254
39954
  * Accessory device helpers — shared across drivers.
39255
39955
  *
39256
39956
  * Many vendor-specific drivers register accessory child devices on
@@ -43090,6 +43790,30 @@ Object.freeze({
43090
43790
  addonId: null,
43091
43791
  access: "create"
43092
43792
  },
43793
+ "deviceExtension.listCandidates": {
43794
+ capName: "device-extension",
43795
+ capScope: "device",
43796
+ addonId: null,
43797
+ access: "view"
43798
+ },
43799
+ "deviceExtension.listSlots": {
43800
+ capName: "device-extension",
43801
+ capScope: "device",
43802
+ addonId: null,
43803
+ access: "view"
43804
+ },
43805
+ "deviceExtension.listSources": {
43806
+ capName: "device-extension",
43807
+ capScope: "device",
43808
+ addonId: null,
43809
+ access: "view"
43810
+ },
43811
+ "deviceExtension.setSlot": {
43812
+ capName: "device-extension",
43813
+ capScope: "device",
43814
+ addonId: null,
43815
+ access: "create"
43816
+ },
43093
43817
  "deviceManager.addLocation": {
43094
43818
  capName: "device-manager",
43095
43819
  capScope: "system",
@@ -43840,6 +44564,12 @@ Object.freeze({
43840
44564
  addonId: null,
43841
44565
  access: "view"
43842
44566
  },
44567
+ "embeddingEncoder.resetFailedModels": {
44568
+ capName: "embedding-encoder",
44569
+ capScope: "system",
44570
+ addonId: null,
44571
+ access: "delete"
44572
+ },
43843
44573
  "enumSensor.getStatus": {
43844
44574
  capName: "enum-sensor",
43845
44575
  capScope: "device",
@@ -46174,6 +46904,12 @@ Object.freeze({
46174
46904
  addonId: null,
46175
46905
  access: "view"
46176
46906
  },
46907
+ "pipelineOrchestrator.getClusterModelChoice": {
46908
+ capName: "pipeline-orchestrator",
46909
+ capScope: "system",
46910
+ addonId: null,
46911
+ access: "view"
46912
+ },
46177
46913
  "pipelineOrchestrator.getDeviceLiveContribution": {
46178
46914
  capName: "pipeline-orchestrator",
46179
46915
  capScope: "system",
@@ -48999,6 +49735,26 @@ Object.freeze({
48999
49735
  form: "single",
49000
49736
  optional: false
49001
49737
  }],
49738
+ "deviceExtension.listCandidates": [{
49739
+ name: "deviceId",
49740
+ form: "single",
49741
+ optional: false
49742
+ }],
49743
+ "deviceExtension.listSlots": [{
49744
+ name: "deviceId",
49745
+ form: "single",
49746
+ optional: false
49747
+ }],
49748
+ "deviceExtension.listSources": [{
49749
+ name: "deviceId",
49750
+ form: "single",
49751
+ optional: false
49752
+ }],
49753
+ "deviceExtension.setSlot": [{
49754
+ name: "deviceId",
49755
+ form: "single",
49756
+ optional: false
49757
+ }],
49002
49758
  "deviceManager.adoptionRelease": [{
49003
49759
  name: "camDeviceId",
49004
49760
  form: "single",
@@ -52621,169 +53377,6 @@ function readTimelapseGeneratedAt(rule, deviceId) {
52621
53377
  if (map !== void 0) return map[String(deviceId)] ?? 0;
52622
53378
  return rule.lastGeneratedAt ?? 0;
52623
53379
  }
52624
- /**
52625
- * A model choice has a SCOPE, and a scope change has a workflow.
52626
- *
52627
- * ## The two scopes
52628
- *
52629
- * Almost every pipeline step's model is a **node** question: which build runs
52630
- * fastest on THIS accelerator. Two nodes may legitimately answer differently —
52631
- * a Coral runs the tflite SSD, a Mac runs the coreml YOLO — because the answers
52632
- * are compared against nothing. They produce boxes, and a box is a box.
52633
- *
52634
- * Two steps are not like that. `face-embedding` and `clip-embedding` produce
52635
- * **vectors that land in ONE shared index** (`identity_samples`,
52636
- * `vec_object_clip`) and are ranked against each other by cosine similarity.
52637
- * Cosine similarity between two encoders is not a weak signal, it is a
52638
- * meaningless number — and nothing inside a vector can tell you it happened.
52639
- * So for those two steps the model is a **cluster** question with exactly one
52640
- * answer, stored in exactly one row.
52641
- *
52642
- * That is the same argument [D52](../../../../docs/decisions/adr-0052.md) makes
52643
- * for the crop convention (`detail-crop.ts`), one level up: the crop decides
52644
- * WHAT pixels the encoder sees, this decides WHICH encoder sees them. Both are
52645
- * cluster-wide for the same reason and neither may become per-node.
52646
- *
52647
- * ## Why the registry lives here and not in the step catalog
52648
- *
52649
- * The scope itself is declared on the step, in
52650
- * `detection-pipeline/registry/step-definitions.ts` (`StepDefinition.modelScope`)
52651
- * — that is where a new step declares what kind of choice its model is. But the
52652
- * catalog lives inside `addon-pipeline`, and three packages that must NOT
52653
- * import an addon need to know the set: the orchestrator (which renders and
52654
- * stores the row), post-analysis (which pins the row for a re-embed pass) and
52655
- * admin-ui (which mirrors it). So the set is mirrored here, and
52656
- * `scripts/check-cluster-model-scope.ts` fails the build when the two disagree.
52657
- * A hand-copied key that stops matching is exactly how a setting silently stops
52658
- * arriving while both sides still look correct.
52659
- *
52660
- * ## The defaults ARE today's behaviour
52661
- *
52662
- * {@link DEFAULT_CLUSTER_STEP_MODELS} reproduces the catalog `defaultModelId`
52663
- * of both steps. Declaring the scope therefore changes nothing on the day it
52664
- * ships: the cluster row starts out saying what every node was already doing.
52665
- * Changing it is legitimate — that is what the knob is for — but it invalidates
52666
- * the stored vectors of that surface, and must be followed by a re-embed pass
52667
- * (`face-reembed-pass.ts`, `embedding-rebuild.ts`).
52668
- */
52669
- /**
52670
- * The cluster-scoped steps. Mirrored from the catalog's `modelScope: 'cluster'`
52671
- * declarations and guarded by `scripts/check-cluster-model-scope.ts`.
52672
- */
52673
- var CLUSTER_MODEL_SCOPED_STEPS = [{
52674
- stepId: "face-embedding",
52675
- label: "Face recognition model",
52676
- defaultModelId: "arcface-r100",
52677
- indexName: "the enrolled face gallery",
52678
- options: [
52679
- {
52680
- id: "arcface-r100",
52681
- label: "ArcFace (ResNet34)"
52682
- },
52683
- {
52684
- id: "auraface-r100",
52685
- label: "AuraFace R100"
52686
- },
52687
- {
52688
- id: "inception-resnet-v1",
52689
- label: "Inception ResNet V1"
52690
- }
52691
- ]
52692
- }, {
52693
- stepId: "clip-embedding",
52694
- label: "Semantic search model",
52695
- defaultModelId: "mobileclip-s1",
52696
- indexName: "the object semantic-search index",
52697
- options: [{
52698
- id: "mobileclip-s1",
52699
- label: "MobileCLIP S1"
52700
- }, {
52701
- id: "mobileclip-s2",
52702
- label: "MobileCLIP S2"
52703
- }]
52704
- }];
52705
- /**
52706
- * The settings key holding one step's cluster model choice.
52707
- *
52708
- * Step-qualified so the keys stay unique across the addon's whole schema, which
52709
- * is what lets {@link pickClusterStepModels} walk every section instead of
52710
- * trusting the section id.
52711
- */
52712
- function clusterModelSettingKey(stepId) {
52713
- return `clusterModel:${stepId}`;
52714
- }
52715
- /** The cluster row when nobody has configured one — today's catalog defaults. */
52716
- var DEFAULT_CLUSTER_STEP_MODELS = Object.freeze(Object.fromEntries(CLUSTER_MODEL_SCOPED_STEPS.map((s) => [s.stepId, s.defaultModelId])));
52717
- /** A stored choice is a non-empty model id, or it is not a choice. */
52718
- var ChosenModelIdSchema = string().min(1);
52719
- /**
52720
- * Narrow a FLAT settings record to the cluster row.
52721
- *
52722
- * Per-FIELD fallback, deliberately (same rule as `readDetailCropConvention`): a
52723
- * junk face model must not also discard a valid clip model. An absent, empty or
52724
- * non-string value resolves to the step's catalog default — the historical
52725
- * behaviour — never to a blank id, because a blank id downstream becomes
52726
- * "substitute the format default", which is precisely the substitution this
52727
- * scope exists to forbid.
52728
- */
52729
- function readClusterStepModels(config) {
52730
- const out = {};
52731
- for (const step of CLUSTER_MODEL_SCOPED_STEPS) {
52732
- const parsed = ChosenModelIdSchema.safeParse(config[clusterModelSettingKey(step.stepId)]);
52733
- out[step.stepId] = parsed.success ? parsed.data : step.defaultModelId;
52734
- }
52735
- return out;
52736
- }
52737
- function isHydratedField$2(entry) {
52738
- return typeof entry === "object" && entry !== null && "key" in entry;
52739
- }
52740
- /**
52741
- * Extract the cluster row from an `addon-settings.getGlobalSettings` payload.
52742
- *
52743
- * Walks EVERY section rather than looking inside {@link CLUSTER_MODEL_SECTION_ID}
52744
- * alone: the keys are unique across the addon's schema, and a section rename
52745
- * must not silently revert the whole cluster to the defaults. A `null` payload
52746
- * (addon mid-boot) is the defaults.
52747
- */
52748
- function pickClusterStepModels(view) {
52749
- if (view === null) return DEFAULT_CLUSTER_STEP_MODELS;
52750
- const flat = {};
52751
- const wanted = new Set(CLUSTER_MODEL_SCOPED_STEPS.map((s) => clusterModelSettingKey(s.stepId)));
52752
- for (const section of view.sections) for (const entry of section.fields) {
52753
- if (!isHydratedField$2(entry) || typeof entry.key !== "string") continue;
52754
- if (wanted.has(entry.key)) flat[entry.key] = entry.value;
52755
- }
52756
- return readClusterStepModels(flat);
52757
- }
52758
- var CLUSTER_STEP_SETTING_FIELDS = [{
52759
- stepId: "face-embedding",
52760
- key: "minLandmarkFaceSize",
52761
- label: "Min face size for recognition (detection px)",
52762
- 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.",
52763
- type: "slider",
52764
- min: 0,
52765
- max: 64,
52766
- step: 2,
52767
- default: 24
52768
- }];
52769
- function clusterStepSettingKey(stepId, fieldKey) {
52770
- return `clusterStepSetting:${stepId}:${fieldKey}`;
52771
- }
52772
- var ClusterSettingNumberSchema = number().finite();
52773
- function readClusterStepSettings(config) {
52774
- const out = {};
52775
- for (const field of CLUSTER_STEP_SETTING_FIELDS) {
52776
- const parsed = ClusterSettingNumberSchema.safeParse(config[clusterStepSettingKey(field.stepId, field.key)]);
52777
- const value = parsed.success ? parsed.data : field.default;
52778
- const existing = out[field.stepId] ?? {};
52779
- out[field.stepId] = {
52780
- ...existing,
52781
- [field.key]: value
52782
- };
52783
- }
52784
- return out;
52785
- }
52786
- readClusterStepSettings({});
52787
53380
  object({
52788
53381
  /**
52789
53382
  * Fraction of the box's own size added on EACH side before cutting.
@@ -53325,4 +53918,395 @@ function vectorDimFromBase64(encoded) {
53325
53918
  return Math.floor(Buffer.from(encoded, "base64").byteLength / 4);
53326
53919
  }
53327
53920
  //#endregion
53328
- export { NcTemplatePreviewSchema as $, resolvePoolMemoryPolicy as $t, NC_DEFAULT_SNOOZE_MINUTES as A, literal as An, evictionPolicyOfLocation as At, NcConditionsSchema as B, isSystemDelivery as Bt, MAX_BIRTH_DECISION_RECORDS as C, isDeviceScopedCap as Cn, cosineSimilarity as Ct, NC_ALARM_SYSTEM_EVENT_KINDS as D, array as Dn, embeddingEncoderCapability as Dt, MediaFileKindEnum as E, _enum as En, describeSystemEventFamilyProblem as Et, NC_TAXONOMY as F, string as Fn, isEventOwnerType as Ft, NcRuleUpdateInputSchema as G, occupancyScope as Gt, NcRulePatchSchema as H, kebabToCamel as Ht, NC_TEMPLATE_VARS as I, unknown as In, isKnownTemplateVar as It, NcSnoozeSchema as J, pipelineAnalyticsCapability as Jt, NcScheduleSchema as K, parseProcStatus as Kt, NcAlarmConfigSchema as L, EventCategory as Ln, isMediaOwnerType as Lt, NC_SNOOZE_MAX_MINUTES as M, object as Mn, failureContributionCapability as Mt, NC_SYSTEM_EVENT_KIND_GROUP_SPECS as N, partialRecord as Nn, hfModelUrl as Nt, NC_CONDITION_CATALOG as O, boolean as On, encodeVectorBase64 as Ot, NC_TANK_SYSTEM_EVENT_KINDS as P, record as Pn, isDetectionMacroClass as Pt, NcTemplatePreviewInputSchema as Q, resolveLocationMode as Qt, NcAlarmSettingsPatchSchema as R, isScheduleActive as Rt, MAX_ARCHIVED_DEBUG_NOTES as S, hydrateSchema as Sn, consumableLowPercentOf as St, MOTION_CLOSE_AFTER_MS as T, sleep as Tn, describeSystemEventDeliveryProblem as Tt, NcRuleSchema as U, mayWriteToLocation as Ut, NcRuleInputSchema as V, isSystemEventSummaryRule as Vt, NcRuleTargetSchema as W, notificationRulesCapability as Wt, NcSystemEventKindSchema as X, readDeviceStateFrom as Xt, NcSnoozeSuppressedSchema as Y, plateGalleryCapability as Yt, NcTaxonomySchema as Z, readTimelapseGeneratedAt as Zt, FIRST_LEVEL_MACRO_CLASSES as _, CamProfileSchema as _n, alarmPanelCapability as _t, BirthDecisionRecordSchema as a, subKindsOf as an, RetrainStatusSchema as at, LabelAttributionSchema as b, customAction as bn, audioModeOf as bt, CoverStateSchema as c, systemEventFilterApplies as cn, SCENE_DEFAULT_UNCOVERED_POLICY as ct, DEFAULT_TIMELAPSE_PREVIEW_TEXT as d, templateVarsFor as dn, TIMELAPSE_DENSE_FLOOR_SEC as dt, ruleBelongsToAlarm as en, NcTemplateVarDescriptorSchema as et, DETECTION_MACRO_CLASSES as f, vectorDimFromBase64 as fn, TimelapseRuleInputSchema as ft, EVENT_OWNER_TYPES as g, BaseAddon as gn, addonWidgetsSourceCapability as gt, EVENT_KIND_BY_CAP as h, canonicalHash as hn, TrackSourceSchema as ht, BaseDevice as i, storageOccupancyCapability as in, RECORDING_SOURCE_CAMSTACK_ADDON as it, NC_SENSOR_TRANSITION_KINDS as j, number as jn, faceGalleryCapability as jt, NC_CONSUMABLE_SYSTEM_EVENT_KINDS as k, discriminatedUnion as kn, evaluateSensorEdge as kt, DEFAULT_EVENT_COLOR as l, systemEventSummaryScheduleOf as ln, SCENE_DIVERGED as lt, DeclaredDevices as m, errMsg as mn, TimelapseRuleSchema as mt, AlarmArmModeSchema as n, sensorRaisedOf as nn, PoolMemoryWatchdog as nt, CLUSTER_MODEL_SCOPED_STEPS as o, systemEventDeliveryProblems as on, SCENE_CONFIRM_DEFAULT_TIMEOUT_MS as ot, DETECTION_PIPELINE_CAP_NAME as p, zoneAnalyticsCapability as pn, TimelapseRulePatchSchema as pt, NcSnoozeInputSchema as q, pickClusterStepModels as qt, ArchivedDebugNoteSchema as r, servedTemplateVars as rn, RECORDING_EXPORT_MAX_READ_BYTES as rt, COCO_TO_MACRO as s, systemEventFamilyProblems as sn, SCENE_DEFAULT_ANCHOR_THRESHOLD as st, AUDIO_MACRO_LABELS as t, sceneMonitorCapability as tn, OpsLogEntrySchema as tt, DEFAULT_FIRST_SIGHTING_FRESHNESS_MS as u, templateCarriesSummary as un, SceneMonitorSchema as ut, FULL_IMAGE_BBOX as v, DeviceType as vn, assertTimelapseCadences as vt, MAX_BIRTH_LATENCY_PROXY_MS as w, nodePin as wn, deriveRecordingMode as wt, LockStateSchema as x, defineCustomActions as xn, buildEventKindDescriptor as xt, FailureCounters as y, createEvent as yn, audioMetricsCapability as yt, NcConditionDescriptorSchema as z, isSourceCap as zt };
53921
+ //#region src/pipeline-analytics/cluster-model-pin.ts
53922
+ /**
53923
+ * Where a re-embed pass gets the model it pins.
53924
+ *
53925
+ * ## Why not `embeddingEncoder.getInfo`
53926
+ *
53927
+ * That is what the CLIP rebuild used, and it answers a subtly different
53928
+ * question: "which model is the encoder addon currently holding", not "which
53929
+ * model has the operator chosen for the cluster". The two agree until they do
53930
+ * not — an encoder mid-reload, a node that never picked up a change — and when
53931
+ * they disagree the pass writes a whole index in the wrong space with a status
53932
+ * line that looks fine. Since `face-embedding` and `clip-embedding` declare
53933
+ * `modelScope: 'cluster'`, there is now exactly one authority for each, and it
53934
+ * is a stored row rather than a live process's opinion.
53935
+ *
53936
+ * ## Why the read is not cached here
53937
+ *
53938
+ * A pass reads it ONCE, at the start, and pins that value for its whole run
53939
+ * (D54). A cache would only matter for a caller that re-read it mid-pass, which
53940
+ * is precisely the thing the pin exists to prevent — so there is nothing to
53941
+ * cache and the absence is deliberate.
53942
+ *
53943
+ * ## Why a failed read refuses instead of defaulting
53944
+ *
53945
+ * A pass that cannot name its model must not run. The previous CLIP path's
53946
+ * `?? 'unknown'` is the shipped version of the alternative: rows stamped with an
53947
+ * id nothing ran, in an index whose same-model gate then has nothing to reason
53948
+ * about.
53949
+ */
53950
+ /** The addon whose GLOBAL settings hold the cluster row. */
53951
+ var CLUSTER_MODEL_OWNER_ADDON_ID = "pipeline-orchestrator";
53952
+ /** The step ids this module can pin — the same two the catalog declares. */
53953
+ var FACE_EMBEDDING_STEP_ID = "face-embedding";
53954
+ var CLIP_EMBEDDING_STEP_ID = "clip-embedding";
53955
+ /**
53956
+ * The cluster row, or `null` when it could not be read.
53957
+ *
53958
+ * `null` and not "the defaults": a caller that cannot distinguish "the operator
53959
+ * chose arcface" from "I could not ask" will run a pass on a guess. The one
53960
+ * production caller turns `null` into a refusal to start.
53961
+ */
53962
+ async function readClusterModelRow(api, logger) {
53963
+ try {
53964
+ return pickClusterStepModels(await api.addonSettings.getGlobalSettings.query({ addonId: CLUSTER_MODEL_OWNER_ADDON_ID }));
53965
+ } catch (err) {
53966
+ logger.warn("cluster model row unreadable — a re-embed pass must not guess which encoder the operator chose", { meta: {
53967
+ owner: CLUSTER_MODEL_OWNER_ADDON_ID,
53968
+ error: err instanceof Error ? err.message : String(err)
53969
+ } });
53970
+ return null;
53971
+ }
53972
+ }
53973
+ /**
53974
+ * Pin one cluster-scoped step's model for a whole pass.
53975
+ *
53976
+ * Returns `null` on an unreadable row OR an unknown step id — both mean the
53977
+ * caller must not start, and folding them together is safe because the caller's
53978
+ * move is identical: refuse, loudly.
53979
+ */
53980
+ async function resolveClusterModelPin(api, stepId, logger) {
53981
+ if (!CLUSTER_MODEL_SCOPED_STEPS.some((s) => s.stepId === stepId)) {
53982
+ logger.warn("cluster model pin requested for a step that is not cluster-scoped", { meta: {
53983
+ stepId,
53984
+ clusterScoped: CLUSTER_MODEL_SCOPED_STEPS.map((s) => s.stepId)
53985
+ } });
53986
+ return null;
53987
+ }
53988
+ const row = await readClusterModelRow(api, logger);
53989
+ if (row === null) return null;
53990
+ const modelId = row[stepId];
53991
+ return modelId !== void 0 && modelId !== "" ? modelId : null;
53992
+ }
53993
+ /**
53994
+ * The error texts a cap call carries when the provider or the router has no
53995
+ * such method: the kernel's `Capability "…" has no method "…"`, tRPC's
53996
+ * `No procedure found on path`, and the forked-child hop's
53997
+ * `method '…' not found on provider '…'` (child-cap-dispatch.ts). NOT `is not a function`: that is any
53998
+ * `TypeError` thrown INSIDE the owner while it answers, and reading it as
53999
+ * "the owner predates the method" would file a bug in the owner under a
54000
+ * rolling-release reason nobody investigates.
54001
+ */
54002
+ var METHOD_UNAVAILABLE_FINGERPRINTS = [
54003
+ /has no method/i,
54004
+ /no procedure found/i,
54005
+ /method not found/i,
54006
+ /method '[^']*' not found on provider/i
54007
+ ];
54008
+ /**
54009
+ * The pin read for a pass that REWRITES an index (D651 fix rounds 1–3).
54010
+ *
54011
+ * Asks the OWNER. The orchestrator owns `clusterModel:*` and answers from a
54012
+ * three-way read of its own store, once its boot has settled
54013
+ * (`pipelineOrchestrator.getClusterModelChoice`). Never the hydrated view,
54014
+ * which answers `value ?? default`, and never the owner's private store
54015
+ * layout. Silent on purpose: the callers log state CHANGES.
54016
+ */
54017
+ async function readClusterModelPinStrict(api, stepId) {
54018
+ const method = api.pipelineOrchestrator?.getClusterModelChoice;
54019
+ if (method === void 0) return {
54020
+ kind: "unknown",
54021
+ reason: "method-unavailable"
54022
+ };
54023
+ let raw;
54024
+ try {
54025
+ raw = await method.query({ stepId });
54026
+ } catch (err) {
54027
+ const error = err instanceof Error ? err.message : String(err);
54028
+ return METHOD_UNAVAILABLE_FINGERPRINTS.some((re) => re.test(error)) ? {
54029
+ kind: "unknown",
54030
+ reason: "method-unavailable",
54031
+ error
54032
+ } : {
54033
+ kind: "unknown",
54034
+ reason: "read-failed",
54035
+ error
54036
+ };
54037
+ }
54038
+ if (raw === void 0) return {
54039
+ kind: "unknown",
54040
+ reason: "method-unavailable"
54041
+ };
54042
+ const parsed = ClusterModelChoiceSchema.safeParse(raw);
54043
+ if (!parsed.success) return {
54044
+ kind: "unknown",
54045
+ reason: "read-failed",
54046
+ error: "unparseable owner answer"
54047
+ };
54048
+ const choice = parsed.data;
54049
+ if (choice.kind === "stored") return {
54050
+ kind: "known",
54051
+ modelId: choice.modelId
54052
+ };
54053
+ if (choice.kind === "absent") return {
54054
+ kind: "not-stored",
54055
+ defaultModelId: choice.defaultModelId
54056
+ };
54057
+ return choice.error !== void 0 ? {
54058
+ kind: "unknown",
54059
+ reason: choice.reason,
54060
+ error: choice.error
54061
+ } : {
54062
+ kind: "unknown",
54063
+ reason: choice.reason
54064
+ };
54065
+ }
54066
+ //#endregion
54067
+ //#region src/embedding-encoder/catalogs/embedding-models.ts
54068
+ var HF_REPO = "camstack/camstack-models";
54069
+ var hf = (path) => hfModelUrl(HF_REPO, path);
54070
+ /**
54071
+ * The text tower's tokenizer, in HF `tokenizers` format, hosted next to every
54072
+ * text-encoder onnx (`.../onnx/tokenizer.json`) and fetched as a sibling file so
54073
+ * it lands beside the model. Each model folder hosts ITS OWN (MobileCLIP: the
54074
+ * CLIP BPE, vocab 49408; SigLIP2: Gemma SentencePiece, 256k, lower-casing).
54075
+ */
54076
+ var TOKENIZER_FILE = "tokenizer.json";
54077
+ /** SigLIP2's tokenizer — a DIFFERENT file name on purpose: see `ClipModelMeta.tokenizerFile`. */
54078
+ var SIGLIP2_TOKENIZER_FILE = "camstack-siglip2-b16-224-tokenizer.json";
54079
+ var ovFormat = (url, sizeMB) => {
54080
+ const base = url.split("/").pop() ?? "";
54081
+ const files = base.endsWith(".xml") ? [base.replace(/\.xml$/, ".bin")] : void 0;
54082
+ return {
54083
+ url,
54084
+ sizeMB,
54085
+ runtimes: ["python"],
54086
+ ...files ? { files } : {}
54087
+ };
54088
+ };
54089
+ /**
54090
+ * Files inside an .mlpackage directory bundle.
54091
+ * Must be fetched alongside the package root when isDirectory is true.
54092
+ */
54093
+ var MLPACKAGE_FILES = [
54094
+ "Manifest.json",
54095
+ "Data/com.apple.CoreML/model.mlmodel",
54096
+ "Data/com.apple.CoreML/weights/weight.bin"
54097
+ ];
54098
+ /**
54099
+ * The MobileCLIP feature-space contract (D649 — see `clip-model.ts` in
54100
+ * `@camstack/types`). S1 and S2 share the historical 512-d `object-clip` index,
54101
+ * separated by each row's `modelId`; the CLIP BPE window is 77 tokens padded
54102
+ * with 0; 0.2 is the floor the search always shipped with, measured to keep 96%
54103
+ * of matched COCO caption-image pairs on S1.
54104
+ */
54105
+ var mobileclipMeta = (textModelId) => ({
54106
+ textModelId,
54107
+ embeddingDim: 512,
54108
+ vectorIndex: "object-clip",
54109
+ tokenizerFile: TOKENIZER_FILE,
54110
+ contextLength: 77,
54111
+ padId: 0,
54112
+ searchMinScore: .2
54113
+ });
54114
+ /**
54115
+ * SigLIP2 B/16-224 (D649). 768-d, so its OWN index; a 64-token Gemma
54116
+ * SentencePiece window padded with 0 (the hosted `tokenizer.json` lower-cases,
54117
+ * see `scripts/build-siglip2-model.py`). The floor is SIGLIP2_SEARCH_MIN_SCORE.
54118
+ */
54119
+ var SIGLIP2_META = {
54120
+ textModelId: "siglip2-b16-224-text",
54121
+ embeddingDim: 768,
54122
+ vectorIndex: "object-clip-siglip2-b16-224",
54123
+ tokenizerFile: SIGLIP2_TOKENIZER_FILE,
54124
+ contextLength: 64,
54125
+ padId: 0,
54126
+ searchMinScore: .1
54127
+ };
54128
+ /**
54129
+ * NO onnx vision builds, deliberately (2026-08-21). The int8 ONNX vision
54130
+ * exports were measured misaligned with the text encoders (matched image↔text
54131
+ * cosine ≈ 0.01 vs ≈ 0.22 for the fp16 openvino/coreml builds) — see the
54132
+ * catalog note in `addon-pipeline/.../model-catalogs.ts`. The image-encode leg
54133
+ * that consumed them here (`embeddingEncoder.encode` → PythonRawTensorEngine)
54134
+ * is retired with them: its only caller discarded the vector, and its
54135
+ * `preprocessForClip` applied OpenAI mean/std that MobileCLIP never used.
54136
+ * S0 was retired the same day (measured worst of the family on fleet crops).
54137
+ */
54138
+ var CLIP_IMAGE_MODELS = [
54139
+ {
54140
+ id: "mobileclip-s1",
54141
+ name: "MobileCLIP S1",
54142
+ description: "Apple MobileCLIP S1 — balanced vision encoder, 512-dim, 256×256 (fp16 OpenVINO/CoreML)",
54143
+ inputSize: {
54144
+ width: 256,
54145
+ height: 256
54146
+ },
54147
+ labels: [],
54148
+ inputNormalization: "none",
54149
+ clip: mobileclipMeta("mobileclip-s1-text"),
54150
+ formats: {
54151
+ openvino: ovFormat(hf("clip/mobileclip-s1/openvino/camstack-mobileclip-s1-vision.xml"), 55),
54152
+ coreml: {
54153
+ url: hf("clip/mobileclip-s1/coreml/camstack-mobileclip-s1-vision.mlpackage"),
54154
+ sizeMB: 65,
54155
+ isDirectory: true,
54156
+ files: [...MLPACKAGE_FILES],
54157
+ runtimes: ["python"]
54158
+ }
54159
+ }
54160
+ },
54161
+ {
54162
+ id: "mobileclip-s2",
54163
+ name: "MobileCLIP S2",
54164
+ description: "Apple MobileCLIP S2 — high-accuracy vision encoder, 512-dim, 256×256 (fp16 OpenVINO/CoreML)",
54165
+ inputSize: {
54166
+ width: 256,
54167
+ height: 256
54168
+ },
54169
+ labels: [],
54170
+ inputNormalization: "none",
54171
+ clip: mobileclipMeta("mobileclip-s2-text"),
54172
+ formats: {
54173
+ openvino: ovFormat(hf("clip/mobileclip-s2/openvino/camstack-mobileclip-s2-vision.xml"), 90),
54174
+ coreml: {
54175
+ url: hf("clip/mobileclip-s2/coreml/camstack-mobileclip-s2-vision.mlpackage"),
54176
+ sizeMB: 110,
54177
+ isDirectory: true,
54178
+ files: [...MLPACKAGE_FILES],
54179
+ runtimes: ["python"]
54180
+ }
54181
+ }
54182
+ },
54183
+ {
54184
+ id: "siglip2-b16-224",
54185
+ name: "SigLIP2 B/16",
54186
+ description: "Google SigLIP2 base, patch 16, 224×224 — Apache-2.0 vision encoder, 768-dim (fp16 OpenVINO/CoreML)",
54187
+ inputSize: {
54188
+ width: 224,
54189
+ height: 224
54190
+ },
54191
+ labels: [],
54192
+ inputNormalization: "none",
54193
+ license: "Apache-2.0",
54194
+ clip: SIGLIP2_META,
54195
+ formats: {
54196
+ openvino: ovFormat(hf("clip/siglip2/openvino/camstack-siglip2-b16-224-vision.xml"), 186),
54197
+ coreml: {
54198
+ url: hf("clip/siglip2/coreml/camstack-siglip2-b16-224-vision.mlpackage"),
54199
+ sizeMB: 185,
54200
+ isDirectory: true,
54201
+ files: [...MLPACKAGE_FILES],
54202
+ runtimes: ["python"]
54203
+ }
54204
+ }
54205
+ }
54206
+ ];
54207
+ /**
54208
+ * The int8 TEXT onnx encoders are healthy — unlike the retired int8 vision
54209
+ * exports. Verified 2026-08-21: the live search path (fp16 openvino vision
54210
+ * vectors ⋅ int8 onnx text queries) ranks correctly on the real index, and the
54211
+ * local cross-check aligns them with the fp16 vision space (cos ≈ 0.22 on
54212
+ * matched pairs).
54213
+ */
54214
+ var CLIP_TEXT_MODELS = [
54215
+ {
54216
+ id: "mobileclip-s1-text",
54217
+ name: "MobileCLIP S1 Text Encoder",
54218
+ description: "Text encoder for MobileCLIP S1, 512-dim, int8 quantized (61 MB)",
54219
+ inputSize: {
54220
+ width: 0,
54221
+ height: 0
54222
+ },
54223
+ labels: [],
54224
+ formats: {
54225
+ onnx: {
54226
+ url: hf("clip/mobileclip-s1/onnx/camstack-mobileclip-s1-text.onnx"),
54227
+ sizeMB: 61,
54228
+ files: [TOKENIZER_FILE]
54229
+ },
54230
+ openvino: ovFormat(hf("clip/mobileclip-s1/openvino/camstack-mobileclip-s1-text.xml"), 121)
54231
+ }
54232
+ },
54233
+ {
54234
+ id: "mobileclip-s2-text",
54235
+ name: "MobileCLIP S2 Text Encoder",
54236
+ description: "Text encoder for MobileCLIP S2, 512-dim, int8 quantized (61 MB)",
54237
+ inputSize: {
54238
+ width: 0,
54239
+ height: 0
54240
+ },
54241
+ labels: [],
54242
+ formats: {
54243
+ onnx: {
54244
+ url: hf("clip/mobileclip-s2/onnx/camstack-mobileclip-s2-text.onnx"),
54245
+ sizeMB: 61,
54246
+ files: [TOKENIZER_FILE]
54247
+ },
54248
+ openvino: ovFormat(hf("clip/mobileclip-s2/openvino/camstack-mobileclip-s2-text.xml"), 121)
54249
+ }
54250
+ },
54251
+ {
54252
+ id: "siglip2-b16-224-text",
54253
+ name: "SigLIP2 B/16 Text Encoder",
54254
+ description: "Text encoder for SigLIP2 B/16, 768-dim, fp16 (565 MB)",
54255
+ inputSize: {
54256
+ width: 0,
54257
+ height: 0
54258
+ },
54259
+ labels: [],
54260
+ license: "Apache-2.0",
54261
+ formats: {
54262
+ onnx: {
54263
+ url: hf("clip/siglip2/onnx/camstack-siglip2-b16-224-text.onnx"),
54264
+ sizeMB: 565,
54265
+ files: [SIGLIP2_TOKENIZER_FILE]
54266
+ },
54267
+ openvino: ovFormat(hf("clip/siglip2/openvino/camstack-siglip2-b16-224-text.xml"), 565)
54268
+ }
54269
+ }
54270
+ ];
54271
+ //#endregion
54272
+ //#region src/shared/clip/clip-model-registry.ts
54273
+ /** The model in force when nobody has chosen — the cluster row's default. */
54274
+ var DEFAULT_CLIP_MODEL = "mobileclip-s1";
54275
+ /**
54276
+ * Build a registry from catalog entries. Throws when two models share an index
54277
+ * at different dimensions: that is a catalog defect, and the vector store would
54278
+ * refuse the second model's writes one at a time, forever, at runtime.
54279
+ */
54280
+ function buildClipModelRegistry(entries) {
54281
+ const models = /* @__PURE__ */ new Map();
54282
+ const spaces = /* @__PURE__ */ new Map();
54283
+ for (const entry of entries) {
54284
+ const meta = entry.clip;
54285
+ if (meta === void 0) continue;
54286
+ models.set(entry.id, {
54287
+ modelId: entry.id,
54288
+ inputSize: entry.inputSize.width,
54289
+ meta
54290
+ });
54291
+ const existing = spaces.get(meta.vectorIndex);
54292
+ 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}`);
54293
+ spaces.set(meta.vectorIndex, {
54294
+ index: meta.vectorIndex,
54295
+ dim: meta.embeddingDim,
54296
+ modelIds: [...existing?.modelIds ?? [], entry.id]
54297
+ });
54298
+ }
54299
+ const all = [...spaces.values()];
54300
+ return {
54301
+ resolve: (modelId) => models.get(modelId) ?? null,
54302
+ spaceFor: (modelId) => {
54303
+ const model = models.get(modelId);
54304
+ return model === void 0 ? null : spaces.get(model.meta.vectorIndex) ?? null;
54305
+ },
54306
+ spaces: () => all
54307
+ };
54308
+ }
54309
+ /** The built-in catalog's registry. */
54310
+ var BUILTIN_CLIP_MODELS = buildClipModelRegistry(CLIP_IMAGE_MODELS);
54311
+ //#endregion
54312
+ export { NcRuleSchema as $, EventCategory as $n, isSourceCap as $t, LabelAttributionSchema as A, canonicalHash as An, audioMetricsCapability as At, NC_DEFAULT_SNOOZE_MINUTES as B, normalizeNodeId as Bn, embeddingRefusalOf as Bt, EMBEDDING_REQUIREMENTS_FAILED as C, systemEventFilterApplies as Cn, TimelapseRuleInputSchema as Ct, FIRST_LEVEL_MACRO_CLASSES as D, vectorDimFromBase64 as Dn, addonWidgetsSourceCapability as Dt, EVENT_OWNER_TYPES as E, templateVarsFor as En, TrackSourceSchema as Et, MOTION_CLOSE_AFTER_MS as F, customAction as Fn, deriveRecordingMode as Ft, NC_TAXONOMY as G, discriminatedUnion as Gn, evictionPolicyOfLocation as Gt, NC_SNOOZE_MAX_MINUTES as H, _enum as Hn, embeddingRequirementsUnavailableError as Ht, MediaFileKindEnum as I, defineCustomActions as In, describeSystemEventDeliveryProblem as It, NcAlarmSettingsPatchSchema as J, object as Jn, isDetectionMacroClass as Jt, NC_TEMPLATE_VARS as K, literal as Kn, faceGalleryCapability as Kt, NC_ALARM_SYSTEM_EVENT_KINDS as L, hydrateSchema as Ln, describeSystemEventFamilyProblem as Lt, MAX_ARCHIVED_DEBUG_NOTES as M, CamProfileSchema as Mn, buildEventKindDescriptor as Mt, MAX_BIRTH_DECISION_RECORDS as N, DeviceType as Nn, consumableLowPercentOf as Nt, FULL_IMAGE_BBOX as O, zoneAnalyticsCapability as On, alarmPanelCapability as Ot, MAX_BIRTH_LATENCY_PROXY_MS as P, createEvent as Pn, cosineSimilarity as Pt, NcRulePatchSchema as Q, unknown as Qn, isScheduleActive as Qt, NC_CONDITION_CATALOG as R, isDeviceScopedCap as Rn, embeddingEncoderCapability as Rt, EMBEDDING_MODEL_FAILED as S, systemEventFamilyProblems as Sn, TIMELAPSE_DENSE_FLOOR_SEC as St, EVENT_KIND_BY_CAP as T, templateCarriesSummary as Tn, TimelapseRuleSchema as Tt, NC_SYSTEM_EVENT_KIND_GROUP_SPECS as U, array as Un, encodeVectorBase64 as Ut, NC_SENSOR_TRANSITION_KINDS as V, sleep as Vn, embeddingRequirementsFailedError as Vt, NC_TANK_SYSTEM_EVENT_KINDS as W, boolean as Wn, evaluateSensorEdge as Wt, NcConditionsSchema as X, record as Xn, isKnownTemplateVar as Xt, NcConditionDescriptorSchema as Y, partialRecord as Yn, isEventOwnerType as Yt, NcRuleInputSchema as Z, string as Zn, isMediaOwnerType as Zt, DEFAULT_FIRST_SIGHTING_FRESHNESS_MS as _, sensorRaisedOf as _n, SCENE_CONFIRM_DEFAULT_TIMEOUT_MS as _t, CLIP_EMBEDDING_STEP_ID as a, notificationRulesCapability as an, NcSnoozeSuppressedSchema as at, DETECTION_PIPELINE_CAP_NAME as b, subKindsOf as bn, SCENE_DIVERGED as bt, resolveClusterModelPin as c, pipelineAnalyticsCapability as cn, NcTemplatePreviewInputSchema as ct, ArchivedDebugNoteSchema as d, readTimelapseGeneratedAt as dn, OpsLogEntrySchema as dt, isSystemDelivery as en, NcRuleTargetSchema as et, BaseDevice as f, resolveClipSearchMinScore as fn, PoolMemoryWatchdog as ft, DEFAULT_EVENT_COLOR as g, sceneMonitorCapability as gn, RetrainStatusSchema as gt, CoverStateSchema as h, ruleBelongsToAlarm as hn, RebuildObjectEmbeddingsRefusalSchema as ht, CLIP_TEXT_MODELS as i, mayWriteToLocation as in, NcSnoozeSchema as it, LockStateSchema as j, BaseAddon as jn, audioModeOf as jt, FailureCounters as k, errMsg as kn, assertTimelapseCadences as kt, AUDIO_MACRO_LABELS as l, plateGalleryCapability as ln, NcTemplatePreviewSchema as lt, COCO_TO_MACRO as m, resolvePoolMemoryPolicy as mn, RECORDING_SOURCE_CAMSTACK_ADDON as mt, DEFAULT_CLIP_MODEL as n, isVectorIndexDimConflict as nn, NcScheduleSchema as nt, FACE_EMBEDDING_STEP_ID as o, occupancyScope as on, NcSystemEventKindSchema as ot, BirthDecisionRecordSchema as p, resolveLocationMode as pn, RECORDING_EXPORT_MAX_READ_BYTES as pt, NcAlarmConfigSchema as q, number as qn, failureContributionCapability as qt, CLIP_IMAGE_MODELS as r, kebabToCamel as rn, NcSnoozeInputSchema as rt, readClusterModelPinStrict as s, parseProcStatus as sn, NcTaxonomySchema as st, BUILTIN_CLIP_MODELS as t, isSystemEventSummaryRule as tn, NcRuleUpdateInputSchema as tt, AlarmArmModeSchema as u, readDeviceStateFrom as un, NcTemplateVarDescriptorSchema as ut, DEFAULT_TIMELAPSE_PREVIEW_TEXT as v, servedTemplateVars as vn, SCENE_DEFAULT_ANCHOR_THRESHOLD as vt, EMBEDDING_REQUIREMENTS_UNAVAILABLE as w, systemEventSummaryScheduleOf as wn, TimelapseRulePatchSchema as wt, DeclaredDevices as x, systemEventDeliveryProblems as xn, SceneMonitorSchema as xt, DETECTION_MACRO_CLASSES as y, storageOccupancyCapability as yn, SCENE_DEFAULT_UNCOVERED_POLICY as yt, NC_CONSUMABLE_SYSTEM_EVENT_KINDS as z, nodePin as zn, embeddingModelFailedError as zt };