@camstack/addon-export-hap 1.2.40 → 1.2.42

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.
@@ -16281,7 +16281,23 @@ var NcHistoryEntrySchema = object({
16281
16281
  updatedAt: number(),
16282
16282
  /** Failure detail — present on a `dead` row. */
16283
16283
  error: string().optional(),
16284
- subject: NcHistorySubjectSchema
16284
+ subject: NcHistorySubjectSchema,
16285
+ /**
16286
+ * Ids of the artefacts (still, then gif, then clip) this row's successful
16287
+ * delivery indexed in the artefact library — a REFERENCE, never the bytes
16288
+ * (an artefact is often megabytes; this row is durable JSON rewritten on
16289
+ * every delivery attempt). Absent on a row still pending/dead, a row
16290
+ * delivered before this field shipped, or a wiring with no artefact index.
16291
+ *
16292
+ * Resolve one to a fetchable URL with `resolveArtifactUrl` — an id
16293
+ * outlives any one URL's TTL, so a caller mints a fresh link on demand
16294
+ * rather than trusting one frozen at delivery time. `resolveArtifactUrl`
16295
+ * also answers `null` for an id whose artefact has since expired past the
16296
+ * retained shelf's own age bound — the degrade a caller (the Home
16297
+ * Assistant export) must render as "no image right now", never as a
16298
+ * broken link.
16299
+ */
16300
+ artifactIds: array(string().min(1)).optional()
16285
16301
  });
16286
16302
  /**
16287
16303
  * Query filter for `getHistory` (spec §4.2). Every field is a narrowing
@@ -16508,7 +16524,7 @@ method(object({}), object({ rules: array(NcRuleSchema) }), { auth: "admin" }), m
16508
16524
  }), method(object({}), object({
16509
16525
  catalog: array(NcConditionDescriptorSchema),
16510
16526
  taxonomy: NcTaxonomySchema.optional()
16511
- })), 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 }), {
16527
+ })), 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 }), {
16512
16528
  kind: "mutation",
16513
16529
  caller: "required"
16514
16530
  }), method(object({ snoozeId: string() }), object({ success: literal(true) }), {
@@ -16848,896 +16864,1496 @@ var OauthIntegrationDescriptorSchema = object({
16848
16864
  });
16849
16865
  method(_void(), OauthIntegrationDescriptorSchema, { auth: "admin" });
16850
16866
  /**
16851
- * pipeline-analytics device-scoped wrapper cap. Refines raw
16852
- * per-frame detections emitted by the pipeline runner into tracked
16853
- * objects, per-kind event collections (motion / object / audio), and
16854
- * persisted media. Owns the post-detection domain end-to-end:
16855
- *
16856
- * runner emits PipelineInferenceResult
16857
- * ↓ (event bus)
16858
- * pipeline-analytics subscriber
16859
- * ↓ SORT tracker + zone engine + state analyzer + event emitter
16860
- * → three DB collections (one per kind), one FS media tree, one
16861
- * unified event emitter (FrameTracked + TrackStarted/Ended +
16862
- * DetectionEvent on bus)
16863
- *
16864
- * Pure subscriber model. No `processFrame` cap method — the runner
16865
- * already publishes the raw frame on the bus. The cap surface is
16866
- * only QUERIES + per-device settings, bound on/off via
16867
- * `device-manager.setWrapperActive`. `defaultActive: true` because
16868
- * every camera with a detection pipeline wants its raw detections
16869
- * refined; operators opt out per-device via BindingsTab when needed.
16870
- *
16871
- * Replaces the legacy `analysis-pipeline`, `analysis-data-persistence`
16872
- * (per-device surface) and `track-trail` caps — see P11 cleanup.
16867
+ * Reference to the frame's retained NATIVE surface + the parent crop's placement
16868
+ * within the frame, so the executor can re-cut a leaf child ROI at native
16869
+ * resolution on the detail plane. See the `runPipeline` `nativeCropRef` field.
16873
16870
  */
16874
- var TrackStateSchema = _enum([
16875
- "new",
16876
- "entered",
16877
- "left",
16878
- "moving",
16879
- "idle"
16880
- ]);
16881
- var EventKindSchema = _enum([
16882
- "motion",
16883
- "object",
16884
- "audio"
16885
- ]);
16871
+ var NativeCropRefSchema = object({
16872
+ /** Handle keying the retained native surface (node-pinned to its owner). */
16873
+ handle: FrameHandleSchema,
16874
+ /** The parent crop's padded/clamped rectangle in FRAME-space pixels. */
16875
+ cropFrameSpace: object({
16876
+ x: number(),
16877
+ y: number(),
16878
+ w: number(),
16879
+ h: number()
16880
+ })
16881
+ });
16882
+ object({
16883
+ crop: object({
16884
+ left: number(),
16885
+ top: number(),
16886
+ width: number().positive(),
16887
+ height: number().positive()
16888
+ }).optional(),
16889
+ content: object({
16890
+ width: number().int().positive(),
16891
+ height: number().int().positive()
16892
+ }),
16893
+ fit: _enum(["stretch", "contain"]),
16894
+ format: _enum([
16895
+ "rgb",
16896
+ "gray",
16897
+ "jpeg"
16898
+ ])
16899
+ });
16886
16900
  /**
16887
- * Spatial filter for `listTracks` the rect + polygon variants of the shared
16888
- * MaskShape vocabulary (see `mask-shape.ts`). Coordinates are NORMALIZED 0..1
16889
- * of the camera frame (top-left origin), matching the drawing-plane editor.
16901
+ * Process-local frame identity. It is serializable so it can ride an in-process
16902
+ * capability call, but `registryId` deliberately prevents resolution in any
16903
+ * other process or execution group.
16890
16904
  */
16891
- var TrackZoneFilterSchema = discriminatedUnion("kind", [MaskRectShapeSchema, MaskPolygonShapeSchema]);
16892
- /** Closed icon vocabulary so clients render a known glyph per kind. */
16893
- var EventKindIconSchema = _enum([
16894
- "motion",
16895
- "audio",
16896
- "person",
16897
- "vehicle",
16898
- "animal",
16899
- "door",
16900
- "pir",
16901
- "smoke",
16902
- "water",
16903
- "button",
16904
- "package",
16905
- "generic"
16905
+ var FrameRefSchema = object({
16906
+ registryId: string().min(1),
16907
+ id: string().min(1),
16908
+ width: number().int().positive(),
16909
+ height: number().int().positive(),
16910
+ format: _enum(["rgb", "gray"]),
16911
+ timestamp: number(),
16912
+ capturedAt: number().optional()
16913
+ });
16914
+ var ModelFormatSchema$1 = _enum([
16915
+ "onnx",
16916
+ "coreml",
16917
+ "openvino",
16918
+ "tflite",
16919
+ "pt",
16920
+ "gguf"
16906
16921
  ]);
16907
- var EventKindCategorySchema = _enum([
16908
- "motion",
16909
- "audio",
16910
- "detection",
16911
- "sensor",
16912
- "control",
16913
- "custom",
16914
- "package"
16922
+ var PipelineSlotSchema = _enum([
16923
+ "detector",
16924
+ "cropper",
16925
+ "classifier",
16926
+ "refiner",
16927
+ "audio-classifier"
16915
16928
  ]);
16916
- /** Taxonomy level — macro (timeline lane) vs sub (events-page leaf). */
16917
- var EventKindLevelSchema = _enum(["macro", "sub"]);
16918
- var EventKindDescriptorSchema = object({
16919
- /** Stable kind id (e.g. 'motion', 'vehicle', 'car', 'lock'). */
16920
- kind: string(),
16921
- /** i18n key resolved on the UI side; `label` is the English fallback. */
16922
- labelKey: string(),
16923
- /** English fallback label (kept for clients that don't translate). */
16924
- label: string(),
16925
- /** Hex color for timeline/legend rendering. */
16926
- color: string(),
16927
- /** Dictionary id → lucide component on the UI side. */
16928
- iconId: string(),
16929
- /** Legacy closed-vocab glyph — fallback for `iconId`. */
16930
- icon: EventKindIconSchema,
16931
- category: EventKindCategorySchema,
16932
- /** Macro parent for this kind ('car' → 'vehicle'); null for a macro. */
16933
- parentKind: string().nullable(),
16934
- /** Derived from `parentKind`, explicit for the client tree. */
16935
- level: EventKindLevelSchema,
16936
- /** Which cap + device contributes this kind. For built-ins the camera
16937
- * itself; for sensor kinds the LINKED source device. */
16938
- source: object({
16939
- capName: string(),
16940
- deviceId: number()
16941
- })
16929
+ var PipelineEngineChoiceSchema = object({
16930
+ runtime: _enum(["node", "python"]),
16931
+ backend: string(),
16932
+ format: ModelFormatSchema$1,
16933
+ device: string().optional()
16942
16934
  });
16943
- /** One camera's event vocabulary, as returned by `listEventKindsBatch`. */
16944
- var EventKindsForDeviceSchema = object({
16945
- deviceId: number(),
16946
- kinds: array(EventKindDescriptorSchema).readonly()
16935
+ var AvailableEngineSchema = object({
16936
+ engine: PipelineEngineChoiceSchema,
16937
+ devices: array(object({
16938
+ id: string(),
16939
+ label: string(),
16940
+ description: string().optional()
16941
+ })).readonly(),
16942
+ defaultDevice: string()
16947
16943
  });
16948
- var SensorEventSchema = object({
16944
+ var PipelineDefaultStepSchema = lazy(() => object({
16945
+ addonId: string(),
16946
+ addonName: string(),
16947
+ slot: PipelineSlotSchema,
16948
+ inputClasses: array(string()).readonly(),
16949
+ outputClasses: array(string()).readonly(),
16950
+ enabled: boolean(),
16951
+ modelId: string(),
16952
+ children: array(PipelineDefaultStepSchema).readonly(),
16953
+ group: string().optional(),
16954
+ settings: record(string(), unknown()).optional()
16955
+ }));
16956
+ var PipelineTemplateStepSchema = lazy(() => object({
16957
+ addonId: string(),
16958
+ enabled: boolean(),
16959
+ modelId: string(),
16960
+ children: array(PipelineTemplateStepSchema).readonly(),
16961
+ settings: record(string(), unknown()).optional()
16962
+ }));
16963
+ var PipelineTemplateSchema$1 = object({
16949
16964
  id: string(),
16950
- /** The CAMERA the event is attributed to (a sensor linked to N cameras
16951
- * yields N rows, one per camera). */
16952
- deviceId: number(),
16953
- /** The linked sensor device whose state changed. */
16954
- sourceDeviceId: number(),
16955
- /** Event kind id — matches an `EventKindDescriptor.kind`. */
16956
- kind: string(),
16957
- /** Snapshot of the sensor cap's runtime-state slice at the change. */
16958
- value: record(string(), unknown()).nullable(),
16959
- timestamp: number()
16965
+ name: string(),
16966
+ createdAt: string(),
16967
+ updatedAt: string(),
16968
+ engine: PipelineEngineChoiceSchema,
16969
+ steps: array(PipelineTemplateStepSchema).readonly()
16960
16970
  });
16961
- var TrackPositionSchema = object({
16962
- x: number(),
16963
- y: number(),
16964
- timestamp: number(),
16965
- bbox: BoundingBoxSchema
16971
+ var PipelineModelOptionSchema = object({
16972
+ id: string(),
16973
+ name: string(),
16974
+ formats: record(string(), object({
16975
+ downloaded: boolean(),
16976
+ sizeMB: number()
16977
+ })),
16978
+ group: ModelVariantGroupSchema.optional(),
16979
+ legacy: boolean().optional(),
16980
+ provider: ModelProviderIdSchema.optional()
16966
16981
  });
16967
- var TrackSnapshotSchema = object({
16968
- timestamp: number(),
16969
- position: TrackPositionSchema,
16970
- /** MediaStore key; resolve via `getTrackMedia({ trackId })`. */
16971
- mediaKey: string()
16982
+ var ConfigFieldBridge = custom();
16983
+ var PipelineAddonSchemaSchema = object({
16984
+ id: string(),
16985
+ name: string(),
16986
+ slot: PipelineSlotSchema,
16987
+ inputClasses: array(string()).readonly(),
16988
+ outputClasses: array(string()).readonly(),
16989
+ childSlots: array(PipelineSlotSchema).readonly(),
16990
+ models: array(PipelineModelOptionSchema).readonly(),
16991
+ defaultModelId: string(),
16992
+ defaultModelIdByFormat: record(string(), string()).optional(),
16993
+ enabledByDefault: boolean().optional(),
16994
+ backfillIntoExistingOverrides: boolean().optional(),
16995
+ defaultConfidence: number(),
16996
+ group: string().optional(),
16997
+ configSchema: array(ConfigFieldBridge).readonly().optional()
16972
16998
  });
16973
- /**
16974
- * Normalized 0..1 trajectory envelope (min/max over every position bbox,
16975
- * divided by the track's detection-frame dims), computed at persist time.
16976
- * Absent when the frame dims were unknown when the track was persisted
16977
- * (legacy rows / dims-less sources) and on active (in-RAM) tracks.
16978
- */
16979
- var TrackEnvelopeSchema = object({
16980
- minX: number(),
16981
- minY: number(),
16982
- maxX: number(),
16983
- maxY: number()
16999
+ var PipelineSlotSchemaSchema = object({
17000
+ id: PipelineSlotSchema,
17001
+ label: string(),
17002
+ priority: number(),
17003
+ parentSlot: PipelineSlotSchema.nullable(),
17004
+ addons: array(PipelineAddonSchemaSchema).readonly()
16984
17005
  });
16985
- /**
16986
- * Row projection for track list queries. `full` (default) returns the
16987
- * complete Track including the frame-rate `positions[]` history and the
16988
- * `snapshots[]` references — megabytes across a page of tracks. `slim`
16989
- * keeps every scalar the list surfaces actually render (ids, class(es),
16990
- * label / audioLabels / importance enrichment, firstSeen/lastSeen, state,
16991
- * zonesVisited, bestEventId, envelope, hasFace, hasEmbeddedFace, hasRider) and returns `positions` /
16992
- * `snapshots` as EMPTY arrays — detail views re-fetch the full row via
16993
- * `getTrack`. Mirrors the event-store `projection` convention
16994
- * (`getObjectEvents` et al.).
16995
- */
16996
- var TrackProjectionSchema = _enum(["full", "slim"]);
16997
- /**
16998
- * One audio-classification label heard on the track's camera while the
16999
- * track was alive, aggregated per label. An "episode" is one persisted
17000
- * audio event (the confident-classification path: score ≥ the device's
17001
- * `classificationMinScore`, class-change-or-heartbeat coalesced) — NOT
17002
- * one 32 ms inference chunk, so counts stay human-scaled.
17003
- */
17004
- var TrackAudioLabelSchema = object({
17005
- label: string(),
17006
- /** Highest classification score observed across the label's episodes. */
17007
- peakScore: number(),
17008
- /** Number of coalesced audio-event episodes carrying this label. */
17009
- count: number(),
17010
- firstAt: number(),
17011
- lastAt: number()
17006
+ var PipelineSchemaSchema = object({
17007
+ availableEngines: array(AvailableEngineSchema).readonly(),
17008
+ selectedEngine: PipelineEngineChoiceSchema,
17009
+ slots: array(PipelineSlotSchemaSchema).readonly()
17012
17010
  });
17013
- /**
17014
- * How a track was produced. `pipeline` (default / absent) = the spatial
17015
- * detection+tracking pipeline. Every OTHER value is a SYNTHETIC projection —
17016
- * no positions, a single snapshot, and no bbox trajectory at all:
17017
- *
17018
- * - `sensor` — a linked sensor/control device state change.
17019
- * - `audio` — an audio event on the camera itself that was anomalous for
17020
- * THAT camera, loud, and heard while nothing visual was happening (D62).
17021
- *
17022
- * The spatial subsystems (tracker association, occupancy count, re-id /
17023
- * embedding, resurrection) MUST skip every synthetic source. Test for that
17024
- * with `isSpatialTrack`, which allow-lists `pipeline` — a `!== 'sensor'`
17025
- * check silently readmits every source added after it was written.
17026
- */
17027
- var TrackSourceSchema = _enum([
17028
- "pipeline",
17029
- "sensor",
17030
- "audio"
17031
- ]);
17032
- /**
17033
- * Where a track sits in the RETRAIN lifecycle (D81).
17034
- *
17035
- * - `none` never marked, or un-marked. Evictable.
17036
- * - `staging`the operator wants this track as training material and has not
17037
- * finished with it. **This is the only state retention holds**: the track and
17038
- * everything it owns (object events, crops, keyframes, CLIP vector) survive
17039
- * the device's age window.
17040
- * - `trained` — the retrain page has taken what it needed. The frames it chose
17041
- * were COPIED into the retrain dataset at selection time, so the dataset no
17042
- * longer depends on the track's media and the track becomes EVICTABLE again.
17043
- * Terminal for the plain `markForTrain` toggle: returning it to `staging` is
17044
- * a deliberate action of the retrain page, not a side effect of a checkbox.
17045
- *
17046
- * There is no `null`. The state is stored `TEXT NOT NULL DEFAULT 'none'` because
17047
- * the store's filter language has only positive equality and `whereIn` — no
17048
- * negation, no IS NULL — so a NULL would be unselectable by ANY predicate and
17049
- * would make the entire pre-column history immortal in one deploy.
17050
- */
17051
- var RetrainStatusSchema = _enum([
17052
- "none",
17053
- "staging",
17054
- "trained"
17055
- ]);
17056
- /**
17057
- * Per-track OPERATOR flags — set by hand from the admin UI or the viewer, never
17058
- * by the pipeline. Spread into `TrackSchema` and `KeyEventSchema` from one place
17059
- * so the two surfaces cannot drift.
17060
- *
17061
- * **Absent ≠ false.** A track that has never been touched omits the field; an
17062
- * explicitly un-flagged track carries `false`. Legacy rows written before the
17063
- * columns existed read as absent, and a consumer that needs a boolean should say
17064
- * `flag === true`, not `flag !== false`.
17065
- *
17066
- * `markForTrain` is the WIRE FACE of {@link RetrainStatusSchema}, not a column:
17067
- * it is exactly `retrainStatus === 'staging'`, in both directions. Writing
17068
- * `true` moves `none → staging`, writing `false` moves `staging → none`, and a
17069
- * `trained` track reports `false` while refusing both writes. The boolean is
17070
- * kept because three surfaces drive a toggle off it; anything that needs to tell
17071
- * "never marked" from "already trained" must read `retrainStatus`.
17072
- *
17073
- * `debug` does NOT pin; it is attention, not durability.
17074
- *
17075
- * `favourited` IS a BOOLEAN pin (durability bit), not a retrain lifecycle.
17076
- * A favourited track is skipped by retention the same way `staging` is, but
17077
- * it does not enter `none|staging|trained` and has no staging budget.
17078
- */
17079
- var TrackFlagFields = {
17080
- /** Operator marked this track as training material — i.e. `retrainStatus` is
17081
- * `'staging'`. */
17082
- markForTrain: boolean().optional(),
17083
- /** Operator marked this track for diagnostic attention. */
17084
- debug: boolean().optional(),
17085
- /** Operator favourited this track. Pins it against pruning. */
17086
- favourited: boolean().optional()
17087
- };
17088
- /**
17089
- * The lifecycle field itself, on the READ surfaces only (`Track`, `KeyEvent`).
17090
- * Deliberately NOT part of {@link TrackFlagFields}: that group also builds the
17091
- * write patch, and the status is not something the toggle sets — it is what the
17092
- * toggle's boolean is derived from. Absent on an in-RAM track never touched;
17093
- * always present on a persisted row (the column default materialises `'none'`).
17094
- */
17095
- var TrackRetrainFields = { retrainStatus: RetrainStatusSchema.optional() };
17096
- /**
17097
- * The write half: a PARTIAL patch. An omitted key is left untouched, so setting
17098
- * one flag can never clear the other — the toggles are independent and are
17099
- * driven from three surfaces that do not know about each other.
17100
- */
17101
- var TrackFlagsPatchSchema = object(TrackFlagFields);
17102
- /**
17103
- * The resolved flag state after a write. Both fields are REQUIRED here (absent
17104
- * collapses to `false`) so a caller can drive a toggle's checked state off the
17105
- * mutation result without a re-fetch.
17106
- */
17107
- var TrackFlagsSchema = object({
17108
- trackId: string(),
17109
- markForTrain: boolean(),
17110
- debug: boolean(),
17111
- favourited: boolean(),
17112
- /** The lifecycle state the boolean was derived from. Required here (unlike on
17113
- * a track row) because this shape is only ever produced by the write body,
17114
- * which always knows it — and a surface that has just written needs to render
17115
- * `trained` without a re-fetch. */
17116
- retrainStatus: RetrainStatusSchema
17011
+ var EngineProvisioningSchema = object({
17012
+ runtimeId: _enum([
17013
+ "onnx",
17014
+ "openvino",
17015
+ "coreml",
17016
+ "edgetpu"
17017
+ ]).nullable(),
17018
+ device: string().nullable(),
17019
+ state: _enum([
17020
+ "idle",
17021
+ "installing",
17022
+ "verifying",
17023
+ "ready",
17024
+ "failed"
17025
+ ]),
17026
+ progress: number().optional(),
17027
+ error: string().optional(),
17028
+ nextRetryAt: number().optional(),
17029
+ /**
17030
+ * Gate A (config-correctness gate at engine change): human-readable
17031
+ * config issues surfaced EAGERLY when the node's engine changes — model
17032
+ * substitutions ("chose X, running Y") and zero-build steps ("no model
17033
+ * has a <format> build"). Additive/optional: informational only, never
17034
+ * enforced here `assertEngineReady` (readiness) still gates inference.
17035
+ * Absent/empty when the node-default tree resolves cleanly.
17036
+ */
17037
+ configIssues: array(string()).optional()
17117
17038
  });
17118
- union([literal(1), literal(2)]);
17119
- /**
17120
- * WHO decided a label, and when. Carried per tier so a value can be traced to
17121
- * the step and model that produced it — which is what makes the write rule
17122
- * arguable after the fact ("why is 592's label `dog` and not `Canis lupus`?")
17123
- * and what lets a migrated, UNATTRIBUTED value be told apart from a real one.
17124
- *
17125
- * `stepId` is the pipeline step id (`animal-classifier`, `bird-classifier`,
17126
- * `plate-ocr`, `face-embedding`, `object-detection`), or the sentinel
17127
- * `migration:4g` for a value the 4g migration moved from the single-slot era —
17128
- * that value has no provenance, and the write rule lets ANY properly-attributed
17129
- * write of the same tier replace it regardless of score.
17130
- */
17131
- var LabelAttributionSchema = object({
17132
- stepId: string(),
17039
+ var PipelineStepInputSchema = lazy(() => object({
17040
+ addonId: string(),
17133
17041
  modelId: string().optional(),
17134
- decidedAt: number(),
17042
+ enabled: boolean().default(true),
17043
+ children: array(PipelineStepInputSchema).optional(),
17044
+ settings: record(string(), unknown()).optional(),
17045
+ jumpDeviceKey: string().optional()
17046
+ }));
17047
+ var ModelSubstitutionSchema = object({
17048
+ addonId: string(),
17049
+ chosen: string(),
17050
+ running: string(),
17051
+ format: string()
17052
+ });
17053
+ var PipelineValidationIssueSchema = object({
17054
+ addonId: string(),
17055
+ kind: _enum(["unknown-addon", "no-format-build"]),
17056
+ detail: string()
17057
+ });
17058
+ var PipelineValidationResultSchema = object({
17059
+ ok: boolean(),
17060
+ issues: array(PipelineValidationIssueSchema).readonly(),
17061
+ substitutions: array(ModelSubstitutionSchema).readonly(),
17062
+ /** The node's `currentEngine.format` this validation ran against. */
17063
+ format: string()
17064
+ });
17065
+ var ReferenceImageEntrySchema = object({
17066
+ filename: string(),
17067
+ stepIds: array(string()).readonly().optional()
17068
+ });
17069
+ var ReferenceImageBodySchema = object({
17070
+ base64: string(),
17071
+ filename: string()
17072
+ });
17073
+ var ReferenceAudioEntrySchema = object({
17074
+ filename: string(),
17075
+ sizeKb: number()
17076
+ });
17077
+ var ReferenceAudioBodySchema = object({ base64: string() });
17078
+ var AudioBackendSchema = object({
17079
+ id: string(),
17080
+ name: string(),
17081
+ description: string(),
17082
+ available: boolean(),
17135
17083
  /**
17136
- * The GALLERY id behind a recognised tier-2 label — a face-gallery
17137
- * `Identity.id` or a plate-gallery `Vehicle.id` (both `randomUUID`).
17138
- *
17139
- * The text alone is a DISPLAY NAME, and a display name is renameable: a
17140
- * notification rule authored on "Gianluca" stopped matching the moment the
17141
- * operator fixed the spelling in the gallery, and nothing said so. The id is
17142
- * the thing that does not move, so it is what a rule matches on
17143
- * (`NcConditions.identities`) and the text is what a human is shown.
17144
- *
17145
- * Absent when the label names no gallery row — a plate the OCR read but no
17146
- * vehicle claims, a sub-class, a species, any tier-1 value.
17084
+ * Raw classifier labels this backend can emit (e.g. YAMNet's
17085
+ * 521-class set or Apple SoundAnalysis's 303-class set). Used by
17086
+ * the benchmark UI to populate the `enabledMicroClasses` filter
17087
+ * specific to the selected backend without a separate fetch.
17147
17088
  */
17148
- identityId: string().optional()
17089
+ rawLabels: array(string()).readonly().optional()
17090
+ });
17091
+ var AudioCapabilitiesSchema = object({
17092
+ activeBackend: string(),
17093
+ availableBackends: array(AudioBackendSchema).readonly(),
17094
+ sampleRate: number(),
17095
+ chunkDurationMs: number()
17096
+ });
17097
+ var DownloadModelResultSchema = object({
17098
+ filePath: string(),
17099
+ sizeMB: number(),
17100
+ durationMs: number()
17149
17101
  });
17150
17102
  /**
17151
- * The TIERED label model (roadmap 4g), spread into `TrackSchema` and
17152
- * `ObjectEventSchema` from ONE place so the two surfaces cannot drift — a
17153
- * track and its events always answer the same question the same way.
17154
- *
17155
- * Two scalar columns, not an array: every consumer wants "the coarse one" or
17156
- * "the fine one", and an array made both a scan. `label` is tier 1, `subLabel`
17157
- * is tier 2, and each carries its own score + attribution.
17158
- *
17159
- * **Reading it.** What a human should be shown is `subLabel ?? label` — the
17160
- * finest thing known. Before 4g the single `label` column held the finest
17161
- * value, so a consumer that has not been updated reads the tier-1 slot and
17162
- * shows nothing on a species-only row; that is why the migration puts every
17163
- * pre-4g value in tier 2 (it cannot regress a display that reads the fallback)
17164
- * and why the read surfaces were changed in the same train.
17165
- *
17166
- * **Writing it.** The slots are independent, which is the whole point: a
17167
- * tier-1 write (`bird`) can never overwrite a tier-2 value (`Turdus
17168
- * migratorius`), so fineness cannot regress by construction. Within a tier the
17169
- * higher score wins. One rule, one implementation — see
17170
- * `pipeline/label-tier.ts` in addon-post-analysis.
17171
- */
17172
- var TieredLabelFields = {
17173
- /** Tier 1 — the sub-class. See {@link LabelTierSchema}. */
17174
- label: string().optional(),
17175
- /** Confidence of the tier-1 value, as reported by the deciding step. */
17176
- labelScore: number().optional(),
17177
- /** Provenance of the tier-1 value. See {@link LabelAttributionSchema}. */
17178
- labelMeta: LabelAttributionSchema.optional(),
17179
- /** Tier 2 — the instance. See {@link LabelTierSchema}. */
17180
- subLabel: string().optional(),
17181
- /** Confidence of the tier-2 value, as reported by the deciding step. */
17182
- subLabelScore: number().optional(),
17183
- /** Provenance of the tier-2 value. See {@link LabelAttributionSchema}. */
17184
- subLabelMeta: LabelAttributionSchema.optional()
17185
- };
17186
- /** Per-camera slice of a training-export estimate. */
17187
- var TrainingExportDeviceTotalsSchema = object({
17188
- deviceId: number(),
17189
- tracks: number().int(),
17190
- files: number().int(),
17191
- bytes: number().int()
17192
- });
17193
- /**
17194
- * What a training export WOULD contain. Computed from media index rows only —
17195
- * no blob is read to produce this.
17103
+ * Wrapper carrying a single test run's result. Replaces the legacy
17104
+ * ad-hoc `{labels: [{className, originalClass, score}]}` shape with the
17105
+ * canonical `AudioResult` from the Phase 6 output rework: one
17106
+ * `AudioDetection` per class above `minScore`, top-N candidates in
17107
+ * `debug.alternateLabels['audio-classifier']`, per-source timings in
17108
+ * `debug.stepTimings`. The outer `success`/`error` fields stay so the
17109
+ * benchmark UI can still report a clean failure when the classifier
17110
+ * cap isn't available.
17196
17111
  */
17197
- var TrainingExportSummarySchema = object({
17198
- generatedAt: number(),
17199
- trackCount: number().int(),
17200
- fileCount: number().int(),
17201
- byteCount: number().int(),
17202
- /** More marked tracks exist than a single pass carries. */
17203
- truncated: boolean(),
17204
- devices: array(TrainingExportDeviceTotalsSchema).readonly()
17112
+ var AudioTestResultSchema = object({
17113
+ success: boolean(),
17114
+ error: string().optional(),
17115
+ frame: custom().optional()
17205
17116
  });
17206
- var TrackSchema = object({
17207
- trackId: string(),
17208
- deviceId: number(),
17209
- className: string(),
17210
- ...TieredLabelFields,
17211
- producingDeviceName: string().optional(),
17212
- /** Track provenance. Absent `pipeline` (legacy rows). */
17213
- source: TrackSourceSchema.optional(),
17214
- firstSeen: number(),
17215
- lastSeen: number(),
17216
- /** Frame-rate position history (subject to maxPositionHistory cap). */
17217
- positions: array(TrackPositionSchema).readonly(),
17218
- /** Periodic snapshots at snapshotIntervalMs cadence (subject to
17219
- * saveThumbnails policy). */
17220
- snapshots: array(TrackSnapshotSchema).readonly(),
17221
- /** Deduplicated zones the track has entered at least once. Zone IDS. */
17222
- zonesVisited: array(string()).readonly(),
17117
+ var PipelineConfigBridge = custom();
17118
+ var ConfigUISchemaBridge = custom();
17119
+ var ConfigUISchemaNullableBridge = custom();
17120
+ var InferenceCapabilitiesBridge = custom();
17121
+ var ModelAvailabilityListBridge = custom();
17122
+ var PipelineRunResultBridge = custom();
17123
+ method(_void(), array(PipelineEngineChoiceSchema)), method(_void(), PipelineEngineChoiceSchema), method(PipelineEngineChoiceSchema, array(PipelineDefaultStepSchema)), method(object({ nodeId: string() }), EngineProvisioningSchema), method(_void(), record(string(), object({
17124
+ modelId: string(),
17125
+ settings: record(string(), unknown()).readonly()
17126
+ }))), method(object({ steps: record(string(), object({
17127
+ modelId: string(),
17128
+ settings: record(string(), unknown()).readonly()
17129
+ })) }), object({ success: literal(true) }), {
17130
+ kind: "mutation",
17131
+ auth: "admin"
17132
+ }), method(object({ nodeId: string() }), object({
17133
+ success: literal(true),
17134
+ clearedDevices: number()
17135
+ }), {
17136
+ kind: "mutation",
17137
+ auth: "admin"
17138
+ }), method(object({ nodeId: string() }), object({ unhealthy: array(object({
17139
+ /** `<backend>:<device>`, e.g. `openvino:gpu`. */
17140
+ deviceKey: string(),
17223
17141
  /**
17224
- * Human NAMES for {@link zonesVisited}, resolved at READ time against the
17225
- * `zones` capability.
17226
- *
17227
- * `zonesVisited` persists ids (`cfeec78c-8d69-…`), which no operator can type
17228
- * and no card can render — so every free-text search surface was structurally
17229
- * unable to answer "show me the tracks in Uscio", and did not fail loudly, it
17230
- * just returned nothing. Resolving here rather than in each client keeps ONE
17231
- * derivation and costs the clients no extra call (the `zones` cap is
17232
- * per-device, so a client-side resolve would be a per-camera fan-out on a
17233
- * surface built to avoid exactly that).
17234
- *
17235
- * Resolved, never invented: a zone deleted since the track was written has no
17236
- * name and is DROPPED, so this array can be shorter than `zonesVisited` — the
17237
- * two are not positionally aligned. Absent when the track visited no zone, or
17238
- * when the zone catalogue could not be read.
17142
+ * `failed` the per-device restart budget is exhausted; no pool
17143
+ * will be spawned until an operator re-arms it or the runner
17144
+ * respawns. `backoff` — under budget, waiting out the backoff (or
17145
+ * a cached pool observed dead and not yet condemned).
17239
17146
  */
17240
- zoneNames: array(string()).readonly().optional(),
17241
- /** Deduplicated set of detector classes observed for this track over its
17242
- * life (a track may be reclassified, e.g. person→vehicle). Absent on
17243
- * legacy rows written before class accumulation shipped. */
17244
- classes: array(string()).readonly().optional(),
17245
- /** Cumulative normalized distance travelled (0..1 units = full frame width). */
17246
- totalDistance: number(),
17247
- state: TrackStateSchema,
17248
- active: boolean(),
17249
- /** Deterministic key-event importance score in [0,1] (server-computed at
17250
- * track expiry, recomputed on late label). Absent on legacy rows written
17251
- * before scoring shipped — consumers degrade to absence / compute-on-read. */
17252
- importance: number().optional(),
17253
- /** Id of the track's highest-confidence ObjectEvent (its representative
17254
- * "best" frame). Absent when the track produced no object events. */
17255
- bestEventId: string().optional(),
17256
- /** Tag of the importance sub-signal that dominated the score
17257
- * (identity|dwell|proximity|class|confidence|travel|zone). */
17258
- importanceReason: string().optional(),
17259
- /** Audio-classification labels heard on the camera during the track's
17260
- * life (score ≥ device `classificationMinScore`), aggregated per label.
17261
- * Absent on legacy rows / tracks with no confident audio. */
17262
- audioLabels: array(TrackAudioLabelSchema).readonly().optional(),
17263
- /** Normalized 0..1 trajectory envelope (see {@link TrackEnvelopeSchema}).
17264
- * Populated from the persisted envelope columns on historical reads;
17265
- * absent on legacy rows, dims-less tracks and active (in-RAM) tracks. */
17266
- envelope: TrackEnvelopeSchema.optional(),
17147
+ state: _enum(["failed", "backoff"]),
17148
+ /** Epoch ms of the death that produced this state. */
17149
+ since: number(),
17150
+ /** Pool deaths inside the current window. */
17151
+ deaths: number(),
17152
+ /** The last death's message. */
17153
+ lastError: string()
17154
+ })).readonly() })), method(object({
17155
+ nodeId: string(),
17156
+ deviceKey: string()
17157
+ }), object({ rearmed: boolean() }), {
17158
+ kind: "mutation",
17159
+ auth: "admin"
17160
+ }), 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({
17161
+ name: string(),
17162
+ steps: array(PipelineTemplateStepSchema).readonly(),
17163
+ engine: PipelineEngineChoiceSchema
17164
+ }), PipelineTemplateSchema$1, { kind: "mutation" }), method(object({
17165
+ id: string(),
17166
+ name: string().optional(),
17167
+ steps: array(PipelineTemplateStepSchema).readonly().optional()
17168
+ }), PipelineTemplateSchema$1, { kind: "mutation" }), method(object({ id: string() }), _void(), { kind: "mutation" }), method(_void(), InferenceCapabilitiesBridge), method(object({ addonId: string() }), ModelAvailabilityListBridge), method(object({
17169
+ addonId: string(),
17170
+ modelId: string(),
17171
+ format: ModelFormatSchema$1
17172
+ }), DownloadModelResultSchema, { kind: "mutation" }), method(object({
17173
+ addonId: string(),
17174
+ modelId: string(),
17175
+ format: ModelFormatSchema$1
17176
+ }), object({ success: literal(true) }), { kind: "mutation" }), method(object({
17177
+ engine: PipelineEngineChoiceSchema.optional(),
17178
+ steps: array(PipelineStepInputSchema).min(1),
17179
+ frame: FrameInputSchema.optional(),
17267
17180
  /**
17268
- * A face DETECTOR found a face on this track — nothing more. It says the
17269
- * detail plane produced a `face` detail; it does NOT say the face was
17270
- * embedded, matched, above `minFacePx`, or that the recognizer was even
17271
- * enabled. Set once and never cleared.
17272
- *
17273
- * **This exists so "face present but not recognised" is expressible.** A
17274
- * recognised identity lands in `subLabel` (attributed to the face chain via
17275
- * `subLabelMeta.stepId`), so before this field a track with an unmatched face
17276
- * and a track with no face at all were byte-identical on the wire and no
17277
- * surface could tell them apart. The read is `hasFace === true && subLabel
17278
- * === undefined`.
17279
- *
17280
- * **Absent ≠ false.** Every row written before the column existed omits it,
17281
- * and so does every server that predates the field — a consumer must test
17282
- * `=== true` and render nothing otherwise, never infer "no face".
17181
+ * Process-local lazy frame. Valid only when caller and provider resolve
17182
+ * in the same execution-group process; split/cross-node callers use
17183
+ * `frame`/`image` inline compatibility instead.
17283
17184
  */
17284
- hasFace: boolean().optional(),
17185
+ frameRef: FrameRefSchema.optional(),
17285
17186
  /**
17286
- * This track has a face row IN THE GALLERY: a crop **and** an embedding a
17287
- * face an operator could ASSIGN to an identity.
17288
- *
17289
- * The STRICT twin of {@link hasFace}, and the pair only earns its keep
17290
- * because the two disagree. `hasFace` is stamped at the TOP of the face
17291
- * branch, before every gate, and means no more than "a face detector produced
17292
- * a face detail". This one is stamped at the single moment the gallery row
17293
- * LANDS — after `FaceRecognizer.onTrackEnd` successfully persists it, i.e.
17294
- * past the embedding-magnitude verdict, the `minFacePx` detection gate, the
17295
- * candidate gate, the imageless-track drop (no crop was ever captured) and
17296
- * the crop-store drop. Everything between the detector and that insert can
17297
- * legitimately refuse the face, so a flag written any earlier promises the
17298
- * operator something to assign and delivers nothing.
17299
- *
17300
- * **Independent of recognition.** A face collected but never auto-matched is
17301
- * still assignable — it is in fact the face an operator most wants to reach —
17302
- * so this is NOT gated on `recognizedIdentityId`. Recognition lands in
17303
- * `subLabel`; this says only that the raw material exists.
17304
- *
17305
- * **Set once, never cleared.** A track that produced a gallery row produced
17306
- * one; deleting the row later is the gallery's business, not this flag's.
17307
- *
17308
- * **Absent ≠ false**, the same rule as {@link hasFace}: every row written
17309
- * before the column omits it, and so does every server that predates the
17310
- * field. A consumer must test `=== true` and render nothing otherwise —
17311
- * never infer "no assignable face".
17187
+ * CB5 shm passthrough a `FrameHandle` naming the same ring slot
17188
+ * the decoded pixels live in. One more member of the one-of
17189
+ * frame/frameHandle/image/imageBase64/referenceImage group.
17312
17190
  */
17313
- hasEmbeddedFace: boolean().optional(),
17191
+ frameHandle: FrameHandleSchema.optional(),
17192
+ imageBase64: string().optional(),
17314
17193
  /**
17315
- * This subject CONTAINS a folded rider a person the rider-pairing step
17316
- * ([D34](../decisions/adr-0034.md)) removed from the frame BEFORE the tracker,
17317
- * so the passage is tracked once and as a VEHICLE.
17318
- *
17319
- * It exists because the fold's record was dishonest. D34 and the code both
17320
- * said "the person is not lost — it is reported so both entities stay on the
17321
- * record"; in fact the pair went into a per-processor RAM field behind an
17322
- * accessor nobody called, and every durable surface said `vehicle`, full
17323
- * stop. This is the composition note that makes the row true.
17324
- *
17325
- * A COMPOSITION, never a class and never a label. "This vehicle contains a
17326
- * person" is not an answer to "what is this" — both label tiers would refuse
17327
- * a macro token anyway (D89), and correctly. Nothing here changes what the
17328
- * subject IS: a cyclist stays one vehicle track, occupancy still counts one,
17329
- * and a `person` rule still does not fire for someone cycling past.
17330
- *
17331
- * **Absent ≠ false**, exactly like {@link hasFace}: every row written before
17332
- * the column, and every hub that predates the field, omits it. Test
17333
- * `=== true` and render nothing otherwise — never infer "no rider".
17194
+ * Binary JPEG bytespreferred over `imageBase64` on internal
17195
+ * hops (hub forked worker via Moleculer MsgPack) because it
17196
+ * skips the 33% base64 overhead + the per-call base64 decode on
17197
+ * the detection-pipeline worker. Callers can pass either; exactly
17198
+ * one of `frame`/`image`/`imageBase64`/`referenceImage` is required.
17334
17199
  */
17335
- hasRider: boolean().optional(),
17336
- ...TrackFlagFields,
17337
- ...TrackRetrainFields
17338
- });
17339
- var BaseEventFields = {
17340
- id: string(),
17341
- deviceId: number(),
17342
- timestamp: number()
17343
- };
17344
- var MotionEventSchema = object({
17345
- ...BaseEventFields,
17346
- kind: literal("motion"),
17347
- regionCount: number(),
17348
- /** Heavy JSON array omitted in slim projection. */
17349
- regions: array(object({
17350
- bbox: BoundingBoxSchema,
17351
- pixelCount: number(),
17352
- intensity: number()
17353
- })).readonly().optional(),
17354
- /** Omitted in slim projection. */
17355
- frameWidth: number().optional(),
17356
- /** Omitted in slim projection. */
17357
- frameHeight: number().optional(),
17358
- /** Populated by B5 (recording playback URL for this event). */
17359
- mediaUrl: string().optional()
17360
- });
17200
+ image: _instanceof(Uint8Array).optional(),
17201
+ referenceImage: string().optional(),
17202
+ deviceId: number().optional(),
17203
+ sessionId: string().optional(),
17204
+ /**
17205
+ * Execution plane. 'full' (default) runs the whole tree — benchmark,
17206
+ * reference-image, and detail-subtree calls. 'frame' is the live
17207
+ * per-frame dispatch: ONLY root-plane steps run; crop children
17208
+ * (inputClasses ≠ null) are skipped and served per-track via
17209
+ * pipelineRunner.runDetailSubtree (two-plane design).
17210
+ */
17211
+ plane: _enum(["full", "frame"]).optional(),
17212
+ /**
17213
+ * Inference-device selector (Phase 2 multi-device). Format
17214
+ * `<backend>:<device>` (e.g. `openvino:gpu`, `edgetpu:usb`, `cpu`).
17215
+ * Omitted ⇒ the runner's default device (current single-engine
17216
+ * behaviour). Selects WHICH device pool of the node runs the call.
17217
+ */
17218
+ deviceKey: string().optional(),
17219
+ /**
17220
+ * Two-plane NATIVE child-crop reference. Set by `runDetailSubtree` ONLY
17221
+ * when the parent crop was resolved from the frame's retained NATIVE
17222
+ * surface (a frameHandle HIT). Lets the executor re-cut a LEAF crop
17223
+ * child's ROI (plate-ocr, face-embedding, leaf classifiers) at native
17224
+ * resolution from that surface — the SAME quality path faces already
17225
+ * had — instead of the downscaled parent tile. `handle` keys the native
17226
+ * surface (node-pinned to its owner); `cropFrameSpace` is the parent
17227
+ * crop's padded/clamped rectangle in FRAME-space pixels, used to compose
17228
+ * the executor's crop-normalized child ROI back into frame-normalized
17229
+ * coordinates. Auxiliary to the image source (`image`/`frame`/…), NOT one
17230
+ * of the mutually-exclusive image inputs. Absent ⇒ tile-crop children
17231
+ * (today's behaviour on the fallback path).
17232
+ */
17233
+ nativeCropRef: NativeCropRefSchema.optional()
17234
+ }), PipelineRunResultBridge, { kind: "mutation" }), method(object({
17235
+ engine: PipelineEngineChoiceSchema.optional(),
17236
+ steps: array(PipelineStepInputSchema).min(1),
17237
+ frames: array(FrameInputSchema).min(1).max(255),
17238
+ deviceId: number().optional(),
17239
+ sessionId: string().optional(),
17240
+ /**
17241
+ * Pure-inference benchmark hint. A NONZERO uint32 pins every frame in
17242
+ * the batch to the Python pool's bench preprocess cache
17243
+ * (`_bench_frame_id`) so a REPEATED benchmark frame is decoded +
17244
+ * preprocessed ONCE and every later inference is a pure-inference cache
17245
+ * hit — the sustained-throughput run measures inference, not
17246
+ * decode+preprocess+infer. Omitted/0 for live frames (all different →
17247
+ * full preprocess every call, correct). Fresh per sustained run;
17248
+ * released via `uncacheFrame`.
17249
+ */
17250
+ frameId: number().int().nonnegative().optional(),
17251
+ /** Inference-device selector (Phase 2 multi-device); see runPipeline. */
17252
+ deviceKey: string().optional()
17253
+ }), object({ results: array(PipelineRunResultBridge).readonly() }), { kind: "mutation" }), method(object({
17254
+ data: _instanceof(Uint8Array),
17255
+ width: number().int().positive(),
17256
+ height: number().int().positive(),
17257
+ format: _enum([
17258
+ "rgb",
17259
+ "bgr",
17260
+ "gray"
17261
+ ])
17262
+ }), object({
17263
+ frameId: number(),
17264
+ width: number(),
17265
+ height: number()
17266
+ }), { kind: "mutation" }), method(object({
17267
+ stepId: string(),
17268
+ frameId: number().int()
17269
+ }), record(string(), unknown()), { kind: "mutation" }), method(object({ frameId: number().int() }), _void(), { kind: "mutation" }), method(_void(), object({
17270
+ batchMode: string(),
17271
+ windowMs: number(),
17272
+ maxBatchSize: number(),
17273
+ concurrency: number()
17274
+ })), method(_void(), array(object({
17275
+ engineKey: string(),
17276
+ engine: PipelineEngineChoiceSchema,
17277
+ modelsLoaded: array(string()).readonly(),
17278
+ inUseByCameras: array(number()).readonly(),
17279
+ /**
17280
+ * Origin of this resident factory.
17281
+ * - `runtime` — main camera-serving engine (no idle TTL).
17282
+ * - `warm-override` — benchmark/test override held in the warm
17283
+ * cache; auto-disposed after the idle TTL.
17284
+ * - `device-pool` — a concurrent per-device pool (Phase 2
17285
+ * multi-device, keyed by `deviceKey`) resolved
17286
+ * via `resolveDeviceFactory`. Runs alongside the
17287
+ * `runtime` engine on a DIFFERENT accelerator
17288
+ * (NPU / iGPU / Coral) — this is how the
17289
+ * Engines tab shows all pools running at once.
17290
+ */
17291
+ kind: _enum([
17292
+ "runtime",
17293
+ "warm-override",
17294
+ "device-pool"
17295
+ ]),
17296
+ /** Native pid of the underlying Python pool (null when no pool). */
17297
+ poolPid: number().nullable(),
17298
+ /** ms since this factory was last used (null when not warm-tracked). */
17299
+ idleMs: number().nullable(),
17300
+ /** Idle TTL after which `warm-override` factories self-evict (null when not applicable). */
17301
+ idleTtlMs: number().nullable()
17302
+ })).readonly()), method(object({ engine: PipelineEngineChoiceSchema }), object({ success: literal(true) }), {
17303
+ kind: "mutation",
17304
+ auth: "admin"
17305
+ }), method(object({
17306
+ engine: PipelineEngineChoiceSchema,
17307
+ force: boolean().optional()
17308
+ }), object({
17309
+ success: boolean(),
17310
+ reason: string().optional()
17311
+ }), {
17312
+ kind: "mutation",
17313
+ auth: "admin"
17314
+ }), 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({
17315
+ addonId: string(),
17316
+ modelId: string(),
17317
+ filename: string().optional(),
17318
+ settings: record(string(), unknown()).optional()
17319
+ }), AudioTestResultSchema, { kind: "mutation" }), method(_void(), ConfigUISchemaNullableBridge);
17361
17320
  /**
17362
- * Which detection SOURCE produced an object event. `pipeline` = the ML
17363
- * detection pipeline (decoded-frame inference); `onboard` = the camera's
17364
- * native on-device AI. Both flow through the SAME analysis layers (zoning,
17365
- * tracking, per-kind persistence) but stay distinguishable so consumers
17366
- * (advanced-notifier, occupancy, …) can select which source(s) to act on.
17367
- * Absent on legacy rows treat as `pipeline`.
17321
+ * Per-stage gating mode applied to the zones a rule references.
17322
+ *
17323
+ * - `include`: the rule contributes to a **whitelist** for its stage.
17324
+ * When at least one `include` rule fires for a stage, only entities
17325
+ * inside one of those zones pass that stage.
17326
+ * - `exclude`: the rule contributes to a **blacklist** for its stage.
17327
+ * Entities inside one of those zones are dropped at that stage.
17328
+ *
17329
+ * `monitor`-style observation (count without filtering) is not a rule
17330
+ * mode — zones without any matching rule are observed naturally by
17331
+ * `zone-analytics` (live snapshot + history), so an "I just want to
17332
+ * count, not filter" use case needs no rule at all.
17368
17333
  */
17369
- var DetectionSourceSchema = _enum(["pipeline", "onboard"]);
17334
+ var ZoneRuleModeEnum = _enum(["include", "exclude"]);
17370
17335
  /**
17371
- * The confirmed zone crossing that produced an object event. Present ONLY on
17372
- * an event emitted BY a crossing (`zone.enter` / `zone.exit`); a movement-state
17373
- * event (`object.entering` / `leaving` / `stationary` / `loitering`) and an
17374
- * appearance event carry none, so a rule asking for a direction fails closed
17375
- * on them.
17336
+ * Per-consumer rule that references existing zones (geometry) and
17337
+ * defines how a specific pipeline stage should treat them. Each
17338
+ * consumer addon owns its own `ZoneRule[]` array in its per-device
17339
+ * settings:
17376
17340
  *
17377
- * Exactly ONE crossing per event: the emitter turns each confirmed crossing
17378
- * into its own event, so a frame in which a track enters A while leaving B
17379
- * produces two events with two directions — never one ambiguous row.
17341
+ * - `addon-motion-wasm` `motionZoneRules: ZoneRule[]` (motion stage)
17342
+ * - `addon-detection-pipeline` `detectionZoneRules: ZoneRule[]` (detection stage)
17343
+ * - future: notification rules, audio gating, etc.
17380
17344
  *
17381
- * `zoneId` is load-bearing for an EXIT: the event's `zones` list is the
17382
- * membership the box has NOW, and by definition it no longer contains the zone
17383
- * that was just left. Without the id here, a zone-scoped rule could never match
17384
- * the exit it asked for.
17345
+ * One rule applies to N zones (`zoneIds[]`) so the operator can
17346
+ * express "ignore motion in ALL of {garden, street}" with a single
17347
+ * rule. `classFilter` narrows the rule to specific object classes
17348
+ * "drop person detections in the street, but keep cars" is one
17349
+ * `exclude` rule with `classFilter: ['person']`.
17350
+ *
17351
+ * `enabled` is a soft toggle — the operator can keep the rule
17352
+ * configured but inert without deleting it.
17385
17353
  */
17386
- var ZoneCrossingSchema = object({
17387
- direction: _enum(["enter", "exit"]),
17388
- /** Admin zone id crossed. */
17389
- zoneId: string(),
17390
- /** Zone display name at crossing time (falls back to the id). */
17391
- zoneName: string().optional()
17392
- });
17393
- var ObjectEventSchema = object({
17394
- ...BaseEventFields,
17395
- kind: literal("object"),
17396
- /** Detection source. Optional for backward-compat; absent ⇒ `pipeline`. */
17397
- source: DetectionSourceSchema.optional(),
17354
+ var ZoneRuleSchema = object({
17355
+ /** Stable rule id — survives edits, used by the UI for diffing. */
17356
+ id: string(),
17357
+ /** Optional human-readable label rendered in the rule editor. */
17358
+ name: string().optional(),
17359
+ /** Zones this rule targets. The rule's `mode` applies to ALL
17360
+ * listed zones (OR-set: a detection in any one of them counts).
17361
+ * At least one zone id required — a rule with no targets is a
17362
+ * configuration mistake and the form validator rejects it. */
17363
+ zoneIds: array(string()).min(1).readonly(),
17364
+ mode: ZoneRuleModeEnum,
17398
17365
  /**
17399
- * Inference-frame id shared by every object event emitted from the SAME frame
17400
- * the "scene/parent" key. Lets a consumer group co-occurring detections (e.g.
17401
- * 2 people + 1 dog) under one full frame, and link a track's frames over time
17402
- * (group by `trackId`, pick a representative `frameId` as the parent frame).
17403
- * Optional for backward-compat with pre-existing rows / the slim projection
17404
- * includes it (it is light). Absent on rows written before this field.
17366
+ * Class names this rule applies to. Empty / undefined rule
17367
+ * applies to every class. Class strings match the `macroClass`
17368
+ * field on detections (e.g. `person`, `car`, `dog`).
17405
17369
  */
17406
- frameId: string().optional(),
17407
- /** Omitted in slim projection. */
17408
- trackId: string().optional(),
17409
- className: string(),
17410
- ...TieredLabelFields,
17411
- /** Omitted in slim projection. */
17412
- confidence: number().optional(),
17413
- /** Heavy JSON — omitted in slim projection. */
17414
- bbox: BoundingBoxSchema.optional(),
17415
- /** Heavy JSON — omitted in slim projection. */
17416
- zones: array(string()).readonly().optional(),
17417
- /** Omitted in slim projection. */
17418
- state: TrackStateSchema.optional(),
17370
+ classFilter: array(string()).readonly().optional(),
17419
17371
  /**
17420
- * The zone crossing this event IS, when it is one. Absent on every other
17421
- * event kind (movement state, appearance, package) see
17422
- * {@link ZoneCrossingSchema}. Omitted in slim projection.
17372
+ * Minimum bbox/mask overlap (0–1) with any of the rule's zones
17373
+ * required to consider an entity "in the zone". Defaults to the
17374
+ * consumer's stage default when omitted. Kept for back-compat with
17375
+ * existing per-rule overrides; new operators pick the value via
17376
+ * `bboxInclusionPct` (operator-friendly 0–100). Whichever field is
17377
+ * set, the lower-level engine reads it as a 0–1 fraction.
17423
17378
  */
17424
- zoneCrossing: ZoneCrossingSchema.optional(),
17425
- /** Detection-frame dimensions in pixels — let consumers normalize the
17426
- * pixel-space `bbox` onto a displayed image. Omitted in slim projection. */
17427
- frameWidth: number().optional(),
17428
- frameHeight: number().optional(),
17429
- /** MediaStore key for the crop attached to this event (if any). */
17430
- mediaKey: string().optional(),
17431
- /** Design B: MediaStore key of the track's native-resolution key frame (the
17432
- * best-detection full frame). Resolve via the event-media data-plane
17433
- * (`/addon/<addonId>/event-media/<keyFrameMediaKey>`) for a detail view that
17434
- * draws `bbox` over the native frame. Absent on legacy rows / non-decoded
17435
- * sources — consumers fall back to `mediaKey` (the tight crop). */
17436
- keyFrameMediaKey: string().optional(),
17437
- /** Populated by B5 (recording playback URL for this event). */
17438
- mediaUrl: string().optional(),
17439
- /** The parent track's key-event importance [0,1], propagated to every object
17440
- * event of the track (so an event row can be sorted by importance without a
17441
- * track join). Absent on legacy rows / before the track was scored. */
17442
- importance: number().optional()
17443
- });
17444
- var AudioEventSchema = object({
17445
- ...BaseEventFields,
17446
- kind: literal("audio"),
17447
- rms: number(),
17448
- dbfs: number(),
17449
- classification: object({
17450
- className: string(),
17451
- originalClass: string().optional(),
17452
- score: number()
17453
- }).optional(),
17454
- /** Populated by B5 (recording playback URL for this event). */
17455
- mediaUrl: string().optional()
17456
- });
17457
- var MediaFileKindEnum = _enum([
17458
- "crop",
17459
- "thumbnail",
17460
- "snapshot",
17461
- "firstFrame",
17462
- "lastFrame",
17463
- "fullFrame",
17464
- "fullFrameBoxed",
17465
- "faceCrop",
17466
- "plateCrop",
17467
- "keyFrame",
17468
- "keyFrameSmall",
17469
- "thumbnailSmall"
17470
- ]);
17471
- var MediaFileSchema = object({
17472
- key: string(),
17473
- kind: MediaFileKindEnum,
17474
- base64: string(),
17475
- sizeBytes: number(),
17476
- timestamp: number()
17379
+ overlapThreshold: number().min(0).max(1).optional(),
17380
+ /**
17381
+ * Operator-friendly version of `overlapThreshold` the percentage
17382
+ * of the detection's bbox that must lie inside the zone for the
17383
+ * rule to match. Documented default is 85%; the engine substitutes
17384
+ * that when the field is omitted (kept optional so existing rules
17385
+ * stored without it stay valid).
17386
+ *
17387
+ * When BOTH `overlapThreshold` and `bboxInclusionPct` are set on a
17388
+ * rule, the engine prefers `bboxInclusionPct` because it's the
17389
+ * field exposed in the UI. Internally both feed the same gate.
17390
+ */
17391
+ bboxInclusionPct: number().min(0).max(100).optional(),
17392
+ /**
17393
+ * When `true` and a detection has a segmentation mask, use the
17394
+ * mask for overlap instead of the bbox. Detection-stage only;
17395
+ * motion rules ignore this field.
17396
+ */
17397
+ preferMask: boolean().optional(),
17398
+ /**
17399
+ * Soft-toggle: `false` disables the rule without deleting it.
17400
+ * Defaults to `true` so operators creating a rule via the UI
17401
+ * see it active immediately.
17402
+ */
17403
+ enabled: boolean().default(true)
17477
17404
  });
17405
+ array(ZoneRuleSchema).readonly();
17478
17406
  /**
17479
- * One media row WITHOUT its bytes.
17407
+ * Zone pure geometry + identity. NO filtering behaviour.
17480
17408
  *
17481
- * A track's media is 5-8 MB of base64 (measured: 7.67 MB across 23 files for a
17482
- * 140 s track), and a client that renders tiles from the media data plane needs
17483
- * to know only WHAT EXISTS the bytes then arrive per tile, lazily, over HTTP
17484
- * with an immutable cache, instead of all at once inside a tRPC response that
17485
- * blocks the whole view.
17409
+ * Zones describe **where** in the frame the operator wants to flag
17410
+ * something; consumer-owned {@link ZoneRule} arrays describe **how**
17411
+ * each pipeline stage uses them. Splitting the two means a single
17412
+ * polygon "Driveway" can simultaneously back a motion-exclude rule,
17413
+ * a detection-include rule on `['car']`, and an occupancy aggregate
17414
+ * — without three duplicated polygons.
17486
17415
  *
17487
- * `sizeBytes` is carried because it is what lets a client decide between the
17488
- * stored blob and a `?variant=thumb` rendering without fetching either.
17416
+ * Owned by the orchestrator addon (provider) and mirrored into the
17417
+ * `zones` device-state slice on every mutation. Consumers
17418
+ * (motion-wasm, pipeline-executor, analytics, admin UI) read either
17419
+ * via `api.zones.listZones` (one-shot) or via `dev.state.zones` (live
17420
+ * mirror with `onChanged`).
17421
+ *
17422
+ * Coordinates are normalised fractions of the frame (0–1) so zones
17423
+ * survive resolution changes and stream profile switches.
17424
+ *
17425
+ * `kind` discriminates between full polygons (closed regions used
17426
+ * for intrusion / occupancy filters) and tripwires (open 2-point
17427
+ * line segments used for cross events). Onboard / firmware-reported
17428
+ * zones (Reolink, ONVIF) are out of scope for now — see the deferred
17429
+ * task list.
17489
17430
  */
17490
- var MediaFileInfoSchema = MediaFileSchema.omit({ base64: true });
17431
+ var ZoneKindEnum = _enum(["polygon", "tripwire"]);
17432
+ /** Polygon vertex in fraction-of-frame coordinates (0–1). */
17433
+ var PolygonPointSchema = object({
17434
+ x: number(),
17435
+ y: number()
17436
+ });
17437
+ /** A camera detection zone — pure geometry/identity. */
17438
+ var ZoneSchema = object({
17439
+ id: string(),
17440
+ name: string(),
17441
+ kind: ZoneKindEnum.default("polygon"),
17442
+ /** Polygon vertices, fraction of frame (0–1). */
17443
+ polygon: array(PolygonPointSchema).readonly(),
17444
+ /** Visual color for UI rendering. */
17445
+ color: string().default("#3b82f6")
17446
+ });
17447
+ DeviceType.Camera, method(object({ deviceId: number() }), array(ZoneSchema).readonly()), method(object({
17448
+ deviceId: number(),
17449
+ zone: ZoneSchema
17450
+ }), _void(), {
17451
+ kind: "mutation",
17452
+ auth: "admin"
17453
+ }), method(object({
17454
+ deviceId: number(),
17455
+ zoneId: string()
17456
+ }), _void(), {
17457
+ kind: "mutation",
17458
+ auth: "admin"
17459
+ }), method(object({
17460
+ deviceId: number(),
17461
+ zone: ZoneSchema
17462
+ }), _void(), {
17463
+ kind: "mutation",
17464
+ auth: "admin"
17465
+ }), object({ zones: array(ZoneSchema).readonly() });
17491
17466
  /**
17492
- * The MACRO tier of an annotation — a CLOSED set.
17467
+ * pipeline-analytics device-scoped wrapper cap. Refines raw
17468
+ * per-frame detections emitted by the pipeline runner into tracked
17469
+ * objects, per-kind event collections (motion / object / audio), and
17470
+ * persisted media. Owns the post-detection domain end-to-end:
17493
17471
  *
17494
- * This is what the exported detector predicts, so a typo here is a new class
17495
- * with one example in it. `label` and `subLabel` are open strings by contrast:
17496
- * the whole point of the page is teaching the model things it does not know
17497
- * yet, and constraining that vocabulary would make it useless.
17472
+ * runner emits PipelineInferenceResult
17473
+ * (event bus)
17474
+ * pipeline-analytics subscriber
17475
+ * SORT tracker + zone engine + state analyzer + event emitter
17476
+ * → three DB collections (one per kind), one FS media tree, one
17477
+ * unified event emitter (FrameTracked + TrackStarted/Ended +
17478
+ * DetectionEvent on bus)
17498
17479
  *
17499
- * A macro class is NEVER a label. The provider refuses a write whose `label` or
17500
- * `subLabel` is one of these values, in any casing, because once `person`
17501
- * exists in both tiers "every person box" stops being answerable without
17502
- * knowing every string anyone ever typed — and the damage is retroactive.
17480
+ * Pure subscriber model. No `processFrame` cap method the runner
17481
+ * already publishes the raw frame on the bus. The cap surface is
17482
+ * only QUERIES + per-device settings, bound on/off via
17483
+ * `device-manager.setWrapperActive`. `defaultActive: true` because
17484
+ * every camera with a detection pipeline wants its raw detections
17485
+ * refined; operators opt out per-device via BindingsTab when needed.
17486
+ *
17487
+ * Replaces the legacy `analysis-pipeline`, `analysis-data-persistence`
17488
+ * (per-device surface) and `track-trail` caps — see P11 cleanup.
17503
17489
  */
17504
- var RetrainMacroClassSchema = _enum([
17490
+ var TrackStateSchema = _enum([
17491
+ "new",
17492
+ "entered",
17493
+ "left",
17494
+ "moving",
17495
+ "idle"
17496
+ ]);
17497
+ var EventKindSchema = _enum([
17498
+ "motion",
17499
+ "object",
17500
+ "audio"
17501
+ ]);
17502
+ /**
17503
+ * Spatial filter for `listTracks` — the rect + polygon variants of the shared
17504
+ * MaskShape vocabulary (see `mask-shape.ts`). Coordinates are NORMALIZED 0..1
17505
+ * of the camera frame (top-left origin), matching the drawing-plane editor.
17506
+ */
17507
+ var TrackZoneFilterSchema = discriminatedUnion("kind", [MaskRectShapeSchema, MaskPolygonShapeSchema]);
17508
+ /** Closed icon vocabulary so clients render a known glyph per kind. */
17509
+ var EventKindIconSchema = _enum([
17510
+ "motion",
17511
+ "audio",
17505
17512
  "person",
17506
17513
  "vehicle",
17507
17514
  "animal",
17515
+ "door",
17516
+ "pir",
17517
+ "smoke",
17518
+ "water",
17519
+ "button",
17508
17520
  "package",
17509
- "face",
17510
- "plate"
17521
+ "generic"
17511
17522
  ]);
17512
- /** A subject to learn, or a phantom to unlearn (taught by OMISSION). */
17513
- var RetrainAnnotationKindSchema = _enum(["subject", "model_error"]);
17514
- /** Did a human draw this box, or did the assist propose it? */
17515
- var RetrainAnnotationSourceSchema = _enum(["operator", "assist"]);
17516
- /** Normalised `[0,1]` rectangle against the FULL frame — the canonical form. */
17517
- var RetrainBboxSchema = object({
17523
+ var EventKindCategorySchema = _enum([
17524
+ "motion",
17525
+ "audio",
17526
+ "detection",
17527
+ "sensor",
17528
+ "control",
17529
+ "custom",
17530
+ "package"
17531
+ ]);
17532
+ /** Taxonomy level — macro (timeline lane) vs sub (events-page leaf). */
17533
+ var EventKindLevelSchema = _enum(["macro", "sub"]);
17534
+ var EventKindDescriptorSchema = object({
17535
+ /** Stable kind id (e.g. 'motion', 'vehicle', 'car', 'lock'). */
17536
+ kind: string(),
17537
+ /** i18n key resolved on the UI side; `label` is the English fallback. */
17538
+ labelKey: string(),
17539
+ /** English fallback label (kept for clients that don't translate). */
17540
+ label: string(),
17541
+ /** Hex color for timeline/legend rendering. */
17542
+ color: string(),
17543
+ /** Dictionary id → lucide component on the UI side. */
17544
+ iconId: string(),
17545
+ /** Legacy closed-vocab glyph — fallback for `iconId`. */
17546
+ icon: EventKindIconSchema,
17547
+ category: EventKindCategorySchema,
17548
+ /** Macro parent for this kind ('car' → 'vehicle'); null for a macro. */
17549
+ parentKind: string().nullable(),
17550
+ /** Derived from `parentKind`, explicit for the client tree. */
17551
+ level: EventKindLevelSchema,
17552
+ /** Which cap + device contributes this kind. For built-ins the camera
17553
+ * itself; for sensor kinds the LINKED source device. */
17554
+ source: object({
17555
+ capName: string(),
17556
+ deviceId: number()
17557
+ })
17558
+ });
17559
+ /** One camera's event vocabulary, as returned by `listEventKindsBatch`. */
17560
+ var EventKindsForDeviceSchema = object({
17561
+ deviceId: number(),
17562
+ kinds: array(EventKindDescriptorSchema).readonly()
17563
+ });
17564
+ var SensorEventSchema = object({
17565
+ id: string(),
17566
+ /** The CAMERA the event is attributed to (a sensor linked to N cameras
17567
+ * yields N rows, one per camera). */
17568
+ deviceId: number(),
17569
+ /** The linked sensor device whose state changed. */
17570
+ sourceDeviceId: number(),
17571
+ /** Event kind id — matches an `EventKindDescriptor.kind`. */
17572
+ kind: string(),
17573
+ /** Snapshot of the sensor cap's runtime-state slice at the change. */
17574
+ value: record(string(), unknown()).nullable(),
17575
+ timestamp: number()
17576
+ });
17577
+ var TrackPositionSchema = object({
17518
17578
  x: number(),
17519
17579
  y: number(),
17520
- w: number(),
17521
- h: number()
17580
+ timestamp: number(),
17581
+ bbox: BoundingBoxSchema
17582
+ });
17583
+ var TrackSnapshotSchema = object({
17584
+ timestamp: number(),
17585
+ position: TrackPositionSchema,
17586
+ /** MediaStore key; resolve via `getTrackMedia({ trackId })`. */
17587
+ mediaKey: string()
17522
17588
  });
17523
17589
  /**
17524
- * One annotated subject.
17525
- *
17526
- * `bbox` is normalised against the full frame, ALWAYS. The per-model shapes
17527
- * (letterboxed root / zone-cropped package / subject-cropped classifier) are
17528
- * derived from it at export and never stored — storing them is how one feature
17529
- * space ends up holding two crops of the same subject (D52).
17530
- */
17531
- var RetrainAnnotationSchema = object({
17532
- id: string(),
17590
+ * Normalized 0..1 trajectory envelope (min/max over every position bbox,
17591
+ * divided by the track's detection-frame dims), computed at persist time.
17592
+ * Absent when the frame dims were unknown when the track was persisted
17593
+ * (legacy rows / dims-less sources) and on active (in-RAM) tracks.
17594
+ */
17595
+ var TrackEnvelopeSchema = object({
17596
+ minX: number(),
17597
+ minY: number(),
17598
+ maxX: number(),
17599
+ maxY: number()
17600
+ });
17601
+ /**
17602
+ * Row projection for track list queries. `full` (default) returns the
17603
+ * complete Track including the frame-rate `positions[]` history and the
17604
+ * `snapshots[]` references — megabytes across a page of tracks. `slim`
17605
+ * keeps every scalar the list surfaces actually render (ids, class(es),
17606
+ * label / audioLabels / importance enrichment, firstSeen/lastSeen, state,
17607
+ * zonesVisited, bestEventId, envelope, hasFace, hasEmbeddedFace, hasRider) and returns `positions` /
17608
+ * `snapshots` as EMPTY arrays — detail views re-fetch the full row via
17609
+ * `getTrack`. Mirrors the event-store `projection` convention
17610
+ * (`getObjectEvents` et al.).
17611
+ */
17612
+ var TrackProjectionSchema = _enum(["full", "slim"]);
17613
+ /**
17614
+ * One audio-classification label heard on the track's camera while the
17615
+ * track was alive, aggregated per label. An "episode" is one persisted
17616
+ * audio event (the confident-classification path: score ≥ the device's
17617
+ * `classificationMinScore`, class-change-or-heartbeat coalesced) — NOT
17618
+ * one 32 ms inference chunk, so counts stay human-scaled.
17619
+ */
17620
+ var TrackAudioLabelSchema = object({
17621
+ label: string(),
17622
+ /** Highest classification score observed across the label's episodes. */
17623
+ peakScore: number(),
17624
+ /** Number of coalesced audio-event episodes carrying this label. */
17625
+ count: number(),
17626
+ firstAt: number(),
17627
+ lastAt: number()
17628
+ });
17629
+ /**
17630
+ * How a track was produced. `pipeline` (default / absent) = the spatial
17631
+ * detection+tracking pipeline. Every OTHER value is a SYNTHETIC projection —
17632
+ * no positions, a single snapshot, and no bbox trajectory at all:
17633
+ *
17634
+ * - `sensor` — a linked sensor/control device state change.
17635
+ * - `audio` — an audio event on the camera itself that was anomalous for
17636
+ * THAT camera, loud, and heard while nothing visual was happening (D62).
17637
+ *
17638
+ * The spatial subsystems (tracker association, occupancy count, re-id /
17639
+ * embedding, resurrection) MUST skip every synthetic source. Test for that
17640
+ * with `isSpatialTrack`, which allow-lists `pipeline` — a `!== 'sensor'`
17641
+ * check silently readmits every source added after it was written.
17642
+ */
17643
+ var TrackSourceSchema = _enum([
17644
+ "pipeline",
17645
+ "sensor",
17646
+ "audio"
17647
+ ]);
17648
+ /**
17649
+ * Where a track sits in the RETRAIN lifecycle (D81).
17650
+ *
17651
+ * - `none` — never marked, or un-marked. Evictable.
17652
+ * - `staging` — the operator wants this track as training material and has not
17653
+ * finished with it. **This is the only state retention holds**: the track and
17654
+ * everything it owns (object events, crops, keyframes, CLIP vector) survive
17655
+ * the device's age window.
17656
+ * - `trained` — the retrain page has taken what it needed. The frames it chose
17657
+ * were COPIED into the retrain dataset at selection time, so the dataset no
17658
+ * longer depends on the track's media and the track becomes EVICTABLE again.
17659
+ * Terminal for the plain `markForTrain` toggle: returning it to `staging` is
17660
+ * a deliberate action of the retrain page, not a side effect of a checkbox.
17661
+ *
17662
+ * There is no `null`. The state is stored `TEXT NOT NULL DEFAULT 'none'` because
17663
+ * the store's filter language has only positive equality and `whereIn` — no
17664
+ * negation, no IS NULL — so a NULL would be unselectable by ANY predicate and
17665
+ * would make the entire pre-column history immortal in one deploy.
17666
+ */
17667
+ var RetrainStatusSchema = _enum([
17668
+ "none",
17669
+ "staging",
17670
+ "trained"
17671
+ ]);
17672
+ /**
17673
+ * Per-track OPERATOR flags — set by hand from the admin UI or the viewer, never
17674
+ * by the pipeline. Spread into `TrackSchema` and `KeyEventSchema` from one place
17675
+ * so the two surfaces cannot drift.
17676
+ *
17677
+ * **Absent ≠ false.** A track that has never been touched omits the field; an
17678
+ * explicitly un-flagged track carries `false`. Legacy rows written before the
17679
+ * columns existed read as absent, and a consumer that needs a boolean should say
17680
+ * `flag === true`, not `flag !== false`.
17681
+ *
17682
+ * `markForTrain` is the WIRE FACE of {@link RetrainStatusSchema}, not a column:
17683
+ * it is exactly `retrainStatus === 'staging'`, in both directions. Writing
17684
+ * `true` moves `none → staging`, writing `false` moves `staging → none`, and a
17685
+ * `trained` track reports `false` while refusing both writes. The boolean is
17686
+ * kept because three surfaces drive a toggle off it; anything that needs to tell
17687
+ * "never marked" from "already trained" must read `retrainStatus`.
17688
+ *
17689
+ * `debug` does NOT pin; it is attention, not durability.
17690
+ *
17691
+ * `favourited` IS a BOOLEAN pin (durability bit), not a retrain lifecycle.
17692
+ * A favourited track is skipped by retention the same way `staging` is, but
17693
+ * it does not enter `none|staging|trained` and has no staging budget.
17694
+ */
17695
+ var TrackFlagFields = {
17696
+ /** Operator marked this track as training material — i.e. `retrainStatus` is
17697
+ * `'staging'`. */
17698
+ markForTrain: boolean().optional(),
17699
+ /** Operator marked this track for diagnostic attention. */
17700
+ debug: boolean().optional(),
17701
+ /** Operator favourited this track. Pins it against pruning. */
17702
+ favourited: boolean().optional()
17703
+ };
17704
+ /**
17705
+ * The lifecycle field itself, on the READ surfaces only (`Track`, `KeyEvent`).
17706
+ * Deliberately NOT part of {@link TrackFlagFields}: that group also builds the
17707
+ * write patch, and the status is not something the toggle sets — it is what the
17708
+ * toggle's boolean is derived from. Absent on an in-RAM track never touched;
17709
+ * always present on a persisted row (the column default materialises `'none'`).
17710
+ */
17711
+ var TrackRetrainFields = { retrainStatus: RetrainStatusSchema.optional() };
17712
+ /**
17713
+ * The write half: a PARTIAL patch. An omitted key is left untouched, so setting
17714
+ * one flag can never clear the other — the toggles are independent and are
17715
+ * driven from three surfaces that do not know about each other.
17716
+ */
17717
+ var TrackFlagsPatchSchema = object(TrackFlagFields);
17718
+ /**
17719
+ * The resolved flag state after a write. Both fields are REQUIRED here (absent
17720
+ * collapses to `false`) so a caller can drive a toggle's checked state off the
17721
+ * mutation result without a re-fetch.
17722
+ */
17723
+ var TrackFlagsSchema = object({
17533
17724
  trackId: string(),
17534
- deviceId: number(),
17535
- /** The COPY in retrain storage — never the source track's media key. */
17536
- mediaKey: string(),
17537
- bbox: RetrainBboxSchema,
17538
- macroClass: RetrainMacroClassSchema,
17725
+ markForTrain: boolean(),
17726
+ debug: boolean(),
17727
+ favourited: boolean(),
17728
+ /** The lifecycle state the boolean was derived from. Required here (unlike on
17729
+ * a track row) because this shape is only ever produced by the write body,
17730
+ * which always knows it — and a surface that has just written needs to render
17731
+ * `trained` without a re-fetch. */
17732
+ retrainStatus: RetrainStatusSchema
17733
+ });
17734
+ union([literal(1), literal(2)]);
17735
+ /**
17736
+ * WHO decided a label, and when. Carried per tier so a value can be traced to
17737
+ * the step and model that produced it — which is what makes the write rule
17738
+ * arguable after the fact ("why is 592's label `dog` and not `Canis lupus`?")
17739
+ * and what lets a migrated, UNATTRIBUTED value be told apart from a real one.
17740
+ *
17741
+ * `stepId` is the pipeline step id (`animal-classifier`, `bird-classifier`,
17742
+ * `plate-ocr`, `face-embedding`, `object-detection`), or the sentinel
17743
+ * `migration:4g` for a value the 4g migration moved from the single-slot era —
17744
+ * that value has no provenance, and the write rule lets ANY properly-attributed
17745
+ * write of the same tier replace it regardless of score.
17746
+ */
17747
+ var LabelAttributionSchema = object({
17748
+ stepId: string(),
17749
+ modelId: string().optional(),
17750
+ decidedAt: number(),
17751
+ /**
17752
+ * The GALLERY id behind a recognised tier-2 label — a face-gallery
17753
+ * `Identity.id` or a plate-gallery `Vehicle.id` (both `randomUUID`).
17754
+ *
17755
+ * The text alone is a DISPLAY NAME, and a display name is renameable: a
17756
+ * notification rule authored on "Gianluca" stopped matching the moment the
17757
+ * operator fixed the spelling in the gallery, and nothing said so. The id is
17758
+ * the thing that does not move, so it is what a rule matches on
17759
+ * (`NcConditions.identities`) and the text is what a human is shown.
17760
+ *
17761
+ * Absent when the label names no gallery row — a plate the OCR read but no
17762
+ * vehicle claims, a sub-class, a species, any tier-1 value.
17763
+ */
17764
+ identityId: string().optional()
17765
+ });
17766
+ /**
17767
+ * The TIERED label model (roadmap 4g), spread into `TrackSchema` and
17768
+ * `ObjectEventSchema` from ONE place so the two surfaces cannot drift — a
17769
+ * track and its events always answer the same question the same way.
17770
+ *
17771
+ * Two scalar columns, not an array: every consumer wants "the coarse one" or
17772
+ * "the fine one", and an array made both a scan. `label` is tier 1, `subLabel`
17773
+ * is tier 2, and each carries its own score + attribution.
17774
+ *
17775
+ * **Reading it.** What a human should be shown is `subLabel ?? label` — the
17776
+ * finest thing known. Before 4g the single `label` column held the finest
17777
+ * value, so a consumer that has not been updated reads the tier-1 slot and
17778
+ * shows nothing on a species-only row; that is why the migration puts every
17779
+ * pre-4g value in tier 2 (it cannot regress a display that reads the fallback)
17780
+ * and why the read surfaces were changed in the same train.
17781
+ *
17782
+ * **Writing it.** The slots are independent, which is the whole point: a
17783
+ * tier-1 write (`bird`) can never overwrite a tier-2 value (`Turdus
17784
+ * migratorius`), so fineness cannot regress by construction. Within a tier the
17785
+ * higher score wins. One rule, one implementation — see
17786
+ * `pipeline/label-tier.ts` in addon-post-analysis.
17787
+ */
17788
+ var TieredLabelFields = {
17789
+ /** Tier 1 — the sub-class. See {@link LabelTierSchema}. */
17539
17790
  label: string().optional(),
17791
+ /** Confidence of the tier-1 value, as reported by the deciding step. */
17792
+ labelScore: number().optional(),
17793
+ /** Provenance of the tier-1 value. See {@link LabelAttributionSchema}. */
17794
+ labelMeta: LabelAttributionSchema.optional(),
17795
+ /** Tier 2 — the instance. See {@link LabelTierSchema}. */
17540
17796
  subLabel: string().optional(),
17541
- kind: RetrainAnnotationKindSchema,
17542
- source: RetrainAnnotationSourceSchema,
17543
- /** Which model proposed this box or, on a `model_error`, drew the phantom. */
17544
- assistModelId: string().optional(),
17545
- assistScore: number().optional(),
17546
- exportedInBatch: string().optional(),
17547
- createdAt: number()
17797
+ /** Confidence of the tier-2 value, as reported by the deciding step. */
17798
+ subLabelScore: number().optional(),
17799
+ /** Provenance of the tier-2 value. See {@link LabelAttributionSchema}. */
17800
+ subLabelMeta: LabelAttributionSchema.optional()
17801
+ };
17802
+ /** Per-camera slice of a training-export estimate. */
17803
+ var TrainingExportDeviceTotalsSchema = object({
17804
+ deviceId: number(),
17805
+ tracks: number().int(),
17806
+ files: number().int(),
17807
+ bytes: number().int()
17548
17808
  });
17549
- /** The write form — the server owns `id`, `createdAt` and the frame binding. */
17550
- var RetrainAnnotationDraftSchema = RetrainAnnotationSchema.omit({
17551
- id: true,
17552
- trackId: true,
17553
- deviceId: true,
17554
- mediaKey: true,
17555
- createdAt: true,
17556
- exportedInBatch: true
17809
+ /**
17810
+ * What a training export WOULD contain. Computed from media index rows only —
17811
+ * no blob is read to produce this.
17812
+ */
17813
+ var TrainingExportSummarySchema = object({
17814
+ generatedAt: number(),
17815
+ trackCount: number().int(),
17816
+ fileCount: number().int(),
17817
+ byteCount: number().int(),
17818
+ /** More marked tracks exist than a single pass carries. */
17819
+ truncated: boolean(),
17820
+ devices: array(TrainingExportDeviceTotalsSchema).readonly()
17557
17821
  });
17558
- /** A track sitting in `staging`, with everything the worklist needs to rank it. */
17559
- var RetrainTrackSchema = object({
17822
+ var TrackSchema = object({
17560
17823
  trackId: string(),
17561
17824
  deviceId: number(),
17562
17825
  className: string(),
17563
- label: string().optional(),
17826
+ ...TieredLabelFields,
17827
+ producingDeviceName: string().optional(),
17828
+ /** Track provenance. Absent ⇒ `pipeline` (legacy rows). */
17829
+ source: TrackSourceSchema.optional(),
17564
17830
  firstSeen: number(),
17565
17831
  lastSeen: number(),
17566
- /** How many frames the dataset already holds from this track. */
17567
- frameCount: number().int(),
17568
- /** How many subjects have been annotated on those frames. `0` with
17569
- * `frameCount: 0` is exactly "staging, still to work". */
17570
- annotationCount: number().int()
17571
- });
17572
- /** A frame the picker may offer — an index row, no blob was read to produce it. */
17573
- var RetrainFrameCandidateSchema = object({
17574
- mediaKey: string(),
17575
- kind: MediaFileKindEnum,
17576
- timestamp: number(),
17577
- sizeBytes: number().int(),
17578
- /** A copy of this original already exists selecting it is free and cannot
17579
- * fail, whatever became of the original. */
17580
- copied: boolean()
17832
+ /** Frame-rate position history (subject to maxPositionHistory cap). */
17833
+ positions: array(TrackPositionSchema).readonly(),
17834
+ /** Periodic snapshots at snapshotIntervalMs cadence (subject to
17835
+ * saveThumbnails policy). */
17836
+ snapshots: array(TrackSnapshotSchema).readonly(),
17837
+ /** Deduplicated zones the track has entered at least once. Zone IDS. */
17838
+ zonesVisited: array(string()).readonly(),
17839
+ /**
17840
+ * Human NAMES for {@link zonesVisited}, resolved at READ time against the
17841
+ * `zones` capability.
17842
+ *
17843
+ * `zonesVisited` persists ids (`cfeec78c-8d69-…`), which no operator can type
17844
+ * and no card can render so every free-text search surface was structurally
17845
+ * unable to answer "show me the tracks in Uscio", and did not fail loudly, it
17846
+ * just returned nothing. Resolving here rather than in each client keeps ONE
17847
+ * derivation and costs the clients no extra call (the `zones` cap is
17848
+ * per-device, so a client-side resolve would be a per-camera fan-out on a
17849
+ * surface built to avoid exactly that).
17850
+ *
17851
+ * Resolved, never invented: a zone deleted since the track was written has no
17852
+ * name and is DROPPED, so this array can be shorter than `zonesVisited` — the
17853
+ * two are not positionally aligned. Absent when the track visited no zone, or
17854
+ * when the zone catalogue could not be read.
17855
+ */
17856
+ zoneNames: array(string()).readonly().optional(),
17857
+ /** Deduplicated set of detector classes observed for this track over its
17858
+ * life (a track may be reclassified, e.g. person→vehicle). Absent on
17859
+ * legacy rows written before class accumulation shipped. */
17860
+ classes: array(string()).readonly().optional(),
17861
+ /** Cumulative normalized distance travelled (0..1 units = full frame width). */
17862
+ totalDistance: number(),
17863
+ state: TrackStateSchema,
17864
+ active: boolean(),
17865
+ /** Deterministic key-event importance score in [0,1] (server-computed at
17866
+ * track expiry, recomputed on late label). Absent on legacy rows written
17867
+ * before scoring shipped — consumers degrade to absence / compute-on-read. */
17868
+ importance: number().optional(),
17869
+ /** Id of the track's highest-confidence ObjectEvent (its representative
17870
+ * "best" frame). Absent when the track produced no object events. */
17871
+ bestEventId: string().optional(),
17872
+ /** Tag of the importance sub-signal that dominated the score
17873
+ * (identity|dwell|proximity|class|confidence|travel|zone). */
17874
+ importanceReason: string().optional(),
17875
+ /** Audio-classification labels heard on the camera during the track's
17876
+ * life (score ≥ device `classificationMinScore`), aggregated per label.
17877
+ * Absent on legacy rows / tracks with no confident audio. */
17878
+ audioLabels: array(TrackAudioLabelSchema).readonly().optional(),
17879
+ /** Normalized 0..1 trajectory envelope (see {@link TrackEnvelopeSchema}).
17880
+ * Populated from the persisted envelope columns on historical reads;
17881
+ * absent on legacy rows, dims-less tracks and active (in-RAM) tracks. */
17882
+ envelope: TrackEnvelopeSchema.optional(),
17883
+ /**
17884
+ * A face DETECTOR found a face on this track — nothing more. It says the
17885
+ * detail plane produced a `face` detail; it does NOT say the face was
17886
+ * embedded, matched, above `minFacePx`, or that the recognizer was even
17887
+ * enabled. Set once and never cleared.
17888
+ *
17889
+ * **This exists so "face present but not recognised" is expressible.** A
17890
+ * recognised identity lands in `subLabel` (attributed to the face chain via
17891
+ * `subLabelMeta.stepId`), so before this field a track with an unmatched face
17892
+ * and a track with no face at all were byte-identical on the wire and no
17893
+ * surface could tell them apart. The read is `hasFace === true && subLabel
17894
+ * === undefined`.
17895
+ *
17896
+ * **Absent ≠ false.** Every row written before the column existed omits it,
17897
+ * and so does every server that predates the field — a consumer must test
17898
+ * `=== true` and render nothing otherwise, never infer "no face".
17899
+ */
17900
+ hasFace: boolean().optional(),
17901
+ /**
17902
+ * This track has a face row IN THE GALLERY: a crop **and** an embedding — a
17903
+ * face an operator could ASSIGN to an identity.
17904
+ *
17905
+ * The STRICT twin of {@link hasFace}, and the pair only earns its keep
17906
+ * because the two disagree. `hasFace` is stamped at the TOP of the face
17907
+ * branch, before every gate, and means no more than "a face detector produced
17908
+ * a face detail". This one is stamped at the single moment the gallery row
17909
+ * LANDS — after `FaceRecognizer.onTrackEnd` successfully persists it, i.e.
17910
+ * past the embedding-magnitude verdict, the `minFacePx` detection gate, the
17911
+ * candidate gate, the imageless-track drop (no crop was ever captured) and
17912
+ * the crop-store drop. Everything between the detector and that insert can
17913
+ * legitimately refuse the face, so a flag written any earlier promises the
17914
+ * operator something to assign and delivers nothing.
17915
+ *
17916
+ * **Independent of recognition.** A face collected but never auto-matched is
17917
+ * still assignable — it is in fact the face an operator most wants to reach —
17918
+ * so this is NOT gated on `recognizedIdentityId`. Recognition lands in
17919
+ * `subLabel`; this says only that the raw material exists.
17920
+ *
17921
+ * **Set once, never cleared.** A track that produced a gallery row produced
17922
+ * one; deleting the row later is the gallery's business, not this flag's.
17923
+ *
17924
+ * **Absent ≠ false**, the same rule as {@link hasFace}: every row written
17925
+ * before the column omits it, and so does every server that predates the
17926
+ * field. A consumer must test `=== true` and render nothing otherwise —
17927
+ * never infer "no assignable face".
17928
+ */
17929
+ hasEmbeddedFace: boolean().optional(),
17930
+ /**
17931
+ * This subject CONTAINS a folded rider — a person the rider-pairing step
17932
+ * ([D34](../decisions/adr-0034.md)) removed from the frame BEFORE the tracker,
17933
+ * so the passage is tracked once and as a VEHICLE.
17934
+ *
17935
+ * It exists because the fold's record was dishonest. D34 and the code both
17936
+ * said "the person is not lost — it is reported so both entities stay on the
17937
+ * record"; in fact the pair went into a per-processor RAM field behind an
17938
+ * accessor nobody called, and every durable surface said `vehicle`, full
17939
+ * stop. This is the composition note that makes the row true.
17940
+ *
17941
+ * A COMPOSITION, never a class and never a label. "This vehicle contains a
17942
+ * person" is not an answer to "what is this" — both label tiers would refuse
17943
+ * a macro token anyway (D89), and correctly. Nothing here changes what the
17944
+ * subject IS: a cyclist stays one vehicle track, occupancy still counts one,
17945
+ * and a `person` rule still does not fire for someone cycling past.
17946
+ *
17947
+ * **Absent ≠ false**, exactly like {@link hasFace}: every row written before
17948
+ * the column, and every hub that predates the field, omits it. Test
17949
+ * `=== true` and render nothing otherwise — never infer "no rider".
17950
+ */
17951
+ hasRider: boolean().optional(),
17952
+ ...TrackFlagFields,
17953
+ ...TrackRetrainFields
17581
17954
  });
17582
- /** A frame the dataset OWNS: bytes copied at selection time. */
17583
- var RetrainFrameSchema = object({
17584
- frameId: string(),
17955
+ var BaseEventFields = {
17956
+ id: string(),
17585
17957
  deviceId: number(),
17586
- trackId: string(),
17587
- /** Provenance only. It may already point at nothing — that is expected. */
17588
- sourceMediaKey: string(),
17589
- sourceKind: MediaFileKindEnum,
17590
- sizeBytes: number().int(),
17591
- width: number().int(),
17592
- height: number().int(),
17593
- copiedAt: number()
17594
- });
17595
- /** Why a copy-on-select could not be honoured — named, never a silent skip. */
17596
- var RetrainCopyRefusalSchema = _enum([
17597
- "source-missing",
17598
- "unreadable-image",
17599
- "write-failed"
17600
- ]);
17601
- var RetrainFrameSelectionSchema = object({
17602
- copied: array(RetrainFrameSchema).readonly(),
17603
- refused: array(object({
17604
- sourceMediaKey: string(),
17605
- reason: RetrainCopyRefusalSchema
17606
- })).readonly()
17607
- });
17608
- var RetrainFrameListSchema = object({
17609
- candidates: array(RetrainFrameCandidateSchema).readonly(),
17610
- copies: array(RetrainFrameSchema).readonly(),
17611
- /** What the page pre-selects — the native key frame when one survives. */
17612
- autoPickMediaKey: string().optional()
17958
+ timestamp: number()
17959
+ };
17960
+ var MotionEventSchema = object({
17961
+ ...BaseEventFields,
17962
+ kind: literal("motion"),
17963
+ regionCount: number(),
17964
+ /** Heavy JSON array — omitted in slim projection. */
17965
+ regions: array(object({
17966
+ bbox: BoundingBoxSchema,
17967
+ pixelCount: number(),
17968
+ intensity: number()
17969
+ })).readonly().optional(),
17970
+ /** Omitted in slim projection. */
17971
+ frameWidth: number().optional(),
17972
+ /** Omitted in slim projection. */
17973
+ frameHeight: number().optional(),
17974
+ /** Populated by B5 (recording playback URL for this event). */
17975
+ mediaUrl: string().optional()
17613
17976
  });
17614
- /** What the operator asked the assist to look for. */
17615
- var RetrainAssistSubjectSchema = discriminatedUnion("kind", [object({
17616
- kind: literal("package"),
17617
- zone: RetrainBboxSchema.optional()
17618
- }), object({
17619
- kind: literal("objects"),
17620
- modelId: string(),
17621
- minScore: number().optional()
17622
- })]);
17623
17977
  /**
17624
- * The assist's answer a discriminated union, because "the model saw nothing"
17625
- * and "this node cannot run that model" lead to different next moves and a
17626
- * nullable result cannot tell them apart.
17978
+ * Which detection SOURCE produced an object event. `pipeline` = the ML
17979
+ * detection pipeline (decoded-frame inference); `onboard` = the camera's
17980
+ * native on-device AI. Both flow through the SAME analysis layers (zoning,
17981
+ * tracking, per-kind persistence) but stay distinguishable so consumers
17982
+ * (advanced-notifier, occupancy, …) can select which source(s) to act on.
17983
+ * Absent on legacy rows ⇒ treat as `pipeline`.
17627
17984
  */
17628
- var RetrainAssistResultSchema = discriminatedUnion("kind", [object({
17629
- kind: literal("proposed"),
17630
- modelId: string(),
17631
- stepId: string(),
17632
- minScore: number(),
17633
- /** Drafts, ready to edit. `source: 'assist'` until the operator touches one. */
17634
- proposals: array(RetrainAnnotationDraftSchema).readonly(),
17635
- /** Returned by the runner but removed by the threshold. */
17636
- belowThreshold: number().int()
17637
- }), object({
17638
- kind: literal("refused"),
17639
- /** `no-zone` is ours; the rest are the runner's own refusal vocabulary. */
17640
- reason: string(),
17641
- detail: string().optional()
17642
- })]);
17643
- /** The outcome of a lifecycle move owned by the retrain page. */
17644
- var RetrainTransitionResultSchema = object({
17645
- trackId: string(),
17646
- /** Where the track ended up, whatever happened. */
17647
- retrainStatus: RetrainStatusSchema,
17648
- /** `false` ⇒ the move was refused or was a no-op; `reason` says which. */
17649
- changed: boolean(),
17650
- reason: _enum([
17651
- "unknown-track",
17652
- "no-frames-copied",
17653
- "not-staging",
17654
- "not-trained",
17655
- "unchanged"
17656
- ]).optional()
17985
+ var DetectionSourceSchema = _enum(["pipeline", "onboard"]);
17986
+ /**
17987
+ * The confirmed zone crossing that produced an object event. Present ONLY on
17988
+ * an event emitted BY a crossing (`zone.enter` / `zone.exit`); a movement-state
17989
+ * event (`object.entering` / `leaving` / `stationary` / `loitering`) and an
17990
+ * appearance event carry none, so a rule asking for a direction fails closed
17991
+ * on them.
17992
+ *
17993
+ * Exactly ONE crossing per event: the emitter turns each confirmed crossing
17994
+ * into its own event, so a frame in which a track enters A while leaving B
17995
+ * produces two events with two directions — never one ambiguous row.
17996
+ *
17997
+ * `zoneId` is load-bearing for an EXIT: the event's `zones` list is the
17998
+ * membership the box has NOW, and by definition it no longer contains the zone
17999
+ * that was just left. Without the id here, a zone-scoped rule could never match
18000
+ * the exit it asked for.
18001
+ */
18002
+ var ZoneCrossingSchema = object({
18003
+ direction: _enum(["enter", "exit"]),
18004
+ /** Admin zone id crossed. */
18005
+ zoneId: string(),
18006
+ /** Zone display name at crossing time (falls back to the id). */
18007
+ zoneName: string().optional()
17657
18008
  });
17658
- var DEFAULT_EVENT_QUERY_LIMIT = 1e3;
17659
- var MAX_EVENT_QUERY_LIMIT = 5e3;
17660
- var DeviceEventQueryInput = object({
17661
- deviceId: number(),
17662
- since: number().optional(),
17663
- until: number().optional(),
17664
- limit: number().int().min(1).max(MAX_EVENT_QUERY_LIMIT).default(DEFAULT_EVENT_QUERY_LIMIT),
17665
- /** `slim` drops heavy JSON fields (regions/bbox/zones) and carries an
17666
- * optional `mediaUrl` (populated by B5). `full` (default) keeps today's
17667
- * exact behaviour. Callers may omit this field the store defaults to
17668
- * `full` when not provided. */
17669
- projection: _enum(["full", "slim"]).optional()
18009
+ var ObjectEventSchema = object({
18010
+ ...BaseEventFields,
18011
+ kind: literal("object"),
18012
+ /** Detection source. Optional for backward-compat; absent ⇒ `pipeline`. */
18013
+ source: DetectionSourceSchema.optional(),
18014
+ /**
18015
+ * Inference-frame id shared by every object event emitted from the SAME frame
18016
+ * the "scene/parent" key. Lets a consumer group co-occurring detections (e.g.
18017
+ * 2 people + 1 dog) under one full frame, and link a track's frames over time
18018
+ * (group by `trackId`, pick a representative `frameId` as the parent frame).
18019
+ * Optional for backward-compat with pre-existing rows / the slim projection
18020
+ * includes it (it is light). Absent on rows written before this field.
18021
+ */
18022
+ frameId: string().optional(),
18023
+ /** Omitted in slim projection. */
18024
+ trackId: string().optional(),
18025
+ className: string(),
18026
+ ...TieredLabelFields,
18027
+ /** Omitted in slim projection. */
18028
+ confidence: number().optional(),
18029
+ /** Heavy JSON — omitted in slim projection. */
18030
+ bbox: BoundingBoxSchema.optional(),
18031
+ /** Heavy JSON — omitted in slim projection. */
18032
+ zones: array(string()).readonly().optional(),
18033
+ /** Omitted in slim projection. */
18034
+ state: TrackStateSchema.optional(),
18035
+ /**
18036
+ * The zone crossing this event IS, when it is one. Absent on every other
18037
+ * event kind (movement state, appearance, package) — see
18038
+ * {@link ZoneCrossingSchema}. Omitted in slim projection.
18039
+ */
18040
+ zoneCrossing: ZoneCrossingSchema.optional(),
18041
+ /** Detection-frame dimensions in pixels — let consumers normalize the
18042
+ * pixel-space `bbox` onto a displayed image. Omitted in slim projection. */
18043
+ frameWidth: number().optional(),
18044
+ frameHeight: number().optional(),
18045
+ /** MediaStore key for the crop attached to this event (if any). */
18046
+ mediaKey: string().optional(),
18047
+ /** Design B: MediaStore key of the track's native-resolution key frame (the
18048
+ * best-detection full frame). Resolve via the event-media data-plane
18049
+ * (`/addon/<addonId>/event-media/<keyFrameMediaKey>`) for a detail view that
18050
+ * draws `bbox` over the native frame. Absent on legacy rows / non-decoded
18051
+ * sources — consumers fall back to `mediaKey` (the tight crop). */
18052
+ keyFrameMediaKey: string().optional(),
18053
+ /** Populated by B5 (recording playback URL for this event). */
18054
+ mediaUrl: string().optional(),
18055
+ /** The parent track's key-event importance [0,1], propagated to every object
18056
+ * event of the track (so an event row can be sorted by importance without a
18057
+ * track join). Absent on legacy rows / before the track was scored. */
18058
+ importance: number().optional()
17670
18059
  });
17671
- var ObjectEventQueryInput = DeviceEventQueryInput.extend({ classFilter: string().optional() });
17672
- var RecentTracksQueryInput = object({
17673
- /** Devices to merge. An empty array yields `{ tracks: [], nextCursor: null }`. */
17674
- deviceIds: array(number()),
17675
- /** Window lower bound on `lastSeen` (inclusive). */
17676
- since: number().optional(),
17677
- /** Window upper bound on `lastSeen` (inclusive). */
17678
- until: number().optional(),
17679
- /** Page size. Default 200, max 1000. */
17680
- limit: number().int().min(1).max(1e3).default(200),
17681
- /** Opaque continuation cursor from a previous page's `nextCursor`.
17682
- * Encodes the (lastSeen, trackId) sort position — treat as opaque. */
17683
- cursor: string().optional(),
17684
- /** See {@link TrackProjectionSchema}. Default `full`. */
17685
- projection: TrackProjectionSchema.optional(),
17686
- /** Include stationary-promoted rows (parked objects). Default false: the
17687
- * feed lists passages; parking records live on the stationary registry. */
17688
- includeStationary: boolean().optional()
18060
+ var AudioEventSchema = object({
18061
+ ...BaseEventFields,
18062
+ kind: literal("audio"),
18063
+ rms: number(),
18064
+ dbfs: number(),
18065
+ classification: object({
18066
+ className: string(),
18067
+ originalClass: string().optional(),
18068
+ score: number()
18069
+ }).optional(),
18070
+ /** Populated by B5 (recording playback URL for this event). */
18071
+ mediaUrl: string().optional()
17689
18072
  });
17690
- var RecentTracksPageSchema = object({
17691
- /** Merged page, ordered by (`lastSeen` DESC, `trackId` DESC). */
17692
- tracks: array(TrackSchema).readonly(),
17693
- /** Cursor for the next page, or null when this page is the last. */
17694
- nextCursor: string().nullable()
18073
+ var MediaFileKindEnum = _enum([
18074
+ "crop",
18075
+ "thumbnail",
18076
+ "snapshot",
18077
+ "firstFrame",
18078
+ "lastFrame",
18079
+ "fullFrame",
18080
+ "fullFrameBoxed",
18081
+ "faceCrop",
18082
+ "plateCrop",
18083
+ "keyFrame",
18084
+ "keyFrameSmall",
18085
+ "thumbnailSmall"
18086
+ ]);
18087
+ var MediaFileSchema = object({
18088
+ key: string(),
18089
+ kind: MediaFileKindEnum,
18090
+ base64: string(),
18091
+ sizeBytes: number(),
18092
+ timestamp: number()
17695
18093
  });
17696
- var LIST_GROUPS_DEFAULT_LIMIT = 40;
17697
- var LIST_GROUPS_MAX_LIMIT = 100;
17698
- var AnalyticsGroupRecordSchema = object({
18094
+ /**
18095
+ * One media row WITHOUT its bytes.
18096
+ *
18097
+ * A track's media is 5-8 MB of base64 (measured: 7.67 MB across 23 files for a
18098
+ * 140 s track), and a client that renders tiles from the media data plane needs
18099
+ * to know only WHAT EXISTS — the bytes then arrive per tile, lazily, over HTTP
18100
+ * with an immutable cache, instead of all at once inside a tRPC response that
18101
+ * blocks the whole view.
18102
+ *
18103
+ * `sizeBytes` is carried because it is what lets a client decide between the
18104
+ * stored blob and a `?variant=thumb` rendering without fetching either.
18105
+ */
18106
+ var MediaFileInfoSchema = MediaFileSchema.omit({ base64: true });
18107
+ /**
18108
+ * The MACRO tier of an annotation — a CLOSED set.
18109
+ *
18110
+ * This is what the exported detector predicts, so a typo here is a new class
18111
+ * with one example in it. `label` and `subLabel` are open strings by contrast:
18112
+ * the whole point of the page is teaching the model things it does not know
18113
+ * yet, and constraining that vocabulary would make it useless.
18114
+ *
18115
+ * A macro class is NEVER a label. The provider refuses a write whose `label` or
18116
+ * `subLabel` is one of these values, in any casing, because once `person`
18117
+ * exists in both tiers "every person box" stops being answerable without
18118
+ * knowing every string anyone ever typed — and the damage is retroactive.
18119
+ */
18120
+ var RetrainMacroClassSchema = _enum([
18121
+ "person",
18122
+ "vehicle",
18123
+ "animal",
18124
+ "package",
18125
+ "face",
18126
+ "plate"
18127
+ ]);
18128
+ /** A subject to learn, or a phantom to unlearn (taught by OMISSION). */
18129
+ var RetrainAnnotationKindSchema = _enum(["subject", "model_error"]);
18130
+ /** Did a human draw this box, or did the assist propose it? */
18131
+ var RetrainAnnotationSourceSchema = _enum(["operator", "assist"]);
18132
+ /** Normalised `[0,1]` rectangle against the FULL frame — the canonical form. */
18133
+ var RetrainBboxSchema = object({
18134
+ x: number(),
18135
+ y: number(),
18136
+ w: number(),
18137
+ h: number()
18138
+ });
18139
+ /**
18140
+ * One annotated subject.
18141
+ *
18142
+ * `bbox` is normalised against the full frame, ALWAYS. The per-model shapes
18143
+ * (letterboxed root / zone-cropped package / subject-cropped classifier) are
18144
+ * derived from it at export and never stored — storing them is how one feature
18145
+ * space ends up holding two crops of the same subject (D52).
18146
+ */
18147
+ var RetrainAnnotationSchema = object({
17699
18148
  id: string(),
17700
- deviceId: number().int(),
17701
- openedAt: number().int(),
17702
- closedAt: number().int(),
17703
- timestamp: number().int(),
17704
- memberCount: number().int(),
17705
- memberTrackIds: array(string()).readonly(),
17706
- className: string(),
17707
- classes: array(string()).readonly(),
17708
- /** Relative event-media path, or null when the group has no picture yet. */
17709
- mediaUrl: string().nullable(),
17710
- singleton: boolean()
18149
+ trackId: string(),
18150
+ deviceId: number(),
18151
+ /** The COPY in retrain storage — never the source track's media key. */
18152
+ mediaKey: string(),
18153
+ bbox: RetrainBboxSchema,
18154
+ macroClass: RetrainMacroClassSchema,
18155
+ label: string().optional(),
18156
+ subLabel: string().optional(),
18157
+ kind: RetrainAnnotationKindSchema,
18158
+ source: RetrainAnnotationSourceSchema,
18159
+ /** Which model proposed this box — or, on a `model_error`, drew the phantom. */
18160
+ assistModelId: string().optional(),
18161
+ assistScore: number().optional(),
18162
+ exportedInBatch: string().optional(),
18163
+ createdAt: number()
17711
18164
  });
17712
- var AnalyticsGroupMemberSchema = object({
18165
+ /** The write form — the server owns `id`, `createdAt` and the frame binding. */
18166
+ var RetrainAnnotationDraftSchema = RetrainAnnotationSchema.omit({
18167
+ id: true,
18168
+ trackId: true,
18169
+ deviceId: true,
18170
+ mediaKey: true,
18171
+ createdAt: true,
18172
+ exportedInBatch: true
18173
+ });
18174
+ /** A track sitting in `staging`, with everything the worklist needs to rank it. */
18175
+ var RetrainTrackSchema = object({
17713
18176
  trackId: string(),
17714
- deviceId: number().int(),
18177
+ deviceId: number(),
17715
18178
  className: string(),
17716
- firstSeen: number().int(),
17717
- lastSeen: number().int(),
17718
- mediaUrl: string().nullable()
17719
- });
17720
- var AnalyticsGroupDetailSchema = AnalyticsGroupRecordSchema.extend({ members: array(AnalyticsGroupMemberSchema).readonly() });
17721
- var ListGroupsQueryInput = object({
17722
- /** Devices to merge. An empty array yields `{ groups: [], nextCursor: null }`. */
17723
- deviceIds: array(number()),
17724
- /** Window lower bound on `closedAt` (inclusive). */
17725
- since: number().optional(),
17726
- /** Window upper bound on `openedAt` (inclusive). */
17727
- until: number().optional(),
17728
- limit: number().int().min(1).max(LIST_GROUPS_MAX_LIMIT).default(LIST_GROUPS_DEFAULT_LIMIT),
17729
- /** Opaque continuation cursor from a previous page's `nextCursor`. */
17730
- cursor: string().optional()
18179
+ label: string().optional(),
18180
+ firstSeen: number(),
18181
+ lastSeen: number(),
18182
+ /** How many frames the dataset already holds from this track. */
18183
+ frameCount: number().int(),
18184
+ /** How many subjects have been annotated on those frames. `0` with
18185
+ * `frameCount: 0` is exactly "staging, still to work". */
18186
+ annotationCount: number().int()
17731
18187
  });
17732
- var ListGroupsPageSchema = object({
17733
- groups: array(AnalyticsGroupRecordSchema).readonly(),
17734
- nextCursor: string().nullable()
18188
+ /** A frame the picker may offer — an index row, no blob was read to produce it. */
18189
+ var RetrainFrameCandidateSchema = object({
18190
+ mediaKey: string(),
18191
+ kind: MediaFileKindEnum,
18192
+ timestamp: number(),
18193
+ sizeBytes: number().int(),
18194
+ /** A copy of this original already exists — selecting it is free and cannot
18195
+ * fail, whatever became of the original. */
18196
+ copied: boolean()
17735
18197
  });
17736
- var KeyEventQueryInput = object({
18198
+ /** A frame the dataset OWNS: bytes copied at selection time. */
18199
+ var RetrainFrameSchema = object({
18200
+ frameId: string(),
17737
18201
  deviceId: number(),
17738
- /** Window lower bound (track firstSeen ≥ since). */
17739
- since: number(),
17740
- /** Window upper bound (track firstSeen ≤ until). */
18202
+ trackId: string(),
18203
+ /** Provenance only. It may already point at nothing — that is expected. */
18204
+ sourceMediaKey: string(),
18205
+ sourceKind: MediaFileKindEnum,
18206
+ sizeBytes: number().int(),
18207
+ width: number().int(),
18208
+ height: number().int(),
18209
+ copiedAt: number()
18210
+ });
18211
+ /** Why a copy-on-select could not be honoured — named, never a silent skip. */
18212
+ var RetrainCopyRefusalSchema = _enum([
18213
+ "source-missing",
18214
+ "unreadable-image",
18215
+ "write-failed"
18216
+ ]);
18217
+ var RetrainFrameSelectionSchema = object({
18218
+ copied: array(RetrainFrameSchema).readonly(),
18219
+ refused: array(object({
18220
+ sourceMediaKey: string(),
18221
+ reason: RetrainCopyRefusalSchema
18222
+ })).readonly()
18223
+ });
18224
+ var RetrainFrameListSchema = object({
18225
+ candidates: array(RetrainFrameCandidateSchema).readonly(),
18226
+ copies: array(RetrainFrameSchema).readonly(),
18227
+ /** What the page pre-selects — the native key frame when one survives. */
18228
+ autoPickMediaKey: string().optional()
18229
+ });
18230
+ /** What the operator asked the assist to look for. */
18231
+ var RetrainAssistSubjectSchema = discriminatedUnion("kind", [object({
18232
+ kind: literal("package"),
18233
+ zone: RetrainBboxSchema.optional()
18234
+ }), object({
18235
+ kind: literal("objects"),
18236
+ modelId: string(),
18237
+ minScore: number().optional()
18238
+ })]);
18239
+ /**
18240
+ * The assist's answer — a discriminated union, because "the model saw nothing"
18241
+ * and "this node cannot run that model" lead to different next moves and a
18242
+ * nullable result cannot tell them apart.
18243
+ */
18244
+ var RetrainAssistResultSchema = discriminatedUnion("kind", [object({
18245
+ kind: literal("proposed"),
18246
+ modelId: string(),
18247
+ stepId: string(),
18248
+ minScore: number(),
18249
+ /** Drafts, ready to edit. `source: 'assist'` until the operator touches one. */
18250
+ proposals: array(RetrainAnnotationDraftSchema).readonly(),
18251
+ /** Returned by the runner but removed by the threshold. */
18252
+ belowThreshold: number().int()
18253
+ }), object({
18254
+ kind: literal("refused"),
18255
+ /** `no-zone` is ours; the rest are the runner's own refusal vocabulary. */
18256
+ reason: string(),
18257
+ detail: string().optional()
18258
+ })]);
18259
+ /** The outcome of a lifecycle move owned by the retrain page. */
18260
+ var RetrainTransitionResultSchema = object({
18261
+ trackId: string(),
18262
+ /** Where the track ended up, whatever happened. */
18263
+ retrainStatus: RetrainStatusSchema,
18264
+ /** `false` ⇒ the move was refused or was a no-op; `reason` says which. */
18265
+ changed: boolean(),
18266
+ reason: _enum([
18267
+ "unknown-track",
18268
+ "no-frames-copied",
18269
+ "not-staging",
18270
+ "not-trained",
18271
+ "unchanged"
18272
+ ]).optional()
18273
+ });
18274
+ var DEFAULT_EVENT_QUERY_LIMIT = 1e3;
18275
+ var MAX_EVENT_QUERY_LIMIT = 5e3;
18276
+ var DeviceEventQueryInput = object({
18277
+ deviceId: number(),
18278
+ since: number().optional(),
18279
+ until: number().optional(),
18280
+ limit: number().int().min(1).max(MAX_EVENT_QUERY_LIMIT).default(DEFAULT_EVENT_QUERY_LIMIT),
18281
+ /** `slim` drops heavy JSON fields (regions/bbox/zones) and carries an
18282
+ * optional `mediaUrl` (populated by B5). `full` (default) keeps today's
18283
+ * exact behaviour. Callers may omit this field — the store defaults to
18284
+ * `full` when not provided. */
18285
+ projection: _enum(["full", "slim"]).optional()
18286
+ });
18287
+ var ObjectEventQueryInput = DeviceEventQueryInput.extend({ classFilter: string().optional() });
18288
+ var RecentTracksQueryInput = object({
18289
+ /** Devices to merge. An empty array yields `{ tracks: [], nextCursor: null }`. */
18290
+ deviceIds: array(number()),
18291
+ /** Window lower bound on `lastSeen` (inclusive). */
18292
+ since: number().optional(),
18293
+ /** Window upper bound on `lastSeen` (inclusive). */
18294
+ until: number().optional(),
18295
+ /** Page size. Default 200, max 1000. */
18296
+ limit: number().int().min(1).max(1e3).default(200),
18297
+ /** Opaque continuation cursor from a previous page's `nextCursor`.
18298
+ * Encodes the (lastSeen, trackId) sort position — treat as opaque. */
18299
+ cursor: string().optional(),
18300
+ /** See {@link TrackProjectionSchema}. Default `full`. */
18301
+ projection: TrackProjectionSchema.optional(),
18302
+ /** Include stationary-promoted rows (parked objects). Default false: the
18303
+ * feed lists passages; parking records live on the stationary registry. */
18304
+ includeStationary: boolean().optional()
18305
+ });
18306
+ var RecentTracksPageSchema = object({
18307
+ /** Merged page, ordered by (`lastSeen` DESC, `trackId` DESC). */
18308
+ tracks: array(TrackSchema).readonly(),
18309
+ /** Cursor for the next page, or null when this page is the last. */
18310
+ nextCursor: string().nullable()
18311
+ });
18312
+ var LIST_GROUPS_DEFAULT_LIMIT = 40;
18313
+ var LIST_GROUPS_MAX_LIMIT = 100;
18314
+ var AnalyticsGroupRecordSchema = object({
18315
+ id: string(),
18316
+ deviceId: number().int(),
18317
+ openedAt: number().int(),
18318
+ closedAt: number().int(),
18319
+ timestamp: number().int(),
18320
+ memberCount: number().int(),
18321
+ memberTrackIds: array(string()).readonly(),
18322
+ className: string(),
18323
+ classes: array(string()).readonly(),
18324
+ /** Relative event-media path, or null when the group has no picture yet. */
18325
+ mediaUrl: string().nullable(),
18326
+ singleton: boolean()
18327
+ });
18328
+ var AnalyticsGroupMemberSchema = object({
18329
+ trackId: string(),
18330
+ deviceId: number().int(),
18331
+ className: string(),
18332
+ firstSeen: number().int(),
18333
+ lastSeen: number().int(),
18334
+ mediaUrl: string().nullable()
18335
+ });
18336
+ var AnalyticsGroupDetailSchema = AnalyticsGroupRecordSchema.extend({ members: array(AnalyticsGroupMemberSchema).readonly() });
18337
+ var ListGroupsQueryInput = object({
18338
+ /** Devices to merge. An empty array yields `{ groups: [], nextCursor: null }`. */
18339
+ deviceIds: array(number()),
18340
+ /** Window lower bound on `closedAt` (inclusive). */
18341
+ since: number().optional(),
18342
+ /** Window upper bound on `openedAt` (inclusive). */
18343
+ until: number().optional(),
18344
+ limit: number().int().min(1).max(LIST_GROUPS_MAX_LIMIT).default(LIST_GROUPS_DEFAULT_LIMIT),
18345
+ /** Opaque continuation cursor from a previous page's `nextCursor`. */
18346
+ cursor: string().optional()
18347
+ });
18348
+ var ListGroupsPageSchema = object({
18349
+ groups: array(AnalyticsGroupRecordSchema).readonly(),
18350
+ nextCursor: string().nullable()
18351
+ });
18352
+ var KeyEventQueryInput = object({
18353
+ deviceId: number(),
18354
+ /** Window lower bound (track firstSeen ≥ since). */
18355
+ since: number(),
18356
+ /** Window upper bound (track firstSeen ≤ until). */
17741
18357
  until: number(),
17742
18358
  limit: number().int().min(1).max(200).default(50),
17743
18359
  /** Drop tracks scoring below this importance. */
@@ -17936,6 +18552,24 @@ var RebuildStatusSchema = object({
17936
18552
  /** Present when the pass ended by throwing. */
17937
18553
  error: string().nullable()
17938
18554
  });
18555
+ var ReplayFrameInputSchema = object({
18556
+ timestamp: number(),
18557
+ frame: PipelineRunResultBridge
18558
+ });
18559
+ var RunReplayFrameProcessorResultSchema = object({ tracks: array(object({
18560
+ className: string(),
18561
+ firstSeenMs: number(),
18562
+ lastSeenMs: number(),
18563
+ /** Bbox of the track's FIRST matched detection, pixel-space in the clip's
18564
+ * frame — a representative box for the diff's `(className, window, IoU)`
18565
+ * pairing (`replay-diff.ts`). A replay does not need the full per-frame
18566
+ * trajectory production's `Track.positions` keeps. */
18567
+ bbox: BoundingBoxSchema,
18568
+ /** How many of the input frames this track matched a real detection on
18569
+ * (never a coasted/extrapolated frame) — the replay's own signal for "how
18570
+ * solid is this track", cheaper than re-deriving it from a trajectory. */
18571
+ framesMatched: number().int()
18572
+ })).readonly() });
17939
18573
  DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).readonly()), method(object({
17940
18574
  deviceId: number(),
17941
18575
  trackId: string()
@@ -18106,502 +18740,80 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
18106
18740
  }), RetrainAssistResultSchema, {
18107
18741
  kind: "mutation",
18108
18742
  auth: "admin"
18109
- }), method(object({ trackId: string() }), array(RetrainAnnotationSchema).readonly(), {
18110
- kind: "query",
18111
- auth: "admin"
18112
- }), method(object({
18113
- deviceId: number(),
18114
- trackId: string(),
18115
- frameId: string(),
18116
- annotations: array(RetrainAnnotationDraftSchema)
18117
- }), array(RetrainAnnotationSchema).readonly(), {
18118
- kind: "mutation",
18119
- auth: "admin"
18120
- }), method(object({
18121
- deviceId: number(),
18122
- trackId: string()
18123
- }), RetrainTransitionResultSchema, {
18124
- kind: "mutation",
18125
- auth: "admin"
18126
18743
  }), method(object({
18127
18744
  deviceId: number(),
18128
- trackId: string()
18129
- }), RetrainTransitionResultSchema, {
18745
+ source: DetectionSourceSchema,
18746
+ zones: array(ZoneSchema).readonly().optional(),
18747
+ detectionRules: array(ZoneRuleSchema).readonly().optional(),
18748
+ zoneMembershipMinOverlap: number().min(0).max(1).optional(),
18749
+ frames: array(ReplayFrameInputSchema).min(1)
18750
+ }), RunReplayFrameProcessorResultSchema, {
18130
18751
  kind: "mutation",
18131
18752
  auth: "admin"
18132
- }), method(object({ deviceIds: array(number()).optional() }), object({ url: string() }), {
18753
+ }), method(object({ trackId: string() }), array(RetrainAnnotationSchema).readonly(), {
18133
18754
  kind: "query",
18134
18755
  auth: "admin"
18135
18756
  }), method(object({
18136
- eventId: string(),
18137
- kind: MediaFileKindEnum.optional(),
18138
- deviceId: number()
18139
- }), array(MediaFileSchema).readonly()), method(object({
18140
- trackId: string(),
18141
- kinds: array(MediaFileKindEnum).optional(),
18142
- deviceId: number()
18143
- }), array(MediaFileSchema).readonly()), method(object({
18144
- trackId: string(),
18145
- deviceId: number()
18146
- }), array(MediaFileInfoSchema).readonly()), method(SearchObjectEventsInput, array(ScoredObjectEventSchema).readonly()), method(object({}), WipeObjectEmbeddingsResultSchema, {
18147
- kind: "mutation",
18148
- auth: "admin"
18149
- }), method(RebuildObjectEmbeddingsInput, RebuildObjectEmbeddingsResultSchema, {
18150
- kind: "mutation",
18151
- auth: "admin"
18152
- }), method(object({}), RebuildStatusSchema), object({
18153
- deviceId: number(),
18154
- timestamp: number(),
18155
- frameWidth: number(),
18156
- frameHeight: number(),
18157
- detections: array(OverlayDetectionSchema).readonly()
18158
- }), object({
18159
- deviceId: number(),
18160
- trackId: string(),
18161
- className: string()
18162
- }), object({
18163
18757
  deviceId: number(),
18164
18758
  trackId: string(),
18165
- className: string(),
18166
- durationMs: number()
18167
- }), object({
18168
- deviceId: number(),
18169
- kind: EventKindSchema,
18170
- eventId: string(),
18171
- timestamp: number()
18172
- });
18173
- /**
18174
- * Reference to the frame's retained NATIVE surface + the parent crop's placement
18175
- * within the frame, so the executor can re-cut a leaf child ROI at native
18176
- * resolution on the detail plane. See the `runPipeline` `nativeCropRef` field.
18177
- */
18178
- var NativeCropRefSchema = object({
18179
- /** Handle keying the retained native surface (node-pinned to its owner). */
18180
- handle: FrameHandleSchema,
18181
- /** The parent crop's padded/clamped rectangle in FRAME-space pixels. */
18182
- cropFrameSpace: object({
18183
- x: number(),
18184
- y: number(),
18185
- w: number(),
18186
- h: number()
18187
- })
18188
- });
18189
- object({
18190
- crop: object({
18191
- left: number(),
18192
- top: number(),
18193
- width: number().positive(),
18194
- height: number().positive()
18195
- }).optional(),
18196
- content: object({
18197
- width: number().int().positive(),
18198
- height: number().int().positive()
18199
- }),
18200
- fit: _enum(["stretch", "contain"]),
18201
- format: _enum([
18202
- "rgb",
18203
- "gray",
18204
- "jpeg"
18205
- ])
18206
- });
18207
- /**
18208
- * Process-local frame identity. It is serializable so it can ride an in-process
18209
- * capability call, but `registryId` deliberately prevents resolution in any
18210
- * other process or execution group.
18211
- */
18212
- var FrameRefSchema = object({
18213
- registryId: string().min(1),
18214
- id: string().min(1),
18215
- width: number().int().positive(),
18216
- height: number().int().positive(),
18217
- format: _enum(["rgb", "gray"]),
18218
- timestamp: number(),
18219
- capturedAt: number().optional()
18220
- });
18221
- var ModelFormatSchema$1 = _enum([
18222
- "onnx",
18223
- "coreml",
18224
- "openvino",
18225
- "tflite",
18226
- "pt",
18227
- "gguf"
18228
- ]);
18229
- var PipelineSlotSchema = _enum([
18230
- "detector",
18231
- "cropper",
18232
- "classifier",
18233
- "refiner",
18234
- "audio-classifier"
18235
- ]);
18236
- var PipelineEngineChoiceSchema = object({
18237
- runtime: _enum(["node", "python"]),
18238
- backend: string(),
18239
- format: ModelFormatSchema$1,
18240
- device: string().optional()
18241
- });
18242
- var AvailableEngineSchema = object({
18243
- engine: PipelineEngineChoiceSchema,
18244
- devices: array(object({
18245
- id: string(),
18246
- label: string(),
18247
- description: string().optional()
18248
- })).readonly(),
18249
- defaultDevice: string()
18250
- });
18251
- var PipelineDefaultStepSchema = lazy(() => object({
18252
- addonId: string(),
18253
- addonName: string(),
18254
- slot: PipelineSlotSchema,
18255
- inputClasses: array(string()).readonly(),
18256
- outputClasses: array(string()).readonly(),
18257
- enabled: boolean(),
18258
- modelId: string(),
18259
- children: array(PipelineDefaultStepSchema).readonly(),
18260
- group: string().optional(),
18261
- settings: record(string(), unknown()).optional()
18262
- }));
18263
- var PipelineTemplateStepSchema = lazy(() => object({
18264
- addonId: string(),
18265
- enabled: boolean(),
18266
- modelId: string(),
18267
- children: array(PipelineTemplateStepSchema).readonly(),
18268
- settings: record(string(), unknown()).optional()
18269
- }));
18270
- var PipelineTemplateSchema$1 = object({
18271
- id: string(),
18272
- name: string(),
18273
- createdAt: string(),
18274
- updatedAt: string(),
18275
- engine: PipelineEngineChoiceSchema,
18276
- steps: array(PipelineTemplateStepSchema).readonly()
18277
- });
18278
- var PipelineModelOptionSchema = object({
18279
- id: string(),
18280
- name: string(),
18281
- formats: record(string(), object({
18282
- downloaded: boolean(),
18283
- sizeMB: number()
18284
- })),
18285
- group: ModelVariantGroupSchema.optional(),
18286
- legacy: boolean().optional(),
18287
- provider: ModelProviderIdSchema.optional()
18288
- });
18289
- var ConfigFieldBridge = custom();
18290
- var PipelineAddonSchemaSchema = object({
18291
- id: string(),
18292
- name: string(),
18293
- slot: PipelineSlotSchema,
18294
- inputClasses: array(string()).readonly(),
18295
- outputClasses: array(string()).readonly(),
18296
- childSlots: array(PipelineSlotSchema).readonly(),
18297
- models: array(PipelineModelOptionSchema).readonly(),
18298
- defaultModelId: string(),
18299
- defaultModelIdByFormat: record(string(), string()).optional(),
18300
- enabledByDefault: boolean().optional(),
18301
- backfillIntoExistingOverrides: boolean().optional(),
18302
- defaultConfidence: number(),
18303
- group: string().optional(),
18304
- configSchema: array(ConfigFieldBridge).readonly().optional()
18305
- });
18306
- var PipelineSlotSchemaSchema = object({
18307
- id: PipelineSlotSchema,
18308
- label: string(),
18309
- priority: number(),
18310
- parentSlot: PipelineSlotSchema.nullable(),
18311
- addons: array(PipelineAddonSchemaSchema).readonly()
18312
- });
18313
- var PipelineSchemaSchema = object({
18314
- availableEngines: array(AvailableEngineSchema).readonly(),
18315
- selectedEngine: PipelineEngineChoiceSchema,
18316
- slots: array(PipelineSlotSchemaSchema).readonly()
18317
- });
18318
- var EngineProvisioningSchema = object({
18319
- runtimeId: _enum([
18320
- "onnx",
18321
- "openvino",
18322
- "coreml",
18323
- "edgetpu"
18324
- ]).nullable(),
18325
- device: string().nullable(),
18326
- state: _enum([
18327
- "idle",
18328
- "installing",
18329
- "verifying",
18330
- "ready",
18331
- "failed"
18332
- ]),
18333
- progress: number().optional(),
18334
- error: string().optional(),
18335
- nextRetryAt: number().optional(),
18336
- /**
18337
- * Gate A (config-correctness gate at engine change): human-readable
18338
- * config issues surfaced EAGERLY when the node's engine changes — model
18339
- * substitutions ("chose X, running Y") and zero-build steps ("no model
18340
- * has a <format> build"). Additive/optional: informational only, never
18341
- * enforced here — `assertEngineReady` (readiness) still gates inference.
18342
- * Absent/empty when the node-default tree resolves cleanly.
18343
- */
18344
- configIssues: array(string()).optional()
18345
- });
18346
- var PipelineStepInputSchema = lazy(() => object({
18347
- addonId: string(),
18348
- modelId: string().optional(),
18349
- enabled: boolean().default(true),
18350
- children: array(PipelineStepInputSchema).optional(),
18351
- settings: record(string(), unknown()).optional(),
18352
- jumpDeviceKey: string().optional()
18353
- }));
18354
- var ModelSubstitutionSchema = object({
18355
- addonId: string(),
18356
- chosen: string(),
18357
- running: string(),
18358
- format: string()
18359
- });
18360
- var PipelineValidationIssueSchema = object({
18361
- addonId: string(),
18362
- kind: _enum(["unknown-addon", "no-format-build"]),
18363
- detail: string()
18364
- });
18365
- var PipelineValidationResultSchema = object({
18366
- ok: boolean(),
18367
- issues: array(PipelineValidationIssueSchema).readonly(),
18368
- substitutions: array(ModelSubstitutionSchema).readonly(),
18369
- /** The node's `currentEngine.format` this validation ran against. */
18370
- format: string()
18371
- });
18372
- var ReferenceImageEntrySchema = object({
18373
- filename: string(),
18374
- stepIds: array(string()).readonly().optional()
18375
- });
18376
- var ReferenceImageBodySchema = object({
18377
- base64: string(),
18378
- filename: string()
18379
- });
18380
- var ReferenceAudioEntrySchema = object({
18381
- filename: string(),
18382
- sizeKb: number()
18383
- });
18384
- var ReferenceAudioBodySchema = object({ base64: string() });
18385
- var AudioBackendSchema = object({
18386
- id: string(),
18387
- name: string(),
18388
- description: string(),
18389
- available: boolean(),
18390
- /**
18391
- * Raw classifier labels this backend can emit (e.g. YAMNet's
18392
- * 521-class set or Apple SoundAnalysis's 303-class set). Used by
18393
- * the benchmark UI to populate the `enabledMicroClasses` filter
18394
- * specific to the selected backend without a separate fetch.
18395
- */
18396
- rawLabels: array(string()).readonly().optional()
18397
- });
18398
- var AudioCapabilitiesSchema = object({
18399
- activeBackend: string(),
18400
- availableBackends: array(AudioBackendSchema).readonly(),
18401
- sampleRate: number(),
18402
- chunkDurationMs: number()
18403
- });
18404
- var DownloadModelResultSchema = object({
18405
- filePath: string(),
18406
- sizeMB: number(),
18407
- durationMs: number()
18408
- });
18409
- /**
18410
- * Wrapper carrying a single test run's result. Replaces the legacy
18411
- * ad-hoc `{labels: [{className, originalClass, score}]}` shape with the
18412
- * canonical `AudioResult` from the Phase 6 output rework: one
18413
- * `AudioDetection` per class above `minScore`, top-N candidates in
18414
- * `debug.alternateLabels['audio-classifier']`, per-source timings in
18415
- * `debug.stepTimings`. The outer `success`/`error` fields stay so the
18416
- * benchmark UI can still report a clean failure when the classifier
18417
- * cap isn't available.
18418
- */
18419
- var AudioTestResultSchema = object({
18420
- success: boolean(),
18421
- error: string().optional(),
18422
- frame: custom().optional()
18423
- });
18424
- var PipelineConfigBridge = custom();
18425
- var ConfigUISchemaBridge = custom();
18426
- var ConfigUISchemaNullableBridge = custom();
18427
- var InferenceCapabilitiesBridge = custom();
18428
- var ModelAvailabilityListBridge = custom();
18429
- var PipelineRunResultBridge = custom();
18430
- method(_void(), array(PipelineEngineChoiceSchema)), method(_void(), PipelineEngineChoiceSchema), method(PipelineEngineChoiceSchema, array(PipelineDefaultStepSchema)), method(object({ nodeId: string() }), EngineProvisioningSchema), method(_void(), record(string(), object({
18431
- modelId: string(),
18432
- settings: record(string(), unknown()).readonly()
18433
- }))), method(object({ steps: record(string(), object({
18434
- modelId: string(),
18435
- settings: record(string(), unknown()).readonly()
18436
- })) }), object({ success: literal(true) }), {
18437
- kind: "mutation",
18438
- auth: "admin"
18439
- }), method(object({ nodeId: string() }), object({
18440
- success: literal(true),
18441
- clearedDevices: number()
18442
- }), {
18443
- kind: "mutation",
18444
- auth: "admin"
18445
- }), 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({
18446
- name: string(),
18447
- steps: array(PipelineTemplateStepSchema).readonly(),
18448
- engine: PipelineEngineChoiceSchema
18449
- }), PipelineTemplateSchema$1, { kind: "mutation" }), method(object({
18450
- id: string(),
18451
- name: string().optional(),
18452
- steps: array(PipelineTemplateStepSchema).readonly().optional()
18453
- }), PipelineTemplateSchema$1, { kind: "mutation" }), method(object({ id: string() }), _void(), { kind: "mutation" }), method(_void(), InferenceCapabilitiesBridge), method(object({ addonId: string() }), ModelAvailabilityListBridge), method(object({
18454
- addonId: string(),
18455
- modelId: string(),
18456
- format: ModelFormatSchema$1
18457
- }), DownloadModelResultSchema, { kind: "mutation" }), method(object({
18458
- addonId: string(),
18459
- modelId: string(),
18460
- format: ModelFormatSchema$1
18461
- }), object({ success: literal(true) }), { kind: "mutation" }), method(object({
18462
- engine: PipelineEngineChoiceSchema.optional(),
18463
- steps: array(PipelineStepInputSchema).min(1),
18464
- frame: FrameInputSchema.optional(),
18465
- /**
18466
- * Process-local lazy frame. Valid only when caller and provider resolve
18467
- * in the same execution-group process; split/cross-node callers use
18468
- * `frame`/`image` inline compatibility instead.
18469
- */
18470
- frameRef: FrameRefSchema.optional(),
18471
- /**
18472
- * CB5 shm passthrough — a `FrameHandle` naming the same ring slot
18473
- * the decoded pixels live in. One more member of the one-of
18474
- * frame/frameHandle/image/imageBase64/referenceImage group.
18475
- */
18476
- frameHandle: FrameHandleSchema.optional(),
18477
- imageBase64: string().optional(),
18478
- /**
18479
- * Binary JPEG bytes — preferred over `imageBase64` on internal
18480
- * hops (hub → forked worker via Moleculer MsgPack) because it
18481
- * skips the 33% base64 overhead + the per-call base64 decode on
18482
- * the detection-pipeline worker. Callers can pass either; exactly
18483
- * one of `frame`/`image`/`imageBase64`/`referenceImage` is required.
18484
- */
18485
- image: _instanceof(Uint8Array).optional(),
18486
- referenceImage: string().optional(),
18487
- deviceId: number().optional(),
18488
- sessionId: string().optional(),
18489
- /**
18490
- * Execution plane. 'full' (default) runs the whole tree — benchmark,
18491
- * reference-image, and detail-subtree calls. 'frame' is the live
18492
- * per-frame dispatch: ONLY root-plane steps run; crop children
18493
- * (inputClasses ≠ null) are skipped and served per-track via
18494
- * pipelineRunner.runDetailSubtree (two-plane design).
18495
- */
18496
- plane: _enum(["full", "frame"]).optional(),
18497
- /**
18498
- * Inference-device selector (Phase 2 multi-device). Format
18499
- * `<backend>:<device>` (e.g. `openvino:gpu`, `edgetpu:usb`, `cpu`).
18500
- * Omitted ⇒ the runner's default device (current single-engine
18501
- * behaviour). Selects WHICH device pool of the node runs the call.
18502
- */
18503
- deviceKey: string().optional(),
18504
- /**
18505
- * Two-plane NATIVE child-crop reference. Set by `runDetailSubtree` ONLY
18506
- * when the parent crop was resolved from the frame's retained NATIVE
18507
- * surface (a frameHandle HIT). Lets the executor re-cut a LEAF crop
18508
- * child's ROI (plate-ocr, face-embedding, leaf classifiers) at native
18509
- * resolution from that surface — the SAME quality path faces already
18510
- * had — instead of the downscaled parent tile. `handle` keys the native
18511
- * surface (node-pinned to its owner); `cropFrameSpace` is the parent
18512
- * crop's padded/clamped rectangle in FRAME-space pixels, used to compose
18513
- * the executor's crop-normalized child ROI back into frame-normalized
18514
- * coordinates. Auxiliary to the image source (`image`/`frame`/…), NOT one
18515
- * of the mutually-exclusive image inputs. Absent ⇒ tile-crop children
18516
- * (today's behaviour on the fallback path).
18517
- */
18518
- nativeCropRef: NativeCropRefSchema.optional()
18519
- }), PipelineRunResultBridge, { kind: "mutation" }), method(object({
18520
- engine: PipelineEngineChoiceSchema.optional(),
18521
- steps: array(PipelineStepInputSchema).min(1),
18522
- frames: array(FrameInputSchema).min(1).max(255),
18523
- deviceId: number().optional(),
18524
- sessionId: string().optional(),
18525
- /**
18526
- * Pure-inference benchmark hint. A NONZERO uint32 pins every frame in
18527
- * the batch to the Python pool's bench preprocess cache
18528
- * (`_bench_frame_id`) so a REPEATED benchmark frame is decoded +
18529
- * preprocessed ONCE and every later inference is a pure-inference cache
18530
- * hit — the sustained-throughput run measures inference, not
18531
- * decode+preprocess+infer. Omitted/0 for live frames (all different →
18532
- * full preprocess every call, correct). Fresh per sustained run;
18533
- * released via `uncacheFrame`.
18534
- */
18535
- frameId: number().int().nonnegative().optional(),
18536
- /** Inference-device selector (Phase 2 multi-device); see runPipeline. */
18537
- deviceKey: string().optional()
18538
- }), object({ results: array(PipelineRunResultBridge).readonly() }), { kind: "mutation" }), method(object({
18539
- data: _instanceof(Uint8Array),
18540
- width: number().int().positive(),
18541
- height: number().int().positive(),
18542
- format: _enum([
18543
- "rgb",
18544
- "bgr",
18545
- "gray"
18546
- ])
18547
- }), object({
18548
- frameId: number(),
18549
- width: number(),
18550
- height: number()
18551
- }), { kind: "mutation" }), method(object({
18552
- stepId: string(),
18553
- frameId: number().int()
18554
- }), record(string(), unknown()), { kind: "mutation" }), method(object({ frameId: number().int() }), _void(), { kind: "mutation" }), method(_void(), object({
18555
- batchMode: string(),
18556
- windowMs: number(),
18557
- maxBatchSize: number(),
18558
- concurrency: number()
18559
- })), method(_void(), array(object({
18560
- engineKey: string(),
18561
- engine: PipelineEngineChoiceSchema,
18562
- modelsLoaded: array(string()).readonly(),
18563
- inUseByCameras: array(number()).readonly(),
18564
- /**
18565
- * Origin of this resident factory.
18566
- * - `runtime` — main camera-serving engine (no idle TTL).
18567
- * - `warm-override` — benchmark/test override held in the warm
18568
- * cache; auto-disposed after the idle TTL.
18569
- * - `device-pool` — a concurrent per-device pool (Phase 2
18570
- * multi-device, keyed by `deviceKey`) resolved
18571
- * via `resolveDeviceFactory`. Runs alongside the
18572
- * `runtime` engine on a DIFFERENT accelerator
18573
- * (NPU / iGPU / Coral) — this is how the
18574
- * Engines tab shows all pools running at once.
18575
- */
18576
- kind: _enum([
18577
- "runtime",
18578
- "warm-override",
18579
- "device-pool"
18580
- ]),
18581
- /** Native pid of the underlying Python pool (null when no pool). */
18582
- poolPid: number().nullable(),
18583
- /** ms since this factory was last used (null when not warm-tracked). */
18584
- idleMs: number().nullable(),
18585
- /** Idle TTL after which `warm-override` factories self-evict (null when not applicable). */
18586
- idleTtlMs: number().nullable()
18587
- })).readonly()), method(object({ engine: PipelineEngineChoiceSchema }), object({ success: literal(true) }), {
18759
+ frameId: string(),
18760
+ annotations: array(RetrainAnnotationDraftSchema)
18761
+ }), array(RetrainAnnotationSchema).readonly(), {
18588
18762
  kind: "mutation",
18589
18763
  auth: "admin"
18590
18764
  }), method(object({
18591
- engine: PipelineEngineChoiceSchema,
18592
- force: boolean().optional()
18593
- }), object({
18594
- success: boolean(),
18595
- reason: string().optional()
18596
- }), {
18765
+ deviceId: number(),
18766
+ trackId: string()
18767
+ }), RetrainTransitionResultSchema, {
18597
18768
  kind: "mutation",
18598
18769
  auth: "admin"
18599
- }), 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({
18600
- addonId: string(),
18601
- modelId: string(),
18602
- filename: string().optional(),
18603
- settings: record(string(), unknown()).optional()
18604
- }), AudioTestResultSchema, { kind: "mutation" }), method(_void(), ConfigUISchemaNullableBridge);
18770
+ }), method(object({
18771
+ deviceId: number(),
18772
+ trackId: string()
18773
+ }), RetrainTransitionResultSchema, {
18774
+ kind: "mutation",
18775
+ auth: "admin"
18776
+ }), method(object({ deviceIds: array(number()).optional() }), object({ url: string() }), {
18777
+ kind: "query",
18778
+ auth: "admin"
18779
+ }), method(object({
18780
+ eventId: string(),
18781
+ kind: MediaFileKindEnum.optional(),
18782
+ deviceId: number()
18783
+ }), array(MediaFileSchema).readonly()), method(object({
18784
+ trackId: string(),
18785
+ kinds: array(MediaFileKindEnum).optional(),
18786
+ deviceId: number()
18787
+ }), array(MediaFileSchema).readonly()), method(object({
18788
+ trackId: string(),
18789
+ deviceId: number()
18790
+ }), array(MediaFileInfoSchema).readonly()), method(SearchObjectEventsInput, array(ScoredObjectEventSchema).readonly()), method(object({}), WipeObjectEmbeddingsResultSchema, {
18791
+ kind: "mutation",
18792
+ auth: "admin"
18793
+ }), method(RebuildObjectEmbeddingsInput, RebuildObjectEmbeddingsResultSchema, {
18794
+ kind: "mutation",
18795
+ auth: "admin"
18796
+ }), method(object({}), RebuildStatusSchema), object({
18797
+ deviceId: number(),
18798
+ timestamp: number(),
18799
+ frameWidth: number(),
18800
+ frameHeight: number(),
18801
+ detections: array(OverlayDetectionSchema).readonly()
18802
+ }), object({
18803
+ deviceId: number(),
18804
+ trackId: string(),
18805
+ className: string()
18806
+ }), object({
18807
+ deviceId: number(),
18808
+ trackId: string(),
18809
+ className: string(),
18810
+ durationMs: number()
18811
+ }), object({
18812
+ deviceId: number(),
18813
+ kind: EventKindSchema,
18814
+ eventId: string(),
18815
+ timestamp: number()
18816
+ });
18605
18817
  object({
18606
18818
  activeCameras: number(),
18607
18819
  throttledCameras: number(),
@@ -18627,66 +18839,6 @@ var CameraMetricsSchema = object({
18627
18839
  });
18628
18840
  var CameraMetricsWithDeviceIdSchema = CameraMetricsSchema.extend({ deviceId: number() });
18629
18841
  /**
18630
- * Zone — pure geometry + identity. NO filtering behaviour.
18631
- *
18632
- * Zones describe **where** in the frame the operator wants to flag
18633
- * something; consumer-owned {@link ZoneRule} arrays describe **how**
18634
- * each pipeline stage uses them. Splitting the two means a single
18635
- * polygon "Driveway" can simultaneously back a motion-exclude rule,
18636
- * a detection-include rule on `['car']`, and an occupancy aggregate
18637
- * — without three duplicated polygons.
18638
- *
18639
- * Owned by the orchestrator addon (provider) and mirrored into the
18640
- * `zones` device-state slice on every mutation. Consumers
18641
- * (motion-wasm, pipeline-executor, analytics, admin UI) read either
18642
- * via `api.zones.listZones` (one-shot) or via `dev.state.zones` (live
18643
- * mirror with `onChanged`).
18644
- *
18645
- * Coordinates are normalised fractions of the frame (0–1) so zones
18646
- * survive resolution changes and stream profile switches.
18647
- *
18648
- * `kind` discriminates between full polygons (closed regions used
18649
- * for intrusion / occupancy filters) and tripwires (open 2-point
18650
- * line segments used for cross events). Onboard / firmware-reported
18651
- * zones (Reolink, ONVIF) are out of scope for now — see the deferred
18652
- * task list.
18653
- */
18654
- var ZoneKindEnum = _enum(["polygon", "tripwire"]);
18655
- /** Polygon vertex in fraction-of-frame coordinates (0–1). */
18656
- var PolygonPointSchema = object({
18657
- x: number(),
18658
- y: number()
18659
- });
18660
- /** A camera detection zone — pure geometry/identity. */
18661
- var ZoneSchema = object({
18662
- id: string(),
18663
- name: string(),
18664
- kind: ZoneKindEnum.default("polygon"),
18665
- /** Polygon vertices, fraction of frame (0–1). */
18666
- polygon: array(PolygonPointSchema).readonly(),
18667
- /** Visual color for UI rendering. */
18668
- color: string().default("#3b82f6")
18669
- });
18670
- DeviceType.Camera, method(object({ deviceId: number() }), array(ZoneSchema).readonly()), method(object({
18671
- deviceId: number(),
18672
- zone: ZoneSchema
18673
- }), _void(), {
18674
- kind: "mutation",
18675
- auth: "admin"
18676
- }), method(object({
18677
- deviceId: number(),
18678
- zoneId: string()
18679
- }), _void(), {
18680
- kind: "mutation",
18681
- auth: "admin"
18682
- }), method(object({
18683
- deviceId: number(),
18684
- zone: ZoneSchema
18685
- }), _void(), {
18686
- kind: "mutation",
18687
- auth: "admin"
18688
- }), object({ zones: array(ZoneSchema).readonly() });
18689
- /**
18690
18842
  * A bounding box in NORMALIZED [0,1] frame coordinates for `getNativeCrop`. The
18691
18843
  * decode worker resolves it against the RETAINED native frame's real pixel dims,
18692
18844
  * so the caller supplies only the detection-res bbox divided by the detection
@@ -25712,6 +25864,39 @@ var ReadGopBytesResultSchema = object({
25712
25864
  /** Media ms the returned fragment covers. */
25713
25865
  gopDurMs: number()
25714
25866
  });
25867
+ /**
25868
+ * A time WINDOW of one finalized segment, cut by byte range — the multi-GOP
25869
+ * twin of {@link ReadGopBytesResultSchema}'s single instant. Built for the
25870
+ * replay clip's `recording` source (`docs/design/plans/2026-08-26-replay-clip-su-pipeline.md`):
25871
+ * a replay needs several seconds of native pixels, not one frame.
25872
+ *
25873
+ * `ok.data` is standalone-demuxable, same as a GOP read. `ok.reachesRequestedEnd`
25874
+ * is `false` when the returned bytes were cut short by the read's own safety
25875
+ * byte cap before covering `[fromMs, toMs)` — a truncation, reported, not a
25876
+ * silently shorter answer. `spans-multiple-segments` is a REFUSAL, not a
25877
+ * degradation: a window whose end falls past the covering segment would need
25878
+ * bytes stitched from a second segment file (its own `ftyp`+`moov`), which is
25879
+ * not one standalone-demuxable stream — the caller's answer is to request a
25880
+ * shorter window or one aligned to a single segment, not to receive spliced
25881
+ * bytes nothing has proven decodable.
25882
+ */
25883
+ var ReadWindowBytesResultSchema = discriminatedUnion("kind", [object({
25884
+ kind: literal("ok"),
25885
+ data: _instanceof(Uint8Array),
25886
+ /** Absolute epoch ms of the returned bytes' first sample — at or before
25887
+ * the requested `fromMs` (anchored on the nearest keyframe). */
25888
+ gopStartMs: number(),
25889
+ /** Media ms the returned bytes cover, from `gopStartMs`. */
25890
+ gopDurMs: number(),
25891
+ /** `false` ⇒ the safety byte cap cut the read short before it reached
25892
+ * the requested `toMs`; the caller got fewer frames than asked for. */
25893
+ reachesRequestedEnd: boolean()
25894
+ }), object({
25895
+ kind: literal("spans-multiple-segments"),
25896
+ /** Where the covering segment's own footage runs out — informational,
25897
+ * not a retry hint (retrying the same window would refuse again). */
25898
+ segmentEndMs: number()
25899
+ })]);
25715
25900
  method(object({
25716
25901
  deviceId: number(),
25717
25902
  fromMs: number(),
@@ -25762,6 +25947,15 @@ method(object({
25762
25947
  }), ReadGopBytesResultSchema, {
25763
25948
  kind: "query",
25764
25949
  auth: "admin"
25950
+ }), method(object({
25951
+ deviceId: number(),
25952
+ profile: string(),
25953
+ startMs: number(),
25954
+ fromMs: number(),
25955
+ toMs: number()
25956
+ }), ReadWindowBytesResultSchema, {
25957
+ kind: "query",
25958
+ auth: "admin"
25765
25959
  }), method(object({
25766
25960
  deviceId: number(),
25767
25961
  config: RecordingConfigSchema
@@ -26316,92 +26510,6 @@ DeviceType.Camera, method(object({ deviceId: number() }), SceneMonitorStatusSche
26316
26510
  kind: "mutation",
26317
26511
  auth: "admin"
26318
26512
  });
26319
- /**
26320
- * Per-stage gating mode applied to the zones a rule references.
26321
- *
26322
- * - `include`: the rule contributes to a **whitelist** for its stage.
26323
- * When at least one `include` rule fires for a stage, only entities
26324
- * inside one of those zones pass that stage.
26325
- * - `exclude`: the rule contributes to a **blacklist** for its stage.
26326
- * Entities inside one of those zones are dropped at that stage.
26327
- *
26328
- * `monitor`-style observation (count without filtering) is not a rule
26329
- * mode — zones without any matching rule are observed naturally by
26330
- * `zone-analytics` (live snapshot + history), so an "I just want to
26331
- * count, not filter" use case needs no rule at all.
26332
- */
26333
- var ZoneRuleModeEnum = _enum(["include", "exclude"]);
26334
- /**
26335
- * Per-consumer rule that references existing zones (geometry) and
26336
- * defines how a specific pipeline stage should treat them. Each
26337
- * consumer addon owns its own `ZoneRule[]` array in its per-device
26338
- * settings:
26339
- *
26340
- * - `addon-motion-wasm` → `motionZoneRules: ZoneRule[]` (motion stage)
26341
- * - `addon-detection-pipeline` → `detectionZoneRules: ZoneRule[]` (detection stage)
26342
- * - future: notification rules, audio gating, etc.
26343
- *
26344
- * One rule applies to N zones (`zoneIds[]`) so the operator can
26345
- * express "ignore motion in ALL of {garden, street}" with a single
26346
- * rule. `classFilter` narrows the rule to specific object classes —
26347
- * "drop person detections in the street, but keep cars" is one
26348
- * `exclude` rule with `classFilter: ['person']`.
26349
- *
26350
- * `enabled` is a soft toggle — the operator can keep the rule
26351
- * configured but inert without deleting it.
26352
- */
26353
- var ZoneRuleSchema = object({
26354
- /** Stable rule id — survives edits, used by the UI for diffing. */
26355
- id: string(),
26356
- /** Optional human-readable label rendered in the rule editor. */
26357
- name: string().optional(),
26358
- /** Zones this rule targets. The rule's `mode` applies to ALL
26359
- * listed zones (OR-set: a detection in any one of them counts).
26360
- * At least one zone id required — a rule with no targets is a
26361
- * configuration mistake and the form validator rejects it. */
26362
- zoneIds: array(string()).min(1).readonly(),
26363
- mode: ZoneRuleModeEnum,
26364
- /**
26365
- * Class names this rule applies to. Empty / undefined ⇒ rule
26366
- * applies to every class. Class strings match the `macroClass`
26367
- * field on detections (e.g. `person`, `car`, `dog`).
26368
- */
26369
- classFilter: array(string()).readonly().optional(),
26370
- /**
26371
- * Minimum bbox/mask overlap (0–1) with any of the rule's zones
26372
- * required to consider an entity "in the zone". Defaults to the
26373
- * consumer's stage default when omitted. Kept for back-compat with
26374
- * existing per-rule overrides; new operators pick the value via
26375
- * `bboxInclusionPct` (operator-friendly 0–100). Whichever field is
26376
- * set, the lower-level engine reads it as a 0–1 fraction.
26377
- */
26378
- overlapThreshold: number().min(0).max(1).optional(),
26379
- /**
26380
- * Operator-friendly version of `overlapThreshold` — the percentage
26381
- * of the detection's bbox that must lie inside the zone for the
26382
- * rule to match. Documented default is 85%; the engine substitutes
26383
- * that when the field is omitted (kept optional so existing rules
26384
- * stored without it stay valid).
26385
- *
26386
- * When BOTH `overlapThreshold` and `bboxInclusionPct` are set on a
26387
- * rule, the engine prefers `bboxInclusionPct` because it's the
26388
- * field exposed in the UI. Internally both feed the same gate.
26389
- */
26390
- bboxInclusionPct: number().min(0).max(100).optional(),
26391
- /**
26392
- * When `true` and a detection has a segmentation mask, use the
26393
- * mask for overlap instead of the bbox. Detection-stage only;
26394
- * motion rules ignore this field.
26395
- */
26396
- preferMask: boolean().optional(),
26397
- /**
26398
- * Soft-toggle: `false` disables the rule without deleting it.
26399
- * Defaults to `true` so operators creating a rule via the UI
26400
- * see it active immediately.
26401
- */
26402
- enabled: boolean().default(true)
26403
- });
26404
- array(ZoneRuleSchema).readonly();
26405
26513
  object({
26406
26514
  /** Whether the script is currently executing. */
26407
26515
  isRunning: boolean(),
@@ -30291,6 +30399,12 @@ Object.freeze({
30291
30399
  addonId: null,
30292
30400
  access: "view"
30293
30401
  },
30402
+ "notificationRules.resolveArtifactUrl": {
30403
+ capName: "notification-rules",
30404
+ capScope: "system",
30405
+ addonId: null,
30406
+ access: "view"
30407
+ },
30294
30408
  "notificationRules.setAlarmConfig": {
30295
30409
  capName: "notification-rules",
30296
30410
  capScope: "system",
@@ -30735,6 +30849,12 @@ Object.freeze({
30735
30849
  addonId: null,
30736
30850
  access: "create"
30737
30851
  },
30852
+ "pipelineAnalytics.runReplayFrameProcessor": {
30853
+ capName: "pipeline-analytics",
30854
+ capScope: "device",
30855
+ addonId: null,
30856
+ access: "create"
30857
+ },
30738
30858
  "pipelineAnalytics.saveRetrainAnnotations": {
30739
30859
  capName: "pipeline-analytics",
30740
30860
  capScope: "device",
@@ -30867,6 +30987,12 @@ Object.freeze({
30867
30987
  addonId: null,
30868
30988
  access: "view"
30869
30989
  },
30990
+ "pipelineExecutor.getInferenceDeviceHealth": {
30991
+ capName: "pipeline-executor",
30992
+ capScope: "system",
30993
+ addonId: null,
30994
+ access: "view"
30995
+ },
30870
30996
  "pipelineExecutor.getOrchestratorConfigSchema": {
30871
30997
  capName: "pipeline-executor",
30872
30998
  capScope: "system",
@@ -30939,6 +31065,12 @@ Object.freeze({
30939
31065
  addonId: null,
30940
31066
  access: "view"
30941
31067
  },
31068
+ "pipelineExecutor.rearmInferenceDevice": {
31069
+ capName: "pipeline-executor",
31070
+ capScope: "system",
31071
+ addonId: null,
31072
+ access: "create"
31073
+ },
30942
31074
  "pipelineExecutor.runAudioTest": {
30943
31075
  capName: "pipeline-executor",
30944
31076
  capScope: "system",
@@ -31677,6 +31809,12 @@ Object.freeze({
31677
31809
  addonId: null,
31678
31810
  access: "view"
31679
31811
  },
31812
+ "recording.readWindowBytes": {
31813
+ capName: "recording",
31814
+ capScope: "system",
31815
+ addonId: null,
31816
+ access: "view"
31817
+ },
31680
31818
  "recording.refreshStorageLocationsForMigration": {
31681
31819
  capName: "recording",
31682
31820
  capScope: "system",
@@ -34187,6 +34325,11 @@ Object.freeze({
34187
34325
  form: "single",
34188
34326
  optional: false
34189
34327
  }],
34328
+ "pipelineAnalytics.runReplayFrameProcessor": [{
34329
+ name: "deviceId",
34330
+ form: "single",
34331
+ optional: false
34332
+ }],
34190
34333
  "pipelineAnalytics.saveRetrainAnnotations": [{
34191
34334
  name: "deviceId",
34192
34335
  form: "single",
@@ -34502,6 +34645,11 @@ Object.freeze({
34502
34645
  form: "single",
34503
34646
  optional: false
34504
34647
  }],
34648
+ "recording.readWindowBytes": [{
34649
+ name: "deviceId",
34650
+ form: "single",
34651
+ optional: false
34652
+ }],
34505
34653
  "recording.relocateFootage": [{
34506
34654
  name: "deviceId",
34507
34655
  form: "single",