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