@camstack/addon-pipeline-orchestrator 1.2.167 → 1.2.168

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -21282,8 +21282,25 @@ var occupancyRecheckFramesField = {
21282
21282
  * (analyzer attaches detected `regions[]`; onboard does not — the
21283
21283
  * camera typically only reports a binary signal plus an optional
21284
21284
  * channel/AI class which lives in dedicated event channels).
21285
- */
21286
- var MotionSourceEnum = _enum(["onboard", "analyzer"]);
21285
+ *
21286
+ * - `onboard` — the camera's firmware said something moved.
21287
+ * - `analyzer` — this runner's frame-diff said so, and attaches `regions[]`.
21288
+ * - `device-activity` — the DEVICE said it is doing its job: the
21289
+ * `recording-signal` LEVEL the same device raises for the recorder
21290
+ * ([D380](../../../../docs/decisions/adr-0380-a-device-decided-recording-is-a-mode-with-no-schedule-seeded-once.md)),
21291
+ * republished as a motion source. It attaches **nothing** — no regions, no
21292
+ * class: the only fact it carries is that the device is active, and a robot
21293
+ * vacuum that is itself the moving object has no region worth sending. It is
21294
+ * a LEVEL, so unlike `onboard` it has a real falling edge, and unlike
21295
+ * `analyzer` it must not open the frame-diff side-channel — the runner's
21296
+ * `handleOnboardMotionAnalyzer` gate is `source === 'onboard'` and stays that
21297
+ * way ([D392](../../../../docs/decisions/adr-0392-a-device-that-says-it-is-working-is-a-motion-source-of-its-own.md)).
21298
+ */
21299
+ var MotionSourceEnum = _enum([
21300
+ "onboard",
21301
+ "analyzer",
21302
+ "device-activity"
21303
+ ]);
21287
21304
  /**
21288
21305
  * List of motion sources active on a camera. Empty array is valid:
21289
21306
  * "no source" — happens for battery cams without firmware motion when
@@ -21547,13 +21564,20 @@ var RunnerCameraDeviceUIFields = [
21547
21564
  type: "multiselect",
21548
21565
  label: "Motion Sources",
21549
21566
  default: ["analyzer"],
21550
- options: [{
21551
- value: "analyzer",
21552
- label: "Frame-diff Analyzer (motion addon)"
21553
- }, {
21554
- value: "onboard",
21555
- label: "Camera Onboard Sensor"
21556
- }]
21567
+ options: [
21568
+ {
21569
+ value: "analyzer",
21570
+ label: "Frame-diff Analyzer (motion addon)"
21571
+ },
21572
+ {
21573
+ value: "onboard",
21574
+ label: "Camera Onboard Sensor"
21575
+ },
21576
+ {
21577
+ value: "device-activity",
21578
+ label: "Device activity (the device says it is working)"
21579
+ }
21580
+ ]
21557
21581
  },
21558
21582
  {
21559
21583
  key: "motionFps",
@@ -29550,8 +29574,38 @@ var RecordingSignalStatusSchema = object({
29550
29574
  /** Ms epoch of the last `active` transition. 0 if never observed. */
29551
29575
  lastChangedAt: number()
29552
29576
  });
29553
- RecordingSignalStatusSchema.extend({ lastFetchedAt: number() });
29554
- DeviceType.Camera, method(object({ deviceId: number() }), RecordingSignalStatusSchema);
29577
+ /** The runtime-state slice: the status plus the clock every slice carries. */
29578
+ var RecordingSignalRuntimeStateSchema = RecordingSignalStatusSchema.extend({ lastFetchedAt: number() });
29579
+ var recordingSignalCapability = {
29580
+ name: "recording-signal",
29581
+ scope: "device",
29582
+ deviceNative: true,
29583
+ mode: "singleton",
29584
+ deviceTypes: [DeviceType.Camera],
29585
+ methods: {
29586
+ /** The current level, straight from the slice the provider keeps fresh. */
29587
+ getStatus: method(object({ deviceId: number() }), RecordingSignalStatusSchema) },
29588
+ status: {
29589
+ schema: RecordingSignalStatusSchema,
29590
+ kind: "push",
29591
+ empty: {
29592
+ active: false,
29593
+ reason: "unknown",
29594
+ lastChangedAt: 0
29595
+ }
29596
+ },
29597
+ runtimeState: RecordingSignalRuntimeStateSchema,
29598
+ /**
29599
+ * Runtime-state durability: **session** — a restored `active: true` from
29600
+ * before a restart is exactly the stale level the recorder's reconcile bound
29601
+ * exists to end, and the provider re-derives the true level on activation
29602
+ * anyway. Nothing is lost by forgetting it; a lie is avoided.
29603
+ *
29604
+ * See `RuntimeStateDurability`. Enforced by
29605
+ * `scripts/check-runtime-state-durability.ts`.
29606
+ */
29607
+ durability: "session"
29608
+ };
29555
29609
  /**
29556
29610
  * scene-monitor — device-scoped reference-region state cap. An operator marks
29557
29611
  * a rect ROI on a camera frame and names one or more states; the engine
@@ -40027,477 +40081,278 @@ function deviceBackendToFormat(backend) {
40027
40081
  return DEVICE_BACKEND_TO_FORMAT[backend] ?? "onnx";
40028
40082
  }
40029
40083
  //#endregion
40030
- //#region src/inference-device-model.ts
40084
+ //#region src/audio-chunk-poller.ts
40031
40085
  /**
40032
- * Per-device default object-detection model + deviceKey parsing for the
40033
- * orchestrator's device-aware `getNodeInferenceDevices` view.
40086
+ * `AudioChunkPoller` the consumer-side poll loop of the decoded audio-chunk
40087
+ * plane (Phase 5 / D9).
40034
40088
  *
40035
- * This DUPLICATES the executor's per-device model resolution (P0-3:
40036
- * `resolveDeviceEngine` + `MODEL_BY_CLASS` + the object-detection step's
40037
- * `defaultModelIdByFormat` in `@camstack/addon-pipeline`). It is duplicated
40038
- * not imported because cross-addon imports are forbidden (the orchestrator
40039
- * and the detection-pipeline are separate addons; only tRPC crosses the
40040
- * boundary). Keep this in sync with `default-detection-model.ts` /
40041
- * `step-definitions.ts` if the executor's defaults change.
40089
+ * Replaces the live-object `IStreamBroker.onDecodedAudioChunk(cb)` callback
40090
+ * path. A live callback cannot cross a process boundary; once the `pipeline`
40091
+ * group is dissolved (Task 8) the orchestrator runs in a different process
40092
+ * from the broker, so audio delivery must go over tRPC.
40042
40093
  *
40043
- * The returned ids are honest catalog ids (verified present):
40044
- * - `yolov9m-320-int8` — Intel NPU + iGPU (yolo26 does NOT compile on the NPU)
40045
- * - `yolov9m-320` — Apple ANE (CoreML)
40046
- * - `ssd-mobilenet-v2-coco-edgetpu` — Coral USB Edge TPU (tflite)
40047
- * - `yolo26n` — CPU / CUDA (the object-detection step's universal
40048
- * nano default)
40094
+ * The consumer:
40049
40095
  *
40050
- * Do not promote the accelerated ids to 640. The evaluation in
40051
- * `docs/benchmarks/pipeline-frame-model-eval.md` failed the 640 promotion
40052
- * gates (0/3 miss recovered at the current threshold).
40096
+ * 1. `subscribeAudioChunks({ brokerId, tag })` over tRPC the broker
40097
+ * registers a per-subscription bounded FIFO queue and returns a
40098
+ * `subscriptionId`;
40099
+ * 2. polls `pullAudioChunks({ subscriptionId, maxCount })` on a modest
40100
+ * interval, draining `DecodedAudioChunk`s in FIFO arrival order;
40101
+ * 3. feeds each chunk to its downstream audio logic;
40102
+ * 4. on teardown, `unsubscribeAudioChunks`.
40103
+ *
40104
+ * Audio is not latency-critical like video, and chunks arrive only ~every
40105
+ * 500ms (the broker's `AudioCodecSession` window). A modest poll period plus
40106
+ * a small per-poll burst keeps latency low without busy-spinning. The
40107
+ * broker's queue is FIFO/no-drop-sized so a poll-period of jitter never
40108
+ * loses a chunk.
40109
+ *
40110
+ * Boot-race tolerance: the broker for a given camStream may not be registered
40111
+ * yet when the orchestrator wires the subscription (provider addons publish
40112
+ * their cameraStreams asynchronously after their probe completes).
40113
+ * `subscribeAudioChunks` retries with exponential backoff (capped at
40114
+ * `MAX_SUBSCRIBE_RETRY_BACKOFF_MS`) until it succeeds or the returned
40115
+ * teardown closure is invoked. Mirrors the `FrameHandlePoller` recovery
40116
+ * shape so video and audio plumbing self-heal identically.
40053
40117
  */
40118
+ /** Poll period — audio chunks arrive ~every 500ms; 200ms keeps latency low. */
40119
+ var POLL_INTERVAL_MS$1 = 200;
40120
+ /** How many chunks to drain per poll — a small burst absorbs jitter. */
40121
+ var PULL_MAX_COUNT = 8;
40054
40122
  /**
40055
- * The always-on object-detection ROOT step id. A camera session's tracks all
40056
- * originate from this detector, so a device whose engine format can't run it
40057
- * cannot host a camera root. Mirrors the addon-pipeline step id (cross-addon
40058
- * import is forbidden this is the same duplication rationale as the model
40059
- * defaults above).
40123
+ * Consecutive pull failures before we attempt to re-subscribe. A single failed
40124
+ * poll is treated as a blip (re-subscribing would leak a broker-side FIFO); a
40125
+ * sustained failure means the broker child restarted and dropped our
40126
+ * subscription, so we re-establish it.
40060
40127
  */
40061
- var OBJECT_DETECTION_STEP_ID = "object-detection";
40128
+ var RESUBSCRIBE_AFTER_FAILURES = 2;
40129
+ /** Re-subscribe at most once every N ticks while failing (~1s at 200ms). */
40130
+ var RESUBSCRIBE_THROTTLE_TICKS = 5;
40131
+ /** First subscribe-retry delay, doubled on every subsequent failure. */
40132
+ var INITIAL_SUBSCRIBE_RETRY_BACKOFF_MS = 250;
40062
40133
  /**
40063
- * Build the camera-root capability predicate for a node from its live catalog:
40064
- * `format canHostCameraRoot`. A format can host a camera root iff the
40065
- * catalog lists at least one object-detection model with a build for that
40066
- * format — byte-for-byte the resolver's per-device skip-gate test for the root
40067
- * step (`addonHasCompatibleModel`), so a device is deemed eligible iff the root
40068
- * would ACTUALLY provision on it.
40069
- *
40070
- * Fails OPEN when the catalog has no object-detection slot at all (never
40071
- * observed in production) so a malformed/empty catalog never strands every
40072
- * device off the balancer. Pure + deterministic.
40134
+ * Subscribe-retry backoff ceiling. 5 s matches the frame-handle poller fast
40135
+ * enough to recover within a single reconcile of the orchestrator and slow
40136
+ * enough that a misconfigured camStream costs ~12 op/min, not 5/s.
40073
40137
  */
40074
- function makeRootCapabilityGuard(catalog) {
40075
- for (const slot of catalog.slots) {
40076
- const objDet = slot.addons.find((a) => a.id === OBJECT_DETECTION_STEP_ID);
40077
- if (objDet) return (format) => objDet.models.some((m) => Boolean(m.formats[format]));
40078
- }
40079
- return () => true;
40080
- }
40081
- /** Split a deviceKey (`<backend>:<device>`, or bare `cpu`) into its parts + format.
40082
- * Format comes from the shared {@link deviceBackendToFormat} SSOT (`@camstack/types`)
40083
- * — the previously-local `BACKEND_FORMAT` copy is gone (R3/node-F2). Used only for
40084
- * STORED-ONLY keys (a configured device the live probe didn't return); a probed
40085
- * device carries its own honest `format` from the descriptor. */
40086
- function parseDeviceKey(deviceKey) {
40087
- const colon = deviceKey.indexOf(":");
40088
- const backend = colon >= 0 ? deviceKey.slice(0, colon) : deviceKey;
40089
- return {
40090
- backend,
40091
- device: colon >= 0 ? deviceKey.slice(colon + 1) : deviceKey,
40092
- format: deviceBackendToFormat(backend)
40093
- };
40094
- }
40138
+ var MAX_SUBSCRIBE_RETRY_BACKOFF_MS = 5e3;
40095
40139
  /**
40096
- * The object-detection model the executor defaults to for a deviceKey. Mirrors
40097
- * the executor's `MODEL_BY_CLASS` classification (`classifyAccelerator`) plus
40098
- * the tflite `defaultModelIdByFormat` for Coral. Never throws; unknown backends
40099
- * fall back to the universal nano default (`yolo26n`).
40140
+ * Attempts after which a still-failing subscribe escalates from the fast 5 s
40141
+ * ceiling to {@link LONG_SUBSCRIBE_RETRY_BACKOFF_MS}. ~15 attempts ≈ one
40142
+ * minute of fast retries — plenty for the boot races the 5 s ceiling exists
40143
+ * for. A broker that is STILL absent after that is a long-lived condition
40144
+ * (e.g. a DISABLED camera, whose broker the stream-broker reconcile refuses
40145
+ * to recreate — 2026-07-23) and retrying every 5 s forever is pure log/RPC
40146
+ * churn. The slow loop stays alive so audio still recovers automatically
40147
+ * (≤60 s) once the camera is re-enabled.
40100
40148
  */
40101
- function defaultModelIdForDevice(deviceKey) {
40102
- const { backend, device } = parseDeviceKey(deviceKey);
40103
- if (backend === "openvino") {
40104
- if (device === "cpu") return "yolo26n";
40105
- return "yolov9m-320-int8";
40106
- }
40107
- if (backend === "edgetpu") return "ssd-mobilenet-v2-coco-edgetpu";
40108
- if (backend === "coreml") return "yolov9m-320";
40109
- return "yolo26n";
40110
- }
40149
+ var PERSISTENT_SUBSCRIBE_FAILURE_ATTEMPTS = 15;
40150
+ var LONG_SUBSCRIBE_RETRY_BACKOFF_MS = 6e4;
40111
40151
  /**
40112
- * Step-tree device jump (phase 1): validate every `steps[step].jumpDeviceKey`
40113
- * manual override in a to-be-saved `inferenceDevices` map. A jump target MUST be
40114
- * an enabled∧available device on the SAME node and DIFFERENT from the owning
40115
- * device. `enabledAvailableKeys` is the effective enabled∧available set (from
40116
- * `mergeInferenceDevices(probe, submitted)`) so an absent/unplugged/disabled
40117
- * target is rejected honestly (an operator can't route a step onto a dead pool).
40118
- * Returns the FIRST human-readable error, or `null` when every override is
40119
- * valid. Pure + deterministic.
40152
+ * Subscribe to a broker's decoded audio-chunk stream and start the poll loop.
40153
+ *
40154
+ * Always resolves to a teardown closure when the broker is not yet
40155
+ * registered the closure cancels the ongoing retry loop; when polling is
40156
+ * active it stops the loop and releases the broker subscription. Mirrors
40157
+ * `startFrameHandlePoller` so video and audio recover identically.
40120
40158
  */
40121
- function validateJumpTargets(inferenceDevices, enabledAvailableKeys) {
40122
- for (const [deviceKey, entry] of Object.entries(inferenceDevices)) for (const [stepId, step] of Object.entries(entry.steps ?? {})) {
40123
- const target = step.jumpDeviceKey;
40124
- if (target === void 0) continue;
40125
- if (target === deviceKey) return `step "${stepId}" on "${deviceKey}" has a jumpDeviceKey pointing at its own device`;
40126
- if (!enabledAvailableKeys.has(target)) return `step "${stepId}" on "${deviceKey}" has a jumpDeviceKey "${target}" that is not an enabled, available device on this node`;
40127
- }
40128
- return null;
40159
+ function startAudioChunkPoller(options) {
40160
+ const lifecycle = {
40161
+ stopped: false,
40162
+ retryTimer: void 0,
40163
+ pollTimer: void 0,
40164
+ activeSubscriptionId: null
40165
+ };
40166
+ const teardown = () => {
40167
+ if (lifecycle.stopped) return;
40168
+ lifecycle.stopped = true;
40169
+ if (lifecycle.retryTimer) {
40170
+ clearTimeout(lifecycle.retryTimer);
40171
+ lifecycle.retryTimer = void 0;
40172
+ }
40173
+ if (lifecycle.pollTimer) {
40174
+ clearTimeout(lifecycle.pollTimer);
40175
+ lifecycle.pollTimer = void 0;
40176
+ }
40177
+ const subId = lifecycle.activeSubscriptionId;
40178
+ if (subId) {
40179
+ lifecycle.activeSubscriptionId = null;
40180
+ options.api.streamBroker.unsubscribeAudioChunks.mutate({ subscriptionId: subId }, nodePin(options.ownerNodeId)).catch((err) => {
40181
+ options.logger.warn("audio-chunk poller: unsubscribeAudioChunks failed", { meta: {
40182
+ brokerId: options.brokerId,
40183
+ subscriptionId: subId,
40184
+ error: errMsg(err)
40185
+ } });
40186
+ });
40187
+ }
40188
+ };
40189
+ subscribeWithRetry(options, lifecycle);
40190
+ return teardown;
40129
40191
  }
40130
40192
  /**
40131
- * Merge a node's live-probed inference devices with its stored per-device map.
40132
- *
40133
- * The default is **AUTO = all discovered ACCELERATORS enabled** (spec C2,
40134
- * opt-OUT) with TWO deliberate exceptions, both **opt-IN** (default disabled):
40135
- *
40136
- * - **CPU**: `enumerateInferenceDevices` always emits a universal `cpu`
40137
- * floor on every platform; auto-enabling it would let the balancer
40138
- * round-robin ~1/N of sessions onto the slow CPU pool alongside the
40139
- * NPU/iGPU/ANE. CPU stays the always-available FALLBACK (a node with no
40140
- * eligible accelerator leaves `deviceKey` unset → the runner's default
40141
- * pool, which is CPU), not a balanced target — matching the spec's "no
40142
- * device eligible → fall back to CPU".
40143
- * - **Coral Edge TPU (`edgetpu`)**: the standing rule since the Coral
40144
- * executor landed is that it surfaces as selectable but is NEVER
40145
- * auto-picked — it runs a DIFFERENT, weaker model family (tflite SSD
40146
- * MobileNet, not the YOLO the other accelerators run), so silently
40147
- * enrolling a plugged-in Coral changes detection QUALITY, not just
40148
- * placement. The opt-OUT default did exactly that on 2026-08-01: a hub
40149
- * Coral nobody enabled entered the session rotation and camera 615 spent
40150
- * hours at 2.4fps failing tflite model resolution. An operator who wants
40151
- * the Coral balanced opts it in explicitly (`enabled: true`).
40152
- *
40153
- * So: an NPU/iGPU/ANE accelerator with NO stored entry is `enabled:true`; a
40154
- * CPU or edgetpu device with no stored entry is `enabled:false`; an explicit
40155
- * stored `enabled` always wins (an operator can opt CPU/Coral in, or an
40156
- * accelerator out). A stored-only key (configured but the probe did not
40157
- * return it — removed/unplugged HW) keeps its stored `enabled` and surfaces
40158
- * as `available:false`, so the UI still shows it.
40159
- *
40160
- * Pure + deterministic (sorted by key) — the single merge authority shared by
40161
- * the `getNodeInferenceDevices` view and the dispatcher's eligible-device pick.
40193
+ * Run the subscribe poll handshake with exponential backoff on subscribe
40194
+ * failures. Resolves once the subscription is acquired (and the poll loop has
40195
+ * been started) or once `lifecycle.stopped` flips, whichever comes first.
40162
40196
  */
40163
- function mergeInferenceDevices(probed, stored) {
40164
- const probedByKey = new Map(probed.map((d) => [d.key, d]));
40165
- const keys = new Set([...probedByKey.keys(), ...Object.keys(stored)]);
40166
- const out = [];
40167
- for (const key of Array.from(keys).toSorted()) {
40168
- const descriptor = probedByKey.get(key);
40169
- const opt = stored[key];
40170
- const parsed = descriptor ?? parseDeviceKey(key);
40171
- const weight = opt?.weight !== void 0 && opt.weight > 0 ? opt.weight : 1;
40172
- const autoDefault = parsed.backend !== "cpu" && parsed.backend !== "edgetpu";
40173
- out.push({
40174
- key,
40175
- backend: parsed.backend,
40176
- device: parsed.device,
40177
- format: parsed.format,
40178
- available: descriptor?.available ?? false,
40179
- enabled: opt?.enabled ?? autoDefault,
40180
- weight,
40181
- maxSessions: opt?.maxSessions ?? null,
40182
- defaultModelId: defaultModelIdForDevice(key),
40183
- ...opt?.steps && Object.keys(opt.steps).length > 0 ? { steps: { ...opt.steps } } : {}
40184
- });
40197
+ async function subscribeWithRetry(options, lifecycle) {
40198
+ const { api, brokerId, tag, ownerNodeId, logger } = options;
40199
+ const pin = nodePin(ownerNodeId);
40200
+ let backoffMs = INITIAL_SUBSCRIBE_RETRY_BACKOFF_MS;
40201
+ let attempt = 0;
40202
+ while (!lifecycle.stopped) {
40203
+ attempt += 1;
40204
+ try {
40205
+ const result = await api.streamBroker.subscribeAudioChunks.mutate({
40206
+ brokerId,
40207
+ tag
40208
+ }, pin);
40209
+ if (lifecycle.stopped) {
40210
+ await api.streamBroker.unsubscribeAudioChunks.mutate({ subscriptionId: result.subscriptionId }, pin).catch((err) => {
40211
+ logger.warn("audio-chunk poller: late unsubscribe failed", { meta: {
40212
+ brokerId,
40213
+ subscriptionId: result.subscriptionId,
40214
+ error: errMsg(err)
40215
+ } });
40216
+ });
40217
+ return;
40218
+ }
40219
+ if (attempt > 1) logger.info("audio-chunk poller: subscribeAudioChunks recovered", { meta: {
40220
+ brokerId,
40221
+ tag,
40222
+ attempt
40223
+ } });
40224
+ lifecycle.activeSubscriptionId = result.subscriptionId;
40225
+ startPolling(options, lifecycle);
40226
+ return;
40227
+ } catch (err) {
40228
+ if (lifecycle.stopped) return;
40229
+ if (attempt === 1) logger.warn("audio-chunk poller: subscribeAudioChunks failed, retrying", { meta: {
40230
+ brokerId,
40231
+ tag,
40232
+ error: errMsg(err),
40233
+ nextRetryInMs: backoffMs
40234
+ } });
40235
+ else logger.debug("audio-chunk poller: subscribeAudioChunks still failing", { meta: {
40236
+ brokerId,
40237
+ tag,
40238
+ attempt,
40239
+ error: errMsg(err),
40240
+ nextRetryInMs: backoffMs
40241
+ } });
40242
+ await sleep(backoffMs, lifecycle);
40243
+ backoffMs = Math.min(attempt >= PERSISTENT_SUBSCRIBE_FAILURE_ATTEMPTS ? LONG_SUBSCRIBE_RETRY_BACKOFF_MS : MAX_SUBSCRIBE_RETRY_BACKOFF_MS, backoffMs * 2);
40244
+ }
40185
40245
  }
40186
- return out;
40187
40246
  }
40188
40247
  /**
40189
- * The per-device concurrent-session caps for a node as `deviceKey → maxSessions`
40190
- * (only devices that carry an explicit cap; absent = unlimited). Fed to the
40191
- * device balancer's `nodeCaps` so a device at its cap is skipped (audit F3).
40248
+ * Drive the steady-state poll loop. Mid-stream `pullAudioChunks` failures
40249
+ * trigger a fresh `subscribeAudioChunks` via the recovery branch covers
40250
+ * the broker child restart case where our `subscriptionId` is silently
40251
+ * disowned.
40192
40252
  */
40193
- function inferenceDeviceCaps(stored) {
40194
- const out = {};
40195
- for (const [key, entry] of Object.entries(stored)) if (entry.maxSessions !== void 0 && entry.maxSessions > 0) out[key] = entry.maxSessions;
40196
- return out;
40197
- }
40198
- /** Is this device the CPU fallback rather than a real accelerator? */
40199
- function isCpuFallback(view) {
40200
- return view.backend === "cpu";
40201
- }
40202
- function resolveInferenceDeviceEligibility(probed, stored, canRunRoot, isPoolUsable) {
40203
- const eligible = {};
40204
- const excluded = [];
40205
- const merged = mergeInferenceDevices(probed, stored);
40206
- const acceleratorServes = merged.some((d) => !isCpuFallback(d) && d.enabled && d.available && (!canRunRoot || canRunRoot(d.format)));
40207
- for (const d of merged) {
40208
- if (!d.enabled) {
40209
- excluded.push({
40210
- key: d.key,
40211
- reason: "disabled",
40212
- format: d.format
40213
- });
40214
- continue;
40215
- }
40216
- if (!d.available) {
40217
- excluded.push({
40218
- key: d.key,
40219
- reason: "unavailable",
40220
- format: d.format
40221
- });
40222
- continue;
40223
- }
40224
- if (isPoolUsable && !isPoolUsable(d.key)) {
40225
- excluded.push({
40226
- key: d.key,
40227
- reason: "unavailable",
40228
- format: d.format
40229
- });
40230
- continue;
40231
- }
40232
- if (canRunRoot && !canRunRoot(d.format)) {
40233
- excluded.push({
40234
- key: d.key,
40235
- reason: "cannot-host-camera-root",
40236
- format: d.format
40237
- });
40238
- continue;
40253
+ function startPolling(options, lifecycle) {
40254
+ const { api, brokerId, tag, ownerNodeId, onChunk, logger } = options;
40255
+ const pin = nodePin(ownerNodeId);
40256
+ let consecutiveFailures = 0;
40257
+ const resubscribe = async () => {
40258
+ try {
40259
+ const result = await api.streamBroker.subscribeAudioChunks.mutate({
40260
+ brokerId,
40261
+ tag
40262
+ }, pin);
40263
+ lifecycle.activeSubscriptionId = result.subscriptionId;
40264
+ logger.info("audio-chunk poller: re-subscribed after broker outage", { meta: {
40265
+ brokerId,
40266
+ tag,
40267
+ subscriptionId: result.subscriptionId,
40268
+ afterFailures: consecutiveFailures
40269
+ } });
40270
+ return true;
40271
+ } catch {
40272
+ return false;
40239
40273
  }
40240
- if (isCpuFallback(d) && acceleratorServes) {
40241
- excluded.push({
40242
- key: d.key,
40243
- reason: "accelerator-preferred",
40244
- format: d.format
40245
- });
40246
- continue;
40274
+ };
40275
+ const tick = async () => {
40276
+ if (lifecycle.stopped) return;
40277
+ const subId = lifecycle.activeSubscriptionId;
40278
+ if (!subId) return;
40279
+ try {
40280
+ const chunks = await api.streamBroker.pullAudioChunks.query({
40281
+ subscriptionId: subId,
40282
+ maxCount: PULL_MAX_COUNT
40283
+ }, pin);
40284
+ if (consecutiveFailures > 0) logger.info("audio-chunk poller: stream recovered", { meta: {
40285
+ brokerId,
40286
+ subscriptionId: subId
40287
+ } });
40288
+ consecutiveFailures = 0;
40289
+ for (const chunk of chunks) {
40290
+ if (lifecycle.stopped) break;
40291
+ await onChunk(chunk);
40292
+ }
40293
+ } catch (err) {
40294
+ consecutiveFailures += 1;
40295
+ if (consecutiveFailures === 1) logger.warn("audio-chunk poller: pullAudioChunks failed — attempting recovery", { meta: {
40296
+ brokerId,
40297
+ subscriptionId: subId,
40298
+ error: errMsg(err)
40299
+ } });
40300
+ if (!lifecycle.stopped && consecutiveFailures >= RESUBSCRIBE_AFTER_FAILURES && (consecutiveFailures - RESUBSCRIBE_AFTER_FAILURES) % RESUBSCRIBE_THROTTLE_TICKS === 0) await resubscribe();
40247
40301
  }
40248
- eligible[d.key] = d.weight;
40249
- }
40250
- return {
40251
- eligible,
40252
- excluded
40302
+ if (!lifecycle.stopped) lifecycle.pollTimer = setTimeout(() => void tick(), POLL_INTERVAL_MS$1);
40253
40303
  };
40304
+ tick();
40254
40305
  }
40255
40306
  /**
40256
- * Join the merged device rows with the eligibility verdict so the UI can NAME
40257
- * why an accelerator is not in play instead of leaving the operator to deduce
40258
- * it from `enabled`/`available`.
40259
- *
40260
- * Deduction is not possible for two of the four reasons — `accelerator-preferred`
40261
- * is a node-WIDE rule (a CPU row reads `enabled:true, available:true` and still
40262
- * never gets a session, D215) and `cannot-host-camera-root` needs the node's
40263
- * model catalog. Both live in {@link resolveInferenceDeviceEligibility}, so this
40264
- * function only transports its answer; it never re-derives one.
40265
- *
40266
- * Pure; preserves `merged`'s order (sorted by key) and every other field.
40307
+ * Cancellable sleep wakes early when `lifecycle.stopped` flips. We
40308
+ * keep a local wrapper around the shared {@link sleep} helper because
40309
+ * the lifecycle tracks the active retry timer for `teardown()` to
40310
+ * clear; pure `sleep()` would leak the timer if teardown fired while
40311
+ * we were waiting.
40267
40312
  */
40268
- function annotateInferenceDeviceExclusions(merged, eligibility) {
40269
- const reasonByKey = new Map(eligibility.excluded.map((e) => [e.key, e.reason]));
40270
- return merged.map((view) => ({
40271
- ...view,
40272
- exclusion: reasonByKey.get(view.key) ?? null
40273
- }));
40313
+ function sleep(ms, lifecycle) {
40314
+ return new Promise((resolve) => {
40315
+ if (lifecycle.stopped) {
40316
+ resolve();
40317
+ return;
40318
+ }
40319
+ lifecycle.retryTimer = setTimeout(() => {
40320
+ lifecycle.retryTimer = void 0;
40321
+ resolve();
40322
+ }, ms);
40323
+ });
40274
40324
  }
40275
- function resolveNodeInferenceUsability(eligibility) {
40276
- const eligibleKeys = Object.keys(eligibility.eligible).toSorted();
40277
- const unavailableKeys = eligibility.excluded.filter((e) => e.reason === "unavailable").map((e) => e.key).toSorted();
40325
+ //#endregion
40326
+ //#region src/audio-load-balancer.ts
40327
+ function balanceAudio(input) {
40328
+ if (input.nodes.length === 0) return null;
40329
+ if (input.preferredNode) {
40330
+ const pinned = input.nodes.find((n) => n.nodeId === input.preferredNode);
40331
+ if (pinned) return {
40332
+ nodeId: pinned.nodeId,
40333
+ reason: "manual"
40334
+ };
40335
+ }
40278
40336
  return {
40279
- usable: eligibleKeys.length > 0 || unavailableKeys.length === 0,
40280
- unavailableKeys,
40281
- eligibleKeys
40337
+ nodeId: input.nodes.slice().toSorted((a, b) => a.deviceCount - b.deviceCount)[0].nodeId,
40338
+ reason: "capacity"
40282
40339
  };
40283
40340
  }
40341
+ //#endregion
40342
+ //#region src/orchestrator-types.ts
40343
+ var PHASE_MODE_VALUES = new Set([
40344
+ "disabled",
40345
+ "always-on",
40346
+ "on-motion"
40347
+ ]);
40348
+ function isPipelinePhaseMode(v) {
40349
+ return PHASE_MODE_VALUES.has(v);
40350
+ }
40284
40351
  /**
40285
- * Step-tree device jump (phase 1): the attach-payload roster of a node's
40286
- * enabled∧available inference devices with the balancer knobs (`weight`,
40287
- * `maxSessions`) the runner uses to AUTO-jump an enrichment step off a device
40288
- * whose format can't run it. Built from the SAME `eligible` (deviceKey→weight)
40289
- * and `caps` (deviceKey→maxSessions) the dispatcher already computes, so the
40290
- * roster the runner sees exactly matches the balancer's candidate set. Sorted
40291
- * by key for determinism. Populated onto `RunnerCameraConfig.inferenceDevices`
40292
- * ONLY when a `deviceKey` is elected and there are ≥2 entries.
40293
- */
40294
- function buildInferenceDeviceRoster(eligible, caps) {
40295
- return Object.entries(eligible).map(([deviceKey, weight]) => ({
40296
- deviceKey,
40297
- weight: weight > 0 ? weight : 1,
40298
- maxSessions: caps[deviceKey] ?? null
40299
- })).toSorted((a, b) => a.deviceKey < b.deviceKey ? -1 : a.deviceKey > b.deviceKey ? 1 : 0);
40300
- }
40301
- //#endregion
40302
- //#region src/node-inference-usability-mirror.ts
40303
- var NodeInferenceUsabilityMirror = class {
40304
- state = /* @__PURE__ */ new Map();
40305
- /**
40306
- * Fold one observation in and report whether the caller should act.
40307
- * Never throws.
40308
- */
40309
- observe(nodeId, usable) {
40310
- const prev = this.state.get(nodeId);
40311
- if (usable) {
40312
- this.state.set(nodeId, {
40313
- usable: true,
40314
- armed: false
40315
- });
40316
- return prev !== void 0 && !prev.usable ? "recovered" : null;
40317
- }
40318
- if (prev === void 0) {
40319
- this.state.set(nodeId, {
40320
- usable: true,
40321
- armed: true
40322
- });
40323
- return null;
40324
- }
40325
- if (!prev.usable) {
40326
- this.state.set(nodeId, {
40327
- usable: false,
40328
- armed: true
40329
- });
40330
- return null;
40331
- }
40332
- if (!prev.armed) {
40333
- this.state.set(nodeId, {
40334
- usable: true,
40335
- armed: true
40336
- });
40337
- return null;
40338
- }
40339
- this.state.set(nodeId, {
40340
- usable: false,
40341
- armed: true
40342
- });
40343
- return "became-unusable";
40344
- }
40345
- /** Can this node be given cameras? Unknown nodes answer YES. */
40346
- isUsable(nodeId) {
40347
- return this.state.get(nodeId)?.usable ?? true;
40348
- }
40349
- /** Nodes currently excluded — for the placement log and diagnostics. */
40350
- unusableNodeIds() {
40351
- const out = [];
40352
- for (const [nodeId, s] of this.state) if (!s.usable) out.push(nodeId);
40353
- return out.toSorted();
40354
- }
40355
- forget(nodeId) {
40356
- this.state.delete(nodeId);
40357
- }
40358
- reset() {
40359
- this.state.clear();
40360
- }
40361
- };
40362
- //#endregion
40363
- //#region src/inference-device-usability-mirror.ts
40364
- /**
40365
- * InferenceDeviceUsabilityMirror — "can this NODE's THIS DEVICE still infer?",
40366
- * kept off the placement path.
40367
- *
40368
- * The per-`(nodeId, deviceKey)` twin of {@link NodeInferenceUsabilityMirror},
40369
- * and deliberately not a second mechanism: it composes the key and delegates
40370
- * every decision to that class, so the arm/apply reluctance D49 pinned lives in
40371
- * exactly one implementation and cannot drift between the node tier and the
40372
- * device tier.
40373
- *
40374
- * ## Why this tier had to exist
40375
- *
40376
- * The node tier already answers "does this node have ANY usable accelerator".
40377
- * On 2026-08-25 the hub's answer was, correctly, yes — its NPU was healthy the
40378
- * whole time. What died was one DEVICE, `openvino:gpu`, and nothing anywhere
40379
- * asked that question: the per-dispatch capability gate is keyed on model
40380
- * FORMAT and `openvino:gpu` and `openvino:npu` share the format `openvino`, so
40381
- * it is blind between them by construction. The balancer kept rotating cameras
40382
- * onto the dead pool — 20 sessions in 20 minutes, every one `tieBreak:
40383
- * "rotation"` — for 31 hours.
40384
- *
40385
- * ## Why a mirror and not the event
40386
- *
40387
- * D49, verbatim: *a one-shot event never gates on a fallible read*. The gate is
40388
- * this in-memory mirror, refreshed off the event path by the same
40389
- * `resolveEligibleInferenceDevices` the dispatcher already runs (plus the
40390
- * session controller's background refresher). The consequences that buys:
40391
- *
40392
- * - **A read that fails changes nothing.** The caller folds in an observation
40393
- * only when it HAS one; an unreachable node, a version-skewed executor or a
40394
- * rejected RPC never reaches {@link observe}, so the previous verdict
40395
- * stands. This is the whole reason the health read is specified as
40396
- * "synchronous over in-memory state, never throws for its own reasons": an
40397
- * empty answer must mean *nothing is refused*, not *I could not tell*.
40398
- * - **Excluding a healthy device needs a second, consecutive read.** Exclusion
40399
- * is the direction that DESTROYS work — it strands an accelerator that may
40400
- * be perfectly fine — so one bad observation only ARMS.
40401
- * - **Re-admitting is immediate and unconditional.** One good observation puts
40402
- * the device straight back. Being slow to exclude costs some wasted
40403
- * inference attempts; being slow to re-admit costs an idle accelerator and a
40404
- * node that looks broken.
40405
- */
40406
- /**
40407
- * NUL — impossible in both a Moleculer node id and a `<backend>:<device>` key,
40408
- * so the composite key can never be ambiguous. A separator that CAN occur in
40409
- * either half makes two distinct pairs collide, and a collision here silently
40410
- * excludes an accelerator nobody reported.
40411
- */
40412
- var SEPARATOR = "\0";
40413
- var InferenceDeviceUsabilityMirror = class {
40414
- /** The one implementation of the arm/apply state machine (D49). */
40415
- mirror = new NodeInferenceUsabilityMirror();
40416
- /**
40417
- * Fold one observation in and report whether the caller should act.
40418
- * Never throws.
40419
- */
40420
- observe(nodeId, deviceKey, usable) {
40421
- return this.mirror.observe(`${nodeId}${SEPARATOR}${deviceKey}`, usable);
40422
- }
40423
- /** Can the balancer put a session on this device? Unknown pairs answer YES. */
40424
- isUsable(nodeId, deviceKey) {
40425
- return this.mirror.isUsable(`${nodeId}${SEPARATOR}${deviceKey}`);
40426
- }
40427
- /** Pairs currently excluded — for the placement log and diagnostics. */
40428
- unusableDevices() {
40429
- return this.mirror.unusableNodeIds().map((composite) => {
40430
- const at = composite.indexOf(SEPARATOR);
40431
- return {
40432
- nodeId: composite.slice(0, at),
40433
- deviceKey: composite.slice(at + 1)
40434
- };
40435
- });
40436
- }
40437
- /** The excluded device keys on ONE node. */
40438
- unusableDeviceKeys(nodeId) {
40439
- return this.unusableDevices().filter((d) => d.nodeId === nodeId).map((d) => d.deviceKey);
40440
- }
40441
- forget(nodeId, deviceKey) {
40442
- this.mirror.forget(`${nodeId}${SEPARATOR}${deviceKey}`);
40443
- }
40444
- reset() {
40445
- this.mirror.reset();
40446
- }
40447
- };
40448
- /**
40449
- * Fold ONE node's health answer into the mirror and return what changed.
40450
- *
40451
- * This is the whole reading discipline, in one place, because both halves of it
40452
- * are easy to get subtly wrong and neither failure is visible in a log:
40453
- *
40454
- * - **`unhealthy === null` — the read FAILED — changes nothing.** Not a single
40455
- * entry is touched. An unreachable node, a version-skewed executor or a
40456
- * rejected RPC must be distinguishable from "asked, nothing is refused", or
40457
- * a flaky link silently re-admits a dead accelerator (D49).
40458
- * - **Every device the node HAS is observed**, not merely the refused ones.
40459
- * The first draft observed `refused ∪ already-excluded`, which omits exactly
40460
- * the devices the mirror has ARMED — so their disarming good read never
40461
- * arrived and two bad reads an HOUR apart, with a hundred healthy ones
40462
- * between them, excluded a working accelerator. "Consecutive" is only a
40463
- * property if the good observations are delivered.
40464
- *
40465
- * Pure with respect to everything except `mirror`, and never throws — it is
40466
- * called from the dispatcher's own read path.
40467
- */
40468
- function foldInferenceDeviceHealth(mirror, nodeId, unhealthy, present) {
40469
- if (unhealthy === null) return [];
40470
- const refused = new Set(unhealthy);
40471
- const observed = new Set([
40472
- ...present,
40473
- ...refused,
40474
- ...mirror.unusableDeviceKeys(nodeId)
40475
- ]);
40476
- const changes = [];
40477
- for (const deviceKey of observed) {
40478
- const transition = mirror.observe(nodeId, deviceKey, !refused.has(deviceKey));
40479
- if (transition !== null) changes.push({
40480
- deviceKey,
40481
- transition
40482
- });
40483
- }
40484
- return changes;
40485
- }
40486
- //#endregion
40487
- //#region src/orchestrator-types.ts
40488
- var PHASE_MODE_VALUES = new Set([
40489
- "disabled",
40490
- "always-on",
40491
- "on-motion"
40492
- ]);
40493
- function isPipelinePhaseMode(v) {
40494
- return PHASE_MODE_VALUES.has(v);
40495
- }
40496
- /**
40497
- * Periodic sweep interval for `retryPendingDispatches` — re-dispatches cameras
40498
- * that are KNOWN but UNASSIGNED (pending/over-cap/no-frame-source/load-shed).
40499
- * `reconcileDispatch` is additive-only and never revisits these, so a slow
40500
- * safety-net timer + event-driven debounce triggers recover them.
40352
+ * Periodic sweep interval for `retryPendingDispatches` re-dispatches cameras
40353
+ * that are KNOWN but UNASSIGNED (pending/over-cap/no-frame-source/load-shed).
40354
+ * `reconcileDispatch` is additive-only and never revisits these, so a slow
40355
+ * safety-net timer + event-driven debounce triggers recover them.
40501
40356
  */
40502
40357
  var PENDING_RETRY_INTERVAL_MS = 6e4;
40503
40358
  /** Debounce window for `schedulePendingRetry` — coalesces capacity/eligibility/readiness signals. */
@@ -40616,264 +40471,6 @@ var pipelineOrchestratorActions = defineCustomActions({
40616
40471
  */
40617
40472
  var TRANSIENT_SLOT_READ = Symbol("transient-slot-read");
40618
40473
  //#endregion
40619
- //#region src/audio-chunk-poller.ts
40620
- /**
40621
- * `AudioChunkPoller` — the consumer-side poll loop of the decoded audio-chunk
40622
- * plane (Phase 5 / D9).
40623
- *
40624
- * Replaces the live-object `IStreamBroker.onDecodedAudioChunk(cb)` callback
40625
- * path. A live callback cannot cross a process boundary; once the `pipeline`
40626
- * group is dissolved (Task 8) the orchestrator runs in a different process
40627
- * from the broker, so audio delivery must go over tRPC.
40628
- *
40629
- * The consumer:
40630
- *
40631
- * 1. `subscribeAudioChunks({ brokerId, tag })` over tRPC — the broker
40632
- * registers a per-subscription bounded FIFO queue and returns a
40633
- * `subscriptionId`;
40634
- * 2. polls `pullAudioChunks({ subscriptionId, maxCount })` on a modest
40635
- * interval, draining `DecodedAudioChunk`s in FIFO arrival order;
40636
- * 3. feeds each chunk to its downstream audio logic;
40637
- * 4. on teardown, `unsubscribeAudioChunks`.
40638
- *
40639
- * Audio is not latency-critical like video, and chunks arrive only ~every
40640
- * 500ms (the broker's `AudioCodecSession` window). A modest poll period plus
40641
- * a small per-poll burst keeps latency low without busy-spinning. The
40642
- * broker's queue is FIFO/no-drop-sized so a poll-period of jitter never
40643
- * loses a chunk.
40644
- *
40645
- * Boot-race tolerance: the broker for a given camStream may not be registered
40646
- * yet when the orchestrator wires the subscription (provider addons publish
40647
- * their cameraStreams asynchronously after their probe completes).
40648
- * `subscribeAudioChunks` retries with exponential backoff (capped at
40649
- * `MAX_SUBSCRIBE_RETRY_BACKOFF_MS`) until it succeeds or the returned
40650
- * teardown closure is invoked. Mirrors the `FrameHandlePoller` recovery
40651
- * shape so video and audio plumbing self-heal identically.
40652
- */
40653
- /** Poll period — audio chunks arrive ~every 500ms; 200ms keeps latency low. */
40654
- var POLL_INTERVAL_MS$1 = 200;
40655
- /** How many chunks to drain per poll — a small burst absorbs jitter. */
40656
- var PULL_MAX_COUNT = 8;
40657
- /**
40658
- * Consecutive pull failures before we attempt to re-subscribe. A single failed
40659
- * poll is treated as a blip (re-subscribing would leak a broker-side FIFO); a
40660
- * sustained failure means the broker child restarted and dropped our
40661
- * subscription, so we re-establish it.
40662
- */
40663
- var RESUBSCRIBE_AFTER_FAILURES = 2;
40664
- /** Re-subscribe at most once every N ticks while failing (~1s at 200ms). */
40665
- var RESUBSCRIBE_THROTTLE_TICKS = 5;
40666
- /** First subscribe-retry delay, doubled on every subsequent failure. */
40667
- var INITIAL_SUBSCRIBE_RETRY_BACKOFF_MS = 250;
40668
- /**
40669
- * Subscribe-retry backoff ceiling. 5 s matches the frame-handle poller — fast
40670
- * enough to recover within a single reconcile of the orchestrator and slow
40671
- * enough that a misconfigured camStream costs ~12 op/min, not 5/s.
40672
- */
40673
- var MAX_SUBSCRIBE_RETRY_BACKOFF_MS = 5e3;
40674
- /**
40675
- * Attempts after which a still-failing subscribe escalates from the fast 5 s
40676
- * ceiling to {@link LONG_SUBSCRIBE_RETRY_BACKOFF_MS}. ~15 attempts ≈ one
40677
- * minute of fast retries — plenty for the boot races the 5 s ceiling exists
40678
- * for. A broker that is STILL absent after that is a long-lived condition
40679
- * (e.g. a DISABLED camera, whose broker the stream-broker reconcile refuses
40680
- * to recreate — 2026-07-23) and retrying every 5 s forever is pure log/RPC
40681
- * churn. The slow loop stays alive so audio still recovers automatically
40682
- * (≤60 s) once the camera is re-enabled.
40683
- */
40684
- var PERSISTENT_SUBSCRIBE_FAILURE_ATTEMPTS = 15;
40685
- var LONG_SUBSCRIBE_RETRY_BACKOFF_MS = 6e4;
40686
- /**
40687
- * Subscribe to a broker's decoded audio-chunk stream and start the poll loop.
40688
- *
40689
- * Always resolves to a teardown closure — when the broker is not yet
40690
- * registered the closure cancels the ongoing retry loop; when polling is
40691
- * active it stops the loop and releases the broker subscription. Mirrors
40692
- * `startFrameHandlePoller` so video and audio recover identically.
40693
- */
40694
- function startAudioChunkPoller(options) {
40695
- const lifecycle = {
40696
- stopped: false,
40697
- retryTimer: void 0,
40698
- pollTimer: void 0,
40699
- activeSubscriptionId: null
40700
- };
40701
- const teardown = () => {
40702
- if (lifecycle.stopped) return;
40703
- lifecycle.stopped = true;
40704
- if (lifecycle.retryTimer) {
40705
- clearTimeout(lifecycle.retryTimer);
40706
- lifecycle.retryTimer = void 0;
40707
- }
40708
- if (lifecycle.pollTimer) {
40709
- clearTimeout(lifecycle.pollTimer);
40710
- lifecycle.pollTimer = void 0;
40711
- }
40712
- const subId = lifecycle.activeSubscriptionId;
40713
- if (subId) {
40714
- lifecycle.activeSubscriptionId = null;
40715
- options.api.streamBroker.unsubscribeAudioChunks.mutate({ subscriptionId: subId }, nodePin(options.ownerNodeId)).catch((err) => {
40716
- options.logger.warn("audio-chunk poller: unsubscribeAudioChunks failed", { meta: {
40717
- brokerId: options.brokerId,
40718
- subscriptionId: subId,
40719
- error: errMsg(err)
40720
- } });
40721
- });
40722
- }
40723
- };
40724
- subscribeWithRetry(options, lifecycle);
40725
- return teardown;
40726
- }
40727
- /**
40728
- * Run the subscribe → poll handshake with exponential backoff on subscribe
40729
- * failures. Resolves once the subscription is acquired (and the poll loop has
40730
- * been started) or once `lifecycle.stopped` flips, whichever comes first.
40731
- */
40732
- async function subscribeWithRetry(options, lifecycle) {
40733
- const { api, brokerId, tag, ownerNodeId, logger } = options;
40734
- const pin = nodePin(ownerNodeId);
40735
- let backoffMs = INITIAL_SUBSCRIBE_RETRY_BACKOFF_MS;
40736
- let attempt = 0;
40737
- while (!lifecycle.stopped) {
40738
- attempt += 1;
40739
- try {
40740
- const result = await api.streamBroker.subscribeAudioChunks.mutate({
40741
- brokerId,
40742
- tag
40743
- }, pin);
40744
- if (lifecycle.stopped) {
40745
- await api.streamBroker.unsubscribeAudioChunks.mutate({ subscriptionId: result.subscriptionId }, pin).catch((err) => {
40746
- logger.warn("audio-chunk poller: late unsubscribe failed", { meta: {
40747
- brokerId,
40748
- subscriptionId: result.subscriptionId,
40749
- error: errMsg(err)
40750
- } });
40751
- });
40752
- return;
40753
- }
40754
- if (attempt > 1) logger.info("audio-chunk poller: subscribeAudioChunks recovered", { meta: {
40755
- brokerId,
40756
- tag,
40757
- attempt
40758
- } });
40759
- lifecycle.activeSubscriptionId = result.subscriptionId;
40760
- startPolling(options, lifecycle);
40761
- return;
40762
- } catch (err) {
40763
- if (lifecycle.stopped) return;
40764
- if (attempt === 1) logger.warn("audio-chunk poller: subscribeAudioChunks failed, retrying", { meta: {
40765
- brokerId,
40766
- tag,
40767
- error: errMsg(err),
40768
- nextRetryInMs: backoffMs
40769
- } });
40770
- else logger.debug("audio-chunk poller: subscribeAudioChunks still failing", { meta: {
40771
- brokerId,
40772
- tag,
40773
- attempt,
40774
- error: errMsg(err),
40775
- nextRetryInMs: backoffMs
40776
- } });
40777
- await sleep(backoffMs, lifecycle);
40778
- backoffMs = Math.min(attempt >= PERSISTENT_SUBSCRIBE_FAILURE_ATTEMPTS ? LONG_SUBSCRIBE_RETRY_BACKOFF_MS : MAX_SUBSCRIBE_RETRY_BACKOFF_MS, backoffMs * 2);
40779
- }
40780
- }
40781
- }
40782
- /**
40783
- * Drive the steady-state poll loop. Mid-stream `pullAudioChunks` failures
40784
- * trigger a fresh `subscribeAudioChunks` via the recovery branch — covers
40785
- * the broker child restart case where our `subscriptionId` is silently
40786
- * disowned.
40787
- */
40788
- function startPolling(options, lifecycle) {
40789
- const { api, brokerId, tag, ownerNodeId, onChunk, logger } = options;
40790
- const pin = nodePin(ownerNodeId);
40791
- let consecutiveFailures = 0;
40792
- const resubscribe = async () => {
40793
- try {
40794
- const result = await api.streamBroker.subscribeAudioChunks.mutate({
40795
- brokerId,
40796
- tag
40797
- }, pin);
40798
- lifecycle.activeSubscriptionId = result.subscriptionId;
40799
- logger.info("audio-chunk poller: re-subscribed after broker outage", { meta: {
40800
- brokerId,
40801
- tag,
40802
- subscriptionId: result.subscriptionId,
40803
- afterFailures: consecutiveFailures
40804
- } });
40805
- return true;
40806
- } catch {
40807
- return false;
40808
- }
40809
- };
40810
- const tick = async () => {
40811
- if (lifecycle.stopped) return;
40812
- const subId = lifecycle.activeSubscriptionId;
40813
- if (!subId) return;
40814
- try {
40815
- const chunks = await api.streamBroker.pullAudioChunks.query({
40816
- subscriptionId: subId,
40817
- maxCount: PULL_MAX_COUNT
40818
- }, pin);
40819
- if (consecutiveFailures > 0) logger.info("audio-chunk poller: stream recovered", { meta: {
40820
- brokerId,
40821
- subscriptionId: subId
40822
- } });
40823
- consecutiveFailures = 0;
40824
- for (const chunk of chunks) {
40825
- if (lifecycle.stopped) break;
40826
- await onChunk(chunk);
40827
- }
40828
- } catch (err) {
40829
- consecutiveFailures += 1;
40830
- if (consecutiveFailures === 1) logger.warn("audio-chunk poller: pullAudioChunks failed — attempting recovery", { meta: {
40831
- brokerId,
40832
- subscriptionId: subId,
40833
- error: errMsg(err)
40834
- } });
40835
- if (!lifecycle.stopped && consecutiveFailures >= RESUBSCRIBE_AFTER_FAILURES && (consecutiveFailures - RESUBSCRIBE_AFTER_FAILURES) % RESUBSCRIBE_THROTTLE_TICKS === 0) await resubscribe();
40836
- }
40837
- if (!lifecycle.stopped) lifecycle.pollTimer = setTimeout(() => void tick(), POLL_INTERVAL_MS$1);
40838
- };
40839
- tick();
40840
- }
40841
- /**
40842
- * Cancellable sleep — wakes early when `lifecycle.stopped` flips. We
40843
- * keep a local wrapper around the shared {@link sleep} helper because
40844
- * the lifecycle tracks the active retry timer for `teardown()` to
40845
- * clear; pure `sleep()` would leak the timer if teardown fired while
40846
- * we were waiting.
40847
- */
40848
- function sleep(ms, lifecycle) {
40849
- return new Promise((resolve) => {
40850
- if (lifecycle.stopped) {
40851
- resolve();
40852
- return;
40853
- }
40854
- lifecycle.retryTimer = setTimeout(() => {
40855
- lifecycle.retryTimer = void 0;
40856
- resolve();
40857
- }, ms);
40858
- });
40859
- }
40860
- //#endregion
40861
- //#region src/audio-load-balancer.ts
40862
- function balanceAudio(input) {
40863
- if (input.nodes.length === 0) return null;
40864
- if (input.preferredNode) {
40865
- const pinned = input.nodes.find((n) => n.nodeId === input.preferredNode);
40866
- if (pinned) return {
40867
- nodeId: pinned.nodeId,
40868
- reason: "manual"
40869
- };
40870
- }
40871
- return {
40872
- nodeId: input.nodes.slice().toSorted((a, b) => a.deviceCount - b.deviceCount)[0].nodeId,
40873
- reason: "capacity"
40874
- };
40875
- }
40876
- //#endregion
40877
40474
  //#region src/audio-window-accumulator.ts
40878
40475
  var AudioWindowAccumulator = class {
40879
40476
  deviceId;
@@ -41377,234 +40974,847 @@ var AudioSubscriptionController = class {
41377
40974
  meta: { error: errMsg(err) }
41378
40975
  });
41379
40976
  });
41380
- }, windowMs);
41381
- this.motionAudioWindowTimers.set(deviceId, timer);
41382
- }
41383
- /** True while a motion-driven audio window is open for this device. */
41384
- isMotionAudioWindowOpen(deviceId) {
41385
- return this.motionAudioWindowTimers.has(deviceId);
41386
- }
41387
- /**
41388
- * Close an on-motion audio window and drop its subscription. Shared by both
41389
- * closers (quiet window elapsed / falling edge cooldown) so they can never
41390
- * disagree about what "closed" means. `reason` is logged so a camera that
41391
- * loses audio can always be told WHY from the per-device log view.
41392
- */
41393
- async closeMotionAudioWindow(deviceId, reason) {
41394
- const pendingWindow = this.motionAudioWindowTimers.get(deviceId);
41395
- if (pendingWindow) {
41396
- clearTimeout(pendingWindow);
41397
- this.motionAudioWindowTimers.delete(deviceId);
40977
+ }, windowMs);
40978
+ this.motionAudioWindowTimers.set(deviceId, timer);
40979
+ }
40980
+ /** True while a motion-driven audio window is open for this device. */
40981
+ isMotionAudioWindowOpen(deviceId) {
40982
+ return this.motionAudioWindowTimers.has(deviceId);
40983
+ }
40984
+ /**
40985
+ * Close an on-motion audio window and drop its subscription. Shared by both
40986
+ * closers (quiet window elapsed / falling edge cooldown) so they can never
40987
+ * disagree about what "closed" means. `reason` is logged so a camera that
40988
+ * loses audio can always be told WHY from the per-device log view.
40989
+ */
40990
+ async closeMotionAudioWindow(deviceId, reason) {
40991
+ const pendingWindow = this.motionAudioWindowTimers.get(deviceId);
40992
+ if (pendingWindow) {
40993
+ clearTimeout(pendingWindow);
40994
+ this.motionAudioWindowTimers.delete(deviceId);
40995
+ }
40996
+ await this.withAudioSubLock(deviceId, async () => {
40997
+ const unsub = this.audioSubscriptions.get(deviceId);
40998
+ if (!unsub) return;
40999
+ try {
41000
+ unsub();
41001
+ } catch {}
41002
+ this.audioSubscriptions.delete(deviceId);
41003
+ this.deps.logger.info("lazy audio: window closed", {
41004
+ tags: { deviceId },
41005
+ meta: { reason }
41006
+ });
41007
+ });
41008
+ }
41009
+ /**
41010
+ * Audio teardown for one device — the audio half of `stopDetection`.
41011
+ * Tears down through the per-device lock so it can't race a concurrent
41012
+ * subscribe (which would re-store a handle this teardown never sees).
41013
+ */
41014
+ async stopForDevice(deviceId) {
41015
+ await this.withAudioSubLock(deviceId, async () => {
41016
+ const unsub = this.audioSubscriptions.get(deviceId);
41017
+ if (unsub) {
41018
+ try {
41019
+ unsub();
41020
+ } catch {}
41021
+ this.audioSubscriptions.delete(deviceId);
41022
+ }
41023
+ });
41024
+ const lazyTimer = this.lazyAudioTeardownTimers.get(deviceId);
41025
+ if (lazyTimer) {
41026
+ clearTimeout(lazyTimer);
41027
+ this.lazyAudioTeardownTimers.delete(deviceId);
41028
+ }
41029
+ const windowTimer = this.motionAudioWindowTimers.get(deviceId);
41030
+ if (windowTimer) {
41031
+ clearTimeout(windowTimer);
41032
+ this.motionAudioWindowTimers.delete(deviceId);
41033
+ }
41034
+ this.audioAssignments.delete(deviceId);
41035
+ }
41036
+ /**
41037
+ * Centralized write into `audioSubscriptions`. If shutdown has begun, the
41038
+ * map has already been (or is about to be) cleared lock-free in
41039
+ * `shutdown()`; storing here would leak a zombie entry whose `unsub` is
41040
+ * never called. So when shutting down we immediately invoke `unsub`
41041
+ * (best-effort, error-swallowed) and DO NOT store. `protected` so
41042
+ * `audio-sub-lock.spec.ts`'s test subclass can assert the shutdown-guard
41043
+ * behavior without casts.
41044
+ */
41045
+ storeAudioSub(deviceId, unsub) {
41046
+ if (this.audioShuttingDown) {
41047
+ try {
41048
+ unsub();
41049
+ } catch {}
41050
+ return;
41051
+ }
41052
+ this.audioSubscriptions.set(deviceId, unsub);
41053
+ }
41054
+ /**
41055
+ * Serialize an audio-subscription critical section per device. `fn` is
41056
+ * chained onto the device's current lock tail, so concurrent calls for the
41057
+ * SAME deviceId run sequentially (FIFO); different deviceIds never block
41058
+ * each other. Thin delegate onto the `audioSubLocks` `KeyedAsyncLock`
41059
+ * instance. `protected` so `audio-sub-lock.spec.ts`'s test subclass can
41060
+ * drive the lock without casts.
41061
+ */
41062
+ withAudioSubLock(deviceId, fn) {
41063
+ return this.audioSubLocks.run(deviceId, fn);
41064
+ }
41065
+ /**
41066
+ * Subscribe to decoded audio chunks for a camera and feed them into the
41067
+ * audio-analyzer. Reads the analyzer's settings via its own
41068
+ * `resolveDeviceSettings(deviceId)` method so the orchestrator does not
41069
+ * touch the audio-analyzer schema field names directly.
41070
+ */
41071
+ async subscribeAudioStream(deviceId, config) {
41072
+ const api = this.deps.api();
41073
+ if (!api) {
41074
+ this.deps.logger.warn("this.ctx.api not available — cannot subscribe audio", { tags: { deviceId } });
41075
+ return null;
41076
+ }
41077
+ if (!await this.deps.isAudioAnalysisActive(deviceId)) return null;
41078
+ if (config.audioMode === "disabled") {
41079
+ this.deps.logger.debug("audio subscribe skipped: audioMode=disabled", { tags: { deviceId } });
41080
+ return null;
41081
+ }
41082
+ if (config.audioMode === "on-motion" && !this.isMotionAudioWindowOpen(deviceId)) {
41083
+ this.deps.logger.info("audio subscribe deferred: audioMode=on-motion, no window open", { tags: { deviceId } });
41084
+ return null;
41085
+ }
41086
+ const audioStream = config.audioStreamId ?? config.motionStreamId;
41087
+ const audioBrokerId = makeSourceBrokerId(deviceId, audioStream);
41088
+ if ((await this.deps.probeAudioTrack(deviceId, audioStream)).kind === "absent") {
41089
+ this.deps.logger.warn("audio subscription REFUSED — this stream carries no audio track", {
41090
+ tags: { deviceId },
41091
+ meta: {
41092
+ camStreamId: audioStream,
41093
+ brokerId: audioBrokerId,
41094
+ selectedBy: config.audioStreamId !== void 0 ? "audioStreamId" : "motionStreamId",
41095
+ hint: "point the camera’s audio at a stream that has an audio track — no stream is substituted automatically"
41096
+ }
41097
+ });
41098
+ return null;
41099
+ }
41100
+ const settings = await api.audioAnalysis.resolveDeviceSettings.query({ deviceId });
41101
+ if (!settings) {
41102
+ this.deps.logger.warn("audio-analysis returned no settings — audio subscription skipped", { tags: { deviceId } });
41103
+ return null;
41104
+ }
41105
+ const audioNodeId = await this.dispatch(deviceId);
41106
+ const isRemoteAudio = audioNodeId !== this.deps.localNodeId();
41107
+ this.deps.logger.info("audio subscription: resolved audio node", {
41108
+ tags: { deviceId },
41109
+ meta: {
41110
+ audioNodeId,
41111
+ isRemote: isRemoteAudio
41112
+ }
41113
+ });
41114
+ const accumulator = new AudioWindowAccumulator(deviceId);
41115
+ const teardown = startAudioChunkPoller({
41116
+ api,
41117
+ brokerId: audioBrokerId,
41118
+ tag: "audio-analyzer",
41119
+ ownerNodeId: this.deps.ingestNode(),
41120
+ logger: this.deps.logger.withTags({ deviceId }),
41121
+ onChunk: async (chunk) => {
41122
+ this.deps.watchdogNote(deviceId, "audio");
41123
+ try {
41124
+ const audioChunkInput = accumulator.push(chunk);
41125
+ if (!audioChunkInput) return;
41126
+ const result = await api.audioAnalyzer.analyseChunk.mutate({
41127
+ chunk: audioChunkInput,
41128
+ settings,
41129
+ ...isRemoteAudio ? { nodeId: audioNodeId } : {}
41130
+ });
41131
+ if (!result) return;
41132
+ const frame = buildAudioResultFrame(deviceId, result);
41133
+ this.deps.eventBus.emit({
41134
+ id: `audio-inference-${deviceId}-${Date.now()}`,
41135
+ timestamp: /* @__PURE__ */ new Date(),
41136
+ source: {
41137
+ type: "device",
41138
+ id: deviceId,
41139
+ nodeId: "hub",
41140
+ addonId: "pipeline-orchestrator",
41141
+ deviceId
41142
+ },
41143
+ category: EventCategory.PipelineAudioInferenceResult,
41144
+ data: {
41145
+ deviceId,
41146
+ frame,
41147
+ nodeId: "hub"
41148
+ }
41149
+ });
41150
+ } catch (err) {
41151
+ const msg = errMsg(err);
41152
+ this.deps.logger.error("Audio analysis failed", {
41153
+ tags: { deviceId },
41154
+ meta: { error: msg }
41155
+ });
41156
+ }
41157
+ }
41158
+ });
41159
+ this.deps.logger.info("Audio stream subscribed", { tags: { deviceId } });
41160
+ return () => {
41161
+ teardown();
41162
+ accumulator.reset();
41163
+ };
41164
+ }
41165
+ /**
41166
+ * Set true at the very start of `onShutdown`, before the audio teardown /
41167
+ * map clears below. Once set, `withAudioSubLock` turns queued/new critical
41168
+ * sections into no-ops and `storeAudioSub` refuses to store, so no
41169
+ * critical section that was in-flight (or queued) when shutdown began can
41170
+ * resurrect a zombie subscription into the cleared `audioSubscriptions`
41171
+ * map. MUST be called before anything else in `onShutdown` that could
41172
+ * race a queued audio critical section (mirrors the original
41173
+ * `this.audioShuttingDown = true` being the very first statement).
41174
+ */
41175
+ beginShutdown() {
41176
+ this.audioShuttingDown = true;
41177
+ }
41178
+ /**
41179
+ * Full audio teardown — combines the former `onShutdown`'s two separate
41180
+ * audio blocks (lazy-teardown-timer clear, then — after several unrelated
41181
+ * session/reconcile/load-shed clears — subscription teardown + lock clear
41182
+ * + assignment-map clears) into one call. Safe to combine: both blocks
41183
+ * are synchronous with no interleaved `await`, and every original
41184
+ * statement between them (`sessionRegistry.clear()`,
41185
+ * `cameraFpsMap.clear()`, `remoteHealthAttempts.clear()`,
41186
+ * `loadShedState.clear()`, `loadShedResumeTimer` cleanup) touches state
41187
+ * fully disjoint from anything audio — so their relative order to each
41188
+ * other is unaffected, and the audio-internal order (timers →
41189
+ * subscriptions → lock → assignment maps) is reproduced exactly.
41190
+ */
41191
+ shutdown() {
41192
+ for (const t of this.lazyAudioTeardownTimers.values()) clearTimeout(t);
41193
+ this.lazyAudioTeardownTimers.clear();
41194
+ for (const t of this.motionAudioWindowTimers.values()) clearTimeout(t);
41195
+ this.motionAudioWindowTimers.clear();
41196
+ for (const unsub of this.audioSubscriptions.values()) try {
41197
+ unsub();
41198
+ } catch {}
41199
+ this.audioSubscriptions.clear();
41200
+ this.audioSubLocks.clear();
41201
+ this.audioAssignments.clear();
41202
+ this.readyAudioNodes.clear();
41203
+ }
41204
+ };
41205
+ //#endregion
41206
+ //#region src/disk-reconcile-fleet.ts
41207
+ async function reconcileFleetFromDisk(deps) {
41208
+ const deviceIds = await deps.listDeviceIds();
41209
+ const failed = [];
41210
+ let cameras = 0;
41211
+ let mediaDropped = 0;
41212
+ let tracks = 0;
41213
+ let events = 0;
41214
+ let completed = 0;
41215
+ for (const deviceId of deviceIds) {
41216
+ try {
41217
+ await deps.rescanRecordings(deviceId);
41218
+ const counts = await deps.reconcileAnalytics(deviceId);
41219
+ cameras += 1;
41220
+ mediaDropped += counts.mediaDropped;
41221
+ tracks += counts.tracks;
41222
+ events += counts.events;
41223
+ } catch {
41224
+ failed.push(deviceId);
41225
+ }
41226
+ completed += 1;
41227
+ deps.onProgress?.({
41228
+ deviceId,
41229
+ total: deviceIds.length,
41230
+ completed,
41231
+ failed: [...failed],
41232
+ mediaDropped,
41233
+ tracks,
41234
+ events
41235
+ });
41236
+ }
41237
+ return {
41238
+ cameras,
41239
+ failed,
41240
+ mediaDropped,
41241
+ tracks,
41242
+ events
41243
+ };
41244
+ }
41245
+ //#endregion
41246
+ //#region src/disk-reconcile-job.ts
41247
+ /**
41248
+ * In-memory disk-wins fleet job. The tRPC mutation starts this and returns
41249
+ * immediately; the walk runs in the addon process so a 60s UDS timeout cannot
41250
+ * abort it. Status is polled via getReconcileFromDiskStatus.
41251
+ */
41252
+ function idleDiskReconcileJob() {
41253
+ return {
41254
+ state: "idle",
41255
+ total: 0,
41256
+ completed: 0,
41257
+ currentDeviceId: null,
41258
+ failed: [],
41259
+ mediaDropped: 0,
41260
+ tracks: 0,
41261
+ events: 0,
41262
+ startedAtMs: null,
41263
+ finishedAtMs: null,
41264
+ error: null
41265
+ };
41266
+ }
41267
+ function isTimeoutError(err) {
41268
+ const message = err instanceof Error ? err.message : String(err);
41269
+ return /timed out/i.test(message);
41270
+ }
41271
+ async function withTimeoutRetry(run) {
41272
+ try {
41273
+ return await run();
41274
+ } catch (err) {
41275
+ if (!isTimeoutError(err)) throw err;
41276
+ return await run();
41277
+ }
41278
+ }
41279
+ function createDiskReconcileJobRunner(now = Date.now) {
41280
+ let job = idleDiskReconcileJob();
41281
+ let inFlight = null;
41282
+ const snapshot = () => job;
41283
+ const start = (deps) => {
41284
+ if (job.state === "running" && inFlight) return job;
41285
+ job = {
41286
+ ...idleDiskReconcileJob(),
41287
+ state: "running",
41288
+ startedAtMs: now()
41289
+ };
41290
+ deps.log?.("pipeline disk reconcile started");
41291
+ inFlight = (async () => {
41292
+ try {
41293
+ const result = await reconcileFleetFromDisk({
41294
+ listDeviceIds: deps.listDeviceIds,
41295
+ rescanRecordings: (deviceId) => withTimeoutRetry(() => deps.rescanRecordings(deviceId)),
41296
+ reconcileAnalytics: (deviceId) => withTimeoutRetry(() => deps.reconcileAnalytics(deviceId)),
41297
+ onProgress: (update) => {
41298
+ job = {
41299
+ ...job,
41300
+ total: update.total,
41301
+ completed: update.completed,
41302
+ currentDeviceId: update.deviceId,
41303
+ failed: update.failed,
41304
+ mediaDropped: update.mediaDropped,
41305
+ tracks: update.tracks,
41306
+ events: update.events
41307
+ };
41308
+ deps.onProgress?.(update);
41309
+ deps.log?.("pipeline disk reconcile camera", {
41310
+ deviceId: update.deviceId,
41311
+ completed: update.completed,
41312
+ total: update.total,
41313
+ failed: update.failed.length,
41314
+ mediaDropped: update.mediaDropped,
41315
+ tracks: update.tracks,
41316
+ events: update.events
41317
+ });
41318
+ }
41319
+ });
41320
+ job = {
41321
+ ...job,
41322
+ state: "done",
41323
+ total: result.cameras + result.failed.length,
41324
+ completed: result.cameras + result.failed.length,
41325
+ currentDeviceId: null,
41326
+ failed: result.failed,
41327
+ mediaDropped: result.mediaDropped,
41328
+ tracks: result.tracks,
41329
+ events: result.events,
41330
+ finishedAtMs: now(),
41331
+ error: null
41332
+ };
41333
+ deps.log?.("pipeline disk reconcile", {
41334
+ cameras: result.cameras,
41335
+ failed: result.failed,
41336
+ mediaDropped: result.mediaDropped,
41337
+ tracks: result.tracks,
41338
+ events: result.events
41339
+ });
41340
+ } catch (err) {
41341
+ const error = err instanceof Error ? err.message : String(err);
41342
+ job = {
41343
+ ...job,
41344
+ state: "error",
41345
+ currentDeviceId: null,
41346
+ finishedAtMs: now(),
41347
+ error
41348
+ };
41349
+ deps.log?.("pipeline disk reconcile failed", { error });
41350
+ } finally {
41351
+ inFlight = null;
41352
+ }
41353
+ })();
41354
+ return job;
41355
+ };
41356
+ return {
41357
+ snapshot,
41358
+ start
41359
+ };
41360
+ }
41361
+ //#endregion
41362
+ //#region src/inference-device-model.ts
41363
+ /**
41364
+ * Per-device default object-detection model + deviceKey parsing for the
41365
+ * orchestrator's device-aware `getNodeInferenceDevices` view.
41366
+ *
41367
+ * This DUPLICATES the executor's per-device model resolution (P0-3:
41368
+ * `resolveDeviceEngine` + `MODEL_BY_CLASS` + the object-detection step's
41369
+ * `defaultModelIdByFormat` in `@camstack/addon-pipeline`). It is duplicated —
41370
+ * not imported — because cross-addon imports are forbidden (the orchestrator
41371
+ * and the detection-pipeline are separate addons; only tRPC crosses the
41372
+ * boundary). Keep this in sync with `default-detection-model.ts` /
41373
+ * `step-definitions.ts` if the executor's defaults change.
41374
+ *
41375
+ * The returned ids are honest catalog ids (verified present):
41376
+ * - `yolov9m-320-int8` — Intel NPU + iGPU (yolo26 does NOT compile on the NPU)
41377
+ * - `yolov9m-320` — Apple ANE (CoreML)
41378
+ * - `ssd-mobilenet-v2-coco-edgetpu` — Coral USB Edge TPU (tflite)
41379
+ * - `yolo26n` — CPU / CUDA (the object-detection step's universal
41380
+ * nano default)
41381
+ *
41382
+ * Do not promote the accelerated ids to 640. The evaluation in
41383
+ * `docs/benchmarks/pipeline-frame-model-eval.md` failed the 640 promotion
41384
+ * gates (0/3 miss recovered at the current threshold).
41385
+ */
41386
+ /**
41387
+ * The always-on object-detection ROOT step id. A camera session's tracks all
41388
+ * originate from this detector, so a device whose engine format can't run it
41389
+ * cannot host a camera root. Mirrors the addon-pipeline step id (cross-addon
41390
+ * import is forbidden — this is the same duplication rationale as the model
41391
+ * defaults above).
41392
+ */
41393
+ var OBJECT_DETECTION_STEP_ID = "object-detection";
41394
+ /**
41395
+ * Build the camera-root capability predicate for a node from its live catalog:
41396
+ * `format → canHostCameraRoot`. A format can host a camera root iff the
41397
+ * catalog lists at least one object-detection model with a build for that
41398
+ * format — byte-for-byte the resolver's per-device skip-gate test for the root
41399
+ * step (`addonHasCompatibleModel`), so a device is deemed eligible iff the root
41400
+ * would ACTUALLY provision on it.
41401
+ *
41402
+ * Fails OPEN when the catalog has no object-detection slot at all (never
41403
+ * observed in production) so a malformed/empty catalog never strands every
41404
+ * device off the balancer. Pure + deterministic.
41405
+ */
41406
+ function makeRootCapabilityGuard(catalog) {
41407
+ for (const slot of catalog.slots) {
41408
+ const objDet = slot.addons.find((a) => a.id === OBJECT_DETECTION_STEP_ID);
41409
+ if (objDet) return (format) => objDet.models.some((m) => Boolean(m.formats[format]));
41410
+ }
41411
+ return () => true;
41412
+ }
41413
+ /** Split a deviceKey (`<backend>:<device>`, or bare `cpu`) into its parts + format.
41414
+ * Format comes from the shared {@link deviceBackendToFormat} SSOT (`@camstack/types`)
41415
+ * — the previously-local `BACKEND_FORMAT` copy is gone (R3/node-F2). Used only for
41416
+ * STORED-ONLY keys (a configured device the live probe didn't return); a probed
41417
+ * device carries its own honest `format` from the descriptor. */
41418
+ function parseDeviceKey(deviceKey) {
41419
+ const colon = deviceKey.indexOf(":");
41420
+ const backend = colon >= 0 ? deviceKey.slice(0, colon) : deviceKey;
41421
+ return {
41422
+ backend,
41423
+ device: colon >= 0 ? deviceKey.slice(colon + 1) : deviceKey,
41424
+ format: deviceBackendToFormat(backend)
41425
+ };
41426
+ }
41427
+ /**
41428
+ * The object-detection model the executor defaults to for a deviceKey. Mirrors
41429
+ * the executor's `MODEL_BY_CLASS` classification (`classifyAccelerator`) plus
41430
+ * the tflite `defaultModelIdByFormat` for Coral. Never throws; unknown backends
41431
+ * fall back to the universal nano default (`yolo26n`).
41432
+ */
41433
+ function defaultModelIdForDevice(deviceKey) {
41434
+ const { backend, device } = parseDeviceKey(deviceKey);
41435
+ if (backend === "openvino") {
41436
+ if (device === "cpu") return "yolo26n";
41437
+ return "yolov9m-320-int8";
41438
+ }
41439
+ if (backend === "edgetpu") return "ssd-mobilenet-v2-coco-edgetpu";
41440
+ if (backend === "coreml") return "yolov9m-320";
41441
+ return "yolo26n";
41442
+ }
41443
+ /**
41444
+ * Step-tree device jump (phase 1): validate every `steps[step].jumpDeviceKey`
41445
+ * manual override in a to-be-saved `inferenceDevices` map. A jump target MUST be
41446
+ * an enabled∧available device on the SAME node and DIFFERENT from the owning
41447
+ * device. `enabledAvailableKeys` is the effective enabled∧available set (from
41448
+ * `mergeInferenceDevices(probe, submitted)`) so an absent/unplugged/disabled
41449
+ * target is rejected honestly (an operator can't route a step onto a dead pool).
41450
+ * Returns the FIRST human-readable error, or `null` when every override is
41451
+ * valid. Pure + deterministic.
41452
+ */
41453
+ function validateJumpTargets(inferenceDevices, enabledAvailableKeys) {
41454
+ for (const [deviceKey, entry] of Object.entries(inferenceDevices)) for (const [stepId, step] of Object.entries(entry.steps ?? {})) {
41455
+ const target = step.jumpDeviceKey;
41456
+ if (target === void 0) continue;
41457
+ if (target === deviceKey) return `step "${stepId}" on "${deviceKey}" has a jumpDeviceKey pointing at its own device`;
41458
+ if (!enabledAvailableKeys.has(target)) return `step "${stepId}" on "${deviceKey}" has a jumpDeviceKey "${target}" that is not an enabled, available device on this node`;
41459
+ }
41460
+ return null;
41461
+ }
41462
+ /**
41463
+ * Merge a node's live-probed inference devices with its stored per-device map.
41464
+ *
41465
+ * The default is **AUTO = all discovered ACCELERATORS enabled** (spec C2,
41466
+ * opt-OUT) with TWO deliberate exceptions, both **opt-IN** (default disabled):
41467
+ *
41468
+ * - **CPU**: `enumerateInferenceDevices` always emits a universal `cpu`
41469
+ * floor on every platform; auto-enabling it would let the balancer
41470
+ * round-robin ~1/N of sessions onto the slow CPU pool alongside the
41471
+ * NPU/iGPU/ANE. CPU stays the always-available FALLBACK (a node with no
41472
+ * eligible accelerator leaves `deviceKey` unset → the runner's default
41473
+ * pool, which is CPU), not a balanced target — matching the spec's "no
41474
+ * device eligible → fall back to CPU".
41475
+ * - **Coral Edge TPU (`edgetpu`)**: the standing rule since the Coral
41476
+ * executor landed is that it surfaces as selectable but is NEVER
41477
+ * auto-picked — it runs a DIFFERENT, weaker model family (tflite SSD
41478
+ * MobileNet, not the YOLO the other accelerators run), so silently
41479
+ * enrolling a plugged-in Coral changes detection QUALITY, not just
41480
+ * placement. The opt-OUT default did exactly that on 2026-08-01: a hub
41481
+ * Coral nobody enabled entered the session rotation and camera 615 spent
41482
+ * hours at 2.4fps failing tflite model resolution. An operator who wants
41483
+ * the Coral balanced opts it in explicitly (`enabled: true`).
41484
+ *
41485
+ * So: an NPU/iGPU/ANE accelerator with NO stored entry is `enabled:true`; a
41486
+ * CPU or edgetpu device with no stored entry is `enabled:false`; an explicit
41487
+ * stored `enabled` always wins (an operator can opt CPU/Coral in, or an
41488
+ * accelerator out). A stored-only key (configured but the probe did not
41489
+ * return it — removed/unplugged HW) keeps its stored `enabled` and surfaces
41490
+ * as `available:false`, so the UI still shows it.
41491
+ *
41492
+ * Pure + deterministic (sorted by key) — the single merge authority shared by
41493
+ * the `getNodeInferenceDevices` view and the dispatcher's eligible-device pick.
41494
+ */
41495
+ function mergeInferenceDevices(probed, stored) {
41496
+ const probedByKey = new Map(probed.map((d) => [d.key, d]));
41497
+ const keys = new Set([...probedByKey.keys(), ...Object.keys(stored)]);
41498
+ const out = [];
41499
+ for (const key of Array.from(keys).toSorted()) {
41500
+ const descriptor = probedByKey.get(key);
41501
+ const opt = stored[key];
41502
+ const parsed = descriptor ?? parseDeviceKey(key);
41503
+ const weight = opt?.weight !== void 0 && opt.weight > 0 ? opt.weight : 1;
41504
+ const autoDefault = parsed.backend !== "cpu" && parsed.backend !== "edgetpu";
41505
+ out.push({
41506
+ key,
41507
+ backend: parsed.backend,
41508
+ device: parsed.device,
41509
+ format: parsed.format,
41510
+ available: descriptor?.available ?? false,
41511
+ enabled: opt?.enabled ?? autoDefault,
41512
+ weight,
41513
+ maxSessions: opt?.maxSessions ?? null,
41514
+ defaultModelId: defaultModelIdForDevice(key),
41515
+ ...opt?.steps && Object.keys(opt.steps).length > 0 ? { steps: { ...opt.steps } } : {}
41516
+ });
41517
+ }
41518
+ return out;
41519
+ }
41520
+ /**
41521
+ * The per-device concurrent-session caps for a node as `deviceKey → maxSessions`
41522
+ * (only devices that carry an explicit cap; absent = unlimited). Fed to the
41523
+ * device balancer's `nodeCaps` so a device at its cap is skipped (audit F3).
41524
+ */
41525
+ function inferenceDeviceCaps(stored) {
41526
+ const out = {};
41527
+ for (const [key, entry] of Object.entries(stored)) if (entry.maxSessions !== void 0 && entry.maxSessions > 0) out[key] = entry.maxSessions;
41528
+ return out;
41529
+ }
41530
+ /** Is this device the CPU fallback rather than a real accelerator? */
41531
+ function isCpuFallback(view) {
41532
+ return view.backend === "cpu";
41533
+ }
41534
+ function resolveInferenceDeviceEligibility(probed, stored, canRunRoot, isPoolUsable) {
41535
+ const eligible = {};
41536
+ const excluded = [];
41537
+ const merged = mergeInferenceDevices(probed, stored);
41538
+ const acceleratorServes = merged.some((d) => !isCpuFallback(d) && d.enabled && d.available && (!canRunRoot || canRunRoot(d.format)));
41539
+ for (const d of merged) {
41540
+ if (!d.enabled) {
41541
+ excluded.push({
41542
+ key: d.key,
41543
+ reason: "disabled",
41544
+ format: d.format
41545
+ });
41546
+ continue;
41547
+ }
41548
+ if (!d.available) {
41549
+ excluded.push({
41550
+ key: d.key,
41551
+ reason: "unavailable",
41552
+ format: d.format
41553
+ });
41554
+ continue;
41398
41555
  }
41399
- await this.withAudioSubLock(deviceId, async () => {
41400
- const unsub = this.audioSubscriptions.get(deviceId);
41401
- if (!unsub) return;
41402
- try {
41403
- unsub();
41404
- } catch {}
41405
- this.audioSubscriptions.delete(deviceId);
41406
- this.deps.logger.info("lazy audio: window closed", {
41407
- tags: { deviceId },
41408
- meta: { reason }
41556
+ if (isPoolUsable && !isPoolUsable(d.key)) {
41557
+ excluded.push({
41558
+ key: d.key,
41559
+ reason: "unavailable",
41560
+ format: d.format
41409
41561
  });
41410
- });
41411
- }
41412
- /**
41413
- * Audio teardown for one device — the audio half of `stopDetection`.
41414
- * Tears down through the per-device lock so it can't race a concurrent
41415
- * subscribe (which would re-store a handle this teardown never sees).
41416
- */
41417
- async stopForDevice(deviceId) {
41418
- await this.withAudioSubLock(deviceId, async () => {
41419
- const unsub = this.audioSubscriptions.get(deviceId);
41420
- if (unsub) {
41421
- try {
41422
- unsub();
41423
- } catch {}
41424
- this.audioSubscriptions.delete(deviceId);
41425
- }
41426
- });
41427
- const lazyTimer = this.lazyAudioTeardownTimers.get(deviceId);
41428
- if (lazyTimer) {
41429
- clearTimeout(lazyTimer);
41430
- this.lazyAudioTeardownTimers.delete(deviceId);
41562
+ continue;
41431
41563
  }
41432
- const windowTimer = this.motionAudioWindowTimers.get(deviceId);
41433
- if (windowTimer) {
41434
- clearTimeout(windowTimer);
41435
- this.motionAudioWindowTimers.delete(deviceId);
41564
+ if (canRunRoot && !canRunRoot(d.format)) {
41565
+ excluded.push({
41566
+ key: d.key,
41567
+ reason: "cannot-host-camera-root",
41568
+ format: d.format
41569
+ });
41570
+ continue;
41436
41571
  }
41437
- this.audioAssignments.delete(deviceId);
41438
- }
41439
- /**
41440
- * Centralized write into `audioSubscriptions`. If shutdown has begun, the
41441
- * map has already been (or is about to be) cleared lock-free in
41442
- * `shutdown()`; storing here would leak a zombie entry whose `unsub` is
41443
- * never called. So when shutting down we immediately invoke `unsub`
41444
- * (best-effort, error-swallowed) and DO NOT store. `protected` so
41445
- * `audio-sub-lock.spec.ts`'s test subclass can assert the shutdown-guard
41446
- * behavior without casts.
41447
- */
41448
- storeAudioSub(deviceId, unsub) {
41449
- if (this.audioShuttingDown) {
41450
- try {
41451
- unsub();
41452
- } catch {}
41453
- return;
41572
+ if (isCpuFallback(d) && acceleratorServes) {
41573
+ excluded.push({
41574
+ key: d.key,
41575
+ reason: "accelerator-preferred",
41576
+ format: d.format
41577
+ });
41578
+ continue;
41454
41579
  }
41455
- this.audioSubscriptions.set(deviceId, unsub);
41456
- }
41457
- /**
41458
- * Serialize an audio-subscription critical section per device. `fn` is
41459
- * chained onto the device's current lock tail, so concurrent calls for the
41460
- * SAME deviceId run sequentially (FIFO); different deviceIds never block
41461
- * each other. Thin delegate onto the `audioSubLocks` `KeyedAsyncLock`
41462
- * instance. `protected` so `audio-sub-lock.spec.ts`'s test subclass can
41463
- * drive the lock without casts.
41464
- */
41465
- withAudioSubLock(deviceId, fn) {
41466
- return this.audioSubLocks.run(deviceId, fn);
41580
+ eligible[d.key] = d.weight;
41467
41581
  }
41582
+ return {
41583
+ eligible,
41584
+ excluded
41585
+ };
41586
+ }
41587
+ /**
41588
+ * Join the merged device rows with the eligibility verdict so the UI can NAME
41589
+ * why an accelerator is not in play instead of leaving the operator to deduce
41590
+ * it from `enabled`/`available`.
41591
+ *
41592
+ * Deduction is not possible for two of the four reasons — `accelerator-preferred`
41593
+ * is a node-WIDE rule (a CPU row reads `enabled:true, available:true` and still
41594
+ * never gets a session, D215) and `cannot-host-camera-root` needs the node's
41595
+ * model catalog. Both live in {@link resolveInferenceDeviceEligibility}, so this
41596
+ * function only transports its answer; it never re-derives one.
41597
+ *
41598
+ * Pure; preserves `merged`'s order (sorted by key) and every other field.
41599
+ */
41600
+ function annotateInferenceDeviceExclusions(merged, eligibility) {
41601
+ const reasonByKey = new Map(eligibility.excluded.map((e) => [e.key, e.reason]));
41602
+ return merged.map((view) => ({
41603
+ ...view,
41604
+ exclusion: reasonByKey.get(view.key) ?? null
41605
+ }));
41606
+ }
41607
+ function resolveNodeInferenceUsability(eligibility) {
41608
+ const eligibleKeys = Object.keys(eligibility.eligible).toSorted();
41609
+ const unavailableKeys = eligibility.excluded.filter((e) => e.reason === "unavailable").map((e) => e.key).toSorted();
41610
+ return {
41611
+ usable: eligibleKeys.length > 0 || unavailableKeys.length === 0,
41612
+ unavailableKeys,
41613
+ eligibleKeys
41614
+ };
41615
+ }
41616
+ /**
41617
+ * Step-tree device jump (phase 1): the attach-payload roster of a node's
41618
+ * enabled∧available inference devices with the balancer knobs (`weight`,
41619
+ * `maxSessions`) the runner uses to AUTO-jump an enrichment step off a device
41620
+ * whose format can't run it. Built from the SAME `eligible` (deviceKey→weight)
41621
+ * and `caps` (deviceKey→maxSessions) the dispatcher already computes, so the
41622
+ * roster the runner sees exactly matches the balancer's candidate set. Sorted
41623
+ * by key for determinism. Populated onto `RunnerCameraConfig.inferenceDevices`
41624
+ * ONLY when a `deviceKey` is elected and there are ≥2 entries.
41625
+ */
41626
+ function buildInferenceDeviceRoster(eligible, caps) {
41627
+ return Object.entries(eligible).map(([deviceKey, weight]) => ({
41628
+ deviceKey,
41629
+ weight: weight > 0 ? weight : 1,
41630
+ maxSessions: caps[deviceKey] ?? null
41631
+ })).toSorted((a, b) => a.deviceKey < b.deviceKey ? -1 : a.deviceKey > b.deviceKey ? 1 : 0);
41632
+ }
41633
+ //#endregion
41634
+ //#region src/node-inference-usability-mirror.ts
41635
+ var NodeInferenceUsabilityMirror = class {
41636
+ state = /* @__PURE__ */ new Map();
41468
41637
  /**
41469
- * Subscribe to decoded audio chunks for a camera and feed them into the
41470
- * audio-analyzer. Reads the analyzer's settings via its own
41471
- * `resolveDeviceSettings(deviceId)` method so the orchestrator does not
41472
- * touch the audio-analyzer schema field names directly.
41638
+ * Fold one observation in and report whether the caller should act.
41639
+ * Never throws.
41473
41640
  */
41474
- async subscribeAudioStream(deviceId, config) {
41475
- const api = this.deps.api();
41476
- if (!api) {
41477
- this.deps.logger.warn("this.ctx.api not available — cannot subscribe audio", { tags: { deviceId } });
41478
- return null;
41479
- }
41480
- if (!await this.deps.isAudioAnalysisActive(deviceId)) return null;
41481
- if (config.audioMode === "disabled") {
41482
- this.deps.logger.debug("audio subscribe skipped: audioMode=disabled", { tags: { deviceId } });
41483
- return null;
41641
+ observe(nodeId, usable) {
41642
+ const prev = this.state.get(nodeId);
41643
+ if (usable) {
41644
+ this.state.set(nodeId, {
41645
+ usable: true,
41646
+ armed: false
41647
+ });
41648
+ return prev !== void 0 && !prev.usable ? "recovered" : null;
41484
41649
  }
41485
- if (config.audioMode === "on-motion" && !this.isMotionAudioWindowOpen(deviceId)) {
41486
- this.deps.logger.info("audio subscribe deferred: audioMode=on-motion, no window open", { tags: { deviceId } });
41650
+ if (prev === void 0) {
41651
+ this.state.set(nodeId, {
41652
+ usable: true,
41653
+ armed: true
41654
+ });
41487
41655
  return null;
41488
41656
  }
41489
- const audioStream = config.audioStreamId ?? config.motionStreamId;
41490
- const audioBrokerId = makeSourceBrokerId(deviceId, audioStream);
41491
- if ((await this.deps.probeAudioTrack(deviceId, audioStream)).kind === "absent") {
41492
- this.deps.logger.warn("audio subscription REFUSED — this stream carries no audio track", {
41493
- tags: { deviceId },
41494
- meta: {
41495
- camStreamId: audioStream,
41496
- brokerId: audioBrokerId,
41497
- selectedBy: config.audioStreamId !== void 0 ? "audioStreamId" : "motionStreamId",
41498
- hint: "point the camera’s audio at a stream that has an audio track — no stream is substituted automatically"
41499
- }
41657
+ if (!prev.usable) {
41658
+ this.state.set(nodeId, {
41659
+ usable: false,
41660
+ armed: true
41500
41661
  });
41501
41662
  return null;
41502
41663
  }
41503
- const settings = await api.audioAnalysis.resolveDeviceSettings.query({ deviceId });
41504
- if (!settings) {
41505
- this.deps.logger.warn("audio-analysis returned no settings — audio subscription skipped", { tags: { deviceId } });
41664
+ if (!prev.armed) {
41665
+ this.state.set(nodeId, {
41666
+ usable: true,
41667
+ armed: true
41668
+ });
41506
41669
  return null;
41507
41670
  }
41508
- const audioNodeId = await this.dispatch(deviceId);
41509
- const isRemoteAudio = audioNodeId !== this.deps.localNodeId();
41510
- this.deps.logger.info("audio subscription: resolved audio node", {
41511
- tags: { deviceId },
41512
- meta: {
41513
- audioNodeId,
41514
- isRemote: isRemoteAudio
41515
- }
41516
- });
41517
- const accumulator = new AudioWindowAccumulator(deviceId);
41518
- const teardown = startAudioChunkPoller({
41519
- api,
41520
- brokerId: audioBrokerId,
41521
- tag: "audio-analyzer",
41522
- ownerNodeId: this.deps.ingestNode(),
41523
- logger: this.deps.logger.withTags({ deviceId }),
41524
- onChunk: async (chunk) => {
41525
- this.deps.watchdogNote(deviceId, "audio");
41526
- try {
41527
- const audioChunkInput = accumulator.push(chunk);
41528
- if (!audioChunkInput) return;
41529
- const result = await api.audioAnalyzer.analyseChunk.mutate({
41530
- chunk: audioChunkInput,
41531
- settings,
41532
- ...isRemoteAudio ? { nodeId: audioNodeId } : {}
41533
- });
41534
- if (!result) return;
41535
- const frame = buildAudioResultFrame(deviceId, result);
41536
- this.deps.eventBus.emit({
41537
- id: `audio-inference-${deviceId}-${Date.now()}`,
41538
- timestamp: /* @__PURE__ */ new Date(),
41539
- source: {
41540
- type: "device",
41541
- id: deviceId,
41542
- nodeId: "hub",
41543
- addonId: "pipeline-orchestrator",
41544
- deviceId
41545
- },
41546
- category: EventCategory.PipelineAudioInferenceResult,
41547
- data: {
41548
- deviceId,
41549
- frame,
41550
- nodeId: "hub"
41551
- }
41552
- });
41553
- } catch (err) {
41554
- const msg = errMsg(err);
41555
- this.deps.logger.error("Audio analysis failed", {
41556
- tags: { deviceId },
41557
- meta: { error: msg }
41558
- });
41559
- }
41560
- }
41671
+ this.state.set(nodeId, {
41672
+ usable: false,
41673
+ armed: true
41561
41674
  });
41562
- this.deps.logger.info("Audio stream subscribed", { tags: { deviceId } });
41563
- return () => {
41564
- teardown();
41565
- accumulator.reset();
41566
- };
41675
+ return "became-unusable";
41567
41676
  }
41568
- /**
41569
- * Set true at the very start of `onShutdown`, before the audio teardown /
41570
- * map clears below. Once set, `withAudioSubLock` turns queued/new critical
41571
- * sections into no-ops and `storeAudioSub` refuses to store, so no
41572
- * critical section that was in-flight (or queued) when shutdown began can
41573
- * resurrect a zombie subscription into the cleared `audioSubscriptions`
41574
- * map. MUST be called before anything else in `onShutdown` that could
41575
- * race a queued audio critical section (mirrors the original
41576
- * `this.audioShuttingDown = true` being the very first statement).
41577
- */
41578
- beginShutdown() {
41579
- this.audioShuttingDown = true;
41677
+ /** Can this node be given cameras? Unknown nodes answer YES. */
41678
+ isUsable(nodeId) {
41679
+ return this.state.get(nodeId)?.usable ?? true;
41680
+ }
41681
+ /** Nodes currently excluded for the placement log and diagnostics. */
41682
+ unusableNodeIds() {
41683
+ const out = [];
41684
+ for (const [nodeId, s] of this.state) if (!s.usable) out.push(nodeId);
41685
+ return out.toSorted();
41686
+ }
41687
+ forget(nodeId) {
41688
+ this.state.delete(nodeId);
41580
41689
  }
41690
+ reset() {
41691
+ this.state.clear();
41692
+ }
41693
+ };
41694
+ //#endregion
41695
+ //#region src/inference-device-usability-mirror.ts
41696
+ /**
41697
+ * InferenceDeviceUsabilityMirror — "can this NODE's THIS DEVICE still infer?",
41698
+ * kept off the placement path.
41699
+ *
41700
+ * The per-`(nodeId, deviceKey)` twin of {@link NodeInferenceUsabilityMirror},
41701
+ * and deliberately not a second mechanism: it composes the key and delegates
41702
+ * every decision to that class, so the arm/apply reluctance D49 pinned lives in
41703
+ * exactly one implementation and cannot drift between the node tier and the
41704
+ * device tier.
41705
+ *
41706
+ * ## Why this tier had to exist
41707
+ *
41708
+ * The node tier already answers "does this node have ANY usable accelerator".
41709
+ * On 2026-08-25 the hub's answer was, correctly, yes — its NPU was healthy the
41710
+ * whole time. What died was one DEVICE, `openvino:gpu`, and nothing anywhere
41711
+ * asked that question: the per-dispatch capability gate is keyed on model
41712
+ * FORMAT and `openvino:gpu` and `openvino:npu` share the format `openvino`, so
41713
+ * it is blind between them by construction. The balancer kept rotating cameras
41714
+ * onto the dead pool — 20 sessions in 20 minutes, every one `tieBreak:
41715
+ * "rotation"` — for 31 hours.
41716
+ *
41717
+ * ## Why a mirror and not the event
41718
+ *
41719
+ * D49, verbatim: *a one-shot event never gates on a fallible read*. The gate is
41720
+ * this in-memory mirror, refreshed off the event path by the same
41721
+ * `resolveEligibleInferenceDevices` the dispatcher already runs (plus the
41722
+ * session controller's background refresher). The consequences that buys:
41723
+ *
41724
+ * - **A read that fails changes nothing.** The caller folds in an observation
41725
+ * only when it HAS one; an unreachable node, a version-skewed executor or a
41726
+ * rejected RPC never reaches {@link observe}, so the previous verdict
41727
+ * stands. This is the whole reason the health read is specified as
41728
+ * "synchronous over in-memory state, never throws for its own reasons": an
41729
+ * empty answer must mean *nothing is refused*, not *I could not tell*.
41730
+ * - **Excluding a healthy device needs a second, consecutive read.** Exclusion
41731
+ * is the direction that DESTROYS work — it strands an accelerator that may
41732
+ * be perfectly fine — so one bad observation only ARMS.
41733
+ * - **Re-admitting is immediate and unconditional.** One good observation puts
41734
+ * the device straight back. Being slow to exclude costs some wasted
41735
+ * inference attempts; being slow to re-admit costs an idle accelerator and a
41736
+ * node that looks broken.
41737
+ */
41738
+ /**
41739
+ * NUL — impossible in both a Moleculer node id and a `<backend>:<device>` key,
41740
+ * so the composite key can never be ambiguous. A separator that CAN occur in
41741
+ * either half makes two distinct pairs collide, and a collision here silently
41742
+ * excludes an accelerator nobody reported.
41743
+ */
41744
+ var SEPARATOR = "\0";
41745
+ var InferenceDeviceUsabilityMirror = class {
41746
+ /** The one implementation of the arm/apply state machine (D49). */
41747
+ mirror = new NodeInferenceUsabilityMirror();
41581
41748
  /**
41582
- * Full audio teardown combines the former `onShutdown`'s two separate
41583
- * audio blocks (lazy-teardown-timer clear, then — after several unrelated
41584
- * session/reconcile/load-shed clears — subscription teardown + lock clear
41585
- * + assignment-map clears) into one call. Safe to combine: both blocks
41586
- * are synchronous with no interleaved `await`, and every original
41587
- * statement between them (`sessionRegistry.clear()`,
41588
- * `cameraFpsMap.clear()`, `remoteHealthAttempts.clear()`,
41589
- * `loadShedState.clear()`, `loadShedResumeTimer` cleanup) touches state
41590
- * fully disjoint from anything audio — so their relative order to each
41591
- * other is unaffected, and the audio-internal order (timers →
41592
- * subscriptions → lock → assignment maps) is reproduced exactly.
41749
+ * Fold one observation in and report whether the caller should act.
41750
+ * Never throws.
41593
41751
  */
41594
- shutdown() {
41595
- for (const t of this.lazyAudioTeardownTimers.values()) clearTimeout(t);
41596
- this.lazyAudioTeardownTimers.clear();
41597
- for (const t of this.motionAudioWindowTimers.values()) clearTimeout(t);
41598
- this.motionAudioWindowTimers.clear();
41599
- for (const unsub of this.audioSubscriptions.values()) try {
41600
- unsub();
41601
- } catch {}
41602
- this.audioSubscriptions.clear();
41603
- this.audioSubLocks.clear();
41604
- this.audioAssignments.clear();
41605
- this.readyAudioNodes.clear();
41752
+ observe(nodeId, deviceKey, usable) {
41753
+ return this.mirror.observe(`${nodeId}${SEPARATOR}${deviceKey}`, usable);
41754
+ }
41755
+ /** Can the balancer put a session on this device? Unknown pairs answer YES. */
41756
+ isUsable(nodeId, deviceKey) {
41757
+ return this.mirror.isUsable(`${nodeId}${SEPARATOR}${deviceKey}`);
41758
+ }
41759
+ /** Pairs currently excluded — for the placement log and diagnostics. */
41760
+ unusableDevices() {
41761
+ return this.mirror.unusableNodeIds().map((composite) => {
41762
+ const at = composite.indexOf(SEPARATOR);
41763
+ return {
41764
+ nodeId: composite.slice(0, at),
41765
+ deviceKey: composite.slice(at + 1)
41766
+ };
41767
+ });
41768
+ }
41769
+ /** The excluded device keys on ONE node. */
41770
+ unusableDeviceKeys(nodeId) {
41771
+ return this.unusableDevices().filter((d) => d.nodeId === nodeId).map((d) => d.deviceKey);
41772
+ }
41773
+ forget(nodeId, deviceKey) {
41774
+ this.mirror.forget(`${nodeId}${SEPARATOR}${deviceKey}`);
41775
+ }
41776
+ reset() {
41777
+ this.mirror.reset();
41606
41778
  }
41607
41779
  };
41780
+ /**
41781
+ * Fold ONE node's health answer into the mirror and return what changed.
41782
+ *
41783
+ * This is the whole reading discipline, in one place, because both halves of it
41784
+ * are easy to get subtly wrong and neither failure is visible in a log:
41785
+ *
41786
+ * - **`unhealthy === null` — the read FAILED — changes nothing.** Not a single
41787
+ * entry is touched. An unreachable node, a version-skewed executor or a
41788
+ * rejected RPC must be distinguishable from "asked, nothing is refused", or
41789
+ * a flaky link silently re-admits a dead accelerator (D49).
41790
+ * - **Every device the node HAS is observed**, not merely the refused ones.
41791
+ * The first draft observed `refused ∪ already-excluded`, which omits exactly
41792
+ * the devices the mirror has ARMED — so their disarming good read never
41793
+ * arrived and two bad reads an HOUR apart, with a hundred healthy ones
41794
+ * between them, excluded a working accelerator. "Consecutive" is only a
41795
+ * property if the good observations are delivered.
41796
+ *
41797
+ * Pure with respect to everything except `mirror`, and never throws — it is
41798
+ * called from the dispatcher's own read path.
41799
+ */
41800
+ function foldInferenceDeviceHealth(mirror, nodeId, unhealthy, present) {
41801
+ if (unhealthy === null) return [];
41802
+ const refused = new Set(unhealthy);
41803
+ const observed = new Set([
41804
+ ...present,
41805
+ ...refused,
41806
+ ...mirror.unusableDeviceKeys(nodeId)
41807
+ ]);
41808
+ const changes = [];
41809
+ for (const deviceKey of observed) {
41810
+ const transition = mirror.observe(nodeId, deviceKey, !refused.has(deviceKey));
41811
+ if (transition !== null) changes.push({
41812
+ deviceKey,
41813
+ transition
41814
+ });
41815
+ }
41816
+ return changes;
41817
+ }
41608
41818
  //#endregion
41609
41819
  //#region src/load-balancer.ts
41610
41820
  /**
@@ -43540,6 +43750,90 @@ function applyDeviceProvisioning(steps, base, override) {
43540
43750
  });
43541
43751
  }
43542
43752
  //#endregion
43753
+ //#region src/device-activity-source.ts
43754
+ /** The source's own name on the wire. One constant, used by every emit + gate. */
43755
+ var DEVICE_ACTIVITY_SOURCE = "device-activity";
43756
+ var DeviceActivitySource = class {
43757
+ #deps;
43758
+ #devices = /* @__PURE__ */ new Map();
43759
+ constructor(deps) {
43760
+ this.#deps = deps;
43761
+ }
43762
+ /**
43763
+ * A `recording-signal` level landed for a device. Idempotent in the level:
43764
+ * only a CHANGE emits an edge, and the sustain tick — not a repeated push —
43765
+ * is what keeps the session open.
43766
+ */
43767
+ onSignalLevel(deviceId, active, reason, atMs) {
43768
+ const entry = this.#devices.get(deviceId) ?? {
43769
+ active: false,
43770
+ timer: null
43771
+ };
43772
+ const wasActive = entry.active;
43773
+ entry.active = active;
43774
+ this.#devices.set(deviceId, entry);
43775
+ if (active === wasActive) return;
43776
+ if (active) {
43777
+ this.#deps.logger.info("device-activity: the device reports it is working", {
43778
+ tags: { deviceId },
43779
+ meta: { reason }
43780
+ });
43781
+ this.#emit(deviceId, true, atMs);
43782
+ this.#arm(deviceId, entry);
43783
+ return;
43784
+ }
43785
+ this.#clear(entry);
43786
+ this.#deps.logger.info("device-activity: the device reports it has stopped", {
43787
+ tags: { deviceId },
43788
+ meta: { reason }
43789
+ });
43790
+ this.#emit(deviceId, false, atMs);
43791
+ }
43792
+ /** Drop every timer (addon teardown). The mirror goes with the instance. */
43793
+ stop() {
43794
+ for (const entry of this.#devices.values()) this.#clear(entry);
43795
+ this.#devices.clear();
43796
+ }
43797
+ #arm(deviceId, entry) {
43798
+ this.#clear(entry);
43799
+ const sustainMs = this.#deps.sustainMsFor(deviceId);
43800
+ const timer = setInterval(() => {
43801
+ const current = this.#devices.get(deviceId);
43802
+ if (!current || !current.active) {
43803
+ this.#clear(current ?? entry);
43804
+ return;
43805
+ }
43806
+ this.#emit(deviceId, true, Date.now());
43807
+ }, sustainMs);
43808
+ timer.unref?.();
43809
+ entry.timer = timer;
43810
+ }
43811
+ #clear(entry) {
43812
+ if (entry.timer === null) return;
43813
+ clearInterval(entry.timer);
43814
+ entry.timer = null;
43815
+ }
43816
+ /**
43817
+ * Emit, unless this camera does not carry the source. A suppressed emit is
43818
+ * SAID — an operator who never ticked the box and an addon that is quietly
43819
+ * broken look identical from the outside otherwise.
43820
+ */
43821
+ #emit(deviceId, detected, timestamp) {
43822
+ const sources = this.#deps.motionSourcesFor(deviceId);
43823
+ if (sources === null || !sources.includes("device-activity")) {
43824
+ this.#deps.logger.debug("device-activity: level not forwarded — the camera does not list `device-activity`", {
43825
+ tags: { deviceId },
43826
+ meta: {
43827
+ detected,
43828
+ sources: sources ?? "no-active-detection"
43829
+ }
43830
+ });
43831
+ return;
43832
+ }
43833
+ this.#deps.emitMotion(deviceId, detected, timestamp);
43834
+ }
43835
+ };
43836
+ //#endregion
43543
43837
  //#region src/device-detection-settings.ts
43544
43838
  /** Read a required string leaf out of the hydrated `flat` schema values. */
43545
43839
  function mustString(flat, deviceId, key) {
@@ -43565,6 +43859,32 @@ function numberOrDefault(flat, key) {
43565
43859
  const dflt = uiField && "default" in uiField ? uiField.default : void 0;
43566
43860
  return typeof dflt === "number" ? dflt : 0;
43567
43861
  }
43862
+ /** The activity rate from the hydrated store, or the shipped default. */
43863
+ function activityFps(flat) {
43864
+ const v = flat["activityDetectionFps"];
43865
+ return typeof v === "number" && v > 0 ? v : 1;
43866
+ }
43867
+ /**
43868
+ * The detection rate a session opens at, given WHAT OPENED IT.
43869
+ *
43870
+ * A CAP, not a set: `min(cameraRate, activityRate)`. A camera already slower
43871
+ * than the activity rate stays slower, so lowering the global rate keeps
43872
+ * working. Why this lever and not the other two: a per-device `detectionFps`
43873
+ * would also slow the sessions a real motion trigger opens on the same camera,
43874
+ * and it becomes silently wrong the day the device gains a second trigger; a
43875
+ * per-SOURCE rate table would have to reach the runner and be re-applied
43876
+ * whenever the source holding the session changes, which the attach-time config
43877
+ * cannot express. Scoping it to the session's TRIGGER puts the number exactly
43878
+ * where its justification lives.
43879
+ *
43880
+ * Applies to the session the activity level OPENS. A session already open at
43881
+ * the camera rate when the level rises is not re-attached to slow it down —
43882
+ * re-attaching a live session to change one number costs a decode restart.
43883
+ */
43884
+ function detectionFpsForTrigger(config, trigger) {
43885
+ if (trigger !== "device-activity") return config.detectionFps;
43886
+ return Math.min(config.detectionFps, config.activityDetectionFps ?? 1);
43887
+ }
43568
43888
  /**
43569
43889
  * Pure decision/derivation half of the former `resolveDeviceDetectionSettings`.
43570
43890
  * Given the I/O-gathered raw materials, resolves every operator-wins →
@@ -43574,14 +43894,19 @@ function numberOrDefault(flat, key) {
43574
43894
  * the original method's "narrowing failed" catch.
43575
43895
  */
43576
43896
  function resolveDetectionSettings(input) {
43577
- const { deviceId, raw, flat, features, hasOnboardMotion, pipelineEnabled, motionDetectionEnabled } = input;
43897
+ const { deviceId, raw, flat, features, hasOnboardMotion, hasActivitySignal, pipelineEnabled, motionDetectionEnabled } = input;
43578
43898
  const profile = resolveDeviceProfile(features);
43579
43899
  const userMotionSources = raw["motionSources"];
43580
43900
  let motionSources;
43581
43901
  if (userMotionSources !== void 0) motionSources = MotionSourcesSchema.parse(userMotionSources);
43582
- else if (hasOnboardMotion) motionSources = ["onboard"];
43583
- else if (profile && features.includes(DeviceFeature.BatteryOperated)) motionSources = [];
43584
- else motionSources = MotionSourcesSchema.parse(flat["motionSources"]);
43902
+ else {
43903
+ let defaulted;
43904
+ if (hasOnboardMotion) defaulted = ["onboard"];
43905
+ else if (hasActivitySignal) defaulted = [];
43906
+ else if (profile && features.includes(DeviceFeature.BatteryOperated)) defaulted = [];
43907
+ else defaulted = MotionSourcesSchema.parse(flat["motionSources"]);
43908
+ motionSources = hasActivitySignal ? [...defaulted, DEVICE_ACTIVITY_SOURCE] : defaulted;
43909
+ }
43585
43910
  const userDetectionMode = raw["detectionMode"];
43586
43911
  const detectionMode = typeof userDetectionMode === "string" && isPipelinePhaseMode(userDetectionMode) ? userDetectionMode : profile?.defaults.detectionMode ?? "on-motion";
43587
43912
  const userAudioMode = raw["audioMode"];
@@ -43600,6 +43925,7 @@ function resolveDetectionSettings(input) {
43600
43925
  detectionStreamProfile: mustString(flat, deviceId, "detectionStreamProfile"),
43601
43926
  motionFps: numberOrDefault(flat, "motionFps"),
43602
43927
  detectionFps: numberOrDefault(flat, "detectionFps"),
43928
+ activityDetectionFps: activityFps(flat),
43603
43929
  motionCooldownMs: numberOrDefault(flat, "motionCooldownMs"),
43604
43930
  maxSessionHoldMs: numberOrDefault(flat, "maxSessionHoldMs"),
43605
43931
  audioMotionWindowMs: numberOrDefault(flat, "audioMotionWindowMs"),
@@ -43656,6 +43982,7 @@ function buildDetectionConfigFromInputs(resolved, assigned) {
43656
43982
  detectionStreamId: detectionCamStreamId,
43657
43983
  motionFps: resolved.motionFps,
43658
43984
  detectionFps: resolved.detectionFps,
43985
+ activityDetectionFps: resolved.activityDetectionFps,
43659
43986
  motionCooldownMs: resolved.motionCooldownMs,
43660
43987
  maxSessionHoldMs: resolved.maxSessionHoldMs,
43661
43988
  audioMotionWindowMs: resolved.audioMotionWindowMs,
@@ -43681,6 +44008,7 @@ function detectionConfigEquals(a, b) {
43681
44008
  if (a.detectionStreamId !== b.detectionStreamId) return false;
43682
44009
  if (a.motionFps !== b.motionFps) return false;
43683
44010
  if (a.detectionFps !== b.detectionFps) return false;
44011
+ if (a.activityDetectionFps !== b.activityDetectionFps) return false;
43684
44012
  if (a.motionCooldownMs !== b.motionCooldownMs) return false;
43685
44013
  if (a.maxSessionHoldMs !== b.maxSessionHoldMs) return false;
43686
44014
  if (a.audioMotionWindowMs !== b.audioMotionWindowMs) return false;
@@ -44307,6 +44635,7 @@ var DetectionWiringController = class {
44307
44635
  try {
44308
44636
  const features = await this.lookupDeviceFeatures(deviceId);
44309
44637
  const hasOnboardMotion = raw["motionSources"] === void 0 ? await this.deps.deviceHasOnboardMotionCap(deviceId) : false;
44638
+ const hasActivitySignal = raw["motionSources"] === void 0 ? await this.deps.deviceHasActivitySignalCap(deviceId) : false;
44310
44639
  const pipelineEnabled = await this.isDetectionPipelineActive(deviceId);
44311
44640
  const motionDetectionEnabled = await this.isMotionDetectionActive(deviceId);
44312
44641
  return resolveDetectionSettings({
@@ -44315,6 +44644,7 @@ var DetectionWiringController = class {
44315
44644
  flat,
44316
44645
  features,
44317
44646
  hasOnboardMotion,
44647
+ hasActivitySignal,
44318
44648
  pipelineEnabled,
44319
44649
  motionDetectionEnabled
44320
44650
  });
@@ -44920,9 +45250,10 @@ var DeviceConfigContributions = class {
44920
45250
  const schema = this.deps.deviceSettingsSchema();
44921
45251
  if (!schema) return null;
44922
45252
  const hasOnboardMotion = await this.deps.deviceHasOnboardMotionCap(input.deviceId);
44923
- const rawWithDefaults = raw["motionSources"] === void 0 && hasOnboardMotion ? {
45253
+ const hasActivitySignal = await this.deps.deviceHasActivitySignalCap(input.deviceId);
45254
+ const rawWithDefaults = raw["motionSources"] === void 0 && (hasOnboardMotion || hasActivitySignal) ? {
44924
45255
  ...raw,
44925
- motionSources: ["onboard"]
45256
+ motionSources: [...hasOnboardMotion ? ["onboard"] : [], ...hasActivitySignal ? ["device-activity"] : []]
44926
45257
  } : raw;
44927
45258
  const baseSections = hydrateSchema({
44928
45259
  ...schema,
@@ -47742,7 +48073,8 @@ function wireOrchestratorSubscriptions(deps) {
47742
48073
  if (!isEvent(event, EventCategory.MotionOnMotionChanged)) return;
47743
48074
  const { deviceId, detected, timestamp } = event.data;
47744
48075
  if (typeof deviceId !== "number") return;
47745
- deps.handleSessionMotion(deviceId, detected, typeof timestamp === "number" ? timestamp : void 0).catch((err) => {
48076
+ const parsedSource = MotionSourceEnum.safeParse(event.data.source);
48077
+ deps.handleSessionMotion(deviceId, detected, typeof timestamp === "number" ? timestamp : void 0, parsedSource.success ? parsedSource.data : void 0).catch((err) => {
47746
48078
  deps.logger.warn("session motion handler failed", {
47747
48079
  tags: { deviceId },
47748
48080
  meta: {
@@ -47764,8 +48096,47 @@ function wireOrchestratorSubscriptions(deps) {
47764
48096
  const deviceId = event.source.deviceId;
47765
48097
  if (typeof deviceId === "number") deps.noteWatchdogSignal(deviceId, "motion");
47766
48098
  });
48099
+ const activitySource = new DeviceActivitySource({
48100
+ logger: deps.logger,
48101
+ emitMotion: (deviceId, detected, timestamp) => {
48102
+ if (isTornDown) return;
48103
+ deps.eventBus.emit(createEvent(EventCategory.MotionOnMotionChanged, {
48104
+ type: "device",
48105
+ id: deviceId,
48106
+ deviceId
48107
+ }, {
48108
+ deviceId,
48109
+ detected,
48110
+ timestamp,
48111
+ source: DEVICE_ACTIVITY_SOURCE
48112
+ }));
48113
+ },
48114
+ motionSourcesFor: (deviceId) => deps.getActiveDetectionConfig(deviceId)?.motionSources ?? null,
48115
+ sustainMsFor: (deviceId) => {
48116
+ const cooldownMs = deps.getActiveDetectionConfig(deviceId)?.motionCooldownMs;
48117
+ return Math.max(1e3, Math.floor((cooldownMs ?? 3e4) / 2));
48118
+ }
48119
+ });
48120
+ const unsubDeviceActivity = deps.eventBus.subscribe({ category: EventCategory.DeviceStateChanged }, (event) => {
48121
+ const data = event.data;
48122
+ if (typeof data !== "object" || data === null) return;
48123
+ if (data["capName"] !== recordingSignalCapability.name) return;
48124
+ const deviceId = data["deviceId"];
48125
+ if (typeof deviceId !== "number") return;
48126
+ const level = RecordingSignalStatusSchema.safeParse(data["slice"]);
48127
+ if (!level.success) {
48128
+ deps.logger.warn("device-activity: signal slice does not parse — ignored", {
48129
+ tags: { deviceId },
48130
+ meta: { slice: data["slice"] }
48131
+ });
48132
+ return;
48133
+ }
48134
+ const atMs = event.timestamp instanceof Date ? event.timestamp.getTime() : Date.now();
48135
+ activitySource.onSignalLevel(deviceId, level.data.active, level.data.reason, atMs);
48136
+ });
47767
48137
  return () => {
47768
48138
  isTornDown = true;
48139
+ activitySource.stop();
47769
48140
  for (const t of profileSlotTimers.values()) clearTimeout(t);
47770
48141
  profileSlotTimers.clear();
47771
48142
  unsubDeviceRegistered();
@@ -47780,6 +48151,7 @@ function wireOrchestratorSubscriptions(deps) {
47780
48151
  unsubSessionMotion();
47781
48152
  unsubFrameTracked();
47782
48153
  unsubMotionAnalysis();
48154
+ unsubDeviceActivity();
47783
48155
  };
47784
48156
  }
47785
48157
  //#endregion
@@ -50539,7 +50911,7 @@ var SessionDispatchController = class {
50539
50911
  * standing attach, so `hasStandingAttach` stays true for them and
50540
50912
  * `decideSessionAction` still returns `'ignore'`.
50541
50913
  */
50542
- async handleSessionMotion(deviceId, detected, emittedAt) {
50914
+ async handleSessionMotion(deviceId, detected, emittedAt, trigger) {
50543
50915
  const receivedAt = Date.now();
50544
50916
  const busLagMs = emittedAt !== void 0 ? receivedAt - emittedAt : void 0;
50545
50917
  const config = this.deps.getActiveDetectionConfig(deviceId);
@@ -50574,7 +50946,7 @@ var SessionDispatchController = class {
50574
50946
  return;
50575
50947
  }
50576
50948
  this.activeRefireCountByDevice.delete(deviceId);
50577
- await this.dispatchDetectionSession(deviceId, cur);
50949
+ await this.dispatchDetectionSession(deviceId, cur, trigger);
50578
50950
  if (this.sessionRegistry.has(deviceId)) this.scheduleSessionTeardown(deviceId, cooldownMs);
50579
50951
  const doneAt = Date.now();
50580
50952
  this.deps.logger.info("session motion → attach latency", {
@@ -50613,7 +50985,7 @@ var SessionDispatchController = class {
50613
50985
  * `dispatchCamera`) avoids any risk of changing that already-live
50614
50986
  * standing-camera path.
50615
50987
  */
50616
- async dispatchDetectionSession(deviceId, config) {
50988
+ async dispatchDetectionSession(deviceId, config, trigger) {
50617
50989
  const log = this.deps.logger.withTags({ deviceId });
50618
50990
  await this.deps.reconcilePlacementFromRunners();
50619
50991
  const preferredAgent = await this.deps.readPipelinePin(deviceId);
@@ -50669,13 +51041,19 @@ var SessionDispatchController = class {
50669
51041
  const steps = applyDeviceProvisioning(pipelineConfig.steps, deviceBase, deviceOverride);
50670
51042
  const inferenceDevices = deviceKey && Object.keys(enabledDevices).length >= 2 ? buildInferenceDeviceRoster(enabledDevices, deviceCaps) : void 0;
50671
51043
  const zones = await this.deps.listZones(deviceId);
51044
+ const sessionDetectionFps = detectionFpsForTrigger(config, trigger);
51045
+ if (sessionDetectionFps !== config.detectionFps) log.info("session opened at the device-activity rate", { meta: {
51046
+ trigger,
51047
+ detectionFps: sessionDetectionFps,
51048
+ cameraDetectionFps: config.detectionFps
51049
+ } });
50672
51050
  const sessionConfig = {
50673
51051
  deviceId,
50674
51052
  ...deviceKey ? { deviceKey } : {},
50675
51053
  ...inferenceDevices ? { inferenceDevices } : {},
50676
51054
  motionCooldownMs: config.motionCooldownMs,
50677
51055
  motionFps: config.motionFps,
50678
- detectionFps: config.detectionFps,
51056
+ detectionFps: sessionDetectionFps,
50679
51057
  motionStreamId: config.motionStreamId,
50680
51058
  detectionStreamId: config.detectionStreamId,
50681
51059
  motionSources: [],
@@ -51980,6 +52358,7 @@ async function buildOrchestratorControllers(deps) {
51980
52358
  localNodeId: () => localNodeId,
51981
52359
  deviceSettingsSchema: () => deps.deviceSettingsSchema(),
51982
52360
  deviceHasOnboardMotionCap: (deviceId) => deps.deviceHasOnboardMotionCap(deviceId),
52361
+ deviceHasActivitySignalCap: (deviceId) => deps.deviceHasActivitySignalCap(deviceId),
51983
52362
  deviceHasNativeObjectDetectionCap: (deviceId) => deps.deviceHasNativeObjectDetectionCap(deviceId),
51984
52363
  setCameraPipelineForAgent: (input) => deps.setCameraPipelineForAgent(input),
51985
52364
  emitCameraUpdated: (deviceId, config) => deps.emitCameraUpdated(deviceId, config),
@@ -52297,6 +52676,7 @@ async function buildOrchestratorControllers(deps) {
52297
52676
  },
52298
52677
  isCapActiveForDevice: (deviceId, capName) => deps.isCapActiveForDevice(deviceId, capName),
52299
52678
  deviceHasOnboardMotionCap: (deviceId) => deps.deviceHasOnboardMotionCap(deviceId),
52679
+ deviceHasActivitySignalCap: (deviceId) => deps.deviceHasActivitySignalCap(deviceId),
52300
52680
  deviceSettingsSchema: () => deps.deviceSettingsSchema()
52301
52681
  });
52302
52682
  await detectionWiring.hydrateFeaturesMirror().catch((err) => {
@@ -52332,255 +52712,6 @@ async function buildOrchestratorControllers(deps) {
52332
52712
  };
52333
52713
  }
52334
52714
  //#endregion
52335
- //#region src/viewer-ui-provider.ts
52336
- /**
52337
- * viewer-ui provider — the pipeline-orchestrator serves the CamStack viewer web
52338
- * SPA (mirrors what the now-removed standalone addon-viewer-ui used to do).
52339
- *
52340
- * Why here: the orchestrator is a hub bootstrap addon (always installed + baked),
52341
- * so folding the viewer serving into it avoids a second addon whose only job was
52342
- * to hold static files. The viewer's Expo web export is COPIED into this addon's
52343
- * `assets/viewer/` locally by the viewer repo's `scripts/copy-dist-to-orchestrator.js`
52344
- * (run from a checkout that HAS the `camstack/` submodule + Expo toolchain — the
52345
- * publish/image CI does not, which is exactly why we copy a pre-built dist rather
52346
- * than build it here). vite emits only into `dist/`, so `assets/viewer` survives
52347
- * the addon build; `assets` is in the package `files`, so it ships on
52348
- * `camstack deploy`. The hub's `main.ts` resolves the `viewer-ui` singleton at
52349
- * boot and mounts the SPA at `/viewer/camstack`.
52350
- *
52351
- * `index.js` runs from `dist/`, so the SPA root is one level up + `assets/viewer`.
52352
- */
52353
- var __dirname = path.dirname(fileURLToPath(import.meta.url));
52354
- /** Absolute path to the staged viewer web SPA (`<addon-root>/assets/viewer`). */
52355
- function resolveViewerDistDir() {
52356
- return path.resolve(__dirname, "..", "assets", "viewer");
52357
- }
52358
- /** Version of the staged viewer, written by the copy script; 'unknown' if absent. */
52359
- function readViewerVersion() {
52360
- try {
52361
- const raw = fs.readFileSync(path.join(resolveViewerDistDir(), ".viewer-version"), "utf-8").trim();
52362
- if (raw) return raw;
52363
- } catch {}
52364
- return "unknown";
52365
- }
52366
- /** Build the viewer-ui provider. Serves whatever dist was staged into
52367
- * `assets/viewer`; when nothing is staged the hub's mount cleanly 404s. */
52368
- function createViewerUiProvider() {
52369
- return {
52370
- getStaticDir: async () => ({ staticDir: resolveViewerDistDir() }),
52371
- getVersion: async () => ({ version: readViewerVersion() })
52372
- };
52373
- }
52374
- //#endregion
52375
- //#region src/disk-reconcile-fleet.ts
52376
- async function reconcileFleetFromDisk(deps) {
52377
- const deviceIds = await deps.listDeviceIds();
52378
- const failed = [];
52379
- let cameras = 0;
52380
- let mediaDropped = 0;
52381
- let tracks = 0;
52382
- let events = 0;
52383
- let completed = 0;
52384
- for (const deviceId of deviceIds) {
52385
- try {
52386
- await deps.rescanRecordings(deviceId);
52387
- const counts = await deps.reconcileAnalytics(deviceId);
52388
- cameras += 1;
52389
- mediaDropped += counts.mediaDropped;
52390
- tracks += counts.tracks;
52391
- events += counts.events;
52392
- } catch {
52393
- failed.push(deviceId);
52394
- }
52395
- completed += 1;
52396
- deps.onProgress?.({
52397
- deviceId,
52398
- total: deviceIds.length,
52399
- completed,
52400
- failed: [...failed],
52401
- mediaDropped,
52402
- tracks,
52403
- events
52404
- });
52405
- }
52406
- return {
52407
- cameras,
52408
- failed,
52409
- mediaDropped,
52410
- tracks,
52411
- events
52412
- };
52413
- }
52414
- //#endregion
52415
- //#region src/disk-reconcile-job.ts
52416
- /**
52417
- * In-memory disk-wins fleet job. The tRPC mutation starts this and returns
52418
- * immediately; the walk runs in the addon process so a 60s UDS timeout cannot
52419
- * abort it. Status is polled via getReconcileFromDiskStatus.
52420
- */
52421
- function idleDiskReconcileJob() {
52422
- return {
52423
- state: "idle",
52424
- total: 0,
52425
- completed: 0,
52426
- currentDeviceId: null,
52427
- failed: [],
52428
- mediaDropped: 0,
52429
- tracks: 0,
52430
- events: 0,
52431
- startedAtMs: null,
52432
- finishedAtMs: null,
52433
- error: null
52434
- };
52435
- }
52436
- function isTimeoutError(err) {
52437
- const message = err instanceof Error ? err.message : String(err);
52438
- return /timed out/i.test(message);
52439
- }
52440
- async function withTimeoutRetry(run) {
52441
- try {
52442
- return await run();
52443
- } catch (err) {
52444
- if (!isTimeoutError(err)) throw err;
52445
- return await run();
52446
- }
52447
- }
52448
- function createDiskReconcileJobRunner(now = Date.now) {
52449
- let job = idleDiskReconcileJob();
52450
- let inFlight = null;
52451
- const snapshot = () => job;
52452
- const start = (deps) => {
52453
- if (job.state === "running" && inFlight) return job;
52454
- job = {
52455
- ...idleDiskReconcileJob(),
52456
- state: "running",
52457
- startedAtMs: now()
52458
- };
52459
- deps.log?.("pipeline disk reconcile started");
52460
- inFlight = (async () => {
52461
- try {
52462
- const result = await reconcileFleetFromDisk({
52463
- listDeviceIds: deps.listDeviceIds,
52464
- rescanRecordings: (deviceId) => withTimeoutRetry(() => deps.rescanRecordings(deviceId)),
52465
- reconcileAnalytics: (deviceId) => withTimeoutRetry(() => deps.reconcileAnalytics(deviceId)),
52466
- onProgress: (update) => {
52467
- job = {
52468
- ...job,
52469
- total: update.total,
52470
- completed: update.completed,
52471
- currentDeviceId: update.deviceId,
52472
- failed: update.failed,
52473
- mediaDropped: update.mediaDropped,
52474
- tracks: update.tracks,
52475
- events: update.events
52476
- };
52477
- deps.onProgress?.(update);
52478
- deps.log?.("pipeline disk reconcile camera", {
52479
- deviceId: update.deviceId,
52480
- completed: update.completed,
52481
- total: update.total,
52482
- failed: update.failed.length,
52483
- mediaDropped: update.mediaDropped,
52484
- tracks: update.tracks,
52485
- events: update.events
52486
- });
52487
- }
52488
- });
52489
- job = {
52490
- ...job,
52491
- state: "done",
52492
- total: result.cameras + result.failed.length,
52493
- completed: result.cameras + result.failed.length,
52494
- currentDeviceId: null,
52495
- failed: result.failed,
52496
- mediaDropped: result.mediaDropped,
52497
- tracks: result.tracks,
52498
- events: result.events,
52499
- finishedAtMs: now(),
52500
- error: null
52501
- };
52502
- deps.log?.("pipeline disk reconcile", {
52503
- cameras: result.cameras,
52504
- failed: result.failed,
52505
- mediaDropped: result.mediaDropped,
52506
- tracks: result.tracks,
52507
- events: result.events
52508
- });
52509
- } catch (err) {
52510
- const error = err instanceof Error ? err.message : String(err);
52511
- job = {
52512
- ...job,
52513
- state: "error",
52514
- currentDeviceId: null,
52515
- finishedAtMs: now(),
52516
- error
52517
- };
52518
- deps.log?.("pipeline disk reconcile failed", { error });
52519
- } finally {
52520
- inFlight = null;
52521
- }
52522
- })();
52523
- return job;
52524
- };
52525
- return {
52526
- snapshot,
52527
- start
52528
- };
52529
- }
52530
- //#endregion
52531
- //#region src/widget-catalog.ts
52532
- var pipelineOrchestratorWidgets = [{
52533
- tab: "device-tab",
52534
- label: "Pipeline Quick Stats",
52535
- preAuth: false,
52536
- kind: "remote",
52537
- remote: {
52538
- remoteName: "addon_pipeline_orchestrator_widgets",
52539
- exposedModule: "./widgets",
52540
- componentKey: "pipeline-quick-stats"
52541
- },
52542
- stableId: "pipeline-quick-stats",
52543
- description: "Phase / Detection FPS / Inference / Active Tracks tile row.",
52544
- icon: "activity",
52545
- bundle: "remoteEntry.js",
52546
- hosts: ["device-tab", "dashboard"],
52547
- requires: {
52548
- deviceContext: true,
52549
- integrationContext: false
52550
- },
52551
- defaultSize: "md",
52552
- allowedSizes: [
52553
- "sm",
52554
- "md",
52555
- "lg"
52556
- ],
52557
- defaultColumns: 6,
52558
- defaultRows: 1
52559
- }, {
52560
- tab: "device-tab",
52561
- label: "Zone Editor",
52562
- preAuth: false,
52563
- kind: "remote",
52564
- remote: {
52565
- remoteName: "addon_pipeline_orchestrator_widgets",
52566
- exposedModule: "./widgets",
52567
- componentKey: "zone-editor"
52568
- },
52569
- stableId: "zone-editor",
52570
- description: "Polygon / tripwire CRUD + per-stage rule editor.",
52571
- icon: "shapes",
52572
- bundle: "remoteEntry.js",
52573
- hosts: ["device-tab"],
52574
- requires: {
52575
- deviceContext: true,
52576
- integrationContext: false
52577
- },
52578
- defaultSize: "xl",
52579
- allowedSizes: ["lg", "xl"],
52580
- defaultColumns: 12,
52581
- defaultRows: 4
52582
- }];
52583
- //#endregion
52584
52715
  //#region src/settings-ui-schemas.ts
52585
52716
  /** Build the addon-level schema sections (cluster roles + crop + balancer + failover). */
52586
52717
  function buildGlobalSettingsSections(options) {
@@ -52945,6 +53076,22 @@ function buildDeviceSettingsSections(nodeOptions) {
52945
53076
  field: "detectionMode",
52946
53077
  notEquals: "disabled"
52947
53078
  }
53079
+ },
53080
+ {
53081
+ key: "activityDetectionFps",
53082
+ type: "slider",
53083
+ label: "Detection FPS while the device is working",
53084
+ min: 1,
53085
+ max: 10,
53086
+ step: 1,
53087
+ default: 1,
53088
+ showValue: true,
53089
+ unit: "fps",
53090
+ description: "A device-activity session lasts as long as the job does — a cleaning run is tens of minutes. This caps the rate for that session only; a session opened by motion keeps the rate above.",
53091
+ showWhen: {
53092
+ field: "motionSources",
53093
+ includes: "device-activity"
53094
+ }
52948
53095
  }
52949
53096
  ]
52950
53097
  },
@@ -53034,6 +53181,99 @@ function deriveRuntimeSettings(config) {
53034
53181
  };
53035
53182
  }
53036
53183
  //#endregion
53184
+ //#region src/viewer-ui-provider.ts
53185
+ /**
53186
+ * viewer-ui provider — the pipeline-orchestrator serves the CamStack viewer web
53187
+ * SPA (mirrors what the now-removed standalone addon-viewer-ui used to do).
53188
+ *
53189
+ * Why here: the orchestrator is a hub bootstrap addon (always installed + baked),
53190
+ * so folding the viewer serving into it avoids a second addon whose only job was
53191
+ * to hold static files. The viewer's Expo web export is COPIED into this addon's
53192
+ * `assets/viewer/` locally by the viewer repo's `scripts/copy-dist-to-orchestrator.js`
53193
+ * (run from a checkout that HAS the `camstack/` submodule + Expo toolchain — the
53194
+ * publish/image CI does not, which is exactly why we copy a pre-built dist rather
53195
+ * than build it here). vite emits only into `dist/`, so `assets/viewer` survives
53196
+ * the addon build; `assets` is in the package `files`, so it ships on
53197
+ * `camstack deploy`. The hub's `main.ts` resolves the `viewer-ui` singleton at
53198
+ * boot and mounts the SPA at `/viewer/camstack`.
53199
+ *
53200
+ * `index.js` runs from `dist/`, so the SPA root is one level up + `assets/viewer`.
53201
+ */
53202
+ var __dirname = path.dirname(fileURLToPath(import.meta.url));
53203
+ /** Absolute path to the staged viewer web SPA (`<addon-root>/assets/viewer`). */
53204
+ function resolveViewerDistDir() {
53205
+ return path.resolve(__dirname, "..", "assets", "viewer");
53206
+ }
53207
+ /** Version of the staged viewer, written by the copy script; 'unknown' if absent. */
53208
+ function readViewerVersion() {
53209
+ try {
53210
+ const raw = fs.readFileSync(path.join(resolveViewerDistDir(), ".viewer-version"), "utf-8").trim();
53211
+ if (raw) return raw;
53212
+ } catch {}
53213
+ return "unknown";
53214
+ }
53215
+ /** Build the viewer-ui provider. Serves whatever dist was staged into
53216
+ * `assets/viewer`; when nothing is staged the hub's mount cleanly 404s. */
53217
+ function createViewerUiProvider() {
53218
+ return {
53219
+ getStaticDir: async () => ({ staticDir: resolveViewerDistDir() }),
53220
+ getVersion: async () => ({ version: readViewerVersion() })
53221
+ };
53222
+ }
53223
+ //#endregion
53224
+ //#region src/widget-catalog.ts
53225
+ var pipelineOrchestratorWidgets = [{
53226
+ tab: "device-tab",
53227
+ label: "Pipeline Quick Stats",
53228
+ preAuth: false,
53229
+ kind: "remote",
53230
+ remote: {
53231
+ remoteName: "addon_pipeline_orchestrator_widgets",
53232
+ exposedModule: "./widgets",
53233
+ componentKey: "pipeline-quick-stats"
53234
+ },
53235
+ stableId: "pipeline-quick-stats",
53236
+ description: "Phase / Detection FPS / Inference / Active Tracks tile row.",
53237
+ icon: "activity",
53238
+ bundle: "remoteEntry.js",
53239
+ hosts: ["device-tab", "dashboard"],
53240
+ requires: {
53241
+ deviceContext: true,
53242
+ integrationContext: false
53243
+ },
53244
+ defaultSize: "md",
53245
+ allowedSizes: [
53246
+ "sm",
53247
+ "md",
53248
+ "lg"
53249
+ ],
53250
+ defaultColumns: 6,
53251
+ defaultRows: 1
53252
+ }, {
53253
+ tab: "device-tab",
53254
+ label: "Zone Editor",
53255
+ preAuth: false,
53256
+ kind: "remote",
53257
+ remote: {
53258
+ remoteName: "addon_pipeline_orchestrator_widgets",
53259
+ exposedModule: "./widgets",
53260
+ componentKey: "zone-editor"
53261
+ },
53262
+ stableId: "zone-editor",
53263
+ description: "Polygon / tripwire CRUD + per-stage rule editor.",
53264
+ icon: "shapes",
53265
+ bundle: "remoteEntry.js",
53266
+ hosts: ["device-tab"],
53267
+ requires: {
53268
+ deviceContext: true,
53269
+ integrationContext: false
53270
+ },
53271
+ defaultSize: "xl",
53272
+ allowedSizes: ["lg", "xl"],
53273
+ defaultColumns: 12,
53274
+ defaultRows: 4
53275
+ }];
53276
+ //#endregion
53037
53277
  //#region src/index.ts
53038
53278
  /**
53039
53279
  * addon-pipeline-orchestrator — hub-side camera-to-agent load balancer.
@@ -53348,6 +53588,7 @@ var PipelineOrchestratorAddon = class PipelineOrchestratorAddon extends BaseAddo
53348
53588
  isCapActiveForDevice: (deviceId, capName) => this.isCapActiveForDevice(deviceId, capName),
53349
53589
  isAudioAnalysisActive: (deviceId) => this.isAudioAnalysisActive(deviceId),
53350
53590
  deviceHasOnboardMotionCap: (deviceId) => this.deviceHasOnboardMotionCap(deviceId),
53591
+ deviceHasActivitySignalCap: (deviceId) => this.deviceHasActivitySignalCap(deviceId),
53351
53592
  deviceHasNativeObjectDetectionCap: (deviceId) => this.deviceHasNativeObjectDetectionCap(deviceId),
53352
53593
  handleDeviceRegistered: (deviceId) => this.handleDeviceRegistered(deviceId),
53353
53594
  handleDeviceUnregistered: (deviceId) => this.handleDeviceUnregistered(deviceId),
@@ -54534,6 +54775,26 @@ var PipelineOrchestratorAddon = class PipelineOrchestratorAddon extends BaseAddo
54534
54775
  * we err toward the analyzer (never lose detection coverage when the
54535
54776
  * binding lookup hiccups).
54536
54777
  */
54778
+ /**
54779
+ * True when the device's driver registered `recording-signal` — the cap a
54780
+ * device uses to say, itself, that it is working (a robot vacuum cleaning).
54781
+ * Drives the `device-activity` entry in the `motionSources` DEFAULT (D392),
54782
+ * so the source arrives on exactly the devices that can raise it and on no
54783
+ * other camera in the fleet.
54784
+ *
54785
+ * Same failure discipline as `deviceHasOnboardMotionCap`: a binding lookup
54786
+ * that throws answers `false`, which loses the DEFAULT and never the
54787
+ * operator's explicit choice (this is asked only when they pinned nothing).
54788
+ */
54789
+ async deviceHasActivitySignalCap(deviceId) {
54790
+ const api = this.api;
54791
+ if (!api) return false;
54792
+ try {
54793
+ return (await api.deviceManager.getBindings.query({ deviceId })).entries.some((e) => e.kind === "native" && e.capName === "recording-signal");
54794
+ } catch {
54795
+ return false;
54796
+ }
54797
+ }
54537
54798
  async deviceHasOnboardMotionCap(deviceId) {
54538
54799
  const api = this.api;
54539
54800
  if (!api) return false;