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