@camstack/addon-decoder-nodeav 1.2.28 → 1.2.30

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