@camstack/addon-matter-broker 0.2.28 → 0.2.29

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