@camstack/addon-remote-storage 1.2.28 → 1.2.29

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