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