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