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