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