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