@camstack/addon-tailscale 1.2.29 → 1.2.31

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