@camstack/types 1.2.109 → 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.
Files changed (55) hide show
  1. package/dist/addon.js +1 -1
  2. package/dist/addon.mjs +1 -1
  3. package/dist/capabilities/addons.cap.d.ts +9 -9
  4. package/dist/capabilities/broker.cap.d.ts +4 -4
  5. package/dist/capabilities/camera-streams.cap.d.ts +5 -5
  6. package/dist/capabilities/climate-control.cap.d.ts +8 -8
  7. package/dist/capabilities/core-blocks.cap.d.ts +16 -16
  8. package/dist/capabilities/day-night.cap.d.ts +8 -8
  9. package/dist/capabilities/decoder.cap.d.ts +13 -13
  10. package/dist/capabilities/device-manager.cap.d.ts +5 -5
  11. package/dist/capabilities/face-gallery.cap.d.ts +1 -1
  12. package/dist/capabilities/image-settings.cap.d.ts +16 -16
  13. package/dist/capabilities/llm-runtime.cap.d.ts +3 -3
  14. package/dist/capabilities/llm.cap.d.ts +4 -4
  15. package/dist/capabilities/media-player.cap.d.ts +9 -9
  16. package/dist/capabilities/metrics-provider.cap.d.ts +2 -2
  17. package/dist/capabilities/model-convert.cap.d.ts +3 -3
  18. package/dist/capabilities/motion-detection.cap.d.ts +4 -4
  19. package/dist/capabilities/notification-output.cap.d.ts +9 -9
  20. package/dist/capabilities/notification-rules.cap.d.ts +10 -10
  21. package/dist/capabilities/oauth-integration.cap.d.ts +2 -2
  22. package/dist/capabilities/osd-manager.cap.d.ts +2 -2
  23. package/dist/capabilities/pipeline-analytics.cap.d.ts +191 -54
  24. package/dist/capabilities/pipeline-executor.cap.d.ts +117 -19
  25. package/dist/capabilities/pipeline-orchestrator.cap.d.ts +21 -21
  26. package/dist/capabilities/pipeline-runner.cap.d.ts +6 -6
  27. package/dist/capabilities/platform-probe.cap.d.ts +2 -2
  28. package/dist/capabilities/recording-export.cap.d.ts +7 -7
  29. package/dist/capabilities/recording.cap.d.ts +7 -7
  30. package/dist/capabilities/schemas/detection-shared.d.ts +4 -4
  31. package/dist/capabilities/schemas/orchestrator-metrics.d.ts +2 -2
  32. package/dist/capabilities/schemas/streaming-shared.d.ts +11 -11
  33. package/dist/capabilities/sso-bridge.cap.d.ts +3 -3
  34. package/dist/capabilities/storage-migration.cap.d.ts +4 -4
  35. package/dist/capabilities/storage.cap.d.ts +2 -2
  36. package/dist/capabilities/stream-broker.cap.d.ts +50 -50
  37. package/dist/capabilities/user-management.cap.d.ts +20 -20
  38. package/dist/capabilities/vacuum-control.cap.d.ts +26 -26
  39. package/dist/capabilities/webrtc-session.cap.d.ts +4 -4
  40. package/dist/generated/addon-api.d.ts +50 -8
  41. package/dist/generated/method-access-map.d.ts +1 -1
  42. package/dist/generated/method-device-selectors.d.ts +1 -1
  43. package/dist/generated/system-proxy.d.ts +1 -1
  44. package/dist/index.js +2140 -1951
  45. package/dist/index.mjs +2140 -1951
  46. package/dist/interfaces/adoption-job.d.ts +2 -2
  47. package/dist/interfaces/relocate.d.ts +10 -10
  48. package/dist/interfaces/stream-broker.d.ts +2 -2
  49. package/dist/lifecycle/job.d.ts +8 -8
  50. package/dist/{sleep-BJTBu5cu.js → sleep-BCRrMlni.js} +4 -0
  51. package/dist/{sleep-Dj1DG9Od.mjs → sleep-DJlqY62B.mjs} +4 -0
  52. package/dist/types/frame-view.d.ts +10 -24
  53. package/dist/types/labels.d.ts +30 -1
  54. package/dist/types/models.d.ts +4 -4
  55. package/package.json +1 -1
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-BJTBu5cu.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");
@@ -2286,7 +2286,26 @@ var CLASS_MAP_MACRO_TARGETS = [
2286
2286
  "animal",
2287
2287
  "package"
2288
2288
  ];
2289
- var ClassMapDefinitionSchema = zod.z.object({
2289
+ /**
2290
+ * Wire schema for a per-model CATALOG classMap override
2291
+ * (`ModelCatalogEntry.classMap` / `ModelConvertMetadata.classMap`) —
2292
+ * restricted to {@link CLASS_MAP_MACRO_TARGETS}, the only macros the
2293
+ * detection pipeline executor actually routes.
2294
+ *
2295
+ * This is deliberately a DIFFERENT, narrower shape than the general-purpose
2296
+ * `ClassMapDefinition` interface above (e.g. `IDetectionAddon.getClassMap()`
2297
+ * and the audio `YAMNET_TO_MACRO` catalog both use macro targets outside this
2298
+ * enum) — the two used to share the name `ClassMapDefinition`/
2299
+ * `ClassMapDefinitionSchema`, which made the schema-type-twin guard
2300
+ * (`scripts/check-schema-type-twins.ts`) flag them as a duplicated shape. They
2301
+ * are not: it is two different concepts colliding on a name. Keep this type
2302
+ * under its own name rather than reusing `ClassMapDefinition` — reusing it
2303
+ * would either narrow every `ClassMapDefinition` consumer to the four
2304
+ * detection macros (breaking `YAMNET_TO_MACRO`) or drop the validation this
2305
+ * schema exists for (see the "rejects a classMap whose target is not a
2306
+ * detection macro" test in `model-catalog-schema.test.ts`).
2307
+ */
2308
+ var DetectionCatalogClassMapSchema = zod.z.object({
2290
2309
  mapping: zod.z.record(zod.z.string(), zod.z.enum(CLASS_MAP_MACRO_TARGETS)),
2291
2310
  preserveOriginal: zod.z.boolean()
2292
2311
  });
@@ -2658,7 +2677,7 @@ var ModelCatalogEntrySchema = zod.z.object({
2658
2677
  * applies (Frigate / COCO public catalog). Set on a custom model whose raw
2659
2678
  * labels already ARE the CamStack macros (Scrypted identity map).
2660
2679
  */
2661
- classMap: ClassMapDefinitionSchema.optional()
2680
+ classMap: DetectionCatalogClassMapSchema.optional()
2662
2681
  });
2663
2682
  var ConvertTargetSchema = zod.z.discriminatedUnion("format", [zod.z.object({
2664
2683
  format: zod.z.literal("openvino"),
@@ -2688,7 +2707,7 @@ var ModelConvertMetadataSchema = zod.z.object({
2688
2707
  "segmentation"
2689
2708
  ]),
2690
2709
  faceAlignment: zod.z.boolean().optional(),
2691
- classMap: ClassMapDefinitionSchema.optional()
2710
+ classMap: DetectionCatalogClassMapSchema.optional()
2692
2711
  });
2693
2712
  var ConvertArtifactSchema = zod.z.object({
2694
2713
  format: zod.z.enum(MODEL_FORMATS),
@@ -14774,373 +14793,1208 @@ var oauthIntegrationCapability = {
14774
14793
  getDescriptor: require_sleep.method(zod.z.void(), OauthIntegrationDescriptorSchema, { auth: "admin" }) }
14775
14794
  };
14776
14795
  //#endregion
14777
- //#region src/capabilities/pipeline-analytics.cap.ts
14796
+ //#region src/capabilities/pipeline-executor.cap.ts
14778
14797
  /**
14779
- * pipeline-analytics device-scoped wrapper cap. Refines raw
14780
- * per-frame detections emitted by the pipeline runner into tracked
14781
- * objects, per-kind event collections (motion / object / audio), and
14782
- * persisted media. Owns the post-detection domain end-to-end:
14783
- *
14784
- * runner emits PipelineInferenceResult
14785
- * ↓ (event bus)
14786
- * pipeline-analytics subscriber
14787
- * ↓ SORT tracker + zone engine + state analyzer + event emitter
14788
- * → three DB collections (one per kind), one FS media tree, one
14789
- * unified event emitter (FrameTracked + TrackStarted/Ended +
14790
- * DetectionEvent on bus)
14791
- *
14792
- * Pure subscriber model. No `processFrame` cap method — the runner
14793
- * already publishes the raw frame on the bus. The cap surface is
14794
- * only QUERIES + per-device settings, bound on/off via
14795
- * `device-manager.setWrapperActive`. `defaultActive: true` because
14796
- * every camera with a detection pipeline wants its raw detections
14797
- * refined; operators opt out per-device via BindingsTab when needed.
14798
- *
14799
- * Replaces the legacy `analysis-pipeline`, `analysis-data-persistence`
14800
- * (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.
14801
14801
  */
14802
- var TrackStateSchema = zod.z.enum([
14803
- "new",
14804
- "entered",
14805
- "left",
14806
- "moving",
14807
- "idle"
14808
- ]);
14809
- var EventKindSchema = zod.z.enum([
14810
- "motion",
14811
- "object",
14812
- "audio"
14813
- ]);
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
+ });
14814
14831
  /**
14815
- * Spatial filter for `listTracks` the rect + polygon variants of the shared
14816
- * MaskShape vocabulary (see `mask-shape.ts`). Coordinates are NORMALIZED 0..1
14817
- * 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.
14818
14835
  */
14819
- var TrackZoneFilterSchema = zod.z.discriminatedUnion("kind", [MaskRectShapeSchema, MaskPolygonShapeSchema]);
14820
- /** Closed icon vocabulary so clients render a known glyph per kind. */
14821
- var EventKindIconSchema = zod.z.enum([
14822
- "motion",
14823
- "audio",
14824
- "person",
14825
- "vehicle",
14826
- "animal",
14827
- "door",
14828
- "pir",
14829
- "smoke",
14830
- "water",
14831
- "button",
14832
- "package",
14833
- "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"
14834
14852
  ]);
14835
- var EventKindCategorySchema = zod.z.enum([
14836
- "motion",
14837
- "audio",
14838
- "detection",
14839
- "sensor",
14840
- "control",
14841
- "custom",
14842
- "package"
14853
+ var PipelineSlotSchema = zod.z.enum([
14854
+ "detector",
14855
+ "cropper",
14856
+ "classifier",
14857
+ "refiner",
14858
+ "audio-classifier"
14843
14859
  ]);
14844
- /** Taxonomy level — macro (timeline lane) vs sub (events-page leaf). */
14845
- var EventKindLevelSchema = zod.z.enum(["macro", "sub"]);
14846
- var EventKindDescriptorSchema = zod.z.object({
14847
- /** Stable kind id (e.g. 'motion', 'vehicle', 'car', 'lock'). */
14848
- kind: zod.z.string(),
14849
- /** i18n key resolved on the UI side; `label` is the English fallback. */
14850
- labelKey: zod.z.string(),
14851
- /** 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(),
14852
14868
  label: zod.z.string(),
14853
- /** Hex color for timeline/legend rendering. */
14854
- color: zod.z.string(),
14855
- /** Dictionary id → lucide component on the UI side. */
14856
- iconId: zod.z.string(),
14857
- /** Legacy closed-vocab glyph — fallback for `iconId`. */
14858
- icon: EventKindIconSchema,
14859
- category: EventKindCategorySchema,
14860
- /** Macro parent for this kind ('car' → 'vehicle'); null for a macro. */
14861
- parentKind: zod.z.string().nullable(),
14862
- /** Derived from `parentKind`, explicit for the client tree. */
14863
- level: EventKindLevelSchema,
14864
- /** Which cap + device contributes this kind. For built-ins the camera
14865
- * itself; for sensor kinds the LINKED source device. */
14866
- source: zod.z.object({
14867
- capName: zod.z.string(),
14868
- deviceId: zod.z.number()
14869
- })
14869
+ description: zod.z.string().optional()
14870
14870
  });
14871
- /** One camera's event vocabulary, as returned by `listEventKindsBatch`. */
14872
- var EventKindsForDeviceSchema = zod.z.object({
14873
- deviceId: zod.z.number(),
14874
- 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()
14875
14875
  });
14876
- 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({
14877
14896
  id: zod.z.string(),
14878
- /** The CAMERA the event is attributed to (a sensor linked to N cameras
14879
- * yields N rows, one per camera). */
14880
- deviceId: zod.z.number(),
14881
- /** The linked sensor device whose state changed. */
14882
- sourceDeviceId: zod.z.number(),
14883
- /** Event kind id — matches an `EventKindDescriptor.kind`. */
14884
- kind: zod.z.string(),
14885
- /** Snapshot of the sensor cap's runtime-state slice at the change. */
14886
- value: zod.z.record(zod.z.string(), zod.z.unknown()).nullable(),
14887
- timestamp: zod.z.number()
14888
- });
14889
- var TrackPositionSchema = zod.z.object({
14890
- x: zod.z.number(),
14891
- y: zod.z.number(),
14892
- timestamp: zod.z.number(),
14893
- 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()
14894
14902
  });
14895
- var TrackSnapshotSchema = zod.z.object({
14896
- timestamp: zod.z.number(),
14897
- position: TrackPositionSchema,
14898
- /** MediaStore key; resolve via `getTrackMedia({ trackId })`. */
14899
- 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()
14900
14913
  });
14901
- /**
14902
- * Normalized 0..1 trajectory envelope (min/max over every position bbox,
14903
- * divided by the track's detection-frame dims), computed at persist time.
14904
- * Absent when the frame dims were unknown when the track was persisted
14905
- * (legacy rows / dims-less sources) and on active (in-RAM) tracks.
14906
- */
14907
- var TrackEnvelopeSchema = zod.z.object({
14908
- minX: zod.z.number(),
14909
- minY: zod.z.number(),
14910
- maxX: zod.z.number(),
14911
- 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()
14912
14930
  });
14913
- /**
14914
- * Row projection for track list queries. `full` (default) returns the
14915
- * complete Track including the frame-rate `positions[]` history and the
14916
- * `snapshots[]` references — megabytes across a page of tracks. `slim`
14917
- * keeps every scalar the list surfaces actually render (ids, class(es),
14918
- * label / audioLabels / importance enrichment, firstSeen/lastSeen, state,
14919
- * zonesVisited, bestEventId, envelope, hasFace, hasEmbeddedFace, hasRider) and returns `positions` /
14920
- * `snapshots` as EMPTY arrays — detail views re-fetch the full row via
14921
- * `getTrack`. Mirrors the event-store `projection` convention
14922
- * (`getObjectEvents` et al.).
14923
- */
14924
- var TrackProjectionSchema = zod.z.enum(["full", "slim"]);
14925
- /**
14926
- * One audio-classification label heard on the track's camera while the
14927
- * track was alive, aggregated per label. An "episode" is one persisted
14928
- * audio event (the confident-classification path: score ≥ the device's
14929
- * `classificationMinScore`, class-change-or-heartbeat coalesced) — NOT
14930
- * one 32 ms inference chunk, so counts stay human-scaled.
14931
- */
14932
- var TrackAudioLabelSchema = zod.z.object({
14931
+ var PipelineSlotSchemaSchema = zod.z.object({
14932
+ id: PipelineSlotSchema,
14933
14933
  label: zod.z.string(),
14934
- /** Highest classification score observed across the label's episodes. */
14935
- peakScore: zod.z.number(),
14936
- /** Number of coalesced audio-event episodes carrying this label. */
14937
- count: zod.z.number(),
14938
- firstAt: zod.z.number(),
14939
- 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()
14940
15033
  });
14941
15034
  /**
14942
- * How a track was produced. `pipeline` (default / absent) = the spatial
14943
- * detection+tracking pipeline. Every OTHER value is a SYNTHETIC projection —
14944
- * no positions, a single snapshot, and no bbox trajectory at all:
14945
- *
14946
- * - `sensor` a linked sensor/control device state change.
14947
- * - `audio` an audio event on the camera itself that was anomalous for
14948
- * THAT camera, loud, and heard while nothing visual was happening (D62).
14949
- *
14950
- * The spatial subsystems (tracker association, occupancy count, re-id /
14951
- * embedding, resurrection) MUST skip every synthetic source. Test for that
14952
- * with `isSpatialTrack`, which allow-lists `pipeline` — a `!== 'sensor'`
14953
- * check silently readmits every source added after it was written.
14954
- */
14955
- var TrackSourceSchema = zod.z.enum([
14956
- "pipeline",
14957
- "sensor",
14958
- "audio"
14959
- ]);
14960
- /**
14961
- * Where a track sits in the RETRAIN lifecycle (D81).
14962
- *
14963
- * - `none` — never marked, or un-marked. Evictable.
14964
- * - `staging` — the operator wants this track as training material and has not
14965
- * finished with it. **This is the only state retention holds**: the track and
14966
- * everything it owns (object events, crops, keyframes, CLIP vector) survive
14967
- * the device's age window.
14968
- * - `trained` — the retrain page has taken what it needed. The frames it chose
14969
- * were COPIED into the retrain dataset at selection time, so the dataset no
14970
- * longer depends on the track's media and the track becomes EVICTABLE again.
14971
- * Terminal for the plain `markForTrain` toggle: returning it to `staging` is
14972
- * a deliberate action of the retrain page, not a side effect of a checkbox.
14973
- *
14974
- * There is no `null`. The state is stored `TEXT NOT NULL DEFAULT 'none'` because
14975
- * the store's filter language has only positive equality and `whereIn` — no
14976
- * negation, no IS NULL — so a NULL would be unselectable by ANY predicate and
14977
- * would make the entire pre-column history immortal in one deploy.
14978
- */
14979
- var RetrainStatusSchema = zod.z.enum([
14980
- "none",
14981
- "staging",
14982
- "trained"
14983
- ]);
14984
- /**
14985
- * Per-track OPERATOR flags — set by hand from the admin UI or the viewer, never
14986
- * by the pipeline. Spread into `TrackSchema` and `KeyEventSchema` from one place
14987
- * so the two surfaces cannot drift.
14988
- *
14989
- * **Absent ≠ false.** A track that has never been touched omits the field; an
14990
- * explicitly un-flagged track carries `false`. Legacy rows written before the
14991
- * columns existed read as absent, and a consumer that needs a boolean should say
14992
- * `flag === true`, not `flag !== false`.
14993
- *
14994
- * `markForTrain` is the WIRE FACE of {@link RetrainStatusSchema}, not a column:
14995
- * it is exactly `retrainStatus === 'staging'`, in both directions. Writing
14996
- * `true` moves `none → staging`, writing `false` moves `staging → none`, and a
14997
- * `trained` track reports `false` while refusing both writes. The boolean is
14998
- * kept because three surfaces drive a toggle off it; anything that needs to tell
14999
- * "never marked" from "already trained" must read `retrainStatus`.
15000
- *
15001
- * `debug` does NOT pin; it is attention, not durability.
15002
- *
15003
- * `favourited` IS a BOOLEAN pin (durability bit), not a retrain lifecycle.
15004
- * A favourited track is skipped by retention the same way `staging` is, but
15005
- * it does not enter `none|staging|trained` and has no staging budget.
15006
- */
15007
- var TrackFlagFields = {
15008
- /** Operator marked this track as training material — i.e. `retrainStatus` is
15009
- * `'staging'`. */
15010
- markForTrain: zod.z.boolean().optional(),
15011
- /** Operator marked this track for diagnostic attention. */
15012
- debug: zod.z.boolean().optional(),
15013
- /** Operator favourited this track. Pins it against pruning. */
15014
- favourited: zod.z.boolean().optional()
15015
- };
15016
- /**
15017
- * The lifecycle field itself, on the READ surfaces only (`Track`, `KeyEvent`).
15018
- * Deliberately NOT part of {@link TrackFlagFields}: that group also builds the
15019
- * write patch, and the status is not something the toggle sets — it is what the
15020
- * toggle's boolean is derived from. Absent on an in-RAM track never touched;
15021
- * always present on a persisted row (the column default materialises `'none'`).
15022
- */
15023
- var TrackRetrainFields = { retrainStatus: RetrainStatusSchema.optional() };
15024
- /**
15025
- * The write half: a PARTIAL patch. An omitted key is left untouched, so setting
15026
- * one flag can never clear the other — the toggles are independent and are
15027
- * driven from three surfaces that do not know about each other.
15028
- */
15029
- var TrackFlagsPatchSchema = zod.z.object(TrackFlagFields);
15030
- /**
15031
- * The resolved flag state after a write. Both fields are REQUIRED here (absent
15032
- * collapses to `false`) so a caller can drive a toggle's checked state off the
15033
- * 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.
15034
15043
  */
15035
- var TrackFlagsSchema = zod.z.object({
15036
- trackId: zod.z.string(),
15037
- markForTrain: zod.z.boolean(),
15038
- debug: zod.z.boolean(),
15039
- favourited: zod.z.boolean(),
15040
- /** The lifecycle state the boolean was derived from. Required here (unlike on
15041
- * a track row) because this shape is only ever produced by the write body,
15042
- * which always knows it — and a surface that has just written needs to render
15043
- * `trained` without a re-fetch. */
15044
- 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()
15045
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();
15046
15055
  /**
15047
- * WHICH tier a label occupies. The slot a label lands in is DECLARED by the
15048
- * step that produced it (`StepDefinition.labelTier`), never inferred from the
15049
- * text or the step's name.
15056
+ * Pipeline executor detection engine + configuration + inference API.
15050
15057
  *
15051
- * - `1` a SUB-CLASS: finer than the macro class, still a taxonomy token.
15052
- * `animal-type` (`dog`, `bird`), `vehicle-type` (`van`), and the root
15053
- * detector's own raw class when it is finer than the macro it maps to.
15054
- * - `2` — an INSTANCE: the finest thing said about this subject.
15055
- * `species` (`Turdus migratorius`), `identity` (`Alice`), `plate-text`.
15058
+ * Merged from: pipeline-executor, pipeline-config, inference, detection-config.
15059
+ * Implemented by the detection-pipeline addon.
15056
15060
  *
15057
- * The macro class itself (`person`, `vehicle`, `animal`, `package`, `face`,
15058
- * `plate`, `audio`) is NOT a tier it is `className`, and a macro token
15059
- * offered for either label slot is refused (2026-08-07 rule; the refusal is
15060
- * 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.
15061
15066
  */
15062
- var LabelTierSchema = zod.z.union([zod.z.literal(1), zod.z.literal(2)]);
15063
- /**
15064
- * WHO decided a label, and when. Carried per tier so a value can be traced to
15065
- * the step and model that produced it — which is what makes the write rule
15066
- * arguable after the fact ("why is 592's label `dog` and not `Canis lupus`?")
15067
- * and what lets a migrated, UNATTRIBUTED value be told apart from a real one.
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
15438
+ /**
15439
+ * Per-stage gating mode applied to the zones a rule references.
15068
15440
  *
15069
- * `stepId` is the pipeline step id (`animal-classifier`, `bird-classifier`,
15070
- * `plate-ocr`, `face-embedding`, `object-detection`), or the sentinel
15071
- * `migration:4g` for a value the 4g migration moved from the single-slot era —
15072
- * that value has no provenance, and the write rule lets ANY properly-attributed
15073
- * 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.
15074
15451
  */
15075
- var LabelAttributionSchema = zod.z.object({
15076
- stepId: zod.z.string(),
15077
- modelId: zod.z.string().optional(),
15078
- 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,
15079
15483
  /**
15080
- * The GALLERY id behind a recognised tier-2 label a face-gallery
15081
- * `Identity.id` or a plate-gallery `Vehicle.id` (both `randomUUID`).
15082
- *
15083
- * The text alone is a DISPLAY NAME, and a display name is renameable: a
15084
- * notification rule authored on "Gianluca" stopped matching the moment the
15085
- * operator fixed the spelling in the gallery, and nothing said so. The id is
15086
- * the thing that does not move, so it is what a rule matches on
15087
- * (`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).
15088
15504
  *
15089
- * Absent when the label names no gallery row a plate the OCR read but no
15090
- * 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.
15091
15508
  */
15092
- 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)
15093
15522
  });
15094
15523
  /**
15095
- * The TIERED label model (roadmap 4g), spread into `TrackSchema` and
15096
- * `ObjectEventSchema` from ONE place so the two surfaces cannot drift — a
15097
- * 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.
15098
15532
  *
15099
- * Two scalar columns, not an array: every consumer wants "the coarse one" or
15100
- * "the fine one", and an array made both a scan. `label` is tier 1, `subLabel`
15101
- * 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.
15102
15539
  *
15103
- * **Reading it.** What a human should be shown is `subLabel ?? label` — the
15104
- * finest thing known. Before 4g the single `label` column held the finest
15105
- * value, so a consumer that has not been updated reads the tier-1 slot and
15106
- * shows nothing on a species-only row; that is why the migration puts every
15107
- * pre-4g value in tier 2 (it cannot regress a display that reads the fallback)
15108
- * 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`).
15109
15545
  *
15110
- * **Writing it.** The slots are independent, which is the whole point: a
15111
- * tier-1 write (`bird`) can never overwrite a tier-2 value (`Turdus
15112
- * migratorius`), so fineness cannot regress by construction. Within a tier the
15113
- * higher score wins. One rule, one implementation — see
15114
- * `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.
15115
15554
  */
15116
- var TieredLabelFields = {
15117
- /** Tier 1 the sub-class. See {@link LabelTierSchema}. */
15118
- label: zod.z.string().optional(),
15119
- /** Confidence of the tier-1 value, as reported by the deciding step. */
15120
- labelScore: zod.z.number().optional(),
15121
- /** Provenance of the tier-1 value. See {@link LabelAttributionSchema}. */
15122
- labelMeta: LabelAttributionSchema.optional(),
15123
- /** Tier 2 — the instance. See {@link LabelTierSchema}. */
15124
- subLabel: zod.z.string().optional(),
15125
- /** Confidence of the tier-2 value, as reported by the deciding step. */
15126
- subLabelScore: zod.z.number().optional(),
15127
- /** Provenance of the tier-2 value. See {@link LabelAttributionSchema}. */
15128
- subLabelMeta: LabelAttributionSchema.optional()
15129
- };
15130
- /** Per-camera slice of a training-export estimate. */
15131
- var TrainingExportDeviceTotalsSchema = zod.z.object({
15132
- deviceId: zod.z.number(),
15133
- tracks: zod.z.number().int(),
15134
- files: zod.z.number().int(),
15135
- 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()
15136
15560
  });
15137
- /**
15138
- * What a training export WOULD contain. Computed from media index rows only —
15139
- * no blob is read to produce this.
15140
- */
15141
- var TrainingExportSummarySchema = zod.z.object({
15142
- generatedAt: zod.z.number(),
15143
- 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(),
15144
15998
  fileCount: zod.z.number().int(),
15145
15999
  byteCount: zod.z.number().int(),
15146
16000
  /** More marked tracks exist than a single pass carries. */
@@ -15618,1489 +16472,975 @@ var DeviceEventQueryInput = zod.z.object({
15618
16472
  * optional `mediaUrl` (populated by B5). `full` (default) keeps today's
15619
16473
  * exact behaviour. Callers may omit this field — the store defaults to
15620
16474
  * `full` when not provided. */
15621
- projection: zod.z.enum(["full", "slim"]).optional()
15622
- });
15623
- var ObjectEventQueryInput = DeviceEventQueryInput.extend({ classFilter: zod.z.string().optional() });
15624
- var RecentTracksQueryInput = zod.z.object({
15625
- /** Devices to merge. An empty array yields `{ tracks: [], nextCursor: null }`. */
15626
- deviceIds: zod.z.array(zod.z.number()),
15627
- /** Window lower bound on `lastSeen` (inclusive). */
15628
- since: zod.z.number().optional(),
15629
- /** Window upper bound on `lastSeen` (inclusive). */
15630
- until: zod.z.number().optional(),
15631
- /** Page size. Default 200, max 1000. */
15632
- limit: zod.z.number().int().min(1).max(1e3).default(200),
15633
- /** Opaque continuation cursor from a previous page's `nextCursor`.
15634
- * Encodes the (lastSeen, trackId) sort position — treat as opaque. */
15635
- cursor: zod.z.string().optional(),
15636
- /** See {@link TrackProjectionSchema}. Default `full`. */
15637
- projection: TrackProjectionSchema.optional(),
15638
- /** Include stationary-promoted rows (parked objects). Default false: the
15639
- * feed lists passages; parking records live on the stationary registry. */
15640
- includeStationary: zod.z.boolean().optional()
15641
- });
15642
- var RecentTracksPageSchema = zod.z.object({
15643
- /** Merged page, ordered by (`lastSeen` DESC, `trackId` DESC). */
15644
- tracks: zod.z.array(TrackSchema).readonly(),
15645
- /** Cursor for the next page, or null when this page is the last. */
15646
- nextCursor: zod.z.string().nullable()
15647
- });
15648
- var LIST_GROUPS_DEFAULT_LIMIT = 40;
15649
- var LIST_GROUPS_MAX_LIMIT = 100;
15650
- var AnalyticsGroupRecordSchema = zod.z.object({
15651
- id: zod.z.string(),
15652
- deviceId: zod.z.number().int(),
15653
- openedAt: zod.z.number().int(),
15654
- closedAt: zod.z.number().int(),
15655
- timestamp: zod.z.number().int(),
15656
- memberCount: zod.z.number().int(),
15657
- memberTrackIds: zod.z.array(zod.z.string()).readonly(),
15658
- className: zod.z.string(),
15659
- classes: zod.z.array(zod.z.string()).readonly(),
15660
- /** Relative event-media path, or null when the group has no picture yet. */
15661
- mediaUrl: zod.z.string().nullable(),
15662
- singleton: zod.z.boolean()
15663
- });
15664
- var AnalyticsGroupMemberSchema = zod.z.object({
15665
- trackId: zod.z.string(),
15666
- deviceId: zod.z.number().int(),
15667
- className: zod.z.string(),
15668
- firstSeen: zod.z.number().int(),
15669
- lastSeen: zod.z.number().int(),
15670
- mediaUrl: zod.z.string().nullable()
15671
- });
15672
- var AnalyticsGroupDetailSchema = AnalyticsGroupRecordSchema.extend({ members: zod.z.array(AnalyticsGroupMemberSchema).readonly() });
15673
- var ListGroupsQueryInput = zod.z.object({
15674
- /** Devices to merge. An empty array yields `{ groups: [], nextCursor: null }`. */
15675
- deviceIds: zod.z.array(zod.z.number()),
15676
- /** Window lower bound on `closedAt` (inclusive). */
15677
- since: zod.z.number().optional(),
15678
- /** Window upper bound on `openedAt` (inclusive). */
15679
- until: zod.z.number().optional(),
15680
- limit: zod.z.number().int().min(1).max(LIST_GROUPS_MAX_LIMIT).default(LIST_GROUPS_DEFAULT_LIMIT),
15681
- /** Opaque continuation cursor from a previous page's `nextCursor`. */
15682
- cursor: zod.z.string().optional()
15683
- });
15684
- var ListGroupsPageSchema = zod.z.object({
15685
- groups: zod.z.array(AnalyticsGroupRecordSchema).readonly(),
15686
- nextCursor: zod.z.string().nullable()
15687
- });
15688
- var KeyEventQueryInput = zod.z.object({
15689
- deviceId: zod.z.number(),
15690
- /** Window lower bound (track firstSeen ≥ since). */
15691
- since: zod.z.number(),
15692
- /** Window upper bound (track firstSeen ≤ until). */
15693
- until: zod.z.number(),
15694
- limit: zod.z.number().int().min(1).max(200).default(50),
15695
- /** Drop tracks scoring below this importance. */
15696
- minImportance: zod.z.number().min(0).max(1).optional(),
15697
- /** Restrict to a single class (e.g. 'person'). */
15698
- classFilter: zod.z.string().optional()
15699
- });
15700
- var KeyEventSchema = zod.z.object({
15701
- /** The representative event id (the track's best ObjectEvent, else its trackId). */
15702
- id: zod.z.string(),
15703
- trackId: zod.z.string(),
15704
- /** Track start time (firstSeen). */
15705
- timestamp: zod.z.number(),
15706
- className: zod.z.string(),
15707
- ...TieredLabelFields,
15708
- importance: zod.z.number(),
15709
- /** Highest-confidence ObjectEvent id for the track (empty when none). */
15710
- bestEventId: zod.z.string(),
15711
- /** Track lifetime in ms (lastSeen - firstSeen). */
15712
- windowMs: zod.z.number().optional(),
15713
- ...TrackFlagFields,
15714
- ...TrackRetrainFields
15715
- });
15716
- var TrackedDetectionSchema = zod.z.object({
15717
- trackId: zod.z.string(),
15718
- className: zod.z.string(),
15719
- confidence: zod.z.number(),
15720
- bbox: BoundingBoxSchema,
15721
- zones: zod.z.array(zod.z.string()).readonly(),
15722
- state: TrackStateSchema
15723
- });
15724
- var OverlayDetectionSchema = zod.z.looseObject({
15725
- id: zod.z.string(),
15726
- kind: zod.z.enum(["first-level", "detail"]),
15727
- macroClass: zod.z.string(),
15728
- score: zod.z.number(),
15729
- bbox: zod.z.object({
15730
- x: zod.z.number(),
15731
- y: zod.z.number(),
15732
- width: zod.z.number(),
15733
- height: zod.z.number()
15734
- }),
15735
- labels: zod.z.array(zod.z.looseObject({
15736
- label: zod.z.string(),
15737
- score: zod.z.number()
15738
- })).readonly(),
15739
- parentId: zod.z.string().optional()
15740
- });
15741
- var ScoredObjectEventSchema = ObjectEventSchema.extend({ score: zod.z.number() });
15742
- var SearchObjectEventsInput = zod.z.object({
15743
- text: zod.z.string(),
15744
- deviceId: zod.z.number().optional(),
15745
- since: zod.z.number().optional(),
15746
- until: zod.z.number().optional(),
15747
- classFilter: zod.z.string().optional(),
15748
- limit: zod.z.number().default(50),
15749
- minScore: zod.z.number().min(0).max(1).default(.2)
15750
- });
15751
- var TrackCascadeCountsSchema = zod.z.object({
15752
- /** Persisted track roots deleted (authoritative). */
15753
- tracks: zod.z.number().int(),
15754
- /** Object events removed with their tracks (best-effort; see note above). */
15755
- events: zod.z.number().int(),
15756
- /** Track/face/plate-owned media removed (best-effort). Never identity media. */
15757
- media: zod.z.number().int(),
15758
- /** Unassigned (non-enrolled) face reads removed (best-effort). */
15759
- faces: zod.z.number().int(),
15760
- /** Unassigned plate reads removed (best-effort; plate leg deferred to plate-intelligence). */
15761
- plates: zod.z.number().int(),
15762
- /** Per-track CLIP search vectors removed (best-effort). */
15763
- embeddings: zod.z.number().int(),
15764
- /** Group membership + group rows removed with their last member (best-effort). */
15765
- groups: zod.z.number().int()
15766
- });
15767
- /** Disk-wins reconcile: media rows whose blobs are gone, then empty tracks. */
15768
- var DiskReconcileCountsSchema = zod.z.object({
15769
- mediaDropped: zod.z.number().int(),
15770
- tracks: zod.z.number().int(),
15771
- events: zod.z.number().int()
15772
- });
15773
- /** Event-store footprint for one camera. */
15774
- var EventStoreDeviceFootprintSchema = zod.z.object({
15775
- deviceId: zod.z.number(),
15776
- /** Persisted event rows (motion + object + audio) for the camera. */
15777
- rows: zod.z.number().int(),
15778
- /** Event-owned media bytes on disk for the camera. */
15779
- bytes: zod.z.number().int()
15780
- });
15781
- /** Aggregate event-store footprint: global totals + per-camera breakdown. */
15782
- var EventStoreFootprintSchema = zod.z.object({
15783
- totalRows: zod.z.number().int(),
15784
- totalBytes: zod.z.number().int(),
15785
- devices: zod.z.array(EventStoreDeviceFootprintSchema).readonly()
15786
- });
15787
- /** Per-kind counts returned by the event-prune / device-delete mutations. */
15788
- var EventPruneCountsSchema = zod.z.object({
15789
- motion: zod.z.number().int(),
15790
- object: zod.z.number().int(),
15791
- audio: zod.z.number().int()
15792
- });
15793
- /**
15794
- * Re-embed stored tracks from their key frames.
15795
- *
15796
- * The reason this is an operator-callable method and not a migration script:
15797
- * every knob that decides what a vector MEANS — encoder model, crop margin,
15798
- * squaring — is only changeable if the existing vectors can be regenerated.
15799
- * Mixing feature spaces in one index makes cosine scores incomparable, and the
15800
- * symptom is a quality regression with no visible cause.
15801
- */
15802
- var RebuildObjectEmbeddingsInput = zod.z.object({
15803
- /** Restrict to one camera. Omit for the whole fleet. */
15804
- deviceId: zod.z.number().optional(),
15805
- since: zod.z.number().optional(),
15806
- until: zod.z.number().optional(),
15807
- /** Stop after this many tracks; the result reports whether more remain. */
15808
- maxTracks: zod.z.number().int().positive().optional(),
15809
- /**
15810
- * Run every embedding on THIS node instead of round-robining the fleet.
15811
- *
15812
- * Named `executeOnNodeId` and not `nodeId` on purpose: an inline `nodeId`
15813
- * field in cap args is read by `parent-unowned-call.ts` as a ROUTING PIN, so
15814
- * calling it that would pin the rebuild REQUEST itself to that node — the
15815
- * rebuild orchestration lives on the hub, and only the per-track step runs
15816
- * remotely. This field is data; the per-track pin is applied inside.
15817
- *
15818
- * Absent ⇒ round-robin over every online node whose runner can serve the
15819
- * pinned model.
15820
- */
15821
- executeOnNodeId: zod.z.string().optional(),
15822
- /**
15823
- * Milliseconds to wait between tracks; omit for the built-in default, `0` to
15824
- * run flat out.
15825
- *
15826
- * A rebuild is bulk maintenance on hub-main's single thread. Measured
15827
- * 2026-08-06, an unpaced pass held that thread busy 82.2 s out of 120 and
15828
- * pushed `nodes.topology` from 0.25 s to 26 s for 43 minutes. The value in
15829
- * force is logged at start and finish so a deliberately slow pass reads
15830
- * differently from a stalled one.
15831
- */
15832
- pacingMs: zod.z.number().int().nonnegative().optional()
15833
- });
15834
- /**
15835
- * Result of emptying the CLIP index.
15836
- *
15837
- * The clean slate before a policy change: a new crop margin or encoder model
15838
- * leaves two feature spaces in one index whose cosine scores are not
15839
- * comparable, so wiping and rebuilding is the only way to be sure every vector
15840
- * means the same thing.
15841
- */
15842
- var WipeObjectEmbeddingsResultSchema = zod.z.object({ deleted: zod.z.number() });
15843
- /**
15844
- * Acknowledgement that a rebuild STARTED.
15845
- *
15846
- * The pass costs ~1s per track — 45 minutes for a 2,600-track fleet — so it
15847
- * runs detached and this returns immediately. Waiting for it made the client
15848
- * time out while the work carried on server-side, which is the worst of both:
15849
- * no result and no way to know it was still going. Poll
15850
- * `getObjectEmbeddingRebuildStatus` for progress.
15851
- */
15852
- var RebuildObjectEmbeddingsResultSchema = zod.z.object({
15853
- started: zod.z.boolean(),
15854
- /** True when a pass was already running; the new request is ignored. */
15855
- alreadyRunning: zod.z.boolean()
15856
- });
15857
- var RebuildStatusSchema = zod.z.object({
15858
- running: zod.z.boolean(),
15859
- scanned: zod.z.number(),
15860
- rebuilt: zod.z.number(),
15861
- /** Tracks whose key frame is gone — nothing to re-embed from. */
15862
- missingKeyFrame: zod.z.number(),
15863
- /** Tracks with no usable detection box. */
15864
- missingBbox: zod.z.number(),
15865
- /**
15866
- * Tracks an executing node REFUSED rather than broke on — an unreadable key
15867
- * frame, a step that threw. Separate from `failed` because the remedy is
15868
- * different, and because a whole camera silently contributing zero vectors
15869
- * is the shape of failure a rebuild must never hide.
15870
- */
15871
- notRunnable: zod.z.number(),
15872
- /**
15873
- * The pass stopped because NO node could serve the pinned model.
15874
- *
15875
- * Distinct from `notRunnable` on purpose: that one says "this track was
15876
- * refused", this one says "the cluster cannot do this work at all" — every
15877
- * candidate node either lacks the `clip-embedding` step, lacks a build of the
15878
- * pinned model for its engine format, or dropped out. The remedy is a model /
15879
- * engine change, not a per-camera one. Non-zero here always comes with
15880
- * `complete: false`.
15881
- */
15882
- noCapableNode: zod.z.number(),
15883
- failed: zod.z.number(),
15884
- /** Set once a pass ends: true only when EVERYTHING was covered. */
15885
- complete: zod.z.boolean().nullable(),
15886
- startedAtMs: zod.z.number().nullable(),
15887
- finishedAtMs: zod.z.number().nullable(),
15888
- /** Present when the pass ended by throwing. */
15889
- error: zod.z.string().nullable()
15890
- });
15891
- var pipelineAnalyticsCapability = {
15892
- name: "pipeline-analytics",
15893
- scope: "device",
15894
- mode: "singleton",
15895
- kind: "wrapper",
15896
- defaultActive: true,
15897
- deviceTypes: [require_sleep.DeviceType.Camera],
15898
- exposesDeviceSettings: true,
15899
- methods: {
15900
- getActiveTracks: require_sleep.method(zod.z.object({ deviceId: zod.z.number() }), zod.z.array(TrackSchema).readonly()),
15901
- getTrack: require_sleep.method(zod.z.object({
15902
- deviceId: zod.z.number(),
15903
- trackId: zod.z.string()
15904
- }), TrackSchema.nullable()),
15905
- /** Historical completed tracks for a device. Queried from the
15906
- * persisted `pipeline-analytics:tracks` collection; active tracks
15907
- * still in RAM are not included. */
15908
- listTracks: require_sleep.method(zod.z.object({
15909
- deviceId: zod.z.number(),
15910
- since: zod.z.number().optional(),
15911
- until: zod.z.number().optional(),
15912
- limit: zod.z.number().optional(),
15913
- /** Spatial filter — only tracks whose trajectory intersects the zone
15914
- * (normalized 0..1 rect or polygon). SQL-prefiltered on the persisted
15915
- * envelope columns, then precisely tested per position. Tracks with
15916
- * an unknown envelope (no frame dims at persist time) always match. */
15917
- zone: TrackZoneFilterSchema.optional(),
15918
- /** See {@link TrackProjectionSchema}. Default `full` (backward
15919
- * compatible — omitting the field keeps today's exact behaviour). */
15920
- projection: TrackProjectionSchema.optional(),
15921
- /** Include stationary-promoted rows (parked objects handed to the
15922
- * stationary registry). Default false: the timeline lists passages,
15923
- * not parking records (operator decision, 2026-08-15). */
15924
- includeStationary: zod.z.boolean().optional()
15925
- }), zod.z.array(TrackSchema).readonly()),
15926
- /**
15927
- * Batched cluster-wide track listing — ONE call for the events page /
15928
- * reel first paint instead of a per-camera `listTracks` fan-out. Merges
15929
- * the persisted completed tracks of every requested device, sorted by
15930
- * `lastSeen` DESC with a stable (lastSeen, trackId) cursor. Per-device
15931
- * indexed pages (`idx_tracks_device_lastSeen`) are k-way merged
15932
- * provider-side; `projection: 'slim'` drops the heavy `positions[]` /
15933
- * `snapshots[]` JSON (returned as empty arrays). Active in-RAM tracks
15934
- * are not included (same contract as `listTracks`).
15935
- */
15936
- listRecentTracks: require_sleep.method(RecentTracksQueryInput, RecentTracksPageSchema),
15937
- /**
15938
- * Batched co-moving group listing — the Groups feed. Same merge/cursor
15939
- * contract as {@link listRecentTracks}. A group is a sealed partition of
15940
- * one session; `getGroup` is the detail with members.
15941
- */
15942
- listGroups: require_sleep.method(ListGroupsQueryInput, ListGroupsPageSchema),
15943
- getGroup: require_sleep.method(zod.z.object({
15944
- deviceId: zod.z.number(),
15945
- groupId: zod.z.string().min(1)
15946
- }), AnalyticsGroupDetailSchema.nullable()),
15947
- clearTracks: require_sleep.method(zod.z.object({ deviceId: zod.z.number() }), zod.z.void(), {
15948
- kind: "mutation",
15949
- auth: "admin"
15950
- }),
15951
- getMotionEvents: require_sleep.method(DeviceEventQueryInput, zod.z.array(MotionEventSchema).readonly()),
15952
- getObjectEvents: require_sleep.method(ObjectEventQueryInput, zod.z.array(ObjectEventSchema).readonly()),
15953
- getAudioEvents: require_sleep.method(DeviceEventQueryInput, zod.z.array(AudioEventSchema).readonly()),
15954
- /**
15955
- * Every event kind the device can produce: built-ins (motion + audio),
15956
- * detection classes actually observed for the device (from the track
15957
- * history), and sensor kinds contributed by LINKED devices (resolved via
15958
- * `device-manager.getLinkedDevices`, mapped through `EVENT_KIND_BY_CAP`).
15959
- */
15960
- listEventKinds: require_sleep.method(zod.z.object({ deviceId: zod.z.number() }), zod.z.array(EventKindDescriptorSchema).readonly()),
15961
- /**
15962
- * The same answer for many cameras in ONE call.
15963
- *
15964
- * `listEventKinds` is the slowest per-device query on the hub — measured
15965
- * at ~100 ms against 6-11 ms for its neighbours — because composing it
15966
- * costs a `getCameraStatus`, a `getLinkedDevices` and one `getBindings`
15967
- * per linked device. The viewer asks for it once per camera at first
15968
- * paint, so twelve cameras paid twelve of those round-trips on top of the
15969
- * per-camera cost.
15970
- *
15971
- * Batched, the camera statuses come from ONE `getCameraStatuses` instead
15972
- * of N, and the per-device composition runs concurrently.
15973
- *
15974
- * Per-device rather than pre-merged on purpose: a caller that renders one
15975
- * camera's lanes needs to know WHICH camera a kind came from, and merging
15976
- * is three lines the caller can do. `listEventKinds` stays for
15977
- * single-device callers.
15978
- */
15979
- listEventKindsBatch: require_sleep.method(zod.z.object({ deviceIds: zod.z.array(zod.z.number()).min(1).max(200) }), zod.z.array(EventKindsForDeviceSchema).readonly()),
15980
- /**
15981
- * Sensor-event history for a camera: state changes of LINKED sensor
15982
- * devices, attributed to the camera at ingest time (one row per linked
15983
- * camera). Mirrors `getAudioEvents` query semantics; `kinds` narrows to
15984
- * a kind subset.
15985
- */
15986
- getSensorEvents: require_sleep.method(zod.z.object({
15987
- deviceId: zod.z.number(),
15988
- since: zod.z.number().optional(),
15989
- until: zod.z.number().optional(),
15990
- kinds: zod.z.array(zod.z.string()).optional(),
15991
- limit: zod.z.number().int().min(1).max(MAX_EVENT_QUERY_LIMIT).default(DEFAULT_EVENT_QUERY_LIMIT)
15992
- }), zod.z.array(SensorEventSchema).readonly()),
15993
- /**
15994
- * Importance-ranked highlights for a device+window. Queries completed
15995
- * tracks by (deviceId, firstSeen ∈ [since,until]), scores each (or reuses
15996
- * the persisted score), filters by minImportance/classFilter, orders by
15997
- * importance desc, and returns up to `limit` compact key events mapped to
15998
- * each track's best event. Legacy tracks lacking a persisted score are
15999
- * scored on-read (no write). Degrades to `[]` on error.
16000
- */
16001
- getKeyEvents: require_sleep.method(KeyEventQueryInput, zod.z.array(KeyEventSchema).readonly()),
16002
- /** Server-side bucketed event counts for the 24-hour timeline.
16003
- * Returns one entry per non-empty bucket; empty buckets are omitted. */
16004
- getEventDensity: require_sleep.method(zod.z.object({
16005
- deviceId: zod.z.number(),
16006
- since: zod.z.number(),
16007
- until: zod.z.number(),
16008
- bucketMs: zod.z.number().int().positive()
16009
- }), zod.z.array(zod.z.object({
16010
- bucketStart: zod.z.number(),
16011
- motion: zod.z.number().int(),
16012
- object: zod.z.number().int(),
16013
- audio: zod.z.number().int()
16014
- })).readonly()),
16015
- /**
16016
- * @deprecated Prefer `pruneTracksBefore` — the track is the ROOT of the
16017
- * analytics model and retention must cascade from it (design §5.1). This
16018
- * event-only prune leaves orphaned tracks/faces/plates/embeddings behind.
16019
- * Retained as a compat shim for the Phase-B3 recorder orchestration caller,
16020
- * which prunes events to keep history aligned with available footage and
16021
- * reads the per-kind counts. Delete all events (motion + object + audio)
16022
- * for the given device older than `cutoffMs` (exclusive) + their thumbnails
16023
- * in lockstep; returns per-kind deleted counts.
16024
- */
16025
- pruneEventsBefore: require_sleep.method(zod.z.object({
16026
- deviceId: zod.z.number(),
16027
- cutoffMs: zod.z.number()
16028
- }), zod.z.object({
16029
- motion: zod.z.number().int(),
16030
- object: zod.z.number().int(),
16031
- audio: zod.z.number().int()
16032
- }), {
16033
- kind: "mutation",
16034
- auth: "admin"
16035
- }),
16036
- /**
16037
- * Track-centric retention entry point (design §5.1). Selects every
16038
- * persisted track for the device whose `lastSeen < cutoffMs` (paged) and
16039
- * runs the extensible whole-track deletion cascade (design §3): object
16040
- * events + their media, track/face/plate-owned media, unassigned face
16041
- * reads, per-track CLIP embeddings, then the track root LAST. ENROLLED
16042
- * (assigned) faces/plates and `ownerKind:'identity'` media are exempt —
16043
- * the durable matching gallery always persists. Fires the per-track
16044
- * live-state cleanup so a pruned track can't linger in dispatch/overlay
16045
- * state. Returns per-family deleted counts (`tracks` authoritative).
16046
- *
16047
- * Replaces `pruneEventsBefore` as the correct time-based retention prune.
16048
- */
16049
- pruneTracksBefore: require_sleep.method(zod.z.object({
16050
- deviceId: zod.z.number(),
16051
- cutoffMs: zod.z.number()
16052
- }), TrackCascadeCountsSchema, {
16053
- kind: "mutation",
16054
- auth: "admin"
16055
- }),
16056
- /**
16057
- * Operator "clean slate" for a device (design §5.3): prune EVERY track for
16058
- * the device via the same cascade as `pruneTracksBefore` with `cutoffMs =
16059
- * now`. One call per device — no client-side track enumeration. Enrolled
16060
- * gallery + identity media are exempt (design §4). Returns per-family
16061
- * deleted counts.
16062
- */
16063
- wipeAllAnalytics: require_sleep.method(zod.z.object({ deviceId: zod.z.number() }), TrackCascadeCountsSchema, {
16064
- kind: "mutation",
16065
- auth: "admin"
16066
- }),
16067
- /**
16068
- * Disk-wins reconcile for one camera. Drops media index rows whose blobs
16069
- * are gone, then cascades tracks (including favourited and staging) that
16070
- * have no remaining files. Enrolled identity/vehicle/scene media is never
16071
- * probed. Trackless motion/audio events with no remaining file are dropped,
16072
- * including snapshot-less rows.
16073
- */
16074
- reconcileFromDisk: require_sleep.method(zod.z.object({ deviceId: zod.z.number() }), DiskReconcileCountsSchema, {
16075
- kind: "mutation",
16076
- auth: "admin"
16077
- }),
16078
- /**
16079
- * Delete whole tracks (object events) by id for the given device,
16080
- * cascading their media in lockstep. Returns the number of tracks
16081
- * actually deleted plus the ids that could not be removed.
16082
- *
16083
- * Operator-driven from the DI Events page (batch delete). Routes through
16084
- * the same widened track-deletion cascade (design §5.2).
16085
- */
16086
- deleteTracks: require_sleep.method(zod.z.object({
16087
- deviceId: zod.z.number(),
16088
- trackIds: zod.z.array(zod.z.string()).min(1)
16089
- }), zod.z.object({
16090
- deleted: zod.z.number().int(),
16091
- failed: zod.z.array(zod.z.string()).readonly()
16092
- }), {
16093
- kind: "mutation",
16094
- auth: "admin"
16095
- }),
16096
- /**
16097
- * Set the per-track operator flags (`markForTrain`, `debug`, `favourited`) on ONE track.
16098
- * The patch is PARTIAL — an omitted key is left untouched — because the
16099
- * three surfaces that write it (admin Events grid, viewer track detail,
16100
- * viewer cluster detail) each own one toggle and must not clobber the other.
16101
- *
16102
- * Writes the track ROW: `markForTrain`/`debug` are per-TRACK state, so they
16103
- * live where `label` and `importance` live, not in any per-device settings
16104
- * store. Updates the in-RAM active track too, so a flag set on a live track
16105
- * survives its expiry-time persist.
16106
- *
16107
- * `auth: 'protected'` (the default), NOT `admin`: the viewer is an
16108
- * authenticated non-admin surface and two of the three call sites are
16109
- * there. The note that used to sit here said to revisit this the day a flag
16110
- * gained an effect that costs storage, and D81 is that day — `markForTrain`
16111
- * now pins. It STAYS protected, and the reason is that the alternative
16112
- * makes the feature pointless: marking a track is something you do while
16113
- * looking at it, on the surface you were already looking at it on, and that
16114
- * surface is the viewer. What the storage cost gets instead is a BOUND — a
16115
- * per-device pin budget enforced in the body, refusing a new pin past the
16116
- * limit while always allowing un-marking. `deleteTracks` next door is still
16117
- * admin, because destroying evidence and preserving it are not symmetric.
16118
- *
16119
- * `markForTrain` writes the retrain LIFECYCLE, not a boolean column: `true`
16120
- * is `none → staging`, `false` is `staging → none`. A track already
16121
- * `trained` refuses BOTH — its frames are copies inside the retrain dataset
16122
- * and re-staging it from a generic toggle is how the same material gets
16123
- * annotated twice under two ground truths. Returning a trained track to
16124
- * staging is a deliberate action of the retrain page, which is also the only
16125
- * thing that produces `trained` in the first place.
16126
- *
16127
- * Returns the RESOLVED state of both flags (absent → `false`) plus the
16128
- * `retrainStatus` they were derived from, so a caller can drive its toggle
16129
- * — and render a `trained` badge — without a re-fetch. Rejects an unknown
16130
- * track, a new staging mark on a device already holding its full budget, and
16131
- * any `markForTrain` write against a trained track.
16132
- */
16133
- setTrackFlags: require_sleep.method(zod.z.object({
16134
- /** Log/audit scope only — the trackId is globally unique on its own. */
16135
- deviceId: zod.z.number(),
16136
- trackId: zod.z.string(),
16137
- flags: TrackFlagsPatchSchema
16138
- }), TrackFlagsSchema, { kind: "mutation" }),
16139
- /**
16140
- * Durable event-store footprint for the management UI: event rows
16141
- * (motion + object + audio) counted per camera + total, plus the
16142
- * event-owned media bytes on disk per camera + total. Stat/count-based,
16143
- * computed on demand.
16144
- */
16145
- getEventStoreFootprint: require_sleep.method(zod.z.object({}), EventStoreFootprintSchema, {
16146
- kind: "query",
16147
- auth: "admin"
16148
- }),
16149
- /**
16150
- * Cluster-wide prune of events older than `olderThanMs` (exclusive) across
16151
- * every camera, deleting each event's media in lockstep. Logged to the
16152
- * events ops-log with `reason` (default `'retention'`). Returns the summed
16153
- * per-kind deleted counts.
16154
- */
16155
- pruneEvents: require_sleep.method(zod.z.object({
16156
- olderThanMs: zod.z.number(),
16157
- reason: OpsLogReasonSchema.optional()
16158
- }), EventPruneCountsSchema, {
16159
- kind: "mutation",
16160
- auth: "admin"
16161
- }),
16162
- /**
16163
- * Manually delete EVERY event (motion + object + audio) for one camera and
16164
- * its event-owned media in lockstep. Logged to the events ops-log as
16165
- * `op:'manual-delete', reason:'manual'`. Destructive — the admin UI guards
16166
- * it behind a confirm.
16167
- */
16168
- deleteDeviceEvents: require_sleep.method(zod.z.object({ deviceId: zod.z.number() }), EventPruneCountsSchema, {
16169
- kind: "mutation",
16170
- auth: "admin"
16171
- }),
16172
- /** The events ops-log rows (newest-first), optionally scoped to one camera.
16173
- * Backed by a declared pipeline-analytics SQLite collection. */
16174
- /** Internal migration-participant lease. It drains active MediaStore
16175
- * writes and refuses new ones without changing analytics bindings. */
16176
- pauseForStorageMigration: require_sleep.method(StorageMigrationLeaseInputSchema, zod.z.object({ paused: zod.z.literal(true) }), {
16177
- kind: "mutation",
16178
- auth: "admin"
16179
- }),
16180
- resumeForStorageMigration: require_sleep.method(StorageMigrationLeaseInputSchema, zod.z.object({ resumed: zod.z.literal(true) }), {
16181
- kind: "mutation",
16182
- auth: "admin"
16183
- }),
16184
- /** Drops cached location roots after the storage coordinator repoints a
16185
- * default so future event-media writes use the new root. */
16186
- refreshStorageLocationsForMigration: require_sleep.method(StorageMigrationLeaseInputSchema, zod.z.object({ refreshed: zod.z.literal(true) }), {
16187
- kind: "mutation",
16188
- auth: "admin"
16189
- }),
16190
- startStorageMigrationMove: require_sleep.method(StorageMigrationMediaMoveInputSchema, zod.z.object({ jobId: zod.z.string() }), {
16191
- kind: "mutation",
16192
- auth: "admin"
16193
- }),
16194
- getStorageMigrationMoveStatus: require_sleep.method(zod.z.object({ jobId: zod.z.string() }), RelocateJobSchema.nullable(), { auth: "admin" }),
16195
- cancelStorageMigrationMove: require_sleep.method(zod.z.object({ jobId: zod.z.string() }), zod.z.object({ cancelled: zod.z.boolean() }), {
16196
- kind: "mutation",
16197
- auth: "admin"
16198
- }),
16199
- listOpsLog: require_sleep.method(OpsLogQueryInputSchema, zod.z.array(OpsLogEntrySchema).readonly(), {
16200
- kind: "query",
16201
- auth: "admin"
16202
- }),
16203
- /**
16204
- * The CHEAP QUESTION, asked before any media moves: how big is the dataset
16205
- * the marked (`markForTrain`) tracks would produce?
16206
- *
16207
- * Answered from media INDEX rows only — key, kind, size, timestamp — so it
16208
- * costs ~2 KB of reads per track and no blob reads at all. The measured harm
16209
- * behind D56 was a bulk pass that read and base64'd every blob a track owned
16210
- * before deciding anything, taking hub-main to 82 s busy out of 120; an
16211
- * export is that same I/O shape, so it inherits the same discipline: know
16212
- * the size, then decide.
16213
- *
16214
- * `truncated` reports that more marked tracks exist than one pass carries.
16215
- * Empty `deviceIds` ⇒ every device that has marked tracks.
16216
- */
16217
- getTrainingExportSummary: require_sleep.method(zod.z.object({ deviceIds: zod.z.array(zod.z.number()).optional() }), TrainingExportSummarySchema, {
16218
- kind: "query",
16219
- auth: "admin"
16220
- }),
16221
- /**
16222
- * Where to download the dataset archive.
16223
- *
16224
- * The BYTES do not come back through this cap — they come from the returned
16225
- * data-plane URL, which streams a tar built entry by entry. A multi-gigabyte
16226
- * archive base64'd through a unary RPC envelope would be held whole in
16227
- * memory twice on a hub this repo has already OOM'd once (D9/D18 are the
16228
- * same lesson about frames). `getDownloadUrl` on `recordingExport` is the
16229
- * precedent, and this follows it deliberately.
16230
- *
16231
- * The archive contains a `manifest.json` FIRST, then the stored media
16232
- * VERBATIM under `tracks/<deviceId>/<trackId>/…`. No crop is derived and no
16233
- * model is run: a training set's pixels must be the pixels the pipeline saw.
16234
- */
16235
- getTrainingExportUrl: require_sleep.method(zod.z.object({ deviceIds: zod.z.array(zod.z.number()).optional() }), zod.z.object({ url: zod.z.string() }), {
16236
- kind: "query",
16237
- auth: "admin"
16238
- }),
16239
- /**
16240
- * The staging worklist for one camera, or for every camera that has one.
16241
- *
16242
- * Fetched ON DEMAND, over the staging set only — the page never scans
16243
- * history, because making the working set small is the entire purpose of
16244
- * the mark. Each row carries how many frames the dataset already holds from
16245
- * the track and how many subjects were annotated on them, so
16246
- * `frameCount: 0` reads as "still to work" without a second call per track.
16247
- *
16248
- * `auth: 'admin'`, unlike the viewer-level mark itself: marking a track is
16249
- * curation you do while looking at it, but building the training set the
16250
- * fleet's models are fine-tuned on is not.
16251
- */
16252
- listRetrainStaging: require_sleep.method(zod.z.object({
16253
- /** Empty ⇒ every camera that has staging tracks. A LIST, not a single
16254
- * `deviceId`, deliberately: `deviceId` would make this device-bound and
16255
- * route it at one camera's owner, and "every camera" would stop being
16256
- * expressible at all. */
16257
- deviceIds: zod.z.array(zod.z.number()).optional(),
16258
- limit: zod.z.number().int().min(1).max(500).optional()
16259
- }), zod.z.array(RetrainTrackSchema).readonly(), {
16260
- kind: "query",
16261
- auth: "admin"
16262
- }),
16263
- /**
16264
- * What a track can contribute, and what it already has.
16265
- *
16266
- * `candidates` are the track's whole, unannotated frames — index rows only,
16267
- * so this is cheap. `copies` are the frames already inside the dataset, and
16268
- * a candidate whose copy exists is marked `copied: true`: selecting it again
16269
- * is free and CANNOT fail, whatever became of the original.
16270
- *
16271
- * A crop, a thumbnail and `fullFrameBoxed` are never candidates. The last
16272
- * one matters most: it has the model's own rectangle burned into the pixels,
16273
- * and a detector trained on it learns to find a green line.
16274
- */
16275
- listRetrainFrames: require_sleep.method(zod.z.object({ trackId: zod.z.string() }), RetrainFrameListSchema, {
16276
- kind: "query",
16277
- auth: "admin"
16278
- }),
16279
- /**
16280
- * COPY-ON-SELECT — the write that makes `trained` safe to evict.
16281
- *
16282
- * Selecting a frame copies its bytes into retrain storage immediately: not
16283
- * a reference, not a lease. Once the copy exists the dataset no longer
16284
- * depends on the track's media, which is exactly what lets D81 hand a
16285
- * `trained` track back to retention.
16286
- *
16287
- * The order inside is load-bearing and is pinned by a test: an EXISTING
16288
- * copy is returned without touching the source, so an original that
16289
- * evaporated blocks the selection of THAT ORIGINAL and never the copy
16290
- * already taken. Every refusal comes back named — a dropped selection is
16291
- * never silent, on the wire or in the log.
16292
- */
16293
- selectRetrainFrames: require_sleep.method(zod.z.object({
16294
- deviceId: zod.z.number(),
16295
- trackId: zod.z.string(),
16296
- mediaKeys: zod.z.array(zod.z.string()).min(1)
16297
- }), RetrainFrameSelectionSchema, {
16298
- kind: "mutation",
16299
- auth: "admin"
16300
- }),
16301
- /** Un-select a frame: its annotations go first, then the copy and its blob.
16302
- * Deliberately destructive and deliberately explicit — it is the only way
16303
- * a frame leaves the dataset before export. */
16304
- deselectRetrainFrame: require_sleep.method(zod.z.object({
16305
- deviceId: zod.z.number(),
16306
- trackId: zod.z.string(),
16307
- frameId: zod.z.string()
16308
- }), zod.z.object({
16309
- removed: zod.z.boolean(),
16310
- removedAnnotations: zod.z.number().int()
16311
- }), {
16312
- kind: "mutation",
16313
- auth: "admin"
16314
- }),
16315
- /**
16316
- * The pixels of ONE copied frame, base64.
16317
- *
16318
- * Through the cap rather than a data plane because it is genuinely one
16319
- * frame at a time, on demand, at human speed — the shape D9/D18 permit
16320
- * (what they forbid is frames crossing a boundary at frame RATE). The
16321
- * annotation canvas needs the image and its exact dimensions in the same
16322
- * answer: a canvas that places a normalised box against a size it guessed
16323
- * draws every box in the wrong place.
16324
- */
16325
- getRetrainFrameImage: require_sleep.method(zod.z.object({ frameId: zod.z.string() }), zod.z.object({
16326
- base64: zod.z.string(),
16327
- width: zod.z.number().int(),
16328
- height: zod.z.number().int()
16329
- }), {
16330
- kind: "query",
16331
- auth: "admin"
16332
- }),
16333
- /**
16334
- * Ask the pipeline what it sees, as a PROPOSAL.
16335
- *
16336
- * Runs through `pipelineRunner.runStatelessStep` on the COPIED frame, and
16337
- * every box comes back as a draft with `source: 'assist'` plus the model and
16338
- * score that produced it. The operator confirms, edits, adds and deletes;
16339
- * nothing is stored until `saveRetrainAnnotations`.
16340
- *
16341
- * For packages the request is `rfdetr-package` on the ZONE CROP at 0.35 —
16342
- * never the whole frame, where a package detector at that threshold proposes
16343
- * furniture. A package request with no zone is REFUSED rather than widened,
16344
- * because the silent widening would look like a bad model for as long as
16345
- * nobody checked which rectangle it ran on.
16346
- */
16347
- proposeRetrainAnnotations: require_sleep.method(zod.z.object({
16348
- deviceId: zod.z.number(),
16349
- trackId: zod.z.string(),
16350
- frameId: zod.z.string(),
16351
- subject: RetrainAssistSubjectSchema,
16352
- /** Which node runs it. Absent ⇒ wherever an unowned call lands. */
16353
- nodeId: zod.z.string().optional()
16354
- }), RetrainAssistResultSchema, {
16355
- kind: "mutation",
16356
- auth: "admin"
16357
- }),
16358
- /** Every annotation on a track, oldest first. */
16359
- listRetrainAnnotations: require_sleep.method(zod.z.object({ trackId: zod.z.string() }), zod.z.array(RetrainAnnotationSchema).readonly(), {
16360
- kind: "query",
16361
- auth: "admin"
16362
- }),
16363
- /**
16364
- * Replace EVERY annotation on one frame with the supplied set.
16365
- *
16366
- * Whole-frame replacement, not per-box upsert: the unit of ground truth is
16367
- * the frame, and "the operator deleted a box" must be the same durable
16368
- * outcome as "the operator never drew it". A per-box patch would let a frame
16369
- * keep a box the operator removed on a surface that only knew about the
16370
- * boxes it sent.
16371
- *
16372
- * Refuses a macro class typed into `label` or `subLabel` — the tiers are
16373
- * separate and the guard is at the WRITE, because a mixed taxonomy cannot
16374
- * be un-mixed by reading it.
16375
- */
16376
- saveRetrainAnnotations: require_sleep.method(zod.z.object({
16377
- deviceId: zod.z.number(),
16378
- trackId: zod.z.string(),
16379
- frameId: zod.z.string(),
16380
- annotations: zod.z.array(RetrainAnnotationDraftSchema)
16381
- }), zod.z.array(RetrainAnnotationSchema).readonly(), {
16382
- kind: "mutation",
16383
- auth: "admin"
16384
- }),
16385
- /**
16386
- * Finish with a track: `staging → trained`. **The only writer of that
16387
- * state** — D81 shipped the column with it deliberately unreachable.
16388
- *
16389
- * Refuses a track the dataset holds no copies from. `trained` un-pins the
16390
- * track's media, so completing without a copy is a delete order for material
16391
- * nothing ever extracted anything from; that refusal IS the safety argument
16392
- * of D81, expressed as a precondition.
16393
- */
16394
- completeRetrainTrack: require_sleep.method(zod.z.object({
16395
- deviceId: zod.z.number(),
16396
- trackId: zod.z.string()
16397
- }), RetrainTransitionResultSchema, {
16398
- kind: "mutation",
16399
- auth: "admin"
16400
- }),
16401
- /**
16402
- * The deliberate return: `trained → staging`, for the rare case.
16403
- *
16404
- * The generic `setTrackFlags` toggle refuses this in both directions by
16405
- * design (D81) — re-staging from a checkbox is how the same material gets
16406
- * annotated twice under two ground truths. Doing it here means the operator
16407
- * is looking at the annotations that already exist while they decide, and
16408
- * those annotations are LEFT ALONE: "put this back" must not be a
16409
- * destructive act wearing a navigational name.
16410
- */
16411
- restageRetrainTrack: require_sleep.method(zod.z.object({
16412
- deviceId: zod.z.number(),
16413
- trackId: zod.z.string()
16414
- }), RetrainTransitionResultSchema, {
16415
- kind: "mutation",
16416
- auth: "admin"
16417
- }),
16418
- /**
16419
- * Where to download the ANNOTATED dataset.
16420
- *
16421
- * The sibling of `getTrainingExportUrl` and deliberately not the same
16422
- * archive: that one streams a marked track's stored media verbatim, this one
16423
- * streams the retrain COPIES plus an `annotations.json` carrying, for every
16424
- * subject, the canonical full-frame box AND the geometry derived for each
16425
- * model shape (letterboxed root / zone-cropped package / subject-cropped
16426
- * classifier). Derived at export, never stored — one box in, three shapes
16427
- * out, so two crops of the same subject can never end up in one feature
16428
- * space (D52).
16429
- */
16430
- getRetrainExportUrl: require_sleep.method(zod.z.object({ deviceIds: zod.z.array(zod.z.number()).optional() }), zod.z.object({ url: zod.z.string() }), {
16431
- kind: "query",
16432
- auth: "admin"
16433
- }),
16434
- getEventMedia: require_sleep.method(zod.z.object({
16435
- eventId: zod.z.string(),
16436
- kind: MediaFileKindEnum.optional(),
16437
- deviceId: zod.z.number()
16438
- }), zod.z.array(MediaFileSchema).readonly()),
16439
- /** All media rows owned by a track. `kinds` narrows to a kind subset so a
16440
- * client can fetch the SMALL display variants on open and pull the
16441
- * multi-MB native variants only on demand (mirrors `getEventMedia.kind`).
16442
- * Absent ⇒ every kind (back-compat). */
16443
- getTrackMedia: require_sleep.method(zod.z.object({
16444
- trackId: zod.z.string(),
16445
- kinds: zod.z.array(MediaFileKindEnum).optional(),
16446
- deviceId: zod.z.number()
16447
- }), zod.z.array(MediaFileSchema).readonly()),
16448
- /**
16449
- * What media a track HAS, without any of it.
16450
- *
16451
- * The detail view needs the shape of a track's media to build its strip —
16452
- * which kinds exist, in what order, at what size — and then wants each tile
16453
- * fetched as an image, not as base64 inside this response. Measured: the
16454
- * full `getTrackMedia` is 5.3-7.7 MB and blocks the view; this manifest is
16455
- * ~2 KB.
16456
- *
16457
- * It also restores a fact a `kinds` filter destroys: filtering
16458
- * `getTrackMedia` drops whole ROWS, taking `kind` and `sizeBytes` with
16459
- * them, so a client that fetched only the small variants could no longer
16460
- * tell a full-resolution variant existed — and the affordance that opens it
16461
- * would silently disappear.
16462
- */
16463
- listTrackMedia: require_sleep.method(zod.z.object({
16464
- trackId: zod.z.string(),
16465
- deviceId: zod.z.number()
16466
- }), zod.z.array(MediaFileInfoSchema).readonly()),
16467
- /**
16468
- * Search object events by text query using CLIP cosine similarity.
16469
- * Encodes `text` via the `embedding-encoder` cap, queries the
16470
- * `ObjectEmbeddingStore` with optional prefilters, ranks all matching
16471
- * embeddings by cosine similarity, and joins winners to their
16472
- * ObjectEvents by trackId. Returns up to `limit` events scored ≥
16473
- * `minScore`, sorted descending by score.
16474
- */
16475
- searchObjectEvents: require_sleep.method(SearchObjectEventsInput, zod.z.array(ScoredObjectEventSchema).readonly()),
16476
- wipeObjectEmbeddings: require_sleep.method(zod.z.object({}), WipeObjectEmbeddingsResultSchema, {
16477
- kind: "mutation",
16478
- auth: "admin"
16479
- }),
16480
- rebuildObjectEmbeddings: require_sleep.method(RebuildObjectEmbeddingsInput, RebuildObjectEmbeddingsResultSchema, {
16481
- kind: "mutation",
16482
- auth: "admin"
16483
- }),
16484
- getObjectEmbeddingRebuildStatus: require_sleep.method(zod.z.object({}), RebuildStatusSchema)
16485
- },
16486
- events: {
16487
- /**
16488
- * Enriched frame emitted after refinement — the live-overlay source of
16489
- * truth (two-plane re-injection). Carries the frame's detections in the
16490
- * `ObjectDetection` wire shape: first-level roots (with track info +
16491
- * enrichment labels) plus synthesized `kind:'detail'` face/plate entries
16492
- * re-projected from per-track detail state, so stream overlays render
16493
- * boxes + recognized names without querying full Track state.
16494
- */
16495
- onFrameTracked: { data: zod.z.object({
16496
- deviceId: zod.z.number(),
16497
- timestamp: zod.z.number(),
16498
- frameWidth: zod.z.number(),
16499
- frameHeight: zod.z.number(),
16500
- detections: zod.z.array(OverlayDetectionSchema).readonly()
16501
- }) },
16502
- /** Track entered active state (first-seen). */
16503
- onTrackStarted: { data: zod.z.object({
16504
- deviceId: zod.z.number(),
16505
- trackId: zod.z.string(),
16506
- className: zod.z.string()
16507
- }) },
16508
- /** Track expired (TTL reached after last detection). */
16509
- onTrackEnded: { data: zod.z.object({
16510
- deviceId: zod.z.number(),
16511
- trackId: zod.z.string(),
16512
- className: zod.z.string(),
16513
- durationMs: zod.z.number()
16514
- }) },
16515
- /** Canonical "something happened at device X" event, per-kind. */
16516
- onDetectionEvent: { data: zod.z.object({
16517
- deviceId: zod.z.number(),
16518
- kind: EventKindSchema,
16519
- eventId: zod.z.string(),
16520
- timestamp: zod.z.number()
16521
- }) }
16522
- }
16523
- };
16524
- //#endregion
16525
- //#region src/capabilities/pipeline-executor.cap.ts
16526
- /**
16527
- * Reference to the frame's retained NATIVE surface + the parent crop's placement
16528
- * within the frame, so the executor can re-cut a leaf child ROI at native
16529
- * resolution on the detail plane. See the `runPipeline` `nativeCropRef` field.
16530
- */
16531
- var NativeCropRefSchema = zod.z.object({
16532
- /** Handle keying the retained native surface (node-pinned to its owner). */
16533
- handle: require_sleep.FrameHandleSchema,
16534
- /** The parent crop's padded/clamped rectangle in FRAME-space pixels. */
16535
- cropFrameSpace: zod.z.object({
16536
- x: zod.z.number(),
16537
- y: zod.z.number(),
16538
- w: zod.z.number(),
16539
- h: zod.z.number()
16540
- })
16541
- });
16542
- zod.z.object({
16543
- crop: zod.z.object({
16544
- left: zod.z.number(),
16545
- top: zod.z.number(),
16546
- width: zod.z.number().positive(),
16547
- height: zod.z.number().positive()
16548
- }).optional(),
16549
- content: zod.z.object({
16550
- width: zod.z.number().int().positive(),
16551
- height: zod.z.number().int().positive()
16552
- }),
16553
- fit: zod.z.enum(["stretch", "contain"]),
16554
- format: zod.z.enum([
16555
- "rgb",
16556
- "gray",
16557
- "jpeg"
16558
- ])
16559
- });
16560
- var FrameRefSchema = zod.z.object({
16561
- registryId: zod.z.string().min(1),
16562
- id: zod.z.string().min(1),
16563
- width: zod.z.number().int().positive(),
16564
- height: zod.z.number().int().positive(),
16565
- format: zod.z.enum(["rgb", "gray"]),
16566
- timestamp: zod.z.number(),
16567
- capturedAt: zod.z.number().optional()
16568
- });
16569
- var ModelFormatSchema$1 = zod.z.enum([
16570
- "onnx",
16571
- "coreml",
16572
- "openvino",
16573
- "tflite",
16574
- "pt",
16575
- "gguf"
16576
- ]);
16577
- var PipelineSlotSchema = zod.z.enum([
16578
- "detector",
16579
- "cropper",
16580
- "classifier",
16581
- "refiner",
16582
- "audio-classifier"
16583
- ]);
16584
- var PipelineEngineChoiceSchema = zod.z.object({
16585
- runtime: zod.z.enum(["node", "python"]),
16586
- backend: zod.z.string(),
16587
- format: ModelFormatSchema$1,
16588
- device: zod.z.string().optional()
16589
- });
16590
- var EngineDeviceInfoSchema = zod.z.object({
16591
- id: zod.z.string(),
16592
- label: zod.z.string(),
16593
- description: zod.z.string().optional()
16475
+ projection: zod.z.enum(["full", "slim"]).optional()
16594
16476
  });
16595
- var AvailableEngineSchema = zod.z.object({
16596
- engine: PipelineEngineChoiceSchema,
16597
- devices: zod.z.array(EngineDeviceInfoSchema).readonly(),
16598
- 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()
16599
16495
  });
16600
- var PipelineDefaultStepSchema = zod.z.lazy(() => zod.z.object({
16601
- addonId: zod.z.string(),
16602
- addonName: zod.z.string(),
16603
- slot: PipelineSlotSchema,
16604
- inputClasses: zod.z.array(zod.z.string()).readonly(),
16605
- outputClasses: zod.z.array(zod.z.string()).readonly(),
16606
- enabled: zod.z.boolean(),
16607
- modelId: zod.z.string(),
16608
- children: zod.z.array(PipelineDefaultStepSchema).readonly(),
16609
- group: zod.z.string().optional(),
16610
- settings: zod.z.record(zod.z.string(), zod.z.unknown()).optional()
16611
- }));
16612
- var PipelineTemplateStepSchema = zod.z.lazy(() => zod.z.object({
16613
- addonId: zod.z.string(),
16614
- enabled: zod.z.boolean(),
16615
- modelId: zod.z.string(),
16616
- children: zod.z.array(PipelineTemplateStepSchema).readonly(),
16617
- settings: zod.z.record(zod.z.string(), zod.z.unknown()).optional()
16618
- }));
16619
- var PipelineTemplateSchema$1 = zod.z.object({
16620
- id: zod.z.string(),
16621
- name: zod.z.string(),
16622
- createdAt: zod.z.string(),
16623
- updatedAt: zod.z.string(),
16624
- engine: PipelineEngineChoiceSchema,
16625
- 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()
16626
16501
  });
16627
- 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({
16628
16505
  id: zod.z.string(),
16629
- name: zod.z.string(),
16630
- formats: zod.z.record(zod.z.string(), zod.z.object({
16631
- downloaded: zod.z.boolean(),
16632
- sizeMB: zod.z.number()
16633
- })),
16634
- group: ModelVariantGroupSchema.optional(),
16635
- legacy: zod.z.boolean().optional(),
16636
- 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()
16637
16517
  });
16638
- var ConfigFieldBridge = zod.z.custom();
16639
- var PipelineAddonSchemaSchema = zod.z.object({
16640
- id: zod.z.string(),
16641
- name: zod.z.string(),
16642
- slot: PipelineSlotSchema,
16643
- inputClasses: zod.z.array(zod.z.string()).readonly(),
16644
- outputClasses: zod.z.array(zod.z.string()).readonly(),
16645
- childSlots: zod.z.array(PipelineSlotSchema).readonly(),
16646
- models: zod.z.array(PipelineModelOptionSchema).readonly(),
16647
- defaultModelId: zod.z.string(),
16648
- defaultModelIdByFormat: zod.z.record(zod.z.string(), zod.z.string()).optional(),
16649
- enabledByDefault: zod.z.boolean().optional(),
16650
- backfillIntoExistingOverrides: zod.z.boolean().optional(),
16651
- defaultConfidence: zod.z.number(),
16652
- group: zod.z.string().optional(),
16653
- 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()
16654
16525
  });
16655
- var PipelineSlotSchemaSchema = zod.z.object({
16656
- id: PipelineSlotSchema,
16657
- label: zod.z.string(),
16658
- priority: zod.z.number(),
16659
- parentSlot: PipelineSlotSchema.nullable(),
16660
- 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()
16661
16537
  });
16662
- var PipelineSchemaSchema = zod.z.object({
16663
- availableEngines: zod.z.array(AvailableEngineSchema).readonly(),
16664
- selectedEngine: PipelineEngineChoiceSchema,
16665
- 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()
16666
16541
  });
16667
- var EngineProvisioningSchema = zod.z.object({
16668
- runtimeId: zod.z.enum([
16669
- "onnx",
16670
- "openvino",
16671
- "coreml",
16672
- "edgetpu"
16673
- ]).nullable(),
16674
- device: zod.z.string().nullable(),
16675
- state: zod.z.enum([
16676
- "idle",
16677
- "installing",
16678
- "verifying",
16679
- "ready",
16680
- "failed"
16681
- ]),
16682
- progress: zod.z.number().optional(),
16683
- error: zod.z.string().optional(),
16684
- nextRetryAt: zod.z.number().optional(),
16685
- /**
16686
- * Gate A (config-correctness gate at engine change): human-readable
16687
- * config issues surfaced EAGERLY when the node's engine changes — model
16688
- * substitutions ("chose X, running Y") and zero-build steps ("no model
16689
- * has a <format> build"). Additive/optional: informational only, never
16690
- * enforced here — `assertEngineReady` (readiness) still gates inference.
16691
- * Absent/empty when the node-default tree resolves cleanly.
16692
- */
16693
- 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()
16694
16553
  });
16695
- var PipelineStepInputSchema = zod.z.lazy(() => zod.z.object({
16696
- addonId: zod.z.string(),
16697
- modelId: zod.z.string().optional(),
16698
- enabled: zod.z.boolean().default(true),
16699
- children: zod.z.array(PipelineStepInputSchema).optional(),
16700
- settings: zod.z.record(zod.z.string(), zod.z.unknown()).optional(),
16701
- jumpDeviceKey: zod.z.string().optional()
16702
- }));
16703
- var ModelSubstitutionSchema = zod.z.object({
16704
- addonId: zod.z.string(),
16705
- chosen: zod.z.string(),
16706
- running: zod.z.string(),
16707
- 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
16708
16569
  });
16709
- var PipelineValidationIssueSchema = zod.z.object({
16710
- addonId: zod.z.string(),
16711
- kind: zod.z.enum(["unknown-addon", "no-format-build"]),
16712
- 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
16713
16577
  });
16714
- var PipelineValidationResultSchema = zod.z.object({
16715
- ok: zod.z.boolean(),
16716
- issues: zod.z.array(PipelineValidationIssueSchema).readonly(),
16717
- substitutions: zod.z.array(ModelSubstitutionSchema).readonly(),
16718
- /** The node's `currentEngine.format` this validation ran against. */
16719
- 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()
16720
16594
  });
16721
- var ReferenceImageEntrySchema = zod.z.object({
16722
- filename: zod.z.string(),
16723
- 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)
16724
16604
  });
16725
- var ReferenceImageBodySchema = zod.z.object({
16726
- base64: zod.z.string(),
16727
- 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()
16728
16620
  });
16729
- var ReferenceAudioEntrySchema = zod.z.object({
16730
- filename: zod.z.string(),
16731
- 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()
16732
16626
  });
16733
- var ReferenceAudioBodySchema = zod.z.object({ base64: zod.z.string() });
16734
- var AudioBackendSchema = zod.z.object({
16735
- id: zod.z.string(),
16736
- name: zod.z.string(),
16737
- description: zod.z.string(),
16738
- available: zod.z.boolean(),
16739
- /**
16740
- * Raw classifier labels this backend can emit (e.g. YAMNet's
16741
- * 521-class set or Apple SoundAnalysis's 303-class set). Used by
16742
- * the benchmark UI to populate the `enabledMicroClasses` filter
16743
- * specific to the selected backend without a separate fetch.
16744
- */
16745
- 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()
16746
16634
  });
16747
- var AudioCapabilitiesSchema = zod.z.object({
16748
- activeBackend: zod.z.string(),
16749
- availableBackends: zod.z.array(AudioBackendSchema).readonly(),
16750
- sampleRate: zod.z.number(),
16751
- 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()
16752
16640
  });
16753
- var DownloadModelResultSchema = zod.z.object({
16754
- filePath: zod.z.string(),
16755
- sizeMB: zod.z.number(),
16756
- 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()
16757
16646
  });
16758
16647
  /**
16759
- * Wrapper carrying a single test run's result. Replaces the legacy
16760
- * ad-hoc `{labels: [{className, originalClass, score}]}` shape with the
16761
- * canonical `AudioResult` from the Phase 6 output rework: one
16762
- * `AudioDetection` per class above `minScore`, top-N candidates in
16763
- * `debug.alternateLabels['audio-classifier']`, per-source timings in
16764
- * `debug.stepTimings`. The outer `success`/`error` fields stay so the
16765
- * benchmark UI can still report a clean failure when the classifier
16766
- * 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.
16767
16655
  */
16768
- var AudioTestResultSchema = zod.z.object({
16769
- success: zod.z.boolean(),
16770
- error: zod.z.string().optional(),
16771
- 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()
16772
16687
  });
16773
- var PipelineConfigBridge = zod.z.custom();
16774
- var ConfigUISchemaBridge = zod.z.custom();
16775
- var ConfigUISchemaNullableBridge = zod.z.custom();
16776
- var InferenceCapabilitiesBridge = zod.z.custom();
16777
- var ModelAvailabilityListBridge = zod.z.custom();
16778
- var PipelineRunResultBridge = zod.z.custom();
16779
16688
  /**
16780
- * Pipeline executor detection engine + configuration + inference API.
16689
+ * Result of emptying the CLIP index.
16781
16690
  *
16782
- * Merged from: pipeline-executor, pipeline-config, inference, detection-config.
16783
- * 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.
16784
16699
  *
16785
- * Per-device surface (DeviceSettingsContribution + the "is detection
16786
- * enabled for this camera?" toggle) lives on the paired
16787
- * `detection-pipeline` cap (device-scoped, singleton, wrapper
16788
- * defaultActive) same split pattern used by stream-broker /
16789
- * 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.
16790
16705
  */
16791
- var pipelineExecutorCapability = {
16792
- name: "pipeline-executor",
16793
- 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",
16794
16767
  mode: "singleton",
16768
+ kind: "wrapper",
16769
+ defaultActive: true,
16770
+ deviceTypes: [require_sleep.DeviceType.Camera],
16771
+ exposesDeviceSettings: true,
16795
16772
  methods: {
16796
- getAvailableEngines: require_sleep.method(zod.z.void(), zod.z.array(PipelineEngineChoiceSchema)),
16797
- getSelectedEngine: require_sleep.method(zod.z.void(), PipelineEngineChoiceSchema),
16798
- 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()),
16799
16853
  /**
16800
- * Per-node detection-engine provisioning snapshot. Returns the live
16801
- * state of the lazy runtime-provisioning machine on `nodeId`
16802
- * (idle / installing / verifying / ready / failed). The UI pairs this
16803
- * one-shot query with the `pipeline.engine-provisioning` live event
16804
- * (emitted on every transition) to drive a per-node "engine ready?"
16805
- * 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.
16806
16858
  */
16807
- getEngineProvisioning: require_sleep.method(zod.z.object({ nodeId: zod.z.string() }), EngineProvisioningSchema),
16808
- getVideoPipelineSteps: require_sleep.method(zod.z.void(), zod.z.record(zod.z.string(), zod.z.object({
16809
- modelId: zod.z.string(),
16810
- settings: zod.z.record(zod.z.string(), zod.z.unknown()).readonly()
16811
- }))),
16812
- setVideoPipelineSteps: require_sleep.method(zod.z.object({ steps: zod.z.record(zod.z.string(), zod.z.object({
16813
- modelId: zod.z.string(),
16814
- settings: zod.z.record(zod.z.string(), zod.z.unknown()).readonly()
16815
- })) }), 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
+ }), {
16816
16906
  kind: "mutation",
16817
16907
  auth: "admin"
16818
16908
  }),
16819
16909
  /**
16820
- * Clear THIS node's executor-side PER-DEVICE settings stores (the
16821
- * per-camera step overrides the object-detection root reads via
16822
- * `applyDeviceOverridesToTree`). `nodeId` is the ROUTING key the
16823
- * generated cap-router strips it (default `nodeIdMode: 'routing'`) and
16824
- * dispatches to that node, so the provider method runs ON the target
16825
- * 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).
16826
16919
  *
16827
- * This is the slimmed executor leg of the orchestrator's
16828
- * `resetNodePipelineDefaults` flow (which owns the real reset: node
16829
- * addonDefaults pins + per-camera orchestrator overrides). The legacy
16830
- * `resetToDefault` — which reset a persisted global step-tree seed
16831
- * nothing in the live per-camera path read — was removed together with
16832
- * that seed.
16920
+ * Replaces `pruneEventsBefore` as the correct time-based retention prune.
16833
16921
  */
16834
- clearDeviceOverrides: require_sleep.method(zod.z.object({ nodeId: zod.z.string() }), zod.z.object({
16835
- success: zod.z.literal(true),
16836
- 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()
16837
16965
  }), {
16838
16966
  kind: "mutation",
16839
16967
  auth: "admin"
16840
16968
  }),
16841
- getSchema: require_sleep.method(zod.z.void(), PipelineSchemaSchema),
16842
- getGlobalSteps: require_sleep.method(zod.z.void(), zod.z.array(PipelineDefaultStepSchema).readonly().nullable()),
16843
- getGlobalPipelineConfig: require_sleep.method(zod.z.void(), PipelineConfigBridge),
16844
- getOrchestratorConfigSchema: require_sleep.method(zod.z.void(), ConfigUISchemaBridge),
16845
16969
  /**
16846
- * Gate B (pre-init config-correctness gate). PURE COMPUTE against this
16847
- * node's `currentEngine.format`resolves `steps` the same way the
16848
- * runtime dispatch path would, and reports what WOULD happen without
16849
- * touching any node-global state. Called by the orchestrator at attach
16850
- * time (`attachOn`), node-pinned to the TARGET node, so config problems
16851
- * surface BEFORE `pipelineRunner.attachCamera` rather than at the first
16852
- * per-frame resolve. `ok` is false iff `issues` is non-empty (both
16853
- * `unknown-addon` and `no-format-build` are HARD issues); `substitutions`
16854
- * is informational (a degraded-but-loadable model swap) and never
16855
- * 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.
16856
17005
  */
16857
- validatePipeline: require_sleep.method(zod.z.object({ steps: zod.z.array(PipelineStepInputSchema) }), PipelineValidationResultSchema),
16858
- listTemplates: require_sleep.method(zod.z.void(), zod.z.array(PipelineTemplateSchema$1).readonly()),
16859
- saveTemplate: require_sleep.method(zod.z.object({
16860
- name: zod.z.string(),
16861
- steps: zod.z.array(PipelineTemplateStepSchema).readonly(),
16862
- engine: PipelineEngineChoiceSchema
16863
- }), PipelineTemplateSchema$1, { kind: "mutation" }),
16864
- updateTemplate: require_sleep.method(zod.z.object({
16865
- id: zod.z.string(),
16866
- name: zod.z.string().optional(),
16867
- steps: zod.z.array(PipelineTemplateStepSchema).readonly().optional()
16868
- }), PipelineTemplateSchema$1, { kind: "mutation" }),
16869
- deleteTemplate: require_sleep.method(zod.z.object({ id: zod.z.string() }), zod.z.void(), { kind: "mutation" }),
16870
- getCapabilities: require_sleep.method(zod.z.void(), InferenceCapabilitiesBridge),
16871
- getAddonModels: require_sleep.method(zod.z.object({ addonId: zod.z.string() }), ModelAvailabilityListBridge),
16872
- downloadModel: require_sleep.method(zod.z.object({
16873
- addonId: zod.z.string(),
16874
- modelId: zod.z.string(),
16875
- format: ModelFormatSchema$1
16876
- }), DownloadModelResultSchema, { kind: "mutation" }),
16877
- deleteModel: require_sleep.method(zod.z.object({
16878
- addonId: zod.z.string(),
16879
- modelId: zod.z.string(),
16880
- format: ModelFormatSchema$1
16881
- }), 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" }),
16882
17012
  /**
16883
- * Stateless single-frame execution. Callers (runner, benchmark) pass
16884
- * the complete `engine` + `steps` tree; the executor holds no state
16885
- * 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?
16886
17102
  *
16887
- * `engine` is optional during the migration window to preserve the
16888
- * legacy call shape used by existing benchmark code; once all
16889
- * 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.
16890
17109
  *
16891
- * Exactly one of `frame`, `frameRef`, `frameHandle`, `imageBase64`,
16892
- * `referenceImage` must be provided:
16893
- * - `frame`: runtime dispatch path (runner → decoded broker frame).
16894
- * Carries the raw buffer, dimensions, and format; the executor
16895
- * uses it directly without base64 round-tripping.
16896
- * - `frameHandle` (CB5): a zero-pixel shm `FrameHandle` for the SAME
16897
- * decoded frame. Both runner and executor are hub-local processes
16898
- * sharing `/dev/shm`, so the executor maps the named segment and
16899
- * reads the pixels back zero-copy — eliminating the ~1.2MB
16900
- * re-serialisation over UDS/MsgPack the `frame` path pays per call.
16901
- * High-risk: the FrameRing is a latest-wins seqlock with no
16902
- * refcount, so a recycled slot yields a null read; the executor
16903
- * then degrades to an empty result and the runner ships pixels via
16904
- * `frame` as the fallback (queue-depth gated on the runner side).
16905
- * - `imageBase64`: one-shot test path (benchmark ImageTab).
16906
- * - `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.
16907
17112
  */
16908
- runPipeline: require_sleep.method(zod.z.object({
16909
- engine: PipelineEngineChoiceSchema.optional(),
16910
- steps: zod.z.array(PipelineStepInputSchema).min(1),
16911
- frame: FrameInputSchema.optional(),
16912
- /**
16913
- * Process-local lazy frame. Valid only when caller and provider resolve
16914
- * in the same execution-group process; split/cross-node callers use
16915
- * `frame`/`image` inline compatibility instead.
16916
- */
16917
- frameRef: FrameRefSchema.optional(),
16918
- /**
16919
- * CB5 shm passthrough — a `FrameHandle` naming the same ring slot
16920
- * the decoded pixels live in. One more member of the one-of
16921
- * frame/frameHandle/image/imageBase64/referenceImage group.
16922
- */
16923
- frameHandle: require_sleep.FrameHandleSchema.optional(),
16924
- imageBase64: zod.z.string().optional(),
16925
- /**
16926
- * Binary JPEG bytes — preferred over `imageBase64` on internal
16927
- * hops (hub → forked worker via Moleculer MsgPack) because it
16928
- * skips the 33% base64 overhead + the per-call base64 decode on
16929
- * the detection-pipeline worker. Callers can pass either; exactly
16930
- * one of `frame`/`image`/`imageBase64`/`referenceImage` is required.
16931
- */
16932
- image: zod.z.instanceof(Uint8Array).optional(),
16933
- referenceImage: zod.z.string().optional(),
16934
- deviceId: zod.z.number().optional(),
16935
- sessionId: zod.z.string().optional(),
16936
- /**
16937
- * Execution plane. 'full' (default) runs the whole tree — benchmark,
16938
- * reference-image, and detail-subtree calls. 'frame' is the live
16939
- * per-frame dispatch: ONLY root-plane steps run; crop children
16940
- * (inputClasses ≠ null) are skipped and served per-track via
16941
- * pipelineRunner.runDetailSubtree (two-plane design).
16942
- */
16943
- plane: zod.z.enum(["full", "frame"]).optional(),
16944
- /**
16945
- * Inference-device selector (Phase 2 multi-device). Format
16946
- * `<backend>:<device>` (e.g. `openvino:gpu`, `edgetpu:usb`, `cpu`).
16947
- * Omitted ⇒ the runner's default device (current single-engine
16948
- * behaviour). Selects WHICH device pool of the node runs the call.
16949
- */
16950
- deviceKey: zod.z.string().optional(),
16951
- /**
16952
- * Two-plane NATIVE child-crop reference. Set by `runDetailSubtree` ONLY
16953
- * when the parent crop was resolved from the frame's retained NATIVE
16954
- * surface (a frameHandle HIT). Lets the executor re-cut a LEAF crop
16955
- * child's ROI (plate-ocr, face-embedding, leaf classifiers) at native
16956
- * resolution from that surface — the SAME quality path faces already
16957
- * had — instead of the downscaled parent tile. `handle` keys the native
16958
- * surface (node-pinned to its owner); `cropFrameSpace` is the parent
16959
- * crop's padded/clamped rectangle in FRAME-space pixels, used to compose
16960
- * the executor's crop-normalized child ROI back into frame-normalized
16961
- * coordinates. Auxiliary to the image source (`image`/`frame`/…), NOT one
16962
- * of the mutually-exclusive image inputs. Absent ⇒ tile-crop children
16963
- * (today's behaviour on the fallback path).
16964
- */
16965
- nativeCropRef: NativeCropRefSchema.optional()
16966
- }), 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
+ }),
16967
17117
  /**
16968
- * Batched run N raw frames packed into one cap call. The provider
16969
- * routes the batch through `SharedInferencePool.inferBatch`
16970
- * (`MSG_INFER_BATCH = 0x03`) so the IPC framing and JSON response
16971
- * envelope cost is amortised N:1 vs N concurrent `runPipeline`
16972
- * calls. Single root step + uniform model assumed; trees with crop
16973
- * children fall back to sequential execution.
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
+ }),
17229
+ /**
17230
+ * Ask the pipeline what it sees, as a PROPOSAL.
17231
+ *
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`.
16974
17236
  *
16975
- * Used by `scripts/bench-batch-style.mts` for batch benchmarking
16976
- * N frames in one call to amortise per-call IPC overhead.
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.
16977
17242
  */
16978
- runPipelineBatch: require_sleep.method(zod.z.object({
16979
- engine: PipelineEngineChoiceSchema.optional(),
16980
- steps: zod.z.array(PipelineStepInputSchema).min(1),
16981
- frames: zod.z.array(FrameInputSchema).min(1).max(255),
16982
- deviceId: zod.z.number().optional(),
16983
- sessionId: zod.z.string().optional(),
16984
- /**
16985
- * Pure-inference benchmark hint. A NONZERO uint32 pins every frame in
16986
- * the batch to the Python pool's bench preprocess cache
16987
- * (`_bench_frame_id`) so a REPEATED benchmark frame is decoded +
16988
- * preprocessed ONCE and every later inference is a pure-inference cache
16989
- * hit — the sustained-throughput run measures inference, not
16990
- * decode+preprocess+infer. Omitted/0 for live frames (all different →
16991
- * full preprocess every call, correct). Fresh per sustained run;
16992
- * released via `uncacheFrame`.
16993
- */
16994
- frameId: zod.z.number().int().nonnegative().optional(),
16995
- /** Inference-device selector (Phase 2 multi-device); see runPipeline. */
16996
- deviceKey: zod.z.string().optional()
16997
- }), 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
+ }),
16998
17254
  /**
16999
- * Cache a raw frame inside the Python inference pool's memory.
17000
- * Returns a numeric `frameId` that `inferCached` references
17001
- * subsequent calls send only 5 bytes through the pipe instead of
17002
- * 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.
17003
17268
  */
17004
- cacheFrameInPool: require_sleep.method(zod.z.object({
17005
- data: zod.z.instanceof(Uint8Array),
17006
- width: zod.z.number().int().positive(),
17007
- height: zod.z.number().int().positive(),
17008
- format: zod.z.enum([
17009
- "rgb",
17010
- "bgr",
17011
- "gray"
17012
- ])
17013
- }), zod.z.object({
17014
- frameId: zod.z.number(),
17015
- width: zod.z.number(),
17016
- height: zod.z.number()
17017
- }), { 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
+ }),
17018
17285
  /**
17019
- * Run inference on a previously cached frame. Sends only 5 bytes
17020
- * (model_idx + frameId) through the IPC pipe — eliminates the
17021
- * ~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.
17022
17297
  */
17023
- inferCached: require_sleep.method(zod.z.object({
17024
- stepId: zod.z.string(),
17025
- frameId: zod.z.number().int()
17026
- }), 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
+ }),
17027
17307
  /**
17028
- * 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.
17029
17315
  */
17030
- uncacheFrame: require_sleep.method(zod.z.object({ frameId: zod.z.number().int() }), zod.z.void(), { kind: "mutation" }),
17031
- /** Returns the effective pool tuning (resolved from user overrides + backend defaults). */
17032
- getEffectiveTuning: require_sleep.method(zod.z.void(), zod.z.object({
17033
- batchMode: zod.z.string(),
17034
- windowMs: zod.z.number(),
17035
- maxBatchSize: zod.z.number(),
17036
- concurrency: zod.z.number()
17037
- })),
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
+ }),
17038
17323
  /**
17039
- * List every EngineFactory currently loaded in this executor's RAM,
17040
- * with the models resident and a coarse "in use" marker derived from
17041
- * 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.
17042
17332
  */
17043
- listLoadedEngines: require_sleep.method(zod.z.void(), zod.z.array(zod.z.object({
17044
- engineKey: zod.z.string(),
17045
- engine: PipelineEngineChoiceSchema,
17046
- modelsLoaded: zod.z.array(zod.z.string()).readonly(),
17047
- inUseByCameras: zod.z.array(zod.z.number()).readonly(),
17048
- /**
17049
- * Origin of this resident factory.
17050
- * - `runtime` — main camera-serving engine (no idle TTL).
17051
- * - `warm-override` — benchmark/test override held in the warm
17052
- * cache; auto-disposed after the idle TTL.
17053
- * - `device-pool` — a concurrent per-device pool (Phase 2
17054
- * multi-device, keyed by `deviceKey`) resolved
17055
- * via `resolveDeviceFactory`. Runs alongside the
17056
- * `runtime` engine on a DIFFERENT accelerator
17057
- * (NPU / iGPU / Coral) — this is how the
17058
- * Engines tab shows all pools running at once.
17059
- */
17060
- kind: zod.z.enum([
17061
- "runtime",
17062
- "warm-override",
17063
- "device-pool"
17064
- ]),
17065
- /** Native pid of the underlying Python pool (null when no pool). */
17066
- poolPid: zod.z.number().nullable(),
17067
- /** ms since this factory was last used (null when not warm-tracked). */
17068
- idleMs: zod.z.number().nullable(),
17069
- /** Idle TTL after which `warm-override` factories self-evict (null when not applicable). */
17070
- idleTtlMs: zod.z.number().nullable()
17071
- })).readonly()),
17072
- /** Warm up an engine without running a frame. No-op if already loaded. */
17073
- 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, {
17074
17337
  kind: "mutation",
17075
17338
  auth: "admin"
17076
17339
  }),
17077
17340
  /**
17078
- * Unload an engine from RAM. `force:true` unloads even when cameras
17079
- * are actively using it (they re-spin on next frame). Default is
17080
- * 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).
17081
17351
  */
17082
- killEngine: require_sleep.method(zod.z.object({
17083
- engine: PipelineEngineChoiceSchema,
17084
- force: zod.z.boolean().optional()
17085
- }), zod.z.object({
17086
- success: zod.z.boolean(),
17087
- reason: zod.z.string().optional()
17088
- }), {
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, {
17089
17399
  kind: "mutation",
17090
17400
  auth: "admin"
17091
17401
  }),
17092
- listReferenceImages: require_sleep.method(zod.z.void(), zod.z.array(ReferenceImageEntrySchema).readonly()),
17093
- getReferenceImage: require_sleep.method(zod.z.object({ filename: zod.z.string() }), ReferenceImageBodySchema.nullable()),
17094
- getReferenceAudioFiles: require_sleep.method(zod.z.void(), zod.z.array(ReferenceAudioEntrySchema).readonly()),
17095
- getReferenceAudio: require_sleep.method(zod.z.object({ filename: zod.z.string() }), ReferenceAudioBodySchema.nullable()),
17096
- getAudioCapabilities: require_sleep.method(zod.z.void(), AudioCapabilitiesSchema),
17097
- runAudioTest: require_sleep.method(zod.z.object({
17098
- addonId: zod.z.string(),
17099
- modelId: zod.z.string(),
17100
- filename: zod.z.string().optional(),
17101
- settings: zod.z.record(zod.z.string(), zod.z.unknown()).optional()
17102
- }), AudioTestResultSchema, { kind: "mutation" }),
17103
- 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
+ }) }
17104
17444
  }
17105
17445
  };
17106
17446
  //#endregion
@@ -17131,108 +17471,6 @@ var CameraMetricsSchema = zod.z.object({
17131
17471
  });
17132
17472
  var CameraMetricsWithDeviceIdSchema = CameraMetricsSchema.extend({ deviceId: zod.z.number() });
17133
17473
  //#endregion
17134
- //#region src/capabilities/zones.cap.ts
17135
- /**
17136
- * Zone — pure geometry + identity. NO filtering behaviour.
17137
- *
17138
- * Zones describe **where** in the frame the operator wants to flag
17139
- * something; consumer-owned {@link ZoneRule} arrays describe **how**
17140
- * each pipeline stage uses them. Splitting the two means a single
17141
- * polygon "Driveway" can simultaneously back a motion-exclude rule,
17142
- * a detection-include rule on `['car']`, and an occupancy aggregate
17143
- * — without three duplicated polygons.
17144
- *
17145
- * Owned by the orchestrator addon (provider) and mirrored into the
17146
- * `zones` device-state slice on every mutation. Consumers
17147
- * (motion-wasm, pipeline-executor, analytics, admin UI) read either
17148
- * via `api.zones.listZones` (one-shot) or via `dev.state.zones` (live
17149
- * mirror with `onChanged`).
17150
- *
17151
- * Coordinates are normalised fractions of the frame (0–1) so zones
17152
- * survive resolution changes and stream profile switches.
17153
- *
17154
- * `kind` discriminates between full polygons (closed regions used
17155
- * for intrusion / occupancy filters) and tripwires (open 2-point
17156
- * line segments used for cross events). Onboard / firmware-reported
17157
- * zones (Reolink, ONVIF) are out of scope for now — see the deferred
17158
- * task list.
17159
- */
17160
- var ZoneKindEnum = zod.z.enum(["polygon", "tripwire"]);
17161
- /** Polygon vertex in fraction-of-frame coordinates (0–1). */
17162
- var PolygonPointSchema = zod.z.object({
17163
- x: zod.z.number(),
17164
- y: zod.z.number()
17165
- });
17166
- /** A camera detection zone — pure geometry/identity. */
17167
- var ZoneSchema = zod.z.object({
17168
- id: zod.z.string(),
17169
- name: zod.z.string(),
17170
- kind: ZoneKindEnum.default("polygon"),
17171
- /** Polygon vertices, fraction of frame (0–1). */
17172
- polygon: zod.z.array(PolygonPointSchema).readonly(),
17173
- /** Visual color for UI rendering. */
17174
- color: zod.z.string().default("#3b82f6")
17175
- });
17176
- /**
17177
- * Zones capability — per-camera CRUD over polygon detection zones.
17178
- *
17179
- * Provider lives in `addon-pipeline-orchestrator` (hub-only). Persists
17180
- * to per-device settings and mirrors into the `zones` device-state
17181
- * slice on every mutation, so downstream consumers can subscribe via
17182
- * `dev.state.zones.onChanged`.
17183
- *
17184
- * The cap surface only handles geometry + identity; filtering
17185
- * behaviour (per-class, include/exclude, threshold) lives in the
17186
- * consumer addons' rule arrays — see `ZoneRuleSchema` exported from
17187
- * `capabilities/schemas/zone-rule.js`.
17188
- */
17189
- var zonesCapability = {
17190
- name: "zones",
17191
- scope: "device",
17192
- mode: "singleton",
17193
- deviceTypes: [require_sleep.DeviceType.Camera],
17194
- methods: {
17195
- listZones: require_sleep.method(zod.z.object({ deviceId: zod.z.number() }), zod.z.array(ZoneSchema).readonly()),
17196
- addZone: require_sleep.method(zod.z.object({
17197
- deviceId: zod.z.number(),
17198
- zone: ZoneSchema
17199
- }), zod.z.void(), {
17200
- kind: "mutation",
17201
- auth: "admin"
17202
- }),
17203
- removeZone: require_sleep.method(zod.z.object({
17204
- deviceId: zod.z.number(),
17205
- zoneId: zod.z.string()
17206
- }), zod.z.void(), {
17207
- kind: "mutation",
17208
- auth: "admin"
17209
- }),
17210
- updateZone: require_sleep.method(zod.z.object({
17211
- deviceId: zod.z.number(),
17212
- zone: ZoneSchema
17213
- }), zod.z.void(), {
17214
- kind: "mutation",
17215
- auth: "admin"
17216
- })
17217
- },
17218
- /**
17219
- * Runtime-state slice — the live zone catalogue mirrored by the
17220
- * orchestrator on every CRUD mutation. Consumers read via
17221
- * `device.state.zones.value` / `.watch(...)` without round-tripping
17222
- * the cap, and the codegen DeviceProxy auto-wires the reactive
17223
- * handle. Slice shape is `{ zones: Zone[] }` so future extensions
17224
- * (e.g. zone groupings) can sit alongside the polygon list.
17225
- */
17226
- runtimeState: zod.z.object({ zones: zod.z.array(ZoneSchema).readonly() }),
17227
- /**
17228
- * 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.
17229
- *
17230
- * See `RuntimeStateDurability`. Enforced by
17231
- * `scripts/check-runtime-state-durability.ts`.
17232
- */
17233
- durability: "restored"
17234
- };
17235
- //#endregion
17236
17474
  //#region src/capabilities/pipeline-runner.cap.ts
17237
17475
  /**
17238
17476
  * A bounding box in NORMALIZED [0,1] frame coordinates for `getNativeCrop`. The
@@ -29164,98 +29402,6 @@ var sceneMonitorCapability = {
29164
29402
  durability: "session"
29165
29403
  };
29166
29404
  //#endregion
29167
- //#region src/capabilities/schemas/zone-rule.ts
29168
- /**
29169
- * Per-stage gating mode applied to the zones a rule references.
29170
- *
29171
- * - `include`: the rule contributes to a **whitelist** for its stage.
29172
- * When at least one `include` rule fires for a stage, only entities
29173
- * inside one of those zones pass that stage.
29174
- * - `exclude`: the rule contributes to a **blacklist** for its stage.
29175
- * Entities inside one of those zones are dropped at that stage.
29176
- *
29177
- * `monitor`-style observation (count without filtering) is not a rule
29178
- * mode — zones without any matching rule are observed naturally by
29179
- * `zone-analytics` (live snapshot + history), so an "I just want to
29180
- * count, not filter" use case needs no rule at all.
29181
- */
29182
- var ZoneRuleModeEnum = zod.z.enum(["include", "exclude"]);
29183
- /**
29184
- * Per-consumer rule that references existing zones (geometry) and
29185
- * defines how a specific pipeline stage should treat them. Each
29186
- * consumer addon owns its own `ZoneRule[]` array in its per-device
29187
- * settings:
29188
- *
29189
- * - `addon-motion-wasm` → `motionZoneRules: ZoneRule[]` (motion stage)
29190
- * - `addon-detection-pipeline` → `detectionZoneRules: ZoneRule[]` (detection stage)
29191
- * - future: notification rules, audio gating, etc.
29192
- *
29193
- * One rule applies to N zones (`zoneIds[]`) so the operator can
29194
- * express "ignore motion in ALL of {garden, street}" with a single
29195
- * rule. `classFilter` narrows the rule to specific object classes —
29196
- * "drop person detections in the street, but keep cars" is one
29197
- * `exclude` rule with `classFilter: ['person']`.
29198
- *
29199
- * `enabled` is a soft toggle — the operator can keep the rule
29200
- * configured but inert without deleting it.
29201
- */
29202
- var ZoneRuleSchema = zod.z.object({
29203
- /** Stable rule id — survives edits, used by the UI for diffing. */
29204
- id: zod.z.string(),
29205
- /** Optional human-readable label rendered in the rule editor. */
29206
- name: zod.z.string().optional(),
29207
- /** Zones this rule targets. The rule's `mode` applies to ALL
29208
- * listed zones (OR-set: a detection in any one of them counts).
29209
- * At least one zone id required — a rule with no targets is a
29210
- * configuration mistake and the form validator rejects it. */
29211
- zoneIds: zod.z.array(zod.z.string()).min(1).readonly(),
29212
- mode: ZoneRuleModeEnum,
29213
- /**
29214
- * Class names this rule applies to. Empty / undefined ⇒ rule
29215
- * applies to every class. Class strings match the `macroClass`
29216
- * field on detections (e.g. `person`, `car`, `dog`).
29217
- */
29218
- classFilter: zod.z.array(zod.z.string()).readonly().optional(),
29219
- /**
29220
- * Minimum bbox/mask overlap (0–1) with any of the rule's zones
29221
- * required to consider an entity "in the zone". Defaults to the
29222
- * consumer's stage default when omitted. Kept for back-compat with
29223
- * existing per-rule overrides; new operators pick the value via
29224
- * `bboxInclusionPct` (operator-friendly 0–100). Whichever field is
29225
- * set, the lower-level engine reads it as a 0–1 fraction.
29226
- */
29227
- overlapThreshold: zod.z.number().min(0).max(1).optional(),
29228
- /**
29229
- * Operator-friendly version of `overlapThreshold` — the percentage
29230
- * of the detection's bbox that must lie inside the zone for the
29231
- * rule to match. Documented default is 85%; the engine substitutes
29232
- * that when the field is omitted (kept optional so existing rules
29233
- * stored without it stay valid).
29234
- *
29235
- * When BOTH `overlapThreshold` and `bboxInclusionPct` are set on a
29236
- * rule, the engine prefers `bboxInclusionPct` because it's the
29237
- * field exposed in the UI. Internally both feed the same gate.
29238
- */
29239
- bboxInclusionPct: zod.z.number().min(0).max(100).optional(),
29240
- /**
29241
- * When `true` and a detection has a segmentation mask, use the
29242
- * mask for overlap instead of the bbox. Detection-stage only;
29243
- * motion rules ignore this field.
29244
- */
29245
- preferMask: zod.z.boolean().optional(),
29246
- /**
29247
- * Soft-toggle: `false` disables the rule without deleting it.
29248
- * Defaults to `true` so operators creating a rule via the UI
29249
- * see it active immediately.
29250
- */
29251
- enabled: zod.z.boolean().default(true)
29252
- });
29253
- /**
29254
- * Convenience array schema — used by addon device-settings
29255
- * contributions and runtime payloads (e.g. `RunnerCameraConfig`).
29256
- */
29257
- var ZoneRulesArraySchema = zod.z.array(ZoneRuleSchema).readonly();
29258
- //#endregion
29259
29405
  //#region src/capabilities/script-runner.cap.ts
29260
29406
  /**
29261
29407
  * Script-runner cap. Models HA `script.*` entities on
@@ -38127,6 +38273,12 @@ var METHOD_ACCESS_MAP = Object.freeze({
38127
38273
  addonId: null,
38128
38274
  access: "create"
38129
38275
  },
38276
+ "pipelineAnalytics.cancelRelocateMedia": {
38277
+ capName: "pipeline-analytics",
38278
+ capScope: "device",
38279
+ addonId: null,
38280
+ access: "create"
38281
+ },
38130
38282
  "pipelineAnalytics.cancelStorageMigrationMove": {
38131
38283
  capName: "pipeline-analytics",
38132
38284
  capScope: "device",
@@ -38301,6 +38453,12 @@ var METHOD_ACCESS_MAP = Object.freeze({
38301
38453
  addonId: null,
38302
38454
  access: "view"
38303
38455
  },
38456
+ "pipelineAnalytics.listRelocateMediaJobs": {
38457
+ capName: "pipeline-analytics",
38458
+ capScope: "device",
38459
+ addonId: null,
38460
+ access: "view"
38461
+ },
38304
38462
  "pipelineAnalytics.listRetrainAnnotations": {
38305
38463
  capName: "pipeline-analytics",
38306
38464
  capScope: "device",
@@ -38379,6 +38537,12 @@ var METHOD_ACCESS_MAP = Object.freeze({
38379
38537
  addonId: null,
38380
38538
  access: "create"
38381
38539
  },
38540
+ "pipelineAnalytics.relocateMedia": {
38541
+ capName: "pipeline-analytics",
38542
+ capScope: "device",
38543
+ addonId: null,
38544
+ access: "create"
38545
+ },
38382
38546
  "pipelineAnalytics.restageRetrainTrack": {
38383
38547
  capName: "pipeline-analytics",
38384
38548
  capScope: "device",
@@ -38391,6 +38555,12 @@ var METHOD_ACCESS_MAP = Object.freeze({
38391
38555
  addonId: null,
38392
38556
  access: "create"
38393
38557
  },
38558
+ "pipelineAnalytics.runReplayFrameProcessor": {
38559
+ capName: "pipeline-analytics",
38560
+ capScope: "device",
38561
+ addonId: null,
38562
+ access: "create"
38563
+ },
38394
38564
  "pipelineAnalytics.saveRetrainAnnotations": {
38395
38565
  capName: "pipeline-analytics",
38396
38566
  capScope: "device",
@@ -38523,6 +38693,12 @@ var METHOD_ACCESS_MAP = Object.freeze({
38523
38693
  addonId: null,
38524
38694
  access: "view"
38525
38695
  },
38696
+ "pipelineExecutor.getInferenceDeviceHealth": {
38697
+ capName: "pipeline-executor",
38698
+ capScope: "system",
38699
+ addonId: null,
38700
+ access: "view"
38701
+ },
38526
38702
  "pipelineExecutor.getOrchestratorConfigSchema": {
38527
38703
  capName: "pipeline-executor",
38528
38704
  capScope: "system",
@@ -38595,6 +38771,12 @@ var METHOD_ACCESS_MAP = Object.freeze({
38595
38771
  addonId: null,
38596
38772
  access: "view"
38597
38773
  },
38774
+ "pipelineExecutor.rearmInferenceDevice": {
38775
+ capName: "pipeline-executor",
38776
+ capScope: "system",
38777
+ addonId: null,
38778
+ access: "create"
38779
+ },
38598
38780
  "pipelineExecutor.runAudioTest": {
38599
38781
  capName: "pipeline-executor",
38600
38782
  capScope: "system",
@@ -42100,6 +42282,11 @@ var METHOD_DEVICE_SELECTORS = Object.freeze({
42100
42282
  form: "single",
42101
42283
  optional: false
42102
42284
  }],
42285
+ "pipelineAnalytics.runReplayFrameProcessor": [{
42286
+ name: "deviceId",
42287
+ form: "single",
42288
+ optional: false
42289
+ }],
42103
42290
  "pipelineAnalytics.saveRetrainAnnotations": [{
42104
42291
  name: "deviceId",
42105
42292
  form: "single",
@@ -43723,6 +43910,8 @@ function createSystemProxy(api) {
43723
43910
  getVideoPipelineSteps: (input) => dispatch("pipelineExecutor", "getVideoPipelineSteps", "query", input),
43724
43911
  setVideoPipelineSteps: (input) => dispatch("pipelineExecutor", "setVideoPipelineSteps", "mutation", input),
43725
43912
  clearDeviceOverrides: (input) => dispatch("pipelineExecutor", "clearDeviceOverrides", "mutation", input),
43913
+ getInferenceDeviceHealth: (input) => dispatch("pipelineExecutor", "getInferenceDeviceHealth", "query", input),
43914
+ rearmInferenceDevice: (input) => dispatch("pipelineExecutor", "rearmInferenceDevice", "mutation", input),
43726
43915
  getSchema: (input) => dispatch("pipelineExecutor", "getSchema", "query", input),
43727
43916
  getGlobalSteps: (input) => dispatch("pipelineExecutor", "getGlobalSteps", "query", input),
43728
43917
  getGlobalPipelineConfig: (input) => dispatch("pipelineExecutor", "getGlobalPipelineConfig", "query", input),
@@ -48034,7 +48223,6 @@ exports.CapScopeSchema = CapScopeSchema;
48034
48223
  exports.CapabilityBindingsSchema = CapabilityBindingsSchema;
48035
48224
  exports.CarbonMonoxideStatusSchema = CarbonMonoxideStatusSchema;
48036
48225
  exports.ChargingStatus = require_sleep.ChargingStatus;
48037
- exports.ClassMapDefinitionSchema = ClassMapDefinitionSchema;
48038
48226
  exports.ClientNetworkStatsSchema = ClientNetworkStatsSchema;
48039
48227
  exports.ClimateControlStatusSchema = ClimateControlStatusSchema;
48040
48228
  exports.ClipPlaybackSchema = ClipPlaybackSchema;
@@ -48120,6 +48308,7 @@ exports.DecoderSessionConfigSchema = DecoderSessionConfigSchema;
48120
48308
  exports.DecoderStatsSchema = DecoderStatsSchema;
48121
48309
  exports.DeleteIntegrationResultSchema = DeleteIntegrationResultSchema;
48122
48310
  exports.DetailCropConventionSchema = DetailCropConventionSchema;
48311
+ exports.DetectionCatalogClassMapSchema = DetectionCatalogClassMapSchema;
48123
48312
  exports.DetectionSourceSchema = DetectionSourceSchema;
48124
48313
  exports.DeviceCodeSeveritySchema = DeviceCodeSeveritySchema;
48125
48314
  exports.DeviceConfig = DeviceConfig;