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