@camstack/addon-auth 1.2.32 → 1.2.33

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