@camstack/types 1.2.110 → 1.2.111

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.
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_event_category = require("./event-category-EY0GNjV9.js");
3
- const require_sleep = require("./sleep-DnbNfEhn.js");
3
+ const require_sleep = require("./sleep-BCRrMlni.js");
4
4
  const require_canonical_hash = require("./canonical-hash-DNV8S5ET.js");
5
5
  const require_enums = require("./enums.js");
6
6
  const require_err_msg = require("./err-msg-COpsHMw2.js");
@@ -14793,373 +14793,1208 @@ var oauthIntegrationCapability = {
14793
14793
  getDescriptor: require_sleep.method(zod.z.void(), OauthIntegrationDescriptorSchema, { auth: "admin" }) }
14794
14794
  };
14795
14795
  //#endregion
14796
- //#region src/capabilities/pipeline-analytics.cap.ts
14796
+ //#region src/capabilities/pipeline-executor.cap.ts
14797
14797
  /**
14798
- * pipeline-analytics device-scoped wrapper cap. Refines raw
14799
- * per-frame detections emitted by the pipeline runner into tracked
14800
- * objects, per-kind event collections (motion / object / audio), and
14801
- * persisted media. Owns the post-detection domain end-to-end:
14802
- *
14803
- * runner emits PipelineInferenceResult
14804
- * ↓ (event bus)
14805
- * pipeline-analytics subscriber
14806
- * ↓ SORT tracker + zone engine + state analyzer + event emitter
14807
- * → three DB collections (one per kind), one FS media tree, one
14808
- * unified event emitter (FrameTracked + TrackStarted/Ended +
14809
- * DetectionEvent on bus)
14810
- *
14811
- * Pure subscriber model. No `processFrame` cap method — the runner
14812
- * already publishes the raw frame on the bus. The cap surface is
14813
- * only QUERIES + per-device settings, bound on/off via
14814
- * `device-manager.setWrapperActive`. `defaultActive: true` because
14815
- * every camera with a detection pipeline wants its raw detections
14816
- * refined; operators opt out per-device via BindingsTab when needed.
14817
- *
14818
- * Replaces the legacy `analysis-pipeline`, `analysis-data-persistence`
14819
- * (per-device surface) and `track-trail` caps — see P11 cleanup.
14798
+ * Reference to the frame's retained NATIVE surface + the parent crop's placement
14799
+ * within the frame, so the executor can re-cut a leaf child ROI at native
14800
+ * resolution on the detail plane. See the `runPipeline` `nativeCropRef` field.
14820
14801
  */
14821
- var TrackStateSchema = zod.z.enum([
14822
- "new",
14823
- "entered",
14824
- "left",
14825
- "moving",
14826
- "idle"
14827
- ]);
14828
- var EventKindSchema = zod.z.enum([
14829
- "motion",
14830
- "object",
14831
- "audio"
14832
- ]);
14802
+ var NativeCropRefSchema = zod.z.object({
14803
+ /** Handle keying the retained native surface (node-pinned to its owner). */
14804
+ handle: require_sleep.FrameHandleSchema,
14805
+ /** The parent crop's padded/clamped rectangle in FRAME-space pixels. */
14806
+ cropFrameSpace: zod.z.object({
14807
+ x: zod.z.number(),
14808
+ y: zod.z.number(),
14809
+ w: zod.z.number(),
14810
+ h: zod.z.number()
14811
+ })
14812
+ });
14813
+ zod.z.object({
14814
+ crop: zod.z.object({
14815
+ left: zod.z.number(),
14816
+ top: zod.z.number(),
14817
+ width: zod.z.number().positive(),
14818
+ height: zod.z.number().positive()
14819
+ }).optional(),
14820
+ content: zod.z.object({
14821
+ width: zod.z.number().int().positive(),
14822
+ height: zod.z.number().int().positive()
14823
+ }),
14824
+ fit: zod.z.enum(["stretch", "contain"]),
14825
+ format: zod.z.enum([
14826
+ "rgb",
14827
+ "gray",
14828
+ "jpeg"
14829
+ ])
14830
+ });
14833
14831
  /**
14834
- * Spatial filter for `listTracks` the rect + polygon variants of the shared
14835
- * MaskShape vocabulary (see `mask-shape.ts`). Coordinates are NORMALIZED 0..1
14836
- * of the camera frame (top-left origin), matching the drawing-plane editor.
14832
+ * Process-local frame identity. It is serializable so it can ride an in-process
14833
+ * capability call, but `registryId` deliberately prevents resolution in any
14834
+ * other process or execution group.
14837
14835
  */
14838
- var TrackZoneFilterSchema = zod.z.discriminatedUnion("kind", [MaskRectShapeSchema, MaskPolygonShapeSchema]);
14839
- /** Closed icon vocabulary so clients render a known glyph per kind. */
14840
- var EventKindIconSchema = zod.z.enum([
14841
- "motion",
14842
- "audio",
14843
- "person",
14844
- "vehicle",
14845
- "animal",
14846
- "door",
14847
- "pir",
14848
- "smoke",
14849
- "water",
14850
- "button",
14851
- "package",
14852
- "generic"
14836
+ var FrameRefSchema = zod.z.object({
14837
+ registryId: zod.z.string().min(1),
14838
+ id: zod.z.string().min(1),
14839
+ width: zod.z.number().int().positive(),
14840
+ height: zod.z.number().int().positive(),
14841
+ format: zod.z.enum(["rgb", "gray"]),
14842
+ timestamp: zod.z.number(),
14843
+ capturedAt: zod.z.number().optional()
14844
+ });
14845
+ var ModelFormatSchema$1 = zod.z.enum([
14846
+ "onnx",
14847
+ "coreml",
14848
+ "openvino",
14849
+ "tflite",
14850
+ "pt",
14851
+ "gguf"
14853
14852
  ]);
14854
- var EventKindCategorySchema = zod.z.enum([
14855
- "motion",
14856
- "audio",
14857
- "detection",
14858
- "sensor",
14859
- "control",
14860
- "custom",
14861
- "package"
14853
+ var PipelineSlotSchema = zod.z.enum([
14854
+ "detector",
14855
+ "cropper",
14856
+ "classifier",
14857
+ "refiner",
14858
+ "audio-classifier"
14862
14859
  ]);
14863
- /** Taxonomy level — macro (timeline lane) vs sub (events-page leaf). */
14864
- var EventKindLevelSchema = zod.z.enum(["macro", "sub"]);
14865
- var EventKindDescriptorSchema = zod.z.object({
14866
- /** Stable kind id (e.g. 'motion', 'vehicle', 'car', 'lock'). */
14867
- kind: zod.z.string(),
14868
- /** i18n key resolved on the UI side; `label` is the English fallback. */
14869
- labelKey: zod.z.string(),
14870
- /** English fallback label (kept for clients that don't translate). */
14860
+ var PipelineEngineChoiceSchema = zod.z.object({
14861
+ runtime: zod.z.enum(["node", "python"]),
14862
+ backend: zod.z.string(),
14863
+ format: ModelFormatSchema$1,
14864
+ device: zod.z.string().optional()
14865
+ });
14866
+ var EngineDeviceInfoSchema = zod.z.object({
14867
+ id: zod.z.string(),
14871
14868
  label: zod.z.string(),
14872
- /** Hex color for timeline/legend rendering. */
14873
- color: zod.z.string(),
14874
- /** Dictionary id → lucide component on the UI side. */
14875
- iconId: zod.z.string(),
14876
- /** Legacy closed-vocab glyph — fallback for `iconId`. */
14877
- icon: EventKindIconSchema,
14878
- category: EventKindCategorySchema,
14879
- /** Macro parent for this kind ('car' → 'vehicle'); null for a macro. */
14880
- parentKind: zod.z.string().nullable(),
14881
- /** Derived from `parentKind`, explicit for the client tree. */
14882
- level: EventKindLevelSchema,
14883
- /** Which cap + device contributes this kind. For built-ins the camera
14884
- * itself; for sensor kinds the LINKED source device. */
14885
- source: zod.z.object({
14886
- capName: zod.z.string(),
14887
- deviceId: zod.z.number()
14888
- })
14869
+ description: zod.z.string().optional()
14889
14870
  });
14890
- /** One camera's event vocabulary, as returned by `listEventKindsBatch`. */
14891
- var EventKindsForDeviceSchema = zod.z.object({
14892
- deviceId: zod.z.number(),
14893
- kinds: zod.z.array(EventKindDescriptorSchema).readonly()
14871
+ var AvailableEngineSchema = zod.z.object({
14872
+ engine: PipelineEngineChoiceSchema,
14873
+ devices: zod.z.array(EngineDeviceInfoSchema).readonly(),
14874
+ defaultDevice: zod.z.string()
14894
14875
  });
14895
- var SensorEventSchema = zod.z.object({
14876
+ var PipelineDefaultStepSchema = zod.z.lazy(() => zod.z.object({
14877
+ addonId: zod.z.string(),
14878
+ addonName: zod.z.string(),
14879
+ slot: PipelineSlotSchema,
14880
+ inputClasses: zod.z.array(zod.z.string()).readonly(),
14881
+ outputClasses: zod.z.array(zod.z.string()).readonly(),
14882
+ enabled: zod.z.boolean(),
14883
+ modelId: zod.z.string(),
14884
+ children: zod.z.array(PipelineDefaultStepSchema).readonly(),
14885
+ group: zod.z.string().optional(),
14886
+ settings: zod.z.record(zod.z.string(), zod.z.unknown()).optional()
14887
+ }));
14888
+ var PipelineTemplateStepSchema = zod.z.lazy(() => zod.z.object({
14889
+ addonId: zod.z.string(),
14890
+ enabled: zod.z.boolean(),
14891
+ modelId: zod.z.string(),
14892
+ children: zod.z.array(PipelineTemplateStepSchema).readonly(),
14893
+ settings: zod.z.record(zod.z.string(), zod.z.unknown()).optional()
14894
+ }));
14895
+ var PipelineTemplateSchema$1 = zod.z.object({
14896
14896
  id: zod.z.string(),
14897
- /** The CAMERA the event is attributed to (a sensor linked to N cameras
14898
- * yields N rows, one per camera). */
14899
- deviceId: zod.z.number(),
14900
- /** The linked sensor device whose state changed. */
14901
- sourceDeviceId: zod.z.number(),
14902
- /** Event kind id — matches an `EventKindDescriptor.kind`. */
14903
- kind: zod.z.string(),
14904
- /** Snapshot of the sensor cap's runtime-state slice at the change. */
14905
- value: zod.z.record(zod.z.string(), zod.z.unknown()).nullable(),
14906
- timestamp: zod.z.number()
14907
- });
14908
- var TrackPositionSchema = zod.z.object({
14909
- x: zod.z.number(),
14910
- y: zod.z.number(),
14911
- timestamp: zod.z.number(),
14912
- bbox: BoundingBoxSchema
14897
+ name: zod.z.string(),
14898
+ createdAt: zod.z.string(),
14899
+ updatedAt: zod.z.string(),
14900
+ engine: PipelineEngineChoiceSchema,
14901
+ steps: zod.z.array(PipelineTemplateStepSchema).readonly()
14913
14902
  });
14914
- var TrackSnapshotSchema = zod.z.object({
14915
- timestamp: zod.z.number(),
14916
- position: TrackPositionSchema,
14917
- /** MediaStore key; resolve via `getTrackMedia({ trackId })`. */
14918
- mediaKey: zod.z.string()
14903
+ var PipelineModelOptionSchema = zod.z.object({
14904
+ id: zod.z.string(),
14905
+ name: zod.z.string(),
14906
+ formats: zod.z.record(zod.z.string(), zod.z.object({
14907
+ downloaded: zod.z.boolean(),
14908
+ sizeMB: zod.z.number()
14909
+ })),
14910
+ group: ModelVariantGroupSchema.optional(),
14911
+ legacy: zod.z.boolean().optional(),
14912
+ provider: ModelProviderIdSchema.optional()
14919
14913
  });
14920
- /**
14921
- * Normalized 0..1 trajectory envelope (min/max over every position bbox,
14922
- * divided by the track's detection-frame dims), computed at persist time.
14923
- * Absent when the frame dims were unknown when the track was persisted
14924
- * (legacy rows / dims-less sources) and on active (in-RAM) tracks.
14925
- */
14926
- var TrackEnvelopeSchema = zod.z.object({
14927
- minX: zod.z.number(),
14928
- minY: zod.z.number(),
14929
- maxX: zod.z.number(),
14930
- maxY: zod.z.number()
14914
+ var ConfigFieldBridge = zod.z.custom();
14915
+ var PipelineAddonSchemaSchema = zod.z.object({
14916
+ id: zod.z.string(),
14917
+ name: zod.z.string(),
14918
+ slot: PipelineSlotSchema,
14919
+ inputClasses: zod.z.array(zod.z.string()).readonly(),
14920
+ outputClasses: zod.z.array(zod.z.string()).readonly(),
14921
+ childSlots: zod.z.array(PipelineSlotSchema).readonly(),
14922
+ models: zod.z.array(PipelineModelOptionSchema).readonly(),
14923
+ defaultModelId: zod.z.string(),
14924
+ defaultModelIdByFormat: zod.z.record(zod.z.string(), zod.z.string()).optional(),
14925
+ enabledByDefault: zod.z.boolean().optional(),
14926
+ backfillIntoExistingOverrides: zod.z.boolean().optional(),
14927
+ defaultConfidence: zod.z.number(),
14928
+ group: zod.z.string().optional(),
14929
+ configSchema: zod.z.array(ConfigFieldBridge).readonly().optional()
14931
14930
  });
14932
- /**
14933
- * Row projection for track list queries. `full` (default) returns the
14934
- * complete Track including the frame-rate `positions[]` history and the
14935
- * `snapshots[]` references — megabytes across a page of tracks. `slim`
14936
- * keeps every scalar the list surfaces actually render (ids, class(es),
14937
- * label / audioLabels / importance enrichment, firstSeen/lastSeen, state,
14938
- * zonesVisited, bestEventId, envelope, hasFace, hasEmbeddedFace, hasRider) and returns `positions` /
14939
- * `snapshots` as EMPTY arrays — detail views re-fetch the full row via
14940
- * `getTrack`. Mirrors the event-store `projection` convention
14941
- * (`getObjectEvents` et al.).
14942
- */
14943
- var TrackProjectionSchema = zod.z.enum(["full", "slim"]);
14944
- /**
14945
- * One audio-classification label heard on the track's camera while the
14946
- * track was alive, aggregated per label. An "episode" is one persisted
14947
- * audio event (the confident-classification path: score ≥ the device's
14948
- * `classificationMinScore`, class-change-or-heartbeat coalesced) — NOT
14949
- * one 32 ms inference chunk, so counts stay human-scaled.
14950
- */
14951
- var TrackAudioLabelSchema = zod.z.object({
14931
+ var PipelineSlotSchemaSchema = zod.z.object({
14932
+ id: PipelineSlotSchema,
14952
14933
  label: zod.z.string(),
14953
- /** Highest classification score observed across the label's episodes. */
14954
- peakScore: zod.z.number(),
14955
- /** Number of coalesced audio-event episodes carrying this label. */
14956
- count: zod.z.number(),
14957
- firstAt: zod.z.number(),
14958
- lastAt: zod.z.number()
14934
+ priority: zod.z.number(),
14935
+ parentSlot: PipelineSlotSchema.nullable(),
14936
+ addons: zod.z.array(PipelineAddonSchemaSchema).readonly()
14937
+ });
14938
+ var PipelineSchemaSchema = zod.z.object({
14939
+ availableEngines: zod.z.array(AvailableEngineSchema).readonly(),
14940
+ selectedEngine: PipelineEngineChoiceSchema,
14941
+ slots: zod.z.array(PipelineSlotSchemaSchema).readonly()
14942
+ });
14943
+ var EngineProvisioningSchema = zod.z.object({
14944
+ runtimeId: zod.z.enum([
14945
+ "onnx",
14946
+ "openvino",
14947
+ "coreml",
14948
+ "edgetpu"
14949
+ ]).nullable(),
14950
+ device: zod.z.string().nullable(),
14951
+ state: zod.z.enum([
14952
+ "idle",
14953
+ "installing",
14954
+ "verifying",
14955
+ "ready",
14956
+ "failed"
14957
+ ]),
14958
+ progress: zod.z.number().optional(),
14959
+ error: zod.z.string().optional(),
14960
+ nextRetryAt: zod.z.number().optional(),
14961
+ /**
14962
+ * Gate A (config-correctness gate at engine change): human-readable
14963
+ * config issues surfaced EAGERLY when the node's engine changes — model
14964
+ * substitutions ("chose X, running Y") and zero-build steps ("no model
14965
+ * has a <format> build"). Additive/optional: informational only, never
14966
+ * enforced here — `assertEngineReady` (readiness) still gates inference.
14967
+ * Absent/empty when the node-default tree resolves cleanly.
14968
+ */
14969
+ configIssues: zod.z.array(zod.z.string()).optional()
14970
+ });
14971
+ var PipelineStepInputSchema = zod.z.lazy(() => zod.z.object({
14972
+ addonId: zod.z.string(),
14973
+ modelId: zod.z.string().optional(),
14974
+ enabled: zod.z.boolean().default(true),
14975
+ children: zod.z.array(PipelineStepInputSchema).optional(),
14976
+ settings: zod.z.record(zod.z.string(), zod.z.unknown()).optional(),
14977
+ jumpDeviceKey: zod.z.string().optional()
14978
+ }));
14979
+ var ModelSubstitutionSchema = zod.z.object({
14980
+ addonId: zod.z.string(),
14981
+ chosen: zod.z.string(),
14982
+ running: zod.z.string(),
14983
+ format: zod.z.string()
14984
+ });
14985
+ var PipelineValidationIssueSchema = zod.z.object({
14986
+ addonId: zod.z.string(),
14987
+ kind: zod.z.enum(["unknown-addon", "no-format-build"]),
14988
+ detail: zod.z.string()
14989
+ });
14990
+ var PipelineValidationResultSchema = zod.z.object({
14991
+ ok: zod.z.boolean(),
14992
+ issues: zod.z.array(PipelineValidationIssueSchema).readonly(),
14993
+ substitutions: zod.z.array(ModelSubstitutionSchema).readonly(),
14994
+ /** The node's `currentEngine.format` this validation ran against. */
14995
+ format: zod.z.string()
14996
+ });
14997
+ var ReferenceImageEntrySchema = zod.z.object({
14998
+ filename: zod.z.string(),
14999
+ stepIds: zod.z.array(zod.z.string()).readonly().optional()
15000
+ });
15001
+ var ReferenceImageBodySchema = zod.z.object({
15002
+ base64: zod.z.string(),
15003
+ filename: zod.z.string()
15004
+ });
15005
+ var ReferenceAudioEntrySchema = zod.z.object({
15006
+ filename: zod.z.string(),
15007
+ sizeKb: zod.z.number()
15008
+ });
15009
+ var ReferenceAudioBodySchema = zod.z.object({ base64: zod.z.string() });
15010
+ var AudioBackendSchema = zod.z.object({
15011
+ id: zod.z.string(),
15012
+ name: zod.z.string(),
15013
+ description: zod.z.string(),
15014
+ available: zod.z.boolean(),
15015
+ /**
15016
+ * Raw classifier labels this backend can emit (e.g. YAMNet's
15017
+ * 521-class set or Apple SoundAnalysis's 303-class set). Used by
15018
+ * the benchmark UI to populate the `enabledMicroClasses` filter
15019
+ * specific to the selected backend without a separate fetch.
15020
+ */
15021
+ rawLabels: zod.z.array(zod.z.string()).readonly().optional()
15022
+ });
15023
+ var AudioCapabilitiesSchema = zod.z.object({
15024
+ activeBackend: zod.z.string(),
15025
+ availableBackends: zod.z.array(AudioBackendSchema).readonly(),
15026
+ sampleRate: zod.z.number(),
15027
+ chunkDurationMs: zod.z.number()
15028
+ });
15029
+ var DownloadModelResultSchema = zod.z.object({
15030
+ filePath: zod.z.string(),
15031
+ sizeMB: zod.z.number(),
15032
+ durationMs: zod.z.number()
14959
15033
  });
14960
15034
  /**
14961
- * How a track was produced. `pipeline` (default / absent) = the spatial
14962
- * detection+tracking pipeline. Every OTHER value is a SYNTHETIC projection —
14963
- * no positions, a single snapshot, and no bbox trajectory at all:
14964
- *
14965
- * - `sensor` a linked sensor/control device state change.
14966
- * - `audio` an audio event on the camera itself that was anomalous for
14967
- * THAT camera, loud, and heard while nothing visual was happening (D62).
14968
- *
14969
- * The spatial subsystems (tracker association, occupancy count, re-id /
14970
- * embedding, resurrection) MUST skip every synthetic source. Test for that
14971
- * with `isSpatialTrack`, which allow-lists `pipeline` — a `!== 'sensor'`
14972
- * check silently readmits every source added after it was written.
14973
- */
14974
- var TrackSourceSchema = zod.z.enum([
14975
- "pipeline",
14976
- "sensor",
14977
- "audio"
14978
- ]);
14979
- /**
14980
- * Where a track sits in the RETRAIN lifecycle (D81).
14981
- *
14982
- * - `none` — never marked, or un-marked. Evictable.
14983
- * - `staging` — the operator wants this track as training material and has not
14984
- * finished with it. **This is the only state retention holds**: the track and
14985
- * everything it owns (object events, crops, keyframes, CLIP vector) survive
14986
- * the device's age window.
14987
- * - `trained` — the retrain page has taken what it needed. The frames it chose
14988
- * were COPIED into the retrain dataset at selection time, so the dataset no
14989
- * longer depends on the track's media and the track becomes EVICTABLE again.
14990
- * Terminal for the plain `markForTrain` toggle: returning it to `staging` is
14991
- * a deliberate action of the retrain page, not a side effect of a checkbox.
14992
- *
14993
- * There is no `null`. The state is stored `TEXT NOT NULL DEFAULT 'none'` because
14994
- * the store's filter language has only positive equality and `whereIn` — no
14995
- * negation, no IS NULL — so a NULL would be unselectable by ANY predicate and
14996
- * would make the entire pre-column history immortal in one deploy.
14997
- */
14998
- var RetrainStatusSchema = zod.z.enum([
14999
- "none",
15000
- "staging",
15001
- "trained"
15002
- ]);
15003
- /**
15004
- * Per-track OPERATOR flags — set by hand from the admin UI or the viewer, never
15005
- * by the pipeline. Spread into `TrackSchema` and `KeyEventSchema` from one place
15006
- * so the two surfaces cannot drift.
15007
- *
15008
- * **Absent ≠ false.** A track that has never been touched omits the field; an
15009
- * explicitly un-flagged track carries `false`. Legacy rows written before the
15010
- * columns existed read as absent, and a consumer that needs a boolean should say
15011
- * `flag === true`, not `flag !== false`.
15012
- *
15013
- * `markForTrain` is the WIRE FACE of {@link RetrainStatusSchema}, not a column:
15014
- * it is exactly `retrainStatus === 'staging'`, in both directions. Writing
15015
- * `true` moves `none → staging`, writing `false` moves `staging → none`, and a
15016
- * `trained` track reports `false` while refusing both writes. The boolean is
15017
- * kept because three surfaces drive a toggle off it; anything that needs to tell
15018
- * "never marked" from "already trained" must read `retrainStatus`.
15019
- *
15020
- * `debug` does NOT pin; it is attention, not durability.
15021
- *
15022
- * `favourited` IS a BOOLEAN pin (durability bit), not a retrain lifecycle.
15023
- * A favourited track is skipped by retention the same way `staging` is, but
15024
- * it does not enter `none|staging|trained` and has no staging budget.
15025
- */
15026
- var TrackFlagFields = {
15027
- /** Operator marked this track as training material — i.e. `retrainStatus` is
15028
- * `'staging'`. */
15029
- markForTrain: zod.z.boolean().optional(),
15030
- /** Operator marked this track for diagnostic attention. */
15031
- debug: zod.z.boolean().optional(),
15032
- /** Operator favourited this track. Pins it against pruning. */
15033
- favourited: zod.z.boolean().optional()
15034
- };
15035
- /**
15036
- * The lifecycle field itself, on the READ surfaces only (`Track`, `KeyEvent`).
15037
- * Deliberately NOT part of {@link TrackFlagFields}: that group also builds the
15038
- * write patch, and the status is not something the toggle sets — it is what the
15039
- * toggle's boolean is derived from. Absent on an in-RAM track never touched;
15040
- * always present on a persisted row (the column default materialises `'none'`).
15041
- */
15042
- var TrackRetrainFields = { retrainStatus: RetrainStatusSchema.optional() };
15043
- /**
15044
- * The write half: a PARTIAL patch. An omitted key is left untouched, so setting
15045
- * one flag can never clear the other — the toggles are independent and are
15046
- * driven from three surfaces that do not know about each other.
15047
- */
15048
- var TrackFlagsPatchSchema = zod.z.object(TrackFlagFields);
15049
- /**
15050
- * The resolved flag state after a write. Both fields are REQUIRED here (absent
15051
- * collapses to `false`) so a caller can drive a toggle's checked state off the
15052
- * mutation result without a re-fetch.
15035
+ * Wrapper carrying a single test run's result. Replaces the legacy
15036
+ * ad-hoc `{labels: [{className, originalClass, score}]}` shape with the
15037
+ * canonical `AudioResult` from the Phase 6 output rework: one
15038
+ * `AudioDetection` per class above `minScore`, top-N candidates in
15039
+ * `debug.alternateLabels['audio-classifier']`, per-source timings in
15040
+ * `debug.stepTimings`. The outer `success`/`error` fields stay so the
15041
+ * benchmark UI can still report a clean failure when the classifier
15042
+ * cap isn't available.
15053
15043
  */
15054
- var TrackFlagsSchema = zod.z.object({
15055
- trackId: zod.z.string(),
15056
- markForTrain: zod.z.boolean(),
15057
- debug: zod.z.boolean(),
15058
- favourited: zod.z.boolean(),
15059
- /** The lifecycle state the boolean was derived from. Required here (unlike on
15060
- * a track row) because this shape is only ever produced by the write body,
15061
- * which always knows it — and a surface that has just written needs to render
15062
- * `trained` without a re-fetch. */
15063
- retrainStatus: RetrainStatusSchema
15044
+ var AudioTestResultSchema = zod.z.object({
15045
+ success: zod.z.boolean(),
15046
+ error: zod.z.string().optional(),
15047
+ frame: zod.z.custom().optional()
15064
15048
  });
15049
+ var PipelineConfigBridge = zod.z.custom();
15050
+ var ConfigUISchemaBridge = zod.z.custom();
15051
+ var ConfigUISchemaNullableBridge = zod.z.custom();
15052
+ var InferenceCapabilitiesBridge = zod.z.custom();
15053
+ var ModelAvailabilityListBridge = zod.z.custom();
15054
+ var PipelineRunResultBridge = zod.z.custom();
15065
15055
  /**
15066
- * WHICH tier a label occupies. The slot a label lands in is DECLARED by the
15067
- * step that produced it (`StepDefinition.labelTier`), never inferred from the
15068
- * text or the step's name.
15056
+ * Pipeline executor detection engine + configuration + inference API.
15069
15057
  *
15070
- * - `1` a SUB-CLASS: finer than the macro class, still a taxonomy token.
15071
- * `animal-type` (`dog`, `bird`), `vehicle-type` (`van`), and the root
15072
- * detector's own raw class when it is finer than the macro it maps to.
15073
- * - `2` — an INSTANCE: the finest thing said about this subject.
15074
- * `species` (`Turdus migratorius`), `identity` (`Alice`), `plate-text`.
15058
+ * Merged from: pipeline-executor, pipeline-config, inference, detection-config.
15059
+ * Implemented by the detection-pipeline addon.
15075
15060
  *
15076
- * The macro class itself (`person`, `vehicle`, `animal`, `package`, `face`,
15077
- * `plate`, `audio`) is NOT a tier it is `className`, and a macro token
15078
- * offered for either label slot is refused (2026-08-07 rule; the refusal is
15079
- * logged as `label tier collapse refused`).
15061
+ * Per-device surface (DeviceSettingsContribution + the "is detection
15062
+ * enabled for this camera?" toggle) lives on the paired
15063
+ * `detection-pipeline` cap (device-scoped, singleton, wrapper
15064
+ * defaultActive) same split pattern used by stream-broker /
15065
+ * camera-streams and audio-analyzer / audio-analysis.
15080
15066
  */
15081
- var LabelTierSchema = zod.z.union([zod.z.literal(1), zod.z.literal(2)]);
15067
+ var pipelineExecutorCapability = {
15068
+ name: "pipeline-executor",
15069
+ scope: "system",
15070
+ mode: "singleton",
15071
+ methods: {
15072
+ getAvailableEngines: require_sleep.method(zod.z.void(), zod.z.array(PipelineEngineChoiceSchema)),
15073
+ getSelectedEngine: require_sleep.method(zod.z.void(), PipelineEngineChoiceSchema),
15074
+ getDefaultSteps: require_sleep.method(PipelineEngineChoiceSchema, zod.z.array(PipelineDefaultStepSchema)),
15075
+ /**
15076
+ * Per-node detection-engine provisioning snapshot. Returns the live
15077
+ * state of the lazy runtime-provisioning machine on `nodeId`
15078
+ * (idle / installing / verifying / ready / failed). The UI pairs this
15079
+ * one-shot query with the `pipeline.engine-provisioning` live event
15080
+ * (emitted on every transition) to drive a per-node "engine ready?"
15081
+ * indicator without polling. Phase 2.
15082
+ */
15083
+ getEngineProvisioning: require_sleep.method(zod.z.object({ nodeId: zod.z.string() }), EngineProvisioningSchema),
15084
+ getVideoPipelineSteps: require_sleep.method(zod.z.void(), zod.z.record(zod.z.string(), zod.z.object({
15085
+ modelId: zod.z.string(),
15086
+ settings: zod.z.record(zod.z.string(), zod.z.unknown()).readonly()
15087
+ }))),
15088
+ setVideoPipelineSteps: require_sleep.method(zod.z.object({ steps: zod.z.record(zod.z.string(), zod.z.object({
15089
+ modelId: zod.z.string(),
15090
+ settings: zod.z.record(zod.z.string(), zod.z.unknown()).readonly()
15091
+ })) }), zod.z.object({ success: zod.z.literal(true) }), {
15092
+ kind: "mutation",
15093
+ auth: "admin"
15094
+ }),
15095
+ /**
15096
+ * Clear THIS node's executor-side PER-DEVICE settings stores (the
15097
+ * per-camera step overrides the object-detection root reads via
15098
+ * `applyDeviceOverridesToTree`). `nodeId` is the ROUTING key — the
15099
+ * generated cap-router strips it (default `nodeIdMode: 'routing'`) and
15100
+ * dispatches to that node, so the provider method runs ON the target
15101
+ * node and receives no `nodeId`.
15102
+ *
15103
+ * This is the slimmed executor leg of the orchestrator's
15104
+ * `resetNodePipelineDefaults` flow (which owns the real reset: node
15105
+ * addonDefaults pins + per-camera orchestrator overrides). The legacy
15106
+ * `resetToDefault` — which reset a persisted global step-tree seed
15107
+ * nothing in the live per-camera path read — was removed together with
15108
+ * that seed.
15109
+ */
15110
+ clearDeviceOverrides: require_sleep.method(zod.z.object({ nodeId: zod.z.string() }), zod.z.object({
15111
+ success: zod.z.literal(true),
15112
+ clearedDevices: zod.z.number()
15113
+ }), {
15114
+ kind: "mutation",
15115
+ auth: "admin"
15116
+ }),
15117
+ /**
15118
+ * Which of THIS node's inference devices the executor currently refuses,
15119
+ * and why. `nodeId` is the ROUTING key (stripped by the generated router).
15120
+ *
15121
+ * The channel that did not exist. Pool health was known only inside the
15122
+ * detection addon and was an input to no routing decision anywhere: the
15123
+ * per-dispatch capability gate is keyed on model FORMAT and so can never
15124
+ * separate `openvino:gpu` from `openvino:npu`, and the orchestrator's live
15125
+ * eligibility probe (`platformProbe.getCapabilities`) answers about
15126
+ * HARDWARE — which was present throughout. So when the hub's `openvino:gpu`
15127
+ * Python worker was SIGABRT'd by the Intel GPU plugin on 2026-08-25, the
15128
+ * balancer went on handing that dead pool cameras by rotation for 31 hours:
15129
+ * ~370 000 `PoolWorker[w0]: not initialized` lines, every frame lost.
15130
+ *
15131
+ * Read semantics the caller depends on, and which the provider guarantees:
15132
+ * this is a synchronous read of in-memory state. It never probes hardware,
15133
+ * never spawns a pool and never throws — an EMPTY `unhealthy` means "asked,
15134
+ * nothing is refused", which is what re-admits a device. A read that FAILS
15135
+ * (node offline, version skew) must therefore be distinguishable from an
15136
+ * empty answer, and it is: it rejects.
15137
+ */
15138
+ getInferenceDeviceHealth: require_sleep.method(zod.z.object({ nodeId: zod.z.string() }), zod.z.object({ unhealthy: zod.z.array(zod.z.object({
15139
+ /** `<backend>:<device>`, e.g. `openvino:gpu`. */
15140
+ deviceKey: zod.z.string(),
15141
+ /**
15142
+ * `failed` — the per-device restart budget is exhausted; no pool
15143
+ * will be spawned until an operator re-arms it or the runner
15144
+ * respawns. `backoff` — under budget, waiting out the backoff (or
15145
+ * a cached pool observed dead and not yet condemned).
15146
+ */
15147
+ state: zod.z.enum(["failed", "backoff"]),
15148
+ /** Epoch ms of the death that produced this state. */
15149
+ since: zod.z.number(),
15150
+ /** Pool deaths inside the current window. */
15151
+ deaths: zod.z.number(),
15152
+ /** The last death's message. */
15153
+ lastError: zod.z.string()
15154
+ })).readonly() })),
15155
+ /**
15156
+ * Re-arm a terminally `failed` inference device on `nodeId`: forget its
15157
+ * restart budget so the next dispatch builds a fresh pool.
15158
+ *
15159
+ * The terminal state is deliberate (the abort it bounds is deterministic —
15160
+ * an automatic probation would just respawn Python forever, more slowly),
15161
+ * and a terminal state an operator cannot leave is a silent fault. This is
15162
+ * the way out. `rearmed:false` means there was nothing to forget.
15163
+ */
15164
+ rearmInferenceDevice: require_sleep.method(zod.z.object({
15165
+ nodeId: zod.z.string(),
15166
+ deviceKey: zod.z.string()
15167
+ }), zod.z.object({ rearmed: zod.z.boolean() }), {
15168
+ kind: "mutation",
15169
+ auth: "admin"
15170
+ }),
15171
+ getSchema: require_sleep.method(zod.z.void(), PipelineSchemaSchema),
15172
+ getGlobalSteps: require_sleep.method(zod.z.void(), zod.z.array(PipelineDefaultStepSchema).readonly().nullable()),
15173
+ getGlobalPipelineConfig: require_sleep.method(zod.z.void(), PipelineConfigBridge),
15174
+ getOrchestratorConfigSchema: require_sleep.method(zod.z.void(), ConfigUISchemaBridge),
15175
+ /**
15176
+ * Gate B (pre-init config-correctness gate). PURE COMPUTE against this
15177
+ * node's `currentEngine.format` — resolves `steps` the same way the
15178
+ * runtime dispatch path would, and reports what WOULD happen without
15179
+ * touching any node-global state. Called by the orchestrator at attach
15180
+ * time (`attachOn`), node-pinned to the TARGET node, so config problems
15181
+ * surface BEFORE `pipelineRunner.attachCamera` rather than at the first
15182
+ * per-frame resolve. `ok` is false iff `issues` is non-empty (both
15183
+ * `unknown-addon` and `no-format-build` are HARD issues); `substitutions`
15184
+ * is informational (a degraded-but-loadable model swap) and never
15185
+ * affects `ok`. Never throws.
15186
+ */
15187
+ validatePipeline: require_sleep.method(zod.z.object({ steps: zod.z.array(PipelineStepInputSchema) }), PipelineValidationResultSchema),
15188
+ listTemplates: require_sleep.method(zod.z.void(), zod.z.array(PipelineTemplateSchema$1).readonly()),
15189
+ saveTemplate: require_sleep.method(zod.z.object({
15190
+ name: zod.z.string(),
15191
+ steps: zod.z.array(PipelineTemplateStepSchema).readonly(),
15192
+ engine: PipelineEngineChoiceSchema
15193
+ }), PipelineTemplateSchema$1, { kind: "mutation" }),
15194
+ updateTemplate: require_sleep.method(zod.z.object({
15195
+ id: zod.z.string(),
15196
+ name: zod.z.string().optional(),
15197
+ steps: zod.z.array(PipelineTemplateStepSchema).readonly().optional()
15198
+ }), PipelineTemplateSchema$1, { kind: "mutation" }),
15199
+ deleteTemplate: require_sleep.method(zod.z.object({ id: zod.z.string() }), zod.z.void(), { kind: "mutation" }),
15200
+ getCapabilities: require_sleep.method(zod.z.void(), InferenceCapabilitiesBridge),
15201
+ getAddonModels: require_sleep.method(zod.z.object({ addonId: zod.z.string() }), ModelAvailabilityListBridge),
15202
+ downloadModel: require_sleep.method(zod.z.object({
15203
+ addonId: zod.z.string(),
15204
+ modelId: zod.z.string(),
15205
+ format: ModelFormatSchema$1
15206
+ }), DownloadModelResultSchema, { kind: "mutation" }),
15207
+ deleteModel: require_sleep.method(zod.z.object({
15208
+ addonId: zod.z.string(),
15209
+ modelId: zod.z.string(),
15210
+ format: ModelFormatSchema$1
15211
+ }), zod.z.object({ success: zod.z.literal(true) }), { kind: "mutation" }),
15212
+ /**
15213
+ * Stateless single-frame execution. Callers (runner, benchmark) pass
15214
+ * the complete `engine` + `steps` tree; the executor holds no state
15215
+ * about cameras or saved pipelines.
15216
+ *
15217
+ * `engine` is optional during the migration window to preserve the
15218
+ * legacy call shape used by existing benchmark code; once all
15219
+ * callers pass it explicitly we make it required.
15220
+ *
15221
+ * Exactly one of `frame`, `frameRef`, `frameHandle`, `imageBase64`,
15222
+ * `referenceImage` must be provided:
15223
+ * - `frame`: runtime dispatch path (runner → decoded broker frame).
15224
+ * Carries the raw buffer, dimensions, and format; the executor
15225
+ * uses it directly without base64 round-tripping.
15226
+ * - `frameHandle` (CB5): a zero-pixel shm `FrameHandle` for the SAME
15227
+ * decoded frame. Both runner and executor are hub-local processes
15228
+ * sharing `/dev/shm`, so the executor maps the named segment and
15229
+ * reads the pixels back zero-copy — eliminating the ~1.2MB
15230
+ * re-serialisation over UDS/MsgPack the `frame` path pays per call.
15231
+ * High-risk: the FrameRing is a latest-wins seqlock with no
15232
+ * refcount, so a recycled slot yields a null read; the executor
15233
+ * then degrades to an empty result and the runner ships pixels via
15234
+ * `frame` as the fallback (queue-depth gated on the runner side).
15235
+ * - `imageBase64`: one-shot test path (benchmark ImageTab).
15236
+ * - `referenceImage`: named file from the reference-image store.
15237
+ */
15238
+ runPipeline: require_sleep.method(zod.z.object({
15239
+ engine: PipelineEngineChoiceSchema.optional(),
15240
+ steps: zod.z.array(PipelineStepInputSchema).min(1),
15241
+ frame: FrameInputSchema.optional(),
15242
+ /**
15243
+ * Process-local lazy frame. Valid only when caller and provider resolve
15244
+ * in the same execution-group process; split/cross-node callers use
15245
+ * `frame`/`image` inline compatibility instead.
15246
+ */
15247
+ frameRef: FrameRefSchema.optional(),
15248
+ /**
15249
+ * CB5 shm passthrough — a `FrameHandle` naming the same ring slot
15250
+ * the decoded pixels live in. One more member of the one-of
15251
+ * frame/frameHandle/image/imageBase64/referenceImage group.
15252
+ */
15253
+ frameHandle: require_sleep.FrameHandleSchema.optional(),
15254
+ imageBase64: zod.z.string().optional(),
15255
+ /**
15256
+ * Binary JPEG bytes — preferred over `imageBase64` on internal
15257
+ * hops (hub → forked worker via Moleculer MsgPack) because it
15258
+ * skips the 33% base64 overhead + the per-call base64 decode on
15259
+ * the detection-pipeline worker. Callers can pass either; exactly
15260
+ * one of `frame`/`image`/`imageBase64`/`referenceImage` is required.
15261
+ */
15262
+ image: zod.z.instanceof(Uint8Array).optional(),
15263
+ referenceImage: zod.z.string().optional(),
15264
+ deviceId: zod.z.number().optional(),
15265
+ sessionId: zod.z.string().optional(),
15266
+ /**
15267
+ * Execution plane. 'full' (default) runs the whole tree — benchmark,
15268
+ * reference-image, and detail-subtree calls. 'frame' is the live
15269
+ * per-frame dispatch: ONLY root-plane steps run; crop children
15270
+ * (inputClasses ≠ null) are skipped and served per-track via
15271
+ * pipelineRunner.runDetailSubtree (two-plane design).
15272
+ */
15273
+ plane: zod.z.enum(["full", "frame"]).optional(),
15274
+ /**
15275
+ * Inference-device selector (Phase 2 multi-device). Format
15276
+ * `<backend>:<device>` (e.g. `openvino:gpu`, `edgetpu:usb`, `cpu`).
15277
+ * Omitted ⇒ the runner's default device (current single-engine
15278
+ * behaviour). Selects WHICH device pool of the node runs the call.
15279
+ */
15280
+ deviceKey: zod.z.string().optional(),
15281
+ /**
15282
+ * Two-plane NATIVE child-crop reference. Set by `runDetailSubtree` ONLY
15283
+ * when the parent crop was resolved from the frame's retained NATIVE
15284
+ * surface (a frameHandle HIT). Lets the executor re-cut a LEAF crop
15285
+ * child's ROI (plate-ocr, face-embedding, leaf classifiers) at native
15286
+ * resolution from that surface — the SAME quality path faces already
15287
+ * had — instead of the downscaled parent tile. `handle` keys the native
15288
+ * surface (node-pinned to its owner); `cropFrameSpace` is the parent
15289
+ * crop's padded/clamped rectangle in FRAME-space pixels, used to compose
15290
+ * the executor's crop-normalized child ROI back into frame-normalized
15291
+ * coordinates. Auxiliary to the image source (`image`/`frame`/…), NOT one
15292
+ * of the mutually-exclusive image inputs. Absent ⇒ tile-crop children
15293
+ * (today's behaviour on the fallback path).
15294
+ */
15295
+ nativeCropRef: NativeCropRefSchema.optional()
15296
+ }), PipelineRunResultBridge, { kind: "mutation" }),
15297
+ /**
15298
+ * Batched run — N raw frames packed into one cap call. The provider
15299
+ * routes the batch through `SharedInferencePool.inferBatch`
15300
+ * (`MSG_INFER_BATCH = 0x03`) so the IPC framing and JSON response
15301
+ * envelope cost is amortised N:1 vs N concurrent `runPipeline`
15302
+ * calls. Single root step + uniform model assumed; trees with crop
15303
+ * children fall back to sequential execution.
15304
+ *
15305
+ * Used by `scripts/bench-batch-style.mts` for batch benchmarking —
15306
+ * N frames in one call to amortise per-call IPC overhead.
15307
+ */
15308
+ runPipelineBatch: require_sleep.method(zod.z.object({
15309
+ engine: PipelineEngineChoiceSchema.optional(),
15310
+ steps: zod.z.array(PipelineStepInputSchema).min(1),
15311
+ frames: zod.z.array(FrameInputSchema).min(1).max(255),
15312
+ deviceId: zod.z.number().optional(),
15313
+ sessionId: zod.z.string().optional(),
15314
+ /**
15315
+ * Pure-inference benchmark hint. A NONZERO uint32 pins every frame in
15316
+ * the batch to the Python pool's bench preprocess cache
15317
+ * (`_bench_frame_id`) so a REPEATED benchmark frame is decoded +
15318
+ * preprocessed ONCE and every later inference is a pure-inference cache
15319
+ * hit — the sustained-throughput run measures inference, not
15320
+ * decode+preprocess+infer. Omitted/0 for live frames (all different →
15321
+ * full preprocess every call, correct). Fresh per sustained run;
15322
+ * released via `uncacheFrame`.
15323
+ */
15324
+ frameId: zod.z.number().int().nonnegative().optional(),
15325
+ /** Inference-device selector (Phase 2 multi-device); see runPipeline. */
15326
+ deviceKey: zod.z.string().optional()
15327
+ }), zod.z.object({ results: zod.z.array(PipelineRunResultBridge).readonly() }), { kind: "mutation" }),
15328
+ /**
15329
+ * Cache a raw frame inside the Python inference pool's memory.
15330
+ * Returns a numeric `frameId` that `inferCached` references —
15331
+ * subsequent calls send only 5 bytes through the pipe instead of
15332
+ * 1.2MB raw data, eliminating the pipe transfer bottleneck.
15333
+ */
15334
+ cacheFrameInPool: require_sleep.method(zod.z.object({
15335
+ data: zod.z.instanceof(Uint8Array),
15336
+ width: zod.z.number().int().positive(),
15337
+ height: zod.z.number().int().positive(),
15338
+ format: zod.z.enum([
15339
+ "rgb",
15340
+ "bgr",
15341
+ "gray"
15342
+ ])
15343
+ }), zod.z.object({
15344
+ frameId: zod.z.number(),
15345
+ width: zod.z.number(),
15346
+ height: zod.z.number()
15347
+ }), { kind: "mutation" }),
15348
+ /**
15349
+ * Run inference on a previously cached frame. Sends only 5 bytes
15350
+ * (model_idx + frameId) through the IPC pipe — eliminates the
15351
+ * ~35ms per-call overhead of transferring 1.2MB raw data.
15352
+ */
15353
+ inferCached: require_sleep.method(zod.z.object({
15354
+ stepId: zod.z.string(),
15355
+ frameId: zod.z.number().int()
15356
+ }), zod.z.record(zod.z.string(), zod.z.unknown()), { kind: "mutation" }),
15357
+ /**
15358
+ * Release a cached frame from the Python pool's memory.
15359
+ */
15360
+ uncacheFrame: require_sleep.method(zod.z.object({ frameId: zod.z.number().int() }), zod.z.void(), { kind: "mutation" }),
15361
+ /** Returns the effective pool tuning (resolved from user overrides + backend defaults). */
15362
+ getEffectiveTuning: require_sleep.method(zod.z.void(), zod.z.object({
15363
+ batchMode: zod.z.string(),
15364
+ windowMs: zod.z.number(),
15365
+ maxBatchSize: zod.z.number(),
15366
+ concurrency: zod.z.number()
15367
+ })),
15368
+ /**
15369
+ * List every EngineFactory currently loaded in this executor's RAM,
15370
+ * with the models resident and a coarse "in use" marker derived from
15371
+ * ongoing inference activity. Used by the Pipeline page Engines tab.
15372
+ */
15373
+ listLoadedEngines: require_sleep.method(zod.z.void(), zod.z.array(zod.z.object({
15374
+ engineKey: zod.z.string(),
15375
+ engine: PipelineEngineChoiceSchema,
15376
+ modelsLoaded: zod.z.array(zod.z.string()).readonly(),
15377
+ inUseByCameras: zod.z.array(zod.z.number()).readonly(),
15378
+ /**
15379
+ * Origin of this resident factory.
15380
+ * - `runtime` — main camera-serving engine (no idle TTL).
15381
+ * - `warm-override` — benchmark/test override held in the warm
15382
+ * cache; auto-disposed after the idle TTL.
15383
+ * - `device-pool` — a concurrent per-device pool (Phase 2
15384
+ * multi-device, keyed by `deviceKey`) resolved
15385
+ * via `resolveDeviceFactory`. Runs alongside the
15386
+ * `runtime` engine on a DIFFERENT accelerator
15387
+ * (NPU / iGPU / Coral) — this is how the
15388
+ * Engines tab shows all pools running at once.
15389
+ */
15390
+ kind: zod.z.enum([
15391
+ "runtime",
15392
+ "warm-override",
15393
+ "device-pool"
15394
+ ]),
15395
+ /** Native pid of the underlying Python pool (null when no pool). */
15396
+ poolPid: zod.z.number().nullable(),
15397
+ /** ms since this factory was last used (null when not warm-tracked). */
15398
+ idleMs: zod.z.number().nullable(),
15399
+ /** Idle TTL after which `warm-override` factories self-evict (null when not applicable). */
15400
+ idleTtlMs: zod.z.number().nullable()
15401
+ })).readonly()),
15402
+ /** Warm up an engine without running a frame. No-op if already loaded. */
15403
+ spinEngine: require_sleep.method(zod.z.object({ engine: PipelineEngineChoiceSchema }), zod.z.object({ success: zod.z.literal(true) }), {
15404
+ kind: "mutation",
15405
+ auth: "admin"
15406
+ }),
15407
+ /**
15408
+ * Unload an engine from RAM. `force:true` unloads even when cameras
15409
+ * are actively using it (they re-spin on next frame). Default is
15410
+ * gated — returns `{success:false, reason}` when in use.
15411
+ */
15412
+ killEngine: require_sleep.method(zod.z.object({
15413
+ engine: PipelineEngineChoiceSchema,
15414
+ force: zod.z.boolean().optional()
15415
+ }), zod.z.object({
15416
+ success: zod.z.boolean(),
15417
+ reason: zod.z.string().optional()
15418
+ }), {
15419
+ kind: "mutation",
15420
+ auth: "admin"
15421
+ }),
15422
+ listReferenceImages: require_sleep.method(zod.z.void(), zod.z.array(ReferenceImageEntrySchema).readonly()),
15423
+ getReferenceImage: require_sleep.method(zod.z.object({ filename: zod.z.string() }), ReferenceImageBodySchema.nullable()),
15424
+ getReferenceAudioFiles: require_sleep.method(zod.z.void(), zod.z.array(ReferenceAudioEntrySchema).readonly()),
15425
+ getReferenceAudio: require_sleep.method(zod.z.object({ filename: zod.z.string() }), ReferenceAudioBodySchema.nullable()),
15426
+ getAudioCapabilities: require_sleep.method(zod.z.void(), AudioCapabilitiesSchema),
15427
+ runAudioTest: require_sleep.method(zod.z.object({
15428
+ addonId: zod.z.string(),
15429
+ modelId: zod.z.string(),
15430
+ filename: zod.z.string().optional(),
15431
+ settings: zod.z.record(zod.z.string(), zod.z.unknown()).optional()
15432
+ }), AudioTestResultSchema, { kind: "mutation" }),
15433
+ getDetectionConfigSchema: require_sleep.method(zod.z.void(), ConfigUISchemaNullableBridge)
15434
+ }
15435
+ };
15436
+ //#endregion
15437
+ //#region src/capabilities/schemas/zone-rule.ts
15082
15438
  /**
15083
- * WHO decided a label, and when. Carried per tier so a value can be traced to
15084
- * the step and model that produced it — which is what makes the write rule
15085
- * arguable after the fact ("why is 592's label `dog` and not `Canis lupus`?")
15086
- * and what lets a migrated, UNATTRIBUTED value be told apart from a real one.
15439
+ * Per-stage gating mode applied to the zones a rule references.
15087
15440
  *
15088
- * `stepId` is the pipeline step id (`animal-classifier`, `bird-classifier`,
15089
- * `plate-ocr`, `face-embedding`, `object-detection`), or the sentinel
15090
- * `migration:4g` for a value the 4g migration moved from the single-slot era —
15091
- * that value has no provenance, and the write rule lets ANY properly-attributed
15092
- * write of the same tier replace it regardless of score.
15441
+ * - `include`: the rule contributes to a **whitelist** for its stage.
15442
+ * When at least one `include` rule fires for a stage, only entities
15443
+ * inside one of those zones pass that stage.
15444
+ * - `exclude`: the rule contributes to a **blacklist** for its stage.
15445
+ * Entities inside one of those zones are dropped at that stage.
15446
+ *
15447
+ * `monitor`-style observation (count without filtering) is not a rule
15448
+ * mode — zones without any matching rule are observed naturally by
15449
+ * `zone-analytics` (live snapshot + history), so an "I just want to
15450
+ * count, not filter" use case needs no rule at all.
15093
15451
  */
15094
- var LabelAttributionSchema = zod.z.object({
15095
- stepId: zod.z.string(),
15096
- modelId: zod.z.string().optional(),
15097
- decidedAt: zod.z.number(),
15452
+ var ZoneRuleModeEnum = zod.z.enum(["include", "exclude"]);
15453
+ /**
15454
+ * Per-consumer rule that references existing zones (geometry) and
15455
+ * defines how a specific pipeline stage should treat them. Each
15456
+ * consumer addon owns its own `ZoneRule[]` array in its per-device
15457
+ * settings:
15458
+ *
15459
+ * - `addon-motion-wasm` → `motionZoneRules: ZoneRule[]` (motion stage)
15460
+ * - `addon-detection-pipeline` → `detectionZoneRules: ZoneRule[]` (detection stage)
15461
+ * - future: notification rules, audio gating, etc.
15462
+ *
15463
+ * One rule applies to N zones (`zoneIds[]`) so the operator can
15464
+ * express "ignore motion in ALL of {garden, street}" with a single
15465
+ * rule. `classFilter` narrows the rule to specific object classes —
15466
+ * "drop person detections in the street, but keep cars" is one
15467
+ * `exclude` rule with `classFilter: ['person']`.
15468
+ *
15469
+ * `enabled` is a soft toggle — the operator can keep the rule
15470
+ * configured but inert without deleting it.
15471
+ */
15472
+ var ZoneRuleSchema = zod.z.object({
15473
+ /** Stable rule id — survives edits, used by the UI for diffing. */
15474
+ id: zod.z.string(),
15475
+ /** Optional human-readable label rendered in the rule editor. */
15476
+ name: zod.z.string().optional(),
15477
+ /** Zones this rule targets. The rule's `mode` applies to ALL
15478
+ * listed zones (OR-set: a detection in any one of them counts).
15479
+ * At least one zone id required — a rule with no targets is a
15480
+ * configuration mistake and the form validator rejects it. */
15481
+ zoneIds: zod.z.array(zod.z.string()).min(1).readonly(),
15482
+ mode: ZoneRuleModeEnum,
15098
15483
  /**
15099
- * The GALLERY id behind a recognised tier-2 label a face-gallery
15100
- * `Identity.id` or a plate-gallery `Vehicle.id` (both `randomUUID`).
15101
- *
15102
- * The text alone is a DISPLAY NAME, and a display name is renameable: a
15103
- * notification rule authored on "Gianluca" stopped matching the moment the
15104
- * operator fixed the spelling in the gallery, and nothing said so. The id is
15105
- * the thing that does not move, so it is what a rule matches on
15106
- * (`NcConditions.identities`) and the text is what a human is shown.
15484
+ * Class names this rule applies to. Empty / undefined rule
15485
+ * applies to every class. Class strings match the `macroClass`
15486
+ * field on detections (e.g. `person`, `car`, `dog`).
15487
+ */
15488
+ classFilter: zod.z.array(zod.z.string()).readonly().optional(),
15489
+ /**
15490
+ * Minimum bbox/mask overlap (0–1) with any of the rule's zones
15491
+ * required to consider an entity "in the zone". Defaults to the
15492
+ * consumer's stage default when omitted. Kept for back-compat with
15493
+ * existing per-rule overrides; new operators pick the value via
15494
+ * `bboxInclusionPct` (operator-friendly 0–100). Whichever field is
15495
+ * set, the lower-level engine reads it as a 0–1 fraction.
15496
+ */
15497
+ overlapThreshold: zod.z.number().min(0).max(1).optional(),
15498
+ /**
15499
+ * Operator-friendly version of `overlapThreshold` — the percentage
15500
+ * of the detection's bbox that must lie inside the zone for the
15501
+ * rule to match. Documented default is 85%; the engine substitutes
15502
+ * that when the field is omitted (kept optional so existing rules
15503
+ * stored without it stay valid).
15107
15504
  *
15108
- * Absent when the label names no gallery row a plate the OCR read but no
15109
- * vehicle claims, a sub-class, a species, any tier-1 value.
15505
+ * When BOTH `overlapThreshold` and `bboxInclusionPct` are set on a
15506
+ * rule, the engine prefers `bboxInclusionPct` because it's the
15507
+ * field exposed in the UI. Internally both feed the same gate.
15110
15508
  */
15111
- identityId: zod.z.string().optional()
15509
+ bboxInclusionPct: zod.z.number().min(0).max(100).optional(),
15510
+ /**
15511
+ * When `true` and a detection has a segmentation mask, use the
15512
+ * mask for overlap instead of the bbox. Detection-stage only;
15513
+ * motion rules ignore this field.
15514
+ */
15515
+ preferMask: zod.z.boolean().optional(),
15516
+ /**
15517
+ * Soft-toggle: `false` disables the rule without deleting it.
15518
+ * Defaults to `true` so operators creating a rule via the UI
15519
+ * see it active immediately.
15520
+ */
15521
+ enabled: zod.z.boolean().default(true)
15112
15522
  });
15113
15523
  /**
15114
- * The TIERED label model (roadmap 4g), spread into `TrackSchema` and
15115
- * `ObjectEventSchema` from ONE place so the two surfaces cannot drift — a
15116
- * track and its events always answer the same question the same way.
15524
+ * Convenience array schema used by addon device-settings
15525
+ * contributions and runtime payloads (e.g. `RunnerCameraConfig`).
15526
+ */
15527
+ var ZoneRulesArraySchema = zod.z.array(ZoneRuleSchema).readonly();
15528
+ //#endregion
15529
+ //#region src/capabilities/zones.cap.ts
15530
+ /**
15531
+ * Zone — pure geometry + identity. NO filtering behaviour.
15117
15532
  *
15118
- * Two scalar columns, not an array: every consumer wants "the coarse one" or
15119
- * "the fine one", and an array made both a scan. `label` is tier 1, `subLabel`
15120
- * is tier 2, and each carries its own score + attribution.
15533
+ * Zones describe **where** in the frame the operator wants to flag
15534
+ * something; consumer-owned {@link ZoneRule} arrays describe **how**
15535
+ * each pipeline stage uses them. Splitting the two means a single
15536
+ * polygon "Driveway" can simultaneously back a motion-exclude rule,
15537
+ * a detection-include rule on `['car']`, and an occupancy aggregate
15538
+ * — without three duplicated polygons.
15121
15539
  *
15122
- * **Reading it.** What a human should be shown is `subLabel ?? label` — the
15123
- * finest thing known. Before 4g the single `label` column held the finest
15124
- * value, so a consumer that has not been updated reads the tier-1 slot and
15125
- * shows nothing on a species-only row; that is why the migration puts every
15126
- * pre-4g value in tier 2 (it cannot regress a display that reads the fallback)
15127
- * and why the read surfaces were changed in the same train.
15540
+ * Owned by the orchestrator addon (provider) and mirrored into the
15541
+ * `zones` device-state slice on every mutation. Consumers
15542
+ * (motion-wasm, pipeline-executor, analytics, admin UI) read either
15543
+ * via `api.zones.listZones` (one-shot) or via `dev.state.zones` (live
15544
+ * mirror with `onChanged`).
15128
15545
  *
15129
- * **Writing it.** The slots are independent, which is the whole point: a
15130
- * tier-1 write (`bird`) can never overwrite a tier-2 value (`Turdus
15131
- * migratorius`), so fineness cannot regress by construction. Within a tier the
15132
- * higher score wins. One rule, one implementation — see
15133
- * `pipeline/label-tier.ts` in addon-post-analysis.
15546
+ * Coordinates are normalised fractions of the frame (0–1) so zones
15547
+ * survive resolution changes and stream profile switches.
15548
+ *
15549
+ * `kind` discriminates between full polygons (closed regions used
15550
+ * for intrusion / occupancy filters) and tripwires (open 2-point
15551
+ * line segments used for cross events). Onboard / firmware-reported
15552
+ * zones (Reolink, ONVIF) are out of scope for now — see the deferred
15553
+ * task list.
15134
15554
  */
15135
- var TieredLabelFields = {
15136
- /** Tier 1 the sub-class. See {@link LabelTierSchema}. */
15137
- label: zod.z.string().optional(),
15138
- /** Confidence of the tier-1 value, as reported by the deciding step. */
15139
- labelScore: zod.z.number().optional(),
15140
- /** Provenance of the tier-1 value. See {@link LabelAttributionSchema}. */
15141
- labelMeta: LabelAttributionSchema.optional(),
15142
- /** Tier 2 — the instance. See {@link LabelTierSchema}. */
15143
- subLabel: zod.z.string().optional(),
15144
- /** Confidence of the tier-2 value, as reported by the deciding step. */
15145
- subLabelScore: zod.z.number().optional(),
15146
- /** Provenance of the tier-2 value. See {@link LabelAttributionSchema}. */
15147
- subLabelMeta: LabelAttributionSchema.optional()
15148
- };
15149
- /** Per-camera slice of a training-export estimate. */
15150
- var TrainingExportDeviceTotalsSchema = zod.z.object({
15151
- deviceId: zod.z.number(),
15152
- tracks: zod.z.number().int(),
15153
- files: zod.z.number().int(),
15154
- bytes: zod.z.number().int()
15555
+ var ZoneKindEnum = zod.z.enum(["polygon", "tripwire"]);
15556
+ /** Polygon vertex in fraction-of-frame coordinates (0–1). */
15557
+ var PolygonPointSchema = zod.z.object({
15558
+ x: zod.z.number(),
15559
+ y: zod.z.number()
15155
15560
  });
15156
- /**
15157
- * What a training export WOULD contain. Computed from media index rows only —
15158
- * no blob is read to produce this.
15159
- */
15160
- var TrainingExportSummarySchema = zod.z.object({
15161
- generatedAt: zod.z.number(),
15162
- trackCount: zod.z.number().int(),
15561
+ /** A camera detection zone — pure geometry/identity. */
15562
+ var ZoneSchema = zod.z.object({
15563
+ id: zod.z.string(),
15564
+ name: zod.z.string(),
15565
+ kind: ZoneKindEnum.default("polygon"),
15566
+ /** Polygon vertices, fraction of frame (0–1). */
15567
+ polygon: zod.z.array(PolygonPointSchema).readonly(),
15568
+ /** Visual color for UI rendering. */
15569
+ color: zod.z.string().default("#3b82f6")
15570
+ });
15571
+ /**
15572
+ * Zones capability — per-camera CRUD over polygon detection zones.
15573
+ *
15574
+ * Provider lives in `addon-pipeline-orchestrator` (hub-only). Persists
15575
+ * to per-device settings and mirrors into the `zones` device-state
15576
+ * slice on every mutation, so downstream consumers can subscribe via
15577
+ * `dev.state.zones.onChanged`.
15578
+ *
15579
+ * The cap surface only handles geometry + identity; filtering
15580
+ * behaviour (per-class, include/exclude, threshold) lives in the
15581
+ * consumer addons' rule arrays — see `ZoneRuleSchema` exported from
15582
+ * `capabilities/schemas/zone-rule.js`.
15583
+ */
15584
+ var zonesCapability = {
15585
+ name: "zones",
15586
+ scope: "device",
15587
+ mode: "singleton",
15588
+ deviceTypes: [require_sleep.DeviceType.Camera],
15589
+ methods: {
15590
+ listZones: require_sleep.method(zod.z.object({ deviceId: zod.z.number() }), zod.z.array(ZoneSchema).readonly()),
15591
+ addZone: require_sleep.method(zod.z.object({
15592
+ deviceId: zod.z.number(),
15593
+ zone: ZoneSchema
15594
+ }), zod.z.void(), {
15595
+ kind: "mutation",
15596
+ auth: "admin"
15597
+ }),
15598
+ removeZone: require_sleep.method(zod.z.object({
15599
+ deviceId: zod.z.number(),
15600
+ zoneId: zod.z.string()
15601
+ }), zod.z.void(), {
15602
+ kind: "mutation",
15603
+ auth: "admin"
15604
+ }),
15605
+ updateZone: require_sleep.method(zod.z.object({
15606
+ deviceId: zod.z.number(),
15607
+ zone: ZoneSchema
15608
+ }), zod.z.void(), {
15609
+ kind: "mutation",
15610
+ auth: "admin"
15611
+ })
15612
+ },
15613
+ /**
15614
+ * Runtime-state slice — the live zone catalogue mirrored by the
15615
+ * orchestrator on every CRUD mutation. Consumers read via
15616
+ * `device.state.zones.value` / `.watch(...)` without round-tripping
15617
+ * the cap, and the codegen DeviceProxy auto-wires the reactive
15618
+ * handle. Slice shape is `{ zones: Zone[] }` so future extensions
15619
+ * (e.g. zone groupings) can sit alongside the polygon list.
15620
+ */
15621
+ runtimeState: zod.z.object({ zones: zod.z.array(ZoneSchema).readonly() }),
15622
+ /**
15623
+ * Runtime-state durability: **restored** — written only on operator mutation, so a camera that never had one has nothing to re-derive from. This is the slice `zone-mirror-hydration.ts` exists to paper over.
15624
+ *
15625
+ * See `RuntimeStateDurability`. Enforced by
15626
+ * `scripts/check-runtime-state-durability.ts`.
15627
+ */
15628
+ durability: "restored"
15629
+ };
15630
+ //#endregion
15631
+ //#region src/capabilities/pipeline-analytics.cap.ts
15632
+ /**
15633
+ * pipeline-analytics — device-scoped wrapper cap. Refines raw
15634
+ * per-frame detections emitted by the pipeline runner into tracked
15635
+ * objects, per-kind event collections (motion / object / audio), and
15636
+ * persisted media. Owns the post-detection domain end-to-end:
15637
+ *
15638
+ * runner emits PipelineInferenceResult
15639
+ * ↓ (event bus)
15640
+ * pipeline-analytics subscriber
15641
+ * ↓ SORT tracker + zone engine + state analyzer + event emitter
15642
+ * → three DB collections (one per kind), one FS media tree, one
15643
+ * unified event emitter (FrameTracked + TrackStarted/Ended +
15644
+ * DetectionEvent on bus)
15645
+ *
15646
+ * Pure subscriber model. No `processFrame` cap method — the runner
15647
+ * already publishes the raw frame on the bus. The cap surface is
15648
+ * only QUERIES + per-device settings, bound on/off via
15649
+ * `device-manager.setWrapperActive`. `defaultActive: true` because
15650
+ * every camera with a detection pipeline wants its raw detections
15651
+ * refined; operators opt out per-device via BindingsTab when needed.
15652
+ *
15653
+ * Replaces the legacy `analysis-pipeline`, `analysis-data-persistence`
15654
+ * (per-device surface) and `track-trail` caps — see P11 cleanup.
15655
+ */
15656
+ var TrackStateSchema = zod.z.enum([
15657
+ "new",
15658
+ "entered",
15659
+ "left",
15660
+ "moving",
15661
+ "idle"
15662
+ ]);
15663
+ var EventKindSchema = zod.z.enum([
15664
+ "motion",
15665
+ "object",
15666
+ "audio"
15667
+ ]);
15668
+ /**
15669
+ * Spatial filter for `listTracks` — the rect + polygon variants of the shared
15670
+ * MaskShape vocabulary (see `mask-shape.ts`). Coordinates are NORMALIZED 0..1
15671
+ * of the camera frame (top-left origin), matching the drawing-plane editor.
15672
+ */
15673
+ var TrackZoneFilterSchema = zod.z.discriminatedUnion("kind", [MaskRectShapeSchema, MaskPolygonShapeSchema]);
15674
+ /** Closed icon vocabulary so clients render a known glyph per kind. */
15675
+ var EventKindIconSchema = zod.z.enum([
15676
+ "motion",
15677
+ "audio",
15678
+ "person",
15679
+ "vehicle",
15680
+ "animal",
15681
+ "door",
15682
+ "pir",
15683
+ "smoke",
15684
+ "water",
15685
+ "button",
15686
+ "package",
15687
+ "generic"
15688
+ ]);
15689
+ var EventKindCategorySchema = zod.z.enum([
15690
+ "motion",
15691
+ "audio",
15692
+ "detection",
15693
+ "sensor",
15694
+ "control",
15695
+ "custom",
15696
+ "package"
15697
+ ]);
15698
+ /** Taxonomy level — macro (timeline lane) vs sub (events-page leaf). */
15699
+ var EventKindLevelSchema = zod.z.enum(["macro", "sub"]);
15700
+ var EventKindDescriptorSchema = zod.z.object({
15701
+ /** Stable kind id (e.g. 'motion', 'vehicle', 'car', 'lock'). */
15702
+ kind: zod.z.string(),
15703
+ /** i18n key resolved on the UI side; `label` is the English fallback. */
15704
+ labelKey: zod.z.string(),
15705
+ /** English fallback label (kept for clients that don't translate). */
15706
+ label: zod.z.string(),
15707
+ /** Hex color for timeline/legend rendering. */
15708
+ color: zod.z.string(),
15709
+ /** Dictionary id → lucide component on the UI side. */
15710
+ iconId: zod.z.string(),
15711
+ /** Legacy closed-vocab glyph — fallback for `iconId`. */
15712
+ icon: EventKindIconSchema,
15713
+ category: EventKindCategorySchema,
15714
+ /** Macro parent for this kind ('car' → 'vehicle'); null for a macro. */
15715
+ parentKind: zod.z.string().nullable(),
15716
+ /** Derived from `parentKind`, explicit for the client tree. */
15717
+ level: EventKindLevelSchema,
15718
+ /** Which cap + device contributes this kind. For built-ins the camera
15719
+ * itself; for sensor kinds the LINKED source device. */
15720
+ source: zod.z.object({
15721
+ capName: zod.z.string(),
15722
+ deviceId: zod.z.number()
15723
+ })
15724
+ });
15725
+ /** One camera's event vocabulary, as returned by `listEventKindsBatch`. */
15726
+ var EventKindsForDeviceSchema = zod.z.object({
15727
+ deviceId: zod.z.number(),
15728
+ kinds: zod.z.array(EventKindDescriptorSchema).readonly()
15729
+ });
15730
+ var SensorEventSchema = zod.z.object({
15731
+ id: zod.z.string(),
15732
+ /** The CAMERA the event is attributed to (a sensor linked to N cameras
15733
+ * yields N rows, one per camera). */
15734
+ deviceId: zod.z.number(),
15735
+ /** The linked sensor device whose state changed. */
15736
+ sourceDeviceId: zod.z.number(),
15737
+ /** Event kind id — matches an `EventKindDescriptor.kind`. */
15738
+ kind: zod.z.string(),
15739
+ /** Snapshot of the sensor cap's runtime-state slice at the change. */
15740
+ value: zod.z.record(zod.z.string(), zod.z.unknown()).nullable(),
15741
+ timestamp: zod.z.number()
15742
+ });
15743
+ var TrackPositionSchema = zod.z.object({
15744
+ x: zod.z.number(),
15745
+ y: zod.z.number(),
15746
+ timestamp: zod.z.number(),
15747
+ bbox: BoundingBoxSchema
15748
+ });
15749
+ var TrackSnapshotSchema = zod.z.object({
15750
+ timestamp: zod.z.number(),
15751
+ position: TrackPositionSchema,
15752
+ /** MediaStore key; resolve via `getTrackMedia({ trackId })`. */
15753
+ mediaKey: zod.z.string()
15754
+ });
15755
+ /**
15756
+ * Normalized 0..1 trajectory envelope (min/max over every position bbox,
15757
+ * divided by the track's detection-frame dims), computed at persist time.
15758
+ * Absent when the frame dims were unknown when the track was persisted
15759
+ * (legacy rows / dims-less sources) and on active (in-RAM) tracks.
15760
+ */
15761
+ var TrackEnvelopeSchema = zod.z.object({
15762
+ minX: zod.z.number(),
15763
+ minY: zod.z.number(),
15764
+ maxX: zod.z.number(),
15765
+ maxY: zod.z.number()
15766
+ });
15767
+ /**
15768
+ * Row projection for track list queries. `full` (default) returns the
15769
+ * complete Track including the frame-rate `positions[]` history and the
15770
+ * `snapshots[]` references — megabytes across a page of tracks. `slim`
15771
+ * keeps every scalar the list surfaces actually render (ids, class(es),
15772
+ * label / audioLabels / importance enrichment, firstSeen/lastSeen, state,
15773
+ * zonesVisited, bestEventId, envelope, hasFace, hasEmbeddedFace, hasRider) and returns `positions` /
15774
+ * `snapshots` as EMPTY arrays — detail views re-fetch the full row via
15775
+ * `getTrack`. Mirrors the event-store `projection` convention
15776
+ * (`getObjectEvents` et al.).
15777
+ */
15778
+ var TrackProjectionSchema = zod.z.enum(["full", "slim"]);
15779
+ /**
15780
+ * One audio-classification label heard on the track's camera while the
15781
+ * track was alive, aggregated per label. An "episode" is one persisted
15782
+ * audio event (the confident-classification path: score ≥ the device's
15783
+ * `classificationMinScore`, class-change-or-heartbeat coalesced) — NOT
15784
+ * one 32 ms inference chunk, so counts stay human-scaled.
15785
+ */
15786
+ var TrackAudioLabelSchema = zod.z.object({
15787
+ label: zod.z.string(),
15788
+ /** Highest classification score observed across the label's episodes. */
15789
+ peakScore: zod.z.number(),
15790
+ /** Number of coalesced audio-event episodes carrying this label. */
15791
+ count: zod.z.number(),
15792
+ firstAt: zod.z.number(),
15793
+ lastAt: zod.z.number()
15794
+ });
15795
+ /**
15796
+ * How a track was produced. `pipeline` (default / absent) = the spatial
15797
+ * detection+tracking pipeline. Every OTHER value is a SYNTHETIC projection —
15798
+ * no positions, a single snapshot, and no bbox trajectory at all:
15799
+ *
15800
+ * - `sensor` — a linked sensor/control device state change.
15801
+ * - `audio` — an audio event on the camera itself that was anomalous for
15802
+ * THAT camera, loud, and heard while nothing visual was happening (D62).
15803
+ *
15804
+ * The spatial subsystems (tracker association, occupancy count, re-id /
15805
+ * embedding, resurrection) MUST skip every synthetic source. Test for that
15806
+ * with `isSpatialTrack`, which allow-lists `pipeline` — a `!== 'sensor'`
15807
+ * check silently readmits every source added after it was written.
15808
+ */
15809
+ var TrackSourceSchema = zod.z.enum([
15810
+ "pipeline",
15811
+ "sensor",
15812
+ "audio"
15813
+ ]);
15814
+ /**
15815
+ * Where a track sits in the RETRAIN lifecycle (D81).
15816
+ *
15817
+ * - `none` — never marked, or un-marked. Evictable.
15818
+ * - `staging` — the operator wants this track as training material and has not
15819
+ * finished with it. **This is the only state retention holds**: the track and
15820
+ * everything it owns (object events, crops, keyframes, CLIP vector) survive
15821
+ * the device's age window.
15822
+ * - `trained` — the retrain page has taken what it needed. The frames it chose
15823
+ * were COPIED into the retrain dataset at selection time, so the dataset no
15824
+ * longer depends on the track's media and the track becomes EVICTABLE again.
15825
+ * Terminal for the plain `markForTrain` toggle: returning it to `staging` is
15826
+ * a deliberate action of the retrain page, not a side effect of a checkbox.
15827
+ *
15828
+ * There is no `null`. The state is stored `TEXT NOT NULL DEFAULT 'none'` because
15829
+ * the store's filter language has only positive equality and `whereIn` — no
15830
+ * negation, no IS NULL — so a NULL would be unselectable by ANY predicate and
15831
+ * would make the entire pre-column history immortal in one deploy.
15832
+ */
15833
+ var RetrainStatusSchema = zod.z.enum([
15834
+ "none",
15835
+ "staging",
15836
+ "trained"
15837
+ ]);
15838
+ /**
15839
+ * Per-track OPERATOR flags — set by hand from the admin UI or the viewer, never
15840
+ * by the pipeline. Spread into `TrackSchema` and `KeyEventSchema` from one place
15841
+ * so the two surfaces cannot drift.
15842
+ *
15843
+ * **Absent ≠ false.** A track that has never been touched omits the field; an
15844
+ * explicitly un-flagged track carries `false`. Legacy rows written before the
15845
+ * columns existed read as absent, and a consumer that needs a boolean should say
15846
+ * `flag === true`, not `flag !== false`.
15847
+ *
15848
+ * `markForTrain` is the WIRE FACE of {@link RetrainStatusSchema}, not a column:
15849
+ * it is exactly `retrainStatus === 'staging'`, in both directions. Writing
15850
+ * `true` moves `none → staging`, writing `false` moves `staging → none`, and a
15851
+ * `trained` track reports `false` while refusing both writes. The boolean is
15852
+ * kept because three surfaces drive a toggle off it; anything that needs to tell
15853
+ * "never marked" from "already trained" must read `retrainStatus`.
15854
+ *
15855
+ * `debug` does NOT pin; it is attention, not durability.
15856
+ *
15857
+ * `favourited` IS a BOOLEAN pin (durability bit), not a retrain lifecycle.
15858
+ * A favourited track is skipped by retention the same way `staging` is, but
15859
+ * it does not enter `none|staging|trained` and has no staging budget.
15860
+ */
15861
+ var TrackFlagFields = {
15862
+ /** Operator marked this track as training material — i.e. `retrainStatus` is
15863
+ * `'staging'`. */
15864
+ markForTrain: zod.z.boolean().optional(),
15865
+ /** Operator marked this track for diagnostic attention. */
15866
+ debug: zod.z.boolean().optional(),
15867
+ /** Operator favourited this track. Pins it against pruning. */
15868
+ favourited: zod.z.boolean().optional()
15869
+ };
15870
+ /**
15871
+ * The lifecycle field itself, on the READ surfaces only (`Track`, `KeyEvent`).
15872
+ * Deliberately NOT part of {@link TrackFlagFields}: that group also builds the
15873
+ * write patch, and the status is not something the toggle sets — it is what the
15874
+ * toggle's boolean is derived from. Absent on an in-RAM track never touched;
15875
+ * always present on a persisted row (the column default materialises `'none'`).
15876
+ */
15877
+ var TrackRetrainFields = { retrainStatus: RetrainStatusSchema.optional() };
15878
+ /**
15879
+ * The write half: a PARTIAL patch. An omitted key is left untouched, so setting
15880
+ * one flag can never clear the other — the toggles are independent and are
15881
+ * driven from three surfaces that do not know about each other.
15882
+ */
15883
+ var TrackFlagsPatchSchema = zod.z.object(TrackFlagFields);
15884
+ /**
15885
+ * The resolved flag state after a write. Both fields are REQUIRED here (absent
15886
+ * collapses to `false`) so a caller can drive a toggle's checked state off the
15887
+ * mutation result without a re-fetch.
15888
+ */
15889
+ var TrackFlagsSchema = zod.z.object({
15890
+ trackId: zod.z.string(),
15891
+ markForTrain: zod.z.boolean(),
15892
+ debug: zod.z.boolean(),
15893
+ favourited: zod.z.boolean(),
15894
+ /** The lifecycle state the boolean was derived from. Required here (unlike on
15895
+ * a track row) because this shape is only ever produced by the write body,
15896
+ * which always knows it — and a surface that has just written needs to render
15897
+ * `trained` without a re-fetch. */
15898
+ retrainStatus: RetrainStatusSchema
15899
+ });
15900
+ /**
15901
+ * WHICH tier a label occupies. The slot a label lands in is DECLARED by the
15902
+ * step that produced it (`StepDefinition.labelTier`), never inferred from the
15903
+ * text or the step's name.
15904
+ *
15905
+ * - `1` — a SUB-CLASS: finer than the macro class, still a taxonomy token.
15906
+ * `animal-type` (`dog`, `bird`), `vehicle-type` (`van`), and the root
15907
+ * detector's own raw class when it is finer than the macro it maps to.
15908
+ * - `2` — an INSTANCE: the finest thing said about this subject.
15909
+ * `species` (`Turdus migratorius`), `identity` (`Alice`), `plate-text`.
15910
+ *
15911
+ * The macro class itself (`person`, `vehicle`, `animal`, `package`, `face`,
15912
+ * `plate`, `audio`) is NOT a tier — it is `className`, and a macro token
15913
+ * offered for either label slot is refused (2026-08-07 rule; the refusal is
15914
+ * logged as `label tier collapse refused`).
15915
+ */
15916
+ var LabelTierSchema = zod.z.union([zod.z.literal(1), zod.z.literal(2)]);
15917
+ /**
15918
+ * WHO decided a label, and when. Carried per tier so a value can be traced to
15919
+ * the step and model that produced it — which is what makes the write rule
15920
+ * arguable after the fact ("why is 592's label `dog` and not `Canis lupus`?")
15921
+ * and what lets a migrated, UNATTRIBUTED value be told apart from a real one.
15922
+ *
15923
+ * `stepId` is the pipeline step id (`animal-classifier`, `bird-classifier`,
15924
+ * `plate-ocr`, `face-embedding`, `object-detection`), or the sentinel
15925
+ * `migration:4g` for a value the 4g migration moved from the single-slot era —
15926
+ * that value has no provenance, and the write rule lets ANY properly-attributed
15927
+ * write of the same tier replace it regardless of score.
15928
+ */
15929
+ var LabelAttributionSchema = zod.z.object({
15930
+ stepId: zod.z.string(),
15931
+ modelId: zod.z.string().optional(),
15932
+ decidedAt: zod.z.number(),
15933
+ /**
15934
+ * The GALLERY id behind a recognised tier-2 label — a face-gallery
15935
+ * `Identity.id` or a plate-gallery `Vehicle.id` (both `randomUUID`).
15936
+ *
15937
+ * The text alone is a DISPLAY NAME, and a display name is renameable: a
15938
+ * notification rule authored on "Gianluca" stopped matching the moment the
15939
+ * operator fixed the spelling in the gallery, and nothing said so. The id is
15940
+ * the thing that does not move, so it is what a rule matches on
15941
+ * (`NcConditions.identities`) and the text is what a human is shown.
15942
+ *
15943
+ * Absent when the label names no gallery row — a plate the OCR read but no
15944
+ * vehicle claims, a sub-class, a species, any tier-1 value.
15945
+ */
15946
+ identityId: zod.z.string().optional()
15947
+ });
15948
+ /**
15949
+ * The TIERED label model (roadmap 4g), spread into `TrackSchema` and
15950
+ * `ObjectEventSchema` from ONE place so the two surfaces cannot drift — a
15951
+ * track and its events always answer the same question the same way.
15952
+ *
15953
+ * Two scalar columns, not an array: every consumer wants "the coarse one" or
15954
+ * "the fine one", and an array made both a scan. `label` is tier 1, `subLabel`
15955
+ * is tier 2, and each carries its own score + attribution.
15956
+ *
15957
+ * **Reading it.** What a human should be shown is `subLabel ?? label` — the
15958
+ * finest thing known. Before 4g the single `label` column held the finest
15959
+ * value, so a consumer that has not been updated reads the tier-1 slot and
15960
+ * shows nothing on a species-only row; that is why the migration puts every
15961
+ * pre-4g value in tier 2 (it cannot regress a display that reads the fallback)
15962
+ * and why the read surfaces were changed in the same train.
15963
+ *
15964
+ * **Writing it.** The slots are independent, which is the whole point: a
15965
+ * tier-1 write (`bird`) can never overwrite a tier-2 value (`Turdus
15966
+ * migratorius`), so fineness cannot regress by construction. Within a tier the
15967
+ * higher score wins. One rule, one implementation — see
15968
+ * `pipeline/label-tier.ts` in addon-post-analysis.
15969
+ */
15970
+ var TieredLabelFields = {
15971
+ /** Tier 1 — the sub-class. See {@link LabelTierSchema}. */
15972
+ label: zod.z.string().optional(),
15973
+ /** Confidence of the tier-1 value, as reported by the deciding step. */
15974
+ labelScore: zod.z.number().optional(),
15975
+ /** Provenance of the tier-1 value. See {@link LabelAttributionSchema}. */
15976
+ labelMeta: LabelAttributionSchema.optional(),
15977
+ /** Tier 2 — the instance. See {@link LabelTierSchema}. */
15978
+ subLabel: zod.z.string().optional(),
15979
+ /** Confidence of the tier-2 value, as reported by the deciding step. */
15980
+ subLabelScore: zod.z.number().optional(),
15981
+ /** Provenance of the tier-2 value. See {@link LabelAttributionSchema}. */
15982
+ subLabelMeta: LabelAttributionSchema.optional()
15983
+ };
15984
+ /** Per-camera slice of a training-export estimate. */
15985
+ var TrainingExportDeviceTotalsSchema = zod.z.object({
15986
+ deviceId: zod.z.number(),
15987
+ tracks: zod.z.number().int(),
15988
+ files: zod.z.number().int(),
15989
+ bytes: zod.z.number().int()
15990
+ });
15991
+ /**
15992
+ * What a training export WOULD contain. Computed from media index rows only —
15993
+ * no blob is read to produce this.
15994
+ */
15995
+ var TrainingExportSummarySchema = zod.z.object({
15996
+ generatedAt: zod.z.number(),
15997
+ trackCount: zod.z.number().int(),
15163
15998
  fileCount: zod.z.number().int(),
15164
15999
  byteCount: zod.z.number().int(),
15165
16000
  /** More marked tracks exist than a single pass carries. */
@@ -15633,1521 +16468,979 @@ var DeviceEventQueryInput = zod.z.object({
15633
16468
  since: zod.z.number().optional(),
15634
16469
  until: zod.z.number().optional(),
15635
16470
  limit: zod.z.number().int().min(1).max(MAX_EVENT_QUERY_LIMIT).default(DEFAULT_EVENT_QUERY_LIMIT),
15636
- /** `slim` drops heavy JSON fields (regions/bbox/zones) and carries an
15637
- * optional `mediaUrl` (populated by B5). `full` (default) keeps today's
15638
- * exact behaviour. Callers may omit this field — the store defaults to
15639
- * `full` when not provided. */
15640
- projection: zod.z.enum(["full", "slim"]).optional()
15641
- });
15642
- var ObjectEventQueryInput = DeviceEventQueryInput.extend({ classFilter: zod.z.string().optional() });
15643
- var RecentTracksQueryInput = zod.z.object({
15644
- /** Devices to merge. An empty array yields `{ tracks: [], nextCursor: null }`. */
15645
- deviceIds: zod.z.array(zod.z.number()),
15646
- /** Window lower bound on `lastSeen` (inclusive). */
15647
- since: zod.z.number().optional(),
15648
- /** Window upper bound on `lastSeen` (inclusive). */
15649
- until: zod.z.number().optional(),
15650
- /** Page size. Default 200, max 1000. */
15651
- limit: zod.z.number().int().min(1).max(1e3).default(200),
15652
- /** Opaque continuation cursor from a previous page's `nextCursor`.
15653
- * Encodes the (lastSeen, trackId) sort position — treat as opaque. */
15654
- cursor: zod.z.string().optional(),
15655
- /** See {@link TrackProjectionSchema}. Default `full`. */
15656
- projection: TrackProjectionSchema.optional(),
15657
- /** Include stationary-promoted rows (parked objects). Default false: the
15658
- * feed lists passages; parking records live on the stationary registry. */
15659
- includeStationary: zod.z.boolean().optional()
15660
- });
15661
- var RecentTracksPageSchema = zod.z.object({
15662
- /** Merged page, ordered by (`lastSeen` DESC, `trackId` DESC). */
15663
- tracks: zod.z.array(TrackSchema).readonly(),
15664
- /** Cursor for the next page, or null when this page is the last. */
15665
- nextCursor: zod.z.string().nullable()
15666
- });
15667
- var LIST_GROUPS_DEFAULT_LIMIT = 40;
15668
- var LIST_GROUPS_MAX_LIMIT = 100;
15669
- var AnalyticsGroupRecordSchema = zod.z.object({
15670
- id: zod.z.string(),
15671
- deviceId: zod.z.number().int(),
15672
- openedAt: zod.z.number().int(),
15673
- closedAt: zod.z.number().int(),
15674
- timestamp: zod.z.number().int(),
15675
- memberCount: zod.z.number().int(),
15676
- memberTrackIds: zod.z.array(zod.z.string()).readonly(),
15677
- className: zod.z.string(),
15678
- classes: zod.z.array(zod.z.string()).readonly(),
15679
- /** Relative event-media path, or null when the group has no picture yet. */
15680
- mediaUrl: zod.z.string().nullable(),
15681
- singleton: zod.z.boolean()
15682
- });
15683
- var AnalyticsGroupMemberSchema = zod.z.object({
15684
- trackId: zod.z.string(),
15685
- deviceId: zod.z.number().int(),
15686
- className: zod.z.string(),
15687
- firstSeen: zod.z.number().int(),
15688
- lastSeen: zod.z.number().int(),
15689
- mediaUrl: zod.z.string().nullable()
15690
- });
15691
- var AnalyticsGroupDetailSchema = AnalyticsGroupRecordSchema.extend({ members: zod.z.array(AnalyticsGroupMemberSchema).readonly() });
15692
- var ListGroupsQueryInput = zod.z.object({
15693
- /** Devices to merge. An empty array yields `{ groups: [], nextCursor: null }`. */
15694
- deviceIds: zod.z.array(zod.z.number()),
15695
- /** Window lower bound on `closedAt` (inclusive). */
15696
- since: zod.z.number().optional(),
15697
- /** Window upper bound on `openedAt` (inclusive). */
15698
- until: zod.z.number().optional(),
15699
- limit: zod.z.number().int().min(1).max(LIST_GROUPS_MAX_LIMIT).default(LIST_GROUPS_DEFAULT_LIMIT),
15700
- /** Opaque continuation cursor from a previous page's `nextCursor`. */
15701
- cursor: zod.z.string().optional()
15702
- });
15703
- var ListGroupsPageSchema = zod.z.object({
15704
- groups: zod.z.array(AnalyticsGroupRecordSchema).readonly(),
15705
- nextCursor: zod.z.string().nullable()
15706
- });
15707
- var KeyEventQueryInput = zod.z.object({
15708
- deviceId: zod.z.number(),
15709
- /** Window lower bound (track firstSeen ≥ since). */
15710
- since: zod.z.number(),
15711
- /** Window upper bound (track firstSeen ≤ until). */
15712
- until: zod.z.number(),
15713
- limit: zod.z.number().int().min(1).max(200).default(50),
15714
- /** Drop tracks scoring below this importance. */
15715
- minImportance: zod.z.number().min(0).max(1).optional(),
15716
- /** Restrict to a single class (e.g. 'person'). */
15717
- classFilter: zod.z.string().optional()
15718
- });
15719
- var KeyEventSchema = zod.z.object({
15720
- /** The representative event id (the track's best ObjectEvent, else its trackId). */
15721
- id: zod.z.string(),
15722
- trackId: zod.z.string(),
15723
- /** Track start time (firstSeen). */
15724
- timestamp: zod.z.number(),
15725
- className: zod.z.string(),
15726
- ...TieredLabelFields,
15727
- importance: zod.z.number(),
15728
- /** Highest-confidence ObjectEvent id for the track (empty when none). */
15729
- bestEventId: zod.z.string(),
15730
- /** Track lifetime in ms (lastSeen - firstSeen). */
15731
- windowMs: zod.z.number().optional(),
15732
- ...TrackFlagFields,
15733
- ...TrackRetrainFields
15734
- });
15735
- var TrackedDetectionSchema = zod.z.object({
15736
- trackId: zod.z.string(),
15737
- className: zod.z.string(),
15738
- confidence: zod.z.number(),
15739
- bbox: BoundingBoxSchema,
15740
- zones: zod.z.array(zod.z.string()).readonly(),
15741
- state: TrackStateSchema
15742
- });
15743
- var OverlayDetectionSchema = zod.z.looseObject({
15744
- id: zod.z.string(),
15745
- kind: zod.z.enum(["first-level", "detail"]),
15746
- macroClass: zod.z.string(),
15747
- score: zod.z.number(),
15748
- bbox: zod.z.object({
15749
- x: zod.z.number(),
15750
- y: zod.z.number(),
15751
- width: zod.z.number(),
15752
- height: zod.z.number()
15753
- }),
15754
- labels: zod.z.array(zod.z.looseObject({
15755
- label: zod.z.string(),
15756
- score: zod.z.number()
15757
- })).readonly(),
15758
- parentId: zod.z.string().optional()
15759
- });
15760
- var ScoredObjectEventSchema = ObjectEventSchema.extend({ score: zod.z.number() });
15761
- var SearchObjectEventsInput = zod.z.object({
15762
- text: zod.z.string(),
15763
- deviceId: zod.z.number().optional(),
15764
- since: zod.z.number().optional(),
15765
- until: zod.z.number().optional(),
15766
- classFilter: zod.z.string().optional(),
15767
- limit: zod.z.number().default(50),
15768
- minScore: zod.z.number().min(0).max(1).default(.2)
15769
- });
15770
- var TrackCascadeCountsSchema = zod.z.object({
15771
- /** Persisted track roots deleted (authoritative). */
15772
- tracks: zod.z.number().int(),
15773
- /** Object events removed with their tracks (best-effort; see note above). */
15774
- events: zod.z.number().int(),
15775
- /** Track/face/plate-owned media removed (best-effort). Never identity media. */
15776
- media: zod.z.number().int(),
15777
- /** Unassigned (non-enrolled) face reads removed (best-effort). */
15778
- faces: zod.z.number().int(),
15779
- /** Unassigned plate reads removed (best-effort; plate leg deferred to plate-intelligence). */
15780
- plates: zod.z.number().int(),
15781
- /** Per-track CLIP search vectors removed (best-effort). */
15782
- embeddings: zod.z.number().int(),
15783
- /** Group membership + group rows removed with their last member (best-effort). */
15784
- groups: zod.z.number().int()
15785
- });
15786
- /** Disk-wins reconcile: media rows whose blobs are gone, then empty tracks. */
15787
- var DiskReconcileCountsSchema = zod.z.object({
15788
- mediaDropped: zod.z.number().int(),
15789
- tracks: zod.z.number().int(),
15790
- events: zod.z.number().int()
15791
- });
15792
- /** Event-store footprint for one camera. */
15793
- var EventStoreDeviceFootprintSchema = zod.z.object({
15794
- deviceId: zod.z.number(),
15795
- /** Persisted event rows (motion + object + audio) for the camera. */
15796
- rows: zod.z.number().int(),
15797
- /** Event-owned media bytes on disk for the camera. */
15798
- bytes: zod.z.number().int()
15799
- });
15800
- /** Aggregate event-store footprint: global totals + per-camera breakdown. */
15801
- var EventStoreFootprintSchema = zod.z.object({
15802
- totalRows: zod.z.number().int(),
15803
- totalBytes: zod.z.number().int(),
15804
- devices: zod.z.array(EventStoreDeviceFootprintSchema).readonly()
15805
- });
15806
- /** Per-kind counts returned by the event-prune / device-delete mutations. */
15807
- var EventPruneCountsSchema = zod.z.object({
15808
- motion: zod.z.number().int(),
15809
- object: zod.z.number().int(),
15810
- audio: zod.z.number().int()
15811
- });
15812
- /**
15813
- * Re-embed stored tracks from their key frames.
15814
- *
15815
- * The reason this is an operator-callable method and not a migration script:
15816
- * every knob that decides what a vector MEANS — encoder model, crop margin,
15817
- * squaring — is only changeable if the existing vectors can be regenerated.
15818
- * Mixing feature spaces in one index makes cosine scores incomparable, and the
15819
- * symptom is a quality regression with no visible cause.
15820
- */
15821
- var RebuildObjectEmbeddingsInput = zod.z.object({
15822
- /** Restrict to one camera. Omit for the whole fleet. */
15823
- deviceId: zod.z.number().optional(),
15824
- since: zod.z.number().optional(),
15825
- until: zod.z.number().optional(),
15826
- /** Stop after this many tracks; the result reports whether more remain. */
15827
- maxTracks: zod.z.number().int().positive().optional(),
15828
- /**
15829
- * Run every embedding on THIS node instead of round-robining the fleet.
15830
- *
15831
- * Named `executeOnNodeId` and not `nodeId` on purpose: an inline `nodeId`
15832
- * field in cap args is read by `parent-unowned-call.ts` as a ROUTING PIN, so
15833
- * calling it that would pin the rebuild REQUEST itself to that node — the
15834
- * rebuild orchestration lives on the hub, and only the per-track step runs
15835
- * remotely. This field is data; the per-track pin is applied inside.
15836
- *
15837
- * Absent ⇒ round-robin over every online node whose runner can serve the
15838
- * pinned model.
15839
- */
15840
- executeOnNodeId: zod.z.string().optional(),
15841
- /**
15842
- * Milliseconds to wait between tracks; omit for the built-in default, `0` to
15843
- * run flat out.
15844
- *
15845
- * A rebuild is bulk maintenance on hub-main's single thread. Measured
15846
- * 2026-08-06, an unpaced pass held that thread busy 82.2 s out of 120 and
15847
- * pushed `nodes.topology` from 0.25 s to 26 s for 43 minutes. The value in
15848
- * force is logged at start and finish so a deliberately slow pass reads
15849
- * differently from a stalled one.
15850
- */
15851
- pacingMs: zod.z.number().int().nonnegative().optional()
15852
- });
15853
- /**
15854
- * Result of emptying the CLIP index.
15855
- *
15856
- * The clean slate before a policy change: a new crop margin or encoder model
15857
- * leaves two feature spaces in one index whose cosine scores are not
15858
- * comparable, so wiping and rebuilding is the only way to be sure every vector
15859
- * means the same thing.
15860
- */
15861
- var WipeObjectEmbeddingsResultSchema = zod.z.object({ deleted: zod.z.number() });
15862
- /**
15863
- * Acknowledgement that a rebuild STARTED.
15864
- *
15865
- * The pass costs ~1s per track — 45 minutes for a 2,600-track fleet — so it
15866
- * runs detached and this returns immediately. Waiting for it made the client
15867
- * time out while the work carried on server-side, which is the worst of both:
15868
- * no result and no way to know it was still going. Poll
15869
- * `getObjectEmbeddingRebuildStatus` for progress.
15870
- */
15871
- var RebuildObjectEmbeddingsResultSchema = zod.z.object({
15872
- started: zod.z.boolean(),
15873
- /** True when a pass was already running; the new request is ignored. */
15874
- alreadyRunning: zod.z.boolean()
15875
- });
15876
- var RebuildStatusSchema = zod.z.object({
15877
- running: zod.z.boolean(),
15878
- scanned: zod.z.number(),
15879
- rebuilt: zod.z.number(),
15880
- /** Tracks whose key frame is gone — nothing to re-embed from. */
15881
- missingKeyFrame: zod.z.number(),
15882
- /** Tracks with no usable detection box. */
15883
- missingBbox: zod.z.number(),
15884
- /**
15885
- * Tracks an executing node REFUSED rather than broke on — an unreadable key
15886
- * frame, a step that threw. Separate from `failed` because the remedy is
15887
- * different, and because a whole camera silently contributing zero vectors
15888
- * is the shape of failure a rebuild must never hide.
15889
- */
15890
- notRunnable: zod.z.number(),
15891
- /**
15892
- * The pass stopped because NO node could serve the pinned model.
15893
- *
15894
- * Distinct from `notRunnable` on purpose: that one says "this track was
15895
- * refused", this one says "the cluster cannot do this work at all" — every
15896
- * candidate node either lacks the `clip-embedding` step, lacks a build of the
15897
- * pinned model for its engine format, or dropped out. The remedy is a model /
15898
- * engine change, not a per-camera one. Non-zero here always comes with
15899
- * `complete: false`.
15900
- */
15901
- noCapableNode: zod.z.number(),
15902
- failed: zod.z.number(),
15903
- /** Set once a pass ends: true only when EVERYTHING was covered. */
15904
- complete: zod.z.boolean().nullable(),
15905
- startedAtMs: zod.z.number().nullable(),
15906
- finishedAtMs: zod.z.number().nullable(),
15907
- /** Present when the pass ended by throwing. */
15908
- error: zod.z.string().nullable()
15909
- });
15910
- var pipelineAnalyticsCapability = {
15911
- name: "pipeline-analytics",
15912
- scope: "device",
15913
- mode: "singleton",
15914
- kind: "wrapper",
15915
- defaultActive: true,
15916
- deviceTypes: [require_sleep.DeviceType.Camera],
15917
- exposesDeviceSettings: true,
15918
- methods: {
15919
- getActiveTracks: require_sleep.method(zod.z.object({ deviceId: zod.z.number() }), zod.z.array(TrackSchema).readonly()),
15920
- getTrack: require_sleep.method(zod.z.object({
15921
- deviceId: zod.z.number(),
15922
- trackId: zod.z.string()
15923
- }), TrackSchema.nullable()),
15924
- /** Historical completed tracks for a device. Queried from the
15925
- * persisted `pipeline-analytics:tracks` collection; active tracks
15926
- * still in RAM are not included. */
15927
- listTracks: require_sleep.method(zod.z.object({
15928
- deviceId: zod.z.number(),
15929
- since: zod.z.number().optional(),
15930
- until: zod.z.number().optional(),
15931
- limit: zod.z.number().optional(),
15932
- /** Spatial filter — only tracks whose trajectory intersects the zone
15933
- * (normalized 0..1 rect or polygon). SQL-prefiltered on the persisted
15934
- * envelope columns, then precisely tested per position. Tracks with
15935
- * an unknown envelope (no frame dims at persist time) always match. */
15936
- zone: TrackZoneFilterSchema.optional(),
15937
- /** See {@link TrackProjectionSchema}. Default `full` (backward
15938
- * compatible — omitting the field keeps today's exact behaviour). */
15939
- projection: TrackProjectionSchema.optional(),
15940
- /** Include stationary-promoted rows (parked objects handed to the
15941
- * stationary registry). Default false: the timeline lists passages,
15942
- * not parking records (operator decision, 2026-08-15). */
15943
- includeStationary: zod.z.boolean().optional()
15944
- }), zod.z.array(TrackSchema).readonly()),
15945
- /**
15946
- * Batched cluster-wide track listing — ONE call for the events page /
15947
- * reel first paint instead of a per-camera `listTracks` fan-out. Merges
15948
- * the persisted completed tracks of every requested device, sorted by
15949
- * `lastSeen` DESC with a stable (lastSeen, trackId) cursor. Per-device
15950
- * indexed pages (`idx_tracks_device_lastSeen`) are k-way merged
15951
- * provider-side; `projection: 'slim'` drops the heavy `positions[]` /
15952
- * `snapshots[]` JSON (returned as empty arrays). Active in-RAM tracks
15953
- * are not included (same contract as `listTracks`).
15954
- */
15955
- listRecentTracks: require_sleep.method(RecentTracksQueryInput, RecentTracksPageSchema),
15956
- /**
15957
- * Batched co-moving group listing — the Groups feed. Same merge/cursor
15958
- * contract as {@link listRecentTracks}. A group is a sealed partition of
15959
- * one session; `getGroup` is the detail with members.
15960
- */
15961
- listGroups: require_sleep.method(ListGroupsQueryInput, ListGroupsPageSchema),
15962
- getGroup: require_sleep.method(zod.z.object({
15963
- deviceId: zod.z.number(),
15964
- groupId: zod.z.string().min(1)
15965
- }), AnalyticsGroupDetailSchema.nullable()),
15966
- clearTracks: require_sleep.method(zod.z.object({ deviceId: zod.z.number() }), zod.z.void(), {
15967
- kind: "mutation",
15968
- auth: "admin"
15969
- }),
15970
- getMotionEvents: require_sleep.method(DeviceEventQueryInput, zod.z.array(MotionEventSchema).readonly()),
15971
- getObjectEvents: require_sleep.method(ObjectEventQueryInput, zod.z.array(ObjectEventSchema).readonly()),
15972
- getAudioEvents: require_sleep.method(DeviceEventQueryInput, zod.z.array(AudioEventSchema).readonly()),
15973
- /**
15974
- * Every event kind the device can produce: built-ins (motion + audio),
15975
- * detection classes actually observed for the device (from the track
15976
- * history), and sensor kinds contributed by LINKED devices (resolved via
15977
- * `device-manager.getLinkedDevices`, mapped through `EVENT_KIND_BY_CAP`).
15978
- */
15979
- listEventKinds: require_sleep.method(zod.z.object({ deviceId: zod.z.number() }), zod.z.array(EventKindDescriptorSchema).readonly()),
15980
- /**
15981
- * The same answer for many cameras in ONE call.
15982
- *
15983
- * `listEventKinds` is the slowest per-device query on the hub — measured
15984
- * at ~100 ms against 6-11 ms for its neighbours — because composing it
15985
- * costs a `getCameraStatus`, a `getLinkedDevices` and one `getBindings`
15986
- * per linked device. The viewer asks for it once per camera at first
15987
- * paint, so twelve cameras paid twelve of those round-trips on top of the
15988
- * per-camera cost.
15989
- *
15990
- * Batched, the camera statuses come from ONE `getCameraStatuses` instead
15991
- * of N, and the per-device composition runs concurrently.
15992
- *
15993
- * Per-device rather than pre-merged on purpose: a caller that renders one
15994
- * camera's lanes needs to know WHICH camera a kind came from, and merging
15995
- * is three lines the caller can do. `listEventKinds` stays for
15996
- * single-device callers.
15997
- */
15998
- listEventKindsBatch: require_sleep.method(zod.z.object({ deviceIds: zod.z.array(zod.z.number()).min(1).max(200) }), zod.z.array(EventKindsForDeviceSchema).readonly()),
15999
- /**
16000
- * Sensor-event history for a camera: state changes of LINKED sensor
16001
- * devices, attributed to the camera at ingest time (one row per linked
16002
- * camera). Mirrors `getAudioEvents` query semantics; `kinds` narrows to
16003
- * a kind subset.
16004
- */
16005
- getSensorEvents: require_sleep.method(zod.z.object({
16006
- deviceId: zod.z.number(),
16007
- since: zod.z.number().optional(),
16008
- until: zod.z.number().optional(),
16009
- kinds: zod.z.array(zod.z.string()).optional(),
16010
- limit: zod.z.number().int().min(1).max(MAX_EVENT_QUERY_LIMIT).default(DEFAULT_EVENT_QUERY_LIMIT)
16011
- }), zod.z.array(SensorEventSchema).readonly()),
16012
- /**
16013
- * Importance-ranked highlights for a device+window. Queries completed
16014
- * tracks by (deviceId, firstSeen ∈ [since,until]), scores each (or reuses
16015
- * the persisted score), filters by minImportance/classFilter, orders by
16016
- * importance desc, and returns up to `limit` compact key events mapped to
16017
- * each track's best event. Legacy tracks lacking a persisted score are
16018
- * scored on-read (no write). Degrades to `[]` on error.
16019
- */
16020
- getKeyEvents: require_sleep.method(KeyEventQueryInput, zod.z.array(KeyEventSchema).readonly()),
16021
- /** Server-side bucketed event counts for the 24-hour timeline.
16022
- * Returns one entry per non-empty bucket; empty buckets are omitted. */
16023
- getEventDensity: require_sleep.method(zod.z.object({
16024
- deviceId: zod.z.number(),
16025
- since: zod.z.number(),
16026
- until: zod.z.number(),
16027
- bucketMs: zod.z.number().int().positive()
16028
- }), zod.z.array(zod.z.object({
16029
- bucketStart: zod.z.number(),
16030
- motion: zod.z.number().int(),
16031
- object: zod.z.number().int(),
16032
- audio: zod.z.number().int()
16033
- })).readonly()),
16034
- /**
16035
- * @deprecated Prefer `pruneTracksBefore` — the track is the ROOT of the
16036
- * analytics model and retention must cascade from it (design §5.1). This
16037
- * event-only prune leaves orphaned tracks/faces/plates/embeddings behind.
16038
- * Retained as a compat shim for the Phase-B3 recorder orchestration caller,
16039
- * which prunes events to keep history aligned with available footage and
16040
- * reads the per-kind counts. Delete all events (motion + object + audio)
16041
- * for the given device older than `cutoffMs` (exclusive) + their thumbnails
16042
- * in lockstep; returns per-kind deleted counts.
16043
- */
16044
- pruneEventsBefore: require_sleep.method(zod.z.object({
16045
- deviceId: zod.z.number(),
16046
- cutoffMs: zod.z.number()
16047
- }), zod.z.object({
16048
- motion: zod.z.number().int(),
16049
- object: zod.z.number().int(),
16050
- audio: zod.z.number().int()
16051
- }), {
16052
- kind: "mutation",
16053
- auth: "admin"
16054
- }),
16055
- /**
16056
- * Track-centric retention entry point (design §5.1). Selects every
16057
- * persisted track for the device whose `lastSeen < cutoffMs` (paged) and
16058
- * runs the extensible whole-track deletion cascade (design §3): object
16059
- * events + their media, track/face/plate-owned media, unassigned face
16060
- * reads, per-track CLIP embeddings, then the track root LAST. ENROLLED
16061
- * (assigned) faces/plates and `ownerKind:'identity'` media are exempt —
16062
- * the durable matching gallery always persists. Fires the per-track
16063
- * live-state cleanup so a pruned track can't linger in dispatch/overlay
16064
- * state. Returns per-family deleted counts (`tracks` authoritative).
16065
- *
16066
- * Replaces `pruneEventsBefore` as the correct time-based retention prune.
16067
- */
16068
- pruneTracksBefore: require_sleep.method(zod.z.object({
16069
- deviceId: zod.z.number(),
16070
- cutoffMs: zod.z.number()
16071
- }), TrackCascadeCountsSchema, {
16072
- kind: "mutation",
16073
- auth: "admin"
16074
- }),
16075
- /**
16076
- * Operator "clean slate" for a device (design §5.3): prune EVERY track for
16077
- * the device via the same cascade as `pruneTracksBefore` with `cutoffMs =
16078
- * now`. One call per device — no client-side track enumeration. Enrolled
16079
- * gallery + identity media are exempt (design §4). Returns per-family
16080
- * deleted counts.
16081
- */
16082
- wipeAllAnalytics: require_sleep.method(zod.z.object({ deviceId: zod.z.number() }), TrackCascadeCountsSchema, {
16083
- kind: "mutation",
16084
- auth: "admin"
16085
- }),
16086
- /**
16087
- * Disk-wins reconcile for one camera. Drops media index rows whose blobs
16088
- * are gone, then cascades tracks (including favourited and staging) that
16089
- * have no remaining files. Enrolled identity/vehicle/scene media is never
16090
- * probed. Trackless motion/audio events with no remaining file are dropped,
16091
- * including snapshot-less rows.
16092
- */
16093
- reconcileFromDisk: require_sleep.method(zod.z.object({ deviceId: zod.z.number() }), DiskReconcileCountsSchema, {
16094
- kind: "mutation",
16095
- auth: "admin"
16096
- }),
16097
- /**
16098
- * Delete whole tracks (object events) by id for the given device,
16099
- * cascading their media in lockstep. Returns the number of tracks
16100
- * actually deleted plus the ids that could not be removed.
16101
- *
16102
- * Operator-driven from the DI Events page (batch delete). Routes through
16103
- * the same widened track-deletion cascade (design §5.2).
16104
- */
16105
- deleteTracks: require_sleep.method(zod.z.object({
16106
- deviceId: zod.z.number(),
16107
- trackIds: zod.z.array(zod.z.string()).min(1)
16108
- }), zod.z.object({
16109
- deleted: zod.z.number().int(),
16110
- failed: zod.z.array(zod.z.string()).readonly()
16111
- }), {
16112
- kind: "mutation",
16113
- auth: "admin"
16114
- }),
16115
- /**
16116
- * Set the per-track operator flags (`markForTrain`, `debug`, `favourited`) on ONE track.
16117
- * The patch is PARTIAL — an omitted key is left untouched — because the
16118
- * three surfaces that write it (admin Events grid, viewer track detail,
16119
- * viewer cluster detail) each own one toggle and must not clobber the other.
16120
- *
16121
- * Writes the track ROW: `markForTrain`/`debug` are per-TRACK state, so they
16122
- * live where `label` and `importance` live, not in any per-device settings
16123
- * store. Updates the in-RAM active track too, so a flag set on a live track
16124
- * survives its expiry-time persist.
16125
- *
16126
- * `auth: 'protected'` (the default), NOT `admin`: the viewer is an
16127
- * authenticated non-admin surface and two of the three call sites are
16128
- * there. The note that used to sit here said to revisit this the day a flag
16129
- * gained an effect that costs storage, and D81 is that day — `markForTrain`
16130
- * now pins. It STAYS protected, and the reason is that the alternative
16131
- * makes the feature pointless: marking a track is something you do while
16132
- * looking at it, on the surface you were already looking at it on, and that
16133
- * surface is the viewer. What the storage cost gets instead is a BOUND — a
16134
- * per-device pin budget enforced in the body, refusing a new pin past the
16135
- * limit while always allowing un-marking. `deleteTracks` next door is still
16136
- * admin, because destroying evidence and preserving it are not symmetric.
16137
- *
16138
- * `markForTrain` writes the retrain LIFECYCLE, not a boolean column: `true`
16139
- * is `none → staging`, `false` is `staging → none`. A track already
16140
- * `trained` refuses BOTH — its frames are copies inside the retrain dataset
16141
- * and re-staging it from a generic toggle is how the same material gets
16142
- * annotated twice under two ground truths. Returning a trained track to
16143
- * staging is a deliberate action of the retrain page, which is also the only
16144
- * thing that produces `trained` in the first place.
16145
- *
16146
- * Returns the RESOLVED state of both flags (absent → `false`) plus the
16147
- * `retrainStatus` they were derived from, so a caller can drive its toggle
16148
- * — and render a `trained` badge — without a re-fetch. Rejects an unknown
16149
- * track, a new staging mark on a device already holding its full budget, and
16150
- * any `markForTrain` write against a trained track.
16151
- */
16152
- setTrackFlags: require_sleep.method(zod.z.object({
16153
- /** Log/audit scope only — the trackId is globally unique on its own. */
16154
- deviceId: zod.z.number(),
16155
- trackId: zod.z.string(),
16156
- flags: TrackFlagsPatchSchema
16157
- }), TrackFlagsSchema, { kind: "mutation" }),
16158
- /**
16159
- * Durable event-store footprint for the management UI: event rows
16160
- * (motion + object + audio) counted per camera + total, plus the
16161
- * event-owned media bytes on disk per camera + total. Stat/count-based,
16162
- * computed on demand.
16163
- */
16164
- getEventStoreFootprint: require_sleep.method(zod.z.object({}), EventStoreFootprintSchema, {
16165
- kind: "query",
16166
- auth: "admin"
16167
- }),
16168
- /**
16169
- * Cluster-wide prune of events older than `olderThanMs` (exclusive) across
16170
- * every camera, deleting each event's media in lockstep. Logged to the
16171
- * events ops-log with `reason` (default `'retention'`). Returns the summed
16172
- * per-kind deleted counts.
16173
- */
16174
- pruneEvents: require_sleep.method(zod.z.object({
16175
- olderThanMs: zod.z.number(),
16176
- reason: OpsLogReasonSchema.optional()
16177
- }), EventPruneCountsSchema, {
16178
- kind: "mutation",
16179
- auth: "admin"
16180
- }),
16181
- /**
16182
- * Manually delete EVERY event (motion + object + audio) for one camera and
16183
- * its event-owned media in lockstep. Logged to the events ops-log as
16184
- * `op:'manual-delete', reason:'manual'`. Destructive — the admin UI guards
16185
- * it behind a confirm.
16186
- */
16187
- deleteDeviceEvents: require_sleep.method(zod.z.object({ deviceId: zod.z.number() }), EventPruneCountsSchema, {
16188
- kind: "mutation",
16189
- auth: "admin"
16190
- }),
16191
- /** The events ops-log rows (newest-first), optionally scoped to one camera.
16192
- * Backed by a declared pipeline-analytics SQLite collection. */
16193
- /** Internal migration-participant lease. It drains active MediaStore
16194
- * writes and refuses new ones without changing analytics bindings. */
16195
- pauseForStorageMigration: require_sleep.method(StorageMigrationLeaseInputSchema, zod.z.object({ paused: zod.z.literal(true) }), {
16196
- kind: "mutation",
16197
- auth: "admin"
16198
- }),
16199
- resumeForStorageMigration: require_sleep.method(StorageMigrationLeaseInputSchema, zod.z.object({ resumed: zod.z.literal(true) }), {
16200
- kind: "mutation",
16201
- auth: "admin"
16202
- }),
16203
- /** Drops cached location roots after the storage coordinator repoints a
16204
- * default so future event-media writes use the new root. */
16205
- refreshStorageLocationsForMigration: require_sleep.method(StorageMigrationLeaseInputSchema, zod.z.object({ refreshed: zod.z.literal(true) }), {
16206
- kind: "mutation",
16207
- auth: "admin"
16208
- }),
16209
- startStorageMigrationMove: require_sleep.method(StorageMigrationMediaMoveInputSchema, zod.z.object({ jobId: zod.z.string() }), {
16210
- kind: "mutation",
16211
- auth: "admin"
16212
- }),
16213
- getStorageMigrationMoveStatus: require_sleep.method(zod.z.object({ jobId: zod.z.string() }), RelocateJobSchema.nullable(), { auth: "admin" }),
16214
- cancelStorageMigrationMove: require_sleep.method(zod.z.object({ jobId: zod.z.string() }), zod.z.object({ cancelled: zod.z.boolean() }), {
16215
- kind: "mutation",
16216
- auth: "admin"
16217
- }),
16218
- /**
16219
- * Moves event media between locations — the OPERATOR's mover, without the
16220
- * coordinator's lease. Twin of `recording.relocateFootage`: the same
16221
- * engine the lease-gated coordinated migration uses
16222
- * (`startStorageMigrationMove`), armable in the background and WITHOUT
16223
- * pausing anything. Exists because `eventMedia` was the only storage
16224
- * class whose only move path went through the recorder's global pause.
16225
- */
16226
- relocateMedia: require_sleep.method(RelocateMediaInputSchema, zod.z.object({ jobId: zod.z.string() }), {
16227
- kind: "mutation",
16228
- auth: "admin"
16229
- }),
16230
- /** Every relocate job this addon knows about, newest first (in RAM: the
16231
- * move is resumable, so a lost list costs nothing but the display). */
16232
- listRelocateMediaJobs: require_sleep.method(zod.z.object({}), zod.z.array(RelocateJobSchema).readonly(), {
16233
- kind: "query",
16234
- auth: "admin"
16235
- }),
16236
- /** Cancel a running or queued relocate job. */
16237
- cancelRelocateMedia: require_sleep.method(zod.z.object({ jobId: zod.z.string() }), zod.z.object({ cancelled: zod.z.boolean() }), {
16238
- kind: "mutation",
16239
- auth: "admin"
16240
- }),
16241
- listOpsLog: require_sleep.method(OpsLogQueryInputSchema, zod.z.array(OpsLogEntrySchema).readonly(), {
16242
- kind: "query",
16243
- auth: "admin"
16244
- }),
16245
- /**
16246
- * The CHEAP QUESTION, asked before any media moves: how big is the dataset
16247
- * the marked (`markForTrain`) tracks would produce?
16248
- *
16249
- * Answered from media INDEX rows only — key, kind, size, timestamp — so it
16250
- * costs ~2 KB of reads per track and no blob reads at all. The measured harm
16251
- * behind D56 was a bulk pass that read and base64'd every blob a track owned
16252
- * before deciding anything, taking hub-main to 82 s busy out of 120; an
16253
- * export is that same I/O shape, so it inherits the same discipline: know
16254
- * the size, then decide.
16255
- *
16256
- * `truncated` reports that more marked tracks exist than one pass carries.
16257
- * Empty `deviceIds` ⇒ every device that has marked tracks.
16258
- */
16259
- getTrainingExportSummary: require_sleep.method(zod.z.object({ deviceIds: zod.z.array(zod.z.number()).optional() }), TrainingExportSummarySchema, {
16260
- kind: "query",
16261
- auth: "admin"
16262
- }),
16263
- /**
16264
- * Where to download the dataset archive.
16265
- *
16266
- * The BYTES do not come back through this cap — they come from the returned
16267
- * data-plane URL, which streams a tar built entry by entry. A multi-gigabyte
16268
- * archive base64'd through a unary RPC envelope would be held whole in
16269
- * memory twice on a hub this repo has already OOM'd once (D9/D18 are the
16270
- * same lesson about frames). `getDownloadUrl` on `recordingExport` is the
16271
- * precedent, and this follows it deliberately.
16272
- *
16273
- * The archive contains a `manifest.json` FIRST, then the stored media
16274
- * VERBATIM under `tracks/<deviceId>/<trackId>/…`. No crop is derived and no
16275
- * model is run: a training set's pixels must be the pixels the pipeline saw.
16276
- */
16277
- getTrainingExportUrl: require_sleep.method(zod.z.object({ deviceIds: zod.z.array(zod.z.number()).optional() }), zod.z.object({ url: zod.z.string() }), {
16278
- kind: "query",
16279
- auth: "admin"
16280
- }),
16281
- /**
16282
- * The staging worklist for one camera, or for every camera that has one.
16283
- *
16284
- * Fetched ON DEMAND, over the staging set only — the page never scans
16285
- * history, because making the working set small is the entire purpose of
16286
- * the mark. Each row carries how many frames the dataset already holds from
16287
- * the track and how many subjects were annotated on them, so
16288
- * `frameCount: 0` reads as "still to work" without a second call per track.
16289
- *
16290
- * `auth: 'admin'`, unlike the viewer-level mark itself: marking a track is
16291
- * curation you do while looking at it, but building the training set the
16292
- * fleet's models are fine-tuned on is not.
16293
- */
16294
- listRetrainStaging: require_sleep.method(zod.z.object({
16295
- /** Empty ⇒ every camera that has staging tracks. A LIST, not a single
16296
- * `deviceId`, deliberately: `deviceId` would make this device-bound and
16297
- * route it at one camera's owner, and "every camera" would stop being
16298
- * expressible at all. */
16299
- deviceIds: zod.z.array(zod.z.number()).optional(),
16300
- limit: zod.z.number().int().min(1).max(500).optional()
16301
- }), zod.z.array(RetrainTrackSchema).readonly(), {
16302
- kind: "query",
16303
- auth: "admin"
16304
- }),
16305
- /**
16306
- * What a track can contribute, and what it already has.
16307
- *
16308
- * `candidates` are the track's whole, unannotated frames — index rows only,
16309
- * so this is cheap. `copies` are the frames already inside the dataset, and
16310
- * a candidate whose copy exists is marked `copied: true`: selecting it again
16311
- * is free and CANNOT fail, whatever became of the original.
16312
- *
16313
- * A crop, a thumbnail and `fullFrameBoxed` are never candidates. The last
16314
- * one matters most: it has the model's own rectangle burned into the pixels,
16315
- * and a detector trained on it learns to find a green line.
16316
- */
16317
- listRetrainFrames: require_sleep.method(zod.z.object({ trackId: zod.z.string() }), RetrainFrameListSchema, {
16318
- kind: "query",
16319
- auth: "admin"
16320
- }),
16321
- /**
16322
- * COPY-ON-SELECT — the write that makes `trained` safe to evict.
16323
- *
16324
- * Selecting a frame copies its bytes into retrain storage immediately: not
16325
- * a reference, not a lease. Once the copy exists the dataset no longer
16326
- * depends on the track's media, which is exactly what lets D81 hand a
16327
- * `trained` track back to retention.
16328
- *
16329
- * The order inside is load-bearing and is pinned by a test: an EXISTING
16330
- * copy is returned without touching the source, so an original that
16331
- * evaporated blocks the selection of THAT ORIGINAL and never the copy
16332
- * already taken. Every refusal comes back named — a dropped selection is
16333
- * never silent, on the wire or in the log.
16334
- */
16335
- selectRetrainFrames: require_sleep.method(zod.z.object({
16336
- deviceId: zod.z.number(),
16337
- trackId: zod.z.string(),
16338
- mediaKeys: zod.z.array(zod.z.string()).min(1)
16339
- }), RetrainFrameSelectionSchema, {
16340
- kind: "mutation",
16341
- auth: "admin"
16342
- }),
16343
- /** Un-select a frame: its annotations go first, then the copy and its blob.
16344
- * Deliberately destructive and deliberately explicit — it is the only way
16345
- * a frame leaves the dataset before export. */
16346
- deselectRetrainFrame: require_sleep.method(zod.z.object({
16347
- deviceId: zod.z.number(),
16348
- trackId: zod.z.string(),
16349
- frameId: zod.z.string()
16350
- }), zod.z.object({
16351
- removed: zod.z.boolean(),
16352
- removedAnnotations: zod.z.number().int()
16353
- }), {
16354
- kind: "mutation",
16355
- auth: "admin"
16356
- }),
16357
- /**
16358
- * The pixels of ONE copied frame, base64.
16359
- *
16360
- * Through the cap rather than a data plane because it is genuinely one
16361
- * frame at a time, on demand, at human speed — the shape D9/D18 permit
16362
- * (what they forbid is frames crossing a boundary at frame RATE). The
16363
- * annotation canvas needs the image and its exact dimensions in the same
16364
- * answer: a canvas that places a normalised box against a size it guessed
16365
- * draws every box in the wrong place.
16366
- */
16367
- getRetrainFrameImage: require_sleep.method(zod.z.object({ frameId: zod.z.string() }), zod.z.object({
16368
- base64: zod.z.string(),
16369
- width: zod.z.number().int(),
16370
- height: zod.z.number().int()
16371
- }), {
16372
- kind: "query",
16373
- auth: "admin"
16374
- }),
16375
- /**
16376
- * Ask the pipeline what it sees, as a PROPOSAL.
16377
- *
16378
- * Runs through `pipelineRunner.runStatelessStep` on the COPIED frame, and
16379
- * every box comes back as a draft with `source: 'assist'` plus the model and
16380
- * score that produced it. The operator confirms, edits, adds and deletes;
16381
- * nothing is stored until `saveRetrainAnnotations`.
16382
- *
16383
- * For packages the request is `rfdetr-package` on the ZONE CROP at 0.35 —
16384
- * never the whole frame, where a package detector at that threshold proposes
16385
- * furniture. A package request with no zone is REFUSED rather than widened,
16386
- * because the silent widening would look like a bad model for as long as
16387
- * nobody checked which rectangle it ran on.
16388
- */
16389
- proposeRetrainAnnotations: require_sleep.method(zod.z.object({
16390
- deviceId: zod.z.number(),
16391
- trackId: zod.z.string(),
16392
- frameId: zod.z.string(),
16393
- subject: RetrainAssistSubjectSchema,
16394
- /** Which node runs it. Absent ⇒ wherever an unowned call lands. */
16395
- nodeId: zod.z.string().optional()
16396
- }), RetrainAssistResultSchema, {
16397
- kind: "mutation",
16398
- auth: "admin"
16399
- }),
16400
- /** Every annotation on a track, oldest first. */
16401
- listRetrainAnnotations: require_sleep.method(zod.z.object({ trackId: zod.z.string() }), zod.z.array(RetrainAnnotationSchema).readonly(), {
16402
- kind: "query",
16403
- auth: "admin"
16404
- }),
16405
- /**
16406
- * Replace EVERY annotation on one frame with the supplied set.
16407
- *
16408
- * Whole-frame replacement, not per-box upsert: the unit of ground truth is
16409
- * the frame, and "the operator deleted a box" must be the same durable
16410
- * outcome as "the operator never drew it". A per-box patch would let a frame
16411
- * keep a box the operator removed on a surface that only knew about the
16412
- * boxes it sent.
16413
- *
16414
- * Refuses a macro class typed into `label` or `subLabel` — the tiers are
16415
- * separate and the guard is at the WRITE, because a mixed taxonomy cannot
16416
- * be un-mixed by reading it.
16417
- */
16418
- saveRetrainAnnotations: require_sleep.method(zod.z.object({
16419
- deviceId: zod.z.number(),
16420
- trackId: zod.z.string(),
16421
- frameId: zod.z.string(),
16422
- annotations: zod.z.array(RetrainAnnotationDraftSchema)
16423
- }), zod.z.array(RetrainAnnotationSchema).readonly(), {
16424
- kind: "mutation",
16425
- auth: "admin"
16426
- }),
16427
- /**
16428
- * Finish with a track: `staging → trained`. **The only writer of that
16429
- * state** — D81 shipped the column with it deliberately unreachable.
16430
- *
16431
- * Refuses a track the dataset holds no copies from. `trained` un-pins the
16432
- * track's media, so completing without a copy is a delete order for material
16433
- * nothing ever extracted anything from; that refusal IS the safety argument
16434
- * of D81, expressed as a precondition.
16435
- */
16436
- completeRetrainTrack: require_sleep.method(zod.z.object({
16437
- deviceId: zod.z.number(),
16438
- trackId: zod.z.string()
16439
- }), RetrainTransitionResultSchema, {
16440
- kind: "mutation",
16441
- auth: "admin"
16442
- }),
16443
- /**
16444
- * The deliberate return: `trained → staging`, for the rare case.
16445
- *
16446
- * The generic `setTrackFlags` toggle refuses this in both directions by
16447
- * design (D81) — re-staging from a checkbox is how the same material gets
16448
- * annotated twice under two ground truths. Doing it here means the operator
16449
- * is looking at the annotations that already exist while they decide, and
16450
- * those annotations are LEFT ALONE: "put this back" must not be a
16451
- * destructive act wearing a navigational name.
16452
- */
16453
- restageRetrainTrack: require_sleep.method(zod.z.object({
16454
- deviceId: zod.z.number(),
16455
- trackId: zod.z.string()
16456
- }), RetrainTransitionResultSchema, {
16457
- kind: "mutation",
16458
- auth: "admin"
16459
- }),
16460
- /**
16461
- * Where to download the ANNOTATED dataset.
16462
- *
16463
- * The sibling of `getTrainingExportUrl` and deliberately not the same
16464
- * archive: that one streams a marked track's stored media verbatim, this one
16465
- * streams the retrain COPIES plus an `annotations.json` carrying, for every
16466
- * subject, the canonical full-frame box AND the geometry derived for each
16467
- * model shape (letterboxed root / zone-cropped package / subject-cropped
16468
- * classifier). Derived at export, never stored — one box in, three shapes
16469
- * out, so two crops of the same subject can never end up in one feature
16470
- * space (D52).
16471
- */
16472
- getRetrainExportUrl: require_sleep.method(zod.z.object({ deviceIds: zod.z.array(zod.z.number()).optional() }), zod.z.object({ url: zod.z.string() }), {
16473
- kind: "query",
16474
- auth: "admin"
16475
- }),
16476
- getEventMedia: require_sleep.method(zod.z.object({
16477
- eventId: zod.z.string(),
16478
- kind: MediaFileKindEnum.optional(),
16479
- deviceId: zod.z.number()
16480
- }), zod.z.array(MediaFileSchema).readonly()),
16481
- /** All media rows owned by a track. `kinds` narrows to a kind subset so a
16482
- * client can fetch the SMALL display variants on open and pull the
16483
- * multi-MB native variants only on demand (mirrors `getEventMedia.kind`).
16484
- * Absent ⇒ every kind (back-compat). */
16485
- getTrackMedia: require_sleep.method(zod.z.object({
16486
- trackId: zod.z.string(),
16487
- kinds: zod.z.array(MediaFileKindEnum).optional(),
16488
- deviceId: zod.z.number()
16489
- }), zod.z.array(MediaFileSchema).readonly()),
16490
- /**
16491
- * What media a track HAS, without any of it.
16492
- *
16493
- * The detail view needs the shape of a track's media to build its strip —
16494
- * which kinds exist, in what order, at what size — and then wants each tile
16495
- * fetched as an image, not as base64 inside this response. Measured: the
16496
- * full `getTrackMedia` is 5.3-7.7 MB and blocks the view; this manifest is
16497
- * ~2 KB.
16498
- *
16499
- * It also restores a fact a `kinds` filter destroys: filtering
16500
- * `getTrackMedia` drops whole ROWS, taking `kind` and `sizeBytes` with
16501
- * them, so a client that fetched only the small variants could no longer
16502
- * tell a full-resolution variant existed — and the affordance that opens it
16503
- * would silently disappear.
16504
- */
16505
- listTrackMedia: require_sleep.method(zod.z.object({
16506
- trackId: zod.z.string(),
16507
- deviceId: zod.z.number()
16508
- }), zod.z.array(MediaFileInfoSchema).readonly()),
16509
- /**
16510
- * Search object events by text query using CLIP cosine similarity.
16511
- * Encodes `text` via the `embedding-encoder` cap, queries the
16512
- * `ObjectEmbeddingStore` with optional prefilters, ranks all matching
16513
- * embeddings by cosine similarity, and joins winners to their
16514
- * ObjectEvents by trackId. Returns up to `limit` events scored ≥
16515
- * `minScore`, sorted descending by score.
16516
- */
16517
- searchObjectEvents: require_sleep.method(SearchObjectEventsInput, zod.z.array(ScoredObjectEventSchema).readonly()),
16518
- wipeObjectEmbeddings: require_sleep.method(zod.z.object({}), WipeObjectEmbeddingsResultSchema, {
16519
- kind: "mutation",
16520
- auth: "admin"
16521
- }),
16522
- rebuildObjectEmbeddings: require_sleep.method(RebuildObjectEmbeddingsInput, RebuildObjectEmbeddingsResultSchema, {
16523
- kind: "mutation",
16524
- auth: "admin"
16525
- }),
16526
- getObjectEmbeddingRebuildStatus: require_sleep.method(zod.z.object({}), RebuildStatusSchema)
16527
- },
16528
- events: {
16529
- /**
16530
- * Enriched frame emitted after refinement — the live-overlay source of
16531
- * truth (two-plane re-injection). Carries the frame's detections in the
16532
- * `ObjectDetection` wire shape: first-level roots (with track info +
16533
- * enrichment labels) plus synthesized `kind:'detail'` face/plate entries
16534
- * re-projected from per-track detail state, so stream overlays render
16535
- * boxes + recognized names without querying full Track state.
16536
- */
16537
- onFrameTracked: { data: zod.z.object({
16538
- deviceId: zod.z.number(),
16539
- timestamp: zod.z.number(),
16540
- frameWidth: zod.z.number(),
16541
- frameHeight: zod.z.number(),
16542
- detections: zod.z.array(OverlayDetectionSchema).readonly()
16543
- }) },
16544
- /** Track entered active state (first-seen). */
16545
- onTrackStarted: { data: zod.z.object({
16546
- deviceId: zod.z.number(),
16547
- trackId: zod.z.string(),
16548
- className: zod.z.string()
16549
- }) },
16550
- /** Track expired (TTL reached after last detection). */
16551
- onTrackEnded: { data: zod.z.object({
16552
- deviceId: zod.z.number(),
16553
- trackId: zod.z.string(),
16554
- className: zod.z.string(),
16555
- durationMs: zod.z.number()
16556
- }) },
16557
- /** Canonical "something happened at device X" event, per-kind. */
16558
- onDetectionEvent: { data: zod.z.object({
16559
- deviceId: zod.z.number(),
16560
- kind: EventKindSchema,
16561
- eventId: zod.z.string(),
16562
- timestamp: zod.z.number()
16563
- }) }
16564
- }
16565
- };
16566
- //#endregion
16567
- //#region src/capabilities/pipeline-executor.cap.ts
16568
- /**
16569
- * Reference to the frame's retained NATIVE surface + the parent crop's placement
16570
- * within the frame, so the executor can re-cut a leaf child ROI at native
16571
- * resolution on the detail plane. See the `runPipeline` `nativeCropRef` field.
16572
- */
16573
- var NativeCropRefSchema = zod.z.object({
16574
- /** Handle keying the retained native surface (node-pinned to its owner). */
16575
- handle: require_sleep.FrameHandleSchema,
16576
- /** The parent crop's padded/clamped rectangle in FRAME-space pixels. */
16577
- cropFrameSpace: zod.z.object({
16578
- x: zod.z.number(),
16579
- y: zod.z.number(),
16580
- w: zod.z.number(),
16581
- h: zod.z.number()
16582
- })
16583
- });
16584
- zod.z.object({
16585
- crop: zod.z.object({
16586
- left: zod.z.number(),
16587
- top: zod.z.number(),
16588
- width: zod.z.number().positive(),
16589
- height: zod.z.number().positive()
16590
- }).optional(),
16591
- content: zod.z.object({
16592
- width: zod.z.number().int().positive(),
16593
- height: zod.z.number().int().positive()
16594
- }),
16595
- fit: zod.z.enum(["stretch", "contain"]),
16596
- format: zod.z.enum([
16597
- "rgb",
16598
- "gray",
16599
- "jpeg"
16600
- ])
16601
- });
16602
- /**
16603
- * Process-local frame identity. It is serializable so it can ride an in-process
16604
- * capability call, but `registryId` deliberately prevents resolution in any
16605
- * other process or execution group.
16606
- */
16607
- var FrameRefSchema = zod.z.object({
16608
- registryId: zod.z.string().min(1),
16609
- id: zod.z.string().min(1),
16610
- width: zod.z.number().int().positive(),
16611
- height: zod.z.number().int().positive(),
16612
- format: zod.z.enum(["rgb", "gray"]),
16613
- timestamp: zod.z.number(),
16614
- capturedAt: zod.z.number().optional()
16615
- });
16616
- var ModelFormatSchema$1 = zod.z.enum([
16617
- "onnx",
16618
- "coreml",
16619
- "openvino",
16620
- "tflite",
16621
- "pt",
16622
- "gguf"
16623
- ]);
16624
- var PipelineSlotSchema = zod.z.enum([
16625
- "detector",
16626
- "cropper",
16627
- "classifier",
16628
- "refiner",
16629
- "audio-classifier"
16630
- ]);
16631
- var PipelineEngineChoiceSchema = zod.z.object({
16632
- runtime: zod.z.enum(["node", "python"]),
16633
- backend: zod.z.string(),
16634
- format: ModelFormatSchema$1,
16635
- device: zod.z.string().optional()
16636
- });
16637
- var EngineDeviceInfoSchema = zod.z.object({
16638
- id: zod.z.string(),
16639
- label: zod.z.string(),
16640
- description: zod.z.string().optional()
16471
+ /** `slim` drops heavy JSON fields (regions/bbox/zones) and carries an
16472
+ * optional `mediaUrl` (populated by B5). `full` (default) keeps today's
16473
+ * exact behaviour. Callers may omit this field — the store defaults to
16474
+ * `full` when not provided. */
16475
+ projection: zod.z.enum(["full", "slim"]).optional()
16641
16476
  });
16642
- var AvailableEngineSchema = zod.z.object({
16643
- engine: PipelineEngineChoiceSchema,
16644
- devices: zod.z.array(EngineDeviceInfoSchema).readonly(),
16645
- defaultDevice: zod.z.string()
16477
+ var ObjectEventQueryInput = DeviceEventQueryInput.extend({ classFilter: zod.z.string().optional() });
16478
+ var RecentTracksQueryInput = zod.z.object({
16479
+ /** Devices to merge. An empty array yields `{ tracks: [], nextCursor: null }`. */
16480
+ deviceIds: zod.z.array(zod.z.number()),
16481
+ /** Window lower bound on `lastSeen` (inclusive). */
16482
+ since: zod.z.number().optional(),
16483
+ /** Window upper bound on `lastSeen` (inclusive). */
16484
+ until: zod.z.number().optional(),
16485
+ /** Page size. Default 200, max 1000. */
16486
+ limit: zod.z.number().int().min(1).max(1e3).default(200),
16487
+ /** Opaque continuation cursor from a previous page's `nextCursor`.
16488
+ * Encodes the (lastSeen, trackId) sort position — treat as opaque. */
16489
+ cursor: zod.z.string().optional(),
16490
+ /** See {@link TrackProjectionSchema}. Default `full`. */
16491
+ projection: TrackProjectionSchema.optional(),
16492
+ /** Include stationary-promoted rows (parked objects). Default false: the
16493
+ * feed lists passages; parking records live on the stationary registry. */
16494
+ includeStationary: zod.z.boolean().optional()
16646
16495
  });
16647
- var PipelineDefaultStepSchema = zod.z.lazy(() => zod.z.object({
16648
- addonId: zod.z.string(),
16649
- addonName: zod.z.string(),
16650
- slot: PipelineSlotSchema,
16651
- inputClasses: zod.z.array(zod.z.string()).readonly(),
16652
- outputClasses: zod.z.array(zod.z.string()).readonly(),
16653
- enabled: zod.z.boolean(),
16654
- modelId: zod.z.string(),
16655
- children: zod.z.array(PipelineDefaultStepSchema).readonly(),
16656
- group: zod.z.string().optional(),
16657
- settings: zod.z.record(zod.z.string(), zod.z.unknown()).optional()
16658
- }));
16659
- var PipelineTemplateStepSchema = zod.z.lazy(() => zod.z.object({
16660
- addonId: zod.z.string(),
16661
- enabled: zod.z.boolean(),
16662
- modelId: zod.z.string(),
16663
- children: zod.z.array(PipelineTemplateStepSchema).readonly(),
16664
- settings: zod.z.record(zod.z.string(), zod.z.unknown()).optional()
16665
- }));
16666
- var PipelineTemplateSchema$1 = zod.z.object({
16667
- id: zod.z.string(),
16668
- name: zod.z.string(),
16669
- createdAt: zod.z.string(),
16670
- updatedAt: zod.z.string(),
16671
- engine: PipelineEngineChoiceSchema,
16672
- steps: zod.z.array(PipelineTemplateStepSchema).readonly()
16496
+ var RecentTracksPageSchema = zod.z.object({
16497
+ /** Merged page, ordered by (`lastSeen` DESC, `trackId` DESC). */
16498
+ tracks: zod.z.array(TrackSchema).readonly(),
16499
+ /** Cursor for the next page, or null when this page is the last. */
16500
+ nextCursor: zod.z.string().nullable()
16673
16501
  });
16674
- var PipelineModelOptionSchema = zod.z.object({
16502
+ var LIST_GROUPS_DEFAULT_LIMIT = 40;
16503
+ var LIST_GROUPS_MAX_LIMIT = 100;
16504
+ var AnalyticsGroupRecordSchema = zod.z.object({
16675
16505
  id: zod.z.string(),
16676
- name: zod.z.string(),
16677
- formats: zod.z.record(zod.z.string(), zod.z.object({
16678
- downloaded: zod.z.boolean(),
16679
- sizeMB: zod.z.number()
16680
- })),
16681
- group: ModelVariantGroupSchema.optional(),
16682
- legacy: zod.z.boolean().optional(),
16683
- provider: ModelProviderIdSchema.optional()
16506
+ deviceId: zod.z.number().int(),
16507
+ openedAt: zod.z.number().int(),
16508
+ closedAt: zod.z.number().int(),
16509
+ timestamp: zod.z.number().int(),
16510
+ memberCount: zod.z.number().int(),
16511
+ memberTrackIds: zod.z.array(zod.z.string()).readonly(),
16512
+ className: zod.z.string(),
16513
+ classes: zod.z.array(zod.z.string()).readonly(),
16514
+ /** Relative event-media path, or null when the group has no picture yet. */
16515
+ mediaUrl: zod.z.string().nullable(),
16516
+ singleton: zod.z.boolean()
16684
16517
  });
16685
- var ConfigFieldBridge = zod.z.custom();
16686
- var PipelineAddonSchemaSchema = zod.z.object({
16687
- id: zod.z.string(),
16688
- name: zod.z.string(),
16689
- slot: PipelineSlotSchema,
16690
- inputClasses: zod.z.array(zod.z.string()).readonly(),
16691
- outputClasses: zod.z.array(zod.z.string()).readonly(),
16692
- childSlots: zod.z.array(PipelineSlotSchema).readonly(),
16693
- models: zod.z.array(PipelineModelOptionSchema).readonly(),
16694
- defaultModelId: zod.z.string(),
16695
- defaultModelIdByFormat: zod.z.record(zod.z.string(), zod.z.string()).optional(),
16696
- enabledByDefault: zod.z.boolean().optional(),
16697
- backfillIntoExistingOverrides: zod.z.boolean().optional(),
16698
- defaultConfidence: zod.z.number(),
16699
- group: zod.z.string().optional(),
16700
- configSchema: zod.z.array(ConfigFieldBridge).readonly().optional()
16518
+ var AnalyticsGroupMemberSchema = zod.z.object({
16519
+ trackId: zod.z.string(),
16520
+ deviceId: zod.z.number().int(),
16521
+ className: zod.z.string(),
16522
+ firstSeen: zod.z.number().int(),
16523
+ lastSeen: zod.z.number().int(),
16524
+ mediaUrl: zod.z.string().nullable()
16701
16525
  });
16702
- var PipelineSlotSchemaSchema = zod.z.object({
16703
- id: PipelineSlotSchema,
16704
- label: zod.z.string(),
16705
- priority: zod.z.number(),
16706
- parentSlot: PipelineSlotSchema.nullable(),
16707
- addons: zod.z.array(PipelineAddonSchemaSchema).readonly()
16526
+ var AnalyticsGroupDetailSchema = AnalyticsGroupRecordSchema.extend({ members: zod.z.array(AnalyticsGroupMemberSchema).readonly() });
16527
+ var ListGroupsQueryInput = zod.z.object({
16528
+ /** Devices to merge. An empty array yields `{ groups: [], nextCursor: null }`. */
16529
+ deviceIds: zod.z.array(zod.z.number()),
16530
+ /** Window lower bound on `closedAt` (inclusive). */
16531
+ since: zod.z.number().optional(),
16532
+ /** Window upper bound on `openedAt` (inclusive). */
16533
+ until: zod.z.number().optional(),
16534
+ limit: zod.z.number().int().min(1).max(LIST_GROUPS_MAX_LIMIT).default(LIST_GROUPS_DEFAULT_LIMIT),
16535
+ /** Opaque continuation cursor from a previous page's `nextCursor`. */
16536
+ cursor: zod.z.string().optional()
16708
16537
  });
16709
- var PipelineSchemaSchema = zod.z.object({
16710
- availableEngines: zod.z.array(AvailableEngineSchema).readonly(),
16711
- selectedEngine: PipelineEngineChoiceSchema,
16712
- slots: zod.z.array(PipelineSlotSchemaSchema).readonly()
16538
+ var ListGroupsPageSchema = zod.z.object({
16539
+ groups: zod.z.array(AnalyticsGroupRecordSchema).readonly(),
16540
+ nextCursor: zod.z.string().nullable()
16713
16541
  });
16714
- var EngineProvisioningSchema = zod.z.object({
16715
- runtimeId: zod.z.enum([
16716
- "onnx",
16717
- "openvino",
16718
- "coreml",
16719
- "edgetpu"
16720
- ]).nullable(),
16721
- device: zod.z.string().nullable(),
16722
- state: zod.z.enum([
16723
- "idle",
16724
- "installing",
16725
- "verifying",
16726
- "ready",
16727
- "failed"
16728
- ]),
16729
- progress: zod.z.number().optional(),
16730
- error: zod.z.string().optional(),
16731
- nextRetryAt: zod.z.number().optional(),
16732
- /**
16733
- * Gate A (config-correctness gate at engine change): human-readable
16734
- * config issues surfaced EAGERLY when the node's engine changes — model
16735
- * substitutions ("chose X, running Y") and zero-build steps ("no model
16736
- * has a <format> build"). Additive/optional: informational only, never
16737
- * enforced here — `assertEngineReady` (readiness) still gates inference.
16738
- * Absent/empty when the node-default tree resolves cleanly.
16739
- */
16740
- configIssues: zod.z.array(zod.z.string()).optional()
16542
+ var KeyEventQueryInput = zod.z.object({
16543
+ deviceId: zod.z.number(),
16544
+ /** Window lower bound (track firstSeen ≥ since). */
16545
+ since: zod.z.number(),
16546
+ /** Window upper bound (track firstSeen ≤ until). */
16547
+ until: zod.z.number(),
16548
+ limit: zod.z.number().int().min(1).max(200).default(50),
16549
+ /** Drop tracks scoring below this importance. */
16550
+ minImportance: zod.z.number().min(0).max(1).optional(),
16551
+ /** Restrict to a single class (e.g. 'person'). */
16552
+ classFilter: zod.z.string().optional()
16741
16553
  });
16742
- var PipelineStepInputSchema = zod.z.lazy(() => zod.z.object({
16743
- addonId: zod.z.string(),
16744
- modelId: zod.z.string().optional(),
16745
- enabled: zod.z.boolean().default(true),
16746
- children: zod.z.array(PipelineStepInputSchema).optional(),
16747
- settings: zod.z.record(zod.z.string(), zod.z.unknown()).optional(),
16748
- jumpDeviceKey: zod.z.string().optional()
16749
- }));
16750
- var ModelSubstitutionSchema = zod.z.object({
16751
- addonId: zod.z.string(),
16752
- chosen: zod.z.string(),
16753
- running: zod.z.string(),
16754
- format: zod.z.string()
16554
+ var KeyEventSchema = zod.z.object({
16555
+ /** The representative event id (the track's best ObjectEvent, else its trackId). */
16556
+ id: zod.z.string(),
16557
+ trackId: zod.z.string(),
16558
+ /** Track start time (firstSeen). */
16559
+ timestamp: zod.z.number(),
16560
+ className: zod.z.string(),
16561
+ ...TieredLabelFields,
16562
+ importance: zod.z.number(),
16563
+ /** Highest-confidence ObjectEvent id for the track (empty when none). */
16564
+ bestEventId: zod.z.string(),
16565
+ /** Track lifetime in ms (lastSeen - firstSeen). */
16566
+ windowMs: zod.z.number().optional(),
16567
+ ...TrackFlagFields,
16568
+ ...TrackRetrainFields
16755
16569
  });
16756
- var PipelineValidationIssueSchema = zod.z.object({
16757
- addonId: zod.z.string(),
16758
- kind: zod.z.enum(["unknown-addon", "no-format-build"]),
16759
- detail: zod.z.string()
16570
+ var TrackedDetectionSchema = zod.z.object({
16571
+ trackId: zod.z.string(),
16572
+ className: zod.z.string(),
16573
+ confidence: zod.z.number(),
16574
+ bbox: BoundingBoxSchema,
16575
+ zones: zod.z.array(zod.z.string()).readonly(),
16576
+ state: TrackStateSchema
16760
16577
  });
16761
- var PipelineValidationResultSchema = zod.z.object({
16762
- ok: zod.z.boolean(),
16763
- issues: zod.z.array(PipelineValidationIssueSchema).readonly(),
16764
- substitutions: zod.z.array(ModelSubstitutionSchema).readonly(),
16765
- /** The node's `currentEngine.format` this validation ran against. */
16766
- format: zod.z.string()
16578
+ var OverlayDetectionSchema = zod.z.looseObject({
16579
+ id: zod.z.string(),
16580
+ kind: zod.z.enum(["first-level", "detail"]),
16581
+ macroClass: zod.z.string(),
16582
+ score: zod.z.number(),
16583
+ bbox: zod.z.object({
16584
+ x: zod.z.number(),
16585
+ y: zod.z.number(),
16586
+ width: zod.z.number(),
16587
+ height: zod.z.number()
16588
+ }),
16589
+ labels: zod.z.array(zod.z.looseObject({
16590
+ label: zod.z.string(),
16591
+ score: zod.z.number()
16592
+ })).readonly(),
16593
+ parentId: zod.z.string().optional()
16767
16594
  });
16768
- var ReferenceImageEntrySchema = zod.z.object({
16769
- filename: zod.z.string(),
16770
- stepIds: zod.z.array(zod.z.string()).readonly().optional()
16595
+ var ScoredObjectEventSchema = ObjectEventSchema.extend({ score: zod.z.number() });
16596
+ var SearchObjectEventsInput = zod.z.object({
16597
+ text: zod.z.string(),
16598
+ deviceId: zod.z.number().optional(),
16599
+ since: zod.z.number().optional(),
16600
+ until: zod.z.number().optional(),
16601
+ classFilter: zod.z.string().optional(),
16602
+ limit: zod.z.number().default(50),
16603
+ minScore: zod.z.number().min(0).max(1).default(.2)
16771
16604
  });
16772
- var ReferenceImageBodySchema = zod.z.object({
16773
- base64: zod.z.string(),
16774
- filename: zod.z.string()
16605
+ var TrackCascadeCountsSchema = zod.z.object({
16606
+ /** Persisted track roots deleted (authoritative). */
16607
+ tracks: zod.z.number().int(),
16608
+ /** Object events removed with their tracks (best-effort; see note above). */
16609
+ events: zod.z.number().int(),
16610
+ /** Track/face/plate-owned media removed (best-effort). Never identity media. */
16611
+ media: zod.z.number().int(),
16612
+ /** Unassigned (non-enrolled) face reads removed (best-effort). */
16613
+ faces: zod.z.number().int(),
16614
+ /** Unassigned plate reads removed (best-effort; plate leg deferred to plate-intelligence). */
16615
+ plates: zod.z.number().int(),
16616
+ /** Per-track CLIP search vectors removed (best-effort). */
16617
+ embeddings: zod.z.number().int(),
16618
+ /** Group membership + group rows removed with their last member (best-effort). */
16619
+ groups: zod.z.number().int()
16775
16620
  });
16776
- var ReferenceAudioEntrySchema = zod.z.object({
16777
- filename: zod.z.string(),
16778
- sizeKb: zod.z.number()
16621
+ /** Disk-wins reconcile: media rows whose blobs are gone, then empty tracks. */
16622
+ var DiskReconcileCountsSchema = zod.z.object({
16623
+ mediaDropped: zod.z.number().int(),
16624
+ tracks: zod.z.number().int(),
16625
+ events: zod.z.number().int()
16779
16626
  });
16780
- var ReferenceAudioBodySchema = zod.z.object({ base64: zod.z.string() });
16781
- var AudioBackendSchema = zod.z.object({
16782
- id: zod.z.string(),
16783
- name: zod.z.string(),
16784
- description: zod.z.string(),
16785
- available: zod.z.boolean(),
16786
- /**
16787
- * Raw classifier labels this backend can emit (e.g. YAMNet's
16788
- * 521-class set or Apple SoundAnalysis's 303-class set). Used by
16789
- * the benchmark UI to populate the `enabledMicroClasses` filter
16790
- * specific to the selected backend without a separate fetch.
16791
- */
16792
- rawLabels: zod.z.array(zod.z.string()).readonly().optional()
16627
+ /** Event-store footprint for one camera. */
16628
+ var EventStoreDeviceFootprintSchema = zod.z.object({
16629
+ deviceId: zod.z.number(),
16630
+ /** Persisted event rows (motion + object + audio) for the camera. */
16631
+ rows: zod.z.number().int(),
16632
+ /** Event-owned media bytes on disk for the camera. */
16633
+ bytes: zod.z.number().int()
16793
16634
  });
16794
- var AudioCapabilitiesSchema = zod.z.object({
16795
- activeBackend: zod.z.string(),
16796
- availableBackends: zod.z.array(AudioBackendSchema).readonly(),
16797
- sampleRate: zod.z.number(),
16798
- chunkDurationMs: zod.z.number()
16635
+ /** Aggregate event-store footprint: global totals + per-camera breakdown. */
16636
+ var EventStoreFootprintSchema = zod.z.object({
16637
+ totalRows: zod.z.number().int(),
16638
+ totalBytes: zod.z.number().int(),
16639
+ devices: zod.z.array(EventStoreDeviceFootprintSchema).readonly()
16799
16640
  });
16800
- var DownloadModelResultSchema = zod.z.object({
16801
- filePath: zod.z.string(),
16802
- sizeMB: zod.z.number(),
16803
- durationMs: zod.z.number()
16641
+ /** Per-kind counts returned by the event-prune / device-delete mutations. */
16642
+ var EventPruneCountsSchema = zod.z.object({
16643
+ motion: zod.z.number().int(),
16644
+ object: zod.z.number().int(),
16645
+ audio: zod.z.number().int()
16804
16646
  });
16805
16647
  /**
16806
- * Wrapper carrying a single test run's result. Replaces the legacy
16807
- * ad-hoc `{labels: [{className, originalClass, score}]}` shape with the
16808
- * canonical `AudioResult` from the Phase 6 output rework: one
16809
- * `AudioDetection` per class above `minScore`, top-N candidates in
16810
- * `debug.alternateLabels['audio-classifier']`, per-source timings in
16811
- * `debug.stepTimings`. The outer `success`/`error` fields stay so the
16812
- * benchmark UI can still report a clean failure when the classifier
16813
- * cap isn't available.
16648
+ * Re-embed stored tracks from their key frames.
16649
+ *
16650
+ * The reason this is an operator-callable method and not a migration script:
16651
+ * every knob that decides what a vector MEANS — encoder model, crop margin,
16652
+ * squaring is only changeable if the existing vectors can be regenerated.
16653
+ * Mixing feature spaces in one index makes cosine scores incomparable, and the
16654
+ * symptom is a quality regression with no visible cause.
16814
16655
  */
16815
- var AudioTestResultSchema = zod.z.object({
16816
- success: zod.z.boolean(),
16817
- error: zod.z.string().optional(),
16818
- frame: zod.z.custom().optional()
16656
+ var RebuildObjectEmbeddingsInput = zod.z.object({
16657
+ /** Restrict to one camera. Omit for the whole fleet. */
16658
+ deviceId: zod.z.number().optional(),
16659
+ since: zod.z.number().optional(),
16660
+ until: zod.z.number().optional(),
16661
+ /** Stop after this many tracks; the result reports whether more remain. */
16662
+ maxTracks: zod.z.number().int().positive().optional(),
16663
+ /**
16664
+ * Run every embedding on THIS node instead of round-robining the fleet.
16665
+ *
16666
+ * Named `executeOnNodeId` and not `nodeId` on purpose: an inline `nodeId`
16667
+ * field in cap args is read by `parent-unowned-call.ts` as a ROUTING PIN, so
16668
+ * calling it that would pin the rebuild REQUEST itself to that node — the
16669
+ * rebuild orchestration lives on the hub, and only the per-track step runs
16670
+ * remotely. This field is data; the per-track pin is applied inside.
16671
+ *
16672
+ * Absent ⇒ round-robin over every online node whose runner can serve the
16673
+ * pinned model.
16674
+ */
16675
+ executeOnNodeId: zod.z.string().optional(),
16676
+ /**
16677
+ * Milliseconds to wait between tracks; omit for the built-in default, `0` to
16678
+ * run flat out.
16679
+ *
16680
+ * A rebuild is bulk maintenance on hub-main's single thread. Measured
16681
+ * 2026-08-06, an unpaced pass held that thread busy 82.2 s out of 120 and
16682
+ * pushed `nodes.topology` from 0.25 s to 26 s for 43 minutes. The value in
16683
+ * force is logged at start and finish so a deliberately slow pass reads
16684
+ * differently from a stalled one.
16685
+ */
16686
+ pacingMs: zod.z.number().int().nonnegative().optional()
16819
16687
  });
16820
- var PipelineConfigBridge = zod.z.custom();
16821
- var ConfigUISchemaBridge = zod.z.custom();
16822
- var ConfigUISchemaNullableBridge = zod.z.custom();
16823
- var InferenceCapabilitiesBridge = zod.z.custom();
16824
- var ModelAvailabilityListBridge = zod.z.custom();
16825
- var PipelineRunResultBridge = zod.z.custom();
16826
16688
  /**
16827
- * Pipeline executor detection engine + configuration + inference API.
16689
+ * Result of emptying the CLIP index.
16828
16690
  *
16829
- * Merged from: pipeline-executor, pipeline-config, inference, detection-config.
16830
- * Implemented by the detection-pipeline addon.
16691
+ * The clean slate before a policy change: a new crop margin or encoder model
16692
+ * leaves two feature spaces in one index whose cosine scores are not
16693
+ * comparable, so wiping and rebuilding is the only way to be sure every vector
16694
+ * means the same thing.
16695
+ */
16696
+ var WipeObjectEmbeddingsResultSchema = zod.z.object({ deleted: zod.z.number() });
16697
+ /**
16698
+ * Acknowledgement that a rebuild STARTED.
16831
16699
  *
16832
- * Per-device surface (DeviceSettingsContribution + the "is detection
16833
- * enabled for this camera?" toggle) lives on the paired
16834
- * `detection-pipeline` cap (device-scoped, singleton, wrapper
16835
- * defaultActive) same split pattern used by stream-broker /
16836
- * camera-streams and audio-analyzer / audio-analysis.
16700
+ * The pass costs ~1s per track — 45 minutes for a 2,600-track fleet — so it
16701
+ * runs detached and this returns immediately. Waiting for it made the client
16702
+ * time out while the work carried on server-side, which is the worst of both:
16703
+ * no result and no way to know it was still going. Poll
16704
+ * `getObjectEmbeddingRebuildStatus` for progress.
16837
16705
  */
16838
- var pipelineExecutorCapability = {
16839
- name: "pipeline-executor",
16840
- scope: "system",
16706
+ var RebuildObjectEmbeddingsResultSchema = zod.z.object({
16707
+ started: zod.z.boolean(),
16708
+ /** True when a pass was already running; the new request is ignored. */
16709
+ alreadyRunning: zod.z.boolean()
16710
+ });
16711
+ var RebuildStatusSchema = zod.z.object({
16712
+ running: zod.z.boolean(),
16713
+ scanned: zod.z.number(),
16714
+ rebuilt: zod.z.number(),
16715
+ /** Tracks whose key frame is gone — nothing to re-embed from. */
16716
+ missingKeyFrame: zod.z.number(),
16717
+ /** Tracks with no usable detection box. */
16718
+ missingBbox: zod.z.number(),
16719
+ /**
16720
+ * Tracks an executing node REFUSED rather than broke on — an unreadable key
16721
+ * frame, a step that threw. Separate from `failed` because the remedy is
16722
+ * different, and because a whole camera silently contributing zero vectors
16723
+ * is the shape of failure a rebuild must never hide.
16724
+ */
16725
+ notRunnable: zod.z.number(),
16726
+ /**
16727
+ * The pass stopped because NO node could serve the pinned model.
16728
+ *
16729
+ * Distinct from `notRunnable` on purpose: that one says "this track was
16730
+ * refused", this one says "the cluster cannot do this work at all" — every
16731
+ * candidate node either lacks the `clip-embedding` step, lacks a build of the
16732
+ * pinned model for its engine format, or dropped out. The remedy is a model /
16733
+ * engine change, not a per-camera one. Non-zero here always comes with
16734
+ * `complete: false`.
16735
+ */
16736
+ noCapableNode: zod.z.number(),
16737
+ failed: zod.z.number(),
16738
+ /** Set once a pass ends: true only when EVERYTHING was covered. */
16739
+ complete: zod.z.boolean().nullable(),
16740
+ startedAtMs: zod.z.number().nullable(),
16741
+ finishedAtMs: zod.z.number().nullable(),
16742
+ /** Present when the pass ended by throwing. */
16743
+ error: zod.z.string().nullable()
16744
+ });
16745
+ var ReplayFrameInputSchema = zod.z.object({
16746
+ timestamp: zod.z.number(),
16747
+ frame: PipelineRunResultBridge
16748
+ });
16749
+ var ReplayTrackSchema = zod.z.object({
16750
+ className: zod.z.string(),
16751
+ firstSeenMs: zod.z.number(),
16752
+ lastSeenMs: zod.z.number(),
16753
+ /** Bbox of the track's FIRST matched detection, pixel-space in the clip's
16754
+ * frame — a representative box for the diff's `(className, window, IoU)`
16755
+ * pairing (`replay-diff.ts`). A replay does not need the full per-frame
16756
+ * trajectory production's `Track.positions` keeps. */
16757
+ bbox: BoundingBoxSchema,
16758
+ /** How many of the input frames this track matched a real detection on
16759
+ * (never a coasted/extrapolated frame) — the replay's own signal for "how
16760
+ * solid is this track", cheaper than re-deriving it from a trajectory. */
16761
+ framesMatched: zod.z.number().int()
16762
+ });
16763
+ var RunReplayFrameProcessorResultSchema = zod.z.object({ tracks: zod.z.array(ReplayTrackSchema).readonly() });
16764
+ var pipelineAnalyticsCapability = {
16765
+ name: "pipeline-analytics",
16766
+ scope: "device",
16841
16767
  mode: "singleton",
16768
+ kind: "wrapper",
16769
+ defaultActive: true,
16770
+ deviceTypes: [require_sleep.DeviceType.Camera],
16771
+ exposesDeviceSettings: true,
16842
16772
  methods: {
16843
- getAvailableEngines: require_sleep.method(zod.z.void(), zod.z.array(PipelineEngineChoiceSchema)),
16844
- getSelectedEngine: require_sleep.method(zod.z.void(), PipelineEngineChoiceSchema),
16845
- getDefaultSteps: require_sleep.method(PipelineEngineChoiceSchema, zod.z.array(PipelineDefaultStepSchema)),
16773
+ getActiveTracks: require_sleep.method(zod.z.object({ deviceId: zod.z.number() }), zod.z.array(TrackSchema).readonly()),
16774
+ getTrack: require_sleep.method(zod.z.object({
16775
+ deviceId: zod.z.number(),
16776
+ trackId: zod.z.string()
16777
+ }), TrackSchema.nullable()),
16778
+ /** Historical completed tracks for a device. Queried from the
16779
+ * persisted `pipeline-analytics:tracks` collection; active tracks
16780
+ * still in RAM are not included. */
16781
+ listTracks: require_sleep.method(zod.z.object({
16782
+ deviceId: zod.z.number(),
16783
+ since: zod.z.number().optional(),
16784
+ until: zod.z.number().optional(),
16785
+ limit: zod.z.number().optional(),
16786
+ /** Spatial filter — only tracks whose trajectory intersects the zone
16787
+ * (normalized 0..1 rect or polygon). SQL-prefiltered on the persisted
16788
+ * envelope columns, then precisely tested per position. Tracks with
16789
+ * an unknown envelope (no frame dims at persist time) always match. */
16790
+ zone: TrackZoneFilterSchema.optional(),
16791
+ /** See {@link TrackProjectionSchema}. Default `full` (backward
16792
+ * compatible — omitting the field keeps today's exact behaviour). */
16793
+ projection: TrackProjectionSchema.optional(),
16794
+ /** Include stationary-promoted rows (parked objects handed to the
16795
+ * stationary registry). Default false: the timeline lists passages,
16796
+ * not parking records (operator decision, 2026-08-15). */
16797
+ includeStationary: zod.z.boolean().optional()
16798
+ }), zod.z.array(TrackSchema).readonly()),
16799
+ /**
16800
+ * Batched cluster-wide track listing — ONE call for the events page /
16801
+ * reel first paint instead of a per-camera `listTracks` fan-out. Merges
16802
+ * the persisted completed tracks of every requested device, sorted by
16803
+ * `lastSeen` DESC with a stable (lastSeen, trackId) cursor. Per-device
16804
+ * indexed pages (`idx_tracks_device_lastSeen`) are k-way merged
16805
+ * provider-side; `projection: 'slim'` drops the heavy `positions[]` /
16806
+ * `snapshots[]` JSON (returned as empty arrays). Active in-RAM tracks
16807
+ * are not included (same contract as `listTracks`).
16808
+ */
16809
+ listRecentTracks: require_sleep.method(RecentTracksQueryInput, RecentTracksPageSchema),
16810
+ /**
16811
+ * Batched co-moving group listing — the Groups feed. Same merge/cursor
16812
+ * contract as {@link listRecentTracks}. A group is a sealed partition of
16813
+ * one session; `getGroup` is the detail with members.
16814
+ */
16815
+ listGroups: require_sleep.method(ListGroupsQueryInput, ListGroupsPageSchema),
16816
+ getGroup: require_sleep.method(zod.z.object({
16817
+ deviceId: zod.z.number(),
16818
+ groupId: zod.z.string().min(1)
16819
+ }), AnalyticsGroupDetailSchema.nullable()),
16820
+ clearTracks: require_sleep.method(zod.z.object({ deviceId: zod.z.number() }), zod.z.void(), {
16821
+ kind: "mutation",
16822
+ auth: "admin"
16823
+ }),
16824
+ getMotionEvents: require_sleep.method(DeviceEventQueryInput, zod.z.array(MotionEventSchema).readonly()),
16825
+ getObjectEvents: require_sleep.method(ObjectEventQueryInput, zod.z.array(ObjectEventSchema).readonly()),
16826
+ getAudioEvents: require_sleep.method(DeviceEventQueryInput, zod.z.array(AudioEventSchema).readonly()),
16827
+ /**
16828
+ * Every event kind the device can produce: built-ins (motion + audio),
16829
+ * detection classes actually observed for the device (from the track
16830
+ * history), and sensor kinds contributed by LINKED devices (resolved via
16831
+ * `device-manager.getLinkedDevices`, mapped through `EVENT_KIND_BY_CAP`).
16832
+ */
16833
+ listEventKinds: require_sleep.method(zod.z.object({ deviceId: zod.z.number() }), zod.z.array(EventKindDescriptorSchema).readonly()),
16834
+ /**
16835
+ * The same answer for many cameras in ONE call.
16836
+ *
16837
+ * `listEventKinds` is the slowest per-device query on the hub — measured
16838
+ * at ~100 ms against 6-11 ms for its neighbours — because composing it
16839
+ * costs a `getCameraStatus`, a `getLinkedDevices` and one `getBindings`
16840
+ * per linked device. The viewer asks for it once per camera at first
16841
+ * paint, so twelve cameras paid twelve of those round-trips on top of the
16842
+ * per-camera cost.
16843
+ *
16844
+ * Batched, the camera statuses come from ONE `getCameraStatuses` instead
16845
+ * of N, and the per-device composition runs concurrently.
16846
+ *
16847
+ * Per-device rather than pre-merged on purpose: a caller that renders one
16848
+ * camera's lanes needs to know WHICH camera a kind came from, and merging
16849
+ * is three lines the caller can do. `listEventKinds` stays for
16850
+ * single-device callers.
16851
+ */
16852
+ listEventKindsBatch: require_sleep.method(zod.z.object({ deviceIds: zod.z.array(zod.z.number()).min(1).max(200) }), zod.z.array(EventKindsForDeviceSchema).readonly()),
16846
16853
  /**
16847
- * Per-node detection-engine provisioning snapshot. Returns the live
16848
- * state of the lazy runtime-provisioning machine on `nodeId`
16849
- * (idle / installing / verifying / ready / failed). The UI pairs this
16850
- * one-shot query with the `pipeline.engine-provisioning` live event
16851
- * (emitted on every transition) to drive a per-node "engine ready?"
16852
- * indicator without polling. Phase 2.
16854
+ * Sensor-event history for a camera: state changes of LINKED sensor
16855
+ * devices, attributed to the camera at ingest time (one row per linked
16856
+ * camera). Mirrors `getAudioEvents` query semantics; `kinds` narrows to
16857
+ * a kind subset.
16853
16858
  */
16854
- getEngineProvisioning: require_sleep.method(zod.z.object({ nodeId: zod.z.string() }), EngineProvisioningSchema),
16855
- getVideoPipelineSteps: require_sleep.method(zod.z.void(), zod.z.record(zod.z.string(), zod.z.object({
16856
- modelId: zod.z.string(),
16857
- settings: zod.z.record(zod.z.string(), zod.z.unknown()).readonly()
16858
- }))),
16859
- setVideoPipelineSteps: require_sleep.method(zod.z.object({ steps: zod.z.record(zod.z.string(), zod.z.object({
16860
- modelId: zod.z.string(),
16861
- settings: zod.z.record(zod.z.string(), zod.z.unknown()).readonly()
16862
- })) }), zod.z.object({ success: zod.z.literal(true) }), {
16859
+ getSensorEvents: require_sleep.method(zod.z.object({
16860
+ deviceId: zod.z.number(),
16861
+ since: zod.z.number().optional(),
16862
+ until: zod.z.number().optional(),
16863
+ kinds: zod.z.array(zod.z.string()).optional(),
16864
+ limit: zod.z.number().int().min(1).max(MAX_EVENT_QUERY_LIMIT).default(DEFAULT_EVENT_QUERY_LIMIT)
16865
+ }), zod.z.array(SensorEventSchema).readonly()),
16866
+ /**
16867
+ * Importance-ranked highlights for a device+window. Queries completed
16868
+ * tracks by (deviceId, firstSeen ∈ [since,until]), scores each (or reuses
16869
+ * the persisted score), filters by minImportance/classFilter, orders by
16870
+ * importance desc, and returns up to `limit` compact key events mapped to
16871
+ * each track's best event. Legacy tracks lacking a persisted score are
16872
+ * scored on-read (no write). Degrades to `[]` on error.
16873
+ */
16874
+ getKeyEvents: require_sleep.method(KeyEventQueryInput, zod.z.array(KeyEventSchema).readonly()),
16875
+ /** Server-side bucketed event counts for the 24-hour timeline.
16876
+ * Returns one entry per non-empty bucket; empty buckets are omitted. */
16877
+ getEventDensity: require_sleep.method(zod.z.object({
16878
+ deviceId: zod.z.number(),
16879
+ since: zod.z.number(),
16880
+ until: zod.z.number(),
16881
+ bucketMs: zod.z.number().int().positive()
16882
+ }), zod.z.array(zod.z.object({
16883
+ bucketStart: zod.z.number(),
16884
+ motion: zod.z.number().int(),
16885
+ object: zod.z.number().int(),
16886
+ audio: zod.z.number().int()
16887
+ })).readonly()),
16888
+ /**
16889
+ * @deprecated Prefer `pruneTracksBefore` — the track is the ROOT of the
16890
+ * analytics model and retention must cascade from it (design §5.1). This
16891
+ * event-only prune leaves orphaned tracks/faces/plates/embeddings behind.
16892
+ * Retained as a compat shim for the Phase-B3 recorder orchestration caller,
16893
+ * which prunes events to keep history aligned with available footage and
16894
+ * reads the per-kind counts. Delete all events (motion + object + audio)
16895
+ * for the given device older than `cutoffMs` (exclusive) + their thumbnails
16896
+ * in lockstep; returns per-kind deleted counts.
16897
+ */
16898
+ pruneEventsBefore: require_sleep.method(zod.z.object({
16899
+ deviceId: zod.z.number(),
16900
+ cutoffMs: zod.z.number()
16901
+ }), zod.z.object({
16902
+ motion: zod.z.number().int(),
16903
+ object: zod.z.number().int(),
16904
+ audio: zod.z.number().int()
16905
+ }), {
16863
16906
  kind: "mutation",
16864
16907
  auth: "admin"
16865
16908
  }),
16866
16909
  /**
16867
- * Clear THIS node's executor-side PER-DEVICE settings stores (the
16868
- * per-camera step overrides the object-detection root reads via
16869
- * `applyDeviceOverridesToTree`). `nodeId` is the ROUTING key the
16870
- * generated cap-router strips it (default `nodeIdMode: 'routing'`) and
16871
- * dispatches to that node, so the provider method runs ON the target
16872
- * node and receives no `nodeId`.
16910
+ * Track-centric retention entry point (design §5.1). Selects every
16911
+ * persisted track for the device whose `lastSeen < cutoffMs` (paged) and
16912
+ * runs the extensible whole-track deletion cascade (design §3): object
16913
+ * events + their media, track/face/plate-owned media, unassigned face
16914
+ * reads, per-track CLIP embeddings, then the track root LAST. ENROLLED
16915
+ * (assigned) faces/plates and `ownerKind:'identity'` media are exempt —
16916
+ * the durable matching gallery always persists. Fires the per-track
16917
+ * live-state cleanup so a pruned track can't linger in dispatch/overlay
16918
+ * state. Returns per-family deleted counts (`tracks` authoritative).
16873
16919
  *
16874
- * This is the slimmed executor leg of the orchestrator's
16875
- * `resetNodePipelineDefaults` flow (which owns the real reset: node
16876
- * addonDefaults pins + per-camera orchestrator overrides). The legacy
16877
- * `resetToDefault` — which reset a persisted global step-tree seed
16878
- * nothing in the live per-camera path read — was removed together with
16879
- * that seed.
16920
+ * Replaces `pruneEventsBefore` as the correct time-based retention prune.
16880
16921
  */
16881
- clearDeviceOverrides: require_sleep.method(zod.z.object({ nodeId: zod.z.string() }), zod.z.object({
16882
- success: zod.z.literal(true),
16883
- clearedDevices: zod.z.number()
16922
+ pruneTracksBefore: require_sleep.method(zod.z.object({
16923
+ deviceId: zod.z.number(),
16924
+ cutoffMs: zod.z.number()
16925
+ }), TrackCascadeCountsSchema, {
16926
+ kind: "mutation",
16927
+ auth: "admin"
16928
+ }),
16929
+ /**
16930
+ * Operator "clean slate" for a device (design §5.3): prune EVERY track for
16931
+ * the device via the same cascade as `pruneTracksBefore` with `cutoffMs =
16932
+ * now`. One call per device — no client-side track enumeration. Enrolled
16933
+ * gallery + identity media are exempt (design §4). Returns per-family
16934
+ * deleted counts.
16935
+ */
16936
+ wipeAllAnalytics: require_sleep.method(zod.z.object({ deviceId: zod.z.number() }), TrackCascadeCountsSchema, {
16937
+ kind: "mutation",
16938
+ auth: "admin"
16939
+ }),
16940
+ /**
16941
+ * Disk-wins reconcile for one camera. Drops media index rows whose blobs
16942
+ * are gone, then cascades tracks (including favourited and staging) that
16943
+ * have no remaining files. Enrolled identity/vehicle/scene media is never
16944
+ * probed. Trackless motion/audio events with no remaining file are dropped,
16945
+ * including snapshot-less rows.
16946
+ */
16947
+ reconcileFromDisk: require_sleep.method(zod.z.object({ deviceId: zod.z.number() }), DiskReconcileCountsSchema, {
16948
+ kind: "mutation",
16949
+ auth: "admin"
16950
+ }),
16951
+ /**
16952
+ * Delete whole tracks (object events) by id for the given device,
16953
+ * cascading their media in lockstep. Returns the number of tracks
16954
+ * actually deleted plus the ids that could not be removed.
16955
+ *
16956
+ * Operator-driven from the DI Events page (batch delete). Routes through
16957
+ * the same widened track-deletion cascade (design §5.2).
16958
+ */
16959
+ deleteTracks: require_sleep.method(zod.z.object({
16960
+ deviceId: zod.z.number(),
16961
+ trackIds: zod.z.array(zod.z.string()).min(1)
16962
+ }), zod.z.object({
16963
+ deleted: zod.z.number().int(),
16964
+ failed: zod.z.array(zod.z.string()).readonly()
16884
16965
  }), {
16885
16966
  kind: "mutation",
16886
16967
  auth: "admin"
16887
16968
  }),
16888
- getSchema: require_sleep.method(zod.z.void(), PipelineSchemaSchema),
16889
- getGlobalSteps: require_sleep.method(zod.z.void(), zod.z.array(PipelineDefaultStepSchema).readonly().nullable()),
16890
- getGlobalPipelineConfig: require_sleep.method(zod.z.void(), PipelineConfigBridge),
16891
- getOrchestratorConfigSchema: require_sleep.method(zod.z.void(), ConfigUISchemaBridge),
16892
16969
  /**
16893
- * Gate B (pre-init config-correctness gate). PURE COMPUTE against this
16894
- * node's `currentEngine.format`resolves `steps` the same way the
16895
- * runtime dispatch path would, and reports what WOULD happen without
16896
- * touching any node-global state. Called by the orchestrator at attach
16897
- * time (`attachOn`), node-pinned to the TARGET node, so config problems
16898
- * surface BEFORE `pipelineRunner.attachCamera` rather than at the first
16899
- * per-frame resolve. `ok` is false iff `issues` is non-empty (both
16900
- * `unknown-addon` and `no-format-build` are HARD issues); `substitutions`
16901
- * is informational (a degraded-but-loadable model swap) and never
16902
- * affects `ok`. Never throws.
16970
+ * Set the per-track operator flags (`markForTrain`, `debug`, `favourited`) on ONE track.
16971
+ * The patch is PARTIAL an omitted key is left untouched — because the
16972
+ * three surfaces that write it (admin Events grid, viewer track detail,
16973
+ * viewer cluster detail) each own one toggle and must not clobber the other.
16974
+ *
16975
+ * Writes the track ROW: `markForTrain`/`debug` are per-TRACK state, so they
16976
+ * live where `label` and `importance` live, not in any per-device settings
16977
+ * store. Updates the in-RAM active track too, so a flag set on a live track
16978
+ * survives its expiry-time persist.
16979
+ *
16980
+ * `auth: 'protected'` (the default), NOT `admin`: the viewer is an
16981
+ * authenticated non-admin surface and two of the three call sites are
16982
+ * there. The note that used to sit here said to revisit this the day a flag
16983
+ * gained an effect that costs storage, and D81 is that day — `markForTrain`
16984
+ * now pins. It STAYS protected, and the reason is that the alternative
16985
+ * makes the feature pointless: marking a track is something you do while
16986
+ * looking at it, on the surface you were already looking at it on, and that
16987
+ * surface is the viewer. What the storage cost gets instead is a BOUND — a
16988
+ * per-device pin budget enforced in the body, refusing a new pin past the
16989
+ * limit while always allowing un-marking. `deleteTracks` next door is still
16990
+ * admin, because destroying evidence and preserving it are not symmetric.
16991
+ *
16992
+ * `markForTrain` writes the retrain LIFECYCLE, not a boolean column: `true`
16993
+ * is `none → staging`, `false` is `staging → none`. A track already
16994
+ * `trained` refuses BOTH — its frames are copies inside the retrain dataset
16995
+ * and re-staging it from a generic toggle is how the same material gets
16996
+ * annotated twice under two ground truths. Returning a trained track to
16997
+ * staging is a deliberate action of the retrain page, which is also the only
16998
+ * thing that produces `trained` in the first place.
16999
+ *
17000
+ * Returns the RESOLVED state of both flags (absent → `false`) plus the
17001
+ * `retrainStatus` they were derived from, so a caller can drive its toggle
17002
+ * — and render a `trained` badge — without a re-fetch. Rejects an unknown
17003
+ * track, a new staging mark on a device already holding its full budget, and
17004
+ * any `markForTrain` write against a trained track.
16903
17005
  */
16904
- validatePipeline: require_sleep.method(zod.z.object({ steps: zod.z.array(PipelineStepInputSchema) }), PipelineValidationResultSchema),
16905
- listTemplates: require_sleep.method(zod.z.void(), zod.z.array(PipelineTemplateSchema$1).readonly()),
16906
- saveTemplate: require_sleep.method(zod.z.object({
16907
- name: zod.z.string(),
16908
- steps: zod.z.array(PipelineTemplateStepSchema).readonly(),
16909
- engine: PipelineEngineChoiceSchema
16910
- }), PipelineTemplateSchema$1, { kind: "mutation" }),
16911
- updateTemplate: require_sleep.method(zod.z.object({
16912
- id: zod.z.string(),
16913
- name: zod.z.string().optional(),
16914
- steps: zod.z.array(PipelineTemplateStepSchema).readonly().optional()
16915
- }), PipelineTemplateSchema$1, { kind: "mutation" }),
16916
- deleteTemplate: require_sleep.method(zod.z.object({ id: zod.z.string() }), zod.z.void(), { kind: "mutation" }),
16917
- getCapabilities: require_sleep.method(zod.z.void(), InferenceCapabilitiesBridge),
16918
- getAddonModels: require_sleep.method(zod.z.object({ addonId: zod.z.string() }), ModelAvailabilityListBridge),
16919
- downloadModel: require_sleep.method(zod.z.object({
16920
- addonId: zod.z.string(),
16921
- modelId: zod.z.string(),
16922
- format: ModelFormatSchema$1
16923
- }), DownloadModelResultSchema, { kind: "mutation" }),
16924
- deleteModel: require_sleep.method(zod.z.object({
16925
- addonId: zod.z.string(),
16926
- modelId: zod.z.string(),
16927
- format: ModelFormatSchema$1
16928
- }), zod.z.object({ success: zod.z.literal(true) }), { kind: "mutation" }),
17006
+ setTrackFlags: require_sleep.method(zod.z.object({
17007
+ /** Log/audit scope only — the trackId is globally unique on its own. */
17008
+ deviceId: zod.z.number(),
17009
+ trackId: zod.z.string(),
17010
+ flags: TrackFlagsPatchSchema
17011
+ }), TrackFlagsSchema, { kind: "mutation" }),
16929
17012
  /**
16930
- * Stateless single-frame execution. Callers (runner, benchmark) pass
16931
- * the complete `engine` + `steps` tree; the executor holds no state
16932
- * about cameras or saved pipelines.
17013
+ * Durable event-store footprint for the management UI: event rows
17014
+ * (motion + object + audio) counted per camera + total, plus the
17015
+ * event-owned media bytes on disk per camera + total. Stat/count-based,
17016
+ * computed on demand.
17017
+ */
17018
+ getEventStoreFootprint: require_sleep.method(zod.z.object({}), EventStoreFootprintSchema, {
17019
+ kind: "query",
17020
+ auth: "admin"
17021
+ }),
17022
+ /**
17023
+ * Cluster-wide prune of events older than `olderThanMs` (exclusive) across
17024
+ * every camera, deleting each event's media in lockstep. Logged to the
17025
+ * events ops-log with `reason` (default `'retention'`). Returns the summed
17026
+ * per-kind deleted counts.
17027
+ */
17028
+ pruneEvents: require_sleep.method(zod.z.object({
17029
+ olderThanMs: zod.z.number(),
17030
+ reason: OpsLogReasonSchema.optional()
17031
+ }), EventPruneCountsSchema, {
17032
+ kind: "mutation",
17033
+ auth: "admin"
17034
+ }),
17035
+ /**
17036
+ * Manually delete EVERY event (motion + object + audio) for one camera and
17037
+ * its event-owned media in lockstep. Logged to the events ops-log as
17038
+ * `op:'manual-delete', reason:'manual'`. Destructive — the admin UI guards
17039
+ * it behind a confirm.
17040
+ */
17041
+ deleteDeviceEvents: require_sleep.method(zod.z.object({ deviceId: zod.z.number() }), EventPruneCountsSchema, {
17042
+ kind: "mutation",
17043
+ auth: "admin"
17044
+ }),
17045
+ /** The events ops-log rows (newest-first), optionally scoped to one camera.
17046
+ * Backed by a declared pipeline-analytics SQLite collection. */
17047
+ /** Internal migration-participant lease. It drains active MediaStore
17048
+ * writes and refuses new ones without changing analytics bindings. */
17049
+ pauseForStorageMigration: require_sleep.method(StorageMigrationLeaseInputSchema, zod.z.object({ paused: zod.z.literal(true) }), {
17050
+ kind: "mutation",
17051
+ auth: "admin"
17052
+ }),
17053
+ resumeForStorageMigration: require_sleep.method(StorageMigrationLeaseInputSchema, zod.z.object({ resumed: zod.z.literal(true) }), {
17054
+ kind: "mutation",
17055
+ auth: "admin"
17056
+ }),
17057
+ /** Drops cached location roots after the storage coordinator repoints a
17058
+ * default so future event-media writes use the new root. */
17059
+ refreshStorageLocationsForMigration: require_sleep.method(StorageMigrationLeaseInputSchema, zod.z.object({ refreshed: zod.z.literal(true) }), {
17060
+ kind: "mutation",
17061
+ auth: "admin"
17062
+ }),
17063
+ startStorageMigrationMove: require_sleep.method(StorageMigrationMediaMoveInputSchema, zod.z.object({ jobId: zod.z.string() }), {
17064
+ kind: "mutation",
17065
+ auth: "admin"
17066
+ }),
17067
+ getStorageMigrationMoveStatus: require_sleep.method(zod.z.object({ jobId: zod.z.string() }), RelocateJobSchema.nullable(), { auth: "admin" }),
17068
+ cancelStorageMigrationMove: require_sleep.method(zod.z.object({ jobId: zod.z.string() }), zod.z.object({ cancelled: zod.z.boolean() }), {
17069
+ kind: "mutation",
17070
+ auth: "admin"
17071
+ }),
17072
+ /**
17073
+ * Moves event media between locations — the OPERATOR's mover, without the
17074
+ * coordinator's lease. Twin of `recording.relocateFootage`: the same
17075
+ * engine the lease-gated coordinated migration uses
17076
+ * (`startStorageMigrationMove`), armable in the background and WITHOUT
17077
+ * pausing anything. Exists because `eventMedia` was the only storage
17078
+ * class whose only move path went through the recorder's global pause.
17079
+ */
17080
+ relocateMedia: require_sleep.method(RelocateMediaInputSchema, zod.z.object({ jobId: zod.z.string() }), {
17081
+ kind: "mutation",
17082
+ auth: "admin"
17083
+ }),
17084
+ /** Every relocate job this addon knows about, newest first (in RAM: the
17085
+ * move is resumable, so a lost list costs nothing but the display). */
17086
+ listRelocateMediaJobs: require_sleep.method(zod.z.object({}), zod.z.array(RelocateJobSchema).readonly(), {
17087
+ kind: "query",
17088
+ auth: "admin"
17089
+ }),
17090
+ /** Cancel a running or queued relocate job. */
17091
+ cancelRelocateMedia: require_sleep.method(zod.z.object({ jobId: zod.z.string() }), zod.z.object({ cancelled: zod.z.boolean() }), {
17092
+ kind: "mutation",
17093
+ auth: "admin"
17094
+ }),
17095
+ listOpsLog: require_sleep.method(OpsLogQueryInputSchema, zod.z.array(OpsLogEntrySchema).readonly(), {
17096
+ kind: "query",
17097
+ auth: "admin"
17098
+ }),
17099
+ /**
17100
+ * The CHEAP QUESTION, asked before any media moves: how big is the dataset
17101
+ * the marked (`markForTrain`) tracks would produce?
16933
17102
  *
16934
- * `engine` is optional during the migration window to preserve the
16935
- * legacy call shape used by existing benchmark code; once all
16936
- * callers pass it explicitly we make it required.
17103
+ * Answered from media INDEX rows only key, kind, size, timestamp — so it
17104
+ * costs ~2 KB of reads per track and no blob reads at all. The measured harm
17105
+ * behind D56 was a bulk pass that read and base64'd every blob a track owned
17106
+ * before deciding anything, taking hub-main to 82 s busy out of 120; an
17107
+ * export is that same I/O shape, so it inherits the same discipline: know
17108
+ * the size, then decide.
16937
17109
  *
16938
- * Exactly one of `frame`, `frameRef`, `frameHandle`, `imageBase64`,
16939
- * `referenceImage` must be provided:
16940
- * - `frame`: runtime dispatch path (runner → decoded broker frame).
16941
- * Carries the raw buffer, dimensions, and format; the executor
16942
- * uses it directly without base64 round-tripping.
16943
- * - `frameHandle` (CB5): a zero-pixel shm `FrameHandle` for the SAME
16944
- * decoded frame. Both runner and executor are hub-local processes
16945
- * sharing `/dev/shm`, so the executor maps the named segment and
16946
- * reads the pixels back zero-copy — eliminating the ~1.2MB
16947
- * re-serialisation over UDS/MsgPack the `frame` path pays per call.
16948
- * High-risk: the FrameRing is a latest-wins seqlock with no
16949
- * refcount, so a recycled slot yields a null read; the executor
16950
- * then degrades to an empty result and the runner ships pixels via
16951
- * `frame` as the fallback (queue-depth gated on the runner side).
16952
- * - `imageBase64`: one-shot test path (benchmark ImageTab).
16953
- * - `referenceImage`: named file from the reference-image store.
17110
+ * `truncated` reports that more marked tracks exist than one pass carries.
17111
+ * Empty `deviceIds` every device that has marked tracks.
16954
17112
  */
16955
- runPipeline: require_sleep.method(zod.z.object({
16956
- engine: PipelineEngineChoiceSchema.optional(),
16957
- steps: zod.z.array(PipelineStepInputSchema).min(1),
16958
- frame: FrameInputSchema.optional(),
16959
- /**
16960
- * Process-local lazy frame. Valid only when caller and provider resolve
16961
- * in the same execution-group process; split/cross-node callers use
16962
- * `frame`/`image` inline compatibility instead.
16963
- */
16964
- frameRef: FrameRefSchema.optional(),
16965
- /**
16966
- * CB5 shm passthrough a `FrameHandle` naming the same ring slot
16967
- * the decoded pixels live in. One more member of the one-of
16968
- * frame/frameHandle/image/imageBase64/referenceImage group.
16969
- */
16970
- frameHandle: require_sleep.FrameHandleSchema.optional(),
16971
- imageBase64: zod.z.string().optional(),
16972
- /**
16973
- * Binary JPEG bytes preferred over `imageBase64` on internal
16974
- * hops (hub → forked worker via Moleculer MsgPack) because it
16975
- * skips the 33% base64 overhead + the per-call base64 decode on
16976
- * the detection-pipeline worker. Callers can pass either; exactly
16977
- * one of `frame`/`image`/`imageBase64`/`referenceImage` is required.
16978
- */
16979
- image: zod.z.instanceof(Uint8Array).optional(),
16980
- referenceImage: zod.z.string().optional(),
16981
- deviceId: zod.z.number().optional(),
16982
- sessionId: zod.z.string().optional(),
16983
- /**
16984
- * Execution plane. 'full' (default) runs the whole tree benchmark,
16985
- * reference-image, and detail-subtree calls. 'frame' is the live
16986
- * per-frame dispatch: ONLY root-plane steps run; crop children
16987
- * (inputClasses null) are skipped and served per-track via
16988
- * pipelineRunner.runDetailSubtree (two-plane design).
16989
- */
16990
- plane: zod.z.enum(["full", "frame"]).optional(),
16991
- /**
16992
- * Inference-device selector (Phase 2 multi-device). Format
16993
- * `<backend>:<device>` (e.g. `openvino:gpu`, `edgetpu:usb`, `cpu`).
16994
- * Omitted the runner's default device (current single-engine
16995
- * behaviour). Selects WHICH device pool of the node runs the call.
16996
- */
16997
- deviceKey: zod.z.string().optional(),
16998
- /**
16999
- * Two-plane NATIVE child-crop reference. Set by `runDetailSubtree` ONLY
17000
- * when the parent crop was resolved from the frame's retained NATIVE
17001
- * surface (a frameHandle HIT). Lets the executor re-cut a LEAF crop
17002
- * child's ROI (plate-ocr, face-embedding, leaf classifiers) at native
17003
- * resolution from that surface — the SAME quality path faces already
17004
- * had instead of the downscaled parent tile. `handle` keys the native
17005
- * surface (node-pinned to its owner); `cropFrameSpace` is the parent
17006
- * crop's padded/clamped rectangle in FRAME-space pixels, used to compose
17007
- * the executor's crop-normalized child ROI back into frame-normalized
17008
- * coordinates. Auxiliary to the image source (`image`/`frame`/…), NOT one
17009
- * of the mutually-exclusive image inputs. Absent tile-crop children
17010
- * (today's behaviour on the fallback path).
17011
- */
17012
- nativeCropRef: NativeCropRefSchema.optional()
17013
- }), PipelineRunResultBridge, { kind: "mutation" }),
17113
+ getTrainingExportSummary: require_sleep.method(zod.z.object({ deviceIds: zod.z.array(zod.z.number()).optional() }), TrainingExportSummarySchema, {
17114
+ kind: "query",
17115
+ auth: "admin"
17116
+ }),
17117
+ /**
17118
+ * Where to download the dataset archive.
17119
+ *
17120
+ * The BYTES do not come back through this cap — they come from the returned
17121
+ * data-plane URL, which streams a tar built entry by entry. A multi-gigabyte
17122
+ * archive base64'd through a unary RPC envelope would be held whole in
17123
+ * memory twice on a hub this repo has already OOM'd once (D9/D18 are the
17124
+ * same lesson about frames). `getDownloadUrl` on `recordingExport` is the
17125
+ * precedent, and this follows it deliberately.
17126
+ *
17127
+ * The archive contains a `manifest.json` FIRST, then the stored media
17128
+ * VERBATIM under `tracks/<deviceId>/<trackId>/…`. No crop is derived and no
17129
+ * model is run: a training set's pixels must be the pixels the pipeline saw.
17130
+ */
17131
+ getTrainingExportUrl: require_sleep.method(zod.z.object({ deviceIds: zod.z.array(zod.z.number()).optional() }), zod.z.object({ url: zod.z.string() }), {
17132
+ kind: "query",
17133
+ auth: "admin"
17134
+ }),
17135
+ /**
17136
+ * The staging worklist for one camera, or for every camera that has one.
17137
+ *
17138
+ * Fetched ON DEMAND, over the staging set only — the page never scans
17139
+ * history, because making the working set small is the entire purpose of
17140
+ * the mark. Each row carries how many frames the dataset already holds from
17141
+ * the track and how many subjects were annotated on them, so
17142
+ * `frameCount: 0` reads as "still to work" without a second call per track.
17143
+ *
17144
+ * `auth: 'admin'`, unlike the viewer-level mark itself: marking a track is
17145
+ * curation you do while looking at it, but building the training set the
17146
+ * fleet's models are fine-tuned on is not.
17147
+ */
17148
+ listRetrainStaging: require_sleep.method(zod.z.object({
17149
+ /** Empty ⇒ every camera that has staging tracks. A LIST, not a single
17150
+ * `deviceId`, deliberately: `deviceId` would make this device-bound and
17151
+ * route it at one camera's owner, and "every camera" would stop being
17152
+ * expressible at all. */
17153
+ deviceIds: zod.z.array(zod.z.number()).optional(),
17154
+ limit: zod.z.number().int().min(1).max(500).optional()
17155
+ }), zod.z.array(RetrainTrackSchema).readonly(), {
17156
+ kind: "query",
17157
+ auth: "admin"
17158
+ }),
17159
+ /**
17160
+ * What a track can contribute, and what it already has.
17161
+ *
17162
+ * `candidates` are the track's whole, unannotated frames index rows only,
17163
+ * so this is cheap. `copies` are the frames already inside the dataset, and
17164
+ * a candidate whose copy exists is marked `copied: true`: selecting it again
17165
+ * is free and CANNOT fail, whatever became of the original.
17166
+ *
17167
+ * A crop, a thumbnail and `fullFrameBoxed` are never candidates. The last
17168
+ * one matters most: it has the model's own rectangle burned into the pixels,
17169
+ * and a detector trained on it learns to find a green line.
17170
+ */
17171
+ listRetrainFrames: require_sleep.method(zod.z.object({ trackId: zod.z.string() }), RetrainFrameListSchema, {
17172
+ kind: "query",
17173
+ auth: "admin"
17174
+ }),
17175
+ /**
17176
+ * COPY-ON-SELECT — the write that makes `trained` safe to evict.
17177
+ *
17178
+ * Selecting a frame copies its bytes into retrain storage immediately: not
17179
+ * a reference, not a lease. Once the copy exists the dataset no longer
17180
+ * depends on the track's media, which is exactly what lets D81 hand a
17181
+ * `trained` track back to retention.
17182
+ *
17183
+ * The order inside is load-bearing and is pinned by a test: an EXISTING
17184
+ * copy is returned without touching the source, so an original that
17185
+ * evaporated blocks the selection of THAT ORIGINAL and never the copy
17186
+ * already taken. Every refusal comes back named — a dropped selection is
17187
+ * never silent, on the wire or in the log.
17188
+ */
17189
+ selectRetrainFrames: require_sleep.method(zod.z.object({
17190
+ deviceId: zod.z.number(),
17191
+ trackId: zod.z.string(),
17192
+ mediaKeys: zod.z.array(zod.z.string()).min(1)
17193
+ }), RetrainFrameSelectionSchema, {
17194
+ kind: "mutation",
17195
+ auth: "admin"
17196
+ }),
17197
+ /** Un-select a frame: its annotations go first, then the copy and its blob.
17198
+ * Deliberately destructive and deliberately explicit — it is the only way
17199
+ * a frame leaves the dataset before export. */
17200
+ deselectRetrainFrame: require_sleep.method(zod.z.object({
17201
+ deviceId: zod.z.number(),
17202
+ trackId: zod.z.string(),
17203
+ frameId: zod.z.string()
17204
+ }), zod.z.object({
17205
+ removed: zod.z.boolean(),
17206
+ removedAnnotations: zod.z.number().int()
17207
+ }), {
17208
+ kind: "mutation",
17209
+ auth: "admin"
17210
+ }),
17211
+ /**
17212
+ * The pixels of ONE copied frame, base64.
17213
+ *
17214
+ * Through the cap rather than a data plane because it is genuinely one
17215
+ * frame at a time, on demand, at human speed — the shape D9/D18 permit
17216
+ * (what they forbid is frames crossing a boundary at frame RATE). The
17217
+ * annotation canvas needs the image and its exact dimensions in the same
17218
+ * answer: a canvas that places a normalised box against a size it guessed
17219
+ * draws every box in the wrong place.
17220
+ */
17221
+ getRetrainFrameImage: require_sleep.method(zod.z.object({ frameId: zod.z.string() }), zod.z.object({
17222
+ base64: zod.z.string(),
17223
+ width: zod.z.number().int(),
17224
+ height: zod.z.number().int()
17225
+ }), {
17226
+ kind: "query",
17227
+ auth: "admin"
17228
+ }),
17014
17229
  /**
17015
- * Batched run N raw frames packed into one cap call. The provider
17016
- * routes the batch through `SharedInferencePool.inferBatch`
17017
- * (`MSG_INFER_BATCH = 0x03`) so the IPC framing and JSON response
17018
- * envelope cost is amortised N:1 vs N concurrent `runPipeline`
17019
- * calls. Single root step + uniform model assumed; trees with crop
17020
- * children fall back to sequential execution.
17230
+ * Ask the pipeline what it sees, as a PROPOSAL.
17021
17231
  *
17022
- * Used by `scripts/bench-batch-style.mts` for batch benchmarking
17023
- * N frames in one call to amortise per-call IPC overhead.
17232
+ * Runs through `pipelineRunner.runStatelessStep` on the COPIED frame, and
17233
+ * every box comes back as a draft with `source: 'assist'` plus the model and
17234
+ * score that produced it. The operator confirms, edits, adds and deletes;
17235
+ * nothing is stored until `saveRetrainAnnotations`.
17236
+ *
17237
+ * For packages the request is `rfdetr-package` on the ZONE CROP at 0.35 —
17238
+ * never the whole frame, where a package detector at that threshold proposes
17239
+ * furniture. A package request with no zone is REFUSED rather than widened,
17240
+ * because the silent widening would look like a bad model for as long as
17241
+ * nobody checked which rectangle it ran on.
17024
17242
  */
17025
- runPipelineBatch: require_sleep.method(zod.z.object({
17026
- engine: PipelineEngineChoiceSchema.optional(),
17027
- steps: zod.z.array(PipelineStepInputSchema).min(1),
17028
- frames: zod.z.array(FrameInputSchema).min(1).max(255),
17029
- deviceId: zod.z.number().optional(),
17030
- sessionId: zod.z.string().optional(),
17031
- /**
17032
- * Pure-inference benchmark hint. A NONZERO uint32 pins every frame in
17033
- * the batch to the Python pool's bench preprocess cache
17034
- * (`_bench_frame_id`) so a REPEATED benchmark frame is decoded +
17035
- * preprocessed ONCE and every later inference is a pure-inference cache
17036
- * hit — the sustained-throughput run measures inference, not
17037
- * decode+preprocess+infer. Omitted/0 for live frames (all different →
17038
- * full preprocess every call, correct). Fresh per sustained run;
17039
- * released via `uncacheFrame`.
17040
- */
17041
- frameId: zod.z.number().int().nonnegative().optional(),
17042
- /** Inference-device selector (Phase 2 multi-device); see runPipeline. */
17043
- deviceKey: zod.z.string().optional()
17044
- }), zod.z.object({ results: zod.z.array(PipelineRunResultBridge).readonly() }), { kind: "mutation" }),
17243
+ proposeRetrainAnnotations: require_sleep.method(zod.z.object({
17244
+ deviceId: zod.z.number(),
17245
+ trackId: zod.z.string(),
17246
+ frameId: zod.z.string(),
17247
+ subject: RetrainAssistSubjectSchema,
17248
+ /** Which node runs it. Absent ⇒ wherever an unowned call lands. */
17249
+ nodeId: zod.z.string().optional()
17250
+ }), RetrainAssistResultSchema, {
17251
+ kind: "mutation",
17252
+ auth: "admin"
17253
+ }),
17045
17254
  /**
17046
- * Cache a raw frame inside the Python inference pool's memory.
17047
- * Returns a numeric `frameId` that `inferCached` references
17048
- * subsequent calls send only 5 bytes through the pipe instead of
17049
- * 1.2MB raw data, eliminating the pipe transfer bottleneck.
17255
+ * The FrameProcessor pass of a replay run see the `Replay` section
17256
+ * above this capability's definition for why this is not the
17257
+ * `processFrame` method this file's header says pipeline-analytics does
17258
+ * not have.
17259
+ *
17260
+ * Constructs a FRESH `FrameProcessor` for `(deviceId, source)`, feeds it
17261
+ * `frames` IN THE ORDER GIVEN (the caller is responsible for time
17262
+ * ordering — this method does not sort), and returns the tracks it
17263
+ * produced. Zero persistence: no `TrackStore`, no event bus, no media
17264
+ * capture. `zones` / `detectionRules` are the run's OWN zone set —
17265
+ * typically the camera's real zones plus an ephemeral overlay
17266
+ * (`addon-benchmark`'s `replay-plan.ts`), never read from or written to
17267
+ * the `zones` capability by this method itself.
17050
17268
  */
17051
- cacheFrameInPool: require_sleep.method(zod.z.object({
17052
- data: zod.z.instanceof(Uint8Array),
17053
- width: zod.z.number().int().positive(),
17054
- height: zod.z.number().int().positive(),
17055
- format: zod.z.enum([
17056
- "rgb",
17057
- "bgr",
17058
- "gray"
17059
- ])
17060
- }), zod.z.object({
17061
- frameId: zod.z.number(),
17062
- width: zod.z.number(),
17063
- height: zod.z.number()
17064
- }), { kind: "mutation" }),
17269
+ runReplayFrameProcessor: require_sleep.method(zod.z.object({
17270
+ deviceId: zod.z.number(),
17271
+ source: DetectionSourceSchema,
17272
+ zones: zod.z.array(ZoneSchema).readonly().optional(),
17273
+ detectionRules: zod.z.array(ZoneRuleSchema).readonly().optional(),
17274
+ zoneMembershipMinOverlap: zod.z.number().min(0).max(1).optional(),
17275
+ frames: zod.z.array(ReplayFrameInputSchema).min(1)
17276
+ }), RunReplayFrameProcessorResultSchema, {
17277
+ kind: "mutation",
17278
+ auth: "admin"
17279
+ }),
17280
+ /** Every annotation on a track, oldest first. */
17281
+ listRetrainAnnotations: require_sleep.method(zod.z.object({ trackId: zod.z.string() }), zod.z.array(RetrainAnnotationSchema).readonly(), {
17282
+ kind: "query",
17283
+ auth: "admin"
17284
+ }),
17065
17285
  /**
17066
- * Run inference on a previously cached frame. Sends only 5 bytes
17067
- * (model_idx + frameId) through the IPC pipe — eliminates the
17068
- * ~35ms per-call overhead of transferring 1.2MB raw data.
17286
+ * Replace EVERY annotation on one frame with the supplied set.
17287
+ *
17288
+ * Whole-frame replacement, not per-box upsert: the unit of ground truth is
17289
+ * the frame, and "the operator deleted a box" must be the same durable
17290
+ * outcome as "the operator never drew it". A per-box patch would let a frame
17291
+ * keep a box the operator removed on a surface that only knew about the
17292
+ * boxes it sent.
17293
+ *
17294
+ * Refuses a macro class typed into `label` or `subLabel` — the tiers are
17295
+ * separate and the guard is at the WRITE, because a mixed taxonomy cannot
17296
+ * be un-mixed by reading it.
17069
17297
  */
17070
- inferCached: require_sleep.method(zod.z.object({
17071
- stepId: zod.z.string(),
17072
- frameId: zod.z.number().int()
17073
- }), zod.z.record(zod.z.string(), zod.z.unknown()), { kind: "mutation" }),
17298
+ saveRetrainAnnotations: require_sleep.method(zod.z.object({
17299
+ deviceId: zod.z.number(),
17300
+ trackId: zod.z.string(),
17301
+ frameId: zod.z.string(),
17302
+ annotations: zod.z.array(RetrainAnnotationDraftSchema)
17303
+ }), zod.z.array(RetrainAnnotationSchema).readonly(), {
17304
+ kind: "mutation",
17305
+ auth: "admin"
17306
+ }),
17074
17307
  /**
17075
- * Release a cached frame from the Python pool's memory.
17308
+ * Finish with a track: `staging trained`. **The only writer of that
17309
+ * state** — D81 shipped the column with it deliberately unreachable.
17310
+ *
17311
+ * Refuses a track the dataset holds no copies from. `trained` un-pins the
17312
+ * track's media, so completing without a copy is a delete order for material
17313
+ * nothing ever extracted anything from; that refusal IS the safety argument
17314
+ * of D81, expressed as a precondition.
17076
17315
  */
17077
- uncacheFrame: require_sleep.method(zod.z.object({ frameId: zod.z.number().int() }), zod.z.void(), { kind: "mutation" }),
17078
- /** Returns the effective pool tuning (resolved from user overrides + backend defaults). */
17079
- getEffectiveTuning: require_sleep.method(zod.z.void(), zod.z.object({
17080
- batchMode: zod.z.string(),
17081
- windowMs: zod.z.number(),
17082
- maxBatchSize: zod.z.number(),
17083
- concurrency: zod.z.number()
17084
- })),
17316
+ completeRetrainTrack: require_sleep.method(zod.z.object({
17317
+ deviceId: zod.z.number(),
17318
+ trackId: zod.z.string()
17319
+ }), RetrainTransitionResultSchema, {
17320
+ kind: "mutation",
17321
+ auth: "admin"
17322
+ }),
17085
17323
  /**
17086
- * List every EngineFactory currently loaded in this executor's RAM,
17087
- * with the models resident and a coarse "in use" marker derived from
17088
- * ongoing inference activity. Used by the Pipeline page Engines tab.
17324
+ * The deliberate return: `trained staging`, for the rare case.
17325
+ *
17326
+ * The generic `setTrackFlags` toggle refuses this in both directions by
17327
+ * design (D81) — re-staging from a checkbox is how the same material gets
17328
+ * annotated twice under two ground truths. Doing it here means the operator
17329
+ * is looking at the annotations that already exist while they decide, and
17330
+ * those annotations are LEFT ALONE: "put this back" must not be a
17331
+ * destructive act wearing a navigational name.
17089
17332
  */
17090
- listLoadedEngines: require_sleep.method(zod.z.void(), zod.z.array(zod.z.object({
17091
- engineKey: zod.z.string(),
17092
- engine: PipelineEngineChoiceSchema,
17093
- modelsLoaded: zod.z.array(zod.z.string()).readonly(),
17094
- inUseByCameras: zod.z.array(zod.z.number()).readonly(),
17095
- /**
17096
- * Origin of this resident factory.
17097
- * - `runtime` — main camera-serving engine (no idle TTL).
17098
- * - `warm-override` — benchmark/test override held in the warm
17099
- * cache; auto-disposed after the idle TTL.
17100
- * - `device-pool` — a concurrent per-device pool (Phase 2
17101
- * multi-device, keyed by `deviceKey`) resolved
17102
- * via `resolveDeviceFactory`. Runs alongside the
17103
- * `runtime` engine on a DIFFERENT accelerator
17104
- * (NPU / iGPU / Coral) — this is how the
17105
- * Engines tab shows all pools running at once.
17106
- */
17107
- kind: zod.z.enum([
17108
- "runtime",
17109
- "warm-override",
17110
- "device-pool"
17111
- ]),
17112
- /** Native pid of the underlying Python pool (null when no pool). */
17113
- poolPid: zod.z.number().nullable(),
17114
- /** ms since this factory was last used (null when not warm-tracked). */
17115
- idleMs: zod.z.number().nullable(),
17116
- /** Idle TTL after which `warm-override` factories self-evict (null when not applicable). */
17117
- idleTtlMs: zod.z.number().nullable()
17118
- })).readonly()),
17119
- /** Warm up an engine without running a frame. No-op if already loaded. */
17120
- spinEngine: require_sleep.method(zod.z.object({ engine: PipelineEngineChoiceSchema }), zod.z.object({ success: zod.z.literal(true) }), {
17333
+ restageRetrainTrack: require_sleep.method(zod.z.object({
17334
+ deviceId: zod.z.number(),
17335
+ trackId: zod.z.string()
17336
+ }), RetrainTransitionResultSchema, {
17121
17337
  kind: "mutation",
17122
17338
  auth: "admin"
17123
17339
  }),
17124
17340
  /**
17125
- * Unload an engine from RAM. `force:true` unloads even when cameras
17126
- * are actively using it (they re-spin on next frame). Default is
17127
- * gated returns `{success:false, reason}` when in use.
17341
+ * Where to download the ANNOTATED dataset.
17342
+ *
17343
+ * The sibling of `getTrainingExportUrl` and deliberately not the same
17344
+ * archive: that one streams a marked track's stored media verbatim, this one
17345
+ * streams the retrain COPIES plus an `annotations.json` carrying, for every
17346
+ * subject, the canonical full-frame box AND the geometry derived for each
17347
+ * model shape (letterboxed root / zone-cropped package / subject-cropped
17348
+ * classifier). Derived at export, never stored — one box in, three shapes
17349
+ * out, so two crops of the same subject can never end up in one feature
17350
+ * space (D52).
17128
17351
  */
17129
- killEngine: require_sleep.method(zod.z.object({
17130
- engine: PipelineEngineChoiceSchema,
17131
- force: zod.z.boolean().optional()
17132
- }), zod.z.object({
17133
- success: zod.z.boolean(),
17134
- reason: zod.z.string().optional()
17135
- }), {
17352
+ getRetrainExportUrl: require_sleep.method(zod.z.object({ deviceIds: zod.z.array(zod.z.number()).optional() }), zod.z.object({ url: zod.z.string() }), {
17353
+ kind: "query",
17354
+ auth: "admin"
17355
+ }),
17356
+ getEventMedia: require_sleep.method(zod.z.object({
17357
+ eventId: zod.z.string(),
17358
+ kind: MediaFileKindEnum.optional(),
17359
+ deviceId: zod.z.number()
17360
+ }), zod.z.array(MediaFileSchema).readonly()),
17361
+ /** All media rows owned by a track. `kinds` narrows to a kind subset so a
17362
+ * client can fetch the SMALL display variants on open and pull the
17363
+ * multi-MB native variants only on demand (mirrors `getEventMedia.kind`).
17364
+ * Absent ⇒ every kind (back-compat). */
17365
+ getTrackMedia: require_sleep.method(zod.z.object({
17366
+ trackId: zod.z.string(),
17367
+ kinds: zod.z.array(MediaFileKindEnum).optional(),
17368
+ deviceId: zod.z.number()
17369
+ }), zod.z.array(MediaFileSchema).readonly()),
17370
+ /**
17371
+ * What media a track HAS, without any of it.
17372
+ *
17373
+ * The detail view needs the shape of a track's media to build its strip —
17374
+ * which kinds exist, in what order, at what size — and then wants each tile
17375
+ * fetched as an image, not as base64 inside this response. Measured: the
17376
+ * full `getTrackMedia` is 5.3-7.7 MB and blocks the view; this manifest is
17377
+ * ~2 KB.
17378
+ *
17379
+ * It also restores a fact a `kinds` filter destroys: filtering
17380
+ * `getTrackMedia` drops whole ROWS, taking `kind` and `sizeBytes` with
17381
+ * them, so a client that fetched only the small variants could no longer
17382
+ * tell a full-resolution variant existed — and the affordance that opens it
17383
+ * would silently disappear.
17384
+ */
17385
+ listTrackMedia: require_sleep.method(zod.z.object({
17386
+ trackId: zod.z.string(),
17387
+ deviceId: zod.z.number()
17388
+ }), zod.z.array(MediaFileInfoSchema).readonly()),
17389
+ /**
17390
+ * Search object events by text query using CLIP cosine similarity.
17391
+ * Encodes `text` via the `embedding-encoder` cap, queries the
17392
+ * `ObjectEmbeddingStore` with optional prefilters, ranks all matching
17393
+ * embeddings by cosine similarity, and joins winners to their
17394
+ * ObjectEvents by trackId. Returns up to `limit` events scored ≥
17395
+ * `minScore`, sorted descending by score.
17396
+ */
17397
+ searchObjectEvents: require_sleep.method(SearchObjectEventsInput, zod.z.array(ScoredObjectEventSchema).readonly()),
17398
+ wipeObjectEmbeddings: require_sleep.method(zod.z.object({}), WipeObjectEmbeddingsResultSchema, {
17136
17399
  kind: "mutation",
17137
17400
  auth: "admin"
17138
17401
  }),
17139
- listReferenceImages: require_sleep.method(zod.z.void(), zod.z.array(ReferenceImageEntrySchema).readonly()),
17140
- getReferenceImage: require_sleep.method(zod.z.object({ filename: zod.z.string() }), ReferenceImageBodySchema.nullable()),
17141
- getReferenceAudioFiles: require_sleep.method(zod.z.void(), zod.z.array(ReferenceAudioEntrySchema).readonly()),
17142
- getReferenceAudio: require_sleep.method(zod.z.object({ filename: zod.z.string() }), ReferenceAudioBodySchema.nullable()),
17143
- getAudioCapabilities: require_sleep.method(zod.z.void(), AudioCapabilitiesSchema),
17144
- runAudioTest: require_sleep.method(zod.z.object({
17145
- addonId: zod.z.string(),
17146
- modelId: zod.z.string(),
17147
- filename: zod.z.string().optional(),
17148
- settings: zod.z.record(zod.z.string(), zod.z.unknown()).optional()
17149
- }), AudioTestResultSchema, { kind: "mutation" }),
17150
- getDetectionConfigSchema: require_sleep.method(zod.z.void(), ConfigUISchemaNullableBridge)
17402
+ rebuildObjectEmbeddings: require_sleep.method(RebuildObjectEmbeddingsInput, RebuildObjectEmbeddingsResultSchema, {
17403
+ kind: "mutation",
17404
+ auth: "admin"
17405
+ }),
17406
+ getObjectEmbeddingRebuildStatus: require_sleep.method(zod.z.object({}), RebuildStatusSchema)
17407
+ },
17408
+ events: {
17409
+ /**
17410
+ * Enriched frame emitted after refinement — the live-overlay source of
17411
+ * truth (two-plane re-injection). Carries the frame's detections in the
17412
+ * `ObjectDetection` wire shape: first-level roots (with track info +
17413
+ * enrichment labels) plus synthesized `kind:'detail'` face/plate entries
17414
+ * re-projected from per-track detail state, so stream overlays render
17415
+ * boxes + recognized names without querying full Track state.
17416
+ */
17417
+ onFrameTracked: { data: zod.z.object({
17418
+ deviceId: zod.z.number(),
17419
+ timestamp: zod.z.number(),
17420
+ frameWidth: zod.z.number(),
17421
+ frameHeight: zod.z.number(),
17422
+ detections: zod.z.array(OverlayDetectionSchema).readonly()
17423
+ }) },
17424
+ /** Track entered active state (first-seen). */
17425
+ onTrackStarted: { data: zod.z.object({
17426
+ deviceId: zod.z.number(),
17427
+ trackId: zod.z.string(),
17428
+ className: zod.z.string()
17429
+ }) },
17430
+ /** Track expired (TTL reached after last detection). */
17431
+ onTrackEnded: { data: zod.z.object({
17432
+ deviceId: zod.z.number(),
17433
+ trackId: zod.z.string(),
17434
+ className: zod.z.string(),
17435
+ durationMs: zod.z.number()
17436
+ }) },
17437
+ /** Canonical "something happened at device X" event, per-kind. */
17438
+ onDetectionEvent: { data: zod.z.object({
17439
+ deviceId: zod.z.number(),
17440
+ kind: EventKindSchema,
17441
+ eventId: zod.z.string(),
17442
+ timestamp: zod.z.number()
17443
+ }) }
17151
17444
  }
17152
17445
  };
17153
17446
  //#endregion
@@ -17178,108 +17471,6 @@ var CameraMetricsSchema = zod.z.object({
17178
17471
  });
17179
17472
  var CameraMetricsWithDeviceIdSchema = CameraMetricsSchema.extend({ deviceId: zod.z.number() });
17180
17473
  //#endregion
17181
- //#region src/capabilities/zones.cap.ts
17182
- /**
17183
- * Zone — pure geometry + identity. NO filtering behaviour.
17184
- *
17185
- * Zones describe **where** in the frame the operator wants to flag
17186
- * something; consumer-owned {@link ZoneRule} arrays describe **how**
17187
- * each pipeline stage uses them. Splitting the two means a single
17188
- * polygon "Driveway" can simultaneously back a motion-exclude rule,
17189
- * a detection-include rule on `['car']`, and an occupancy aggregate
17190
- * — without three duplicated polygons.
17191
- *
17192
- * Owned by the orchestrator addon (provider) and mirrored into the
17193
- * `zones` device-state slice on every mutation. Consumers
17194
- * (motion-wasm, pipeline-executor, analytics, admin UI) read either
17195
- * via `api.zones.listZones` (one-shot) or via `dev.state.zones` (live
17196
- * mirror with `onChanged`).
17197
- *
17198
- * Coordinates are normalised fractions of the frame (0–1) so zones
17199
- * survive resolution changes and stream profile switches.
17200
- *
17201
- * `kind` discriminates between full polygons (closed regions used
17202
- * for intrusion / occupancy filters) and tripwires (open 2-point
17203
- * line segments used for cross events). Onboard / firmware-reported
17204
- * zones (Reolink, ONVIF) are out of scope for now — see the deferred
17205
- * task list.
17206
- */
17207
- var ZoneKindEnum = zod.z.enum(["polygon", "tripwire"]);
17208
- /** Polygon vertex in fraction-of-frame coordinates (0–1). */
17209
- var PolygonPointSchema = zod.z.object({
17210
- x: zod.z.number(),
17211
- y: zod.z.number()
17212
- });
17213
- /** A camera detection zone — pure geometry/identity. */
17214
- var ZoneSchema = zod.z.object({
17215
- id: zod.z.string(),
17216
- name: zod.z.string(),
17217
- kind: ZoneKindEnum.default("polygon"),
17218
- /** Polygon vertices, fraction of frame (0–1). */
17219
- polygon: zod.z.array(PolygonPointSchema).readonly(),
17220
- /** Visual color for UI rendering. */
17221
- color: zod.z.string().default("#3b82f6")
17222
- });
17223
- /**
17224
- * Zones capability — per-camera CRUD over polygon detection zones.
17225
- *
17226
- * Provider lives in `addon-pipeline-orchestrator` (hub-only). Persists
17227
- * to per-device settings and mirrors into the `zones` device-state
17228
- * slice on every mutation, so downstream consumers can subscribe via
17229
- * `dev.state.zones.onChanged`.
17230
- *
17231
- * The cap surface only handles geometry + identity; filtering
17232
- * behaviour (per-class, include/exclude, threshold) lives in the
17233
- * consumer addons' rule arrays — see `ZoneRuleSchema` exported from
17234
- * `capabilities/schemas/zone-rule.js`.
17235
- */
17236
- var zonesCapability = {
17237
- name: "zones",
17238
- scope: "device",
17239
- mode: "singleton",
17240
- deviceTypes: [require_sleep.DeviceType.Camera],
17241
- methods: {
17242
- listZones: require_sleep.method(zod.z.object({ deviceId: zod.z.number() }), zod.z.array(ZoneSchema).readonly()),
17243
- addZone: require_sleep.method(zod.z.object({
17244
- deviceId: zod.z.number(),
17245
- zone: ZoneSchema
17246
- }), zod.z.void(), {
17247
- kind: "mutation",
17248
- auth: "admin"
17249
- }),
17250
- removeZone: require_sleep.method(zod.z.object({
17251
- deviceId: zod.z.number(),
17252
- zoneId: zod.z.string()
17253
- }), zod.z.void(), {
17254
- kind: "mutation",
17255
- auth: "admin"
17256
- }),
17257
- updateZone: require_sleep.method(zod.z.object({
17258
- deviceId: zod.z.number(),
17259
- zone: ZoneSchema
17260
- }), zod.z.void(), {
17261
- kind: "mutation",
17262
- auth: "admin"
17263
- })
17264
- },
17265
- /**
17266
- * Runtime-state slice — the live zone catalogue mirrored by the
17267
- * orchestrator on every CRUD mutation. Consumers read via
17268
- * `device.state.zones.value` / `.watch(...)` without round-tripping
17269
- * the cap, and the codegen DeviceProxy auto-wires the reactive
17270
- * handle. Slice shape is `{ zones: Zone[] }` so future extensions
17271
- * (e.g. zone groupings) can sit alongside the polygon list.
17272
- */
17273
- runtimeState: zod.z.object({ zones: zod.z.array(ZoneSchema).readonly() }),
17274
- /**
17275
- * Runtime-state durability: **restored** — written only on operator mutation, so a camera that never had one has nothing to re-derive from. This is the slice `zone-mirror-hydration.ts` exists to paper over.
17276
- *
17277
- * See `RuntimeStateDurability`. Enforced by
17278
- * `scripts/check-runtime-state-durability.ts`.
17279
- */
17280
- durability: "restored"
17281
- };
17282
- //#endregion
17283
17474
  //#region src/capabilities/pipeline-runner.cap.ts
17284
17475
  /**
17285
17476
  * A bounding box in NORMALIZED [0,1] frame coordinates for `getNativeCrop`. The
@@ -29211,98 +29402,6 @@ var sceneMonitorCapability = {
29211
29402
  durability: "session"
29212
29403
  };
29213
29404
  //#endregion
29214
- //#region src/capabilities/schemas/zone-rule.ts
29215
- /**
29216
- * Per-stage gating mode applied to the zones a rule references.
29217
- *
29218
- * - `include`: the rule contributes to a **whitelist** for its stage.
29219
- * When at least one `include` rule fires for a stage, only entities
29220
- * inside one of those zones pass that stage.
29221
- * - `exclude`: the rule contributes to a **blacklist** for its stage.
29222
- * Entities inside one of those zones are dropped at that stage.
29223
- *
29224
- * `monitor`-style observation (count without filtering) is not a rule
29225
- * mode — zones without any matching rule are observed naturally by
29226
- * `zone-analytics` (live snapshot + history), so an "I just want to
29227
- * count, not filter" use case needs no rule at all.
29228
- */
29229
- var ZoneRuleModeEnum = zod.z.enum(["include", "exclude"]);
29230
- /**
29231
- * Per-consumer rule that references existing zones (geometry) and
29232
- * defines how a specific pipeline stage should treat them. Each
29233
- * consumer addon owns its own `ZoneRule[]` array in its per-device
29234
- * settings:
29235
- *
29236
- * - `addon-motion-wasm` → `motionZoneRules: ZoneRule[]` (motion stage)
29237
- * - `addon-detection-pipeline` → `detectionZoneRules: ZoneRule[]` (detection stage)
29238
- * - future: notification rules, audio gating, etc.
29239
- *
29240
- * One rule applies to N zones (`zoneIds[]`) so the operator can
29241
- * express "ignore motion in ALL of {garden, street}" with a single
29242
- * rule. `classFilter` narrows the rule to specific object classes —
29243
- * "drop person detections in the street, but keep cars" is one
29244
- * `exclude` rule with `classFilter: ['person']`.
29245
- *
29246
- * `enabled` is a soft toggle — the operator can keep the rule
29247
- * configured but inert without deleting it.
29248
- */
29249
- var ZoneRuleSchema = zod.z.object({
29250
- /** Stable rule id — survives edits, used by the UI for diffing. */
29251
- id: zod.z.string(),
29252
- /** Optional human-readable label rendered in the rule editor. */
29253
- name: zod.z.string().optional(),
29254
- /** Zones this rule targets. The rule's `mode` applies to ALL
29255
- * listed zones (OR-set: a detection in any one of them counts).
29256
- * At least one zone id required — a rule with no targets is a
29257
- * configuration mistake and the form validator rejects it. */
29258
- zoneIds: zod.z.array(zod.z.string()).min(1).readonly(),
29259
- mode: ZoneRuleModeEnum,
29260
- /**
29261
- * Class names this rule applies to. Empty / undefined ⇒ rule
29262
- * applies to every class. Class strings match the `macroClass`
29263
- * field on detections (e.g. `person`, `car`, `dog`).
29264
- */
29265
- classFilter: zod.z.array(zod.z.string()).readonly().optional(),
29266
- /**
29267
- * Minimum bbox/mask overlap (0–1) with any of the rule's zones
29268
- * required to consider an entity "in the zone". Defaults to the
29269
- * consumer's stage default when omitted. Kept for back-compat with
29270
- * existing per-rule overrides; new operators pick the value via
29271
- * `bboxInclusionPct` (operator-friendly 0–100). Whichever field is
29272
- * set, the lower-level engine reads it as a 0–1 fraction.
29273
- */
29274
- overlapThreshold: zod.z.number().min(0).max(1).optional(),
29275
- /**
29276
- * Operator-friendly version of `overlapThreshold` — the percentage
29277
- * of the detection's bbox that must lie inside the zone for the
29278
- * rule to match. Documented default is 85%; the engine substitutes
29279
- * that when the field is omitted (kept optional so existing rules
29280
- * stored without it stay valid).
29281
- *
29282
- * When BOTH `overlapThreshold` and `bboxInclusionPct` are set on a
29283
- * rule, the engine prefers `bboxInclusionPct` because it's the
29284
- * field exposed in the UI. Internally both feed the same gate.
29285
- */
29286
- bboxInclusionPct: zod.z.number().min(0).max(100).optional(),
29287
- /**
29288
- * When `true` and a detection has a segmentation mask, use the
29289
- * mask for overlap instead of the bbox. Detection-stage only;
29290
- * motion rules ignore this field.
29291
- */
29292
- preferMask: zod.z.boolean().optional(),
29293
- /**
29294
- * Soft-toggle: `false` disables the rule without deleting it.
29295
- * Defaults to `true` so operators creating a rule via the UI
29296
- * see it active immediately.
29297
- */
29298
- enabled: zod.z.boolean().default(true)
29299
- });
29300
- /**
29301
- * Convenience array schema — used by addon device-settings
29302
- * contributions and runtime payloads (e.g. `RunnerCameraConfig`).
29303
- */
29304
- var ZoneRulesArraySchema = zod.z.array(ZoneRuleSchema).readonly();
29305
- //#endregion
29306
29405
  //#region src/capabilities/script-runner.cap.ts
29307
29406
  /**
29308
29407
  * Script-runner cap. Models HA `script.*` entities on
@@ -38456,6 +38555,12 @@ var METHOD_ACCESS_MAP = Object.freeze({
38456
38555
  addonId: null,
38457
38556
  access: "create"
38458
38557
  },
38558
+ "pipelineAnalytics.runReplayFrameProcessor": {
38559
+ capName: "pipeline-analytics",
38560
+ capScope: "device",
38561
+ addonId: null,
38562
+ access: "create"
38563
+ },
38459
38564
  "pipelineAnalytics.saveRetrainAnnotations": {
38460
38565
  capName: "pipeline-analytics",
38461
38566
  capScope: "device",
@@ -38588,6 +38693,12 @@ var METHOD_ACCESS_MAP = Object.freeze({
38588
38693
  addonId: null,
38589
38694
  access: "view"
38590
38695
  },
38696
+ "pipelineExecutor.getInferenceDeviceHealth": {
38697
+ capName: "pipeline-executor",
38698
+ capScope: "system",
38699
+ addonId: null,
38700
+ access: "view"
38701
+ },
38591
38702
  "pipelineExecutor.getOrchestratorConfigSchema": {
38592
38703
  capName: "pipeline-executor",
38593
38704
  capScope: "system",
@@ -38660,6 +38771,12 @@ var METHOD_ACCESS_MAP = Object.freeze({
38660
38771
  addonId: null,
38661
38772
  access: "view"
38662
38773
  },
38774
+ "pipelineExecutor.rearmInferenceDevice": {
38775
+ capName: "pipeline-executor",
38776
+ capScope: "system",
38777
+ addonId: null,
38778
+ access: "create"
38779
+ },
38663
38780
  "pipelineExecutor.runAudioTest": {
38664
38781
  capName: "pipeline-executor",
38665
38782
  capScope: "system",
@@ -42165,6 +42282,11 @@ var METHOD_DEVICE_SELECTORS = Object.freeze({
42165
42282
  form: "single",
42166
42283
  optional: false
42167
42284
  }],
42285
+ "pipelineAnalytics.runReplayFrameProcessor": [{
42286
+ name: "deviceId",
42287
+ form: "single",
42288
+ optional: false
42289
+ }],
42168
42290
  "pipelineAnalytics.saveRetrainAnnotations": [{
42169
42291
  name: "deviceId",
42170
42292
  form: "single",
@@ -43788,6 +43910,8 @@ function createSystemProxy(api) {
43788
43910
  getVideoPipelineSteps: (input) => dispatch("pipelineExecutor", "getVideoPipelineSteps", "query", input),
43789
43911
  setVideoPipelineSteps: (input) => dispatch("pipelineExecutor", "setVideoPipelineSteps", "mutation", input),
43790
43912
  clearDeviceOverrides: (input) => dispatch("pipelineExecutor", "clearDeviceOverrides", "mutation", input),
43913
+ getInferenceDeviceHealth: (input) => dispatch("pipelineExecutor", "getInferenceDeviceHealth", "query", input),
43914
+ rearmInferenceDevice: (input) => dispatch("pipelineExecutor", "rearmInferenceDevice", "mutation", input),
43791
43915
  getSchema: (input) => dispatch("pipelineExecutor", "getSchema", "query", input),
43792
43916
  getGlobalSteps: (input) => dispatch("pipelineExecutor", "getGlobalSteps", "query", input),
43793
43917
  getGlobalPipelineConfig: (input) => dispatch("pipelineExecutor", "getGlobalPipelineConfig", "query", input),