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