@camstack/addon-tailscale 1.2.29 → 1.2.30

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