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