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