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