@camstack/addon-notifiers 1.2.33 → 1.2.35

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