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