@camstack/addon-provider-rtsp 1.2.29 → 1.2.30

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