@camstack/addon-export-hap 1.2.40 → 1.2.41

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