@camstack/addon-provider-reolink 1.2.51 → 1.2.52

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