@camstack/addon-remote-storage 1.2.28 → 1.2.29

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.
@@ -16032,1760 +16032,1956 @@ var OauthIntegrationDescriptorSchema = object({
16032
16032
  });
16033
16033
  method(_void(), OauthIntegrationDescriptorSchema, { auth: "admin" });
16034
16034
  /**
16035
- * pipeline-analytics device-scoped wrapper cap. Refines raw
16036
- * per-frame detections emitted by the pipeline runner into tracked
16037
- * objects, per-kind event collections (motion / object / audio), and
16038
- * persisted media. Owns the post-detection domain end-to-end:
16039
- *
16040
- * runner emits PipelineInferenceResult
16041
- * ↓ (event bus)
16042
- * pipeline-analytics subscriber
16043
- * ↓ SORT tracker + zone engine + state analyzer + event emitter
16044
- * → three DB collections (one per kind), one FS media tree, one
16045
- * unified event emitter (FrameTracked + TrackStarted/Ended +
16046
- * DetectionEvent on bus)
16047
- *
16048
- * Pure subscriber model. No `processFrame` cap method — the runner
16049
- * already publishes the raw frame on the bus. The cap surface is
16050
- * only QUERIES + per-device settings, bound on/off via
16051
- * `device-manager.setWrapperActive`. `defaultActive: true` because
16052
- * every camera with a detection pipeline wants its raw detections
16053
- * refined; operators opt out per-device via BindingsTab when needed.
16054
- *
16055
- * Replaces the legacy `analysis-pipeline`, `analysis-data-persistence`
16056
- * (per-device surface) and `track-trail` caps — see P11 cleanup.
16035
+ * Reference to the frame's retained NATIVE surface + the parent crop's placement
16036
+ * within the frame, so the executor can re-cut a leaf child ROI at native
16037
+ * resolution on the detail plane. See the `runPipeline` `nativeCropRef` field.
16057
16038
  */
16058
- var TrackStateSchema = _enum([
16059
- "new",
16060
- "entered",
16061
- "left",
16062
- "moving",
16063
- "idle"
16064
- ]);
16065
- var EventKindSchema = _enum([
16066
- "motion",
16067
- "object",
16068
- "audio"
16069
- ]);
16039
+ var NativeCropRefSchema = object({
16040
+ /** Handle keying the retained native surface (node-pinned to its owner). */
16041
+ handle: FrameHandleSchema,
16042
+ /** The parent crop's padded/clamped rectangle in FRAME-space pixels. */
16043
+ cropFrameSpace: object({
16044
+ x: number(),
16045
+ y: number(),
16046
+ w: number(),
16047
+ h: number()
16048
+ })
16049
+ });
16050
+ object({
16051
+ crop: object({
16052
+ left: number(),
16053
+ top: number(),
16054
+ width: number().positive(),
16055
+ height: number().positive()
16056
+ }).optional(),
16057
+ content: object({
16058
+ width: number().int().positive(),
16059
+ height: number().int().positive()
16060
+ }),
16061
+ fit: _enum(["stretch", "contain"]),
16062
+ format: _enum([
16063
+ "rgb",
16064
+ "gray",
16065
+ "jpeg"
16066
+ ])
16067
+ });
16070
16068
  /**
16071
- * Spatial filter for `listTracks` the rect + polygon variants of the shared
16072
- * MaskShape vocabulary (see `mask-shape.ts`). Coordinates are NORMALIZED 0..1
16073
- * of the camera frame (top-left origin), matching the drawing-plane editor.
16069
+ * Process-local frame identity. It is serializable so it can ride an in-process
16070
+ * capability call, but `registryId` deliberately prevents resolution in any
16071
+ * other process or execution group.
16074
16072
  */
16075
- var TrackZoneFilterSchema = discriminatedUnion("kind", [MaskRectShapeSchema, MaskPolygonShapeSchema]);
16076
- /** Closed icon vocabulary so clients render a known glyph per kind. */
16077
- var EventKindIconSchema = _enum([
16078
- "motion",
16079
- "audio",
16080
- "person",
16081
- "vehicle",
16082
- "animal",
16083
- "door",
16084
- "pir",
16085
- "smoke",
16086
- "water",
16087
- "button",
16088
- "package",
16089
- "generic"
16073
+ var FrameRefSchema = object({
16074
+ registryId: string().min(1),
16075
+ id: string().min(1),
16076
+ width: number().int().positive(),
16077
+ height: number().int().positive(),
16078
+ format: _enum(["rgb", "gray"]),
16079
+ timestamp: number(),
16080
+ capturedAt: number().optional()
16081
+ });
16082
+ var ModelFormatSchema$1 = _enum([
16083
+ "onnx",
16084
+ "coreml",
16085
+ "openvino",
16086
+ "tflite",
16087
+ "pt",
16088
+ "gguf"
16090
16089
  ]);
16091
- var EventKindCategorySchema = _enum([
16092
- "motion",
16093
- "audio",
16094
- "detection",
16095
- "sensor",
16096
- "control",
16097
- "custom",
16098
- "package"
16090
+ var PipelineSlotSchema = _enum([
16091
+ "detector",
16092
+ "cropper",
16093
+ "classifier",
16094
+ "refiner",
16095
+ "audio-classifier"
16099
16096
  ]);
16100
- /** Taxonomy level — macro (timeline lane) vs sub (events-page leaf). */
16101
- var EventKindLevelSchema = _enum(["macro", "sub"]);
16102
- var EventKindDescriptorSchema = object({
16103
- /** Stable kind id (e.g. 'motion', 'vehicle', 'car', 'lock'). */
16104
- kind: string(),
16105
- /** i18n key resolved on the UI side; `label` is the English fallback. */
16106
- labelKey: string(),
16107
- /** English fallback label (kept for clients that don't translate). */
16108
- label: string(),
16109
- /** Hex color for timeline/legend rendering. */
16110
- color: string(),
16111
- /** Dictionary id → lucide component on the UI side. */
16112
- iconId: string(),
16113
- /** Legacy closed-vocab glyph — fallback for `iconId`. */
16114
- icon: EventKindIconSchema,
16115
- category: EventKindCategorySchema,
16116
- /** Macro parent for this kind ('car' → 'vehicle'); null for a macro. */
16117
- parentKind: string().nullable(),
16118
- /** Derived from `parentKind`, explicit for the client tree. */
16119
- level: EventKindLevelSchema,
16120
- /** Which cap + device contributes this kind. For built-ins the camera
16121
- * itself; for sensor kinds the LINKED source device. */
16122
- source: object({
16123
- capName: string(),
16124
- deviceId: number()
16125
- })
16097
+ var PipelineEngineChoiceSchema = object({
16098
+ runtime: _enum(["node", "python"]),
16099
+ backend: string(),
16100
+ format: ModelFormatSchema$1,
16101
+ device: string().optional()
16126
16102
  });
16127
- /** One camera's event vocabulary, as returned by `listEventKindsBatch`. */
16128
- var EventKindsForDeviceSchema = object({
16129
- deviceId: number(),
16130
- kinds: array(EventKindDescriptorSchema).readonly()
16103
+ var AvailableEngineSchema = object({
16104
+ engine: PipelineEngineChoiceSchema,
16105
+ devices: array(object({
16106
+ id: string(),
16107
+ label: string(),
16108
+ description: string().optional()
16109
+ })).readonly(),
16110
+ defaultDevice: string()
16131
16111
  });
16132
- var SensorEventSchema = object({
16112
+ var PipelineDefaultStepSchema = lazy(() => object({
16113
+ addonId: string(),
16114
+ addonName: string(),
16115
+ slot: PipelineSlotSchema,
16116
+ inputClasses: array(string()).readonly(),
16117
+ outputClasses: array(string()).readonly(),
16118
+ enabled: boolean(),
16119
+ modelId: string(),
16120
+ children: array(PipelineDefaultStepSchema).readonly(),
16121
+ group: string().optional(),
16122
+ settings: record(string(), unknown()).optional()
16123
+ }));
16124
+ var PipelineTemplateStepSchema = lazy(() => object({
16125
+ addonId: string(),
16126
+ enabled: boolean(),
16127
+ modelId: string(),
16128
+ children: array(PipelineTemplateStepSchema).readonly(),
16129
+ settings: record(string(), unknown()).optional()
16130
+ }));
16131
+ var PipelineTemplateSchema$1 = object({
16133
16132
  id: string(),
16134
- /** The CAMERA the event is attributed to (a sensor linked to N cameras
16135
- * yields N rows, one per camera). */
16136
- deviceId: number(),
16137
- /** The linked sensor device whose state changed. */
16138
- sourceDeviceId: number(),
16139
- /** Event kind id — matches an `EventKindDescriptor.kind`. */
16140
- kind: string(),
16141
- /** Snapshot of the sensor cap's runtime-state slice at the change. */
16142
- value: record(string(), unknown()).nullable(),
16143
- timestamp: number()
16133
+ name: string(),
16134
+ createdAt: string(),
16135
+ updatedAt: string(),
16136
+ engine: PipelineEngineChoiceSchema,
16137
+ steps: array(PipelineTemplateStepSchema).readonly()
16144
16138
  });
16145
- var TrackPositionSchema = object({
16146
- x: number(),
16147
- y: number(),
16148
- timestamp: number(),
16149
- bbox: BoundingBoxSchema
16139
+ var PipelineModelOptionSchema = object({
16140
+ id: string(),
16141
+ name: string(),
16142
+ formats: record(string(), object({
16143
+ downloaded: boolean(),
16144
+ sizeMB: number()
16145
+ })),
16146
+ group: ModelVariantGroupSchema.optional(),
16147
+ legacy: boolean().optional(),
16148
+ provider: ModelProviderIdSchema.optional()
16150
16149
  });
16151
- var TrackSnapshotSchema = object({
16152
- timestamp: number(),
16153
- position: TrackPositionSchema,
16154
- /** MediaStore key; resolve via `getTrackMedia({ trackId })`. */
16155
- mediaKey: string()
16150
+ var ConfigFieldBridge = custom();
16151
+ var PipelineAddonSchemaSchema = object({
16152
+ id: string(),
16153
+ name: string(),
16154
+ slot: PipelineSlotSchema,
16155
+ inputClasses: array(string()).readonly(),
16156
+ outputClasses: array(string()).readonly(),
16157
+ childSlots: array(PipelineSlotSchema).readonly(),
16158
+ models: array(PipelineModelOptionSchema).readonly(),
16159
+ defaultModelId: string(),
16160
+ defaultModelIdByFormat: record(string(), string()).optional(),
16161
+ enabledByDefault: boolean().optional(),
16162
+ backfillIntoExistingOverrides: boolean().optional(),
16163
+ defaultConfidence: number(),
16164
+ group: string().optional(),
16165
+ configSchema: array(ConfigFieldBridge).readonly().optional()
16156
16166
  });
16157
- /**
16158
- * Normalized 0..1 trajectory envelope (min/max over every position bbox,
16159
- * divided by the track's detection-frame dims), computed at persist time.
16160
- * Absent when the frame dims were unknown when the track was persisted
16161
- * (legacy rows / dims-less sources) and on active (in-RAM) tracks.
16162
- */
16163
- var TrackEnvelopeSchema = object({
16164
- minX: number(),
16165
- minY: number(),
16166
- maxX: number(),
16167
- maxY: number()
16167
+ var PipelineSlotSchemaSchema = object({
16168
+ id: PipelineSlotSchema,
16169
+ label: string(),
16170
+ priority: number(),
16171
+ parentSlot: PipelineSlotSchema.nullable(),
16172
+ addons: array(PipelineAddonSchemaSchema).readonly()
16168
16173
  });
16169
- /**
16170
- * Row projection for track list queries. `full` (default) returns the
16171
- * complete Track including the frame-rate `positions[]` history and the
16172
- * `snapshots[]` references — megabytes across a page of tracks. `slim`
16173
- * keeps every scalar the list surfaces actually render (ids, class(es),
16174
- * label / audioLabels / importance enrichment, firstSeen/lastSeen, state,
16175
- * zonesVisited, bestEventId, envelope, hasFace, hasEmbeddedFace, hasRider) and returns `positions` /
16176
- * `snapshots` as EMPTY arrays — detail views re-fetch the full row via
16177
- * `getTrack`. Mirrors the event-store `projection` convention
16178
- * (`getObjectEvents` et al.).
16179
- */
16180
- var TrackProjectionSchema = _enum(["full", "slim"]);
16181
- /**
16182
- * One audio-classification label heard on the track's camera while the
16183
- * track was alive, aggregated per label. An "episode" is one persisted
16184
- * audio event (the confident-classification path: score ≥ the device's
16185
- * `classificationMinScore`, class-change-or-heartbeat coalesced) — NOT
16186
- * one 32 ms inference chunk, so counts stay human-scaled.
16187
- */
16188
- var TrackAudioLabelSchema = object({
16189
- label: string(),
16190
- /** Highest classification score observed across the label's episodes. */
16191
- peakScore: number(),
16192
- /** Number of coalesced audio-event episodes carrying this label. */
16193
- count: number(),
16194
- firstAt: number(),
16195
- lastAt: number()
16174
+ var PipelineSchemaSchema = object({
16175
+ availableEngines: array(AvailableEngineSchema).readonly(),
16176
+ selectedEngine: PipelineEngineChoiceSchema,
16177
+ slots: array(PipelineSlotSchemaSchema).readonly()
16196
16178
  });
16197
- /**
16198
- * How a track was produced. `pipeline` (default / absent) = the spatial
16199
- * detection+tracking pipeline. Every OTHER value is a SYNTHETIC projection —
16200
- * no positions, a single snapshot, and no bbox trajectory at all:
16201
- *
16202
- * - `sensor` — a linked sensor/control device state change.
16203
- * - `audio` — an audio event on the camera itself that was anomalous for
16204
- * THAT camera, loud, and heard while nothing visual was happening (D62).
16205
- *
16206
- * The spatial subsystems (tracker association, occupancy count, re-id /
16207
- * embedding, resurrection) MUST skip every synthetic source. Test for that
16208
- * with `isSpatialTrack`, which allow-lists `pipeline` — a `!== 'sensor'`
16209
- * check silently readmits every source added after it was written.
16210
- */
16211
- var TrackSourceSchema = _enum([
16212
- "pipeline",
16213
- "sensor",
16214
- "audio"
16215
- ]);
16216
- /**
16217
- * Where a track sits in the RETRAIN lifecycle (D81).
16218
- *
16219
- * - `none` never marked, or un-marked. Evictable.
16220
- * - `staging`the operator wants this track as training material and has not
16221
- * finished with it. **This is the only state retention holds**: the track and
16222
- * everything it owns (object events, crops, keyframes, CLIP vector) survive
16223
- * the device's age window.
16224
- * - `trained` — the retrain page has taken what it needed. The frames it chose
16225
- * were COPIED into the retrain dataset at selection time, so the dataset no
16226
- * longer depends on the track's media and the track becomes EVICTABLE again.
16227
- * Terminal for the plain `markForTrain` toggle: returning it to `staging` is
16228
- * a deliberate action of the retrain page, not a side effect of a checkbox.
16229
- *
16230
- * There is no `null`. The state is stored `TEXT NOT NULL DEFAULT 'none'` because
16231
- * the store's filter language has only positive equality and `whereIn` — no
16232
- * negation, no IS NULL — so a NULL would be unselectable by ANY predicate and
16233
- * would make the entire pre-column history immortal in one deploy.
16234
- */
16235
- var RetrainStatusSchema = _enum([
16236
- "none",
16237
- "staging",
16238
- "trained"
16239
- ]);
16240
- /**
16241
- * Per-track OPERATOR flags — set by hand from the admin UI or the viewer, never
16242
- * by the pipeline. Spread into `TrackSchema` and `KeyEventSchema` from one place
16243
- * so the two surfaces cannot drift.
16244
- *
16245
- * **Absent ≠ false.** A track that has never been touched omits the field; an
16246
- * explicitly un-flagged track carries `false`. Legacy rows written before the
16247
- * columns existed read as absent, and a consumer that needs a boolean should say
16248
- * `flag === true`, not `flag !== false`.
16249
- *
16250
- * `markForTrain` is the WIRE FACE of {@link RetrainStatusSchema}, not a column:
16251
- * it is exactly `retrainStatus === 'staging'`, in both directions. Writing
16252
- * `true` moves `none → staging`, writing `false` moves `staging → none`, and a
16253
- * `trained` track reports `false` while refusing both writes. The boolean is
16254
- * kept because three surfaces drive a toggle off it; anything that needs to tell
16255
- * "never marked" from "already trained" must read `retrainStatus`.
16256
- *
16257
- * `debug` does NOT pin; it is attention, not durability.
16258
- *
16259
- * `favourited` IS a BOOLEAN pin (durability bit), not a retrain lifecycle.
16260
- * A favourited track is skipped by retention the same way `staging` is, but
16261
- * it does not enter `none|staging|trained` and has no staging budget.
16262
- */
16263
- var TrackFlagFields = {
16264
- /** Operator marked this track as training material — i.e. `retrainStatus` is
16265
- * `'staging'`. */
16266
- markForTrain: boolean().optional(),
16267
- /** Operator marked this track for diagnostic attention. */
16268
- debug: boolean().optional(),
16269
- /** Operator favourited this track. Pins it against pruning. */
16270
- favourited: boolean().optional()
16271
- };
16272
- /**
16273
- * The lifecycle field itself, on the READ surfaces only (`Track`, `KeyEvent`).
16274
- * Deliberately NOT part of {@link TrackFlagFields}: that group also builds the
16275
- * write patch, and the status is not something the toggle sets — it is what the
16276
- * toggle's boolean is derived from. Absent on an in-RAM track never touched;
16277
- * always present on a persisted row (the column default materialises `'none'`).
16278
- */
16279
- var TrackRetrainFields = { retrainStatus: RetrainStatusSchema.optional() };
16280
- /**
16281
- * The write half: a PARTIAL patch. An omitted key is left untouched, so setting
16282
- * one flag can never clear the other — the toggles are independent and are
16283
- * driven from three surfaces that do not know about each other.
16284
- */
16285
- var TrackFlagsPatchSchema = object(TrackFlagFields);
16286
- /**
16287
- * The resolved flag state after a write. Both fields are REQUIRED here (absent
16288
- * collapses to `false`) so a caller can drive a toggle's checked state off the
16289
- * mutation result without a re-fetch.
16290
- */
16291
- var TrackFlagsSchema = object({
16292
- trackId: string(),
16293
- markForTrain: boolean(),
16294
- debug: boolean(),
16295
- favourited: boolean(),
16296
- /** The lifecycle state the boolean was derived from. Required here (unlike on
16297
- * a track row) because this shape is only ever produced by the write body,
16298
- * which always knows it — and a surface that has just written needs to render
16299
- * `trained` without a re-fetch. */
16300
- retrainStatus: RetrainStatusSchema
16179
+ var EngineProvisioningSchema = object({
16180
+ runtimeId: _enum([
16181
+ "onnx",
16182
+ "openvino",
16183
+ "coreml",
16184
+ "edgetpu"
16185
+ ]).nullable(),
16186
+ device: string().nullable(),
16187
+ state: _enum([
16188
+ "idle",
16189
+ "installing",
16190
+ "verifying",
16191
+ "ready",
16192
+ "failed"
16193
+ ]),
16194
+ progress: number().optional(),
16195
+ error: string().optional(),
16196
+ nextRetryAt: number().optional(),
16197
+ /**
16198
+ * Gate A (config-correctness gate at engine change): human-readable
16199
+ * config issues surfaced EAGERLY when the node's engine changes — model
16200
+ * substitutions ("chose X, running Y") and zero-build steps ("no model
16201
+ * has a <format> build"). Additive/optional: informational only, never
16202
+ * enforced here `assertEngineReady` (readiness) still gates inference.
16203
+ * Absent/empty when the node-default tree resolves cleanly.
16204
+ */
16205
+ configIssues: array(string()).optional()
16301
16206
  });
16302
- union([literal(1), literal(2)]);
16303
- /**
16304
- * WHO decided a label, and when. Carried per tier so a value can be traced to
16305
- * the step and model that produced it — which is what makes the write rule
16306
- * arguable after the fact ("why is 592's label `dog` and not `Canis lupus`?")
16307
- * and what lets a migrated, UNATTRIBUTED value be told apart from a real one.
16308
- *
16309
- * `stepId` is the pipeline step id (`animal-classifier`, `bird-classifier`,
16310
- * `plate-ocr`, `face-embedding`, `object-detection`), or the sentinel
16311
- * `migration:4g` for a value the 4g migration moved from the single-slot era —
16312
- * that value has no provenance, and the write rule lets ANY properly-attributed
16313
- * write of the same tier replace it regardless of score.
16314
- */
16315
- var LabelAttributionSchema = object({
16316
- stepId: string(),
16207
+ var PipelineStepInputSchema = lazy(() => object({
16208
+ addonId: string(),
16317
16209
  modelId: string().optional(),
16318
- decidedAt: number(),
16210
+ enabled: boolean().default(true),
16211
+ children: array(PipelineStepInputSchema).optional(),
16212
+ settings: record(string(), unknown()).optional(),
16213
+ jumpDeviceKey: string().optional()
16214
+ }));
16215
+ var ModelSubstitutionSchema = object({
16216
+ addonId: string(),
16217
+ chosen: string(),
16218
+ running: string(),
16219
+ format: string()
16220
+ });
16221
+ var PipelineValidationIssueSchema = object({
16222
+ addonId: string(),
16223
+ kind: _enum(["unknown-addon", "no-format-build"]),
16224
+ detail: string()
16225
+ });
16226
+ var PipelineValidationResultSchema = object({
16227
+ ok: boolean(),
16228
+ issues: array(PipelineValidationIssueSchema).readonly(),
16229
+ substitutions: array(ModelSubstitutionSchema).readonly(),
16230
+ /** The node's `currentEngine.format` this validation ran against. */
16231
+ format: string()
16232
+ });
16233
+ var ReferenceImageEntrySchema = object({
16234
+ filename: string(),
16235
+ stepIds: array(string()).readonly().optional()
16236
+ });
16237
+ var ReferenceImageBodySchema = object({
16238
+ base64: string(),
16239
+ filename: string()
16240
+ });
16241
+ var ReferenceAudioEntrySchema = object({
16242
+ filename: string(),
16243
+ sizeKb: number()
16244
+ });
16245
+ var ReferenceAudioBodySchema = object({ base64: string() });
16246
+ var AudioBackendSchema = object({
16247
+ id: string(),
16248
+ name: string(),
16249
+ description: string(),
16250
+ available: boolean(),
16319
16251
  /**
16320
- * The GALLERY id behind a recognised tier-2 label — a face-gallery
16321
- * `Identity.id` or a plate-gallery `Vehicle.id` (both `randomUUID`).
16322
- *
16323
- * The text alone is a DISPLAY NAME, and a display name is renameable: a
16324
- * notification rule authored on "Gianluca" stopped matching the moment the
16325
- * operator fixed the spelling in the gallery, and nothing said so. The id is
16326
- * the thing that does not move, so it is what a rule matches on
16327
- * (`NcConditions.identities`) and the text is what a human is shown.
16328
- *
16329
- * Absent when the label names no gallery row — a plate the OCR read but no
16330
- * vehicle claims, a sub-class, a species, any tier-1 value.
16252
+ * Raw classifier labels this backend can emit (e.g. YAMNet's
16253
+ * 521-class set or Apple SoundAnalysis's 303-class set). Used by
16254
+ * the benchmark UI to populate the `enabledMicroClasses` filter
16255
+ * specific to the selected backend without a separate fetch.
16331
16256
  */
16332
- identityId: string().optional()
16257
+ rawLabels: array(string()).readonly().optional()
16258
+ });
16259
+ var AudioCapabilitiesSchema = object({
16260
+ activeBackend: string(),
16261
+ availableBackends: array(AudioBackendSchema).readonly(),
16262
+ sampleRate: number(),
16263
+ chunkDurationMs: number()
16264
+ });
16265
+ var DownloadModelResultSchema = object({
16266
+ filePath: string(),
16267
+ sizeMB: number(),
16268
+ durationMs: number()
16333
16269
  });
16334
16270
  /**
16335
- * The TIERED label model (roadmap 4g), spread into `TrackSchema` and
16336
- * `ObjectEventSchema` from ONE place so the two surfaces cannot drift — a
16337
- * track and its events always answer the same question the same way.
16338
- *
16339
- * Two scalar columns, not an array: every consumer wants "the coarse one" or
16340
- * "the fine one", and an array made both a scan. `label` is tier 1, `subLabel`
16341
- * is tier 2, and each carries its own score + attribution.
16342
- *
16343
- * **Reading it.** What a human should be shown is `subLabel ?? label` — the
16344
- * finest thing known. Before 4g the single `label` column held the finest
16345
- * value, so a consumer that has not been updated reads the tier-1 slot and
16346
- * shows nothing on a species-only row; that is why the migration puts every
16347
- * pre-4g value in tier 2 (it cannot regress a display that reads the fallback)
16348
- * and why the read surfaces were changed in the same train.
16349
- *
16350
- * **Writing it.** The slots are independent, which is the whole point: a
16351
- * tier-1 write (`bird`) can never overwrite a tier-2 value (`Turdus
16352
- * migratorius`), so fineness cannot regress by construction. Within a tier the
16353
- * higher score wins. One rule, one implementation — see
16354
- * `pipeline/label-tier.ts` in addon-post-analysis.
16355
- */
16356
- var TieredLabelFields = {
16357
- /** Tier 1 — the sub-class. See {@link LabelTierSchema}. */
16358
- label: string().optional(),
16359
- /** Confidence of the tier-1 value, as reported by the deciding step. */
16360
- labelScore: number().optional(),
16361
- /** Provenance of the tier-1 value. See {@link LabelAttributionSchema}. */
16362
- labelMeta: LabelAttributionSchema.optional(),
16363
- /** Tier 2 — the instance. See {@link LabelTierSchema}. */
16364
- subLabel: string().optional(),
16365
- /** Confidence of the tier-2 value, as reported by the deciding step. */
16366
- subLabelScore: number().optional(),
16367
- /** Provenance of the tier-2 value. See {@link LabelAttributionSchema}. */
16368
- subLabelMeta: LabelAttributionSchema.optional()
16369
- };
16370
- /** Per-camera slice of a training-export estimate. */
16371
- var TrainingExportDeviceTotalsSchema = object({
16372
- deviceId: number(),
16373
- tracks: number().int(),
16374
- files: number().int(),
16375
- bytes: number().int()
16376
- });
16377
- /**
16378
- * What a training export WOULD contain. Computed from media index rows only —
16379
- * no blob is read to produce this.
16271
+ * Wrapper carrying a single test run's result. Replaces the legacy
16272
+ * ad-hoc `{labels: [{className, originalClass, score}]}` shape with the
16273
+ * canonical `AudioResult` from the Phase 6 output rework: one
16274
+ * `AudioDetection` per class above `minScore`, top-N candidates in
16275
+ * `debug.alternateLabels['audio-classifier']`, per-source timings in
16276
+ * `debug.stepTimings`. The outer `success`/`error` fields stay so the
16277
+ * benchmark UI can still report a clean failure when the classifier
16278
+ * cap isn't available.
16380
16279
  */
16381
- var TrainingExportSummarySchema = object({
16382
- generatedAt: number(),
16383
- trackCount: number().int(),
16384
- fileCount: number().int(),
16385
- byteCount: number().int(),
16386
- /** More marked tracks exist than a single pass carries. */
16387
- truncated: boolean(),
16388
- devices: array(TrainingExportDeviceTotalsSchema).readonly()
16280
+ var AudioTestResultSchema = object({
16281
+ success: boolean(),
16282
+ error: string().optional(),
16283
+ frame: custom().optional()
16389
16284
  });
16390
- var TrackSchema = object({
16391
- trackId: string(),
16392
- deviceId: number(),
16393
- className: string(),
16394
- ...TieredLabelFields,
16395
- producingDeviceName: string().optional(),
16396
- /** Track provenance. Absent `pipeline` (legacy rows). */
16397
- source: TrackSourceSchema.optional(),
16398
- firstSeen: number(),
16399
- lastSeen: number(),
16400
- /** Frame-rate position history (subject to maxPositionHistory cap). */
16401
- positions: array(TrackPositionSchema).readonly(),
16402
- /** Periodic snapshots at snapshotIntervalMs cadence (subject to
16403
- * saveThumbnails policy). */
16404
- snapshots: array(TrackSnapshotSchema).readonly(),
16405
- /** Deduplicated zones the track has entered at least once. Zone IDS. */
16406
- zonesVisited: array(string()).readonly(),
16285
+ var PipelineConfigBridge = custom();
16286
+ var ConfigUISchemaBridge = custom();
16287
+ var ConfigUISchemaNullableBridge = custom();
16288
+ var InferenceCapabilitiesBridge = custom();
16289
+ var ModelAvailabilityListBridge = custom();
16290
+ var PipelineRunResultBridge = custom();
16291
+ method(_void(), array(PipelineEngineChoiceSchema)), method(_void(), PipelineEngineChoiceSchema), method(PipelineEngineChoiceSchema, array(PipelineDefaultStepSchema)), method(object({ nodeId: string() }), EngineProvisioningSchema), method(_void(), record(string(), object({
16292
+ modelId: string(),
16293
+ settings: record(string(), unknown()).readonly()
16294
+ }))), method(object({ steps: record(string(), object({
16295
+ modelId: string(),
16296
+ settings: record(string(), unknown()).readonly()
16297
+ })) }), object({ success: literal(true) }), {
16298
+ kind: "mutation",
16299
+ auth: "admin"
16300
+ }), method(object({ nodeId: string() }), object({
16301
+ success: literal(true),
16302
+ clearedDevices: number()
16303
+ }), {
16304
+ kind: "mutation",
16305
+ auth: "admin"
16306
+ }), method(object({ nodeId: string() }), object({ unhealthy: array(object({
16307
+ /** `<backend>:<device>`, e.g. `openvino:gpu`. */
16308
+ deviceKey: string(),
16407
16309
  /**
16408
- * Human NAMES for {@link zonesVisited}, resolved at READ time against the
16409
- * `zones` capability.
16410
- *
16411
- * `zonesVisited` persists ids (`cfeec78c-8d69-…`), which no operator can type
16412
- * and no card can render — so every free-text search surface was structurally
16413
- * unable to answer "show me the tracks in Uscio", and did not fail loudly, it
16414
- * just returned nothing. Resolving here rather than in each client keeps ONE
16415
- * derivation and costs the clients no extra call (the `zones` cap is
16416
- * per-device, so a client-side resolve would be a per-camera fan-out on a
16417
- * surface built to avoid exactly that).
16418
- *
16419
- * Resolved, never invented: a zone deleted since the track was written has no
16420
- * name and is DROPPED, so this array can be shorter than `zonesVisited` — the
16421
- * two are not positionally aligned. Absent when the track visited no zone, or
16422
- * when the zone catalogue could not be read.
16310
+ * `failed` the per-device restart budget is exhausted; no pool
16311
+ * will be spawned until an operator re-arms it or the runner
16312
+ * respawns. `backoff` — under budget, waiting out the backoff (or
16313
+ * a cached pool observed dead and not yet condemned).
16423
16314
  */
16424
- zoneNames: array(string()).readonly().optional(),
16425
- /** Deduplicated set of detector classes observed for this track over its
16426
- * life (a track may be reclassified, e.g. person→vehicle). Absent on
16427
- * legacy rows written before class accumulation shipped. */
16428
- classes: array(string()).readonly().optional(),
16429
- /** Cumulative normalized distance travelled (0..1 units = full frame width). */
16430
- totalDistance: number(),
16431
- state: TrackStateSchema,
16432
- active: boolean(),
16433
- /** Deterministic key-event importance score in [0,1] (server-computed at
16434
- * track expiry, recomputed on late label). Absent on legacy rows written
16435
- * before scoring shipped — consumers degrade to absence / compute-on-read. */
16436
- importance: number().optional(),
16437
- /** Id of the track's highest-confidence ObjectEvent (its representative
16438
- * "best" frame). Absent when the track produced no object events. */
16439
- bestEventId: string().optional(),
16440
- /** Tag of the importance sub-signal that dominated the score
16441
- * (identity|dwell|proximity|class|confidence|travel|zone). */
16442
- importanceReason: string().optional(),
16443
- /** Audio-classification labels heard on the camera during the track's
16444
- * life (score ≥ device `classificationMinScore`), aggregated per label.
16445
- * Absent on legacy rows / tracks with no confident audio. */
16446
- audioLabels: array(TrackAudioLabelSchema).readonly().optional(),
16447
- /** Normalized 0..1 trajectory envelope (see {@link TrackEnvelopeSchema}).
16448
- * Populated from the persisted envelope columns on historical reads;
16449
- * absent on legacy rows, dims-less tracks and active (in-RAM) tracks. */
16450
- envelope: TrackEnvelopeSchema.optional(),
16315
+ state: _enum(["failed", "backoff"]),
16316
+ /** Epoch ms of the death that produced this state. */
16317
+ since: number(),
16318
+ /** Pool deaths inside the current window. */
16319
+ deaths: number(),
16320
+ /** The last death's message. */
16321
+ lastError: string()
16322
+ })).readonly() })), method(object({
16323
+ nodeId: string(),
16324
+ deviceKey: string()
16325
+ }), object({ rearmed: boolean() }), {
16326
+ kind: "mutation",
16327
+ auth: "admin"
16328
+ }), 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({
16329
+ name: string(),
16330
+ steps: array(PipelineTemplateStepSchema).readonly(),
16331
+ engine: PipelineEngineChoiceSchema
16332
+ }), PipelineTemplateSchema$1, { kind: "mutation" }), method(object({
16333
+ id: string(),
16334
+ name: string().optional(),
16335
+ steps: array(PipelineTemplateStepSchema).readonly().optional()
16336
+ }), PipelineTemplateSchema$1, { kind: "mutation" }), method(object({ id: string() }), _void(), { kind: "mutation" }), method(_void(), InferenceCapabilitiesBridge), method(object({ addonId: string() }), ModelAvailabilityListBridge), method(object({
16337
+ addonId: string(),
16338
+ modelId: string(),
16339
+ format: ModelFormatSchema$1
16340
+ }), DownloadModelResultSchema, { kind: "mutation" }), method(object({
16341
+ addonId: string(),
16342
+ modelId: string(),
16343
+ format: ModelFormatSchema$1
16344
+ }), object({ success: literal(true) }), { kind: "mutation" }), method(object({
16345
+ engine: PipelineEngineChoiceSchema.optional(),
16346
+ steps: array(PipelineStepInputSchema).min(1),
16347
+ frame: FrameInputSchema.optional(),
16451
16348
  /**
16452
- * A face DETECTOR found a face on this track — nothing more. It says the
16453
- * detail plane produced a `face` detail; it does NOT say the face was
16454
- * embedded, matched, above `minFacePx`, or that the recognizer was even
16455
- * enabled. Set once and never cleared.
16456
- *
16457
- * **This exists so "face present but not recognised" is expressible.** A
16458
- * recognised identity lands in `subLabel` (attributed to the face chain via
16459
- * `subLabelMeta.stepId`), so before this field a track with an unmatched face
16460
- * and a track with no face at all were byte-identical on the wire and no
16461
- * surface could tell them apart. The read is `hasFace === true && subLabel
16462
- * === undefined`.
16463
- *
16464
- * **Absent ≠ false.** Every row written before the column existed omits it,
16465
- * and so does every server that predates the field — a consumer must test
16466
- * `=== true` and render nothing otherwise, never infer "no face".
16349
+ * Process-local lazy frame. Valid only when caller and provider resolve
16350
+ * in the same execution-group process; split/cross-node callers use
16351
+ * `frame`/`image` inline compatibility instead.
16467
16352
  */
16468
- hasFace: boolean().optional(),
16353
+ frameRef: FrameRefSchema.optional(),
16469
16354
  /**
16470
- * This track has a face row IN THE GALLERY: a crop **and** an embedding a
16471
- * face an operator could ASSIGN to an identity.
16472
- *
16473
- * The STRICT twin of {@link hasFace}, and the pair only earns its keep
16474
- * because the two disagree. `hasFace` is stamped at the TOP of the face
16475
- * branch, before every gate, and means no more than "a face detector produced
16476
- * a face detail". This one is stamped at the single moment the gallery row
16477
- * LANDS — after `FaceRecognizer.onTrackEnd` successfully persists it, i.e.
16478
- * past the embedding-magnitude verdict, the `minFacePx` detection gate, the
16479
- * candidate gate, the imageless-track drop (no crop was ever captured) and
16480
- * the crop-store drop. Everything between the detector and that insert can
16481
- * legitimately refuse the face, so a flag written any earlier promises the
16482
- * operator something to assign and delivers nothing.
16483
- *
16484
- * **Independent of recognition.** A face collected but never auto-matched is
16485
- * still assignable — it is in fact the face an operator most wants to reach —
16486
- * so this is NOT gated on `recognizedIdentityId`. Recognition lands in
16487
- * `subLabel`; this says only that the raw material exists.
16488
- *
16489
- * **Set once, never cleared.** A track that produced a gallery row produced
16490
- * one; deleting the row later is the gallery's business, not this flag's.
16491
- *
16492
- * **Absent ≠ false**, the same rule as {@link hasFace}: every row written
16493
- * before the column omits it, and so does every server that predates the
16494
- * field. A consumer must test `=== true` and render nothing otherwise —
16495
- * never infer "no assignable face".
16355
+ * CB5 shm passthrough a `FrameHandle` naming the same ring slot
16356
+ * the decoded pixels live in. One more member of the one-of
16357
+ * frame/frameHandle/image/imageBase64/referenceImage group.
16496
16358
  */
16497
- hasEmbeddedFace: boolean().optional(),
16359
+ frameHandle: FrameHandleSchema.optional(),
16360
+ imageBase64: string().optional(),
16498
16361
  /**
16499
- * This subject CONTAINS a folded rider a person the rider-pairing step
16500
- * ([D34](../decisions/adr-0034.md)) removed from the frame BEFORE the tracker,
16501
- * so the passage is tracked once and as a VEHICLE.
16502
- *
16503
- * It exists because the fold's record was dishonest. D34 and the code both
16504
- * said "the person is not lost — it is reported so both entities stay on the
16505
- * record"; in fact the pair went into a per-processor RAM field behind an
16506
- * accessor nobody called, and every durable surface said `vehicle`, full
16507
- * stop. This is the composition note that makes the row true.
16508
- *
16509
- * A COMPOSITION, never a class and never a label. "This vehicle contains a
16510
- * person" is not an answer to "what is this" — both label tiers would refuse
16511
- * a macro token anyway (D89), and correctly. Nothing here changes what the
16512
- * subject IS: a cyclist stays one vehicle track, occupancy still counts one,
16513
- * and a `person` rule still does not fire for someone cycling past.
16514
- *
16515
- * **Absent ≠ false**, exactly like {@link hasFace}: every row written before
16516
- * the column, and every hub that predates the field, omits it. Test
16517
- * `=== true` and render nothing otherwise — never infer "no rider".
16362
+ * Binary JPEG bytespreferred over `imageBase64` on internal
16363
+ * hops (hub forked worker via Moleculer MsgPack) because it
16364
+ * skips the 33% base64 overhead + the per-call base64 decode on
16365
+ * the detection-pipeline worker. Callers can pass either; exactly
16366
+ * one of `frame`/`image`/`imageBase64`/`referenceImage` is required.
16518
16367
  */
16519
- hasRider: boolean().optional(),
16520
- ...TrackFlagFields,
16521
- ...TrackRetrainFields
16522
- });
16523
- var BaseEventFields = {
16524
- id: string(),
16525
- deviceId: number(),
16526
- timestamp: number()
16527
- };
16528
- var MotionEventSchema = object({
16529
- ...BaseEventFields,
16530
- kind: literal("motion"),
16531
- regionCount: number(),
16532
- /** Heavy JSON array omitted in slim projection. */
16533
- regions: array(object({
16534
- bbox: BoundingBoxSchema,
16535
- pixelCount: number(),
16536
- intensity: number()
16537
- })).readonly().optional(),
16538
- /** Omitted in slim projection. */
16539
- frameWidth: number().optional(),
16540
- /** Omitted in slim projection. */
16541
- frameHeight: number().optional(),
16542
- /** Populated by B5 (recording playback URL for this event). */
16543
- mediaUrl: string().optional()
16544
- });
16368
+ image: _instanceof(Uint8Array).optional(),
16369
+ referenceImage: string().optional(),
16370
+ deviceId: number().optional(),
16371
+ sessionId: string().optional(),
16372
+ /**
16373
+ * Execution plane. 'full' (default) runs the whole tree — benchmark,
16374
+ * reference-image, and detail-subtree calls. 'frame' is the live
16375
+ * per-frame dispatch: ONLY root-plane steps run; crop children
16376
+ * (inputClasses ≠ null) are skipped and served per-track via
16377
+ * pipelineRunner.runDetailSubtree (two-plane design).
16378
+ */
16379
+ plane: _enum(["full", "frame"]).optional(),
16380
+ /**
16381
+ * Inference-device selector (Phase 2 multi-device). Format
16382
+ * `<backend>:<device>` (e.g. `openvino:gpu`, `edgetpu:usb`, `cpu`).
16383
+ * Omitted ⇒ the runner's default device (current single-engine
16384
+ * behaviour). Selects WHICH device pool of the node runs the call.
16385
+ */
16386
+ deviceKey: string().optional(),
16387
+ /**
16388
+ * Two-plane NATIVE child-crop reference. Set by `runDetailSubtree` ONLY
16389
+ * when the parent crop was resolved from the frame's retained NATIVE
16390
+ * surface (a frameHandle HIT). Lets the executor re-cut a LEAF crop
16391
+ * child's ROI (plate-ocr, face-embedding, leaf classifiers) at native
16392
+ * resolution from that surface — the SAME quality path faces already
16393
+ * had — instead of the downscaled parent tile. `handle` keys the native
16394
+ * surface (node-pinned to its owner); `cropFrameSpace` is the parent
16395
+ * crop's padded/clamped rectangle in FRAME-space pixels, used to compose
16396
+ * the executor's crop-normalized child ROI back into frame-normalized
16397
+ * coordinates. Auxiliary to the image source (`image`/`frame`/…), NOT one
16398
+ * of the mutually-exclusive image inputs. Absent ⇒ tile-crop children
16399
+ * (today's behaviour on the fallback path).
16400
+ */
16401
+ nativeCropRef: NativeCropRefSchema.optional()
16402
+ }), PipelineRunResultBridge, { kind: "mutation" }), method(object({
16403
+ engine: PipelineEngineChoiceSchema.optional(),
16404
+ steps: array(PipelineStepInputSchema).min(1),
16405
+ frames: array(FrameInputSchema).min(1).max(255),
16406
+ deviceId: number().optional(),
16407
+ sessionId: string().optional(),
16408
+ /**
16409
+ * Pure-inference benchmark hint. A NONZERO uint32 pins every frame in
16410
+ * the batch to the Python pool's bench preprocess cache
16411
+ * (`_bench_frame_id`) so a REPEATED benchmark frame is decoded +
16412
+ * preprocessed ONCE and every later inference is a pure-inference cache
16413
+ * hit — the sustained-throughput run measures inference, not
16414
+ * decode+preprocess+infer. Omitted/0 for live frames (all different →
16415
+ * full preprocess every call, correct). Fresh per sustained run;
16416
+ * released via `uncacheFrame`.
16417
+ */
16418
+ frameId: number().int().nonnegative().optional(),
16419
+ /** Inference-device selector (Phase 2 multi-device); see runPipeline. */
16420
+ deviceKey: string().optional()
16421
+ }), object({ results: array(PipelineRunResultBridge).readonly() }), { kind: "mutation" }), method(object({
16422
+ data: _instanceof(Uint8Array),
16423
+ width: number().int().positive(),
16424
+ height: number().int().positive(),
16425
+ format: _enum([
16426
+ "rgb",
16427
+ "bgr",
16428
+ "gray"
16429
+ ])
16430
+ }), object({
16431
+ frameId: number(),
16432
+ width: number(),
16433
+ height: number()
16434
+ }), { kind: "mutation" }), method(object({
16435
+ stepId: string(),
16436
+ frameId: number().int()
16437
+ }), record(string(), unknown()), { kind: "mutation" }), method(object({ frameId: number().int() }), _void(), { kind: "mutation" }), method(_void(), object({
16438
+ batchMode: string(),
16439
+ windowMs: number(),
16440
+ maxBatchSize: number(),
16441
+ concurrency: number()
16442
+ })), method(_void(), array(object({
16443
+ engineKey: string(),
16444
+ engine: PipelineEngineChoiceSchema,
16445
+ modelsLoaded: array(string()).readonly(),
16446
+ inUseByCameras: array(number()).readonly(),
16447
+ /**
16448
+ * Origin of this resident factory.
16449
+ * - `runtime` — main camera-serving engine (no idle TTL).
16450
+ * - `warm-override` — benchmark/test override held in the warm
16451
+ * cache; auto-disposed after the idle TTL.
16452
+ * - `device-pool` — a concurrent per-device pool (Phase 2
16453
+ * multi-device, keyed by `deviceKey`) resolved
16454
+ * via `resolveDeviceFactory`. Runs alongside the
16455
+ * `runtime` engine on a DIFFERENT accelerator
16456
+ * (NPU / iGPU / Coral) — this is how the
16457
+ * Engines tab shows all pools running at once.
16458
+ */
16459
+ kind: _enum([
16460
+ "runtime",
16461
+ "warm-override",
16462
+ "device-pool"
16463
+ ]),
16464
+ /** Native pid of the underlying Python pool (null when no pool). */
16465
+ poolPid: number().nullable(),
16466
+ /** ms since this factory was last used (null when not warm-tracked). */
16467
+ idleMs: number().nullable(),
16468
+ /** Idle TTL after which `warm-override` factories self-evict (null when not applicable). */
16469
+ idleTtlMs: number().nullable()
16470
+ })).readonly()), method(object({ engine: PipelineEngineChoiceSchema }), object({ success: literal(true) }), {
16471
+ kind: "mutation",
16472
+ auth: "admin"
16473
+ }), method(object({
16474
+ engine: PipelineEngineChoiceSchema,
16475
+ force: boolean().optional()
16476
+ }), object({
16477
+ success: boolean(),
16478
+ reason: string().optional()
16479
+ }), {
16480
+ kind: "mutation",
16481
+ auth: "admin"
16482
+ }), 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({
16483
+ addonId: string(),
16484
+ modelId: string(),
16485
+ filename: string().optional(),
16486
+ settings: record(string(), unknown()).optional()
16487
+ }), AudioTestResultSchema, { kind: "mutation" }), method(_void(), ConfigUISchemaNullableBridge);
16545
16488
  /**
16546
- * Which detection SOURCE produced an object event. `pipeline` = the ML
16547
- * detection pipeline (decoded-frame inference); `onboard` = the camera's
16548
- * native on-device AI. Both flow through the SAME analysis layers (zoning,
16549
- * tracking, per-kind persistence) but stay distinguishable so consumers
16550
- * (advanced-notifier, occupancy, …) can select which source(s) to act on.
16551
- * Absent on legacy rows treat as `pipeline`.
16489
+ * Per-stage gating mode applied to the zones a rule references.
16490
+ *
16491
+ * - `include`: the rule contributes to a **whitelist** for its stage.
16492
+ * When at least one `include` rule fires for a stage, only entities
16493
+ * inside one of those zones pass that stage.
16494
+ * - `exclude`: the rule contributes to a **blacklist** for its stage.
16495
+ * Entities inside one of those zones are dropped at that stage.
16496
+ *
16497
+ * `monitor`-style observation (count without filtering) is not a rule
16498
+ * mode — zones without any matching rule are observed naturally by
16499
+ * `zone-analytics` (live snapshot + history), so an "I just want to
16500
+ * count, not filter" use case needs no rule at all.
16552
16501
  */
16553
- var DetectionSourceSchema = _enum(["pipeline", "onboard"]);
16502
+ var ZoneRuleModeEnum = _enum(["include", "exclude"]);
16554
16503
  /**
16555
- * The confirmed zone crossing that produced an object event. Present ONLY on
16556
- * an event emitted BY a crossing (`zone.enter` / `zone.exit`); a movement-state
16557
- * event (`object.entering` / `leaving` / `stationary` / `loitering`) and an
16558
- * appearance event carry none, so a rule asking for a direction fails closed
16559
- * on them.
16504
+ * Per-consumer rule that references existing zones (geometry) and
16505
+ * defines how a specific pipeline stage should treat them. Each
16506
+ * consumer addon owns its own `ZoneRule[]` array in its per-device
16507
+ * settings:
16560
16508
  *
16561
- * Exactly ONE crossing per event: the emitter turns each confirmed crossing
16562
- * into its own event, so a frame in which a track enters A while leaving B
16563
- * produces two events with two directions — never one ambiguous row.
16509
+ * - `addon-motion-wasm` `motionZoneRules: ZoneRule[]` (motion stage)
16510
+ * - `addon-detection-pipeline` `detectionZoneRules: ZoneRule[]` (detection stage)
16511
+ * - future: notification rules, audio gating, etc.
16564
16512
  *
16565
- * `zoneId` is load-bearing for an EXIT: the event's `zones` list is the
16566
- * membership the box has NOW, and by definition it no longer contains the zone
16567
- * that was just left. Without the id here, a zone-scoped rule could never match
16568
- * the exit it asked for.
16513
+ * One rule applies to N zones (`zoneIds[]`) so the operator can
16514
+ * express "ignore motion in ALL of {garden, street}" with a single
16515
+ * rule. `classFilter` narrows the rule to specific object classes
16516
+ * "drop person detections in the street, but keep cars" is one
16517
+ * `exclude` rule with `classFilter: ['person']`.
16518
+ *
16519
+ * `enabled` is a soft toggle — the operator can keep the rule
16520
+ * configured but inert without deleting it.
16569
16521
  */
16570
- var ZoneCrossingSchema = object({
16571
- direction: _enum(["enter", "exit"]),
16572
- /** Admin zone id crossed. */
16573
- zoneId: string(),
16574
- /** Zone display name at crossing time (falls back to the id). */
16575
- zoneName: string().optional()
16576
- });
16577
- var ObjectEventSchema = object({
16578
- ...BaseEventFields,
16579
- kind: literal("object"),
16580
- /** Detection source. Optional for backward-compat; absent ⇒ `pipeline`. */
16581
- source: DetectionSourceSchema.optional(),
16522
+ var ZoneRuleSchema = object({
16523
+ /** Stable rule id — survives edits, used by the UI for diffing. */
16524
+ id: string(),
16525
+ /** Optional human-readable label rendered in the rule editor. */
16526
+ name: string().optional(),
16527
+ /** Zones this rule targets. The rule's `mode` applies to ALL
16528
+ * listed zones (OR-set: a detection in any one of them counts).
16529
+ * At least one zone id required — a rule with no targets is a
16530
+ * configuration mistake and the form validator rejects it. */
16531
+ zoneIds: array(string()).min(1).readonly(),
16532
+ mode: ZoneRuleModeEnum,
16582
16533
  /**
16583
- * Inference-frame id shared by every object event emitted from the SAME frame
16584
- * the "scene/parent" key. Lets a consumer group co-occurring detections (e.g.
16585
- * 2 people + 1 dog) under one full frame, and link a track's frames over time
16586
- * (group by `trackId`, pick a representative `frameId` as the parent frame).
16587
- * Optional for backward-compat with pre-existing rows / the slim projection
16588
- * includes it (it is light). Absent on rows written before this field.
16534
+ * Class names this rule applies to. Empty / undefined rule
16535
+ * applies to every class. Class strings match the `macroClass`
16536
+ * field on detections (e.g. `person`, `car`, `dog`).
16589
16537
  */
16590
- frameId: string().optional(),
16591
- /** Omitted in slim projection. */
16592
- trackId: string().optional(),
16593
- className: string(),
16594
- ...TieredLabelFields,
16595
- /** Omitted in slim projection. */
16596
- confidence: number().optional(),
16597
- /** Heavy JSON — omitted in slim projection. */
16598
- bbox: BoundingBoxSchema.optional(),
16599
- /** Heavy JSON — omitted in slim projection. */
16600
- zones: array(string()).readonly().optional(),
16601
- /** Omitted in slim projection. */
16602
- state: TrackStateSchema.optional(),
16538
+ classFilter: array(string()).readonly().optional(),
16603
16539
  /**
16604
- * The zone crossing this event IS, when it is one. Absent on every other
16605
- * event kind (movement state, appearance, package) see
16606
- * {@link ZoneCrossingSchema}. Omitted in slim projection.
16540
+ * Minimum bbox/mask overlap (0–1) with any of the rule's zones
16541
+ * required to consider an entity "in the zone". Defaults to the
16542
+ * consumer's stage default when omitted. Kept for back-compat with
16543
+ * existing per-rule overrides; new operators pick the value via
16544
+ * `bboxInclusionPct` (operator-friendly 0–100). Whichever field is
16545
+ * set, the lower-level engine reads it as a 0–1 fraction.
16607
16546
  */
16608
- zoneCrossing: ZoneCrossingSchema.optional(),
16609
- /** Detection-frame dimensions in pixels — let consumers normalize the
16610
- * pixel-space `bbox` onto a displayed image. Omitted in slim projection. */
16611
- frameWidth: number().optional(),
16612
- frameHeight: number().optional(),
16613
- /** MediaStore key for the crop attached to this event (if any). */
16614
- mediaKey: string().optional(),
16615
- /** Design B: MediaStore key of the track's native-resolution key frame (the
16616
- * best-detection full frame). Resolve via the event-media data-plane
16617
- * (`/addon/<addonId>/event-media/<keyFrameMediaKey>`) for a detail view that
16618
- * draws `bbox` over the native frame. Absent on legacy rows / non-decoded
16619
- * sources — consumers fall back to `mediaKey` (the tight crop). */
16620
- keyFrameMediaKey: string().optional(),
16621
- /** Populated by B5 (recording playback URL for this event). */
16622
- mediaUrl: string().optional(),
16623
- /** The parent track's key-event importance [0,1], propagated to every object
16624
- * event of the track (so an event row can be sorted by importance without a
16625
- * track join). Absent on legacy rows / before the track was scored. */
16626
- importance: number().optional()
16627
- });
16628
- var AudioEventSchema = object({
16629
- ...BaseEventFields,
16630
- kind: literal("audio"),
16631
- rms: number(),
16632
- dbfs: number(),
16633
- classification: object({
16634
- className: string(),
16635
- originalClass: string().optional(),
16636
- score: number()
16637
- }).optional(),
16638
- /** Populated by B5 (recording playback URL for this event). */
16639
- mediaUrl: string().optional()
16640
- });
16641
- var MediaFileKindEnum = _enum([
16642
- "crop",
16643
- "thumbnail",
16644
- "snapshot",
16645
- "firstFrame",
16646
- "lastFrame",
16647
- "fullFrame",
16648
- "fullFrameBoxed",
16649
- "faceCrop",
16650
- "plateCrop",
16651
- "keyFrame",
16652
- "keyFrameSmall",
16653
- "thumbnailSmall"
16654
- ]);
16655
- var MediaFileSchema = object({
16656
- key: string(),
16657
- kind: MediaFileKindEnum,
16658
- base64: string(),
16659
- sizeBytes: number(),
16660
- timestamp: number()
16547
+ overlapThreshold: number().min(0).max(1).optional(),
16548
+ /**
16549
+ * Operator-friendly version of `overlapThreshold` the percentage
16550
+ * of the detection's bbox that must lie inside the zone for the
16551
+ * rule to match. Documented default is 85%; the engine substitutes
16552
+ * that when the field is omitted (kept optional so existing rules
16553
+ * stored without it stay valid).
16554
+ *
16555
+ * When BOTH `overlapThreshold` and `bboxInclusionPct` are set on a
16556
+ * rule, the engine prefers `bboxInclusionPct` because it's the
16557
+ * field exposed in the UI. Internally both feed the same gate.
16558
+ */
16559
+ bboxInclusionPct: number().min(0).max(100).optional(),
16560
+ /**
16561
+ * When `true` and a detection has a segmentation mask, use the
16562
+ * mask for overlap instead of the bbox. Detection-stage only;
16563
+ * motion rules ignore this field.
16564
+ */
16565
+ preferMask: boolean().optional(),
16566
+ /**
16567
+ * Soft-toggle: `false` disables the rule without deleting it.
16568
+ * Defaults to `true` so operators creating a rule via the UI
16569
+ * see it active immediately.
16570
+ */
16571
+ enabled: boolean().default(true)
16661
16572
  });
16573
+ array(ZoneRuleSchema).readonly();
16662
16574
  /**
16663
- * One media row WITHOUT its bytes.
16575
+ * Zone pure geometry + identity. NO filtering behaviour.
16664
16576
  *
16665
- * A track's media is 5-8 MB of base64 (measured: 7.67 MB across 23 files for a
16666
- * 140 s track), and a client that renders tiles from the media data plane needs
16667
- * to know only WHAT EXISTS the bytes then arrive per tile, lazily, over HTTP
16668
- * with an immutable cache, instead of all at once inside a tRPC response that
16669
- * blocks the whole view.
16577
+ * Zones describe **where** in the frame the operator wants to flag
16578
+ * something; consumer-owned {@link ZoneRule} arrays describe **how**
16579
+ * each pipeline stage uses them. Splitting the two means a single
16580
+ * polygon "Driveway" can simultaneously back a motion-exclude rule,
16581
+ * a detection-include rule on `['car']`, and an occupancy aggregate
16582
+ * — without three duplicated polygons.
16670
16583
  *
16671
- * `sizeBytes` is carried because it is what lets a client decide between the
16672
- * stored blob and a `?variant=thumb` rendering without fetching either.
16584
+ * Owned by the orchestrator addon (provider) and mirrored into the
16585
+ * `zones` device-state slice on every mutation. Consumers
16586
+ * (motion-wasm, pipeline-executor, analytics, admin UI) read either
16587
+ * via `api.zones.listZones` (one-shot) or via `dev.state.zones` (live
16588
+ * mirror with `onChanged`).
16589
+ *
16590
+ * Coordinates are normalised fractions of the frame (0–1) so zones
16591
+ * survive resolution changes and stream profile switches.
16592
+ *
16593
+ * `kind` discriminates between full polygons (closed regions used
16594
+ * for intrusion / occupancy filters) and tripwires (open 2-point
16595
+ * line segments used for cross events). Onboard / firmware-reported
16596
+ * zones (Reolink, ONVIF) are out of scope for now — see the deferred
16597
+ * task list.
16673
16598
  */
16674
- var MediaFileInfoSchema = MediaFileSchema.omit({ base64: true });
16599
+ var ZoneKindEnum = _enum(["polygon", "tripwire"]);
16600
+ /** Polygon vertex in fraction-of-frame coordinates (0–1). */
16601
+ var PolygonPointSchema = object({
16602
+ x: number(),
16603
+ y: number()
16604
+ });
16605
+ /** A camera detection zone — pure geometry/identity. */
16606
+ var ZoneSchema = object({
16607
+ id: string(),
16608
+ name: string(),
16609
+ kind: ZoneKindEnum.default("polygon"),
16610
+ /** Polygon vertices, fraction of frame (0–1). */
16611
+ polygon: array(PolygonPointSchema).readonly(),
16612
+ /** Visual color for UI rendering. */
16613
+ color: string().default("#3b82f6")
16614
+ });
16615
+ DeviceType.Camera, method(object({ deviceId: number() }), array(ZoneSchema).readonly()), method(object({
16616
+ deviceId: number(),
16617
+ zone: ZoneSchema
16618
+ }), _void(), {
16619
+ kind: "mutation",
16620
+ auth: "admin"
16621
+ }), method(object({
16622
+ deviceId: number(),
16623
+ zoneId: string()
16624
+ }), _void(), {
16625
+ kind: "mutation",
16626
+ auth: "admin"
16627
+ }), method(object({
16628
+ deviceId: number(),
16629
+ zone: ZoneSchema
16630
+ }), _void(), {
16631
+ kind: "mutation",
16632
+ auth: "admin"
16633
+ }), object({ zones: array(ZoneSchema).readonly() });
16675
16634
  /**
16676
- * The MACRO tier of an annotation — a CLOSED set.
16635
+ * pipeline-analytics device-scoped wrapper cap. Refines raw
16636
+ * per-frame detections emitted by the pipeline runner into tracked
16637
+ * objects, per-kind event collections (motion / object / audio), and
16638
+ * persisted media. Owns the post-detection domain end-to-end:
16677
16639
  *
16678
- * This is what the exported detector predicts, so a typo here is a new class
16679
- * with one example in it. `label` and `subLabel` are open strings by contrast:
16680
- * the whole point of the page is teaching the model things it does not know
16681
- * yet, and constraining that vocabulary would make it useless.
16640
+ * runner emits PipelineInferenceResult
16641
+ * (event bus)
16642
+ * pipeline-analytics subscriber
16643
+ * SORT tracker + zone engine + state analyzer + event emitter
16644
+ * → three DB collections (one per kind), one FS media tree, one
16645
+ * unified event emitter (FrameTracked + TrackStarted/Ended +
16646
+ * DetectionEvent on bus)
16682
16647
  *
16683
- * A macro class is NEVER a label. The provider refuses a write whose `label` or
16684
- * `subLabel` is one of these values, in any casing, because once `person`
16685
- * exists in both tiers "every person box" stops being answerable without
16686
- * knowing every string anyone ever typed — and the damage is retroactive.
16648
+ * Pure subscriber model. No `processFrame` cap method the runner
16649
+ * already publishes the raw frame on the bus. The cap surface is
16650
+ * only QUERIES + per-device settings, bound on/off via
16651
+ * `device-manager.setWrapperActive`. `defaultActive: true` because
16652
+ * every camera with a detection pipeline wants its raw detections
16653
+ * refined; operators opt out per-device via BindingsTab when needed.
16654
+ *
16655
+ * Replaces the legacy `analysis-pipeline`, `analysis-data-persistence`
16656
+ * (per-device surface) and `track-trail` caps — see P11 cleanup.
16687
16657
  */
16688
- var RetrainMacroClassSchema = _enum([
16658
+ var TrackStateSchema = _enum([
16659
+ "new",
16660
+ "entered",
16661
+ "left",
16662
+ "moving",
16663
+ "idle"
16664
+ ]);
16665
+ var EventKindSchema = _enum([
16666
+ "motion",
16667
+ "object",
16668
+ "audio"
16669
+ ]);
16670
+ /**
16671
+ * Spatial filter for `listTracks` — the rect + polygon variants of the shared
16672
+ * MaskShape vocabulary (see `mask-shape.ts`). Coordinates are NORMALIZED 0..1
16673
+ * of the camera frame (top-left origin), matching the drawing-plane editor.
16674
+ */
16675
+ var TrackZoneFilterSchema = discriminatedUnion("kind", [MaskRectShapeSchema, MaskPolygonShapeSchema]);
16676
+ /** Closed icon vocabulary so clients render a known glyph per kind. */
16677
+ var EventKindIconSchema = _enum([
16678
+ "motion",
16679
+ "audio",
16689
16680
  "person",
16690
16681
  "vehicle",
16691
16682
  "animal",
16683
+ "door",
16684
+ "pir",
16685
+ "smoke",
16686
+ "water",
16687
+ "button",
16692
16688
  "package",
16693
- "face",
16694
- "plate"
16689
+ "generic"
16695
16690
  ]);
16696
- /** A subject to learn, or a phantom to unlearn (taught by OMISSION). */
16697
- var RetrainAnnotationKindSchema = _enum(["subject", "model_error"]);
16698
- /** Did a human draw this box, or did the assist propose it? */
16699
- var RetrainAnnotationSourceSchema = _enum(["operator", "assist"]);
16700
- /** Normalised `[0,1]` rectangle against the FULL frame — the canonical form. */
16701
- var RetrainBboxSchema = object({
16691
+ var EventKindCategorySchema = _enum([
16692
+ "motion",
16693
+ "audio",
16694
+ "detection",
16695
+ "sensor",
16696
+ "control",
16697
+ "custom",
16698
+ "package"
16699
+ ]);
16700
+ /** Taxonomy level — macro (timeline lane) vs sub (events-page leaf). */
16701
+ var EventKindLevelSchema = _enum(["macro", "sub"]);
16702
+ var EventKindDescriptorSchema = object({
16703
+ /** Stable kind id (e.g. 'motion', 'vehicle', 'car', 'lock'). */
16704
+ kind: string(),
16705
+ /** i18n key resolved on the UI side; `label` is the English fallback. */
16706
+ labelKey: string(),
16707
+ /** English fallback label (kept for clients that don't translate). */
16708
+ label: string(),
16709
+ /** Hex color for timeline/legend rendering. */
16710
+ color: string(),
16711
+ /** Dictionary id → lucide component on the UI side. */
16712
+ iconId: string(),
16713
+ /** Legacy closed-vocab glyph — fallback for `iconId`. */
16714
+ icon: EventKindIconSchema,
16715
+ category: EventKindCategorySchema,
16716
+ /** Macro parent for this kind ('car' → 'vehicle'); null for a macro. */
16717
+ parentKind: string().nullable(),
16718
+ /** Derived from `parentKind`, explicit for the client tree. */
16719
+ level: EventKindLevelSchema,
16720
+ /** Which cap + device contributes this kind. For built-ins the camera
16721
+ * itself; for sensor kinds the LINKED source device. */
16722
+ source: object({
16723
+ capName: string(),
16724
+ deviceId: number()
16725
+ })
16726
+ });
16727
+ /** One camera's event vocabulary, as returned by `listEventKindsBatch`. */
16728
+ var EventKindsForDeviceSchema = object({
16729
+ deviceId: number(),
16730
+ kinds: array(EventKindDescriptorSchema).readonly()
16731
+ });
16732
+ var SensorEventSchema = object({
16733
+ id: string(),
16734
+ /** The CAMERA the event is attributed to (a sensor linked to N cameras
16735
+ * yields N rows, one per camera). */
16736
+ deviceId: number(),
16737
+ /** The linked sensor device whose state changed. */
16738
+ sourceDeviceId: number(),
16739
+ /** Event kind id — matches an `EventKindDescriptor.kind`. */
16740
+ kind: string(),
16741
+ /** Snapshot of the sensor cap's runtime-state slice at the change. */
16742
+ value: record(string(), unknown()).nullable(),
16743
+ timestamp: number()
16744
+ });
16745
+ var TrackPositionSchema = object({
16702
16746
  x: number(),
16703
16747
  y: number(),
16704
- w: number(),
16705
- h: number()
16748
+ timestamp: number(),
16749
+ bbox: BoundingBoxSchema
16750
+ });
16751
+ var TrackSnapshotSchema = object({
16752
+ timestamp: number(),
16753
+ position: TrackPositionSchema,
16754
+ /** MediaStore key; resolve via `getTrackMedia({ trackId })`. */
16755
+ mediaKey: string()
16706
16756
  });
16707
16757
  /**
16708
- * One annotated subject.
16709
- *
16710
- * `bbox` is normalised against the full frame, ALWAYS. The per-model shapes
16711
- * (letterboxed root / zone-cropped package / subject-cropped classifier) are
16712
- * derived from it at export and never stored — storing them is how one feature
16713
- * space ends up holding two crops of the same subject (D52).
16758
+ * Normalized 0..1 trajectory envelope (min/max over every position bbox,
16759
+ * divided by the track's detection-frame dims), computed at persist time.
16760
+ * Absent when the frame dims were unknown when the track was persisted
16761
+ * (legacy rows / dims-less sources) and on active (in-RAM) tracks.
16714
16762
  */
16715
- var RetrainAnnotationSchema = object({
16716
- id: string(),
16763
+ var TrackEnvelopeSchema = object({
16764
+ minX: number(),
16765
+ minY: number(),
16766
+ maxX: number(),
16767
+ maxY: number()
16768
+ });
16769
+ /**
16770
+ * Row projection for track list queries. `full` (default) returns the
16771
+ * complete Track including the frame-rate `positions[]` history and the
16772
+ * `snapshots[]` references — megabytes across a page of tracks. `slim`
16773
+ * keeps every scalar the list surfaces actually render (ids, class(es),
16774
+ * label / audioLabels / importance enrichment, firstSeen/lastSeen, state,
16775
+ * zonesVisited, bestEventId, envelope, hasFace, hasEmbeddedFace, hasRider) and returns `positions` /
16776
+ * `snapshots` as EMPTY arrays — detail views re-fetch the full row via
16777
+ * `getTrack`. Mirrors the event-store `projection` convention
16778
+ * (`getObjectEvents` et al.).
16779
+ */
16780
+ var TrackProjectionSchema = _enum(["full", "slim"]);
16781
+ /**
16782
+ * One audio-classification label heard on the track's camera while the
16783
+ * track was alive, aggregated per label. An "episode" is one persisted
16784
+ * audio event (the confident-classification path: score ≥ the device's
16785
+ * `classificationMinScore`, class-change-or-heartbeat coalesced) — NOT
16786
+ * one 32 ms inference chunk, so counts stay human-scaled.
16787
+ */
16788
+ var TrackAudioLabelSchema = object({
16789
+ label: string(),
16790
+ /** Highest classification score observed across the label's episodes. */
16791
+ peakScore: number(),
16792
+ /** Number of coalesced audio-event episodes carrying this label. */
16793
+ count: number(),
16794
+ firstAt: number(),
16795
+ lastAt: number()
16796
+ });
16797
+ /**
16798
+ * How a track was produced. `pipeline` (default / absent) = the spatial
16799
+ * detection+tracking pipeline. Every OTHER value is a SYNTHETIC projection —
16800
+ * no positions, a single snapshot, and no bbox trajectory at all:
16801
+ *
16802
+ * - `sensor` — a linked sensor/control device state change.
16803
+ * - `audio` — an audio event on the camera itself that was anomalous for
16804
+ * THAT camera, loud, and heard while nothing visual was happening (D62).
16805
+ *
16806
+ * The spatial subsystems (tracker association, occupancy count, re-id /
16807
+ * embedding, resurrection) MUST skip every synthetic source. Test for that
16808
+ * with `isSpatialTrack`, which allow-lists `pipeline` — a `!== 'sensor'`
16809
+ * check silently readmits every source added after it was written.
16810
+ */
16811
+ var TrackSourceSchema = _enum([
16812
+ "pipeline",
16813
+ "sensor",
16814
+ "audio"
16815
+ ]);
16816
+ /**
16817
+ * Where a track sits in the RETRAIN lifecycle (D81).
16818
+ *
16819
+ * - `none` — never marked, or un-marked. Evictable.
16820
+ * - `staging` — the operator wants this track as training material and has not
16821
+ * finished with it. **This is the only state retention holds**: the track and
16822
+ * everything it owns (object events, crops, keyframes, CLIP vector) survive
16823
+ * the device's age window.
16824
+ * - `trained` — the retrain page has taken what it needed. The frames it chose
16825
+ * were COPIED into the retrain dataset at selection time, so the dataset no
16826
+ * longer depends on the track's media and the track becomes EVICTABLE again.
16827
+ * Terminal for the plain `markForTrain` toggle: returning it to `staging` is
16828
+ * a deliberate action of the retrain page, not a side effect of a checkbox.
16829
+ *
16830
+ * There is no `null`. The state is stored `TEXT NOT NULL DEFAULT 'none'` because
16831
+ * the store's filter language has only positive equality and `whereIn` — no
16832
+ * negation, no IS NULL — so a NULL would be unselectable by ANY predicate and
16833
+ * would make the entire pre-column history immortal in one deploy.
16834
+ */
16835
+ var RetrainStatusSchema = _enum([
16836
+ "none",
16837
+ "staging",
16838
+ "trained"
16839
+ ]);
16840
+ /**
16841
+ * Per-track OPERATOR flags — set by hand from the admin UI or the viewer, never
16842
+ * by the pipeline. Spread into `TrackSchema` and `KeyEventSchema` from one place
16843
+ * so the two surfaces cannot drift.
16844
+ *
16845
+ * **Absent ≠ false.** A track that has never been touched omits the field; an
16846
+ * explicitly un-flagged track carries `false`. Legacy rows written before the
16847
+ * columns existed read as absent, and a consumer that needs a boolean should say
16848
+ * `flag === true`, not `flag !== false`.
16849
+ *
16850
+ * `markForTrain` is the WIRE FACE of {@link RetrainStatusSchema}, not a column:
16851
+ * it is exactly `retrainStatus === 'staging'`, in both directions. Writing
16852
+ * `true` moves `none → staging`, writing `false` moves `staging → none`, and a
16853
+ * `trained` track reports `false` while refusing both writes. The boolean is
16854
+ * kept because three surfaces drive a toggle off it; anything that needs to tell
16855
+ * "never marked" from "already trained" must read `retrainStatus`.
16856
+ *
16857
+ * `debug` does NOT pin; it is attention, not durability.
16858
+ *
16859
+ * `favourited` IS a BOOLEAN pin (durability bit), not a retrain lifecycle.
16860
+ * A favourited track is skipped by retention the same way `staging` is, but
16861
+ * it does not enter `none|staging|trained` and has no staging budget.
16862
+ */
16863
+ var TrackFlagFields = {
16864
+ /** Operator marked this track as training material — i.e. `retrainStatus` is
16865
+ * `'staging'`. */
16866
+ markForTrain: boolean().optional(),
16867
+ /** Operator marked this track for diagnostic attention. */
16868
+ debug: boolean().optional(),
16869
+ /** Operator favourited this track. Pins it against pruning. */
16870
+ favourited: boolean().optional()
16871
+ };
16872
+ /**
16873
+ * The lifecycle field itself, on the READ surfaces only (`Track`, `KeyEvent`).
16874
+ * Deliberately NOT part of {@link TrackFlagFields}: that group also builds the
16875
+ * write patch, and the status is not something the toggle sets — it is what the
16876
+ * toggle's boolean is derived from. Absent on an in-RAM track never touched;
16877
+ * always present on a persisted row (the column default materialises `'none'`).
16878
+ */
16879
+ var TrackRetrainFields = { retrainStatus: RetrainStatusSchema.optional() };
16880
+ /**
16881
+ * The write half: a PARTIAL patch. An omitted key is left untouched, so setting
16882
+ * one flag can never clear the other — the toggles are independent and are
16883
+ * driven from three surfaces that do not know about each other.
16884
+ */
16885
+ var TrackFlagsPatchSchema = object(TrackFlagFields);
16886
+ /**
16887
+ * The resolved flag state after a write. Both fields are REQUIRED here (absent
16888
+ * collapses to `false`) so a caller can drive a toggle's checked state off the
16889
+ * mutation result without a re-fetch.
16890
+ */
16891
+ var TrackFlagsSchema = object({
16717
16892
  trackId: string(),
16718
- deviceId: number(),
16719
- /** The COPY in retrain storage — never the source track's media key. */
16720
- mediaKey: string(),
16721
- bbox: RetrainBboxSchema,
16722
- macroClass: RetrainMacroClassSchema,
16893
+ markForTrain: boolean(),
16894
+ debug: boolean(),
16895
+ favourited: boolean(),
16896
+ /** The lifecycle state the boolean was derived from. Required here (unlike on
16897
+ * a track row) because this shape is only ever produced by the write body,
16898
+ * which always knows it — and a surface that has just written needs to render
16899
+ * `trained` without a re-fetch. */
16900
+ retrainStatus: RetrainStatusSchema
16901
+ });
16902
+ union([literal(1), literal(2)]);
16903
+ /**
16904
+ * WHO decided a label, and when. Carried per tier so a value can be traced to
16905
+ * the step and model that produced it — which is what makes the write rule
16906
+ * arguable after the fact ("why is 592's label `dog` and not `Canis lupus`?")
16907
+ * and what lets a migrated, UNATTRIBUTED value be told apart from a real one.
16908
+ *
16909
+ * `stepId` is the pipeline step id (`animal-classifier`, `bird-classifier`,
16910
+ * `plate-ocr`, `face-embedding`, `object-detection`), or the sentinel
16911
+ * `migration:4g` for a value the 4g migration moved from the single-slot era —
16912
+ * that value has no provenance, and the write rule lets ANY properly-attributed
16913
+ * write of the same tier replace it regardless of score.
16914
+ */
16915
+ var LabelAttributionSchema = object({
16916
+ stepId: string(),
16917
+ modelId: string().optional(),
16918
+ decidedAt: number(),
16919
+ /**
16920
+ * The GALLERY id behind a recognised tier-2 label — a face-gallery
16921
+ * `Identity.id` or a plate-gallery `Vehicle.id` (both `randomUUID`).
16922
+ *
16923
+ * The text alone is a DISPLAY NAME, and a display name is renameable: a
16924
+ * notification rule authored on "Gianluca" stopped matching the moment the
16925
+ * operator fixed the spelling in the gallery, and nothing said so. The id is
16926
+ * the thing that does not move, so it is what a rule matches on
16927
+ * (`NcConditions.identities`) and the text is what a human is shown.
16928
+ *
16929
+ * Absent when the label names no gallery row — a plate the OCR read but no
16930
+ * vehicle claims, a sub-class, a species, any tier-1 value.
16931
+ */
16932
+ identityId: string().optional()
16933
+ });
16934
+ /**
16935
+ * The TIERED label model (roadmap 4g), spread into `TrackSchema` and
16936
+ * `ObjectEventSchema` from ONE place so the two surfaces cannot drift — a
16937
+ * track and its events always answer the same question the same way.
16938
+ *
16939
+ * Two scalar columns, not an array: every consumer wants "the coarse one" or
16940
+ * "the fine one", and an array made both a scan. `label` is tier 1, `subLabel`
16941
+ * is tier 2, and each carries its own score + attribution.
16942
+ *
16943
+ * **Reading it.** What a human should be shown is `subLabel ?? label` — the
16944
+ * finest thing known. Before 4g the single `label` column held the finest
16945
+ * value, so a consumer that has not been updated reads the tier-1 slot and
16946
+ * shows nothing on a species-only row; that is why the migration puts every
16947
+ * pre-4g value in tier 2 (it cannot regress a display that reads the fallback)
16948
+ * and why the read surfaces were changed in the same train.
16949
+ *
16950
+ * **Writing it.** The slots are independent, which is the whole point: a
16951
+ * tier-1 write (`bird`) can never overwrite a tier-2 value (`Turdus
16952
+ * migratorius`), so fineness cannot regress by construction. Within a tier the
16953
+ * higher score wins. One rule, one implementation — see
16954
+ * `pipeline/label-tier.ts` in addon-post-analysis.
16955
+ */
16956
+ var TieredLabelFields = {
16957
+ /** Tier 1 — the sub-class. See {@link LabelTierSchema}. */
16723
16958
  label: string().optional(),
16959
+ /** Confidence of the tier-1 value, as reported by the deciding step. */
16960
+ labelScore: number().optional(),
16961
+ /** Provenance of the tier-1 value. See {@link LabelAttributionSchema}. */
16962
+ labelMeta: LabelAttributionSchema.optional(),
16963
+ /** Tier 2 — the instance. See {@link LabelTierSchema}. */
16724
16964
  subLabel: string().optional(),
16725
- kind: RetrainAnnotationKindSchema,
16726
- source: RetrainAnnotationSourceSchema,
16727
- /** Which model proposed this box or, on a `model_error`, drew the phantom. */
16728
- assistModelId: string().optional(),
16729
- assistScore: number().optional(),
16730
- exportedInBatch: string().optional(),
16731
- createdAt: number()
16965
+ /** Confidence of the tier-2 value, as reported by the deciding step. */
16966
+ subLabelScore: number().optional(),
16967
+ /** Provenance of the tier-2 value. See {@link LabelAttributionSchema}. */
16968
+ subLabelMeta: LabelAttributionSchema.optional()
16969
+ };
16970
+ /** Per-camera slice of a training-export estimate. */
16971
+ var TrainingExportDeviceTotalsSchema = object({
16972
+ deviceId: number(),
16973
+ tracks: number().int(),
16974
+ files: number().int(),
16975
+ bytes: number().int()
16732
16976
  });
16733
- /** The write form — the server owns `id`, `createdAt` and the frame binding. */
16734
- var RetrainAnnotationDraftSchema = RetrainAnnotationSchema.omit({
16735
- id: true,
16736
- trackId: true,
16737
- deviceId: true,
16738
- mediaKey: true,
16739
- createdAt: true,
16740
- exportedInBatch: true
16977
+ /**
16978
+ * What a training export WOULD contain. Computed from media index rows only —
16979
+ * no blob is read to produce this.
16980
+ */
16981
+ var TrainingExportSummarySchema = object({
16982
+ generatedAt: number(),
16983
+ trackCount: number().int(),
16984
+ fileCount: number().int(),
16985
+ byteCount: number().int(),
16986
+ /** More marked tracks exist than a single pass carries. */
16987
+ truncated: boolean(),
16988
+ devices: array(TrainingExportDeviceTotalsSchema).readonly()
16741
16989
  });
16742
- /** A track sitting in `staging`, with everything the worklist needs to rank it. */
16743
- var RetrainTrackSchema = object({
16990
+ var TrackSchema = object({
16744
16991
  trackId: string(),
16745
16992
  deviceId: number(),
16746
16993
  className: string(),
16747
- label: string().optional(),
16994
+ ...TieredLabelFields,
16995
+ producingDeviceName: string().optional(),
16996
+ /** Track provenance. Absent ⇒ `pipeline` (legacy rows). */
16997
+ source: TrackSourceSchema.optional(),
16748
16998
  firstSeen: number(),
16749
16999
  lastSeen: number(),
16750
- /** How many frames the dataset already holds from this track. */
16751
- frameCount: number().int(),
16752
- /** How many subjects have been annotated on those frames. `0` with
16753
- * `frameCount: 0` is exactly "staging, still to work". */
16754
- annotationCount: number().int()
16755
- });
16756
- /** A frame the picker may offer — an index row, no blob was read to produce it. */
16757
- var RetrainFrameCandidateSchema = object({
16758
- mediaKey: string(),
16759
- kind: MediaFileKindEnum,
16760
- timestamp: number(),
16761
- sizeBytes: number().int(),
16762
- /** A copy of this original already exists selecting it is free and cannot
16763
- * fail, whatever became of the original. */
16764
- copied: boolean()
17000
+ /** Frame-rate position history (subject to maxPositionHistory cap). */
17001
+ positions: array(TrackPositionSchema).readonly(),
17002
+ /** Periodic snapshots at snapshotIntervalMs cadence (subject to
17003
+ * saveThumbnails policy). */
17004
+ snapshots: array(TrackSnapshotSchema).readonly(),
17005
+ /** Deduplicated zones the track has entered at least once. Zone IDS. */
17006
+ zonesVisited: array(string()).readonly(),
17007
+ /**
17008
+ * Human NAMES for {@link zonesVisited}, resolved at READ time against the
17009
+ * `zones` capability.
17010
+ *
17011
+ * `zonesVisited` persists ids (`cfeec78c-8d69-…`), which no operator can type
17012
+ * and no card can render so every free-text search surface was structurally
17013
+ * unable to answer "show me the tracks in Uscio", and did not fail loudly, it
17014
+ * just returned nothing. Resolving here rather than in each client keeps ONE
17015
+ * derivation and costs the clients no extra call (the `zones` cap is
17016
+ * per-device, so a client-side resolve would be a per-camera fan-out on a
17017
+ * surface built to avoid exactly that).
17018
+ *
17019
+ * Resolved, never invented: a zone deleted since the track was written has no
17020
+ * name and is DROPPED, so this array can be shorter than `zonesVisited` — the
17021
+ * two are not positionally aligned. Absent when the track visited no zone, or
17022
+ * when the zone catalogue could not be read.
17023
+ */
17024
+ zoneNames: array(string()).readonly().optional(),
17025
+ /** Deduplicated set of detector classes observed for this track over its
17026
+ * life (a track may be reclassified, e.g. person→vehicle). Absent on
17027
+ * legacy rows written before class accumulation shipped. */
17028
+ classes: array(string()).readonly().optional(),
17029
+ /** Cumulative normalized distance travelled (0..1 units = full frame width). */
17030
+ totalDistance: number(),
17031
+ state: TrackStateSchema,
17032
+ active: boolean(),
17033
+ /** Deterministic key-event importance score in [0,1] (server-computed at
17034
+ * track expiry, recomputed on late label). Absent on legacy rows written
17035
+ * before scoring shipped — consumers degrade to absence / compute-on-read. */
17036
+ importance: number().optional(),
17037
+ /** Id of the track's highest-confidence ObjectEvent (its representative
17038
+ * "best" frame). Absent when the track produced no object events. */
17039
+ bestEventId: string().optional(),
17040
+ /** Tag of the importance sub-signal that dominated the score
17041
+ * (identity|dwell|proximity|class|confidence|travel|zone). */
17042
+ importanceReason: string().optional(),
17043
+ /** Audio-classification labels heard on the camera during the track's
17044
+ * life (score ≥ device `classificationMinScore`), aggregated per label.
17045
+ * Absent on legacy rows / tracks with no confident audio. */
17046
+ audioLabels: array(TrackAudioLabelSchema).readonly().optional(),
17047
+ /** Normalized 0..1 trajectory envelope (see {@link TrackEnvelopeSchema}).
17048
+ * Populated from the persisted envelope columns on historical reads;
17049
+ * absent on legacy rows, dims-less tracks and active (in-RAM) tracks. */
17050
+ envelope: TrackEnvelopeSchema.optional(),
17051
+ /**
17052
+ * A face DETECTOR found a face on this track — nothing more. It says the
17053
+ * detail plane produced a `face` detail; it does NOT say the face was
17054
+ * embedded, matched, above `minFacePx`, or that the recognizer was even
17055
+ * enabled. Set once and never cleared.
17056
+ *
17057
+ * **This exists so "face present but not recognised" is expressible.** A
17058
+ * recognised identity lands in `subLabel` (attributed to the face chain via
17059
+ * `subLabelMeta.stepId`), so before this field a track with an unmatched face
17060
+ * and a track with no face at all were byte-identical on the wire and no
17061
+ * surface could tell them apart. The read is `hasFace === true && subLabel
17062
+ * === undefined`.
17063
+ *
17064
+ * **Absent ≠ false.** Every row written before the column existed omits it,
17065
+ * and so does every server that predates the field — a consumer must test
17066
+ * `=== true` and render nothing otherwise, never infer "no face".
17067
+ */
17068
+ hasFace: boolean().optional(),
17069
+ /**
17070
+ * This track has a face row IN THE GALLERY: a crop **and** an embedding — a
17071
+ * face an operator could ASSIGN to an identity.
17072
+ *
17073
+ * The STRICT twin of {@link hasFace}, and the pair only earns its keep
17074
+ * because the two disagree. `hasFace` is stamped at the TOP of the face
17075
+ * branch, before every gate, and means no more than "a face detector produced
17076
+ * a face detail". This one is stamped at the single moment the gallery row
17077
+ * LANDS — after `FaceRecognizer.onTrackEnd` successfully persists it, i.e.
17078
+ * past the embedding-magnitude verdict, the `minFacePx` detection gate, the
17079
+ * candidate gate, the imageless-track drop (no crop was ever captured) and
17080
+ * the crop-store drop. Everything between the detector and that insert can
17081
+ * legitimately refuse the face, so a flag written any earlier promises the
17082
+ * operator something to assign and delivers nothing.
17083
+ *
17084
+ * **Independent of recognition.** A face collected but never auto-matched is
17085
+ * still assignable — it is in fact the face an operator most wants to reach —
17086
+ * so this is NOT gated on `recognizedIdentityId`. Recognition lands in
17087
+ * `subLabel`; this says only that the raw material exists.
17088
+ *
17089
+ * **Set once, never cleared.** A track that produced a gallery row produced
17090
+ * one; deleting the row later is the gallery's business, not this flag's.
17091
+ *
17092
+ * **Absent ≠ false**, the same rule as {@link hasFace}: every row written
17093
+ * before the column omits it, and so does every server that predates the
17094
+ * field. A consumer must test `=== true` and render nothing otherwise —
17095
+ * never infer "no assignable face".
17096
+ */
17097
+ hasEmbeddedFace: boolean().optional(),
17098
+ /**
17099
+ * This subject CONTAINS a folded rider — a person the rider-pairing step
17100
+ * ([D34](../decisions/adr-0034.md)) removed from the frame BEFORE the tracker,
17101
+ * so the passage is tracked once and as a VEHICLE.
17102
+ *
17103
+ * It exists because the fold's record was dishonest. D34 and the code both
17104
+ * said "the person is not lost — it is reported so both entities stay on the
17105
+ * record"; in fact the pair went into a per-processor RAM field behind an
17106
+ * accessor nobody called, and every durable surface said `vehicle`, full
17107
+ * stop. This is the composition note that makes the row true.
17108
+ *
17109
+ * A COMPOSITION, never a class and never a label. "This vehicle contains a
17110
+ * person" is not an answer to "what is this" — both label tiers would refuse
17111
+ * a macro token anyway (D89), and correctly. Nothing here changes what the
17112
+ * subject IS: a cyclist stays one vehicle track, occupancy still counts one,
17113
+ * and a `person` rule still does not fire for someone cycling past.
17114
+ *
17115
+ * **Absent ≠ false**, exactly like {@link hasFace}: every row written before
17116
+ * the column, and every hub that predates the field, omits it. Test
17117
+ * `=== true` and render nothing otherwise — never infer "no rider".
17118
+ */
17119
+ hasRider: boolean().optional(),
17120
+ ...TrackFlagFields,
17121
+ ...TrackRetrainFields
16765
17122
  });
16766
- /** A frame the dataset OWNS: bytes copied at selection time. */
16767
- var RetrainFrameSchema = object({
16768
- frameId: string(),
17123
+ var BaseEventFields = {
17124
+ id: string(),
16769
17125
  deviceId: number(),
16770
- trackId: string(),
16771
- /** Provenance only. It may already point at nothing — that is expected. */
16772
- sourceMediaKey: string(),
16773
- sourceKind: MediaFileKindEnum,
16774
- sizeBytes: number().int(),
16775
- width: number().int(),
16776
- height: number().int(),
16777
- copiedAt: number()
16778
- });
16779
- /** Why a copy-on-select could not be honoured — named, never a silent skip. */
16780
- var RetrainCopyRefusalSchema = _enum([
16781
- "source-missing",
16782
- "unreadable-image",
16783
- "write-failed"
16784
- ]);
16785
- var RetrainFrameSelectionSchema = object({
16786
- copied: array(RetrainFrameSchema).readonly(),
16787
- refused: array(object({
16788
- sourceMediaKey: string(),
16789
- reason: RetrainCopyRefusalSchema
16790
- })).readonly()
16791
- });
16792
- var RetrainFrameListSchema = object({
16793
- candidates: array(RetrainFrameCandidateSchema).readonly(),
16794
- copies: array(RetrainFrameSchema).readonly(),
16795
- /** What the page pre-selects — the native key frame when one survives. */
16796
- autoPickMediaKey: string().optional()
17126
+ timestamp: number()
17127
+ };
17128
+ var MotionEventSchema = object({
17129
+ ...BaseEventFields,
17130
+ kind: literal("motion"),
17131
+ regionCount: number(),
17132
+ /** Heavy JSON array — omitted in slim projection. */
17133
+ regions: array(object({
17134
+ bbox: BoundingBoxSchema,
17135
+ pixelCount: number(),
17136
+ intensity: number()
17137
+ })).readonly().optional(),
17138
+ /** Omitted in slim projection. */
17139
+ frameWidth: number().optional(),
17140
+ /** Omitted in slim projection. */
17141
+ frameHeight: number().optional(),
17142
+ /** Populated by B5 (recording playback URL for this event). */
17143
+ mediaUrl: string().optional()
16797
17144
  });
16798
- /** What the operator asked the assist to look for. */
16799
- var RetrainAssistSubjectSchema = discriminatedUnion("kind", [object({
16800
- kind: literal("package"),
16801
- zone: RetrainBboxSchema.optional()
16802
- }), object({
16803
- kind: literal("objects"),
16804
- modelId: string(),
16805
- minScore: number().optional()
16806
- })]);
16807
17145
  /**
16808
- * The assist's answer a discriminated union, because "the model saw nothing"
16809
- * and "this node cannot run that model" lead to different next moves and a
16810
- * nullable result cannot tell them apart.
17146
+ * Which detection SOURCE produced an object event. `pipeline` = the ML
17147
+ * detection pipeline (decoded-frame inference); `onboard` = the camera's
17148
+ * native on-device AI. Both flow through the SAME analysis layers (zoning,
17149
+ * tracking, per-kind persistence) but stay distinguishable so consumers
17150
+ * (advanced-notifier, occupancy, …) can select which source(s) to act on.
17151
+ * Absent on legacy rows ⇒ treat as `pipeline`.
16811
17152
  */
16812
- var RetrainAssistResultSchema = discriminatedUnion("kind", [object({
16813
- kind: literal("proposed"),
16814
- modelId: string(),
16815
- stepId: string(),
16816
- minScore: number(),
16817
- /** Drafts, ready to edit. `source: 'assist'` until the operator touches one. */
16818
- proposals: array(RetrainAnnotationDraftSchema).readonly(),
16819
- /** Returned by the runner but removed by the threshold. */
16820
- belowThreshold: number().int()
16821
- }), object({
16822
- kind: literal("refused"),
16823
- /** `no-zone` is ours; the rest are the runner's own refusal vocabulary. */
16824
- reason: string(),
16825
- detail: string().optional()
16826
- })]);
16827
- /** The outcome of a lifecycle move owned by the retrain page. */
16828
- var RetrainTransitionResultSchema = object({
16829
- trackId: string(),
16830
- /** Where the track ended up, whatever happened. */
16831
- retrainStatus: RetrainStatusSchema,
16832
- /** `false` ⇒ the move was refused or was a no-op; `reason` says which. */
16833
- changed: boolean(),
16834
- reason: _enum([
16835
- "unknown-track",
16836
- "no-frames-copied",
16837
- "not-staging",
16838
- "not-trained",
16839
- "unchanged"
16840
- ]).optional()
17153
+ var DetectionSourceSchema = _enum(["pipeline", "onboard"]);
17154
+ /**
17155
+ * The confirmed zone crossing that produced an object event. Present ONLY on
17156
+ * an event emitted BY a crossing (`zone.enter` / `zone.exit`); a movement-state
17157
+ * event (`object.entering` / `leaving` / `stationary` / `loitering`) and an
17158
+ * appearance event carry none, so a rule asking for a direction fails closed
17159
+ * on them.
17160
+ *
17161
+ * Exactly ONE crossing per event: the emitter turns each confirmed crossing
17162
+ * into its own event, so a frame in which a track enters A while leaving B
17163
+ * produces two events with two directions — never one ambiguous row.
17164
+ *
17165
+ * `zoneId` is load-bearing for an EXIT: the event's `zones` list is the
17166
+ * membership the box has NOW, and by definition it no longer contains the zone
17167
+ * that was just left. Without the id here, a zone-scoped rule could never match
17168
+ * the exit it asked for.
17169
+ */
17170
+ var ZoneCrossingSchema = object({
17171
+ direction: _enum(["enter", "exit"]),
17172
+ /** Admin zone id crossed. */
17173
+ zoneId: string(),
17174
+ /** Zone display name at crossing time (falls back to the id). */
17175
+ zoneName: string().optional()
16841
17176
  });
16842
- var DEFAULT_EVENT_QUERY_LIMIT = 1e3;
16843
- var MAX_EVENT_QUERY_LIMIT = 5e3;
16844
- var DeviceEventQueryInput = object({
16845
- deviceId: number(),
16846
- since: number().optional(),
16847
- until: number().optional(),
16848
- limit: number().int().min(1).max(MAX_EVENT_QUERY_LIMIT).default(DEFAULT_EVENT_QUERY_LIMIT),
16849
- /** `slim` drops heavy JSON fields (regions/bbox/zones) and carries an
16850
- * optional `mediaUrl` (populated by B5). `full` (default) keeps today's
16851
- * exact behaviour. Callers may omit this field the store defaults to
16852
- * `full` when not provided. */
16853
- projection: _enum(["full", "slim"]).optional()
16854
- });
16855
- var ObjectEventQueryInput = DeviceEventQueryInput.extend({ classFilter: string().optional() });
16856
- var RecentTracksQueryInput = object({
16857
- /** Devices to merge. An empty array yields `{ tracks: [], nextCursor: null }`. */
16858
- deviceIds: array(number()),
16859
- /** Window lower bound on `lastSeen` (inclusive). */
16860
- since: number().optional(),
16861
- /** Window upper bound on `lastSeen` (inclusive). */
16862
- until: number().optional(),
16863
- /** Page size. Default 200, max 1000. */
16864
- limit: number().int().min(1).max(1e3).default(200),
16865
- /** Opaque continuation cursor from a previous page's `nextCursor`.
16866
- * Encodes the (lastSeen, trackId) sort position — treat as opaque. */
16867
- cursor: string().optional(),
16868
- /** See {@link TrackProjectionSchema}. Default `full`. */
16869
- projection: TrackProjectionSchema.optional(),
16870
- /** Include stationary-promoted rows (parked objects). Default false: the
16871
- * feed lists passages; parking records live on the stationary registry. */
16872
- includeStationary: boolean().optional()
16873
- });
16874
- var RecentTracksPageSchema = object({
16875
- /** Merged page, ordered by (`lastSeen` DESC, `trackId` DESC). */
16876
- tracks: array(TrackSchema).readonly(),
16877
- /** Cursor for the next page, or null when this page is the last. */
16878
- nextCursor: string().nullable()
16879
- });
16880
- var LIST_GROUPS_DEFAULT_LIMIT = 40;
16881
- var LIST_GROUPS_MAX_LIMIT = 100;
16882
- var AnalyticsGroupRecordSchema = object({
16883
- id: string(),
16884
- deviceId: number().int(),
16885
- openedAt: number().int(),
16886
- closedAt: number().int(),
16887
- timestamp: number().int(),
16888
- memberCount: number().int(),
16889
- memberTrackIds: array(string()).readonly(),
16890
- className: string(),
16891
- classes: array(string()).readonly(),
16892
- /** Relative event-media path, or null when the group has no picture yet. */
16893
- mediaUrl: string().nullable(),
16894
- singleton: boolean()
16895
- });
16896
- var AnalyticsGroupMemberSchema = object({
16897
- trackId: string(),
16898
- deviceId: number().int(),
16899
- className: string(),
16900
- firstSeen: number().int(),
16901
- lastSeen: number().int(),
16902
- mediaUrl: string().nullable()
16903
- });
16904
- var AnalyticsGroupDetailSchema = AnalyticsGroupRecordSchema.extend({ members: array(AnalyticsGroupMemberSchema).readonly() });
16905
- var ListGroupsQueryInput = object({
16906
- /** Devices to merge. An empty array yields `{ groups: [], nextCursor: null }`. */
16907
- deviceIds: array(number()),
16908
- /** Window lower bound on `closedAt` (inclusive). */
16909
- since: number().optional(),
16910
- /** Window upper bound on `openedAt` (inclusive). */
16911
- until: number().optional(),
16912
- limit: number().int().min(1).max(LIST_GROUPS_MAX_LIMIT).default(LIST_GROUPS_DEFAULT_LIMIT),
16913
- /** Opaque continuation cursor from a previous page's `nextCursor`. */
16914
- cursor: string().optional()
16915
- });
16916
- var ListGroupsPageSchema = object({
16917
- groups: array(AnalyticsGroupRecordSchema).readonly(),
16918
- nextCursor: string().nullable()
16919
- });
16920
- var KeyEventQueryInput = object({
16921
- deviceId: number(),
16922
- /** Window lower bound (track firstSeen ≥ since). */
16923
- since: number(),
16924
- /** Window upper bound (track firstSeen ≤ until). */
16925
- until: number(),
16926
- limit: number().int().min(1).max(200).default(50),
16927
- /** Drop tracks scoring below this importance. */
16928
- minImportance: number().min(0).max(1).optional(),
16929
- /** Restrict to a single class (e.g. 'person'). */
16930
- classFilter: string().optional()
16931
- });
16932
- var KeyEventSchema = object({
16933
- /** The representative event id (the track's best ObjectEvent, else its trackId). */
16934
- id: string(),
16935
- trackId: string(),
16936
- /** Track start time (firstSeen). */
16937
- timestamp: number(),
17177
+ var ObjectEventSchema = object({
17178
+ ...BaseEventFields,
17179
+ kind: literal("object"),
17180
+ /** Detection source. Optional for backward-compat; absent ⇒ `pipeline`. */
17181
+ source: DetectionSourceSchema.optional(),
17182
+ /**
17183
+ * Inference-frame id shared by every object event emitted from the SAME frame
17184
+ * the "scene/parent" key. Lets a consumer group co-occurring detections (e.g.
17185
+ * 2 people + 1 dog) under one full frame, and link a track's frames over time
17186
+ * (group by `trackId`, pick a representative `frameId` as the parent frame).
17187
+ * Optional for backward-compat with pre-existing rows / the slim projection
17188
+ * includes it (it is light). Absent on rows written before this field.
17189
+ */
17190
+ frameId: string().optional(),
17191
+ /** Omitted in slim projection. */
17192
+ trackId: string().optional(),
16938
17193
  className: string(),
16939
17194
  ...TieredLabelFields,
16940
- importance: number(),
16941
- /** Highest-confidence ObjectEvent id for the track (empty when none). */
16942
- bestEventId: string(),
16943
- /** Track lifetime in ms (lastSeen - firstSeen). */
16944
- windowMs: number().optional(),
16945
- ...TrackFlagFields,
16946
- ...TrackRetrainFields
16947
- });
16948
- object({
16949
- trackId: string(),
16950
- className: string(),
16951
- confidence: number(),
16952
- bbox: BoundingBoxSchema,
16953
- zones: array(string()).readonly(),
16954
- state: TrackStateSchema
17195
+ /** Omitted in slim projection. */
17196
+ confidence: number().optional(),
17197
+ /** Heavy JSON — omitted in slim projection. */
17198
+ bbox: BoundingBoxSchema.optional(),
17199
+ /** Heavy JSON — omitted in slim projection. */
17200
+ zones: array(string()).readonly().optional(),
17201
+ /** Omitted in slim projection. */
17202
+ state: TrackStateSchema.optional(),
17203
+ /**
17204
+ * The zone crossing this event IS, when it is one. Absent on every other
17205
+ * event kind (movement state, appearance, package) — see
17206
+ * {@link ZoneCrossingSchema}. Omitted in slim projection.
17207
+ */
17208
+ zoneCrossing: ZoneCrossingSchema.optional(),
17209
+ /** Detection-frame dimensions in pixels — let consumers normalize the
17210
+ * pixel-space `bbox` onto a displayed image. Omitted in slim projection. */
17211
+ frameWidth: number().optional(),
17212
+ frameHeight: number().optional(),
17213
+ /** MediaStore key for the crop attached to this event (if any). */
17214
+ mediaKey: string().optional(),
17215
+ /** Design B: MediaStore key of the track's native-resolution key frame (the
17216
+ * best-detection full frame). Resolve via the event-media data-plane
17217
+ * (`/addon/<addonId>/event-media/<keyFrameMediaKey>`) for a detail view that
17218
+ * draws `bbox` over the native frame. Absent on legacy rows / non-decoded
17219
+ * sources — consumers fall back to `mediaKey` (the tight crop). */
17220
+ keyFrameMediaKey: string().optional(),
17221
+ /** Populated by B5 (recording playback URL for this event). */
17222
+ mediaUrl: string().optional(),
17223
+ /** The parent track's key-event importance [0,1], propagated to every object
17224
+ * event of the track (so an event row can be sorted by importance without a
17225
+ * track join). Absent on legacy rows / before the track was scored. */
17226
+ importance: number().optional()
16955
17227
  });
16956
- var OverlayDetectionSchema = looseObject({
16957
- id: string(),
16958
- kind: _enum(["first-level", "detail"]),
16959
- macroClass: string(),
16960
- score: number(),
16961
- bbox: object({
16962
- x: number(),
16963
- y: number(),
16964
- width: number(),
16965
- height: number()
16966
- }),
16967
- labels: array(looseObject({
16968
- label: string(),
17228
+ var AudioEventSchema = object({
17229
+ ...BaseEventFields,
17230
+ kind: literal("audio"),
17231
+ rms: number(),
17232
+ dbfs: number(),
17233
+ classification: object({
17234
+ className: string(),
17235
+ originalClass: string().optional(),
16969
17236
  score: number()
16970
- })).readonly(),
16971
- parentId: string().optional()
16972
- });
16973
- var ScoredObjectEventSchema = ObjectEventSchema.extend({ score: number() });
16974
- var SearchObjectEventsInput = object({
16975
- text: string(),
16976
- deviceId: number().optional(),
16977
- since: number().optional(),
16978
- until: number().optional(),
16979
- classFilter: string().optional(),
16980
- limit: number().default(50),
16981
- minScore: number().min(0).max(1).default(.2)
16982
- });
16983
- var TrackCascadeCountsSchema = object({
16984
- /** Persisted track roots deleted (authoritative). */
16985
- tracks: number().int(),
16986
- /** Object events removed with their tracks (best-effort; see note above). */
16987
- events: number().int(),
16988
- /** Track/face/plate-owned media removed (best-effort). Never identity media. */
16989
- media: number().int(),
16990
- /** Unassigned (non-enrolled) face reads removed (best-effort). */
16991
- faces: number().int(),
16992
- /** Unassigned plate reads removed (best-effort; plate leg deferred to plate-intelligence). */
16993
- plates: number().int(),
16994
- /** Per-track CLIP search vectors removed (best-effort). */
16995
- embeddings: number().int(),
16996
- /** Group membership + group rows removed with their last member (best-effort). */
16997
- groups: number().int()
16998
- });
16999
- /** Disk-wins reconcile: media rows whose blobs are gone, then empty tracks. */
17000
- var DiskReconcileCountsSchema = object({
17001
- mediaDropped: number().int(),
17002
- tracks: number().int(),
17003
- events: number().int()
17004
- });
17005
- /** Event-store footprint for one camera. */
17006
- var EventStoreDeviceFootprintSchema = object({
17007
- deviceId: number(),
17008
- /** Persisted event rows (motion + object + audio) for the camera. */
17009
- rows: number().int(),
17010
- /** Event-owned media bytes on disk for the camera. */
17011
- bytes: number().int()
17012
- });
17013
- /** Aggregate event-store footprint: global totals + per-camera breakdown. */
17014
- var EventStoreFootprintSchema = object({
17015
- totalRows: number().int(),
17016
- totalBytes: number().int(),
17017
- devices: array(EventStoreDeviceFootprintSchema).readonly()
17018
- });
17019
- /** Per-kind counts returned by the event-prune / device-delete mutations. */
17020
- var EventPruneCountsSchema = object({
17021
- motion: number().int(),
17022
- object: number().int(),
17023
- audio: number().int()
17237
+ }).optional(),
17238
+ /** Populated by B5 (recording playback URL for this event). */
17239
+ mediaUrl: string().optional()
17024
17240
  });
17025
- /**
17026
- * Re-embed stored tracks from their key frames.
17027
- *
17028
- * The reason this is an operator-callable method and not a migration script:
17029
- * every knob that decides what a vector MEANS — encoder model, crop margin,
17030
- * squaring — is only changeable if the existing vectors can be regenerated.
17031
- * Mixing feature spaces in one index makes cosine scores incomparable, and the
17032
- * symptom is a quality regression with no visible cause.
17033
- */
17034
- var RebuildObjectEmbeddingsInput = object({
17035
- /** Restrict to one camera. Omit for the whole fleet. */
17036
- deviceId: number().optional(),
17037
- since: number().optional(),
17038
- until: number().optional(),
17039
- /** Stop after this many tracks; the result reports whether more remain. */
17040
- maxTracks: number().int().positive().optional(),
17041
- /**
17042
- * Run every embedding on THIS node instead of round-robining the fleet.
17043
- *
17044
- * Named `executeOnNodeId` and not `nodeId` on purpose: an inline `nodeId`
17045
- * field in cap args is read by `parent-unowned-call.ts` as a ROUTING PIN, so
17046
- * calling it that would pin the rebuild REQUEST itself to that node — the
17047
- * rebuild orchestration lives on the hub, and only the per-track step runs
17048
- * remotely. This field is data; the per-track pin is applied inside.
17049
- *
17050
- * Absent round-robin over every online node whose runner can serve the
17051
- * pinned model.
17052
- */
17053
- executeOnNodeId: string().optional(),
17054
- /**
17055
- * Milliseconds to wait between tracks; omit for the built-in default, `0` to
17056
- * run flat out.
17057
- *
17058
- * A rebuild is bulk maintenance on hub-main's single thread. Measured
17059
- * 2026-08-06, an unpaced pass held that thread busy 82.2 s out of 120 and
17060
- * pushed `nodes.topology` from 0.25 s to 26 s for 43 minutes. The value in
17061
- * force is logged at start and finish so a deliberately slow pass reads
17062
- * differently from a stalled one.
17063
- */
17064
- pacingMs: number().int().nonnegative().optional()
17065
- });
17066
- /**
17067
- * Result of emptying the CLIP index.
17068
- *
17069
- * The clean slate before a policy change: a new crop margin or encoder model
17070
- * leaves two feature spaces in one index whose cosine scores are not
17071
- * comparable, so wiping and rebuilding is the only way to be sure every vector
17072
- * means the same thing.
17073
- */
17074
- var WipeObjectEmbeddingsResultSchema = object({ deleted: number() });
17075
- /**
17076
- * Acknowledgement that a rebuild STARTED.
17077
- *
17078
- * The pass costs ~1s per track — 45 minutes for a 2,600-track fleet — so it
17079
- * runs detached and this returns immediately. Waiting for it made the client
17080
- * time out while the work carried on server-side, which is the worst of both:
17081
- * no result and no way to know it was still going. Poll
17082
- * `getObjectEmbeddingRebuildStatus` for progress.
17083
- */
17084
- var RebuildObjectEmbeddingsResultSchema = object({
17085
- started: boolean(),
17086
- /** True when a pass was already running; the new request is ignored. */
17087
- alreadyRunning: boolean()
17088
- });
17089
- var RebuildStatusSchema = object({
17090
- running: boolean(),
17091
- scanned: number(),
17092
- rebuilt: number(),
17093
- /** Tracks whose key frame is gone — nothing to re-embed from. */
17094
- missingKeyFrame: number(),
17095
- /** Tracks with no usable detection box. */
17096
- missingBbox: number(),
17097
- /**
17098
- * Tracks an executing node REFUSED rather than broke on — an unreadable key
17099
- * frame, a step that threw. Separate from `failed` because the remedy is
17100
- * different, and because a whole camera silently contributing zero vectors
17101
- * is the shape of failure a rebuild must never hide.
17102
- */
17103
- notRunnable: number(),
17104
- /**
17105
- * The pass stopped because NO node could serve the pinned model.
17106
- *
17107
- * Distinct from `notRunnable` on purpose: that one says "this track was
17108
- * refused", this one says "the cluster cannot do this work at all" — every
17109
- * candidate node either lacks the `clip-embedding` step, lacks a build of the
17110
- * pinned model for its engine format, or dropped out. The remedy is a model /
17111
- * engine change, not a per-camera one. Non-zero here always comes with
17112
- * `complete: false`.
17113
- */
17114
- noCapableNode: number(),
17115
- failed: number(),
17116
- /** Set once a pass ends: true only when EVERYTHING was covered. */
17117
- complete: boolean().nullable(),
17118
- startedAtMs: number().nullable(),
17119
- finishedAtMs: number().nullable(),
17120
- /** Present when the pass ended by throwing. */
17121
- error: string().nullable()
17122
- });
17123
- DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).readonly()), method(object({
17124
- deviceId: number(),
17125
- trackId: string()
17126
- }), TrackSchema.nullable()), method(object({
17127
- deviceId: number(),
17128
- since: number().optional(),
17129
- until: number().optional(),
17130
- limit: number().optional(),
17131
- /** Spatial filter — only tracks whose trajectory intersects the zone
17132
- * (normalized 0..1 rect or polygon). SQL-prefiltered on the persisted
17133
- * envelope columns, then precisely tested per position. Tracks with
17134
- * an unknown envelope (no frame dims at persist time) always match. */
17135
- zone: TrackZoneFilterSchema.optional(),
17136
- /** See {@link TrackProjectionSchema}. Default `full` (backward
17137
- * compatible — omitting the field keeps today's exact behaviour). */
17138
- projection: TrackProjectionSchema.optional(),
17139
- /** Include stationary-promoted rows (parked objects handed to the
17140
- * stationary registry). Default false: the timeline lists passages,
17141
- * not parking records (operator decision, 2026-08-15). */
17142
- includeStationary: boolean().optional()
17143
- }), array(TrackSchema).readonly()), method(RecentTracksQueryInput, RecentTracksPageSchema), method(ListGroupsQueryInput, ListGroupsPageSchema), method(object({
17144
- deviceId: number(),
17145
- groupId: string().min(1)
17146
- }), AnalyticsGroupDetailSchema.nullable()), method(object({ deviceId: number() }), _void(), {
17147
- kind: "mutation",
17148
- auth: "admin"
17149
- }), 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({
17150
- deviceId: number(),
17151
- since: number().optional(),
17152
- until: number().optional(),
17153
- kinds: array(string()).optional(),
17154
- limit: number().int().min(1).max(MAX_EVENT_QUERY_LIMIT).default(DEFAULT_EVENT_QUERY_LIMIT)
17155
- }), array(SensorEventSchema).readonly()), method(KeyEventQueryInput, array(KeyEventSchema).readonly()), method(object({
17156
- deviceId: number(),
17157
- since: number(),
17158
- until: number(),
17159
- bucketMs: number().int().positive()
17160
- }), array(object({
17161
- bucketStart: number(),
17162
- motion: number().int(),
17163
- object: number().int(),
17164
- audio: number().int()
17165
- })).readonly()), method(object({
17166
- deviceId: number(),
17167
- cutoffMs: number()
17168
- }), object({
17169
- motion: number().int(),
17170
- object: number().int(),
17171
- audio: number().int()
17172
- }), {
17173
- kind: "mutation",
17174
- auth: "admin"
17175
- }), method(object({
17176
- deviceId: number(),
17177
- cutoffMs: number()
17178
- }), TrackCascadeCountsSchema, {
17179
- kind: "mutation",
17180
- auth: "admin"
17181
- }), method(object({ deviceId: number() }), TrackCascadeCountsSchema, {
17182
- kind: "mutation",
17183
- auth: "admin"
17184
- }), method(object({ deviceId: number() }), DiskReconcileCountsSchema, {
17185
- kind: "mutation",
17186
- auth: "admin"
17187
- }), method(object({
17188
- deviceId: number(),
17189
- trackIds: array(string()).min(1)
17190
- }), object({
17191
- deleted: number().int(),
17192
- failed: array(string()).readonly()
17193
- }), {
17194
- kind: "mutation",
17195
- auth: "admin"
17196
- }), method(object({
17197
- /** Log/audit scope only — the trackId is globally unique on its own. */
17198
- deviceId: number(),
17199
- trackId: string(),
17200
- flags: TrackFlagsPatchSchema
17201
- }), TrackFlagsSchema, { kind: "mutation" }), method(object({}), EventStoreFootprintSchema, {
17202
- kind: "query",
17203
- auth: "admin"
17204
- }), method(object({
17205
- olderThanMs: number(),
17206
- reason: OpsLogReasonSchema.optional()
17207
- }), EventPruneCountsSchema, {
17208
- kind: "mutation",
17209
- auth: "admin"
17210
- }), method(object({ deviceId: number() }), EventPruneCountsSchema, {
17211
- kind: "mutation",
17212
- auth: "admin"
17213
- }), method(StorageMigrationLeaseInputSchema, object({ paused: literal(true) }), {
17214
- kind: "mutation",
17215
- auth: "admin"
17216
- }), method(StorageMigrationLeaseInputSchema, object({ resumed: literal(true) }), {
17217
- kind: "mutation",
17218
- auth: "admin"
17219
- }), method(StorageMigrationLeaseInputSchema, object({ refreshed: literal(true) }), {
17220
- kind: "mutation",
17221
- auth: "admin"
17222
- }), method(StorageMigrationMediaMoveInputSchema, object({ jobId: string() }), {
17223
- kind: "mutation",
17224
- auth: "admin"
17225
- }), method(object({ jobId: string() }), RelocateJobSchema.nullable(), { auth: "admin" }), method(object({ jobId: string() }), object({ cancelled: boolean() }), {
17226
- kind: "mutation",
17227
- auth: "admin"
17228
- }), method(RelocateMediaInputSchema, object({ jobId: string() }), {
17229
- kind: "mutation",
17230
- auth: "admin"
17231
- }), method(object({}), array(RelocateJobSchema).readonly(), {
17232
- kind: "query",
17233
- auth: "admin"
17234
- }), method(object({ jobId: string() }), object({ cancelled: boolean() }), {
17235
- kind: "mutation",
17236
- auth: "admin"
17237
- }), method(OpsLogQueryInputSchema, array(OpsLogEntrySchema).readonly(), {
17238
- kind: "query",
17239
- auth: "admin"
17240
- }), method(object({ deviceIds: array(number()).optional() }), TrainingExportSummarySchema, {
17241
- kind: "query",
17242
- auth: "admin"
17243
- }), method(object({ deviceIds: array(number()).optional() }), object({ url: string() }), {
17244
- kind: "query",
17245
- auth: "admin"
17246
- }), method(object({
17247
- /** Empty ⇒ every camera that has staging tracks. A LIST, not a single
17248
- * `deviceId`, deliberately: `deviceId` would make this device-bound and
17249
- * route it at one camera's owner, and "every camera" would stop being
17250
- * expressible at all. */
17251
- deviceIds: array(number()).optional(),
17252
- limit: number().int().min(1).max(500).optional()
17253
- }), array(RetrainTrackSchema).readonly(), {
17254
- kind: "query",
17255
- auth: "admin"
17256
- }), method(object({ trackId: string() }), RetrainFrameListSchema, {
17257
- kind: "query",
17258
- auth: "admin"
17259
- }), method(object({
17260
- deviceId: number(),
17261
- trackId: string(),
17262
- mediaKeys: array(string()).min(1)
17263
- }), RetrainFrameSelectionSchema, {
17264
- kind: "mutation",
17265
- auth: "admin"
17266
- }), method(object({
17267
- deviceId: number(),
17268
- trackId: string(),
17269
- frameId: string()
17270
- }), object({
17271
- removed: boolean(),
17272
- removedAnnotations: number().int()
17273
- }), {
17274
- kind: "mutation",
17275
- auth: "admin"
17276
- }), method(object({ frameId: string() }), object({
17277
- base64: string(),
17278
- width: number().int(),
17279
- height: number().int()
17280
- }), {
17281
- kind: "query",
17282
- auth: "admin"
17283
- }), method(object({
17284
- deviceId: number(),
17285
- trackId: string(),
17286
- frameId: string(),
17287
- subject: RetrainAssistSubjectSchema,
17288
- /** Which node runs it. Absent ⇒ wherever an unowned call lands. */
17289
- nodeId: string().optional()
17290
- }), RetrainAssistResultSchema, {
17291
- kind: "mutation",
17292
- auth: "admin"
17293
- }), method(object({ trackId: string() }), array(RetrainAnnotationSchema).readonly(), {
17294
- kind: "query",
17295
- auth: "admin"
17296
- }), method(object({
17297
- deviceId: number(),
17241
+ var MediaFileKindEnum = _enum([
17242
+ "crop",
17243
+ "thumbnail",
17244
+ "snapshot",
17245
+ "firstFrame",
17246
+ "lastFrame",
17247
+ "fullFrame",
17248
+ "fullFrameBoxed",
17249
+ "faceCrop",
17250
+ "plateCrop",
17251
+ "keyFrame",
17252
+ "keyFrameSmall",
17253
+ "thumbnailSmall"
17254
+ ]);
17255
+ var MediaFileSchema = object({
17256
+ key: string(),
17257
+ kind: MediaFileKindEnum,
17258
+ base64: string(),
17259
+ sizeBytes: number(),
17260
+ timestamp: number()
17261
+ });
17262
+ /**
17263
+ * One media row WITHOUT its bytes.
17264
+ *
17265
+ * A track's media is 5-8 MB of base64 (measured: 7.67 MB across 23 files for a
17266
+ * 140 s track), and a client that renders tiles from the media data plane needs
17267
+ * to know only WHAT EXISTS — the bytes then arrive per tile, lazily, over HTTP
17268
+ * with an immutable cache, instead of all at once inside a tRPC response that
17269
+ * blocks the whole view.
17270
+ *
17271
+ * `sizeBytes` is carried because it is what lets a client decide between the
17272
+ * stored blob and a `?variant=thumb` rendering without fetching either.
17273
+ */
17274
+ var MediaFileInfoSchema = MediaFileSchema.omit({ base64: true });
17275
+ /**
17276
+ * The MACRO tier of an annotation a CLOSED set.
17277
+ *
17278
+ * This is what the exported detector predicts, so a typo here is a new class
17279
+ * with one example in it. `label` and `subLabel` are open strings by contrast:
17280
+ * the whole point of the page is teaching the model things it does not know
17281
+ * yet, and constraining that vocabulary would make it useless.
17282
+ *
17283
+ * A macro class is NEVER a label. The provider refuses a write whose `label` or
17284
+ * `subLabel` is one of these values, in any casing, because once `person`
17285
+ * exists in both tiers "every person box" stops being answerable without
17286
+ * knowing every string anyone ever typed and the damage is retroactive.
17287
+ */
17288
+ var RetrainMacroClassSchema = _enum([
17289
+ "person",
17290
+ "vehicle",
17291
+ "animal",
17292
+ "package",
17293
+ "face",
17294
+ "plate"
17295
+ ]);
17296
+ /** A subject to learn, or a phantom to unlearn (taught by OMISSION). */
17297
+ var RetrainAnnotationKindSchema = _enum(["subject", "model_error"]);
17298
+ /** Did a human draw this box, or did the assist propose it? */
17299
+ var RetrainAnnotationSourceSchema = _enum(["operator", "assist"]);
17300
+ /** Normalised `[0,1]` rectangle against the FULL frame — the canonical form. */
17301
+ var RetrainBboxSchema = object({
17302
+ x: number(),
17303
+ y: number(),
17304
+ w: number(),
17305
+ h: number()
17306
+ });
17307
+ /**
17308
+ * One annotated subject.
17309
+ *
17310
+ * `bbox` is normalised against the full frame, ALWAYS. The per-model shapes
17311
+ * (letterboxed root / zone-cropped package / subject-cropped classifier) are
17312
+ * derived from it at export and never stored — storing them is how one feature
17313
+ * space ends up holding two crops of the same subject (D52).
17314
+ */
17315
+ var RetrainAnnotationSchema = object({
17316
+ id: string(),
17298
17317
  trackId: string(),
17299
- frameId: string(),
17300
- annotations: array(RetrainAnnotationDraftSchema)
17301
- }), array(RetrainAnnotationSchema).readonly(), {
17302
- kind: "mutation",
17303
- auth: "admin"
17304
- }), method(object({
17305
- deviceId: number(),
17306
- trackId: string()
17307
- }), RetrainTransitionResultSchema, {
17308
- kind: "mutation",
17309
- auth: "admin"
17310
- }), method(object({
17311
17318
  deviceId: number(),
17312
- trackId: string()
17313
- }), RetrainTransitionResultSchema, {
17314
- kind: "mutation",
17315
- auth: "admin"
17316
- }), method(object({ deviceIds: array(number()).optional() }), object({ url: string() }), {
17317
- kind: "query",
17318
- auth: "admin"
17319
- }), method(object({
17320
- eventId: string(),
17321
- kind: MediaFileKindEnum.optional(),
17322
- deviceId: number()
17323
- }), array(MediaFileSchema).readonly()), method(object({
17324
- trackId: string(),
17325
- kinds: array(MediaFileKindEnum).optional(),
17326
- deviceId: number()
17327
- }), array(MediaFileSchema).readonly()), method(object({
17319
+ /** The COPY in retrain storage — never the source track's media key. */
17320
+ mediaKey: string(),
17321
+ bbox: RetrainBboxSchema,
17322
+ macroClass: RetrainMacroClassSchema,
17323
+ label: string().optional(),
17324
+ subLabel: string().optional(),
17325
+ kind: RetrainAnnotationKindSchema,
17326
+ source: RetrainAnnotationSourceSchema,
17327
+ /** Which model proposed this box — or, on a `model_error`, drew the phantom. */
17328
+ assistModelId: string().optional(),
17329
+ assistScore: number().optional(),
17330
+ exportedInBatch: string().optional(),
17331
+ createdAt: number()
17332
+ });
17333
+ /** The write form — the server owns `id`, `createdAt` and the frame binding. */
17334
+ var RetrainAnnotationDraftSchema = RetrainAnnotationSchema.omit({
17335
+ id: true,
17336
+ trackId: true,
17337
+ deviceId: true,
17338
+ mediaKey: true,
17339
+ createdAt: true,
17340
+ exportedInBatch: true
17341
+ });
17342
+ /** A track sitting in `staging`, with everything the worklist needs to rank it. */
17343
+ var RetrainTrackSchema = object({
17328
17344
  trackId: string(),
17329
- deviceId: number()
17330
- }), array(MediaFileInfoSchema).readonly()), method(SearchObjectEventsInput, array(ScoredObjectEventSchema).readonly()), method(object({}), WipeObjectEmbeddingsResultSchema, {
17331
- kind: "mutation",
17332
- auth: "admin"
17333
- }), method(RebuildObjectEmbeddingsInput, RebuildObjectEmbeddingsResultSchema, {
17334
- kind: "mutation",
17335
- auth: "admin"
17336
- }), method(object({}), RebuildStatusSchema), object({
17337
17345
  deviceId: number(),
17346
+ className: string(),
17347
+ label: string().optional(),
17348
+ firstSeen: number(),
17349
+ lastSeen: number(),
17350
+ /** How many frames the dataset already holds from this track. */
17351
+ frameCount: number().int(),
17352
+ /** How many subjects have been annotated on those frames. `0` with
17353
+ * `frameCount: 0` is exactly "staging, still to work". */
17354
+ annotationCount: number().int()
17355
+ });
17356
+ /** A frame the picker may offer — an index row, no blob was read to produce it. */
17357
+ var RetrainFrameCandidateSchema = object({
17358
+ mediaKey: string(),
17359
+ kind: MediaFileKindEnum,
17338
17360
  timestamp: number(),
17339
- frameWidth: number(),
17340
- frameHeight: number(),
17341
- detections: array(OverlayDetectionSchema).readonly()
17342
- }), object({
17343
- deviceId: number(),
17344
- trackId: string(),
17345
- className: string()
17346
- }), object({
17361
+ sizeBytes: number().int(),
17362
+ /** A copy of this original already exists — selecting it is free and cannot
17363
+ * fail, whatever became of the original. */
17364
+ copied: boolean()
17365
+ });
17366
+ /** A frame the dataset OWNS: bytes copied at selection time. */
17367
+ var RetrainFrameSchema = object({
17368
+ frameId: string(),
17347
17369
  deviceId: number(),
17348
17370
  trackId: string(),
17349
- className: string(),
17350
- durationMs: number()
17351
- }), object({
17352
- deviceId: number(),
17353
- kind: EventKindSchema,
17354
- eventId: string(),
17355
- timestamp: number()
17371
+ /** Provenance only. It may already point at nothing — that is expected. */
17372
+ sourceMediaKey: string(),
17373
+ sourceKind: MediaFileKindEnum,
17374
+ sizeBytes: number().int(),
17375
+ width: number().int(),
17376
+ height: number().int(),
17377
+ copiedAt: number()
17378
+ });
17379
+ /** Why a copy-on-select could not be honoured — named, never a silent skip. */
17380
+ var RetrainCopyRefusalSchema = _enum([
17381
+ "source-missing",
17382
+ "unreadable-image",
17383
+ "write-failed"
17384
+ ]);
17385
+ var RetrainFrameSelectionSchema = object({
17386
+ copied: array(RetrainFrameSchema).readonly(),
17387
+ refused: array(object({
17388
+ sourceMediaKey: string(),
17389
+ reason: RetrainCopyRefusalSchema
17390
+ })).readonly()
17391
+ });
17392
+ var RetrainFrameListSchema = object({
17393
+ candidates: array(RetrainFrameCandidateSchema).readonly(),
17394
+ copies: array(RetrainFrameSchema).readonly(),
17395
+ /** What the page pre-selects — the native key frame when one survives. */
17396
+ autoPickMediaKey: string().optional()
17356
17397
  });
17398
+ /** What the operator asked the assist to look for. */
17399
+ var RetrainAssistSubjectSchema = discriminatedUnion("kind", [object({
17400
+ kind: literal("package"),
17401
+ zone: RetrainBboxSchema.optional()
17402
+ }), object({
17403
+ kind: literal("objects"),
17404
+ modelId: string(),
17405
+ minScore: number().optional()
17406
+ })]);
17357
17407
  /**
17358
- * Reference to the frame's retained NATIVE surface + the parent crop's placement
17359
- * within the frame, so the executor can re-cut a leaf child ROI at native
17360
- * resolution on the detail plane. See the `runPipeline` `nativeCropRef` field.
17408
+ * The assist's answer a discriminated union, because "the model saw nothing"
17409
+ * and "this node cannot run that model" lead to different next moves and a
17410
+ * nullable result cannot tell them apart.
17361
17411
  */
17362
- var NativeCropRefSchema = object({
17363
- /** Handle keying the retained native surface (node-pinned to its owner). */
17364
- handle: FrameHandleSchema,
17365
- /** The parent crop's padded/clamped rectangle in FRAME-space pixels. */
17366
- cropFrameSpace: object({
17367
- x: number(),
17368
- y: number(),
17369
- w: number(),
17370
- h: number()
17371
- })
17372
- });
17373
- object({
17374
- crop: object({
17375
- left: number(),
17376
- top: number(),
17377
- width: number().positive(),
17378
- height: number().positive()
17379
- }).optional(),
17380
- content: object({
17381
- width: number().int().positive(),
17382
- height: number().int().positive()
17383
- }),
17384
- fit: _enum(["stretch", "contain"]),
17385
- format: _enum([
17386
- "rgb",
17387
- "gray",
17388
- "jpeg"
17389
- ])
17412
+ var RetrainAssistResultSchema = discriminatedUnion("kind", [object({
17413
+ kind: literal("proposed"),
17414
+ modelId: string(),
17415
+ stepId: string(),
17416
+ minScore: number(),
17417
+ /** Drafts, ready to edit. `source: 'assist'` until the operator touches one. */
17418
+ proposals: array(RetrainAnnotationDraftSchema).readonly(),
17419
+ /** Returned by the runner but removed by the threshold. */
17420
+ belowThreshold: number().int()
17421
+ }), object({
17422
+ kind: literal("refused"),
17423
+ /** `no-zone` is ours; the rest are the runner's own refusal vocabulary. */
17424
+ reason: string(),
17425
+ detail: string().optional()
17426
+ })]);
17427
+ /** The outcome of a lifecycle move owned by the retrain page. */
17428
+ var RetrainTransitionResultSchema = object({
17429
+ trackId: string(),
17430
+ /** Where the track ended up, whatever happened. */
17431
+ retrainStatus: RetrainStatusSchema,
17432
+ /** `false` ⇒ the move was refused or was a no-op; `reason` says which. */
17433
+ changed: boolean(),
17434
+ reason: _enum([
17435
+ "unknown-track",
17436
+ "no-frames-copied",
17437
+ "not-staging",
17438
+ "not-trained",
17439
+ "unchanged"
17440
+ ]).optional()
17390
17441
  });
17391
- /**
17392
- * Process-local frame identity. It is serializable so it can ride an in-process
17393
- * capability call, but `registryId` deliberately prevents resolution in any
17394
- * other process or execution group.
17395
- */
17396
- var FrameRefSchema = object({
17397
- registryId: string().min(1),
17398
- id: string().min(1),
17399
- width: number().int().positive(),
17400
- height: number().int().positive(),
17401
- format: _enum(["rgb", "gray"]),
17402
- timestamp: number(),
17403
- capturedAt: number().optional()
17442
+ var DEFAULT_EVENT_QUERY_LIMIT = 1e3;
17443
+ var MAX_EVENT_QUERY_LIMIT = 5e3;
17444
+ var DeviceEventQueryInput = object({
17445
+ deviceId: number(),
17446
+ since: number().optional(),
17447
+ until: number().optional(),
17448
+ limit: number().int().min(1).max(MAX_EVENT_QUERY_LIMIT).default(DEFAULT_EVENT_QUERY_LIMIT),
17449
+ /** `slim` drops heavy JSON fields (regions/bbox/zones) and carries an
17450
+ * optional `mediaUrl` (populated by B5). `full` (default) keeps today's
17451
+ * exact behaviour. Callers may omit this field — the store defaults to
17452
+ * `full` when not provided. */
17453
+ projection: _enum(["full", "slim"]).optional()
17404
17454
  });
17405
- var ModelFormatSchema$1 = _enum([
17406
- "onnx",
17407
- "coreml",
17408
- "openvino",
17409
- "tflite",
17410
- "pt",
17411
- "gguf"
17412
- ]);
17413
- var PipelineSlotSchema = _enum([
17414
- "detector",
17415
- "cropper",
17416
- "classifier",
17417
- "refiner",
17418
- "audio-classifier"
17419
- ]);
17420
- var PipelineEngineChoiceSchema = object({
17421
- runtime: _enum(["node", "python"]),
17422
- backend: string(),
17423
- format: ModelFormatSchema$1,
17424
- device: string().optional()
17455
+ var ObjectEventQueryInput = DeviceEventQueryInput.extend({ classFilter: string().optional() });
17456
+ var RecentTracksQueryInput = object({
17457
+ /** Devices to merge. An empty array yields `{ tracks: [], nextCursor: null }`. */
17458
+ deviceIds: array(number()),
17459
+ /** Window lower bound on `lastSeen` (inclusive). */
17460
+ since: number().optional(),
17461
+ /** Window upper bound on `lastSeen` (inclusive). */
17462
+ until: number().optional(),
17463
+ /** Page size. Default 200, max 1000. */
17464
+ limit: number().int().min(1).max(1e3).default(200),
17465
+ /** Opaque continuation cursor from a previous page's `nextCursor`.
17466
+ * Encodes the (lastSeen, trackId) sort position — treat as opaque. */
17467
+ cursor: string().optional(),
17468
+ /** See {@link TrackProjectionSchema}. Default `full`. */
17469
+ projection: TrackProjectionSchema.optional(),
17470
+ /** Include stationary-promoted rows (parked objects). Default false: the
17471
+ * feed lists passages; parking records live on the stationary registry. */
17472
+ includeStationary: boolean().optional()
17425
17473
  });
17426
- var AvailableEngineSchema = object({
17427
- engine: PipelineEngineChoiceSchema,
17428
- devices: array(object({
17429
- id: string(),
17430
- label: string(),
17431
- description: string().optional()
17432
- })).readonly(),
17433
- defaultDevice: string()
17474
+ var RecentTracksPageSchema = object({
17475
+ /** Merged page, ordered by (`lastSeen` DESC, `trackId` DESC). */
17476
+ tracks: array(TrackSchema).readonly(),
17477
+ /** Cursor for the next page, or null when this page is the last. */
17478
+ nextCursor: string().nullable()
17434
17479
  });
17435
- var PipelineDefaultStepSchema = lazy(() => object({
17436
- addonId: string(),
17437
- addonName: string(),
17438
- slot: PipelineSlotSchema,
17439
- inputClasses: array(string()).readonly(),
17440
- outputClasses: array(string()).readonly(),
17441
- enabled: boolean(),
17442
- modelId: string(),
17443
- children: array(PipelineDefaultStepSchema).readonly(),
17444
- group: string().optional(),
17445
- settings: record(string(), unknown()).optional()
17446
- }));
17447
- var PipelineTemplateStepSchema = lazy(() => object({
17448
- addonId: string(),
17449
- enabled: boolean(),
17450
- modelId: string(),
17451
- children: array(PipelineTemplateStepSchema).readonly(),
17452
- settings: record(string(), unknown()).optional()
17453
- }));
17454
- var PipelineTemplateSchema$1 = object({
17480
+ var LIST_GROUPS_DEFAULT_LIMIT = 40;
17481
+ var LIST_GROUPS_MAX_LIMIT = 100;
17482
+ var AnalyticsGroupRecordSchema = object({
17455
17483
  id: string(),
17456
- name: string(),
17457
- createdAt: string(),
17458
- updatedAt: string(),
17459
- engine: PipelineEngineChoiceSchema,
17460
- steps: array(PipelineTemplateStepSchema).readonly()
17484
+ deviceId: number().int(),
17485
+ openedAt: number().int(),
17486
+ closedAt: number().int(),
17487
+ timestamp: number().int(),
17488
+ memberCount: number().int(),
17489
+ memberTrackIds: array(string()).readonly(),
17490
+ className: string(),
17491
+ classes: array(string()).readonly(),
17492
+ /** Relative event-media path, or null when the group has no picture yet. */
17493
+ mediaUrl: string().nullable(),
17494
+ singleton: boolean()
17461
17495
  });
17462
- var PipelineModelOptionSchema = object({
17463
- id: string(),
17464
- name: string(),
17465
- formats: record(string(), object({
17466
- downloaded: boolean(),
17467
- sizeMB: number()
17468
- })),
17469
- group: ModelVariantGroupSchema.optional(),
17470
- legacy: boolean().optional(),
17471
- provider: ModelProviderIdSchema.optional()
17496
+ var AnalyticsGroupMemberSchema = object({
17497
+ trackId: string(),
17498
+ deviceId: number().int(),
17499
+ className: string(),
17500
+ firstSeen: number().int(),
17501
+ lastSeen: number().int(),
17502
+ mediaUrl: string().nullable()
17472
17503
  });
17473
- var ConfigFieldBridge = custom();
17474
- var PipelineAddonSchemaSchema = object({
17475
- id: string(),
17476
- name: string(),
17477
- slot: PipelineSlotSchema,
17478
- inputClasses: array(string()).readonly(),
17479
- outputClasses: array(string()).readonly(),
17480
- childSlots: array(PipelineSlotSchema).readonly(),
17481
- models: array(PipelineModelOptionSchema).readonly(),
17482
- defaultModelId: string(),
17483
- defaultModelIdByFormat: record(string(), string()).optional(),
17484
- enabledByDefault: boolean().optional(),
17485
- backfillIntoExistingOverrides: boolean().optional(),
17486
- defaultConfidence: number(),
17487
- group: string().optional(),
17488
- configSchema: array(ConfigFieldBridge).readonly().optional()
17504
+ var AnalyticsGroupDetailSchema = AnalyticsGroupRecordSchema.extend({ members: array(AnalyticsGroupMemberSchema).readonly() });
17505
+ var ListGroupsQueryInput = object({
17506
+ /** Devices to merge. An empty array yields `{ groups: [], nextCursor: null }`. */
17507
+ deviceIds: array(number()),
17508
+ /** Window lower bound on `closedAt` (inclusive). */
17509
+ since: number().optional(),
17510
+ /** Window upper bound on `openedAt` (inclusive). */
17511
+ until: number().optional(),
17512
+ limit: number().int().min(1).max(LIST_GROUPS_MAX_LIMIT).default(LIST_GROUPS_DEFAULT_LIMIT),
17513
+ /** Opaque continuation cursor from a previous page's `nextCursor`. */
17514
+ cursor: string().optional()
17489
17515
  });
17490
- var PipelineSlotSchemaSchema = object({
17491
- id: PipelineSlotSchema,
17492
- label: string(),
17493
- priority: number(),
17494
- parentSlot: PipelineSlotSchema.nullable(),
17495
- addons: array(PipelineAddonSchemaSchema).readonly()
17516
+ var ListGroupsPageSchema = object({
17517
+ groups: array(AnalyticsGroupRecordSchema).readonly(),
17518
+ nextCursor: string().nullable()
17496
17519
  });
17497
- var PipelineSchemaSchema = object({
17498
- availableEngines: array(AvailableEngineSchema).readonly(),
17499
- selectedEngine: PipelineEngineChoiceSchema,
17500
- slots: array(PipelineSlotSchemaSchema).readonly()
17520
+ var KeyEventQueryInput = object({
17521
+ deviceId: number(),
17522
+ /** Window lower bound (track firstSeen ≥ since). */
17523
+ since: number(),
17524
+ /** Window upper bound (track firstSeen ≤ until). */
17525
+ until: number(),
17526
+ limit: number().int().min(1).max(200).default(50),
17527
+ /** Drop tracks scoring below this importance. */
17528
+ minImportance: number().min(0).max(1).optional(),
17529
+ /** Restrict to a single class (e.g. 'person'). */
17530
+ classFilter: string().optional()
17501
17531
  });
17502
- var EngineProvisioningSchema = object({
17503
- runtimeId: _enum([
17504
- "onnx",
17505
- "openvino",
17506
- "coreml",
17507
- "edgetpu"
17508
- ]).nullable(),
17509
- device: string().nullable(),
17510
- state: _enum([
17511
- "idle",
17512
- "installing",
17513
- "verifying",
17514
- "ready",
17515
- "failed"
17516
- ]),
17517
- progress: number().optional(),
17518
- error: string().optional(),
17519
- nextRetryAt: number().optional(),
17520
- /**
17521
- * Gate A (config-correctness gate at engine change): human-readable
17522
- * config issues surfaced EAGERLY when the node's engine changes — model
17523
- * substitutions ("chose X, running Y") and zero-build steps ("no model
17524
- * has a <format> build"). Additive/optional: informational only, never
17525
- * enforced here — `assertEngineReady` (readiness) still gates inference.
17526
- * Absent/empty when the node-default tree resolves cleanly.
17527
- */
17528
- configIssues: array(string()).optional()
17532
+ var KeyEventSchema = object({
17533
+ /** The representative event id (the track's best ObjectEvent, else its trackId). */
17534
+ id: string(),
17535
+ trackId: string(),
17536
+ /** Track start time (firstSeen). */
17537
+ timestamp: number(),
17538
+ className: string(),
17539
+ ...TieredLabelFields,
17540
+ importance: number(),
17541
+ /** Highest-confidence ObjectEvent id for the track (empty when none). */
17542
+ bestEventId: string(),
17543
+ /** Track lifetime in ms (lastSeen - firstSeen). */
17544
+ windowMs: number().optional(),
17545
+ ...TrackFlagFields,
17546
+ ...TrackRetrainFields
17529
17547
  });
17530
- var PipelineStepInputSchema = lazy(() => object({
17531
- addonId: string(),
17532
- modelId: string().optional(),
17533
- enabled: boolean().default(true),
17534
- children: array(PipelineStepInputSchema).optional(),
17535
- settings: record(string(), unknown()).optional(),
17536
- jumpDeviceKey: string().optional()
17537
- }));
17538
- var ModelSubstitutionSchema = object({
17539
- addonId: string(),
17540
- chosen: string(),
17541
- running: string(),
17542
- format: string()
17548
+ object({
17549
+ trackId: string(),
17550
+ className: string(),
17551
+ confidence: number(),
17552
+ bbox: BoundingBoxSchema,
17553
+ zones: array(string()).readonly(),
17554
+ state: TrackStateSchema
17555
+ });
17556
+ var OverlayDetectionSchema = looseObject({
17557
+ id: string(),
17558
+ kind: _enum(["first-level", "detail"]),
17559
+ macroClass: string(),
17560
+ score: number(),
17561
+ bbox: object({
17562
+ x: number(),
17563
+ y: number(),
17564
+ width: number(),
17565
+ height: number()
17566
+ }),
17567
+ labels: array(looseObject({
17568
+ label: string(),
17569
+ score: number()
17570
+ })).readonly(),
17571
+ parentId: string().optional()
17543
17572
  });
17544
- var PipelineValidationIssueSchema = object({
17545
- addonId: string(),
17546
- kind: _enum(["unknown-addon", "no-format-build"]),
17547
- detail: string()
17573
+ var ScoredObjectEventSchema = ObjectEventSchema.extend({ score: number() });
17574
+ var SearchObjectEventsInput = object({
17575
+ text: string(),
17576
+ deviceId: number().optional(),
17577
+ since: number().optional(),
17578
+ until: number().optional(),
17579
+ classFilter: string().optional(),
17580
+ limit: number().default(50),
17581
+ minScore: number().min(0).max(1).default(.2)
17548
17582
  });
17549
- var PipelineValidationResultSchema = object({
17550
- ok: boolean(),
17551
- issues: array(PipelineValidationIssueSchema).readonly(),
17552
- substitutions: array(ModelSubstitutionSchema).readonly(),
17553
- /** The node's `currentEngine.format` this validation ran against. */
17554
- format: string()
17583
+ var TrackCascadeCountsSchema = object({
17584
+ /** Persisted track roots deleted (authoritative). */
17585
+ tracks: number().int(),
17586
+ /** Object events removed with their tracks (best-effort; see note above). */
17587
+ events: number().int(),
17588
+ /** Track/face/plate-owned media removed (best-effort). Never identity media. */
17589
+ media: number().int(),
17590
+ /** Unassigned (non-enrolled) face reads removed (best-effort). */
17591
+ faces: number().int(),
17592
+ /** Unassigned plate reads removed (best-effort; plate leg deferred to plate-intelligence). */
17593
+ plates: number().int(),
17594
+ /** Per-track CLIP search vectors removed (best-effort). */
17595
+ embeddings: number().int(),
17596
+ /** Group membership + group rows removed with their last member (best-effort). */
17597
+ groups: number().int()
17555
17598
  });
17556
- var ReferenceImageEntrySchema = object({
17557
- filename: string(),
17558
- stepIds: array(string()).readonly().optional()
17599
+ /** Disk-wins reconcile: media rows whose blobs are gone, then empty tracks. */
17600
+ var DiskReconcileCountsSchema = object({
17601
+ mediaDropped: number().int(),
17602
+ tracks: number().int(),
17603
+ events: number().int()
17559
17604
  });
17560
- var ReferenceImageBodySchema = object({
17561
- base64: string(),
17562
- filename: string()
17605
+ /** Event-store footprint for one camera. */
17606
+ var EventStoreDeviceFootprintSchema = object({
17607
+ deviceId: number(),
17608
+ /** Persisted event rows (motion + object + audio) for the camera. */
17609
+ rows: number().int(),
17610
+ /** Event-owned media bytes on disk for the camera. */
17611
+ bytes: number().int()
17563
17612
  });
17564
- var ReferenceAudioEntrySchema = object({
17565
- filename: string(),
17566
- sizeKb: number()
17613
+ /** Aggregate event-store footprint: global totals + per-camera breakdown. */
17614
+ var EventStoreFootprintSchema = object({
17615
+ totalRows: number().int(),
17616
+ totalBytes: number().int(),
17617
+ devices: array(EventStoreDeviceFootprintSchema).readonly()
17567
17618
  });
17568
- var ReferenceAudioBodySchema = object({ base64: string() });
17569
- var AudioBackendSchema = object({
17570
- id: string(),
17571
- name: string(),
17572
- description: string(),
17573
- available: boolean(),
17619
+ /** Per-kind counts returned by the event-prune / device-delete mutations. */
17620
+ var EventPruneCountsSchema = object({
17621
+ motion: number().int(),
17622
+ object: number().int(),
17623
+ audio: number().int()
17624
+ });
17625
+ /**
17626
+ * Re-embed stored tracks from their key frames.
17627
+ *
17628
+ * The reason this is an operator-callable method and not a migration script:
17629
+ * every knob that decides what a vector MEANS — encoder model, crop margin,
17630
+ * squaring — is only changeable if the existing vectors can be regenerated.
17631
+ * Mixing feature spaces in one index makes cosine scores incomparable, and the
17632
+ * symptom is a quality regression with no visible cause.
17633
+ */
17634
+ var RebuildObjectEmbeddingsInput = object({
17635
+ /** Restrict to one camera. Omit for the whole fleet. */
17636
+ deviceId: number().optional(),
17637
+ since: number().optional(),
17638
+ until: number().optional(),
17639
+ /** Stop after this many tracks; the result reports whether more remain. */
17640
+ maxTracks: number().int().positive().optional(),
17574
17641
  /**
17575
- * Raw classifier labels this backend can emit (e.g. YAMNet's
17576
- * 521-class set or Apple SoundAnalysis's 303-class set). Used by
17577
- * the benchmark UI to populate the `enabledMicroClasses` filter
17578
- * specific to the selected backend without a separate fetch.
17642
+ * Run every embedding on THIS node instead of round-robining the fleet.
17643
+ *
17644
+ * Named `executeOnNodeId` and not `nodeId` on purpose: an inline `nodeId`
17645
+ * field in cap args is read by `parent-unowned-call.ts` as a ROUTING PIN, so
17646
+ * calling it that would pin the rebuild REQUEST itself to that node — the
17647
+ * rebuild orchestration lives on the hub, and only the per-track step runs
17648
+ * remotely. This field is data; the per-track pin is applied inside.
17649
+ *
17650
+ * Absent ⇒ round-robin over every online node whose runner can serve the
17651
+ * pinned model.
17579
17652
  */
17580
- rawLabels: array(string()).readonly().optional()
17581
- });
17582
- var AudioCapabilitiesSchema = object({
17583
- activeBackend: string(),
17584
- availableBackends: array(AudioBackendSchema).readonly(),
17585
- sampleRate: number(),
17586
- chunkDurationMs: number()
17587
- });
17588
- var DownloadModelResultSchema = object({
17589
- filePath: string(),
17590
- sizeMB: number(),
17591
- durationMs: number()
17653
+ executeOnNodeId: string().optional(),
17654
+ /**
17655
+ * Milliseconds to wait between tracks; omit for the built-in default, `0` to
17656
+ * run flat out.
17657
+ *
17658
+ * A rebuild is bulk maintenance on hub-main's single thread. Measured
17659
+ * 2026-08-06, an unpaced pass held that thread busy 82.2 s out of 120 and
17660
+ * pushed `nodes.topology` from 0.25 s to 26 s for 43 minutes. The value in
17661
+ * force is logged at start and finish so a deliberately slow pass reads
17662
+ * differently from a stalled one.
17663
+ */
17664
+ pacingMs: number().int().nonnegative().optional()
17592
17665
  });
17593
17666
  /**
17594
- * Wrapper carrying a single test run's result. Replaces the legacy
17595
- * ad-hoc `{labels: [{className, originalClass, score}]}` shape with the
17596
- * canonical `AudioResult` from the Phase 6 output rework: one
17597
- * `AudioDetection` per class above `minScore`, top-N candidates in
17598
- * `debug.alternateLabels['audio-classifier']`, per-source timings in
17599
- * `debug.stepTimings`. The outer `success`/`error` fields stay so the
17600
- * benchmark UI can still report a clean failure when the classifier
17601
- * cap isn't available.
17667
+ * Result of emptying the CLIP index.
17668
+ *
17669
+ * The clean slate before a policy change: a new crop margin or encoder model
17670
+ * leaves two feature spaces in one index whose cosine scores are not
17671
+ * comparable, so wiping and rebuilding is the only way to be sure every vector
17672
+ * means the same thing.
17602
17673
  */
17603
- var AudioTestResultSchema = object({
17604
- success: boolean(),
17605
- error: string().optional(),
17606
- frame: custom().optional()
17674
+ var WipeObjectEmbeddingsResultSchema = object({ deleted: number() });
17675
+ /**
17676
+ * Acknowledgement that a rebuild STARTED.
17677
+ *
17678
+ * The pass costs ~1s per track — 45 minutes for a 2,600-track fleet — so it
17679
+ * runs detached and this returns immediately. Waiting for it made the client
17680
+ * time out while the work carried on server-side, which is the worst of both:
17681
+ * no result and no way to know it was still going. Poll
17682
+ * `getObjectEmbeddingRebuildStatus` for progress.
17683
+ */
17684
+ var RebuildObjectEmbeddingsResultSchema = object({
17685
+ started: boolean(),
17686
+ /** True when a pass was already running; the new request is ignored. */
17687
+ alreadyRunning: boolean()
17607
17688
  });
17608
- var PipelineConfigBridge = custom();
17609
- var ConfigUISchemaBridge = custom();
17610
- var ConfigUISchemaNullableBridge = custom();
17611
- var InferenceCapabilitiesBridge = custom();
17612
- var ModelAvailabilityListBridge = custom();
17613
- var PipelineRunResultBridge = custom();
17614
- method(_void(), array(PipelineEngineChoiceSchema)), method(_void(), PipelineEngineChoiceSchema), method(PipelineEngineChoiceSchema, array(PipelineDefaultStepSchema)), method(object({ nodeId: string() }), EngineProvisioningSchema), method(_void(), record(string(), object({
17615
- modelId: string(),
17616
- settings: record(string(), unknown()).readonly()
17617
- }))), method(object({ steps: record(string(), object({
17618
- modelId: string(),
17619
- settings: record(string(), unknown()).readonly()
17620
- })) }), object({ success: literal(true) }), {
17689
+ var RebuildStatusSchema = object({
17690
+ running: boolean(),
17691
+ scanned: number(),
17692
+ rebuilt: number(),
17693
+ /** Tracks whose key frame is gone — nothing to re-embed from. */
17694
+ missingKeyFrame: number(),
17695
+ /** Tracks with no usable detection box. */
17696
+ missingBbox: number(),
17697
+ /**
17698
+ * Tracks an executing node REFUSED rather than broke on — an unreadable key
17699
+ * frame, a step that threw. Separate from `failed` because the remedy is
17700
+ * different, and because a whole camera silently contributing zero vectors
17701
+ * is the shape of failure a rebuild must never hide.
17702
+ */
17703
+ notRunnable: number(),
17704
+ /**
17705
+ * The pass stopped because NO node could serve the pinned model.
17706
+ *
17707
+ * Distinct from `notRunnable` on purpose: that one says "this track was
17708
+ * refused", this one says "the cluster cannot do this work at all" — every
17709
+ * candidate node either lacks the `clip-embedding` step, lacks a build of the
17710
+ * pinned model for its engine format, or dropped out. The remedy is a model /
17711
+ * engine change, not a per-camera one. Non-zero here always comes with
17712
+ * `complete: false`.
17713
+ */
17714
+ noCapableNode: number(),
17715
+ failed: number(),
17716
+ /** Set once a pass ends: true only when EVERYTHING was covered. */
17717
+ complete: boolean().nullable(),
17718
+ startedAtMs: number().nullable(),
17719
+ finishedAtMs: number().nullable(),
17720
+ /** Present when the pass ended by throwing. */
17721
+ error: string().nullable()
17722
+ });
17723
+ var ReplayFrameInputSchema = object({
17724
+ timestamp: number(),
17725
+ frame: PipelineRunResultBridge
17726
+ });
17727
+ var RunReplayFrameProcessorResultSchema = object({ tracks: array(object({
17728
+ className: string(),
17729
+ firstSeenMs: number(),
17730
+ lastSeenMs: number(),
17731
+ /** Bbox of the track's FIRST matched detection, pixel-space in the clip's
17732
+ * frame — a representative box for the diff's `(className, window, IoU)`
17733
+ * pairing (`replay-diff.ts`). A replay does not need the full per-frame
17734
+ * trajectory production's `Track.positions` keeps. */
17735
+ bbox: BoundingBoxSchema,
17736
+ /** How many of the input frames this track matched a real detection on
17737
+ * (never a coasted/extrapolated frame) — the replay's own signal for "how
17738
+ * solid is this track", cheaper than re-deriving it from a trajectory. */
17739
+ framesMatched: number().int()
17740
+ })).readonly() });
17741
+ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).readonly()), method(object({
17742
+ deviceId: number(),
17743
+ trackId: string()
17744
+ }), TrackSchema.nullable()), method(object({
17745
+ deviceId: number(),
17746
+ since: number().optional(),
17747
+ until: number().optional(),
17748
+ limit: number().optional(),
17749
+ /** Spatial filter — only tracks whose trajectory intersects the zone
17750
+ * (normalized 0..1 rect or polygon). SQL-prefiltered on the persisted
17751
+ * envelope columns, then precisely tested per position. Tracks with
17752
+ * an unknown envelope (no frame dims at persist time) always match. */
17753
+ zone: TrackZoneFilterSchema.optional(),
17754
+ /** See {@link TrackProjectionSchema}. Default `full` (backward
17755
+ * compatible — omitting the field keeps today's exact behaviour). */
17756
+ projection: TrackProjectionSchema.optional(),
17757
+ /** Include stationary-promoted rows (parked objects handed to the
17758
+ * stationary registry). Default false: the timeline lists passages,
17759
+ * not parking records (operator decision, 2026-08-15). */
17760
+ includeStationary: boolean().optional()
17761
+ }), array(TrackSchema).readonly()), method(RecentTracksQueryInput, RecentTracksPageSchema), method(ListGroupsQueryInput, ListGroupsPageSchema), method(object({
17762
+ deviceId: number(),
17763
+ groupId: string().min(1)
17764
+ }), AnalyticsGroupDetailSchema.nullable()), method(object({ deviceId: number() }), _void(), {
17765
+ kind: "mutation",
17766
+ auth: "admin"
17767
+ }), 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({
17768
+ deviceId: number(),
17769
+ since: number().optional(),
17770
+ until: number().optional(),
17771
+ kinds: array(string()).optional(),
17772
+ limit: number().int().min(1).max(MAX_EVENT_QUERY_LIMIT).default(DEFAULT_EVENT_QUERY_LIMIT)
17773
+ }), array(SensorEventSchema).readonly()), method(KeyEventQueryInput, array(KeyEventSchema).readonly()), method(object({
17774
+ deviceId: number(),
17775
+ since: number(),
17776
+ until: number(),
17777
+ bucketMs: number().int().positive()
17778
+ }), array(object({
17779
+ bucketStart: number(),
17780
+ motion: number().int(),
17781
+ object: number().int(),
17782
+ audio: number().int()
17783
+ })).readonly()), method(object({
17784
+ deviceId: number(),
17785
+ cutoffMs: number()
17786
+ }), object({
17787
+ motion: number().int(),
17788
+ object: number().int(),
17789
+ audio: number().int()
17790
+ }), {
17621
17791
  kind: "mutation",
17622
17792
  auth: "admin"
17623
- }), method(object({ nodeId: string() }), object({
17624
- success: literal(true),
17625
- clearedDevices: number()
17793
+ }), method(object({
17794
+ deviceId: number(),
17795
+ cutoffMs: number()
17796
+ }), TrackCascadeCountsSchema, {
17797
+ kind: "mutation",
17798
+ auth: "admin"
17799
+ }), method(object({ deviceId: number() }), TrackCascadeCountsSchema, {
17800
+ kind: "mutation",
17801
+ auth: "admin"
17802
+ }), method(object({ deviceId: number() }), DiskReconcileCountsSchema, {
17803
+ kind: "mutation",
17804
+ auth: "admin"
17805
+ }), method(object({
17806
+ deviceId: number(),
17807
+ trackIds: array(string()).min(1)
17808
+ }), object({
17809
+ deleted: number().int(),
17810
+ failed: array(string()).readonly()
17626
17811
  }), {
17627
17812
  kind: "mutation",
17628
17813
  auth: "admin"
17629
- }), 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({
17630
- name: string(),
17631
- steps: array(PipelineTemplateStepSchema).readonly(),
17632
- engine: PipelineEngineChoiceSchema
17633
- }), PipelineTemplateSchema$1, { kind: "mutation" }), method(object({
17634
- id: string(),
17635
- name: string().optional(),
17636
- steps: array(PipelineTemplateStepSchema).readonly().optional()
17637
- }), PipelineTemplateSchema$1, { kind: "mutation" }), method(object({ id: string() }), _void(), { kind: "mutation" }), method(_void(), InferenceCapabilitiesBridge), method(object({ addonId: string() }), ModelAvailabilityListBridge), method(object({
17638
- addonId: string(),
17639
- modelId: string(),
17640
- format: ModelFormatSchema$1
17641
- }), DownloadModelResultSchema, { kind: "mutation" }), method(object({
17642
- addonId: string(),
17643
- modelId: string(),
17644
- format: ModelFormatSchema$1
17645
- }), object({ success: literal(true) }), { kind: "mutation" }), method(object({
17646
- engine: PipelineEngineChoiceSchema.optional(),
17647
- steps: array(PipelineStepInputSchema).min(1),
17648
- frame: FrameInputSchema.optional(),
17649
- /**
17650
- * Process-local lazy frame. Valid only when caller and provider resolve
17651
- * in the same execution-group process; split/cross-node callers use
17652
- * `frame`/`image` inline compatibility instead.
17653
- */
17654
- frameRef: FrameRefSchema.optional(),
17655
- /**
17656
- * CB5 shm passthrough — a `FrameHandle` naming the same ring slot
17657
- * the decoded pixels live in. One more member of the one-of
17658
- * frame/frameHandle/image/imageBase64/referenceImage group.
17659
- */
17660
- frameHandle: FrameHandleSchema.optional(),
17661
- imageBase64: string().optional(),
17662
- /**
17663
- * Binary JPEG bytes — preferred over `imageBase64` on internal
17664
- * hops (hub → forked worker via Moleculer MsgPack) because it
17665
- * skips the 33% base64 overhead + the per-call base64 decode on
17666
- * the detection-pipeline worker. Callers can pass either; exactly
17667
- * one of `frame`/`image`/`imageBase64`/`referenceImage` is required.
17668
- */
17669
- image: _instanceof(Uint8Array).optional(),
17670
- referenceImage: string().optional(),
17671
- deviceId: number().optional(),
17672
- sessionId: string().optional(),
17673
- /**
17674
- * Execution plane. 'full' (default) runs the whole tree — benchmark,
17675
- * reference-image, and detail-subtree calls. 'frame' is the live
17676
- * per-frame dispatch: ONLY root-plane steps run; crop children
17677
- * (inputClasses ≠ null) are skipped and served per-track via
17678
- * pipelineRunner.runDetailSubtree (two-plane design).
17679
- */
17680
- plane: _enum(["full", "frame"]).optional(),
17681
- /**
17682
- * Inference-device selector (Phase 2 multi-device). Format
17683
- * `<backend>:<device>` (e.g. `openvino:gpu`, `edgetpu:usb`, `cpu`).
17684
- * Omitted ⇒ the runner's default device (current single-engine
17685
- * behaviour). Selects WHICH device pool of the node runs the call.
17686
- */
17687
- deviceKey: string().optional(),
17688
- /**
17689
- * Two-plane NATIVE child-crop reference. Set by `runDetailSubtree` ONLY
17690
- * when the parent crop was resolved from the frame's retained NATIVE
17691
- * surface (a frameHandle HIT). Lets the executor re-cut a LEAF crop
17692
- * child's ROI (plate-ocr, face-embedding, leaf classifiers) at native
17693
- * resolution from that surface — the SAME quality path faces already
17694
- * had — instead of the downscaled parent tile. `handle` keys the native
17695
- * surface (node-pinned to its owner); `cropFrameSpace` is the parent
17696
- * crop's padded/clamped rectangle in FRAME-space pixels, used to compose
17697
- * the executor's crop-normalized child ROI back into frame-normalized
17698
- * coordinates. Auxiliary to the image source (`image`/`frame`/…), NOT one
17699
- * of the mutually-exclusive image inputs. Absent ⇒ tile-crop children
17700
- * (today's behaviour on the fallback path).
17701
- */
17702
- nativeCropRef: NativeCropRefSchema.optional()
17703
- }), PipelineRunResultBridge, { kind: "mutation" }), method(object({
17704
- engine: PipelineEngineChoiceSchema.optional(),
17705
- steps: array(PipelineStepInputSchema).min(1),
17706
- frames: array(FrameInputSchema).min(1).max(255),
17707
- deviceId: number().optional(),
17708
- sessionId: string().optional(),
17709
- /**
17710
- * Pure-inference benchmark hint. A NONZERO uint32 pins every frame in
17711
- * the batch to the Python pool's bench preprocess cache
17712
- * (`_bench_frame_id`) so a REPEATED benchmark frame is decoded +
17713
- * preprocessed ONCE and every later inference is a pure-inference cache
17714
- * hit — the sustained-throughput run measures inference, not
17715
- * decode+preprocess+infer. Omitted/0 for live frames (all different →
17716
- * full preprocess every call, correct). Fresh per sustained run;
17717
- * released via `uncacheFrame`.
17718
- */
17719
- frameId: number().int().nonnegative().optional(),
17720
- /** Inference-device selector (Phase 2 multi-device); see runPipeline. */
17721
- deviceKey: string().optional()
17722
- }), object({ results: array(PipelineRunResultBridge).readonly() }), { kind: "mutation" }), method(object({
17723
- data: _instanceof(Uint8Array),
17724
- width: number().int().positive(),
17725
- height: number().int().positive(),
17726
- format: _enum([
17727
- "rgb",
17728
- "bgr",
17729
- "gray"
17730
- ])
17814
+ }), method(object({
17815
+ /** Log/audit scope only — the trackId is globally unique on its own. */
17816
+ deviceId: number(),
17817
+ trackId: string(),
17818
+ flags: TrackFlagsPatchSchema
17819
+ }), TrackFlagsSchema, { kind: "mutation" }), method(object({}), EventStoreFootprintSchema, {
17820
+ kind: "query",
17821
+ auth: "admin"
17822
+ }), method(object({
17823
+ olderThanMs: number(),
17824
+ reason: OpsLogReasonSchema.optional()
17825
+ }), EventPruneCountsSchema, {
17826
+ kind: "mutation",
17827
+ auth: "admin"
17828
+ }), method(object({ deviceId: number() }), EventPruneCountsSchema, {
17829
+ kind: "mutation",
17830
+ auth: "admin"
17831
+ }), method(StorageMigrationLeaseInputSchema, object({ paused: literal(true) }), {
17832
+ kind: "mutation",
17833
+ auth: "admin"
17834
+ }), method(StorageMigrationLeaseInputSchema, object({ resumed: literal(true) }), {
17835
+ kind: "mutation",
17836
+ auth: "admin"
17837
+ }), method(StorageMigrationLeaseInputSchema, object({ refreshed: literal(true) }), {
17838
+ kind: "mutation",
17839
+ auth: "admin"
17840
+ }), method(StorageMigrationMediaMoveInputSchema, object({ jobId: string() }), {
17841
+ kind: "mutation",
17842
+ auth: "admin"
17843
+ }), method(object({ jobId: string() }), RelocateJobSchema.nullable(), { auth: "admin" }), method(object({ jobId: string() }), object({ cancelled: boolean() }), {
17844
+ kind: "mutation",
17845
+ auth: "admin"
17846
+ }), method(RelocateMediaInputSchema, object({ jobId: string() }), {
17847
+ kind: "mutation",
17848
+ auth: "admin"
17849
+ }), method(object({}), array(RelocateJobSchema).readonly(), {
17850
+ kind: "query",
17851
+ auth: "admin"
17852
+ }), method(object({ jobId: string() }), object({ cancelled: boolean() }), {
17853
+ kind: "mutation",
17854
+ auth: "admin"
17855
+ }), method(OpsLogQueryInputSchema, array(OpsLogEntrySchema).readonly(), {
17856
+ kind: "query",
17857
+ auth: "admin"
17858
+ }), method(object({ deviceIds: array(number()).optional() }), TrainingExportSummarySchema, {
17859
+ kind: "query",
17860
+ auth: "admin"
17861
+ }), method(object({ deviceIds: array(number()).optional() }), object({ url: string() }), {
17862
+ kind: "query",
17863
+ auth: "admin"
17864
+ }), method(object({
17865
+ /** Empty ⇒ every camera that has staging tracks. A LIST, not a single
17866
+ * `deviceId`, deliberately: `deviceId` would make this device-bound and
17867
+ * route it at one camera's owner, and "every camera" would stop being
17868
+ * expressible at all. */
17869
+ deviceIds: array(number()).optional(),
17870
+ limit: number().int().min(1).max(500).optional()
17871
+ }), array(RetrainTrackSchema).readonly(), {
17872
+ kind: "query",
17873
+ auth: "admin"
17874
+ }), method(object({ trackId: string() }), RetrainFrameListSchema, {
17875
+ kind: "query",
17876
+ auth: "admin"
17877
+ }), method(object({
17878
+ deviceId: number(),
17879
+ trackId: string(),
17880
+ mediaKeys: array(string()).min(1)
17881
+ }), RetrainFrameSelectionSchema, {
17882
+ kind: "mutation",
17883
+ auth: "admin"
17884
+ }), method(object({
17885
+ deviceId: number(),
17886
+ trackId: string(),
17887
+ frameId: string()
17731
17888
  }), object({
17732
- frameId: number(),
17733
- width: number(),
17734
- height: number()
17735
- }), { kind: "mutation" }), method(object({
17736
- stepId: string(),
17737
- frameId: number().int()
17738
- }), record(string(), unknown()), { kind: "mutation" }), method(object({ frameId: number().int() }), _void(), { kind: "mutation" }), method(_void(), object({
17739
- batchMode: string(),
17740
- windowMs: number(),
17741
- maxBatchSize: number(),
17742
- concurrency: number()
17743
- })), method(_void(), array(object({
17744
- engineKey: string(),
17745
- engine: PipelineEngineChoiceSchema,
17746
- modelsLoaded: array(string()).readonly(),
17747
- inUseByCameras: array(number()).readonly(),
17748
- /**
17749
- * Origin of this resident factory.
17750
- * - `runtime` — main camera-serving engine (no idle TTL).
17751
- * - `warm-override` — benchmark/test override held in the warm
17752
- * cache; auto-disposed after the idle TTL.
17753
- * - `device-pool` — a concurrent per-device pool (Phase 2
17754
- * multi-device, keyed by `deviceKey`) resolved
17755
- * via `resolveDeviceFactory`. Runs alongside the
17756
- * `runtime` engine on a DIFFERENT accelerator
17757
- * (NPU / iGPU / Coral) — this is how the
17758
- * Engines tab shows all pools running at once.
17759
- */
17760
- kind: _enum([
17761
- "runtime",
17762
- "warm-override",
17763
- "device-pool"
17764
- ]),
17765
- /** Native pid of the underlying Python pool (null when no pool). */
17766
- poolPid: number().nullable(),
17767
- /** ms since this factory was last used (null when not warm-tracked). */
17768
- idleMs: number().nullable(),
17769
- /** Idle TTL after which `warm-override` factories self-evict (null when not applicable). */
17770
- idleTtlMs: number().nullable()
17771
- })).readonly()), method(object({ engine: PipelineEngineChoiceSchema }), object({ success: literal(true) }), {
17889
+ removed: boolean(),
17890
+ removedAnnotations: number().int()
17891
+ }), {
17892
+ kind: "mutation",
17893
+ auth: "admin"
17894
+ }), method(object({ frameId: string() }), object({
17895
+ base64: string(),
17896
+ width: number().int(),
17897
+ height: number().int()
17898
+ }), {
17899
+ kind: "query",
17900
+ auth: "admin"
17901
+ }), method(object({
17902
+ deviceId: number(),
17903
+ trackId: string(),
17904
+ frameId: string(),
17905
+ subject: RetrainAssistSubjectSchema,
17906
+ /** Which node runs it. Absent ⇒ wherever an unowned call lands. */
17907
+ nodeId: string().optional()
17908
+ }), RetrainAssistResultSchema, {
17772
17909
  kind: "mutation",
17773
17910
  auth: "admin"
17774
17911
  }), method(object({
17775
- engine: PipelineEngineChoiceSchema,
17776
- force: boolean().optional()
17777
- }), object({
17778
- success: boolean(),
17779
- reason: string().optional()
17780
- }), {
17912
+ deviceId: number(),
17913
+ source: DetectionSourceSchema,
17914
+ zones: array(ZoneSchema).readonly().optional(),
17915
+ detectionRules: array(ZoneRuleSchema).readonly().optional(),
17916
+ zoneMembershipMinOverlap: number().min(0).max(1).optional(),
17917
+ frames: array(ReplayFrameInputSchema).min(1)
17918
+ }), RunReplayFrameProcessorResultSchema, {
17781
17919
  kind: "mutation",
17782
17920
  auth: "admin"
17783
- }), 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({
17784
- addonId: string(),
17785
- modelId: string(),
17786
- filename: string().optional(),
17787
- settings: record(string(), unknown()).optional()
17788
- }), AudioTestResultSchema, { kind: "mutation" }), method(_void(), ConfigUISchemaNullableBridge);
17921
+ }), method(object({ trackId: string() }), array(RetrainAnnotationSchema).readonly(), {
17922
+ kind: "query",
17923
+ auth: "admin"
17924
+ }), method(object({
17925
+ deviceId: number(),
17926
+ trackId: string(),
17927
+ frameId: string(),
17928
+ annotations: array(RetrainAnnotationDraftSchema)
17929
+ }), array(RetrainAnnotationSchema).readonly(), {
17930
+ kind: "mutation",
17931
+ auth: "admin"
17932
+ }), method(object({
17933
+ deviceId: number(),
17934
+ trackId: string()
17935
+ }), RetrainTransitionResultSchema, {
17936
+ kind: "mutation",
17937
+ auth: "admin"
17938
+ }), method(object({
17939
+ deviceId: number(),
17940
+ trackId: string()
17941
+ }), RetrainTransitionResultSchema, {
17942
+ kind: "mutation",
17943
+ auth: "admin"
17944
+ }), method(object({ deviceIds: array(number()).optional() }), object({ url: string() }), {
17945
+ kind: "query",
17946
+ auth: "admin"
17947
+ }), method(object({
17948
+ eventId: string(),
17949
+ kind: MediaFileKindEnum.optional(),
17950
+ deviceId: number()
17951
+ }), array(MediaFileSchema).readonly()), method(object({
17952
+ trackId: string(),
17953
+ kinds: array(MediaFileKindEnum).optional(),
17954
+ deviceId: number()
17955
+ }), array(MediaFileSchema).readonly()), method(object({
17956
+ trackId: string(),
17957
+ deviceId: number()
17958
+ }), array(MediaFileInfoSchema).readonly()), method(SearchObjectEventsInput, array(ScoredObjectEventSchema).readonly()), method(object({}), WipeObjectEmbeddingsResultSchema, {
17959
+ kind: "mutation",
17960
+ auth: "admin"
17961
+ }), method(RebuildObjectEmbeddingsInput, RebuildObjectEmbeddingsResultSchema, {
17962
+ kind: "mutation",
17963
+ auth: "admin"
17964
+ }), method(object({}), RebuildStatusSchema), object({
17965
+ deviceId: number(),
17966
+ timestamp: number(),
17967
+ frameWidth: number(),
17968
+ frameHeight: number(),
17969
+ detections: array(OverlayDetectionSchema).readonly()
17970
+ }), object({
17971
+ deviceId: number(),
17972
+ trackId: string(),
17973
+ className: string()
17974
+ }), object({
17975
+ deviceId: number(),
17976
+ trackId: string(),
17977
+ className: string(),
17978
+ durationMs: number()
17979
+ }), object({
17980
+ deviceId: number(),
17981
+ kind: EventKindSchema,
17982
+ eventId: string(),
17983
+ timestamp: number()
17984
+ });
17789
17985
  object({
17790
17986
  activeCameras: number(),
17791
17987
  throttledCameras: number(),
@@ -17811,66 +18007,6 @@ var CameraMetricsSchema = object({
17811
18007
  });
17812
18008
  var CameraMetricsWithDeviceIdSchema = CameraMetricsSchema.extend({ deviceId: number() });
17813
18009
  /**
17814
- * Zone — pure geometry + identity. NO filtering behaviour.
17815
- *
17816
- * Zones describe **where** in the frame the operator wants to flag
17817
- * something; consumer-owned {@link ZoneRule} arrays describe **how**
17818
- * each pipeline stage uses them. Splitting the two means a single
17819
- * polygon "Driveway" can simultaneously back a motion-exclude rule,
17820
- * a detection-include rule on `['car']`, and an occupancy aggregate
17821
- * — without three duplicated polygons.
17822
- *
17823
- * Owned by the orchestrator addon (provider) and mirrored into the
17824
- * `zones` device-state slice on every mutation. Consumers
17825
- * (motion-wasm, pipeline-executor, analytics, admin UI) read either
17826
- * via `api.zones.listZones` (one-shot) or via `dev.state.zones` (live
17827
- * mirror with `onChanged`).
17828
- *
17829
- * Coordinates are normalised fractions of the frame (0–1) so zones
17830
- * survive resolution changes and stream profile switches.
17831
- *
17832
- * `kind` discriminates between full polygons (closed regions used
17833
- * for intrusion / occupancy filters) and tripwires (open 2-point
17834
- * line segments used for cross events). Onboard / firmware-reported
17835
- * zones (Reolink, ONVIF) are out of scope for now — see the deferred
17836
- * task list.
17837
- */
17838
- var ZoneKindEnum = _enum(["polygon", "tripwire"]);
17839
- /** Polygon vertex in fraction-of-frame coordinates (0–1). */
17840
- var PolygonPointSchema = object({
17841
- x: number(),
17842
- y: number()
17843
- });
17844
- /** A camera detection zone — pure geometry/identity. */
17845
- var ZoneSchema = object({
17846
- id: string(),
17847
- name: string(),
17848
- kind: ZoneKindEnum.default("polygon"),
17849
- /** Polygon vertices, fraction of frame (0–1). */
17850
- polygon: array(PolygonPointSchema).readonly(),
17851
- /** Visual color for UI rendering. */
17852
- color: string().default("#3b82f6")
17853
- });
17854
- DeviceType.Camera, method(object({ deviceId: number() }), array(ZoneSchema).readonly()), method(object({
17855
- deviceId: number(),
17856
- zone: ZoneSchema
17857
- }), _void(), {
17858
- kind: "mutation",
17859
- auth: "admin"
17860
- }), method(object({
17861
- deviceId: number(),
17862
- zoneId: string()
17863
- }), _void(), {
17864
- kind: "mutation",
17865
- auth: "admin"
17866
- }), method(object({
17867
- deviceId: number(),
17868
- zone: ZoneSchema
17869
- }), _void(), {
17870
- kind: "mutation",
17871
- auth: "admin"
17872
- }), object({ zones: array(ZoneSchema).readonly() });
17873
- /**
17874
18010
  * A bounding box in NORMALIZED [0,1] frame coordinates for `getNativeCrop`. The
17875
18011
  * decode worker resolves it against the RETAINED native frame's real pixel dims,
17876
18012
  * so the caller supplies only the detection-res bbox divided by the detection
@@ -25512,92 +25648,6 @@ DeviceType.Camera, method(object({ deviceId: number() }), SceneMonitorStatusSche
25512
25648
  kind: "mutation",
25513
25649
  auth: "admin"
25514
25650
  });
25515
- /**
25516
- * Per-stage gating mode applied to the zones a rule references.
25517
- *
25518
- * - `include`: the rule contributes to a **whitelist** for its stage.
25519
- * When at least one `include` rule fires for a stage, only entities
25520
- * inside one of those zones pass that stage.
25521
- * - `exclude`: the rule contributes to a **blacklist** for its stage.
25522
- * Entities inside one of those zones are dropped at that stage.
25523
- *
25524
- * `monitor`-style observation (count without filtering) is not a rule
25525
- * mode — zones without any matching rule are observed naturally by
25526
- * `zone-analytics` (live snapshot + history), so an "I just want to
25527
- * count, not filter" use case needs no rule at all.
25528
- */
25529
- var ZoneRuleModeEnum = _enum(["include", "exclude"]);
25530
- /**
25531
- * Per-consumer rule that references existing zones (geometry) and
25532
- * defines how a specific pipeline stage should treat them. Each
25533
- * consumer addon owns its own `ZoneRule[]` array in its per-device
25534
- * settings:
25535
- *
25536
- * - `addon-motion-wasm` → `motionZoneRules: ZoneRule[]` (motion stage)
25537
- * - `addon-detection-pipeline` → `detectionZoneRules: ZoneRule[]` (detection stage)
25538
- * - future: notification rules, audio gating, etc.
25539
- *
25540
- * One rule applies to N zones (`zoneIds[]`) so the operator can
25541
- * express "ignore motion in ALL of {garden, street}" with a single
25542
- * rule. `classFilter` narrows the rule to specific object classes —
25543
- * "drop person detections in the street, but keep cars" is one
25544
- * `exclude` rule with `classFilter: ['person']`.
25545
- *
25546
- * `enabled` is a soft toggle — the operator can keep the rule
25547
- * configured but inert without deleting it.
25548
- */
25549
- var ZoneRuleSchema = object({
25550
- /** Stable rule id — survives edits, used by the UI for diffing. */
25551
- id: string(),
25552
- /** Optional human-readable label rendered in the rule editor. */
25553
- name: string().optional(),
25554
- /** Zones this rule targets. The rule's `mode` applies to ALL
25555
- * listed zones (OR-set: a detection in any one of them counts).
25556
- * At least one zone id required — a rule with no targets is a
25557
- * configuration mistake and the form validator rejects it. */
25558
- zoneIds: array(string()).min(1).readonly(),
25559
- mode: ZoneRuleModeEnum,
25560
- /**
25561
- * Class names this rule applies to. Empty / undefined ⇒ rule
25562
- * applies to every class. Class strings match the `macroClass`
25563
- * field on detections (e.g. `person`, `car`, `dog`).
25564
- */
25565
- classFilter: array(string()).readonly().optional(),
25566
- /**
25567
- * Minimum bbox/mask overlap (0–1) with any of the rule's zones
25568
- * required to consider an entity "in the zone". Defaults to the
25569
- * consumer's stage default when omitted. Kept for back-compat with
25570
- * existing per-rule overrides; new operators pick the value via
25571
- * `bboxInclusionPct` (operator-friendly 0–100). Whichever field is
25572
- * set, the lower-level engine reads it as a 0–1 fraction.
25573
- */
25574
- overlapThreshold: number().min(0).max(1).optional(),
25575
- /**
25576
- * Operator-friendly version of `overlapThreshold` — the percentage
25577
- * of the detection's bbox that must lie inside the zone for the
25578
- * rule to match. Documented default is 85%; the engine substitutes
25579
- * that when the field is omitted (kept optional so existing rules
25580
- * stored without it stay valid).
25581
- *
25582
- * When BOTH `overlapThreshold` and `bboxInclusionPct` are set on a
25583
- * rule, the engine prefers `bboxInclusionPct` because it's the
25584
- * field exposed in the UI. Internally both feed the same gate.
25585
- */
25586
- bboxInclusionPct: number().min(0).max(100).optional(),
25587
- /**
25588
- * When `true` and a detection has a segmentation mask, use the
25589
- * mask for overlap instead of the bbox. Detection-stage only;
25590
- * motion rules ignore this field.
25591
- */
25592
- preferMask: boolean().optional(),
25593
- /**
25594
- * Soft-toggle: `false` disables the rule without deleting it.
25595
- * Defaults to `true` so operators creating a rule via the UI
25596
- * see it active immediately.
25597
- */
25598
- enabled: boolean().default(true)
25599
- });
25600
- array(ZoneRuleSchema).readonly();
25601
25651
  object({
25602
25652
  /** Whether the script is currently executing. */
25603
25653
  isRunning: boolean(),
@@ -29906,6 +29956,12 @@ Object.freeze({
29906
29956
  addonId: null,
29907
29957
  access: "create"
29908
29958
  },
29959
+ "pipelineAnalytics.runReplayFrameProcessor": {
29960
+ capName: "pipeline-analytics",
29961
+ capScope: "device",
29962
+ addonId: null,
29963
+ access: "create"
29964
+ },
29909
29965
  "pipelineAnalytics.saveRetrainAnnotations": {
29910
29966
  capName: "pipeline-analytics",
29911
29967
  capScope: "device",
@@ -30038,6 +30094,12 @@ Object.freeze({
30038
30094
  addonId: null,
30039
30095
  access: "view"
30040
30096
  },
30097
+ "pipelineExecutor.getInferenceDeviceHealth": {
30098
+ capName: "pipeline-executor",
30099
+ capScope: "system",
30100
+ addonId: null,
30101
+ access: "view"
30102
+ },
30041
30103
  "pipelineExecutor.getOrchestratorConfigSchema": {
30042
30104
  capName: "pipeline-executor",
30043
30105
  capScope: "system",
@@ -30110,6 +30172,12 @@ Object.freeze({
30110
30172
  addonId: null,
30111
30173
  access: "view"
30112
30174
  },
30175
+ "pipelineExecutor.rearmInferenceDevice": {
30176
+ capName: "pipeline-executor",
30177
+ capScope: "system",
30178
+ addonId: null,
30179
+ access: "create"
30180
+ },
30113
30181
  "pipelineExecutor.runAudioTest": {
30114
30182
  capName: "pipeline-executor",
30115
30183
  capScope: "system",
@@ -33358,6 +33426,11 @@ Object.freeze({
33358
33426
  form: "single",
33359
33427
  optional: false
33360
33428
  }],
33429
+ "pipelineAnalytics.runReplayFrameProcessor": [{
33430
+ name: "deviceId",
33431
+ form: "single",
33432
+ optional: false
33433
+ }],
33361
33434
  "pipelineAnalytics.saveRetrainAnnotations": [{
33362
33435
  name: "deviceId",
33363
33436
  form: "single",