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