@camstack/addon-mqtt-broker 1.2.29 → 1.2.31

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