@camstack/addon-provider-rtsp 1.2.29 → 1.2.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/addon.js +1889 -1816
  2. package/dist/addon.mjs +1889 -1816
  3. package/package.json +1 -1
package/dist/addon.js CHANGED
@@ -16405,1760 +16405,1996 @@ var OauthIntegrationDescriptorSchema = object({
16405
16405
  });
16406
16406
  method(_void(), OauthIntegrationDescriptorSchema, { auth: "admin" });
16407
16407
  /**
16408
- * pipeline-analytics device-scoped wrapper cap. Refines raw
16409
- * per-frame detections emitted by the pipeline runner into tracked
16410
- * objects, per-kind event collections (motion / object / audio), and
16411
- * persisted media. Owns the post-detection domain end-to-end:
16412
- *
16413
- * runner emits PipelineInferenceResult
16414
- * ↓ (event bus)
16415
- * pipeline-analytics subscriber
16416
- * ↓ SORT tracker + zone engine + state analyzer + event emitter
16417
- * → three DB collections (one per kind), one FS media tree, one
16418
- * unified event emitter (FrameTracked + TrackStarted/Ended +
16419
- * DetectionEvent on bus)
16420
- *
16421
- * Pure subscriber model. No `processFrame` cap method — the runner
16422
- * already publishes the raw frame on the bus. The cap surface is
16423
- * only QUERIES + per-device settings, bound on/off via
16424
- * `device-manager.setWrapperActive`. `defaultActive: true` because
16425
- * every camera with a detection pipeline wants its raw detections
16426
- * refined; operators opt out per-device via BindingsTab when needed.
16427
- *
16428
- * Replaces the legacy `analysis-pipeline`, `analysis-data-persistence`
16429
- * (per-device surface) and `track-trail` caps — see P11 cleanup.
16408
+ * Reference to the frame's retained NATIVE surface + the parent crop's placement
16409
+ * within the frame, so the executor can re-cut a leaf child ROI at native
16410
+ * resolution on the detail plane. See the `runPipeline` `nativeCropRef` field.
16430
16411
  */
16431
- var TrackStateSchema = _enum([
16432
- "new",
16433
- "entered",
16434
- "left",
16435
- "moving",
16436
- "idle"
16437
- ]);
16438
- var EventKindSchema = _enum([
16439
- "motion",
16440
- "object",
16441
- "audio"
16442
- ]);
16412
+ var NativeCropRefSchema = object({
16413
+ /** Handle keying the retained native surface (node-pinned to its owner). */
16414
+ handle: FrameHandleSchema,
16415
+ /** The parent crop's padded/clamped rectangle in FRAME-space pixels. */
16416
+ cropFrameSpace: object({
16417
+ x: number(),
16418
+ y: number(),
16419
+ w: number(),
16420
+ h: number()
16421
+ })
16422
+ });
16423
+ object({
16424
+ crop: object({
16425
+ left: number(),
16426
+ top: number(),
16427
+ width: number().positive(),
16428
+ height: number().positive()
16429
+ }).optional(),
16430
+ content: object({
16431
+ width: number().int().positive(),
16432
+ height: number().int().positive()
16433
+ }),
16434
+ fit: _enum(["stretch", "contain"]),
16435
+ format: _enum([
16436
+ "rgb",
16437
+ "gray",
16438
+ "jpeg"
16439
+ ])
16440
+ });
16443
16441
  /**
16444
- * Spatial filter for `listTracks` the rect + polygon variants of the shared
16445
- * MaskShape vocabulary (see `mask-shape.ts`). Coordinates are NORMALIZED 0..1
16446
- * of the camera frame (top-left origin), matching the drawing-plane editor.
16442
+ * Process-local frame identity. It is serializable so it can ride an in-process
16443
+ * capability call, but `registryId` deliberately prevents resolution in any
16444
+ * other process or execution group.
16447
16445
  */
16448
- var TrackZoneFilterSchema = discriminatedUnion("kind", [MaskRectShapeSchema, MaskPolygonShapeSchema]);
16449
- /** Closed icon vocabulary so clients render a known glyph per kind. */
16450
- var EventKindIconSchema = _enum([
16451
- "motion",
16452
- "audio",
16453
- "person",
16454
- "vehicle",
16455
- "animal",
16456
- "door",
16457
- "pir",
16458
- "smoke",
16459
- "water",
16460
- "button",
16461
- "package",
16462
- "generic"
16446
+ var FrameRefSchema = object({
16447
+ registryId: string().min(1),
16448
+ id: string().min(1),
16449
+ width: number().int().positive(),
16450
+ height: number().int().positive(),
16451
+ format: _enum(["rgb", "gray"]),
16452
+ timestamp: number(),
16453
+ capturedAt: number().optional()
16454
+ });
16455
+ var ModelFormatSchema$1 = _enum([
16456
+ "onnx",
16457
+ "coreml",
16458
+ "openvino",
16459
+ "tflite",
16460
+ "pt",
16461
+ "gguf"
16463
16462
  ]);
16464
- var EventKindCategorySchema = _enum([
16465
- "motion",
16466
- "audio",
16467
- "detection",
16468
- "sensor",
16469
- "control",
16470
- "custom",
16471
- "package"
16463
+ var PipelineSlotSchema = _enum([
16464
+ "detector",
16465
+ "cropper",
16466
+ "classifier",
16467
+ "refiner",
16468
+ "audio-classifier"
16472
16469
  ]);
16473
- /** Taxonomy level — macro (timeline lane) vs sub (events-page leaf). */
16474
- var EventKindLevelSchema = _enum(["macro", "sub"]);
16475
- var EventKindDescriptorSchema = object({
16476
- /** Stable kind id (e.g. 'motion', 'vehicle', 'car', 'lock'). */
16477
- kind: string(),
16478
- /** i18n key resolved on the UI side; `label` is the English fallback. */
16479
- labelKey: string(),
16480
- /** English fallback label (kept for clients that don't translate). */
16481
- label: string(),
16482
- /** Hex color for timeline/legend rendering. */
16483
- color: string(),
16484
- /** Dictionary id → lucide component on the UI side. */
16485
- iconId: string(),
16486
- /** Legacy closed-vocab glyph — fallback for `iconId`. */
16487
- icon: EventKindIconSchema,
16488
- category: EventKindCategorySchema,
16489
- /** Macro parent for this kind ('car' → 'vehicle'); null for a macro. */
16490
- parentKind: string().nullable(),
16491
- /** Derived from `parentKind`, explicit for the client tree. */
16492
- level: EventKindLevelSchema,
16493
- /** Which cap + device contributes this kind. For built-ins the camera
16494
- * itself; for sensor kinds the LINKED source device. */
16495
- source: object({
16496
- capName: string(),
16497
- deviceId: number()
16498
- })
16470
+ var PipelineEngineChoiceSchema = object({
16471
+ runtime: _enum(["node", "python"]),
16472
+ backend: string(),
16473
+ format: ModelFormatSchema$1,
16474
+ device: string().optional()
16499
16475
  });
16500
- /** One camera's event vocabulary, as returned by `listEventKindsBatch`. */
16501
- var EventKindsForDeviceSchema = object({
16502
- deviceId: number(),
16503
- kinds: array(EventKindDescriptorSchema).readonly()
16476
+ var AvailableEngineSchema = object({
16477
+ engine: PipelineEngineChoiceSchema,
16478
+ devices: array(object({
16479
+ id: string(),
16480
+ label: string(),
16481
+ description: string().optional()
16482
+ })).readonly(),
16483
+ defaultDevice: string()
16504
16484
  });
16505
- var SensorEventSchema = object({
16485
+ var PipelineDefaultStepSchema = lazy(() => object({
16486
+ addonId: string(),
16487
+ addonName: string(),
16488
+ slot: PipelineSlotSchema,
16489
+ inputClasses: array(string()).readonly(),
16490
+ outputClasses: array(string()).readonly(),
16491
+ enabled: boolean(),
16492
+ modelId: string(),
16493
+ children: array(PipelineDefaultStepSchema).readonly(),
16494
+ group: string().optional(),
16495
+ settings: record(string(), unknown()).optional()
16496
+ }));
16497
+ var PipelineTemplateStepSchema = lazy(() => object({
16498
+ addonId: string(),
16499
+ enabled: boolean(),
16500
+ modelId: string(),
16501
+ children: array(PipelineTemplateStepSchema).readonly(),
16502
+ settings: record(string(), unknown()).optional()
16503
+ }));
16504
+ var PipelineTemplateSchema$1 = object({
16506
16505
  id: string(),
16507
- /** The CAMERA the event is attributed to (a sensor linked to N cameras
16508
- * yields N rows, one per camera). */
16509
- deviceId: number(),
16510
- /** The linked sensor device whose state changed. */
16511
- sourceDeviceId: number(),
16512
- /** Event kind id — matches an `EventKindDescriptor.kind`. */
16513
- kind: string(),
16514
- /** Snapshot of the sensor cap's runtime-state slice at the change. */
16515
- value: record(string(), unknown()).nullable(),
16516
- timestamp: number()
16506
+ name: string(),
16507
+ createdAt: string(),
16508
+ updatedAt: string(),
16509
+ engine: PipelineEngineChoiceSchema,
16510
+ steps: array(PipelineTemplateStepSchema).readonly()
16517
16511
  });
16518
- var TrackPositionSchema = object({
16519
- x: number(),
16520
- y: number(),
16521
- timestamp: number(),
16522
- bbox: BoundingBoxSchema
16512
+ var PipelineModelOptionSchema = object({
16513
+ id: string(),
16514
+ name: string(),
16515
+ formats: record(string(), object({
16516
+ downloaded: boolean(),
16517
+ sizeMB: number()
16518
+ })),
16519
+ group: ModelVariantGroupSchema.optional(),
16520
+ legacy: boolean().optional(),
16521
+ provider: ModelProviderIdSchema.optional()
16523
16522
  });
16524
- var TrackSnapshotSchema = object({
16525
- timestamp: number(),
16526
- position: TrackPositionSchema,
16527
- /** MediaStore key; resolve via `getTrackMedia({ trackId })`. */
16528
- mediaKey: string()
16523
+ var ConfigFieldBridge = custom();
16524
+ var PipelineAddonSchemaSchema = object({
16525
+ id: string(),
16526
+ name: string(),
16527
+ slot: PipelineSlotSchema,
16528
+ inputClasses: array(string()).readonly(),
16529
+ outputClasses: array(string()).readonly(),
16530
+ childSlots: array(PipelineSlotSchema).readonly(),
16531
+ models: array(PipelineModelOptionSchema).readonly(),
16532
+ defaultModelId: string(),
16533
+ defaultModelIdByFormat: record(string(), string()).optional(),
16534
+ enabledByDefault: boolean().optional(),
16535
+ backfillIntoExistingOverrides: boolean().optional(),
16536
+ defaultConfidence: number(),
16537
+ group: string().optional(),
16538
+ configSchema: array(ConfigFieldBridge).readonly().optional()
16529
16539
  });
16530
- /**
16531
- * Normalized 0..1 trajectory envelope (min/max over every position bbox,
16532
- * divided by the track's detection-frame dims), computed at persist time.
16533
- * Absent when the frame dims were unknown when the track was persisted
16534
- * (legacy rows / dims-less sources) and on active (in-RAM) tracks.
16535
- */
16536
- var TrackEnvelopeSchema = object({
16537
- minX: number(),
16538
- minY: number(),
16539
- maxX: number(),
16540
- maxY: number()
16540
+ var PipelineSlotSchemaSchema = object({
16541
+ id: PipelineSlotSchema,
16542
+ label: string(),
16543
+ priority: number(),
16544
+ parentSlot: PipelineSlotSchema.nullable(),
16545
+ addons: array(PipelineAddonSchemaSchema).readonly()
16541
16546
  });
16542
- /**
16543
- * Row projection for track list queries. `full` (default) returns the
16544
- * complete Track including the frame-rate `positions[]` history and the
16545
- * `snapshots[]` references — megabytes across a page of tracks. `slim`
16546
- * keeps every scalar the list surfaces actually render (ids, class(es),
16547
- * label / audioLabels / importance enrichment, firstSeen/lastSeen, state,
16548
- * zonesVisited, bestEventId, envelope, hasFace, hasEmbeddedFace, hasRider) and returns `positions` /
16549
- * `snapshots` as EMPTY arrays — detail views re-fetch the full row via
16550
- * `getTrack`. Mirrors the event-store `projection` convention
16551
- * (`getObjectEvents` et al.).
16552
- */
16553
- var TrackProjectionSchema = _enum(["full", "slim"]);
16554
- /**
16555
- * One audio-classification label heard on the track's camera while the
16556
- * track was alive, aggregated per label. An "episode" is one persisted
16557
- * audio event (the confident-classification path: score ≥ the device's
16558
- * `classificationMinScore`, class-change-or-heartbeat coalesced) — NOT
16559
- * one 32 ms inference chunk, so counts stay human-scaled.
16560
- */
16561
- var TrackAudioLabelSchema = object({
16562
- label: string(),
16563
- /** Highest classification score observed across the label's episodes. */
16564
- peakScore: number(),
16565
- /** Number of coalesced audio-event episodes carrying this label. */
16566
- count: number(),
16567
- firstAt: number(),
16568
- lastAt: number()
16547
+ var PipelineSchemaSchema = object({
16548
+ availableEngines: array(AvailableEngineSchema).readonly(),
16549
+ selectedEngine: PipelineEngineChoiceSchema,
16550
+ slots: array(PipelineSlotSchemaSchema).readonly()
16569
16551
  });
16570
- /**
16571
- * How a track was produced. `pipeline` (default / absent) = the spatial
16572
- * detection+tracking pipeline. Every OTHER value is a SYNTHETIC projection —
16573
- * no positions, a single snapshot, and no bbox trajectory at all:
16574
- *
16575
- * - `sensor` — a linked sensor/control device state change.
16576
- * - `audio` — an audio event on the camera itself that was anomalous for
16577
- * THAT camera, loud, and heard while nothing visual was happening (D62).
16578
- *
16579
- * The spatial subsystems (tracker association, occupancy count, re-id /
16580
- * embedding, resurrection) MUST skip every synthetic source. Test for that
16581
- * with `isSpatialTrack`, which allow-lists `pipeline` — a `!== 'sensor'`
16582
- * check silently readmits every source added after it was written.
16583
- */
16584
- var TrackSourceSchema = _enum([
16585
- "pipeline",
16586
- "sensor",
16587
- "audio"
16588
- ]);
16589
- /**
16590
- * Where a track sits in the RETRAIN lifecycle (D81).
16591
- *
16592
- * - `none` never marked, or un-marked. Evictable.
16593
- * - `staging`the operator wants this track as training material and has not
16594
- * finished with it. **This is the only state retention holds**: the track and
16595
- * everything it owns (object events, crops, keyframes, CLIP vector) survive
16596
- * the device's age window.
16597
- * - `trained` — the retrain page has taken what it needed. The frames it chose
16598
- * were COPIED into the retrain dataset at selection time, so the dataset no
16599
- * longer depends on the track's media and the track becomes EVICTABLE again.
16600
- * Terminal for the plain `markForTrain` toggle: returning it to `staging` is
16601
- * a deliberate action of the retrain page, not a side effect of a checkbox.
16602
- *
16603
- * There is no `null`. The state is stored `TEXT NOT NULL DEFAULT 'none'` because
16604
- * the store's filter language has only positive equality and `whereIn` — no
16605
- * negation, no IS NULL — so a NULL would be unselectable by ANY predicate and
16606
- * would make the entire pre-column history immortal in one deploy.
16607
- */
16608
- var RetrainStatusSchema = _enum([
16609
- "none",
16610
- "staging",
16611
- "trained"
16612
- ]);
16613
- /**
16614
- * Per-track OPERATOR flags — set by hand from the admin UI or the viewer, never
16615
- * by the pipeline. Spread into `TrackSchema` and `KeyEventSchema` from one place
16616
- * so the two surfaces cannot drift.
16617
- *
16618
- * **Absent ≠ false.** A track that has never been touched omits the field; an
16619
- * explicitly un-flagged track carries `false`. Legacy rows written before the
16620
- * columns existed read as absent, and a consumer that needs a boolean should say
16621
- * `flag === true`, not `flag !== false`.
16622
- *
16623
- * `markForTrain` is the WIRE FACE of {@link RetrainStatusSchema}, not a column:
16624
- * it is exactly `retrainStatus === 'staging'`, in both directions. Writing
16625
- * `true` moves `none → staging`, writing `false` moves `staging → none`, and a
16626
- * `trained` track reports `false` while refusing both writes. The boolean is
16627
- * kept because three surfaces drive a toggle off it; anything that needs to tell
16628
- * "never marked" from "already trained" must read `retrainStatus`.
16629
- *
16630
- * `debug` does NOT pin; it is attention, not durability.
16631
- *
16632
- * `favourited` IS a BOOLEAN pin (durability bit), not a retrain lifecycle.
16633
- * A favourited track is skipped by retention the same way `staging` is, but
16634
- * it does not enter `none|staging|trained` and has no staging budget.
16635
- */
16636
- var TrackFlagFields = {
16637
- /** Operator marked this track as training material — i.e. `retrainStatus` is
16638
- * `'staging'`. */
16639
- markForTrain: boolean().optional(),
16640
- /** Operator marked this track for diagnostic attention. */
16641
- debug: boolean().optional(),
16642
- /** Operator favourited this track. Pins it against pruning. */
16643
- favourited: boolean().optional()
16644
- };
16645
- /**
16646
- * The lifecycle field itself, on the READ surfaces only (`Track`, `KeyEvent`).
16647
- * Deliberately NOT part of {@link TrackFlagFields}: that group also builds the
16648
- * write patch, and the status is not something the toggle sets — it is what the
16649
- * toggle's boolean is derived from. Absent on an in-RAM track never touched;
16650
- * always present on a persisted row (the column default materialises `'none'`).
16651
- */
16652
- var TrackRetrainFields = { retrainStatus: RetrainStatusSchema.optional() };
16653
- /**
16654
- * The write half: a PARTIAL patch. An omitted key is left untouched, so setting
16655
- * one flag can never clear the other — the toggles are independent and are
16656
- * driven from three surfaces that do not know about each other.
16657
- */
16658
- var TrackFlagsPatchSchema = object(TrackFlagFields);
16659
- /**
16660
- * The resolved flag state after a write. Both fields are REQUIRED here (absent
16661
- * collapses to `false`) so a caller can drive a toggle's checked state off the
16662
- * mutation result without a re-fetch.
16663
- */
16664
- var TrackFlagsSchema = object({
16665
- trackId: string(),
16666
- markForTrain: boolean(),
16667
- debug: boolean(),
16668
- favourited: boolean(),
16669
- /** The lifecycle state the boolean was derived from. Required here (unlike on
16670
- * a track row) because this shape is only ever produced by the write body,
16671
- * which always knows it — and a surface that has just written needs to render
16672
- * `trained` without a re-fetch. */
16673
- retrainStatus: RetrainStatusSchema
16552
+ var EngineProvisioningSchema = object({
16553
+ runtimeId: _enum([
16554
+ "onnx",
16555
+ "openvino",
16556
+ "coreml",
16557
+ "edgetpu"
16558
+ ]).nullable(),
16559
+ device: string().nullable(),
16560
+ state: _enum([
16561
+ "idle",
16562
+ "installing",
16563
+ "verifying",
16564
+ "ready",
16565
+ "failed"
16566
+ ]),
16567
+ progress: number().optional(),
16568
+ error: string().optional(),
16569
+ nextRetryAt: number().optional(),
16570
+ /**
16571
+ * Gate A (config-correctness gate at engine change): human-readable
16572
+ * config issues surfaced EAGERLY when the node's engine changes — model
16573
+ * substitutions ("chose X, running Y") and zero-build steps ("no model
16574
+ * has a <format> build"). Additive/optional: informational only, never
16575
+ * enforced here `assertEngineReady` (readiness) still gates inference.
16576
+ * Absent/empty when the node-default tree resolves cleanly.
16577
+ */
16578
+ configIssues: array(string()).optional()
16674
16579
  });
16675
- union([literal(1), literal(2)]);
16676
- /**
16677
- * WHO decided a label, and when. Carried per tier so a value can be traced to
16678
- * the step and model that produced it — which is what makes the write rule
16679
- * arguable after the fact ("why is 592's label `dog` and not `Canis lupus`?")
16680
- * and what lets a migrated, UNATTRIBUTED value be told apart from a real one.
16681
- *
16682
- * `stepId` is the pipeline step id (`animal-classifier`, `bird-classifier`,
16683
- * `plate-ocr`, `face-embedding`, `object-detection`), or the sentinel
16684
- * `migration:4g` for a value the 4g migration moved from the single-slot era —
16685
- * that value has no provenance, and the write rule lets ANY properly-attributed
16686
- * write of the same tier replace it regardless of score.
16687
- */
16688
- var LabelAttributionSchema = object({
16689
- stepId: string(),
16580
+ var PipelineStepInputSchema = lazy(() => object({
16581
+ addonId: string(),
16690
16582
  modelId: string().optional(),
16691
- decidedAt: number(),
16583
+ enabled: boolean().default(true),
16584
+ children: array(PipelineStepInputSchema).optional(),
16585
+ settings: record(string(), unknown()).optional(),
16586
+ jumpDeviceKey: string().optional()
16587
+ }));
16588
+ var ModelSubstitutionSchema = object({
16589
+ addonId: string(),
16590
+ chosen: string(),
16591
+ running: string(),
16592
+ format: string()
16593
+ });
16594
+ var PipelineValidationIssueSchema = object({
16595
+ addonId: string(),
16596
+ kind: _enum(["unknown-addon", "no-format-build"]),
16597
+ detail: string()
16598
+ });
16599
+ var PipelineValidationResultSchema = object({
16600
+ ok: boolean(),
16601
+ issues: array(PipelineValidationIssueSchema).readonly(),
16602
+ substitutions: array(ModelSubstitutionSchema).readonly(),
16603
+ /** The node's `currentEngine.format` this validation ran against. */
16604
+ format: string()
16605
+ });
16606
+ var ReferenceImageEntrySchema = object({
16607
+ filename: string(),
16608
+ stepIds: array(string()).readonly().optional()
16609
+ });
16610
+ var ReferenceImageBodySchema = object({
16611
+ base64: string(),
16612
+ filename: string()
16613
+ });
16614
+ var ReferenceAudioEntrySchema = object({
16615
+ filename: string(),
16616
+ sizeKb: number()
16617
+ });
16618
+ var ReferenceAudioBodySchema = object({ base64: string() });
16619
+ var AudioBackendSchema = object({
16620
+ id: string(),
16621
+ name: string(),
16622
+ description: string(),
16623
+ available: boolean(),
16692
16624
  /**
16693
- * The GALLERY id behind a recognised tier-2 label — a face-gallery
16694
- * `Identity.id` or a plate-gallery `Vehicle.id` (both `randomUUID`).
16695
- *
16696
- * The text alone is a DISPLAY NAME, and a display name is renameable: a
16697
- * notification rule authored on "Gianluca" stopped matching the moment the
16698
- * operator fixed the spelling in the gallery, and nothing said so. The id is
16699
- * the thing that does not move, so it is what a rule matches on
16700
- * (`NcConditions.identities`) and the text is what a human is shown.
16701
- *
16702
- * Absent when the label names no gallery row — a plate the OCR read but no
16703
- * vehicle claims, a sub-class, a species, any tier-1 value.
16625
+ * Raw classifier labels this backend can emit (e.g. YAMNet's
16626
+ * 521-class set or Apple SoundAnalysis's 303-class set). Used by
16627
+ * the benchmark UI to populate the `enabledMicroClasses` filter
16628
+ * specific to the selected backend without a separate fetch.
16704
16629
  */
16705
- identityId: string().optional()
16630
+ rawLabels: array(string()).readonly().optional()
16631
+ });
16632
+ var AudioCapabilitiesSchema = object({
16633
+ activeBackend: string(),
16634
+ availableBackends: array(AudioBackendSchema).readonly(),
16635
+ sampleRate: number(),
16636
+ chunkDurationMs: number()
16637
+ });
16638
+ var DownloadModelResultSchema = object({
16639
+ filePath: string(),
16640
+ sizeMB: number(),
16641
+ durationMs: number()
16706
16642
  });
16707
16643
  /**
16708
- * The TIERED label model (roadmap 4g), spread into `TrackSchema` and
16709
- * `ObjectEventSchema` from ONE place so the two surfaces cannot drift — a
16710
- * track and its events always answer the same question the same way.
16711
- *
16712
- * Two scalar columns, not an array: every consumer wants "the coarse one" or
16713
- * "the fine one", and an array made both a scan. `label` is tier 1, `subLabel`
16714
- * is tier 2, and each carries its own score + attribution.
16715
- *
16716
- * **Reading it.** What a human should be shown is `subLabel ?? label` — the
16717
- * finest thing known. Before 4g the single `label` column held the finest
16718
- * value, so a consumer that has not been updated reads the tier-1 slot and
16719
- * shows nothing on a species-only row; that is why the migration puts every
16720
- * pre-4g value in tier 2 (it cannot regress a display that reads the fallback)
16721
- * and why the read surfaces were changed in the same train.
16722
- *
16723
- * **Writing it.** The slots are independent, which is the whole point: a
16724
- * tier-1 write (`bird`) can never overwrite a tier-2 value (`Turdus
16725
- * migratorius`), so fineness cannot regress by construction. Within a tier the
16726
- * higher score wins. One rule, one implementation — see
16727
- * `pipeline/label-tier.ts` in addon-post-analysis.
16728
- */
16729
- var TieredLabelFields = {
16730
- /** Tier 1 — the sub-class. See {@link LabelTierSchema}. */
16731
- label: string().optional(),
16732
- /** Confidence of the tier-1 value, as reported by the deciding step. */
16733
- labelScore: number().optional(),
16734
- /** Provenance of the tier-1 value. See {@link LabelAttributionSchema}. */
16735
- labelMeta: LabelAttributionSchema.optional(),
16736
- /** Tier 2 — the instance. See {@link LabelTierSchema}. */
16737
- subLabel: string().optional(),
16738
- /** Confidence of the tier-2 value, as reported by the deciding step. */
16739
- subLabelScore: number().optional(),
16740
- /** Provenance of the tier-2 value. See {@link LabelAttributionSchema}. */
16741
- subLabelMeta: LabelAttributionSchema.optional()
16742
- };
16743
- /** Per-camera slice of a training-export estimate. */
16744
- var TrainingExportDeviceTotalsSchema = object({
16745
- deviceId: number(),
16746
- tracks: number().int(),
16747
- files: number().int(),
16748
- bytes: number().int()
16749
- });
16750
- /**
16751
- * What a training export WOULD contain. Computed from media index rows only —
16752
- * no blob is read to produce this.
16644
+ * Wrapper carrying a single test run's result. Replaces the legacy
16645
+ * ad-hoc `{labels: [{className, originalClass, score}]}` shape with the
16646
+ * canonical `AudioResult` from the Phase 6 output rework: one
16647
+ * `AudioDetection` per class above `minScore`, top-N candidates in
16648
+ * `debug.alternateLabels['audio-classifier']`, per-source timings in
16649
+ * `debug.stepTimings`. The outer `success`/`error` fields stay so the
16650
+ * benchmark UI can still report a clean failure when the classifier
16651
+ * cap isn't available.
16753
16652
  */
16754
- var TrainingExportSummarySchema = object({
16755
- generatedAt: number(),
16756
- trackCount: number().int(),
16757
- fileCount: number().int(),
16758
- byteCount: number().int(),
16759
- /** More marked tracks exist than a single pass carries. */
16760
- truncated: boolean(),
16761
- devices: array(TrainingExportDeviceTotalsSchema).readonly()
16653
+ var AudioTestResultSchema = object({
16654
+ success: boolean(),
16655
+ error: string().optional(),
16656
+ frame: custom().optional()
16762
16657
  });
16763
- var TrackSchema = object({
16764
- trackId: string(),
16765
- deviceId: number(),
16766
- className: string(),
16767
- ...TieredLabelFields,
16768
- producingDeviceName: string().optional(),
16769
- /** Track provenance. Absent `pipeline` (legacy rows). */
16770
- source: TrackSourceSchema.optional(),
16771
- firstSeen: number(),
16772
- lastSeen: number(),
16773
- /** Frame-rate position history (subject to maxPositionHistory cap). */
16774
- positions: array(TrackPositionSchema).readonly(),
16775
- /** Periodic snapshots at snapshotIntervalMs cadence (subject to
16776
- * saveThumbnails policy). */
16777
- snapshots: array(TrackSnapshotSchema).readonly(),
16778
- /** Deduplicated zones the track has entered at least once. Zone IDS. */
16779
- zonesVisited: array(string()).readonly(),
16658
+ var PipelineConfigBridge = custom();
16659
+ var ConfigUISchemaBridge = custom();
16660
+ var ConfigUISchemaNullableBridge = custom();
16661
+ var InferenceCapabilitiesBridge = custom();
16662
+ var ModelAvailabilityListBridge = custom();
16663
+ var PipelineRunResultBridge = custom();
16664
+ method(_void(), array(PipelineEngineChoiceSchema)), method(_void(), PipelineEngineChoiceSchema), method(PipelineEngineChoiceSchema, array(PipelineDefaultStepSchema)), method(object({ nodeId: string() }), EngineProvisioningSchema), method(_void(), record(string(), object({
16665
+ modelId: string(),
16666
+ settings: record(string(), unknown()).readonly()
16667
+ }))), method(object({ steps: record(string(), object({
16668
+ modelId: string(),
16669
+ settings: record(string(), unknown()).readonly()
16670
+ })) }), object({ success: literal(true) }), {
16671
+ kind: "mutation",
16672
+ auth: "admin"
16673
+ }), method(object({ nodeId: string() }), object({
16674
+ success: literal(true),
16675
+ clearedDevices: number()
16676
+ }), {
16677
+ kind: "mutation",
16678
+ auth: "admin"
16679
+ }), method(object({ nodeId: string() }), object({ unhealthy: array(object({
16680
+ /** `<backend>:<device>`, e.g. `openvino:gpu`. */
16681
+ deviceKey: string(),
16780
16682
  /**
16781
- * Human NAMES for {@link zonesVisited}, resolved at READ time against the
16782
- * `zones` capability.
16783
- *
16784
- * `zonesVisited` persists ids (`cfeec78c-8d69-…`), which no operator can type
16785
- * and no card can render — so every free-text search surface was structurally
16786
- * unable to answer "show me the tracks in Uscio", and did not fail loudly, it
16787
- * just returned nothing. Resolving here rather than in each client keeps ONE
16788
- * derivation and costs the clients no extra call (the `zones` cap is
16789
- * per-device, so a client-side resolve would be a per-camera fan-out on a
16790
- * surface built to avoid exactly that).
16791
- *
16792
- * Resolved, never invented: a zone deleted since the track was written has no
16793
- * name and is DROPPED, so this array can be shorter than `zonesVisited` — the
16794
- * two are not positionally aligned. Absent when the track visited no zone, or
16795
- * when the zone catalogue could not be read.
16683
+ * `failed` the per-device restart budget is exhausted; no pool
16684
+ * will be spawned until an operator re-arms it or the runner
16685
+ * respawns. `backoff` — under budget, waiting out the backoff (or
16686
+ * a cached pool observed dead and not yet condemned).
16796
16687
  */
16797
- zoneNames: array(string()).readonly().optional(),
16798
- /** Deduplicated set of detector classes observed for this track over its
16799
- * life (a track may be reclassified, e.g. person→vehicle). Absent on
16800
- * legacy rows written before class accumulation shipped. */
16801
- classes: array(string()).readonly().optional(),
16802
- /** Cumulative normalized distance travelled (0..1 units = full frame width). */
16803
- totalDistance: number(),
16804
- state: TrackStateSchema,
16805
- active: boolean(),
16806
- /** Deterministic key-event importance score in [0,1] (server-computed at
16807
- * track expiry, recomputed on late label). Absent on legacy rows written
16808
- * before scoring shipped — consumers degrade to absence / compute-on-read. */
16809
- importance: number().optional(),
16810
- /** Id of the track's highest-confidence ObjectEvent (its representative
16811
- * "best" frame). Absent when the track produced no object events. */
16812
- bestEventId: string().optional(),
16813
- /** Tag of the importance sub-signal that dominated the score
16814
- * (identity|dwell|proximity|class|confidence|travel|zone). */
16815
- importanceReason: string().optional(),
16816
- /** Audio-classification labels heard on the camera during the track's
16817
- * life (score ≥ device `classificationMinScore`), aggregated per label.
16818
- * Absent on legacy rows / tracks with no confident audio. */
16819
- audioLabels: array(TrackAudioLabelSchema).readonly().optional(),
16820
- /** Normalized 0..1 trajectory envelope (see {@link TrackEnvelopeSchema}).
16821
- * Populated from the persisted envelope columns on historical reads;
16822
- * absent on legacy rows, dims-less tracks and active (in-RAM) tracks. */
16823
- envelope: TrackEnvelopeSchema.optional(),
16688
+ state: _enum(["failed", "backoff"]),
16689
+ /** Epoch ms of the death that produced this state. */
16690
+ since: number(),
16691
+ /** Pool deaths inside the current window. */
16692
+ deaths: number(),
16693
+ /** The last death's message. */
16694
+ lastError: string()
16695
+ })).readonly() })), method(object({
16696
+ nodeId: string(),
16697
+ deviceKey: string()
16698
+ }), object({ rearmed: boolean() }), {
16699
+ kind: "mutation",
16700
+ auth: "admin"
16701
+ }), method(_void(), PipelineSchemaSchema), method(_void(), array(PipelineDefaultStepSchema).readonly().nullable()), method(_void(), PipelineConfigBridge), method(_void(), ConfigUISchemaBridge), method(object({ steps: array(PipelineStepInputSchema) }), PipelineValidationResultSchema), method(_void(), array(PipelineTemplateSchema$1).readonly()), method(object({
16702
+ name: string(),
16703
+ steps: array(PipelineTemplateStepSchema).readonly(),
16704
+ engine: PipelineEngineChoiceSchema
16705
+ }), PipelineTemplateSchema$1, { kind: "mutation" }), method(object({
16706
+ id: string(),
16707
+ name: string().optional(),
16708
+ steps: array(PipelineTemplateStepSchema).readonly().optional()
16709
+ }), PipelineTemplateSchema$1, { kind: "mutation" }), method(object({ id: string() }), _void(), { kind: "mutation" }), method(_void(), InferenceCapabilitiesBridge), method(object({ addonId: string() }), ModelAvailabilityListBridge), method(object({
16710
+ addonId: string(),
16711
+ modelId: string(),
16712
+ format: ModelFormatSchema$1
16713
+ }), DownloadModelResultSchema, { kind: "mutation" }), method(object({
16714
+ addonId: string(),
16715
+ modelId: string(),
16716
+ format: ModelFormatSchema$1
16717
+ }), object({ success: literal(true) }), { kind: "mutation" }), method(object({
16718
+ engine: PipelineEngineChoiceSchema.optional(),
16719
+ steps: array(PipelineStepInputSchema).min(1),
16720
+ frame: FrameInputSchema.optional(),
16824
16721
  /**
16825
- * A face DETECTOR found a face on this track — nothing more. It says the
16826
- * detail plane produced a `face` detail; it does NOT say the face was
16827
- * embedded, matched, above `minFacePx`, or that the recognizer was even
16828
- * enabled. Set once and never cleared.
16829
- *
16830
- * **This exists so "face present but not recognised" is expressible.** A
16831
- * recognised identity lands in `subLabel` (attributed to the face chain via
16832
- * `subLabelMeta.stepId`), so before this field a track with an unmatched face
16833
- * and a track with no face at all were byte-identical on the wire and no
16834
- * surface could tell them apart. The read is `hasFace === true && subLabel
16835
- * === undefined`.
16836
- *
16837
- * **Absent ≠ false.** Every row written before the column existed omits it,
16838
- * and so does every server that predates the field — a consumer must test
16839
- * `=== true` and render nothing otherwise, never infer "no face".
16722
+ * Process-local lazy frame. Valid only when caller and provider resolve
16723
+ * in the same execution-group process; split/cross-node callers use
16724
+ * `frame`/`image` inline compatibility instead.
16840
16725
  */
16841
- hasFace: boolean().optional(),
16726
+ frameRef: FrameRefSchema.optional(),
16842
16727
  /**
16843
- * This track has a face row IN THE GALLERY: a crop **and** an embedding a
16844
- * face an operator could ASSIGN to an identity.
16845
- *
16846
- * The STRICT twin of {@link hasFace}, and the pair only earns its keep
16847
- * because the two disagree. `hasFace` is stamped at the TOP of the face
16848
- * branch, before every gate, and means no more than "a face detector produced
16849
- * a face detail". This one is stamped at the single moment the gallery row
16850
- * LANDS — after `FaceRecognizer.onTrackEnd` successfully persists it, i.e.
16851
- * past the embedding-magnitude verdict, the `minFacePx` detection gate, the
16852
- * candidate gate, the imageless-track drop (no crop was ever captured) and
16853
- * the crop-store drop. Everything between the detector and that insert can
16854
- * legitimately refuse the face, so a flag written any earlier promises the
16855
- * operator something to assign and delivers nothing.
16856
- *
16857
- * **Independent of recognition.** A face collected but never auto-matched is
16858
- * still assignable — it is in fact the face an operator most wants to reach —
16859
- * so this is NOT gated on `recognizedIdentityId`. Recognition lands in
16860
- * `subLabel`; this says only that the raw material exists.
16861
- *
16862
- * **Set once, never cleared.** A track that produced a gallery row produced
16863
- * one; deleting the row later is the gallery's business, not this flag's.
16864
- *
16865
- * **Absent ≠ false**, the same rule as {@link hasFace}: every row written
16866
- * before the column omits it, and so does every server that predates the
16867
- * field. A consumer must test `=== true` and render nothing otherwise —
16868
- * never infer "no assignable face".
16728
+ * CB5 shm passthrough a `FrameHandle` naming the same ring slot
16729
+ * the decoded pixels live in. One more member of the one-of
16730
+ * frame/frameHandle/image/imageBase64/referenceImage group.
16869
16731
  */
16870
- hasEmbeddedFace: boolean().optional(),
16732
+ frameHandle: FrameHandleSchema.optional(),
16733
+ imageBase64: string().optional(),
16871
16734
  /**
16872
- * This subject CONTAINS a folded rider a person the rider-pairing step
16873
- * ([D34](../decisions/adr-0034.md)) removed from the frame BEFORE the tracker,
16874
- * so the passage is tracked once and as a VEHICLE.
16875
- *
16876
- * It exists because the fold's record was dishonest. D34 and the code both
16877
- * said "the person is not lost — it is reported so both entities stay on the
16878
- * record"; in fact the pair went into a per-processor RAM field behind an
16879
- * accessor nobody called, and every durable surface said `vehicle`, full
16880
- * stop. This is the composition note that makes the row true.
16881
- *
16882
- * A COMPOSITION, never a class and never a label. "This vehicle contains a
16883
- * person" is not an answer to "what is this" — both label tiers would refuse
16884
- * a macro token anyway (D89), and correctly. Nothing here changes what the
16885
- * subject IS: a cyclist stays one vehicle track, occupancy still counts one,
16886
- * and a `person` rule still does not fire for someone cycling past.
16887
- *
16888
- * **Absent ≠ false**, exactly like {@link hasFace}: every row written before
16889
- * the column, and every hub that predates the field, omits it. Test
16890
- * `=== true` and render nothing otherwise — never infer "no rider".
16735
+ * Binary JPEG bytespreferred over `imageBase64` on internal
16736
+ * hops (hub forked worker via Moleculer MsgPack) because it
16737
+ * skips the 33% base64 overhead + the per-call base64 decode on
16738
+ * the detection-pipeline worker. Callers can pass either; exactly
16739
+ * one of `frame`/`image`/`imageBase64`/`referenceImage` is required.
16891
16740
  */
16892
- hasRider: boolean().optional(),
16893
- ...TrackFlagFields,
16894
- ...TrackRetrainFields
16895
- });
16896
- var BaseEventFields = {
16897
- id: string(),
16898
- deviceId: number(),
16899
- timestamp: number()
16900
- };
16901
- var MotionEventSchema = object({
16902
- ...BaseEventFields,
16903
- kind: literal("motion"),
16904
- regionCount: number(),
16905
- /** Heavy JSON array omitted in slim projection. */
16906
- regions: array(object({
16907
- bbox: BoundingBoxSchema,
16908
- pixelCount: number(),
16909
- intensity: number()
16910
- })).readonly().optional(),
16911
- /** Omitted in slim projection. */
16912
- frameWidth: number().optional(),
16913
- /** Omitted in slim projection. */
16914
- frameHeight: number().optional(),
16915
- /** Populated by B5 (recording playback URL for this event). */
16916
- mediaUrl: string().optional()
16917
- });
16741
+ image: _instanceof(Uint8Array).optional(),
16742
+ referenceImage: string().optional(),
16743
+ deviceId: number().optional(),
16744
+ sessionId: string().optional(),
16745
+ /**
16746
+ * Execution plane. 'full' (default) runs the whole tree — benchmark,
16747
+ * reference-image, and detail-subtree calls. 'frame' is the live
16748
+ * per-frame dispatch: ONLY root-plane steps run; crop children
16749
+ * (inputClasses ≠ null) are skipped and served per-track via
16750
+ * pipelineRunner.runDetailSubtree (two-plane design).
16751
+ */
16752
+ plane: _enum(["full", "frame"]).optional(),
16753
+ /**
16754
+ * Inference-device selector (Phase 2 multi-device). Format
16755
+ * `<backend>:<device>` (e.g. `openvino:gpu`, `edgetpu:usb`, `cpu`).
16756
+ * Omitted ⇒ the runner's default device (current single-engine
16757
+ * behaviour). Selects WHICH device pool of the node runs the call.
16758
+ */
16759
+ deviceKey: string().optional(),
16760
+ /**
16761
+ * Two-plane NATIVE child-crop reference. Set by `runDetailSubtree` ONLY
16762
+ * when the parent crop was resolved from the frame's retained NATIVE
16763
+ * surface (a frameHandle HIT). Lets the executor re-cut a LEAF crop
16764
+ * child's ROI (plate-ocr, face-embedding, leaf classifiers) at native
16765
+ * resolution from that surface — the SAME quality path faces already
16766
+ * had — instead of the downscaled parent tile. `handle` keys the native
16767
+ * surface (node-pinned to its owner); `cropFrameSpace` is the parent
16768
+ * crop's padded/clamped rectangle in FRAME-space pixels, used to compose
16769
+ * the executor's crop-normalized child ROI back into frame-normalized
16770
+ * coordinates. Auxiliary to the image source (`image`/`frame`/…), NOT one
16771
+ * of the mutually-exclusive image inputs. Absent ⇒ tile-crop children
16772
+ * (today's behaviour on the fallback path).
16773
+ */
16774
+ nativeCropRef: NativeCropRefSchema.optional()
16775
+ }), PipelineRunResultBridge, { kind: "mutation" }), method(object({
16776
+ engine: PipelineEngineChoiceSchema.optional(),
16777
+ steps: array(PipelineStepInputSchema).min(1),
16778
+ frames: array(FrameInputSchema).min(1).max(255),
16779
+ deviceId: number().optional(),
16780
+ sessionId: string().optional(),
16781
+ /**
16782
+ * Pure-inference benchmark hint. A NONZERO uint32 pins every frame in
16783
+ * the batch to the Python pool's bench preprocess cache
16784
+ * (`_bench_frame_id`) so a REPEATED benchmark frame is decoded +
16785
+ * preprocessed ONCE and every later inference is a pure-inference cache
16786
+ * hit — the sustained-throughput run measures inference, not
16787
+ * decode+preprocess+infer. Omitted/0 for live frames (all different →
16788
+ * full preprocess every call, correct). Fresh per sustained run;
16789
+ * released via `uncacheFrame`.
16790
+ */
16791
+ frameId: number().int().nonnegative().optional(),
16792
+ /** Inference-device selector (Phase 2 multi-device); see runPipeline. */
16793
+ deviceKey: string().optional()
16794
+ }), object({ results: array(PipelineRunResultBridge).readonly() }), { kind: "mutation" }), method(object({
16795
+ data: _instanceof(Uint8Array),
16796
+ width: number().int().positive(),
16797
+ height: number().int().positive(),
16798
+ format: _enum([
16799
+ "rgb",
16800
+ "bgr",
16801
+ "gray"
16802
+ ])
16803
+ }), object({
16804
+ frameId: number(),
16805
+ width: number(),
16806
+ height: number()
16807
+ }), { kind: "mutation" }), method(object({
16808
+ stepId: string(),
16809
+ frameId: number().int()
16810
+ }), record(string(), unknown()), { kind: "mutation" }), method(object({ frameId: number().int() }), _void(), { kind: "mutation" }), method(_void(), object({
16811
+ batchMode: string(),
16812
+ windowMs: number(),
16813
+ maxBatchSize: number(),
16814
+ concurrency: number()
16815
+ })), method(_void(), array(object({
16816
+ engineKey: string(),
16817
+ engine: PipelineEngineChoiceSchema,
16818
+ modelsLoaded: array(string()).readonly(),
16819
+ inUseByCameras: array(number()).readonly(),
16820
+ /**
16821
+ * Origin of this resident factory.
16822
+ * - `runtime` — main camera-serving engine (no idle TTL).
16823
+ * - `warm-override` — benchmark/test override held in the warm
16824
+ * cache; auto-disposed after the idle TTL.
16825
+ * - `device-pool` — a concurrent per-device pool (Phase 2
16826
+ * multi-device, keyed by `deviceKey`) resolved
16827
+ * via `resolveDeviceFactory`. Runs alongside the
16828
+ * `runtime` engine on a DIFFERENT accelerator
16829
+ * (NPU / iGPU / Coral) — this is how the
16830
+ * Engines tab shows all pools running at once.
16831
+ */
16832
+ kind: _enum([
16833
+ "runtime",
16834
+ "warm-override",
16835
+ "device-pool"
16836
+ ]),
16837
+ /** Native pid of the underlying Python pool (null when no pool). */
16838
+ poolPid: number().nullable(),
16839
+ /** ms since this factory was last used (null when not warm-tracked). */
16840
+ idleMs: number().nullable(),
16841
+ /** Idle TTL after which `warm-override` factories self-evict (null when not applicable). */
16842
+ idleTtlMs: number().nullable()
16843
+ })).readonly()), method(object({ engine: PipelineEngineChoiceSchema }), object({ success: literal(true) }), {
16844
+ kind: "mutation",
16845
+ auth: "admin"
16846
+ }), method(object({
16847
+ engine: PipelineEngineChoiceSchema,
16848
+ force: boolean().optional()
16849
+ }), object({
16850
+ success: boolean(),
16851
+ reason: string().optional()
16852
+ }), {
16853
+ kind: "mutation",
16854
+ auth: "admin"
16855
+ }), method(_void(), array(ReferenceImageEntrySchema).readonly()), method(object({ filename: string() }), ReferenceImageBodySchema.nullable()), method(_void(), array(ReferenceAudioEntrySchema).readonly()), method(object({ filename: string() }), ReferenceAudioBodySchema.nullable()), method(_void(), AudioCapabilitiesSchema), method(object({
16856
+ addonId: string(),
16857
+ modelId: string(),
16858
+ filename: string().optional(),
16859
+ settings: record(string(), unknown()).optional()
16860
+ }), AudioTestResultSchema, { kind: "mutation" }), method(_void(), ConfigUISchemaNullableBridge);
16918
16861
  /**
16919
- * Which detection SOURCE produced an object event. `pipeline` = the ML
16920
- * detection pipeline (decoded-frame inference); `onboard` = the camera's
16921
- * native on-device AI. Both flow through the SAME analysis layers (zoning,
16922
- * tracking, per-kind persistence) but stay distinguishable so consumers
16923
- * (advanced-notifier, occupancy, …) can select which source(s) to act on.
16924
- * Absent on legacy rows treat as `pipeline`.
16862
+ * Per-stage gating mode applied to the zones a rule references.
16863
+ *
16864
+ * - `include`: the rule contributes to a **whitelist** for its stage.
16865
+ * When at least one `include` rule fires for a stage, only entities
16866
+ * inside one of those zones pass that stage.
16867
+ * - `exclude`: the rule contributes to a **blacklist** for its stage.
16868
+ * Entities inside one of those zones are dropped at that stage.
16869
+ *
16870
+ * `monitor`-style observation (count without filtering) is not a rule
16871
+ * mode — zones without any matching rule are observed naturally by
16872
+ * `zone-analytics` (live snapshot + history), so an "I just want to
16873
+ * count, not filter" use case needs no rule at all.
16925
16874
  */
16926
- var DetectionSourceSchema = _enum(["pipeline", "onboard"]);
16875
+ var ZoneRuleModeEnum = _enum(["include", "exclude"]);
16927
16876
  /**
16928
- * The confirmed zone crossing that produced an object event. Present ONLY on
16929
- * an event emitted BY a crossing (`zone.enter` / `zone.exit`); a movement-state
16930
- * event (`object.entering` / `leaving` / `stationary` / `loitering`) and an
16931
- * appearance event carry none, so a rule asking for a direction fails closed
16932
- * on them.
16877
+ * Per-consumer rule that references existing zones (geometry) and
16878
+ * defines how a specific pipeline stage should treat them. Each
16879
+ * consumer addon owns its own `ZoneRule[]` array in its per-device
16880
+ * settings:
16933
16881
  *
16934
- * Exactly ONE crossing per event: the emitter turns each confirmed crossing
16935
- * into its own event, so a frame in which a track enters A while leaving B
16936
- * produces two events with two directions — never one ambiguous row.
16882
+ * - `addon-motion-wasm` `motionZoneRules: ZoneRule[]` (motion stage)
16883
+ * - `addon-detection-pipeline` `detectionZoneRules: ZoneRule[]` (detection stage)
16884
+ * - future: notification rules, audio gating, etc.
16937
16885
  *
16938
- * `zoneId` is load-bearing for an EXIT: the event's `zones` list is the
16939
- * membership the box has NOW, and by definition it no longer contains the zone
16940
- * that was just left. Without the id here, a zone-scoped rule could never match
16941
- * the exit it asked for.
16886
+ * One rule applies to N zones (`zoneIds[]`) so the operator can
16887
+ * express "ignore motion in ALL of {garden, street}" with a single
16888
+ * rule. `classFilter` narrows the rule to specific object classes
16889
+ * "drop person detections in the street, but keep cars" is one
16890
+ * `exclude` rule with `classFilter: ['person']`.
16891
+ *
16892
+ * `enabled` is a soft toggle — the operator can keep the rule
16893
+ * configured but inert without deleting it.
16942
16894
  */
16943
- var ZoneCrossingSchema = object({
16944
- direction: _enum(["enter", "exit"]),
16945
- /** Admin zone id crossed. */
16946
- zoneId: string(),
16947
- /** Zone display name at crossing time (falls back to the id). */
16948
- zoneName: string().optional()
16949
- });
16950
- var ObjectEventSchema = object({
16951
- ...BaseEventFields,
16952
- kind: literal("object"),
16953
- /** Detection source. Optional for backward-compat; absent ⇒ `pipeline`. */
16954
- source: DetectionSourceSchema.optional(),
16895
+ var ZoneRuleSchema = object({
16896
+ /** Stable rule id — survives edits, used by the UI for diffing. */
16897
+ id: string(),
16898
+ /** Optional human-readable label rendered in the rule editor. */
16899
+ name: string().optional(),
16900
+ /** Zones this rule targets. The rule's `mode` applies to ALL
16901
+ * listed zones (OR-set: a detection in any one of them counts).
16902
+ * At least one zone id required — a rule with no targets is a
16903
+ * configuration mistake and the form validator rejects it. */
16904
+ zoneIds: array(string()).min(1).readonly(),
16905
+ mode: ZoneRuleModeEnum,
16955
16906
  /**
16956
- * Inference-frame id shared by every object event emitted from the SAME frame
16957
- * the "scene/parent" key. Lets a consumer group co-occurring detections (e.g.
16958
- * 2 people + 1 dog) under one full frame, and link a track's frames over time
16959
- * (group by `trackId`, pick a representative `frameId` as the parent frame).
16960
- * Optional for backward-compat with pre-existing rows / the slim projection
16961
- * includes it (it is light). Absent on rows written before this field.
16907
+ * Class names this rule applies to. Empty / undefined rule
16908
+ * applies to every class. Class strings match the `macroClass`
16909
+ * field on detections (e.g. `person`, `car`, `dog`).
16962
16910
  */
16963
- frameId: string().optional(),
16964
- /** Omitted in slim projection. */
16965
- trackId: string().optional(),
16966
- className: string(),
16967
- ...TieredLabelFields,
16968
- /** Omitted in slim projection. */
16969
- confidence: number().optional(),
16970
- /** Heavy JSON — omitted in slim projection. */
16971
- bbox: BoundingBoxSchema.optional(),
16972
- /** Heavy JSON — omitted in slim projection. */
16973
- zones: array(string()).readonly().optional(),
16974
- /** Omitted in slim projection. */
16975
- state: TrackStateSchema.optional(),
16911
+ classFilter: array(string()).readonly().optional(),
16976
16912
  /**
16977
- * The zone crossing this event IS, when it is one. Absent on every other
16978
- * event kind (movement state, appearance, package) see
16979
- * {@link ZoneCrossingSchema}. Omitted in slim projection.
16913
+ * Minimum bbox/mask overlap (0–1) with any of the rule's zones
16914
+ * required to consider an entity "in the zone". Defaults to the
16915
+ * consumer's stage default when omitted. Kept for back-compat with
16916
+ * existing per-rule overrides; new operators pick the value via
16917
+ * `bboxInclusionPct` (operator-friendly 0–100). Whichever field is
16918
+ * set, the lower-level engine reads it as a 0–1 fraction.
16980
16919
  */
16981
- zoneCrossing: ZoneCrossingSchema.optional(),
16982
- /** Detection-frame dimensions in pixels — let consumers normalize the
16983
- * pixel-space `bbox` onto a displayed image. Omitted in slim projection. */
16984
- frameWidth: number().optional(),
16985
- frameHeight: number().optional(),
16986
- /** MediaStore key for the crop attached to this event (if any). */
16987
- mediaKey: string().optional(),
16988
- /** Design B: MediaStore key of the track's native-resolution key frame (the
16989
- * best-detection full frame). Resolve via the event-media data-plane
16990
- * (`/addon/<addonId>/event-media/<keyFrameMediaKey>`) for a detail view that
16991
- * draws `bbox` over the native frame. Absent on legacy rows / non-decoded
16992
- * sources — consumers fall back to `mediaKey` (the tight crop). */
16993
- keyFrameMediaKey: string().optional(),
16994
- /** Populated by B5 (recording playback URL for this event). */
16995
- mediaUrl: string().optional(),
16996
- /** The parent track's key-event importance [0,1], propagated to every object
16997
- * event of the track (so an event row can be sorted by importance without a
16998
- * track join). Absent on legacy rows / before the track was scored. */
16999
- importance: number().optional()
17000
- });
17001
- var AudioEventSchema = object({
17002
- ...BaseEventFields,
17003
- kind: literal("audio"),
17004
- rms: number(),
17005
- dbfs: number(),
17006
- classification: object({
17007
- className: string(),
17008
- originalClass: string().optional(),
17009
- score: number()
17010
- }).optional(),
17011
- /** Populated by B5 (recording playback URL for this event). */
17012
- mediaUrl: string().optional()
16920
+ overlapThreshold: number().min(0).max(1).optional(),
16921
+ /**
16922
+ * Operator-friendly version of `overlapThreshold` the percentage
16923
+ * of the detection's bbox that must lie inside the zone for the
16924
+ * rule to match. Documented default is 85%; the engine substitutes
16925
+ * that when the field is omitted (kept optional so existing rules
16926
+ * stored without it stay valid).
16927
+ *
16928
+ * When BOTH `overlapThreshold` and `bboxInclusionPct` are set on a
16929
+ * rule, the engine prefers `bboxInclusionPct` because it's the
16930
+ * field exposed in the UI. Internally both feed the same gate.
16931
+ */
16932
+ bboxInclusionPct: number().min(0).max(100).optional(),
16933
+ /**
16934
+ * When `true` and a detection has a segmentation mask, use the
16935
+ * mask for overlap instead of the bbox. Detection-stage only;
16936
+ * motion rules ignore this field.
16937
+ */
16938
+ preferMask: boolean().optional(),
16939
+ /**
16940
+ * Soft-toggle: `false` disables the rule without deleting it.
16941
+ * Defaults to `true` so operators creating a rule via the UI
16942
+ * see it active immediately.
16943
+ */
16944
+ enabled: boolean().default(true)
17013
16945
  });
17014
- var MediaFileKindEnum = _enum([
17015
- "crop",
17016
- "thumbnail",
17017
- "snapshot",
17018
- "firstFrame",
17019
- "lastFrame",
17020
- "fullFrame",
17021
- "fullFrameBoxed",
17022
- "faceCrop",
17023
- "plateCrop",
17024
- "keyFrame",
17025
- "keyFrameSmall",
17026
- "thumbnailSmall"
17027
- ]);
17028
- var MediaFileSchema = object({
17029
- key: string(),
17030
- kind: MediaFileKindEnum,
17031
- base64: string(),
17032
- sizeBytes: number(),
17033
- timestamp: number()
16946
+ array(ZoneRuleSchema).readonly();
16947
+ /**
16948
+ * Zone — pure geometry + identity. NO filtering behaviour.
16949
+ *
16950
+ * Zones describe **where** in the frame the operator wants to flag
16951
+ * something; consumer-owned {@link ZoneRule} arrays describe **how**
16952
+ * each pipeline stage uses them. Splitting the two means a single
16953
+ * polygon "Driveway" can simultaneously back a motion-exclude rule,
16954
+ * a detection-include rule on `['car']`, and an occupancy aggregate
16955
+ * — without three duplicated polygons.
16956
+ *
16957
+ * Owned by the orchestrator addon (provider) and mirrored into the
16958
+ * `zones` device-state slice on every mutation. Consumers
16959
+ * (motion-wasm, pipeline-executor, analytics, admin UI) read either
16960
+ * via `api.zones.listZones` (one-shot) or via `dev.state.zones` (live
16961
+ * mirror with `onChanged`).
16962
+ *
16963
+ * Coordinates are normalised fractions of the frame (0–1) so zones
16964
+ * survive resolution changes and stream profile switches.
16965
+ *
16966
+ * `kind` discriminates between full polygons (closed regions used
16967
+ * for intrusion / occupancy filters) and tripwires (open 2-point
16968
+ * line segments used for cross events). Onboard / firmware-reported
16969
+ * zones (Reolink, ONVIF) are out of scope for now — see the deferred
16970
+ * task list.
16971
+ */
16972
+ var ZoneKindEnum = _enum(["polygon", "tripwire"]);
16973
+ /** Polygon vertex in fraction-of-frame coordinates (0–1). */
16974
+ var PolygonPointSchema = object({
16975
+ x: number(),
16976
+ y: number()
16977
+ });
16978
+ /** A camera detection zone — pure geometry/identity. */
16979
+ var ZoneSchema = object({
16980
+ id: string(),
16981
+ name: string(),
16982
+ kind: ZoneKindEnum.default("polygon"),
16983
+ /** Polygon vertices, fraction of frame (0–1). */
16984
+ polygon: array(PolygonPointSchema).readonly(),
16985
+ /** Visual color for UI rendering. */
16986
+ color: string().default("#3b82f6")
17034
16987
  });
17035
16988
  /**
17036
- * One media row WITHOUT its bytes.
16989
+ * Zones capability per-camera CRUD over polygon detection zones.
17037
16990
  *
17038
- * A track's media is 5-8 MB of base64 (measured: 7.67 MB across 23 files for a
17039
- * 140 s track), and a client that renders tiles from the media data plane needs
17040
- * to know only WHAT EXISTS the bytes then arrive per tile, lazily, over HTTP
17041
- * with an immutable cache, instead of all at once inside a tRPC response that
17042
- * blocks the whole view.
16991
+ * Provider lives in `addon-pipeline-orchestrator` (hub-only). Persists
16992
+ * to per-device settings and mirrors into the `zones` device-state
16993
+ * slice on every mutation, so downstream consumers can subscribe via
16994
+ * `dev.state.zones.onChanged`.
17043
16995
  *
17044
- * `sizeBytes` is carried because it is what lets a client decide between the
17045
- * stored blob and a `?variant=thumb` rendering without fetching either.
16996
+ * The cap surface only handles geometry + identity; filtering
16997
+ * behaviour (per-class, include/exclude, threshold) lives in the
16998
+ * consumer addons' rule arrays — see `ZoneRuleSchema` exported from
16999
+ * `capabilities/schemas/zone-rule.js`.
17046
17000
  */
17047
- var MediaFileInfoSchema = MediaFileSchema.omit({ base64: true });
17001
+ var zonesCapability = {
17002
+ name: "zones",
17003
+ scope: "device",
17004
+ mode: "singleton",
17005
+ deviceTypes: [DeviceType.Camera],
17006
+ methods: {
17007
+ listZones: method(object({ deviceId: number() }), array(ZoneSchema).readonly()),
17008
+ addZone: method(object({
17009
+ deviceId: number(),
17010
+ zone: ZoneSchema
17011
+ }), _void(), {
17012
+ kind: "mutation",
17013
+ auth: "admin"
17014
+ }),
17015
+ removeZone: method(object({
17016
+ deviceId: number(),
17017
+ zoneId: string()
17018
+ }), _void(), {
17019
+ kind: "mutation",
17020
+ auth: "admin"
17021
+ }),
17022
+ updateZone: method(object({
17023
+ deviceId: number(),
17024
+ zone: ZoneSchema
17025
+ }), _void(), {
17026
+ kind: "mutation",
17027
+ auth: "admin"
17028
+ })
17029
+ },
17030
+ /**
17031
+ * Runtime-state slice — the live zone catalogue mirrored by the
17032
+ * orchestrator on every CRUD mutation. Consumers read via
17033
+ * `device.state.zones.value` / `.watch(...)` without round-tripping
17034
+ * the cap, and the codegen DeviceProxy auto-wires the reactive
17035
+ * handle. Slice shape is `{ zones: Zone[] }` so future extensions
17036
+ * (e.g. zone groupings) can sit alongside the polygon list.
17037
+ */
17038
+ runtimeState: object({ zones: array(ZoneSchema).readonly() }),
17039
+ /**
17040
+ * Runtime-state durability: **restored** — written only on operator mutation, so a camera that never had one has nothing to re-derive from. This is the slice `zone-mirror-hydration.ts` exists to paper over.
17041
+ *
17042
+ * See `RuntimeStateDurability`. Enforced by
17043
+ * `scripts/check-runtime-state-durability.ts`.
17044
+ */
17045
+ durability: "restored"
17046
+ };
17048
17047
  /**
17049
- * The MACRO tier of an annotation — a CLOSED set.
17048
+ * pipeline-analytics device-scoped wrapper cap. Refines raw
17049
+ * per-frame detections emitted by the pipeline runner into tracked
17050
+ * objects, per-kind event collections (motion / object / audio), and
17051
+ * persisted media. Owns the post-detection domain end-to-end:
17050
17052
  *
17051
- * This is what the exported detector predicts, so a typo here is a new class
17052
- * with one example in it. `label` and `subLabel` are open strings by contrast:
17053
- * the whole point of the page is teaching the model things it does not know
17054
- * yet, and constraining that vocabulary would make it useless.
17053
+ * runner emits PipelineInferenceResult
17054
+ * (event bus)
17055
+ * pipeline-analytics subscriber
17056
+ * SORT tracker + zone engine + state analyzer + event emitter
17057
+ * → three DB collections (one per kind), one FS media tree, one
17058
+ * unified event emitter (FrameTracked + TrackStarted/Ended +
17059
+ * DetectionEvent on bus)
17055
17060
  *
17056
- * A macro class is NEVER a label. The provider refuses a write whose `label` or
17057
- * `subLabel` is one of these values, in any casing, because once `person`
17058
- * exists in both tiers "every person box" stops being answerable without
17059
- * knowing every string anyone ever typed — and the damage is retroactive.
17061
+ * Pure subscriber model. No `processFrame` cap method the runner
17062
+ * already publishes the raw frame on the bus. The cap surface is
17063
+ * only QUERIES + per-device settings, bound on/off via
17064
+ * `device-manager.setWrapperActive`. `defaultActive: true` because
17065
+ * every camera with a detection pipeline wants its raw detections
17066
+ * refined; operators opt out per-device via BindingsTab when needed.
17067
+ *
17068
+ * Replaces the legacy `analysis-pipeline`, `analysis-data-persistence`
17069
+ * (per-device surface) and `track-trail` caps — see P11 cleanup.
17060
17070
  */
17061
- var RetrainMacroClassSchema = _enum([
17071
+ var TrackStateSchema = _enum([
17072
+ "new",
17073
+ "entered",
17074
+ "left",
17075
+ "moving",
17076
+ "idle"
17077
+ ]);
17078
+ var EventKindSchema = _enum([
17079
+ "motion",
17080
+ "object",
17081
+ "audio"
17082
+ ]);
17083
+ /**
17084
+ * Spatial filter for `listTracks` — the rect + polygon variants of the shared
17085
+ * MaskShape vocabulary (see `mask-shape.ts`). Coordinates are NORMALIZED 0..1
17086
+ * of the camera frame (top-left origin), matching the drawing-plane editor.
17087
+ */
17088
+ var TrackZoneFilterSchema = discriminatedUnion("kind", [MaskRectShapeSchema, MaskPolygonShapeSchema]);
17089
+ /** Closed icon vocabulary so clients render a known glyph per kind. */
17090
+ var EventKindIconSchema = _enum([
17091
+ "motion",
17092
+ "audio",
17062
17093
  "person",
17063
17094
  "vehicle",
17064
17095
  "animal",
17096
+ "door",
17097
+ "pir",
17098
+ "smoke",
17099
+ "water",
17100
+ "button",
17065
17101
  "package",
17066
- "face",
17067
- "plate"
17102
+ "generic"
17068
17103
  ]);
17069
- /** A subject to learn, or a phantom to unlearn (taught by OMISSION). */
17070
- var RetrainAnnotationKindSchema = _enum(["subject", "model_error"]);
17071
- /** Did a human draw this box, or did the assist propose it? */
17072
- var RetrainAnnotationSourceSchema = _enum(["operator", "assist"]);
17073
- /** Normalised `[0,1]` rectangle against the FULL frame — the canonical form. */
17074
- var RetrainBboxSchema = object({
17075
- x: number(),
17076
- y: number(),
17077
- w: number(),
17078
- h: number()
17104
+ var EventKindCategorySchema = _enum([
17105
+ "motion",
17106
+ "audio",
17107
+ "detection",
17108
+ "sensor",
17109
+ "control",
17110
+ "custom",
17111
+ "package"
17112
+ ]);
17113
+ /** Taxonomy level — macro (timeline lane) vs sub (events-page leaf). */
17114
+ var EventKindLevelSchema = _enum(["macro", "sub"]);
17115
+ var EventKindDescriptorSchema = object({
17116
+ /** Stable kind id (e.g. 'motion', 'vehicle', 'car', 'lock'). */
17117
+ kind: string(),
17118
+ /** i18n key resolved on the UI side; `label` is the English fallback. */
17119
+ labelKey: string(),
17120
+ /** English fallback label (kept for clients that don't translate). */
17121
+ label: string(),
17122
+ /** Hex color for timeline/legend rendering. */
17123
+ color: string(),
17124
+ /** Dictionary id → lucide component on the UI side. */
17125
+ iconId: string(),
17126
+ /** Legacy closed-vocab glyph — fallback for `iconId`. */
17127
+ icon: EventKindIconSchema,
17128
+ category: EventKindCategorySchema,
17129
+ /** Macro parent for this kind ('car' → 'vehicle'); null for a macro. */
17130
+ parentKind: string().nullable(),
17131
+ /** Derived from `parentKind`, explicit for the client tree. */
17132
+ level: EventKindLevelSchema,
17133
+ /** Which cap + device contributes this kind. For built-ins the camera
17134
+ * itself; for sensor kinds the LINKED source device. */
17135
+ source: object({
17136
+ capName: string(),
17137
+ deviceId: number()
17138
+ })
17079
17139
  });
17080
- /**
17081
- * One annotated subject.
17082
- *
17083
- * `bbox` is normalised against the full frame, ALWAYS. The per-model shapes
17084
- * (letterboxed root / zone-cropped package / subject-cropped classifier) are
17085
- * derived from it at export and never stored — storing them is how one feature
17086
- * space ends up holding two crops of the same subject (D52).
17087
- */
17088
- var RetrainAnnotationSchema = object({
17089
- id: string(),
17090
- trackId: string(),
17140
+ /** One camera's event vocabulary, as returned by `listEventKindsBatch`. */
17141
+ var EventKindsForDeviceSchema = object({
17091
17142
  deviceId: number(),
17092
- /** The COPY in retrain storage — never the source track's media key. */
17093
- mediaKey: string(),
17094
- bbox: RetrainBboxSchema,
17095
- macroClass: RetrainMacroClassSchema,
17096
- label: string().optional(),
17097
- subLabel: string().optional(),
17098
- kind: RetrainAnnotationKindSchema,
17099
- source: RetrainAnnotationSourceSchema,
17100
- /** Which model proposed this box — or, on a `model_error`, drew the phantom. */
17101
- assistModelId: string().optional(),
17102
- assistScore: number().optional(),
17103
- exportedInBatch: string().optional(),
17104
- createdAt: number()
17105
- });
17106
- /** The write form — the server owns `id`, `createdAt` and the frame binding. */
17107
- var RetrainAnnotationDraftSchema = RetrainAnnotationSchema.omit({
17108
- id: true,
17109
- trackId: true,
17110
- deviceId: true,
17111
- mediaKey: true,
17112
- createdAt: true,
17113
- exportedInBatch: true
17143
+ kinds: array(EventKindDescriptorSchema).readonly()
17114
17144
  });
17115
- /** A track sitting in `staging`, with everything the worklist needs to rank it. */
17116
- var RetrainTrackSchema = object({
17117
- trackId: string(),
17145
+ var SensorEventSchema = object({
17146
+ id: string(),
17147
+ /** The CAMERA the event is attributed to (a sensor linked to N cameras
17148
+ * yields N rows, one per camera). */
17118
17149
  deviceId: number(),
17119
- className: string(),
17120
- label: string().optional(),
17121
- firstSeen: number(),
17122
- lastSeen: number(),
17123
- /** How many frames the dataset already holds from this track. */
17124
- frameCount: number().int(),
17125
- /** How many subjects have been annotated on those frames. `0` with
17126
- * `frameCount: 0` is exactly "staging, still to work". */
17127
- annotationCount: number().int()
17150
+ /** The linked sensor device whose state changed. */
17151
+ sourceDeviceId: number(),
17152
+ /** Event kind id — matches an `EventKindDescriptor.kind`. */
17153
+ kind: string(),
17154
+ /** Snapshot of the sensor cap's runtime-state slice at the change. */
17155
+ value: record(string(), unknown()).nullable(),
17156
+ timestamp: number()
17128
17157
  });
17129
- /** A frame the picker may offer — an index row, no blob was read to produce it. */
17130
- var RetrainFrameCandidateSchema = object({
17131
- mediaKey: string(),
17132
- kind: MediaFileKindEnum,
17158
+ var TrackPositionSchema = object({
17159
+ x: number(),
17160
+ y: number(),
17133
17161
  timestamp: number(),
17134
- sizeBytes: number().int(),
17135
- /** A copy of this original already exists — selecting it is free and cannot
17136
- * fail, whatever became of the original. */
17137
- copied: boolean()
17138
- });
17139
- /** A frame the dataset OWNS: bytes copied at selection time. */
17140
- var RetrainFrameSchema = object({
17141
- frameId: string(),
17142
- deviceId: number(),
17143
- trackId: string(),
17144
- /** Provenance only. It may already point at nothing — that is expected. */
17145
- sourceMediaKey: string(),
17146
- sourceKind: MediaFileKindEnum,
17147
- sizeBytes: number().int(),
17148
- width: number().int(),
17149
- height: number().int(),
17150
- copiedAt: number()
17151
- });
17152
- /** Why a copy-on-select could not be honoured — named, never a silent skip. */
17153
- var RetrainCopyRefusalSchema = _enum([
17154
- "source-missing",
17155
- "unreadable-image",
17156
- "write-failed"
17157
- ]);
17158
- var RetrainFrameSelectionSchema = object({
17159
- copied: array(RetrainFrameSchema).readonly(),
17160
- refused: array(object({
17161
- sourceMediaKey: string(),
17162
- reason: RetrainCopyRefusalSchema
17163
- })).readonly()
17162
+ bbox: BoundingBoxSchema
17164
17163
  });
17165
- var RetrainFrameListSchema = object({
17166
- candidates: array(RetrainFrameCandidateSchema).readonly(),
17167
- copies: array(RetrainFrameSchema).readonly(),
17168
- /** What the page pre-selects the native key frame when one survives. */
17169
- autoPickMediaKey: string().optional()
17164
+ var TrackSnapshotSchema = object({
17165
+ timestamp: number(),
17166
+ position: TrackPositionSchema,
17167
+ /** MediaStore key; resolve via `getTrackMedia({ trackId })`. */
17168
+ mediaKey: string()
17170
17169
  });
17171
- /** What the operator asked the assist to look for. */
17172
- var RetrainAssistSubjectSchema = discriminatedUnion("kind", [object({
17173
- kind: literal("package"),
17174
- zone: RetrainBboxSchema.optional()
17175
- }), object({
17176
- kind: literal("objects"),
17177
- modelId: string(),
17178
- minScore: number().optional()
17179
- })]);
17180
17170
  /**
17181
- * The assist's answer a discriminated union, because "the model saw nothing"
17182
- * and "this node cannot run that model" lead to different next moves and a
17183
- * nullable result cannot tell them apart.
17171
+ * Normalized 0..1 trajectory envelope (min/max over every position bbox,
17172
+ * divided by the track's detection-frame dims), computed at persist time.
17173
+ * Absent when the frame dims were unknown when the track was persisted
17174
+ * (legacy rows / dims-less sources) and on active (in-RAM) tracks.
17184
17175
  */
17185
- var RetrainAssistResultSchema = discriminatedUnion("kind", [object({
17186
- kind: literal("proposed"),
17187
- modelId: string(),
17188
- stepId: string(),
17189
- minScore: number(),
17190
- /** Drafts, ready to edit. `source: 'assist'` until the operator touches one. */
17191
- proposals: array(RetrainAnnotationDraftSchema).readonly(),
17192
- /** Returned by the runner but removed by the threshold. */
17193
- belowThreshold: number().int()
17194
- }), object({
17195
- kind: literal("refused"),
17196
- /** `no-zone` is ours; the rest are the runner's own refusal vocabulary. */
17197
- reason: string(),
17198
- detail: string().optional()
17199
- })]);
17200
- /** The outcome of a lifecycle move owned by the retrain page. */
17201
- var RetrainTransitionResultSchema = object({
17202
- trackId: string(),
17203
- /** Where the track ended up, whatever happened. */
17204
- retrainStatus: RetrainStatusSchema,
17205
- /** `false` ⇒ the move was refused or was a no-op; `reason` says which. */
17206
- changed: boolean(),
17207
- reason: _enum([
17208
- "unknown-track",
17209
- "no-frames-copied",
17210
- "not-staging",
17211
- "not-trained",
17212
- "unchanged"
17213
- ]).optional()
17214
- });
17215
- var DEFAULT_EVENT_QUERY_LIMIT = 1e3;
17216
- var MAX_EVENT_QUERY_LIMIT = 5e3;
17217
- var DeviceEventQueryInput = object({
17218
- deviceId: number(),
17219
- since: number().optional(),
17220
- until: number().optional(),
17221
- limit: number().int().min(1).max(MAX_EVENT_QUERY_LIMIT).default(DEFAULT_EVENT_QUERY_LIMIT),
17222
- /** `slim` drops heavy JSON fields (regions/bbox/zones) and carries an
17223
- * optional `mediaUrl` (populated by B5). `full` (default) keeps today's
17224
- * exact behaviour. Callers may omit this field — the store defaults to
17225
- * `full` when not provided. */
17226
- projection: _enum(["full", "slim"]).optional()
17227
- });
17228
- var ObjectEventQueryInput = DeviceEventQueryInput.extend({ classFilter: string().optional() });
17229
- var RecentTracksQueryInput = object({
17230
- /** Devices to merge. An empty array yields `{ tracks: [], nextCursor: null }`. */
17231
- deviceIds: array(number()),
17232
- /** Window lower bound on `lastSeen` (inclusive). */
17233
- since: number().optional(),
17234
- /** Window upper bound on `lastSeen` (inclusive). */
17235
- until: number().optional(),
17236
- /** Page size. Default 200, max 1000. */
17237
- limit: number().int().min(1).max(1e3).default(200),
17238
- /** Opaque continuation cursor from a previous page's `nextCursor`.
17239
- * Encodes the (lastSeen, trackId) sort position — treat as opaque. */
17240
- cursor: string().optional(),
17241
- /** See {@link TrackProjectionSchema}. Default `full`. */
17242
- projection: TrackProjectionSchema.optional(),
17243
- /** Include stationary-promoted rows (parked objects). Default false: the
17244
- * feed lists passages; parking records live on the stationary registry. */
17245
- includeStationary: boolean().optional()
17246
- });
17247
- var RecentTracksPageSchema = object({
17248
- /** Merged page, ordered by (`lastSeen` DESC, `trackId` DESC). */
17249
- tracks: array(TrackSchema).readonly(),
17250
- /** Cursor for the next page, or null when this page is the last. */
17251
- nextCursor: string().nullable()
17252
- });
17253
- var LIST_GROUPS_DEFAULT_LIMIT = 40;
17254
- var LIST_GROUPS_MAX_LIMIT = 100;
17255
- var AnalyticsGroupRecordSchema = object({
17256
- id: string(),
17257
- deviceId: number().int(),
17258
- openedAt: number().int(),
17259
- closedAt: number().int(),
17260
- timestamp: number().int(),
17261
- memberCount: number().int(),
17262
- memberTrackIds: array(string()).readonly(),
17263
- className: string(),
17264
- classes: array(string()).readonly(),
17265
- /** Relative event-media path, or null when the group has no picture yet. */
17266
- mediaUrl: string().nullable(),
17267
- singleton: boolean()
17176
+ var TrackEnvelopeSchema = object({
17177
+ minX: number(),
17178
+ minY: number(),
17179
+ maxX: number(),
17180
+ maxY: number()
17268
17181
  });
17269
- var AnalyticsGroupMemberSchema = object({
17270
- trackId: string(),
17271
- deviceId: number().int(),
17272
- className: string(),
17273
- firstSeen: number().int(),
17274
- lastSeen: number().int(),
17275
- mediaUrl: string().nullable()
17276
- });
17277
- var AnalyticsGroupDetailSchema = AnalyticsGroupRecordSchema.extend({ members: array(AnalyticsGroupMemberSchema).readonly() });
17278
- var ListGroupsQueryInput = object({
17279
- /** Devices to merge. An empty array yields `{ groups: [], nextCursor: null }`. */
17280
- deviceIds: array(number()),
17281
- /** Window lower bound on `closedAt` (inclusive). */
17282
- since: number().optional(),
17283
- /** Window upper bound on `openedAt` (inclusive). */
17284
- until: number().optional(),
17285
- limit: number().int().min(1).max(LIST_GROUPS_MAX_LIMIT).default(LIST_GROUPS_DEFAULT_LIMIT),
17286
- /** Opaque continuation cursor from a previous page's `nextCursor`. */
17287
- cursor: string().optional()
17288
- });
17289
- var ListGroupsPageSchema = object({
17290
- groups: array(AnalyticsGroupRecordSchema).readonly(),
17291
- nextCursor: string().nullable()
17292
- });
17293
- var KeyEventQueryInput = object({
17294
- deviceId: number(),
17295
- /** Window lower bound (track firstSeen ≥ since). */
17296
- since: number(),
17297
- /** Window upper bound (track firstSeen ≤ until). */
17298
- until: number(),
17299
- limit: number().int().min(1).max(200).default(50),
17300
- /** Drop tracks scoring below this importance. */
17301
- minImportance: number().min(0).max(1).optional(),
17302
- /** Restrict to a single class (e.g. 'person'). */
17303
- classFilter: string().optional()
17304
- });
17305
- var KeyEventSchema = object({
17306
- /** The representative event id (the track's best ObjectEvent, else its trackId). */
17307
- id: string(),
17308
- trackId: string(),
17309
- /** Track start time (firstSeen). */
17310
- timestamp: number(),
17311
- className: string(),
17312
- ...TieredLabelFields,
17313
- importance: number(),
17314
- /** Highest-confidence ObjectEvent id for the track (empty when none). */
17315
- bestEventId: string(),
17316
- /** Track lifetime in ms (lastSeen - firstSeen). */
17317
- windowMs: number().optional(),
17318
- ...TrackFlagFields,
17319
- ...TrackRetrainFields
17320
- });
17321
- object({
17322
- trackId: string(),
17323
- className: string(),
17324
- confidence: number(),
17325
- bbox: BoundingBoxSchema,
17326
- zones: array(string()).readonly(),
17327
- state: TrackStateSchema
17328
- });
17329
- var OverlayDetectionSchema = looseObject({
17330
- id: string(),
17331
- kind: _enum(["first-level", "detail"]),
17332
- macroClass: string(),
17333
- score: number(),
17334
- bbox: object({
17335
- x: number(),
17336
- y: number(),
17337
- width: number(),
17338
- height: number()
17339
- }),
17340
- labels: array(looseObject({
17341
- label: string(),
17342
- score: number()
17343
- })).readonly(),
17344
- parentId: string().optional()
17345
- });
17346
- var ScoredObjectEventSchema = ObjectEventSchema.extend({ score: number() });
17347
- var SearchObjectEventsInput = object({
17348
- text: string(),
17349
- deviceId: number().optional(),
17350
- since: number().optional(),
17351
- until: number().optional(),
17352
- classFilter: string().optional(),
17353
- limit: number().default(50),
17354
- minScore: number().min(0).max(1).default(.2)
17355
- });
17356
- var TrackCascadeCountsSchema = object({
17357
- /** Persisted track roots deleted (authoritative). */
17358
- tracks: number().int(),
17359
- /** Object events removed with their tracks (best-effort; see note above). */
17360
- events: number().int(),
17361
- /** Track/face/plate-owned media removed (best-effort). Never identity media. */
17362
- media: number().int(),
17363
- /** Unassigned (non-enrolled) face reads removed (best-effort). */
17364
- faces: number().int(),
17365
- /** Unassigned plate reads removed (best-effort; plate leg deferred to plate-intelligence). */
17366
- plates: number().int(),
17367
- /** Per-track CLIP search vectors removed (best-effort). */
17368
- embeddings: number().int(),
17369
- /** Group membership + group rows removed with their last member (best-effort). */
17370
- groups: number().int()
17371
- });
17372
- /** Disk-wins reconcile: media rows whose blobs are gone, then empty tracks. */
17373
- var DiskReconcileCountsSchema = object({
17374
- mediaDropped: number().int(),
17375
- tracks: number().int(),
17376
- events: number().int()
17377
- });
17378
- /** Event-store footprint for one camera. */
17379
- var EventStoreDeviceFootprintSchema = object({
17380
- deviceId: number(),
17381
- /** Persisted event rows (motion + object + audio) for the camera. */
17382
- rows: number().int(),
17383
- /** Event-owned media bytes on disk for the camera. */
17384
- bytes: number().int()
17385
- });
17386
- /** Aggregate event-store footprint: global totals + per-camera breakdown. */
17387
- var EventStoreFootprintSchema = object({
17388
- totalRows: number().int(),
17389
- totalBytes: number().int(),
17390
- devices: array(EventStoreDeviceFootprintSchema).readonly()
17391
- });
17392
- /** Per-kind counts returned by the event-prune / device-delete mutations. */
17393
- var EventPruneCountsSchema = object({
17394
- motion: number().int(),
17395
- object: number().int(),
17396
- audio: number().int()
17182
+ /**
17183
+ * Row projection for track list queries. `full` (default) returns the
17184
+ * complete Track including the frame-rate `positions[]` history and the
17185
+ * `snapshots[]` references — megabytes across a page of tracks. `slim`
17186
+ * keeps every scalar the list surfaces actually render (ids, class(es),
17187
+ * label / audioLabels / importance enrichment, firstSeen/lastSeen, state,
17188
+ * zonesVisited, bestEventId, envelope, hasFace, hasEmbeddedFace, hasRider) and returns `positions` /
17189
+ * `snapshots` as EMPTY arrays — detail views re-fetch the full row via
17190
+ * `getTrack`. Mirrors the event-store `projection` convention
17191
+ * (`getObjectEvents` et al.).
17192
+ */
17193
+ var TrackProjectionSchema = _enum(["full", "slim"]);
17194
+ /**
17195
+ * One audio-classification label heard on the track's camera while the
17196
+ * track was alive, aggregated per label. An "episode" is one persisted
17197
+ * audio event (the confident-classification path: score ≥ the device's
17198
+ * `classificationMinScore`, class-change-or-heartbeat coalesced) — NOT
17199
+ * one 32 ms inference chunk, so counts stay human-scaled.
17200
+ */
17201
+ var TrackAudioLabelSchema = object({
17202
+ label: string(),
17203
+ /** Highest classification score observed across the label's episodes. */
17204
+ peakScore: number(),
17205
+ /** Number of coalesced audio-event episodes carrying this label. */
17206
+ count: number(),
17207
+ firstAt: number(),
17208
+ lastAt: number()
17397
17209
  });
17398
17210
  /**
17399
- * Re-embed stored tracks from their key frames.
17211
+ * How a track was produced. `pipeline` (default / absent) = the spatial
17212
+ * detection+tracking pipeline. Every OTHER value is a SYNTHETIC projection —
17213
+ * no positions, a single snapshot, and no bbox trajectory at all:
17400
17214
  *
17401
- * The reason this is an operator-callable method and not a migration script:
17402
- * every knob that decides what a vector MEANS encoder model, crop margin,
17403
- * squaring is only changeable if the existing vectors can be regenerated.
17404
- * Mixing feature spaces in one index makes cosine scores incomparable, and the
17405
- * symptom is a quality regression with no visible cause.
17215
+ * - `sensor` a linked sensor/control device state change.
17216
+ * - `audio` an audio event on the camera itself that was anomalous for
17217
+ * THAT camera, loud, and heard while nothing visual was happening (D62).
17218
+ *
17219
+ * The spatial subsystems (tracker association, occupancy count, re-id /
17220
+ * embedding, resurrection) MUST skip every synthetic source. Test for that
17221
+ * with `isSpatialTrack`, which allow-lists `pipeline` — a `!== 'sensor'`
17222
+ * check silently readmits every source added after it was written.
17406
17223
  */
17407
- var RebuildObjectEmbeddingsInput = object({
17408
- /** Restrict to one camera. Omit for the whole fleet. */
17409
- deviceId: number().optional(),
17410
- since: number().optional(),
17411
- until: number().optional(),
17412
- /** Stop after this many tracks; the result reports whether more remain. */
17413
- maxTracks: number().int().positive().optional(),
17414
- /**
17415
- * Run every embedding on THIS node instead of round-robining the fleet.
17416
- *
17417
- * Named `executeOnNodeId` and not `nodeId` on purpose: an inline `nodeId`
17418
- * field in cap args is read by `parent-unowned-call.ts` as a ROUTING PIN, so
17419
- * calling it that would pin the rebuild REQUEST itself to that node — the
17420
- * rebuild orchestration lives on the hub, and only the per-track step runs
17421
- * remotely. This field is data; the per-track pin is applied inside.
17422
- *
17423
- * Absent ⇒ round-robin over every online node whose runner can serve the
17424
- * pinned model.
17425
- */
17426
- executeOnNodeId: string().optional(),
17427
- /**
17428
- * Milliseconds to wait between tracks; omit for the built-in default, `0` to
17429
- * run flat out.
17430
- *
17431
- * A rebuild is bulk maintenance on hub-main's single thread. Measured
17432
- * 2026-08-06, an unpaced pass held that thread busy 82.2 s out of 120 and
17433
- * pushed `nodes.topology` from 0.25 s to 26 s for 43 minutes. The value in
17434
- * force is logged at start and finish so a deliberately slow pass reads
17435
- * differently from a stalled one.
17436
- */
17437
- pacingMs: number().int().nonnegative().optional()
17438
- });
17224
+ var TrackSourceSchema = _enum([
17225
+ "pipeline",
17226
+ "sensor",
17227
+ "audio"
17228
+ ]);
17439
17229
  /**
17440
- * Result of emptying the CLIP index.
17230
+ * Where a track sits in the RETRAIN lifecycle (D81).
17441
17231
  *
17442
- * The clean slate before a policy change: a new crop margin or encoder model
17443
- * leaves two feature spaces in one index whose cosine scores are not
17444
- * comparable, so wiping and rebuilding is the only way to be sure every vector
17445
- * means the same thing.
17232
+ * - `none` never marked, or un-marked. Evictable.
17233
+ * - `staging` the operator wants this track as training material and has not
17234
+ * finished with it. **This is the only state retention holds**: the track and
17235
+ * everything it owns (object events, crops, keyframes, CLIP vector) survive
17236
+ * the device's age window.
17237
+ * - `trained` — the retrain page has taken what it needed. The frames it chose
17238
+ * were COPIED into the retrain dataset at selection time, so the dataset no
17239
+ * longer depends on the track's media and the track becomes EVICTABLE again.
17240
+ * Terminal for the plain `markForTrain` toggle: returning it to `staging` is
17241
+ * a deliberate action of the retrain page, not a side effect of a checkbox.
17242
+ *
17243
+ * There is no `null`. The state is stored `TEXT NOT NULL DEFAULT 'none'` because
17244
+ * the store's filter language has only positive equality and `whereIn` — no
17245
+ * negation, no IS NULL — so a NULL would be unselectable by ANY predicate and
17246
+ * would make the entire pre-column history immortal in one deploy.
17446
17247
  */
17447
- var WipeObjectEmbeddingsResultSchema = object({ deleted: number() });
17248
+ var RetrainStatusSchema = _enum([
17249
+ "none",
17250
+ "staging",
17251
+ "trained"
17252
+ ]);
17448
17253
  /**
17449
- * Acknowledgement that a rebuild STARTED.
17254
+ * Per-track OPERATOR flags set by hand from the admin UI or the viewer, never
17255
+ * by the pipeline. Spread into `TrackSchema` and `KeyEventSchema` from one place
17256
+ * so the two surfaces cannot drift.
17450
17257
  *
17451
- * The pass costs ~1s per track 45 minutes for a 2,600-track fleet so it
17452
- * runs detached and this returns immediately. Waiting for it made the client
17453
- * time out while the work carried on server-side, which is the worst of both:
17454
- * no result and no way to know it was still going. Poll
17455
- * `getObjectEmbeddingRebuildStatus` for progress.
17258
+ * **Absent false.** A track that has never been touched omits the field; an
17259
+ * explicitly un-flagged track carries `false`. Legacy rows written before the
17260
+ * columns existed read as absent, and a consumer that needs a boolean should say
17261
+ * `flag === true`, not `flag !== false`.
17262
+ *
17263
+ * `markForTrain` is the WIRE FACE of {@link RetrainStatusSchema}, not a column:
17264
+ * it is exactly `retrainStatus === 'staging'`, in both directions. Writing
17265
+ * `true` moves `none → staging`, writing `false` moves `staging → none`, and a
17266
+ * `trained` track reports `false` while refusing both writes. The boolean is
17267
+ * kept because three surfaces drive a toggle off it; anything that needs to tell
17268
+ * "never marked" from "already trained" must read `retrainStatus`.
17269
+ *
17270
+ * `debug` does NOT pin; it is attention, not durability.
17271
+ *
17272
+ * `favourited` IS a BOOLEAN pin (durability bit), not a retrain lifecycle.
17273
+ * A favourited track is skipped by retention the same way `staging` is, but
17274
+ * it does not enter `none|staging|trained` and has no staging budget.
17456
17275
  */
17457
- var RebuildObjectEmbeddingsResultSchema = object({
17458
- started: boolean(),
17459
- /** True when a pass was already running; the new request is ignored. */
17460
- alreadyRunning: boolean()
17461
- });
17462
- var RebuildStatusSchema = object({
17463
- running: boolean(),
17464
- scanned: number(),
17465
- rebuilt: number(),
17466
- /** Tracks whose key frame is gone — nothing to re-embed from. */
17467
- missingKeyFrame: number(),
17468
- /** Tracks with no usable detection box. */
17469
- missingBbox: number(),
17470
- /**
17471
- * Tracks an executing node REFUSED rather than broke on an unreadable key
17472
- * frame, a step that threw. Separate from `failed` because the remedy is
17473
- * different, and because a whole camera silently contributing zero vectors
17474
- * is the shape of failure a rebuild must never hide.
17475
- */
17476
- notRunnable: number(),
17477
- /**
17478
- * The pass stopped because NO node could serve the pinned model.
17479
- *
17480
- * Distinct from `notRunnable` on purpose: that one says "this track was
17481
- * refused", this one says "the cluster cannot do this work at all" — every
17482
- * candidate node either lacks the `clip-embedding` step, lacks a build of the
17483
- * pinned model for its engine format, or dropped out. The remedy is a model /
17484
- * engine change, not a per-camera one. Non-zero here always comes with
17485
- * `complete: false`.
17486
- */
17487
- noCapableNode: number(),
17488
- failed: number(),
17489
- /** Set once a pass ends: true only when EVERYTHING was covered. */
17490
- complete: boolean().nullable(),
17491
- startedAtMs: number().nullable(),
17492
- finishedAtMs: number().nullable(),
17493
- /** Present when the pass ended by throwing. */
17494
- error: string().nullable()
17495
- });
17496
- DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).readonly()), method(object({
17497
- deviceId: number(),
17498
- trackId: string()
17499
- }), TrackSchema.nullable()), method(object({
17500
- deviceId: number(),
17501
- since: number().optional(),
17502
- until: number().optional(),
17503
- limit: number().optional(),
17504
- /** Spatial filter — only tracks whose trajectory intersects the zone
17505
- * (normalized 0..1 rect or polygon). SQL-prefiltered on the persisted
17506
- * envelope columns, then precisely tested per position. Tracks with
17507
- * an unknown envelope (no frame dims at persist time) always match. */
17508
- zone: TrackZoneFilterSchema.optional(),
17509
- /** See {@link TrackProjectionSchema}. Default `full` (backward
17510
- * compatible — omitting the field keeps today's exact behaviour). */
17511
- projection: TrackProjectionSchema.optional(),
17512
- /** Include stationary-promoted rows (parked objects handed to the
17513
- * stationary registry). Default false: the timeline lists passages,
17514
- * not parking records (operator decision, 2026-08-15). */
17515
- includeStationary: boolean().optional()
17516
- }), array(TrackSchema).readonly()), method(RecentTracksQueryInput, RecentTracksPageSchema), method(ListGroupsQueryInput, ListGroupsPageSchema), method(object({
17517
- deviceId: number(),
17518
- groupId: string().min(1)
17519
- }), AnalyticsGroupDetailSchema.nullable()), method(object({ deviceId: number() }), _void(), {
17520
- kind: "mutation",
17521
- auth: "admin"
17522
- }), method(DeviceEventQueryInput, array(MotionEventSchema).readonly()), method(ObjectEventQueryInput, array(ObjectEventSchema).readonly()), method(DeviceEventQueryInput, array(AudioEventSchema).readonly()), method(object({ deviceId: number() }), array(EventKindDescriptorSchema).readonly()), method(object({ deviceIds: array(number()).min(1).max(200) }), array(EventKindsForDeviceSchema).readonly()), method(object({
17523
- deviceId: number(),
17524
- since: number().optional(),
17525
- until: number().optional(),
17526
- kinds: array(string()).optional(),
17527
- limit: number().int().min(1).max(MAX_EVENT_QUERY_LIMIT).default(DEFAULT_EVENT_QUERY_LIMIT)
17528
- }), array(SensorEventSchema).readonly()), method(KeyEventQueryInput, array(KeyEventSchema).readonly()), method(object({
17529
- deviceId: number(),
17530
- since: number(),
17531
- until: number(),
17532
- bucketMs: number().int().positive()
17533
- }), array(object({
17534
- bucketStart: number(),
17535
- motion: number().int(),
17536
- object: number().int(),
17537
- audio: number().int()
17538
- })).readonly()), method(object({
17539
- deviceId: number(),
17540
- cutoffMs: number()
17541
- }), object({
17542
- motion: number().int(),
17543
- object: number().int(),
17544
- audio: number().int()
17545
- }), {
17546
- kind: "mutation",
17547
- auth: "admin"
17548
- }), method(object({
17549
- deviceId: number(),
17550
- cutoffMs: number()
17551
- }), TrackCascadeCountsSchema, {
17552
- kind: "mutation",
17553
- auth: "admin"
17554
- }), method(object({ deviceId: number() }), TrackCascadeCountsSchema, {
17555
- kind: "mutation",
17556
- auth: "admin"
17557
- }), method(object({ deviceId: number() }), DiskReconcileCountsSchema, {
17558
- kind: "mutation",
17559
- auth: "admin"
17560
- }), method(object({
17561
- deviceId: number(),
17562
- trackIds: array(string()).min(1)
17563
- }), object({
17564
- deleted: number().int(),
17565
- failed: array(string()).readonly()
17566
- }), {
17567
- kind: "mutation",
17568
- auth: "admin"
17569
- }), method(object({
17570
- /** Log/audit scope only — the trackId is globally unique on its own. */
17571
- deviceId: number(),
17276
+ var TrackFlagFields = {
17277
+ /** Operator marked this track as training material — i.e. `retrainStatus` is
17278
+ * `'staging'`. */
17279
+ markForTrain: boolean().optional(),
17280
+ /** Operator marked this track for diagnostic attention. */
17281
+ debug: boolean().optional(),
17282
+ /** Operator favourited this track. Pins it against pruning. */
17283
+ favourited: boolean().optional()
17284
+ };
17285
+ /**
17286
+ * The lifecycle field itself, on the READ surfaces only (`Track`, `KeyEvent`).
17287
+ * Deliberately NOT part of {@link TrackFlagFields}: that group also builds the
17288
+ * write patch, and the status is not something the toggle sets — it is what the
17289
+ * toggle's boolean is derived from. Absent on an in-RAM track never touched;
17290
+ * always present on a persisted row (the column default materialises `'none'`).
17291
+ */
17292
+ var TrackRetrainFields = { retrainStatus: RetrainStatusSchema.optional() };
17293
+ /**
17294
+ * The write half: a PARTIAL patch. An omitted key is left untouched, so setting
17295
+ * one flag can never clear the other — the toggles are independent and are
17296
+ * driven from three surfaces that do not know about each other.
17297
+ */
17298
+ var TrackFlagsPatchSchema = object(TrackFlagFields);
17299
+ /**
17300
+ * The resolved flag state after a write. Both fields are REQUIRED here (absent
17301
+ * collapses to `false`) so a caller can drive a toggle's checked state off the
17302
+ * mutation result without a re-fetch.
17303
+ */
17304
+ var TrackFlagsSchema = object({
17572
17305
  trackId: string(),
17573
- flags: TrackFlagsPatchSchema
17574
- }), TrackFlagsSchema, { kind: "mutation" }), method(object({}), EventStoreFootprintSchema, {
17575
- kind: "query",
17576
- auth: "admin"
17577
- }), method(object({
17578
- olderThanMs: number(),
17579
- reason: OpsLogReasonSchema.optional()
17580
- }), EventPruneCountsSchema, {
17581
- kind: "mutation",
17582
- auth: "admin"
17583
- }), method(object({ deviceId: number() }), EventPruneCountsSchema, {
17584
- kind: "mutation",
17585
- auth: "admin"
17586
- }), method(StorageMigrationLeaseInputSchema, object({ paused: literal(true) }), {
17587
- kind: "mutation",
17588
- auth: "admin"
17589
- }), method(StorageMigrationLeaseInputSchema, object({ resumed: literal(true) }), {
17590
- kind: "mutation",
17591
- auth: "admin"
17592
- }), method(StorageMigrationLeaseInputSchema, object({ refreshed: literal(true) }), {
17593
- kind: "mutation",
17594
- auth: "admin"
17595
- }), method(StorageMigrationMediaMoveInputSchema, object({ jobId: string() }), {
17596
- kind: "mutation",
17597
- auth: "admin"
17598
- }), method(object({ jobId: string() }), RelocateJobSchema.nullable(), { auth: "admin" }), method(object({ jobId: string() }), object({ cancelled: boolean() }), {
17599
- kind: "mutation",
17600
- auth: "admin"
17601
- }), method(RelocateMediaInputSchema, object({ jobId: string() }), {
17602
- kind: "mutation",
17603
- auth: "admin"
17604
- }), method(object({}), array(RelocateJobSchema).readonly(), {
17605
- kind: "query",
17606
- auth: "admin"
17607
- }), method(object({ jobId: string() }), object({ cancelled: boolean() }), {
17608
- kind: "mutation",
17609
- auth: "admin"
17610
- }), method(OpsLogQueryInputSchema, array(OpsLogEntrySchema).readonly(), {
17611
- kind: "query",
17612
- auth: "admin"
17613
- }), method(object({ deviceIds: array(number()).optional() }), TrainingExportSummarySchema, {
17614
- kind: "query",
17615
- auth: "admin"
17616
- }), method(object({ deviceIds: array(number()).optional() }), object({ url: string() }), {
17617
- kind: "query",
17618
- auth: "admin"
17619
- }), method(object({
17620
- /** Empty every camera that has staging tracks. A LIST, not a single
17621
- * `deviceId`, deliberately: `deviceId` would make this device-bound and
17622
- * route it at one camera's owner, and "every camera" would stop being
17623
- * expressible at all. */
17624
- deviceIds: array(number()).optional(),
17625
- limit: number().int().min(1).max(500).optional()
17626
- }), array(RetrainTrackSchema).readonly(), {
17627
- kind: "query",
17628
- auth: "admin"
17629
- }), method(object({ trackId: string() }), RetrainFrameListSchema, {
17630
- kind: "query",
17631
- auth: "admin"
17632
- }), method(object({
17306
+ markForTrain: boolean(),
17307
+ debug: boolean(),
17308
+ favourited: boolean(),
17309
+ /** The lifecycle state the boolean was derived from. Required here (unlike on
17310
+ * a track row) because this shape is only ever produced by the write body,
17311
+ * which always knows it — and a surface that has just written needs to render
17312
+ * `trained` without a re-fetch. */
17313
+ retrainStatus: RetrainStatusSchema
17314
+ });
17315
+ union([literal(1), literal(2)]);
17316
+ /**
17317
+ * WHO decided a label, and when. Carried per tier so a value can be traced to
17318
+ * the step and model that produced it — which is what makes the write rule
17319
+ * arguable after the fact ("why is 592's label `dog` and not `Canis lupus`?")
17320
+ * and what lets a migrated, UNATTRIBUTED value be told apart from a real one.
17321
+ *
17322
+ * `stepId` is the pipeline step id (`animal-classifier`, `bird-classifier`,
17323
+ * `plate-ocr`, `face-embedding`, `object-detection`), or the sentinel
17324
+ * `migration:4g` for a value the 4g migration moved from the single-slot era —
17325
+ * that value has no provenance, and the write rule lets ANY properly-attributed
17326
+ * write of the same tier replace it regardless of score.
17327
+ */
17328
+ var LabelAttributionSchema = object({
17329
+ stepId: string(),
17330
+ modelId: string().optional(),
17331
+ decidedAt: number(),
17332
+ /**
17333
+ * The GALLERY id behind a recognised tier-2 label — a face-gallery
17334
+ * `Identity.id` or a plate-gallery `Vehicle.id` (both `randomUUID`).
17335
+ *
17336
+ * The text alone is a DISPLAY NAME, and a display name is renameable: a
17337
+ * notification rule authored on "Gianluca" stopped matching the moment the
17338
+ * operator fixed the spelling in the gallery, and nothing said so. The id is
17339
+ * the thing that does not move, so it is what a rule matches on
17340
+ * (`NcConditions.identities`) and the text is what a human is shown.
17341
+ *
17342
+ * Absent when the label names no gallery row — a plate the OCR read but no
17343
+ * vehicle claims, a sub-class, a species, any tier-1 value.
17344
+ */
17345
+ identityId: string().optional()
17346
+ });
17347
+ /**
17348
+ * The TIERED label model (roadmap 4g), spread into `TrackSchema` and
17349
+ * `ObjectEventSchema` from ONE place so the two surfaces cannot drift — a
17350
+ * track and its events always answer the same question the same way.
17351
+ *
17352
+ * Two scalar columns, not an array: every consumer wants "the coarse one" or
17353
+ * "the fine one", and an array made both a scan. `label` is tier 1, `subLabel`
17354
+ * is tier 2, and each carries its own score + attribution.
17355
+ *
17356
+ * **Reading it.** What a human should be shown is `subLabel ?? label` — the
17357
+ * finest thing known. Before 4g the single `label` column held the finest
17358
+ * value, so a consumer that has not been updated reads the tier-1 slot and
17359
+ * shows nothing on a species-only row; that is why the migration puts every
17360
+ * pre-4g value in tier 2 (it cannot regress a display that reads the fallback)
17361
+ * and why the read surfaces were changed in the same train.
17362
+ *
17363
+ * **Writing it.** The slots are independent, which is the whole point: a
17364
+ * tier-1 write (`bird`) can never overwrite a tier-2 value (`Turdus
17365
+ * migratorius`), so fineness cannot regress by construction. Within a tier the
17366
+ * higher score wins. One rule, one implementation — see
17367
+ * `pipeline/label-tier.ts` in addon-post-analysis.
17368
+ */
17369
+ var TieredLabelFields = {
17370
+ /** Tier 1 — the sub-class. See {@link LabelTierSchema}. */
17371
+ label: string().optional(),
17372
+ /** Confidence of the tier-1 value, as reported by the deciding step. */
17373
+ labelScore: number().optional(),
17374
+ /** Provenance of the tier-1 value. See {@link LabelAttributionSchema}. */
17375
+ labelMeta: LabelAttributionSchema.optional(),
17376
+ /** Tier 2 — the instance. See {@link LabelTierSchema}. */
17377
+ subLabel: string().optional(),
17378
+ /** Confidence of the tier-2 value, as reported by the deciding step. */
17379
+ subLabelScore: number().optional(),
17380
+ /** Provenance of the tier-2 value. See {@link LabelAttributionSchema}. */
17381
+ subLabelMeta: LabelAttributionSchema.optional()
17382
+ };
17383
+ /** Per-camera slice of a training-export estimate. */
17384
+ var TrainingExportDeviceTotalsSchema = object({
17633
17385
  deviceId: number(),
17386
+ tracks: number().int(),
17387
+ files: number().int(),
17388
+ bytes: number().int()
17389
+ });
17390
+ /**
17391
+ * What a training export WOULD contain. Computed from media index rows only —
17392
+ * no blob is read to produce this.
17393
+ */
17394
+ var TrainingExportSummarySchema = object({
17395
+ generatedAt: number(),
17396
+ trackCount: number().int(),
17397
+ fileCount: number().int(),
17398
+ byteCount: number().int(),
17399
+ /** More marked tracks exist than a single pass carries. */
17400
+ truncated: boolean(),
17401
+ devices: array(TrainingExportDeviceTotalsSchema).readonly()
17402
+ });
17403
+ var TrackSchema = object({
17634
17404
  trackId: string(),
17635
- mediaKeys: array(string()).min(1)
17636
- }), RetrainFrameSelectionSchema, {
17637
- kind: "mutation",
17638
- auth: "admin"
17639
- }), method(object({
17640
17405
  deviceId: number(),
17641
- trackId: string(),
17642
- frameId: string()
17643
- }), object({
17644
- removed: boolean(),
17645
- removedAnnotations: number().int()
17646
- }), {
17647
- kind: "mutation",
17648
- auth: "admin"
17649
- }), method(object({ frameId: string() }), object({
17406
+ className: string(),
17407
+ ...TieredLabelFields,
17408
+ producingDeviceName: string().optional(),
17409
+ /** Track provenance. Absent ⇒ `pipeline` (legacy rows). */
17410
+ source: TrackSourceSchema.optional(),
17411
+ firstSeen: number(),
17412
+ lastSeen: number(),
17413
+ /** Frame-rate position history (subject to maxPositionHistory cap). */
17414
+ positions: array(TrackPositionSchema).readonly(),
17415
+ /** Periodic snapshots at snapshotIntervalMs cadence (subject to
17416
+ * saveThumbnails policy). */
17417
+ snapshots: array(TrackSnapshotSchema).readonly(),
17418
+ /** Deduplicated zones the track has entered at least once. Zone IDS. */
17419
+ zonesVisited: array(string()).readonly(),
17420
+ /**
17421
+ * Human NAMES for {@link zonesVisited}, resolved at READ time against the
17422
+ * `zones` capability.
17423
+ *
17424
+ * `zonesVisited` persists ids (`cfeec78c-8d69-…`), which no operator can type
17425
+ * and no card can render — so every free-text search surface was structurally
17426
+ * unable to answer "show me the tracks in Uscio", and did not fail loudly, it
17427
+ * just returned nothing. Resolving here rather than in each client keeps ONE
17428
+ * derivation and costs the clients no extra call (the `zones` cap is
17429
+ * per-device, so a client-side resolve would be a per-camera fan-out on a
17430
+ * surface built to avoid exactly that).
17431
+ *
17432
+ * Resolved, never invented: a zone deleted since the track was written has no
17433
+ * name and is DROPPED, so this array can be shorter than `zonesVisited` — the
17434
+ * two are not positionally aligned. Absent when the track visited no zone, or
17435
+ * when the zone catalogue could not be read.
17436
+ */
17437
+ zoneNames: array(string()).readonly().optional(),
17438
+ /** Deduplicated set of detector classes observed for this track over its
17439
+ * life (a track may be reclassified, e.g. person→vehicle). Absent on
17440
+ * legacy rows written before class accumulation shipped. */
17441
+ classes: array(string()).readonly().optional(),
17442
+ /** Cumulative normalized distance travelled (0..1 units = full frame width). */
17443
+ totalDistance: number(),
17444
+ state: TrackStateSchema,
17445
+ active: boolean(),
17446
+ /** Deterministic key-event importance score in [0,1] (server-computed at
17447
+ * track expiry, recomputed on late label). Absent on legacy rows written
17448
+ * before scoring shipped — consumers degrade to absence / compute-on-read. */
17449
+ importance: number().optional(),
17450
+ /** Id of the track's highest-confidence ObjectEvent (its representative
17451
+ * "best" frame). Absent when the track produced no object events. */
17452
+ bestEventId: string().optional(),
17453
+ /** Tag of the importance sub-signal that dominated the score
17454
+ * (identity|dwell|proximity|class|confidence|travel|zone). */
17455
+ importanceReason: string().optional(),
17456
+ /** Audio-classification labels heard on the camera during the track's
17457
+ * life (score ≥ device `classificationMinScore`), aggregated per label.
17458
+ * Absent on legacy rows / tracks with no confident audio. */
17459
+ audioLabels: array(TrackAudioLabelSchema).readonly().optional(),
17460
+ /** Normalized 0..1 trajectory envelope (see {@link TrackEnvelopeSchema}).
17461
+ * Populated from the persisted envelope columns on historical reads;
17462
+ * absent on legacy rows, dims-less tracks and active (in-RAM) tracks. */
17463
+ envelope: TrackEnvelopeSchema.optional(),
17464
+ /**
17465
+ * A face DETECTOR found a face on this track — nothing more. It says the
17466
+ * detail plane produced a `face` detail; it does NOT say the face was
17467
+ * embedded, matched, above `minFacePx`, or that the recognizer was even
17468
+ * enabled. Set once and never cleared.
17469
+ *
17470
+ * **This exists so "face present but not recognised" is expressible.** A
17471
+ * recognised identity lands in `subLabel` (attributed to the face chain via
17472
+ * `subLabelMeta.stepId`), so before this field a track with an unmatched face
17473
+ * and a track with no face at all were byte-identical on the wire and no
17474
+ * surface could tell them apart. The read is `hasFace === true && subLabel
17475
+ * === undefined`.
17476
+ *
17477
+ * **Absent ≠ false.** Every row written before the column existed omits it,
17478
+ * and so does every server that predates the field — a consumer must test
17479
+ * `=== true` and render nothing otherwise, never infer "no face".
17480
+ */
17481
+ hasFace: boolean().optional(),
17482
+ /**
17483
+ * This track has a face row IN THE GALLERY: a crop **and** an embedding — a
17484
+ * face an operator could ASSIGN to an identity.
17485
+ *
17486
+ * The STRICT twin of {@link hasFace}, and the pair only earns its keep
17487
+ * because the two disagree. `hasFace` is stamped at the TOP of the face
17488
+ * branch, before every gate, and means no more than "a face detector produced
17489
+ * a face detail". This one is stamped at the single moment the gallery row
17490
+ * LANDS — after `FaceRecognizer.onTrackEnd` successfully persists it, i.e.
17491
+ * past the embedding-magnitude verdict, the `minFacePx` detection gate, the
17492
+ * candidate gate, the imageless-track drop (no crop was ever captured) and
17493
+ * the crop-store drop. Everything between the detector and that insert can
17494
+ * legitimately refuse the face, so a flag written any earlier promises the
17495
+ * operator something to assign and delivers nothing.
17496
+ *
17497
+ * **Independent of recognition.** A face collected but never auto-matched is
17498
+ * still assignable — it is in fact the face an operator most wants to reach —
17499
+ * so this is NOT gated on `recognizedIdentityId`. Recognition lands in
17500
+ * `subLabel`; this says only that the raw material exists.
17501
+ *
17502
+ * **Set once, never cleared.** A track that produced a gallery row produced
17503
+ * one; deleting the row later is the gallery's business, not this flag's.
17504
+ *
17505
+ * **Absent ≠ false**, the same rule as {@link hasFace}: every row written
17506
+ * before the column omits it, and so does every server that predates the
17507
+ * field. A consumer must test `=== true` and render nothing otherwise —
17508
+ * never infer "no assignable face".
17509
+ */
17510
+ hasEmbeddedFace: boolean().optional(),
17511
+ /**
17512
+ * This subject CONTAINS a folded rider — a person the rider-pairing step
17513
+ * ([D34](../decisions/adr-0034.md)) removed from the frame BEFORE the tracker,
17514
+ * so the passage is tracked once and as a VEHICLE.
17515
+ *
17516
+ * It exists because the fold's record was dishonest. D34 and the code both
17517
+ * said "the person is not lost — it is reported so both entities stay on the
17518
+ * record"; in fact the pair went into a per-processor RAM field behind an
17519
+ * accessor nobody called, and every durable surface said `vehicle`, full
17520
+ * stop. This is the composition note that makes the row true.
17521
+ *
17522
+ * A COMPOSITION, never a class and never a label. "This vehicle contains a
17523
+ * person" is not an answer to "what is this" — both label tiers would refuse
17524
+ * a macro token anyway (D89), and correctly. Nothing here changes what the
17525
+ * subject IS: a cyclist stays one vehicle track, occupancy still counts one,
17526
+ * and a `person` rule still does not fire for someone cycling past.
17527
+ *
17528
+ * **Absent ≠ false**, exactly like {@link hasFace}: every row written before
17529
+ * the column, and every hub that predates the field, omits it. Test
17530
+ * `=== true` and render nothing otherwise — never infer "no rider".
17531
+ */
17532
+ hasRider: boolean().optional(),
17533
+ ...TrackFlagFields,
17534
+ ...TrackRetrainFields
17535
+ });
17536
+ var BaseEventFields = {
17537
+ id: string(),
17538
+ deviceId: number(),
17539
+ timestamp: number()
17540
+ };
17541
+ var MotionEventSchema = object({
17542
+ ...BaseEventFields,
17543
+ kind: literal("motion"),
17544
+ regionCount: number(),
17545
+ /** Heavy JSON array — omitted in slim projection. */
17546
+ regions: array(object({
17547
+ bbox: BoundingBoxSchema,
17548
+ pixelCount: number(),
17549
+ intensity: number()
17550
+ })).readonly().optional(),
17551
+ /** Omitted in slim projection. */
17552
+ frameWidth: number().optional(),
17553
+ /** Omitted in slim projection. */
17554
+ frameHeight: number().optional(),
17555
+ /** Populated by B5 (recording playback URL for this event). */
17556
+ mediaUrl: string().optional()
17557
+ });
17558
+ /**
17559
+ * Which detection SOURCE produced an object event. `pipeline` = the ML
17560
+ * detection pipeline (decoded-frame inference); `onboard` = the camera's
17561
+ * native on-device AI. Both flow through the SAME analysis layers (zoning,
17562
+ * tracking, per-kind persistence) but stay distinguishable so consumers
17563
+ * (advanced-notifier, occupancy, …) can select which source(s) to act on.
17564
+ * Absent on legacy rows ⇒ treat as `pipeline`.
17565
+ */
17566
+ var DetectionSourceSchema = _enum(["pipeline", "onboard"]);
17567
+ /**
17568
+ * The confirmed zone crossing that produced an object event. Present ONLY on
17569
+ * an event emitted BY a crossing (`zone.enter` / `zone.exit`); a movement-state
17570
+ * event (`object.entering` / `leaving` / `stationary` / `loitering`) and an
17571
+ * appearance event carry none, so a rule asking for a direction fails closed
17572
+ * on them.
17573
+ *
17574
+ * Exactly ONE crossing per event: the emitter turns each confirmed crossing
17575
+ * into its own event, so a frame in which a track enters A while leaving B
17576
+ * produces two events with two directions — never one ambiguous row.
17577
+ *
17578
+ * `zoneId` is load-bearing for an EXIT: the event's `zones` list is the
17579
+ * membership the box has NOW, and by definition it no longer contains the zone
17580
+ * that was just left. Without the id here, a zone-scoped rule could never match
17581
+ * the exit it asked for.
17582
+ */
17583
+ var ZoneCrossingSchema = object({
17584
+ direction: _enum(["enter", "exit"]),
17585
+ /** Admin zone id crossed. */
17586
+ zoneId: string(),
17587
+ /** Zone display name at crossing time (falls back to the id). */
17588
+ zoneName: string().optional()
17589
+ });
17590
+ var ObjectEventSchema = object({
17591
+ ...BaseEventFields,
17592
+ kind: literal("object"),
17593
+ /** Detection source. Optional for backward-compat; absent ⇒ `pipeline`. */
17594
+ source: DetectionSourceSchema.optional(),
17595
+ /**
17596
+ * Inference-frame id shared by every object event emitted from the SAME frame
17597
+ * — the "scene/parent" key. Lets a consumer group co-occurring detections (e.g.
17598
+ * 2 people + 1 dog) under one full frame, and link a track's frames over time
17599
+ * (group by `trackId`, pick a representative `frameId` as the parent frame).
17600
+ * Optional for backward-compat with pre-existing rows / the slim projection
17601
+ * includes it (it is light). Absent on rows written before this field.
17602
+ */
17603
+ frameId: string().optional(),
17604
+ /** Omitted in slim projection. */
17605
+ trackId: string().optional(),
17606
+ className: string(),
17607
+ ...TieredLabelFields,
17608
+ /** Omitted in slim projection. */
17609
+ confidence: number().optional(),
17610
+ /** Heavy JSON — omitted in slim projection. */
17611
+ bbox: BoundingBoxSchema.optional(),
17612
+ /** Heavy JSON — omitted in slim projection. */
17613
+ zones: array(string()).readonly().optional(),
17614
+ /** Omitted in slim projection. */
17615
+ state: TrackStateSchema.optional(),
17616
+ /**
17617
+ * The zone crossing this event IS, when it is one. Absent on every other
17618
+ * event kind (movement state, appearance, package) — see
17619
+ * {@link ZoneCrossingSchema}. Omitted in slim projection.
17620
+ */
17621
+ zoneCrossing: ZoneCrossingSchema.optional(),
17622
+ /** Detection-frame dimensions in pixels — let consumers normalize the
17623
+ * pixel-space `bbox` onto a displayed image. Omitted in slim projection. */
17624
+ frameWidth: number().optional(),
17625
+ frameHeight: number().optional(),
17626
+ /** MediaStore key for the crop attached to this event (if any). */
17627
+ mediaKey: string().optional(),
17628
+ /** Design B: MediaStore key of the track's native-resolution key frame (the
17629
+ * best-detection full frame). Resolve via the event-media data-plane
17630
+ * (`/addon/<addonId>/event-media/<keyFrameMediaKey>`) for a detail view that
17631
+ * draws `bbox` over the native frame. Absent on legacy rows / non-decoded
17632
+ * sources — consumers fall back to `mediaKey` (the tight crop). */
17633
+ keyFrameMediaKey: string().optional(),
17634
+ /** Populated by B5 (recording playback URL for this event). */
17635
+ mediaUrl: string().optional(),
17636
+ /** The parent track's key-event importance [0,1], propagated to every object
17637
+ * event of the track (so an event row can be sorted by importance without a
17638
+ * track join). Absent on legacy rows / before the track was scored. */
17639
+ importance: number().optional()
17640
+ });
17641
+ var AudioEventSchema = object({
17642
+ ...BaseEventFields,
17643
+ kind: literal("audio"),
17644
+ rms: number(),
17645
+ dbfs: number(),
17646
+ classification: object({
17647
+ className: string(),
17648
+ originalClass: string().optional(),
17649
+ score: number()
17650
+ }).optional(),
17651
+ /** Populated by B5 (recording playback URL for this event). */
17652
+ mediaUrl: string().optional()
17653
+ });
17654
+ var MediaFileKindEnum = _enum([
17655
+ "crop",
17656
+ "thumbnail",
17657
+ "snapshot",
17658
+ "firstFrame",
17659
+ "lastFrame",
17660
+ "fullFrame",
17661
+ "fullFrameBoxed",
17662
+ "faceCrop",
17663
+ "plateCrop",
17664
+ "keyFrame",
17665
+ "keyFrameSmall",
17666
+ "thumbnailSmall"
17667
+ ]);
17668
+ var MediaFileSchema = object({
17669
+ key: string(),
17670
+ kind: MediaFileKindEnum,
17650
17671
  base64: string(),
17651
- width: number().int(),
17652
- height: number().int()
17653
- }), {
17654
- kind: "query",
17655
- auth: "admin"
17656
- }), method(object({
17657
- deviceId: number(),
17658
- trackId: string(),
17659
- frameId: string(),
17660
- subject: RetrainAssistSubjectSchema,
17661
- /** Which node runs it. Absent ⇒ wherever an unowned call lands. */
17662
- nodeId: string().optional()
17663
- }), RetrainAssistResultSchema, {
17664
- kind: "mutation",
17665
- auth: "admin"
17666
- }), method(object({ trackId: string() }), array(RetrainAnnotationSchema).readonly(), {
17667
- kind: "query",
17668
- auth: "admin"
17669
- }), method(object({
17670
- deviceId: number(),
17672
+ sizeBytes: number(),
17673
+ timestamp: number()
17674
+ });
17675
+ /**
17676
+ * One media row WITHOUT its bytes.
17677
+ *
17678
+ * A track's media is 5-8 MB of base64 (measured: 7.67 MB across 23 files for a
17679
+ * 140 s track), and a client that renders tiles from the media data plane needs
17680
+ * to know only WHAT EXISTS — the bytes then arrive per tile, lazily, over HTTP
17681
+ * with an immutable cache, instead of all at once inside a tRPC response that
17682
+ * blocks the whole view.
17683
+ *
17684
+ * `sizeBytes` is carried because it is what lets a client decide between the
17685
+ * stored blob and a `?variant=thumb` rendering without fetching either.
17686
+ */
17687
+ var MediaFileInfoSchema = MediaFileSchema.omit({ base64: true });
17688
+ /**
17689
+ * The MACRO tier of an annotation — a CLOSED set.
17690
+ *
17691
+ * This is what the exported detector predicts, so a typo here is a new class
17692
+ * with one example in it. `label` and `subLabel` are open strings by contrast:
17693
+ * the whole point of the page is teaching the model things it does not know
17694
+ * yet, and constraining that vocabulary would make it useless.
17695
+ *
17696
+ * A macro class is NEVER a label. The provider refuses a write whose `label` or
17697
+ * `subLabel` is one of these values, in any casing, because once `person`
17698
+ * exists in both tiers "every person box" stops being answerable without
17699
+ * knowing every string anyone ever typed — and the damage is retroactive.
17700
+ */
17701
+ var RetrainMacroClassSchema = _enum([
17702
+ "person",
17703
+ "vehicle",
17704
+ "animal",
17705
+ "package",
17706
+ "face",
17707
+ "plate"
17708
+ ]);
17709
+ /** A subject to learn, or a phantom to unlearn (taught by OMISSION). */
17710
+ var RetrainAnnotationKindSchema = _enum(["subject", "model_error"]);
17711
+ /** Did a human draw this box, or did the assist propose it? */
17712
+ var RetrainAnnotationSourceSchema = _enum(["operator", "assist"]);
17713
+ /** Normalised `[0,1]` rectangle against the FULL frame — the canonical form. */
17714
+ var RetrainBboxSchema = object({
17715
+ x: number(),
17716
+ y: number(),
17717
+ w: number(),
17718
+ h: number()
17719
+ });
17720
+ /**
17721
+ * One annotated subject.
17722
+ *
17723
+ * `bbox` is normalised against the full frame, ALWAYS. The per-model shapes
17724
+ * (letterboxed root / zone-cropped package / subject-cropped classifier) are
17725
+ * derived from it at export and never stored — storing them is how one feature
17726
+ * space ends up holding two crops of the same subject (D52).
17727
+ */
17728
+ var RetrainAnnotationSchema = object({
17729
+ id: string(),
17671
17730
  trackId: string(),
17672
- frameId: string(),
17673
- annotations: array(RetrainAnnotationDraftSchema)
17674
- }), array(RetrainAnnotationSchema).readonly(), {
17675
- kind: "mutation",
17676
- auth: "admin"
17677
- }), method(object({
17678
- deviceId: number(),
17679
- trackId: string()
17680
- }), RetrainTransitionResultSchema, {
17681
- kind: "mutation",
17682
- auth: "admin"
17683
- }), method(object({
17684
17731
  deviceId: number(),
17685
- trackId: string()
17686
- }), RetrainTransitionResultSchema, {
17687
- kind: "mutation",
17688
- auth: "admin"
17689
- }), method(object({ deviceIds: array(number()).optional() }), object({ url: string() }), {
17690
- kind: "query",
17691
- auth: "admin"
17692
- }), method(object({
17693
- eventId: string(),
17694
- kind: MediaFileKindEnum.optional(),
17695
- deviceId: number()
17696
- }), array(MediaFileSchema).readonly()), method(object({
17697
- trackId: string(),
17698
- kinds: array(MediaFileKindEnum).optional(),
17699
- deviceId: number()
17700
- }), array(MediaFileSchema).readonly()), method(object({
17732
+ /** The COPY in retrain storage — never the source track's media key. */
17733
+ mediaKey: string(),
17734
+ bbox: RetrainBboxSchema,
17735
+ macroClass: RetrainMacroClassSchema,
17736
+ label: string().optional(),
17737
+ subLabel: string().optional(),
17738
+ kind: RetrainAnnotationKindSchema,
17739
+ source: RetrainAnnotationSourceSchema,
17740
+ /** Which model proposed this box — or, on a `model_error`, drew the phantom. */
17741
+ assistModelId: string().optional(),
17742
+ assistScore: number().optional(),
17743
+ exportedInBatch: string().optional(),
17744
+ createdAt: number()
17745
+ });
17746
+ /** The write form — the server owns `id`, `createdAt` and the frame binding. */
17747
+ var RetrainAnnotationDraftSchema = RetrainAnnotationSchema.omit({
17748
+ id: true,
17749
+ trackId: true,
17750
+ deviceId: true,
17751
+ mediaKey: true,
17752
+ createdAt: true,
17753
+ exportedInBatch: true
17754
+ });
17755
+ /** A track sitting in `staging`, with everything the worklist needs to rank it. */
17756
+ var RetrainTrackSchema = object({
17701
17757
  trackId: string(),
17702
- deviceId: number()
17703
- }), array(MediaFileInfoSchema).readonly()), method(SearchObjectEventsInput, array(ScoredObjectEventSchema).readonly()), method(object({}), WipeObjectEmbeddingsResultSchema, {
17704
- kind: "mutation",
17705
- auth: "admin"
17706
- }), method(RebuildObjectEmbeddingsInput, RebuildObjectEmbeddingsResultSchema, {
17707
- kind: "mutation",
17708
- auth: "admin"
17709
- }), method(object({}), RebuildStatusSchema), object({
17710
17758
  deviceId: number(),
17759
+ className: string(),
17760
+ label: string().optional(),
17761
+ firstSeen: number(),
17762
+ lastSeen: number(),
17763
+ /** How many frames the dataset already holds from this track. */
17764
+ frameCount: number().int(),
17765
+ /** How many subjects have been annotated on those frames. `0` with
17766
+ * `frameCount: 0` is exactly "staging, still to work". */
17767
+ annotationCount: number().int()
17768
+ });
17769
+ /** A frame the picker may offer — an index row, no blob was read to produce it. */
17770
+ var RetrainFrameCandidateSchema = object({
17771
+ mediaKey: string(),
17772
+ kind: MediaFileKindEnum,
17711
17773
  timestamp: number(),
17712
- frameWidth: number(),
17713
- frameHeight: number(),
17714
- detections: array(OverlayDetectionSchema).readonly()
17715
- }), object({
17716
- deviceId: number(),
17717
- trackId: string(),
17718
- className: string()
17719
- }), object({
17774
+ sizeBytes: number().int(),
17775
+ /** A copy of this original already exists — selecting it is free and cannot
17776
+ * fail, whatever became of the original. */
17777
+ copied: boolean()
17778
+ });
17779
+ /** A frame the dataset OWNS: bytes copied at selection time. */
17780
+ var RetrainFrameSchema = object({
17781
+ frameId: string(),
17720
17782
  deviceId: number(),
17721
17783
  trackId: string(),
17722
- className: string(),
17723
- durationMs: number()
17724
- }), object({
17725
- deviceId: number(),
17726
- kind: EventKindSchema,
17727
- eventId: string(),
17728
- timestamp: number()
17784
+ /** Provenance only. It may already point at nothing — that is expected. */
17785
+ sourceMediaKey: string(),
17786
+ sourceKind: MediaFileKindEnum,
17787
+ sizeBytes: number().int(),
17788
+ width: number().int(),
17789
+ height: number().int(),
17790
+ copiedAt: number()
17729
17791
  });
17730
- /**
17731
- * Reference to the frame's retained NATIVE surface + the parent crop's placement
17732
- * within the frame, so the executor can re-cut a leaf child ROI at native
17733
- * resolution on the detail plane. See the `runPipeline` `nativeCropRef` field.
17734
- */
17735
- var NativeCropRefSchema = object({
17736
- /** Handle keying the retained native surface (node-pinned to its owner). */
17737
- handle: FrameHandleSchema,
17738
- /** The parent crop's padded/clamped rectangle in FRAME-space pixels. */
17739
- cropFrameSpace: object({
17740
- x: number(),
17741
- y: number(),
17742
- w: number(),
17743
- h: number()
17744
- })
17792
+ /** Why a copy-on-select could not be honoured — named, never a silent skip. */
17793
+ var RetrainCopyRefusalSchema = _enum([
17794
+ "source-missing",
17795
+ "unreadable-image",
17796
+ "write-failed"
17797
+ ]);
17798
+ var RetrainFrameSelectionSchema = object({
17799
+ copied: array(RetrainFrameSchema).readonly(),
17800
+ refused: array(object({
17801
+ sourceMediaKey: string(),
17802
+ reason: RetrainCopyRefusalSchema
17803
+ })).readonly()
17745
17804
  });
17746
- object({
17747
- crop: object({
17748
- left: number(),
17749
- top: number(),
17750
- width: number().positive(),
17751
- height: number().positive()
17752
- }).optional(),
17753
- content: object({
17754
- width: number().int().positive(),
17755
- height: number().int().positive()
17756
- }),
17757
- fit: _enum(["stretch", "contain"]),
17758
- format: _enum([
17759
- "rgb",
17760
- "gray",
17761
- "jpeg"
17762
- ])
17805
+ var RetrainFrameListSchema = object({
17806
+ candidates: array(RetrainFrameCandidateSchema).readonly(),
17807
+ copies: array(RetrainFrameSchema).readonly(),
17808
+ /** What the page pre-selects — the native key frame when one survives. */
17809
+ autoPickMediaKey: string().optional()
17763
17810
  });
17811
+ /** What the operator asked the assist to look for. */
17812
+ var RetrainAssistSubjectSchema = discriminatedUnion("kind", [object({
17813
+ kind: literal("package"),
17814
+ zone: RetrainBboxSchema.optional()
17815
+ }), object({
17816
+ kind: literal("objects"),
17817
+ modelId: string(),
17818
+ minScore: number().optional()
17819
+ })]);
17764
17820
  /**
17765
- * Process-local frame identity. It is serializable so it can ride an in-process
17766
- * capability call, but `registryId` deliberately prevents resolution in any
17767
- * other process or execution group.
17821
+ * The assist's answer a discriminated union, because "the model saw nothing"
17822
+ * and "this node cannot run that model" lead to different next moves and a
17823
+ * nullable result cannot tell them apart.
17768
17824
  */
17769
- var FrameRefSchema = object({
17770
- registryId: string().min(1),
17771
- id: string().min(1),
17772
- width: number().int().positive(),
17773
- height: number().int().positive(),
17774
- format: _enum(["rgb", "gray"]),
17775
- timestamp: number(),
17776
- capturedAt: number().optional()
17825
+ var RetrainAssistResultSchema = discriminatedUnion("kind", [object({
17826
+ kind: literal("proposed"),
17827
+ modelId: string(),
17828
+ stepId: string(),
17829
+ minScore: number(),
17830
+ /** Drafts, ready to edit. `source: 'assist'` until the operator touches one. */
17831
+ proposals: array(RetrainAnnotationDraftSchema).readonly(),
17832
+ /** Returned by the runner but removed by the threshold. */
17833
+ belowThreshold: number().int()
17834
+ }), object({
17835
+ kind: literal("refused"),
17836
+ /** `no-zone` is ours; the rest are the runner's own refusal vocabulary. */
17837
+ reason: string(),
17838
+ detail: string().optional()
17839
+ })]);
17840
+ /** The outcome of a lifecycle move owned by the retrain page. */
17841
+ var RetrainTransitionResultSchema = object({
17842
+ trackId: string(),
17843
+ /** Where the track ended up, whatever happened. */
17844
+ retrainStatus: RetrainStatusSchema,
17845
+ /** `false` ⇒ the move was refused or was a no-op; `reason` says which. */
17846
+ changed: boolean(),
17847
+ reason: _enum([
17848
+ "unknown-track",
17849
+ "no-frames-copied",
17850
+ "not-staging",
17851
+ "not-trained",
17852
+ "unchanged"
17853
+ ]).optional()
17777
17854
  });
17778
- var ModelFormatSchema$1 = _enum([
17779
- "onnx",
17780
- "coreml",
17781
- "openvino",
17782
- "tflite",
17783
- "pt",
17784
- "gguf"
17785
- ]);
17786
- var PipelineSlotSchema = _enum([
17787
- "detector",
17788
- "cropper",
17789
- "classifier",
17790
- "refiner",
17791
- "audio-classifier"
17792
- ]);
17793
- var PipelineEngineChoiceSchema = object({
17794
- runtime: _enum(["node", "python"]),
17795
- backend: string(),
17796
- format: ModelFormatSchema$1,
17797
- device: string().optional()
17855
+ var DEFAULT_EVENT_QUERY_LIMIT = 1e3;
17856
+ var MAX_EVENT_QUERY_LIMIT = 5e3;
17857
+ var DeviceEventQueryInput = object({
17858
+ deviceId: number(),
17859
+ since: number().optional(),
17860
+ until: number().optional(),
17861
+ limit: number().int().min(1).max(MAX_EVENT_QUERY_LIMIT).default(DEFAULT_EVENT_QUERY_LIMIT),
17862
+ /** `slim` drops heavy JSON fields (regions/bbox/zones) and carries an
17863
+ * optional `mediaUrl` (populated by B5). `full` (default) keeps today's
17864
+ * exact behaviour. Callers may omit this field — the store defaults to
17865
+ * `full` when not provided. */
17866
+ projection: _enum(["full", "slim"]).optional()
17798
17867
  });
17799
- var AvailableEngineSchema = object({
17800
- engine: PipelineEngineChoiceSchema,
17801
- devices: array(object({
17802
- id: string(),
17803
- label: string(),
17804
- description: string().optional()
17805
- })).readonly(),
17806
- defaultDevice: string()
17868
+ var ObjectEventQueryInput = DeviceEventQueryInput.extend({ classFilter: string().optional() });
17869
+ var RecentTracksQueryInput = object({
17870
+ /** Devices to merge. An empty array yields `{ tracks: [], nextCursor: null }`. */
17871
+ deviceIds: array(number()),
17872
+ /** Window lower bound on `lastSeen` (inclusive). */
17873
+ since: number().optional(),
17874
+ /** Window upper bound on `lastSeen` (inclusive). */
17875
+ until: number().optional(),
17876
+ /** Page size. Default 200, max 1000. */
17877
+ limit: number().int().min(1).max(1e3).default(200),
17878
+ /** Opaque continuation cursor from a previous page's `nextCursor`.
17879
+ * Encodes the (lastSeen, trackId) sort position — treat as opaque. */
17880
+ cursor: string().optional(),
17881
+ /** See {@link TrackProjectionSchema}. Default `full`. */
17882
+ projection: TrackProjectionSchema.optional(),
17883
+ /** Include stationary-promoted rows (parked objects). Default false: the
17884
+ * feed lists passages; parking records live on the stationary registry. */
17885
+ includeStationary: boolean().optional()
17807
17886
  });
17808
- var PipelineDefaultStepSchema = lazy(() => object({
17809
- addonId: string(),
17810
- addonName: string(),
17811
- slot: PipelineSlotSchema,
17812
- inputClasses: array(string()).readonly(),
17813
- outputClasses: array(string()).readonly(),
17814
- enabled: boolean(),
17815
- modelId: string(),
17816
- children: array(PipelineDefaultStepSchema).readonly(),
17817
- group: string().optional(),
17818
- settings: record(string(), unknown()).optional()
17819
- }));
17820
- var PipelineTemplateStepSchema = lazy(() => object({
17821
- addonId: string(),
17822
- enabled: boolean(),
17823
- modelId: string(),
17824
- children: array(PipelineTemplateStepSchema).readonly(),
17825
- settings: record(string(), unknown()).optional()
17826
- }));
17827
- var PipelineTemplateSchema$1 = object({
17828
- id: string(),
17829
- name: string(),
17830
- createdAt: string(),
17831
- updatedAt: string(),
17832
- engine: PipelineEngineChoiceSchema,
17833
- steps: array(PipelineTemplateStepSchema).readonly()
17887
+ var RecentTracksPageSchema = object({
17888
+ /** Merged page, ordered by (`lastSeen` DESC, `trackId` DESC). */
17889
+ tracks: array(TrackSchema).readonly(),
17890
+ /** Cursor for the next page, or null when this page is the last. */
17891
+ nextCursor: string().nullable()
17834
17892
  });
17835
- var PipelineModelOptionSchema = object({
17893
+ var LIST_GROUPS_DEFAULT_LIMIT = 40;
17894
+ var LIST_GROUPS_MAX_LIMIT = 100;
17895
+ var AnalyticsGroupRecordSchema = object({
17836
17896
  id: string(),
17837
- name: string(),
17838
- formats: record(string(), object({
17839
- downloaded: boolean(),
17840
- sizeMB: number()
17841
- })),
17842
- group: ModelVariantGroupSchema.optional(),
17843
- legacy: boolean().optional(),
17844
- provider: ModelProviderIdSchema.optional()
17897
+ deviceId: number().int(),
17898
+ openedAt: number().int(),
17899
+ closedAt: number().int(),
17900
+ timestamp: number().int(),
17901
+ memberCount: number().int(),
17902
+ memberTrackIds: array(string()).readonly(),
17903
+ className: string(),
17904
+ classes: array(string()).readonly(),
17905
+ /** Relative event-media path, or null when the group has no picture yet. */
17906
+ mediaUrl: string().nullable(),
17907
+ singleton: boolean()
17845
17908
  });
17846
- var ConfigFieldBridge = custom();
17847
- var PipelineAddonSchemaSchema = object({
17848
- id: string(),
17849
- name: string(),
17850
- slot: PipelineSlotSchema,
17851
- inputClasses: array(string()).readonly(),
17852
- outputClasses: array(string()).readonly(),
17853
- childSlots: array(PipelineSlotSchema).readonly(),
17854
- models: array(PipelineModelOptionSchema).readonly(),
17855
- defaultModelId: string(),
17856
- defaultModelIdByFormat: record(string(), string()).optional(),
17857
- enabledByDefault: boolean().optional(),
17858
- backfillIntoExistingOverrides: boolean().optional(),
17859
- defaultConfidence: number(),
17860
- group: string().optional(),
17861
- configSchema: array(ConfigFieldBridge).readonly().optional()
17909
+ var AnalyticsGroupMemberSchema = object({
17910
+ trackId: string(),
17911
+ deviceId: number().int(),
17912
+ className: string(),
17913
+ firstSeen: number().int(),
17914
+ lastSeen: number().int(),
17915
+ mediaUrl: string().nullable()
17862
17916
  });
17863
- var PipelineSlotSchemaSchema = object({
17864
- id: PipelineSlotSchema,
17865
- label: string(),
17866
- priority: number(),
17867
- parentSlot: PipelineSlotSchema.nullable(),
17868
- addons: array(PipelineAddonSchemaSchema).readonly()
17917
+ var AnalyticsGroupDetailSchema = AnalyticsGroupRecordSchema.extend({ members: array(AnalyticsGroupMemberSchema).readonly() });
17918
+ var ListGroupsQueryInput = object({
17919
+ /** Devices to merge. An empty array yields `{ groups: [], nextCursor: null }`. */
17920
+ deviceIds: array(number()),
17921
+ /** Window lower bound on `closedAt` (inclusive). */
17922
+ since: number().optional(),
17923
+ /** Window upper bound on `openedAt` (inclusive). */
17924
+ until: number().optional(),
17925
+ limit: number().int().min(1).max(LIST_GROUPS_MAX_LIMIT).default(LIST_GROUPS_DEFAULT_LIMIT),
17926
+ /** Opaque continuation cursor from a previous page's `nextCursor`. */
17927
+ cursor: string().optional()
17869
17928
  });
17870
- var PipelineSchemaSchema = object({
17871
- availableEngines: array(AvailableEngineSchema).readonly(),
17872
- selectedEngine: PipelineEngineChoiceSchema,
17873
- slots: array(PipelineSlotSchemaSchema).readonly()
17929
+ var ListGroupsPageSchema = object({
17930
+ groups: array(AnalyticsGroupRecordSchema).readonly(),
17931
+ nextCursor: string().nullable()
17874
17932
  });
17875
- var EngineProvisioningSchema = object({
17876
- runtimeId: _enum([
17877
- "onnx",
17878
- "openvino",
17879
- "coreml",
17880
- "edgetpu"
17881
- ]).nullable(),
17882
- device: string().nullable(),
17883
- state: _enum([
17884
- "idle",
17885
- "installing",
17886
- "verifying",
17887
- "ready",
17888
- "failed"
17889
- ]),
17890
- progress: number().optional(),
17891
- error: string().optional(),
17892
- nextRetryAt: number().optional(),
17893
- /**
17894
- * Gate A (config-correctness gate at engine change): human-readable
17895
- * config issues surfaced EAGERLY when the node's engine changes — model
17896
- * substitutions ("chose X, running Y") and zero-build steps ("no model
17897
- * has a <format> build"). Additive/optional: informational only, never
17898
- * enforced here — `assertEngineReady` (readiness) still gates inference.
17899
- * Absent/empty when the node-default tree resolves cleanly.
17900
- */
17901
- configIssues: array(string()).optional()
17933
+ var KeyEventQueryInput = object({
17934
+ deviceId: number(),
17935
+ /** Window lower bound (track firstSeen ≥ since). */
17936
+ since: number(),
17937
+ /** Window upper bound (track firstSeen ≤ until). */
17938
+ until: number(),
17939
+ limit: number().int().min(1).max(200).default(50),
17940
+ /** Drop tracks scoring below this importance. */
17941
+ minImportance: number().min(0).max(1).optional(),
17942
+ /** Restrict to a single class (e.g. 'person'). */
17943
+ classFilter: string().optional()
17902
17944
  });
17903
- var PipelineStepInputSchema = lazy(() => object({
17904
- addonId: string(),
17905
- modelId: string().optional(),
17906
- enabled: boolean().default(true),
17907
- children: array(PipelineStepInputSchema).optional(),
17908
- settings: record(string(), unknown()).optional(),
17909
- jumpDeviceKey: string().optional()
17910
- }));
17911
- var ModelSubstitutionSchema = object({
17912
- addonId: string(),
17913
- chosen: string(),
17914
- running: string(),
17915
- format: string()
17945
+ var KeyEventSchema = object({
17946
+ /** The representative event id (the track's best ObjectEvent, else its trackId). */
17947
+ id: string(),
17948
+ trackId: string(),
17949
+ /** Track start time (firstSeen). */
17950
+ timestamp: number(),
17951
+ className: string(),
17952
+ ...TieredLabelFields,
17953
+ importance: number(),
17954
+ /** Highest-confidence ObjectEvent id for the track (empty when none). */
17955
+ bestEventId: string(),
17956
+ /** Track lifetime in ms (lastSeen - firstSeen). */
17957
+ windowMs: number().optional(),
17958
+ ...TrackFlagFields,
17959
+ ...TrackRetrainFields
17916
17960
  });
17917
- var PipelineValidationIssueSchema = object({
17918
- addonId: string(),
17919
- kind: _enum(["unknown-addon", "no-format-build"]),
17920
- detail: string()
17961
+ object({
17962
+ trackId: string(),
17963
+ className: string(),
17964
+ confidence: number(),
17965
+ bbox: BoundingBoxSchema,
17966
+ zones: array(string()).readonly(),
17967
+ state: TrackStateSchema
17921
17968
  });
17922
- var PipelineValidationResultSchema = object({
17923
- ok: boolean(),
17924
- issues: array(PipelineValidationIssueSchema).readonly(),
17925
- substitutions: array(ModelSubstitutionSchema).readonly(),
17926
- /** The node's `currentEngine.format` this validation ran against. */
17927
- format: string()
17969
+ var OverlayDetectionSchema = looseObject({
17970
+ id: string(),
17971
+ kind: _enum(["first-level", "detail"]),
17972
+ macroClass: string(),
17973
+ score: number(),
17974
+ bbox: object({
17975
+ x: number(),
17976
+ y: number(),
17977
+ width: number(),
17978
+ height: number()
17979
+ }),
17980
+ labels: array(looseObject({
17981
+ label: string(),
17982
+ score: number()
17983
+ })).readonly(),
17984
+ parentId: string().optional()
17985
+ });
17986
+ var ScoredObjectEventSchema = ObjectEventSchema.extend({ score: number() });
17987
+ var SearchObjectEventsInput = object({
17988
+ text: string(),
17989
+ deviceId: number().optional(),
17990
+ since: number().optional(),
17991
+ until: number().optional(),
17992
+ classFilter: string().optional(),
17993
+ limit: number().default(50),
17994
+ minScore: number().min(0).max(1).default(.2)
17995
+ });
17996
+ var TrackCascadeCountsSchema = object({
17997
+ /** Persisted track roots deleted (authoritative). */
17998
+ tracks: number().int(),
17999
+ /** Object events removed with their tracks (best-effort; see note above). */
18000
+ events: number().int(),
18001
+ /** Track/face/plate-owned media removed (best-effort). Never identity media. */
18002
+ media: number().int(),
18003
+ /** Unassigned (non-enrolled) face reads removed (best-effort). */
18004
+ faces: number().int(),
18005
+ /** Unassigned plate reads removed (best-effort; plate leg deferred to plate-intelligence). */
18006
+ plates: number().int(),
18007
+ /** Per-track CLIP search vectors removed (best-effort). */
18008
+ embeddings: number().int(),
18009
+ /** Group membership + group rows removed with their last member (best-effort). */
18010
+ groups: number().int()
17928
18011
  });
17929
- var ReferenceImageEntrySchema = object({
17930
- filename: string(),
17931
- stepIds: array(string()).readonly().optional()
18012
+ /** Disk-wins reconcile: media rows whose blobs are gone, then empty tracks. */
18013
+ var DiskReconcileCountsSchema = object({
18014
+ mediaDropped: number().int(),
18015
+ tracks: number().int(),
18016
+ events: number().int()
17932
18017
  });
17933
- var ReferenceImageBodySchema = object({
17934
- base64: string(),
17935
- filename: string()
18018
+ /** Event-store footprint for one camera. */
18019
+ var EventStoreDeviceFootprintSchema = object({
18020
+ deviceId: number(),
18021
+ /** Persisted event rows (motion + object + audio) for the camera. */
18022
+ rows: number().int(),
18023
+ /** Event-owned media bytes on disk for the camera. */
18024
+ bytes: number().int()
17936
18025
  });
17937
- var ReferenceAudioEntrySchema = object({
17938
- filename: string(),
17939
- sizeKb: number()
18026
+ /** Aggregate event-store footprint: global totals + per-camera breakdown. */
18027
+ var EventStoreFootprintSchema = object({
18028
+ totalRows: number().int(),
18029
+ totalBytes: number().int(),
18030
+ devices: array(EventStoreDeviceFootprintSchema).readonly()
17940
18031
  });
17941
- var ReferenceAudioBodySchema = object({ base64: string() });
17942
- var AudioBackendSchema = object({
17943
- id: string(),
17944
- name: string(),
17945
- description: string(),
17946
- available: boolean(),
18032
+ /** Per-kind counts returned by the event-prune / device-delete mutations. */
18033
+ var EventPruneCountsSchema = object({
18034
+ motion: number().int(),
18035
+ object: number().int(),
18036
+ audio: number().int()
18037
+ });
18038
+ /**
18039
+ * Re-embed stored tracks from their key frames.
18040
+ *
18041
+ * The reason this is an operator-callable method and not a migration script:
18042
+ * every knob that decides what a vector MEANS — encoder model, crop margin,
18043
+ * squaring — is only changeable if the existing vectors can be regenerated.
18044
+ * Mixing feature spaces in one index makes cosine scores incomparable, and the
18045
+ * symptom is a quality regression with no visible cause.
18046
+ */
18047
+ var RebuildObjectEmbeddingsInput = object({
18048
+ /** Restrict to one camera. Omit for the whole fleet. */
18049
+ deviceId: number().optional(),
18050
+ since: number().optional(),
18051
+ until: number().optional(),
18052
+ /** Stop after this many tracks; the result reports whether more remain. */
18053
+ maxTracks: number().int().positive().optional(),
17947
18054
  /**
17948
- * Raw classifier labels this backend can emit (e.g. YAMNet's
17949
- * 521-class set or Apple SoundAnalysis's 303-class set). Used by
17950
- * the benchmark UI to populate the `enabledMicroClasses` filter
17951
- * specific to the selected backend without a separate fetch.
18055
+ * Run every embedding on THIS node instead of round-robining the fleet.
18056
+ *
18057
+ * Named `executeOnNodeId` and not `nodeId` on purpose: an inline `nodeId`
18058
+ * field in cap args is read by `parent-unowned-call.ts` as a ROUTING PIN, so
18059
+ * calling it that would pin the rebuild REQUEST itself to that node — the
18060
+ * rebuild orchestration lives on the hub, and only the per-track step runs
18061
+ * remotely. This field is data; the per-track pin is applied inside.
18062
+ *
18063
+ * Absent ⇒ round-robin over every online node whose runner can serve the
18064
+ * pinned model.
17952
18065
  */
17953
- rawLabels: array(string()).readonly().optional()
17954
- });
17955
- var AudioCapabilitiesSchema = object({
17956
- activeBackend: string(),
17957
- availableBackends: array(AudioBackendSchema).readonly(),
17958
- sampleRate: number(),
17959
- chunkDurationMs: number()
17960
- });
17961
- var DownloadModelResultSchema = object({
17962
- filePath: string(),
17963
- sizeMB: number(),
17964
- durationMs: number()
18066
+ executeOnNodeId: string().optional(),
18067
+ /**
18068
+ * Milliseconds to wait between tracks; omit for the built-in default, `0` to
18069
+ * run flat out.
18070
+ *
18071
+ * A rebuild is bulk maintenance on hub-main's single thread. Measured
18072
+ * 2026-08-06, an unpaced pass held that thread busy 82.2 s out of 120 and
18073
+ * pushed `nodes.topology` from 0.25 s to 26 s for 43 minutes. The value in
18074
+ * force is logged at start and finish so a deliberately slow pass reads
18075
+ * differently from a stalled one.
18076
+ */
18077
+ pacingMs: number().int().nonnegative().optional()
17965
18078
  });
17966
18079
  /**
17967
- * Wrapper carrying a single test run's result. Replaces the legacy
17968
- * ad-hoc `{labels: [{className, originalClass, score}]}` shape with the
17969
- * canonical `AudioResult` from the Phase 6 output rework: one
17970
- * `AudioDetection` per class above `minScore`, top-N candidates in
17971
- * `debug.alternateLabels['audio-classifier']`, per-source timings in
17972
- * `debug.stepTimings`. The outer `success`/`error` fields stay so the
17973
- * benchmark UI can still report a clean failure when the classifier
17974
- * cap isn't available.
18080
+ * Result of emptying the CLIP index.
18081
+ *
18082
+ * The clean slate before a policy change: a new crop margin or encoder model
18083
+ * leaves two feature spaces in one index whose cosine scores are not
18084
+ * comparable, so wiping and rebuilding is the only way to be sure every vector
18085
+ * means the same thing.
17975
18086
  */
17976
- var AudioTestResultSchema = object({
17977
- success: boolean(),
17978
- error: string().optional(),
17979
- frame: custom().optional()
18087
+ var WipeObjectEmbeddingsResultSchema = object({ deleted: number() });
18088
+ /**
18089
+ * Acknowledgement that a rebuild STARTED.
18090
+ *
18091
+ * The pass costs ~1s per track — 45 minutes for a 2,600-track fleet — so it
18092
+ * runs detached and this returns immediately. Waiting for it made the client
18093
+ * time out while the work carried on server-side, which is the worst of both:
18094
+ * no result and no way to know it was still going. Poll
18095
+ * `getObjectEmbeddingRebuildStatus` for progress.
18096
+ */
18097
+ var RebuildObjectEmbeddingsResultSchema = object({
18098
+ started: boolean(),
18099
+ /** True when a pass was already running; the new request is ignored. */
18100
+ alreadyRunning: boolean()
17980
18101
  });
17981
- var PipelineConfigBridge = custom();
17982
- var ConfigUISchemaBridge = custom();
17983
- var ConfigUISchemaNullableBridge = custom();
17984
- var InferenceCapabilitiesBridge = custom();
17985
- var ModelAvailabilityListBridge = custom();
17986
- var PipelineRunResultBridge = custom();
17987
- method(_void(), array(PipelineEngineChoiceSchema)), method(_void(), PipelineEngineChoiceSchema), method(PipelineEngineChoiceSchema, array(PipelineDefaultStepSchema)), method(object({ nodeId: string() }), EngineProvisioningSchema), method(_void(), record(string(), object({
17988
- modelId: string(),
17989
- settings: record(string(), unknown()).readonly()
17990
- }))), method(object({ steps: record(string(), object({
17991
- modelId: string(),
17992
- settings: record(string(), unknown()).readonly()
17993
- })) }), object({ success: literal(true) }), {
18102
+ var RebuildStatusSchema = object({
18103
+ running: boolean(),
18104
+ scanned: number(),
18105
+ rebuilt: number(),
18106
+ /** Tracks whose key frame is gone — nothing to re-embed from. */
18107
+ missingKeyFrame: number(),
18108
+ /** Tracks with no usable detection box. */
18109
+ missingBbox: number(),
18110
+ /**
18111
+ * Tracks an executing node REFUSED rather than broke on — an unreadable key
18112
+ * frame, a step that threw. Separate from `failed` because the remedy is
18113
+ * different, and because a whole camera silently contributing zero vectors
18114
+ * is the shape of failure a rebuild must never hide.
18115
+ */
18116
+ notRunnable: number(),
18117
+ /**
18118
+ * The pass stopped because NO node could serve the pinned model.
18119
+ *
18120
+ * Distinct from `notRunnable` on purpose: that one says "this track was
18121
+ * refused", this one says "the cluster cannot do this work at all" — every
18122
+ * candidate node either lacks the `clip-embedding` step, lacks a build of the
18123
+ * pinned model for its engine format, or dropped out. The remedy is a model /
18124
+ * engine change, not a per-camera one. Non-zero here always comes with
18125
+ * `complete: false`.
18126
+ */
18127
+ noCapableNode: number(),
18128
+ failed: number(),
18129
+ /** Set once a pass ends: true only when EVERYTHING was covered. */
18130
+ complete: boolean().nullable(),
18131
+ startedAtMs: number().nullable(),
18132
+ finishedAtMs: number().nullable(),
18133
+ /** Present when the pass ended by throwing. */
18134
+ error: string().nullable()
18135
+ });
18136
+ var ReplayFrameInputSchema = object({
18137
+ timestamp: number(),
18138
+ frame: PipelineRunResultBridge
18139
+ });
18140
+ var RunReplayFrameProcessorResultSchema = object({ tracks: array(object({
18141
+ className: string(),
18142
+ firstSeenMs: number(),
18143
+ lastSeenMs: number(),
18144
+ /** Bbox of the track's FIRST matched detection, pixel-space in the clip's
18145
+ * frame — a representative box for the diff's `(className, window, IoU)`
18146
+ * pairing (`replay-diff.ts`). A replay does not need the full per-frame
18147
+ * trajectory production's `Track.positions` keeps. */
18148
+ bbox: BoundingBoxSchema,
18149
+ /** How many of the input frames this track matched a real detection on
18150
+ * (never a coasted/extrapolated frame) — the replay's own signal for "how
18151
+ * solid is this track", cheaper than re-deriving it from a trajectory. */
18152
+ framesMatched: number().int()
18153
+ })).readonly() });
18154
+ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).readonly()), method(object({
18155
+ deviceId: number(),
18156
+ trackId: string()
18157
+ }), TrackSchema.nullable()), method(object({
18158
+ deviceId: number(),
18159
+ since: number().optional(),
18160
+ until: number().optional(),
18161
+ limit: number().optional(),
18162
+ /** Spatial filter — only tracks whose trajectory intersects the zone
18163
+ * (normalized 0..1 rect or polygon). SQL-prefiltered on the persisted
18164
+ * envelope columns, then precisely tested per position. Tracks with
18165
+ * an unknown envelope (no frame dims at persist time) always match. */
18166
+ zone: TrackZoneFilterSchema.optional(),
18167
+ /** See {@link TrackProjectionSchema}. Default `full` (backward
18168
+ * compatible — omitting the field keeps today's exact behaviour). */
18169
+ projection: TrackProjectionSchema.optional(),
18170
+ /** Include stationary-promoted rows (parked objects handed to the
18171
+ * stationary registry). Default false: the timeline lists passages,
18172
+ * not parking records (operator decision, 2026-08-15). */
18173
+ includeStationary: boolean().optional()
18174
+ }), array(TrackSchema).readonly()), method(RecentTracksQueryInput, RecentTracksPageSchema), method(ListGroupsQueryInput, ListGroupsPageSchema), method(object({
18175
+ deviceId: number(),
18176
+ groupId: string().min(1)
18177
+ }), AnalyticsGroupDetailSchema.nullable()), method(object({ deviceId: number() }), _void(), {
18178
+ kind: "mutation",
18179
+ auth: "admin"
18180
+ }), method(DeviceEventQueryInput, array(MotionEventSchema).readonly()), method(ObjectEventQueryInput, array(ObjectEventSchema).readonly()), method(DeviceEventQueryInput, array(AudioEventSchema).readonly()), method(object({ deviceId: number() }), array(EventKindDescriptorSchema).readonly()), method(object({ deviceIds: array(number()).min(1).max(200) }), array(EventKindsForDeviceSchema).readonly()), method(object({
18181
+ deviceId: number(),
18182
+ since: number().optional(),
18183
+ until: number().optional(),
18184
+ kinds: array(string()).optional(),
18185
+ limit: number().int().min(1).max(MAX_EVENT_QUERY_LIMIT).default(DEFAULT_EVENT_QUERY_LIMIT)
18186
+ }), array(SensorEventSchema).readonly()), method(KeyEventQueryInput, array(KeyEventSchema).readonly()), method(object({
18187
+ deviceId: number(),
18188
+ since: number(),
18189
+ until: number(),
18190
+ bucketMs: number().int().positive()
18191
+ }), array(object({
18192
+ bucketStart: number(),
18193
+ motion: number().int(),
18194
+ object: number().int(),
18195
+ audio: number().int()
18196
+ })).readonly()), method(object({
18197
+ deviceId: number(),
18198
+ cutoffMs: number()
18199
+ }), object({
18200
+ motion: number().int(),
18201
+ object: number().int(),
18202
+ audio: number().int()
18203
+ }), {
18204
+ kind: "mutation",
18205
+ auth: "admin"
18206
+ }), method(object({
18207
+ deviceId: number(),
18208
+ cutoffMs: number()
18209
+ }), TrackCascadeCountsSchema, {
18210
+ kind: "mutation",
18211
+ auth: "admin"
18212
+ }), method(object({ deviceId: number() }), TrackCascadeCountsSchema, {
18213
+ kind: "mutation",
18214
+ auth: "admin"
18215
+ }), method(object({ deviceId: number() }), DiskReconcileCountsSchema, {
18216
+ kind: "mutation",
18217
+ auth: "admin"
18218
+ }), method(object({
18219
+ deviceId: number(),
18220
+ trackIds: array(string()).min(1)
18221
+ }), object({
18222
+ deleted: number().int(),
18223
+ failed: array(string()).readonly()
18224
+ }), {
18225
+ kind: "mutation",
18226
+ auth: "admin"
18227
+ }), method(object({
18228
+ /** Log/audit scope only — the trackId is globally unique on its own. */
18229
+ deviceId: number(),
18230
+ trackId: string(),
18231
+ flags: TrackFlagsPatchSchema
18232
+ }), TrackFlagsSchema, { kind: "mutation" }), method(object({}), EventStoreFootprintSchema, {
18233
+ kind: "query",
18234
+ auth: "admin"
18235
+ }), method(object({
18236
+ olderThanMs: number(),
18237
+ reason: OpsLogReasonSchema.optional()
18238
+ }), EventPruneCountsSchema, {
17994
18239
  kind: "mutation",
17995
18240
  auth: "admin"
17996
- }), method(object({ nodeId: string() }), object({
17997
- success: literal(true),
17998
- clearedDevices: number()
17999
- }), {
18241
+ }), method(object({ deviceId: number() }), EventPruneCountsSchema, {
18000
18242
  kind: "mutation",
18001
18243
  auth: "admin"
18002
- }), method(_void(), PipelineSchemaSchema), method(_void(), array(PipelineDefaultStepSchema).readonly().nullable()), method(_void(), PipelineConfigBridge), method(_void(), ConfigUISchemaBridge), method(object({ steps: array(PipelineStepInputSchema) }), PipelineValidationResultSchema), method(_void(), array(PipelineTemplateSchema$1).readonly()), method(object({
18003
- name: string(),
18004
- steps: array(PipelineTemplateStepSchema).readonly(),
18005
- engine: PipelineEngineChoiceSchema
18006
- }), PipelineTemplateSchema$1, { kind: "mutation" }), method(object({
18007
- id: string(),
18008
- name: string().optional(),
18009
- steps: array(PipelineTemplateStepSchema).readonly().optional()
18010
- }), PipelineTemplateSchema$1, { kind: "mutation" }), method(object({ id: string() }), _void(), { kind: "mutation" }), method(_void(), InferenceCapabilitiesBridge), method(object({ addonId: string() }), ModelAvailabilityListBridge), method(object({
18011
- addonId: string(),
18012
- modelId: string(),
18013
- format: ModelFormatSchema$1
18014
- }), DownloadModelResultSchema, { kind: "mutation" }), method(object({
18015
- addonId: string(),
18016
- modelId: string(),
18017
- format: ModelFormatSchema$1
18018
- }), object({ success: literal(true) }), { kind: "mutation" }), method(object({
18019
- engine: PipelineEngineChoiceSchema.optional(),
18020
- steps: array(PipelineStepInputSchema).min(1),
18021
- frame: FrameInputSchema.optional(),
18022
- /**
18023
- * Process-local lazy frame. Valid only when caller and provider resolve
18024
- * in the same execution-group process; split/cross-node callers use
18025
- * `frame`/`image` inline compatibility instead.
18026
- */
18027
- frameRef: FrameRefSchema.optional(),
18028
- /**
18029
- * CB5 shm passthrough a `FrameHandle` naming the same ring slot
18030
- * the decoded pixels live in. One more member of the one-of
18031
- * frame/frameHandle/image/imageBase64/referenceImage group.
18032
- */
18033
- frameHandle: FrameHandleSchema.optional(),
18034
- imageBase64: string().optional(),
18035
- /**
18036
- * Binary JPEG bytes preferred over `imageBase64` on internal
18037
- * hops (hub forked worker via Moleculer MsgPack) because it
18038
- * skips the 33% base64 overhead + the per-call base64 decode on
18039
- * the detection-pipeline worker. Callers can pass either; exactly
18040
- * one of `frame`/`image`/`imageBase64`/`referenceImage` is required.
18041
- */
18042
- image: _instanceof(Uint8Array).optional(),
18043
- referenceImage: string().optional(),
18044
- deviceId: number().optional(),
18045
- sessionId: string().optional(),
18046
- /**
18047
- * Execution plane. 'full' (default) runs the whole tree — benchmark,
18048
- * reference-image, and detail-subtree calls. 'frame' is the live
18049
- * per-frame dispatch: ONLY root-plane steps run; crop children
18050
- * (inputClasses ≠ null) are skipped and served per-track via
18051
- * pipelineRunner.runDetailSubtree (two-plane design).
18052
- */
18053
- plane: _enum(["full", "frame"]).optional(),
18054
- /**
18055
- * Inference-device selector (Phase 2 multi-device). Format
18056
- * `<backend>:<device>` (e.g. `openvino:gpu`, `edgetpu:usb`, `cpu`).
18057
- * Omitted ⇒ the runner's default device (current single-engine
18058
- * behaviour). Selects WHICH device pool of the node runs the call.
18059
- */
18060
- deviceKey: string().optional(),
18061
- /**
18062
- * Two-plane NATIVE child-crop reference. Set by `runDetailSubtree` ONLY
18063
- * when the parent crop was resolved from the frame's retained NATIVE
18064
- * surface (a frameHandle HIT). Lets the executor re-cut a LEAF crop
18065
- * child's ROI (plate-ocr, face-embedding, leaf classifiers) at native
18066
- * resolution from that surface — the SAME quality path faces already
18067
- * had — instead of the downscaled parent tile. `handle` keys the native
18068
- * surface (node-pinned to its owner); `cropFrameSpace` is the parent
18069
- * crop's padded/clamped rectangle in FRAME-space pixels, used to compose
18070
- * the executor's crop-normalized child ROI back into frame-normalized
18071
- * coordinates. Auxiliary to the image source (`image`/`frame`/…), NOT one
18072
- * of the mutually-exclusive image inputs. Absent ⇒ tile-crop children
18073
- * (today's behaviour on the fallback path).
18074
- */
18075
- nativeCropRef: NativeCropRefSchema.optional()
18076
- }), PipelineRunResultBridge, { kind: "mutation" }), method(object({
18077
- engine: PipelineEngineChoiceSchema.optional(),
18078
- steps: array(PipelineStepInputSchema).min(1),
18079
- frames: array(FrameInputSchema).min(1).max(255),
18080
- deviceId: number().optional(),
18081
- sessionId: string().optional(),
18082
- /**
18083
- * Pure-inference benchmark hint. A NONZERO uint32 pins every frame in
18084
- * the batch to the Python pool's bench preprocess cache
18085
- * (`_bench_frame_id`) so a REPEATED benchmark frame is decoded +
18086
- * preprocessed ONCE and every later inference is a pure-inference cache
18087
- * hit — the sustained-throughput run measures inference, not
18088
- * decode+preprocess+infer. Omitted/0 for live frames (all different →
18089
- * full preprocess every call, correct). Fresh per sustained run;
18090
- * released via `uncacheFrame`.
18091
- */
18092
- frameId: number().int().nonnegative().optional(),
18093
- /** Inference-device selector (Phase 2 multi-device); see runPipeline. */
18094
- deviceKey: string().optional()
18095
- }), object({ results: array(PipelineRunResultBridge).readonly() }), { kind: "mutation" }), method(object({
18096
- data: _instanceof(Uint8Array),
18097
- width: number().int().positive(),
18098
- height: number().int().positive(),
18099
- format: _enum([
18100
- "rgb",
18101
- "bgr",
18102
- "gray"
18103
- ])
18244
+ }), method(StorageMigrationLeaseInputSchema, object({ paused: literal(true) }), {
18245
+ kind: "mutation",
18246
+ auth: "admin"
18247
+ }), method(StorageMigrationLeaseInputSchema, object({ resumed: literal(true) }), {
18248
+ kind: "mutation",
18249
+ auth: "admin"
18250
+ }), method(StorageMigrationLeaseInputSchema, object({ refreshed: literal(true) }), {
18251
+ kind: "mutation",
18252
+ auth: "admin"
18253
+ }), method(StorageMigrationMediaMoveInputSchema, object({ jobId: string() }), {
18254
+ kind: "mutation",
18255
+ auth: "admin"
18256
+ }), method(object({ jobId: string() }), RelocateJobSchema.nullable(), { auth: "admin" }), method(object({ jobId: string() }), object({ cancelled: boolean() }), {
18257
+ kind: "mutation",
18258
+ auth: "admin"
18259
+ }), method(RelocateMediaInputSchema, object({ jobId: string() }), {
18260
+ kind: "mutation",
18261
+ auth: "admin"
18262
+ }), method(object({}), array(RelocateJobSchema).readonly(), {
18263
+ kind: "query",
18264
+ auth: "admin"
18265
+ }), method(object({ jobId: string() }), object({ cancelled: boolean() }), {
18266
+ kind: "mutation",
18267
+ auth: "admin"
18268
+ }), method(OpsLogQueryInputSchema, array(OpsLogEntrySchema).readonly(), {
18269
+ kind: "query",
18270
+ auth: "admin"
18271
+ }), method(object({ deviceIds: array(number()).optional() }), TrainingExportSummarySchema, {
18272
+ kind: "query",
18273
+ auth: "admin"
18274
+ }), method(object({ deviceIds: array(number()).optional() }), object({ url: string() }), {
18275
+ kind: "query",
18276
+ auth: "admin"
18277
+ }), method(object({
18278
+ /** Empty every camera that has staging tracks. A LIST, not a single
18279
+ * `deviceId`, deliberately: `deviceId` would make this device-bound and
18280
+ * route it at one camera's owner, and "every camera" would stop being
18281
+ * expressible at all. */
18282
+ deviceIds: array(number()).optional(),
18283
+ limit: number().int().min(1).max(500).optional()
18284
+ }), array(RetrainTrackSchema).readonly(), {
18285
+ kind: "query",
18286
+ auth: "admin"
18287
+ }), method(object({ trackId: string() }), RetrainFrameListSchema, {
18288
+ kind: "query",
18289
+ auth: "admin"
18290
+ }), method(object({
18291
+ deviceId: number(),
18292
+ trackId: string(),
18293
+ mediaKeys: array(string()).min(1)
18294
+ }), RetrainFrameSelectionSchema, {
18295
+ kind: "mutation",
18296
+ auth: "admin"
18297
+ }), method(object({
18298
+ deviceId: number(),
18299
+ trackId: string(),
18300
+ frameId: string()
18104
18301
  }), object({
18105
- frameId: number(),
18106
- width: number(),
18107
- height: number()
18108
- }), { kind: "mutation" }), method(object({
18109
- stepId: string(),
18110
- frameId: number().int()
18111
- }), record(string(), unknown()), { kind: "mutation" }), method(object({ frameId: number().int() }), _void(), { kind: "mutation" }), method(_void(), object({
18112
- batchMode: string(),
18113
- windowMs: number(),
18114
- maxBatchSize: number(),
18115
- concurrency: number()
18116
- })), method(_void(), array(object({
18117
- engineKey: string(),
18118
- engine: PipelineEngineChoiceSchema,
18119
- modelsLoaded: array(string()).readonly(),
18120
- inUseByCameras: array(number()).readonly(),
18121
- /**
18122
- * Origin of this resident factory.
18123
- * - `runtime` — main camera-serving engine (no idle TTL).
18124
- * - `warm-override` — benchmark/test override held in the warm
18125
- * cache; auto-disposed after the idle TTL.
18126
- * - `device-pool` — a concurrent per-device pool (Phase 2
18127
- * multi-device, keyed by `deviceKey`) resolved
18128
- * via `resolveDeviceFactory`. Runs alongside the
18129
- * `runtime` engine on a DIFFERENT accelerator
18130
- * (NPU / iGPU / Coral) — this is how the
18131
- * Engines tab shows all pools running at once.
18132
- */
18133
- kind: _enum([
18134
- "runtime",
18135
- "warm-override",
18136
- "device-pool"
18137
- ]),
18138
- /** Native pid of the underlying Python pool (null when no pool). */
18139
- poolPid: number().nullable(),
18140
- /** ms since this factory was last used (null when not warm-tracked). */
18141
- idleMs: number().nullable(),
18142
- /** Idle TTL after which `warm-override` factories self-evict (null when not applicable). */
18143
- idleTtlMs: number().nullable()
18144
- })).readonly()), method(object({ engine: PipelineEngineChoiceSchema }), object({ success: literal(true) }), {
18302
+ removed: boolean(),
18303
+ removedAnnotations: number().int()
18304
+ }), {
18305
+ kind: "mutation",
18306
+ auth: "admin"
18307
+ }), method(object({ frameId: string() }), object({
18308
+ base64: string(),
18309
+ width: number().int(),
18310
+ height: number().int()
18311
+ }), {
18312
+ kind: "query",
18313
+ auth: "admin"
18314
+ }), method(object({
18315
+ deviceId: number(),
18316
+ trackId: string(),
18317
+ frameId: string(),
18318
+ subject: RetrainAssistSubjectSchema,
18319
+ /** Which node runs it. Absent ⇒ wherever an unowned call lands. */
18320
+ nodeId: string().optional()
18321
+ }), RetrainAssistResultSchema, {
18322
+ kind: "mutation",
18323
+ auth: "admin"
18324
+ }), method(object({
18325
+ deviceId: number(),
18326
+ source: DetectionSourceSchema,
18327
+ zones: array(ZoneSchema).readonly().optional(),
18328
+ detectionRules: array(ZoneRuleSchema).readonly().optional(),
18329
+ zoneMembershipMinOverlap: number().min(0).max(1).optional(),
18330
+ frames: array(ReplayFrameInputSchema).min(1)
18331
+ }), RunReplayFrameProcessorResultSchema, {
18332
+ kind: "mutation",
18333
+ auth: "admin"
18334
+ }), method(object({ trackId: string() }), array(RetrainAnnotationSchema).readonly(), {
18335
+ kind: "query",
18336
+ auth: "admin"
18337
+ }), method(object({
18338
+ deviceId: number(),
18339
+ trackId: string(),
18340
+ frameId: string(),
18341
+ annotations: array(RetrainAnnotationDraftSchema)
18342
+ }), array(RetrainAnnotationSchema).readonly(), {
18343
+ kind: "mutation",
18344
+ auth: "admin"
18345
+ }), method(object({
18346
+ deviceId: number(),
18347
+ trackId: string()
18348
+ }), RetrainTransitionResultSchema, {
18349
+ kind: "mutation",
18350
+ auth: "admin"
18351
+ }), method(object({
18352
+ deviceId: number(),
18353
+ trackId: string()
18354
+ }), RetrainTransitionResultSchema, {
18145
18355
  kind: "mutation",
18146
18356
  auth: "admin"
18357
+ }), method(object({ deviceIds: array(number()).optional() }), object({ url: string() }), {
18358
+ kind: "query",
18359
+ auth: "admin"
18147
18360
  }), method(object({
18148
- engine: PipelineEngineChoiceSchema,
18149
- force: boolean().optional()
18150
- }), object({
18151
- success: boolean(),
18152
- reason: string().optional()
18153
- }), {
18361
+ eventId: string(),
18362
+ kind: MediaFileKindEnum.optional(),
18363
+ deviceId: number()
18364
+ }), array(MediaFileSchema).readonly()), method(object({
18365
+ trackId: string(),
18366
+ kinds: array(MediaFileKindEnum).optional(),
18367
+ deviceId: number()
18368
+ }), array(MediaFileSchema).readonly()), method(object({
18369
+ trackId: string(),
18370
+ deviceId: number()
18371
+ }), array(MediaFileInfoSchema).readonly()), method(SearchObjectEventsInput, array(ScoredObjectEventSchema).readonly()), method(object({}), WipeObjectEmbeddingsResultSchema, {
18154
18372
  kind: "mutation",
18155
18373
  auth: "admin"
18156
- }), method(_void(), array(ReferenceImageEntrySchema).readonly()), method(object({ filename: string() }), ReferenceImageBodySchema.nullable()), method(_void(), array(ReferenceAudioEntrySchema).readonly()), method(object({ filename: string() }), ReferenceAudioBodySchema.nullable()), method(_void(), AudioCapabilitiesSchema), method(object({
18157
- addonId: string(),
18158
- modelId: string(),
18159
- filename: string().optional(),
18160
- settings: record(string(), unknown()).optional()
18161
- }), AudioTestResultSchema, { kind: "mutation" }), method(_void(), ConfigUISchemaNullableBridge);
18374
+ }), method(RebuildObjectEmbeddingsInput, RebuildObjectEmbeddingsResultSchema, {
18375
+ kind: "mutation",
18376
+ auth: "admin"
18377
+ }), method(object({}), RebuildStatusSchema), object({
18378
+ deviceId: number(),
18379
+ timestamp: number(),
18380
+ frameWidth: number(),
18381
+ frameHeight: number(),
18382
+ detections: array(OverlayDetectionSchema).readonly()
18383
+ }), object({
18384
+ deviceId: number(),
18385
+ trackId: string(),
18386
+ className: string()
18387
+ }), object({
18388
+ deviceId: number(),
18389
+ trackId: string(),
18390
+ className: string(),
18391
+ durationMs: number()
18392
+ }), object({
18393
+ deviceId: number(),
18394
+ kind: EventKindSchema,
18395
+ eventId: string(),
18396
+ timestamp: number()
18397
+ });
18162
18398
  object({
18163
18399
  activeCameras: number(),
18164
18400
  throttledCameras: number(),
@@ -18184,106 +18420,6 @@ var CameraMetricsSchema = object({
18184
18420
  });
18185
18421
  var CameraMetricsWithDeviceIdSchema = CameraMetricsSchema.extend({ deviceId: number() });
18186
18422
  /**
18187
- * Zone — pure geometry + identity. NO filtering behaviour.
18188
- *
18189
- * Zones describe **where** in the frame the operator wants to flag
18190
- * something; consumer-owned {@link ZoneRule} arrays describe **how**
18191
- * each pipeline stage uses them. Splitting the two means a single
18192
- * polygon "Driveway" can simultaneously back a motion-exclude rule,
18193
- * a detection-include rule on `['car']`, and an occupancy aggregate
18194
- * — without three duplicated polygons.
18195
- *
18196
- * Owned by the orchestrator addon (provider) and mirrored into the
18197
- * `zones` device-state slice on every mutation. Consumers
18198
- * (motion-wasm, pipeline-executor, analytics, admin UI) read either
18199
- * via `api.zones.listZones` (one-shot) or via `dev.state.zones` (live
18200
- * mirror with `onChanged`).
18201
- *
18202
- * Coordinates are normalised fractions of the frame (0–1) so zones
18203
- * survive resolution changes and stream profile switches.
18204
- *
18205
- * `kind` discriminates between full polygons (closed regions used
18206
- * for intrusion / occupancy filters) and tripwires (open 2-point
18207
- * line segments used for cross events). Onboard / firmware-reported
18208
- * zones (Reolink, ONVIF) are out of scope for now — see the deferred
18209
- * task list.
18210
- */
18211
- var ZoneKindEnum = _enum(["polygon", "tripwire"]);
18212
- /** Polygon vertex in fraction-of-frame coordinates (0–1). */
18213
- var PolygonPointSchema = object({
18214
- x: number(),
18215
- y: number()
18216
- });
18217
- /** A camera detection zone — pure geometry/identity. */
18218
- var ZoneSchema = object({
18219
- id: string(),
18220
- name: string(),
18221
- kind: ZoneKindEnum.default("polygon"),
18222
- /** Polygon vertices, fraction of frame (0–1). */
18223
- polygon: array(PolygonPointSchema).readonly(),
18224
- /** Visual color for UI rendering. */
18225
- color: string().default("#3b82f6")
18226
- });
18227
- /**
18228
- * Zones capability — per-camera CRUD over polygon detection zones.
18229
- *
18230
- * Provider lives in `addon-pipeline-orchestrator` (hub-only). Persists
18231
- * to per-device settings and mirrors into the `zones` device-state
18232
- * slice on every mutation, so downstream consumers can subscribe via
18233
- * `dev.state.zones.onChanged`.
18234
- *
18235
- * The cap surface only handles geometry + identity; filtering
18236
- * behaviour (per-class, include/exclude, threshold) lives in the
18237
- * consumer addons' rule arrays — see `ZoneRuleSchema` exported from
18238
- * `capabilities/schemas/zone-rule.js`.
18239
- */
18240
- var zonesCapability = {
18241
- name: "zones",
18242
- scope: "device",
18243
- mode: "singleton",
18244
- deviceTypes: [DeviceType.Camera],
18245
- methods: {
18246
- listZones: method(object({ deviceId: number() }), array(ZoneSchema).readonly()),
18247
- addZone: method(object({
18248
- deviceId: number(),
18249
- zone: ZoneSchema
18250
- }), _void(), {
18251
- kind: "mutation",
18252
- auth: "admin"
18253
- }),
18254
- removeZone: method(object({
18255
- deviceId: number(),
18256
- zoneId: string()
18257
- }), _void(), {
18258
- kind: "mutation",
18259
- auth: "admin"
18260
- }),
18261
- updateZone: method(object({
18262
- deviceId: number(),
18263
- zone: ZoneSchema
18264
- }), _void(), {
18265
- kind: "mutation",
18266
- auth: "admin"
18267
- })
18268
- },
18269
- /**
18270
- * Runtime-state slice — the live zone catalogue mirrored by the
18271
- * orchestrator on every CRUD mutation. Consumers read via
18272
- * `device.state.zones.value` / `.watch(...)` without round-tripping
18273
- * the cap, and the codegen DeviceProxy auto-wires the reactive
18274
- * handle. Slice shape is `{ zones: Zone[] }` so future extensions
18275
- * (e.g. zone groupings) can sit alongside the polygon list.
18276
- */
18277
- runtimeState: object({ zones: array(ZoneSchema).readonly() }),
18278
- /**
18279
- * Runtime-state durability: **restored** — written only on operator mutation, so a camera that never had one has nothing to re-derive from. This is the slice `zone-mirror-hydration.ts` exists to paper over.
18280
- *
18281
- * See `RuntimeStateDurability`. Enforced by
18282
- * `scripts/check-runtime-state-durability.ts`.
18283
- */
18284
- durability: "restored"
18285
- };
18286
- /**
18287
18423
  * A bounding box in NORMALIZED [0,1] frame coordinates for `getNativeCrop`. The
18288
18424
  * decode worker resolves it against the RETAINED native frame's real pixel dims,
18289
18425
  * so the caller supplies only the detection-res bbox divided by the detection
@@ -27706,92 +27842,6 @@ var sceneMonitorCapability = {
27706
27842
  durability: "session"
27707
27843
  };
27708
27844
  /**
27709
- * Per-stage gating mode applied to the zones a rule references.
27710
- *
27711
- * - `include`: the rule contributes to a **whitelist** for its stage.
27712
- * When at least one `include` rule fires for a stage, only entities
27713
- * inside one of those zones pass that stage.
27714
- * - `exclude`: the rule contributes to a **blacklist** for its stage.
27715
- * Entities inside one of those zones are dropped at that stage.
27716
- *
27717
- * `monitor`-style observation (count without filtering) is not a rule
27718
- * mode — zones without any matching rule are observed naturally by
27719
- * `zone-analytics` (live snapshot + history), so an "I just want to
27720
- * count, not filter" use case needs no rule at all.
27721
- */
27722
- var ZoneRuleModeEnum = _enum(["include", "exclude"]);
27723
- /**
27724
- * Per-consumer rule that references existing zones (geometry) and
27725
- * defines how a specific pipeline stage should treat them. Each
27726
- * consumer addon owns its own `ZoneRule[]` array in its per-device
27727
- * settings:
27728
- *
27729
- * - `addon-motion-wasm` → `motionZoneRules: ZoneRule[]` (motion stage)
27730
- * - `addon-detection-pipeline` → `detectionZoneRules: ZoneRule[]` (detection stage)
27731
- * - future: notification rules, audio gating, etc.
27732
- *
27733
- * One rule applies to N zones (`zoneIds[]`) so the operator can
27734
- * express "ignore motion in ALL of {garden, street}" with a single
27735
- * rule. `classFilter` narrows the rule to specific object classes —
27736
- * "drop person detections in the street, but keep cars" is one
27737
- * `exclude` rule with `classFilter: ['person']`.
27738
- *
27739
- * `enabled` is a soft toggle — the operator can keep the rule
27740
- * configured but inert without deleting it.
27741
- */
27742
- var ZoneRuleSchema = object({
27743
- /** Stable rule id — survives edits, used by the UI for diffing. */
27744
- id: string(),
27745
- /** Optional human-readable label rendered in the rule editor. */
27746
- name: string().optional(),
27747
- /** Zones this rule targets. The rule's `mode` applies to ALL
27748
- * listed zones (OR-set: a detection in any one of them counts).
27749
- * At least one zone id required — a rule with no targets is a
27750
- * configuration mistake and the form validator rejects it. */
27751
- zoneIds: array(string()).min(1).readonly(),
27752
- mode: ZoneRuleModeEnum,
27753
- /**
27754
- * Class names this rule applies to. Empty / undefined ⇒ rule
27755
- * applies to every class. Class strings match the `macroClass`
27756
- * field on detections (e.g. `person`, `car`, `dog`).
27757
- */
27758
- classFilter: array(string()).readonly().optional(),
27759
- /**
27760
- * Minimum bbox/mask overlap (0–1) with any of the rule's zones
27761
- * required to consider an entity "in the zone". Defaults to the
27762
- * consumer's stage default when omitted. Kept for back-compat with
27763
- * existing per-rule overrides; new operators pick the value via
27764
- * `bboxInclusionPct` (operator-friendly 0–100). Whichever field is
27765
- * set, the lower-level engine reads it as a 0–1 fraction.
27766
- */
27767
- overlapThreshold: number().min(0).max(1).optional(),
27768
- /**
27769
- * Operator-friendly version of `overlapThreshold` — the percentage
27770
- * of the detection's bbox that must lie inside the zone for the
27771
- * rule to match. Documented default is 85%; the engine substitutes
27772
- * that when the field is omitted (kept optional so existing rules
27773
- * stored without it stay valid).
27774
- *
27775
- * When BOTH `overlapThreshold` and `bboxInclusionPct` are set on a
27776
- * rule, the engine prefers `bboxInclusionPct` because it's the
27777
- * field exposed in the UI. Internally both feed the same gate.
27778
- */
27779
- bboxInclusionPct: number().min(0).max(100).optional(),
27780
- /**
27781
- * When `true` and a detection has a segmentation mask, use the
27782
- * mask for overlap instead of the bbox. Detection-stage only;
27783
- * motion rules ignore this field.
27784
- */
27785
- preferMask: boolean().optional(),
27786
- /**
27787
- * Soft-toggle: `false` disables the rule without deleting it.
27788
- * Defaults to `true` so operators creating a rule via the UI
27789
- * see it active immediately.
27790
- */
27791
- enabled: boolean().default(true)
27792
- });
27793
- array(ZoneRuleSchema).readonly();
27794
- /**
27795
27845
  * Script-runner cap. Models HA `script.*` entities on
27796
27846
  * `DeviceType.Script`. A Script is a pre-recorded action sequence
27797
27847
  * that can be invoked imperatively — optionally with a variables
@@ -33794,6 +33844,12 @@ Object.freeze({
33794
33844
  addonId: null,
33795
33845
  access: "create"
33796
33846
  },
33847
+ "pipelineAnalytics.runReplayFrameProcessor": {
33848
+ capName: "pipeline-analytics",
33849
+ capScope: "device",
33850
+ addonId: null,
33851
+ access: "create"
33852
+ },
33797
33853
  "pipelineAnalytics.saveRetrainAnnotations": {
33798
33854
  capName: "pipeline-analytics",
33799
33855
  capScope: "device",
@@ -33926,6 +33982,12 @@ Object.freeze({
33926
33982
  addonId: null,
33927
33983
  access: "view"
33928
33984
  },
33985
+ "pipelineExecutor.getInferenceDeviceHealth": {
33986
+ capName: "pipeline-executor",
33987
+ capScope: "system",
33988
+ addonId: null,
33989
+ access: "view"
33990
+ },
33929
33991
  "pipelineExecutor.getOrchestratorConfigSchema": {
33930
33992
  capName: "pipeline-executor",
33931
33993
  capScope: "system",
@@ -33998,6 +34060,12 @@ Object.freeze({
33998
34060
  addonId: null,
33999
34061
  access: "view"
34000
34062
  },
34063
+ "pipelineExecutor.rearmInferenceDevice": {
34064
+ capName: "pipeline-executor",
34065
+ capScope: "system",
34066
+ addonId: null,
34067
+ access: "create"
34068
+ },
34001
34069
  "pipelineExecutor.runAudioTest": {
34002
34070
  capName: "pipeline-executor",
34003
34071
  capScope: "system",
@@ -37246,6 +37314,11 @@ Object.freeze({
37246
37314
  form: "single",
37247
37315
  optional: false
37248
37316
  }],
37317
+ "pipelineAnalytics.runReplayFrameProcessor": [{
37318
+ name: "deviceId",
37319
+ form: "single",
37320
+ optional: false
37321
+ }],
37249
37322
  "pipelineAnalytics.saveRetrainAnnotations": [{
37250
37323
  name: "deviceId",
37251
37324
  form: "single",