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