@camstack/addon-export-alexa 1.2.35 → 1.2.37

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