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