@camstack/addon-mqtt-broker 1.2.29 → 1.2.30

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