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