@camstack/addon-model-studio 1.1.43 → 1.1.44

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