@camstack/addon-export-alexa 1.2.35 → 1.2.36

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