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