@camstack/addon-smtp-nodemailer 1.2.28 → 1.2.29

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