@camstack/addon-decoder-nodeav 1.2.28 → 1.2.29

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