@camstack/addon-auth 1.2.32 → 1.2.34

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.
@@ -15653,7 +15653,23 @@ var NcHistoryEntrySchema = object({
15653
15653
  updatedAt: number(),
15654
15654
  /** Failure detail — present on a `dead` row. */
15655
15655
  error: string().optional(),
15656
- subject: NcHistorySubjectSchema
15656
+ subject: NcHistorySubjectSchema,
15657
+ /**
15658
+ * Ids of the artefacts (still, then gif, then clip) this row's successful
15659
+ * delivery indexed in the artefact library — a REFERENCE, never the bytes
15660
+ * (an artefact is often megabytes; this row is durable JSON rewritten on
15661
+ * every delivery attempt). Absent on a row still pending/dead, a row
15662
+ * delivered before this field shipped, or a wiring with no artefact index.
15663
+ *
15664
+ * Resolve one to a fetchable URL with `resolveArtifactUrl` — an id
15665
+ * outlives any one URL's TTL, so a caller mints a fresh link on demand
15666
+ * rather than trusting one frozen at delivery time. `resolveArtifactUrl`
15667
+ * also answers `null` for an id whose artefact has since expired past the
15668
+ * retained shelf's own age bound — the degrade a caller (the Home
15669
+ * Assistant export) must render as "no image right now", never as a
15670
+ * broken link.
15671
+ */
15672
+ artifactIds: array(string().min(1)).optional()
15657
15673
  });
15658
15674
  /**
15659
15675
  * Query filter for `getHistory` (spec §4.2). Every field is a narrowing
@@ -15880,7 +15896,7 @@ method(object({}), object({ rules: array(NcRuleSchema) }), { auth: "admin" }), m
15880
15896
  }), method(object({}), object({
15881
15897
  catalog: array(NcConditionDescriptorSchema),
15882
15898
  taxonomy: NcTaxonomySchema.optional()
15883
- })), method(object({ filter: NcHistoryFilterSchema.default({ limit: 100 }) }), object({ entries: array(NcHistoryEntrySchema) }), { auth: "admin" }), method(object({}), object({ snoozes: array(NcSnoozeSchema) }), { caller: "required" }), method(object({ snooze: NcSnoozeInputSchema }), object({ snooze: NcSnoozeSchema }), {
15899
+ })), method(object({ filter: NcHistoryFilterSchema.default({ limit: 100 }) }), object({ entries: array(NcHistoryEntrySchema) }), { auth: "admin" }), method(object({ artifactId: string().min(1) }), object({ url: string().nullable() }), { auth: "admin" }), method(object({}), object({ snoozes: array(NcSnoozeSchema) }), { caller: "required" }), method(object({ snooze: NcSnoozeInputSchema }), object({ snooze: NcSnoozeSchema }), {
15884
15900
  kind: "mutation",
15885
15901
  caller: "required"
15886
15902
  }), method(object({ snoozeId: string() }), object({ success: literal(true) }), {
@@ -16220,896 +16236,1496 @@ var OauthIntegrationDescriptorSchema = object({
16220
16236
  });
16221
16237
  method(_void(), OauthIntegrationDescriptorSchema, { auth: "admin" });
16222
16238
  /**
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.
16239
+ * Reference to the frame's retained NATIVE surface + the parent crop's placement
16240
+ * within the frame, so the executor can re-cut a leaf child ROI at native
16241
+ * resolution on the detail plane. See the `runPipeline` `nativeCropRef` field.
16245
16242
  */
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
- ]);
16243
+ var NativeCropRefSchema = object({
16244
+ /** Handle keying the retained native surface (node-pinned to its owner). */
16245
+ handle: FrameHandleSchema,
16246
+ /** The parent crop's padded/clamped rectangle in FRAME-space pixels. */
16247
+ cropFrameSpace: object({
16248
+ x: number(),
16249
+ y: number(),
16250
+ w: number(),
16251
+ h: number()
16252
+ })
16253
+ });
16254
+ object({
16255
+ crop: object({
16256
+ left: number(),
16257
+ top: number(),
16258
+ width: number().positive(),
16259
+ height: number().positive()
16260
+ }).optional(),
16261
+ content: object({
16262
+ width: number().int().positive(),
16263
+ height: number().int().positive()
16264
+ }),
16265
+ fit: _enum(["stretch", "contain"]),
16266
+ format: _enum([
16267
+ "rgb",
16268
+ "gray",
16269
+ "jpeg"
16270
+ ])
16271
+ });
16258
16272
  /**
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.
16273
+ * Process-local frame identity. It is serializable so it can ride an in-process
16274
+ * capability call, but `registryId` deliberately prevents resolution in any
16275
+ * other process or execution group.
16262
16276
  */
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"
16277
+ var FrameRefSchema = object({
16278
+ registryId: string().min(1),
16279
+ id: string().min(1),
16280
+ width: number().int().positive(),
16281
+ height: number().int().positive(),
16282
+ format: _enum(["rgb", "gray"]),
16283
+ timestamp: number(),
16284
+ capturedAt: number().optional()
16285
+ });
16286
+ var ModelFormatSchema$1 = _enum([
16287
+ "onnx",
16288
+ "coreml",
16289
+ "openvino",
16290
+ "tflite",
16291
+ "pt",
16292
+ "gguf"
16278
16293
  ]);
16279
- var EventKindCategorySchema = _enum([
16280
- "motion",
16281
- "audio",
16282
- "detection",
16283
- "sensor",
16284
- "control",
16285
- "custom",
16286
- "package"
16294
+ var PipelineSlotSchema = _enum([
16295
+ "detector",
16296
+ "cropper",
16297
+ "classifier",
16298
+ "refiner",
16299
+ "audio-classifier"
16287
16300
  ]);
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
- })
16301
+ var PipelineEngineChoiceSchema = object({
16302
+ runtime: _enum(["node", "python"]),
16303
+ backend: string(),
16304
+ format: ModelFormatSchema$1,
16305
+ device: string().optional()
16314
16306
  });
16315
- /** One camera's event vocabulary, as returned by `listEventKindsBatch`. */
16316
- var EventKindsForDeviceSchema = object({
16317
- deviceId: number(),
16318
- kinds: array(EventKindDescriptorSchema).readonly()
16307
+ var AvailableEngineSchema = object({
16308
+ engine: PipelineEngineChoiceSchema,
16309
+ devices: array(object({
16310
+ id: string(),
16311
+ label: string(),
16312
+ description: string().optional()
16313
+ })).readonly(),
16314
+ defaultDevice: string()
16319
16315
  });
16320
- var SensorEventSchema = object({
16316
+ var PipelineDefaultStepSchema = lazy(() => object({
16317
+ addonId: string(),
16318
+ addonName: string(),
16319
+ slot: PipelineSlotSchema,
16320
+ inputClasses: array(string()).readonly(),
16321
+ outputClasses: array(string()).readonly(),
16322
+ enabled: boolean(),
16323
+ modelId: string(),
16324
+ children: array(PipelineDefaultStepSchema).readonly(),
16325
+ group: string().optional(),
16326
+ settings: record(string(), unknown()).optional()
16327
+ }));
16328
+ var PipelineTemplateStepSchema = lazy(() => object({
16329
+ addonId: string(),
16330
+ enabled: boolean(),
16331
+ modelId: string(),
16332
+ children: array(PipelineTemplateStepSchema).readonly(),
16333
+ settings: record(string(), unknown()).optional()
16334
+ }));
16335
+ var PipelineTemplateSchema$1 = object({
16321
16336
  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()
16337
+ name: string(),
16338
+ createdAt: string(),
16339
+ updatedAt: string(),
16340
+ engine: PipelineEngineChoiceSchema,
16341
+ steps: array(PipelineTemplateStepSchema).readonly()
16332
16342
  });
16333
- var TrackPositionSchema = object({
16334
- x: number(),
16335
- y: number(),
16336
- timestamp: number(),
16337
- bbox: BoundingBoxSchema
16343
+ var PipelineModelOptionSchema = object({
16344
+ id: string(),
16345
+ name: string(),
16346
+ formats: record(string(), object({
16347
+ downloaded: boolean(),
16348
+ sizeMB: number()
16349
+ })),
16350
+ group: ModelVariantGroupSchema.optional(),
16351
+ legacy: boolean().optional(),
16352
+ provider: ModelProviderIdSchema.optional()
16338
16353
  });
16339
- var TrackSnapshotSchema = object({
16340
- timestamp: number(),
16341
- position: TrackPositionSchema,
16342
- /** MediaStore key; resolve via `getTrackMedia({ trackId })`. */
16343
- mediaKey: string()
16354
+ var ConfigFieldBridge = custom();
16355
+ var PipelineAddonSchemaSchema = object({
16356
+ id: string(),
16357
+ name: string(),
16358
+ slot: PipelineSlotSchema,
16359
+ inputClasses: array(string()).readonly(),
16360
+ outputClasses: array(string()).readonly(),
16361
+ childSlots: array(PipelineSlotSchema).readonly(),
16362
+ models: array(PipelineModelOptionSchema).readonly(),
16363
+ defaultModelId: string(),
16364
+ defaultModelIdByFormat: record(string(), string()).optional(),
16365
+ enabledByDefault: boolean().optional(),
16366
+ backfillIntoExistingOverrides: boolean().optional(),
16367
+ defaultConfidence: number(),
16368
+ group: string().optional(),
16369
+ configSchema: array(ConfigFieldBridge).readonly().optional()
16344
16370
  });
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()
16371
+ var PipelineSlotSchemaSchema = object({
16372
+ id: PipelineSlotSchema,
16373
+ label: string(),
16374
+ priority: number(),
16375
+ parentSlot: PipelineSlotSchema.nullable(),
16376
+ addons: array(PipelineAddonSchemaSchema).readonly()
16356
16377
  });
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()
16378
+ var PipelineSchemaSchema = object({
16379
+ availableEngines: array(AvailableEngineSchema).readonly(),
16380
+ selectedEngine: PipelineEngineChoiceSchema,
16381
+ slots: array(PipelineSlotSchemaSchema).readonly()
16384
16382
  });
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
16383
+ var EngineProvisioningSchema = object({
16384
+ runtimeId: _enum([
16385
+ "onnx",
16386
+ "openvino",
16387
+ "coreml",
16388
+ "edgetpu"
16389
+ ]).nullable(),
16390
+ device: string().nullable(),
16391
+ state: _enum([
16392
+ "idle",
16393
+ "installing",
16394
+ "verifying",
16395
+ "ready",
16396
+ "failed"
16397
+ ]),
16398
+ progress: number().optional(),
16399
+ error: string().optional(),
16400
+ nextRetryAt: number().optional(),
16401
+ /**
16402
+ * Gate A (config-correctness gate at engine change): human-readable
16403
+ * config issues surfaced EAGERLY when the node's engine changes — model
16404
+ * substitutions ("chose X, running Y") and zero-build steps ("no model
16405
+ * has a <format> build"). Additive/optional: informational only, never
16406
+ * enforced here `assertEngineReady` (readiness) still gates inference.
16407
+ * Absent/empty when the node-default tree resolves cleanly.
16408
+ */
16409
+ configIssues: array(string()).optional()
16489
16410
  });
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(),
16411
+ var PipelineStepInputSchema = lazy(() => object({
16412
+ addonId: string(),
16505
16413
  modelId: string().optional(),
16506
- decidedAt: number(),
16414
+ enabled: boolean().default(true),
16415
+ children: array(PipelineStepInputSchema).optional(),
16416
+ settings: record(string(), unknown()).optional(),
16417
+ jumpDeviceKey: string().optional()
16418
+ }));
16419
+ var ModelSubstitutionSchema = object({
16420
+ addonId: string(),
16421
+ chosen: string(),
16422
+ running: string(),
16423
+ format: string()
16424
+ });
16425
+ var PipelineValidationIssueSchema = object({
16426
+ addonId: string(),
16427
+ kind: _enum(["unknown-addon", "no-format-build"]),
16428
+ detail: string()
16429
+ });
16430
+ var PipelineValidationResultSchema = object({
16431
+ ok: boolean(),
16432
+ issues: array(PipelineValidationIssueSchema).readonly(),
16433
+ substitutions: array(ModelSubstitutionSchema).readonly(),
16434
+ /** The node's `currentEngine.format` this validation ran against. */
16435
+ format: string()
16436
+ });
16437
+ var ReferenceImageEntrySchema = object({
16438
+ filename: string(),
16439
+ stepIds: array(string()).readonly().optional()
16440
+ });
16441
+ var ReferenceImageBodySchema = object({
16442
+ base64: string(),
16443
+ filename: string()
16444
+ });
16445
+ var ReferenceAudioEntrySchema = object({
16446
+ filename: string(),
16447
+ sizeKb: number()
16448
+ });
16449
+ var ReferenceAudioBodySchema = object({ base64: string() });
16450
+ var AudioBackendSchema = object({
16451
+ id: string(),
16452
+ name: string(),
16453
+ description: string(),
16454
+ available: boolean(),
16507
16455
  /**
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.
16456
+ * Raw classifier labels this backend can emit (e.g. YAMNet's
16457
+ * 521-class set or Apple SoundAnalysis's 303-class set). Used by
16458
+ * the benchmark UI to populate the `enabledMicroClasses` filter
16459
+ * specific to the selected backend without a separate fetch.
16519
16460
  */
16520
- identityId: string().optional()
16461
+ rawLabels: array(string()).readonly().optional()
16462
+ });
16463
+ var AudioCapabilitiesSchema = object({
16464
+ activeBackend: string(),
16465
+ availableBackends: array(AudioBackendSchema).readonly(),
16466
+ sampleRate: number(),
16467
+ chunkDurationMs: number()
16468
+ });
16469
+ var DownloadModelResultSchema = object({
16470
+ filePath: string(),
16471
+ sizeMB: number(),
16472
+ durationMs: number()
16521
16473
  });
16522
16474
  /**
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.
16475
+ * Wrapper carrying a single test run's result. Replaces the legacy
16476
+ * ad-hoc `{labels: [{className, originalClass, score}]}` shape with the
16477
+ * canonical `AudioResult` from the Phase 6 output rework: one
16478
+ * `AudioDetection` per class above `minScore`, top-N candidates in
16479
+ * `debug.alternateLabels['audio-classifier']`, per-source timings in
16480
+ * `debug.stepTimings`. The outer `success`/`error` fields stay so the
16481
+ * benchmark UI can still report a clean failure when the classifier
16482
+ * cap isn't available.
16568
16483
  */
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()
16484
+ var AudioTestResultSchema = object({
16485
+ success: boolean(),
16486
+ error: string().optional(),
16487
+ frame: custom().optional()
16577
16488
  });
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(),
16489
+ var PipelineConfigBridge = custom();
16490
+ var ConfigUISchemaBridge = custom();
16491
+ var ConfigUISchemaNullableBridge = custom();
16492
+ var InferenceCapabilitiesBridge = custom();
16493
+ var ModelAvailabilityListBridge = custom();
16494
+ var PipelineRunResultBridge = custom();
16495
+ method(_void(), array(PipelineEngineChoiceSchema)), method(_void(), PipelineEngineChoiceSchema), method(PipelineEngineChoiceSchema, array(PipelineDefaultStepSchema)), method(object({ nodeId: string() }), EngineProvisioningSchema), method(_void(), record(string(), object({
16496
+ modelId: string(),
16497
+ settings: record(string(), unknown()).readonly()
16498
+ }))), method(object({ steps: record(string(), object({
16499
+ modelId: string(),
16500
+ settings: record(string(), unknown()).readonly()
16501
+ })) }), object({ success: literal(true) }), {
16502
+ kind: "mutation",
16503
+ auth: "admin"
16504
+ }), method(object({ nodeId: string() }), object({
16505
+ success: literal(true),
16506
+ clearedDevices: number()
16507
+ }), {
16508
+ kind: "mutation",
16509
+ auth: "admin"
16510
+ }), method(object({ nodeId: string() }), object({ unhealthy: array(object({
16511
+ /** `<backend>:<device>`, e.g. `openvino:gpu`. */
16512
+ deviceKey: string(),
16595
16513
  /**
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.
16514
+ * `failed` the per-device restart budget is exhausted; no pool
16515
+ * will be spawned until an operator re-arms it or the runner
16516
+ * respawns. `backoff` — under budget, waiting out the backoff (or
16517
+ * a cached pool observed dead and not yet condemned).
16611
16518
  */
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(),
16519
+ state: _enum(["failed", "backoff"]),
16520
+ /** Epoch ms of the death that produced this state. */
16521
+ since: number(),
16522
+ /** Pool deaths inside the current window. */
16523
+ deaths: number(),
16524
+ /** The last death's message. */
16525
+ lastError: string()
16526
+ })).readonly() })), method(object({
16527
+ nodeId: string(),
16528
+ deviceKey: string()
16529
+ }), object({ rearmed: boolean() }), {
16530
+ kind: "mutation",
16531
+ auth: "admin"
16532
+ }), 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({
16533
+ name: string(),
16534
+ steps: array(PipelineTemplateStepSchema).readonly(),
16535
+ engine: PipelineEngineChoiceSchema
16536
+ }), PipelineTemplateSchema$1, { kind: "mutation" }), method(object({
16537
+ id: string(),
16538
+ name: string().optional(),
16539
+ steps: array(PipelineTemplateStepSchema).readonly().optional()
16540
+ }), PipelineTemplateSchema$1, { kind: "mutation" }), method(object({ id: string() }), _void(), { kind: "mutation" }), method(_void(), InferenceCapabilitiesBridge), method(object({ addonId: string() }), ModelAvailabilityListBridge), method(object({
16541
+ addonId: string(),
16542
+ modelId: string(),
16543
+ format: ModelFormatSchema$1
16544
+ }), DownloadModelResultSchema, { kind: "mutation" }), method(object({
16545
+ addonId: string(),
16546
+ modelId: string(),
16547
+ format: ModelFormatSchema$1
16548
+ }), object({ success: literal(true) }), { kind: "mutation" }), method(object({
16549
+ engine: PipelineEngineChoiceSchema.optional(),
16550
+ steps: array(PipelineStepInputSchema).min(1),
16551
+ frame: FrameInputSchema.optional(),
16639
16552
  /**
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".
16553
+ * Process-local lazy frame. Valid only when caller and provider resolve
16554
+ * in the same execution-group process; split/cross-node callers use
16555
+ * `frame`/`image` inline compatibility instead.
16655
16556
  */
16656
- hasFace: boolean().optional(),
16557
+ frameRef: FrameRefSchema.optional(),
16657
16558
  /**
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".
16559
+ * CB5 shm passthrough a `FrameHandle` naming the same ring slot
16560
+ * the decoded pixels live in. One more member of the one-of
16561
+ * frame/frameHandle/image/imageBase64/referenceImage group.
16684
16562
  */
16685
- hasEmbeddedFace: boolean().optional(),
16563
+ frameHandle: FrameHandleSchema.optional(),
16564
+ imageBase64: string().optional(),
16686
16565
  /**
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".
16566
+ * Binary JPEG bytespreferred over `imageBase64` on internal
16567
+ * hops (hub forked worker via Moleculer MsgPack) because it
16568
+ * skips the 33% base64 overhead + the per-call base64 decode on
16569
+ * the detection-pipeline worker. Callers can pass either; exactly
16570
+ * one of `frame`/`image`/`imageBase64`/`referenceImage` is required.
16706
16571
  */
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
- });
16572
+ image: _instanceof(Uint8Array).optional(),
16573
+ referenceImage: string().optional(),
16574
+ deviceId: number().optional(),
16575
+ sessionId: string().optional(),
16576
+ /**
16577
+ * Execution plane. 'full' (default) runs the whole tree — benchmark,
16578
+ * reference-image, and detail-subtree calls. 'frame' is the live
16579
+ * per-frame dispatch: ONLY root-plane steps run; crop children
16580
+ * (inputClasses ≠ null) are skipped and served per-track via
16581
+ * pipelineRunner.runDetailSubtree (two-plane design).
16582
+ */
16583
+ plane: _enum(["full", "frame"]).optional(),
16584
+ /**
16585
+ * Inference-device selector (Phase 2 multi-device). Format
16586
+ * `<backend>:<device>` (e.g. `openvino:gpu`, `edgetpu:usb`, `cpu`).
16587
+ * Omitted ⇒ the runner's default device (current single-engine
16588
+ * behaviour). Selects WHICH device pool of the node runs the call.
16589
+ */
16590
+ deviceKey: string().optional(),
16591
+ /**
16592
+ * Two-plane NATIVE child-crop reference. Set by `runDetailSubtree` ONLY
16593
+ * when the parent crop was resolved from the frame's retained NATIVE
16594
+ * surface (a frameHandle HIT). Lets the executor re-cut a LEAF crop
16595
+ * child's ROI (plate-ocr, face-embedding, leaf classifiers) at native
16596
+ * resolution from that surface — the SAME quality path faces already
16597
+ * had — instead of the downscaled parent tile. `handle` keys the native
16598
+ * surface (node-pinned to its owner); `cropFrameSpace` is the parent
16599
+ * crop's padded/clamped rectangle in FRAME-space pixels, used to compose
16600
+ * the executor's crop-normalized child ROI back into frame-normalized
16601
+ * coordinates. Auxiliary to the image source (`image`/`frame`/…), NOT one
16602
+ * of the mutually-exclusive image inputs. Absent ⇒ tile-crop children
16603
+ * (today's behaviour on the fallback path).
16604
+ */
16605
+ nativeCropRef: NativeCropRefSchema.optional()
16606
+ }), PipelineRunResultBridge, { kind: "mutation" }), method(object({
16607
+ engine: PipelineEngineChoiceSchema.optional(),
16608
+ steps: array(PipelineStepInputSchema).min(1),
16609
+ frames: array(FrameInputSchema).min(1).max(255),
16610
+ deviceId: number().optional(),
16611
+ sessionId: string().optional(),
16612
+ /**
16613
+ * Pure-inference benchmark hint. A NONZERO uint32 pins every frame in
16614
+ * the batch to the Python pool's bench preprocess cache
16615
+ * (`_bench_frame_id`) so a REPEATED benchmark frame is decoded +
16616
+ * preprocessed ONCE and every later inference is a pure-inference cache
16617
+ * hit — the sustained-throughput run measures inference, not
16618
+ * decode+preprocess+infer. Omitted/0 for live frames (all different →
16619
+ * full preprocess every call, correct). Fresh per sustained run;
16620
+ * released via `uncacheFrame`.
16621
+ */
16622
+ frameId: number().int().nonnegative().optional(),
16623
+ /** Inference-device selector (Phase 2 multi-device); see runPipeline. */
16624
+ deviceKey: string().optional()
16625
+ }), object({ results: array(PipelineRunResultBridge).readonly() }), { kind: "mutation" }), method(object({
16626
+ data: _instanceof(Uint8Array),
16627
+ width: number().int().positive(),
16628
+ height: number().int().positive(),
16629
+ format: _enum([
16630
+ "rgb",
16631
+ "bgr",
16632
+ "gray"
16633
+ ])
16634
+ }), object({
16635
+ frameId: number(),
16636
+ width: number(),
16637
+ height: number()
16638
+ }), { kind: "mutation" }), method(object({
16639
+ stepId: string(),
16640
+ frameId: number().int()
16641
+ }), record(string(), unknown()), { kind: "mutation" }), method(object({ frameId: number().int() }), _void(), { kind: "mutation" }), method(_void(), object({
16642
+ batchMode: string(),
16643
+ windowMs: number(),
16644
+ maxBatchSize: number(),
16645
+ concurrency: number()
16646
+ })), method(_void(), array(object({
16647
+ engineKey: string(),
16648
+ engine: PipelineEngineChoiceSchema,
16649
+ modelsLoaded: array(string()).readonly(),
16650
+ inUseByCameras: array(number()).readonly(),
16651
+ /**
16652
+ * Origin of this resident factory.
16653
+ * - `runtime` — main camera-serving engine (no idle TTL).
16654
+ * - `warm-override` — benchmark/test override held in the warm
16655
+ * cache; auto-disposed after the idle TTL.
16656
+ * - `device-pool` — a concurrent per-device pool (Phase 2
16657
+ * multi-device, keyed by `deviceKey`) resolved
16658
+ * via `resolveDeviceFactory`. Runs alongside the
16659
+ * `runtime` engine on a DIFFERENT accelerator
16660
+ * (NPU / iGPU / Coral) — this is how the
16661
+ * Engines tab shows all pools running at once.
16662
+ */
16663
+ kind: _enum([
16664
+ "runtime",
16665
+ "warm-override",
16666
+ "device-pool"
16667
+ ]),
16668
+ /** Native pid of the underlying Python pool (null when no pool). */
16669
+ poolPid: number().nullable(),
16670
+ /** ms since this factory was last used (null when not warm-tracked). */
16671
+ idleMs: number().nullable(),
16672
+ /** Idle TTL after which `warm-override` factories self-evict (null when not applicable). */
16673
+ idleTtlMs: number().nullable()
16674
+ })).readonly()), method(object({ engine: PipelineEngineChoiceSchema }), object({ success: literal(true) }), {
16675
+ kind: "mutation",
16676
+ auth: "admin"
16677
+ }), method(object({
16678
+ engine: PipelineEngineChoiceSchema,
16679
+ force: boolean().optional()
16680
+ }), object({
16681
+ success: boolean(),
16682
+ reason: string().optional()
16683
+ }), {
16684
+ kind: "mutation",
16685
+ auth: "admin"
16686
+ }), 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({
16687
+ addonId: string(),
16688
+ modelId: string(),
16689
+ filename: string().optional(),
16690
+ settings: record(string(), unknown()).optional()
16691
+ }), AudioTestResultSchema, { kind: "mutation" }), method(_void(), ConfigUISchemaNullableBridge);
16733
16692
  /**
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`.
16693
+ * Per-stage gating mode applied to the zones a rule references.
16694
+ *
16695
+ * - `include`: the rule contributes to a **whitelist** for its stage.
16696
+ * When at least one `include` rule fires for a stage, only entities
16697
+ * inside one of those zones pass that stage.
16698
+ * - `exclude`: the rule contributes to a **blacklist** for its stage.
16699
+ * Entities inside one of those zones are dropped at that stage.
16700
+ *
16701
+ * `monitor`-style observation (count without filtering) is not a rule
16702
+ * mode — zones without any matching rule are observed naturally by
16703
+ * `zone-analytics` (live snapshot + history), so an "I just want to
16704
+ * count, not filter" use case needs no rule at all.
16740
16705
  */
16741
- var DetectionSourceSchema = _enum(["pipeline", "onboard"]);
16706
+ var ZoneRuleModeEnum = _enum(["include", "exclude"]);
16742
16707
  /**
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.
16708
+ * Per-consumer rule that references existing zones (geometry) and
16709
+ * defines how a specific pipeline stage should treat them. Each
16710
+ * consumer addon owns its own `ZoneRule[]` array in its per-device
16711
+ * settings:
16748
16712
  *
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.
16713
+ * - `addon-motion-wasm` `motionZoneRules: ZoneRule[]` (motion stage)
16714
+ * - `addon-detection-pipeline` `detectionZoneRules: ZoneRule[]` (detection stage)
16715
+ * - future: notification rules, audio gating, etc.
16752
16716
  *
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.
16717
+ * One rule applies to N zones (`zoneIds[]`) so the operator can
16718
+ * express "ignore motion in ALL of {garden, street}" with a single
16719
+ * rule. `classFilter` narrows the rule to specific object classes
16720
+ * "drop person detections in the street, but keep cars" is one
16721
+ * `exclude` rule with `classFilter: ['person']`.
16722
+ *
16723
+ * `enabled` is a soft toggle — the operator can keep the rule
16724
+ * configured but inert without deleting it.
16757
16725
  */
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(),
16726
+ var ZoneRuleSchema = object({
16727
+ /** Stable rule id — survives edits, used by the UI for diffing. */
16728
+ id: string(),
16729
+ /** Optional human-readable label rendered in the rule editor. */
16730
+ name: string().optional(),
16731
+ /** Zones this rule targets. The rule's `mode` applies to ALL
16732
+ * listed zones (OR-set: a detection in any one of them counts).
16733
+ * At least one zone id required — a rule with no targets is a
16734
+ * configuration mistake and the form validator rejects it. */
16735
+ zoneIds: array(string()).min(1).readonly(),
16736
+ mode: ZoneRuleModeEnum,
16770
16737
  /**
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.
16738
+ * Class names this rule applies to. Empty / undefined rule
16739
+ * applies to every class. Class strings match the `macroClass`
16740
+ * field on detections (e.g. `person`, `car`, `dog`).
16777
16741
  */
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(),
16742
+ classFilter: array(string()).readonly().optional(),
16791
16743
  /**
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.
16744
+ * Minimum bbox/mask overlap (0–1) with any of the rule's zones
16745
+ * required to consider an entity "in the zone". Defaults to the
16746
+ * consumer's stage default when omitted. Kept for back-compat with
16747
+ * existing per-rule overrides; new operators pick the value via
16748
+ * `bboxInclusionPct` (operator-friendly 0–100). Whichever field is
16749
+ * set, the lower-level engine reads it as a 0–1 fraction.
16795
16750
  */
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()
16751
+ overlapThreshold: number().min(0).max(1).optional(),
16752
+ /**
16753
+ * Operator-friendly version of `overlapThreshold` the percentage
16754
+ * of the detection's bbox that must lie inside the zone for the
16755
+ * rule to match. Documented default is 85%; the engine substitutes
16756
+ * that when the field is omitted (kept optional so existing rules
16757
+ * stored without it stay valid).
16758
+ *
16759
+ * When BOTH `overlapThreshold` and `bboxInclusionPct` are set on a
16760
+ * rule, the engine prefers `bboxInclusionPct` because it's the
16761
+ * field exposed in the UI. Internally both feed the same gate.
16762
+ */
16763
+ bboxInclusionPct: number().min(0).max(100).optional(),
16764
+ /**
16765
+ * When `true` and a detection has a segmentation mask, use the
16766
+ * mask for overlap instead of the bbox. Detection-stage only;
16767
+ * motion rules ignore this field.
16768
+ */
16769
+ preferMask: boolean().optional(),
16770
+ /**
16771
+ * Soft-toggle: `false` disables the rule without deleting it.
16772
+ * Defaults to `true` so operators creating a rule via the UI
16773
+ * see it active immediately.
16774
+ */
16775
+ enabled: boolean().default(true)
16849
16776
  });
16777
+ array(ZoneRuleSchema).readonly();
16850
16778
  /**
16851
- * One media row WITHOUT its bytes.
16779
+ * Zone pure geometry + identity. NO filtering behaviour.
16852
16780
  *
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.
16781
+ * Zones describe **where** in the frame the operator wants to flag
16782
+ * something; consumer-owned {@link ZoneRule} arrays describe **how**
16783
+ * each pipeline stage uses them. Splitting the two means a single
16784
+ * polygon "Driveway" can simultaneously back a motion-exclude rule,
16785
+ * a detection-include rule on `['car']`, and an occupancy aggregate
16786
+ * — without three duplicated polygons.
16858
16787
  *
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.
16788
+ * Owned by the orchestrator addon (provider) and mirrored into the
16789
+ * `zones` device-state slice on every mutation. Consumers
16790
+ * (motion-wasm, pipeline-executor, analytics, admin UI) read either
16791
+ * via `api.zones.listZones` (one-shot) or via `dev.state.zones` (live
16792
+ * mirror with `onChanged`).
16793
+ *
16794
+ * Coordinates are normalised fractions of the frame (0–1) so zones
16795
+ * survive resolution changes and stream profile switches.
16796
+ *
16797
+ * `kind` discriminates between full polygons (closed regions used
16798
+ * for intrusion / occupancy filters) and tripwires (open 2-point
16799
+ * line segments used for cross events). Onboard / firmware-reported
16800
+ * zones (Reolink, ONVIF) are out of scope for now — see the deferred
16801
+ * task list.
16861
16802
  */
16862
- var MediaFileInfoSchema = MediaFileSchema.omit({ base64: true });
16803
+ var ZoneKindEnum = _enum(["polygon", "tripwire"]);
16804
+ /** Polygon vertex in fraction-of-frame coordinates (0–1). */
16805
+ var PolygonPointSchema = object({
16806
+ x: number(),
16807
+ y: number()
16808
+ });
16809
+ /** A camera detection zone — pure geometry/identity. */
16810
+ var ZoneSchema = object({
16811
+ id: string(),
16812
+ name: string(),
16813
+ kind: ZoneKindEnum.default("polygon"),
16814
+ /** Polygon vertices, fraction of frame (0–1). */
16815
+ polygon: array(PolygonPointSchema).readonly(),
16816
+ /** Visual color for UI rendering. */
16817
+ color: string().default("#3b82f6")
16818
+ });
16819
+ DeviceType.Camera, method(object({ deviceId: number() }), array(ZoneSchema).readonly()), method(object({
16820
+ deviceId: number(),
16821
+ zone: ZoneSchema
16822
+ }), _void(), {
16823
+ kind: "mutation",
16824
+ auth: "admin"
16825
+ }), method(object({
16826
+ deviceId: number(),
16827
+ zoneId: string()
16828
+ }), _void(), {
16829
+ kind: "mutation",
16830
+ auth: "admin"
16831
+ }), method(object({
16832
+ deviceId: number(),
16833
+ zone: ZoneSchema
16834
+ }), _void(), {
16835
+ kind: "mutation",
16836
+ auth: "admin"
16837
+ }), object({ zones: array(ZoneSchema).readonly() });
16863
16838
  /**
16864
- * The MACRO tier of an annotation — a CLOSED set.
16839
+ * pipeline-analytics device-scoped wrapper cap. Refines raw
16840
+ * per-frame detections emitted by the pipeline runner into tracked
16841
+ * objects, per-kind event collections (motion / object / audio), and
16842
+ * persisted media. Owns the post-detection domain end-to-end:
16865
16843
  *
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.
16844
+ * runner emits PipelineInferenceResult
16845
+ * (event bus)
16846
+ * pipeline-analytics subscriber
16847
+ * SORT tracker + zone engine + state analyzer + event emitter
16848
+ * → three DB collections (one per kind), one FS media tree, one
16849
+ * unified event emitter (FrameTracked + TrackStarted/Ended +
16850
+ * DetectionEvent on bus)
16870
16851
  *
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.
16852
+ * Pure subscriber model. No `processFrame` cap method the runner
16853
+ * already publishes the raw frame on the bus. The cap surface is
16854
+ * only QUERIES + per-device settings, bound on/off via
16855
+ * `device-manager.setWrapperActive`. `defaultActive: true` because
16856
+ * every camera with a detection pipeline wants its raw detections
16857
+ * refined; operators opt out per-device via BindingsTab when needed.
16858
+ *
16859
+ * Replaces the legacy `analysis-pipeline`, `analysis-data-persistence`
16860
+ * (per-device surface) and `track-trail` caps — see P11 cleanup.
16875
16861
  */
16876
- var RetrainMacroClassSchema = _enum([
16862
+ var TrackStateSchema = _enum([
16863
+ "new",
16864
+ "entered",
16865
+ "left",
16866
+ "moving",
16867
+ "idle"
16868
+ ]);
16869
+ var EventKindSchema = _enum([
16870
+ "motion",
16871
+ "object",
16872
+ "audio"
16873
+ ]);
16874
+ /**
16875
+ * Spatial filter for `listTracks` — the rect + polygon variants of the shared
16876
+ * MaskShape vocabulary (see `mask-shape.ts`). Coordinates are NORMALIZED 0..1
16877
+ * of the camera frame (top-left origin), matching the drawing-plane editor.
16878
+ */
16879
+ var TrackZoneFilterSchema = discriminatedUnion("kind", [MaskRectShapeSchema, MaskPolygonShapeSchema]);
16880
+ /** Closed icon vocabulary so clients render a known glyph per kind. */
16881
+ var EventKindIconSchema = _enum([
16882
+ "motion",
16883
+ "audio",
16877
16884
  "person",
16878
16885
  "vehicle",
16879
16886
  "animal",
16887
+ "door",
16888
+ "pir",
16889
+ "smoke",
16890
+ "water",
16891
+ "button",
16880
16892
  "package",
16881
- "face",
16882
- "plate"
16893
+ "generic"
16883
16894
  ]);
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({
16895
+ var EventKindCategorySchema = _enum([
16896
+ "motion",
16897
+ "audio",
16898
+ "detection",
16899
+ "sensor",
16900
+ "control",
16901
+ "custom",
16902
+ "package"
16903
+ ]);
16904
+ /** Taxonomy level — macro (timeline lane) vs sub (events-page leaf). */
16905
+ var EventKindLevelSchema = _enum(["macro", "sub"]);
16906
+ var EventKindDescriptorSchema = object({
16907
+ /** Stable kind id (e.g. 'motion', 'vehicle', 'car', 'lock'). */
16908
+ kind: string(),
16909
+ /** i18n key resolved on the UI side; `label` is the English fallback. */
16910
+ labelKey: string(),
16911
+ /** English fallback label (kept for clients that don't translate). */
16912
+ label: string(),
16913
+ /** Hex color for timeline/legend rendering. */
16914
+ color: string(),
16915
+ /** Dictionary id → lucide component on the UI side. */
16916
+ iconId: string(),
16917
+ /** Legacy closed-vocab glyph — fallback for `iconId`. */
16918
+ icon: EventKindIconSchema,
16919
+ category: EventKindCategorySchema,
16920
+ /** Macro parent for this kind ('car' → 'vehicle'); null for a macro. */
16921
+ parentKind: string().nullable(),
16922
+ /** Derived from `parentKind`, explicit for the client tree. */
16923
+ level: EventKindLevelSchema,
16924
+ /** Which cap + device contributes this kind. For built-ins the camera
16925
+ * itself; for sensor kinds the LINKED source device. */
16926
+ source: object({
16927
+ capName: string(),
16928
+ deviceId: number()
16929
+ })
16930
+ });
16931
+ /** One camera's event vocabulary, as returned by `listEventKindsBatch`. */
16932
+ var EventKindsForDeviceSchema = object({
16933
+ deviceId: number(),
16934
+ kinds: array(EventKindDescriptorSchema).readonly()
16935
+ });
16936
+ var SensorEventSchema = object({
16937
+ id: string(),
16938
+ /** The CAMERA the event is attributed to (a sensor linked to N cameras
16939
+ * yields N rows, one per camera). */
16940
+ deviceId: number(),
16941
+ /** The linked sensor device whose state changed. */
16942
+ sourceDeviceId: number(),
16943
+ /** Event kind id — matches an `EventKindDescriptor.kind`. */
16944
+ kind: string(),
16945
+ /** Snapshot of the sensor cap's runtime-state slice at the change. */
16946
+ value: record(string(), unknown()).nullable(),
16947
+ timestamp: number()
16948
+ });
16949
+ var TrackPositionSchema = object({
16890
16950
  x: number(),
16891
16951
  y: number(),
16892
- w: number(),
16893
- h: number()
16952
+ timestamp: number(),
16953
+ bbox: BoundingBoxSchema
16954
+ });
16955
+ var TrackSnapshotSchema = object({
16956
+ timestamp: number(),
16957
+ position: TrackPositionSchema,
16958
+ /** MediaStore key; resolve via `getTrackMedia({ trackId })`. */
16959
+ mediaKey: string()
16894
16960
  });
16895
16961
  /**
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).
16902
- */
16903
- var RetrainAnnotationSchema = object({
16904
- id: string(),
16962
+ * Normalized 0..1 trajectory envelope (min/max over every position bbox,
16963
+ * divided by the track's detection-frame dims), computed at persist time.
16964
+ * Absent when the frame dims were unknown when the track was persisted
16965
+ * (legacy rows / dims-less sources) and on active (in-RAM) tracks.
16966
+ */
16967
+ var TrackEnvelopeSchema = object({
16968
+ minX: number(),
16969
+ minY: number(),
16970
+ maxX: number(),
16971
+ maxY: number()
16972
+ });
16973
+ /**
16974
+ * Row projection for track list queries. `full` (default) returns the
16975
+ * complete Track including the frame-rate `positions[]` history and the
16976
+ * `snapshots[]` references — megabytes across a page of tracks. `slim`
16977
+ * keeps every scalar the list surfaces actually render (ids, class(es),
16978
+ * label / audioLabels / importance enrichment, firstSeen/lastSeen, state,
16979
+ * zonesVisited, bestEventId, envelope, hasFace, hasEmbeddedFace, hasRider) and returns `positions` /
16980
+ * `snapshots` as EMPTY arrays — detail views re-fetch the full row via
16981
+ * `getTrack`. Mirrors the event-store `projection` convention
16982
+ * (`getObjectEvents` et al.).
16983
+ */
16984
+ var TrackProjectionSchema = _enum(["full", "slim"]);
16985
+ /**
16986
+ * One audio-classification label heard on the track's camera while the
16987
+ * track was alive, aggregated per label. An "episode" is one persisted
16988
+ * audio event (the confident-classification path: score ≥ the device's
16989
+ * `classificationMinScore`, class-change-or-heartbeat coalesced) — NOT
16990
+ * one 32 ms inference chunk, so counts stay human-scaled.
16991
+ */
16992
+ var TrackAudioLabelSchema = object({
16993
+ label: string(),
16994
+ /** Highest classification score observed across the label's episodes. */
16995
+ peakScore: number(),
16996
+ /** Number of coalesced audio-event episodes carrying this label. */
16997
+ count: number(),
16998
+ firstAt: number(),
16999
+ lastAt: number()
17000
+ });
17001
+ /**
17002
+ * How a track was produced. `pipeline` (default / absent) = the spatial
17003
+ * detection+tracking pipeline. Every OTHER value is a SYNTHETIC projection —
17004
+ * no positions, a single snapshot, and no bbox trajectory at all:
17005
+ *
17006
+ * - `sensor` — a linked sensor/control device state change.
17007
+ * - `audio` — an audio event on the camera itself that was anomalous for
17008
+ * THAT camera, loud, and heard while nothing visual was happening (D62).
17009
+ *
17010
+ * The spatial subsystems (tracker association, occupancy count, re-id /
17011
+ * embedding, resurrection) MUST skip every synthetic source. Test for that
17012
+ * with `isSpatialTrack`, which allow-lists `pipeline` — a `!== 'sensor'`
17013
+ * check silently readmits every source added after it was written.
17014
+ */
17015
+ var TrackSourceSchema = _enum([
17016
+ "pipeline",
17017
+ "sensor",
17018
+ "audio"
17019
+ ]);
17020
+ /**
17021
+ * Where a track sits in the RETRAIN lifecycle (D81).
17022
+ *
17023
+ * - `none` — never marked, or un-marked. Evictable.
17024
+ * - `staging` — the operator wants this track as training material and has not
17025
+ * finished with it. **This is the only state retention holds**: the track and
17026
+ * everything it owns (object events, crops, keyframes, CLIP vector) survive
17027
+ * the device's age window.
17028
+ * - `trained` — the retrain page has taken what it needed. The frames it chose
17029
+ * were COPIED into the retrain dataset at selection time, so the dataset no
17030
+ * longer depends on the track's media and the track becomes EVICTABLE again.
17031
+ * Terminal for the plain `markForTrain` toggle: returning it to `staging` is
17032
+ * a deliberate action of the retrain page, not a side effect of a checkbox.
17033
+ *
17034
+ * There is no `null`. The state is stored `TEXT NOT NULL DEFAULT 'none'` because
17035
+ * the store's filter language has only positive equality and `whereIn` — no
17036
+ * negation, no IS NULL — so a NULL would be unselectable by ANY predicate and
17037
+ * would make the entire pre-column history immortal in one deploy.
17038
+ */
17039
+ var RetrainStatusSchema = _enum([
17040
+ "none",
17041
+ "staging",
17042
+ "trained"
17043
+ ]);
17044
+ /**
17045
+ * Per-track OPERATOR flags — set by hand from the admin UI or the viewer, never
17046
+ * by the pipeline. Spread into `TrackSchema` and `KeyEventSchema` from one place
17047
+ * so the two surfaces cannot drift.
17048
+ *
17049
+ * **Absent ≠ false.** A track that has never been touched omits the field; an
17050
+ * explicitly un-flagged track carries `false`. Legacy rows written before the
17051
+ * columns existed read as absent, and a consumer that needs a boolean should say
17052
+ * `flag === true`, not `flag !== false`.
17053
+ *
17054
+ * `markForTrain` is the WIRE FACE of {@link RetrainStatusSchema}, not a column:
17055
+ * it is exactly `retrainStatus === 'staging'`, in both directions. Writing
17056
+ * `true` moves `none → staging`, writing `false` moves `staging → none`, and a
17057
+ * `trained` track reports `false` while refusing both writes. The boolean is
17058
+ * kept because three surfaces drive a toggle off it; anything that needs to tell
17059
+ * "never marked" from "already trained" must read `retrainStatus`.
17060
+ *
17061
+ * `debug` does NOT pin; it is attention, not durability.
17062
+ *
17063
+ * `favourited` IS a BOOLEAN pin (durability bit), not a retrain lifecycle.
17064
+ * A favourited track is skipped by retention the same way `staging` is, but
17065
+ * it does not enter `none|staging|trained` and has no staging budget.
17066
+ */
17067
+ var TrackFlagFields = {
17068
+ /** Operator marked this track as training material — i.e. `retrainStatus` is
17069
+ * `'staging'`. */
17070
+ markForTrain: boolean().optional(),
17071
+ /** Operator marked this track for diagnostic attention. */
17072
+ debug: boolean().optional(),
17073
+ /** Operator favourited this track. Pins it against pruning. */
17074
+ favourited: boolean().optional()
17075
+ };
17076
+ /**
17077
+ * The lifecycle field itself, on the READ surfaces only (`Track`, `KeyEvent`).
17078
+ * Deliberately NOT part of {@link TrackFlagFields}: that group also builds the
17079
+ * write patch, and the status is not something the toggle sets — it is what the
17080
+ * toggle's boolean is derived from. Absent on an in-RAM track never touched;
17081
+ * always present on a persisted row (the column default materialises `'none'`).
17082
+ */
17083
+ var TrackRetrainFields = { retrainStatus: RetrainStatusSchema.optional() };
17084
+ /**
17085
+ * The write half: a PARTIAL patch. An omitted key is left untouched, so setting
17086
+ * one flag can never clear the other — the toggles are independent and are
17087
+ * driven from three surfaces that do not know about each other.
17088
+ */
17089
+ var TrackFlagsPatchSchema = object(TrackFlagFields);
17090
+ /**
17091
+ * The resolved flag state after a write. Both fields are REQUIRED here (absent
17092
+ * collapses to `false`) so a caller can drive a toggle's checked state off the
17093
+ * mutation result without a re-fetch.
17094
+ */
17095
+ var TrackFlagsSchema = object({
16905
17096
  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,
17097
+ markForTrain: boolean(),
17098
+ debug: boolean(),
17099
+ favourited: boolean(),
17100
+ /** The lifecycle state the boolean was derived from. Required here (unlike on
17101
+ * a track row) because this shape is only ever produced by the write body,
17102
+ * which always knows it — and a surface that has just written needs to render
17103
+ * `trained` without a re-fetch. */
17104
+ retrainStatus: RetrainStatusSchema
17105
+ });
17106
+ union([literal(1), literal(2)]);
17107
+ /**
17108
+ * WHO decided a label, and when. Carried per tier so a value can be traced to
17109
+ * the step and model that produced it — which is what makes the write rule
17110
+ * arguable after the fact ("why is 592's label `dog` and not `Canis lupus`?")
17111
+ * and what lets a migrated, UNATTRIBUTED value be told apart from a real one.
17112
+ *
17113
+ * `stepId` is the pipeline step id (`animal-classifier`, `bird-classifier`,
17114
+ * `plate-ocr`, `face-embedding`, `object-detection`), or the sentinel
17115
+ * `migration:4g` for a value the 4g migration moved from the single-slot era —
17116
+ * that value has no provenance, and the write rule lets ANY properly-attributed
17117
+ * write of the same tier replace it regardless of score.
17118
+ */
17119
+ var LabelAttributionSchema = object({
17120
+ stepId: string(),
17121
+ modelId: string().optional(),
17122
+ decidedAt: number(),
17123
+ /**
17124
+ * The GALLERY id behind a recognised tier-2 label — a face-gallery
17125
+ * `Identity.id` or a plate-gallery `Vehicle.id` (both `randomUUID`).
17126
+ *
17127
+ * The text alone is a DISPLAY NAME, and a display name is renameable: a
17128
+ * notification rule authored on "Gianluca" stopped matching the moment the
17129
+ * operator fixed the spelling in the gallery, and nothing said so. The id is
17130
+ * the thing that does not move, so it is what a rule matches on
17131
+ * (`NcConditions.identities`) and the text is what a human is shown.
17132
+ *
17133
+ * Absent when the label names no gallery row — a plate the OCR read but no
17134
+ * vehicle claims, a sub-class, a species, any tier-1 value.
17135
+ */
17136
+ identityId: string().optional()
17137
+ });
17138
+ /**
17139
+ * The TIERED label model (roadmap 4g), spread into `TrackSchema` and
17140
+ * `ObjectEventSchema` from ONE place so the two surfaces cannot drift — a
17141
+ * track and its events always answer the same question the same way.
17142
+ *
17143
+ * Two scalar columns, not an array: every consumer wants "the coarse one" or
17144
+ * "the fine one", and an array made both a scan. `label` is tier 1, `subLabel`
17145
+ * is tier 2, and each carries its own score + attribution.
17146
+ *
17147
+ * **Reading it.** What a human should be shown is `subLabel ?? label` — the
17148
+ * finest thing known. Before 4g the single `label` column held the finest
17149
+ * value, so a consumer that has not been updated reads the tier-1 slot and
17150
+ * shows nothing on a species-only row; that is why the migration puts every
17151
+ * pre-4g value in tier 2 (it cannot regress a display that reads the fallback)
17152
+ * and why the read surfaces were changed in the same train.
17153
+ *
17154
+ * **Writing it.** The slots are independent, which is the whole point: a
17155
+ * tier-1 write (`bird`) can never overwrite a tier-2 value (`Turdus
17156
+ * migratorius`), so fineness cannot regress by construction. Within a tier the
17157
+ * higher score wins. One rule, one implementation — see
17158
+ * `pipeline/label-tier.ts` in addon-post-analysis.
17159
+ */
17160
+ var TieredLabelFields = {
17161
+ /** Tier 1 — the sub-class. See {@link LabelTierSchema}. */
16911
17162
  label: string().optional(),
17163
+ /** Confidence of the tier-1 value, as reported by the deciding step. */
17164
+ labelScore: number().optional(),
17165
+ /** Provenance of the tier-1 value. See {@link LabelAttributionSchema}. */
17166
+ labelMeta: LabelAttributionSchema.optional(),
17167
+ /** Tier 2 — the instance. See {@link LabelTierSchema}. */
16912
17168
  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()
17169
+ /** Confidence of the tier-2 value, as reported by the deciding step. */
17170
+ subLabelScore: number().optional(),
17171
+ /** Provenance of the tier-2 value. See {@link LabelAttributionSchema}. */
17172
+ subLabelMeta: LabelAttributionSchema.optional()
17173
+ };
17174
+ /** Per-camera slice of a training-export estimate. */
17175
+ var TrainingExportDeviceTotalsSchema = object({
17176
+ deviceId: number(),
17177
+ tracks: number().int(),
17178
+ files: number().int(),
17179
+ bytes: number().int()
16920
17180
  });
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
17181
+ /**
17182
+ * What a training export WOULD contain. Computed from media index rows only —
17183
+ * no blob is read to produce this.
17184
+ */
17185
+ var TrainingExportSummarySchema = object({
17186
+ generatedAt: number(),
17187
+ trackCount: number().int(),
17188
+ fileCount: number().int(),
17189
+ byteCount: number().int(),
17190
+ /** More marked tracks exist than a single pass carries. */
17191
+ truncated: boolean(),
17192
+ devices: array(TrainingExportDeviceTotalsSchema).readonly()
16929
17193
  });
16930
- /** A track sitting in `staging`, with everything the worklist needs to rank it. */
16931
- var RetrainTrackSchema = object({
17194
+ var TrackSchema = object({
16932
17195
  trackId: string(),
16933
17196
  deviceId: number(),
16934
17197
  className: string(),
16935
- label: string().optional(),
17198
+ ...TieredLabelFields,
17199
+ producingDeviceName: string().optional(),
17200
+ /** Track provenance. Absent ⇒ `pipeline` (legacy rows). */
17201
+ source: TrackSourceSchema.optional(),
16936
17202
  firstSeen: number(),
16937
17203
  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()
17204
+ /** Frame-rate position history (subject to maxPositionHistory cap). */
17205
+ positions: array(TrackPositionSchema).readonly(),
17206
+ /** Periodic snapshots at snapshotIntervalMs cadence (subject to
17207
+ * saveThumbnails policy). */
17208
+ snapshots: array(TrackSnapshotSchema).readonly(),
17209
+ /** Deduplicated zones the track has entered at least once. Zone IDS. */
17210
+ zonesVisited: array(string()).readonly(),
17211
+ /**
17212
+ * Human NAMES for {@link zonesVisited}, resolved at READ time against the
17213
+ * `zones` capability.
17214
+ *
17215
+ * `zonesVisited` persists ids (`cfeec78c-8d69-…`), which no operator can type
17216
+ * and no card can render so every free-text search surface was structurally
17217
+ * unable to answer "show me the tracks in Uscio", and did not fail loudly, it
17218
+ * just returned nothing. Resolving here rather than in each client keeps ONE
17219
+ * derivation and costs the clients no extra call (the `zones` cap is
17220
+ * per-device, so a client-side resolve would be a per-camera fan-out on a
17221
+ * surface built to avoid exactly that).
17222
+ *
17223
+ * Resolved, never invented: a zone deleted since the track was written has no
17224
+ * name and is DROPPED, so this array can be shorter than `zonesVisited` — the
17225
+ * two are not positionally aligned. Absent when the track visited no zone, or
17226
+ * when the zone catalogue could not be read.
17227
+ */
17228
+ zoneNames: array(string()).readonly().optional(),
17229
+ /** Deduplicated set of detector classes observed for this track over its
17230
+ * life (a track may be reclassified, e.g. person→vehicle). Absent on
17231
+ * legacy rows written before class accumulation shipped. */
17232
+ classes: array(string()).readonly().optional(),
17233
+ /** Cumulative normalized distance travelled (0..1 units = full frame width). */
17234
+ totalDistance: number(),
17235
+ state: TrackStateSchema,
17236
+ active: boolean(),
17237
+ /** Deterministic key-event importance score in [0,1] (server-computed at
17238
+ * track expiry, recomputed on late label). Absent on legacy rows written
17239
+ * before scoring shipped — consumers degrade to absence / compute-on-read. */
17240
+ importance: number().optional(),
17241
+ /** Id of the track's highest-confidence ObjectEvent (its representative
17242
+ * "best" frame). Absent when the track produced no object events. */
17243
+ bestEventId: string().optional(),
17244
+ /** Tag of the importance sub-signal that dominated the score
17245
+ * (identity|dwell|proximity|class|confidence|travel|zone). */
17246
+ importanceReason: string().optional(),
17247
+ /** Audio-classification labels heard on the camera during the track's
17248
+ * life (score ≥ device `classificationMinScore`), aggregated per label.
17249
+ * Absent on legacy rows / tracks with no confident audio. */
17250
+ audioLabels: array(TrackAudioLabelSchema).readonly().optional(),
17251
+ /** Normalized 0..1 trajectory envelope (see {@link TrackEnvelopeSchema}).
17252
+ * Populated from the persisted envelope columns on historical reads;
17253
+ * absent on legacy rows, dims-less tracks and active (in-RAM) tracks. */
17254
+ envelope: TrackEnvelopeSchema.optional(),
17255
+ /**
17256
+ * A face DETECTOR found a face on this track — nothing more. It says the
17257
+ * detail plane produced a `face` detail; it does NOT say the face was
17258
+ * embedded, matched, above `minFacePx`, or that the recognizer was even
17259
+ * enabled. Set once and never cleared.
17260
+ *
17261
+ * **This exists so "face present but not recognised" is expressible.** A
17262
+ * recognised identity lands in `subLabel` (attributed to the face chain via
17263
+ * `subLabelMeta.stepId`), so before this field a track with an unmatched face
17264
+ * and a track with no face at all were byte-identical on the wire and no
17265
+ * surface could tell them apart. The read is `hasFace === true && subLabel
17266
+ * === undefined`.
17267
+ *
17268
+ * **Absent ≠ false.** Every row written before the column existed omits it,
17269
+ * and so does every server that predates the field — a consumer must test
17270
+ * `=== true` and render nothing otherwise, never infer "no face".
17271
+ */
17272
+ hasFace: boolean().optional(),
17273
+ /**
17274
+ * This track has a face row IN THE GALLERY: a crop **and** an embedding — a
17275
+ * face an operator could ASSIGN to an identity.
17276
+ *
17277
+ * The STRICT twin of {@link hasFace}, and the pair only earns its keep
17278
+ * because the two disagree. `hasFace` is stamped at the TOP of the face
17279
+ * branch, before every gate, and means no more than "a face detector produced
17280
+ * a face detail". This one is stamped at the single moment the gallery row
17281
+ * LANDS — after `FaceRecognizer.onTrackEnd` successfully persists it, i.e.
17282
+ * past the embedding-magnitude verdict, the `minFacePx` detection gate, the
17283
+ * candidate gate, the imageless-track drop (no crop was ever captured) and
17284
+ * the crop-store drop. Everything between the detector and that insert can
17285
+ * legitimately refuse the face, so a flag written any earlier promises the
17286
+ * operator something to assign and delivers nothing.
17287
+ *
17288
+ * **Independent of recognition.** A face collected but never auto-matched is
17289
+ * still assignable — it is in fact the face an operator most wants to reach —
17290
+ * so this is NOT gated on `recognizedIdentityId`. Recognition lands in
17291
+ * `subLabel`; this says only that the raw material exists.
17292
+ *
17293
+ * **Set once, never cleared.** A track that produced a gallery row produced
17294
+ * one; deleting the row later is the gallery's business, not this flag's.
17295
+ *
17296
+ * **Absent ≠ false**, the same rule as {@link hasFace}: every row written
17297
+ * before the column omits it, and so does every server that predates the
17298
+ * field. A consumer must test `=== true` and render nothing otherwise —
17299
+ * never infer "no assignable face".
17300
+ */
17301
+ hasEmbeddedFace: boolean().optional(),
17302
+ /**
17303
+ * This subject CONTAINS a folded rider — a person the rider-pairing step
17304
+ * ([D34](../decisions/adr-0034.md)) removed from the frame BEFORE the tracker,
17305
+ * so the passage is tracked once and as a VEHICLE.
17306
+ *
17307
+ * It exists because the fold's record was dishonest. D34 and the code both
17308
+ * said "the person is not lost — it is reported so both entities stay on the
17309
+ * record"; in fact the pair went into a per-processor RAM field behind an
17310
+ * accessor nobody called, and every durable surface said `vehicle`, full
17311
+ * stop. This is the composition note that makes the row true.
17312
+ *
17313
+ * A COMPOSITION, never a class and never a label. "This vehicle contains a
17314
+ * person" is not an answer to "what is this" — both label tiers would refuse
17315
+ * a macro token anyway (D89), and correctly. Nothing here changes what the
17316
+ * subject IS: a cyclist stays one vehicle track, occupancy still counts one,
17317
+ * and a `person` rule still does not fire for someone cycling past.
17318
+ *
17319
+ * **Absent ≠ false**, exactly like {@link hasFace}: every row written before
17320
+ * the column, and every hub that predates the field, omits it. Test
17321
+ * `=== true` and render nothing otherwise — never infer "no rider".
17322
+ */
17323
+ hasRider: boolean().optional(),
17324
+ ...TrackFlagFields,
17325
+ ...TrackRetrainFields
16953
17326
  });
16954
- /** A frame the dataset OWNS: bytes copied at selection time. */
16955
- var RetrainFrameSchema = object({
16956
- frameId: string(),
17327
+ var BaseEventFields = {
17328
+ id: string(),
16957
17329
  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()
17330
+ timestamp: number()
17331
+ };
17332
+ var MotionEventSchema = object({
17333
+ ...BaseEventFields,
17334
+ kind: literal("motion"),
17335
+ regionCount: number(),
17336
+ /** Heavy JSON array — omitted in slim projection. */
17337
+ regions: array(object({
17338
+ bbox: BoundingBoxSchema,
17339
+ pixelCount: number(),
17340
+ intensity: number()
17341
+ })).readonly().optional(),
17342
+ /** Omitted in slim projection. */
17343
+ frameWidth: number().optional(),
17344
+ /** Omitted in slim projection. */
17345
+ frameHeight: number().optional(),
17346
+ /** Populated by B5 (recording playback URL for this event). */
17347
+ mediaUrl: string().optional()
16985
17348
  });
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
17349
  /**
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.
17350
+ * Which detection SOURCE produced an object event. `pipeline` = the ML
17351
+ * detection pipeline (decoded-frame inference); `onboard` = the camera's
17352
+ * native on-device AI. Both flow through the SAME analysis layers (zoning,
17353
+ * tracking, per-kind persistence) but stay distinguishable so consumers
17354
+ * (advanced-notifier, occupancy, …) can select which source(s) to act on.
17355
+ * Absent on legacy rows ⇒ treat as `pipeline`.
16999
17356
  */
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()
17357
+ var DetectionSourceSchema = _enum(["pipeline", "onboard"]);
17358
+ /**
17359
+ * The confirmed zone crossing that produced an object event. Present ONLY on
17360
+ * an event emitted BY a crossing (`zone.enter` / `zone.exit`); a movement-state
17361
+ * event (`object.entering` / `leaving` / `stationary` / `loitering`) and an
17362
+ * appearance event carry none, so a rule asking for a direction fails closed
17363
+ * on them.
17364
+ *
17365
+ * Exactly ONE crossing per event: the emitter turns each confirmed crossing
17366
+ * into its own event, so a frame in which a track enters A while leaving B
17367
+ * produces two events with two directions — never one ambiguous row.
17368
+ *
17369
+ * `zoneId` is load-bearing for an EXIT: the event's `zones` list is the
17370
+ * membership the box has NOW, and by definition it no longer contains the zone
17371
+ * that was just left. Without the id here, a zone-scoped rule could never match
17372
+ * the exit it asked for.
17373
+ */
17374
+ var ZoneCrossingSchema = object({
17375
+ direction: _enum(["enter", "exit"]),
17376
+ /** Admin zone id crossed. */
17377
+ zoneId: string(),
17378
+ /** Zone display name at crossing time (falls back to the id). */
17379
+ zoneName: string().optional()
17029
17380
  });
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()
17381
+ var ObjectEventSchema = object({
17382
+ ...BaseEventFields,
17383
+ kind: literal("object"),
17384
+ /** Detection source. Optional for backward-compat; absent ⇒ `pipeline`. */
17385
+ source: DetectionSourceSchema.optional(),
17386
+ /**
17387
+ * Inference-frame id shared by every object event emitted from the SAME frame
17388
+ * the "scene/parent" key. Lets a consumer group co-occurring detections (e.g.
17389
+ * 2 people + 1 dog) under one full frame, and link a track's frames over time
17390
+ * (group by `trackId`, pick a representative `frameId` as the parent frame).
17391
+ * Optional for backward-compat with pre-existing rows / the slim projection
17392
+ * includes it (it is light). Absent on rows written before this field.
17393
+ */
17394
+ frameId: string().optional(),
17395
+ /** Omitted in slim projection. */
17396
+ trackId: string().optional(),
17397
+ className: string(),
17398
+ ...TieredLabelFields,
17399
+ /** Omitted in slim projection. */
17400
+ confidence: number().optional(),
17401
+ /** Heavy JSON — omitted in slim projection. */
17402
+ bbox: BoundingBoxSchema.optional(),
17403
+ /** Heavy JSON — omitted in slim projection. */
17404
+ zones: array(string()).readonly().optional(),
17405
+ /** Omitted in slim projection. */
17406
+ state: TrackStateSchema.optional(),
17407
+ /**
17408
+ * The zone crossing this event IS, when it is one. Absent on every other
17409
+ * event kind (movement state, appearance, package) — see
17410
+ * {@link ZoneCrossingSchema}. Omitted in slim projection.
17411
+ */
17412
+ zoneCrossing: ZoneCrossingSchema.optional(),
17413
+ /** Detection-frame dimensions in pixels — let consumers normalize the
17414
+ * pixel-space `bbox` onto a displayed image. Omitted in slim projection. */
17415
+ frameWidth: number().optional(),
17416
+ frameHeight: number().optional(),
17417
+ /** MediaStore key for the crop attached to this event (if any). */
17418
+ mediaKey: string().optional(),
17419
+ /** Design B: MediaStore key of the track's native-resolution key frame (the
17420
+ * best-detection full frame). Resolve via the event-media data-plane
17421
+ * (`/addon/<addonId>/event-media/<keyFrameMediaKey>`) for a detail view that
17422
+ * draws `bbox` over the native frame. Absent on legacy rows / non-decoded
17423
+ * sources — consumers fall back to `mediaKey` (the tight crop). */
17424
+ keyFrameMediaKey: string().optional(),
17425
+ /** Populated by B5 (recording playback URL for this event). */
17426
+ mediaUrl: string().optional(),
17427
+ /** The parent track's key-event importance [0,1], propagated to every object
17428
+ * event of the track (so an event row can be sorted by importance without a
17429
+ * track join). Absent on legacy rows / before the track was scored. */
17430
+ importance: number().optional()
17042
17431
  });
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()
17432
+ var AudioEventSchema = object({
17433
+ ...BaseEventFields,
17434
+ kind: literal("audio"),
17435
+ rms: number(),
17436
+ dbfs: number(),
17437
+ classification: object({
17438
+ className: string(),
17439
+ originalClass: string().optional(),
17440
+ score: number()
17441
+ }).optional(),
17442
+ /** Populated by B5 (recording playback URL for this event). */
17443
+ mediaUrl: string().optional()
17061
17444
  });
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()
17445
+ var MediaFileKindEnum = _enum([
17446
+ "crop",
17447
+ "thumbnail",
17448
+ "snapshot",
17449
+ "firstFrame",
17450
+ "lastFrame",
17451
+ "fullFrame",
17452
+ "fullFrameBoxed",
17453
+ "faceCrop",
17454
+ "plateCrop",
17455
+ "keyFrame",
17456
+ "keyFrameSmall",
17457
+ "thumbnailSmall"
17458
+ ]);
17459
+ var MediaFileSchema = object({
17460
+ key: string(),
17461
+ kind: MediaFileKindEnum,
17462
+ base64: string(),
17463
+ sizeBytes: number(),
17464
+ timestamp: number()
17067
17465
  });
17068
- var LIST_GROUPS_DEFAULT_LIMIT = 40;
17069
- var LIST_GROUPS_MAX_LIMIT = 100;
17070
- var AnalyticsGroupRecordSchema = object({
17466
+ /**
17467
+ * One media row WITHOUT its bytes.
17468
+ *
17469
+ * A track's media is 5-8 MB of base64 (measured: 7.67 MB across 23 files for a
17470
+ * 140 s track), and a client that renders tiles from the media data plane needs
17471
+ * to know only WHAT EXISTS — the bytes then arrive per tile, lazily, over HTTP
17472
+ * with an immutable cache, instead of all at once inside a tRPC response that
17473
+ * blocks the whole view.
17474
+ *
17475
+ * `sizeBytes` is carried because it is what lets a client decide between the
17476
+ * stored blob and a `?variant=thumb` rendering without fetching either.
17477
+ */
17478
+ var MediaFileInfoSchema = MediaFileSchema.omit({ base64: true });
17479
+ /**
17480
+ * The MACRO tier of an annotation — a CLOSED set.
17481
+ *
17482
+ * This is what the exported detector predicts, so a typo here is a new class
17483
+ * with one example in it. `label` and `subLabel` are open strings by contrast:
17484
+ * the whole point of the page is teaching the model things it does not know
17485
+ * yet, and constraining that vocabulary would make it useless.
17486
+ *
17487
+ * A macro class is NEVER a label. The provider refuses a write whose `label` or
17488
+ * `subLabel` is one of these values, in any casing, because once `person`
17489
+ * exists in both tiers "every person box" stops being answerable without
17490
+ * knowing every string anyone ever typed — and the damage is retroactive.
17491
+ */
17492
+ var RetrainMacroClassSchema = _enum([
17493
+ "person",
17494
+ "vehicle",
17495
+ "animal",
17496
+ "package",
17497
+ "face",
17498
+ "plate"
17499
+ ]);
17500
+ /** A subject to learn, or a phantom to unlearn (taught by OMISSION). */
17501
+ var RetrainAnnotationKindSchema = _enum(["subject", "model_error"]);
17502
+ /** Did a human draw this box, or did the assist propose it? */
17503
+ var RetrainAnnotationSourceSchema = _enum(["operator", "assist"]);
17504
+ /** Normalised `[0,1]` rectangle against the FULL frame — the canonical form. */
17505
+ var RetrainBboxSchema = object({
17506
+ x: number(),
17507
+ y: number(),
17508
+ w: number(),
17509
+ h: number()
17510
+ });
17511
+ /**
17512
+ * One annotated subject.
17513
+ *
17514
+ * `bbox` is normalised against the full frame, ALWAYS. The per-model shapes
17515
+ * (letterboxed root / zone-cropped package / subject-cropped classifier) are
17516
+ * derived from it at export and never stored — storing them is how one feature
17517
+ * space ends up holding two crops of the same subject (D52).
17518
+ */
17519
+ var RetrainAnnotationSchema = object({
17071
17520
  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()
17521
+ trackId: string(),
17522
+ deviceId: number(),
17523
+ /** The COPY in retrain storage — never the source track's media key. */
17524
+ mediaKey: string(),
17525
+ bbox: RetrainBboxSchema,
17526
+ macroClass: RetrainMacroClassSchema,
17527
+ label: string().optional(),
17528
+ subLabel: string().optional(),
17529
+ kind: RetrainAnnotationKindSchema,
17530
+ source: RetrainAnnotationSourceSchema,
17531
+ /** Which model proposed this box — or, on a `model_error`, drew the phantom. */
17532
+ assistModelId: string().optional(),
17533
+ assistScore: number().optional(),
17534
+ exportedInBatch: string().optional(),
17535
+ createdAt: number()
17083
17536
  });
17084
- var AnalyticsGroupMemberSchema = object({
17537
+ /** The write form — the server owns `id`, `createdAt` and the frame binding. */
17538
+ var RetrainAnnotationDraftSchema = RetrainAnnotationSchema.omit({
17539
+ id: true,
17540
+ trackId: true,
17541
+ deviceId: true,
17542
+ mediaKey: true,
17543
+ createdAt: true,
17544
+ exportedInBatch: true
17545
+ });
17546
+ /** A track sitting in `staging`, with everything the worklist needs to rank it. */
17547
+ var RetrainTrackSchema = object({
17085
17548
  trackId: string(),
17086
- deviceId: number().int(),
17549
+ deviceId: number(),
17087
17550
  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()
17551
+ label: string().optional(),
17552
+ firstSeen: number(),
17553
+ lastSeen: number(),
17554
+ /** How many frames the dataset already holds from this track. */
17555
+ frameCount: number().int(),
17556
+ /** How many subjects have been annotated on those frames. `0` with
17557
+ * `frameCount: 0` is exactly "staging, still to work". */
17558
+ annotationCount: number().int()
17103
17559
  });
17104
- var ListGroupsPageSchema = object({
17105
- groups: array(AnalyticsGroupRecordSchema).readonly(),
17106
- nextCursor: string().nullable()
17560
+ /** A frame the picker may offer — an index row, no blob was read to produce it. */
17561
+ var RetrainFrameCandidateSchema = object({
17562
+ mediaKey: string(),
17563
+ kind: MediaFileKindEnum,
17564
+ timestamp: number(),
17565
+ sizeBytes: number().int(),
17566
+ /** A copy of this original already exists — selecting it is free and cannot
17567
+ * fail, whatever became of the original. */
17568
+ copied: boolean()
17107
17569
  });
17108
- var KeyEventQueryInput = object({
17570
+ /** A frame the dataset OWNS: bytes copied at selection time. */
17571
+ var RetrainFrameSchema = object({
17572
+ frameId: string(),
17109
17573
  deviceId: number(),
17110
- /** Window lower bound (track firstSeen ≥ since). */
17111
- since: number(),
17112
- /** Window upper bound (track firstSeen ≤ until). */
17574
+ trackId: string(),
17575
+ /** Provenance only. It may already point at nothing — that is expected. */
17576
+ sourceMediaKey: string(),
17577
+ sourceKind: MediaFileKindEnum,
17578
+ sizeBytes: number().int(),
17579
+ width: number().int(),
17580
+ height: number().int(),
17581
+ copiedAt: number()
17582
+ });
17583
+ /** Why a copy-on-select could not be honoured — named, never a silent skip. */
17584
+ var RetrainCopyRefusalSchema = _enum([
17585
+ "source-missing",
17586
+ "unreadable-image",
17587
+ "write-failed"
17588
+ ]);
17589
+ var RetrainFrameSelectionSchema = object({
17590
+ copied: array(RetrainFrameSchema).readonly(),
17591
+ refused: array(object({
17592
+ sourceMediaKey: string(),
17593
+ reason: RetrainCopyRefusalSchema
17594
+ })).readonly()
17595
+ });
17596
+ var RetrainFrameListSchema = object({
17597
+ candidates: array(RetrainFrameCandidateSchema).readonly(),
17598
+ copies: array(RetrainFrameSchema).readonly(),
17599
+ /** What the page pre-selects — the native key frame when one survives. */
17600
+ autoPickMediaKey: string().optional()
17601
+ });
17602
+ /** What the operator asked the assist to look for. */
17603
+ var RetrainAssistSubjectSchema = discriminatedUnion("kind", [object({
17604
+ kind: literal("package"),
17605
+ zone: RetrainBboxSchema.optional()
17606
+ }), object({
17607
+ kind: literal("objects"),
17608
+ modelId: string(),
17609
+ minScore: number().optional()
17610
+ })]);
17611
+ /**
17612
+ * The assist's answer — a discriminated union, because "the model saw nothing"
17613
+ * and "this node cannot run that model" lead to different next moves and a
17614
+ * nullable result cannot tell them apart.
17615
+ */
17616
+ var RetrainAssistResultSchema = discriminatedUnion("kind", [object({
17617
+ kind: literal("proposed"),
17618
+ modelId: string(),
17619
+ stepId: string(),
17620
+ minScore: number(),
17621
+ /** Drafts, ready to edit. `source: 'assist'` until the operator touches one. */
17622
+ proposals: array(RetrainAnnotationDraftSchema).readonly(),
17623
+ /** Returned by the runner but removed by the threshold. */
17624
+ belowThreshold: number().int()
17625
+ }), object({
17626
+ kind: literal("refused"),
17627
+ /** `no-zone` is ours; the rest are the runner's own refusal vocabulary. */
17628
+ reason: string(),
17629
+ detail: string().optional()
17630
+ })]);
17631
+ /** The outcome of a lifecycle move owned by the retrain page. */
17632
+ var RetrainTransitionResultSchema = object({
17633
+ trackId: string(),
17634
+ /** Where the track ended up, whatever happened. */
17635
+ retrainStatus: RetrainStatusSchema,
17636
+ /** `false` ⇒ the move was refused or was a no-op; `reason` says which. */
17637
+ changed: boolean(),
17638
+ reason: _enum([
17639
+ "unknown-track",
17640
+ "no-frames-copied",
17641
+ "not-staging",
17642
+ "not-trained",
17643
+ "unchanged"
17644
+ ]).optional()
17645
+ });
17646
+ var DEFAULT_EVENT_QUERY_LIMIT = 1e3;
17647
+ var MAX_EVENT_QUERY_LIMIT = 5e3;
17648
+ var DeviceEventQueryInput = object({
17649
+ deviceId: number(),
17650
+ since: number().optional(),
17651
+ until: number().optional(),
17652
+ limit: number().int().min(1).max(MAX_EVENT_QUERY_LIMIT).default(DEFAULT_EVENT_QUERY_LIMIT),
17653
+ /** `slim` drops heavy JSON fields (regions/bbox/zones) and carries an
17654
+ * optional `mediaUrl` (populated by B5). `full` (default) keeps today's
17655
+ * exact behaviour. Callers may omit this field — the store defaults to
17656
+ * `full` when not provided. */
17657
+ projection: _enum(["full", "slim"]).optional()
17658
+ });
17659
+ var ObjectEventQueryInput = DeviceEventQueryInput.extend({ classFilter: string().optional() });
17660
+ var RecentTracksQueryInput = object({
17661
+ /** Devices to merge. An empty array yields `{ tracks: [], nextCursor: null }`. */
17662
+ deviceIds: array(number()),
17663
+ /** Window lower bound on `lastSeen` (inclusive). */
17664
+ since: number().optional(),
17665
+ /** Window upper bound on `lastSeen` (inclusive). */
17666
+ until: number().optional(),
17667
+ /** Page size. Default 200, max 1000. */
17668
+ limit: number().int().min(1).max(1e3).default(200),
17669
+ /** Opaque continuation cursor from a previous page's `nextCursor`.
17670
+ * Encodes the (lastSeen, trackId) sort position — treat as opaque. */
17671
+ cursor: string().optional(),
17672
+ /** See {@link TrackProjectionSchema}. Default `full`. */
17673
+ projection: TrackProjectionSchema.optional(),
17674
+ /** Include stationary-promoted rows (parked objects). Default false: the
17675
+ * feed lists passages; parking records live on the stationary registry. */
17676
+ includeStationary: boolean().optional()
17677
+ });
17678
+ var RecentTracksPageSchema = object({
17679
+ /** Merged page, ordered by (`lastSeen` DESC, `trackId` DESC). */
17680
+ tracks: array(TrackSchema).readonly(),
17681
+ /** Cursor for the next page, or null when this page is the last. */
17682
+ nextCursor: string().nullable()
17683
+ });
17684
+ var LIST_GROUPS_DEFAULT_LIMIT = 40;
17685
+ var LIST_GROUPS_MAX_LIMIT = 100;
17686
+ var AnalyticsGroupRecordSchema = object({
17687
+ id: string(),
17688
+ deviceId: number().int(),
17689
+ openedAt: number().int(),
17690
+ closedAt: number().int(),
17691
+ timestamp: number().int(),
17692
+ memberCount: number().int(),
17693
+ memberTrackIds: array(string()).readonly(),
17694
+ className: string(),
17695
+ classes: array(string()).readonly(),
17696
+ /** Relative event-media path, or null when the group has no picture yet. */
17697
+ mediaUrl: string().nullable(),
17698
+ singleton: boolean()
17699
+ });
17700
+ var AnalyticsGroupMemberSchema = object({
17701
+ trackId: string(),
17702
+ deviceId: number().int(),
17703
+ className: string(),
17704
+ firstSeen: number().int(),
17705
+ lastSeen: number().int(),
17706
+ mediaUrl: string().nullable()
17707
+ });
17708
+ var AnalyticsGroupDetailSchema = AnalyticsGroupRecordSchema.extend({ members: array(AnalyticsGroupMemberSchema).readonly() });
17709
+ var ListGroupsQueryInput = object({
17710
+ /** Devices to merge. An empty array yields `{ groups: [], nextCursor: null }`. */
17711
+ deviceIds: array(number()),
17712
+ /** Window lower bound on `closedAt` (inclusive). */
17713
+ since: number().optional(),
17714
+ /** Window upper bound on `openedAt` (inclusive). */
17715
+ until: number().optional(),
17716
+ limit: number().int().min(1).max(LIST_GROUPS_MAX_LIMIT).default(LIST_GROUPS_DEFAULT_LIMIT),
17717
+ /** Opaque continuation cursor from a previous page's `nextCursor`. */
17718
+ cursor: string().optional()
17719
+ });
17720
+ var ListGroupsPageSchema = object({
17721
+ groups: array(AnalyticsGroupRecordSchema).readonly(),
17722
+ nextCursor: string().nullable()
17723
+ });
17724
+ var KeyEventQueryInput = object({
17725
+ deviceId: number(),
17726
+ /** Window lower bound (track firstSeen ≥ since). */
17727
+ since: number(),
17728
+ /** Window upper bound (track firstSeen ≤ until). */
17113
17729
  until: number(),
17114
17730
  limit: number().int().min(1).max(200).default(50),
17115
17731
  /** Drop tracks scoring below this importance. */
@@ -17308,6 +17924,24 @@ var RebuildStatusSchema = object({
17308
17924
  /** Present when the pass ended by throwing. */
17309
17925
  error: string().nullable()
17310
17926
  });
17927
+ var ReplayFrameInputSchema = object({
17928
+ timestamp: number(),
17929
+ frame: PipelineRunResultBridge
17930
+ });
17931
+ var RunReplayFrameProcessorResultSchema = object({ tracks: array(object({
17932
+ className: string(),
17933
+ firstSeenMs: number(),
17934
+ lastSeenMs: number(),
17935
+ /** Bbox of the track's FIRST matched detection, pixel-space in the clip's
17936
+ * frame — a representative box for the diff's `(className, window, IoU)`
17937
+ * pairing (`replay-diff.ts`). A replay does not need the full per-frame
17938
+ * trajectory production's `Track.positions` keeps. */
17939
+ bbox: BoundingBoxSchema,
17940
+ /** How many of the input frames this track matched a real detection on
17941
+ * (never a coasted/extrapolated frame) — the replay's own signal for "how
17942
+ * solid is this track", cheaper than re-deriving it from a trajectory. */
17943
+ framesMatched: number().int()
17944
+ })).readonly() });
17311
17945
  DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).readonly()), method(object({
17312
17946
  deviceId: number(),
17313
17947
  trackId: string()
@@ -17478,502 +18112,80 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
17478
18112
  }), RetrainAssistResultSchema, {
17479
18113
  kind: "mutation",
17480
18114
  auth: "admin"
17481
- }), method(object({ trackId: string() }), array(RetrainAnnotationSchema).readonly(), {
17482
- kind: "query",
17483
- auth: "admin"
17484
- }), method(object({
17485
- deviceId: number(),
17486
- 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
18115
  }), method(object({
17499
18116
  deviceId: number(),
17500
- trackId: string()
17501
- }), RetrainTransitionResultSchema, {
18117
+ source: DetectionSourceSchema,
18118
+ zones: array(ZoneSchema).readonly().optional(),
18119
+ detectionRules: array(ZoneRuleSchema).readonly().optional(),
18120
+ zoneMembershipMinOverlap: number().min(0).max(1).optional(),
18121
+ frames: array(ReplayFrameInputSchema).min(1)
18122
+ }), RunReplayFrameProcessorResultSchema, {
17502
18123
  kind: "mutation",
17503
18124
  auth: "admin"
17504
- }), method(object({ deviceIds: array(number()).optional() }), object({ url: string() }), {
18125
+ }), method(object({ trackId: string() }), array(RetrainAnnotationSchema).readonly(), {
17505
18126
  kind: "query",
17506
18127
  auth: "admin"
17507
18128
  }), 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({
17516
- 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
- deviceId: number(),
17526
- 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({
17535
18129
  deviceId: number(),
17536
18130
  trackId: string(),
17537
- className: string(),
17538
- durationMs: number()
17539
- }), object({
17540
- deviceId: number(),
17541
- kind: EventKindSchema,
17542
- eventId: string(),
17543
- timestamp: number()
17544
- });
17545
- /**
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.
17549
- */
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
- ])
17578
- });
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()
17592
- });
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()
17613
- });
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()
17622
- });
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({
17643
- id: string(),
17644
- name: string(),
17645
- createdAt: string(),
17646
- updatedAt: string(),
17647
- engine: PipelineEngineChoiceSchema,
17648
- steps: array(PipelineTemplateStepSchema).readonly()
17649
- });
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()
17660
- });
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()
17677
- });
17678
- var PipelineSlotSchemaSchema = object({
17679
- id: PipelineSlotSchema,
17680
- label: string(),
17681
- priority: number(),
17682
- parentSlot: PipelineSlotSchema.nullable(),
17683
- addons: array(PipelineAddonSchemaSchema).readonly()
17684
- });
17685
- var PipelineSchemaSchema = object({
17686
- availableEngines: array(AvailableEngineSchema).readonly(),
17687
- selectedEngine: PipelineEngineChoiceSchema,
17688
- slots: array(PipelineSlotSchemaSchema).readonly()
17689
- });
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()
17717
- });
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()
17731
- });
17732
- var PipelineValidationIssueSchema = object({
17733
- addonId: string(),
17734
- kind: _enum(["unknown-addon", "no-format-build"]),
17735
- detail: string()
17736
- });
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()
17743
- });
17744
- var ReferenceImageEntrySchema = object({
17745
- filename: string(),
17746
- stepIds: array(string()).readonly().optional()
17747
- });
17748
- var ReferenceImageBodySchema = object({
17749
- base64: string(),
17750
- filename: string()
17751
- });
17752
- var ReferenceAudioEntrySchema = object({
17753
- filename: string(),
17754
- sizeKb: number()
17755
- });
17756
- var ReferenceAudioBodySchema = object({ base64: string() });
17757
- var AudioBackendSchema = object({
17758
- id: string(),
17759
- name: string(),
17760
- description: string(),
17761
- available: boolean(),
17762
- /**
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.
17767
- */
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()
17780
- });
17781
- /**
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.
17790
- */
17791
- var AudioTestResultSchema = object({
17792
- success: boolean(),
17793
- error: string().optional(),
17794
- frame: custom().optional()
17795
- });
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) }), {
17809
- kind: "mutation",
17810
- auth: "admin"
17811
- }), method(object({ nodeId: string() }), object({
17812
- success: literal(true),
17813
- clearedDevices: number()
17814
- }), {
17815
- kind: "mutation",
17816
- 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
- ])
17919
- }), 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) }), {
18131
+ frameId: string(),
18132
+ annotations: array(RetrainAnnotationDraftSchema)
18133
+ }), array(RetrainAnnotationSchema).readonly(), {
17960
18134
  kind: "mutation",
17961
18135
  auth: "admin"
17962
18136
  }), method(object({
17963
- engine: PipelineEngineChoiceSchema,
17964
- force: boolean().optional()
17965
- }), object({
17966
- success: boolean(),
17967
- reason: string().optional()
17968
- }), {
18137
+ deviceId: number(),
18138
+ trackId: string()
18139
+ }), RetrainTransitionResultSchema, {
17969
18140
  kind: "mutation",
17970
18141
  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);
18142
+ }), method(object({
18143
+ deviceId: number(),
18144
+ trackId: string()
18145
+ }), RetrainTransitionResultSchema, {
18146
+ kind: "mutation",
18147
+ auth: "admin"
18148
+ }), method(object({ deviceIds: array(number()).optional() }), object({ url: string() }), {
18149
+ kind: "query",
18150
+ auth: "admin"
18151
+ }), method(object({
18152
+ eventId: string(),
18153
+ kind: MediaFileKindEnum.optional(),
18154
+ deviceId: number()
18155
+ }), array(MediaFileSchema).readonly()), method(object({
18156
+ trackId: string(),
18157
+ kinds: array(MediaFileKindEnum).optional(),
18158
+ deviceId: number()
18159
+ }), array(MediaFileSchema).readonly()), method(object({
18160
+ trackId: string(),
18161
+ deviceId: number()
18162
+ }), array(MediaFileInfoSchema).readonly()), method(SearchObjectEventsInput, array(ScoredObjectEventSchema).readonly()), method(object({}), WipeObjectEmbeddingsResultSchema, {
18163
+ kind: "mutation",
18164
+ auth: "admin"
18165
+ }), method(RebuildObjectEmbeddingsInput, RebuildObjectEmbeddingsResultSchema, {
18166
+ kind: "mutation",
18167
+ auth: "admin"
18168
+ }), method(object({}), RebuildStatusSchema), object({
18169
+ deviceId: number(),
18170
+ timestamp: number(),
18171
+ frameWidth: number(),
18172
+ frameHeight: number(),
18173
+ detections: array(OverlayDetectionSchema).readonly()
18174
+ }), object({
18175
+ deviceId: number(),
18176
+ trackId: string(),
18177
+ className: string()
18178
+ }), object({
18179
+ deviceId: number(),
18180
+ trackId: string(),
18181
+ className: string(),
18182
+ durationMs: number()
18183
+ }), object({
18184
+ deviceId: number(),
18185
+ kind: EventKindSchema,
18186
+ eventId: string(),
18187
+ timestamp: number()
18188
+ });
17977
18189
  object({
17978
18190
  activeCameras: number(),
17979
18191
  throttledCameras: number(),
@@ -17999,66 +18211,6 @@ var CameraMetricsSchema = object({
17999
18211
  });
18000
18212
  var CameraMetricsWithDeviceIdSchema = CameraMetricsSchema.extend({ deviceId: number() });
18001
18213
  /**
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
18214
  * A bounding box in NORMALIZED [0,1] frame coordinates for `getNativeCrop`. The
18063
18215
  * decode worker resolves it against the RETAINED native frame's real pixel dims,
18064
18216
  * so the caller supplies only the detection-res bbox divided by the detection
@@ -25071,6 +25223,39 @@ var ReadGopBytesResultSchema = object({
25071
25223
  /** Media ms the returned fragment covers. */
25072
25224
  gopDurMs: number()
25073
25225
  });
25226
+ /**
25227
+ * A time WINDOW of one finalized segment, cut by byte range — the multi-GOP
25228
+ * twin of {@link ReadGopBytesResultSchema}'s single instant. Built for the
25229
+ * replay clip's `recording` source (`docs/design/plans/2026-08-26-replay-clip-su-pipeline.md`):
25230
+ * a replay needs several seconds of native pixels, not one frame.
25231
+ *
25232
+ * `ok.data` is standalone-demuxable, same as a GOP read. `ok.reachesRequestedEnd`
25233
+ * is `false` when the returned bytes were cut short by the read's own safety
25234
+ * byte cap before covering `[fromMs, toMs)` — a truncation, reported, not a
25235
+ * silently shorter answer. `spans-multiple-segments` is a REFUSAL, not a
25236
+ * degradation: a window whose end falls past the covering segment would need
25237
+ * bytes stitched from a second segment file (its own `ftyp`+`moov`), which is
25238
+ * not one standalone-demuxable stream — the caller's answer is to request a
25239
+ * shorter window or one aligned to a single segment, not to receive spliced
25240
+ * bytes nothing has proven decodable.
25241
+ */
25242
+ var ReadWindowBytesResultSchema = discriminatedUnion("kind", [object({
25243
+ kind: literal("ok"),
25244
+ data: _instanceof(Uint8Array),
25245
+ /** Absolute epoch ms of the returned bytes' first sample — at or before
25246
+ * the requested `fromMs` (anchored on the nearest keyframe). */
25247
+ gopStartMs: number(),
25248
+ /** Media ms the returned bytes cover, from `gopStartMs`. */
25249
+ gopDurMs: number(),
25250
+ /** `false` ⇒ the safety byte cap cut the read short before it reached
25251
+ * the requested `toMs`; the caller got fewer frames than asked for. */
25252
+ reachesRequestedEnd: boolean()
25253
+ }), object({
25254
+ kind: literal("spans-multiple-segments"),
25255
+ /** Where the covering segment's own footage runs out — informational,
25256
+ * not a retry hint (retrying the same window would refuse again). */
25257
+ segmentEndMs: number()
25258
+ })]);
25074
25259
  method(object({
25075
25260
  deviceId: number(),
25076
25261
  fromMs: number(),
@@ -25121,6 +25306,15 @@ method(object({
25121
25306
  }), ReadGopBytesResultSchema, {
25122
25307
  kind: "query",
25123
25308
  auth: "admin"
25309
+ }), method(object({
25310
+ deviceId: number(),
25311
+ profile: string(),
25312
+ startMs: number(),
25313
+ fromMs: number(),
25314
+ toMs: number()
25315
+ }), ReadWindowBytesResultSchema, {
25316
+ kind: "query",
25317
+ auth: "admin"
25124
25318
  }), method(object({
25125
25319
  deviceId: number(),
25126
25320
  config: RecordingConfigSchema
@@ -25675,92 +25869,6 @@ DeviceType.Camera, method(object({ deviceId: number() }), SceneMonitorStatusSche
25675
25869
  kind: "mutation",
25676
25870
  auth: "admin"
25677
25871
  });
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
25872
  object({
25765
25873
  /** Whether the script is currently executing. */
25766
25874
  isRunning: boolean(),
@@ -29625,6 +29733,12 @@ Object.freeze({
29625
29733
  addonId: null,
29626
29734
  access: "view"
29627
29735
  },
29736
+ "notificationRules.resolveArtifactUrl": {
29737
+ capName: "notification-rules",
29738
+ capScope: "system",
29739
+ addonId: null,
29740
+ access: "view"
29741
+ },
29628
29742
  "notificationRules.setAlarmConfig": {
29629
29743
  capName: "notification-rules",
29630
29744
  capScope: "system",
@@ -30069,6 +30183,12 @@ Object.freeze({
30069
30183
  addonId: null,
30070
30184
  access: "create"
30071
30185
  },
30186
+ "pipelineAnalytics.runReplayFrameProcessor": {
30187
+ capName: "pipeline-analytics",
30188
+ capScope: "device",
30189
+ addonId: null,
30190
+ access: "create"
30191
+ },
30072
30192
  "pipelineAnalytics.saveRetrainAnnotations": {
30073
30193
  capName: "pipeline-analytics",
30074
30194
  capScope: "device",
@@ -30201,6 +30321,12 @@ Object.freeze({
30201
30321
  addonId: null,
30202
30322
  access: "view"
30203
30323
  },
30324
+ "pipelineExecutor.getInferenceDeviceHealth": {
30325
+ capName: "pipeline-executor",
30326
+ capScope: "system",
30327
+ addonId: null,
30328
+ access: "view"
30329
+ },
30204
30330
  "pipelineExecutor.getOrchestratorConfigSchema": {
30205
30331
  capName: "pipeline-executor",
30206
30332
  capScope: "system",
@@ -30273,6 +30399,12 @@ Object.freeze({
30273
30399
  addonId: null,
30274
30400
  access: "view"
30275
30401
  },
30402
+ "pipelineExecutor.rearmInferenceDevice": {
30403
+ capName: "pipeline-executor",
30404
+ capScope: "system",
30405
+ addonId: null,
30406
+ access: "create"
30407
+ },
30276
30408
  "pipelineExecutor.runAudioTest": {
30277
30409
  capName: "pipeline-executor",
30278
30410
  capScope: "system",
@@ -31011,6 +31143,12 @@ Object.freeze({
31011
31143
  addonId: null,
31012
31144
  access: "view"
31013
31145
  },
31146
+ "recording.readWindowBytes": {
31147
+ capName: "recording",
31148
+ capScope: "system",
31149
+ addonId: null,
31150
+ access: "view"
31151
+ },
31014
31152
  "recording.refreshStorageLocationsForMigration": {
31015
31153
  capName: "recording",
31016
31154
  capScope: "system",
@@ -33521,6 +33659,11 @@ Object.freeze({
33521
33659
  form: "single",
33522
33660
  optional: false
33523
33661
  }],
33662
+ "pipelineAnalytics.runReplayFrameProcessor": [{
33663
+ name: "deviceId",
33664
+ form: "single",
33665
+ optional: false
33666
+ }],
33524
33667
  "pipelineAnalytics.saveRetrainAnnotations": [{
33525
33668
  name: "deviceId",
33526
33669
  form: "single",
@@ -33836,6 +33979,11 @@ Object.freeze({
33836
33979
  form: "single",
33837
33980
  optional: false
33838
33981
  }],
33982
+ "recording.readWindowBytes": [{
33983
+ name: "deviceId",
33984
+ form: "single",
33985
+ optional: false
33986
+ }],
33839
33987
  "recording.relocateFootage": [{
33840
33988
  name: "deviceId",
33841
33989
  form: "single",