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