@camstack/addon-ai 0.4.22 → 0.4.23

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