@camstack/addon-ai 0.4.22 → 0.4.23

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