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