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