@camstack/addon-decoder-nodeav 1.2.28 → 1.2.30

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